MCP end to end

阅读约需 69分钟 分钟,7节中含5个示例。

版次 2026.11.14 示例于 2026年11月19日 通过 70个示例中有70个通过 变化内容

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

最近一次修改见于版次 2026.11.11

MCP 服务器很少从零开始。需要它的团队多半已经在运行一个 HTTP API,这个 API 有自己的数据、认证和客户端,而服务器的任务,是把其中一部分交到模型面前。因此,首先要有你要封装的那个 API,并且让它运行在示例能够访问到的地方。

本书每一章都围绕这家商店 Fernhill Supply 展开,我们称之为商店。商店是虚构的,不代表任何真实的企业;它的域名 fernhill.example 是一个保留名称,永远无法解析。它的支持团队负责回复客户工单,而大多数工单都需要到商店的系统中查询:订单在哪里、某件商品是否有库存,或者一次退款会是多少金额。本书的目标是构建一个宿主程序,让它读取这些工单,并调用商店的工具来回答。

商店已经具备了每一章都要封装的“原有系统”:商店的 API。这是一个用于订单、库存和退款的 HTTP API,它会检查 X-API-Key 请求头中的 API 密钥。它的记录是商店的数据,由本书自带的代码根据同一个固定的种子生成,因此每次运行看到的客户、订单和工单都相同。examples/lib/ 中的三个共享模块承载了这套准备工作,使示例保持简短:

  • lib.shop_data 负责生成商店的数据。load_shop() 以 Python 数据类的形式返回其中的客户、商品、库存水平、订单、退款和工单。
  • lib.shop_api 是商店的 API,是建立在这些数据之上的 Starlette 应用。
  • lib.loopback 在 127.0.0.1 的一个空闲端口上提供应用服务,并在代码块结束时将其停止。

在封装这个 API 之前,先像任何客户端那样运行它:带密钥请求一次,不带密钥请求一次,再请求一个不存在的订单一次。

start-the-shop-api.py Python 3.12.15 · httpx2 2.16.2 · starlette 1.10.0 · uvicorn 0.54.0 通过
"""Start the shop's existing HTTP API on loopback and call it three ways: with its key, without it, and for an order that doesn't exist. The point rests on the `without key` line, which shows the API refuses a caller it can't identify."""import httpx2from lib import loopback, shop_apifrom lib.shop_data import SHOP_SEED, load_shopshop = load_shop()  # one fixed seed, so every run sees the same customers, orders and ticketsprint("seed:", SHOP_SEED)print("customers:", len(shop.customers))print("products:", len(shop.products))print("orders:", len(shop.orders))print("tickets:", len(shop.tickets))with loopback.serve(shop_api.create_app()) as base_url:  # serves on 127.0.0.1 at a free port until the block ends    # the API checks this header; DEMO_API_KEY is the key the shop's API accepts    response = httpx2.get(f"{base_url}/orders/O-2476", headers={"X-API-Key": shop_api.DEMO_API_KEY})    order = response.json()    print("with key:", response.status_code)    print("order status:", order["status"])    print("shipped on:", order["shipped_on"])    print("total:", order["total"])    print("without key:", httpx2.get(f"{base_url}/orders/O-2476").status_code)  # no header at all    # O-7144 is a well-formed ID that the generated orders do not contain    print("unknown order:", httpx2.get(f"{base_url}/orders/O-7144",                                       headers={"X-API-Key": shop_api.DEMO_API_KEY}).status_code)
输出python start-the-shop-api.py
seed: 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

最近一次修改见于版次 2026.11.14

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.

order-status-server.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · starlette 1.10.0 · uvicorn 0.54.0 通过
"""The shop's first MCP server: one tool, get_order_status, that wraps GET /orders/{order_id} on the shop's API. The point rests on the description and schema lines, the only parts of the tool a model reads."""import asyncioimport jsonimport osimport sysimport httpx2from mcp import Client, StdioServerParametersfrom mcp.server.mcpserver import MCPServerfrom mcp.server.mcpserver.exceptions import ToolErrorserver = MCPServer("shop-orders", version="0.1.0")@server.tool()def get_order_status(order_id: str) -> dict:    """Look up one of the shop's orders by its ID, such as O-1873: its status, dates, lines and total."""    # read on each call: a missing variable raises KeyError here, and the SDK reports only a generic error    response = httpx2.get(f"{os.environ['SHOP_API_URL']}/orders/{order_id}",                          headers={"X-API-Key": os.environ["SHOP_API_KEY"]},                          timeout=5.0)  # seconds; a slow shop API fails this call instead of holding the worker    # the shop answers 404 for an order it doesn't have, so the model gets a message it can act on    if response.status_code == 404:        raise ToolError(f"The shop has no order {order_id}. Order IDs look like O-1873.")    response.raise_for_status()  # any other failure, such as a wrong key, stays on the server as an HTTPError    return response.json()async def show_tools() -> None:    from lib import loopback, shop_api    with loopback.serve(shop_api.create_app()) as base_url:        # the API's address and key are the only variables the server gets        params = StdioServerParameters(command=sys.executable, args=[__file__, "--serve"],                                       env=shop_api.server_env(base_url))        async with Client(params) as client:            for tool in (await client.list_tools()).tools:                print("tool:", tool.name)                print("description:", tool.description)                print("input schema:", json.dumps(tool.input_schema))if __name__ == "__main__":    if "--serve" in sys.argv:        server.run()                  # stdio is the default transport    else:        asyncio.run(show_tools())
输出python order-status-server.py
tool: 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

最近一次修改见于版次 2026.11.11

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.

call-order-status.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · starlette 1.10.0 · uvicorn 0.54.0 通过
"""Launch the shop's server over stdio and call get_order_status for a real order and a wrong one, then for a server 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."""import asyncioimport jsonimport sysfrom mcp import Client, StdioServerParametersfrom mcp.types import Implementationfrom lib import loopback, shop_apiSHOP_HOST = Implementation(name="shop-host", version="0.1.0")  # the name the server's logs and the wire showasync def main() -> None:    with loopback.serve(shop_api.create_app()) as base_url:        env = {"SHOP_API_URL": base_url, "SHOP_API_KEY": shop_api.DEMO_API_KEY}  # the only two variables the server reads        # relative to the examples folder, where examples run, so the server file is found        params = StdioServerParameters(command=sys.executable, args=["order-status-server.py", "--serve"], env=env)        async with Client(params, client_info=SHOP_HOST) as client:            print("protocol revision:", client.protocol_version)            print("server:", client.server_info.name, client.server_info.version)            result = await client.call_tool("get_order_status", {"order_id": "O-2476"})            assert result.is_error is False        # a real order comes back as a result, not an error            # the tool returns the order as JSON text in its first content block            print("order status:", json.loads(result.content[0].text)["status"])            wrong = await client.call_tool("get_order_status", {"order_id": "O-7144"})            assert wrong.is_error is True          # an unknown order is a failed tool result, not an exception            print("wrong ID says:", wrong.content[0].text)        # no env=, so the server starts without the shop's variables and its tool fails at the first call        no_env = StdioServerParameters(command=sys.executable, args=["order-status-server.py", "--serve"])        async with Client(no_env, client_info=SHOP_HOST) as client:            broken = await client.call_tool("get_order_status", {"order_id": "O-2476"})            print("without env says:", broken.content[0].text)asyncio.run(main())
输出python call-order-status.py
protocol 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

最近一次修改见于版次 2026.11.11

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.

trace-first-call.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · starlette 1.10.0 · uvicorn 0.54.0 通过
"""Record every message the client and the shop's server exchange for one tool call, and print them in order. The point rests on the methods line: the exchange has no initialize."""import asyncioimport pathlibimport sysfrom mcp import Client, StdioServerParametersfrom mcp.types import Implementationfrom lib import loopback, shop_api, wireasync def main() -> None:    with loopback.serve(shop_api.create_app()) as base_url:        server = StdioServerParameters(command=sys.executable, args=["order-status-server.py", "--serve"],                                       env=shop_api.server_env(base_url))        pathlib.Path("wire.jsonl").unlink(missing_ok=True)   # the relay appends, so start each run empty        # the relay starts the server and copies every line both ways, appending each one to the log        params = wire.relay(server, log="wire.jsonl")        async with Client(params, client_info=Implementation(name="shop-host", version="0.1.0")) as client:            await client.list_tools()            await client.call_tool("get_order_status", {"order_id": "O-2476"})    # messages 1, 5 and 6 print in full; the rest on one line, with strings cut at 48 characters    messages = wire.print_trace("wire.jsonl", full=(1, 5, 6), depth=4, max_string=48)    print("messages:", len(messages))    print("methods:", ", ".join(m["method"] for m in messages if "method" in m))  # results carry no methodasyncio.run(main())
输出python trace-first-call.py
1. -> 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:

  1. server/discover is the first request. Its params hold only _meta, with three entries: io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientInfo naming shop-host, and io.modelcontextprotocol/clientCapabilities, which is empty because this client declares none. Every server must implement server/discover (discovery).
  2. Its result lists supportedVersions and the server's capabilities, and the server's own _meta carries io.modelcontextprotocol/serverInfo. The result also has resultType and two cache hints, ttlMs and cacheScope, which Cache list results explains.
  3. tools/list carries the same _meta again.
  4. Its result holds the tool definition that the server example printed.
  5. tools/call names the tool and gives its arguments, and once more carries the protocol version, the client's name and its capabilities.
  6. Its result holds the order as text content, with isError set to false and resultType set 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.

让模型选择工具

最近一次修改见于版次 2026.11.11

在客户端示例中,由代码选择工具及其参数。在商店的场景里,这一选择应当由模型来做。工具由模型控制。宿主向模型展示可用的工具,由模型决定调用哪一个、使用什么参数(工具)。其余一切仍由宿主负责:它构造提示词,读取模型的回复,通过自己的客户端发起调用,并决定如何处理结果。

本书的宿主循环 lib.host 是本书自己编写的一个小型宿主,因此每一步都清晰可见。这里它只执行一轮:先把服务器的工具渲染进本书自己的系统提示词,给出每个工具的名称、描述和输入模式,然后把该提示词和一张工单发送给模型,并解析回复。若回复中含有一个带有工具名称和参数的 <tool_call> 块,就是一次选择;其他任何回复都是用文字给出的答复。循环把提示词和解析逻辑放在本书的代码中,而不是某个模型库里,因此同一份代码在制作录制时驱动真实模型,在示例中则驱动回放。

这里的示例从不调用模型,因为模型的输出不具确定性,而示例必须能离线运行。录制在 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,其清单中写明了模型文件的修订版本和哈希值。

不确定的部分是模型,所以示例给它三张工单:一张按商店的写法给出订单 ID,一张只给出裸订单号,还有一张询问库存,而这台服务器上没有任何工具能回答这个问题。

host-picks-a-tool.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · starlette 1.10.0 · uvicorn 0.54.0 通过
"""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."""import asyncioimport jsonimport sysfrom mcp import Client, StdioServerParametersfrom mcp.types import Implementationfrom lib import loopback, shop_apifrom lib.host import ReplayModel, choose_toolfrom lib.shop_data import load_shopmodel = ReplayModel("pick-a-tool")  # answers only with the replies recorded for these exact messagesasync def main() -> None:    shop = load_shop()    with loopback.serve(shop_api.create_app()) as base_url:        params = StdioServerParameters(command=sys.executable, args=["order-status-server.py", "--serve"],                                       env=shop_api.server_env(base_url))        async with Client(params, client_info=Implementation(name="shop-host", version="0.1.0")) as client:            tools = (await client.list_tools()).tools            for ticket_id in ("T-0003", "T-0010", "T-0015"):                ticket = shop.ticket(ticket_id)                # the longest paragraph of the ticket, which holds the customer's question                print(f"{ticket_id} asks:", max(ticket.body.split("\n\n"), key=len))                choice = choose_tool(model, ticket, tools)                print(f"{ticket_id} tool:", choice.tool or "none")                if choice.tool is None:  # the model answered in words, so there is no call to make                    print(f"{ticket_id} reply:", choice.reply[:72] + "…")  # a reply can run long, so the output shows only its opening                    continue                print(f"{ticket_id} order id:", choice.arguments.get("order_id"))                result = await client.call_tool(choice.tool, choice.arguments)                print(f"{ticket_id} order status:", json.loads(result.content[0].text)["status"])asyncio.run(main())
输出python host-picks-a-tool.py
T-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 本身无法强制执行这一点(规范概览)。工具页面还补充说,始终应当有人参与其中,并能够拒绝工具调用(工具)。我们在此跳过这一步,因为该工具只做读取,所访问的服务器由商店自己运营,错误的调用不会改变任何东西。我们只建议在这种情况下跳过。在产生副作用之前请求同意位于讲 MCP 安全模型的章中,其中加入了同意步骤。

工作准则: 把宿主的提示词和对模型回复的解析保留在你自己的代码中,并针对录制的回复而不是实时模型来测试循环。录制模型的原始文本,而不是 SDK 对象,这样 SDK 的新版本就不会使录制失效,同时让回放在输入变化时失败。只有在用于决定发布哪些描述和哪个模型的测量运行中,才切换到实时模型。

生产环境中会出什么问题

最近一次修改见于版次 2026.11.11

商店的第一个服务器在一台机器上可以正常运行。投入生产后,同样的几个部分会以若干种方式出错,每种方式都有一个需要留意的迹象。

标准输出上的任何内容都会破坏通道。 某个库打印了一条横幅,或者调试时遗留了一个 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 传输)。在 2.3.0 版本下,mcp.Client 不会重启任何东西:进行中的调用会以一个 MCPError 失败,其内容为 Connection closed,宿主必须打开一个新的 Client 并重试(mcp/client/stdio.py、mcp/shared/jsonrpc_dispatcher.py)。重试 get_order_status 是无害的,但重试退款则不是,这正是商店的退款工具需要在服务器上做一次性检查的原因(让往返状态防篡改)。关闭时,客户端会关闭服务器的标准输入并等待;SDK 给予 2 秒的时间,之后才升级为发送信号(mcp/client/stdio.py),所以服务器应当在输入结束时尽快退出。

启动缓慢会耗费时间,还可能改变协议修订版本。 SDK 的客户端会等待 10 秒,以获得对 server/discover 的应答(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。请在日志中保留服务器的标准错误,因为它真正的错误都输出在那里。

本章做出的决定

最近一次修改见于版次 2026.11.11
  • 商店的数据来自同一份种子,并在固定日期截止,因此书中的每个示例看到的都是相同的客户、订单和工单。
  • **商店的 API 仍然是记录系统。**MCP 服务器只是一个轻量适配器,使用它自己的密钥调用该 API。
  • 一个只读工具 get_order_status 封装一个端点。它的文档字符串是写给模型看的。
  • **模型可以据以采取行动的失败会抛出 ToolError;**其他异常只会以通用消息的形式到达客户端,详细信息则保留在服务器的标准错误中。
  • **先使用 stdio,**采用 MCPServer.run() 的默认传输方式。可流式 HTTP 将在通过可流式 HTTP 提供服务中介绍。
  • **mcp.Client 使用默认的自动模式,**绝不手动初始化 ClientSession,因此在固定的修订版本上,第一条消息就是 server/discover。
  • **启动服务器时使用 sys.executable 和显式的 env=,**凭据通过环境变量传递,绝不经由传输通道。
  • **追踪记录来自真实 stdio 子进程上的中继,**因为进程内客户端不发送 JSON-RPC。
  • **宿主循环的提示词和解析是本书自己的代码,**示例回放的是 Qwen3-4B-Instruct-2507 的录制结果,这是一个在 CPU 上运行的开源模型。
  • **录制结果只回应它见过的那些完全相同的消息。**提示词、工单或工具列表一旦改变,回放就会失败,而不会返回过时的回复。
  • **本章没有同意步骤,**这偏离了规范,我们只在工具为只读、且服务器由商店自己运行的情况下接受这一做法。同意机制将在在产生副作用之前征求同意中引入。

本章,在本版次中

版次 2026.11.14示例于 2026年11月19日 通过本章 5个示例 个示例中有 5 个通过

译自英文版图书,版次 2026.11.14。

引用本节

格式

每种格式均引用英文原书,本译本以其为准。

每种格式都会注明该版次。其链接会打开当前版次,节标题处会说明该节文本最后一次修改的时间。访问日期和检索日期即为您打开此页的当天。

本页内容

第 1 章,共 12 章: MCP end to end

  1. 认识商店及其 API
  2. Wrap one endpoint as a tool
  3. Call the tool from a client
  4. Read the messages on the wire
  5. 让模型选择工具
  6. 生产环境中会出什么问题
  7. 本章做出的决定

返回顶部全部章节