MCP end to end
閱讀約需 69 分鐘 分鐘,7 節 中共有 5 個範例。
此部分尚未翻譯,因此以英文呈現。
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,並讓它在你的範例能連到的地方執行。
本書每一章都以這家商店 Fernhill Supply 為對象,我們稱之為商店。這家商店純屬虛構,不代表任何真實企業;它的網域 fernhill.example 是保留名稱,永遠無法解析。它的客服團隊負責回覆客戶的工單,而多數工單都需要到商店的系統中查詢:訂單目前在哪裡、商品是否有庫存,或是退款會是多少金額。本書的目標,是做出一個能讀取這些工單,並呼叫商店工具來回答的主機端。
商店已經具備每一章要包裝的「改造前」系統:商店的 API。這是一套處理訂單、庫存與退款的 HTTP API,會檢查 X-API-Key 標頭中的 API 金鑰。它的紀錄是商店的資料,由本書自己的程式碼依據同一個固定種子產生,因此每次執行看到的客戶、訂單與工單都相同。examples/lib/ 中有三個共用模組負責這項設定,讓範例保持簡短:
lib.shop_data負責產生商店的資料。load_shop()會以 Python 資料類別(dataclass)的形式,回傳客戶、商品、庫存量、訂單、退款與工單。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,並讓它繼續作為記錄系統。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.
讓模型選擇工具
在用戶端範例中,是由程式碼選擇工具及其引數。在這家商店的情境裡,這項選擇應該由模型來做。工具是由模型控制的。主機(host)向模型呈現可用的工具,由模型決定要呼叫哪一個,以及使用什麼引數(工具)。其餘的一切仍由主機負責:它建構提示詞、讀取模型的回覆、透過自己的用戶端發出呼叫,並決定如何處理結果。
本書的主機迴圈 lib.host 是本書自行撰寫的一個小型主機,因此每個步驟都看得見。在這裡它只執行一個回合:先把伺服器的工具轉譯成本書自己的系統提示詞,列出每個工具的名稱、描述與輸入結構描述(input schema),再把該提示詞與一張工單送給模型,並解析回覆。回覆中若含有一個帶著工具名稱與引數的 <tool_call> 區塊,就是一次選擇;其他任何回覆都是以文字給出的答案。這個迴圈把提示詞與解析都放在本書的程式碼中,而不是放在某個模型函式庫裡,因此同一份程式碼,在製作錄製檔時驅動真實的模型,在範例中則驅動重播。
這裡的範例從不呼叫模型,因為模型的輸出不具確定性,而範例必須能離線執行。錄製檔(recording)保存模型的原始回覆,位於 examples/data/recorded/ 之下,由 recordings/ 中的腳本一次製作完成,範例則以 ReplayModel 重播。如果提示詞、工單或工具有任何變動,重播就會明確地失敗。本書的每一份錄製檔都使用 Qwen3-4B-Instruct-2507,這是一個採用 Apache-2.0 授權的開放模型,以 4 位元量化(Q4_K_M,使用第三方的 GGUF 轉換版本),並以 llama.cpp 在 CPU 上執行,因此任何人都能重新製作錄製檔。腳本 recordings/pick_a_tool.py 針對相同的伺服器與提示詞,製作了本章的錄製檔 pick-a-tool,其清單(manifest)載明了模型檔案的修訂版本與雜湊值。
不確定的部分是模型,所以範例給它三張工單:一張以商店書寫訂單編號的方式引用訂單編號,一張只給出單純的訂單數字,還有一張詢問庫存,而這個伺服器上沒有任何工具能回答。
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 …
對於需要訂單資料的兩張工單,模型選了查詢工具;對於需要庫存資料的那一張,模型則不採取任何工具。在工單 T-0003 中,模型為工單所指的訂單選了 get_order_status,主機的呼叫查到該訂單為 shipped。工單 T-0010 只給了單純的數字,模型卻仍然送出 O-2496,也就是描述與提示詞都示範的格式。至於 T-0015 的庫存問題,模型沒有呼叫任何工具,即 none,並以文字說明它無法查詢庫存。對於只提供訂單查詢的伺服器而言,這是正確的行為,而第 3 章會加入該工單所需的 check_stock 工具。
三次錄製下來的選擇,顯示了這個迴圈能夠運作,但它們並不能衡量模型做出良好選擇的頻率。撰寫模型讀得懂的描述以更多工單比較不同的描述,而衡量正確選擇工具的頻率則在整個工單佇列上衡量準確率。
這個主機未經詢問任何人就呼叫 get_order_status,這與規格有所出入。規格把同意的責任放在主機身上:主機「必須在叫用任何工具之前取得使用者明確的同意」,而 MCP 本身無法強制執行這一點(規格概觀)。工具頁面還補充,應該(SHOULD)始終有一個人在迴圈中,能夠拒絕工具呼叫(工具)。我們在這裡略過這個步驟,因為該工具只做讀取,對象是商店自己運行的伺服器,錯誤的呼叫不會改變任何東西。我們建議只在這種情況下才略過。在談 MCP 安全模型的那一章中,在產生副作用之前徵求同意會加入同意這個步驟。
實用原則: 把主機的提示詞與模型回覆的解析保留在自己的程式碼中,並以錄製的回覆而非即時模型來測試迴圈。記錄模型的原始文字,而不是 SDK 物件,這樣 SDK 的發行版本就不會使錄製檔失效,同時要讓重播在輸入改變時失敗。只有在進行衡量執行、以決定要交付哪些描述與哪個模型時,才切換到即時模型。
正式環境中會出什麼問題
商店的第一個伺服器在一台機器上運作正常。放進正式環境後,同樣那幾個部分會以幾種方式失敗,每一種都有可供留意的徵兆。
標準輸出上的任何內容都會破壞通道。 函式庫印出橫幅,或除錯時遺留的 print(),都會在伺服器的標準輸出上留下一行不是 JSON-RPC 的內容,而 stdio 傳輸層禁止這種情況(stdio 傳輸層)。用戶端會把它顯示為解析錯誤或遺失的回應,而且往往只出現在會印出內容的那一條程式路徑上。SDK 自身的記錄輸出到標準錯誤(mcp/server/mcpserver/utilities/logging.py),因此你的記錄也應導向那裡。
伺服器繼承的環境比你想的少。 stdio 用戶端只傳遞一份簡短的允許清單中的變數,其餘一概不傳(mcp/client/stdio.py),所以在你的 shell 中能運作的伺服器,由主機程式啟動時就會失敗。徵兆就是用戶端範例所示的那一種:用戶端出現籠統的 Error executing tool,而伺服器的標準錯誤中出現 KeyError。請在 env= 中傳入每一個變數,並在變數缺少時於啟動時就失敗,而不是等到第一次呼叫才失敗。商店的伺服器刻意在工具內部讀取變數,好讓用戶端範例能展示這種延遲發生的失敗;你要上線的伺服器則應在開始提供服務之前,一次讀取完畢。
伺服器在呼叫途中死亡。 規格要求用戶端重新啟動已結束的 stdio 伺服器,而且因為協定是無狀態的,「任何進行中的請求都會直接遺失,用戶端可以重試這些請求」(stdio 傳輸層)。mcp.Client 在 2.3.0 不會自動重新啟動任何東西:進行中的呼叫會以 MCPError 失敗,訊息為 Connection closed,主機程式必須開啟新的 Client 再重試(mcp/client/stdio.py、mcp/shared/jsonrpc_dispatcher.py)。重試 get_order_status 無害,但重試退款就不然,這正是商店的退款工具需要在伺服器上做一次性檢查的原因(讓往返狀態無法被竄改)。關閉時,用戶端會關閉伺服器的標準輸入並等待;SDK 會給它 2 秒,之後才升級為傳送訊號(mcp/client/stdio.py),所以伺服器應在輸入結束時迅速退出。
啟動緩慢既耗時,也可能改變修訂版本。 SDK 的用戶端會等待 server/discover 的回應達 10 秒(mcp/client/session.py)。伺服器若在讀取第一則訊息之前載入大型模型或開啟許多連線,在冷機器上就可能錯過這個時間窗。自動模式隨後會把逾時視為探測失敗,並送出舊式的 initialize 交握,而該交握沒有預設的時間限制(mcp/client/_probe.py)。以此 SDK 建置、且已回應過遲到探測的伺服器,會以其支援的版本拒絕 initialize,用戶端便再探測一次,因此連線會在超過 10 秒之後才成功。若是來自其他 SDK、同樣會回應 initialize 的伺服器,則可能在沒有任何錯誤的情況下定案於某個 2025 修訂版本。徵兆是 client.protocol_version,而不是伺服器已死。請延後進行耗時的設定,或等伺服器讀取輸入之後再做。
對方使用的是 2025 修訂版本。 自動模式下的 Client 面對 2025 年代的伺服器時,會退回舊式交握。退回之後,連線使用的是 2025 修訂版本,因此所固定修訂版本的功能都不存在(變更記錄),而 client.protocol_version 會告訴你取得的是哪個修訂版本。若伺服器不支援用戶端的版本,會以錯誤回應,處理伺服器不支援的版本對此有說明。當錯誤來自他人的伺服器時,讀取線路上的訊息中的追蹤紀錄能告訴你雙方各自送出的是哪個修訂版本。
其他語言落後或領先。 MCP 文件依層級列出官方 SDK。第 1 層是 TypeScript、Python、C#、Go、Rust 與 Ruby,且各層級會隨時間改變(SDK)。以某種語言撰寫的主機程式與以另一種語言撰寫的伺服器,對某個修訂版本的細節可能有不同的實作,而線路上的內容正是判定何者正確之處。
實用原則: 在正式環境中啟動 stdio 伺服器的那台機器上,請檢查三件事:只有 JSON-RPC 會到達標準輸出、伺服器需要的每個變數都已明確傳入,以及伺服器在啟動後 10 秒內回應 server/discover。請把伺服器的標準錯誤保留在你的記錄中,因為它真正的錯誤都會輸出到那裡。
本章做出的決定
- 商店的資料來自單一種子,並止於固定日期,因此本書中的每個範例看到的都是相同的客戶、訂單與客服單。
- 商店的 API 仍是記錄系統(system of record)。 MCP 伺服器只是一層薄薄的轉接層,以它自己的金鑰呼叫該 API。
- 一個唯讀工具
get_order_status,包裝一個端點。它的 docstring 是寫給模型看的。 - 模型能據以採取行動的失敗會引發
ToolError;其他例外則以通用訊息傳到用戶端,細節只留在伺服器的標準錯誤輸出中。 - 先用 stdio,採用
MCPServer.run()的預設傳輸方式。Streamable HTTP 會在〈Serve over Streamable HTTP〉中介紹。 - 使用預設自動模式的
mcp.Client,絕不手動初始化ClientSession,因此在固定的修訂版本下,第一則訊息是server/discover。 - 以
sys.executable與明確的env=啟動伺服器,憑證透過環境變數傳遞,絕不經由傳輸線路傳送。 - 追蹤紀錄來自真實 stdio 子行程上的中繼器,因為行程內的用戶端不會送出 JSON-RPC。
- 主機迴圈的提示詞與解析,是本書自己的程式碼,範例重播的是 Qwen3-4B-Instruct-2507 的錄製紀錄,這是一個在 CPU 上執行的開放模型。
- 錄製紀錄只回應它見過的完全相同的訊息。 提示詞、客服單或工具清單一有改變,重播就會失敗,而不是回傳過時的回覆。
- 本章沒有同意步驟,這與規格不同,我們只在工具為唯讀、且伺服器由商店自己執行時才接受這種做法。同意機制會在〈Ask for consent before side effects〉中加入。
本章,於本版次中
版次 2026.11.14範例於 2026年11 月 19 通過測試本章 5 個範例 個範例中有 5 個通過
譯自英文書,版次 2026.11.14。