MCP end to end
읽는 데 약 54분분 걸린다, 7절에 5개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.14판을 번역한 것이다. 원문 읽기
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
By the end of this chapter you can put an existing HTTP API behind a Model Context Protocol server over stdio, call its tool from a client, read every message the two exchange, and let a model choose the tool through a small host. Every example runs on one machine; the chapter's claims hold for revision 2026-07-28 of the specification and for mcp 2.3.0, the Python SDK.
A customer writes to Fernhill Supply, a small online shop for kitchen and garden goods, to ask where an order is. The answer lives in Fernhill Supply's systems, not in the ticket, so a model in the support team's host can answer only if something lets it look the order up. This chapter takes on that problem, and Meet the shop and its API introduces the shop in full.
The Model Context Protocol (MCP) is how an application that uses a model gets tools and data from programs it didn't write. Three roles share the work, and the book keeps their names exact. The host is the application the user works in, such as a support desk or a coding assistant. A client is the host's connection to one server. A server exposes capabilities, such as tools a model can call (specification overview). The messages between a client and a server are JSON-RPC 2.0.
This chapter builds a rough version of the whole thing: an API, a server with one tool, a client, a wire trace and one recorded model choice. Each later chapter makes one of those parts solid.
쇼핑몰과 그 API 살펴보기
MCP 서버가 아무것도 없는 상태에서 시작하는 경우는 드물다. 서버가 필요한 팀 대부분은 이미 자체 데이터와 인증, 클라이언트를 갖춘 HTTP API를 운영하고 있으며, 서버가 하는 일은 그 API의 일부를 모델 앞에 내놓는 것이다. 따라서 가장 먼저 갖춰야 할 것은 감싸려는 API이고, 이 API는 예제가 접근할 수 있는 곳에서 실행되고 있어야 한다.
모든 장은 Fernhill Supply라는 쇼핑몰을 다루며, 이를 쇼핑몰이라고 부른다. 이 쇼핑몰은 가상의 업체로, 실제 사업체를 나타내지 않는다. 도메인인 fernhill.example은 결코 해석되지 않는 예약된 이름이다. 쇼핑몰의 지원팀은 고객 티켓에 답하는데, 대부분의 티켓에는 쇼핑몰 시스템에서 조회할 내용이 있다. 주문이 어디에 있는지, 상품의 재고가 있는지, 환불 금액이 얼마가 되는지 등이다. 이 책의 목표는 이런 티켓을 읽고 쇼핑몰의 도구를 호출해 답하는 호스트를 만드는 것이다.
쇼핑몰에는 모든 장이 감싸게 될 "이전" 상태가 이미 있다. 바로 쇼핑몰의 API로, 주문, 재고, 환불을 다루는 HTTP API이며 X-API-Key 헤더에 담긴 API 키를 검사한다. 이 API의 레코드는 쇼핑몰의 데이터이다. 이 데이터는 책의 코드가 고정된 시드 하나로 생성하므로 실행할 때마다 같은 고객, 주문, 티켓이 나온다. 이 구성은 examples/lib/에 있는 공유 모듈 세 개에 담겨 있어서 예제를 짧게 유지할 수 있다.
lib.shop_data는 쇼핑몰의 데이터를 생성한다.load_shop()는 고객, 상품, 재고 수준, 주문, 환불, 티켓을 Python 데이터클래스로 반환한다.lib.shop_api는 쇼핑몰의 API로, 그 데이터 위에서 동작하는 Starlette 앱이다.lib.loopback는 사용 가능한 포트를 골라 127.0.0.1에서 앱을 제공하고, 블록이 끝나면 앱을 중지한다.
API를 감싸기 전에 다른 클라이언트와 똑같은 방식으로 실행해 본다. 키를 넣어 한 번, 키 없이 한 번, 존재하지 않는 주문에 대해 한 번 호출한다.
1"""Start the shop's existing HTTP API on loopback and call it three ways: with its key, without it, and for an order2 that doesn't exist. The point rests on the `without key` line, which shows the API refuses a caller it can't identify."""3import httpx245from lib import loopback, shop_api6from lib.shop_data import SHOP_SEED, load_shop78shop = load_shop() # one fixed seed, so every run sees the same customers, orders and tickets9print("seed:", SHOP_SEED)10print("customers:", len(shop.customers))11print("products:", len(shop.products))12print("orders:", len(shop.orders))13print("tickets:", len(shop.tickets))1415with loopback.serve(shop_api.create_app()) as base_url: # serves on 127.0.0.1 at a free port until the block ends16 # the API checks this header; DEMO_API_KEY is the key the shop's API accepts17 response = httpx2.get(f"{base_url}/orders/O-2476", headers={"X-API-Key": shop_api.DEMO_API_KEY})18 order = response.json()19 print("with key:", response.status_code)20 print("order status:", order["status"])21 print("shipped on:", order["shipped_on"])22 print("total:", order["total"])23 print("without key:", httpx2.get(f"{base_url}/orders/O-2476").status_code) # no header at all24 # O-7144 is a well-formed ID that the generated orders do not contain25 print("unknown order:", httpx2.get(f"{base_url}/orders/O-7144",26 headers={"X-API-Key": shop_api.DEMO_API_KEY}).status_code)
python start-the-shop-api.pyseed: 4217
customers: 240
products: 64
orders: 1500
tickets: 48
with key: 200
order status: shipped
shipped on: 2026-06-24
total: 99.00
without key: 401
unknown order: 404
시드는 4217이며, 예제 옆의 출력은 이 시드가 만들어 내는 고객, 상품, 주문, 티켓의 수를 보여 준다. 이메일은 example.com 도메인을 쓰고, 전화번호는 두 자리만 남기고 가려지며, 결제 정보는 공개된 테스트 카드의 마지막 네 자리와 함께 "card ending"만 표시한다. examples/data/shop/README.md의 데이터 카드에 모든 필드가 나와 있다.
키를 넣으면 API는 200라고 답한다. 주문 O-2476의 상태는 shipped이고 2026-06-24에 발송되었으며, 합계는 €99.00이다. 쇼핑몰은 모든 가격을 유로로 매기고, API는 금액을 통화 코드 없이 일반 소수로 보낸다.
키가 없으면 401라고 답하고, 존재하지 않는 주문에는 404가 돌아온다. 이 세 가지 답이 MCP 서버가 지켜야 하는 계약이다. 서버는 키를 보관하고 같은 엔드포인트인 GET /orders/{order_id}를 호출하여 그 답을 모델이 읽을 수 있는 형태로 바꾼다. 주문 처리 자체를 다시 구현하지는 않는다.
작업 규칙: 이미 운영 중인 API를 감싸고, 그 API를 기준 시스템으로 유지한다. MCP 서버는 자체 자격 증명으로 API를 호출하고 그 답을 변환하는 얇은 어댑터여야 한다. 그래야 API의 검증, 권한 부여, 로그가 모델뿐 아니라 모든 클라이언트에 대해 계속 동작한다. 감쌀 API가 없을 때만 데이터베이스 위에 직접 구축하고, 이때도 비즈니스 규칙은 두 종류의 클라이언트가 함께 쓰는 한 곳에 둔다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Wrap one endpoint as a tool
The shop's API from the previous section answers "what is the status of order O-2476" for any HTTP client. To answer that for a model, the shop needs an MCP server that exposes the lookup as a tool: a named action with a description and a JSON Schema for its inputs, which a model can decide to call (tools). The server publishes its tools in tools/list, and a client runs one with tools/call.
In the Python SDK the server class is MCPServer, imported from mcp.server.mcpserver. The SDK's 1.x releases called it FastMCP, and at 2.3.0 importing mcp.server.fastmcp fails with a pointer to the migration guide. You register a tool with @server.tool(), parentheses included, since the bare @server.tool raises a TypeError that asks for them (mcp source, mcp/server/mcpserver/server.py). The SDK takes the tool's name from the function, its description from the docstring and its input schema from the type hints. server.run() serves over stdio, where the client starts the server as a subprocess and the two exchange messages on standard input and output, which is run()'s default.
The shop's first server is called shop-orders, and its one tool, get_order_status, wraps GET /orders/{order_id}. It reads the API's address and key from its environment, so they never appear in the code or on the wire. Server examples follow one pattern: the file defines the server, and with no arguments it starts a client that launches the same file with --serve and lists the tools. Run it to see the tool the way a model receives it.
1"""The shop's first MCP server: one tool, get_order_status, that wraps GET /orders/{order_id} on the shop's API. The2 point rests on the description and schema lines, the only parts of the tool a model reads."""3import asyncio4import json5import os6import sys78import httpx29from mcp import Client, StdioServerParameters10from mcp.server.mcpserver import MCPServer11from mcp.server.mcpserver.exceptions import ToolError1213server = MCPServer("shop-orders", version="0.1.0")141516@server.tool()17def get_order_status(order_id: str) -> dict:18 """Look up one of the shop's orders by its ID, such as O-1873: its status, dates, lines and total."""19 # read on each call: a missing variable raises KeyError here, and the SDK reports only a generic error20 response = httpx2.get(f"{os.environ['SHOP_API_URL']}/orders/{order_id}",21 headers={"X-API-Key": os.environ["SHOP_API_KEY"]},22 timeout=5.0) # seconds; a slow shop API fails this call instead of holding the worker23 # the shop answers 404 for an order it doesn't have, so the model gets a message it can act on24 if response.status_code == 404:25 raise ToolError(f"The shop has no order {order_id}. Order IDs look like O-1873.")26 response.raise_for_status() # any other failure, such as a wrong key, stays on the server as an HTTPError27 return response.json()282930async def show_tools() -> None:31 from lib import loopback, shop_api32 with loopback.serve(shop_api.create_app()) as base_url:33 # the API's address and key are the only variables the server gets34 params = StdioServerParameters(command=sys.executable, args=[__file__, "--serve"],35 env=shop_api.server_env(base_url))36 async with Client(params) as client:37 for tool in (await client.list_tools()).tools:38 print("tool:", tool.name)39 print("description:", tool.description)40 print("input schema:", json.dumps(tool.input_schema))414243if __name__ == "__main__":44 if "--serve" in sys.argv:45 server.run() # stdio is the default transport46 else:47 asyncio.run(show_tools())
python order-status-server.pytool: get_order_status
description: Look up one of the shop's orders by its ID, such as O-1873: its status, dates, lines and total.
input schema: {"type": "object", "properties": {"order_id": {"title": "Order Id", "type": "string"}}, "required": ["order_id"], "title": "get_order_statusArguments"}
What the client sees is the tool's definition. Its name is get_order_status, its description is the docstring word for word, and its input schema says that order_id is a required string. The SDK built that schema from the order_id: str hint and added title fields of its own, such as "Order Id". The model reads only the description and the schema, so the docstring is written for a model: what the tool does, what an ID looks like and what comes back. Write descriptions the model reads measures how much that wording matters.
The function is a plain def that makes a blocking HTTP call, and at 2.3.0 the SDK runs synchronous tools on a worker thread, so a slow call to the shop's API doesn't stall the server's other requests (migration guide). The function also raises ToolError on a 404, and the SDK passes a ToolError's message to the client as a failed tool result. Any other exception becomes a generic Error executing tool message, and its text stays on the server (mcp/server/mcpserver/tools/base.py). Call the tool from a client shows both kinds of failure.
The server needs no HTTP library of its own, because the SDK depends on httpx2, a fork of HTTPX, at 2.3.0 (migration guide). The tool uses only httpx2.get(), the response's status_code, raise_for_status() and json(), which work as they do in HTTPX.
Working rule: Start with one read-only tool for one endpoint, and write its docstring for a model: what it does, what its inputs look like, what it returns. Raise ToolError with a message that tells the model what to do differently, and let unexpected exceptions stay generic so internal details never leave the server. Past a handful of endpoints, shape the tools around the tasks the model has to do rather than one per endpoint (Shape tools around tasks, not endpoints).
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Call the tool from a client
Wrap one endpoint as a tool defined shop-orders but never ran it, because a stdio server runs only when something launches it. In the shop's case that something is the host, and the part of the host that talks to one server is a client. Over stdio, a client starts the server as a subprocess, writes requests to its standard input and reads responses from its standard output (stdio transport).
At the pinned revision there is no handshake and no session. Each request stands alone and carries the protocol version and the client's capabilities in its _meta field, and the specification says a server "MUST NOT rely on prior requests over the same connection to establish context" (base protocol). The same page also says an open connection, such as a stdio process, isn't a conversation or a session. Revisions up to 2025-11-25 opened every connection with an initialize handshake; Remove initialize and session IDs covers moving off it.
The Python SDK's high-level client is mcp.Client, and given a StdioServerParameters it launches the command as a subprocess. In its default mode="auto" it first sends server/discover at the pinned revision. It falls back to the old initialize handshake whenever the probe times out or fails with any error, except a -32022 whose list of versions shares none with the client's, the case Handle a version the server doesn't support covers (mcp/client/client.py, mcp/client/_probe.py). A 2025-era server answers server/discover with an error, so it gets the old handshake. Use Client, not a hand-called initialize() on a low-level ClientSession, which always speaks the pre-2026 handshake (migration guide).
The command is sys.executable, the Python running the example, rather than "python", so the server runs in the same environment with the same pinned packages, whatever is first on the PATH. The shop API's address and key go in env= explicitly, because the stdio client doesn't pass the parent's environment through. On Linux and macOS it passes only HOME, LOGNAME, PATH, SHELL, TERM and USER, plus what you give it (mcp/client/stdio.py). The client also names itself, shop-host, so the server's logs and the wire show who called.
The next example makes three calls to show failures from the client's side: one for a real order, one for an order ID that doesn't exist, and one from a second client that forgets the environment.
1"""Launch the shop's server over stdio and call get_order_status for a real order and a wrong one, then for a server2 started without the shop's variables. The asserts pin the error flags the prose states: a real order is not an error, and a wrong ID is."""3import asyncio4import json5import sys67from mcp import Client, StdioServerParameters8from mcp.types import Implementation910from lib import loopback, shop_api1112SHOP_HOST = Implementation(name="shop-host", version="0.1.0") # the name the server's logs and the wire show131415async def main() -> None:16 with loopback.serve(shop_api.create_app()) as base_url:17 env = {"SHOP_API_URL": base_url, "SHOP_API_KEY": shop_api.DEMO_API_KEY} # the only two variables the server reads18 # relative to the examples folder, where examples run, so the server file is found19 params = StdioServerParameters(command=sys.executable, args=["order-status-server.py", "--serve"], env=env)20 async with Client(params, client_info=SHOP_HOST) as client:21 print("protocol revision:", client.protocol_version)22 print("server:", client.server_info.name, client.server_info.version)23 result = await client.call_tool("get_order_status", {"order_id": "O-2476"})24 assert result.is_error is False # a real order comes back as a result, not an error25 # the tool returns the order as JSON text in its first content block26 print("order status:", json.loads(result.content[0].text)["status"])27 wrong = await client.call_tool("get_order_status", {"order_id": "O-7144"})28 assert wrong.is_error is True # an unknown order is a failed tool result, not an exception29 print("wrong ID says:", wrong.content[0].text)3031 # no env=, so the server starts without the shop's variables and its tool fails at the first call32 no_env = StdioServerParameters(command=sys.executable, args=["order-status-server.py", "--serve"])33 async with Client(no_env, client_info=SHOP_HOST) as client:34 broken = await client.call_tool("get_order_status", {"order_id": "O-2476"})35 print("without env says:", broken.content[0].text)363738asyncio.run(main())
python call-order-status.pyprotocol revision: 2026-07-28
server: shop-orders 0.1.0
order status: shipped
wrong ID says: Error executing tool get_order_status: The shop has no order O-7144. Order IDs look like O-1873.
without env says: Error executing tool get_order_status
The first call works. The real order comes back as an ordinary result, not an error, with status shipped, the same answer the shop's API gave directly. On the way, the client and server agreed on revision 2026-07-28, and the server/discover answer gave the client the server's name and version, shop-orders 0.1.0.
The wrong ID, O-7144, comes back as a flagged result, not an exception, and its text is the ToolError message, prefixed by the SDK. A model that reads "Order IDs look like O-1873" can ask the customer again. The third call fails differently. The server started without SHOP_API_URL, so the tool raised a KeyError, and all the client got was Error executing tool get_order_status. The KeyError itself went to the server's standard error, where an operator can find it and a model can't. That split is deliberate, because it puts a missing variable in the server's logs and never in the conversation.
Working rule: Connect with mcp.Client, launch stdio servers with sys.executable and an explicit env=, and give the client a name. Pass each variable the server needs and nothing else from your environment, so no server sees secrets meant for another program. When a tool fails with only the SDK's generic message, read the server's standard error before you change the client.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Read the messages on the wire
The client in the previous section hid every message behind call_tool(). When a server misbehaves, or you need to know what the pinned revision really sends, read the messages. Over stdio, each message is one line of JSON-RPC on the server's standard input or output, with no embedded newlines. The server "MUST NOT" write anything to its stdout that isn't a valid MCP message, and its logs belong on standard error (stdio transport).
A faithful trace needs a real subprocess. The SDK's in-process client, Client(server) given a server object, dispatches calls directly in its default auto mode, sending no JSON-RPC at all (mcp/client/client.py), so it can't show you the wire. The book's trace printer, lib.wire, puts a small relay between the client and the server instead: the client launches the relay, the relay launches the real server, and the relay copies every line both ways unchanged while appending it to a log.
wire.print_trace() then prints that log in order, with numbered messages, arrows for direction (-> from client to server, <- back) and request IDs renumbered so the output stays stable. Values under names that look like secrets print as [redacted]; this trace has none.
To see the wire, run the call for order O-2476 from the client example through the relay. Three of its messages print in full, and the rest on one line each.
1"""Record every message the client and the shop's server exchange for one tool call, and print them in order. The point2 rests on the methods line: the exchange has no initialize."""3import asyncio4import pathlib5import sys67from mcp import Client, StdioServerParameters8from mcp.types import Implementation910from lib import loopback, shop_api, wire111213async def main() -> None:14 with loopback.serve(shop_api.create_app()) as base_url:15 server = StdioServerParameters(command=sys.executable, args=["order-status-server.py", "--serve"],16 env=shop_api.server_env(base_url))17 pathlib.Path("wire.jsonl").unlink(missing_ok=True) # the relay appends, so start each run empty18 # the relay starts the server and copies every line both ways, appending each one to the log19 params = wire.relay(server, log="wire.jsonl")20 async with Client(params, client_info=Implementation(name="shop-host", version="0.1.0")) as client:21 await client.list_tools()22 await client.call_tool("get_order_status", {"order_id": "O-2476"})23 # messages 1, 5 and 6 print in full; the rest on one line, with strings cut at 48 characters24 messages = wire.print_trace("wire.jsonl", full=(1, 5, 6), depth=4, max_string=48)25 print("messages:", len(messages))26 print("methods:", ", ".join(m["method"] for m in messages if "method" in m)) # results carry no method272829asyncio.run(main())
python trace-first-call.py1. -> request server/discover (id 1)
{
"jsonrpc": "2.0",
"id": 1,
"method": "server/discover",
"params": {
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientInfo": {
"name": "shop-host",
"version": "0.1.0"
},
"io.modelcontextprotocol/clientCapabilities": {}
}
}
}
2. <- result (id 1) result: {"cacheScope": "private", "capabilities": "{…}", "resultType": "complete", "supportedVersions": "[…]", "ttlMs": 0, "_meta": "{…}"}
3. -> request tools/list (id 2) params: {"_meta": "{…}"}
4. <- result (id 2) result: {"cacheScope": "private", "resultType": "complete", "tools": "[…]", "ttlMs": 0, "_meta": "{…}"}
5. -> request tools/call (id 3)
{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "get_order_status",
"arguments": {
"order_id": "O-2476"
},
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientInfo": {
"name": "shop-host",
"version": "0.1.0"
},
"io.modelcontextprotocol/clientCapabilities": {}
}
}
}
6. <- result (id 3)
{
"jsonrpc": "2.0",
"id": 3,
"result": {
"content": [
{
"text": "{\n \"order_id\": \"O-2476\",\n \"customer_id\": \"C-0…",
"type": "text"
}
],
"isError": false,
"resultType": "complete",
"_meta": {
"io.modelcontextprotocol/serverInfo": {
"name": "shop-orders",
"version": "0.1.0"
}
}
}
}
messages: 6
methods: server/discover, tools/list, tools/call
Nothing here is a handshake: there is no initialize. The exchange is 6 messages, and the methods, in order, are server/discover, tools/list, tools/call. Reading them one at a time:
server/discoveris the first request. Itsparamshold only_meta, with three entries:io.modelcontextprotocol/protocolVersion,io.modelcontextprotocol/clientInfonamingshop-host, andio.modelcontextprotocol/clientCapabilities, which is empty because this client declares none. Every server must implementserver/discover(discovery).- Its result lists
supportedVersionsand the server'scapabilities, and the server's own_metacarriesio.modelcontextprotocol/serverInfo. The result also hasresultTypeand two cache hints,ttlMsandcacheScope, which Cache list results explains. tools/listcarries the same_metaagain.- Its result holds the tool definition that the server example printed.
tools/callnames the tool and gives itsarguments, and once more carries the protocol version, the client's name and its capabilities.- Its result holds the order as text
content, withisErrorset to false andresultTypeset to"complete".
Three requests, each saying who is asking and at which revision, because no request may lean on the one before it.
Every result carries resultType, and "complete" marks an ordinary answer. The other kind, a request for input mid-call, is the subject of Return an input request instead of a result. A client treats a result without the field, from an older server, as complete (base protocol). The SDK's server adds resultType and the serverInfo stamp itself (mcp/server/runner.py).
One thing is missing from the trace on purpose: the shop's API key. It reached the server through the subprocess's environment, and the server sent it only to the shop's API. The specification wants stdio servers to retrieve credentials from the environment, not to follow the OAuth flow that Authorize clients with OAuth teaches for HTTP (base protocol).
Working rule: When a call behaves unexpectedly, trace the wire before you read the SDK's code: a relay that copies and logs lines works with any client and any server. Never write to standard output from a stdio server, not even a debugging print(), because the client reads every line there as a message. Use logging, which the SDK sends to standard error, or write to standard error yourself.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Let a model choose the tool
In the client example, the code chose the tool and its arguments. In the shop's case a model should make that choice. Tools are model-controlled. The host shows a model the available tools, and the model decides which to call and with what arguments (tools). The host stays in charge of everything else. It builds the prompt, reads the model's reply, makes the call through its client, and decides what to do with the result.
The book's host loop, lib.host, is a small host the book writes itself, so each step is visible. Here it does one turn: it renders the server's tools into the book's own system prompt, giving each tool's name, description and input schema, then sends that prompt and one ticket to a model and parses the reply. A reply holding a <tool_call> block with a tool's name and arguments is a choice, and any other reply is an answer in words. The loop keeps the prompt and parsing in the book's code, not a model library's, so the same code drives the real model when a recording is made and the replay in examples.
Examples here never call a model, because its output isn't deterministic and examples must run offline. A recording holds the model's raw replies under examples/data/recorded/, made once by a script in recordings/, and examples replay them with ReplayModel. The replay fails loudly if the prompt, the ticket or the tools have changed. Every recording in this book uses Qwen3-4B-Instruct-2507, an open model under the Apache-2.0 licence, quantized to 4 bits (Q4_K_M, in a third-party GGUF conversion) and run on the CPU with llama.cpp, so anyone can make the recordings again. The script recordings/pick_a_tool.py made this chapter's recording, pick-a-tool, against the same server and prompt, and its manifest names the model file's revision and hash.
The uncertain part is the model, so the example gives it three tickets: one quotes an order ID the way the shop writes it, one gives a bare order number, and one asks about stock, which no tool on this server can answer.
1"""The book's host loop shows three tickets and the server's tools to a model, then calls the tool the model chooses, from recorded replies in examples/data/recorded/. The point rests on the three `tool` lines."""2import asyncio3import json4import sys56from mcp import Client, StdioServerParameters7from mcp.types import Implementation89from lib import loopback, shop_api10from lib.host import ReplayModel, choose_tool11from lib.shop_data import load_shop1213model = ReplayModel("pick-a-tool") # answers only with the replies recorded for these exact messages141516async def main() -> None:17 shop = load_shop()18 with loopback.serve(shop_api.create_app()) as base_url:19 params = StdioServerParameters(command=sys.executable, args=["order-status-server.py", "--serve"],20 env=shop_api.server_env(base_url))21 async with Client(params, client_info=Implementation(name="shop-host", version="0.1.0")) as client:22 tools = (await client.list_tools()).tools23 for ticket_id in ("T-0003", "T-0010", "T-0015"):24 ticket = shop.ticket(ticket_id)25 # the longest paragraph of the ticket, which holds the customer's question26 print(f"{ticket_id} asks:", max(ticket.body.split("\n\n"), key=len))27 choice = choose_tool(model, ticket, tools)28 print(f"{ticket_id} tool:", choice.tool or "none")29 if choice.tool is None: # the model answered in words, so there is no call to make30 print(f"{ticket_id} reply:", choice.reply[:72] + "…") # a reply can run long, so the output shows only its opening31 continue32 print(f"{ticket_id} order id:", choice.arguments.get("order_id"))33 result = await client.call_tool(choice.tool, choice.arguments)34 print(f"{ticket_id} order status:", json.loads(result.content[0].text)["status"])353637asyncio.run(main())
python host-picks-a-tool.pyT-0003 asks: Can you tell me when O-1942 will arrive. I need it before the weekend
T-0003 tool: get_order_status
T-0003 order id: O-1942
T-0003 order status: shipped
T-0010 asks: where is my order 2496? its been ages and the tracking page says nothing
T-0010 tool: get_order_status
T-0010 order id: O-2496
T-0010 order status: shipped
T-0015 asks: Do you have enamelled casserole in stock? I'd want two of them
T-0015 tool: none
T-0015 reply: I don't have access to real-time inventory or stock levels for Fernhill …
The model picked the lookup for the two tickets that need an order and declined the one that needs stock. On ticket T-0003 it chose get_order_status for the order the ticket names, and the host's call found that order shipped. Ticket T-0010 gave only a bare number, yet the model still sent O-2496, the form both the description and the prompt show. For the stock question in T-0015, the model called no tool, none, and said in words that it couldn't check stock. That is the right behaviour for a server that offers only order lookups, and chapter 3 adds the check_stock tool the ticket needs.
Three recorded choices show the loop working. They don't measure how often a model chooses well. Write descriptions the model reads compares descriptions on more tickets, and Measure how often the right tool is chosen measures accuracy over the whole ticket queue.
This host calls get_order_status without asking anyone, which departs from the specification. The specification puts consent on the host: hosts "must obtain explicit user consent before invoking any tool", and MCP itself can't enforce that (specification overview). The tools page adds that there SHOULD always be a human in the loop, able to deny a tool call (tools). We skip it here, because the tool only reads, from a server the shop runs, and a wrong call changes nothing. We recommend skipping it only in that case. Ask for consent before side effects, in the chapter on MCP's security model, adds the consent step.
Working rule: Keep the host's prompt and the parsing of the model's reply in your own code, and test the loop against recorded replies rather than a live model. Record the model's raw text, not SDK objects, so an SDK release doesn't invalidate a recording, and make a replay fail when its input changes. Switch to a live model only for the measurement runs that decide which descriptions and which model you ship.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
What goes wrong in production
The shop's first server works on one machine. Taken into production, the same few parts fail in a handful of ways, each with a sign to watch for.
Anything on standard output breaks the channel. A library that prints a banner, or a stray print() while debugging, puts a line on the server's standard output that isn't JSON-RPC, which the stdio transport forbids (stdio transport). The client shows it as parse errors or dropped responses, often only on the one code path that prints. The SDK's own logging goes to standard error (mcp/server/mcpserver/utilities/logging.py), so route yours there as well.
The server inherits less than you think. The stdio client passes a short allowlist of variables and nothing else (mcp/client/stdio.py), so a server that works from your shell fails when a host launches it. The sign is the one the client example showed: a generic Error executing tool in the client and a KeyError in the server's standard error. Pass every variable in env=, and fail at startup if one is missing, not at the first call. The shop's server reads its variables inside the tool on purpose, so that the client example could show the late failure; a server you ship should read them once, before it serves.
The server dies mid-call. The specification asks the client to restart a stdio server that exits, and because the protocol is stateless, "any in-flight requests are simply lost and the client can retry them" (stdio transport). mcp.Client restarts nothing at 2.3.0: a call in flight fails with an MCPError that says Connection closed, and the host must open a new Client and retry (mcp/client/stdio.py, mcp/shared/jsonrpc_dispatcher.py). A retried get_order_status is harmless, but a retried refund isn't, which is why the shop's refund tool needs a once-only check on the server (Keep round-trip state tamper-proof). On shutdown the client closes the server's standard input and waits; the SDK allows it 2 seconds before escalating to a signal (mcp/client/stdio.py), so servers should exit promptly on end of input.
A slow start costs time and can change the revision. The SDK's client waits 10 seconds for the answer to server/discover (mcp/client/session.py). A server that loads a large model or opens many connections before reading its first message can miss that window on a cold machine. Auto mode then treats the timeout as a failed probe and sends the old initialize handshake, which has no default time limit (mcp/client/_probe.py). A server built on this SDK that has already answered the late probe rejects initialize with its supported versions, and the client probes once more, so the connection succeeds more than 10 seconds late. A server from another SDK that also answers initialize can settle on a 2025 revision without any error. The sign is client.protocol_version, not a dead server. Do slow setup lazily, or after the server reads its input.
The other side speaks a 2025 revision. Client in auto mode falls back to the old handshake for a 2025-era server. After a fallback the connection speaks the 2025 revision, so none of the pinned revision's features are there (changelog), and client.protocol_version says which revision you got. A server that doesn't support the client's version answers with an error, which Handle a version the server doesn't support shows. When the error comes from someone else's server, the trace from Read the messages on the wire tells you which revision each side sent.
Other languages lag or lead. The MCP documentation lists official SDKs by tier. Tier 1 is TypeScript, Python, C#, Go, Rust and Ruby, and the tiers change over time (SDKs). A host in one language and a server in another can implement a revision's details differently, and the wire is where you settle which one is right.
Working rule: On the machine that launches a stdio server in production, check three things: nothing but JSON-RPC reaches standard output, every variable the server needs is passed explicitly, and the server answers server/discover within 10 seconds of starting. Keep the server's standard error in your logs, because that is where its real errors go.
이 장에서 내린 결정
- 상점의 데이터는 하나의 시드에서 나오며 고정된 날짜에서 끝난다. 따라서 이 책의 모든 예제는 같은 고객, 주문, 티켓을 본다.
- 상점의 API는 계속 기준 시스템으로 남는다. MCP 서버는 자체 키로 이 API를 호출하는 얇은 어댑터다.
- 읽기 전용 도구 하나인
get_order_status이 엔드포인트 하나를 감싼다. 이 도구의 독스트링은 모델이 읽을 것을 전제로 작성한다. - 모델이 대응할 수 있는 실패는
ToolError를 발생시킨다. 그 밖의 예외는 일반적인 메시지로 클라이언트에 전달되고, 자세한 내용은 서버의 표준 오류에만 남는다. - 먼저 stdio를 다루며,
MCPServer.run()의 기본 전송 방식을 사용한다. Streamable HTTP는 Serve over Streamable HTTP에서 다룬다. mcp.Client를 기본 자동 모드로 사용하며, 직접 초기화한ClientSession는 쓰지 않는다. 그래서 첫 메시지는 고정된 리비전의server/discover가 된다.- 서버는
sys.executable와 명시적인env=로 실행하며, 자격 증명은 환경을 통해 전달하고 통신 구간에는 싣지 않는다. - 트레이스는 실제 stdio 서브프로세스 위의 릴레이에서 얻는다. 인프로세스 클라이언트는 JSON-RPC를 전혀 보내지 않기 때문이다.
- 호스트 루프의 프롬프트와 파싱은 이 책이 직접 작성한 코드이며, 예제는 CPU에서 실행한 오픈 모델인 Qwen3-4B-Instruct-2507의 녹화본을 재생한다.
- 녹화본은 자신이 본 메시지에만 정확히 응답한다. 프롬프트, 티켓, 도구 목록이 바뀌면 오래된 응답을 돌려주는 대신 재생이 실패한다.
- 이 장에는 동의 단계가 없다. 이는 명세에서 벗어난 것이며, 상점이 운영하는 서버의 읽기 전용 도구에 한해서만 받아들인다. 동의 단계는 Ask for consent before side effects에서 도입한다.
이 판의 이 장
2026.11.14판예제 통과 2026년 11월 19이 장에서 5개 예제개 중 5개가 통과한다
영어판 2026.11.14판을 번역한 것이다.