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

モデルの互換性

モデルツールバージョン
Claude 4.xモデルtext_editor_20250728
Claude Sonnet 3.7 (廃止)text_editor_20250124
Claude 4モデル用のtext_editor_20250728ツールにはundo_editコマンドが含まれていません。この機能が必要な場合は、Claude Sonnet 3.7 (廃止)を使用する必要があります。
古いツールバージョンは、新しいモデルとの下位互換性が保証されていません。常にモデルバージョンに対応するツールバージョンを使用してください。

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

テキストエディタツールを使用する場合の例は以下の通りです:
  • コードデバッグ: Claudeにコード内のバグ(構文エラーからロジックの問題まで)を特定・修正させます。
  • コードリファクタリング: Claudeに対象の編集を通じてコード構造、可読性、パフォーマンスを改善させます。
  • ドキュメント生成: Claudeにdocstring、コメント、またはREADMEファイルをコードベースに追加させます。
  • テスト作成: Claudeに実装の理解に基づいてコードのユニットテストを作成させます。

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

  • Claude 4
  • Claude Sonnet 3.7
Messages APIを使用してテキストエディタツール(str_replace_based_edit_toolという名前)をClaudeに提供します。大きなファイルを表示する際の切り詰めを制御するために、オプションで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-sonnet-4-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?"
      }
    ]
  }'
テキストエディタツールは以下の方法で使用できます:
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を指定するとファイルの最後まで読みます。このパラメータはファイルを表示する場合にのみ適用され、ディレクトリには適用されません。
// ファイルを表示する例
{
  "type": "tool_use",
  "id": "toolu_01A09q90qw90lq917835lq9",
  "name": "str_replace_editor",
  "input": {
    "command": "view",
    "path": "primes.py"
  }
}

// ディレクトリを表示する例
{
  "type": "tool_use",
  "id": "toolu_02B19r91rw91mr917835mr9",
  "name": "str_replace_editor",
  "input": {
    "command": "view",
    "path": "src/"
  }
}

str_replace

str_replaceコマンドを使用すると、Claudeはファイル内の特定の文字列を新しい文字列に置き換えることができます。これは正確な編集を行うために使用されます。 パラメータ:
  • command: 「str_replace」である必要があります
  • path: 編集するファイルへのパス
  • old_str: 置き換えるテキスト(空白とインデントを含めて完全に一致する必要があります)
  • new_str: 古いテキストの代わりに挿入する新しいテキスト
{
  "type": "tool_use",
  "id": "toolu_01A09q90qw90lq917835lq9",
  "name": "str_replace_editor",
  "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):"
  }
}

create

createコマンドを使用すると、Claudeは指定されたコンテンツで新しいファイルを作成できます。 パラメータ:
  • command: 「create」である必要があります
  • path: 新しいファイルを作成するパス
  • file_text: 新しいファイルに書き込むコンテンツ
{
  "type": "tool_use",
  "id": "toolu_01A09q90qw90lq917835lq9",
  "name": "str_replace_editor",
  "input": {
    "command": "create",
    "path": "test_primes.py",
    "file_text": "import unittest\nimport primes\n\nclass TestPrimes(unittest.TestCase):\n    def test_is_prime(self):\n        self.assertTrue(primes.is_prime(2))\n        self.assertTrue(primes.is_prime(3))\n        self.assertFalse(primes.is_prime(4))\n\nif __name__ == '__main__':\n    unittest.main()"
  }
}

insert

insertコマンドを使用すると、Claudeはファイル内の特定の場所にテキストを挿入できます。 パラメータ:
  • command: 「insert」である必要があります
  • path: 編集するファイルへのパス
  • insert_line: テキストを挿入する行番号の後(ファイルの最初の場合は0)
  • new_str: 挿入するテキスト
{
  "type": "tool_use",
  "id": "toolu_01A09q90qw90lq917835lq9",
  "name": "str_replace_editor",
  "input": {
    "command": "insert",
    "path": "primes.py",
    "insert_line": 0,
    "new_str": "\"\"\"Module for working with prime numbers.\n\nThis module provides functions to check if a number is prime\nand to generate a list of prime numbers up to a given limit.\n\"\"\"\n"
  }
}

undo_edit

undo_editコマンドを使用すると、Claudeはファイルに加えた最後の編集を元に戻すことができます。
このコマンドはClaudeソネット3.7 (廃止)でのみ利用可能です。text_editor_20250728を使用するClaude 4モデルではサポートされていません。
パラメータ:
  • command: 「undo_edit」である必要があります
  • path: 最後の編集を元に戻すファイルへのパス
{
  "type": "tool_use",
  "id": "toolu_01A09q90qw90lq917835lq9",
  "name": "str_replace_editor",
  "input": {
    "command": "undo_edit",
    "path": "primes.py"
  }
}

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

  • Claude 4
  • Claude Sonnet 3.7
この例は、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-sonnet-4-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?"
      }
    ]
  }'
Claudeはまずテキストエディタツールを使用してファイルを表示します:
{
  "id": "msg_01XAbCDeFgHiJkLmNoPQrStU",
  "model": "claude-sonnet-4-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に返す必要があります:
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-sonnet-4-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()"
                }
            ]
        }
    ]
  }'
行番号上記の例では、viewツールの結果には各行の前に行番号が付いたファイルの内容が含まれています(例:「1: def is_prime(n):」)。行番号は必須ではありませんが、view_rangeパラメータを使用してファイルの特定のセクションを検査し、insert_lineパラメータを使用して正確な場所にコンテンツを追加するために不可欠です。
Claudeは構文エラーを特定し、str_replaceコマンドを使用してそれを修正します:
{
  "id": "msg_01VwXyZAbCdEfGhIjKlMnO",
  "model": "claude-sonnet-4-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-sonnet-4-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."
                }
            ]
        }
    ]
)
最後に、Claudeは修正の完全な説明を提供します:
{
  "id": "msg_01IjKlMnOpQrStUvWxYzAb",
  "model": "claude-sonnet-4-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."
    }
  ]
}

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

テキストエディタツールはスキーマレスツールとして実装されています。このツールを使用する場合、他のツールのようにinputスキーマを提供する必要はありません。スキーマはClaudeのモデルに組み込まれており、変更することはできません。 ツールタイプはモデルバージョンによって異なります:
  • Claude 4: type: "text_editor_20250728"
  • Claude Sonnet 3.7: type: "text_editor_20250124"
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':
        # ファイルの内容を読み込んで返す
        pass
    elif command == 'str_replace':
        # ファイル内のテキストを置き換える
        pass
    elif command == 'create':
        # 新しいファイルを作成する
        pass
    elif command == 'insert':
        # 場所にテキストを挿入する
        pass
    elif command == 'undo_edit':
        # Claude 4モデルかどうかを確認する
        if 'str_replace_based_edit_tool' in model_version:
            return {"error": "undo_edit command is not supported in Claude 4"}
        # Claude 3.7のバックアップから復元する
        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
        }
テキストエディタツールを実装する際は、以下の点に注意してください:
  1. セキュリティ: ツールはローカルファイルシステムにアクセスできるため、適切なセキュリティ対策を実装してください。
  2. バックアップ: 重要なファイルの編集を許可する前に、常にバックアップを作成してください。
  3. 検証: 意図しない変更を防ぐために、すべての入力を検証してください。
  4. 一意のマッチング: 置き換えが正確に1つの場所にマッチすることを確認して、意図しない編集を避けてください。

エラーを処理する

テキストエディタツールを使用する場合、さまざまなエラーが発生する可能性があります。以下は、それらを処理する方法に関するガイダンスです:
Claudeが存在しないファイルを表示または編集しようとした場合、tool_resultに適切なエラーメッセージを返します:
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
      "content": "Error: File not found",
      "is_error": true
    }
  ]
}
Claudeのstr_replaceコマンドがファイル内の複数の場所にマッチする場合、適切なエラーメッセージを返します:
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
      "content": "Error: Found 3 matches for replacement text. Please provide more context to make a unique match.",
      "is_error": true
    }
  ]
}
Claudeのstr_replaceコマンドがファイル内のテキストにマッチしない場合、適切なエラーメッセージを返します:
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
      "content": "Error: No match found for replacement. Please check your text and try again.",
      "is_error": true
    }
  ]
}
ファイルの作成、読み取り、または編集にパーミッションの問題がある場合、適切なエラーメッセージを返します:
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
      "content": "Error: Permission denied. Cannot write to file.",
      "is_error": true
    }
  ]
}

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

Claudeにコードの修正または編集を依頼する場合、検査する必要があるファイルまたは対処する必要がある問題について具体的に説明してください。明確なコンテキストは、Claudeが正しいファイルを特定し、適切な変更を加えるのに役立ちます。あまり役に立たないプロンプト: 「コードを修正できますか?」より良いプロンプト: 「primes.pyファイルに構文エラーがあり、実行できません。修正できますか?」
特に複数のファイルまたは異なるディレクトリ内のファイルを操作する場合は、ファイルパスを明確に指定してください。あまり役に立たないプロンプト: 「ヘルパーファイルを確認してください」より良いプロンプト: 「utils/helpers.pyファイルにパフォーマンスの問題がないか確認できますか?」
アプリケーションにバックアップシステムを実装して、Claudeが編集を許可する前にファイルのコピーを作成してください。特に重要なコードまたは本番コードの場合は重要です。
def backup_file(file_path):
    """編集前にファイルのバックアップを作成します。"""
    backup_path = f"{file_path}.backup"
    if os.path.exists(file_path):
        with open(file_path, 'r') as src, open(backup_path, 'w') as dst:
            dst.write(src.read())
str_replaceコマンドは、置き換えるテキストの完全一致が必要です。アプリケーションは、古いテキストに対して正確に1つのマッチがあることを確認するか、適切なエラーメッセージを提供する必要があります。
def safe_replace(file_path, old_text, new_text):
    """正確に1つのマッチがある場合にのみテキストを置き換えます。"""
    with open(file_path, 'r') as f:
        content = f.read()
    
    count = content.count(old_text)
    if count == 0:
        return "Error: No match found"
    elif count > 1:
        return f"Error: Found {count} matches"
    else:
        new_content = content.replace(old_text, new_text)
        with open(file_path, 'w') as f:
            f.write(new_content)
        return "Successfully replaced text"
Claudeがファイルに変更を加えた後、テストを実行するか、コードが期待通りに機能することを確認して、変更を検証してください。
def verify_changes(file_path):
    """変更後にテストまたはチェックを実行します。"""
    try:
        # Pythonファイルの場合、構文エラーをチェックします
        if file_path.endswith('.py'):
            import ast
            with open(file_path, 'r') as f:
                ast.parse(f.read())
            return "Syntax check passed"
    except Exception as e:
        return f"Verification failed: {str(e)}"

価格とトークン使用量

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.x)700 tokens
text_editor_20250124 (Claude Sonnet 3.7 (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の機能を活用して開発ワークフローと生産性を向上させる方法を見るのが楽しみです。