MCP가 API에 더하는 것
읽는 데 약 60분분 걸린다, 11절에 6개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.14판을 번역한 것이다. 원문 읽기
이 페이지의 내용
- 호스트, 클라이언트, 서버를 구분한다
- Put each capability in the right primitive
- 도구는 모델이 선택하는 동작이다
- 리소스는 애플리케이션이 고르는 데이터다
- Prompts are templates the user chooses
- Carry the version and capabilities on every request
- Handle a version the server doesn't support
- 목록 결과 캐시하기
- Keep an HTTP API where MCP adds nothing
- What goes wrong in production
- 이 장에서 내린 결정
이 장을 마치면 호스트, 클라이언트, 서버가 각각 무엇을 하는지 설명할 수 있다. 상점의 각 기능을 알맞은 Model Context Protocol 프리미티브에 배치할 수 있다. 모든 요청이 싣고 다니는 버전과 기능(capabilities)을 읽을 수 있다. 상점이 일반 HTTP API를 그대로 두어야 하는 경우도 판단할 수 있다. 이 장의 주장과 예제는 명세의 2026-07-28 개정판과 Python SDK인 mcp의 2.3.0 버전에 맞춘 것이다.
이 장이 상점에 요구하는 것은 HTTP API 하나다. 상점은 주방용품과 정원용품을 파는 Fernhill Supply의 가상 온라인 매장이다. 지원팀의 호스트는 이 API의 주문 조회를 이미 사용하고 있다. MCP end to end에서는 이 조회를 Model Context Protocol(MCP) 서버 뒤에 두어, 지원팀 호스트의 모델이 호출할 수 있게 했다. 그 서버에는 도구가 하나뿐이었다. 지원팀은 더 많은 것을 원한다. 하나는 환불 정책이다. 호스트는 티켓에 금액 이야기가 나올 때마다 이 정책을 곁에 두어야 한다. 다른 하나는 환불 요청을 검토하는 표준 방식이다. 한편 같은 API에서 매일 밤 재고 수준을 읽어 가는 창고팀은 자신들도 MCP로 옮겨야 하는지 묻는다.
두 질문은 모두 이미 동작하는 API에 MCP가 무엇을 더하는지에 달려 있다. HTTP 클라이언트는 개발자가 문서로 읽은 엔드포인트를 기준으로 작성된다. MCP 클라이언트는 서버가 무엇을 제공하는지를 실행 시점에 모델이 읽을 수 있는 형태로 알게 된다. 또한 프로토콜은 각 기능을 언제 사용할지 누가 결정하는지를 정한다. 이 장은 이러한 추가 요소를 하나씩 다루고, 그것이 통신 구간에서 치르는 비용을 측정하며, 상점이 그 비용을 치르지 말아야 할 곳을 짚으며 끝맺는다.
호스트, 클라이언트, 서버를 구분한다
Wrap one endpoint as a tool의 서버는 그 장의 코드가 구동하는 클라이언트 뒤에서 실행되었다. 쇼핑몰이 서버에 기능을 더 추가하기 전에, 각 부분이 무엇을 하는지 정확히 구분해 두어야 한다. MCP의 보장은 프로세스가 아니라 역할에 적용되기 때문이다.
명세는 세 가지 역할을 정한다(architecture). 호스트는 사용자가 작업하는 애플리케이션이다. 호스트는 클라이언트를 만들고, 모델과의 대화를 유지하며, 보안 정책과 동의를 집행한다. 클라이언트는 호스트가 서버 하나와 맺는 연결이다. 명세는 "Each client is created by the host and communicates with exactly one server"라고 적는다. 서버는 도구 같은 기능을 제공하며, 호스트에 대해서는 그 밖의 어떤 것도 알지 못한다. 같은 페이지는 이러한 분리에서 나오는 설계 원칙을 하나 제시한다. 서버는 대화 전체를 보아서는 안 되고, 다른 서버를 들여다보아서도 안 된다는 것이다. 각 서버가 무엇을 볼지는 호스트가 결정하며, 서버를 가로지르는 모든 일은 호스트에서 일어난다.
지원 팀의 호스트는 호스트 역할을 맡아 이 책의 호스트 루프를 실행한다. 호스트가 사용하는 각 서버에는 고유한 클라이언트가 하나씩 주어진다. 이 장에서는 shop-support 하나만 쓰고, Catch poisoned tool descriptions에서는 파트너가 제공하는 두 번째 서버가 등장한다. 이 서버는 쇼핑몰 서버가 무엇을 반환했는지 결코 알아서는 안 된다. shop-support는 이 장의 서버이다. 이 서버는 1장의 get_order_status 도구를 그대로 두고, 환불 정책이라는 리소스와 review_refund 프롬프트를 추가하여 각 종류의 기능이 한 번씩 나타나도록 한다. 이 책의 다른 서버 예제와 마찬가지로, 이 파일은 서버를 정의하고, 인자 없이 실행하면 --serve로 서버를 띄우는 클라이언트를 시작한다.
클라이언트가 가장 먼저 하는 일은 서버에 무엇을 제공하는지 묻는 것이다. **기능(capability)**은 클라이언트나 서버가 지원한다고 선언하는 것이다. 예를 들어 도구를 제공하는 서버나 입력 요청에 응답할 수 있는 클라이언트가 그렇다. 고정된 리비전에서는 요청 하나, 즉 server/discover로 이를 알 수 있다. 그 응답에는 서버가 지원하는 버전, 서버의 기능, 서버의 이름이 들어 있으므로 클라이언트는 이 응답 하나로 서버가 지원하는 모든 것을 보여 줄 수 있다(discovery). 그런 다음 클라이언트는 tools/list, resources/list, prompts/list로 각 종류의 기능을 나열한다. 기본값인 자동 모드에서 mcp.Client는 열릴 때 server/discover를 보내고, 그 응답을 client.session.discover_result로 보관한다(mcp/client/session.py).
1"""shop-support, the chapter 2 server, offers one tool, one resource and one prompt. Run bare, the file starts it as a2client, which prints what it discovers: the tools, resources and prompts lines are the ones the prose reads."""3import asyncio4import os5import sys67import httpx28from mcp import Client, StdioServerParameters9from mcp.server.caching import CacheHint10from mcp.server.mcpserver import MCPServer11from mcp.server.mcpserver.exceptions import ToolError1213from lib.policies import policy1415# ttl_ms is in milliseconds, so 300_000 is five minutes; "public" lets a shared cache reuse the tool list.16server = MCPServer("shop-support", version="0.2.0",17 cache_hints={"tools/list": CacheHint(ttl_ms=300_000, scope="public")})181920@server.tool()21def get_order_status(order_id: str) -> dict:22 """Look up one of the shop's orders by its ID, such as O-1873: its status, dates, lines and total."""23 response = httpx2.get(f"{os.environ['SHOP_API_URL']}/orders/{order_id}",24 headers={"X-API-Key": os.environ["SHOP_API_KEY"]}, timeout=5.0) # timeout in seconds25 if response.status_code == 404:26 raise ToolError(f"The shop has no order {order_id}. Order IDs look like O-1873.")27 response.raise_for_status()28 return response.json()293031@server.resource("shop://policies/refund", name="refund-policy", mime_type="text/markdown")32def refund_policy() -> str:33 return policy("refund").path.read_text(encoding="utf-8") # examples/data/shop/policies/refund.md343536@server.prompt()37def review_refund(order_id: str) -> str:38 """Review a customer's refund request for one order against the shop's refund policy."""39 return (f"Review the refund request for order {order_id}. Look up the order with get_order_status, read the "40 "refund policy at shop://policies/refund, and say whether the refund needs a person to confirm it.")414243async def main() -> None:44 # No variables are passed: listing never calls the tool, so the server needs none of the shop's API settings.45 async with Client(StdioServerParameters(command=sys.executable, args=[__file__, "--serve"], env={})) as client:46 print("server:", client.server_info.name, client.server_info.version)47 print("protocol revision:", client.protocol_version)48 # auto mode keeps the server/discover answer on the session, so the versions come from there49 print("supported versions:", ", ".join(client.session.discover_result.supported_versions))50 # exclude_none drops the capabilities the server didn't declare, leaving only the ones it offers51 print("capabilities:", ", ".join(sorted(client.server_capabilities.model_dump(exclude_none=True))))52 print("tools:", ", ".join(t.name for t in (await client.list_tools()).tools))53 print("resources:", ", ".join(str(r.uri) for r in (await client.list_resources()).resources))54 print("prompts:", ", ".join(p.name for p in (await client.list_prompts()).prompts))555657if __name__ == "__main__":58 # With --serve this file is the server the client launches; run bare, it is the client.59 server.run() if "--serve" in sys.argv else asyncio.run(main())
python list-what-the-server-offers.pyserver: shop-support 0.2.0
protocol revision: 2026-07-28
supported versions: 2026-07-28
capabilities: prompts, resources, tools
tools: get_order_status
resources: shop://policies/refund
prompts: review_refund
클라이언트의 코드는 이 셋 중 어느 것도 이름으로 지정하지 않는다. 클라이언트는 서버로부터 이 셋을 알아냈으며, 서버 자신의 이름 shop-support 0.2.0, 서버가 지원하는 리비전 2026-07-28, 서버가 선언하는 기능 prompts, resources, tools도 함께 알아냈다. 이 값들은 예제 옆에 출력된다. 이것이 MCP가 쇼핑몰의 API에 더하는 첫 번째 것이다. 쇼핑몰에 대해 아무것도 모르는 클라이언트가 쇼핑몰이 무엇을 제공하는지 알아낼 수 있고, 각 항목의 설명과 도구와 프롬프트가 받는 인자까지 얻을 수 있으며, 호스트는 이를 모델 앞에 놓을 수 있다. 서버는 도구 목록에 캐시 힌트도 설정하는데, 이는 Cache list results에서 설명한다.
작업 규칙: 호스트에서 각 서버에 고유한 클라이언트를 하나씩 주고, 대화와 서버를 가로지르는 모든 일은 서버가 아니라 호스트의 코드에 둔다. 모든 클라이언트는 서버가 제공하는 것을 가정하지 말고, 먼저 서버가 제공하는 것을 읽는 일로 시작하여, 서버가 도구를 바꾸어도 호스트가 깨지지 않도록 한다. 서버를 작성할 때는 서버가 자신에게 전송된 요청만 볼 수 있다고 가정한다. 명세가 서버에 허용하는 것이 그것뿐이기 때문이다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Put each capability in the right primitive
The shop-support server from the previous section offers one tool, one resource and one prompt. A server's three primitives are its tools, resources and prompts, and they differ less in what they return than in who decides when they're used. The specification's server overview puts it in a table: prompts are user-controlled, resources are application-controlled, and tools are model-controlled (server features). So the question to ask of each capability is not whether it reads or writes, but who should decide when it runs: the model, the host's own code, or the person at the desk.
The tools page mandates no particular interface for a tool. The resources and prompts pages do the same for their primitives. A host can show them however it likes, but one that respects the control model gives each to the party the table names. The next script uses each of shop-support's three once, the way a host would.
1"""Use each of shop-support's three primitives once, as a host would: the tool for the model, the resource for the2host's code, the prompt for the person at the desk. The prose quotes the order's status, the policy's first line and3the prompt's one required argument."""4import asyncio5import json6import sys78from mcp import Client, StdioServerParameters910from lib import loopback, shop_api111213async def main() -> None:14 with loopback.serve(shop_api.create_app()) as base_url:15 # the server from list-what-the-server-offers, run as its own process with --serve; its env points at the shop's API16 params = StdioServerParameters(command=sys.executable, args=["list-what-the-server-offers.py", "--serve"],17 env=shop_api.server_env(base_url))18 async with Client(params) as client:19 # A tool: the host lists it for the model, and calls it when the model asks.20 result = await client.call_tool("get_order_status", {"order_id": "O-2476"})21 assert result.is_error is False # the lookup must succeed for the prose's claim22 # a tool's result is a list of content blocks; the order arrives as JSON text in the first one23 print("tool says order status:", json.loads(result.content[0].text)["status"])2425 # A resource: the host reads it when its own code decides the model needs it.26 policy = (await client.read_resource("shop://policies/refund")).contents[0] # this server returns one item27 print("resource type:", policy.mime_type)28 print("resource first line:", policy.text.splitlines()[0])2930 # A prompt: the host shows it to the user, who picks it and fills in its arguments.31 listed = (await client.list_prompts()).prompts[0] # the first prompt, the only one shop-support offers32 print("prompt arguments:", "; ".join(f"{a.name}, {'required' if a.required else 'optional'}"33 for a in listed.arguments))34 prompt = await client.get_prompt("review_refund", {"order_id": "O-2476"})35 print("prompt messages:", len(prompt.messages))36 print("prompt role:", prompt.messages[0].role)37 print("prompt starts:", prompt.messages[0].content.text[:44] + "…") # 44 characters: enough to name the order383940asyncio.run(main())
python three-primitives-side-by-side.pytool says order status: shipped
resource type: text/markdown
resource first line: # Refund policy
prompt arguments: order_id, required
prompt messages: 1
prompt role: user
prompt starts: Review the refund request for order O-2476. …
도구는 모델이 선택하는 동작이다
도구(tool)는 이름, 설명, 입력 스키마를 갖춘 동작이며, 모델이 이 도구를 호출할지와 어떤 입력으로 호출할지를 결정한다(도구). 호스트는 모델에게 도구 목록을 제공하고, 모델이 요청한 호출을 실행한다. 주문 O-2476의 조회는 오류 없이 성공했고, 주문 상태는 shipped로 돌아왔다.
조회가 여기에 속하는 이유는 조회가 필요한지를 티켓이 결정하기 때문이다. 한 고객은 주문 ID를 알려 주며 택배가 어디에 있는지 묻고, 다른 고객은 프라이팬이 28cm로 나오는지 묻는다. 티켓을 읽는 쪽만 선택할 수 있으며, 이 호스트에서는 그것이 모델이다. 모델이 도구를 선택하게 하기에서는 녹화된 기록을 통해 모델이 이 선택을 하는 모습을 보였다.
작업 규칙: 대화를 보고 사용 여부를 모델이 결정해야 하는 기능은 도구로 만든다. 여기에는 고객이 쓴 내용에 따라 달라지는 조회와, 환불처럼 무언가를 바꾸는 모든 동작이 포함되며, 환불의 경우 호스트가 호출 전에 동의를 요청한다.
리소스는 애플리케이션이 고르는 데이터다
리소스(resource)는 서버가 URI로 노출하는 데이터이며, 이를 언제 읽고 어떻게 처리할지는 애플리케이션이 정한다(리소스). 호스트는 리소스를 모델의 컨텍스트에 첨부하거나, 사용자에게 보여 주거나, 색인할 수 있다. shop-support는 이 책을 위해 작성한 짧은 정책 문서 중 하나인 상점의 환불 정책을 shop://policies/refund 아래에서 제공한다. 이를 읽으면 text/markdown 텍스트가 반환되며, 그 첫 줄은 # Refund policy이다.
환불 정책이 리소스인 이유는 상점이 그 정책이 중요해지는 때를 미리 알고 있기 때문이다. 그때는 금액과 관련된 모든 티켓이다. 호스트의 코드는 모델에 묻지 않고도 이런 티켓에 대해 이 정책을 모델의 컨텍스트에 첨부할 수 있다. 도구로 만들면 모델이 정책을 가져와야 한다는 점을 기억하는 데 의존해야 하고, 매번 한 턴의 비용이 든다. 리소스는 읽기 전용 도구와 같지 않다. 둘 다 데이터를 반환하지만, 리소스를 읽는 주체는 호스트의 코드이며 그 결과는 목록 결과 캐시하기의 규칙에 따라 캐시할 수 있다. 정책을 리소스로 노출하기에서는 상점의 나머지 정책도 같은 방식으로 제공한다.
작업 규칙: 호스트 자체의 코드가 데이터가 필요한 때를 판단할 수 있다면 그 데이터를 리소스로 만든다. 알려진 종류의 티켓에 적용되는 정책이나 사용자가 열어 둔 레코드가 그 예이다. 대화를 읽는 모델만이 필요 여부를 판단할 수 있다면 도구로 둔다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Prompts are templates the user chooses
A prompt is a template of messages, with arguments, that the server defines and the user picks (prompts). The specification is precise about the word: "user-controlled" refers to "who decides when the prompt is used, not who authors its content". The server writes the content, and a host typically offers prompts in a menu or as commands. review_refund takes one argument, order_id, required. Filled in for order O-2476, it returned 1 message from the user role, beginning "Review the refund request for order O-2476. …".
review_refund is a prompt because a person on the support team decides to start a refund review, usually after reading the ticket, and the shop wants every review to follow the same steps. The prompt's text names the tool and the resource the review needs, so the model starts from the policy and the order, not a guess. A prompt isn't a system prompt the user writes: the shop writes it once, on the server, and every host that connects gets the same text. Package a workflow as a prompt grows review_refund into the full review, with the refund amount as a second argument.
Working rule: Make a workflow a prompt when a person should start it and every run should follow the same steps, and keep the prompt's text on the server so that a change reaches every host at once. If no person chooses when it runs, it isn't a prompt: make the steps a tool, or put them in the host's own instructions.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Carry the version and capabilities on every request
The client in Put each capability in the right primitive made three calls, and the server answered each one without remembering the others, by design. At the pinned revision there's no handshake: every request carries, in its _meta field, the protocol version and the client's capabilities, and those fields "MUST be included on every request" (base protocol). Each request should also carry the client's name and version, and each result the server's.
Three rules on the same page shape how the shop's server uses these fields:
- A request without a required field is rejected with JSON-RPC error
-32602(invalid params), and over HTTP with status 400. - A server must not rely on a capability the client didn't declare on that request. If it needs one, it answers with error
-32021, whose data lists the missing capabilities. clientInfoandserverInfoare self-reported. Implementations "SHOULD NOT rely on them for security decisions", so the shop's server never treats the client's name as an identity.
_meta also carries keys of your own, under a reverse-DNS prefix that ends in /. A prefix whose second label is modelcontextprotocol or mcp is reserved for the protocol, and so are traceparent, tracestate and baggage, which belong to OpenTelemetry (base protocol). The shop's domain is fernhill.example, so its keys start with example.fernhill/.
To see the envelope, the client calls get_order_status through lib.wire, which logs every line between the client and the server. It passes one key of the shop's own, a request ID that support staff can quote. It then sends a tools/list request without the client's capabilities, through a second small module, lib.raw_stdio, which starts a stdio server and writes JSON-RPC lines by hand. The code needs that because mcp.Client never sends a malformed request.
1"""Show the _meta that every request and result carries, add one key of the shop's own, and send a request without2the client's capabilities. The prose's claims about the envelope come from the printed keys and the bare request's error code."""3import asyncio4import json5import sys6from pathlib import Path78from mcp import Client, StdioServerParameters9from mcp.types import Implementation1011from lib import byte_meter, loopback, raw_stdio, shop_api, wire1213COMMAND = [sys.executable, "list-what-the-server-offers.py", "--serve"]141516async def main() -> None:17 Path("meta.jsonl").unlink(missing_ok=True) # the relay appends to its log18 with loopback.serve(shop_api.create_app()) as base_url:19 server = StdioServerParameters(command=COMMAND[0], args=COMMAND[1:], env=shop_api.server_env(base_url))20 # the relay logs every line the client and server exchange, so the byte counts are of lines as sent21 async with Client(wire.relay(server, log="meta.jsonl"),22 # the name and version the SDK sends as clientInfo in _meta; the server must not rely on them23 client_info=Implementation(name="shop-host", version="0.1.0")) as client:24 # a key under the shop's own prefix, which the protocol leaves to the shop to define25 await client.call_tool("get_order_status", {"order_id": "O-2476"},26 meta={"example.fernhill/requestId": "req-0001"})27 trace = [message for _, message in wire.read_trace("meta.jsonl")]28 call = next(m for m in trace if m.get("method") == "tools/call") # the first tools/call request in the log29 result = next(m for m in trace if m.get("id") == call["id"] and "result" in m) # its response, with the same id30 for key, value in call["params"]["_meta"].items():31 print(f"request {key}:", json.dumps(value))32 for key, value in result["result"]["_meta"].items():33 print(f"result {key}:", json.dumps(value))34 lines = [json.loads(entry)["line"] for entry in Path("meta.jsonl").read_text(encoding="utf-8").splitlines()] # as sent35 print("request _meta bytes:", byte_meter.meta_bytes(lines, call["params"]["_meta"]))36 print("result _meta bytes:", byte_meter.meta_bytes(lines, result["result"]["_meta"]))3738 with raw_stdio.launch(COMMAND, env={}) as raw: # the same request, without clientCapabilities39 # capabilities=None leaves clientCapabilities out of _meta: the request the server must reject40 reply = raw.request("tools/list", meta=raw_stdio.envelope("2026-07-28", capabilities=None))41 print("without capabilities, error code:", reply["error"]["code"])42 print("without capabilities, message:", reply["error"]["message"])434445asyncio.run(main())
python request-meta-on-the-wire.pyrequest example.fernhill/requestId: "req-0001"
request io.modelcontextprotocol/protocolVersion: "2026-07-28"
request io.modelcontextprotocol/clientInfo: {"name": "shop-host", "version": "0.1.0"}
request io.modelcontextprotocol/clientCapabilities: {}
result io.modelcontextprotocol/serverInfo: {"name": "shop-support", "version": "0.2.0"}
request _meta bytes: 228
result _meta bytes: 88
without capabilities, error code: -32602
without capabilities, message: params._meta is missing the required envelope key(s): io.modelcontextprotocol/clientCapabilities
The shop's key travels beside the protocol's own. The tools/call request's _meta held four keys. The shop's example.fernhill/requestId, set to "req-0001", came first, and the SDK added the protocol's three after it: the version, "2026-07-28", then the client's name, version and capabilities, which the output prints, the capabilities empty because this client declares none. The result's _meta carried the server's name and version, also printed.
The request without capabilities failed with code -32602, and the SDK's message names the missing key: "params._meta is missing the required envelope key(s): io.modelcontextprotocol/clientCapabilities". A hand-written client, or a gateway that rewrites bodies and drops _meta, fails this way on its first request.
What this costs the shop is bytes on every message. Measured on the lines as sent, the request's _meta, with the shop's key, took 228 bytes, and the result's 88. They are part of the per-call overhead that Keep an HTTP API where MCP adds nothing measures. What it buys is a server that needs no memory of earlier requests: any copy of shop-support can answer any request, which is what lets Run replicas without sticky sessions put two replicas behind one address.
Working rule: Read the version and the client's capabilities from each request, never from an earlier one, and answer -32021 when a call needs a capability the request didn't declare. Put the shop's own request metadata under its own reverse-DNS prefix, never under io.modelcontextprotocol/ or mcp. Log clientInfo and serverInfo for debugging, and decide nothing on them.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Handle a version the server doesn't support
Every request in Carry the version and capabilities on every request named its protocol version, so a server can meet, on any request, a version it doesn't implement. No negotiation step settles it in advance. A server that doesn't implement the requested version "MUST respond with an UnsupportedProtocolVersionError listing the versions it does support", error code -32022, with the supported versions and the requested one in its data. The client SHOULD pick a version from that list that both sides support, and retry, or else show the user an error (versioning). Over Streamable HTTP the version also travels in the MCP-Protocol-Version header, which must match the body, and an unsupported version gets status 400 (Streamable HTTP).
The shop meets this when a host built for a later revision connects to shop-support. Showing the error means sending a version the server doesn't know, and the obvious way fails first: mcp.Client accepts as its mode only "auto", "legacy" or one of the SDK's per-request revisions, such as 2026-07-28, and raises before it sends anything (mcp/client/client.py). So the script tries that first, then uses lib.raw_stdio from the previous section to write the request by hand. It asks for 2099-01-01, a made-up revision that stands for any the server lacks, then retries with a version from the server's list.
1"""Ask shop-support for a revision it doesn't implement, read its -32022 error, and retry with the newest revision both2sides list. The prose reads the error code, the versions in its data and the retry's tool list from the printed lines."""3import sys45from mcp import Client, StdioServerParameters6from mcp_types.version import MODERN_PROTOCOL_VERSIONS78from lib import raw_stdio910COMMAND = [sys.executable, "list-what-the-server-offers.py", "--serve"]11UNKNOWN = "2099-01-01" # stands for any revision this server doesn't implement1213try:14 # the SDK's client checks the mode when it is built, so this raises before anything is sent15 Client(StdioServerParameters(command=COMMAND[0], args=COMMAND[1:]), mode=UNKNOWN)16except ValueError as refused:17 print("client refuses:", type(refused).__name__)1819with raw_stdio.launch(COMMAND, env={}) as server:20 # capabilities={} declares no client capabilities: the request is well formed, and only its version is unknown21 error = server.request("tools/list", meta=raw_stdio.envelope(UNKNOWN, capabilities={}))["error"]22 print("error code:", error["code"])23 print("error message:", error["message"])24 print("server supports:", ", ".join(error["data"]["supported"])) # the server lists its versions in the error's data25 print("client asked for:", error["data"]["requested"])2627 # the versions both sides know, in the order the SDK lists them28 mutual = [version for version in MODERN_PROTOCOL_VERSIONS if version in error["data"]["supported"]]29 if not mutual:30 sys.exit("no version in common: show the user an error instead of retrying")31 print("retry with:", mutual[-1]) # the last of that list is the newest version both sides know32 # the same process: at this revision each request names its own version, so the retry needs no new connection33 retry = server.request("tools/list", meta=raw_stdio.envelope(mutual[-1], capabilities={}))34 print("retry tools:", ", ".join(tool["name"] for tool in retry["result"]["tools"]))
python unsupported-version-error.pyclient refuses: ValueError
error code: -32022
error message: Unsupported protocol version
server supports: 2026-07-28
client asked for: 2099-01-01
retry with: 2026-07-28
retry tools: get_order_status
The SDK's client never reached the server: it refused the unknown mode before sending anything, with the error the output beside the example shows. The server's answer is what makes the retry possible. Given the raw request, it refused with the code and message the output prints, and its data listed the versions it supports, 2026-07-28, beside the one the client asked for. From that list the script picked 2026-07-28, the newest version both sides know, and the retry listed get_order_status. The retry went to the same process, because a connection carries no agreed version at the pinned revision, so the next request may name another one.
Two details of the SDK at 2.3.0 matter when you read this error from someone else's server. First, an SDK stdio server decides from the client's first request which era of the protocol to speak. A request whose _meta has a protocol version opens a connection at the pinned revision, even when the version is unknown, which is why this request got -32022 instead of a demand for the 2025 initialize handshake (mcp/server/runner.py). Second, the server's supported list holds only the versions that use per-request _meta, although the same server still accepts 2025 clients through initialize (mcp/shared/inbound.py). The specification's own example of the error lists a 2025 revision as well; the SDK's list doesn't. The SDK's client, in its default auto mode, reads a -32022 whose list shares nothing with its own as a real incompatibility, and any other error on its first request as a 2025 server that needs the old handshake (mcp/client/_probe.py). Serve old and new clients through the window covers that second path.
Working rule: When a server answers -32022, pick the newest version in both your list and its supported list, retry once, and show the user an error naming both lists if they share none. Don't retry in a loop, and don't guess a version the server didn't list. On your own server, keep the supported list exact, because clients choose from it.
목록 결과 캐시하기
호스트, 클라이언트, 서버 분리하기에서 다룬 server/discover 응답과 도구 목록은 상점이 배포할 때만 바뀌지만, 상태를 저장하지 않는 클라이언트는 모델이 한 턴을 진행할 때마다 매번 요청할 수 있다. 고정된 개정판에서 server/discover, tools/list, prompts/list, resources/list, resources/templates/list, resources/read의 각 결과는 두 가지 캐시 힌트를 반드시 담아야 한다(caching).
ttlMs: 결과가 신선하게 유지되는 시간을 밀리초로 나타낸다. HTTP의max-age와 비슷하다. 0이면 즉시 만료된 것으로 본다.cacheScope: 값은"public"또는"private"이다. 전자는 캐시가 여러 호출자 사이에 공유해도 되고, 후자는 인가 컨텍스트가 다른 호출자끼리 절대 공유해서는 안 된다.
같은 문서는 힌트의 의미도 제한한다. TTL은 신선도 힌트이지 폴링 간격이 아니다. 클라이언트는 데이터가 필요할 때 신선도를 확인하며, 폴링을 한다면 지터와 백오프를 사용해야 한다. list_changed 알림은 아직 신선한 캐시 결과를 무효화한다. 또한 cacheScope는 접근 제어가 아니다. 서버는 "MUST NOT rely on cacheScope alone to prevent unauthorized access", 즉 cacheScope만으로 무단 접근을 막아서는 안 된다.
도구 목록은 안정적일 때에만 캐시할 수 있다. 명세에 따르면 서버의 tools/list는 연결마다 달라져서는 안 되지만 요청의 인가에 따라서는 달라질 수 있고, 서버는 도구를 결정적인 순서로 반환해야 한다. 이는 프롬프트 캐시 적중률을 높이는 데 도움이 된다(tools). SDK의 MCPServer는 도구를 등록한 순서대로 나열하므로 이 규칙을 충족한다(mcp/server/mcpserver/tools/tool_manager.py).
SDK에서 서버의 힌트 기본값은 ttl_ms=0과 "private"이므로 서버가 명시적으로 선택하지 않으면 아무것도 재사용되지 않는다. shop-support은 cache_hints={"tools/list": CacheHint(ttl_ms=300_000, scope="public")}로 도구 목록에 대해 이를 선택한다. 5분 동안 유지되며 공유할 수 있다(mcp/server/caching.py). 반대편에서 mcp.Client는 기본적으로 서버의 힌트에 따라 메모리에 캐시하며, 각 목록 호출은 cache_mode로 "use", "refresh", "bypass" 중 하나를 받는다. 자체 meta를 전달하는 호출은 항상 서버에 도달하고, 클라이언트는 TTL을 최대 24시간으로 제한한다(mcp/client/caching.py). 캐시가 얼마나 절약하는지 세려면 힌트를 설정하지 않은 1장의 서버에서 도구를 두 번 나열하고, 이어서 shop-support에서 두 번 나열한 다음, lib.wire로 전송 구간에서 각 서버에 도달한 tools/list 요청이 몇 건인지 센다.
1"""Call list_tools() twice on each of two servers, one that sets no cache hint and one with a five-minute public hint,2and count the tools/list requests that reach each; the prose reads the three counts."""3import asyncio4import sys5from pathlib import Path67from mcp import Client, StdioServerParameters89from lib import wire101112async def list_twice(script: str, second_call: str = "use") -> tuple[str, str, int]:13 log = Path(script).with_suffix(".jsonl") # the relay's log, beside the server file14 log.unlink(missing_ok=True) # the relay appends to its log15 server = StdioServerParameters(command=sys.executable, args=[script, "--serve"], env={})16 async with Client(wire.relay(server, log=str(log))) as client:17 first = await client.list_tools() # cache_mode="use" is the default18 await client.list_tools(cache_mode=second_call)19 name = client.server_info.name20 # responses carry no method, so this counts only the requests that reached the server21 sent = sum(1 for _, message in wire.read_trace(str(log)) if message.get("method") == "tools/list")22 return name, f"ttlMs {first.ttl_ms}, cacheScope {first.cache_scope}", sent232425async def main() -> None:26 name, hint, sent = await list_twice("order-status-server.py") # chapter 1's server, which sets no hint27 print(f"{name} hint:", hint)28 print(f"{name} tools/list sent for two calls:", sent)29 name, hint, sent = await list_twice("list-what-the-server-offers.py") # this chapter's server, with its tool-list hint30 print(f"{name} hint:", hint)31 print(f"{name} tools/list sent for two calls:", sent)32 name, hint, sent = await list_twice("list-what-the-server-offers.py", second_call="bypass") # bypass skips the cache33 print(f"{name} tools/list sent when the second call bypasses:", sent)343536asyncio.run(main())
python cache-the-tool-list.pyshop-orders hint: ttlMs 0, cacheScope private
shop-orders tools/list sent for two calls: 2
shop-support hint: ttlMs 300000, cacheScope public
shop-support tools/list sent for two calls: 1
shop-support tools/list sent when the second call bypasses: 2
힌트가 도착하는 요청 수를 결정한다. 1장의 shop-orders는 ttlMs 0, cacheScope private를 반환했으므로 두 호출 모두 서버에 도달했고, 요청은 모두 2건이었다. shop-support의 목록은 ttlMs 300000, cacheScope public와 함께 돌아왔으므로 클라이언트의 캐시가 두 번째 호출에 응답했고, 서버에 도달한 요청은 1건뿐이었다. 두 번째 호출에 cache_mode="bypass"를 지정하면 두 호출이 다시 모두 서버에 도달하며, 예제 옆의 출력이 그 수를 센다. 모델의 매 턴마다 도구 목록을 렌더링하는 호스트는 턴마다 요청 한 건을 절약한다. 또한 목록의 순서가 유지되므로 모델 프롬프트가 같은 바이트로 시작하며, 이는 제공자의 프롬프트 캐시에 필요한 조건이다.
상점의 도구 목록은 모든 호출자에게 같은 도구가 보이므로 공개로 둘 수 있다. 그러나 고객별 데이터는 그럴 수 없다. 리소스 템플릿으로 레코드 지정하기에서 주문마다 리소스 하나를 제공할 때 그 읽기는 "private"로 유지되므로, 공유 캐시가 한 고객의 주문을 다른 고객의 세션에 넘기는 일은 없다. 토큰이 허용하는 범위로 도구 제한하기를 적용하면 그럴 수 있듯이, 도구 목록이 호출자의 토큰에 따라 달라진다면 그 목록도 비공개가 된다.
작업 규칙: 상점의 도구 목록처럼 모든 호출자에게 같은 목록에는 TTL과 "public" 범위를 설정하고, TTL은 배포 후 오래된 목록을 받아들일 수 있는 시간보다 길지 않게 고른다. 몇 시간이 아니라 몇 분이어야 한다. 요청자가 누구인지에 따라 달라지는 것에는 SDK의 기본값인 "private"를 유지하고, cacheScope를 인가 검사의 대용으로 쓰지 않는다. 클라이언트에서는 기본 캐시를 유지한다. 이 캐시는 client.listen(tools_list_changed=True) 스트림으로 변경 알림이 도착하면 항목을 제거한다(mcp/client/client.py). 이 스트림은 리소스가 바뀔 때 클라이언트에 알리기가 여는 종류의 스트림이다. 이 스트림이 없으면 어떤 알림도 클라이언트에 도달하지 않으므로 하나를 열어 두고, 항목을 의심할 다른 이유가 있을 때는 TTL에 맞춰 폴링하는 대신 cache_mode="refresh"를 사용한다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Keep an HTTP API where MCP adds nothing
Each section so far showed something MCP adds to the shop's API. Separate the host, the client and the server added run-time discovery, and Put each capability in the right primitive gave each capability a control model. Carry the version and capabilities on every request made every request versioned and self-describing. The host's consent step, in Ask for consent before side effects, is another. Each of those helps when a model or a user's host chooses among capabilities at run time. None of them helps a program whose developer already knows which endpoint it will call.
The specification doesn't say when not to use MCP, so this is the book's judgement, not a protocol rule. We recommend a plain HTTP API for three kinds of work:
- Service-to-service calls with no model choosing, such as the warehouse's nightly read of stock levels. Its code calls fixed endpoints, so nobody reads the discovery answers or the descriptions.
- Fixed workflows, where the same steps run in the same order every time. Write them as code over the API, and if a model needs to start one, expose the whole workflow as one tool.
- High-volume batch work, where every byte and round trip is multiplied.
We recommend MCP where a model or a user's host chooses among capabilities at run time, as the support team's host does. The two don't compete. Meet the shop and its API kept the shop's API as the system of record, and shop-support is a thin adapter over it, so the warehouse keeps its API calls while the support team's host uses MCP.
This run prices the adapter, so the trade-off rests on numbers. The script fetches order O-2476 twice: once from the shop's API, with GET /orders/O-2476, and once through shop-support's get_order_status tool over Streamable HTTP, the transport Move the server from stdio to HTTP teaches. lib.byte_meter, a small module for this measurement, puts a TCP relay in front of each server and counts every byte both ways, headers included, and counts the HTTP requests each server handles. Everything runs in one process on 127.0.0.1, over HTTP/1.1 without TLS. On the MCP side, the count covers a host's setup on opening a client, including the tool listing, but not the tool call. That setup is measured twice: in the default auto mode, which first probes the server with server/discover, and with the version pinned. The tool call itself is made with the version pinned. No times are measured, because times on one machine's loopback say little about a network.
1"""Fetch order O-2476 from the shop's API, then through shop-support's tool over Streamable HTTP, and count the cost.2The prose's comparison comes from the byte totals and the request counts the script prints."""3import asyncio4import os5import runpy67import httpx28from mcp import Client910from lib import byte_meter, loopback, shop_api111213async def session(url, traffic, requests, mode: str, calls: int) -> tuple[list[str], int]:14 """Open a client, list the tools as a host does, make `calls` tool calls, close it: the requests and bytes."""15 traffic.reset()16 requests.reset()17 # auto mode first sends server/discover to probe the server; a pinned revision skips that probe18 async with Client(f"{url}/mcp", mode=mode) as client:19 await client.list_tools()20 for _ in range(calls):21 await client.call_tool("get_order_status", {"order_id": "O-2476"})22 return list(requests.names), traffic.sent + traffic.received # bytes both ways, from the relay232425async def main() -> None:26 print("setup: one process, 127.0.0.1, HTTP/1.1, no TLS, bytes counted at a TCP relay, headers included")27 api_app, api_requests = byte_meter.count_requests(shop_api.create_app())28 with loopback.serve(api_app) as api_url, byte_meter.relay(api_url) as (url, traffic):29 # the one API call, sent through the relay so that its bytes are counted the way the tool's are30 httpx2.get(f"{url}/orders/O-2476", headers={"X-API-Key": shop_api.DEMO_API_KEY}).raise_for_status()31 api_bytes = traffic.sent + traffic.received32 print("api call round trips:", api_requests.count)33 print("api call bytes:", api_bytes)3435 os.environ.update(shop_api.server_env(api_url)) # the tool calls the API directly, not through a relay36 shop_support = runpy.run_path("list-what-the-server-offers.py")["server"] # defined there, not run37 mcp_app, mcp_requests = byte_meter.count_requests(shop_support.streamable_http_app())38 with loopback.serve(mcp_app) as mcp_url, byte_meter.relay(mcp_url) as (url, traffic):39 for mode, label in (("auto", "auto"), ("2026-07-28", "pinned")):40 names, setup_bytes = await session(url, traffic, mcp_requests, mode, calls=0) # setup only, no tool call41 print(f"mcp {label} setup request count:", len(names))42 print(f"mcp {label} setup requests:", ", ".join(names))43 print(f"mcp {label} setup bytes:", setup_bytes)44 names, with_call = await session(url, traffic, mcp_requests, "2026-07-28", calls=1)45 call_bytes = with_call - setup_bytes # a pinned session with one call, less the pinned setup46 print("mcp tool call round trips:", names.count("tools/call"))47 print("mcp tool call bytes:", call_bytes)48 print("tool call bytes per api call byte:", round(call_bytes / api_bytes, 1)) # one decimal place, as the prose quotes495051asyncio.run(main())
python api-call-versus-tool-call.pysetup: one process, 127.0.0.1, HTTP/1.1, no TLS, bytes counted at a TCP relay, headers included
api call round trips: 1
api call bytes: 591
mcp auto setup request count: 2
mcp auto setup requests: server/discover, tools/list
mcp auto setup bytes: 2157
mcp pinned setup request count: 1
mcp pinned setup requests: tools/list
mcp pinned setup bytes: 1147
mcp tool call round trips: 1
mcp tool call bytes: 1357
tool call bytes per api call byte: 2.3
On the wire the tool call costs more bytes, not more round trips. The API call takes 1 round trip and the tool call takes 1, but it sends 2.3 times the bytes, which the output beside the example counts. The difference is the JSON-RPC envelope, the _meta on the request and on the result, the routing headers that Streamable HTTP adds, and the order itself, which the SDK returns as indented JSON inside a text block, with its quotes escaped, as Read the messages on the wire showed.
Setup costs more on top of that. In auto mode, opening the client sent 2 requests before its first call; with the version pinned it skipped the server/discover probe and sent 1. The output beside the example lists the requests and their bytes. Behind the server, each tool call also made its own request to the shop's API, which the counts leave out because the caller never sees it.
Some of those bytes buy something without a model. The headers Mcp-Method, on every request, and Mcp-Name, on tools/call, resources/read and prompts/get, let a gateway route by method and by tool without parsing bodies (Streamable HTTP). For the support team's host, which makes a few calls per ticket, 1357 bytes a call is small beside the model's own tokens. For the warehouse's nightly read of 64 products, every call pays for an envelope its code never reads, and the adapter adds a process to a job that ran without one.
Working rule: Keep a plain HTTP API for callers whose code knows which endpoint to call, such as other services, fixed workflows and batch jobs, and put an MCP server in front of the same API for hosts where a model or a user chooses at run time. Measure the overhead on your own transport before you route high-volume traffic through MCP, and pin the protocol version in clients you control, so they skip the discovery probe. Keep auto mode for clients that may meet servers you don't control, which may speak only the 2025 protocol.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
What goes wrong in production
The parts this chapter added fail in a few recognisable ways, and each leaves a trace you can look for.
A capability lands in the wrong primitive. A policy served as a tool gets skipped when the model doesn't think to fetch it, and a refund served as a resource leaves the host no point at which to ask for consent. The sign is behaviour that varies from ticket to ticket for no reason in the ticket: answers about money given without the policy, or side effects with no consent step in the logs. Ask of each capability who should decide when it runs, as Put each capability in the right primitive does.
A gateway drops or rewrites _meta. Proxies and API gateways built for plain JSON APIs sometimes rewrite request bodies. A request that loses its version or capabilities fails with -32602, as Carry the version and capabilities on every request showed. On Streamable HTTP, a body that no longer matches its headers fails with -32020, because the MCP-Protocol-Version, Mcp-Method and Mcp-Name headers must agree with the body (Streamable HTTP). Pass MCP traffic through unchanged, and route on the headers rather than editing bodies.
clientInfo is used as an identity. The client's name in _meta is whatever the client chose to send, and the specification says not to rely on it for security (base protocol). A server that grants more to a client named shop-host grants it to anyone who sends that name. Authorization comes from tokens, which Find the authorization server from the resource starts on.
A public cache entry crosses customers. A result marked "public" may be shared across authorization contexts, even when it came from an authenticated endpoint (caching). A server that marks per-customer data public lets a shared cache serve one customer's order to another. Keep the SDK's "private" default for anything that depends on the caller, and treat every "public" hint in a code review as a claim to check.
A long TTL hides a deploy. With a tool list fresh for hours, a client keeps offering a tool the server has removed, and calls to it fail. The sign is unknown-tool errors that stop when clients restart. Keep tool-list TTLs to minutes, and let clients refresh on a change notification, which reaches a client only on a subscriptions/listen stream it opened, as Tell clients when a resource changes sets up.
A client calls a tool it never listed. At 2.3.0, mcp.Client checks a tool's result against the tool's output schema, and if it hasn't listed the tools yet, it sends tools/list first (mcp/client/session.py). A client that calls tools without listing them pays an extra request on its first call. List the tools when the client opens, as a host does anyway.
Old error codes from old material. The pinned revision reserves -32020 to -32099 for the specification, treats -32000 to -32019 as a legacy range that new code shouldn't use, and asks for application codes outside the range JSON-RPC reserves (base protocol). The revision renumbered its error codes on the way to release (changelog), so material written against a draft can show other numbers for the same errors. Match error codes against the specification, not against a blog post.
The specification moves on. MCP is governed by the Agentic AI Foundation, a directed fund under the Linux Foundation, which took MCP on as a founding project in December 2025 (announcement). Revisions are dated, and a deprecated feature stays for at least twelve months (feature lifecycle). The window is shorter only for an active security risk, and then at least ninety days, or where the deprecated features registry says so. Read the registry when you plan a server's next release, and watch logs for -32022 from clients built for a later revision.
Working rule: Check four things on any server you are about to ship: each capability's primitive matches who decides when it runs, nothing between client and server edits MCP bodies, nothing is decided on clientInfo, and every "public" cache hint covers data that is the same for every caller. Log the protocol version and error code of every failed request, because version and envelope errors are the first sign that a client or a gateway has changed.
이 장에서 내린 결정
- 서버마다 클라이언트 하나를 두고, 클라이언트는 호스트에 둔다. 대화와 여러 서버에 걸친 모든 일은 호스트의 코드에 남는다. 서버는 자신에게 보낸 요청만 본다.
- 상점의 서버는
shop-support이다. 이 서버는 1장의get_order_status도구,shop://policies/refund에 있는 리소스로서의 환불 정책, 프롬프트로서의review_refund를 갖는다. - 각 기능은 실행 시점을 결정해야 할 주체가 제어하는 프리미티브에 배정한다. 도구는 모델이, 리소스는 호스트의 코드가, 프롬프트는 창구에 있는 사람이 결정한다.
- 버전과 기능은 매 요청에서 읽으며, 이전 요청에서 읽은 값을 쓰지 않는다. 없는 기능에 대한 요청에는
-32021를 반환한다. - 상점 고유의
_meta키는example.fernhill/접두사를 사용한다.clientInfo나serverInfo를 근거로 결정하는 일은 없다. -32022이 오면 클라이언트는 한 번 재시도한다. 이때 양쪽이 모두 지원하는 버전 중 가장 최신 버전을 사용하며, 그런 버전이 없으면 오류를 표시한다.- 도구 목록은 공개이며 TTL은 5분이다. 고객별 데이터는 비공개로 두고, 도구 목록이 토큰에 따라 달라지게 되면 도구 목록도 비공개로 바꾼다.
lib.raw_stdio를 통한 손으로 작성한 JSON-RPC는 오류를 보여 줄 때만 쓴다. SDK의 클라이언트로는 일으킬 수 없는 오류가 대상이다.- 서비스 간 호출, 고정된 워크플로, 일괄 작업에는 일반 HTTP API를 권장한다. 모델이나 사용자의 호스트가 실행 시점에 선택하는 경우에는 MCP를 권장한다. 이 권장은
api-call-versus-tool-call의 바이트 수와 왕복 횟수에 근거한다.
이 판의 이 장
2026.11.14판예제 통과 2026년 11월 19이 장에서 6개 예제개 중 6개가 통과한다
영어판 2026.11.14판을 번역한 것이다.