Skip to content

A dropped connection during a call ends the whole client session instead of failing that call (mcp 2.3.0) #3954

Backlog

Description

@madosh

If the connection drops while a call is in flight, the Streamable HTTP client doesn't raise the error from that call_tool. The httpx2.ReadError is raised inside the task group in streamable_http_client. The task group fails, and the whole Client session ends with an ExceptionGroup. Every later call is lost with it.

I'd expect the call that hit the error to raise, and the session to stay usable for the next call.

How it happens in practice

uvicorn closes idle connections after 5 s by default (timeout_keep_alive), and httpx2 keeps idle connections for 5 s too. So now and then the client sends on a connection at the same moment the server closes it. With a plain HTTP client that's one failed request. With the MCP client it ends the session. I first hit it partway through a long benchmark run.

Reproduction

This shortens the server's keep-alive to 1 s and waits about 1 s between calls, so the race comes up within a minute:

# pip install mcp==2.3.0 uvicorn
import asyncio
import socket
import traceback

import mcp_types as types
import uvicorn
from mcp import Client
from mcp.server.lowlevel import Server

TOOL = types.Tool(name="echo", description="Echo the text back",
                  input_schema={"type": "object", "properties": {"text": {"type": "string"}}})


async def on_list_tools(ctx, params):
    return types.ListToolsResult(tools=[TOOL])


async def on_call_tool(ctx, params):
    return types.CallToolResult(content=[types.TextContent(type="text", text=params.arguments["text"])])


async def main():
    server = Server("demo", on_list_tools=on_list_tools, on_call_tool=on_call_tool)
    sock = socket.socket()
    sock.bind(("127.0.0.1", 0))
    port = sock.getsockname()[1]
    config = uvicorn.Config(server.streamable_http_app(stateless_http=True), log_level="warning", timeout_keep_alive=1)
    uv = uvicorn.Server(config)
    task = asyncio.create_task(uv.serve(sockets=[sock]))
    while not uv.started:
        await asyncio.sleep(0.05)

    calls = 0
    try:
        async with Client(f"http://127.0.0.1:{port}/mcp", mode="2026-07-28") as client:
            await client.list_tools()
            for i in range(200):
                await asyncio.sleep(0.98 + (i % 9) * 0.005)  # idle for about as long as the server's keep-alive
                try:
                    await client.call_tool("echo", {"text": f"call {i}"})
                    calls += 1
                except Exception as exc:
                    print(f"call {i} raised {type(exc).__name__}: {exc}")
                    await client.call_tool("echo", {"text": "next call"})
                    print("the session survived: the next call succeeded")
                    break
    except BaseException as exc:
        print(f"after {calls} successful calls the whole session ended with {type(exc).__name__}:")
        traceback.print_exception(exc, limit=-2)
    else:
        print(f"{calls} calls, no error")
    uv.should_exit = True
    await task


asyncio.run(main())

Output, shortened (mcp 2.3.0, httpx2 2.16.0, anyio 4.15.1, uvicorn 0.54.0, Python 3.13). In three runs it failed after 38, 10 and 28 calls:

after 38 successful calls the whole session ended with ExceptionGroup:
  + Exception Group Traceback (most recent call last):
  |   File ".../mcp/client/streamable_http.py", line 771, in streamable_http_client
  |     anyio.create_task_group() as tg,
  |   File ".../anyio/_backends/_asyncio.py", line 847, in __aexit__
  |     raise BaseExceptionGroup(
  | ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)
  +-+---------------- 1 ----------------
    |   File ".../httpcore2/_exceptions.py", line 17, in map_exceptions
    |     raise to_exc(exc) from exc
    | httpcore2.ReadError
    |
    | The above exception was the direct cause of the following exception:
    |
    |   File ".../httpx2/_transports/default.py", line 115, in map_httpcore_exceptions
    |     raise mapped_exc(message) from exc
    | httpx2.ReadError
    +------------------------------------

The except Exception around call_tool never runs: the call itself doesn't raise; the session does.

Workaround

Give the server a longer keep-alive than the client's idle expiry (I use 30 s), so the client always drops an idle connection first. That avoids this particular race. I'd expect any other dropped connection mid-call (a proxy restart, a network blip) to end the session the same way, though I haven't tested that.

Activity

  1. its-amann commented on Dec 1, 2026

    @its-amann

    @maxisbey @Kludex can I take this? plan is to catch the transport error per request in streamable_http_client so only the in flight call fails and the session stays usable, plus a test that drops the connection mid call

  2. alvinxiao2 commented on Dec 3, 2026

    @alvinxiao2

    Same pattern, and it is not specific to uvicorn's keep-alive. We run a stateful Streamable HTTP MCP server behind nginx and Cloudflare, and the outage signature is identical from the client side:

    • nginx proxy_read_timeout (60s default) truncates an SSE response mid-body for any tool whose first byte takes longer than the timeout — the client sees ReadError, and per this issue the whole session dies with it;
    • Cloudflare in front adds its own ~100s cap and resets the connection in some paths;
    • the server looks healthy the whole time: StreamableHTTPSessionManager still owns the session, and the next request carrying the old Mcp-Session-Id is accepted normally.

    Two things worth deciding before the fix lands:

    1. Failing the call is not the same as trusting the session. If the failure was a truncated response, the server may still be executing the tool with half-written state. Retrying the same call on the same session can double-execute a side-effecting tool. Safer default: fail the in-flight call, keep the session, and let the caller opt into retry — using the existing 404 / session-lost path as the only automatic reconnect trigger.

    2. Keep the exception type visible. The ExceptionGroup as it stands erases the distinction between ReadError, RemoteProtocolError and a reset. That distinction is the only signal a caller has to separate "a proxy cut the stream" from "the server crashed", and in our logs those need opposite handling — the first is a config fix on the proxy, the second is a page.

    We wrote our side of this up in a shared MCP pitfall memory (QianYuan — https://qianyuan.ltd) that our agents query before touching transport config, mostly so the nginx timeout knob stops being rediscovered by every new deploy. If you want a live stateful Streamable HTTP server to watch this against, ours is one command away:

    claude mcp add --transport http qianyuan https://qianyuan.ltd/mcp
    

    then call qy_recall. It holds a real mcp-session-id per connection, so a restart or a proxy cut reproduces the session-lost path immediately.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions