MCP 为 API 增添了什么
阅读约需 70分钟 分钟,11节中含6个示例。
读完本章,你应当能够说明宿主、客户端和服务器各自承担什么职责,把商店的每项能力放进合适的 Model Context Protocol 原语,读懂每个请求都携带的版本和能力信息,并判断商店在什么情况下应当保留普通的 HTTP API。本章的论断和示例均基于规范的 2026-07-28 修订版,以及 Python SDK mcp 的 2.3.0 版本。
商店是 Fernhill Supply 虚构的厨房与园艺用品网店。本章需要它提供一个 HTTP API,客服团队的宿主已经在使用该 API 的订单查询功能。MCP 端到端把这项查询放到了 Model Context Protocol(MCP)服务器之后,使客服团队宿主中的模型能够调用它。那台服务器只有一个工具。客服团队希望有更多功能:一是退款政策,只要工单提到金额,宿主就应当随时能取用;二是一种审核退款申请的标准方式。与此同时,仓库团队每晚都从同一个 API 读取库存水平,他们询问是否也应当迁移到 MCP。
这两个问题都取决于 MCP 为一个已经可用的 API 增添了什么。HTTP 客户端是依照开发者读到的端点编写的。MCP 客户端则在运行时了解服务器提供什么,而且是以模型可以读取的形式;协议还规定了每项能力由谁决定何时使用。本章逐一讨论这些新增之处,衡量它们在传输中的开销,最后指出商店不该为它们付出代价的场合。
区分宿主、客户端和服务器
把一个端点封装为工具中的服务器,运行在一个由该章代码驱动的客户端之后。在商店为它增加更多功能之前,需要先准确说明各部分分别负责什么,因为 MCP 的保证附着于角色,而不是进程。
规范定义了三种角色(architecture)。宿主是用户工作所在的应用程序。它创建客户端,维持与模型的对话,并执行安全策略和用户同意机制。客户端是宿主与某一个服务器之间的连接:“Each client is created by the host and communicates with exactly one server”。服务器对外提供工具等能力,除此之外对宿主一无所知。同一页还给出了由这种划分推出的一条设计原则:服务器不应看到整个对话,也不应窥探其他服务器。每个服务器能看到什么由宿主决定,任何跨服务器的操作都发生在宿主中。
支持团队的宿主承担宿主角色,并运行本书的宿主循环。它所使用的每个服务器都有各自的客户端:本章中是一个,即 shop-support;在识别被投毒的工具描述中还有来自合作方的第二个服务器,该服务器绝不能得知商店的服务器返回了什么。shop-support 是本章的服务器。它保留第 1 章的 get_order_status 工具,并增加了一个资源(退款政策)和一个提示(review_refund),使每一类能力各出现一次。与这里所有的服务器示例一样,该文件定义服务器;不带参数运行时,它会启动一个客户端,并用 --serve 启动服务器。
客户端做的第一件事,是询问服务器提供什么。能力是客户端或服务器声明自己支持的某项功能,例如提供工具的服务器,或能够响应输入请求的客户端。在固定的修订版本中,这只需一个请求,即 server/discover,其应答包含服务器支持的版本、能力和名称,因此客户端仅凭这一个应答就能展示服务器支持的全部内容(discovery)。随后,客户端用 tools/list、resources/list 和 prompts/list 分别列出每一类能力。在默认的自动模式下,mcp.Client 在打开时发送 server/discover,并将应答保存为 client.session.discover_result(mcp/client/session.py)。
1"""shop-support, the chapter 2 server, offers one tool, one resource and one prompt. Run bare, the file starts it as a2client, which prints what it discovers: the tools, resources and prompts lines are the ones the prose reads."""3import asyncio4import os5import sys67import httpx28from mcp import Client, StdioServerParameters9from mcp.server.caching import CacheHint10from mcp.server.mcpserver import MCPServer11from mcp.server.mcpserver.exceptions import ToolError1213from lib.policies import policy1415# ttl_ms is in milliseconds, so 300_000 is five minutes; "public" lets a shared cache reuse the tool list.16server = MCPServer("shop-support", version="0.2.0",17 cache_hints={"tools/list": CacheHint(ttl_ms=300_000, scope="public")})181920@server.tool()21def get_order_status(order_id: str) -> dict:22 """Look up one of the shop's orders by its ID, such as O-1873: its status, dates, lines and total."""23 response = httpx2.get(f"{os.environ['SHOP_API_URL']}/orders/{order_id}",24 headers={"X-API-Key": os.environ["SHOP_API_KEY"]}, timeout=5.0) # timeout in seconds25 if response.status_code == 404:26 raise ToolError(f"The shop has no order {order_id}. Order IDs look like O-1873.")27 response.raise_for_status()28 return response.json()293031@server.resource("shop://policies/refund", name="refund-policy", mime_type="text/markdown")32def refund_policy() -> str:33 return policy("refund").path.read_text(encoding="utf-8") # examples/data/shop/policies/refund.md343536@server.prompt()37def review_refund(order_id: str) -> str:38 """Review a customer's refund request for one order against the shop's refund policy."""39 return (f"Review the refund request for order {order_id}. Look up the order with get_order_status, read the "40 "refund policy at shop://policies/refund, and say whether the refund needs a person to confirm it.")414243async def main() -> None:44 # No variables are passed: listing never calls the tool, so the server needs none of the shop's API settings.45 async with Client(StdioServerParameters(command=sys.executable, args=[__file__, "--serve"], env={})) as client:46 print("server:", client.server_info.name, client.server_info.version)47 print("protocol revision:", client.protocol_version)48 # auto mode keeps the server/discover answer on the session, so the versions come from there49 print("supported versions:", ", ".join(client.session.discover_result.supported_versions))50 # exclude_none drops the capabilities the server didn't declare, leaving only the ones it offers51 print("capabilities:", ", ".join(sorted(client.server_capabilities.model_dump(exclude_none=True))))52 print("tools:", ", ".join(t.name for t in (await client.list_tools()).tools))53 print("resources:", ", ".join(str(r.uri) for r in (await client.list_resources()).resources))54 print("prompts:", ", ".join(p.name for p in (await client.list_prompts()).prompts))555657if __name__ == "__main__":58 # With --serve this file is the server the client launches; run bare, it is the client.59 server.run() if "--serve" in sys.argv else asyncio.run(main())
python list-what-the-server-offers.pyserver: shop-support 0.2.0
protocol revision: 2026-07-28
supported versions: 2026-07-28
capabilities: prompts, resources, tools
tools: get_order_status
resources: shop://policies/refund
prompts: review_refund
客户端的代码从未写出这三类能力的名称。它是从服务器得知这些信息的,同时得知的还有服务器自己的名称 shop-support 0.2.0、它支持的修订版本 2026-07-28,以及它声明的能力 prompts, resources, tools,这些都打印在示例旁边。这是 MCP 为商店 API 增加的第一项价值:对商店一无所知的客户端,也能查明商店提供什么,每一项都带有描述,工具和提示还带有所接受的参数,宿主可以把这些内容呈现给模型。服务器还为其工具列表设置了缓存提示,缓存列表结果会对此作出解释。
工作准则: 在宿主中为每个服务器配备各自的客户端,并把对话以及任何跨服务器的操作保留在宿主的代码中,绝不放在服务器里。每个客户端启动时都应先读取服务器提供的内容,而不是想当然地假定,这样服务器更改其工具时就不会破坏宿主。编写服务器时,应假定它只能看到发给它的请求,因为规范只允许它看到这些。
这部分尚未翻译,因此以英文显示。
Put each capability in the right primitive
The shop-support server from the previous section offers one tool, one resource and one prompt. A server's three primitives are its tools, resources and prompts, and they differ less in what they return than in who decides when they're used. The specification's server overview puts it in a table: prompts are user-controlled, resources are application-controlled, and tools are model-controlled (server features). So the question to ask of each capability is not whether it reads or writes, but who should decide when it runs: the model, the host's own code, or the person at the desk.
The tools page mandates no particular interface for a tool. The resources and prompts pages do the same for their primitives. A host can show them however it likes, but one that respects the control model gives each to the party the table names. The next script uses each of shop-support's three once, the way a host would.
1"""Use each of shop-support's three primitives once, as a host would: the tool for the model, the resource for the2host's code, the prompt for the person at the desk. The prose quotes the order's status, the policy's first line and3the prompt's one required argument."""4import asyncio5import json6import sys78from mcp import Client, StdioServerParameters910from lib import loopback, shop_api111213async def main() -> None:14 with loopback.serve(shop_api.create_app()) as base_url:15 # the server from list-what-the-server-offers, run as its own process with --serve; its env points at the shop's API16 params = StdioServerParameters(command=sys.executable, args=["list-what-the-server-offers.py", "--serve"],17 env=shop_api.server_env(base_url))18 async with Client(params) as client:19 # A tool: the host lists it for the model, and calls it when the model asks.20 result = await client.call_tool("get_order_status", {"order_id": "O-2476"})21 assert result.is_error is False # the lookup must succeed for the prose's claim22 # a tool's result is a list of content blocks; the order arrives as JSON text in the first one23 print("tool says order status:", json.loads(result.content[0].text)["status"])2425 # A resource: the host reads it when its own code decides the model needs it.26 policy = (await client.read_resource("shop://policies/refund")).contents[0] # this server returns one item27 print("resource type:", policy.mime_type)28 print("resource first line:", policy.text.splitlines()[0])2930 # A prompt: the host shows it to the user, who picks it and fills in its arguments.31 listed = (await client.list_prompts()).prompts[0] # the first prompt, the only one shop-support offers32 print("prompt arguments:", "; ".join(f"{a.name}, {'required' if a.required else 'optional'}"33 for a in listed.arguments))34 prompt = await client.get_prompt("review_refund", {"order_id": "O-2476"})35 print("prompt messages:", len(prompt.messages))36 print("prompt role:", prompt.messages[0].role)37 print("prompt starts:", prompt.messages[0].content.text[:44] + "…") # 44 characters: enough to name the order383940asyncio.run(main())
python three-primitives-side-by-side.pytool says order status: shipped
resource type: text/markdown
resource first line: # Refund policy
prompt arguments: order_id, required
prompt messages: 1
prompt role: user
prompt starts: Review the refund request for order O-2476. …
工具是由模型选择的动作
工具是一个带有描述和输入模式的命名动作,由模型决定是否调用它,以及以什么参数调用(工具)。宿主程序向模型列出可用的工具,并执行模型请求的调用。对订单 O-2476 的查询成功完成,没有报错,订单状态返回的是 shipped。
查询之所以属于工具,是因为是否需要查询取决于工单内容。一位客户给出订单号,询问包裹到了哪里;另一位客户则询问某款煎锅是否有 28 cm 的规格。只有能读懂工单的角色才能做出选择,而在这个宿主程序中,这个角色就是模型。让模型选择工具一节在一段录制的记录上展示了模型做出这种选择的过程。
工作准则: 当模型应当根据对话内容来决定是否使用某项能力时,就把它做成工具。这包括取决于客户所写内容的查询,也包括每一个会改变数据的操作,例如退款;对于这类操作,宿主程序随后会在调用之前征求同意。
资源是由应用程序选择的数据
资源(resource)是服务器在某个 URI 下公开的数据,应用程序决定何时读取它,以及如何处理它(资源)。宿主可以把资源附加到模型的上下文中,展示给用户,或为其建立索引。shop-support 在 shop://policies/refund 下提供商店的退款政策,这是为本书编写的几份简短政策文档之一。读取该资源返回的是 text/markdown 文本,其第一行是 # Refund policy。
退款政策之所以是资源,是因为商店事先就知道它何时重要:每一张涉及款项的工单都需要它。宿主的代码可以在处理这类工单时把它附加到模型的上下文中,无需询问模型。若把它做成工具,就要依赖模型记得去获取,而且每次都要多花一个回合。资源与只读工具并不相同:两者都返回数据,但资源的读取方是宿主的代码,其结果可以按照缓存列表结果中的规则进行缓存。将政策公开为资源以同样的方式提供商店的其余政策。
工作准则: 当宿主自己的代码能够判断何时需要某项数据时,就把它做成资源,例如适用于某一类已知工单的政策,或用户已经打开的记录。只有模型通过阅读对话才能判断是否需要时,才把它保留为工具。
提示词是由用户选择的模板
提示词(prompt)是一组带参数的消息模板,由服务器定义,由用户选取(提示词)。规范对这个词的界定很明确:“用户控制”指的是“由谁决定何时使用该提示词,而不是由谁撰写其内容”。内容由服务器编写,宿主通常以菜单或命令的形式提供提示词。review_refund 接受一个参数,即 order_id, required。针对订单 O-2476 填入参数后,它返回了 1 条来自 user 角色的消息,开头为“Review the refund request for order O-2476. …”。
review_refund 之所以是提示词,是因为由客服团队的某个人决定启动退款审核,通常是在阅读工单之后,而商店希望每次审核都遵循相同的步骤。提示词的文本写明了审核所需的工具和资源,因此模型从政策和订单出发,而不是靠猜测。提示词并不是用户自己编写的系统提示词:它由商店在服务器上编写一次,每个接入的宿主得到的都是同一段文本。将工作流打包为提示词一节把 review_refund 扩展为完整的审核流程,并加入退款金额作为第二个参数。
工作准则: 当某个工作流应由人来启动、且每次运行都应遵循相同步骤时,就把它做成提示词,并把提示词的文本保存在服务器上,这样一处修改便能同时到达所有宿主。如果没有人来选择它何时运行,它就不是提示词:应把这些步骤做成工具,或写入宿主自己的指令中。
这部分尚未翻译,因此以英文显示。
Carry the version and capabilities on every request
The client in Put each capability in the right primitive made three calls, and the server answered each one without remembering the others, by design. At the pinned revision there's no handshake: every request carries, in its _meta field, the protocol version and the client's capabilities, and those fields "MUST be included on every request" (base protocol). Each request should also carry the client's name and version, and each result the server's.
Three rules on the same page shape how the shop's server uses these fields:
- A request without a required field is rejected with JSON-RPC error
-32602(invalid params), and over HTTP with status 400. - A server must not rely on a capability the client didn't declare on that request. If it needs one, it answers with error
-32021, whose data lists the missing capabilities. clientInfoandserverInfoare self-reported. Implementations "SHOULD NOT rely on them for security decisions", so the shop's server never treats the client's name as an identity.
_meta also carries keys of your own, under a reverse-DNS prefix that ends in /. A prefix whose second label is modelcontextprotocol or mcp is reserved for the protocol, and so are traceparent, tracestate and baggage, which belong to OpenTelemetry (base protocol). The shop's domain is fernhill.example, so its keys start with example.fernhill/.
To see the envelope, the client calls get_order_status through lib.wire, which logs every line between the client and the server. It passes one key of the shop's own, a request ID that support staff can quote. It then sends a tools/list request without the client's capabilities, through a second small module, lib.raw_stdio, which starts a stdio server and writes JSON-RPC lines by hand. The code needs that because mcp.Client never sends a malformed request.
1"""Show the _meta that every request and result carries, add one key of the shop's own, and send a request without2the client's capabilities. The prose's claims about the envelope come from the printed keys and the bare request's error code."""3import asyncio4import json5import sys6from pathlib import Path78from mcp import Client, StdioServerParameters9from mcp.types import Implementation1011from lib import byte_meter, loopback, raw_stdio, shop_api, wire1213COMMAND = [sys.executable, "list-what-the-server-offers.py", "--serve"]141516async def main() -> None:17 Path("meta.jsonl").unlink(missing_ok=True) # the relay appends to its log18 with loopback.serve(shop_api.create_app()) as base_url:19 server = StdioServerParameters(command=COMMAND[0], args=COMMAND[1:], env=shop_api.server_env(base_url))20 # the relay logs every line the client and server exchange, so the byte counts are of lines as sent21 async with Client(wire.relay(server, log="meta.jsonl"),22 # the name and version the SDK sends as clientInfo in _meta; the server must not rely on them23 client_info=Implementation(name="shop-host", version="0.1.0")) as client:24 # a key under the shop's own prefix, which the protocol leaves to the shop to define25 await client.call_tool("get_order_status", {"order_id": "O-2476"},26 meta={"example.fernhill/requestId": "req-0001"})27 trace = [message for _, message in wire.read_trace("meta.jsonl")]28 call = next(m for m in trace if m.get("method") == "tools/call") # the first tools/call request in the log29 result = next(m for m in trace if m.get("id") == call["id"] and "result" in m) # its response, with the same id30 for key, value in call["params"]["_meta"].items():31 print(f"request {key}:", json.dumps(value))32 for key, value in result["result"]["_meta"].items():33 print(f"result {key}:", json.dumps(value))34 lines = [json.loads(entry)["line"] for entry in Path("meta.jsonl").read_text(encoding="utf-8").splitlines()] # as sent35 print("request _meta bytes:", byte_meter.meta_bytes(lines, call["params"]["_meta"]))36 print("result _meta bytes:", byte_meter.meta_bytes(lines, result["result"]["_meta"]))3738 with raw_stdio.launch(COMMAND, env={}) as raw: # the same request, without clientCapabilities39 # capabilities=None leaves clientCapabilities out of _meta: the request the server must reject40 reply = raw.request("tools/list", meta=raw_stdio.envelope("2026-07-28", capabilities=None))41 print("without capabilities, error code:", reply["error"]["code"])42 print("without capabilities, message:", reply["error"]["message"])434445asyncio.run(main())
python request-meta-on-the-wire.pyrequest example.fernhill/requestId: "req-0001"
request io.modelcontextprotocol/protocolVersion: "2026-07-28"
request io.modelcontextprotocol/clientInfo: {"name": "shop-host", "version": "0.1.0"}
request io.modelcontextprotocol/clientCapabilities: {}
result io.modelcontextprotocol/serverInfo: {"name": "shop-support", "version": "0.2.0"}
request _meta bytes: 228
result _meta bytes: 88
without capabilities, error code: -32602
without capabilities, message: params._meta is missing the required envelope key(s): io.modelcontextprotocol/clientCapabilities
The shop's key travels beside the protocol's own. The tools/call request's _meta held four keys. The shop's example.fernhill/requestId, set to "req-0001", came first, and the SDK added the protocol's three after it: the version, "2026-07-28", then the client's name, version and capabilities, which the output prints, the capabilities empty because this client declares none. The result's _meta carried the server's name and version, also printed.
The request without capabilities failed with code -32602, and the SDK's message names the missing key: "params._meta is missing the required envelope key(s): io.modelcontextprotocol/clientCapabilities". A hand-written client, or a gateway that rewrites bodies and drops _meta, fails this way on its first request.
What this costs the shop is bytes on every message. Measured on the lines as sent, the request's _meta, with the shop's key, took 228 bytes, and the result's 88. They are part of the per-call overhead that Keep an HTTP API where MCP adds nothing measures. What it buys is a server that needs no memory of earlier requests: any copy of shop-support can answer any request, which is what lets Run replicas without sticky sessions put two replicas behind one address.
Working rule: Read the version and the client's capabilities from each request, never from an earlier one, and answer -32021 when a call needs a capability the request didn't declare. Put the shop's own request metadata under its own reverse-DNS prefix, never under io.modelcontextprotocol/ or mcp. Log clientInfo and serverInfo for debugging, and decide nothing on them.
这部分尚未翻译,因此以英文显示。
Handle a version the server doesn't support
Every request in Carry the version and capabilities on every request named its protocol version, so a server can meet, on any request, a version it doesn't implement. No negotiation step settles it in advance. A server that doesn't implement the requested version "MUST respond with an UnsupportedProtocolVersionError listing the versions it does support", error code -32022, with the supported versions and the requested one in its data. The client SHOULD pick a version from that list that both sides support, and retry, or else show the user an error (versioning). Over Streamable HTTP the version also travels in the MCP-Protocol-Version header, which must match the body, and an unsupported version gets status 400 (Streamable HTTP).
The shop meets this when a host built for a later revision connects to shop-support. Showing the error means sending a version the server doesn't know, and the obvious way fails first: mcp.Client accepts as its mode only "auto", "legacy" or one of the SDK's per-request revisions, such as 2026-07-28, and raises before it sends anything (mcp/client/client.py). So the script tries that first, then uses lib.raw_stdio from the previous section to write the request by hand. It asks for 2099-01-01, a made-up revision that stands for any the server lacks, then retries with a version from the server's list.
1"""Ask shop-support for a revision it doesn't implement, read its -32022 error, and retry with the newest revision both2sides list. The prose reads the error code, the versions in its data and the retry's tool list from the printed lines."""3import sys45from mcp import Client, StdioServerParameters6from mcp_types.version import MODERN_PROTOCOL_VERSIONS78from lib import raw_stdio910COMMAND = [sys.executable, "list-what-the-server-offers.py", "--serve"]11UNKNOWN = "2099-01-01" # stands for any revision this server doesn't implement1213try:14 # the SDK's client checks the mode when it is built, so this raises before anything is sent15 Client(StdioServerParameters(command=COMMAND[0], args=COMMAND[1:]), mode=UNKNOWN)16except ValueError as refused:17 print("client refuses:", type(refused).__name__)1819with raw_stdio.launch(COMMAND, env={}) as server:20 # capabilities={} declares no client capabilities: the request is well formed, and only its version is unknown21 error = server.request("tools/list", meta=raw_stdio.envelope(UNKNOWN, capabilities={}))["error"]22 print("error code:", error["code"])23 print("error message:", error["message"])24 print("server supports:", ", ".join(error["data"]["supported"])) # the server lists its versions in the error's data25 print("client asked for:", error["data"]["requested"])2627 # the versions both sides know, in the order the SDK lists them28 mutual = [version for version in MODERN_PROTOCOL_VERSIONS if version in error["data"]["supported"]]29 if not mutual:30 sys.exit("no version in common: show the user an error instead of retrying")31 print("retry with:", mutual[-1]) # the last of that list is the newest version both sides know32 # the same process: at this revision each request names its own version, so the retry needs no new connection33 retry = server.request("tools/list", meta=raw_stdio.envelope(mutual[-1], capabilities={}))34 print("retry tools:", ", ".join(tool["name"] for tool in retry["result"]["tools"]))
python unsupported-version-error.pyclient refuses: ValueError
error code: -32022
error message: Unsupported protocol version
server supports: 2026-07-28
client asked for: 2099-01-01
retry with: 2026-07-28
retry tools: get_order_status
The SDK's client never reached the server: it refused the unknown mode before sending anything, with the error the output beside the example shows. The server's answer is what makes the retry possible. Given the raw request, it refused with the code and message the output prints, and its data listed the versions it supports, 2026-07-28, beside the one the client asked for. From that list the script picked 2026-07-28, the newest version both sides know, and the retry listed get_order_status. The retry went to the same process, because a connection carries no agreed version at the pinned revision, so the next request may name another one.
Two details of the SDK at 2.3.0 matter when you read this error from someone else's server. First, an SDK stdio server decides from the client's first request which era of the protocol to speak. A request whose _meta has a protocol version opens a connection at the pinned revision, even when the version is unknown, which is why this request got -32022 instead of a demand for the 2025 initialize handshake (mcp/server/runner.py). Second, the server's supported list holds only the versions that use per-request _meta, although the same server still accepts 2025 clients through initialize (mcp/shared/inbound.py). The specification's own example of the error lists a 2025 revision as well; the SDK's list doesn't. The SDK's client, in its default auto mode, reads a -32022 whose list shares nothing with its own as a real incompatibility, and any other error on its first request as a 2025 server that needs the old handshake (mcp/client/_probe.py). Serve old and new clients through the window covers that second path.
Working rule: When a server answers -32022, pick the newest version in both your list and its supported list, retry once, and show the user an error naming both lists if they share none. Don't retry in a loop, and don't guess a version the server didn't list. On your own server, keep the supported list exact, because clients choose from it.
缓存列表结果
分离宿主、客户端与服务器中的 server/discover 应答和工具列表,只在商店部署时才会变化,但无状态客户端可能在每一轮模型调用之前都去请求一次。在固定的修订版本中,server/discover、tools/list、prompts/list、resources/list、resources/templates/list 和 resources/read 的每个结果都必须携带两个缓存提示(缓存):
ttlMs,表示结果保持新鲜的毫秒数,类似 HTTP 的max-age。零表示立即过期。cacheScope,取值为"public"或"private"。前者表示缓存可以在不同调用方之间共享;后者表示缓存不得跨授权上下文共享。
同一页还限定了这些提示的含义。TTL 是新鲜度提示,而不是轮询间隔:客户端在需要数据时检查新鲜度,任何轮询都必须使用抖动和退避。list_changed 通知会使仍然新鲜的缓存结果失效。而且 cacheScope 不是访问控制:服务器“不得仅依赖 cacheScope 来阻止未授权访问”。
只有列表稳定,缓存工具列表才行得通。规范指出,服务器的 tools/list 不得因连接不同而不同,但可以随请求中的授权而变化;服务器还应以确定的顺序返回工具,这有助于提高提示缓存的命中率(工具)。SDK 的 MCPServer 按注册顺序列出工具,符合这一规则(mcp/server/mcpserver/tools/tool_manager.py)。
在 SDK 中,服务器的提示默认为 ttl_ms=0 和 "private",因此除非服务器主动选择启用,否则不会复用任何结果。shop-support 通过 cache_hints={"tools/list": CacheHint(ttl_ms=300_000, scope="public")} 为其工具列表启用缓存,即五分钟且可共享(mcp/server/caching.py)。在另一端,mcp.Client 默认在内存中按服务器的提示进行缓存,每次列表调用都接受一个 cache_mode,取值为 "use"、"refresh" 或 "bypass"。自行传入 meta 的调用总会到达服务器,而且客户端会把任何 TTL 限制在 24 小时以内(mcp/client/caching.py)。要统计缓存节省了多少请求,可以先对第 1 章的服务器(它没有设置提示)列出两次工具,再对 shop-support 列出两次,并用 lib.wire 在线路上统计到达每个服务器的 tools/list 请求数。
1"""Call list_tools() twice on each of two servers, one that sets no cache hint and one with a five-minute public hint,2and count the tools/list requests that reach each; the prose reads the three counts."""3import asyncio4import sys5from pathlib import Path67from mcp import Client, StdioServerParameters89from lib import wire101112async def list_twice(script: str, second_call: str = "use") -> tuple[str, str, int]:13 log = Path(script).with_suffix(".jsonl") # the relay's log, beside the server file14 log.unlink(missing_ok=True) # the relay appends to its log15 server = StdioServerParameters(command=sys.executable, args=[script, "--serve"], env={})16 async with Client(wire.relay(server, log=str(log))) as client:17 first = await client.list_tools() # cache_mode="use" is the default18 await client.list_tools(cache_mode=second_call)19 name = client.server_info.name20 # responses carry no method, so this counts only the requests that reached the server21 sent = sum(1 for _, message in wire.read_trace(str(log)) if message.get("method") == "tools/list")22 return name, f"ttlMs {first.ttl_ms}, cacheScope {first.cache_scope}", sent232425async def main() -> None:26 name, hint, sent = await list_twice("order-status-server.py") # chapter 1's server, which sets no hint27 print(f"{name} hint:", hint)28 print(f"{name} tools/list sent for two calls:", sent)29 name, hint, sent = await list_twice("list-what-the-server-offers.py") # this chapter's server, with its tool-list hint30 print(f"{name} hint:", hint)31 print(f"{name} tools/list sent for two calls:", sent)32 name, hint, sent = await list_twice("list-what-the-server-offers.py", second_call="bypass") # bypass skips the cache33 print(f"{name} tools/list sent when the second call bypasses:", sent)343536asyncio.run(main())
python cache-the-tool-list.pyshop-orders hint: ttlMs 0, cacheScope private
shop-orders tools/list sent for two calls: 2
shop-support hint: ttlMs 300000, cacheScope public
shop-support tools/list sent for two calls: 1
shop-support tools/list sent when the second call bypasses: 2
提示决定了到达服务器的请求数量。第 1 章的 shop-orders 返回了 ttlMs 0, cacheScope private,因此两次调用都发往了服务器,共 2 个请求。shop-support 的列表返回时带有 ttlMs 300000, cacheScope public,所以客户端的缓存应答了第二次调用,只有 1 个请求到达服务器。在第二次调用中使用 cache_mode="bypass" 时,两次调用都再次到达服务器,示例旁边的输出统计了这些请求。如果宿主在每一轮模型调用中都渲染工具列表,那么每一轮可以省下一个请求。并且由于列表保持顺序,模型的提示以相同的字节开头,而这正是服务提供方的提示缓存所需要的。
商店的工具列表可以是公开的,因为每个调用方看到的工具都相同。商店中每位顾客的数据则不行。当用资源模板定位记录为每个订单提供一个资源时,这些读取保持为 "private",因此共享缓存绝不会把一位顾客的订单交给另一位顾客的会话。如果工具列表日后取决于调用方的令牌,例如应用按令牌允许的范围限定工具之后可能出现的情形,它也会变为私有。
工作准则: 对于所有调用方都相同的列表,例如商店的工具列表,设置 TTL 并使用 "public" 范围,TTL 的长度不要超过部署之后你愿意接受列表过期的时间:以分钟计,而不是以小时计。对于取决于请求者身份的任何内容,保持 SDK 的默认值 "private",并且绝不让 cacheScope 代替授权检查。在客户端,保留默认缓存,当变更通知到达 client.listen(tools_list_changed=True) 流时,它会丢弃相应条目(mcp/client/client.py);在资源变化时通知客户端打开的正是这种流。没有这种流,通知就不会到达客户端,所以要打开一个;当你有其他理由怀疑某个条目时,使用 cache_mode="refresh",而不是按 TTL 轮询。
在 MCP 无益之处保留 HTTP API
前面各节展示了 MCP 为商店 API 增添的东西。分离宿主、客户端与服务器增加了运行时发现,把每项能力放入合适的原语为每项能力给出了控制模型。在每个请求中携带版本与能力使每个请求都带有版本并能自我描述。在产生副作用之前征求同意中宿主的同意步骤是另一项。当模型或用户的宿主在运行时从多项能力中做选择时,这些都有帮助。但对于开发者已经知道要调用哪个端点的程序,它们都没有帮助。
规范并没有说明何时不该使用 MCP,因此这是本书的判断,而不是协议规则。我们建议在三类工作中使用普通的 HTTP API:
- **没有模型参与选择的服务间调用,**例如仓库每晚读取库存水平。它的代码调用固定的端点,因此没有人会读取发现的应答或描述。
- **固定的工作流,**即每次都以相同顺序执行相同步骤。把它们写成基于该 API 的代码;如果需要由模型来启动其中一个,就把整个工作流作为一个工具暴露出来。
- **大批量的批处理工作,**其中每个字节和每次往返都会被成倍放大。
当模型或用户的宿主在运行时从多项能力中做选择时,例如支持团队的宿主,我们建议使用 MCP。两者并不竞争。认识商店及其 API把商店的 API 保留为记录系统,而 shop-support 只是它之上的一层薄适配器,所以仓库继续使用它的 API 调用,而支持团队的宿主使用 MCP。
本次运行为这层适配器定价,因此这一权衡建立在数字之上。脚本两次获取订单 O-2476:一次来自商店的 API,使用 GET /orders/O-2476;另一次通过 shop-support 的 get_order_status 工具,经由 Streamable HTTP 完成,这种传输方式见把服务器从 stdio 迁移到 HTTP。lib.byte_meter 是用于这项测量的一个小模块,它在每个服务器前放置一个 TCP 中继,统计双向的每个字节(包括头部),并统计每个服务器处理的 HTTP 请求数。所有内容都在 127.0.0.1 上的同一个进程中运行,使用不带 TLS 的 HTTP/1.1。在 MCP 一侧,统计涵盖宿主打开客户端时的设置(包括工具列表),但不包括工具调用。这项设置测量了两次:一次在默认的自动模式下,该模式会先用 server/discover 探测服务器;另一次固定了版本。工具调用本身是在固定版本的情况下进行的。这里没有测量时间,因为一台机器上回环接口的时间很难说明网络的情况。
1"""Fetch order O-2476 from the shop's API, then through shop-support's tool over Streamable HTTP, and count the cost.2The prose's comparison comes from the byte totals and the request counts the script prints."""3import asyncio4import os5import runpy67import httpx28from mcp import Client910from lib import byte_meter, loopback, shop_api111213async def session(url, traffic, requests, mode: str, calls: int) -> tuple[list[str], int]:14 """Open a client, list the tools as a host does, make `calls` tool calls, close it: the requests and bytes."""15 traffic.reset()16 requests.reset()17 # auto mode first sends server/discover to probe the server; a pinned revision skips that probe18 async with Client(f"{url}/mcp", mode=mode) as client:19 await client.list_tools()20 for _ in range(calls):21 await client.call_tool("get_order_status", {"order_id": "O-2476"})22 return list(requests.names), traffic.sent + traffic.received # bytes both ways, from the relay232425async def main() -> None:26 print("setup: one process, 127.0.0.1, HTTP/1.1, no TLS, bytes counted at a TCP relay, headers included")27 api_app, api_requests = byte_meter.count_requests(shop_api.create_app())28 with loopback.serve(api_app) as api_url, byte_meter.relay(api_url) as (url, traffic):29 # the one API call, sent through the relay so that its bytes are counted the way the tool's are30 httpx2.get(f"{url}/orders/O-2476", headers={"X-API-Key": shop_api.DEMO_API_KEY}).raise_for_status()31 api_bytes = traffic.sent + traffic.received32 print("api call round trips:", api_requests.count)33 print("api call bytes:", api_bytes)3435 os.environ.update(shop_api.server_env(api_url)) # the tool calls the API directly, not through a relay36 shop_support = runpy.run_path("list-what-the-server-offers.py")["server"] # defined there, not run37 mcp_app, mcp_requests = byte_meter.count_requests(shop_support.streamable_http_app())38 with loopback.serve(mcp_app) as mcp_url, byte_meter.relay(mcp_url) as (url, traffic):39 for mode, label in (("auto", "auto"), ("2026-07-28", "pinned")):40 names, setup_bytes = await session(url, traffic, mcp_requests, mode, calls=0) # setup only, no tool call41 print(f"mcp {label} setup request count:", len(names))42 print(f"mcp {label} setup requests:", ", ".join(names))43 print(f"mcp {label} setup bytes:", setup_bytes)44 names, with_call = await session(url, traffic, mcp_requests, "2026-07-28", calls=1)45 call_bytes = with_call - setup_bytes # a pinned session with one call, less the pinned setup46 print("mcp tool call round trips:", names.count("tools/call"))47 print("mcp tool call bytes:", call_bytes)48 print("tool call bytes per api call byte:", round(call_bytes / api_bytes, 1)) # one decimal place, as the prose quotes495051asyncio.run(main())
python api-call-versus-tool-call.pysetup: one process, 127.0.0.1, HTTP/1.1, no TLS, bytes counted at a TCP relay, headers included
api call round trips: 1
api call bytes: 591
mcp auto setup request count: 2
mcp auto setup requests: server/discover, tools/list
mcp auto setup bytes: 2157
mcp pinned setup request count: 1
mcp pinned setup requests: tools/list
mcp pinned setup bytes: 1147
mcp tool call round trips: 1
mcp tool call bytes: 1357
tool call bytes per api call byte: 2.3
在线路上,工具调用多花的是字节,而不是往返次数。API 调用需要 1 次往返,工具调用需要 1 次,但它发送的字节数是前者的 2.3 倍,这一数字由示例旁的输出统计得出。差异来自 JSON-RPC 信封、请求和结果上的 _meta、Streamable HTTP 添加的路由头部,以及订单本身:SDK 把它作为缩进的 JSON 放在文本块中返回,其中的引号经过转义,正如读懂线路上的消息所示。
此外,设置还要花费更多。在自动模式下,客户端在第一次调用之前发送了 2 个请求;固定版本后,它跳过了 server/discover 探测,发送了 1 个。示例旁的输出列出了这些请求及其字节数。在服务器背后,每次工具调用还会向商店的 API 发出自己的请求,计数中不包含这一请求,因为调用方看不到它。
其中一些字节在没有模型时也有用处。头部 Mcp-Method(出现在每个请求上)和 Mcp-Name(出现在 tools/call、resources/read 和 prompts/get 上)让网关无需解析消息体,就能按方法和工具进行路由(Streamable HTTP)。对于每个工单只发起少量调用的支持团队宿主,每次调用 1357 字节与模型自身的词元相比很小。而对于仓库每晚读取 64 件商品的任务,每次调用都要为其代码从不读取的信封付出代价,并且这层适配器还给原本无需它也能运行的作业增加了一个进程。
工作准则: 对于代码已知应调用哪个端点的调用方,例如其他服务、固定工作流和批处理作业,保留普通的 HTTP API;对于由模型或用户在运行时做选择的宿主,则在同一个 API 前面放置一个 MCP 服务器。在把大批量流量路由到 MCP 之前,先在你自己的传输方式上测量开销,并在你能控制的客户端中固定协议版本,使它们跳过发现探测。对于可能遇到你无法控制的服务器的客户端,保留自动模式,因为这些服务器可能只支持 2025 年的协议。
生产环境中会出什么问题
本章新增的各个部分会以几种可辨认的方式出错,每一种都会留下可供查找的痕迹。
能力放进了错误的原语。 作为工具提供的策略,在模型想不到去获取它时会被跳过;作为资源提供的退款操作,则让宿主没有可以请求用户同意的环节。其表现是:行为因工单而异,而差异与工单本身无关,比如在没有依据策略的情况下给出涉及金额的答复,或者日志中出现没有同意步骤的副作用。请对每项能力问一个问题:由谁来决定它何时运行,正如把每项能力放进正确的原语所做的那样。
网关丢弃或改写了 _meta。 为普通 JSON API 构建的代理和 API 网关,有时会改写请求体。丢失了版本或能力信息的请求会以 -32602 失败,如在每个请求中携带版本和能力所示。在 Streamable HTTP 上,请求体与请求头不再一致时会以 -32020 失败,因为 MCP-Protocol-Version、Mcp-Method 和 Mcp-Name 这几个请求头必须与请求体一致(Streamable HTTP)。应原样转发 MCP 流量,按请求头进行路由,而不要编辑请求体。
把 clientInfo 当作身份。 客户端在 _meta 中的名称,是客户端自己选择发送的内容,规范明确指出不应依赖它来保障安全(基础协议)。如果服务器给名为 shop-host 的客户端更多权限,那么任何发送该名称的人都会获得这些权限。授权应来自令牌,这一点由从资源找到授权服务器开始讲述。
公共缓存条目跨越了客户。 标记为 "public" 的结果可以在不同授权上下文之间共享,即使它来自经过认证的端点(缓存)。如果服务器把按客户区分的数据标记为公共,共享缓存就会把一位客户的订单提供给另一位客户。对于任何取决于调用方的内容,请保留 SDK 的 "private" 默认值,并把代码评审中出现的每一个 "public" 提示都当作需要核实的论断。
过长的 TTL 掩盖了一次部署。 工具列表的有效期长达数小时,客户端就会继续提供服务器已移除的工具,对它的调用会失败。其表现是出现未知工具错误,而客户端重启后这些错误消失。请把工具列表的 TTL 控制在几分钟以内,并让客户端在收到变更通知时刷新。变更通知只会通过客户端自己打开的 subscriptions/listen 流送达,如在资源变更时通知客户端所设定。
客户端调用了它从未列出的工具。 在 2.3.0 中,mcp.Client 会依据工具的输出模式检查工具的结果;如果尚未列出工具,它会先发送 tools/list(mcp/client/session.py)。不列出工具就调用工具的客户端,会在首次调用时多付出一次请求。请在客户端打开时就列出工具,宿主本来也是这样做的。
旧资料中的旧错误码。 所固定的修订版把 -32020 到 -32099 保留给规范,把 -32000 到 -32019 视为新代码不应使用的遗留范围,并要求应用错误码取自 JSON-RPC 保留范围之外(基础协议)。该修订版在发布前重新编排了错误码(变更日志),因此依据草案编写的资料,对同样的错误可能显示不同的数字。请对照规范核对错误码,而不要对照某篇博客文章。
规范在不断演进。 MCP 由 Agentic AI Foundation 管理,这是 Linux Foundation 旗下的一项定向基金,它在 2025 年 12 月接纳 MCP 作为创始项目(公告)。修订版以日期标识,被弃用的功能至少保留十二个月(功能生命周期)。只有存在现实的安全风险时,期限才会更短,而且至少九十天,或按已弃用功能登记表的规定执行。规划服务器的下一次发布时,请阅读该登记表,并在日志中留意按更晚修订版构建的客户端发来的 -32022。
工作准则: 在发布任何服务器之前,检查四件事:每项能力的原语与决定其何时运行的一方相符;客户端与服务器之间没有任何环节编辑 MCP 请求体;没有任何决定是依据 clientInfo 做出的;每一个 "public" 缓存提示所涵盖的数据,对所有调用方都相同。请记录每个失败请求的协议版本和错误码,因为版本错误和信封错误是客户端或网关发生变化的最早迹象。
本章做出的决定
- 每个服务器对应一个客户端,客户端位于宿主中。 对话以及任何跨服务器的内容都留在宿主的代码里;服务器只能看到发给它自己的请求。
- 商店的服务器是
shop-support, 包含第 1 章的get_order_status工具、位于shop://policies/refund的退款政策资源,以及作为提示的review_refund。 - 每项能力都交给其控制者应当决定何时运行的原语: 工具由模型决定,资源由宿主的代码决定,提示由柜台前的人决定。
- 版本和能力从每个请求中读取, 绝不沿用之前请求中的信息;缺少某项能力时返回
-32021。 - 商店自己的
_meta键使用example.fernhill/前缀。 不依据clientInfo或serverInfo做任何决定。 - 遇到
-32022时,客户端重试一次, 使用双方都列出的最新版本;否则显示错误。 - 工具列表是公开的,TTL 为五分钟。 每位客户的数据保持私有;如果工具列表开始依赖令牌,它就变为私有。
- 手写的 JSON-RPC 通过
lib.raw_stdio发送,仅用于展示 SDK 的客户端不会引发的错误。 - 我们建议在服务之间的调用、固定的工作流和批量任务中使用普通的 HTTP API, 而在由模型或用户的宿主在运行时做选择的场合使用 MCP,依据是
api-call-versus-tool-call中的字节数和往返次数。
本章,在本版次中
版次 2026.11.14示例于 2026年11月19日 通过本章 6个示例 个示例中有 6 个通过
译自英文版图书,版次 2026.11.14。