MCP 為 API 增添了什麼

閱讀約需 71 分鐘 分鐘,11 節 中共有 6 個範例。

版次 2026.11.14 範例於 2026年11 月 19 通過測試 70 個範例中有 70 個通過 變更內容

由 AI 翻譯。經人工以英文驗證。 我們如何製作書籍

譯自英文書,版次 2026.11.14。 閱讀原文

讀完本章後,你能說明主機(host)、用戶端(client)與伺服器(server)各自負責什麼,能把商店的每項功能放進正確的 Model Context Protocol 原語(primitive),能讀懂每個請求所攜帶的版本與能力資訊,也能判斷商店何時應該保留單純的 HTTP API。本章的論述與範例以規格的 2026-07-28 修訂版,以及 Python SDK mcp 的 2.3.0 版為依據。

本章所需要的,是 商店 的一套 HTTP API,客服團隊的主機已經在使用其中的訂單查詢功能。商店指的是 Fernhill Supply,一間虛構的廚房與園藝用品線上商店。MCP 端到端實作 把這項查詢放到 Model Context Protocol(MCP)伺服器之後,讓客服團隊主機中的模型能夠呼叫它。那個伺服器只有一個工具。客服團隊想要更多:一是退款政策,只要工單提到金錢,主機就應該隨時取得;二是審核退款申請的標準做法。同時,倉儲團隊每晚都從同一套 API 讀取庫存量,他們詢問是否也該改用 MCP。

這兩個問題都取決於同一點:對一套已經可用的 API,MCP 增添了什麼。HTTP 用戶端是依據開發者讀過的端點寫成的。MCP 用戶端則在執行階段得知伺服器提供什麼,而且是以模型讀得懂的形式;協定也規定了每項功能由誰決定何時使用。本章逐一說明這些新增之處,量測它們在傳輸線路上的成本,最後指出商店不該為它們付出代價的地方。

區分主機、用戶端與伺服器

最近一次變動於第 2026.11.11 版

Wrap one endpoint as a tool 中的伺服器,是在一個由該章程式碼驅動的用戶端背後執行的。在商店為它加入更多功能之前,必須先精確釐清各部分的職責,因為 MCP 的保證是附著在角色上,而不是附著在行程上。

規格書定義了三種角色(architecture)。主機(host)是使用者操作的應用程式。它負責建立用戶端、維持與模型之間的對話,並執行安全政策與使用者同意機制。用戶端(client)是主機與單一伺服器之間的連線:「每個用戶端都由主機建立,且只與一個伺服器通訊」。伺服器(server)對外提供各種能力,例如工具,除此之外對主機一無所知。同一頁還依這種劃分訂出一項設計原則:伺服器不應看到整段對話,也不應窺探其他伺服器。每個伺服器能看到什麼,由主機決定,凡是跨越伺服器的事務,都在主機中發生。

客服團隊的主機扮演主機角色,並執行本書的主機迴圈。它使用的每個伺服器各有一個自己的用戶端:本章只有一個,即 shop-support;在 Catch poisoned tool descriptions 中則有來自合作夥伴的第二個伺服器,它絕不能得知商店的伺服器回傳了什麼。shop-support 是本章的伺服器。它保留第 1 章的 get_order_status 工具,並加入一項資源,即退款政策,以及一個提示,即 review_refund,使每一種能力各出現一次。如同本書所有的伺服器範例,該檔案定義伺服器;不帶引數執行時,則會啟動一個用戶端,並以 --serve 啟動伺服器。

用戶端做的第一件事,是詢問伺服器提供什麼。能力(capability)是用戶端或伺服器宣告自己支援的項目,例如提供工具的伺服器,或能回應輸入請求的用戶端。在固定的修訂版本中,這只需要一個請求 server/discover,其回應包含伺服器支援的版本、能力與名稱,因此用戶端只憑這一個回應,就能呈現伺服器支援的一切(discovery)。接著用戶端以 tools/list、resources/list 與 prompts/list 列出每一種能力。在預設的自動模式下,mcp.Client 會在開啟時送出 server/discover,並將回應保存為 client.session.discover_result(mcp/client/session.py)。

list-what-the-server-offers.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 通過
"""shop-support, the chapter 2 server, offers one tool, one resource and one prompt. Run bare, the file starts it as aclient, which prints what it discovers: the tools, resources and prompts lines are the ones the prose reads."""import asyncioimport osimport sysimport httpx2from mcp import Client, StdioServerParametersfrom mcp.server.caching import CacheHintfrom mcp.server.mcpserver import MCPServerfrom mcp.server.mcpserver.exceptions import ToolErrorfrom lib.policies import policy# ttl_ms is in milliseconds, so 300_000 is five minutes; "public" lets a shared cache reuse the tool list.server = MCPServer("shop-support", version="0.2.0",                   cache_hints={"tools/list": CacheHint(ttl_ms=300_000, scope="public")})@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."""    response = httpx2.get(f"{os.environ['SHOP_API_URL']}/orders/{order_id}",                          headers={"X-API-Key": os.environ["SHOP_API_KEY"]}, timeout=5.0)   # timeout in seconds    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()    return response.json()@server.resource("shop://policies/refund", name="refund-policy", mime_type="text/markdown")def refund_policy() -> str:    return policy("refund").path.read_text(encoding="utf-8")       # examples/data/shop/policies/refund.md@server.prompt()def review_refund(order_id: str) -> str:    """Review a customer's refund request for one order against the shop's refund policy."""    return (f"Review the refund request for order {order_id}. Look up the order with get_order_status, read the "            "refund policy at shop://policies/refund, and say whether the refund needs a person to confirm it.")async def main() -> None:    # No variables are passed: listing never calls the tool, so the server needs none of the shop's API settings.    async with Client(StdioServerParameters(command=sys.executable, args=[__file__, "--serve"], env={})) as client:        print("server:", client.server_info.name, client.server_info.version)        print("protocol revision:", client.protocol_version)        # auto mode keeps the server/discover answer on the session, so the versions come from there        print("supported versions:", ", ".join(client.session.discover_result.supported_versions))        # exclude_none drops the capabilities the server didn't declare, leaving only the ones it offers        print("capabilities:", ", ".join(sorted(client.server_capabilities.model_dump(exclude_none=True))))        print("tools:", ", ".join(t.name for t in (await client.list_tools()).tools))        print("resources:", ", ".join(str(r.uri) for r in (await client.list_resources()).resources))        print("prompts:", ", ".join(p.name for p in (await client.list_prompts()).prompts))if __name__ == "__main__":    # With --serve this file is the server the client launches; run bare, it is the client.    server.run() if "--serve" in sys.argv else asyncio.run(main())
輸出python list-what-the-server-offers.py
server: shop-support 0.2.0
protocol revision: 2026-07-28
supported versions: 2026-07-28
capabilities: prompts, resources, tools
tools: get_order_status
resources: shop://policies/refund
prompts: review_refund

用戶端的程式碼從未寫出這三者的名稱。它是從伺服器得知的,同時得知的還有伺服器本身的名稱 shop-support 0.2.0、它支援的修訂版本 2026-07-28,以及它宣告的能力 prompts, resources, tools,這些都印在範例旁邊。這是 MCP 為商店 API 增添的第一項好處:對商店一無所知的用戶端,也能查出商店提供什麼,包括每個項目的說明,以及工具與提示所接受的引數,而主機可以把這些呈現給模型。伺服器也在它的工具清單上設定了快取提示,Cache list results 會加以說明。

實用原則: 在主機中為每個伺服器各設一個用戶端,並把對話以及任何跨越伺服器的事務留在主機的程式碼中,絕不放在伺服器裡。每個用戶端啟動時,都先讀取伺服器提供的內容,而不是預先假設,這樣伺服器變更其工具時,才不會弄壞主機。撰寫伺服器時,應假設它只看得到送給它的請求,因為規格書只允許它看到這些。

此部分尚未翻譯,因此以英文呈現。

Put each capability in the right primitive

最近一次變動於第 2026.11.14 版

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.

three-primitives-side-by-side.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 通過
"""Use each of shop-support's three primitives once, as a host would: the tool for the model, the resource for thehost's code, the prompt for the person at the desk. The prose quotes the order's status, the policy's first line andthe prompt's one required argument."""import asyncioimport jsonimport sysfrom mcp import Client, StdioServerParametersfrom lib import loopback, shop_apiasync def main() -> None:    with loopback.serve(shop_api.create_app()) as base_url:        # the server from list-what-the-server-offers, run as its own process with --serve; its env points at the shop's API        params = StdioServerParameters(command=sys.executable, args=["list-what-the-server-offers.py", "--serve"],                                       env=shop_api.server_env(base_url))        async with Client(params) as client:            # A tool: the host lists it for the model, and calls it when the model asks.            result = await client.call_tool("get_order_status", {"order_id": "O-2476"})            assert result.is_error is False      # the lookup must succeed for the prose's claim            # a tool's result is a list of content blocks; the order arrives as JSON text in the first one            print("tool says order status:", json.loads(result.content[0].text)["status"])            # A resource: the host reads it when its own code decides the model needs it.            policy = (await client.read_resource("shop://policies/refund")).contents[0]   # this server returns one item            print("resource type:", policy.mime_type)            print("resource first line:", policy.text.splitlines()[0])            # A prompt: the host shows it to the user, who picks it and fills in its arguments.            listed = (await client.list_prompts()).prompts[0]     # the first prompt, the only one shop-support offers            print("prompt arguments:", "; ".join(f"{a.name}, {'required' if a.required else 'optional'}"                                                 for a in listed.arguments))            prompt = await client.get_prompt("review_refund", {"order_id": "O-2476"})            print("prompt messages:", len(prompt.messages))            print("prompt role:", prompt.messages[0].role)            print("prompt starts:", prompt.messages[0].content.text[:44] + "…")   # 44 characters: enough to name the orderasyncio.run(main())
輸出python three-primitives-side-by-side.py
tool 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. …

工具是由模型選擇的動作

最近一次變動於第 2026.11.11 版

工具(tool)是具有名稱、說明與輸入結構描述(input schema)的動作,模型會決定是否呼叫它,以及以什麼參數呼叫(工具)。主機(host)會把工具列給模型,並執行模型要求的呼叫。訂單 O-2476 的查詢順利完成,沒有發生錯誤,訂單狀態回傳為 shipped。

查詢屬於這一類,是因為是否需要查詢,要由客服單來決定。有的客戶附上訂單編號,詢問包裹到了哪裡;有的客戶則詢問平底鍋是否有 28 cm 的尺寸。只有讀過客服單的對象才能做出選擇,而在這個主機中,這個對象就是模型。讓模型選擇工具一節在一段錄製的紀錄上,示範了模型如何做出這樣的選擇。

**實用原則:**當模型應該根據對話內容,來決定是否使用某項功能時,就把這項功能做成工具。這包括取決於客戶所寫內容的查詢,以及所有會變更資料的動作,例如退款;對於這類動作,主機在呼叫之前會先徵求同意。

資源是由應用程式決定如何使用的資料

最近一次變動於第 2026.11.11 版

資源(resource)是伺服器以 URI 公開的資料,由應用程式決定何時讀取,以及如何處理(資源)。主機可能把資源附加到模型的情境中、顯示給使用者,或為它建立索引。shop-support 在 shop://policies/refund 之下提供商店的退款政策,這是為本書撰寫的幾份簡短政策文件之一。讀取結果是 text/markdown 文字,其第一行是 # Refund policy。

退款政策適合做成資源,因為商店事先就知道它何時重要:每一張與金錢有關的客服單都會用到。對於這類客服單,主機的程式碼可以不必詢問模型,直接把它附加到模型的情境中。如果把它做成工具,就得依賴模型記得去取得,而且每次都要多花一個回合。資源與唯讀工具並不相同:兩者都會回傳資料,但資源的讀取者是主機的程式碼,而且其結果可以依照快取清單結果中的規則進行快取。將政策公開為資源會以相同的方式提供商店的其餘政策。

實用原則: 當主機本身的程式碼能判斷何時需要某份資料時,就把它做成資源,例如適用於特定類型客服單的政策,或使用者已開啟的記錄。若只有模型閱讀對話內容後才能判斷是否需要,就讓它維持為工具。

提示(prompt)是由使用者選擇的範本

最近一次變動於第 2026.11.11 版

提示(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

最近一次變動於第 2026.11.11 版

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.
  • clientInfo and serverInfo are 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.

request-meta-on-the-wire.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 通過
"""Show the _meta that every request and result carries, add one key of the shop's own, and send a request withoutthe client's capabilities. The prose's claims about the envelope come from the printed keys and the bare request's error code."""import asyncioimport jsonimport sysfrom pathlib import Pathfrom mcp import Client, StdioServerParametersfrom mcp.types import Implementationfrom lib import byte_meter, loopback, raw_stdio, shop_api, wireCOMMAND = [sys.executable, "list-what-the-server-offers.py", "--serve"]async def main() -> None:    Path("meta.jsonl").unlink(missing_ok=True)       # the relay appends to its log    with loopback.serve(shop_api.create_app()) as base_url:        server = StdioServerParameters(command=COMMAND[0], args=COMMAND[1:], env=shop_api.server_env(base_url))        # the relay logs every line the client and server exchange, so the byte counts are of lines as sent        async with Client(wire.relay(server, log="meta.jsonl"),                          # the name and version the SDK sends as clientInfo in _meta; the server must not rely on them                          client_info=Implementation(name="shop-host", version="0.1.0")) as client:            # a key under the shop's own prefix, which the protocol leaves to the shop to define            await client.call_tool("get_order_status", {"order_id": "O-2476"},                                   meta={"example.fernhill/requestId": "req-0001"})    trace = [message for _, message in wire.read_trace("meta.jsonl")]    call = next(m for m in trace if m.get("method") == "tools/call")          # the first tools/call request in the log    result = next(m for m in trace if m.get("id") == call["id"] and "result" in m)   # its response, with the same id    for key, value in call["params"]["_meta"].items():        print(f"request {key}:", json.dumps(value))    for key, value in result["result"]["_meta"].items():        print(f"result {key}:", json.dumps(value))    lines = [json.loads(entry)["line"] for entry in Path("meta.jsonl").read_text(encoding="utf-8").splitlines()]   # as sent    print("request _meta bytes:", byte_meter.meta_bytes(lines, call["params"]["_meta"]))    print("result _meta bytes:", byte_meter.meta_bytes(lines, result["result"]["_meta"]))    with raw_stdio.launch(COMMAND, env={}) as raw:          # the same request, without clientCapabilities        # capabilities=None leaves clientCapabilities out of _meta: the request the server must reject        reply = raw.request("tools/list", meta=raw_stdio.envelope("2026-07-28", capabilities=None))        print("without capabilities, error code:", reply["error"]["code"])        print("without capabilities, message:", reply["error"]["message"])asyncio.run(main())
輸出python request-meta-on-the-wire.py
request 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

最近一次變動於第 2026.11.14 版

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.

unsupported-version-error.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 通過
"""Ask shop-support for a revision it doesn't implement, read its -32022 error, and retry with the newest revision bothsides list. The prose reads the error code, the versions in its data and the retry's tool list from the printed lines."""import sysfrom mcp import Client, StdioServerParametersfrom mcp_types.version import MODERN_PROTOCOL_VERSIONSfrom lib import raw_stdioCOMMAND = [sys.executable, "list-what-the-server-offers.py", "--serve"]UNKNOWN = "2099-01-01"                       # stands for any revision this server doesn't implementtry:    # the SDK's client checks the mode when it is built, so this raises before anything is sent    Client(StdioServerParameters(command=COMMAND[0], args=COMMAND[1:]), mode=UNKNOWN)except ValueError as refused:    print("client refuses:", type(refused).__name__)with raw_stdio.launch(COMMAND, env={}) as server:    # capabilities={} declares no client capabilities: the request is well formed, and only its version is unknown    error = server.request("tools/list", meta=raw_stdio.envelope(UNKNOWN, capabilities={}))["error"]    print("error code:", error["code"])    print("error message:", error["message"])    print("server supports:", ", ".join(error["data"]["supported"]))     # the server lists its versions in the error's data    print("client asked for:", error["data"]["requested"])    # the versions both sides know, in the order the SDK lists them    mutual = [version for version in MODERN_PROTOCOL_VERSIONS if version in error["data"]["supported"]]    if not mutual:        sys.exit("no version in common: show the user an error instead of retrying")    print("retry with:", mutual[-1])        # the last of that list is the newest version both sides know    # the same process: at this revision each request names its own version, so the retry needs no new connection    retry = server.request("tools/list", meta=raw_stdio.envelope(mutual[-1], capabilities={}))    print("retry tools:", ", ".join(tool["name"] for tool in retry["result"]["tools"]))
輸出python unsupported-version-error.py
client 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.

快取清單結果

最近一次變動於第 2026.11.11 版

區分主機、用戶端與伺服器中的 server/discover 回應與工具清單,只會在商店部署時改變,但無狀態的用戶端卻可能在每一輪模型對話之前都詢問一次。在固定的規格版本中,server/discover、tools/list、prompts/list、resources/list、resources/templates/list 與 resources/read 的每個結果都必須帶有兩項快取提示(快取):

  • ttlMs:結果維持新鮮的毫秒數,類似 HTTP 的 max-age。零表示立即過期。
  • cacheScope:可為 "public",快取可在不同呼叫者之間共用;或為 "private",快取不得跨授權情境共用。

同一頁也限定了這些提示的意義。TTL 是新鮮度提示,不是輪詢間隔:用戶端在需要資料時才檢查新鮮度,任何輪詢都必須使用抖動(jitter)與退避。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 請求。

cache-the-tool-list.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 通過
"""Call list_tools() twice on each of two servers, one that sets no cache hint and one with a five-minute public hint,and count the tools/list requests that reach each; the prose reads the three counts."""import asyncioimport sysfrom pathlib import Pathfrom mcp import Client, StdioServerParametersfrom lib import wireasync def list_twice(script: str, second_call: str = "use") -> tuple[str, str, int]:    log = Path(script).with_suffix(".jsonl")             # the relay's log, beside the server file    log.unlink(missing_ok=True)                          # the relay appends to its log    server = StdioServerParameters(command=sys.executable, args=[script, "--serve"], env={})    async with Client(wire.relay(server, log=str(log))) as client:        first = await client.list_tools()                # cache_mode="use" is the default        await client.list_tools(cache_mode=second_call)        name = client.server_info.name    # responses carry no method, so this counts only the requests that reached the server    sent = sum(1 for _, message in wire.read_trace(str(log)) if message.get("method") == "tools/list")    return name, f"ttlMs {first.ttl_ms}, cacheScope {first.cache_scope}", sentasync def main() -> None:    name, hint, sent = await list_twice("order-status-server.py")         # chapter 1's server, which sets no hint    print(f"{name} hint:", hint)    print(f"{name} tools/list sent for two calls:", sent)    name, hint, sent = await list_twice("list-what-the-server-offers.py")  # this chapter's server, with its tool-list hint    print(f"{name} hint:", hint)    print(f"{name} tools/list sent for two calls:", sent)    name, hint, sent = await list_twice("list-what-the-server-offers.py", second_call="bypass")   # bypass skips the cache    print(f"{name} tools/list sent when the second call bypasses:", sent)asyncio.run(main())
輸出python cache-the-tool-list.py
shop-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" 範圍,並選擇不長於部署後你能接受清單過期的時間:以分鐘計,而非以小時計。對取決於提問者身分的任何內容,維持 SDK 預設的 "private",且絕不讓 cacheScope 取代授權檢查。在用戶端,保留預設的快取,它會在 client.listen(tools_list_changed=True) 串流上收到變更通知時捨棄對應項目(mcp/client/client.py),這類串流就是在資源變更時通知用戶端所開啟的那種。沒有該串流,用戶端就收不到任何通知,所以請開啟一個;當你有其他理由懷疑某個項目時,使用 cache_mode="refresh",而不是依 TTL 輪詢。

在 MCP 沒有加分的地方,保留 HTTP API

最近一次變動於第 2026.11.11 版

前面各節都說明了 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 探測伺服器;另一次則固定版本。工具呼叫本身是在固定版本下進行的。我們沒有量測時間,因為單一機器迴路上的時間,很難說明網路上的狀況。

api-call-versus-tool-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 通過
"""Fetch order O-2476 from the shop's API, then through shop-support's tool over Streamable HTTP, and count the cost.The prose's comparison comes from the byte totals and the request counts the script prints."""import asyncioimport osimport runpyimport httpx2from mcp import Clientfrom lib import byte_meter, loopback, shop_apiasync def session(url, traffic, requests, mode: str, calls: int) -> tuple[list[str], int]:    """Open a client, list the tools as a host does, make `calls` tool calls, close it: the requests and bytes."""    traffic.reset()    requests.reset()    # auto mode first sends server/discover to probe the server; a pinned revision skips that probe    async with Client(f"{url}/mcp", mode=mode) as client:        await client.list_tools()        for _ in range(calls):            await client.call_tool("get_order_status", {"order_id": "O-2476"})    return list(requests.names), traffic.sent + traffic.received     # bytes both ways, from the relayasync def main() -> None:    print("setup: one process, 127.0.0.1, HTTP/1.1, no TLS, bytes counted at a TCP relay, headers included")    api_app, api_requests = byte_meter.count_requests(shop_api.create_app())    with loopback.serve(api_app) as api_url, byte_meter.relay(api_url) as (url, traffic):        # the one API call, sent through the relay so that its bytes are counted the way the tool's are        httpx2.get(f"{url}/orders/O-2476", headers={"X-API-Key": shop_api.DEMO_API_KEY}).raise_for_status()        api_bytes = traffic.sent + traffic.received        print("api call round trips:", api_requests.count)        print("api call bytes:", api_bytes)        os.environ.update(shop_api.server_env(api_url))      # the tool calls the API directly, not through a relay        shop_support = runpy.run_path("list-what-the-server-offers.py")["server"]    # defined there, not run        mcp_app, mcp_requests = byte_meter.count_requests(shop_support.streamable_http_app())        with loopback.serve(mcp_app) as mcp_url, byte_meter.relay(mcp_url) as (url, traffic):            for mode, label in (("auto", "auto"), ("2026-07-28", "pinned")):                names, setup_bytes = await session(url, traffic, mcp_requests, mode, calls=0)   # setup only, no tool call                print(f"mcp {label} setup request count:", len(names))                print(f"mcp {label} setup requests:", ", ".join(names))                print(f"mcp {label} setup bytes:", setup_bytes)            names, with_call = await session(url, traffic, mcp_requests, "2026-07-28", calls=1)            call_bytes = with_call - setup_bytes          # a pinned session with one call, less the pinned setup            print("mcp tool call round trips:", names.count("tools/call"))            print("mcp tool call bytes:", call_bytes)            print("tool call bytes per api call byte:", round(call_bytes / api_bytes, 1))  # one decimal place, as the prose quotesasyncio.run(main())
輸出python api-call-versus-tool-call.py
setup: 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 位元組,與模型本身的 token 相比很小。對於倉儲系統每晚讀取 64 項商品的工作,每次呼叫都要為其程式碼從不讀取的封套付費,而轉接器也為原本不需要它的工作多加了一個行程。

實用原則: 對於程式碼已知要呼叫哪個端點的呼叫端,例如其他服務、固定工作流程與批次作業,請保留一般的 HTTP API;對於由模型或使用者在執行期做選擇的主機,則在同一個 API 前面架設 MCP 伺服器。在把大量流量導入 MCP 之前,請在自己的傳輸方式上量測額外負擔,並在自己掌控的用戶端中固定協定版本,使它們略過探測。對於可能遇到自己無法掌控的伺服器的用戶端,請保留自動模式,因為那些伺服器可能只支援 2025 版協定。

正式環境中會出什麼問題

最近一次變動於第 2026.11.11 版

本章新增的各個部分,會以幾種容易辨認的方式出錯,而每一種都會留下可供查找的痕跡。

能力被放進錯誤的原語。 把政策以工具提供,模型沒想到要去取得時就會被略過;把退款以資源提供,則讓宿主端沒有任何可以請求使用者同意的時間點。徵兆是同一類工單的行為時好時壞,而且原因不在工單本身:回答金額相關問題時沒有依據政策,或是日誌中出現沒有同意步驟的副作用。對每一項能力都要問:該由誰決定它何時執行,做法如同〈把每項能力放進正確的原語〉所示。

閘道器丟棄或改寫 _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" 快取提示所涵蓋的資料,對所有呼叫者都相同。請記錄每個失敗請求的協定版本與錯誤碼,因為版本錯誤與封包結構錯誤,是用戶端或閘道器已發生變更的最早徵兆。

本章的決定

最近一次變動於第 2026.11.11 版
  • **每個伺服器對應一個用戶端,且用戶端位於主機端。**對話以及任何跨伺服器的處理都留在主機端的程式碼中;伺服器只會看到送給它的 requests。
  • **商店的伺服器是 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。

引用本節

格式

各種格式皆引用英文原書,本譯本即依循該原書。

每種格式都會標示本版。其連結會開啟目前版次,節標題會說明該節內文最後一次變動的時間。存取日期與擷取日期即為你開啟此頁的當日。

本頁內容

第 2 章,共 12 章: MCP 為 API 增添了什麼

  1. 區分主機、用戶端與伺服器
  2. Put each capability in the right primitive
  3. 工具是由模型選擇的動作
  4. 資源是由應用程式決定如何使用的資料
  5. 提示(prompt)是由使用者選擇的範本
  6. Carry the version and capabilities on every request
  7. Handle a version the server doesn't support
  8. 快取清單結果
  9. 在 MCP 沒有加分的地方,保留 HTTP API
  10. 正式環境中會出什麼問題
  11. 本章的決定

返回頂端所有章節