핵심 · CH04
내 도구 만들기
지점별 월 목표처럼 회사 시스템에만 있는 정보는 내장 도구로 꺼낼 수 없습니다. 이럴 때 평범한 Python 함수를 도구로 감싸 에이전트에게 줍니다.
1. 도구는 평범한 함수입니다
실습 폴더의 sales_data.py에는 두 함수가 있습니다. revenue_by()는 CSV를 읽어 지점·상품·월별 합계를 내고, monthly_target()은 11월 목표를 돌려줍니다. 목표 값은 CSV에 없고 이 파일에만 있어서, 모델은 도구를 쓰지 않으면 알 방법이 없습니다.
sales_data.py
"""팝콘상사 매출 데이터 도우미 함수. 에이전트의 '도구'는 결국 이런 평범한 함수입니다."""
import csv
from collections import Counter
from pathlib import Path
CSV_PATH = Path(__file__).with_name("sales.csv")
# 회사 내부 시스템에만 있는 값이라고 가정합니다(모델은 모르는 정보).
TARGETS_2026_11 = {"강남점": 5_500_000, "홍대점": 5_500_000, "판교점": 4_500_000}
def load_rows():
with open(CSV_PATH, encoding="utf-8") as f:
return list(csv.DictReader(f))
def revenue_by(group_by: str, month: str = "") -> dict:
"""group_by: branch(지점) | product(상품) | month(월). month: '2026-11'처럼 쓰면 그 달만 셉니다."""
if group_by not in ("branch", "product", "month"):
return {"error": "group_by는 branch, product, month 중 하나여야 합니다"}
total = Counter()
for row in load_rows():
if month and not row["date"].startswith(month):
continue
key = row["date"][:7] if group_by == "month" else row[group_by]
total[key] += int(row["revenue"])
return dict(total.most_common())
def monthly_target(branch: str) -> dict:
"""2026년 11월 지점별 매출 목표(원)."""
if branch not in TARGETS_2026_11:
return {"error": f"{branch}은(는) 없는 지점입니다. 지점: {list(TARGETS_2026_11)}"}
return {"branch": branch, "month": "2026-11", "target": TARGETS_2026_11[branch]}2. 함수를 도구로 감싸 서버에 담습니다
Claude Agent SDK는 내 도구를 MCP 서버라는 묶음에 담아 붙입니다. 별도 프로그램을 띄우는 것이 아니라 내 Python 프로세스 안에서 도는 서버라서 설정이 짧습니다.
04_custom_tools.py
import asyncio
from typing import Any
from claude_agent_sdk import (
tool, create_sdk_mcp_server, query, ClaudeAgentOptions,
AssistantMessage, ResultMessage, TextBlock, ToolUseBlock,
)
from sales_data import revenue_by, monthly_target
@tool("revenue_by", "팝콘상사 매출 합계. group_by는 branch/product/month, month는 '2026-11' 형식(비우면 전체)",
{"group_by": str, "month": str})
async def revenue_by_tool(args: dict[str, Any]) -> dict[str, Any]:
result = revenue_by(args["group_by"], args.get("month", ""))
return {"content": [{"type": "text", "text": str(result)}]}
@tool("monthly_target", "지점의 2026년 11월 매출 목표(원)", {"branch": str})
async def monthly_target_tool(args: dict[str, Any]) -> dict[str, Any]:
return {"content": [{"type": "text", "text": str(monthly_target(args["branch"]))}]}
sales_server = create_sdk_mcp_server(name="sales", version="1.0.0",
tools=[revenue_by_tool, monthly_target_tool])
async def main():
options = ClaudeAgentOptions(
tools=[], # 내장 도구는 끄고
mcp_servers={"sales": sales_server}, # 내가 만든 도구만 붙입니다
allowed_tools=["mcp__sales__revenue_by", "mcp__sales__monthly_target"],
max_turns=8,
)
prompt = "2026년 11월 강남점 매출이 목표를 넘었는지 숫자로 알려 줘."
async for message in query(prompt=prompt, options=options):
if isinstance(message, AssistantMessage):
for block in message.content:
if isinstance(block, ToolUseBlock):
print("[도구]", block.name, block.input)
elif isinstance(block, TextBlock):
print("[답]", block.text)
elif isinstance(message, ResultMessage):
print("[끝]", message.subtype)
asyncio.run(main())@tool(이름, 설명, 입력 형식)— 모델은 이 설명을 읽고 언제 도구를 쓸지 정합니다. 설명을 구체적으로 쓸수록 잘 고릅니다.- 돌려주는 값 —
{"content": [{"type": "text", "text": ...}]}모양으로 돌려줍니다. - 도구 이름 — 붙인 뒤에는
mcp__서버이름__도구이름으로 부릅니다. 여기서는mcp__sales__revenue_by입니다. tools=[]— 내장 도구를 모두 끄고 내 도구만 남겼습니다. 파일을 건드릴 일이 없는 에이전트라면 이게 가장 안전합니다.
3. 실행합니다
python 04_custom_tools.py[도구] mcp__sales__revenue_by {'group_by': 'branch', 'month': '2026-11'}
[도구] mcp__sales__monthly_target {'branch': '강남점'}
[답] 11월 강남점 매출은 5,808,000원으로 목표 5,500,000원을 넘었습니다 ...
[끝] success
답의 숫자가 5,808,000원과 5,500,000원이면 맞습니다. 다르면 모델이 도구를 쓰지 않고 짐작한 것이니, 도구 설명을 더 분명히 쓰거나 시스템 프롬프트에 "숫자는 도구 결과만 쓴다"를 넣습니다(6장).
이미 있는 MCP 서버도 붙일 수 있습니다. GitHub, 데이터베이스, 브라우저처럼 다른 사람이 만든 MCP 서버도
mcp_servers에 명령어나 URL을 적어 연결합니다. 붙이는 방식은 같고, 허락은mcp__서버이름__*처럼 적을 수 있습니다.
이것만 기억하세요
@tool로 함수를 감싸고 create_sdk_mcp_server로 묶어 mcp_servers에 붙입니다. 허락할 때 이름은 mcp__서버__도구입니다.