テキストエディタツール
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)テキストエディタツールは次のように使用します。
Claudeにテキストエディタツールとユーザープロンプトを提供する
- APIリクエストにテキストエディタツールを含めます
- 「コードの構文エラーを修正してもらえますか?」など、ファイルの調査や変更が必要になる可能性のあるユーザープロンプトを提供します
Claudeがツールを使用してファイルまたはディレクトリを調査する
- Claudeは何を確認する必要があるかを判断し、
viewコマンドを使用してファイルの内容を調査したり、ディレクトリの内容を一覧表示したりします - APIレスポンスには、
viewコマンドを含むtool_useコンテンツブロックが含まれます
- Claudeは何を確認する必要があるかを判断し、
viewコマンドを実行して結果を返す
- Claudeのツール使用リクエストからファイルまたはディレクトリのパスを抽出します
- ファイルの内容を読み取るか、ディレクトリの内容を一覧表示します
- ツール設定で
max_charactersパラメータが指定されている場合は、ファイルの内容をその長さに切り捨てます tool_resultコンテンツブロックを含む新しいuserメッセージで会話を続けることで、結果をClaudeに返します
Claudeがツールを使用してファイルを変更する
- ファイルまたはディレクトリを調査した後、Claudeは
str_replaceなどのコマンドを使用して変更を加えたり、insertを使用して特定の行番号にテキストを追加したりすることがあります。 - Claudeが
str_replaceコマンドを使用する場合、Claudeは古いテキストとそれを置き換える新しいテキストを含む、適切にフォーマットされたツール使用リクエストを構築します
- ファイルまたはディレクトリを調査した後、Claudeは
編集を実行して結果を返す
- Claudeのツール使用リクエストからファイルパス、古いテキスト、新しいテキストを抽出します
- ファイル内でテキストの置換を実行します
- 結果をClaudeに返します
Claudeが分析と説明を提供する
- ファイルを調査し、場合によっては編集した後、Claudeは発見した内容と加えた変更についての完全な説明を提供します
テキストエディタツールのコマンド
テキストエディタツールは、ファイルの表示と変更のためのいくつかのコマンドをサポートしています。
view
viewコマンドを使用すると、Claudeはファイルの内容を調査したり、ディレクトリの内容を一覧表示したりできます。ファイル全体または特定の行範囲を読み取ることができます。
パラメータ:
command: "view"である必要がありますpath: 表示するファイルまたはディレクトリへのパスview_range(オプション): 表示する開始行番号と終了行番号を指定する2つの整数の配列。行番号は1から始まり、終了行に-1を指定するとファイルの末尾まで読み取ります。このパラメータはファイルを表示する場合にのみ適用され、ディレクトリには適用されません。
ファイルを表示する例:
{
"type": "tool_use",
"id": "toolu_01A09q90qw90lq917835lq9",
"name": "str_replace_based_edit_tool",
"input": {
"command": "view",
"path": "primes.py"
}
}ディレクトリを表示する例:
{
"type": "tool_use",
"id": "toolu_02B19r91rw91mr917835mr9",
"name": "str_replace_based_edit_tool",
"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_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):"
}
}create
createコマンドを使用すると、Claudeは指定された内容で新しいファイルを作成できます。
パラメータ:
command: "create"である必要がありますpath: 新しいファイルを作成するパスfile_text: 新しいファイルに書き込む内容
{
"type": "tool_use",
"id": "toolu_01A09q90qw90lq917835lq9",
"name": "str_replace_based_edit_tool",
"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)insert_text: 挿入するテキスト
{
"type": "tool_use",
"id": "toolu_01A09q90qw90lq917835lq9",
"name": "str_replace_based_edit_tool",
"input": {
"command": "insert",
"path": "primes.py",
"insert_line": 0,
"insert_text": "\"\"\"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"
}
}例: テキストエディタツールで構文エラーを修正する
この例では、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はまずテキストエディタツールを使用してファイルを表示します。
{
"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コマンドを使用して修正します。
{
"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は修正についての完全な説明を提供します。
{
"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"です。
エディタ実装を初期化する
ファイルの読み取り、書き込み、変更などのファイル操作を処理するヘルパー関数を作成します。ミスから復旧するためのバックアップ機能の実装を検討してください。
エディタツールの呼び出しを処理する
コマンドタイプに基づいて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セキュリティ対策を実装する
検証とセキュリティチェックを追加します。
- ディレクトリトラバーサルを防ぐためにファイルパスを検証する
- 変更を加える前にバックアップを作成する
- エラーを適切に処理する
- 権限チェックを実装する
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が存在しないファイルを表示または変更しようとした場合は、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):
"""Create a backup of a file before editing."""
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):
"""Replace text only if there's exactly one match."""
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):
"""Run tests or checks after making changes."""
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)}"料金とトークン使用量
テキストエディタツールは、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_20250429 | Claude 4向けテキストエディタツールのリリース。このバージョンではundo_editコマンドが削除されていますが、その他のすべての機能は維持されています。ツール名は、str_replaceベースのアーキテクチャを反映するように更新されました。 |
| 2025年3月13日 | text_editor_20250124 | 独立したテキストエディタツールのドキュメントの導入。このバージョンはClaude Sonnet 3.7向けに最適化されていますが、以前のバージョンと同一の機能を備えています。 |
| 2024年10月22日 | text_editor_20241022 | Claude Sonnet 3.5(廃止済み。モデルの非推奨を参照)でのテキストエディタツールの初回リリース。view、create、str_replace、insert、undo_editコマンドを通じて、ファイルの表示、作成、編集の機能を提供します。 |
次のステップ
テキストエディタツールをより便利で強力な方法で使用するためのアイデアをいくつか紹介します。
- 開発ワークフローと統合する: テキストエディタツールを開発ツールやIDEに組み込む
- コードレビューシステムを作成する: Claudeにコードをレビューさせ、改善を加えさせる
- デバッグアシスタントを構築する: Claudeがコードの問題の診断と修正を支援できるシステムを作成する
- ファイル形式の変換を実装する: Claudeにファイルをある形式から別の形式に変換する手助けをさせる
- ドキュメント作成を自動化する: Claudeがコードを自動的にドキュメント化するワークフローを設定する
テキストエディタツールにより、Claudeはコードベースを直接操作できるようになり、デバッグから自動ドキュメント作成までのワークフローをサポートします。
Was this page helpful?