MCP が API に加えるもの

読了まで約70 分分、11 節 節の 6 例 例。

第2026.11.14版 2026年11月19日時点で例が通過 70 例中 70 例が合格 変更点

AIによる翻訳。英語版は人による検証済みである。 当社の書籍の作り方

英語版の書籍(版2026.11.14)から翻訳した。 原文を読む

この章を読み終えると、ホスト、クライアント、サーバーがそれぞれ何を担うかを説明できるようになる。また、店の各機能を適切な Model Context Protocol のプリミティブに割り当て、すべてのリクエストが運ぶバージョンとケイパビリティを読み取り、店が通常の HTTP API を維持すべき場面を判断できるようになる。本章の主張と例は、仕様のリビジョン 2026-07-28 と、Python SDK である mcp のバージョン 2.3.0 に基づいている。

この章が 店 に求めるのは、サポートチームのホストがすでに注文検索に利用している HTTP API である。店とは、キッチン用品とガーデン用品を扱う架空のオンラインストア、Fernhill Supply のことである。MCP end to end では、この検索を Model Context Protocol (MCP) サーバーの背後に置き、サポートチームのホスト上のモデルが呼び出せるようにした。そのサーバーが持つツールは一つだけだった。サポートチームはさらに多くを求めている。一つは返金ポリシーであり、チケットが金銭に触れるときはいつでも、ホストが手元に置いておけるようにしたい。もう一つは、返金依頼を確認するための標準的な方法である。一方、倉庫チームは毎晩同じ API から在庫数を読み取っており、自分たちも MCP に移行すべきかどうかを尋ねている。

どちらの問いも、すでに動いている API に MCP が何を加えるのかにかかっている。HTTP クライアントは、開発者が文書で調べたエンドポイントに対して書かれる。MCP クライアントは、サーバーが何を提供するかを実行時に、モデルが読める形式で知る。さらにプロトコルは、各ケイパビリティをいつ使うかを誰が決めるのかを定めている。本章ではこれらの追加点を一つずつ取り上げ、通信上でのコストを測り、最後に店がそのコストを払うべきでない場面を示す。

ホスト、クライアント、サーバーを分ける

最終変更:版2026.11.11

Wrap one endpoint as a tool のサーバーは、その章のコードが操作するクライアントの背後で動いていた。店がこのサーバーに機能を加える前に、どの部分が何を担うのかを正確に押さえておく必要がある。MCP の保証はプロセスではなく役割に結び付いているからである。

仕様は三つの役割を定めている(architecture)。ホストは、ユーザーが作業するアプリケーションである。ホストはクライアントを作成し、モデルとの会話を保持し、セキュリティポリシーと同意を実施する。クライアントは、ホストが一つのサーバーに対して持つ接続である。仕様には「各クライアントはホストによって作成され、ちょうど一つのサーバーと通信する」とある。サーバーはツールなどの機能を公開し、ホストについてそれ以外は何も知らない。同じページには、この分担から導かれる設計原則も示されている。サーバーは会話全体を見るべきではなく、他のサーバーの内部をのぞくべきでもない。各サーバーに何を見せるかはホストが決め、サーバーをまたぐ処理はすべてホストで行われる。

サポートチームのホストはホストの役割を担い、本書のホストループを実行する。ホストが使う各サーバーには、それぞれ専用のクライアントが与えられる。この章では shop-support の一つだけである。Catch poisoned tool descriptions では、提携先の第二のサーバーが加わる。このサーバーには、店のサーバーが返した内容を決して知らせてはならない。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)。

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 で説明する。

実践ルール: ホストでは各サーバーに専用のクライアントを与え、会話とサーバーをまたぐ処理は、サーバーではなくホストのコードに置くこと。どのクライアントも、サーバーが何を提供するかを想定せず、サーバーが提供するものを読み取ることから始めること。そうすれば、サーバーがツールを変更してもホストが壊れない。サーバーを書くときは、自分に送られたリクエストだけが見えると想定すること。仕様がサーバーに見ることを許すのは、それだけだからである。

各機能を適切なプリミティブに割り当てる

最終変更:版2026.11.14

前の節のshop-supportサーバーは、ツール、リソース、プロンプトを一つずつ提供する。サーバーの三つのプリミティブとはツール、リソース、プロンプトであり、それらの違いは、返すものの違いよりも、いつ使うかを誰が決めるかという点にある。仕様書のサーバー概要はこれを表にまとめている。プロンプトはユーザーが制御し、リソースはアプリケーションが制御し、ツールはモデルが制御する(サーバー機能)。したがって、各機能について問うべきことは、読み取りか書き込みかではなく、いつ実行するかを誰が決めるべきかである。その主体は、モデル、ホスト自身のコード、あるいは机の前にいる人のいずれかとなる。

ツールのページは、ツールに特定のインターフェースを義務づけていない。リソースとプロンプトのページも、それぞれのプリミティブについて同様である。ホストはそれらを好きな形で表示できるが、制御モデルを尊重するホストは、表が示す主体にそれぞれを委ねる。次のスクリプトは、shop-supportの三つのプリミティブをホストが行うのと同じ方法で一度ずつ使用する。

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

ツールとは、説明と入力スキーマを備えた名前付きのアクションである。モデルは、そのツールを呼び出すかどうか、また何を入力として呼び出すかを決定する(ツール)。ホストはモデルに対してツールの一覧を示し、モデルが要求した呼び出しを実行する。注文 O-2476 の照会はエラーなく成功し、注文のステータスは shipped として返された。

照会がここに属するのは、それが必要かどうかをチケットが決めるからである。ある顧客は注文 ID を示して荷物の所在を尋ね、別の顧客はフライパンに 28 cm のサイズがあるかどうかを尋ねる。どちらの場合も、チケットを読むものだけが選択でき、このホストではそれがモデルである。モデルにツールを選ばせるでは、録画を用いてモデルがその選択を行う様子を示した。

実践ルール: 会話の内容に基づいて、モデルがその機能を使うかどうかを判断すべき場合に、その機能をツールにする。これには、顧客の書いた内容によって必要性が変わる照会や、返金のように何かを変更するすべてのアクションが含まれる。後者については、ホストが呼び出しの前に同意を求める。

リソースはアプリケーションが選ぶデータである

最終変更:版2026.11.11

リソースとは、サーバーが URI の下で公開するデータであり、それをいつ読み取り、どう扱うかはアプリケーションが決める(リソース)。ホストは、リソースをモデルのコンテキストに添付することも、ユーザーに表示することも、インデックス化することもできる。shop-support は、本書のために書かれた短いポリシー文書の一つである、ショップの返金ポリシーを shop://policies/refund の下で提供する。これを読み取ると text/markdown のテキストが返され、その1行目は # Refund policy である。

返金ポリシーがリソースであるのは、それが必要になる場面をショップがあらかじめ把握しているからである。その場面とは、金銭に関するすべてのチケットである。ホストのコードは、モデルに尋ねることなく、そうしたチケットについて返金ポリシーをモデルのコンテキストに添付できる。これをツールにすると、モデルが取得を思い出すかどうかに依存し、そのたびに1ターンを消費する。リソースは読み取り専用ツールと同じではない。どちらもデータを返すが、リソースの読み手はホストのコードであり、その結果はリスト結果をキャッシュするに示す規則に従ってキャッシュできる。ポリシーをリソースとして公開するでは、ショップの残りのポリシーも同じ方法で提供する。

実践ルール: ホスト自身のコードが必要になる時点を判断できるデータは、リソースにする。たとえば、既知の種類のチケットに適用されるポリシーや、ユーザーが開いたレコードがこれに当たる。会話を読んだモデルだけが必要かどうかを判断できる場合は、ツールのままにする。

この部分はまだ翻訳されていないため、英語で表示している。

Prompts are templates the user chooses

最終変更:版2026.11.11

A prompt is a template of messages, with arguments, that the server defines and the user picks (prompts). The specification is precise about the word: "user-controlled" refers to "who decides when the prompt is used, not who authors its content". The server writes the content, and a host typically offers prompts in a menu or as commands. review_refund takes one argument, order_id, required. Filled in for order O-2476, it returned 1 message from the user role, beginning "Review the refund request for order O-2476. …".

review_refund is a prompt because a person on the support team decides to start a refund review, usually after reading the ticket, and the shop wants every review to follow the same steps. The prompt's text names the tool and the resource the review needs, so the model starts from the policy and the order, not a guess. A prompt isn't a system prompt the user writes: the shop writes it once, on the server, and every host that connects gets the same text. Package a workflow as a prompt grows review_refund into the full review, with the refund amount as a second argument.

Working rule: Make a workflow a prompt when a person should start it and every run should follow the same steps, and keep the prompt's text on the server so that a change reaches every host at once. If no person chooses when it runs, it isn't a prompt: make the steps a tool, or put them in the host's own instructions.

この部分はまだ翻訳されていないため、英語で表示している。

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 の各結果が、2 つのキャッシュヒントを持たなければならない(caching)。

  • ttlMs:結果が新鮮である期間をミリ秒で表す。HTTP の max-age に似ている。0 は直ちに古くなることを意味する。
  • cacheScope:"public" または "private" のいずれかである。前者はキャッシュが複数の呼び出し元で共有してよいことを示し、後者は認可コンテキストをまたいで共有してはならない(MUST NOT)ことを示す。

同じページは、ヒントの意味に限界も設けている。TTL は新鮮さのヒントであり、ポーリング間隔ではない。クライアントはデータが必要になったときに新鮮さを確認し、ポーリングを行う場合はジッタとバックオフを用いなければならない。list_changed 通知は、まだ新鮮なキャッシュ済みの結果を無効にする。また、cacheScope はアクセス制御ではない。サーバーは「cacheScope だけに頼って不正なアクセスを防いではならない(MUST NOT)」。

ツール一覧のキャッシュは、一覧が安定している場合にのみ機能する。仕様によれば、サーバーの tools/list は接続ごとに変わってはならず(MUST NOT)、リクエストの認可に応じて変わることは許される。また、サーバーはツールを決定的な順序で返すべきであり、これによりプロンプトキャッシュのヒット率が上がる(tools)。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")} によってツール一覧のキャッシュを有効にしている。これは 5 分間で、共有可能という設定である(mcp/server/caching.py)。反対側では、mcp.Client が既定でメモリ内にサーバーのヒントに従ってキャッシュし、各リスト呼び出しは cache_mode として "use"、"refresh"、"bypass" のいずれかを取る。独自の meta を渡した呼び出しは必ずサーバーに届き、クライアントはどの TTL も 24 時間で頭打ちにする(mcp/client/caching.py)。キャッシュによる節約量を数えるために、ヒントを設定していない第 1 章のサーバーからツール一覧を 2 回取得し、続いて shop-support から 2 回取得する。そして 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 回の呼び出しの両方がサーバーに届き、リクエストは合計 2 件になった。shop-support の一覧は ttlMs 300000, cacheScope public とともに返ったので、2 回目の呼び出しにはクライアントのキャッシュが応答し、サーバーに届いたリクエストは 1 件だけだった。2 回目の呼び出しで cache_mode="bypass" を指定すると、2 回ともふたたびサーバーに届き、例の隣にある出力がその数を示す。モデルのターンごとにツール一覧を描画するホストは、1 ターンにつき 1 リクエストを節約できる。また、一覧の順序が保たれるので、モデルのプロンプトは同じバイト列で始まり、これはプロバイダのプロンプトキャッシュに必要な条件である。

ショップのツール一覧は、どの呼び出し元にも同じツールが見えるので、公開にできる。ショップの顧客ごとのデータはそうできない。リソーステンプレートでレコードを指定するが注文ごとに 1 つのリソースを提供するとき、それらの読み取りは "private" のままにする。そうすれば、共有キャッシュがある顧客の注文を別の顧客のセッションに渡すことはない。トークンが許可する範囲でツールを絞るを適用した場合のように、ツール一覧が呼び出し元のトークンに依存するようになれば、その一覧も private になる。

実践ルール: すべての呼び出し元で同じになる一覧、たとえばショップのツール一覧には、TTL と "public" スコープを設定する。TTL は、デプロイ後に古い一覧を許容できる時間より長くしない。数時間ではなく数分にする。誰が問い合わせているかに依存するものには、SDK の既定値である "private" を保ち、cacheScope を認可チェックの代わりにしてはならない。クライアントでは、既定のキャッシュを維持する。このキャッシュは、client.listen(tools_list_changed=True) ストリームで変更通知が届くとエントリを破棄する(mcp/client/client.py)。このストリームは、リソースが変わったことをクライアントに知らせるが開くものと同じ種類である。このストリームがなければ通知はクライアントに届かないので、ストリームを開くこと。エントリを疑う別の理由があるときは、TTL に基づいてポーリングするのではなく、cache_mode="refresh" を使う。

この部分はまだ翻訳されていないため、英語で表示している。

Keep an HTTP API where MCP adds nothing

最終変更:版2026.11.11

Each section so far showed something MCP adds to the shop's API. Separate the host, the client and the server added run-time discovery, and Put each capability in the right primitive gave each capability a control model. Carry the version and capabilities on every request made every request versioned and self-describing. The host's consent step, in Ask for consent before side effects, is another. Each of those helps when a model or a user's host chooses among capabilities at run time. None of them helps a program whose developer already knows which endpoint it will call.

The specification doesn't say when not to use MCP, so this is the book's judgement, not a protocol rule. We recommend a plain HTTP API for three kinds of work:

  • Service-to-service calls with no model choosing, such as the warehouse's nightly read of stock levels. Its code calls fixed endpoints, so nobody reads the discovery answers or the descriptions.
  • Fixed workflows, where the same steps run in the same order every time. Write them as code over the API, and if a model needs to start one, expose the whole workflow as one tool.
  • High-volume batch work, where every byte and round trip is multiplied.

We recommend MCP where a model or a user's host chooses among capabilities at run time, as the support team's host does. The two don't compete. Meet the shop and its API kept the shop's API as the system of record, and shop-support is a thin adapter over it, so the warehouse keeps its API calls while the support team's host uses MCP.

This run prices the adapter, so the trade-off rests on numbers. The script fetches order O-2476 twice: once from the shop's API, with GET /orders/O-2476, and once through shop-support's get_order_status tool over Streamable HTTP, the transport Move the server from stdio to HTTP teaches. lib.byte_meter, a small module for this measurement, puts a TCP relay in front of each server and counts every byte both ways, headers included, and counts the HTTP requests each server handles. Everything runs in one process on 127.0.0.1, over HTTP/1.1 without TLS. On the MCP side, the count covers a host's setup on opening a client, including the tool listing, but not the tool call. That setup is measured twice: in the default auto mode, which first probes the server with server/discover, and with the version pinned. The tool call itself is made with the version pinned. No times are measured, because times on one machine's loopback say little about a network.

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

On the wire the tool call costs more bytes, not more round trips. The API call takes 1 round trip and the tool call takes 1, but it sends 2.3 times the bytes, which the output beside the example counts. The difference is the JSON-RPC envelope, the _meta on the request and on the result, the routing headers that Streamable HTTP adds, and the order itself, which the SDK returns as indented JSON inside a text block, with its quotes escaped, as Read the messages on the wire showed.

Setup costs more on top of that. In auto mode, opening the client sent 2 requests before its first call; with the version pinned it skipped the server/discover probe and sent 1. The output beside the example lists the requests and their bytes. Behind the server, each tool call also made its own request to the shop's API, which the counts leave out because the caller never sees it.

Some of those bytes buy something without a model. The headers Mcp-Method, on every request, and Mcp-Name, on tools/call, resources/read and prompts/get, let a gateway route by method and by tool without parsing bodies (Streamable HTTP). For the support team's host, which makes a few calls per ticket, 1357 bytes a call is small beside the model's own tokens. For the warehouse's nightly read of 64 products, every call pays for an envelope its code never reads, and the adapter adds a process to a job that ran without one.

Working rule: Keep a plain HTTP API for callers whose code knows which endpoint to call, such as other services, fixed workflows and batch jobs, and put an MCP server in front of the same API for hosts where a model or a user chooses at run time. Measure the overhead on your own transport before you route high-volume traffic through MCP, and pin the protocol version in clients you control, so they skip the discovery probe. Keep auto mode for clients that may meet servers you don't control, which may speak only the 2025 protocol.

この部分はまだ翻訳されていないため、英語で表示している。

What goes wrong in production

最終変更:版2026.11.11

The parts this chapter added fail in a few recognisable ways, and each leaves a trace you can look for.

A capability lands in the wrong primitive. A policy served as a tool gets skipped when the model doesn't think to fetch it, and a refund served as a resource leaves the host no point at which to ask for consent. The sign is behaviour that varies from ticket to ticket for no reason in the ticket: answers about money given without the policy, or side effects with no consent step in the logs. Ask of each capability who should decide when it runs, as Put each capability in the right primitive does.

A gateway drops or rewrites _meta. Proxies and API gateways built for plain JSON APIs sometimes rewrite request bodies. A request that loses its version or capabilities fails with -32602, as Carry the version and capabilities on every request showed. On Streamable HTTP, a body that no longer matches its headers fails with -32020, because the MCP-Protocol-Version, Mcp-Method and Mcp-Name headers must agree with the body (Streamable HTTP). Pass MCP traffic through unchanged, and route on the headers rather than editing bodies.

clientInfo is used as an identity. The client's name in _meta is whatever the client chose to send, and the specification says not to rely on it for security (base protocol). A server that grants more to a client named shop-host grants it to anyone who sends that name. Authorization comes from tokens, which Find the authorization server from the resource starts on.

A public cache entry crosses customers. A result marked "public" may be shared across authorization contexts, even when it came from an authenticated endpoint (caching). A server that marks per-customer data public lets a shared cache serve one customer's order to another. Keep the SDK's "private" default for anything that depends on the caller, and treat every "public" hint in a code review as a claim to check.

A long TTL hides a deploy. With a tool list fresh for hours, a client keeps offering a tool the server has removed, and calls to it fail. The sign is unknown-tool errors that stop when clients restart. Keep tool-list TTLs to minutes, and let clients refresh on a change notification, which reaches a client only on a subscriptions/listen stream it opened, as Tell clients when a resource changes sets up.

A client calls a tool it never listed. At 2.3.0, mcp.Client checks a tool's result against the tool's output schema, and if it hasn't listed the tools yet, it sends tools/list first (mcp/client/session.py). A client that calls tools without listing them pays an extra request on its first call. List the tools when the client opens, as a host does anyway.

Old error codes from old material. The pinned revision reserves -32020 to -32099 for the specification, treats -32000 to -32019 as a legacy range that new code shouldn't use, and asks for application codes outside the range JSON-RPC reserves (base protocol). The revision renumbered its error codes on the way to release (changelog), so material written against a draft can show other numbers for the same errors. Match error codes against the specification, not against a blog post.

The specification moves on. MCP is governed by the Agentic AI Foundation, a directed fund under the Linux Foundation, which took MCP on as a founding project in December 2025 (announcement). Revisions are dated, and a deprecated feature stays for at least twelve months (feature lifecycle). The window is shorter only for an active security risk, and then at least ninety days, or where the deprecated features registry says so. Read the registry when you plan a server's next release, and watch logs for -32022 from clients built for a later revision.

Working rule: Check four things on any server you are about to ship: each capability's primitive matches who decides when it runs, nothing between client and server edits MCP bodies, nothing is decided on clientInfo, and every "public" cache hint covers data that is the same for every caller. Log the protocol version and error code of every failed request, because version and envelope errors are the first sign that a client or a gateway has changed.

この章で下した決定

最終変更:版2026.11.11
  • サーバーごとに1つのクライアントを、ホスト内に置く。 会話とサーバーをまたぐ処理はすべてホストのコードに残す。サーバーが目にするのは、自身に送られたリクエストだけである。
  • ショップのサーバーはshop-supportである。 1章のget_order_statusツール、shop://policies/refundにあるリソースとしての返金ポリシー、そしてプロンプトとしてのreview_refundを備える。
  • 各機能は、実行のタイミングを決めるべき制御主体が持つプリミティブに割り当てる。 ツールはモデル、リソースはホストのコード、プロンプトはデスクにいる担当者である。
  • バージョンとケイパビリティは、そのつどリクエストから読み取る。 以前のリクエストから読み取ることはしない。ケイパビリティが欠けている場合は-32021を返す。
  • ショップ独自の_metaキーには、example.fernhill/プレフィックスを使う。 clientInfoやserverInfoに基づいて何かを決めることはしない。
  • -32022を受け取った場合、クライアントは1回だけ再試行する。 両者が挙げるバージョンのうち最新のものを使い、それでも失敗すれば、エラーを表示する。
  • ツール一覧は公開とし、TTLは5分とする。 顧客ごとのデータは非公開のままとし、ツール一覧がトークンに依存するようになった場合は、ツール一覧も非公開にする。
  • 手書きの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)から翻訳した。

この節を引用する

形式

いずれの形式も、本訳書が従う英語版の書籍を出典として示す。

いずれの形式もこの版を明示している。そのリンクは現行版を開き、節の見出しには本文が最後に変更された日付が示される。アクセス日と取得日は、これを開いた日である。

このページの内容

全12章中の第2章: MCP が API に加えるもの

  1. ホスト、クライアント、サーバーを分ける
  2. 各機能を適切なプリミティブに割り当てる
  3. ツールはモデルが選択するアクションである
  4. リソースはアプリケーションが選ぶデータである
  5. Prompts are templates the user chooses
  6. Carry the version and capabilities on every request
  7. Handle a version the server doesn't support
  8. リスト結果のキャッシュ
  9. Keep an HTTP API where MCP adds nothing
  10. What goes wrong in production
  11. この章で下した決定

ページの先頭に戻るすべての章