Streamable HTTP client stays closed after an interrupted response and raises ExceptionGroup on cleanup
Description
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/[email protected] 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
disconnectinterrupts its active HTTP response.- Python reports the request failure.
- A following
pingfails immediately withMCPError: Connection closed. - Context cleanup raises
ExceptionGroup: unhandled errors in a TaskGroupwhose nested cause ishttpx2.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.
Minimal reproduction
# Terminal 1
npx [email protected] serve --transport http --host 127.0.0.1 --port 43118 --path /mcp
# Terminal 2: save as repro.py, then run: python repro.py
import anyio
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client
URL = "http://127.0.0.1:43118/mcp"
async def main():
try:
async with streamable_http_client(URL) as streams:
async with ClientSession(
streams[0], streams[1], read_timeout_seconds=1.0
) as session:
await session.initialize()
try:
await session.call_tool(
"disconnect", {}, read_timeout_seconds=0.6
)
except BaseException as error:
print("disconnect:", type(error).__name__, error)
# Expected: succeeds. Actual: MCPError: Connection closed
print("ping:", await session.call_tool("ping", {}))
except BaseException as error:
# Actual: ExceptionGroup from streamable_http_client cleanup
print("cleanup:", type(error).__name__, error)
anyio.run(main)
Environment
Python 3.12.14; mcp 2.2.0; macOS arm64. Server: mcp-failure-lab 0.9.0; protocol 2026-07-28.
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_responseonly catchesStreamError/ValidationError, so thehttpx2.RemoteProtocolErrorescapes andasync with Client(...)exits with anExceptionGroup. - Server gone between calls:
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/f415ca0d0261fe6a3cba5a2376082f86
Same code on main @ 2af9e30.
@macrogui happy to run my fault harness against your branch and post before/after once it's up.
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 with
application/json, GET -> 405, no session id). Tools: ``slow`` answers after 3 s; ``drop`` closes the
TCP connection without any response (what a client sees when a proxy or peer drops an in-flight
request). Client: the mcp 2.3.0 ``streamable_http_client`` with a caller-owned httpx2 client, the
way 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
"""
import asyncio
import json
import socket
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import httpx2
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client
class H(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *a):
pass
def _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)
def do_GET(self):
self.send_response(405)
self.send_header("content-length", "0")
self.end_headers()
def do_DELETE(self):
self.do_GET()
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers.get("content-length") or 0)) or b"{}")
method, rid = body.get("method"), body.get("id")
if method == "initialize":
return self._json(200, {"jsonrpc": "2.0", "id": rid, "result": {
"protocolVersion": "2025-03-26", "capabilities": {"tools": {}},
"serverInfo": {"name": "standin", "version": "0"}}})
if rid is None: # notifications
self.send_response(202)
self.send_header("content-length", "0")
self.end_headers()
return
if method == "tools/list":
schema = {"type": "object", "properties": {}}
return self._json(200, {"jsonrpc": "2.0", "id": rid, "result": {"tools": [
{"name": "slow", "inputSchema": schema}, {"name": "drop", "inputSchema": schema}]}})
if method == "tools/call":
name = (body.get("params") or {}).get("name")
if name == "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 = True
return
time.sleep(3.0)
return self._json(200, {"jsonrpc": "2.0", "id": rid, "result": {"content": [{"type": "text", "text": "ok"}]}})
return self._json(200, {"jsonrpc": "2.0", "id": rid, "result": {}})
async def call(session, name):
t0 = time.monotonic()
try:
r = await session.call_tool(name, {})
return f"{name}: ok ({''.join(getattr(c, 'text', '') for c in r.content)}) {time.monotonic() - t0:.1f}s"
except BaseException as exc: # noqa: BLE001
return f"{name}: {type(exc).__name__}: {str(exc)[:80]} {time.monotonic() - t0:.1f}s"
async def main(port):
url = f"http://127.0.0.1:{port}/mcp"
out = []
try:
async with httpx2.AsyncClient(timeout=httpx2.Timeout(60.0, read=300.0)) as http:
async with streamable_http_client(url, http_client=http) as streams:
async with ClientSession(streams[0], streams[1]) as session:
await session.initialize()
out.append("A " + await call(session, "slow"))
async def record(name):
out.append("B " + await call(session, name))
await asyncio.gather(record("slow"), record("drop"))
out.append("C " + await call(session, "slow"))
except BaseException as exc: # noqa: BLE001
out.append(f"transport context exited: {type(exc).__name__}: {str(exc)[:160]}")
stack = [exc]
while stack:
e = stack.pop()
for sub in getattr(e, "exceptions", ()) or ():
out.append(f" sub-exception: {type(sub).__module__}.{type(sub).__name__}: {str(sub)[:140]}")
stack.append(sub)
return out
srv = ThreadingHTTPServer(("127.0.0.1", 0), H)
threading.Thread(target=srv.serve_forever, daemon=True).start()
for line in asyncio.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.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. - Caller cancellation and the abort-scope cancel aren't
TransportErrors, so they still propagate.initialize/server/discoverstill fail raw at connect time. - Nothing is re-sent, and a late or duplicate settle is dropped by the dispatcher (
_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.- The resumption GET in
_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.
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, in
a thread of its own. The proxy resets the one connection whose request calls the tool `drop`, as a
load balancer, a restarting server or a keep-alive race would. Meanwhile eight `slow` calls (1 s
each) are in flight on the same client, each in a task of its own, and the task that entered the
client 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 later
call on the same client works.
uv run mcp_drop.py # or: python mcp_drop.py, with mcp and uvicorn installed
"""
import asyncio
import importlib.metadata
import socket
import struct
import threading
import time
import uvicorn
from mcp import Client
from mcp.server.mcpserver import MCPServer
HOST = "127.0.0.1"
MARK = b'"name":"drop"'
def build_server() -> MCPServer:
server = MCPServer("drop-repro", log_level="WARNING")
@server.tool()
async def slow(seconds: float) -> str:
await asyncio.sleep(seconds)
return "ok"
@server.tool()
async def drop() -> str: # never reached: the proxy resets the connection first
return "not dropped"
return server
def free_port() -> int:
with socket.socket() as s:
s.bind((HOST, 0))
return s.getsockname()[1]
async def _pipe(reader, writer) -> None:
try:
while data := await reader.read(65536):
writer.write(data)
await writer.drain()
except (ConnectionError, OSError):
pass
finally:
writer.close()
async def _proxy_conn(cr, cw, target: int) -> None:
sr, sw = await asyncio.open_connection(HOST, target)
down = asyncio.create_task(_pipe(sr, cw))
tail = b""
try:
while data := await cr.read(65536):
if MARK in (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()
return
tail = data[-64:]
sw.write(data)
await sw.drain()
sw.close()
except (ConnectionError, OSError):
sw.transport.abort()
finally:
await asyncio.gather(down, return_exceptions=True)
def start_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()
async def run() -> None:
await asyncio.start_server(lambda r, w: _proxy_conn(r, w, server_port), HOST, proxy_port)
serve = asyncio.create_task(uv.serve())
while not uv.started:
await asyncio.sleep(0.01)
ready.set()
await serve
threading.Thread(target=asyncio.run, args=(run(),), daemon=True).start()
ready.wait(10)
return f"http://{HOST}:{proxy_port}/mcp"
async def main() -> 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()
def log(what: str) -> None:
print(f"{time.monotonic() - t0:5.2f} s {what}", flush=True)
async def call(client: Client, label: str, name: str, args: dict) -> None:
try:
result = await client.call_tool(name, args)
log(f"{label}: ok ({'error result' if result.is_error else 'result'})")
except BaseException as exc: # noqa: BLE001 - we want to see CancelledError too
log(f"{label}: {type(exc).__name__}: {exc}"[:160])
raise
try:
async with Client(url) as client:
log("connected")
calls = [asyncio.create_task(call(client, f"slow {i}", "slow", {"seconds": 1.0})) for i in range(8)]
await asyncio.sleep(0.2)
calls.append(asyncio.create_task(call(client, "drop", "drop", {})))
try:
await asyncio.sleep(2.0) # the entering task's own work, unrelated to MCP
log("unrelated work: done")
except asyncio.CancelledError:
log("unrelated work: CancelledError")
raise
finally:
await asyncio.gather(*calls, return_exceptions=True)
await call(client, "later call", "slow", {"seconds": 0.1})
log("client closed cleanly")
except BaseException as exc: # noqa: BLE001
log(f"leaving `async with Client`: {type(exc).__name__}: {exc}")
for sub in getattr(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.
Generated with Matteo's hands and Claude Code