Skip to content

텍스트 편집기 도구 (Text Editor Tool)

Claude는 Anthropic 스키마의 텍스트 편집기 도구를 사용해 텍스트 파일을 보고 수정할 수 있어요. 덕분에 코드 디버깅, 수정, 개선 같은 작업을 더 쉽게 할 수 있고, 텍스트 문서도 함께 다룰 수 있죠. 이 도구를 쓰면 Claude가 파일과 직접 상호작용하면서, 단순히 변경을 제안하는 수준을 넘어서 직접 손을 대서 도와주는 식으로 동작해요.

모델별 지원 여부는 도구 참조 문서에서 확인할 수 있어요.

텍스트 편집기 도구를 언제 쓰나요?

어떤 상황에서 쓸 수 있을지 몇 가지 예시를 볼게요.

  • 코드 디버깅: 문법 오류부터 로직 문제까지, Claude가 코드의 버그를 찾아 고치게 해요.
  • 코드 리팩터링: 구조, 가독성, 성능을 목표로 한 편집을 통해 코드 품질을 올려요.
  • 문서 생성: 코드베이스에 docstring, 주석, README 파일을 추가하도록 요청해요.
  • 테스트 작성: 구현 분석을 바탕으로 코드의 유닛 테스트를 만들어 달라고 해요.

텍스트 편집기 도구 사용하기

str_replace_based_edit_tool이라는 이름의 텍스트 편집기 도구를 Messages API로 Claude에 제공하면 돼요.

큰 파일을 볼 때 잘라서 보여줄 길이를 제어하려면, 선택적으로 max_characters 파라미터를 지정할 수도 있어요.

client = anthropic.Anthropic()

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

도구는 다음 흐름으로 사용해요.

1. Claude에 텍스트 편집기 도구와 사용자 프롬프트를 제공

  • API 요청에 텍스트 편집기 도구를 포함해요.
  • "내 코드의 문법 오류를 고쳐줄 수 있어?" 같은, 파일을 살펴보거나 수정해야 하는 사용자 프롬프트를 준비해요.

2. Claude가 도구를 사용해 파일이나 디렉터리를 살펴봄

  • Claude는 무엇을 봐야 할지 스스로 판단한 뒤, view 명령으로 파일 내용을 확인하거나 디렉터리 목록을 읽어요.
  • API 응답에는 view 명령이 담긴 tool_use 콘텐츠 블록이 포함돼요.

3. view 명령을 실행하고 결과를 돌려줌

  • Claude의 도구 사용 요청에서 파일 또는 디렉터리 경로를 추출해요.
  • 파일 내용을 읽거나 디렉터리 목록을 가져와요.
  • 도구 구성에 max_characters 파라미터를 지정했다면, 그 길이만큼 파일 내용을 잘라요.
  • user 메시지에 tool_result 콘텐츠 블록을 담아 대화를 이어가며 결과를 Claude에게 돌려줘요.

4. Claude가 도구를 사용해 파일을 수정함

  • 파일이나 디렉터리를 살펴본 뒤, Claude는 필요한 경우 str_replace 명령으로 변경하거나 insert 명령으로 특정 줄 번호에 텍스트를 추가해요.
  • str_replace 명령을 쓸 때 Claude는 바꿀 기존 텍스트와 새 텍스트를 담은, 형식이 올바른 tool use 요청을 만들어요.

5. 편집을 실행하고 결과를 돌려줌

  • 도구 사용 요청에서 파일 경로, old text, new text를 추출해요.
  • 파일에서 텍스트 교체를 수행해요.
  • 결과를 Claude에게 돌려줘요.

6. Claude가 분석과 설명을 제공

  • 파일을 살펴보고 필요하면 편집한 뒤, Claude는 무엇을 발견했고 어떤 변경을 했는지 완전한 설명을 제공해요.

텍스트 편집기 도구의 명령어

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

view

view 명령어를 사용하면 Claude가 파일 내용을 살펴보거나 디렉터리 내용을 나열할 수 있어요. 전체 파일을 읽거나, 특정 줄 범위만 읽을 수도 있어요.

파라미터:

  • command: 반드시 "view"여야 해요.
  • path: 볼 파일 또는 디렉터리의 경로예요.
  • view_range (선택): 보고 싶은 시작·끝 줄 번호를 담은 두 정수로 된 배열이에요. 줄 번호는 1부터 시작하고, 끝 줄이 -1이면 파일 끝까지 읽어요. 이 파라미터는 파일을 볼 때만 적용되고 디렉터리에는 적용되지 않아요.

view 명령어 예시

파일 볼 때 예시:

{
  "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 명령어를 사용하면 파일 안의 특정 문자열을 새 문자열로 바꿀 수 있어요. 정밀한 편집을 할 때 써요.

파라미터:

  • command: 반드시 "str_replace"여야 해요.
  • path: 수정할 파일의 경로예요.
  • old_str: 바꿀 대상 텍스트예요 (공백과 들여쓰기를 포함해 정확히 일치해야 해요).
  • new_str: 기존 텍스트 대신 넣을 새 텍스트예요.

str_replace 명령어 예시

{
  "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 명령어를 사용하면 지정한 내용으로 새 파일을 만들 수 있어요.

파라미터:

  • command: 반드시 "create"여야 해요.
  • path: 새 파일을 만들 경로예요.
  • file_text: 새 파일에 쓸 내용이에요.

create 명령어 예시

{
  "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 명령어를 사용하면 파일의 특정 위치에 텍스트를 삽입할 수 있어요.

파라미터:

  • command: 반드시 "insert"여야 해요.
  • path: 수정할 파일의 경로예요.
  • insert_line: 텍스트를 삽입할 기준이 되는 줄 번호예요 (0이면 파일의 시작 부분).
  • insert_text: 삽입할 텍스트예요.

insert 명령어 예시

{
  "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가 텍스트 편집기 도구를 사용해 파이썬 파일의 문법 오류를 고치는 예시를 볼게요.

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

client = anthropic.Anthropic()

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

마지막으로 Claude가 수정 내용에 대한 완전한 설명을 제공해요:

{
  "id": "msg_01IjKlMnOpQrStUvWxYzAb",
  "model": "claude-opus-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."
    }
  ]
}

텍스트 편집기 도구 구현하기

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

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

1. 편집기 구현 초기화

파일 읽기, 쓰기, 수정 같은 파일 조작을 처리하는 헬퍼 함수를 만들어요. 실수에서 복구할 수 있도록 백업 기능 구현도 고려해 봐요.

2. 편집기 도구 호출 처리

명령 타입에 따라 Claude의 도구 호출을 처리하는 함수를 만들어요:

def handle_editor_tool(tool_call):
       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

3. 보안 조치 구현

검증과 보안 검사를 추가해요:

  • 디렉터리 트래버설(traversal) 공격을 막도록 파일 경로를 검증해요.
  • 변경하기 전에 백업을 만들어요.
  • 오류를 우아하게 처리해요.
  • 권한 검사를 구현해요.

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,
           }

오류 처리

텍스트 편집기 도구를 사용하다 보면 여러 오류가 발생할 수 있어요. 처리 방법을 살펴볼게요.

파일을 찾을 수 없음

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 명령은 바꿀 텍스트가 정확히 일치해야 해요. 애플리케이션은 old text와 정확히 한 번만 매치되도록 보장하거나, 적절한 오류 메시지를 제공해야 해요.

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

가격과 토큰 사용량

텍스트 편집기 도구는 Claude와 함께 쓰는 다른 도구들과 동일한 가격 구조를 사용해요. 사용 중인 Claude 모델에 따라 표준 입력·출력 토큰 가격이 적용돼요.

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

도구 추가 입력 토큰
text_editor_20250429 (Claude 4.x) 700 토큰

도구 가격에 대한 더 자세한 내용은 도구 사용 가격 문서를 참고해요.

다른 도구와 통합하기

텍스트 편집기 도구는 다른 Claude 도구들과 함께 사용할 수 있어요. 도구를 조합할 때는 다음을 확인해요:

  • 사용 중인 모델에 맞는 도구 버전을 매칭해요.
  • 요청에 포함된 모든 도구의 추가 토큰 사용량을 고려해요.

변경 로그

날짜 버전 변경 내용
2025년 7월 28일 text_editor_20250728 일부 문제를 수정하고 선택적 max_characters 파라미터를 추가한 업데이트된 텍스트 편집기 도구 릴리스. 그 외에는 text_editor_20250429와 동일해요.
2025년 4월 29일 text_editor_20250429 Claude 4용 텍스트 편집기 도구 릴리스. 이 버전은 undo_edit 명령을 제거했지만 다른 모든 기능은 유지해요. 도구 이름도 str_replace 기반 아키텍처를 반영하도록 업데이트됐어요.
2025년 3월 13일 text_editor_20250124 독립형 텍스트 편집기 도구 문서 도입. 이 버전은 Claude Sonnet 3.7에 최적화됐지만 이전 버전과 동일한 기능을 가져요.
2024년 10월 22일 text_editor_20241022 Claude Sonnet 3.5와 함께하는 텍스트 편집기 도구의 최초 릴리스 (은퇴됨; 모델 지원 중단 참고). view, create, str_replace, insert, undo_edit 명령을 통해 파일을 보고, 만들고, 편집하는 기능을 제공해요.

다음 단계

텍스트 편집기 도구를 더 편리하고 강력하게 사용할 수 있는 몇 가지 아이디어를 볼게요:

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

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

더 보기