모델이 사용할 수 있는 도구 설계하기
읽는 데 약 67분분 걸린다, 10절에 7개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.14판을 번역한 것이다. 원문 읽기
이 장을 마치면 the shop의 API를 Model Context Protocol 도구로 바꿀 수 있다. 이 도구의 이름, 설명, 입력 스키마, 결과, 오류는 모델이 그에 따라 행동할 수 있어야 한다. 또한 설명 하나를 바꾸었을 때 모델이 선택하는 도구가 어떻게 달라지는지도 측정할 수 있다. 이어지는 내용은 명세의 2026-07-28 개정판과 Python SDK인 mcp 2.3.0에 적용된다.
이 장의 모든 도구는 모델이 the shop의 고객 문의 하나에 답하도록 돕기 위해 존재한다. 그런데 the shop의 서버 shop-support에는 지금까지 도구가 하나뿐이다. Wrap one endpoint as a tool에서 만든 get_order_status이다. What MCP adds to an API에서는 리소스와 프롬프트도 하나씩 추가했지만, 도구 하나로는 대부분의 문의에 답할 수 없다. 고객은 어떤 주문이 어느 것이었는지, 환불하면 금액이 얼마인지, 환불을 해 달라는 요청, 상품의 재고가 있는지도 묻는다.
Model Context Protocol(MCP) 서버의 도구는 모델이 볼 수 있는 the shop의 유일한 부분이다. 모델은 the shop의 코드나 API를 읽지 않는다. 모델은 각 도구의 이름, 설명, 입력 스키마를 읽고 하나를 고른 뒤 인수를 채운다. 그런 다음 오류를 포함해 돌아오는 모든 내용을 읽는다. 따라서 도구는 질문할 수 없는 독자를 위해 설계하는 인터페이스이며, 정의의 모든 부분은 그 독자를 돕거나 오도할 수 있는 지점이다.
이 장에서는 이러한 문의에 대응하는 전체 도구 집합을 만들고, 각 설계 선택을 시험한다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Shape tools around tasks, not endpoints
The shop's API has five endpoints for orders, stock and new refunds, and the quickest way to give a model all five is one tool per endpoint. Generators that turn an API's routes into MCP tools do exactly that. Tools shaped like the API suit a programmer who already knows the workflow. A model has to rebuild the workflow from the tools' names every time: look this up, then compute that, then post it.
The alternative is to shape each tool around a task the model performs for the person it's helping. A task tool may call one endpoint, combine two, or split one in two, and it hides the steps a model would get wrong. Tools are model-controlled: the model decides which to call and with what (server features). The shape of the tools decides which decisions are left to the model.
This chapter rebuilds shop-support in lib.shop_tools, a shared module, so that every example and every later chapter uses the same five tools. The book still calls it the shop's server. Its resource and prompt return in Serve data as resources and prompts. Each of its tools serves one kind of ticket:
find_orderssearches one customer's orders by status or by the date placed. It calls the API's order list and adds a date filter the API doesn't have.get_order_statuslooks up one order by its ID, as in chapter 1.quote_refundworks out what a refund would be, and changes nothing.issue_refundmakes the refund from a quote. Above the policy's limit the shop's API holds it for a person (Return an input request instead of a result); within the limit, nothing in this chapter asks anyone. Consent is the host asking the user before a call that changes something, and it arrives in Ask for consent before side effects.check_stockreports one product's stock in each warehouse.
The module also holds endpoint_tools(), the list a one-tool-per-endpoint generator writes for the same API, so the two shapes can be compared. Both lists print with each tool's required arguments. Then ticket T-0024, "please refund the aluminium muffin tray on o2415", runs both ways.
1"""Two tool lists for the same API, one tool per endpoint as a generator writes them and the shop's five task tools, then2ticket T-0024's refund both ways. The point rests on two printed lines: the endpoint tool records the amount the model3sent, and quote_refund's amount is the server's own figure, which the code asserts is within the limit."""4import asyncio56import httpx27from mcp import Client89from lib import loopback, shop_api, shop_tools101112async def main() -> None:13 for tool in shop_tools.endpoint_tools():14 print("endpoint tool:", tool.name, tool.input_schema["required"])15 with loopback.serve(shop_api.create_app()) as base_url:16 async with Client(shop_tools.server_params(base_url)) as client:17 print("protocol revision:", client.protocol_version)18 for tool in (await client.list_tools()).tools:19 print("task tool:", tool.name, tool.input_schema.get("required", [])) # .get: no "required" key if none2021 # T-0024: "please refund the aluminium muffin tray on o2415". The endpoint tool post_refunds forwards22 # its arguments to POST /refunds, so the amount is whatever the model sends, such as the order's total.23 order = httpx2.get(f"{base_url}/orders/O-2415", headers={"X-API-Key": shop_api.DEMO_API_KEY}).json()24 refund = httpx2.post(f"{base_url}/refunds", headers={"X-API-Key": shop_api.DEMO_API_KEY},25 json={"order_id": "O-2415", "amount": order["total"], "reason": "damaged"})26 print("post_refunds status:", refund.status_code)27 print("post_refunds amount:", refund.json()["amount"])2829 quote = await client.call_tool("quote_refund", {"order_id": "O-2415", "sku": "KG-1050",30 "reason": "arrived damaged"})31 print("quote_refund amount:", quote.structured_content["amount"])32 print("quote_refund within limit:", quote.structured_content["within_limit"])33 assert quote.structured_content["within_limit"] # the muffin tray's line is under the refund policy's limit343536asyncio.run(main())
python tools-from-endpoints.pyendpoint tool: get_orders []
endpoint tool: get_orders_by_order_id ['order_id']
endpoint tool: get_stock_by_sku ['sku']
endpoint tool: post_refunds ['order_id', 'amount']
endpoint tool: post_stock_by_sku_recount ['sku']
protocol revision: 2026-07-28
task tool: find_orders ['customer_id']
task tool: get_order_status ['order_id']
task tool: quote_refund ['order_id']
task tool: issue_refund ['quote_id']
task tool: check_stock ['sku']
post_refunds status: 201
post_refunds amount: 49.96
quote_refund amount: 23.98
quote_refund within limit: True
The endpoint tools mirror the API. get_orders requires no argument at all, so a model can list every customer's orders. post_refunds requires an order_id and an amount. And post_stock_by_sku_recount puts a slow warehouse job in front of a support model. When a model sends the whole order's total to post_refunds, the API accepts it with status 201 and records a refund of €49.96, for a ticket about one product. The API checks only that the amount isn't more than the order's total, so the model's arithmetic is the only check on the money.
The task tools move those decisions into the server. find_orders requires a customer_id, so a search covers one customer, though the model still picks which one. quote_refund takes the order and, optionally, one SKU, and the server works out the amount itself: €23.98 for the muffin tray's line. That amount is within the refund policy's limit, as the quote's within_limit field says. issue_refund takes no amount at all, only the quote's ID. The stock recount stays off this server; Stream progress on a long call puts it on a server of its own.
Splitting the refund in two also follows most of the specification's guidance for state across calls. The pinned revision has no protocol session, so a tool that needs state from an earlier call gets it as an explicit handle: one tool returns an ID, and the next takes it as an argument. The guidance asks that the creating tool's description state how long the handle lives, and that a call with an expired or unknown handle return a tool execution error that says so (tools, "Stateful tools"). In the shop's server, quote_refund returns a quote_id valid for 15 minutes, and its description says so.
What the server doesn't do yet matters as much. It trusts the customer_id and order IDs the caller sends, so a model, or a ticket written to mislead one, can list any customer's orders and quote any order. Whoever holds a quote_id can spend it. The guidance asks for a handle "with sufficient entropy (e.g., a UUIDv4)" on a server without authentication, and, on one with it, a check of the caller's authorization against the handle "on every call" (tools, "Stateful tools"). The shop's quote IDs come from Python's secrets module, so no one can work one out from the order, but they're only 40 bits and bound to no customer. Secure tools against misuse takes the acting user from the verified token's subject, never from an argument. Where customers sign in, that is the customer. At the support team's host it is a member of staff, and the customer comes from the ticket record the server looks up and checks (Keep the server from acting as a confused deputy).
Working rule: Start from the tasks in your tickets or logs, not from your routes, and give each task one tool. Move every decision the model shouldn't make into the server, such as an amount or a sequence of calls. Use a handle when one task needs the result of another, state its lifetime in the description of the tool that creates it, make it unguessable, and check on every call that it belongs to the caller. Expose an endpoint as it stands only when the task and the endpoint are the same, as check_stock and GET /stock/{sku} are.
모델이 읽는 설명 작성하기
이전 절의 작업 도구는 모델이 올바른 도구를 고를 때에만 도움이 되며, 모델은 호스트가 보여 주는 내용을 보고 고른다. 이 책의 호스트 루프인 lib.host는 모델에 각 도구의 이름, 설명, 입력 스키마를 보여 준다. 사양은 설명을 클라이언트가 "사용 가능한 도구에 대한 LLM의 이해를 높이는 데" 쓸 수 있는 "힌트"라고 부른다(스키마, Tool.description).
공개된 설명 대부분은 품질이 낮다. 103개 서버의 도구 856개를 조사한 한 연구에서는 97.1%가 결함을 하나 이상 가지고 있었고, 56%는 도구가 무엇에 쓰이는지 분명하게 밝히지 않았다(Hasan 외, 2026). 인터페이스가 같은 두 도구를 대상으로 한 통제 실험에서는 한 도구의 설명만 고쳤더니, 시험한 모델 중 두 모델에서 그 도구의 사용량이 원래의 10배 넘게 늘었다(Faghih 외, 2025). 길다고 해서 저절로 나아지지는 않는다. 앞의 연구에서 설명을 완전히 다시 쓴 경우 작업 성공률은 중앙값으로 5.85포인트 올랐지만, 단계는 67% 더 늘었고 6건 중 1건은 결과가 나빠졌다.
도움이 되는 설명은 네 가지를 말한다. 도구가 무엇을 하는지, 이웃한 도구 대신 언제 이 도구를 쓰는지, 입력이 어떤 모습인지, 무엇이 돌아오는지다. Python SDK에서 도구의 설명은 그 함수의 docstring이며, description=를 decorator에 넘기면 그 값이 대신 쓰인다(도구). 이 책의 런타임인 Python 3.12.15에서 SDK는 docstring을 쓰인 그대로 전달한다(mcp/server/mcpserver/tools/base.py). 따라서 여러 줄에 걸친 docstring은 줄바꿈과 들여쓰기까지 모델에 보낸다. 쇼핑몰 서버는 설명을 사전 하나(DESCRIPTIONS)에 모아 두고 각 설명을 description=로 넘긴다.
이 예제는 티켓 여덟 건과 쇼핑몰의 도구 다섯 개를 모델에 세 번 보여 주며, 매번 설명 묶음만 다르게 한다. 다른 것은 모두 같다.
- 모호한 묶음은 도구마다 "환불 견적."처럼 엔드포인트 생성기가 쓸 법한 한 줄만 둔다.
- 초안 묶음은 쇼핑몰의 첫 초안으로, docstring으로 작성했다.
- 수정본 묶음은 초안의 결과를 읽은 뒤 쓴 쇼핑몰의 두 번째 초안이다.
여덟 건은 표본 추출이 아니라 쇼핑몰의 티켓 대기열에서 직접 골랐다. 고객의 주문 목록을 묻는 것이 두 건, 주문이 어디 있는지 묻는 것이 두 건, 환불에 관한 것이 세 건, 재고에 관한 것이 한 건이다. 주입된 지시나 잘못 입력된 주문 ID가 들어 있는 티켓은 없다. 실행하기 전에 모호한 묶음과 초안이 각각 첫 호출을 몇 건이나 맞힐지 예측해 보라.
모델은 이 책의 모든 녹화에 쓰는 Qwen3-4B-Instruct-2507이며, 모델이 도구를 고르게 하기에서 설정한 대로 llama.cpp로 CPU에서 실행한다. 스크립트 recordings/description_choices.py가 이 녹화 description-choices를 만들었으며, 티켓마다 응답을 하나씩 샘플링하고 온도는 0.7, 시드는 하나로 고정했다. 채점은 모델이 처음 호출하는 도구만 보고 인수는 보지 않는다. 티켓의 올바른 첫 도구는 쇼핑몰 데이터가 그 티켓에 붙인 도구인데, 한 가지만 다르다. issue_refund에는 quote_id가 필요하므로 환불 요청은 quote_refund로 시작한다.
1"""Predict, then run: eight of the shop's tickets and the same five tools, shown to the model with three sets of2descriptions: one-line ones, the shop's first draft, and its revision. Only the descriptions differ. The model's3replies are a recording (examples/data/recorded/description-choices/), made with recordings/description_choices.py."""4import asyncio5import json67from mcp import Client89from lib import shop_tools10from lib.host import ReplayModel, choose_tool11from lib.shop_data import load_shop1213TICKETS = ("T-0002", "T-0013", "T-0004", "T-0022", "T-0006", "T-0029", "T-0024", "T-0016")14SETS = {"vague": shop_tools.VAGUE_DESCRIPTIONS, "draft": shop_tools.DRAFT_DESCRIPTIONS,15 "revised": shop_tools.DESCRIPTIONS}16model = ReplayModel("description-choices") # the recorded replies, so no model runs here171819def right_tool(ticket) -> str:20 """The tool a correct host calls first. issue_refund takes a quote_id, so a refund starts with quote_refund."""21 return "quote_refund" if ticket.expected_tool == "issue_refund" else ticket.expected_tool222324async def main() -> None:25 shop = load_shop()26 async with Client(shop_tools.create_server()) as client: # in-process: listing tools calls no API27 listed = (await client.list_tools()).tools28 right = dict.fromkeys(SETS, 0)29 for ticket_id in TICKETS:30 ticket = shop.ticket(ticket_id)31 # the same tools each time, with only their descriptions swapped32 choices = {label: choose_tool(model, ticket, shop_tools.with_descriptions(listed, descriptions))33 for label, descriptions in SETS.items()}34 for label, choice in choices.items():35 right[label] += choice.tool == right_tool(ticket)36 if all(choice.tool == right_tool(ticket) for choice in choices.values()):37 print(f"{ticket_id} all three:", right_tool(ticket))38 continue39 print(f"{ticket_id} needs:", right_tool(ticket))40 for label, choice in choices.items():41 print(f"{ticket_id} {label}:", choice.tool or "none")42 if choices["revised"].tool == "quote_refund":43 print(f"{ticket_id} revised sku:", choices["revised"].arguments.get("sku"))44 print(f"{ticket_id} order's skus:", ", ".join(line.sku for line in shop.order(ticket.order_id).lines))45 print("sampling temperature:", json.loads((model.folder / "manifest.json").read_text())["sampling"]["temperature"])46 for label, count in right.items():47 print(f"{label} right:", f"{count} of {len(TICKETS)}")484950asyncio.run(main())
python vague-description-wrong-tool.pyT-0002 all three: find_orders
T-0013 all three: find_orders
T-0004 all three: get_order_status
T-0022 all three: get_order_status
T-0006 needs: quote_refund
T-0006 vague: get_order_status
T-0006 draft: get_order_status
T-0006 revised: quote_refund
T-0006 revised sku: KG-1031
T-0006 order's skus: KG-1043
T-0029 needs: quote_refund
T-0029 vague: find_orders
T-0029 draft: get_order_status
T-0029 revised: quote_refund
T-0029 revised sku: KG-1022
T-0029 order's skus: KG-1019
T-0024 needs: quote_refund
T-0024 vague: get_order_status
T-0024 draft: get_order_status
T-0024 revised: quote_refund
T-0024 revised sku: KG-1022
T-0024 order's skus: KG-1050, KG-1051
T-0016 all three: check_stock
sampling temperature: 0.7
vague right: 5 of 8
draft right: 5 of 8
revised right: 8 of 8
모호한 묶음은 5 of 8건에서 올바른 첫 도구를 골랐고, 초안도 5 of 8건으로 같았다. 이름과 매개변수만으로 주문 티켓 네 건과 재고 티켓 한 건은 충분히 처리되어, 세 묶음 모두 각각 같은 올바른 도구를 골랐다. 초안의 더 긴 문구는 선택이 갈린 환불 티켓 세 건에는 도움이 되지 않았다. "arrived with the enamelled saute pan cracked. what can you refund me"라는 티켓 T-0006에서 모호한 묶음은 get_order_status를, 초안은 get_order_status를 골랐다.
초안은 quote_refund가 무엇을 하는지는 말했지만, 그 도구가 있으면 주문을 따로 조회할 필요가 없다는 점은 말하지 않았다. 수정본은 두 도구 모두에서 이를 밝힌다. get_order_status는 환불 질문을 quote_refund로 보내고, quote_refund는 "주문을 직접 확인하기 때문에" 먼저 호출해 달라고 요청한다. 그러나 수정본이 바꾼 것은 이뿐이 아니다. quote_refund 설명의 첫머리도 다시 썼고, docstring이 아니라 description=로 넘기면서 초안의 줄바꿈과 들여쓰기도 없앴다. 세 가지를 모두 바꾼 수정본은 8 of 8건에서 올바른 첫 도구를 골랐다. 이 실행만으로는 어느 변경이 효과를 냈는지 알 수 없다.
수정본은 도구 선택은 바로잡았지만 인수는 바로잡지 못했다. 환불 호출 세 건 중 제대로 동작했을 것은 하나도 없다. T-0006에서 모델은 sku 매개변수 자체의 설명에 있는 예시인 SKU KG-1031를 보냈고, 모델이 보낸 SKU 세 개 중 어느 것도 해당 주문에 없었다. 실패를 도구 결과로 보고하기는 쇼핑몰 서버가 이 실수를 어떻게 잡아내는지 보여 준다. T-0013의 날짜는 세 묶음 모두에서 틀렸으며, 다음 절에서 다룬다.
이 횟수는 한 번의 측정으로 읽어야 한다. 모델 하나, 시드 하나, 직접 고른 티켓 여덟 건에서 나온 값이며, 시드가 달라지면 일부 선택이 바뀔 수 있다. 수정본은 같은 여덟 건의 결과를 읽은 뒤 작성했으므로 점수가 실제보다 좋게 나온다. 올바른 도구가 선택되는 빈도 측정하기는 티켓 대기열 전체에 걸쳐 선택을 측정하며, 이것이 판단의 기준이 되는 시험이다.
작업 규칙: 설명은 두 문장에서 네 문장으로 쓴다. 도구가 무엇을 하는지, 가장 혼동되는 도구 대신 언제 이 도구를 쓰는지, 입력이 어떤 모습인지, 무엇을 반환하는지를 담는다. 여러 줄 docstring에 기대지 말고 description=로 넘겨서, 모델이 작성한 문구를 정확히 그대로 읽게 한다. 그런 다음 배포할 모델이 실제 티켓에서 도구를 고르는 과정을 녹화하고, 잘못된 선택을 읽고, 그 선택이 가리키는 설명을 고친다. 어느 변경이 효과가 있었는지 알아야 할 때는 녹화마다 한 가지만 바꾸고, 변경을 작성하는 데 쓰지 않은 티켓에서 결과를 확인한다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Type inputs with JSON Schema
A description from the previous section tells the model what a tool wants, and an input schema makes the server enforce it. Every tool has an inputSchema, a JSON Schema object whose root has "type": "object". At the pinned revision any JSON Schema 2020-12 keyword may appear in it (changelog), including oneOf, if, then, else and $ref (schema, Tool.inputSchema). A schema with no $schema field is read as 2020-12, and implementations "MUST NOT" automatically follow a $ref that points to a network URI (base protocol), so by default a schema can't make a client download anything.
The schema does two jobs. It shows the model the shape of a valid call, and it lets the server reject an invalid one before any of the tool's code runs. The specification makes the server's half a requirement: servers "MUST" validate all tool inputs (tools, "Security considerations").
The Python SDK builds the schema from the function's type hints, and pydantic's Annotated[..., Field(...)] adds constraints to them (tools). The shop's server defines its ID types once. OrderId is a string with pattern=r"^O-\d{4}$", and CustomerId and Sku work the same way. find_orders takes status as a Literal of the five order statuses, placed_since as a date, and limit as an integer with ge=1, le=50. The schema the SDK built from those hints prints first. Then find_orders is called three ways: with three bad arguments at once, with a number sent as a string, and with the date the recorded model sent for ticket T-0013 in Write descriptions the model reads. That ticket asked for orders "since 12 Jun".
1"""find_orders' typed inputs: the JSON Schema the SDK builds from them, one result that names three rejected arguments,2a string the SDK converts without complaint, and a date that is valid but wrong. The point rests on the last two order3counts: a date that passes validation can still return the wrong orders."""4import asyncio5import json67from mcp import Client89from lib import loopback, shop_api, shop_tools101112async def main() -> None:13 with loopback.serve(shop_api.create_app()) as base_url:14 async with Client(shop_tools.server_params(base_url)) as client:15 tools = {tool.name: tool for tool in (await client.list_tools()).tools}16 for name, prop in tools["find_orders"].input_schema["properties"].items():17 rules = {k: v for k, v in prop.items() if k in ("pattern", "minimum", "maximum", "default")}18 # an optional argument's schema is anyOf: its type or enum, and null19 kinds = [p.get("enum") or p.get("format") or p["type"] for p in prop.get("anyOf", [prop])]20 print(f"{name}:", json.dumps(kinds), json.dumps(rules))2122 bad = await client.call_tool("find_orders", {"customer_id": "42", "status": "lost", "limit": 500})23 print("bad arguments is error:", bad.is_error)24 assert bad.is_error25 print(bad.content[0].text)2627 # "5" is a string; pydantic converts it to the integer 5 before the tool runs28 loose = await client.call_tool("find_orders", {"customer_id": "C-0085", "limit": "5"})29 print("string limit is error:", loose.is_error)30 assert not loose.is_error31 print("string limit orders:", len(loose.structured_content["orders"]))3233 # T-0013 asks for orders "since 12 Jun"; the recorded model sent 2023-06-12, a valid date34 wrong_year = await client.call_tool("find_orders", {"customer_id": "C-0085", "placed_since": "2023-06-12"})35 right_year = await client.call_tool("find_orders", {"customer_id": "C-0085", "placed_since": "2026-06-12"})36 print("since 2023-06-12 orders:", len(wrong_year.structured_content["orders"]))37 print("since 2026-06-12 orders:", len(right_year.structured_content["orders"]))383940asyncio.run(main())
python reject-bad-arguments.pycustomer_id: ["string"] {"pattern": "^C-\\d{4}$"}
status: [["placed", "shipped", "delivered", "cancelled", "returned"], "null"] {"default": null}
placed_since: ["date", "null"] {"default": null}
limit: ["integer"] {"default": 10, "maximum": 50, "minimum": 1}
bad arguments is error: True
Error executing tool find_orders: 3 validation errors for find_ordersArguments
customer_id
String should match pattern '^C-\d{4}$' [type=string_pattern_mismatch, input_value='42', input_type=str]
For further information visit https://errors.pydantic.dev/2.14/v/string_pattern_mismatch
status
Input should be 'placed', 'shipped', 'delivered', 'cancelled' or 'returned' [type=literal_error, input_value='lost', input_type=str]
For further information visit https://errors.pydantic.dev/2.14/v/literal_error
limit
Input should be less than or equal to 50 [type=less_than_equal, input_value=500, input_type=int]
For further information visit https://errors.pydantic.dev/2.14/v/less_than_equal
string limit is error: False
string limit orders: 5
since 2023-06-12 orders: 5
since 2026-06-12 orders: 1
Each hint became a schema keyword: pattern for the customer ID, enum for the status, "format": "date" for the date, and minimum and maximum for the limit. The call with three bad arguments came back as one failed result, and its text names every argument that failed, the rule it broke and the value sent. A model can correct all three in its next call.
The SDK is more lenient than the schema in one way. The schema says limit is an integer, but the call with "5" succeeded and returned 5 orders. Pydantic, which validates the arguments, converts a numeric string to an integer by default. That's harmless here. Where a string and a number must stay distinct, declare the field with Field(strict=True). Pydantic also drops, without an error, any argument the schema doesn't declare (mcp/server/mcpserver/utilities/func_metadata.py), which Keep the server from acting as a confused deputy relies on.
The date is the mistake no schema catches. The ticket's "12 Jun" has no year, and the model sent 2023-06-12, a valid date three years before the shop's data ends. The call passed validation and returned 5 orders, every order the customer has, instead of the 1 placed since June 12 of the shop's year. The schema checks the form. The meaning has to come from somewhere else, such as the host putting the ticket's date in the prompt, or the description saying how to read a date without a year.
The specification isn't consistent about where a rejected argument goes. Its tools page lists input validation among tool execution errors, which come back as a result. Its schema reference lists "invalid tool arguments" under the JSON-RPC error -32602 (schema, InvalidParamsError). The SDK follows the tools page, and so does this book. Clients "SHOULD" pass execution errors to the model, but only "MAY" pass protocol errors, which the specification says are "less likely to result in successful recovery" (tools, "Error handling"). A result is the path a model can count on reading.
Working rule: Type every argument as narrowly as the API allows: a pattern for IDs, an enum for fixed values, bounds for counts and a format for dates. Let the SDK reject bad calls before your code runs, and return every failure at once. Don't trust the schema with meaning, because a valid date can still be the wrong date. Check what the schema can't express inside the tool, and say in the description how to fill a value that tickets often leave incomplete.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Return structured content with an output schema
The inputs from the previous section have a schema, and results can have one too. A tool may declare an outputSchema, and its result then carries structuredContent: the result's data as JSON that a program can read without parsing text (tools, "Structured content"). When a tool declares an output schema, the server "MUST" return results that conform to it, and clients "SHOULD" validate them. A tool that returns structured content "SHOULD" also return it serialized as JSON in a text block, for clients that read only text. The same section notes that structuredContent is the server's result data, unrelated to a model's "structured outputs".
The output schema serves the host's code more than the model. Code can branch on a field called within_limit instead of searching a sentence for "exceeds", and a test can check a field instead of a string. structuredContent may be any JSON value at the pinned revision (changelog). Revision 2025-11-25 required an object (tools at 2025-11-25), which Migrate a 2025-era server covers.
The Python SDK builds the output schema from the function's return type. Primitive types, None, lists and unions are wrapped in {"result": ...}. Pydantic models, TypedDicts, dataclasses and dict[str, ...] aren't (structured output; mcp/server/mcpserver/utilities/func_metadata.py). quote_refund returns RefundQuote, a pydantic model with the quote's ID, the order, the SKU, the amount, the policy limit, within_limit and the quote's lifetime in seconds. Quoting order O-2289 for ticket T-0006 with no SKU, so the quote covers the whole order, shows the structured result. A second server then has one tool that returns the same amount as a bare string, to show the wrapper.
1"""quote_refund returns a pydantic model, so the SDK publishes its output schema and returns structuredContent; a tool2that returns a bare string gets a {"result": ...} wrapper instead. The point rests on the bare structured content line,3and the quote's within-limit flag and text block, which the code asserts."""4import asyncio5import json67from mcp import Client8from mcp.server.mcpserver import MCPServer910from lib import loopback, shop_api, shop_tools11from lib.shop_data import load_shop, money1213bare = MCPServer("bare-return")141516@bare.tool()17def refund_amount(order_id: str) -> str:18 """The refund for a whole order, as a decimal string."""19 return money(load_shop().order(order_id).total_cents)202122async def main() -> None:23 with loopback.serve(shop_api.create_app()) as base_url:24 async with Client(shop_tools.server_params(base_url)) as client:25 tools = {tool.name: tool for tool in (await client.list_tools()).tools}26 print("output schema requires:", ", ".join(tools["quote_refund"].output_schema["required"]))27 quote = await client.call_tool("quote_refund", {"order_id": "O-2289", "reason": "arrived cracked"})28 shown = {**quote.structured_content, "quote_id": "(random)"} # quote IDs differ on every run29 print("structured content:", json.dumps(shown))30 print("amount:", quote.structured_content["amount"])31 print("within limit:", quote.structured_content["within_limit"])32 assert quote.structured_content["within_limit"] is False33 # the lifetime is in seconds; the prose gives it in minutes34 print("quote lifetime minutes:", quote.structured_content["expires_in_seconds"] // 60)35 # the text block a client that reads only text gets, parsed back to JSON36 same_json = json.loads(quote.content[0].text) == quote.structured_content37 print("text block is the same JSON:", same_json)38 assert same_json3940 async with Client(bare) as client: # in-process: no wire needed to read a schema41 tool = (await client.list_tools()).tools[0]42 print("bare output schema:", json.dumps(tool.output_schema))43 result = await client.call_tool("refund_amount", {"order_id": "O-2289"})44 print("bare structured content:", json.dumps(result.structured_content))454647asyncio.run(main())
python refund-quote-structured.pyoutput schema requires: quote_id, order_id, sku, amount, policy_limit, within_limit, expires_in_seconds
structured content: {"quote_id": "(random)", "order_id": "O-2289", "sku": null, "amount": "180.00", "policy_limit": "150.00", "within_limit": false, "expires_in_seconds": 900}
amount: 180.00
within limit: False
quote lifetime minutes: 15
text block is the same JSON: True
bare output schema: {"properties": {"result": {"title": "Result", "type": "string"}}, "required": ["result"], "title": "refund_amountOutput", "type": "object"}
bare structured content: {"result": "180.00"}
The quote's output schema requires quote_id, order_id, sku, amount, policy_limit, within_limit, expires_in_seconds, and the structured content has each of those fields. Its amount, €180.00, is more than the policy's limit, so within_limit is false, and Return an input request instead of a result is where that flag starts a person's confirmation. The text block holds the same JSON, as the code checks.
The bare tool shows where the SDK lags the specification. The pinned revision allows a string as structured content, but the SDK still wraps any value that isn't an object in {"result": ...}, and publishes an object schema to match (mcp/server/mcpserver/utilities/func_metadata.py). The bare tool's structured content is {"result": "180.00"}, not the bare string. A host written to the specification that expects a string gets an object instead. Return a model from every tool and the question never comes up.
Both sides check structured content. The SDK's client validates every successful result against the output schema it cached from tools/list. It raises a RuntimeError when the structured content doesn't match, or when a tool with an output schema returns none (mcp/client/session.py, validate_tool_result). The SDK's server also checks a tool's return value against the tool's own model before sending it (mcp/server/mcpserver/utilities/func_metadata.py), so a mismatch fails on whichever side changed.
Working rule: Give every tool a pydantic model as its return type, so the SDK publishes an output schema, returns structured content with no wrapper, and adds the text block for you. Put a field in the model for each decision the host's code makes, such as within_limit, rather than leaving it in a sentence. Return a bare string only from a tool whose result no code reads.
실패를 도구 결과로 보고하기
이전 절의 견적은 호출이 성공했을 때의 결과다. 호출이 실패하면 명세는 두 가지 경로 중 하나를 정해 둔다(tools, "Error handling"). 프로토콜 오류는 JSON-RPC 오류이며, 알 수 없는 도구, tools/call 스키마에 맞지 않는 요청, 서버 장애에 해당한다. 도구 실행 오류는 isError를 true로 설정한 일반 결과이며, API 실패, 잘못된 입력, 위반된 비즈니스 규칙에 해당한다. 이 책의 나머지 부분에서 도구 오류라고 부르는 것에 대해 명세는 "언어 모델이 스스로 바로잡는 데 쓸 수 있는 실행 가능한 피드백을 담는다"라고 하며, 클라이언트는 이를 모델에 전달해야 한다("SHOULD").
클라이언트는 실행 오류를 모델에 전달해야 하지만(SHOULD) 프로토콜 오류는 전달해도 될 뿐(MAY)이므로, 어느 경로를 택하느냐에 따라 누가 실패를 고칠 수 있는지가 정해진다. Python SDK에서 ToolError를 발생시키면 작성자가 쓴 메시지를 담은 실행 오류가 만들어진다. MCPError를 발생시키면 프로토콜 오류가 만들어진다. 그 밖의 예외는 모두 충돌로 취급한다. 이때 결과에는 "Error executing tool"과 도구 이름만 담기고, 예외는 서버의 로그에 남는다(handling errors). SDK의 가이드는 이 선택을 하나의 질문으로 제시한다. 더 똑똑한 모델이었다면 이 실패를 피할 수 있었는가? 그렇다면 ToolError를 발생시키고, 그렇지 않다면 MCPError를 발생시킨다.
쇼핑몰 서버는 이 기준을 따른다. 없는 주문, 환불할 수 없는 주문, 주문에 없는 SKU, 알 수 없거나 만료된 견적은 모두 ToolError이며, 각각 대신 무엇을 해야 하는지 알려 주는 메시지를 담는다. 쇼핑몰 API가 401을 반환하는 것은 서버의 키가 잘못되었다는 뜻이고 어떤 모델도 이를 고칠 수 없으므로, 서버는 JSON-RPC의 내부 오류 코드와 함께 MCPError를 발생시킨다. API가 중단된 경우처럼 그 밖의 모든 것은 충돌로 남는다. 다섯 번의 호출은 의도적으로 실패하며, 코드가 호출하는 순서대로 나열하면 다음과 같다.
- 모델이 읽는 설명 쓰기에서 수정한 설명으로 기록된 티켓 T-0006의 호출. 지어낸 SKU를 사용한다.
- 서버가 발급한 적 없는 견적으로 호출한
issue_refund - 존재하지 않는 도구
- 잘못된 키로 시작한 서버에 대한 호출
- 쇼핑몰 API가 멈춘 뒤의 호출
1"""Five failures and the path each takes: three tool execution errors the model reads (isError results), a crash the2model sees only as a generic message, and a protocol error (a JSON-RPC error) that only the host sees. The point rests3on which results are flagged as errors, and the code asserts that a missing tool is one of them."""4import asyncio56from mcp import Client, MCPError78from lib import loopback, shop_api, shop_tools9from lib.host import ReplayModel, choose_tool10from lib.shop_data import load_shop111213async def attempt(params, name: str, arguments: dict, label: str) -> object | None:14 async with Client(params) as client:15 try:16 result = await client.call_tool(name, arguments)17 print(f"{label} is error:", result.is_error)18 print(f"{label} says:", result.content[0].text)19 return result20 except MCPError as error:21 print(f"{label} JSON-RPC error code:", error.code)22 print(f"{label} JSON-RPC error message:", error.message)23 return None242526async def main() -> None:27 with loopback.serve(shop_api.create_app()) as base_url:28 params = shop_tools.server_params(base_url)29 async with Client(params) as client: # T-0006's recorded choice, with the SKU the model made up30 tools = (await client.list_tools()).tools31 choice = choose_tool(ReplayModel("description-choices"), load_shop().ticket("T-0006"), tools)32 await attempt(params, choice.tool, choice.arguments, "wrong SKU")33 await attempt(params, "issue_refund", {"quote_id": "Q-0000000000"}, "unknown quote")34 unknown = await attempt(params, "refund_order", {"order_id": "O-2289"}, "unknown tool")35 assert unknown is not None and unknown.is_error # a failed result, not a protocol error36 # a key the shop's API rejects: the server answers with a protocol error, which the client raises37 await attempt(shop_tools.server_params(base_url, api_key="wrong-key"), "get_order_status",38 {"order_id": "O-2289"}, "rejected key")39 await attempt(params, "get_order_status", {"order_id": "O-2289"}, "API down") # the API has stopped404142asyncio.run(main())
python tool-error-versus-protocol-error.pywrong SKU is error: True
wrong SKU says: Error executing tool quote_refund: Order O-2289 has no line for KG-1031. Its SKUs are KG-1043.
unknown quote is error: True
unknown quote says: Error executing tool issue_refund: There is no quote Q-0000000000. Call quote_refund for the order to get a quote_id.
unknown tool is error: True
unknown tool says: Unknown tool: refund_order
rejected key JSON-RPC error code: -32603
rejected key JSON-RPC error message: The shop's API rejected this server's key. The server needs reconfiguring.
API down is error: True
API down says: Error executing tool get_order_status
지어낸 SKU는 실행 오류로 돌아왔으며, 그 텍스트는 모델에 부족했던 정보를 알려 준다. "Error executing tool quote_refund: Order O-2289 has no line for KG-1031. Its SKUs are KG-1043." 이를 읽은 모델은 올바른 SKU로 다시 호출할 수 있다. 알 수 없는 견적의 메시지도 같은 방식으로 작동한다. "Error executing tool issue_refund: There is no quote Q-0000000000. Call quote_refund for the order to get a quote_id."
알 수 없는 도구는 명세와 다른 점을 보여 준다. 명세의 예는 알 수 없는 도구에 JSON-RPC 오류 -32602로 응답하지만, SDK의 서버는 대신 실행 오류를 반환한다(mcp/server/mcpserver/tools/tool_manager.py). 결과에는 오류 표시가 붙으며, 그 텍스트는 "Unknown tool: refund_order"이다. 모델에게는 이름이 틀렸음을 알려 주므로 이쪽이 더 유용한 응답이다. 프로토콜 오류의 수를 세어 혼란에 빠진 모델을 알아내는 호스트는 이런 경우를 볼 수 없으므로, 실행 오류도 함께 세어야 한다.
잘못된 키는 다른 경로를 택했다. 클라이언트가 MCPError를 발생시켰고, 예제는 이를 JSON-RPC 오류 -32603로 잡았으며 메시지는 "The shop's API rejected this server's key. The server needs reconfiguring."였다. 호스트의 코드는 이를 보며, 모델은 호스트가 전달해 줄 때만 볼 수 있다. API가 중단되었을 때 모델이 받은 것은 "Error executing tool get_order_status"뿐이었고, 예외는 서버의 로그에 남았다(handling errors).
두 경로를 모두 건너뛰는 실수가 하나 더 있다. 오류 메시지를 일반 문자열로 반환하는 도구다. SDK는 반환된 문자열을 isError를 false로 하여 보내므로, 모델은 그 오류를 성공한 답으로 읽는다(handling errors). 대신 예외를 발생시켜야 한다.
작업 규칙: 모델이 바로잡을 수 있는 모든 실패에는 ToolError를 발생시키고, 무엇이 잘못되었는지와 대신 무엇을 보내야 하는지를 구체적으로 짚어 주는 메시지를 쓴다. 유효한 값이 적다면 그 값도 포함한다. MCPError는 구성 오류처럼 어떤 모델도 고칠 수 없는 실패에만 발생시키고, 예상하지 못한 예외는 일반적인 형태로 두어 내부 세부 사항이 서버 안에만 남게 한다. 오류를 일반 문자열로 반환해서는 안 된다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Mark what a tool changes with annotations
The errors in the previous section tell the model what went wrong after a call. A tool's annotations tell the host what a call will do before it's made, so the host can decide whether to ask for consent first. The specification wants a person able to say no to any tool call, as Let a model choose the tool quoted. A tool's annotations hold a title and four hints (schema, ToolAnnotations):
readOnlyHint: the tool doesn't change its environment. The default is false.destructiveHint: a tool that changes something may destroy or overwrite data, rather than only add to it. The default is true.idempotentHint: calling the tool again with the same arguments has no further effect. The default is false.openWorldHint: the tool reaches entities outside a closed domain, such as the web. The default is true.
destructiveHint and idempotentHint mean something only when readOnlyHint is false. The defaults describe the worst case, so to a careful host a tool with no annotations is destructive, not idempotent, and reaches the open world. Annotations go into the Python SDK as ToolAnnotations(read_only_hint=..., destructive_hint=..., idempotent_hint=..., open_world_hint=...) to the tool() decorator (tools).
The shop's four reading tools carry read_only_hint=True and open_world_hint=False, because they only read the shop's own API. issue_refund is the one tool that changes something, and its hints are judgements. We set destructive_hint=False, because a refund adds a record and never overwrites one, and open_world_hint=False, because the tool talks only to the shop's API, which records the request for the shop's staff to pay. idempotent_hint=True is the hint that needs a guarantee behind it: the server returns the same refund for the same quote_id.
The code works out what a host should assume about each tool, filling in the default wherever a hint is missing, and applies a consent rule to the result. It includes the endpoint tool post_refunds, which has no annotations. Then it calls issue_refund twice with one quote, and POST /refunds twice with one amount.
1"""What each tool's annotations tell a host, with the specification's defaults filled in where a hint is missing, and2whether the server keeps issue_refund's idempotent promise when the same call arrives twice. The point rests on the two3refund pairs: issue_refund returns one refund both times, while two posts to the endpoint make two."""4import asyncio56import httpx27from mcp import Client89from lib import loopback, shop_api, shop_tools1011# the specification's defaults, used for any hint a tool leaves out12DEFAULTS = {"read_only_hint": False, "destructive_hint": True, "idempotent_hint": False, "open_world_hint": True}131415def assumed(annotations) -> dict:16 """The hints a host should assume: each one the tool sets, and the specification's default for the rest."""17 given = annotations.model_dump(exclude_none=True) if annotations else {}18 hints = {hint: given.get(hint, default) for hint, default in DEFAULTS.items()}19 if hints["read_only_hint"]: # destructive and idempotent apply only to a tool that changes something20 del hints["destructive_hint"], hints["idempotent_hint"]21 return hints222324async def main() -> None:25 with loopback.serve(shop_api.create_app()) as base_url:26 async with Client(shop_tools.server_params(base_url)) as client:27 tools = (await client.list_tools()).tools + shop_tools.endpoint_tools()[3:4] # + post_refunds28 for tool in tools:29 hints = assumed(tool.annotations)30 shown = ", ".join(h.removesuffix("_hint") for h, on in hints.items() if on) or "nothing"31 print(f"{tool.name} assumes:", shown)32 print(f"{tool.name} asks consent:", not hints["read_only_hint"])3334 quote = (await client.call_tool("quote_refund", {"order_id": "O-2415", "sku": "KG-1050"})).structured_content35 first = await client.call_tool("issue_refund", {"quote_id": quote["quote_id"]})36 again = await client.call_tool("issue_refund", {"quote_id": quote["quote_id"]})37 print("issue_refund first refund:", first.structured_content["refund_id"])38 print("issue_refund second refund:", again.structured_content["refund_id"])3940 # the amount the quote for KG-1050 gave, posted straight to the endpoint41 twice = [httpx2.post(f"{base_url}/refunds", headers={"X-API-Key": shop_api.DEMO_API_KEY},42 json={"order_id": "O-2415", "amount": "23.98"}).json()["refund_id"] for _ in range(2)]43 print("post_refunds first refund:", twice[0])44 print("post_refunds second refund:", twice[1])454647asyncio.run(main())
python annotate-the-refund-tool.pyfind_orders assumes: read_only
find_orders asks consent: False
get_order_status assumes: read_only
get_order_status asks consent: False
quote_refund assumes: read_only
quote_refund asks consent: False
issue_refund assumes: idempotent
issue_refund asks consent: True
check_stock assumes: read_only
check_stock asks consent: False
post_refunds assumes: destructive, open_world
post_refunds asks consent: True
issue_refund first refund: R-0111
issue_refund second refund: R-0111
post_refunds first refund: R-0112
post_refunds second refund: R-0113
Each of the four reading tools comes out as read_only, and issue_refund as idempotent: it isn't read-only, but it is neither destructive nor open-world. The unannotated post_refunds comes out as destructive, open_world, because that's what the defaults say. A host that asks for consent before any tool that isn't read-only asks before both refund tools and none of the others. The shop's host gets that rule in Ask for consent before side effects.
The two pairs of calls show why idempotent_hint=True is safe to claim for issue_refund and wouldn't be for the endpoint. Two calls of issue_refund with one quote returned R-0111 and R-0111: one refund, twice. Two identical posts to the API created R-0112 and R-0113: two refunds. The shop's API has no once-only check, so the server adds one. It stores the refund against its quote, under a lock, because the SDK runs synchronous tools on worker threads and two calls can arrive together.
어노테이션은 보장이 아니라 힌트로 취급한다
프로토콜은 어노테이션이 도구의 실제 동작과 일치하는지 검사하지 않는다. 명세는 어노테이션이 "도구 동작에 대한 충실한 설명을 제공한다고 보장되지 않으며", 클라이언트는 신뢰할 수 있는 서버가 제공한 것이 아니라면 어노테이션을 신뢰할 수 없는 것으로 간주해야 한다("MUST")고 말한다(schema, ToolAnnotations; tools). 환불 도구를 읽기 전용으로 표시하는 서버는 그 표시를 믿는 호스트라면 어디서든 통과한다. 오염된 도구 설명 찾아내기에서는 도구 정의가 의도적으로 거짓말을 하는 서버를 다룬다.
서버 작성자에게 힌트는 코드가 지켜야 하는 약속이다. 상점의 issue_refund가 멱등인 이유는 어노테이션이 그렇다고 말해서가 아니라 견적 저장소가 그렇게 만들기 때문이다. 재시작으로 저장소가 사라지더라도 재시도된 호출은 두 번째 환불을 일으키지 않고 "There is no quote"라는 응답을 받는다. 이 역시 안전한 결과다. 검사는 서버 안에 두고, 어노테이션은 그 검사를 설명하는 것으로 취급한다.
작업 규칙: 모든 도구에 어노테이션을 달아야 한다. 힌트를 생략하면 신중한 호스트는 최악의 경우를 가정하기 때문이다. 도구를 멱등으로 표시하는 것은 서버가 이를 강제할 때만 하고, 환불, 결제처럼 한 번만 일어나야 하는 작업은 서버의 검사 뒤에 두어야 한다. 호스트라면 신뢰하는 서버의 어노테이션을 사용자에게 무엇을 보여 줄지 결정하는 데에만 쓰고, 동의 절차를 생략해도 된다는 허가로는 쓰지 않는다(부작용 전에 동의 구하기). 그 밖의 모든 서버의 어노테이션은 검증되지 않은 주장으로 취급한다.
도구 목록을 작게 유지한다
호스트는 앞의 절들에서 다룬 모든 도구를 설명과 입력 스키마와 함께 매 턴마다 모델의 프롬프트에 넣고, 모델은 도구를 고르기 전에 목록 전체를 읽는다. 도구가 많아지면 토큰이 더 들고, 선택도 더 어려워진다. MCP 서버를 대상으로 한 한 실험에서는 요청과 관련된 도구만 가져오게 하자 선택 정확도가 13.62%에서 43.13%로 세 배 넘게 올랐다(Gan and Sun, 2025). 엣지 장치에서는 작은 모델에 제공하는 도구를 줄이자 함수 호출 성공률이 높아졌고 실행 시간이 최대 70% 줄었다(Paramanayakam and others, 2025). 두 연구는 각자의 환경에서 수행한 단일 연구이므로, 이 수치를 쇼핑몰 예제에 적용할 값이 아니라 효과의 방향으로 읽어야 한다.
비용은 짐작하는 것보다 측정하는 편이 쉽다. 녹화 스크립트는 실행될 때 녹화 모델의 토크나이저로 각 도구가 호스트의 프롬프트에서 차지하는 토큰 수도 함께 세었다. 검사는 수정한 도구, 모델이 읽는 설명 쓰기에서 다룬 모호한 설명의 도구, 엔드포인트 도구의 토큰 수를 각각 합산하고 바이트 수를 측정한다. 토큰을 센 뒤에 도구가 바뀌었다면 검사는 실행을 거부한다.
1"""What the shop's tool list costs in the host's prompt: bytes, and tokens counted with the recording model's tokenizer2when the recording was made (examples/data/recorded/description-choices/prompt_tokens.json). The point rests on the3revised, vague and endpoint prompt token lines."""4import asyncio5import hashlib6import json78from mcp import Client910from lib import shop_tools11from lib.host import RECORDED, tool_specs1213# the token counts and line hashes the recording script wrote14counted = json.loads((RECORDED / "description-choices" / "prompt_tokens.json").read_text())151617def cost(label: str, tools) -> tuple[int, int]:18 """Bytes and tokens of the tools as the host's prompt renders them, one JSON line per tool."""19 lines = [json.dumps(spec, ensure_ascii=False) for spec in tool_specs(tools)]20 # the hash of each line as the host renders it; a tool that changed since then fails here21 for spec, line in zip(tool_specs(tools), lines):22 if counted[label][spec["name"]]["sha256"] != hashlib.sha256(line.encode()).hexdigest():23 raise LookupError(f"{spec['name']} changed since its tokens were counted: re-run the recording script")24 tokens = sum(counted[label][spec["name"]]["tokens"] for spec in tool_specs(tools))25 return sum(len(line.encode()) for line in lines), tokens262728async def main() -> None:29 async with Client(shop_tools.create_server()) as client:30 result = await client.list_tools()31 listed = result.tools32 print("tools/list result bytes:", len(result.model_dump_json(by_alias=True, exclude_none=True).encode()))33 vague = shop_tools.with_descriptions(listed, shop_tools.VAGUE_DESCRIPTIONS)34 for label, tools in (("revised", listed), ("vague", vague), ("endpoint", shop_tools.endpoint_tools())):35 size, tokens = cost(label, tools)36 print(f"{label} prompt bytes:", size)37 print(f"{label} prompt tokens:", tokens)38 tokens_per_tool = cost("revised", listed)[1] / len(listed) # cost returns (bytes, tokens): index 1 is tokens39 print("revised tokens per tool:", round(tokens_per_tool))40 print("20 such tools tokens:", round(20 * tokens_per_tool)) # arithmetic on the counts, not a count41 print("prompt without tools tokens:", counted["prompt_without_tools"])42 print("recording context tokens:", counted["context"])434445asyncio.run(main())
python tool-list-size.pytools/list result bytes: 8049
revised prompt bytes: 3417
revised prompt tokens: 970
vague prompt bytes: 1945
vague prompt tokens: 620
endpoint prompt bytes: 1014
endpoint prompt tokens: 288
revised tokens per tool: 194
20 such tools tokens: 3880
prompt without tools tokens: 136
recording context tokens: 4096
비용의 대부분은 스키마에 있다. 쇼핑몰의 수정한 도구 다섯 개는 프롬프트에서 970토큰을 차지하며, 호스트의 나머지 지침은 136토큰이다. 설명이 모호하면 620토큰이므로, 수정한 설명이 목록 비용의 약 3분의 1을 차지한다. 엔드포인트 도구는 288토큰이다. 설명은 한 줄이고, 스키마에는 패턴도 열거형도 자체 설명도 없다. 수정한 스키마는 JSON Schema로 입력 타입 지정하기에서 잘못된 인수를 잡아낸 바로 그 스키마다. tools/list 결과 전체는 이보다 더 큰데, 출력 바이트 수에서 보듯이 호스트의 프롬프트에서는 빠지는 출력 스키마, 제목, 주석도 담고 있기 때문이다.
도구당 약 194토큰이라면 이와 같은 도구 20개는 모델이 티켓을 읽기 전에 약 3880토큰을 차지한다. 녹화를 실행하는 4096토큰 컨텍스트의 거의 전부다. 이 수치는 측정값이 아니라 산술이며, 실제 도구의 크기는 제각각이다. 목록이 짧으면 두 설명이 겹칠 가능성도 낮아진다. 초안에서 get_order_status와 quote_refund가 겹친 것이 바로 그 문제였다(모델이 읽는 설명 쓰기).
서버는 하나의 대상만 상대함으로써 목록을 짧게 유지한다. 쇼핑몰의 서버는 지원 티켓을 다루므로 재고 재집계 도구는 여기에 없다. 고정된 리비전에서 서버는 연결 하나를 위해 목록을 줄일 수 없다. 다만 목록은 요청이 제시하는 인가에 따라 달라질 수 있고, 항상 정해진 순서로 나온다(목록 결과 캐시하기). 그 절은 결과에 붙는 캐시 힌트를 다루며, 토큰이 허용하는 범위로 도구 제한하기는 토큰에 따라 달라지는 목록을 보여 준다.
작업 규칙: 서버마다 하나의 대상과, 그 대상의 작업에 필요한 소수의 도구만 둔다. 그리고 목록이 호스트의 프롬프트에서 차지하는 비용을 측정한다. 토큰은 스키마와, 모델이 혼동하는 두 도구를 구분하는 문장에 쓰고, 스키마와 중복되는 설명 문구는 줄인다. 호스트에 필요한 도구가 모델이 잘 고를 수 있는 수보다 많다면, 한 서버의 목록이 연결에 따라 달라지게 하지 말고 여러 서버로 나누어 대화에 필요한 서버만 연결한다.
프로덕션에서 잘못되는 것
이 상점의 서버는 한 대의 머신에서 티켓 여덟 건을 처리할 때는 잘 동작한다. 그러나 티켓 큐 전체와 실제 배포 환경에서는 도구 설계가 몇 가지 알아볼 수 있는 방식으로 실패한다.
모델이 구분하지 못하는 두 도구. 모델이 읽는 설명 작성하기의 설명 초안 때문에 모델은 견적을 내야 할 주문을 조회하는 대신 조회해서는 안 될 주문을 조회해 버렸다. 프로덕션에서 이 문제의 징후는 도구가 처리하는 티켓 수보다 훨씬 많거나 훨씬 적게 호출되는 것, 또는 하나로 충분한데 두 도구가 연달아 호출되는 것이다. 레이블이 붙은 티켓을 기준으로 도구 선택 횟수를 세고(올바른 도구가 선택되는 빈도 측정하기), 두 도구를 가르는 문장을 고친다.
모델이 실제 값으로 보내는 예제 값. 환불 티켓 세 건 중 한 건에서 모델은 sku 매개변수의 설명에 있던 예제 SKU를 고객이 적은 것처럼 그대로 보냈다. KG-1031은 실제 상품이므로, 해당 SKU가 주문에 있는지 확인하는 검사가 없었다면 도구는 엉뚱한 상품의 견적을 냈을 것이다. 이 상점의 설명이 실제 예제 ID를 유지하는 것은 녹화를 그 ID로 했기 때문일 뿐이다. 징후는 실제 트래픽으로 설명되는 것보다 훨씬 자주 인자에 나타나는 예제 값이다. 각 인자를 그것이 속한 레코드와 연결하는 검사를 유지하고, 사용 중인 범위를 벗어난 ID처럼 실제일 수 없는 예제를 고른다.
코드와 어긋나는 출력 스키마. SDK의 클라이언트는 tools/list에서 캐시한 출력 스키마로 각 결과를 검증하고, 둘이 일치하지 않으면 RuntimeError를 발생시킨다(mcp/client/session.py). 필드를 제거하거나 변경한 서버를 배포했는데 클라이언트가 이전 목록을 캐시하고 있으면, 그 도구에 대한 모든 호출이 실패한다. 서버 배포 후 호스트에서 RuntimeError: Invalid structured content가 보일 것이다. 출력 스키마를 계약으로 다루고 테스트한다(스키마를 계약으로 검사하기).
모델이 읽을 수 없는 비정상 종료. ToolError 또는 MCPError가 아닌 모든 예외는 "Error executing tool"이라는 메시지만 담긴 채 모델에 전달된다. 대화에 아무 이유도 남기지 않고 같은 호출을 재시도하거나 포기하는 모델을 찾아본다. 서버의 표준 오류 출력을 읽고, 모델이 바로잡을 수 있는 실패는 각각 ToolError로 바꾼다.
프로세스와 함께 사라지는 핸들. 이 상점의 견적은 서버 메모리에 있다. 재시작하면 열려 있는 견적이 모두 사라지고, 모델은 몇 분 전에 만든 견적에 대해 "There is no quote"라는 응답을 받는다. 하나의 주소 뒤에 복제본이 여러 개 있으면 손실은 더 커진다. 한 복제본에서 만든 견적을 다음 복제본이 알지 못하기 때문이다. 서버가 둘 이상의 프로세스로 실행되면 핸들을 공유 저장소에 보관한다(스티키 세션 없이 복제본 실행하기).
서버 사이에서 충돌하는 도구 이름. 서버 두 개에 연결된 호스트에는 get_order_status라는 도구가 둘 보일 수 있다. 명세는 호스트가 구분하는 것이 좋다("SHOULD")고 하며, 예로 각 이름 앞에 서버 식별자를 붙이는 방법을 든다(tools, "Tool names"). 서버 간 도구 이름 짓기에서 이를 구현한다.
헤더에 담기는 개인 데이터. x-mcp-header로 표시한 매개변수는 Streamable HTTP에서 그 값이 HTTP 헤더에 복사되며, 프록시와 로그에서 볼 수 있다. 명세는 서버가 개인 데이터를 포함한 민감한 매개변수를 이런 방식으로 표시해서는 안 된다("SHOULD NOT")고 하므로(tools), 고객 ID나 이메일에는 절대 표시하지 않는다. 이 헤더는 Streamable HTTP로 서비스하기에서 다룬다.
작업 규칙: 상점의 도구를 프로덕션에 배포하기 전에, 실제 티켓을 레이블링한 표본에서 배포할 모델이 도구를 선택하는 과정을 녹화하고, 모델이 바로잡을 수 있는 모든 실패가 유용한 메시지와 함께 ToolError로 반환되는지 확인하며, 각 출력 스키마에 계약 테스트를 적용한다. 배포 후에는 도구 선택 횟수, 인자에 나타나는 예제 값, 호스트의 RuntimeError를 관찰한다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Decisions this chapter made
- Five task tools, not one tool per endpoint:
find_orders,get_order_status,quote_refund,issue_refundandcheck_stock, inlib.shop_tools. The stock recount stays off the support server. - Refunds split into a quote and an issue.
quote_refundcomputes the amount and returns aquote_idvalid for 15 minutes;issue_refundtakes only that handle. - The server trusts the caller's
customer_id, and aquote_idis random but short and bound to no customer. Secure tools against misuse addresses it by taking the acting user from the verified token, not from an argument. - No consent yet. Within the policy's limit,
issue_refundruns without asking a person; the host's consent comes in Ask for consent before side effects. - Descriptions are passed as
description=, from one dictionary. Each says what the tool does, when to use it instead of its neighbour, its inputs and its result. They were revised once, against one model's recorded choices on eight tickets, and the run credits the revision as a whole, not any one sentence of it. - Every argument is typed narrowly with
Annotated[..., Field(...)]: patterns for IDs, an enum for status, bounds forlimit, a date forplaced_since. - Every tool returns a pydantic model, so the SDK publishes an output schema and sends structured content with no
{"result": ...}wrapper. - Rejected arguments come back as execution errors, as the specification's tools page and the SDK have them, so the model can read them and correct its call.
ToolErrorfor what a model can fix, with the valid values in the message;MCPErrorfor a rejected API key; everything else stays a generic crash.- Every tool is annotated. The reading tools are read-only and closed-world.
issue_refundis additive, closed-world and idempotent, with the server's once-only check behind the hint. - Annotations from other servers are untrusted, and consent never depends on them alone.
- Quotes live in the server's memory, which holds for one stdio process. Replicas need a shared store.
이 판의 이 장
2026.11.14판예제 통과 2026년 11월 19이 장에서 7개 예제개 중 7개가 통과한다
영어판 2026.11.14판을 번역한 것이다.