텍스트 편집기 도구

텍스트 편집기 도구 (Text editor tool)

Anthropic 스키마 텍스트 편집기 도구를 주면 Claude가 텍스트 파일을 보고 수정할 수 있어요. 코드나 다른 텍스트 문서를 디버그·수정·개선하는 데 실질적인 도움을 주는 도구예요. Claude가 직접 파일과 상호작용하므로, 변경만 제안하는 게 아니라 손으로 직접 작업해 줘요. 이 페이지는 도구를 쓰는 방법과 view, str_replace, create, insert 명령 처리하는 방법을 다뤄요.

출처: 문서

본문

이 기능에 Zero Data Retention(ZDR)이 어떻게 적용되는지 알아보려면 [API와 데이터 보존](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention) 문서를 참고하세요.

Claude는 Anthropic 스키마 텍스트 편집기 도구로 텍스트 파일을 보고 수정할 수 있어요. 코드나 다른 텍스트 문서를 디버그·수정·개선하는 데 도움을 줘요. 이 도구로 Claude가 우리 파일과 직접 상호작용해서, 변경을 제안하는 것보다 직접 손을 대는 실질적인 도움을 줄 수 있어요.

모델 지원은 도구 레퍼런스를 참고하세요.

텍스트 편집기 도구를 쓸 때 (When to use the text editor tool)

텍스트 편집기 도구를 쓰는 예시는 다음과 같아요:

  • 코드 디버깅: Claude가 구문 오류부터 논리 문제까지 코드의 버그를 찾아 고치게 해요.
  • 코드 리팩터링: Claude가 타겟 편집으로 코드 구조, 가독성, 성능을 개선하게 해요.
  • 문서 생성: Claude에게 코드 베이스에 docstring, 주석, README 파일을 추가하게 해요.
  • 테스트 작성: Claude가 구현을 분석한 뒤 코드에 대한 단위 테스트를 만들게 해요.

텍스트 편집기 도구 사용하기 (Use the text editor tool)

Messages API로 텍스트 편집기 도구(이름 str_replace_based_edit_tool)를 Claude에게 제공하세요.

큰 파일을 볼 때 잘림을 제어하는 max_characters 매개변수를 선택적으로 지정할 수 있어요.

`max_characters`는 텍스트 편집기 도구의 `text_editor_20250728` 이상 버전에서만 호환돼요. ```bash cURL curl https://api.anthropic.com/v1/messages \ -H "content-type: application/json" \ -H "x-api-key: $ANTHR...KEY" \ -H "anthropic-version: 2023-06-01" \ -d '{ "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?" } ] }' ```
ant messages create \
  --model claude-opus-5-5 \
  --max-tokens 1024 \
  --tool '{type: text_editor_20250728, name: str_replace_based_edit_tool, max_characters: 10000}' \
  --message '{role: user, content: There is a syntax error in my primes.py file. Can you help me fix it?}'
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)
const anthropic = new Anthropic();

const response = await anthropic.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?"
    }
  ]
});

console.log(response);
var client = new AnthropicClient();

var response = await client.Messages.Create(
    new()
    {
        Model = Model.ClaudeOpus5_5,
        MaxTokens = 1024,
        Tools = [new ToolTextEditor20250728 { MaxCharacters = 10000 }],
        Messages =
        [
            new()
            {
                Role = Role.User,
                Content = "There's a syntax error in my primes.py file. Can you help me fix it?",
            },
        ],
    }
);

Console.WriteLine(response);
client := anthropic.NewClient()

response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
	Model:     anthropic.ModelClaudeOpus5_5,
	MaxTokens: 1024,
	Tools: []anthropic.ToolUnionParam{
		{OfTextEditor20250728: &anthropic.ToolTextEditor20250728Param{
			MaxCharacters: anthropic.Int(10000),
		}},
	},
	Messages: []anthropic.MessageParam{
		anthropic.NewUserMessage(anthropic.NewTextBlock("There's a syntax error in my primes.py file. Can you help me fix it?")),
	},
})
if err != nil {
	log.Fatal(err)
}
fmt.Println(response)
import com.anthropic.models.messages.ToolTextEditor20250728;
// ...
void main() {
  AnthropicClient client = AnthropicOkHttpClient.fromEnv();

  ToolTextEditor20250728 editorTool =
    ToolTextEditor20250728.builder()
      .maxCharacters(10000L)
      .build();

  MessageCreateParams params = MessageCreateParams.builder()
    .model(Model.CLAUDE_OPUS_5_5)
    .maxTokens(1024)
    .addTool(editorTool)
    .addUserMessage("There's a syntax error in my primes.py file. Can you help me fix it?")
    .build();

  Message message = client.messages().create(params);
  IO.println(message);
}
$client = new Client();

$response = $client->messages->create(
    model: 'claude-opus-5-5',
    maxTokens: 1024,
    tools: [ToolTextEditor20250728::with(maxCharacters: 10000)],
    messages: [
        [
            'role' => 'user',
            'content' => "There's a syntax error in my primes.py file. Can you help me fix it?",
        ],
    ],
);

echo $response;
client = Anthropic::Client.new

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?"
    }
  ]
)

puts response

텍스트 편집기 도구를 이렇게 사용해요:

* API 요청에 텍스트 편집기 도구를 포함하세요 * "Can you fix the syntax error in my code?"처럼 파일을 검사하거나 수정해야 할 수 있는 사용자 프롬프트를 제공하세요 * Claude가 무엇을 봐야 할지 판단하고 `view` 명령으로 파일 내용을 조사하거나 디렉토리 내용을 나열해요 * API 응답에 `view` 명령이 담긴 `tool_use` 콘텐츠 블록이 포함돼요 * Claude의 도구 사용 요청에서 파일 또는 디렉토리 경로를 추출하세요 * 파일 내용을 읽거나 디렉토리 내용을 나열하세요 * 도구 구성에 `max_characters` 매개변수가 지정됐다면 파일 내용을 그 길이로 잘라 주세요 * `tool_result` 콘텐츠 블록이 담긴 새 `user` 메시지로 대화를 이어가 결과를 Claude에게 반환하세요 * 파일이나 디렉토리를 조사한 뒤 Claude는 `str_replace` 같은 명령으로 변경하거나 `insert`로 특정 줄 번호에 텍스트를 추가할 수 있어요 * Claude가 `str_replace` 명령을 쓰면, 교체할 이전 텍스트와 새 텍스트가 담긴 올바른 형식의 도구 사용 요청을 구성해요 * Claude의 도구 사용 요청에서 파일 경로, 이전 텍스트, 새 텍스트를 추출하세요 * 파일에서 텍스트 교체를 수행하세요 * 결과를 Claude에게 반환하세요 * 파일을 조사하고 편집했을 수 있는 뒤 Claude는 무엇을 찾았고 어떤 변경을 했는지 완전한 설명을 제공해요

텍스트 편집기 도구 명령 (Text editor tool commands)

텍스트 편집기 도구는 파일을 보고 수정하는 여러 명령을 지원해요:

view

view 명령은 Claude가 파일 내용을 조사하거나 디렉토리 내용을 나열하게 해 줘요. 파일 전체나 특정 줄 범위를 읽을 수 있어요.

매개변수:

  • command: 반드시 "view"여야 함
  • path: 볼 파일 또는 디렉토리의 경로
  • view_range (선택): 볼 시작·끝 줄 번호를 지정하는 두 정수 배열. 줄 번호는 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: 이전 텍스트 자리에 넣을 새 텍스트
```json { "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: 새 파일에 쓸 내용
```json { "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: 삽입할 텍스트
```json { "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" } } ```

예시: 텍스트 편집기 도구로 구문 오류 고치기 (Example: Fixing a syntax error with the text editor tool)

이 예시는 Claude가 텍스트 편집기 도구로 Python 파일의 구문 오류를 고치는 방법을 보여줘요.

먼저 애플리케이션이 Claude에게 텍스트 편집기 도구와 구문 오류를 고치라는 프롬프트를 제공해요:

```bash cURL curl https://api.anthropic.com/v1/messages \ -H "content-type: application/json" \ -H "x-api-key: $ANTHR...KEY" \ -H "anthropic-version: 2023-06-01" \ -d '{ "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?" } ] }' ```
ant messages create \
  --model claude-opus-5-5 \
  --max-tokens 1024 \
  --tool '{type: text_editor_20250728, name: str_replace_based_edit_tool}' \
  --message '{role: user, content: There is a syntax error in my primes.py file. Can you help me fix it?}'
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)
const anthropic = new Anthropic();

const response = await anthropic.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?"
    }
  ]
});

console.log(response);
var client = new AnthropicClient();

var response = await client.Messages.Create(
    new()
    {
        Model = Model.ClaudeOpus5_5,
        MaxTokens = 1024,
        Tools = [new ToolTextEditor20250728()],
        Messages =
        [
            new()
            {
                Role = Role.User,
                Content = "There's a syntax error in my primes.py file. Can you help me fix it?",
            },
        ],
    }
);

Console.WriteLine(response);
client := anthropic.NewClient()

response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
	Model:     anthropic.ModelClaudeOpus5_5,
	MaxTokens: 1024,
	Tools: []anthropic.ToolUnionParam{
		{OfTextEditor20250728: &anthropic.ToolTextEditor20250728Param{}},
	},
	Messages: []anthropic.MessageParam{
		anthropic.NewUserMessage(anthropic.NewTextBlock("There's a syntax error in my primes.py file. Can you help me fix it?")),
	},
})
if err != nil {
	log.Fatal(err)
}
fmt.Println(response)
import com.anthropic.models.messages.ToolTextEditor20250728;
// ...
void main() {
  AnthropicClient client = AnthropicOkHttpClient.fromEnv();

  ToolTextEditor20250728 editorTool =
    ToolTextEditor20250728.builder().build();

  MessageCreateParams params = MessageCreateParams.builder()
    .model(Model.CLAUDE_OPUS_5_5)
    .maxTokens(1024)
    .addTool(editorTool)
    .addUserMessage("There's a syntax error in my primes.py file. Can you help me fix it?")
    .build();

  Message message = client.messages().create(params);
  IO.println(message);
}
$client = new Client();

$response = $client->messages->create(
    model: 'claude-opus-5-5',
    maxTokens: 1024,
    tools: [new ToolTextEditor20250728()],
    messages: [
        [
            'role' => 'user',
            'content' => "There's a syntax error in my primes.py file. Can you help me fix it?",
        ],
    ],
);

echo $response;
client = Anthropic::Client.new

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?"
    }
  ]
)

puts 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에게 반환해야 해요:

```bash cURL curl https://api.anthropic.com/v1/messages \ -H "content-type: application/json" \ -H "x-api-key: $ANTHR...KEY" \ -H "anthropic-version: 2023-06-01" \ -d '{ "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()" } ] } ] }' ```
ant messages create <<'YAML'
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):
          2:     """Check if a number is prime."""
          3:     if n <= 1:
          4:         return False
          5:     if n <= 3:
          6:         return True
          7:     if n % 2 == 0 or n % 3 == 0:
          8:         return False
          9:     i = 5
          10:     while i * i <= n:
          11:         if n % i == 0 or n % (i + 2) == 0:
          12:             return False
          13:         i += 6
          14:     return True
          15:
          16: def get_primes(limit):
          17:     """Generate a list of prime numbers up to the given limit."""
          18:     primes = []
          19:     for num in range(2, limit + 1)
          20:         if is_prime(num):
          21:             primes.append(num)
          22:     return primes
          23:
          24: def main():
          25:     """Main function to demonstrate prime number generation."""
          26:     limit = 100
          27:     prime_list = get_primes(limit)
          28:     print(f"Prime numbers up to {limit}:")
          29:     print(prime_list)
          30:     print(f"Found {len(prime_list)} prime numbers.")
          31:
          32: if __name__ == "__main__":
          33:     main()
YAML
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)
const anthropic = new Anthropic();

const response = await anthropic.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()'
        }
      ]
    }
  ]
});

console.log(response);
var client = new AnthropicClient();

var response = await client.Messages.Create(
    new()
    {
        Model = Model.ClaudeOpus5_5,
        MaxTokens = 1024,
        Tools = [new ToolTextEditor20250728()],
        Messages =
        [
            new()
            {
                Role = Role.User,
                Content = "There's a syntax error in my primes.py file. Can you help me fix it?",
            },
            new()
            {
                Role = Role.Assistant,
                Content = new MessageParamContent(new List<ContentBlockParam>
                {
                    new ContentBlockParam(new TextBlockParam()
                    {
                        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.",
                    }),
                    new ContentBlockParam(new ToolUseBlockParam()
                    {
                        ID = "toolu_01AbCdEfGhIjKlMnOpQrStU",
                        Name = "str_replace_based_edit_tool",
                        Input = new Dictionary<string, JsonElement>
                        {
                            ["command"] = JsonSerializer.SerializeToElement("view"),
                            ["path"] = JsonSerializer.SerializeToElement("primes.py"),
                        },
                    }),
                }),
            },
            new()
            {
                Role = Role.User,
                Content = new MessageParamContent(new List<ContentBlockParam>
                {
                    new ContentBlockParam(new ToolResultBlockParam()
                    {
                        ToolUseID = "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()",
                    }),
                }),
            },
        ],
    }
);

Console.WriteLine(response);
client := anthropic.NewClient()

response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
	Model:     anthropic.ModelClaudeOpus5_5,
	MaxTokens: 1024,
	Tools: []anthropic.ToolUnionParam{
		{OfTextEditor20250728: &anthropic.ToolTextEditor20250728Param{}},
	},
	Messages: []anthropic.MessageParam{
		anthropic.NewUserMessage(anthropic.NewTextBlock("There's a syntax error in my primes.py file. Can you help me fix it?")),
		anthropic.NewAssistantMessage(
			anthropic.NewTextBlock("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."),
			anthropic.NewToolUseBlock(
				"toolu_01AbCdEfGhIjKlMnOpQrStU",
				map[string]any{"command": "view", "path": "primes.py"},
				"str_replace_based_edit_tool",
			),
		),
		anthropic.NewUserMessage(
			anthropic.NewToolResultBlock(
				"toolu_01AbCdEfGhIjKlMnOpQrStU",
				"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()",
				false,
			),
		),
	},
})
if err != nil {
	log.Fatal(err)
}
fmt.Println(response)
AnthropicClient client = AnthropicOkHttpClient.fromEnv();

MessageCreateParams params = MessageCreateParams.builder()
  .model(Model.CLAUDE_OPUS_5_5)
  .maxTokens(1024)
  .addTool(ToolTextEditor20250728.builder().build())
  .addUserMessage("There's a syntax error in my primes.py file. Can you help me fix it?")
  .addAssistantMessageOfBlockParams(
    List.of(
      ContentBlockParam.ofText(
        TextBlockParam.builder()
          .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.")
          .build()
      ),
      ContentBlockParam.ofToolUse(
        ToolUseBlockParam.builder()
          .id("toolu_01AbCdEfGhIjKlMnOpQrStU")
          .name("str_replace_based_edit_tool")
          .input(
            ToolUseBlockParam.Input.builder()
              .putAdditionalProperty("command", JsonValue.from("view"))
              .putAdditionalProperty("path", JsonValue.from("primes.py"))
              .build()
          )
          .build()
      )
    )
  )
  .addUserMessageOfBlockParams(
    List.of(
      ContentBlockParam.ofToolResult(
        ToolResultBlockParam.builder()
          .toolUseId("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()")
          .build()
      )
    )
  )
  .build();

Message message = client.messages().create(params);
System.out.println(message);
$client = new Client();

$response = $client->messages->create(
    model: 'claude-opus-5-5',
    maxTokens: 1024,
    tools: [new ToolTextEditor20250728()],
    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()",
                ],
            ],
        ],
    ],
);

echo $response;
client = Anthropic::Client.new

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()"
        }
      ]
    }
  ]
)

puts response
**줄 번호**

앞선 예시에서 view 도구 결과는 각 줄 앞에 줄 번호가 붙은 파일 내용을 포함해요(예: "1: def is_prime(n):"). 줄 번호는 필수가 아니지만, view_range 매개변수로 파일의 특정 부분을 조사하고 insert_line 매개변수로 정확한 위치에 내용을 추가하는 데 필수적이에요.

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):"
      }
    }
  ]
}

그럼 애플리케이션이 편집을 수행하고 결과를 반환해야 해요:

```bash cURL curl https://api.anthropic.com/v1/messages \ -H "content-type: application/json" \ -H "x-api-key: $ANTHR...KEY" \ -H "anthropic-version: 2023-06-01" \ -d '{ "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." } ] } ] }' ```
ant messages create <<'YAML'
model: claude-opus-5-5
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.
YAML
response = client.messages.create(
    model="claude-opus-5-5",
    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.",
                }
            ],
        },
    ],
)

print(response)
const response = await client.messages.create({
  model: "claude-opus-5-5",
  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."
        }
      ]
    }
  ]
});

console.log(response);
var client = new AnthropicClient();

var response = await client.Messages.Create(
    new()
    {
        Model = Model.ClaudeOpus5_5,
        MaxTokens = 1024,
        Tools = [new ToolTextEditor20250728()],
        Messages =
        [
            // Previous messages...
            new()
            {
                Role = Role.Assistant,
                Content = new MessageParamContent(new List<ContentBlockParam>
                {
                    new ContentBlockParam(new TextBlockParam()
                    {
                        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.",
                    }),
                    new ContentBlockParam(new ToolUseBlockParam()
                    {
                        ID = "toolu_01PqRsTuVwXyZAbCdEfGh",
                        Name = "str_replace_based_edit_tool",
                        Input = new Dictionary<string, JsonElement>
                        {
                            ["command"] = JsonSerializer.SerializeToElement("str_replace"),
                            ["path"] = JsonSerializer.SerializeToElement("primes.py"),
                            ["old_str"] = JsonSerializer.SerializeToElement("    for num in range(2, limit + 1)"),
                            ["new_str"] = JsonSerializer.SerializeToElement("    for num in range(2, limit + 1):"),
                        },
                    }),
                }),
            },
            new()
            {
                Role = Role.User,
                Content = new MessageParamContent(new List<ContentBlockParam>
                {
                    new ContentBlockParam(new ToolResultBlockParam()
                    {
                        ToolUseID = "toolu_01PqRsTuVwXyZAbCdEfGh",
                        Content = "Successfully replaced text at exactly one location.",
                    }),
                }),
            },
        ],
    }
);

Console.WriteLine(response);
client := anthropic.NewClient()

response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
	Model:     anthropic.ModelClaudeOpus5_5,
	MaxTokens: 1024,
	Tools: []anthropic.ToolUnionParam{
		{OfTextEditor20250728: &anthropic.ToolTextEditor20250728Param{}},
	},
	Messages: []anthropic.MessageParam{
		// Previous messages...
		anthropic.NewAssistantMessage(
			anthropic.NewTextBlock("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."),
			anthropic.NewToolUseBlock(
				"toolu_01PqRsTuVwXyZAbCdEfGh",
				map[string]any{
					"command": "str_replace",
					"path":    "primes.py",
					"old_str": "    for num in range(2, limit + 1)",
					"new_str": "    for num in range(2, limit + 1):",
				},
				"str_replace_based_edit_tool",
			),
		),
		anthropic.NewUserMessage(
			anthropic.NewToolResultBlock(
				"toolu_01PqRsTuVwXyZAbCdEfGh",
				"Successfully replaced text at exactly one location.",
				false,
			),
		),
	},
})
if err != nil {
	log.Fatal(err)
}
fmt.Println(response)
AnthropicClient client = AnthropicOkHttpClient.fromEnv();

MessageCreateParams params = MessageCreateParams.builder()
  .model(Model.CLAUDE_OPUS_5_5)
  .maxTokens(1024)
  .addTool(ToolTextEditor20250728.builder().build())
  // Previous messages would go here
  .addAssistantMessageOfBlockParams(
    List.of(
      ContentBlockParam.ofText(
        TextBlockParam.builder()
          .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."
          )
          .build()
      ),
      ContentBlockParam.ofToolUse(
        ToolUseBlockParam.builder()
          .id("toolu_01PqRsTuVwXyZAbCdEfGh")
          .name("str_replace_based_edit_tool")
          .input(
            ToolUseBlockParam.Input.builder()
              .putAdditionalProperty("command", JsonValue.from("str_replace"))
              .putAdditionalProperty("path", JsonValue.from("primes.py"))
              .putAdditionalProperty(
                "old_str",
                JsonValue.from("    for num in range(2, limit + 1)")
              )
              .putAdditionalProperty(
                "new_str",
                JsonValue.from("    for num in range(2, limit + 1):")
              )
              .build()
          )
          .build()
      )
    )
  )
  .addUserMessageOfBlockParams(
    List.of(
      ContentBlockParam.ofToolResult(
        ToolResultBlockParam.builder()
          .toolUseId("toolu_01PqRsTuVwXyZAbCdEfGh")
          .content("Successfully replaced text at exactly one location.")
          .build()
      )
    )
  )
  .build();

Message message = client.messages().create(params);
System.out.println(message);
$client = new Client();

$response = $client->messages->create(
    model: 'claude-opus-5-5',
    maxTokens: 1024,
    tools: [new ToolTextEditor20250728()],
    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.',
                ],
            ],
        ],
    ],
);

echo $response;
client = Anthropic::Client.new

response = client.messages.create(
  model: "claude-opus-5-5",
  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."
        }
      ]
    }
  ]
)

puts 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."
    }
  ]
}

텍스트 편집기 도구 구현하기 (Implement the text editor tool)

텍스트 편집기 도구는 스키마 없는(schema-less) 도구로 구현돼요. 이 도구를 쓸 때는 다른 도구처럼 입력 스키마를 제공할 필요가 없어요. 스키마는 Claude 모델에 내장돼 있고 수정할 수 없어요.

도구 타입은 Claude 4 이상 모델에서 type: "text_editor_20250728"이에요.

파일을 읽고, 쓰고, 수정하는 파일 작업을 처리하는 헬퍼 함수를 만드세요. 실수에서 복구할 백업 기능 구현을 고려하세요. 명령 타입에 따라 Claude의 도구 호출을 처리하는 함수를 만드세요:
<CodeGroup exclude="shell">
  ```python Python
  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":
              # Read and return file contents
              pass
          case "str_replace":
              # Replace text in file
              pass
          case "create":
              # Create new file
              pass
          case "insert":
              # Insert text at location
              pass
  ```

  ```typescript TypeScript
  function handleEditorTool(toolCall: { input: { command?: string; path?: string } }): void {
    const inputParams = toolCall.input;
    const command = inputParams.command ?? "";
    const filePath = inputParams.path ?? "";

    switch (command) {
      case "view":
        // Read and return file contents
        break;
      case "str_replace":
        // Replace text in file
        break;
      case "create":
        // Create new file
        break;
      case "insert":
        // Insert text at location
        break;
    }
  }
  ```

  ```csharp C#
  static string HandleEditorTool(IReadOnlyDictionary<string, JsonElement> input)
  {
      input.TryGetValue("command", out var commandEl);
      input.TryGetValue("path", out var pathEl);
      var command = commandEl.ValueKind == JsonValueKind.String ? commandEl.GetString() : null;
      var filePath = pathEl.ValueKind == JsonValueKind.String ? pathEl.GetString() : null;

      if (command == "view")
      {
          // Read and return file contents
      }
      else if (command == "str_replace")
      {
          // Replace text in file
      }
      else if (command == "create")
      {
          // Create new file
      }
      else if (command == "insert")
      {
          // Insert text at location
      }
      return "";
  }
  ```

  ```go Go
  func handleEditorTool(input map[string]any) string {
  	command, _ := input["command"].(string)
  	filePath, _ := input["path"].(string)
  // ...

  	switch command {
  	case "view":
  		// Read and return file contents
  	case "str_replace":
  		// Replace text in file
  	case "create":
  		// Create new file
  	case "insert":
  		// Insert text at location
  	}
  	return ""
  }
  ```

  ```java Java
  static void handleEditorTool(Map<String, Object> input) {
    var command = (String) input.getOrDefault("command", "");
    var filePath = (String) input.getOrDefault("path", "");

    if (command.equals("view")) {
      // Read and return file contents
    } else if (command.equals("str_replace")) {
      // Replace text in file
    } else if (command.equals("create")) {
      // Create new file
    } else if (command.equals("insert")) {
      // Insert text at location
    }
  }
  ```

  ```php PHP
  function handle_editor_tool(array $input): string
  {
      $command = $input['command'] ?? '';
      $filePath = $input['path'] ?? '';

      if ($command === 'view') {
          // Read and return file contents
      } elseif ($command === 'str_replace') {
          // Replace text in file
      } elseif ($command === 'create') {
          // Create new file
      } elseif ($command === 'insert') {
          // Insert text at location
      }
      return '';
  }
  ```

  ```ruby Ruby
  def handle_editor_tool(input)
    command = input[:command] || ""
    file_path = input[:path] || ""

    case command
    when "view"
      # Read and return file contents
    when "str_replace"
      # Replace text in file
    when "create"
      # Create new file
    when "insert"
      # Insert text at location
    end
  end
  ```
</CodeGroup>
검증과 보안 점검을 추가하세요:
* 디렉토리 탐색을 막으려면 파일 경로를 검증하세요
* 변경 전에 백업을 만드세요
* 오류를 우아하게 처리하세요
* 권한 점검을 구현하세요
Claude 응답에서 도구 호출을 추출하고 처리하세요:
<CodeGroup exclude="shell">
  ```python Python
  # 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,
          }
  ```

  ```typescript TypeScript
  // Process tool use in Claude's response
  for (const block of response.content) {
    if (block.type === "tool_use") {
      // Execute the tool based on command
      const result = handleEditorTool(block);

      // Return result to Claude
      const toolResult = {
        type: "tool_result",
        tool_use_id: block.id,
        content: result
      };
    }
  }
  ```

  ```csharp C#
  // Process tool use in Claude's response
  foreach (var block in response.Content)
  {
      if (block.TryPickToolUse(out var toolUse))
      {
          var result = HandleEditorTool(toolUse.Input);
          var toolResult = new ToolResultBlockParam
          {
              ToolUseID = toolUse.ID,
              Content = result,
          };
      }
  }
  ```

  ```go Go
  // Process tool use in Claude's response
  for _, block := range response.Content {
  	if block.Type == "tool_use" {
  		var input map[string]any
  		if err := json.Unmarshal(block.Input, &input); err != nil {
  			log.Fatal(err)
  		}
  		result := handleEditorTool(input)

  		toolResult := anthropic.NewToolResultBlock(block.ID, result, false)
  // ...
  	}
  }
  ```

  ```java Java
  // Process tool use in Claude's response
  for (var block : response.content()) {
    if (block.type().equals("tool_use")) {
      // Execute the tool based on command
      var result = handleEditorTool(block);

      // Return result to Claude
      var toolResult = Map.of(
        "type", "tool_result",
        "tool_use_id", block.id(),
        "content", result
      );
    }
  }
  ```

  ```php PHP
  // Process tool use in Claude's response
  foreach ($response->content as $block) {
      if ($block->type === 'tool_use') {
          // Execute the tool based on command
          $result = handle_editor_tool($block->input);

          // Return result to Claude
          $toolResult = [
              'type' => 'tool_result',
              'tool_use_id' => $block->id,
              'content' => $result,
          ];
      }
  }
  ```

  ```ruby Ruby
  # Process tool use in Claude's response
  tool_results = response.content.filter_map do |block|
    next unless block.type == :tool_use

    {type: "tool_result", tool_use_id: block.id, content: handle_editor_tool(block.input)}
  end
  ```
</CodeGroup>
텍스트 편집기 도구를 구현할 때 명심하세요:
  1. 보안: 도구가 로컬 파일시스템에 접근할 수 있으니 적절한 보안 조치를 구현하세요.
  2. 백업: 중요한 파일에 편집을 허용하기 전에 항상 백업을 만드세요.
  3. 검증: 의도하지 않은 변경을 막으려면 모든 입력을 검증하세요.
  4. 고유 매칭: 교체가 정확히 한 위치와 일치하도록 해 의도하지 않은 편집을 피하세요.

오류 처리 (Handle errors)

텍스트 편집기 도구를 쓸 때 여러 오류가 발생할 수 있어요. 처리 방법 안내는 다음과 같아요:

Claude가 존재하지 않는 파일을 보거나 수정하려 하면 `tool_result`에 적절한 오류 메시지를 반환하세요:
```json
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
      "content": "Error: File not found",
      "is_error": true
    }
  ]
}
```
Claude의 `str_replace` 명령이 파일에서 여러 위치와 일치하면 적절한 오류 메시지를 반환하세요:
```json
{
  "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` 명령이 파일의 어떤 텍스트와도 일치하지 않으면 적절한 오류 메시지를 반환하세요:
```json
{
  "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
    }
  ]
}
```
파일을 만들거나, 읽거나, 수정하는 데 권한 문제가 있으면 적절한 오류 메시지를 반환하세요:
```json
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
      "content": "Error: Permission denied. Cannot write to file.",
      "is_error": true
    }
  ]
}
```

구현 모범 사례 따르기 (Follow implementation best practices)

Claude에게 코드를 고치거나 수정하라고 요청할 때 어떤 파일을 검사해야 하는지, 어떤 문제를 다뤄야 하는지 구체적으로 말하세요. 명확한 컨텍스트가 Claude가 올바른 파일을 찾고 적절한 변경을 하도록 도와줘요.
**덜 도움이 되는 프롬프트:** "Can you fix my code?"

**더 나은 프롬프트:** "There's a syntax error in my primes.py file that prevents it from running. Can you fix it?"
특히 여러 파일이나 다른 디렉토리의 파일을 다룰 때는 필요한 파일 경로를 명확히 지정하세요.
**덜 도움이 되는 프롬프트:** "Review my helper file"

**더 나은 프롬프트:** "Can you check my utils/helpers.py file for any performance issues?"
특히 중요하거나 프로덕션 코드에서는 Claude가 파일을 편집하기 전에 파일 복사본을 만드는 백업 시스템을 애플리케이션에 구현하세요.
<CodeGroup exclude="shell">
  ```python Python
  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())
  ```

  ```typescript TypeScript
  async function backupFile(filePath: string): Promise<void> {
    const backupPath = `${filePath}.backup`;
    try {
      await access(filePath);
      await copyFile(filePath, backupPath);
    } catch {
      // File does not exist; nothing to back up
    }
  }
  ```

  ```csharp C#
  static void BackupFile(string filePath)
  {
      var backupPath = $"{filePath}.backup";
      if (File.Exists(filePath))
      {
          File.Copy(filePath, backupPath, overwrite: true);
      }
  }
  ```

  ```go Go
  func backupFile(filePath string) error {
  	backupPath := filePath + ".backup"
  	data, err := os.ReadFile(filePath)
  	if err != nil {
  		if os.IsNotExist(err) {
  			return nil
  		}
  		return err
  	}
  	return os.WriteFile(backupPath, data, 0o644)
  }
  ```

  ```java Java
  static void backupFile(String filePath) throws IOException {
    Path source = Path.of(filePath);
    Path backupPath = Path.of(filePath + ".backup");
    if (Files.exists(source)) {
      Files.copy(source, backupPath, StandardCopyOption.REPLACE_EXISTING);
    }
  }
  ```

  ```php PHP
  function backup_file(string $filePath): void
  {
      $backupPath = $filePath . '.backup';
      if (file_exists($filePath)) {
          copy($filePath, $backupPath);
      }
  }
  ```

  ```ruby Ruby
  def backup_file(file_path)
    backup_path = "#{file_path}.backup"
    FileUtils.cp(file_path, backup_path) if File.exist?(file_path)
  end
  ```
</CodeGroup>
`str_replace` 명령은 교체할 텍스트의 정확한 일치를 요구해요. 애플리케이션은 이전 텍스트에 정확히 하나의 일치가 있는지 확인하거나 적절한 오류 메시지를 제공해야 해요.
<CodeGroup exclude="shell">
  ```python Python
  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"
  ```

  ```typescript TypeScript
  async function safeReplace(
    filePath: string,
    oldText: string,
    newText: string
  ): Promise<string> {
    const content = await readFile(filePath, "utf8");

    const count = content.split(oldText).length - 1;
    if (count === 0) {
      return "Error: No match found";
    } else if (count > 1) {
      return `Error: Found ${count} matches`;
    } else {
      const newContent = content.replace(oldText, newText);
      await writeFile(filePath, newContent, "utf8");
      return "Successfully replaced text";
    }
  }
  ```

  ```csharp C#
  static string SafeReplace(string filePath, string oldText, string newText)
  {
      var content = File.ReadAllText(filePath);

      var count = content.Split(oldText).Length - 1;
      if (count == 0)
      {
          return "Error: No match found";
      }
      else if (count > 1)
      {
          return $"Error: Found {count} matches";
      }
      else
      {
          var newContent = content.Replace(oldText, newText);
          File.WriteAllText(filePath, newContent);
          return "Successfully replaced text";
      }
  }
  ```

  ```go Go
  func safeReplace(filePath, oldText, newText string) string {
  	data, err := os.ReadFile(filePath)
  	if err != nil {
  		return fmt.Sprintf("Error: %v", err)
  	}
  	content := string(data)

  	count := strings.Count(content, oldText)
  	if count == 0 {
  		return "Error: No match found"
  	} else if count > 1 {
  		return fmt.Sprintf("Error: Found %d matches", count)
  	}

  	newContent := strings.Replace(content, oldText, newText, 1)
  	if err := os.WriteFile(filePath, []byte(newContent), 0o644); err != nil {
  		return fmt.Sprintf("Error: %v", err)
  	}
  	return "Successfully replaced text"
  }
  ```

  ```java Java
  static String safeReplace(String filePath, String oldText, String newText) throws IOException {
    String content = Files.readString(Path.of(filePath));

    int count = content.split(Pattern.quote(oldText), -1).length - 1;
    if (count == 0) {
      return "Error: No match found";
    } else if (count > 1) {
      return "Error: Found " + count + " matches";
    } else {
      String newContent = content.replace(oldText, newText);
      Files.writeString(Path.of(filePath), newContent);
      return "Successfully replaced text";
    }
  }
  ```

  ```php PHP
  function safe_replace(string $filePath, string $oldText, string $newText): string
  {
      $content = file_get_contents($filePath);

      $count = substr_count($content, $oldText);
      if ($count === 0) {
          return 'Error: No match found';
      } elseif ($count > 1) {
          return "Error: Found {$count} matches";
      } else {
          $newContent = str_replace($oldText, $newText, $content);
          file_put_contents($filePath, $newContent);
          return 'Successfully replaced text';
      }
  }
  ```

  ```ruby Ruby
  def safe_replace(file_path, old_text, new_text)
    content = File.read(file_path)

    count = content.scan(old_text).length
    if count == 0
      "Error: No match found"
    elsif count > 1
      "Error: Found #{count} matches"
    else
      new_content = content.sub(old_text) { new_text }
      File.write(file_path, new_content)
      "Successfully replaced text"
    end
  end
  ```
</CodeGroup>
Claude가 파일을 변경한 뒤에는 테스트를 실행하거나 코드가 예상대로 동작하는지 확인해서 변경 사항을 검증하세요.
<CodeGroup exclude="shell">
  ```python Python
  def verify_changes(file_path):
      """Run tests or checks after making changes."""
      try:
          # For Python files, check for syntax errors
          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)}"
  ```

  ```typescript TypeScript
  function verifyChanges(filePath: string): string {
    try {
      // For Python files, check for syntax errors
      if (filePath.endsWith(".py")) {
        execFileSync("python3", ["-m", "py_compile", filePath]);
        return "Syntax check passed";
      }
      return "No checks defined for this file type";
    } catch (err) {
      return `Verification failed: ${err}`;
    }
  }
  ```

  ```csharp C#
  static string VerifyChanges(string filePath)
  {
      try
      {
          // For Python files, check for syntax errors
          if (filePath.EndsWith(".py"))
          {
              var psi = new ProcessStartInfo("python3")
              {
                  RedirectStandardError = true,
              };
              psi.ArgumentList.Add("-m");
              psi.ArgumentList.Add("py_compile");
              psi.ArgumentList.Add(filePath);
              using var proc = Process.Start(psi)!;
              proc.WaitForExit();
              if (proc.ExitCode != 0)
              {
                  return $"Verification failed: {proc.StandardError.ReadToEnd()}";
              }
              return "Syntax check passed";
          }
          return "No checks defined for this file type";
      }
      catch (Exception e)
      {
          return $"Verification failed: {e.Message}";
      }
  }
  ```

  ```go Go
  func verifyChanges(filePath string) string {
  	// For Python files, check for syntax errors
  	if strings.HasSuffix(filePath, ".py") {
  		cmd := exec.Command("python3", "-m", "py_compile", filePath)
  		if out, err := cmd.CombinedOutput(); err != nil {
  			return fmt.Sprintf("Verification failed: %v: %s", err, out)
  		}
  		return "Syntax check passed"
  	}
  	return "No checks defined for this file type"
  }
  ```

  ```java Java
  static String verifyChanges(String filePath) {
    try {
      // For Python files, check for syntax errors
      if (filePath.endsWith(".py")) {
        Process proc = new ProcessBuilder("python3", "-m", "py_compile", filePath)
          .redirectErrorStream(true)
          .start();
        if (proc.waitFor() != 0) {
          return "Verification failed: " + new String(proc.getInputStream().readAllBytes());
        }
        return "Syntax check passed";
      }
      return "No checks defined for this file type";
    } catch (IOException | InterruptedException e) {
      return "Verification failed: " + e.getMessage();
    }
  }
  ```

  ```php PHP
  function verify_changes(string $filePath): string
  {
      // For Python files, check for syntax errors
      if (str_ends_with($filePath, '.py')) {
          exec('python3 -m py_compile ' . escapeshellarg($filePath) . ' 2>&1', $output, $exitCode);
          if ($exitCode !== 0) {
              return 'Verification failed: ' . implode("\n", $output);
          }
          return 'Syntax check passed';
      }
      return 'No checks defined for this file type';
  }
  ```

  ```ruby Ruby
  def verify_changes(file_path)
    # For Python files, check for syntax errors
    if file_path.end_with?(".py")
      if system("python3", "-m", "py_compile", file_path)
        "Syntax check passed"
      else
        "Verification failed: syntax error in #{file_path}"
      end
    else
      "No checks defined for this file type"
    end
  end
  ```
</CodeGroup>

가격과 토큰 사용량 (Pricing and token usage)

텍스트 편집기 도구는 Claude와 함께 쓰는 다른 도구와 같은 가격 구조를 사용해요. 사용 중인 Claude 모델에 따른 표준 입력·출력 토큰 가격을 따라요.

기본 토큰에 더해 텍스트 편집기 도구에는 다음 추가 입력 토큰이 필요해요:

Tool Additional input tokens
text_editor_20250429 (Claude 4.x) 700 tokens

도구 가격에 대한 더 자세한 정보는 도구 사용 가격을 참고하세요.

다른 도구와 텍스트 편집기 도구 통합하기 (Integrate the text editor tool with other tools)

텍스트 편집기 도구를 다른 Claude 도구와 함께 쓸 수 있어요. 도구를 결합할 때는:

  • 도구 버전을 사용 중인 모델과 일치시키세요
  • 요청에 포함된 모든 도구의 추가 토큰 사용량을 고려하세요

변경 로그 (Change log)

Date Version Changes
July 28, 2025 text_editor_20250728 Release of an updated text editor tool that fixes some issues and adds an optional max_characters parameter. It is otherwise identical to text_editor_20250429.
April 29, 2025 text_editor_20250429 Release of the text editor tool for Claude 4. This version removes the undo_edit command but maintains all other capabilities. The tool name has been updated to reflect its str_replace-based architecture.
March 13, 2025 text_editor_20250124 Introduction of standalone text editor tool documentation. This version is optimized for Claude Sonnet 3.7 but has identical capabilities to the previous version.
October 22, 2024 text_editor_20241022 Initial release of the text editor tool with Claude Sonnet 3.5 (retired; see Model deprecations). Provides capabilities for viewing, creating, and editing files through the view, create, str_replace, insert, and undo_edit commands.

더 알아보기 (Learn more)

  • 개발 워크플로와 통합하기: 텍스트 편집기 도구를 개발 도구나 IDE에 구축해 넣어 보세요
  • 코드 리뷰 시스템 만들기: Claude가 코드를 검토하고 개선하게 해 보세요
  • 디버깅 어시스턴트 구축하기: Claude가 코드의 문제를 진단하고 고치는 데 도움을 주는 시스템을 만드세요
  • 파일 형식 변환 구현하기: Claude가 파일을 한 형식에서 다른 형식으로 변환하게 해 보세요
  • 문서화 자동화: Claude가 코드를 자동으로 문서화하는 워크플로를 설정하세요

텍스트 편집기 도구는 Claude가 코드 베이스와 직접 작업하게 해 줘서, 디버깅부터 자동 문서화까지 워크플로를 지원해요.

Learn how to implement tool workflows for use with Claude. Execute shell commands with Claude.

도구 사용 개요 · Bash 도구