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

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

互換性のあるモデルを使用する

Anthropicのテキストエディタツールは複数のClaudeモデルで利用できます:

  • Claude 4 Opus & Sonnet: text_editor_20250728
  • Claude Sonnet 3.7: text_editor_20250124
  • Claude Sonnet 3.5: text_editor_20241022

Claude Sonnet 3.5では、テキストエディタツールを使用する際にcomputer-use-2024-10-22ベータヘッダーが必要です。

テキストエディタツールは、Claude 4とSonnet 3.7で一般的に利用可能です。

Claude 4モデル用のtext_editor_20250728ツールにはundo_editコマンドが含まれていません。この機能が必要な場合は、それぞれのツールバージョンでClaude 3.7またはSonnet 3.5を使用する必要があります。

ユースケースの適合性を評価する

テキストエディタツールを使用する場合の例:

  • コードデバッグ: Claudeにコードのバグを特定・修正してもらい、構文エラーからロジックの問題まで対応
  • コードリファクタリング: Claudeに対象を絞った編集を通じてコード構造、可読性、パフォーマンスを改善してもらう
  • ドキュメント生成: Claudeにコードベースにdocstring、コメント、READMEファイルを追加してもらう
  • テスト作成: Claudeに実装の理解に基づいてコードの単体テストを作成してもらう

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

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

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

max_characterstext_editor_20250728以降のバージョンのテキストエディタツールでのみ互換性があります。

curl https://api.anthropic.com/v1/messages \
  -H "content-type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "claude-opus-4-20250514",
    "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?"
      }
    ]
  }'

テキストエディタツールは以下の方法で使用できます:

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)
  • new_str: 挿入するテキスト

undo_edit

undo_editコマンドにより、Claudeはファイルに対して行われた最後の編集を元に戻すことができます。

このコマンドは、Claude Sonnet 3.7とClaude Sonnet 3.5でのみ利用可能です。text_editor_20250728を使用するClaude 4モデルではサポートされていません。

パラメータ:

  • command: “undo_edit”である必要があります
  • path: 最後の編集を元に戻すファイルのパス

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

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

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

curl https://api.anthropic.com/v1/messages \
  -H "content-type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "claude-opus-4-20250514",
    "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?"
      }
    ]
  }'

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

{
  "id": "msg_01XAbCDeFgHiJkLmNoPQrStU",
  "model": "claude-opus-4-20250514",
  "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に返す必要があります:

curl https://api.anthropic.com/v1/messages \
  -H "content-type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "claude-opus-4-20250514",
    "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()"
                }
            ]
        }
    ]
  }'

行番号

上記の例では、viewツールの結果には各行に行番号が前置されたファイル内容が含まれています(例:「1: def is_prime(n):」)。行番号は必須ではありませんが、ファイルの特定のセクションを検査するためのview_rangeパラメータと、正確な場所にコンテンツを追加するためのinsert_lineパラメータを正常に使用するために不可欠です。

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

{
  "id": "msg_01VwXyZAbCdEfGhIjKlMnO",
  "model": "claude-opus-4-20250514",
  "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-4-20250514",
    max_tokens=1024,
    tools=[
        {
            "type": "text_editor_20250728",
            "name": "str_replace_based_edit_tool"
        }
    ],
    messages=[
        # Previous 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."
                }
            ]
        }
    ]
)

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

{
  "id": "msg_01IjKlMnOpQrStUvWxYzAb",
  "model": "claude-opus-4-20250514",
  "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"
  • Claude Sonnet 3.7: type: "text_editor_20250124"
  • Claude Sonnet 3.5: type: "text_editor_20241022"
1

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

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

2

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

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

def handle_editor_tool(tool_call, model_version):
    input_params = tool_call.input
    command = input_params.get('command', '')
    file_path = input_params.get('path', '')
    
    if command == 'view':
        # Read and return file contents
        pass
    elif command == 'str_replace':
        # Replace text in file
        pass
    elif command == 'create':
        # Create new file
        pass
    elif command == 'insert':
        # Insert text at location
        pass
    elif command == 'undo_edit':
        # Check if it's a Claude 4 model
        if 'str_replace_based_edit_tool' in model_version:
            return {"error": "undo_edit command is not supported in Claude 4"}
        # Restore from backup for Claude 3.7/3.5
        pass
3

セキュリティ対策を実装する

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

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

Claudeのレスポンスを処理する

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

# Process tool use in Claude's response
for content in response.content:
    if content.type == "tool_use":
        # Execute the tool based on command
        result = handle_editor_tool(content)
        
        # Return result to Claude
        tool_result = {
            "type": "tool_result",
            "tool_use_id": content.id,
            "content": result
        }

テキストエディタツールを実装する際は、以下の点に留意してください:

  1. セキュリティ: ツールはローカルファイルシステムにアクセスできるため、適切なセキュリティ対策を実装してください。
  2. バックアップ: 重要なファイルの編集を許可する前に、常にバックアップを作成してください。
  3. 検証: 意図しない変更を防ぐために、すべての入力を検証してください。
  4. 一意のマッチング: 意図しない編集を避けるために、置換が正確に一つの場所にマッチすることを確認してください。

エラーを処理する

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

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


価格とトークン使用量

The text editor tool uses the same pricing structure as other tools used with Claude. It follows the standard input and output token pricing based on the Claude model you’re using.

In addition to the base tokens, the following additional input tokens are needed for the text editor tool:

ToolAdditional input tokens
text_editor_20250429 (Claude 4)700 tokens
text_editor_20250124 (Claude Sonnet 3.7)700 tokens
text_editor_20241022 (Claude Sonnet 3.5 (deprecated))700 tokens

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

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

テキストエディタツールは他の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でのテキストエディタツールの初回リリース。viewcreatestr_replaceinsertundo_editコマンドを通じてファイルの表示、作成、編集の機能を提供します。

次のステップ

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

  • 開発ワークフローとの統合: テキストエディタツールを開発ツールやIDEに組み込む
  • コードレビューシステムの作成: Claudeにコードをレビューしてもらい、改善を行ってもらう
  • デバッグアシスタントの構築: Claudeがコードの問題の診断と修正を支援するシステムを作成する
  • ファイル形式変換の実装: Claudeにファイルを別の形式に変換してもらう
  • ドキュメント化の自動化: Claudeが自動的にコードを文書化するワークフローを設定する

テキストエディタツールを使用してアプリケーションを構築する際、Claudeの機能を活用して開発ワークフローと生産性を向上させる方法を楽しみにしています。