You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Streamable HTTP client stays closed after an interrupted response and raises ExceptionGroup on cleanup #3522
With the current 2.x release, one interrupted Streamable HTTP tool response permanently closes the Python client session. The failing request is reported, but a subsequent normal request on the same client fails with MCPError: Connection closed. Exiting streamable_http_client(...) then raises an unhandled ExceptionGroup from its background task group.
The same MCP server remains healthy. Under the identical sequence, @modelcontextprotocol/sdk@1.30.0 reports the interrupted request and successfully completes the next ping on the same client.
Expected behavior
The interrupted request should fail, while a subsequent request should be able to use a fresh HTTP connection and succeed. Transport cleanup should not raise an additional ExceptionGroup.
Actual behavior
disconnect interrupts its active HTTP response.
Python reports the request failure.
A following ping fails immediately with MCPError: Connection closed.
Context cleanup raises ExceptionGroup: unhandled errors in a TaskGroup whose nested cause is httpx2.RemoteProtocolError: Server disconnected without sending a response.
Comparison
The official TypeScript client 1.30.0 receives TypeError: fetch failed for the deliberately interrupted request, then successfully sends ping through the same client. This suggests the server remains available and the problem is in Python client recovery/cleanup.
I also searched the existing issues. #3494 concerns a server-side incomplete SSE body during initialize, and #3441 concerns an unresolved 1.x request; neither appears to cover this v2 same-client recovery failure.
Confirmed the full reproduction on main (macOS arm64, Python 3.13, mcp-failure-lab 0.9.0 over HTTP): the interrupted disconnect call fails, the following ping gets MCPError: Connection closed, and exiting streamable_http_client raises the ExceptionGroup (nested cause httpx2.RemoteProtocolError).
Root cause looks like an unhandled escape path rather than the session lifecycle: _run_request_post runs each request's POST with no exception guard, so a transport-level failure (server drops the connection before sending a response) propagates out of the per-request task and cancels the transport's task group — the write stream closes, which is what turns every later request into Connection closed, and the raw error resurfaces as the unhandled TaskGroup exception on cleanup. The contained outcomes (202 Accepted, non-resumable SSE drops, exhausted reconnection) already resolve just the in-flight request via _resolve_abandoned_request; this looks like the one POST failure mode that bypasses that pattern.
I have a branch implementing the same containment for HTTP transport errors — catch httpx2.TransportError around the POST exchange in _handle_post_request, resolve the in-flight request with CONNECTION_CLOSED, keep the session usable (verified: the next ping succeeds against the failure-lab server, and cleanup no longer raises). Happy to open the PR if that's the direction you want — happy to take a different shape too.
Reproduced on mcp 2.3.0 (Python 3.13, Linux), both mode="auto" and mode="legacy". Two more variants that hit the same path, in case they help with regression tests:
Mid-body drop: server sends 200 + application/json + Content-Length: 200, writes 22 bytes, closes. _handle_json_response only catches StreamError/ValidationError, so the httpx2.RemoteProtocolError escapes and async with Client(...) exits with an ExceptionGroup.
Server gone between calls:httpx2.ConnectError on the next POST, same result.
For contrast, a dropped SSE response, HTML in a JSON body, an empty body, and non-2xx statuses all fail just that one call and the session keeps working.
We hit this independently in production (Hermes Agent v0.22.5 → mcp 2.3.0, against a stateless JSON-mode Streamable HTTP server), and can add a minimal self-contained repro that also shows the blast radius: one dropped POST doesn't only break later calls — it cancels other, unrelated calls already in flight on the same session.
Setup: a stdlib stand-in server (POST answers application/json, GET → 405, no session id) with two tools — slow answers after 3 s; drop hard-closes the TCP connection (RST) after 0.5 s without any response, the way a proxy or peer dropping one in-flight request looks. Client: streamable_http_client with a caller-owned httpx2 client.
A slow: ok (ok) 3.0s # baseline
B slow: CancelledError: Cancelled via cancel scope … 0.5s # unrelated call, cancelled
B drop: CancelledError: Cancelled via cancel scope … 0.5s
transport context exited: ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)
sub-exception: httpx2.ReadError
Case C (a follow-up call on the same session) never runs.
As far as we can tell, _run_request_post / _handle_post_request (mcp/client/streamable_http.py, roughly lines 346–446 in 2.3.0) map HTTP status errors to per-request errors, but a transport exception (ReadError, ConnectError, …) escapes into the transport's task group (~line 680), which cancels every sibling request and closes the session — consistent with #3560. Expected: the dropped request fails with a per-request JSON-RPC error; concurrent and later requests are unaffected.
Downstream effect for us: combined with a reconnect bug in the host (NousResearch/hermes-agent#103211), one dropped request became a ~25 s outage of every tool on that server.
Repro script (stdlib server + client, ~100 lines)
"""Does ONE transport-level POST failure kill a whole mcp 2.3.0 Streamable-HTTP session?A local stand-in for a stateless JSON-mode MCP server (e.g. POST answers withapplication/json, GET -> 405, no session id). Tools: ``slow`` answers after 3 s; ``drop`` closes theTCP connection without any response (what a client sees when a proxy or peer drops an in-flightrequest). Client: the mcp 2.3.0 ``streamable_http_client`` with a caller-owned httpx2 client, theway Hermes builds it. Cases: A. ``slow`` alone -> baseline B. ``slow`` and ``drop`` concurrently -> does the unrelated ``slow`` fail too? C. after B, ``slow`` on the same session -> is the session still usable?Usage: venv/bin/python -I sdk_blast_radius.py"""importasyncioimportjsonimportsocketimportthreadingimporttimefromhttp.serverimportBaseHTTPRequestHandler, ThreadingHTTPServerimporthttpx2frommcpimportClientSessionfrommcp.client.streamable_httpimportstreamable_http_clientclassH(BaseHTTPRequestHandler):
protocol_version="HTTP/1.1"deflog_message(self, *a):
passdef_json(self, code, obj):
raw=json.dumps(obj).encode()
self.send_response(code)
self.send_header("content-type", "application/json")
self.send_header("content-length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
defdo_GET(self):
self.send_response(405)
self.send_header("content-length", "0")
self.end_headers()
defdo_DELETE(self):
self.do_GET()
defdo_POST(self):
body=json.loads(self.rfile.read(int(self.headers.get("content-length") or0)) orb"{}")
method, rid=body.get("method"), body.get("id")
ifmethod=="initialize":
returnself._json(200, {"jsonrpc": "2.0", "id": rid, "result": {
"protocolVersion": "2025-03-26", "capabilities": {"tools": {}},
"serverInfo": {"name": "standin", "version": "0"}}})
ifridisNone: # notificationsself.send_response(202)
self.send_header("content-length", "0")
self.end_headers()
returnifmethod=="tools/list":
schema= {"type": "object", "properties": {}}
returnself._json(200, {"jsonrpc": "2.0", "id": rid, "result": {"tools": [
{"name": "slow", "inputSchema": schema}, {"name": "drop", "inputSchema": schema}]}})
ifmethod=="tools/call":
name= (body.get("params") or {}).get("name")
ifname=="drop":
time.sleep(0.5)
# No response: hard-close the TCP connection (RST), as a dropped in-flight request looks.self.connection.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, b"\x01\x00\x00\x00\x00\x00\x00\x00")
self.connection.close()
self.close_connection=Truereturntime.sleep(3.0)
returnself._json(200, {"jsonrpc": "2.0", "id": rid, "result": {"content": [{"type": "text", "text": "ok"}]}})
returnself._json(200, {"jsonrpc": "2.0", "id": rid, "result": {}})
asyncdefcall(session, name):
t0=time.monotonic()
try:
r=awaitsession.call_tool(name, {})
returnf"{name}: ok ({''.join(getattr(c, 'text', '') forcinr.content)}) {time.monotonic() -t0:.1f}s"exceptBaseExceptionasexc: # noqa: BLE001returnf"{name}: {type(exc).__name__}: {str(exc)[:80]}{time.monotonic() -t0:.1f}s"asyncdefmain(port):
url=f"http://127.0.0.1:{port}/mcp"out= []
try:
asyncwithhttpx2.AsyncClient(timeout=httpx2.Timeout(60.0, read=300.0)) ashttp:
asyncwithstreamable_http_client(url, http_client=http) asstreams:
asyncwithClientSession(streams[0], streams[1]) assession:
awaitsession.initialize()
out.append("A "+awaitcall(session, "slow"))
asyncdefrecord(name):
out.append("B "+awaitcall(session, name))
awaitasyncio.gather(record("slow"), record("drop"))
out.append("C "+awaitcall(session, "slow"))
exceptBaseExceptionasexc: # noqa: BLE001out.append(f"transport context exited: {type(exc).__name__}: {str(exc)[:160]}")
stack= [exc]
whilestack:
e=stack.pop()
forsubingetattr(e, "exceptions", ()) or ():
out.append(f" sub-exception: {type(sub).__module__}.{type(sub).__name__}: {str(sub)[:140]}")
stack.append(sub)
returnoutsrv=ThreadingHTTPServer(("127.0.0.1", 0), H)
threading.Thread(target=srv.serve_forever, daemon=True).start()
forlineinasyncio.run(main(srv.server_address[1])):
print(line)
@sanctrl I reproduced the sibling-cancellation case and retargeted the containment from #3584 onto current main 77001c96.
Runnable package includes the localhost reproducer, exact 2.3.0 dependency lock, applicable patch and before/after JSON.
Both 2.3.0 and unpatched main cancel the unrelated request and raise ExceptionGroup. With the patch, the sibling and later calls succeed, cleanup is clean, and the caller-owned HTTP client stays open. Mid-body disconnects and refused connections fail only their request. Caller cancellation and connect-time errors still propagate. The failed POST is observed once, with no automatic retry.
Focused SDK tests: 18 passed with the patch; the same tests on the unpatched client produce 9 failed and 9 passed. This addresses the SDK boundary, not the separate Hermes reconnect bug. The README has the exact run/apply commands; no additional upstream PR was opened.
@epistemedeus thank you for this, it's the fix shape we were hoping for.
We read the patch; we haven't run it or the reproducer. Checked against 77001c96, which is still main and has the same streamable_http.py as v2.3.0:
It applies cleanly to all three files (git apply --check).
The httpx2.TransportError is caught inside the per-request task, before it can reach the transport task group that _run_request_post is started in, so sibling calls and later calls keep going. The failed request is settled with CONNECTION_CLOSED through the existing _resolve_abandoned_request, and a failed notification no longer ends post_writer.
Caller cancellation and the abort-scope cancel aren't TransportErrors, so they still propagate. initialize / server/discover still fail raw at connect time.
Nothing is re-sent, and a late or duplicate settle is dropped by the dispatcher (_resolve_pending ignores unknown ids).
Two things a reviewer might raise:
httpx2.DecodingError (a RequestError but not a TransportError, e.g. a corrupt compressed body) would still end the session.
The resumption GET in _handle_resumption_request has the same uncaught path.
On getting it merged: per CONTRIBUTING.md, an outside PR here stays open only once a maintainer has assigned the issue, which is why #3525 and #3584 were auto-closed. If a maintainer is open to an outside PR for this, would you open it from your package? If you'd rather not, we're glad to open it with your authorship kept on the commits.
Maintainers: from the downstream side, this is the behaviour we'd want. One failed POST should fail one call, which is what the TS client does per the issue description.
Yes, I can open the PR once a maintainer assigns this issue. The package ports #3584, so its original authorship should be retained.
Thanks for separating the source review from an actual run. Decoding errors and resumption GETs need their own regression coverage; the current package demonstrates POST transport-error isolation, not those additional paths.
Confirming on 2.3.0 with the high-level mcp.Client, and adding two things this thread doesn't have yet: (1) the task that entered the client is cancelled too, not only MCP calls; and (2) the SDK's own default keep-alives make the trigger routine.
We keep a pool of long-lived Clients in a service with a few hundred tool calls in flight against a stateless, JSON-response Streamable HTTP server. Under load one POST failed with httpx2.ReadError. The transport's task group scope encloses the body of async with Client(...), so the service's main loop, which had entered the clients, was cancelled and the service exited. Until this is fixed, every client has to live in a sacrificial task of its own.
The script below runs a real MCPServer behind a small TCP proxy that resets the one connection calling drop. Eight 1s calls are in flight in other tasks, and the task that entered the client does 2s of unrelated work:
mcp 2.3.0, httpx2 2.16.0, anyio 4.16.0
0.05s connected
0.26s unrelated work: CancelledError
0.26s slow 0: CancelledError: Cancelled via cancel scope 10a2537f0
... (slow 1 to 7 the same)
0.26s drop: CancelledError: Cancelled via cancel scope 10a2537f0
0.26s leaving `async with Client`: ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)
0.26s sub-exception: ReadError: ReadError('')
With _handle_post_request catching httpx2.TransportError and resolving the request through _resolve_abandoned_request (the shape proposed above), the same script gives:
0.25s drop: MCPError: POST failed: ReadError:
1.30s slow 0 to 7: ok
2.24s unrelated work: done
2.35s later call: ok
2.36s client closed cleanly
So, from a user's side, +1 to that fix. One detail: str() of an httpx2 ReadError is often empty, so the synthesized message is more useful with the exception's type in it.
The SDK's HTTP client keeps an idle connection for 5s (httpx2 Limits.keepalive_expiry), and uvicorn closes one after 5s (timeout_keep_alive); MCPServer.run("streamable-http") starts uvicorn with that default. So a client can send a request on a connection the server is closing at that moment. On a laptop (macOS, Python 3.12, loopback), with 8 clients x 8 calls at once, in 24 rounds separated by idle gaps of 5s ± 20ms (same gaps in both runs), each client reconnecting when it fails:
Server timeout_keep_alive
Calls
Calls lost
Client restarts
5s (uvicorn's default)
1,536
240
30
600s
1,536
0
0
Every loss came after a gap of 4.980–4.989s (5 of the 7 such rounds), and one reset on one connection failed all 8 calls on that client. With the fix above, each race would cost one call instead of a client. It would still cost a call, though. If it helps, MCPServer.run could give uvicorn a timeout_keep_alive longer than the client's default expiry. I'm glad to open a separate issue for that if you'd like it tracked apart.
Reproduction script (needs mcp and uvicorn)
# /// script# requires-python = ">=3.11"# dependencies = ["mcp==2.3.0", "uvicorn"]# ///"""One dropped connection takes down an `mcp.Client` and the task that entered it.A real `MCPServer` (Streamable HTTP, stateless, JSON responses) runs behind a small TCP proxy, ina thread of its own. The proxy resets the one connection whose request calls the tool `drop`, as aload balancer, a restarting server or a keep-alive race would. Meanwhile eight `slow` calls (1 seach) are in flight on the same client, each in a task of its own, and the task that entered theclient does unrelated work for 2 s, as a service's main loop would.Expected: the `drop` call fails; the eight `slow` calls and the unrelated work finish; a latercall on the same client works. uv run mcp_drop.py # or: python mcp_drop.py, with mcp and uvicorn installed"""importasyncioimportimportlib.metadataimportsocketimportstructimportthreadingimporttimeimportuvicornfrommcpimportClientfrommcp.server.mcpserverimportMCPServerHOST="127.0.0.1"MARK=b'"name":"drop"'defbuild_server() ->MCPServer:
server=MCPServer("drop-repro", log_level="WARNING")
@server.tool()asyncdefslow(seconds: float) ->str:
awaitasyncio.sleep(seconds)
return"ok"@server.tool()asyncdefdrop() ->str: # never reached: the proxy resets the connection firstreturn"not dropped"returnserverdeffree_port() ->int:
withsocket.socket() ass:
s.bind((HOST, 0))
returns.getsockname()[1]
asyncdef_pipe(reader, writer) ->None:
try:
whiledata:=awaitreader.read(65536):
writer.write(data)
awaitwriter.drain()
except (ConnectionError, OSError):
passfinally:
writer.close()
asyncdef_proxy_conn(cr, cw, target: int) ->None:
sr, sw=awaitasyncio.open_connection(HOST, target)
down=asyncio.create_task(_pipe(sr, cw))
tail=b""try:
whiledata:=awaitcr.read(65536):
ifMARKin (tail+data).replace(b" ", b""):
# Reset the client's connection (RST, not FIN), and drop the server's side.cw.get_extra_info("socket").setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
cw.transport.abort()
sw.transport.abort()
returntail=data[-64:]
sw.write(data)
awaitsw.drain()
sw.close()
except (ConnectionError, OSError):
sw.transport.abort()
finally:
awaitasyncio.gather(down, return_exceptions=True)
defstart_server_and_proxy() ->str:
"""Starts the server and the proxy in a thread; returns the proxy's MCP URL."""server_port, proxy_port=free_port(), free_port()
app=build_server().streamable_http_app(stateless_http=True, json_response=True, host=HOST)
uv=uvicorn.Server(uvicorn.Config(app, host=HOST, port=server_port, log_level="warning", timeout_keep_alive=600))
ready=threading.Event()
asyncdefrun() ->None:
awaitasyncio.start_server(lambdar, w: _proxy_conn(r, w, server_port), HOST, proxy_port)
serve=asyncio.create_task(uv.serve())
whilenotuv.started:
awaitasyncio.sleep(0.01)
ready.set()
awaitservethreading.Thread(target=asyncio.run, args=(run(),), daemon=True).start()
ready.wait(10)
returnf"http://{HOST}:{proxy_port}/mcp"asyncdefmain() ->None:
print(f"mcp {importlib.metadata.version('mcp')}, httpx2 {importlib.metadata.version('httpx2')}, anyio {importlib.metadata.version('anyio')}")
url=start_server_and_proxy()
t0=time.monotonic()
deflog(what: str) ->None:
print(f"{time.monotonic() -t0:5.2f} s {what}", flush=True)
asyncdefcall(client: Client, label: str, name: str, args: dict) ->None:
try:
result=awaitclient.call_tool(name, args)
log(f"{label}: ok ({'error result'ifresult.is_errorelse'result'})")
exceptBaseExceptionasexc: # noqa: BLE001 - we want to see CancelledError toolog(f"{label}: {type(exc).__name__}: {exc}"[:160])
raisetry:
asyncwithClient(url) asclient:
log("connected")
calls= [asyncio.create_task(call(client, f"slow {i}", "slow", {"seconds": 1.0})) foriinrange(8)]
awaitasyncio.sleep(0.2)
calls.append(asyncio.create_task(call(client, "drop", "drop", {})))
try:
awaitasyncio.sleep(2.0) # the entering task's own work, unrelated to MCPlog("unrelated work: done")
exceptasyncio.CancelledError:
log("unrelated work: CancelledError")
raisefinally:
awaitasyncio.gather(*calls, return_exceptions=True)
awaitcall(client, "later call", "slow", {"seconds": 0.1})
log("client closed cleanly")
exceptBaseExceptionasexc: # noqa: BLE001log(f"leaving `async with Client`: {type(exc).__name__}: {exc}")
forsubingetattr(exc, "exceptions", ()):
log(f" sub-exception: {type(sub).__name__}: {sub!r}"[:160])
if__name__=="__main__":
asyncio.run(main())
AI disclosure: Claude Code wrote the reproduction and the measurements under my direction. I hit this bug in our own service and can answer questions about it.
Activity
macrogui commentedon Sep 17, 2026
Confirmed the full reproduction on
main(macOS arm64, Python 3.13, mcp-failure-lab 0.9.0 over HTTP): the interrupteddisconnectcall fails, the followingpinggetsMCPError: Connection closed, and exitingstreamable_http_clientraises theExceptionGroup(nested causehttpx2.RemoteProtocolError).Root cause looks like an unhandled escape path rather than the session lifecycle:
_run_request_postruns each request's POST with no exception guard, so a transport-level failure (server drops the connection before sending a response) propagates out of the per-request task and cancels the transport's task group — the write stream closes, which is what turns every later request intoConnection closed, and the raw error resurfaces as the unhandled TaskGroup exception on cleanup. The contained outcomes (202 Accepted, non-resumable SSE drops, exhausted reconnection) already resolve just the in-flight request via_resolve_abandoned_request; this looks like the one POST failure mode that bypasses that pattern.I have a branch implementing the same containment for HTTP transport errors — catch
httpx2.TransportErroraround the POST exchange in_handle_post_request, resolve the in-flight request withCONNECTION_CLOSED, keep the session usable (verified: the nextpingsucceeds against the failure-lab server, and cleanup no longer raises). Happy to open the PR if that's the direction you want — happy to take a different shape too.AngelP17 commentedon Oct 21, 2026
Reproduced on mcp 2.3.0 (Python 3.13, Linux), both
mode="auto"andmode="legacy". Two more variants that hit the same path, in case they help with regression tests:200+application/json+Content-Length: 200, writes 22 bytes, closes._handle_json_responseonly catchesStreamError/ValidationError, so thehttpx2.RemoteProtocolErrorescapes andasync with Client(...)exits with anExceptionGroup.httpx2.ConnectErroron the next POST, same result.For contrast, a dropped SSE response, HTML in a JSON body, an empty body, and non-2xx statuses all fail just that one call and the session keeps working.
Standalone repro (only needs
mcp+uvicorn): https://gist.github.com/AngelP17/f415ca0d0261fe6a3cba5a2376082f86Same code on
main@ 2af9e30.@macrogui happy to run my fault harness against your branch and post before/after once it's up.
Review fixes: exact fallback scope, tolerant single-profile path, tex…
Run each cycle in the profile's own runtime scope; correct the 0.4.1 …
sanctrl commentedon Nov 6, 2026
We hit this independently in production (Hermes Agent v0.22.5 →
mcp2.3.0, against a stateless JSON-mode Streamable HTTP server), and can add a minimal self-contained repro that also shows the blast radius: one dropped POST doesn't only break later calls — it cancels other, unrelated calls already in flight on the same session.Setup: a stdlib stand-in server (POST answers
application/json, GET → 405, no session id) with two tools —slowanswers after 3 s;drophard-closes the TCP connection (RST) after 0.5 s without any response, the way a proxy or peer dropping one in-flight request looks. Client:streamable_http_clientwith a caller-owned httpx2 client.Case C (a follow-up call on the same session) never runs.
As far as we can tell,
_run_request_post/_handle_post_request(mcp/client/streamable_http.py, roughly lines 346–446 in 2.3.0) map HTTP status errors to per-request errors, but a transport exception (ReadError,ConnectError, …) escapes into the transport's task group (~line 680), which cancels every sibling request and closes the session — consistent with #3560. Expected: the dropped request fails with a per-request JSON-RPC error; concurrent and later requests are unaffected.Downstream effect for us: combined with a reconnect bug in the host (NousResearch/hermes-agent#103211), one dropped request became a ~25 s outage of every tool on that server.
Repro script (stdlib server + client, ~100 lines)
epistemedeus commentedon Nov 6, 2026
@sanctrl I reproduced the sibling-cancellation case and retargeted the containment from #3584 onto current main
77001c96.Runnable package includes the localhost reproducer, exact 2.3.0 dependency lock, applicable patch and before/after JSON.
Both 2.3.0 and unpatched main cancel the unrelated request and raise
ExceptionGroup. With the patch, the sibling and later calls succeed, cleanup is clean, and the caller-owned HTTP client stays open. Mid-body disconnects and refused connections fail only their request. Caller cancellation and connect-time errors still propagate. The failed POST is observed once, with no automatic retry.Focused SDK tests: 18 passed with the patch; the same tests on the unpatched client produce 9 failed and 9 passed. This addresses the SDK boundary, not the separate Hermes reconnect bug. The README has the exact run/apply commands; no additional upstream PR was opened.
sanctrl commentedon Nov 11, 2026
@epistemedeus thank you for this, it's the fix shape we were hoping for.
We read the patch; we haven't run it or the reproducer. Checked against
77001c96, which is stillmainand has the samestreamable_http.pyas v2.3.0:git apply --check).httpx2.TransportErroris caught inside the per-request task, before it can reach the transport task group that_run_request_postis started in, so sibling calls and later calls keep going. The failed request is settled withCONNECTION_CLOSEDthrough the existing_resolve_abandoned_request, and a failed notification no longer endspost_writer.TransportErrors, so they still propagate.initialize/server/discoverstill fail raw at connect time._resolve_pendingignores unknown ids).Two things a reviewer might raise:
httpx2.DecodingError(aRequestErrorbut not aTransportError, e.g. a corrupt compressed body) would still end the session._handle_resumption_requesthas the same uncaught path.On getting it merged: per CONTRIBUTING.md, an outside PR here stays open only once a maintainer has assigned the issue, which is why #3525 and #3584 were auto-closed. If a maintainer is open to an outside PR for this, would you open it from your package? If you'd rather not, we're glad to open it with your authorship kept on the commits.
Maintainers: from the downstream side, this is the behaviour we'd want. One failed POST should fail one call, which is what the TS client does per the issue description.
epistemedeus commentedon Nov 11, 2026
Yes, I can open the PR once a maintainer assigns this issue. The package ports #3584, so its original authorship should be retained.
Thanks for separating the source review from an actual run. Decoding errors and resumption GETs need their own regression coverage; the current package demonstrates POST transport-error isolation, not those additional paths.
mturilli commentedon Nov 14, 2026
Confirming on 2.3.0 with the high-level
mcp.Client, and adding two things this thread doesn't have yet: (1) the task that entered the client is cancelled too, not only MCP calls; and (2) the SDK's own default keep-alives make the trigger routine.We keep a pool of long-lived
Clients in a service with a few hundred tool calls in flight against a stateless, JSON-response Streamable HTTP server. Under load one POST failed withhttpx2.ReadError. The transport's task group scope encloses the body ofasync with Client(...), so the service's main loop, which had entered the clients, was cancelled and the service exited. Until this is fixed, every client has to live in a sacrificial task of its own.The script below runs a real
MCPServerbehind a small TCP proxy that resets the one connection callingdrop. Eight 1s calls are in flight in other tasks, and the task that entered the client does 2s of unrelated work:With
_handle_post_requestcatchinghttpx2.TransportErrorand resolving the request through_resolve_abandoned_request(the shape proposed above), the same script gives:So, from a user's side, +1 to that fix. One detail:
str()of an httpx2ReadErroris often empty, so the synthesized message is more useful with the exception's type in it.The SDK's HTTP client keeps an idle connection for 5s (httpx2
Limits.keepalive_expiry), and uvicorn closes one after 5s (timeout_keep_alive);MCPServer.run("streamable-http")starts uvicorn with that default. So a client can send a request on a connection the server is closing at that moment. On a laptop (macOS, Python 3.12, loopback), with 8 clients x 8 calls at once, in 24 rounds separated by idle gaps of 5s ± 20ms (same gaps in both runs), each client reconnecting when it fails:timeout_keep_aliveEvery loss came after a gap of 4.980–4.989s (5 of the 7 such rounds), and one reset on one connection failed all 8 calls on that client. With the fix above, each race would cost one call instead of a client. It would still cost a call, though. If it helps,
MCPServer.runcould give uvicorn atimeout_keep_alivelonger than the client's default expiry. I'm glad to open a separate issue for that if you'd like it tracked apart.Reproduction script (needs
mcpanduvicorn)AI disclosure: Claude Code wrote the reproduction and the measurements under my direction. I hit this bug in our own service and can answer questions about it.
Generated with Matteo's hands and Claude Code