テキストエディタツール
Anthropicが定義したテキストエディタツールをClaudeに提供してファイルの表示、作成、編集を行わせ、view、str_replace、create、insertコマンドを処理します。
Claudeは、Anthropicスキーマのテキストエディタツールを使用してテキストファイルを表示および変更し、コードやその他のテキストドキュメントのデバッグ、修正、改善を支援できます。これにより、Claudeはファイルと直接やり取りでき、変更を提案するだけでなく、実践的な支援を提供できます。
モデルのサポートについては、ツールリファレンスを参照してください。
テキストエディタツールを使用するタイミング
テキストエディタツールを使用する場面の例は次のとおりです。
- コードのデバッグ: 構文エラーからロジックの問題まで、コード内のバグをClaudeに特定して修正させます。
- コードのリファクタリング: 的を絞った編集により、Claudeにコードの構造、可読性、パフォーマンスを改善させます。
- ドキュメントの生成: コードベースにdocstring、コメント、またはREADMEファイルを追加するようClaudeに依頼します。
- テストの作成: 実装の分析に基づいて、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の「tool use」(ツール使用)リクエストからファイルまたはディレクトリのパスを抽出します。
- ファイルの内容を読み取るか、ディレクトリの内容を一覧表示します。
- ツール設定で
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からのツール呼び出しを処理する関数を作成します。
Pythondef 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のレスポンスからツール呼び出しを抽出して処理します。
Python# 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_20250728(Claude 4.7以降のモデルおよびClaude Mythos Preview) | 974トークン |
text_editor_20250728(Claude 4.6以前のモデル) | 745トークン |
ツールの料金に関する詳細については、ツール使用の料金を参照してください。
テキストエディタツールを他のツールと統合する
テキストエディタツールは、他の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はコードベースを直接操作でき、デバッグから自動ドキュメント作成まで、さまざまなワークフローをサポートします。
利用可能状況
Claude API
- API
- Messages API
- モデル
- すべてのモデル
Claude Platform on AWS
- API
- Messages API
- モデル
- すべてのモデル
Amazon Bedrock
- API
- Messages API
- モデル
- すべてのモデル
Amazon Bedrock (InvokeModel)
- API
- Messages API
- モデル
- すべてのモデル
Claude Models on Google Cloud (Google managed)
- API
- Messages API
- モデル
- すべてのモデル
Microsoft Foundry
- API
- Messages API
- モデル
- すべてのモデル
データの取り扱い
データの取り扱いの概要対象エンドポイント
/v1/messagestext_editorツールを使用する場合
このページは役に立ちましたか?