Claude Code의 거의 모든 것은 Tool Use 입니다. MCP도 subagent도 Skills 역시요.

자손킴 @jasonkim@hackers.pub

이번 글에서는 지난글에 이어서 Claude가 도구를 사용하는 구체적인 방법을 알아본다. Claude가 사용할 수 있는 도구들의 목록은 Tools 섹션에 포함되어 있다. Tools 섹션에 대해서는 이전 글을 참고한다.

Tool Use 란?

Tool Use는 Claude가 외부 도구(함수)를 호출하여 실제 작업을 수행할 수 있게 하는 메커니즘이다. Claude는 텍스트 생성만으로는 수행할 수 없는 작업들, 예를 들어 파일 읽기, 명령어 실행, 웹 검색 등을 도구를 통해 수행한다.

Claude에게 사용 가능한 도구들의 스키마를 알려주면 Claude는 사용자의 요청을 분석하여 적절한 도구를 선택하고 필요한 파라미터와 함께 도구 사용을 요청한다. 에이전트(클라이언트)는 이 요청을 받아 실제로 도구를 실행하고 그 결과를 다시 Claude에게 전달한다.

Tools 섹션: 도구 정의하기

Claude가 도구를 사용하려면 먼저 어떤 도구가 있는지 알아야 한다. 에이전트는 API 요청의 tools 배열에 사용 가능한 도구들을 정의한다. 각 도구는 이름, 설명, 그리고 입력 스키마를 포함한다.

Bash 도구 정의 예시

{
  "name": "Bash",
  "description": "Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.\n\nIMPORTANT: This tool is for terminal operations like git, npm, docker, etc...",
  "input_schema": {
    "type": "object",
    "properties": {
      "command": {
        "type": "string",
        "description": "The command to execute"
      },
      "timeout": {
        "type": "number",
        "description": "Optional timeout in milliseconds (max 600000)"
      },
      "description": {
        "type": "string",
        "description": "Clear, concise description of what this command does in 5-10 words, in active voice."
      }
    },
    "required": ["command"],
    "additionalProperties": false,
    "$schema": "http://json-schema.org/draft-07/schema#"
  }
}

Glob 도구 정의 예시

{
  "name": "Glob",
  "description": "- Fast file pattern matching tool that works with any codebase size\n- Supports glob patterns like \"**/*.js\" or \"src/**/*.ts\"\n- Returns matching file paths sorted by modification time\n- Use this tool when you need to find files by name patterns",
  "input_schema": {
    "type": "object",
    "properties": {
      "pattern": {
        "type": "string",
        "description": "The glob pattern to match files against"
      },
      "path": {
        "type": "string",
        "description": "The directory to search in. If not specified, the current working directory will be used."
      }
    },
    "required": ["pattern"],
    "additionalProperties": false,
    "$schema": "http://json-schema.org/draft-07/schema#"
  }
}

도구 정의에서 description이 중요하다. Claude는 이 설명을 읽고 어떤 상황에서 해당 도구를 사용해야 하는지 판단한다. input_schema는 JSON Schema 형식으로 Claude가 도구를 호출할 때 어떤 파라미터를 어떤 형식으로 전달해야 하는지 정의한다.

Claude가 도구를 선정하는 방법

Claude가 도구를 선택하는 과정은 Messages API의 대화 흐름 속에서 이루어진다. 실제 예시를 통해 살펴보자.

사용자의 요청

사용자가 "이 NestJS 프로젝트에서 entity 구조를 탐색해주세요"라고 요청하면 에이전트는 다음과 같은 메시지를 API에 전송한다:

{
  "role": "user",
  "content": [
    {
      "type": "text",
      "text": "이 NestJS TypeScript 프로젝트에서 entity 구조를 탐색해주세요..."
    }
  ]
}

Claude의 도구 사용 요청

Claude는 사용자의 요청을 분석하고 작업 수행에 필요한 도구들을 선택하여 tool_use 블록으로 응답한다:

{
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "이 NestJS 프로젝트의 entity 구조를 철저하게 탐색하겠습니다."
    },
    {
      "type": "tool_use",
      "id": "toolu_01ABC123XYZ",
      "name": "Glob",
      "input": {
        "pattern": "**/*.entity.ts"
      }
    },
    {
      "type": "tool_use",
      "id": "toolu_01DEF456UVW",
      "name": "Bash",
      "input": {
        "command": "find /workspace/my-nestjs-project/src -type f -name \"*.ts\" | grep -E \"(entity|entities)\" | head -20",
        "description": "Find entity files in src directory"
      }
    }
  ]
}

여기서 주목할 점이 있다. Claude는 한 번의 응답에서 여러 도구를 동시에 요청할 수 있다. 위 예시에서는 GlobBash 두 도구를 병렬로 요청했다. 각 도구 요청에는 고유한 id가 부여되어 나중에 결과를 매핑할 때 사용된다.

응답의 stop_reason

Claude가 도구 사용을 요청하면 API 응답의 stop_reason"tool_use"로 설정된다:

{
  "id": "msg_01XYZ789ABC",
  "type": "message",
  "role": "assistant",
  "model": "claude-haiku-4-5-20251001",
  "content": [...],
  "stop_reason": "tool_use",
  "usage": {
    "input_tokens": 714,
    "output_tokens": 314
  }
}

stop_reason은 에이전트에게 "응답이 끝난 것이 아니라 도구 실행이 필요하다"는 신호를 보낸다.

에이전트는 tool_use 요청을 받으면 무엇을 하는가?

에이전트(클라이언트)가 stop_reason: "tool_use" 응답을 받으면 다음 단계를 수행해야 한다:

  1. 도구 요청 파싱: 응답의 content 배열에서 type: "tool_use" 블록들을 추출한다.

  2. 도구 실행: 각 도구 요청에 대해 실제 도구를 실행한다. 예를 들어:

    • Bash 도구 → 시스템에서 실제 bash 명령어 실행
    • Glob 도구 → 파일 시스템에서 패턴 매칭 수행
    • Read 도구 → 파일 내용 읽기
  3. 결과 수집: 각 도구의 실행 결과를 수집하고 tool_use_id와 함께 결과를 구성한다.

  4. 모델에 결과 전달: 수집한 결과를 tool_result 형식으로 모델에 다시 전송한다.

이 과정에서 에이전트는 도구 실행의 성공/실패 여부, 타임아웃 처리, 보안 검증 등을 담당한다. Claude는 도구의 스키마와 용도만 알 뿐 실제 실행은 에이전트의 몫이다.

에이전트가 모델에 도구 실행 결과를 알리는 방법

에이전트가 도구를 실행한 후에는 그 결과를 tool_result 형식으로 모델에 전달한다. 이 결과는 user role의 메시지로 전송된다.

tool_result 구조

{
  "role": "user",
  "content": [
    {
      "tool_use_id": "toolu_01DEF456UVW",
      "type": "tool_result",
      "content": "/workspace/my-nestjs-project/src/modules/chat/entities/dm-unlock.entity.ts\n/workspace/my-nestjs-project/src/modules/agora/entities/call-session.entity.ts\n/workspace/my-nestjs-project/src/modules/user/entities/user.entity.ts\n/workspace/my-nestjs-project/src/modules/user/entities/user-profile.entity.ts\n/workspace/my-nestjs-project/src/modules/item/entities/item.entity.ts\n...",
      "is_error": false
    },
    {
      "tool_use_id": "toolu_01ABC123XYZ",
      "type": "tool_result",
      "content": "/workspace/my-nestjs-project/src/modules/agora/entities/agora-event-log.entity.ts\n/workspace/my-nestjs-project/src/modules/agora/entities/call-participant.entity.ts\n/workspace/my-nestjs-project/src/modules/item/entities/item.entity.ts\n...",
      "cache_control": {
        "type": "ephemeral"
      }
    }
  ]
}

tool_result의 핵심 필드는 다음과 같다:

필드 설명
tool_use_id Claude가 요청한 도구의 고유 ID. 어떤 요청에 대한 결과인지 매핑
type 항상 "tool_result"
content 도구 실행의 실제 결과 (문자열)
is_error 도구 실행 실패 시 true
cache_control (선택) 프롬프트 캐싱을 위한 제어 옵션

전체 대화 흐름

tool_result를 받은 Claude는 결과를 분석하고 추가 도구가 필요하면 다시 tool_use를 요청한다. 충분한 정보가 모이면 최종 응답을 생성한다. 이 과정이 반복되면서 복잡한 작업도 단계별로 수행할 수 있다:

User → Claude: "entity 구조를 탐색해주세요"
Claude → Agent: tool_use (Glob, Bash)
Agent → Claude: tool_result (파일 목록)
Claude → Agent: tool_use (Read - 여러 파일)
Agent → Claude: tool_result (파일 내용들)
Claude → User: 최종 분석 결과

실제 예시에서 Claude는 먼저 GlobBash로 entity 파일 목록을 찾고 그 결과를 받은 후 Read 도구로 개별 파일들을 읽어 분석했다:

{
  "type": "text",
  "text": "좋습니다. 이제 주요 entity 파일들을 읽겠습니다."
},
{
  "type": "tool_use",
  "id": "toolu_01GHI789RST",
  "name": "Read",
  "input": {
    "file_path": "/workspace/my-nestjs-project/src/modules/user/entities/user.entity.ts"
  }
},
{
  "type": "tool_use",
  "id": "toolu_01JKL012MNO",
  "name": "Read",
  "input": {
    "file_path": "/workspace/my-nestjs-project/src/modules/user/entities/user-profile.entity.ts"
  }
}

마무리

Claude Code와 같은 에이전트는 모델에 사용할 수 있는 도구를 알려주어 도구를 능동적으로 사용하게 만듦으로써 유저의 실행환경과 상호 협력하여 도구를 실행한다. 유저에게 질문을 하는 AskUserQuestion도 도구이고 심지어 계획 모드를 빠져나가는 ExitPlanMode도 도구다.

MCP(Model Context Protocol) 서버가 제공하는 기능들도 결국 도구로 노출되며 Subagent 호출도 도구를 통해 이루어진다. Skills도 마찬가지다. 결국 Claude Code의 거의 모든 확장 기능은 Tool Use라는 하나의 메커니즘 위에서 동작한다.

이 구조를 이해하면 Claude Code가 어떻게 파일을 읽고, 코드를 실행하고, 웹을 검색하는지 명확해진다. 그리고 새로운 도구를 추가하거나 MCP 서버를 연동할 때도 같은 패턴이 적용된다는 것을 알 수 있다.

Read more →
8

If you have a fediverse account, you can quote this article from your own instance. Search https://hackers.pub/ap/articles/019b35f6-b710-7139-a8be-ca3a31676c62 on your instance and quote it. (Note that quoting is not supported in Mastodon.)