Streamable HTTP로 서비스하기
읽는 데 약 63분분 걸린다, 9절에 6개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.14판을 번역한 것이다. 원문 읽기
이 장을 마치면 상점의 Model Context Protocol 서버를 Streamable HTTP로 서비스하고, 각 요청과 응답에 무엇이 담기는지 읽고, 오래 걸리는 호출의 진행 상황을 스트리밍하고 그 호출을 취소하고, 스티키 세션 없이 하나의 주소 뒤에서 서버를 복제본으로 실행하고, 브라우저가 속아서 보낸 요청을 거부할 수 있다. 이 장의 내용은 명세의 2026-07-28 리비전과 Python SDK인 mcp의 2.3.0 버전에서 유효하다.
앞선 장까지는 모든 호스트가 상점의 서버인 shop-support을 하위 프로세스로 실행하고 stdio로 통신했다. 이 방식은 한 사람이 한 대의 컴퓨터에서 쓸 때는 동작한다. 그러나 상점의 지원 팀은 이제 여러 호스트에서 티켓을 처리한다. 서버는 상점 네트워크 안에서 상점의 API에 접근해야 한다. 팀은 서버에서 느린 작업도 실행하려 한다. 그 작업이 recount_stock이며, 두 창고의 모든 상품을 다시 세는 이 작업은 실제 상점에서는 몇 분이 걸린다. 호스트마다 하위 프로세스를 두는 방식으로는 서버를 공유하거나, 확장하거나, 한곳에서 지켜볼 수 없다.
많은 호스트가 공유하는 서버를 위해 Model Context Protocol(MCP)은 두 번째 전송 방식인 Streamable HTTP를 정의한다. 서버는 하나의 HTTP 엔드포인트에서 요청을 받고, 클라이언트가 보내는 각 메시지는 그 자체로 하나의 POST 요청이다. 이는 명세의 Streamable HTTP 전송에 설명되어 있다. MCP의 나머지는 그대로다. JSON-RPC 메시지, 모든 요청의 _meta, 그리고 같은 도구들이 그대로 쓰인다.
examples/lib/에 있는 작은 공유 모듈 네 개가 이 장의 준비 작업을 맡으므로, 각 예제는 핵심 아이디어만 보여 준다.
lib.http_mcp은 서버 예제를 빈 루프백 포트에서 별도의 프로세스로 시작하고, 고정된 리비전이 요구하는 헤더를 붙여 직접 작성한 요청을 보내며, 앞선 예제가 정의한 서버 객체를 불러온다.- 전송 중인 메시지 읽기의 추적 출력기인
lib.wire에는record_http이 추가된다. 이 함수는 서버의 HTTP 앱을 감싸서 헤더, 본문, 상태, 응답에 담긴 모든 메시지 등 각 교환을 기록한다. lib.recount은 상점의 재고 재계산, SKU, 상품별 API 호출 하나를 담고 있다.lib.shared_state은 여러 서버 프로세스가 여는 하나의 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.
HTTP 교환 하나 읽기
stdio에서 HTTP로 서버 옮기기의 클라이언트는 이 모든 과정을 감췄지만, 프록시나 게이트웨이 뒤에서 호출이 실패하면 읽어야 하는 것은 바로 이 교환이다. 따라서 올바른 교환이 어떤 모습인지 알아 두면 도움이 된다. 고정된 리비전에서는 모든 POST가 본문의 일부를 복사한 헤더를 싣는다. MCP-Protocol-Version는 버전을 반복하고, Mcp-Method는 JSON-RPC 메서드를 반복하며, Mcp-Name는 tools/call, prompts/get, resources/read에서 도구, 프롬프트 또는 리소스를 반복한다. 이 사본이 있는 이유는 로드 밸런서, 게이트웨이, 모니터링이 본문을 파싱하지 않고도 요청을 라우팅하고 검사할 수 있게 하기 위해서이며, 명세의 Streamable HTTP 전송이 이를 설명한다.
본문은 여전히 기준이 되는 정보다. 서버는 헤더가 본문과 일치하지 않는 요청을 반드시 거부해야 하며, 이때 400 Bad Request와 JSON-RPC 오류 -32020, HeaderMismatch를 사용한다. 이 규칙 덕분에 헤더를 기준으로 라우팅해도 안전하다. Mcp-Name: check_stock 요청을 재고 복제본으로 보내는 게이트웨이는 본문도 check_stock를 가리킨다고 신뢰할 수 있다. 그렇지 않으면 서버가 요청을 거부하기 때문이다.
SDK 클라이언트로 get_order_status 호출 하나를 기록하면 올바른 교환을 볼 수 있다. SDK 클라이언트가 결코 보내지 않는 요청 두 개를 lib.http_mcp.post로 보내면 서버가 무엇을 거부하는지 알 수 있다. 하나는 tools/call 요청으로, Mcp-Name는 check_stock인데 본문은 get_order_status를 가리킨다. 다른 하나는 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
클라이언트는 그 호출 하나에 POST를 세 번 보냈다. server/discover, tools/call, tools/list이다. 첫 번째는 핸드셰이크가 없으므로 서버에 무엇을 지원하는지 묻는 요청이다. 마지막은 SDK 클라이언트가 호출 후에 도구 목록을 가져오는 요청으로, 구조화된 결과를 도구의 출력 스키마와 대조해 검사하기 위한 것이다(mcp/client/session.py, validate_tool_result). tools/call POST에는 다음이 실려 있었다.
MCP-Protocol-Version: 2026-07-28Mcp-Method: tools/callMcp-Name: get_order_statusAccept: application/json, text/event-stream. 클라이언트는 두 가지 형태의 응답을 모두 받아들여야 하기 때문이다
본문의 _meta에는 stdio에서와 같은 세 개의 키가 들어 있었다. io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientInfo, io.modelcontextprotocol/clientCapabilities이다. 응답은 200 상태로 application/json 형식으로 돌아왔고, 세션 헤더는 설정하지 않았다(mcp-session-id: none).
응답이 일반 JSON이었던 것은 도구가 결과 전에 아무것도 보내지 않았기 때문이다. SDK는 핸들러가 알림을 보내거나 15초가 지날 때까지는 이벤트 스트림을 확정하지 않는다. 따라서 그 시간 안에 아무것도 보내지 않고 끝나는 핸들러는 JSON 응답을 받는다(mcp/server/_streamable_http_modern.py). 이 15초 제한은 그 비공개 모듈의 세부 구현에 속하므로 릴리스 사이에 바뀔 수 있다.
서버는 도구가 실행되기 전에 불일치한 요청을 거부했으며, 상태는 400, 오류는 -32020 mcp-name header does not match the request body's 'name' parameter였다. SDK 자체 클라이언트는 -32020에서 도구 목록을 다시 가져와 한 번 다시 보내는 방식으로 복구한다. 고정된 버전의 리비전에서는 도구가 매개변수에 x-mcp-header를 표시할 수 있고 클라이언트가 이를 Mcp-Param-{Name} 헤더로 복사하는데, 오래된 목록을 쓰면 이 헤더가 잘못되기 때문이다(mcp/client/client.py, call_tool).
GET도 거부되었다. 405이며 Allow: POST가 함께 왔다. 고정된 리비전만 지원하는 서버는 GET과 DELETE에 405 Method Not Allowed로 응답해야 한다(SHOULD). 그 리비전에는 클라이언트가 GET으로 여는 스트림이 없기 때문이다(전송 명세). SDK의 앱은 2025 리비전도 함께 제공하며, MCP-Protocol-Version에 고정된 버전이 없는 GET은 2025 핸들러로 보낸다. 이 핸들러는 그 GET을 처리하고, 이번 요청처럼 고정된 리비전이 표시된 GET만 거부한다(mcp/server/streamable_http_manager.py).
작업 규칙: HTTP 호출이 실패하면 먼저 교환을 읽는다. 세 개의 라우팅 헤더, 본문의 _meta, 상태, 콘텐츠 유형을 확인한다. 필요하다면 게이트웨이에서 Mcp-Method와 Mcp-Name를 기준으로 라우팅하되, 본문을 다시 쓸 때는 반드시 헤더도 그에 맞게 고쳐 쓴다. 서버가 그 쌍을 -32020으로 거부하기 때문이다. 고정된 리비전만 지원하는 서버에서 405는 더 오래된 클라이언트가 GET 스트림을 열고 있다는 뜻이며, 그런 클라이언트는 SDK의 앱이 대신 처리한다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
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.
클라이언트에 더 이상 필요 없는 호출 취소하기
긴 호출의 진행 상황 스트리밍의 재고 재계산은 클라이언트가 기다리고 있었기 때문에 끝까지 실행되었다. 그러나 호스트가 도중에 응답을 더 이상 필요로 하지 않게 되는 경우가 흔하다. 사용자가 티켓을 닫거나 호스트 자체의 기한이 지나는 경우이다. 그 뒤에도 계속 실행되는 호출은 상점의 API를 낭비하고, 도구가 붙들고 있는 자원도 계속 점유한다.
Streamable HTTP에서 클라이언트는 해당 요청의 응답 스트림을 닫아 요청을 취소한다. 명세의 취소 패턴은 닫힌 스트림을 "취소 신호"라고 부르고, 서버가 클라이언트의 연결 끊김을 해당 요청의 취소로 처리해야 한다(MUST)고 하며, notifications/cancelled 메시지는 "필요하지도 기대되지도" 않는다고 밝힌다. 이는 클라이언트가 여전히 notifications/cancelled를 보내는 stdio와 다르고, HTTP 클라이언트도 이를 보냈던 2025년 개정판들과도 다르다. SDK는 두 부분을 모두 구현한다. SDK의 클라이언트는 기다리는 태스크가 취소되거나 읽기 타임아웃이 지나면 POST를 중단하고 다른 것은 아무것도 보내지 않는다(mcp/client/streamable_http.py). SDK의 서버는 연결 끊김을 감시하다가 핸들러를 실행하는 태스크를 취소한다(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의 취소 가이드와 mcp/server/_streamable_http_modern.py(watch_disconnect)가 두 경우를 모두 설명한다.
이 경로를 처음부터 끝까지 관찰하기 위해, 호스트는 사용자가 티켓을 닫을 때 호스트가 그러듯이 다섯 번째 진행 보고에서 호출을 취소한다. 여기서는 제품 하나에 0.1초가 걸리므로 스트림이 닫힐 때 서버는 아직 여섯 번째 제품의 재계산을 진행하는 중이다. 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번의 재계산을 요청한 상태였다. 취소는 도구가 여섯 번째 재계산을 기다리는 동안 도달했으므로 나머지 제품은 API로 가지 않았다.
전송 구간에는 server/discover, tools/call, 즉 두 번의 POST가 있었고 취소 메시지는 오가지 않았다. 도구 호출의 스트림은 closed by the client이었고 5 progress, 0 result를 담고 있었다. 취소된 호출에 대해 클라이언트는 결과를 받지 못하며, 서버도 결과를 보내지 않는다.
두 가지가 이 동작을 무효로 만든다. json_response=True를 쓰면 SDK의 JSON 경로에는 연결 끊김 감시기가 없으므로 닫힌 연결이 핸들러에 전달되지 않고 핸들러는 끝까지 실행된다(mcp/server/_streamable_http_modern.py). 또한 프록시가 시간 초과로 끊는 것처럼 다른 이유로 스트림이 끊어져도 같은 방식으로 요청이 취소된다. 고정된 개정판에서는 스트림을 재개할 수 없으므로 클라이언트는 새 요청 ID로 요청을 다시 보내야 한다(MUST)(변경 내역). 끊어진 스트림이 중단시킬 수 있는 도구는 두 번 실행해도 안전해야 하며, 재계산은 다시 세어도 같은 수가 나오므로 안전하다. 클라이언트가 사라져도 살아남아야 하는 재계산은 기다리는 대신 태스크 시작하기에서 태스크로 옮긴다.
타임아웃은 취소를 기반으로 동작한다. 취소 패턴은 송신자가 요청마다 타임아웃을 설정해야 하고(SHOULD), 진행 상황이 도착하면 이를 재설정해도 되며(MAY), 항상 최대 한도를 적용해야 한다(SHOULD)고 한다. Client(read_timeout_seconds=...)와 call_tool의 같은 인자가 이 한도를 정하며, 시간이 다 되면 스트림을 닫아 호출을 취소한다(mcp/client/streamable_http.py).
작업 규칙: Streamable HTTP에서는 호출을 기다리는 태스크를 취소하거나 타임아웃을 사용해 호출을 취소하고, 스트림은 SDK가 닫도록 둔다. 긴 도구는 async def로 작성하고, 취소를 다시 발생시키며, await가 필요한 정리 작업은 보호된 스코프 안에 둔다. 오래 실행되는 모든 도구는 재시도해도 안전하게 만든다. 스트림이 끊어지면 호출이 사라지고 클라이언트가 이를 다시 보내기 때문이다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Run replicas without sticky sessions
Every example so far, including the cancelled recount in Cancel a call the client no longer needs, ran one server process. The support team needs more than one, so that a restart or a slow recount doesn't stop every host. A load balancer in front of two replicas sends each request wherever it likes. With 2025-era sessions, the load balancer had to use sticky sessions, which route every request carrying the same Mcp-Session-Id to the replica that held the session. The pinned revision has no sessions, so any replica can serve any request. A server that needs state across calls mints an explicit handle instead, and the client passes it back as an ordinary argument (changelog).
The protocol keeping no state doesn't mean the application keeps none. The shop's server holds three kinds of state that a second replica doesn't see:
- The key that seals
requestState. The refund confirmation from Return an input request instead of a result sends the client a sealedrequestStateand opens it on the retry. By defaultMCPServerseals with a key that each process makes when it starts, and the state also names the server's name as its audience (mcp/server/request_state.py). - The handles the tools mint. Chapter 3's quote store keeps each
quote_idin the memory of the process that made it, as What goes wrong in production in chapter 3 warned. - The record of answered confirmations.
confirmations.OnceOnly, from Keep round-trip state tamper-proof, remembers each answeredrequestStatein one process's memory.
One refund, asked for on replica a and confirmed on replica b, touches all three kinds of state. Two replicas of chapter 5's refund server, each a process on its own port with one shop API behind both, run it. lib.http_mcp.load_server loads the server that refund-asks-to-confirm.py defines, and each replica runs it over HTTP. One client connects to each replica, and both read order O-1873. Then the client on replica a quotes a refund for order O-2289, whose amount is above the policy's limit, and replica a asks for confirmation. The retry with the support lead's yes goes to replica b, as a load balancer might send it. The sequence runs three times, fixing one kind of state each time:
- each replica makes its own key;
- both replicas read one key from
SHOP_REQUEST_STATE_KEY, throughconfirmations.state_security(); - both also keep their quotes and their answered confirmations in one shared store, a SQLite file named by
SHOP_STATE_STORE, and the client then sends the same answer a second time, to replica a.
The shared store is lib.shared_state. Its SharedMap and SharedSet keep entries in a SQLite file that every process on the machine opens, and each carries a lock on a file beside it, so that one replica's check-then-write can't interleave with another's. shop_tools.create_server(quotes=...) and confirmations.OnceOnly(seen=...) take any such container, and fall back to process memory without one, so chapters 3 and 5 run as before. Rows hold JSON, not pickles, and a quote's expiry is stored as a wall-clock time, because a monotonic deadline means nothing on another host. A SQLite file reaches only processes on one machine. A deployment puts the same two tables in a database its replicas share.
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
With their own keys, both reads worked (delivered, delivered), but the retry failed: error -32602 Invalid or expired requestState. Replica b couldn't open a state that replica a sealed, so the SDK refused the retry before the tool ran.
With one shared key, replica b opened the state, and the call failed one step later, inside the tool: "Error executing tool issue_refund: There is no quote Q-…" The quote lived in replica a's memory. The shared key fixed the first kind of state and exposed the second.
With the shared store as well, the retry on replica b released the refund, and its status became requested. Replica b found replica a's quote in the shared store, and with it the refund the shop's API already held, so it released that refund without asking for a second one. The same answer sent again to replica a was refused: "Error executing tool issue_refund: Refund R-0113 was already confirmed" Replica a had never seen the first answer. Without the shared record, its own OnceOnly check would have passed, and it would have asked the shop's API to release the refund again. Only the API's 409 for a refund it no longer holds would have stopped it. The refund completed once, across two replicas, with no sticky sessions. The specification asks for opaque, expiring handles (tools). Where their state lives is the server's choice, but with replicas it must be somewhere every replica reaches.
A deployment that hasn't moved some state yet can use a stopgap from the routing headers in Read one HTTP exchange. It isn't stickiness: a gateway sends every request whose Mcp-Name names a tool that depends on that state to one replica, and spreads the rest. A subscriptions/listen stream is held by one replica, and the SDK ships only an in-memory bus, so events published on another replica never reach it (deploy and scale; mcp/server/subscriptions.py, InMemorySubscriptionBus).
Working rule: Run replicas with no sticky sessions, and give every replica the same server name and the same requestState keys, injected from your secret store. Before you add a second replica, list every piece of state your tools keep in memory, such as handles, once-only records and subscriptions, and move each into storage that every replica reaches. Until one is moved, route the tools that depend on it to a single replica by 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 | |
|---|---|---|
| 시작하는 주체 | 호스트, 호스트마다 하나 | 운영자(여러분), 여러 호스트를 위해 한 번 |
| 접근할 수 있는 대상 | 자신의 호스트 | 해당 주소에 닿는 모든 것 |
| 취소 | notifications/cancelled |
응답 스트림 닫기 |
| 로그 | 표준 오류 | 서버의 로그 |
| 자격 증명 | 호스트의 환경 | OAuth 액세스 토큰 |
| 확장 방식 | 호스트마다 프로세스 하나 | 로드 밸런서 뒤의 레플리카 |
한 사용자를 위해 그 사용자의 머신에서 동작하는 서버에는 stdio를 권하며, 로컬 파일을 읽거나 사용자 본인의 자격 증명을 쓰는 서버가 그 예다. 개발할 때도 stdio를 권한다. 여러 호스트가 서버 하나를 공유할 때, 서버가 호스트에서 닿을 수 없는 시스템 옆에서 실행되어야 할 때, 예를 들어 상점의 API가 내부 네트워크 안에 있을 때, 또는 서버를 서비스로 배포하고 확장하고 감시해야 할 때는 Streamable HTTP를 권한다. 이 경우에는 처음부터 인가를 계획해야 한다. 주소를 가진 서버는 호출하는 쪽이 누구인지 알아야 하기 때문이다(리소스에서 인가 서버 찾기).
호스트가 많아지면 상점의 API에 지원 팀의 노트북이 닿아서는 안 되므로, 서버는 Streamable HTTP로 옮겨 간다. 이 책은 호스트 하나와 서버 하나만 필요한 예제에는 stdio를 그대로 쓴다. 서브프로세스가 그런 서버를 실행하는 가장 짧은 방법이기 때문이다.
작업 규칙: 서버가 한 사용자를 위해 그 사용자의 머신에서 동작한다면 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에는 각자의 설정이 있다. 진행 막대가 0에서 곧바로 완료로 넘어간다면 이 문제다. 진행 상황은 루프백이 아니라 실제 경로로 시험한다.
긴 호출이 딱 떨어지는 초 단위에서 끊긴다. 프록시와 로드 밸런서는 정해진 시간이 지나면 유휴 연결을 닫는다. 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장의 도구는 그대로 둔다. 호스트와 서버가 하나씩인 예제에서는 stdio를 계속 사용한다.
MCPServer.run(transport="streamable-http")은 SDK의 기본값을 따른다. 루프백 주소, 경로/mcp, 그리고 스트리밍하는 기본 응답 모드를 사용한다.stateless_http은 2025년 무렵의 클라이언트를 로드 밸런서 뒤에서 처리해야 할 때까지 설정하지 않는다. 설정하면 그 클라이언트는 취소 기능을 잃는다.json_response=True은 사용하지 않는다. 진행 상황 보고와 취소가 사라지기 때문이다.recount_stock는 제품 하나를 처리할 때마다 전체 수와 메시지를 담아 진행 상황을 보고하며, 두 번 실행해도 안전하다.- 취소는 스트림을 닫는 것이다. 오래 걸리는 도구는
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판을 번역한 것이다.