MCPをエンドツーエンドで理解する
読了まで約57 分分、7 節 節の 5 例 例。
この章を終えるまでに、既存のHTTP APIをstdio経由のModel Context Protocolサーバの背後に置き、クライアントからそのツールを呼び出し、両者がやり取りするすべてのメッセージを読み、小さなホストを通じてモデルにツールを選ばせることができるようになる。すべての例は1台のマシン上で動作する。この章の主張は、仕様のリビジョン2026-07-28、およびPython SDKであるmcp 2.3.0について成り立つ。
顧客が、キッチン用品とガーデン用品を扱う小さなオンラインショップであるFernhill Supplyに、注文がどこにあるかを尋ねるメッセージを送る。その答えはチケットの中ではなくFernhill Supplyのシステムの中にあるため、サポートチームのホストにいるモデルは、注文を調べる手段が与えられて初めて答えることができる。この章はこの問題を扱う。ショップについてはショップとそのAPIを知るで詳しく紹介する。
Model Context Protocol(MCP)は、モデルを利用するアプリケーションが、自分では書いていないプログラムからツールやデータを得るための仕組みである。作業は3つの役割で分担され、本書ではそれらの名称を厳密に使い分ける。**ホストは、ユーザが作業するアプリケーションであり、サポートデスクやコーディングアシスタントがこれにあたる。クライアントは、ホストから1つのサーバへの接続である。サーバ**は、モデルが呼び出せるツールなどの機能を公開する(仕様の概要)。クライアントとサーバの間のメッセージはJSON-RPC 2.0である。
この章では、全体の粗い版を構築する。API、1つのツールを持つサーバ、クライアント、通信のトレース、そして記録されたモデルの選択1件である。以降の各章は、これらの部品を1つずつ堅牢にしていく。
ショップとそのAPIを知る
MCPサーバーが何もないところから始まることはまれである。サーバーを必要とするチームの多くは、独自のデータ、認証、クライアントを備えたHTTP APIをすでに運用しており、サーバーの役割はその一部をモデルの前に差し出すことにある。したがって、最初に必要なのは、ラップする対象のAPIであり、それを例から到達できる場所で動かしておくことである。
どの章でも、Fernhill Supplyというこのショップを題材にする。以下では、これをショップと呼ぶ。ショップは架空のものであり、実在の事業を表してはいない。そのドメイン fernhill.example は予約された名前であり、名前解決されることはない。サポートチームは顧客からのチケットに対応しており、チケットの多くはショップのシステムでの照会を必要とする。たとえば、注文がどこにあるか、商品の在庫があるか、返金がいくらになるか、といった照会である。本書の目標は、こうしたチケットを読み、ショップのツールを呼び出して答えるホストを作ることである。
ショップには、各章がラップする「ラップ前」の状態がすでにある。それがショップのAPIであり、注文、在庫、返金を扱うHTTP APIで、X-API-Key ヘッダーのAPIキーを検査する。そのレコードはショップのデータであり、本書自身のコードが1つの固定シードから生成するため、実行するたびに同じ顧客、注文、チケットが現れる。この構成は examples/lib/ にある3つの共有モジュールにまとめてあり、そのおかげで例は短く保たれる。
lib.shop_dataはショップのデータを生成する。load_shop()は、顧客、商品、在庫量、注文、返金、チケットをPythonのデータクラスとして返す。lib.shop_apiはショップのAPIであり、そのデータの上に作られたStarletteアプリである。lib.loopbackは、空いているポートの127.0.0.1でアプリを提供し、ブロックが終わると停止する。
APIをラップする前に、どのクライアントとも同じ方法で実行してみる。キーを付けて1回、キーなしで1回、存在しない注文に対して1回である。
1"""Start the shop's existing HTTP API on loopback and call it three ways: with its key, without it, and for an order2 that doesn't exist. The point rests on the `without key` line, which shows the API refuses a caller it can't identify."""3import httpx245from lib import loopback, shop_api6from lib.shop_data import SHOP_SEED, load_shop78shop = load_shop() # one fixed seed, so every run sees the same customers, orders and tickets9print("seed:", SHOP_SEED)10print("customers:", len(shop.customers))11print("products:", len(shop.products))12print("orders:", len(shop.orders))13print("tickets:", len(shop.tickets))1415with loopback.serve(shop_api.create_app()) as base_url: # serves on 127.0.0.1 at a free port until the block ends16 # the API checks this header; DEMO_API_KEY is the key the shop's API accepts17 response = httpx2.get(f"{base_url}/orders/O-2476", headers={"X-API-Key": shop_api.DEMO_API_KEY})18 order = response.json()19 print("with key:", response.status_code)20 print("order status:", order["status"])21 print("shipped on:", order["shipped_on"])22 print("total:", order["total"])23 print("without key:", httpx2.get(f"{base_url}/orders/O-2476").status_code) # no header at all24 # O-7144 is a well-formed ID that the generated orders do not contain25 print("unknown order:", httpx2.get(f"{base_url}/orders/O-7144",26 headers={"X-API-Key": shop_api.DEMO_API_KEY}).status_code)
python start-the-shop-api.pyseed: 4217
customers: 240
products: 64
orders: 1500
tickets: 48
with key: 200
order status: shipped
shipped on: 2026-06-24
total: 99.00
without key: 401
unknown order: 404
シードは 4217 であり、例の横の出力は、そのシードが生成する顧客、商品、注文、チケットの数を示している。メールアドレスは example.com のものであり、電話番号は下2桁を除いて伏せられ、支払いは公開されているテスト用カードの下4桁を添えた「card ending」だけを表示する。すべてのフィールドは examples/data/shop/README.md のデータカードに一覧がある。
キーを付けるとAPIは 200 と答える。注文O-2476のステータスは shipped で、2026-06-24 に発送され、合計は€99.00である。ショップはすべてをユーロで価格付けしており、そのAPIは金額を通貨コードなしの単純な小数として送る。
キーがなければ 401 と答え、存在しない注文には 404 が返る。この3つの応答が、MCPサーバーが守らなければならない契約である。サーバーはキーを保持し、同じエンドポイント GET /orders/{order_id} を呼び出して、その応答をモデルが読める形に変える。注文の処理を自前で再実装することはしない。
実践ルール: すでに運用しているAPIをラップし、それを記録システムとして維持する。MCPサーバーは、自身の認証情報でAPIを呼び出して応答を変換する薄いアダプターにとどめる。そうすれば、APIの検証、認可、ログが、モデルだけでなくすべてのクライアントに対して働き続ける。データベースを直接土台にするのは、ラップすべきAPIがない場合に限る。その場合も、業務ルールは両方の種類のクライアントが共有する1か所に置く。
この部分はまだ翻訳されていないため、英語で表示している。
Wrap one endpoint as a tool
The shop's API from the previous section answers "what is the status of order O-2476" for any HTTP client. To answer that for a model, the shop needs an MCP server that exposes the lookup as a tool: a named action with a description and a JSON Schema for its inputs, which a model can decide to call (tools). The server publishes its tools in tools/list, and a client runs one with tools/call.
In the Python SDK the server class is MCPServer, imported from mcp.server.mcpserver. The SDK's 1.x releases called it FastMCP, and at 2.3.0 importing mcp.server.fastmcp fails with a pointer to the migration guide. You register a tool with @server.tool(), parentheses included, since the bare @server.tool raises a TypeError that asks for them (mcp source, mcp/server/mcpserver/server.py). The SDK takes the tool's name from the function, its description from the docstring and its input schema from the type hints. server.run() serves over stdio, where the client starts the server as a subprocess and the two exchange messages on standard input and output, which is run()'s default.
The shop's first server is called shop-orders, and its one tool, get_order_status, wraps GET /orders/{order_id}. It reads the API's address and key from its environment, so they never appear in the code or on the wire. Server examples follow one pattern: the file defines the server, and with no arguments it starts a client that launches the same file with --serve and lists the tools. Run it to see the tool the way a model receives it.
1"""The shop's first MCP server: one tool, get_order_status, that wraps GET /orders/{order_id} on the shop's API. The2 point rests on the description and schema lines, the only parts of the tool a model reads."""3import asyncio4import json5import os6import sys78import httpx29from mcp import Client, StdioServerParameters10from mcp.server.mcpserver import MCPServer11from mcp.server.mcpserver.exceptions import ToolError1213server = MCPServer("shop-orders", version="0.1.0")141516@server.tool()17def get_order_status(order_id: str) -> dict:18 """Look up one of the shop's orders by its ID, such as O-1873: its status, dates, lines and total."""19 # read on each call: a missing variable raises KeyError here, and the SDK reports only a generic error20 response = httpx2.get(f"{os.environ['SHOP_API_URL']}/orders/{order_id}",21 headers={"X-API-Key": os.environ["SHOP_API_KEY"]},22 timeout=5.0) # seconds; a slow shop API fails this call instead of holding the worker23 # the shop answers 404 for an order it doesn't have, so the model gets a message it can act on24 if response.status_code == 404:25 raise ToolError(f"The shop has no order {order_id}. Order IDs look like O-1873.")26 response.raise_for_status() # any other failure, such as a wrong key, stays on the server as an HTTPError27 return response.json()282930async def show_tools() -> None:31 from lib import loopback, shop_api32 with loopback.serve(shop_api.create_app()) as base_url:33 # the API's address and key are the only variables the server gets34 params = StdioServerParameters(command=sys.executable, args=[__file__, "--serve"],35 env=shop_api.server_env(base_url))36 async with Client(params) as client:37 for tool in (await client.list_tools()).tools:38 print("tool:", tool.name)39 print("description:", tool.description)40 print("input schema:", json.dumps(tool.input_schema))414243if __name__ == "__main__":44 if "--serve" in sys.argv:45 server.run() # stdio is the default transport46 else:47 asyncio.run(show_tools())
python order-status-server.pytool: get_order_status
description: Look up one of the shop's orders by its ID, such as O-1873: its status, dates, lines and total.
input schema: {"type": "object", "properties": {"order_id": {"title": "Order Id", "type": "string"}}, "required": ["order_id"], "title": "get_order_statusArguments"}
What the client sees is the tool's definition. Its name is get_order_status, its description is the docstring word for word, and its input schema says that order_id is a required string. The SDK built that schema from the order_id: str hint and added title fields of its own, such as "Order Id". The model reads only the description and the schema, so the docstring is written for a model: what the tool does, what an ID looks like and what comes back. Write descriptions the model reads measures how much that wording matters.
The function is a plain def that makes a blocking HTTP call, and at 2.3.0 the SDK runs synchronous tools on a worker thread, so a slow call to the shop's API doesn't stall the server's other requests (migration guide). The function also raises ToolError on a 404, and the SDK passes a ToolError's message to the client as a failed tool result. Any other exception becomes a generic Error executing tool message, and its text stays on the server (mcp/server/mcpserver/tools/base.py). Call the tool from a client shows both kinds of failure.
The server needs no HTTP library of its own, because the SDK depends on httpx2, a fork of HTTPX, at 2.3.0 (migration guide). The tool uses only httpx2.get(), the response's status_code, raise_for_status() and json(), which work as they do in HTTPX.
Working rule: Start with one read-only tool for one endpoint, and write its docstring for a model: what it does, what its inputs look like, what it returns. Raise ToolError with a message that tells the model what to do differently, and let unexpected exceptions stay generic so internal details never leave the server. Past a handful of endpoints, shape the tools around the tasks the model has to do rather than one per endpoint (Shape tools around tasks, not endpoints).
この部分はまだ翻訳されていないため、英語で表示している。
Call the tool from a client
Wrap one endpoint as a tool defined shop-orders but never ran it, because a stdio server runs only when something launches it. In the shop's case that something is the host, and the part of the host that talks to one server is a client. Over stdio, a client starts the server as a subprocess, writes requests to its standard input and reads responses from its standard output (stdio transport).
At the pinned revision there is no handshake and no session. Each request stands alone and carries the protocol version and the client's capabilities in its _meta field, and the specification says a server "MUST NOT rely on prior requests over the same connection to establish context" (base protocol). The same page also says an open connection, such as a stdio process, isn't a conversation or a session. Revisions up to 2025-11-25 opened every connection with an initialize handshake; Remove initialize and session IDs covers moving off it.
The Python SDK's high-level client is mcp.Client, and given a StdioServerParameters it launches the command as a subprocess. In its default mode="auto" it first sends server/discover at the pinned revision. It falls back to the old initialize handshake whenever the probe times out or fails with any error, except a -32022 whose list of versions shares none with the client's, the case Handle a version the server doesn't support covers (mcp/client/client.py, mcp/client/_probe.py). A 2025-era server answers server/discover with an error, so it gets the old handshake. Use Client, not a hand-called initialize() on a low-level ClientSession, which always speaks the pre-2026 handshake (migration guide).
The command is sys.executable, the Python running the example, rather than "python", so the server runs in the same environment with the same pinned packages, whatever is first on the PATH. The shop API's address and key go in env= explicitly, because the stdio client doesn't pass the parent's environment through. On Linux and macOS it passes only HOME, LOGNAME, PATH, SHELL, TERM and USER, plus what you give it (mcp/client/stdio.py). The client also names itself, shop-host, so the server's logs and the wire show who called.
The next example makes three calls to show failures from the client's side: one for a real order, one for an order ID that doesn't exist, and one from a second client that forgets the environment.
1"""Launch the shop's server over stdio and call get_order_status for a real order and a wrong one, then for a server2 started without the shop's variables. The asserts pin the error flags the prose states: a real order is not an error, and a wrong ID is."""3import asyncio4import json5import sys67from mcp import Client, StdioServerParameters8from mcp.types import Implementation910from lib import loopback, shop_api1112SHOP_HOST = Implementation(name="shop-host", version="0.1.0") # the name the server's logs and the wire show131415async def main() -> None:16 with loopback.serve(shop_api.create_app()) as base_url:17 env = {"SHOP_API_URL": base_url, "SHOP_API_KEY": shop_api.DEMO_API_KEY} # the only two variables the server reads18 # relative to the examples folder, where examples run, so the server file is found19 params = StdioServerParameters(command=sys.executable, args=["order-status-server.py", "--serve"], env=env)20 async with Client(params, client_info=SHOP_HOST) as client:21 print("protocol revision:", client.protocol_version)22 print("server:", client.server_info.name, client.server_info.version)23 result = await client.call_tool("get_order_status", {"order_id": "O-2476"})24 assert result.is_error is False # a real order comes back as a result, not an error25 # the tool returns the order as JSON text in its first content block26 print("order status:", json.loads(result.content[0].text)["status"])27 wrong = await client.call_tool("get_order_status", {"order_id": "O-7144"})28 assert wrong.is_error is True # an unknown order is a failed tool result, not an exception29 print("wrong ID says:", wrong.content[0].text)3031 # no env=, so the server starts without the shop's variables and its tool fails at the first call32 no_env = StdioServerParameters(command=sys.executable, args=["order-status-server.py", "--serve"])33 async with Client(no_env, client_info=SHOP_HOST) as client:34 broken = await client.call_tool("get_order_status", {"order_id": "O-2476"})35 print("without env says:", broken.content[0].text)363738asyncio.run(main())
python call-order-status.pyprotocol revision: 2026-07-28
server: shop-orders 0.1.0
order status: shipped
wrong ID says: Error executing tool get_order_status: The shop has no order O-7144. Order IDs look like O-1873.
without env says: Error executing tool get_order_status
The first call works. The real order comes back as an ordinary result, not an error, with status shipped, the same answer the shop's API gave directly. On the way, the client and server agreed on revision 2026-07-28, and the server/discover answer gave the client the server's name and version, shop-orders 0.1.0.
The wrong ID, O-7144, comes back as a flagged result, not an exception, and its text is the ToolError message, prefixed by the SDK. A model that reads "Order IDs look like O-1873" can ask the customer again. The third call fails differently. The server started without SHOP_API_URL, so the tool raised a KeyError, and all the client got was Error executing tool get_order_status. The KeyError itself went to the server's standard error, where an operator can find it and a model can't. That split is deliberate, because it puts a missing variable in the server's logs and never in the conversation.
Working rule: Connect with mcp.Client, launch stdio servers with sys.executable and an explicit env=, and give the client a name. Pass each variable the server needs and nothing else from your environment, so no server sees secrets meant for another program. When a tool fails with only the SDK's generic message, read the server's standard error before you change the client.
この部分はまだ翻訳されていないため、英語で表示している。
Read the messages on the wire
The client in the previous section hid every message behind call_tool(). When a server misbehaves, or you need to know what the pinned revision really sends, read the messages. Over stdio, each message is one line of JSON-RPC on the server's standard input or output, with no embedded newlines. The server "MUST NOT" write anything to its stdout that isn't a valid MCP message, and its logs belong on standard error (stdio transport).
A faithful trace needs a real subprocess. The SDK's in-process client, Client(server) given a server object, dispatches calls directly in its default auto mode, sending no JSON-RPC at all (mcp/client/client.py), so it can't show you the wire. The book's trace printer, lib.wire, puts a small relay between the client and the server instead: the client launches the relay, the relay launches the real server, and the relay copies every line both ways unchanged while appending it to a log.
wire.print_trace() then prints that log in order, with numbered messages, arrows for direction (-> from client to server, <- back) and request IDs renumbered so the output stays stable. Values under names that look like secrets print as [redacted]; this trace has none.
To see the wire, run the call for order O-2476 from the client example through the relay. Three of its messages print in full, and the rest on one line each.
1"""Record every message the client and the shop's server exchange for one tool call, and print them in order. The point2 rests on the methods line: the exchange has no initialize."""3import asyncio4import pathlib5import sys67from mcp import Client, StdioServerParameters8from mcp.types import Implementation910from lib import loopback, shop_api, wire111213async def main() -> None:14 with loopback.serve(shop_api.create_app()) as base_url:15 server = StdioServerParameters(command=sys.executable, args=["order-status-server.py", "--serve"],16 env=shop_api.server_env(base_url))17 pathlib.Path("wire.jsonl").unlink(missing_ok=True) # the relay appends, so start each run empty18 # the relay starts the server and copies every line both ways, appending each one to the log19 params = wire.relay(server, log="wire.jsonl")20 async with Client(params, client_info=Implementation(name="shop-host", version="0.1.0")) as client:21 await client.list_tools()22 await client.call_tool("get_order_status", {"order_id": "O-2476"})23 # messages 1, 5 and 6 print in full; the rest on one line, with strings cut at 48 characters24 messages = wire.print_trace("wire.jsonl", full=(1, 5, 6), depth=4, max_string=48)25 print("messages:", len(messages))26 print("methods:", ", ".join(m["method"] for m in messages if "method" in m)) # results carry no method272829asyncio.run(main())
python trace-first-call.py1. -> request server/discover (id 1)
{
"jsonrpc": "2.0",
"id": 1,
"method": "server/discover",
"params": {
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientInfo": {
"name": "shop-host",
"version": "0.1.0"
},
"io.modelcontextprotocol/clientCapabilities": {}
}
}
}
2. <- result (id 1) result: {"cacheScope": "private", "capabilities": "{…}", "resultType": "complete", "supportedVersions": "[…]", "ttlMs": 0, "_meta": "{…}"}
3. -> request tools/list (id 2) params: {"_meta": "{…}"}
4. <- result (id 2) result: {"cacheScope": "private", "resultType": "complete", "tools": "[…]", "ttlMs": 0, "_meta": "{…}"}
5. -> request tools/call (id 3)
{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "get_order_status",
"arguments": {
"order_id": "O-2476"
},
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientInfo": {
"name": "shop-host",
"version": "0.1.0"
},
"io.modelcontextprotocol/clientCapabilities": {}
}
}
}
6. <- result (id 3)
{
"jsonrpc": "2.0",
"id": 3,
"result": {
"content": [
{
"text": "{\n \"order_id\": \"O-2476\",\n \"customer_id\": \"C-0…",
"type": "text"
}
],
"isError": false,
"resultType": "complete",
"_meta": {
"io.modelcontextprotocol/serverInfo": {
"name": "shop-orders",
"version": "0.1.0"
}
}
}
}
messages: 6
methods: server/discover, tools/list, tools/call
Nothing here is a handshake: there is no initialize. The exchange is 6 messages, and the methods, in order, are server/discover, tools/list, tools/call. Reading them one at a time:
server/discoveris the first request. Itsparamshold only_meta, with three entries:io.modelcontextprotocol/protocolVersion,io.modelcontextprotocol/clientInfonamingshop-host, andio.modelcontextprotocol/clientCapabilities, which is empty because this client declares none. Every server must implementserver/discover(discovery).- Its result lists
supportedVersionsand the server'scapabilities, and the server's own_metacarriesio.modelcontextprotocol/serverInfo. The result also hasresultTypeand two cache hints,ttlMsandcacheScope, which Cache list results explains. tools/listcarries the same_metaagain.- Its result holds the tool definition that the server example printed.
tools/callnames the tool and gives itsarguments, and once more carries the protocol version, the client's name and its capabilities.- Its result holds the order as text
content, withisErrorset to false andresultTypeset to"complete".
Three requests, each saying who is asking and at which revision, because no request may lean on the one before it.
Every result carries resultType, and "complete" marks an ordinary answer. The other kind, a request for input mid-call, is the subject of Return an input request instead of a result. A client treats a result without the field, from an older server, as complete (base protocol). The SDK's server adds resultType and the serverInfo stamp itself (mcp/server/runner.py).
One thing is missing from the trace on purpose: the shop's API key. It reached the server through the subprocess's environment, and the server sent it only to the shop's API. The specification wants stdio servers to retrieve credentials from the environment, not to follow the OAuth flow that Authorize clients with OAuth teaches for HTTP (base protocol).
Working rule: When a call behaves unexpectedly, trace the wire before you read the SDK's code: a relay that copies and logs lines works with any client and any server. Never write to standard output from a stdio server, not even a debugging print(), because the client reads every line there as a message. Use logging, which the SDK sends to standard error, or write to standard error yourself.
モデルにツールを選ばせる
クライアントの例では、ツールとその引数をコードが選んでいた。このショップの場合、その選択はモデルが行うべきである。ツールはモデル制御である。ホストは利用可能なツールをモデルに示し、モデルはどれを呼び出すか、どの引数で呼び出すかを決める(ツール)。それ以外はすべてホストが担う。ホストはプロンプトを組み立て、モデルの返答を読み、クライアントを通じて呼び出しを行い、その結果をどう扱うかを決める。
本書のホストループ lib.host は、本書が自前で書く小さなホストであり、各ステップが見えるようになっている。ここでは 1 ターンを実行する。サーバーのツールを本書独自のシステムプロンプトに展開し、各ツールの名前、説明、入力スキーマを記す。次に、そのプロンプトと 1 件のチケットをモデルに送り、返答を解析する。ツール名と引数を持つ <tool_call> ブロックを含む返答は選択であり、それ以外の返答は言葉による回答である。このループは、プロンプトと解析をモデルライブラリではなく本書のコードの中に置く。そのため、録画を作るときに実際のモデルを動かすコードと、例で再生を行うコードは同じものになる。
ここでの例はモデルを一切呼び出さない。モデルの出力は決定的ではなく、例はオフラインで動作しなければならないからである。録画(recording)は、モデルの生の返答を examples/data/recorded/ の下に保持したものであり、recordings/ にあるスクリプトで一度だけ作成され、例では ReplayModel で再生する。プロンプト、チケット、ツールのいずれかが変わっていると、再生は明示的に失敗する。本書のすべての録画には Qwen3-4B-Instruct-2507 を使う。これは Apache-2.0 ライセンスのオープンモデルで、4 ビットに量子化(Q4_K_M、サードパーティの GGUF 変換)し、llama.cpp で CPU 上で実行する。したがって、誰でも録画を作り直せる。スクリプト recordings/pick_a_tool.py は、同じサーバーと同じプロンプトを用いて、この章の録画 pick-a-tool を作成した。そのマニフェストには、モデルファイルのリビジョンとハッシュが記されている。
不確かなのはモデルである。そこで、この例ではモデルに 3 件のチケットを与える。1 件はショップの書き方どおりの注文 ID を引用し、1 件は注文番号だけを示し、1 件はこのサーバーのどのツールでも答えられない在庫について尋ねる。
1"""The book's host loop shows three tickets and the server's tools to a model, then calls the tool the model chooses, from recorded replies in examples/data/recorded/. The point rests on the three `tool` lines."""2import asyncio3import json4import sys56from mcp import Client, StdioServerParameters7from mcp.types import Implementation89from lib import loopback, shop_api10from lib.host import ReplayModel, choose_tool11from lib.shop_data import load_shop1213model = ReplayModel("pick-a-tool") # answers only with the replies recorded for these exact messages141516async def main() -> None:17 shop = load_shop()18 with loopback.serve(shop_api.create_app()) as base_url:19 params = StdioServerParameters(command=sys.executable, args=["order-status-server.py", "--serve"],20 env=shop_api.server_env(base_url))21 async with Client(params, client_info=Implementation(name="shop-host", version="0.1.0")) as client:22 tools = (await client.list_tools()).tools23 for ticket_id in ("T-0003", "T-0010", "T-0015"):24 ticket = shop.ticket(ticket_id)25 # the longest paragraph of the ticket, which holds the customer's question26 print(f"{ticket_id} asks:", max(ticket.body.split("\n\n"), key=len))27 choice = choose_tool(model, ticket, tools)28 print(f"{ticket_id} tool:", choice.tool or "none")29 if choice.tool is None: # the model answered in words, so there is no call to make30 print(f"{ticket_id} reply:", choice.reply[:72] + "…") # a reply can run long, so the output shows only its opening31 continue32 print(f"{ticket_id} order id:", choice.arguments.get("order_id"))33 result = await client.call_tool(choice.tool, choice.arguments)34 print(f"{ticket_id} order status:", json.loads(result.content[0].text)["status"])353637asyncio.run(main())
python host-picks-a-tool.pyT-0003 asks: Can you tell me when O-1942 will arrive. I need it before the weekend
T-0003 tool: get_order_status
T-0003 order id: O-1942
T-0003 order status: shipped
T-0010 asks: where is my order 2496? its been ages and the tracking page says nothing
T-0010 tool: get_order_status
T-0010 order id: O-2496
T-0010 order status: shipped
T-0015 asks: Do you have enamelled casserole in stock? I'd want two of them
T-0015 tool: none
T-0015 reply: I don't have access to real-time inventory or stock levels for Fernhill …
モデルは、注文が必要な 2 件のチケットでは照会ツールを選び、在庫が必要な 1 件では選ばなかった。チケット T-0003 では、チケットが指す注文に対して get_order_status を選び、ホストの呼び出しはその注文が shipped であることを見つけた。チケット T-0010 は番号だけを示していたが、モデルは説明にもプロンプトにも示されている形式の O-2496 を送った。T-0015 の在庫に関する質問では、モデルはツールを呼び出さず(none)、在庫は確認できないと言葉で述べた。注文の照会しか提供しないサーバーとしては、これが正しい動作である。このチケットが必要とする check_stock ツールは、第 3 章で追加する。
3 件の録画された選択は、ループが動作することを示している。モデルがどれだけの頻度で適切に選ぶかを測るものではない。モデルが読む説明を書くではより多くのチケットで説明を比較し、正しいツールが選ばれる頻度を測るではチケットキュー全体で精度を測る。
このホストは get_order_status を誰にも確認せずに呼び出すが、これは仕様から外れている。仕様は同意の確認をホストに課しており、ホストは「いかなるツールも呼び出す前に、ユーザーの明示的な同意を得なければならない」とされ、MCP 自体はそれを強制できない(仕様の概要)。ツールのページはさらに、ツール呼び出しを拒否できる人間が常にループ内にいるべきである(SHOULD)と付け加えている(ツール)。ここでそれを省くのは、このツールが読み取りしか行わず、サーバーもショップ自身が運用しており、誤った呼び出しでも何も変わらないからである。省くことを勧めるのは、そのような場合に限る。MCP のセキュリティモデルを扱う章の副作用の前に同意を求めるで、同意のステップを追加する。
実践ルール: ホストのプロンプトとモデルの返答の解析は自分のコードの中に置き、ループは実際のモデルではなく録画された返答に対してテストする。SDK のリリースによって録画が無効にならないよう、SDK のオブジェクトではなくモデルの生のテキストを記録し、入力が変わったら再生が失敗するようにする。実際のモデルに切り替えるのは、どの説明とどのモデルを出荷するかを決める測定の実行に限る。
この部分はまだ翻訳されていないため、英語で表示している。
What goes wrong in production
The shop's first server works on one machine. Taken into production, the same few parts fail in a handful of ways, each with a sign to watch for.
Anything on standard output breaks the channel. A library that prints a banner, or a stray print() while debugging, puts a line on the server's standard output that isn't JSON-RPC, which the stdio transport forbids (stdio transport). The client shows it as parse errors or dropped responses, often only on the one code path that prints. The SDK's own logging goes to standard error (mcp/server/mcpserver/utilities/logging.py), so route yours there as well.
The server inherits less than you think. The stdio client passes a short allowlist of variables and nothing else (mcp/client/stdio.py), so a server that works from your shell fails when a host launches it. The sign is the one the client example showed: a generic Error executing tool in the client and a KeyError in the server's standard error. Pass every variable in env=, and fail at startup if one is missing, not at the first call. The shop's server reads its variables inside the tool on purpose, so that the client example could show the late failure; a server you ship should read them once, before it serves.
The server dies mid-call. The specification asks the client to restart a stdio server that exits, and because the protocol is stateless, "any in-flight requests are simply lost and the client can retry them" (stdio transport). mcp.Client restarts nothing at 2.3.0: a call in flight fails with an MCPError that says Connection closed, and the host must open a new Client and retry (mcp/client/stdio.py, mcp/shared/jsonrpc_dispatcher.py). A retried get_order_status is harmless, but a retried refund isn't, which is why the shop's refund tool needs a once-only check on the server (Keep round-trip state tamper-proof). On shutdown the client closes the server's standard input and waits; the SDK allows it 2 seconds before escalating to a signal (mcp/client/stdio.py), so servers should exit promptly on end of input.
A slow start costs time and can change the revision. The SDK's client waits 10 seconds for the answer to server/discover (mcp/client/session.py). A server that loads a large model or opens many connections before reading its first message can miss that window on a cold machine. Auto mode then treats the timeout as a failed probe and sends the old initialize handshake, which has no default time limit (mcp/client/_probe.py). A server built on this SDK that has already answered the late probe rejects initialize with its supported versions, and the client probes once more, so the connection succeeds more than 10 seconds late. A server from another SDK that also answers initialize can settle on a 2025 revision without any error. The sign is client.protocol_version, not a dead server. Do slow setup lazily, or after the server reads its input.
The other side speaks a 2025 revision. Client in auto mode falls back to the old handshake for a 2025-era server. After a fallback the connection speaks the 2025 revision, so none of the pinned revision's features are there (changelog), and client.protocol_version says which revision you got. A server that doesn't support the client's version answers with an error, which Handle a version the server doesn't support shows. When the error comes from someone else's server, the trace from Read the messages on the wire tells you which revision each side sent.
Other languages lag or lead. The MCP documentation lists official SDKs by tier. Tier 1 is TypeScript, Python, C#, Go, Rust and Ruby, and the tiers change over time (SDKs). A host in one language and a server in another can implement a revision's details differently, and the wire is where you settle which one is right.
Working rule: On the machine that launches a stdio server in production, check three things: nothing but JSON-RPC reaches standard output, every variable the server needs is passed explicitly, and the server answers server/discover within 10 seconds of starting. Keep the server's standard error in your logs, because that is where its real errors go.
この章で下した決定
- ショップのデータは一つのシードから生成され、決められた日付で終わる。そのため、本書のすべての例は同じ顧客、注文、チケットを参照する。
- ショップの API は引き続き正本のシステムである。 MCP サーバーは、独自のキーでその API を呼び出す薄いアダプターにすぎない。
- 読み取り専用のツール
get_order_statusを一つだけ用意し、 一つのエンドポイントをラップする。その docstring はモデル向けに書く。 - モデルが対処できる失敗では
ToolErrorを送出する。 それ以外の例外は汎用的なメッセージとしてクライアントに届き、詳細はサーバーの標準エラー出力にだけ残る。 - まず stdio を使う。 使うのは
MCPServer.run()の既定のトランスポートである。Streamable HTTP は Serve over Streamable HTTP で扱う。 mcp.Clientは既定の自動モードで使う。 手動で初期化したClientSessionは使わない。したがって、最初のメッセージは固定されたリビジョンでのserver/discoverになる。- サーバーは
sys.executableと明示的なenv=で起動し、 認証情報は通信路に載せず環境変数で渡す。 - トレースは、実際の stdio サブプロセスに対するリレーから取得する。 プロセス内のクライアントは JSON-RPC を送らないからである。
- ホストループのプロンプトとパースは本書独自のコードであり、 例では Qwen3-4B-Instruct-2507 の録画を再生する。これは CPU 上で動かしたオープンモデルである。
- 録画は、記録された通りのメッセージにだけ応答する。 プロンプト、チケット、ツール一覧のいずれかが変わると、古い応答を返さずに再生が失敗する。
- この章には同意の手順を置かない。 これは仕様からの逸脱であり、ショップ自身が運用するサーバー上の読み取り専用ツールに限って許容する。同意は Ask for consent before side effects で導入する。
この版における本章
第2026.11.14版2026年11月19日時点で例が通過この章の5 例件のうち5件が合格
英語版の書籍(版2026.11.14)から翻訳した。