Claude는 Anthropic에서 정의한 텍스트 에디터 도구를 사용하여 텍스트 파일을 보고 수정할 수 있으며, 코드나 다른 텍스트 문서를 디버그, 수정, 개선하는 데 도움을 줍니다. 이를 통해 Claude가 파일과 직접 상호작용하여 단순히 변경사항을 제안하는 것이 아니라 실질적인 도움을 제공할 수 있습니다.

텍스트 에디터 도구 사용 전

호환 가능한 모델 사용

Anthropic의 텍스트 에디터 도구는 여러 Claude 모델에서 사용할 수 있습니다:

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

Claude Sonnet 3.5는 텍스트 에디터 도구를 사용할 때 computer-use-2024-10-22 베타 헤더가 필요합니다.

텍스트 에디터 도구는 Claude 4와 Sonnet 3.7에서 일반적으로 사용 가능합니다.

Claude 4 모델용 최신 text_editor_20250429에는 undo_edit 명령이 포함되지 않습니다. 이 기능이 필요한 경우 해당 도구 버전과 함께 Claude 3.7 또는 Sonnet 3.5를 사용해야 합니다.

사용 사례 적합성 평가

텍스트 에디터 도구를 사용하는 경우의 예시:

  • 코드 디버깅: Claude가 구문 오류부터 논리 오류까지 코드의 버그를 식별하고 수정하도록 합니다.
  • 코드 리팩토링: Claude가 대상 편집을 통해 코드 구조, 가독성, 성능을 개선하도록 합니다.
  • 문서 생성: Claude에게 코드베이스에 docstring, 주석 또는 README 파일을 추가하도록 요청합니다.
  • 테스트 생성: Claude가 구현에 대한 이해를 바탕으로 코드에 대한 단위 테스트를 생성하도록 합니다.

텍스트 에디터 도구 사용

Messages API를 사용하여 Claude에게 텍스트 에디터 도구(str_replace_based_edit_tool이라는 이름)를 제공합니다:

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

텍스트 에디터 도구는 다음과 같은 방식으로 사용할 수 있습니다:

1

Claude에게 텍스트 에디터 도구와 사용자 프롬프트 제공

  • API 요청에 텍스트 에디터 도구를 포함합니다
  • “내 코드의 구문 오류를 수정할 수 있나요?”와 같이 파일을 검사하거나 수정해야 할 수 있는 사용자 프롬프트를 제공합니다
2

Claude가 도구를 사용하여 파일이나 디렉토리 검사

  • Claude는 살펴봐야 할 것을 평가하고 view 명령을 사용하여 파일 내용을 검사하거나 디렉토리 내용을 나열합니다
  • API 응답에는 view 명령이 포함된 tool_use 콘텐츠 블록이 포함됩니다
3

view 명령 실행 및 결과 반환

  • Claude의 도구 사용 요청에서 파일 또는 디렉토리 경로를 추출합니다
  • 파일의 내용을 읽거나 디렉토리 내용을 나열하여 Claude에게 반환합니다
  • tool_result 콘텐츠 블록이 포함된 새 user 메시지로 대화를 계속하여 결과를 Claude에게 반환합니다
4

Claude가 도구를 사용하여 파일 수정

  • 파일이나 디렉토리를 검사한 후 Claude는 str_replace와 같은 명령을 사용하여 변경하거나 insert를 사용하여 특정 줄 번호에 텍스트를 추가할 수 있습니다.
  • Claude가 str_replace 명령을 사용하는 경우, Claude는 이전 텍스트와 교체할 새 텍스트로 적절히 형식화된 도구 사용 요청을 구성합니다
5

편집 실행 및 결과 반환

  • Claude의 도구 사용 요청에서 파일 경로, 이전 텍스트, 새 텍스트를 추출합니다
  • 파일에서 텍스트 교체를 수행합니다
  • 결과를 Claude에게 반환합니다
6

Claude가 분석 및 설명 제공

  • 파일을 검사하고 편집한 후 Claude는 발견한 내용과 수행한 변경사항에 대한 완전한 설명을 제공합니다

텍스트 에디터 도구 명령

텍스트 에디터 도구는 파일을 보고 수정하기 위한 여러 명령을 지원합니다:

view

view 명령을 통해 Claude는 파일의 내용을 검사하거나 디렉토리의 내용을 나열할 수 있습니다. 전체 파일을 읽거나 특정 줄 범위를 읽을 수 있습니다.

매개변수:

  • command: “view”여야 합니다
  • path: 보려는 파일 또는 디렉토리의 경로
  • view_range (선택사항): 보려는 시작 및 끝 줄 번호를 지정하는 두 정수의 배열입니다. 줄 번호는 1부터 시작하며, 끝 줄에 -1은 파일 끝까지 읽는다는 의미입니다. 이 매개변수는 파일을 볼 때만 적용되며 디렉토리에는 적용되지 않습니다.

str_replace

str_replace 명령을 통해 Claude는 파일의 특정 문자열을 새 문자열로 교체할 수 있습니다. 이는 정확한 편집을 위해 사용됩니다.

매개변수:

  • command: “str_replace”여야 합니다
  • path: 수정할 파일의 경로
  • old_str: 교체할 텍스트 (공백과 들여쓰기를 포함하여 정확히 일치해야 함)
  • new_str: 이전 텍스트 대신 삽입할 새 텍스트

create

create 명령을 통해 Claude는 지정된 내용으로 새 파일을 생성할 수 있습니다.

매개변수:

  • command: “create”여야 합니다
  • path: 새 파일을 생성할 경로
  • file_text: 새 파일에 쓸 내용

insert

insert 명령을 통해 Claude는 파일의 특정 위치에 텍스트를 삽입할 수 있습니다.

매개변수:

  • command: “insert”여야 합니다
  • path: 수정할 파일의 경로
  • insert_line: 텍스트를 삽입할 줄 번호 (파일 시작의 경우 0)
  • new_str: 삽입할 텍스트

undo_edit

undo_edit 명령을 통해 Claude는 파일에 대한 마지막 편집을 되돌릴 수 있습니다.

이 명령은 Claude Sonnet 3.7과 Claude Sonnet 3.5에서만 사용할 수 있습니다. text_editor_20250429를 사용하는 Claude 4 모델에서는 지원되지 않습니다.

매개변수:

  • command: “undo_edit”여야 합니다
  • path: 마지막 편집을 취소할 파일의 경로

예시: 텍스트 에디터 도구로 구문 오류 수정

이 예시는 Claude 4가 텍스트 에디터 도구를 사용하여 Python 파일의 구문 오류를 수정하는 방법을 보여줍니다.

먼저 애플리케이션이 Claude에게 텍스트 에디터 도구와 구문 오류 수정 프롬프트를 제공합니다:

curl https://api.anthropic.com/v1/messages \
  -H "content-type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "claude-opus-4-20250514",
    "max_tokens": 1024,
    "tools": [
      {
        "type": "text_editor_20250429",
        "name": "str_replace_based_edit_tool"
      }
    ],
    "messages": [
      {
        "role": "user",
        "content": "There'\''s a syntax error in my primes.py file. Can you help me fix it?"
      }
    ]
  }'

Claude는 먼저 텍스트 에디터 도구를 사용하여 파일을 봅니다:

{
  "id": "msg_01XAbCDeFgHiJkLmNoPQrStU",
  "model": "claude-opus-4-20250514",
  "stop_reason": "tool_use",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I'll help you fix the syntax error in your primes.py file. First, let me take a look at the file to identify the issue."
    },
    {
      "type": "tool_use",
      "id": "toolu_01AbCdEfGhIjKlMnOpQrStU",
      "name": "str_replace_based_edit_tool",
      "input": {
        "command": "view",
        "path": "primes.py"
      }
    }
  ]
}

그러면 애플리케이션이 파일을 읽고 그 내용을 Claude에게 반환해야 합니다:

curl https://api.anthropic.com/v1/messages \
  -H "content-type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "claude-opus-4-20250514",
    "max_tokens": 1024,
    "tools": [
      {
        "type": "text_editor_20250429",
        "name": "str_replace_based_edit_tool"
      }
    ],
    "messages": [
      {
        "role": "user",
        "content": "There'\''s a syntax error in my primes.py file. Can you help me fix it?"
      },
      {
            "role": "assistant",
            "content": [
                {
                    "type": "text",
                    "text": "I'\''ll help you fix the syntax error in your primes.py file. First, let me take a look at the file to identify the issue."
                },
                {
                    "type": "tool_use",
                    "id": "toolu_01AbCdEfGhIjKlMnOpQrStU",
                    "name": "str_replace_based_edit_tool",
                    "input": {
                        "command": "view",
                        "path": "primes.py"
                    }
                }
            ]
        },
        {
            "role": "user",
            "content": [
                {
                    "type": "tool_result",
                    "tool_use_id": "toolu_01AbCdEfGhIjKlMnOpQrStU",
                    "content": "1: def is_prime(n):\n2:     \"\"\"Check if a number is prime.\"\"\"\n3:     if n <= 1:\n4:         return False\n5:     if n <= 3:\n6:         return True\n7:     if n % 2 == 0 or n % 3 == 0:\n8:         return False\n9:     i = 5\n10:     while i * i <= n:\n11:         if n % i == 0 or n % (i + 2) == 0:\n12:             return False\n13:         i += 6\n14:     return True\n15: \n16: def get_primes(limit):\n17:     \"\"\"Generate a list of prime numbers up to the given limit.\"\"\"\n18:     primes = []\n19:     for num in range(2, limit + 1)\n20:         if is_prime(num):\n21:             primes.append(num)\n22:     return primes\n23: \n24: def main():\n25:     \"\"\"Main function to demonstrate prime number generation.\"\"\"\n26:     limit = 100\n27:     prime_list = get_primes(limit)\n28:     print(f\"Prime numbers up to {limit}:\")\n29:     print(prime_list)\n30:     print(f\"Found {len(prime_list)} prime numbers.\")\n31: \n32: if __name__ == \"__main__\":\n33:     main()"
                }
            ]
        }
    ]
  }'

줄 번호

위 예시에서 view 도구 결과에는 각 줄에 줄 번호가 앞에 붙은 파일 내용이 포함됩니다(예: “1: def is_prime(n):”). 줄 번호는 필수는 아니지만 view_range 매개변수를 사용하여 파일의 특정 섹션을 검사하고 insert_line 매개변수를 사용하여 정확한 위치에 내용을 추가하는 데 필수적입니다.

Claude는 구문 오류를 식별하고 str_replace 명령을 사용하여 수정합니다:

{
  "id": "msg_01VwXyZAbCdEfGhIjKlMnO",
  "model": "claude-opus-4-20250514",
  "stop_reason": "tool_use",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I found the syntax error in your primes.py file. In the `get_primes` function, there is a missing colon (:) at the end of the for loop line. Let me fix that for you."
    },
    {
      "type": "tool_use",
      "id": "toolu_01PqRsTuVwXyZAbCdEfGh",
      "name": "str_replace_based_edit_tool",
      "input": {
        "command": "str_replace",
        "path": "primes.py",
        "old_str": "    for num in range(2, limit + 1)",
        "new_str": "    for num in range(2, limit + 1):"
      }
    }
  ]
}

그러면 애플리케이션이 편집을 수행하고 결과를 반환해야 합니다:

response = client.messages.create(
    model="claude-opus-4-20250514",
    max_tokens=1024,
    tools=[
        {
            "type": "text_editor_20250429",
            "name": "str_replace_based_edit_tool"
        }
    ],
    messages=[
        # Previous messages...
        {
            "role": "assistant",
            "content": [
                {
                    "type": "text",
                    "text": "I found the syntax error in your primes.py file. In the `get_primes` function, there is a missing colon (:) at the end of the for loop line. Let me fix that for you."
                },
                {
                    "type": "tool_use",
                    "id": "toolu_01PqRsTuVwXyZAbCdEfGh",
                    "name": "str_replace_based_edit_tool",
                    "input": {
                        "command": "str_replace",
                        "path": "primes.py",
                        "old_str": "    for num in range(2, limit + 1)",
                        "new_str": "    for num in range(2, limit + 1):"
                    }
                }
            ]
        },
        {
            "role": "user",
            "content": [
                {
                    "type": "tool_result",
                    "tool_use_id": "toolu_01PqRsTuVwXyZAbCdEfGh",
                    "content": "Successfully replaced text at exactly one location."
                }
            ]
        }
    ]
)

마지막으로 Claude는 수정에 대한 완전한 설명을 제공합니다:

{
  "id": "msg_01IjKlMnOpQrStUvWxYzAb",
  "model": "claude-opus-4-20250514",
  "stop_reason": "end_turn",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I've fixed the syntax error in your primes.py file. The issue was in the `get_primes` function at line 19. There was a missing colon (:) at the end of the for loop line.\n\nHere's what I changed:\n\nFrom:\n```python\nfor num in range(2, limit + 1)\n```\n\nTo:\n```python\nfor num in range(2, limit + 1):\n```\n\nIn Python, a colon is required at the end of statements that start a new code block, such as for loops, if statements, function definitions, etc. Without the colon, Python raises a syntax error because it doesn't know where the code block begins.\n\nYour code should now run correctly. The function will properly generate a list of prime numbers up to the specified limit."
    }
  ]
}

텍스트 에디터 도구 구현

텍스트 에디터 도구는 스키마가 없는 도구로 구현됩니다. 이 도구를 사용할 때 다른 도구와 달리 입력 스키마를 제공할 필요가 없습니다. 스키마는 Claude의 모델에 내장되어 있으며 수정할 수 없습니다.

도구 유형은 모델 버전에 따라 다릅니다:

  • Claude 4: type: "text_editor_20250429"
  • Claude Sonnet 3.7: type: "text_editor_20250124"
  • Claude Sonnet 3.5: type: "text_editor_20241022"
1

에디터 구현 초기화

파일 읽기, 쓰기, 수정과 같은 파일 작업을 처리하는 도우미 함수를 만듭니다. 실수로부터 복구하기 위한 백업 기능 구현을 고려하세요.

2

에디터 도구 호출 처리

명령 유형에 따라 Claude의 도구 호출을 처리하는 함수를 만듭니다:

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

보안 조치 구현

검증 및 보안 검사를 추가합니다:

  • 디렉토리 순회를 방지하기 위해 파일 경로를 검증합니다
  • 변경하기 전에 백업을 생성합니다
  • 오류를 우아하게 처리합니다
  • 권한 검사를 구현합니다
4

Claude의 응답 처리

Claude의 응답에서 도구 호출을 추출하고 처리합니다:

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

텍스트 에디터 도구를 구현할 때 다음 사항을 염두에 두세요:

  1. 보안: 도구가 로컬 파일시스템에 액세스할 수 있으므로 적절한 보안 조치를 구현하세요.
  2. 백업: 중요한 파일을 편집하기 전에 항상 백업을 생성하세요.
  3. 검증: 의도하지 않은 변경을 방지하기 위해 모든 입력을 검증하세요.
  4. 고유 매칭: 의도하지 않은 편집을 피하기 위해 교체가 정확히 한 위치와 일치하는지 확인하세요.

오류 처리

텍스트 에디터 도구를 사용할 때 다양한 오류가 발생할 수 있습니다. 이를 처리하는 방법에 대한 지침은 다음과 같습니다:

구현 모범 사례 따르기


가격 및 토큰 사용량

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

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

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

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

텍스트 에디터 도구를 다른 도구와 통합

텍스트 에디터 도구는 다른 Claude 도구와 함께 사용할 수 있습니다. 도구를 결합할 때 다음을 확인하세요:

  • 사용하는 모델과 도구 버전을 일치시킵니다
  • 요청에 포함된 모든 도구에 대한 추가 토큰 사용량을 고려합니다

변경 로그

날짜버전변경사항
2025년 4월 29일text_editor_20250429Claude 4용 텍스트 에디터 도구 출시. 이 버전은 undo_edit 명령을 제거하지만 다른 모든 기능을 유지합니다. 도구 이름이 str_replace 기반 아키텍처를 반영하도록 업데이트되었습니다.
2025년 3월 13일text_editor_20250124독립형 텍스트 에디터 도구 문서 도입. 이 버전은 Claude Sonnet 3.7에 최적화되었지만 이전 버전과 동일한 기능을 가지고 있습니다.
2024년 10월 22일text_editor_20241022Claude Sonnet 3.5와 함께 텍스트 에디터 도구의 초기 출시. view, create, str_replace, insert, undo_edit 명령을 통해 파일을 보고, 생성하고, 편집하는 기능을 제공합니다.

다음 단계

텍스트 에디터 도구를 더 편리하고 강력한 방식으로 사용하는 방법에 대한 몇 가지 아이디어는 다음과 같습니다:

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

텍스트 에디터 도구로 애플리케이션을 구축하면서 Claude의 기능을 활용하여 개발 워크플로우와 생산성을 향상시키는 방법을 보게 되어 기대됩니다.