Communitygithub.com

에이전트 도구 빌더

AI 에이전트가 세상과 상호작용하는 방법은 도구입니다. 잘 설계된 도구는 제대로 작동하는 에이전트와 환각, 무음 실패, 또는 불필요한 토큰 낭비를 하는 에이전트를 구분짓습니다. 이 스킬은 스키마부터 오류 처리까지 도구 설계를 다룹니다.

에이전트 도구 빌더란 무엇인가요?

이 스킬은 AI 에이전트가 외부 시스템과 상호작용하는 데 사용하는 도구를 설계하는 방법을 가르칩니다. JSON Schema 베스트 프랙티스, 설명 작성법, 유효성 검사, 그리고 AI 도구의 공용어가 되고 있는 MCP(Model Context Protocol) 표준을 다룹니다. 도구 설명이 구현보다 LLM 정확도에 더 중요하다는 핵심 통찰을 강조합니다. 20개 미만의 도구 유지, 명시적 오류 처리, 문자열 반환, 실행 전 유효성 검사 등 구체적인 원칙을 제공하며, Anthropic SDK, OpenAI Functions, Vercel AI SDK, LangChain Tool 등 주요 프레임워크에서의 구현 패턴을 다룹니다. 또한 MCP 서버 구축, 도구 러너 사용, 병렬 도구 실행에 대한 실용적인 예제도 포함되어 있어, 안정적이고 비용 효율적인 AI 에이전트를 구축하려는 모든 개발자에게 필수적인 가이드입니다.

지원 대상✓Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/SamuelChien/mega-skills-collection/tree/HEAD/agent-tool-builder

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

에이전트 도구 빌더은(는) 무엇을 하나요?

도구는 AI 에이전트가 세상과 상호작용하는 방법입니다. 잘 설계된 도구는 제대로 작동하는 에이전트와 환각, 무음 실패, 또는 불필요한 토큰을 10배 더 사용하는 에이전트를 구분짓습니다.

이 스킬은 스키마부터 오류 처리까지 도구 설계를 다룹니다. JSON Schema 베스트 프랙티스, LLM에 실제로 도움이 되는 설명 작성법, 유효성 검사, 그리고 AI 도구의 공용어가 되고 있는 MCP 표준을 다룹니다.

핵심 통찰: 도구 설명이 도구 구현보다 더 중요합니다. LLM은 코드를 절대 보지 않습니다. 스키마와 설명만 볼 뿐입니다.

원칙

  • LLM 정확성을 위해 설명 품질 > 구현 품질
  • 20개 미만의 도구를 목표로 하세요 - 더 많으면 혼란을 유발합니다
  • 모든 도구는 명시적인 오류 처리가 필요합니다 - 무음 실패는 에이전트를 망가뜨립니다
  • 객체가 아닌 문자열을 반환하세요 - LLM은 텍스트를 처리합니다
  • 실행 전 유효성 검사 게이트를 두세요 - 거부, 수정, 또는 에스컬레이션, 절대 무음 실패하지 마세요
  • 단위 테스트뿐만 아니라 LLM으로 도구를 테스트하세요

가능한 작업

  • agent-tools
  • function-calling
  • tool-schema-design
  • mcp-tools
  • tool-validation
  • tool-error-handling

범위

  • multi-agent-coordination → multi-agent-orchestration
  • agent-memory → agent-memory-systems
  • api-design → api-designer
  • llm-prompting → prompt-engineering

도구

표준

  • JSON Schema - 사용 시기: 모든 도구 정의 참고: 도구 스키마를 위한 보편적인 형식
  • MCP (Model Context Protocol) - 사용 시기: 재사용 가능한 크로스 플랫폼 도구 구축 시 참고: Anthropic의 오픈 표준, 널리 채택됨

프레임워크

  • Anthropic SDK - 사용 시기: Claude 기반 에이전트 참고: 베타 도구 러너가 대부분의 복잡성을 처리합니다
  • OpenAI Functions - 사용 시기: OpenAI 기반 에이전트 참고: 엄격 모드를 사용하여 스키마 준수를 보장하세요
  • Vercel AI SDK - 사용 시기: 다중 제공자 도구 처리 시 참고: 제공자 간 차이점을 추상화합니다
  • LangChain Tools - 사용 시기: LangChain 기반 에이전트 참고: MCP 도구를 LangChain 형식으로 변환합니다

패턴

도구 스키마 디자인

에이전트를 위한 명확하고 모호함 없는 JSON Schema 생성

사용 시기: 에이전트를 위한 새 도구를 정의할 때마다

도구 스키마 모범 사례:

1. 상세한 설명 (가장 중요)

나쁜 예 - 너무 모호함:
{
  "name": "get_stock_price",
  "description": "주가를 가져옵니다",
  "input_schema": {
    "type": "object",
    "properties": {
      "ticker": {"type": "string"}
    }
  }
}

좋은 예 - 포괄적임:
{
  "name": "get_stock_price",
  "description": "주어진 티커 심볼에 대한 현재 주가를 검색합니다.
    티커 심볼은 NYSE 또는 NASDAQ과 같은 주요 미국 증권 거래소에
    상장된 회사의 유효한 심볼이어야 합니다.
    USD 단위의 최신 거래 가격을 반환합니다.
    사용자가 현재 또는 최근 주가에 대해 물을 때 사용하세요.
    과거 데이터, 회사 정보 또는 예측을 제공하지 않습니다.",
  "input_schema": {
    "type": "object",
    "properties": {
      "ticker": {
        "type": "string",
        "description": "주식 티커 심볼, 예: Apple Inc.의 경우 AAPL"
      }
    },
    "required": ["ticker"]
  }
}

2. 매개변수 설명

모든 매개변수는 다음이 필요합니다:
- 무엇인지
- 예상되는 형식
- 예시 값
- 예외 케이스/제한 사항

{
  "location": {
    "type": "string",
    "description": "도시와 주/국가. 형식: 미국의 경우 'City, State'
      (예: 'San Francisco, CA'), 국제의 경우 'City, Country'
      (예: 'Tokyo, Japan'). 우편번호나 좌표를 사용하지 마세요."
  },
  "unit": {
    "type": "string",
    "enum": ["celsius", "fahrenheit"],
    "description": "온도 단위. 지정되지 않은 경우 사용자의 로케일로 기본 설정됩니다.
      미국 사용자의 경우 'fahrenheit', 다른 사용자의 경우 'celsius'를 사용하세요."
  }
}

3. 가능한 경우 열거형 사용

열거형은 LLM을 유효한 값으로 제한합니다:

"priority": {
  "type": "string",
  "enum": ["low", "medium", "high", "critical"],
  "description": "작업 우선순위 수준"
}

"action": {
  "type": "string",
  "enum": ["create", "read", "update", "delete"],
  "description": "수행할 CRUD 작업"
}

4. 필수 vs 선택

무엇이 필수인지 명확히 하세요:

{
  "type": "object",
  "properties": {
    "query": {...},      // 필수
    "limit": {...},      // 선택, 기본값 있음
    "offset": {...}      // 선택
  },
  "required": ["query"],
  "additionalProperties": false  // 엄격 모드
}

입력 예제가 있는 도구

예제를 사용하여 LLM 도구 사용을 안내

사용 시기: 중첩 객체나 형식에 민감한 입력이 있는 복잡한 도구

도구 사용 예제 (Anthropic 베타 기능):

예제는 스키마로 표현할 수 없는 구체적인 패턴을 Claude에게 보여줍니다.
복잡한 작업에서 정확도를 72%에서 90%로 향상시킵니다.

{ "name": "create_calendar_event", "description": "선택적 참석자 및 알림이 있는 캘린더 이벤트를 생성합니다", "input_schema": { "type": "object", "properties": { "title": {"type": "string", "description": "이벤트 제목"}, "start_time": { "type": "string", "description": "ISO 8601 날짜시간, 예: 2024-03-15T14:00:00Z" }, "duration_minutes": {"type": "integer", "description": "이벤트 지속 시간(분)"}, "attendees": { "type": "array", "items": {"type": "string"}, "description": "참석자의 이메일 주소" } }, "required": ["title", "start_time", "duration_minutes"] }, "input_examples": [ { "title": "팀 스탠드업", "start_time": "2024-03-15T09:00:00Z", "duration_minutes": 30, "attendees": ["[email protected]", "[email protected]"] }, { "title": "간단한 대화", "start_time": "2024-03-15T14:00:00Z", "duration_minutes": 15 }, { "title": "프로젝트 검토", "start_time": "2024-03-15T16:00:00-05:00", "duration_minutes": 60, "attendees": ["[email protected]"] } ] }

예제 디자인 원칙:

- 플레이스홀더가 아닌 현실적인 데이터 사용

- 최소, 부분 및 전체 사양 패턴 표시

- 간결하게 유지: 도구당 1-5개 예제

- 모호한 경우에 초점


### 도구 오류 처리

LLM이 복구할 수 있도록 도와주는 오류 반환

**사용 시기**: 실패할 수 있는 모든 도구

# 오류 처리 모범 사례:

## 정보를 제공하는 오류 반환

나쁜 예: {"error": "실패"} {"error": true}

좋은 예: { "error": true, "error_type": "not_found", "message": "날씨 데이터베이스에서 'Atlantis' 위치를 찾을 수 없습니다. 'San Francisco, CA'와 같은 실제 도시 이름을 제공해주세요.", "suggestions": ["San Francisco, CA", "Los Angeles, CA"] }


## 오류가 있는 Anthropic 도구 결과

{ "type": "tool_result", "tool_use_id": "toolu_01A09q90qw90lq917835lq9", "content": "오류: 날씨 데이터베이스에서 'Atlantis' 위치를 찾을 수 없습니다. 'San Francisco, CA'와 같은 실제 도시 이름을 제공해주세요.", "is_error": true }


## 처리해야 할 오류 범주
  1. 입력 유효성 검사 오류

    • 필수 매개변수 누락
    • 잘못된 형식
    • 범위를 벗어난 값
  2. 외부 서비스 오류

    • API 사용 불가
    • 속도 제한
    • 시간 초과
  3. 비즈니스 로직 오류

    • 리소스를 찾을 수 없음
    • 권한 거부
    • 충돌/중복
  4. 내부 오류

    • 예상치 못한 예외
    • 데이터 손상

## 구현 패턴

from dataclasses import dataclass from typing import Union

@dataclass class ToolResult: success: bool content: str error_type: str = None suggestions: list[str] = None

def to_response(self) -> dict:
    if self.success:
        return {"content": self.content}
    return {
        "content": f"오류 ({self.error_type}): {self.content}",
        "is_error": True
    }

def get_weather(location: str) -> ToolResult: # 입력 유효성 검사 if not location or len(location) < 2: return ToolResult( success=False, content="위치는 최소 2자 이상이어야 합니다", error_type="validation_error" )

try:
    data = weather_api.fetch(location)
    return ToolResult(
        success=True,
        content=f"온도: {data.temp}°F, 상태: {data.conditions}"
    )
except LocationNotFound:
    return ToolResult(
        success=False,
        content=f"'{location}' 위치를 찾을 수 없습니다",
        error_type="not_found",
        suggestions=weather_api.suggest_locations(location)
    )
except RateLimitError:
    return ToolResult(
        success=False,
        content="날씨 서비스 속도 제한이 초과되었습니다. 60초 후에 다시 시도하세요.",
        error_type="rate_limit"
    )
except Exception as e:
    return ToolResult(
        success=False,
        content=f"예상치 못한 오류: {str(e)}",
        error_type="internal_error"
    )

### MCP 도구 패턴

Model Context Protocol을 사용하여 도구 구축

**사용 시기**: 재사용 가능한 크로스 플랫폼 도구 생성 시

# MCP 도구 구현:

MCP(Model Context Protocol)는 AI 에이전트를 외부 시스템에 연결하기 위한 Anthropic의 오픈 표준입니다. 한 번 구축하면 어디서나 사용할 수 있습니다.


## 기본 MCP 서버 (TypeScript)

import { Server } from "@modelcontextprotocol/sdk/server"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio";

const server = new Server({ name: "weather-server", version: "1.0.0" });

// 도구 정의 server.setRequestHandler("tools/list", async () => ({ tools: [ { name: "get_weather", description: "특정 위치의 현재 날씨를 가져옵니다. 온도, 상태 및 습도를 반환합니다. 특정 도시에 대한 날씨 질문에 사용하세요.", inputSchema: { type: "object", properties: { location: { type: "string", description: "도시와 주, 예: 'San Francisco, CA'" }, unit: { type: "string", enum: ["celsius", "fahrenheit"], default: "fahrenheit" } }, required: ["location"] } } ] }));

// 도구 호출 처리 server.setRequestHandler("tools/call", async (request) => { const { name, arguments: args } = request.params;

if (name === "get_weather") { try { const weather = await fetchWeather(args.location, args.unit); return { content: [ { type: "text", text: JSON.stringify(weather) } ] }; } catch (error) { return { content: [ { type: "text", text: 오류: ${error.message} } ], isError: true }; } }

throw new Error(알 수 없는 도구: ${name}); });

// 서버 시작 const transport = new StdioServerTransport(); await server.connect(transport);


## MCP의 장점
  • LLM 제공자 간의 범용 호환성
  • 재사용 가능한 도구 라이브러리
  • 스트리밍 및 SSE 전송 지원
  • 내장된 관찰 가능성
  • 도구 액세스 제어

### 도구 러너 패턴

자동 처리를 위한 SDK 도구 러너 사용

**사용 시기**: 수동 관리 없이 도구 루프 구축 시

# 도구 러너 (Anthropic SDK 베타):

도구 러너는 도구 호출 루프를 자동으로 처리합니다:

  • Claude가 도구를 호출할 때 실행
  • 대화 상태 관리
  • 오류 재시도 처리
  • 스트리밍 지원 제공

## Python 예제

import anthropic from anthropic import beta_tool

client = anthropic.Anthropic()

@beta_tool def get_weather(location: str, unit: str = "fahrenheit") -> str: '''주어진 위치의 현재 날씨를 가져옵니다.

Args:
    location: 도시와 주, 예: San Francisco, CA
    unit: 온도 단위, 'celsius' 또는 'fahrenheit'
'''
# 구현
return json.dumps({"temperature": "72°F", "conditions": "맑음"})

@beta_tool def search_web(query: str) -> str: '''웹에서 정보를 검색합니다.

Args:
    query: 검색어
'''
# 구현
return json.dumps({"results": [...]})

도구 러너가 루프를 처리합니다

runner = client.beta.messages.tool_runner( model="claude-sonnet-4-5", max_tokens=1024, tools=[get_weather, search_web], messages=[ {"role": "user", "content": "파리의 날씨는 어때?"} ] )

각 메시지 처리

for message in runner: print(message.content[0].text)

또는 최종 결과만 가져오기

final = runner.until_done()


## Zod를 사용한 TypeScript

import { Anthropic } from '@anthropic-ai/sdk'; import { betaZodTool } from '@anthropic-ai/sdk/helpers/beta/zod'; import { z } from 'zod';

const anthropic = new Anthropic();

const getWeatherTool = betaZodTool({ name: 'get_weather', description: '주어진 위치의 현재 날씨를 가져옵니다', inputSchema: z.object({ location: z.string().describe('도시와 주, 예: San Francisco, CA'), unit: z.enum(['celsius', 'fahrenheit']).default('fahrenheit') }), run: async (input) => { // 타입 안전한 입력! return JSON.stringify({temperature: '72°F'}); } });

const runner = anthropic.beta.messages.toolRunner({ model: 'claude-sonnet-4-5', max_tokens: 1024, tools: [getWeatherTool], messages: [{ role: 'user', content: "파리의 날씨는 어때?" }] });

for await (const message of runner) { console.log(message.content[0].text); }


### 병렬 도구 실행

여러 도구를 동시에 실행

**사용 시기**: 병렬로 실행할 수 있는 독립적인 도구 호출

# 병렬 도구 실행:

기본적으로 Claude는 하나의 응답에서 여러 도구를 호출할 수 있습니다. 이는 독립적인 작업의 지연 시간을 획기적으로 줄여줍니다.


## 병렬 결과 처리

Claude가 여러 tool_use 블록을 반환합니다:

response.content = [ {"type": "text", "text": "두 위치를 모두 확인해보겠습니다..."}, {"type": "tool_use", "id": "toolu_01", "name": "get_weather", "input": {"location": "San Francisco, CA"}}, {"type": "tool_use", "id": "toolu_02", "name": "get_weather", "input": {"location": "New York, NY"}}, {"type": "tool_use", "id": "toolu_03", "name": "get_time", "input": {"timezone": "America/Los_Angeles"}}, {"type": "tool_use", "id": "toolu_04", "name": "get_time", "input": {"timezone": "America/New_York"}} ]

모든 도구를 동시에 실행합니다:

import asyncio

async def execute_in_parallel(tool_calls): tasks = [] for call in tool_calls: if call.type == "tool_use": tasks.append(execute_tool(call.name, call.input)) return await asyncio.gather(*tasks)

async def execute_tool(name, input_data): results = { "get_weather": lambda i: fetch_weather(i["location"]), "get_time": lambda i: fetch_time(i["timezone"]) } try: result = await resultsname return { "type": "tool_result", "tool_use_id": "corresponding_id", "content": str(result) } except Exception as e: return { "type": "tool_result", "tool_use_id": "corresponding_id", "content": f"오류: {str(e)}", "is_error": True }


## 고급 병렬 패턴

from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(max_workers=5) as executor: futures = [] for call in tool_calls: future = executor.submit(execute_tool, call.name, call.input) futures.append(future)

parallel_results = [f.result() for f in futures]

결과를 Claude에 다시 전송:

run_results = [ { "type": "tool_result", "tool_use_id": call.id, "content": result["content"] } for call, result in zip(tool_calls, parallel_results) if call.type == "tool_use" ]

final_response = client.beta.messages.create( model="claude-sonnet-4-5", max_tokens=1024, messages=[ {"role": "user", "content": "SF와 NY의 날씨와 시간을 알려줘"}, {"role": "assistant", "content": response.content}, {"role": "user", "content": run_results} ] )


## 병렬 실행을 위한 도구 설계 팁
  • 읽기 전용 도구(데이터 가져오기)를 부작용 도구(데이터 쓰기)와 분리하세요
  • 가능한 경우 도구가 멱등적이도록 만드세요
  • 느린 도구에는 항상 타임아웃을 설정하세요 (기본값: 30초)
  • 동시성 제한을 위해 스로틀링을 사용하세요 (권장: 5-10개의 동시 호출)
  • 충돌 가능성을 줄이기 위해 쓰기 도구를 직렬화하세요

## 문제 해결

일반적인 도구 설계 문제 및 해결 방법

### 무음 실패

**징후**: 에이전트가 잘못된 데이터로 계속 진행하거나, 오류 없이 이상하게 동작합니다.

**해결 방법**:

좋지 않음 - 무시됨:

try: result = api_call() return result except: return None

좋음 - LLM이 볼 수 있음:

try: result = api_call() return {"data": result, "success": True} except Exception as e: return { "data": None, "success": False, "error": f"API 호출 실패: {str(e)}" }


### 모호한 설명

**징후**: LLM이 잘못된 매개변수나 형식으로 도구를 호출합니다.

**해결 방법**: 명시적인 예제와 제약 조건을 포함한 설명을 작성하세요.

### 느린 도구

**징후**: 지연 시간이 높거나 토큰 낭비가 발생합니다.

**해결 방법**:
- 읽기 전용 도구 캐싱 구현
- 작고 집중된 도구 사용 (스위스 아미 나이프 도구 지양)
- 항상 타임아웃 설정
- 페이지네이션 API의 경우 페이지 크기를 제한하세요 (기본값 25개 항목)

### 과도한 도구

**징후**: LLM이 어떤 도구를 사용할지 혼란스러워하거나 잘못된 도구를 선택합니다.

**해결 방법**: 20개 미만의 도구를 유지하세요. 도구를 결합하거나, 계층화하거나, 가능한 경우 제거하세요.
- 관련 도구를 하나의 도구로 병합하세요 (예: get_user / update_user를 user_management로)
- 유사하거나 중복된 기능을 제거하세요
- 명확한 카테고리를 위해 도구 이름에 접두사를 사용하세요 (예: db_query, db_update)

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

SamuelChien/mega-skills-collection

Security audit, hardening, threat modeling (STRIDE/PASTA), Red/Blue Team, OWASP checks, code review, incident response, and infrastructure security for any project.

SamuelChien/mega-skills-collection

Arquitecto de Soluciones Principal y Consultor Tecnológico de Andru.ia. Diagnostica y traza la hoja de ruta óptima para proyectos de IA en español.

SamuelChien/mega-skills-collection

Ingeniero de Sistemas de Andru.ia. Diseña, redacta y despliega nuevas habilidades (skills) dentro del repositorio siguiendo el Estándar de Diamante.

SamuelChien/mega-skills-collection

Estratega de Inteligencia de Dominio de Andru.ia. Analiza el nicho específico de un proyecto para inyectar conocimientos, regulaciones y estándares únicos del sector. Actívalo tras definir el nicho.

SamuelChien/mega-skills-collection

2D game development principles. Sprites, tilemaps, physics, camera.

SamuelChien/mega-skills-collection

3D game development principles. Rendering, shaders, physics, cameras.

SamuelChien/mega-skills-collection

Expert in building 3D experiences for the web - Three.js, React Three Fiber, Spline, WebGL, and interactive 3D scenes. Covers product configurators, 3D portfolios, immersive websites, and bringing depth to web experiences.

SamuelChien/mega-skills-collection

Accessibility audit skill for scanning, fixing, and verifying WCAG 2.2 Level A and AA compliance across React, Next.js, Vue, Angular, Svelte, and plain HTML codebases. Use when auditing accessibility, fixing a11y violations, checking color contrast, generating compliance reports, or integrating accessibility checks into CI/CD pipelines.

SamuelChien/mega-skills-collection

Ab Test Analyzer - Auto-activating skill for Data Analytics. Triggers on: ab test analyzer, ab test analyzer Part of the Data Analytics skill category.

SamuelChien/mega-skills-collection

A B Test Config Creator - Auto-activating skill for ML Deployment. Triggers on: a b test config creator, a b test config creator Part of the ML Deployment skill category.

SamuelChien/mega-skills-collection

When the user wants to plan, design, or implement an A/B test or experiment. Also use when the user mentions "A/B test," "split test," "experiment," "test this change," "variant copy," "multivariate test," "hypothesis," "conversion experiment," "statistical significance," or "test this." For tracking implementation, see analytics-tracking.

SamuelChien/mega-skills-collection

Acceptance Criteria Creator - Auto-activating skill for Enterprise Workflows. Triggers on: acceptance criteria creator, acceptance criteria creator Part of the Enterprise Workflows skill category.

SamuelChien/mega-skills-collection

Use when a coding task should be driven end-to-end from issue intake through implementation, review, deployment, and acceptance verification with minimal human re-intervention.

SamuelChien/mega-skills-collection

Accessibility Audit Runner - Auto-activating skill for Frontend Development. Triggers on: accessibility audit runner, accessibility audit runner Part of the Frontend Development skill category.

SamuelChien/mega-skills-collection

You are an accessibility expert specializing in WCAG compliance, inclusive design, and assistive technology compatibility. Conduct audits, identify barriers, and provide remediation guidance.

SamuelChien/mega-skills-collection

Web accessibility patterns for WCAG 2.2 compliance including ARIA, keyboard navigation, screen readers, and testing

SamuelChien/mega-skills-collection

Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed, or change policy for the Discord channel.

SamuelChien/mega-skills-collection

Create unified specification packages across Business, Development, and Design teams. Staged elaboration (L0 Vision → L1 Requirements → L2 Team Detail → L3 Acceptance Criteria) to build shared understanding. Does not write code.

SamuelChien/mega-skills-collection

Research a company or person and get actionable sales intel. Works standalone with web search, supercharged when you connect enrichment tools or your CRM. Trigger with "research [company]", "look up [person]", "intel on [prospect]", "who is [name] at [company]", or "tell me about [company]".

SamuelChien/mega-skills-collection

Validate messaging consistency across website, GitHub repos, and local documentation generating read-only discrepancy reports. Use when checking content alignment or finding mixed messaging. Trigger with phrases like "check consistency", "validate documentation", or "audit messaging".

관련 스킬