Claude Platform Docs
Messagesツール

テキストエディタツール

Anthropicが定義したテキストエディタツールをClaudeに提供して、ファイルの表示、作成、編集を行い、view、str_replace、create、insertコマンドを処理します。

Claudeは、Anthropicスキーマのテキストエディタツールを使用してテキストファイルを表示および変更でき、コードやその他のテキストドキュメントのデバッグ、修正、改善を支援します。これにより、Claudeはファイルと直接やり取りでき、単に変更を提案するだけでなく、実践的な支援を提供できます。

モデルのサポートについては、ツールリファレンスを参照してください。

テキストエディタツールを使用する場面

テキストエディタツールを使用する場面の例をいくつか示します。

  • コードのデバッグ: 構文エラーからロジックの問題まで、コード内のバグをClaudeに特定して修正させます。
  • コードのリファクタリング: 的を絞った編集を通じて、Claudeにコードの構造、可読性、パフォーマンスを改善させます。
  • ドキュメントの生成: Claudeにdocstring、コメント、またはREADMEファイルをコードベースに追加するよう依頼します。
  • テストの作成: 実装の分析に基づいて、Claudeにコードのユニットテストを作成させます。

テキストエディタツールを使用する

Messages APIを使用して、テキストエディタツール(名前はstr_replace_based_edit_tool)をClaudeに提供します。

オプションでmax_charactersパラメータを指定して、大きなファイルを表示する際の切り捨てを制御できます。

client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=1024,
    tools=[
        {
            "type": "text_editor_20250728",
            "name": "str_replace_based_edit_tool",
            "max_characters": 10000,
        }
    ],
    messages=[
        {
            "role": "user",
            "content": "There's a syntax error in my primes.py file. Can you help me fix it?",
        }
    ],
)

print(response)

テキストエディタツールは次のように使用します。

  1. Claudeにテキストエディタツールとユーザープロンプトを提供する

    • APIリクエストにテキストエディタツールを含めます
    • 「コードの構文エラーを修正してもらえますか?」など、ファイルの調査や変更が必要になる可能性のあるユーザープロンプトを提供します
  2. Claudeがツールを使用してファイルまたはディレクトリを調査する

    • Claudeは何を確認する必要があるかを判断し、viewコマンドを使用してファイルの内容を調査したり、ディレクトリの内容を一覧表示したりします
    • APIレスポンスには、viewコマンドを含むtool_useコンテンツブロックが含まれます
  3. viewコマンドを実行して結果を返す

    • Claudeのツール使用リクエストからファイルまたはディレクトリのパスを抽出します
    • ファイルの内容を読み取るか、ディレクトリの内容を一覧表示します
    • ツール設定でmax_charactersパラメータが指定されている場合は、ファイルの内容をその長さに切り捨てます
    • tool_resultコンテンツブロックを含む新しいuserメッセージで会話を続けることで、結果をClaudeに返します
  4. Claudeがツールを使用してファイルを変更する

    • ファイルまたはディレクトリを調査した後、Claudeはstr_replaceなどのコマンドを使用して変更を加えたり、insertを使用して特定の行番号にテキストを追加したりすることがあります。
    • Claudeがstr_replaceコマンドを使用する場合、Claudeは古いテキストとそれを置き換える新しいテキストを含む、適切にフォーマットされたツール使用リクエストを構築します
  5. 編集を実行して結果を返す

    • Claudeのツール使用リクエストからファイルパス、古いテキスト、新しいテキストを抽出します
    • ファイル内でテキストの置換を実行します
    • 結果をClaudeに返します
  6. Claudeが分析と説明を提供する

    • ファイルを調査し、場合によっては編集した後、Claudeは発見した内容と加えた変更についての完全な説明を提供します

テキストエディタツールのコマンド

テキストエディタツールは、ファイルの表示と変更のためのいくつかのコマンドをサポートしています。

view

viewコマンドを使用すると、Claudeはファイルの内容を調査したり、ディレクトリの内容を一覧表示したりできます。ファイル全体または特定の行範囲を読み取ることができます。

パラメータ:

  • command: "view"である必要があります
  • path: 表示するファイルまたはディレクトリへのパス
  • view_range(オプション): 表示する開始行番号と終了行番号を指定する2つの整数の配列。行番号は1から始まり、終了行に-1を指定するとファイルの末尾まで読み取ります。このパラメータはファイルを表示する場合にのみ適用され、ディレクトリには適用されません。

str_replace

str_replaceコマンドを使用すると、Claudeはファイル内の特定の文字列を新しい文字列に置き換えることができます。これは正確な編集を行うために使用されます。

パラメータ:

  • command: "str_replace"である必要があります
  • path: 変更するファイルへのパス
  • old_str: 置き換えるテキスト(空白やインデントを含め、完全に一致する必要があります)
  • new_str: 古いテキストの代わりに挿入する新しいテキスト

create

createコマンドを使用すると、Claudeは指定された内容で新しいファイルを作成できます。

パラメータ:

  • command: "create"である必要があります
  • path: 新しいファイルを作成するパス
  • file_text: 新しいファイルに書き込む内容

insert

insertコマンドを使用すると、Claudeはファイル内の特定の位置にテキストを挿入できます。

パラメータ:

  • command: "insert"である必要があります
  • path: 変更するファイルへのパス
  • insert_line: テキストを挿入する位置の直前の行番号(ファイルの先頭の場合は0)
  • insert_text: 挿入するテキスト

例: テキストエディタツールで構文エラーを修正する

この例では、ClaudeがテキストエディタツールをどのようにPythonファイルの構文エラーの修正に使用するかを示します。

まず、アプリケーションがClaudeにテキストエディタツールと構文エラーを修正するためのプロンプトを提供します。

client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=1024,
    tools=[{"type": "text_editor_20250728", "name": "str_replace_based_edit_tool"}],
    messages=[
        {
            "role": "user",
            "content": "There's a syntax error in my primes.py file. Can you help me fix it?",
        }
    ],
)

print(response)

Claudeはまずテキストエディタツールを使用してファイルを表示します。

Output
{
  "id": "msg_01XAbCDeFgHiJkLmNoPQrStU",
  "model": "claude-opus-5-5",
  "stop_reason": "tool_use",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I'll help you fix the syntax error in your primes.py file. First, let me take a look at the file to identify the issue."
    },
    {
      "type": "tool_use",
      "id": "toolu_01AbCdEfGhIjKlMnOpQrStU",
      "name": "str_replace_based_edit_tool",
      "input": {
        "command": "view",
        "path": "primes.py"
      }
    }
  ]
}

次に、アプリケーションはファイルを読み取り、その内容をClaudeに返す必要があります。

response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=1024,
    tools=[{"type": "text_editor_20250728", "name": "str_replace_based_edit_tool"}],
    messages=[
        {
            "role": "user",
            "content": "There's a syntax error in my primes.py file. Can you help me fix it?",
        },
        {
            "role": "assistant",
            "content": [
                {
                    "type": "text",
                    "text": "I'll help you fix the syntax error in your primes.py file. First, let me take a look at the file to identify the issue.",
                },
                {
                    "type": "tool_use",
                    "id": "toolu_01AbCdEfGhIjKlMnOpQrStU",
                    "name": "str_replace_based_edit_tool",
                    "input": {"command": "view", "path": "primes.py"},
                },
            ],
        },
        {
            "role": "user",
            "content": [
                {
                    "type": "tool_result",
                    "tool_use_id": "toolu_01AbCdEfGhIjKlMnOpQrStU",
                    "content": '1: def is_prime(n):\n2:     """Check if a number is prime."""\n3:     if n <= 1:\n4:         return False\n5:     if n <= 3:\n6:         return True\n7:     if n % 2 == 0 or n % 3 == 0:\n8:         return False\n9:     i = 5\n10:     while i * i <= n:\n11:         if n % i == 0 or n % (i + 2) == 0:\n12:             return False\n13:         i += 6\n14:     return True\n15: \n16: def get_primes(limit):\n17:     """Generate a list of prime numbers up to the given limit."""\n18:     primes = []\n19:     for num in range(2, limit + 1)\n20:         if is_prime(num):\n21:             primes.append(num)\n22:     return primes\n23: \n24: def main():\n25:     """Main function to demonstrate prime number generation."""\n26:     limit = 100\n27:     prime_list = get_primes(limit)\n28:     print(f"Prime numbers up to {limit}:")\n29:     print(prime_list)\n30:     print(f"Found {len(prime_list)} prime numbers.")\n31: \n32: if __name__ == "__main__":\n33:     main()',
                }
            ],
        },
    ],
)

print(response)

Claudeは構文エラーを特定し、str_replaceコマンドを使用して修正します。

Output
{
  "id": "msg_01VwXyZAbCdEfGhIjKlMnO",
  "model": "claude-opus-5-5",
  "stop_reason": "tool_use",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I found the syntax error in your primes.py file. In the `get_primes` function, there is a missing colon (:) at the end of the for loop line. Let me fix that for you."
    },
    {
      "type": "tool_use",
      "id": "toolu_01PqRsTuVwXyZAbCdEfGh",
      "name": "str_replace_based_edit_tool",
      "input": {
        "command": "str_replace",
        "path": "primes.py",
        "old_str": "    for num in range(2, limit + 1)",
        "new_str": "    for num in range(2, limit + 1):"
      }
    }
  ]
}

次に、アプリケーションは編集を行い、結果を返す必要があります。

response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=1024,
    tools=[{"type": "text_editor_20250728", "name": "str_replace_based_edit_tool"}],
    messages=[
        # 以前のメッセージ...
        {
            "role": "assistant",
            "content": [
                {
                    "type": "text",
                    "text": "I found the syntax error in your primes.py file. In the `get_primes` function, there is a missing colon (:) at the end of the for loop line. Let me fix that for you.",
                },
                {
                    "type": "tool_use",
                    "id": "toolu_01PqRsTuVwXyZAbCdEfGh",
                    "name": "str_replace_based_edit_tool",
                    "input": {
                        "command": "str_replace",
                        "path": "primes.py",
                        "old_str": "    for num in range(2, limit + 1)",
                        "new_str": "    for num in range(2, limit + 1):",
                    },
                },
            ],
        },
        {
            "role": "user",
            "content": [
                {
                    "type": "tool_result",
                    "tool_use_id": "toolu_01PqRsTuVwXyZAbCdEfGh",
                    "content": "Successfully replaced text at exactly one location.",
                }
            ],
        },
    ],
)

print(response)

最後に、Claudeは修正についての完全な説明を提供します。

Output
{
  "id": "msg_01IjKlMnOpQrStUvWxYzAb",
  "model": "claude-opus-5-5",
  "stop_reason": "end_turn",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I've fixed the syntax error in your primes.py file. The issue was in the `get_primes` function at line 19. There was a missing colon (:) at the end of the for loop line.\n\nHere's what I changed:\n\nFrom:\n```python\nfor num in range(2, limit + 1)\n```\n\nTo:\n```python\nfor num in range(2, limit + 1):\n```\n\nIn Python, a colon is required at the end of statements that start a new code block, such as for loops, if statements, function definitions, etc. Without the colon, Python raises a syntax error because it doesn't know where the code block begins.\n\nYour code should now run correctly. The function will properly generate a list of prime numbers up to the specified limit."
    }
  ]
}

テキストエディタツールを実装する

テキストエディタツールはスキーマレスツールとして実装されています。このツールを使用する場合、他のツールのように入力スキーマを提供する必要はありません。スキーマはClaudeのモデルに組み込まれており、変更できません。

ツールタイプは、Claude 4以降のモデルではtype: "text_editor_20250728"です。

  1. エディタ実装を初期化する

    ファイルの読み取り、書き込み、変更などのファイル操作を処理するヘルパー関数を作成します。ミスから復旧するためのバックアップ機能の実装を検討してください。

  2. エディタツールの呼び出しを処理する

    コマンドタイプに基づいてClaudeからのツール呼び出しを処理する関数を作成します。

    def handle_editor_tool(tool_call):
        input_params = tool_call.input
        command = input_params.get("command", "")
        file_path = input_params.get("path", "")
    
        match command:
            case "view":
                # ファイルの内容を読み取って返します
                pass
            case "str_replace":
                # ファイル内のテキストを置換します
                pass
            case "create":
                # 新しいファイルを作成します
                pass
            case "insert":
                # 指定位置にテキストを挿入します
                pass
  3. セキュリティ対策を実装する

    検証とセキュリティチェックを追加します。

    • ディレクトリトラバーサルを防ぐためにファイルパスを検証する
    • 変更を加える前にバックアップを作成する
    • エラーを適切に処理する
    • 権限チェックを実装する
  4. Claudeのレスポンスを処理する

    Claudeのレスポンスからツール呼び出しを抽出して処理します。

    # Claudeの応答内のツール使用を処理
    for content in response.content:
        if content.type == "tool_use":
            # コマンドに基づいてツールを実行
            result = handle_editor_tool(content)
    
            # 結果をClaudeに返す
            tool_result = {
                "type": "tool_result",
                "tool_use_id": content.id,
                "content": result,
            }

エラーを処理する

テキストエディタツールを使用する際には、さまざまなエラーが発生する可能性があります。それらの処理方法についてのガイダンスを以下に示します。

実装のベストプラクティスに従う


料金とトークン使用量

テキストエディタツールは、Claudeで使用される他のツールと同じ料金体系を採用しています。使用しているClaudeモデルに基づく標準的な入力トークンおよび出力トークンの料金に従います。

基本トークンに加えて、テキストエディタツールには以下の追加入力トークンが必要です。

ツール追加入力トークン
text_editor_20250429 (Claude 4.x)700トークン

ツールの料金に関する詳細については、ツール使用の料金を参照してください。

テキストエディタツールを他のツールと統合する

テキストエディタツールは、他のClaudeツールと併用できます。ツールを組み合わせる際は、次の点を確認してください。

  • ツールのバージョンを使用しているモデルと一致させる
  • リクエストに含まれるすべてのツールの追加トークン使用量を考慮する

変更履歴

日付バージョン変更内容
2025年7月28日text_editor_20250728いくつかの問題を修正し、オプションのmax_charactersパラメータを追加した、更新版テキストエディタツールのリリース。それ以外はtext_editor_20250429と同一です。
2025年4月29日text_editor_20250429Claude 4向けテキストエディタツールのリリース。このバージョンではundo_editコマンドが削除されていますが、その他のすべての機能は維持されています。ツール名は、str_replaceベースのアーキテクチャを反映するように更新されました。
2025年3月13日text_editor_20250124独立したテキストエディタツールのドキュメントの導入。このバージョンはClaude Sonnet 3.7向けに最適化されていますが、以前のバージョンと同一の機能を備えています。
2024年10月22日text_editor_20241022Claude Sonnet 3.5(廃止済み。モデルの非推奨を参照)でのテキストエディタツールの初回リリース。view、create、str_replace、insert、undo_editコマンドを通じて、ファイルの表示、作成、編集の機能を提供します。

次のステップ

テキストエディタツールをより便利で強力な方法で使用するためのアイデアをいくつか紹介します。

  • 開発ワークフローと統合する: テキストエディタツールを開発ツールやIDEに組み込む
  • コードレビューシステムを作成する: Claudeにコードをレビューさせ、改善を加えさせる
  • デバッグアシスタントを構築する: Claudeがコードの問題の診断と修正を支援できるシステムを作成する
  • ファイル形式の変換を実装する: Claudeにファイルをある形式から別の形式に変換する手助けをさせる
  • ドキュメント作成を自動化する: Claudeがコードを自動的にドキュメント化するワークフローを設定する

テキストエディタツールにより、Claudeはコードベースを直接操作できるようになり、デバッグから自動ドキュメント作成までのワークフローをサポートします。

Claudeで使用するツールワークフローの実装方法を学びます。

Claudeでシェルコマンドを実行します。

Was this page helpful?