Streamable HTTP で提供する
読了まで約74 分分、9 節 節の 6 例 例。
本章を読み終えると、次のことができるようになる。店舗の Model Context Protocol サーバーを Streamable HTTP で提供する。各リクエストとレスポンスが運ぶ内容を読み取る。時間のかかる呼び出しから進捗をストリーミングし、その呼び出しをキャンセルする。スティッキーセッションを使わずに、1 つのアドレスの背後でサーバーをレプリカとして動かす。ブラウザが騙されて送ってしまったリクエストを拒否する。本章の内容は、仕様のリビジョン 2026-07-28 と、Python SDK のバージョン 2.3.0、すなわち mcp で成り立つ。
前章までは、すべてのホストが、店舗のサーバーである shop-support をサブプロセスとして起動し、標準入出力(stdio)で通信していた。この方式は、1 人が 1 台のマシンで使う場合には機能する。しかし店舗のサポートチームは、いまや多数のホストからチケットを処理している。サーバーは店舗のネットワーク内から店舗の API に到達できなければならない。さらにチームは、サーバー上で時間のかかるジョブを動かしたいと考えている。それが recount_stock であり、両方の倉庫にあるすべての商品を数え直す。実際の店舗では数分かかる。ホストごとにサブプロセスを立てる方式では、共有することも、スケールさせることも、1 か所から監視することもできない。
多数のホストが共有するサーバーのために、Model Context Protocol(MCP)は 2 つ目のトランスポートとして Streamable HTTP を定めている。サーバーは 1 つの HTTP エンドポイントで待ち受け、クライアントが送る各メッセージはそれぞれ独立した POST となる。これは仕様の Streamable HTTP トランスポートに述べられているとおりである。MCP のそれ以外の部分は変わらない。JSON-RPC メッセージ、すべてのリクエストにある _meta、そして同じツールがそのまま使われる。
examples/lib/ にある 4 つの小さな共有モジュールが本章の準備を担うので、各例では中心となる考え方だけを示す。
lib.http_mcpは、サーバーの例を空いているループバックポートで独立したプロセスとして起動し、固定したリビジョンが求めるヘッダーを付けた手書きのリクエストを送り、以前の例が定義したサーバーオブジェクトを読み込む。lib.wireは、ワイヤ上のメッセージを読むで扱ったトレース出力モジュールである。ここでrecord_httpが加わる。これはサーバーの HTTP アプリをラップし、ヘッダー、本文、ステータス、レスポンス内のすべてのメッセージといった、各やり取りを記録する。lib.recountは、店舗の数え直し処理、その SKU、および商品ごとの 1 回の API 呼び出しを保持する。lib.shared_stateは、複数のサーバープロセスが開く 1 つの SQLite ファイルに状態を保持する。これはスティッキーセッションなしでレプリカを動かすのレプリカのために使う。
ほとんどの例では、サーバーの HTTP アプリを例自身のプロセス内で提供する。そのために、空いているループバックポートでアプリを動かす第 1 章のヘルパーである lib.loopback を通すので、レコーダーはサーバー側を観測できる。最初の例とレプリカの例は例外で、デプロイと同様に、サーバーを別々のプロセスとして動かす。すべては 127.0.0.1 にバインドされる。
この部分はまだ翻訳されていないため、英語で表示している。
Move the server from stdio to HTTP
A server on stdio has exactly one client, the host that launched it. A server on Streamable HTTP has an address, and any client that can reach that address can use it. At the pinned revision that costs the server little, because the protocol keeps no state between requests. The changelog records that the revision removed the initialize handshake and the Mcp-Session-Id header, and that each request carries its own protocol version and client capabilities in _meta. A request over HTTP is therefore self-contained, like a call to the shop's own API: one POST in, one response out.
A server answers each request in one of two forms: a single JSON object (Content-Type: application/json), or a Server-Sent Events stream (text/event-stream) that belongs to that one request. The client must accept both, as the transport specification says. The stream exists so that the server can send notifications, such as progress, before the result, which Stream progress on a long call relies on.
In the Python SDK the change is one argument. MCPServer.run(transport="streamable-http") serves the server under uvicorn, by default on 127.0.0.1, port 8000, at the path /mcp (mcp/server/mcpserver/server.py). On the client side, Client takes a URL where it took StdioServerParameters, and connects with the SDK's Streamable HTTP client (mcp/client/client.py). The shop's server keeps chapter 3's five tools unchanged, and only the last lines of its file change. The port comes from http_mcp.port(), not 8000, so it never collides with anything else.
1"""Serves chapter 3's five tools over Streamable HTTP in a process of its own, then calls one from a client that has only2the endpoint's URL. The point rests on the protocol revision and O-1873 status lines: the client settles on the pinned3revision and gets the order's status back."""4import asyncio5import sys6from urllib.parse import urlsplit78from mcp import Client910from lib import http_mcp, loopback, shop_api, shop_tools1112server = shop_tools.create_server(version="0.6.0") # chapter 3's tools, unchanged131415async def main() -> None:16 with loopback.serve(shop_api.create_app()) as api_url:17 with http_mcp.launch(__file__, env=shop_api.server_env(api_url)) as url: # runs this file again with --serve, as its own process18 async with Client(url) as client: # no handshake: the client needs only the URL19 print("endpoint host:", urlsplit(url).hostname)20 print("endpoint path:", urlsplit(url).path)21 print("protocol revision:", client.protocol_version)22 print("server:", client.server_info.name, client.server_info.version)23 print("tools:", len((await client.list_tools()).tools))24 result = await client.call_tool("get_order_status", {"order_id": "O-1873"})25 print("O-1873 status:", result.structured_content["status"])262728if "--serve" in sys.argv:29 server.run(transport="streamable-http", port=http_mcp.port()) # 127.0.0.1, path /mcp30else:31 asyncio.run(main())
python serve-on-loopback.pyendpoint host: 127.0.0.1
endpoint path: /mcp
protocol revision: 2026-07-28
server: shop-support 0.6.0
tools: 5
O-1873 status: delivered
The client reached the server at the SDK's defaults, 127.0.0.1 at /mcp.
It settled on revision 2026-07-28 and found 5 tools on shop-support 0.6.0. Order O-1873 came back delivered, as it does over stdio. The server process got the shop's API address and key in its environment, as the stdio servers did, and nothing else changed.
The SDK's streamable_http_app() also takes a stateless_http flag, At 2.3.0, the app routes each request by its MCP-Protocol-Version header, and a request at the pinned revision goes to a handler that serves one exchange and never sets Mcp-Session-Id, whatever the flag says. The flag only changes how clients on a 2025 revision are served (mcp/server/streamable_http_manager.py). The older HTTP+SSE transport, with its separate event endpoint, has been deprecated since revision 2025-03-26. Its earliest removal is three months after the specification's feature-lifecycle proposal, SEP-2596, reaches Final (deprecated features). Move from HTTP+SSE to Streamable HTTP ports a server off it.
Working rule: Serve over Streamable HTTP with MCPServer.run(transport="streamable-http") and its loopback default while you develop, and give clients the endpoint's URL. Leave stateless_http alone unless you also serve clients on a 2025 revision, where it decides whether they get sessions. Keep stdio for servers that a host launches for one user, as Choose stdio or Streamable HTTP explains.
この部分はまだ翻訳されていないため、英語で表示している。
Read one HTTP exchange
The client in Move the server from stdio to HTTP hid all of this, but when a call fails behind a proxy or a gateway, the exchange is what you read, so it pays to know what a correct one looks like. At the pinned revision, every POST carries headers that copy parts of its body. MCP-Protocol-Version repeats the version, Mcp-Method the JSON-RPC method, and Mcp-Name the tool, prompt or resource for tools/call, prompts/get and resources/read. The copies exist so that load balancers, gateways and monitoring can route and inspect a request without parsing its body, as the specification's Streamable HTTP transport explains.
The body stays the source of truth. A server MUST reject a request whose headers disagree with its body, with 400 Bad Request and the JSON-RPC error -32020, HeaderMismatch. That rule is what makes the headers safe to route on. A gateway that sends Mcp-Name: check_stock to the stock replicas can trust that the body names check_stock too, because a server would refuse the request otherwise.
Recording one get_order_status call with the SDK's client shows a correct exchange. Two requests the SDK's client never sends, through lib.http_mcp.post, show what the server refuses: a tools/call whose Mcp-Name says check_stock while its body names get_order_status, and a GET.
1"""Records the HTTP exchanges behind one tool call, then sends two requests the SDK's client never would. The point rests2on the request headers and response status lines of the tool call, and on the mismatched and GET lines, which show what3the server refuses."""4import asyncio5import os67import httpx28from mcp import Client910from lib import http_mcp, loopback, shop_api, wire1112SHOWN = ("content-type", "accept", "mcp-protocol-version", "mcp-method", "mcp-name")131415async def main() -> None:16 server = http_mcp.load_server("serve-on-loopback.py") # chapter 3's five tools17 app = wire.record_http(server.streamable_http_app(), log="http.jsonl") # logs each exchange as the app saw it18 with loopback.serve(shop_api.create_app()) as api_url, loopback.serve(app) as base_url:19 os.environ.update(shop_api.server_env(api_url)) # the server runs in this process, so it reads the API address here20 async with Client(base_url + "/mcp") as client:21 await client.call_tool("get_order_status", {"order_id": "O-1873"})22 exchanges = wire.read_http_trace("http.jsonl")23 # the recorder keeps header names in lower case24 print("POSTs:", ", ".join(e["request_headers"]["mcp-method"] for e in exchanges))25 call = next(e for e in exchanges if e["request_headers"]["mcp-method"] == "tools/call")26 for name in SHOWN:27 print(f"request {name}:", call["request_headers"][name])28 print("request _meta keys:", ", ".join(call["request"]["params"]["_meta"]))29 print("response status:", call["status"])30 print("response content-type:", call["response_headers"]["content-type"])31 print("response mcp-session-id:", call["response_headers"].get("mcp-session-id", "none"))3233 # the body names get_order_status, so this Mcp-Name header disagrees with it34 wrong = http_mcp.post(base_url + "/mcp", "tools/call", {"name": "get_order_status",35 "arguments": {"order_id": "O-1873"}}, headers={"Mcp-Name": "check_stock"})36 print("mismatched Mcp-Name status:", wrong.status_code)37 print("mismatched Mcp-Name error:", wrong.json()["error"]["code"], wrong.json()["error"]["message"])38 # a GET marked with the pinned revision, which the app refuses rather than serving its 2025 stream39 stream = httpx2.get(base_url + "/mcp", headers={"MCP-Protocol-Version": http_mcp.VERSION})40 print("GET status:", stream.status_code)41 print("GET allow:", stream.headers["allow"])424344asyncio.run(main())
python trace-an-http-exchange.pyPOSTs: server/discover, tools/call, tools/list
request content-type: application/json
request accept: application/json, text/event-stream
request mcp-protocol-version: 2026-07-28
request mcp-method: tools/call
request mcp-name: get_order_status
request _meta keys: io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientInfo, io.modelcontextprotocol/clientCapabilities
response status: 200
response content-type: application/json
response mcp-session-id: none
mismatched Mcp-Name status: 400
mismatched Mcp-Name error: -32020 mcp-name header does not match the request body's 'name' parameter
GET status: 405
GET allow: POST
The client made three POSTs for that one call: server/discover, tools/call, tools/list. The first asks the server what it supports, since there is no handshake. The last is the SDK's client fetching the tool list after the call, so that it can check the structured result against the tool's output schema (mcp/client/session.py, validate_tool_result). The tools/call POST carried:
MCP-Protocol-Version: 2026-07-28Mcp-Method: tools/callMcp-Name: get_order_statusAccept: application/json, text/event-stream, because the client must take either form of response
Its body's _meta held the same three keys that it holds over stdio: io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientInfo, io.modelcontextprotocol/clientCapabilities. The response came back 200 as application/json, and it set no session header (mcp-session-id: none).
The response was plain JSON because the tool sent nothing before its result. The SDK doesn't commit to an event stream until the handler sends a notification or 15 seconds pass, so a handler that finishes silently inside that window gets a JSON response (mcp/server/_streamable_http_modern.py). That 15-second limit belongs to a detail of that private module and may change between releases.
The server refused the mismatched request before the tool ran, with 400 and error -32020 mcp-name header does not match the request body's 'name' parameter. The SDK's own client recovers from -32020 by fetching the tool list again and resending once, because at the pinned revision a tool can mark parameters with x-mcp-header, which clients copy into Mcp-Param-{Name} headers, and a stale listing gets those headers wrong (mcp/client/client.py, call_tool).
The GET was refused too: 405, with Allow: POST. A server that supports only the pinned revision SHOULD answer GET and DELETE with 405 Method Not Allowed, because that revision has no stream a client opens with GET (the transport specification). The SDK's app also serves the 2025 revisions, and sends a GET without the pinned version in MCP-Protocol-Version to its 2025 handler, which serves it and refuses only a GET marked with the pinned revision, as this one was (mcp/server/streamable_http_manager.py).
Working rule: When an HTTP call fails, read the exchange first: the three routing headers, _meta in the body, the status and the content type. Route in a gateway on Mcp-Method and Mcp-Name if you need to, and never rewrite a body without rewriting its headers to match, because the server will refuse the pair with -32020. On a server that supports only the pinned revision, a 405 means an older client is opening a GET stream; the SDK's app serves those clients instead.
この部分はまだ翻訳されていないため、英語で表示している。
Stream progress on a long call
The exchange in Read one HTTP exchange returned in milliseconds. A call that takes minutes leaves the person at the host seeing nothing, and the host can't tell slow from stuck. Progress is MCP's answer to a long call: the server reports how far it has got while the call runs. A client that wants progress puts a progressToken in the request's _meta. The server MAY then send notifications/progress with that token, each carrying a progress value that MUST increase with every notification, and optionally a total and a message (progress). Over Streamable HTTP, these notifications travel only on the response stream of the request they belong to (Streamable HTTP transport).
In the SDK, a tool reports with await ctx.report_progress(progress, total=..., message=...). A client asks for reports on a call with call_tool(..., progress_callback=...), which also puts the token in _meta. When the caller didn't ask, report_progress does nothing (mcp/server/_streamable_http_modern.py, progress), so a tool can always call it.
The shop's API has an endpoint, POST /stock/{sku}/recount, which recounts one product in both warehouses and takes a few seconds per product in the real shop. recount_stock calls it for each of the shop's 64 SKUs and reports after each one. In the examples, lib.recount asks the API to take 0.02 seconds per product, so a full recount takes a few seconds. The same server runs twice: once with the SDK's default, which can stream, and once with json_response=True, which makes every response a single JSON object.
1"""Runs recount_stock with progress reports, once with the SDK's streaming responses and once with JSON-only responses. The2point rests on the content-type and progress report lines: a JSON-only server drops every report, though the recount still3counts the same units."""4import asyncio5import os67from mcp import Client8from mcp.server.mcpserver import Context, MCPServer9from mcp.types import ToolAnnotations1011from lib import loopback, recount, shop_api, wire1213server = MCPServer("shop-support", version="0.6.0")141516@server.tool(title="Recount stock", annotations=ToolAnnotations(read_only_hint=False, idempotent_hint=True))17async def recount_stock(ctx: Context) -> recount.Recount:18 """Recount every product's stock in both warehouses. Slow: reports progress per product."""19 units = 020 async with recount.api() as api:21 for n, sku in enumerate(recount.SKUS, 1): # counts from 1, so the last report is the total22 units += await recount.one(api, sku) # lib.recount has the API take 0.02 seconds per product unless told otherwise23 await ctx.report_progress(n, total=len(recount.SKUS), message=f"recounted {sku}")24 return recount.Recount(skus=len(recount.SKUS), units=units)252627async def run(mode: str, json_response: bool) -> None:28 # json_response=True sends every response as one JSON object, with no stream for reports to travel on29 app = wire.record_http(server.streamable_http_app(json_response=json_response), log=f"{mode}.jsonl")30 reports = []3132 async def on_progress(progress: float, total: float | None, message: str | None) -> None:33 reports.append((progress, total, message))3435 with loopback.serve(app) as base_url:36 async with Client(base_url + "/mcp") as client:37 result = await client.call_tool("recount_stock", progress_callback=on_progress)38 call = next(e for e in wire.read_http_trace(f"{mode}.jsonl") if e["request"]["method"] == "tools/call")39 print(f"{mode} content-type:", call["response_headers"]["content-type"].split(";")[0])40 print(f"{mode} progress reports:", len(reports))41 print(f"{mode} last report:", "{:g} of {:g}, {}".format(*reports[-1]) if reports else "none")42 print(f"{mode} units counted:", result.structured_content["units"])434445async def main() -> None:46 with loopback.serve(shop_api.create_app()) as api_url:47 os.environ.update(shop_api.server_env(api_url)) # the servers run in this process48 await run("sse", json_response=False)49 await run("json", json_response=True)505152asyncio.run(main())
python progress-on-stock-recount.pysse content-type: text/event-stream
sse progress reports: 64
sse last report: 64 of 64, recounted KG-1064
sse units counted: 6969
json content-type: application/json
json progress reports: 0
json last report: none
json units counted: 6969
With the default, the host saw the recount move. The response came back as text/event-stream, and the client received 64 reports, the last of them 64 of 64, recounted KG-1064. The first progress notification is what committed the response to an event stream, so nobody had to wait out the SDK's 15-second window. The recount counted 6969 units.
With json_response=True, the host got nothing until the end. The response was application/json, and the client received 0 reports. The recount still ran and counted 6969 units, and nothing failed. The SDK's JSON path has nowhere to send a notification, so report_progress returns without sending, and neither side logs it (mcp/server/_streamable_http_modern.py). The specification allows that, because progress is optional for the server. The person at the host would have waited the whole recount with no sign of life.
Streaming also has to survive intermediaries, since a proxy that buffers responses holds progress back until the end. The transport specification says servers SHOULD send X-Accel-Buffering: no on event streams to stop that, and the SDK sends it, with Cache-Control: no-cache, no-transform (mcp/server/_streamable_http_modern.py, _SSE_HEADERS).
Working rule: Report progress from any tool that can run longer than a few seconds, with a total when you know it and a message a person can read. Keep the SDK's default response mode. Use json_response=True only for a server whose every tool is quick, and know that it drops every progress report and every cancellation without telling anyone.
クライアントが不要になった呼び出しをキャンセルする
Stream progress on a long callの再集計は、クライアントが待ち続けていたため最後まで実行された。しかし、ホストが途中で応答を必要としなくなることは多い。ユーザーがチケットを閉じる場合や、ホスト自身の期限が過ぎる場合である。その後も実行され続ける呼び出しは、店舗のAPIを無駄に消費し、ツールが保持しているものを占有し続ける。
Streamable HTTPでは、クライアントはそのリクエストのレスポンスストリームを閉じることでリクエストをキャンセルする。仕様のcancellationパターンは、閉じられたストリームを「キャンセルシグナル」と呼び、サーバーはクライアントの切断をそのリクエストのキャンセルとして扱わなければならず(MUST)、notifications/cancelledメッセージは「必須でも期待されてもいない」と定めている。これは、クライアントが依然としてnotifications/cancelledを送る stdio とも、HTTPクライアントもそれを送っていた2025年版のリビジョンとも異なる。SDKは両方の側を実装している。クライアントは、待機しているタスクがキャンセルされたとき、または読み取りタイムアウトが過ぎたときにPOSTを中断し、それ以外は何も送らない(mcp/client/streamable_http.py)。サーバーは切断を監視し、ハンドラーを実行しているタスクをキャンセルする(mcp/server/_streamable_http_modern.py、watch_disconnect)。
async defのツールの内部では、キャンセルは次のawaitの時点でanyioのキャンセル例外として届く。ツールは停止した位置を記録してよいが、例外を再送出しなければならない。何かをawaitしなければならないクリーンアップには、anyio.move_on_after(5, shield=True)のようなシールドされたスコープが必要である。それがなければ、キャンセルがクリーンアップまでキャンセルしてしまう。通常のdefツールはワーカースレッドで実行され、anyio.from_thread.check_cancelled()を呼び出した場合にだけ停止する。これを呼び出さないツールは最後まで実行され、その結果は破棄される。SDK's cancellation guideとmcp/server/_streamable_http_modern.py(watch_disconnect)が両方の場合を説明している。
この経路を端から端まで確認するため、ホストは5回目の進捗報告の時点で呼び出しをキャンセルする。これは、ホストのユーザーがチケットを閉じたときにホストが行う動作と同じである。ここでは1商品あたり0.1秒かかるため、ストリームが閉じられた時点で、サーバーはまだ6番目の商品の再集計の途中にある。recount_stockは各実行がどのように終わったかを記録し、レコーダーはワイヤー上を流れたものを記録する。
1"""Cancels recount_stock after five progress reports by closing its response stream, and records where the server stopped.2The `server saw` and `tools/call stream` lines are the ones the prose's point rests on: they show where the tool3stopped and how the client ended the call."""4import os56import anyio7from mcp import Client8from mcp.server.mcpserver import Context, MCPServer910from lib import loopback, recount, shop_api, wire1112server = MCPServer("shop-support", version="0.6.0")13runs: list = [] # how a recount ended, and how many recounts it asked the API for141516@server.tool(title="Recount stock")17async def recount_stock(ctx: Context) -> recount.Recount:18 """Recount every product's stock in both warehouses. Slow: reports progress per product."""19 done = units = 020 async with recount.api() as api:21 try:22 for asked, sku in enumerate(recount.SKUS, 1): # counted before each request to the API23 units += await recount.one(api, sku, seconds=0.1) # 0.1 seconds per product keeps the server inside the sixth one24 done += 125 await ctx.report_progress(done, total=len(recount.SKUS), message=f"recounted {sku}")26 except anyio.get_cancelled_exc_class():27 runs.extend([f"cancelled with {done} of {len(recount.SKUS)} recounted", asked])28 raise # always re-raise; cleanup that awaits goes under a shielded scope29 return recount.Recount(skus=done, units=units)303132async def main() -> None:33 app = wire.record_http(server.streamable_http_app(), log="cancel.jsonl")34 with loopback.serve(shop_api.create_app()) as api_url, loopback.serve(app) as base_url:35 os.environ.update(shop_api.server_env(api_url))36 async with Client(base_url + "/mcp") as client:37 with anyio.CancelScope() as scope:38 async def on_progress(progress, total, message):39 if progress >= 5: # the threshold: the host cancels after the fifth report40 scope.cancel() # the host no longer needs the answer41 await client.call_tool("recount_stock", progress_callback=on_progress)42 await anyio.sleep(0.5) # give the server time to see the closed stream43 print(f"server saw: {runs[0]}\nrecounts asked of the API: {runs[1]}")44 exchanges = wire.read_http_trace("cancel.jsonl")45 print("POSTs:", ", ".join(e["request"]["method"] for e in exchanges))46 kinds = [m.get("method", "result") for m in exchanges[-1]["messages"]] # a response has no method, so it counts as the result47 print("tools/call stream:", "finished" if exchanges[-1]["complete"] else "closed by the client")48 print("tools/call messages:", kinds.count("notifications/progress"), "progress,", kinds.count("result"), "result")495051anyio.run(main)
python cancel-the-stock-recount.pyserver saw: cancelled with 5 of 64 recounted
recounts asked of the API: 6
POSTs: server/discover, tools/call
tools/call stream: closed by the client
tools/call messages: 5 progress, 0 result
ツールはストリームが閉じられた時点で停止した。サーバーが認識した呼び出しの状態はcancelled with 5 of 64 recountedであり、ツールが店舗のAPIに依頼した再集計は6件であった。キャンセルはツールが6件目を待っている間に届いたため、残りの商品はAPIに送られなかった。
ワイヤー上のPOSTはserver/discover, tools/callの2回であり、キャンセルメッセージは流れなかった。ツール呼び出しのストリームはclosed by the clientで、運んだのは5 progress, 0 resultであった。キャンセルされた呼び出しについて、クライアントは結果を受け取らず、サーバーも結果を送らない。
これを無効にする要因が2つある。1つ目はjson_response=Trueの場合である。SDKのJSON経路には切断の監視機構がないため、閉じられた接続はハンドラーに届かず、ハンドラーは最後まで実行される(mcp/server/_streamable_http_modern.py)。2つ目は、プロキシがタイムアウトさせた場合など、ほかの理由でストリームが切れた場合で、同じ方法でリクエストがキャンセルされる。固定されたリビジョンではストリームを再開できないため、クライアントは新しいリクエストIDでリクエストを再送しなければならない(MUST)(changelog)。切れたストリームによって中断されうるツールは、2回実行しても安全でなければならない。再集計は、もう一度数えても同じ数になるため安全である。クライアントがいなくなっても存続しなければならない再集計については、Start a task instead of waitingがそれをタスクに移す。
タイムアウトはキャンセルの上に位置する。cancellationパターンは、送信者が各リクエストにタイムアウトを設定するべきであり(SHOULD)、進捗が届いたときにそれをリセットしてよく(MAY)、常に最大値を強制するべきである(SHOULD)と定めている。Client(read_timeout_seconds=...)と、call_toolの同じ引数がこの上限を与え、時間切れになるとストリームが閉じられて呼び出しがキャンセルされる(mcp/client/streamable_http.py)。
実践ルール: Streamable HTTPでの呼び出しは、それをawaitしているタスクをキャンセルするか、タイムアウトによってキャンセルし、ストリームを閉じる処理はSDKに任せる。長時間動くツールはasync defで書き、キャンセルを再送出し、awaitを伴うクリーンアップはシールドされたスコープの下に置く。長く実行されるツールはすべて再試行しても安全にする。ストリームが切れると呼び出しが失われ、クライアントがそれを再送するからである。
スティッキーセッションなしでレプリカを動かす
ここまでのすべての例は、クライアントが不要になった呼び出しを取り消すで扱った取り消された再集計を含めて、サーバープロセスを1つだけ動かしていた。サポートチームには複数のプロセスが必要である。再起動や遅い再集計があっても、すべてのホストが止まらないようにするためである。2つのレプリカの前に置いたロードバランサーは、各リクエストを任意の送り先へ振り分ける。2025年版のセッションでは、ロードバランサーはスティッキーセッションを使う必要があった。これは、同じ Mcp-Session-Id を持つすべてのリクエストを、そのセッションを保持するレプリカへ送る方式である。本書が対象とする固定リビジョンにはセッションがないため、どのレプリカもどのリクエストでも処理できる。呼び出しをまたいで状態を必要とするサーバーは、代わりに明示的なハンドルを発行し、クライアントはそれを通常の引数として返す(changelog)。
プロトコルが状態を持たないからといって、アプリケーションも状態を持たないわけではない。ショップのサーバーは、2つ目のレプリカからは見えない3種類の状態を保持している。
requestStateを封印する鍵。 結果の代わりに入力要求を返すの返金確認は、封印されたrequestStateをクライアントへ送り、再試行でそれを開く。既定ではMCPServerは、各プロセスが起動時に作る鍵で封印する。またその状態は、サーバー名を宛先(audience)として指定する(mcp/server/request_state.py)。- ツールが発行するハンドル。 第3章の見積もりストアは、各
quote_idを、それを作ったプロセスのメモリに保持する。これは第3章の本番で何がうまくいかなくなるかで警告したとおりである。 - 回答済みの確認の記録。 往復する状態を改ざん不能に保つの
confirmations.OnceOnlyは、回答済みのrequestStateを1つのプロセスのメモリに記憶する。
レプリカaで要求し、レプリカbで確認した1件の返金は、この3種類すべての状態に触れる。第5章の返金サーバーを2つのレプリカで動かして確かめる。各レプリカは別々のポートで動くプロセスで、背後には共通のショップAPIが1つある。lib.http_mcp.load_server は refund-asks-to-confirm.py が定義するサーバーを読み込み、各レプリカはそれをHTTP上で動かす。クライアントは各レプリカに1つずつ接続し、どちらも注文 O-1873 を読む。次にレプリカa側のクライアントが、注文 O-2289 の返金を見積もる。この金額はポリシーの上限を超えているため、レプリカaは確認を求める。サポートリーダーの承認を添えた再試行は、ロードバランサーならそう送りかねないとおり、レプリカbへ届く。この一連の手順を3回実行し、そのたびに1種類ずつ状態を直す。
- 各レプリカが自分の鍵を作る。
- 両レプリカが
SHOP_REQUEST_STATE_KEYから同じ鍵を読む。confirmations.state_security()を通して読み込む。 - 両レプリカが、見積もりと回答済みの確認も1つの共有ストアに保持する。これは
SHOP_STATE_STOREが指すSQLiteファイルである。その後、クライアントは同じ回答をもう一度、レプリカaへ送る。
共有ストアは lib.shared_state である。その SharedMap と SharedSet は、同じマシン上のすべてのプロセスが開くSQLiteファイルにエントリを保持する。それぞれが隣のファイルでロックを取るため、あるレプリカの確認してから書き込む処理が、別のレプリカの処理と入り混じることはない。shop_tools.create_server(quotes=...) と confirmations.OnceOnly(seen=...) はこの種のコンテナを受け取り、与えられなければプロセスのメモリにフォールバックする。そのため、第3章と第5章はこれまでどおり動く。行にはpickleではなくJSONを格納し、見積もりの有効期限は壁時計の時刻として保存する。単調増加する期限は別のホストでは意味を持たないからである。SQLiteファイルが届くのは1台のマシン上のプロセスだけである。本番のデプロイでは、同じ2つのテーブルを、レプリカが共有するデータベースに置く。
1"""Runs two replicas of chapter 5's refund server through three kinds of shared state, and replays one confirmation across them.2The point rests on the retry and replay lines: each shared kind of state removes one way the second replica fails."""3import asyncio4import re5import sys6import tempfile78from mcp import Client, MCPError910from lib import confirmations, http_mcp, loopback, shared_state, shop_api1112SHARED_KEY = "chapter-6-test-key-not-a-secret-0123456789" # at least 32 bytes; a deployment reads its own13YES = {"action": "accept", "content": {"release": True}} # the support lead's answer, as on the wire141516async def outcome(call) -> str: # refund status, tool error or protocol error17 try:18 result = await call19 except MCPError as error:20 return f"error {error.error.code} {error.error.message}"21 # keeps only the error's first sentence, which names the cause22 text = result.content[0].text.split(". ")[0] if result.is_error else result.structured_content["status"]23 return re.sub(r"Q-[0-9a-f]{10}", "Q-…", text) # quote IDs are random242526async def refund_across(label: str, env: dict) -> None:27 with http_mcp.launch(__file__, env=env) as url_a, http_mcp.launch(__file__, env=env) as url_b:28 async with Client(url_a, elicitation_callback=confirmations.say_yes) as on_a, \29 Client(url_b, elicitation_callback=confirmations.say_yes) as on_b:30 print(f"{label} reads on a and b:", ", ".join([(await c.call_tool("get_order_status", {31 "order_id": "O-1873"})).structured_content["status"] for c in (on_a, on_b)]))32 quoted = await on_a.call_tool("quote_refund", {"order_id": "O-2289"}) # above the policy's limit33 args = {"quote_id": quoted.structured_content["quote_id"]}34 # allow_input_required lets the server answer with an input request, not a result, when it needs confirmation35 first = await on_a.session.call_tool("issue_refund", args, allow_input_required=True) # asks on a36 # the answer goes back with the request state the server sealed, which the retry must open37 answer = dict(input_responses={"confirm": YES}, request_state=first.request_state)38 print(f"{label} retry on b:", await outcome(on_b.session.call_tool("issue_refund", args, **answer)))39 if shared_state.STORE_VARIABLE in env: # only the shared-store run sends the answer a second time40 print(f"{label} replay on a:", await outcome(on_a.session.call_tool("issue_refund", args, **answer)))414243async def main() -> None:44 with loopback.serve(shop_api.create_app()) as api_url, tempfile.TemporaryDirectory() as shared:45 env = shop_api.server_env(api_url) # one shop API behind both replicas46 keyed = {**env, confirmations.STATE_KEY_VARIABLE: SHARED_KEY}47 await refund_across("own keys", env) # each process makes its own key48 await refund_across("shared key", keyed)49 await refund_across("shared store", {**keyed, shared_state.STORE_VARIABLE: f"{shared}/state.db"})505152if "--serve" in sys.argv: # one replica: chapter 5's server, over HTTP53 http_mcp.load_server("refund-asks-to-confirm.py").run(transport="streamable-http", port=http_mcp.port())54else:55 asyncio.run(main())
python two-replicas-one-client.pyown keys reads on a and b: delivered, delivered
own keys retry on b: error -32602 Invalid or expired requestState
shared key reads on a and b: delivered, delivered
shared key retry on b: Error executing tool issue_refund: There is no quote Q-…
shared store reads on a and b: delivered, delivered
shared store retry on b: requested
shared store replay on a: Error executing tool issue_refund: Refund R-0113 was already confirmed
各自の鍵では、どちらの読み取りも成功した(delivered, delivered)が、再試行は失敗した。error -32602 Invalid or expired requestState である。レプリカbはレプリカaが封印した状態を開けなかったため、SDKはツールが実行される前に再試行を拒否した。
鍵を共有すると、レプリカbは状態を開けたが、呼び出しは1段階先のツールの内部で失敗した。「Error executing tool issue_refund: There is no quote Q-…」と表示された。見積もりはレプリカaのメモリにあったのである。共有した鍵は1種類目の状態を直し、2種類目の状態を露呈させた。
共有ストアも使うと、レプリカbでの再試行は返金を実行し、そのステータスは requested になった。レプリカbは共有ストアでレプリカaの見積もりを見つけ、それとともにショップのAPIがすでに保持していた返金も見つけた。そのため、2件目の返金を求めることなく、その返金を実行した。同じ回答をレプリカaにもう一度送ると、拒否された。「Error executing tool issue_refund: Refund R-0113 was already confirmed」と表示された。レプリカaは最初の回答を見ていなかったのである。共有された記録がなければ、レプリカa自身の OnceOnly の検査は通ってしまい、ショップのAPIにもう一度返金の実行を求めていただろう。止めたのは、もう保持していない返金に対するAPIの409だけだったはずである。返金は、スティッキーセッションなしで、2つのレプリカをまたいで1回だけ完了した。仕様は、不透明で有効期限のあるハンドルを求めている(tools)。その状態をどこに置くかはサーバーの選択だが、レプリカがある場合は、すべてのレプリカが届く場所でなければならない。
まだ一部の状態を移していないデプロイは、1回のHTTPのやり取りを読むで扱ったルーティングヘッダーによる応急策を使える。これはスティッキーセッションではない。ゲートウェイは、その状態に依存するツールを Mcp-Name が指しているリクエストをすべて1つのレプリカへ送り、残りは分散させる。subscriptions/listen のストリームは1つのレプリカが保持し、SDKはメモリ内のバスしか提供しない。そのため、別のレプリカで発行されたイベントはそのストリームに届かない(deploy and scale、mcp/server/subscriptions.py、InMemorySubscriptionBus)。
実践ルール: スティッキーセッションを使わずにレプリカを動かし、すべてのレプリカに、同じサーバー名と、シークレットストアから注入した同じ requestState の鍵を与える。2つ目のレプリカを追加する前に、ハンドル、一度きりの記録、購読など、ツールがメモリ上に保持しているすべての状態を一覧にし、それぞれをすべてのレプリカが届くストレージへ移す。移し終えるまでは、それに依存するツールを Mcp-Name によって単一のレプリカへルーティングする。
この部分はまだ翻訳されていないため、英語で表示している。
Reject requests from other origins
The replicas in Run replicas without sticky sessions listen on 127.0.0.1, which feels private. It isn't. Any web page open in a browser on the same machine can send requests to a loopback port. With DNS rebinding, an attacker's domain can be made to resolve to 127.0.0.1 after the page loads, so the browser treats the local server as part of the attacker's site. The specification's tutorial on local servers says that binding to 127.0.0.1 "is not an authentication boundary" (local server security).
The browser hands the server its defence. It sends the page's Origin with each request it makes on the page's behalf. The Streamable HTTP transport in the specification says servers MUST validate Origin on every incoming connection, MUST answer 403 when it is present and invalid, and SHOULD bind to 127.0.0.1 when they run locally. Checking Host as well stops the rebinding case, where the browser names the attacker's domain.
The SDK arms both checks by default. When the app's host is a loopback name and you pass no transport_security, it allows only Host values 127.0.0.1:*, localhost:* and [::1]:*, and only Origin values with the same names under http:// (mcp/server/mcpserver/server.py). Four requests probe that default: tools/list with no Origin, with the server's own origin, with http://attacker.example, and with a Host of fernhill.example. It then builds the same app with host="0.0.0.0", the usual container setting, and sends the two foreign requests again. That app binds to 127.0.0.1, since only the setting is under test.
1"""Sends tools/list to the shop's server with foreign Origin and Host headers, first with the SDK's loopback default and then2with host="0.0.0.0". The point rests on the foreign Origin and foreign Host lines: the default answers 403 and 421, and the30.0.0.0 app answers 200 to both."""4from urllib.parse import urlsplit56from lib import http_mcp, loopback78server = http_mcp.load_server("serve-on-loopback.py") # chapter 3's five tools9FOREIGN = "http://attacker.example" # a page in the user's browser, on another site101112def probe(label: str, url: str, headers: dict[str, str]) -> None:13 response = http_mcp.post(url, "tools/list", headers=headers)14 print(f"{label}:", response.status_code, response.text if response.status_code != 200 else "tools listed")151617def main() -> None:18 with loopback.serve(server.streamable_http_app()) as base_url: # host defaults to 127.0.0.119 # the server's own origin: loopback and the port it listens on, as a page served from it would send20 url, own = base_url + "/mcp", f"http://127.0.0.1:{urlsplit(base_url).port}"21 probe("no Origin", url, {})22 probe("own Origin", url, {"Origin": own})23 probe("foreign Origin", url, {"Origin": FOREIGN})24 probe("foreign Host", url, {"Host": "fernhill.example"}) # a Host the loopback allowlist does not name25 with loopback.serve(server.streamable_http_app(host="0.0.0.0")) as base_url: # still bound to 127.0.0.126 probe("0.0.0.0 app, foreign Origin", base_url + "/mcp", {"Origin": FOREIGN})27 probe("0.0.0.0 app, foreign Host", base_url + "/mcp", {"Host": "fernhill.example"})282930main()
python reject-a-foreign-origin.pyno Origin: 200 tools listed
own Origin: 200 tools listed
foreign Origin: 403 Invalid Origin header
foreign Host: 421 Invalid Host header
0.0.0.0 app, foreign Origin: 200 tools listed
0.0.0.0 app, foreign Host: 200 tools listed
The loopback default turned away both foreign requests. A request with no Origin got 200 tools listed, and so did the server's own origin: 200 tools listed. The foreign origin got 403 Invalid Origin header, and the foreign host got 421 Invalid Host header, both as plain text rather than JSON-RPC (mcp/server/transport_security.py). The specification allows a body of either kind with the 403.
Built with host="0.0.0.0", the app let both through: 200 tools listed and 200 tools listed. A host the SDK doesn't recognise as loopback only stops it arming the default, and with no settings passed, the check is off (mcp/server/transport_security.py). That falls short of the specification's MUST, and nothing in the logs says so.
The request with no Origin shows what this defence covers. Browsers send Origin, while scripts, command-line tools and other servers don't, and the SDK lets a request without one through. Origin validation protects a server from web pages. It does nothing against a program that can reach the port, which is what authorization is for (Authorize clients with OAuth).
Working rule: Keep the SDK's loopback default on a developer's machine. When you deploy on any other address, pass transport_security=TransportSecuritySettings(allowed_hosts=[...], allowed_origins=[...]) with the names your server answers to, such as mcp.fernhill.example, and never rely on the default. Treat Origin validation as protection against browsers only, and put authorization in front of every server that anything but its own host can reach.
stdio と Streamable HTTP を選ぶ
ここまでの各節では、ショップのサーバを Streamable HTTP へ移行した。キャンセル処理からレプリカ、オリジンの検査に至るまで、この移行に要した作業は、移行の対価である。stdio にはそのどれも必要ない。仕様におけるstdio トランスポートでは、クライアントがサーバをサブプロセスとして起動し、その標準入力と標準出力でメッセージをやり取りする。ホストがプロセスを所有するので、ほかのものはそのプロセスに到達できない。サーバが引き継ぐのはホストが渡したものだけであり、ホストが必要とする間だけ存続する。
二つのトランスポートは、誰がサーバを実行するか、そしてそこから何が決まるかという点で異なる。
| stdio | Streamable HTTP | |
|---|---|---|
| 起動する主体 | ホスト(ホストごとに 1 つ) | あなた(複数のホストに対して 1 回) |
| 到達できる相手 | 自身のホスト | そのアドレスに到達できるすべてのもの |
| キャンセル | notifications/cancelled |
レスポンスストリームを閉じる |
| ログ | 標準エラー出力 | サーバのログ |
| 認証情報 | ホストの環境 | OAuth アクセストークン |
| スケールの方法 | ホストごとに 1 プロセス | ロードバランサの背後のレプリカ |
1 人のユーザーのためにそのユーザーのマシン上で動作するサーバ、たとえばローカルファイルを読むサーバやユーザー自身の認証情報を使うサーバ、および開発用途には、stdio を推奨する。複数のホストが 1 つのサーバを共有する場合、ホストが到達できないシステムの近くでサーバを動かす必要がある場合(たとえばネットワーク内にあるショップの API)、あるいはサーバをサービスとしてデプロイし、スケールさせ、監視する必要がある場合には、Streamable HTTP を推奨する。その場合は、最初から認可を計画しておくこと。アドレス上のサーバは、誰が呼び出しているかを知る必要があるからである(リソースから認可サーバを見つける)。
ホストが多数ある場合、ショップの API をサポートチームのノート PC から到達可能にすべきではない。そのため、サーバは Streamable HTTP へ移行する。本書では、ホストとサーバが 1 つずつあれば足りる例には stdio を使い続ける。サブプロセスが、サーバを動かす最も手短な方法だからである。
実践ルール: サーバが 1 人のユーザーのためにそのユーザーのマシン上で動作する場合は、stdio で提供する。複数のホストに対応する場合、ホストが到達できないシステムを守る場合、あるいはスケールが必要な場合は、Streamable HTTP で提供し、最初の外部ユーザーを迎える前にオリジンの検査と認可を備える。同じサーバコードで両方に対応できるので、サーバごとではなくデプロイごとに選ぶ。
本番環境で起こる問題
ショップのサーバーは、ループバック上でクライアントが一つだけの場合には動作する。実際のプロキシ、ロードバランサー、クライアントの背後に置くと、ループバックでは現れない形で障害が起きる。以下にそれぞれの症状を示す。
すべてのリクエストが 421 になる。 デプロイ時に SDK のループバック用許可リストを残したままにしており、リクエストはサーバーの公開名を Host に付けて届く。兆候は、すべての呼び出しで平文の Invalid Host header が返ることであり、ツールのログには何も残らない。サーバーが応答する名前を指定して allowed_hosts を渡す(他のオリジンからのリクエストを拒否する)。
誰も決めていないのにチェックが無効になる。 コンテナで一般的な設定である host="0.0.0.0" でサーバーを起動すると、あらゆる Host と Origin を受け入れる(mcp/server/transport_security.py)。失敗は何も起きないため、兆候は reject-a-foreign-origin のようなプローブが 200 を受け取ることだけである。このプローブを各デプロイに対して実行し、transport_security を明示的に設定する。
進捗がまとめて届く。 レスポンスをバッファリングするプロキシは、結果が出るまですべての通知を保留する。SDK は仕様がこの目的のために定めるヘッダー X-Accel-Buffering: no を送るが、これを無視するプロキシや CDN には、それぞれ独自の設定がある。進捗バーが何もない状態から一気に完了へ飛ぶ場合は、これが原因である。進捗はループバックではなく、実際の経路を通してテストする。
長い呼び出しが切りのよい秒数で終了する。 プロキシやロードバランサーは、一定時間が過ぎるとアイドル状態の接続を閉じる。ストリームが開いた後、SDK は他のイベントがないまま 15 秒が経過するごとに : ping コメントを送り、接続を使用中に保つ(mcp/server/_streamable_http_modern.py)。アイドル上限がそれより短いプロキシや、リクエストごとの合計時間に上限があるプロキシは、それでもストリームを切断し、その切断によってツールはキャンセルされる。同じ継続時間にキャンセルが集中していないかを確認する。MCP のパスについてプロキシの上限を引き上げるか、処理をタスクに移す(待たずにタスクを開始する)。
再試行で処理が二度実行される。 壊れたストリームは再開できず、クライアントは新しい ID でリクエストを再送する(変更履歴)。繰り返しに対して安全でないツールは、副作用を二度実行してしまう。ショップの issue_refund は、見積もりに対する返金が一度しか行われないため安全であり、共有ストアがあれば、どのレプリカでもこれが成り立つ。副作用を持つすべてのツールに、二度目の呼び出しが一度目の結果を返すようなハンドルまたはキーを与え、その記録をすべてのレプリカから見える場所に置く。
json_response=True は進捗とキャンセルを無効にする。 イベントストリームを好まないゲートウェイの背後では、これに頼りたくなるが、SDK は警告を出さない(長い呼び出しの進捗をストリームする)。症状として、長い呼び出しが何も報告せず、クライアントが去った後も実行を続ける。
ゲートウェイがボディを書き換える。 JSON ボディは編集するがヘッダーは編集しないゲートウェイは、リクエストを -32020、HeaderMismatch で失敗させる。SDK のクライアントはツール一覧を取得した後に一度だけ再送するため、tools/call リクエストが二重に現れ、サーバーのレスポンスに -32020 が絶え間なく少量ずつ現れる。
2025 年版のクライアントにはセッションが必要である。 同じアプリが、旧来のハンドシェイクによって 2025 年当時のクライアントにも対応する。既定ではそれらのセッションを一つのプロセスのメモリに保持するため、スティッキールーティングが必要になる(mcp/server/streamable_http_manager.py)。リクエストが別のレプリカに届いた後に、それらのクライアントに限って "Session not found" を伴う 404 が出ないかを監視する(mcp/server/streamable_http_manager.py)。ロードバランサーの背後でそれらに対応する場合は stateless_http=True を設定し、その代償を理解しておく。それらのクライアントはキャンセルを失い、クライアントが何をしてもハンドラーは最後まで実行される(キャンセル)。また、サンプリングやエリシテーションなど、サーバーからクライアントへのリクエストも失う(デプロイとスケール)。移行期間中に新旧のクライアントへ対応するでは、このトレードオフを検討する。
大きなリクエストが 413 で失敗する。 SDK は既定でリクエストボディを 4 MiB に制限する(mcp/server/transport_security.py)。ドキュメントを引数に取るツールは、真っ先にこの制限に達する。そのサーバーについて max_request_body_size を引き上げるか、ドキュメントのバイト列の代わりにドキュメントへの参照を渡す。
実践ルール: ショップのサーバーをあるアドレスで受け付け開始する前に、実際のプロキシ経路を通して四つの点をテストする。外部の Origin が 403 になること、呼び出しの実行中に進捗が届くこと、プロキシのアイドル上限より長い呼び出しが維持されること、呼び出しのストリームを閉じるとツールが停止することである。その後、421、403、-32020 をクライアント別に、キャンセルを経過時間別に監視する。
この章で下した決定
- ショップのサーバーは、サポートチームのホスト向けに Streamable HTTP へ移行する。 第3章のツールは変更しない。1つのホストと1つのサーバーだけの例では、stdio を引き続き使う。
MCPServer.run(transport="streamable-http")は SDK の既定値のまま用いる。 すなわち、ループバック、パス/mcp、そしてストリーミングを行う既定の応答モードである。stateless_httpは、ロードバランサーの背後で 2025 年当時のクライアントに対応する必要が生じるまで未設定のままとし、対応する場合はそのクライアントのキャンセルが失われる。json_response=Trueは使用しない。 進捗通知とキャンセルが失われるためである。recount_stockは、製品ごとの処理が終わるたびに、合計数とメッセージを添えて進捗を報告する。 2回実行しても安全である。- キャンセルとは、ストリームが閉じられることである。 長時間かかるツールは
async defとし、キャンセルを再度送出し、await するクリーンアップはシールドする。 - レプリカは、サーバー名と
requestStateのキーをSHOP_REQUEST_STATE_KEYによって共有する。 見積もりと応答済みの確認は、共有ストアSHOP_STATE_STOREを通じて共有する。返金を含むすべてのリクエストは、どのレプリカでも実行できる。例で用いるストアは、JSON の行を収めた SQLite ファイルで、有効期限は実時間で判定する。実際のデプロイでは、レプリカが共有するデータベースを用いる。 - Origin と Host の検査は有効のままにする。 ループバック以外のアドレスでは、
transport_securityにサーバーの名前を明示的に列挙する。ブラウザ以外の呼び出し元を排除するのは Origin ではなく認可である。 - ゲートウェイは
Mcp-MethodとMcp-Nameに基づいてルーティングしてよい。 ヘッダーが本文と食い違うリクエストはサーバーが拒否するためである。本文を書き換えるゲートウェイはない。 - HTTP のトレースは
lib.wire.record_httpから取得し、手書きのリクエストはlib.http_mcp.postから送る。 これは、SDK のクライアントでは決して起こらないエラーを示すためだけに用いる。 - 例ではレプリカを別々のプロセスとして実行する。 デプロイと同様に、各レプリカが独自のメモリと独自のキーを持つようにするためである。
この版における本章
第2026.11.14版2026年11月19日時点で例が通過この章の6 例件のうち6件が合格
英語版の書籍(版2026.11.14)から翻訳した。