Skip to content

SSE client: a non-2xx response to a POSTed message (e.g. 413) leaves the request pending forever and kills the session #3950

Backlog

Description

@Zalaano666

Summary

With the SSE transport, when the server answers a client POST to the message endpoint with a non-2xx status, mcp.client.sse logs the error and stops sending. The pending request is never resolved, so call_tool waits until the caller's own timeout. Every later request on the same session fails with Connection closed. A request body above the server's default max_request_body_size (4 MiB, answered with 413) triggers this reliably.

Over streamable HTTP, the same oversized request fails promptly with an error, and the session keeps working.

Versions

mcp 2.3.0, httpx2 2.16.2, starlette 1.10.0, uvicorn 0.54.0, Python 3.11.18, Linux.

Minimal reproduction

import asyncio
import threading

import uvicorn
from mcp.client.session import ClientSession
from mcp.client.sse import sse_client
from mcp.server.mcpserver import MCPServer

server = MCPServer("repro")


@server.tool()
def echo(text: str) -> int:
    return len(text)


async def main() -> None:
    config = uvicorn.Config(server.sse_app(), host="127.0.0.1", port=8765, log_level="warning")
    uv = uvicorn.Server(config)
    threading.Thread(target=uv.run, daemon=True).start()
    while not uv.started:
        await asyncio.sleep(0.05)

    async with sse_client("http://127.0.0.1:8765/sse") as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            print("small:", (await session.call_tool("echo", {"text": "x"})).content)
            try:
                # Body above the default 4 MiB max_request_body_size: the server answers 413.
                await asyncio.wait_for(session.call_tool("echo", {"text": "A" * 5_000_000}), 10)
            except TimeoutError:
                print("big: no response after 10 s")
            try:
                await asyncio.wait_for(session.call_tool("echo", {"text": "x"}), 5)
            except Exception as exc:
                print("small after:", type(exc).__name__, exc)
    uv.should_exit = True


asyncio.run(main())

Output:

small: [TextContent(type='text', text='1', annotations=None, meta=None)]
big: no response after 10 s
small after: MCPError Connection closed

The client log shows the server's answer arrived: POST .../messages/?session_id=... "HTTP/1.1 413 Request Entity Too Large", then Error in post_writer with HTTPStatusError: Client error '413 Request Entity Too Large'.

Cause

In mcp/client/sse.py, post_writer._send_message calls response.raise_for_status() (line 142 in 2.3.0). The exception propagates out of the async for loop, the outer except Exception logs Error in post_writer (line 153), and post_writer returns. Nothing reports the failure to the request that was waiting for its response, and no further messages are sent.

Expected

The request whose POST was rejected fails promptly with an error, for example an MCPError carrying the HTTP status, as the streamable HTTP client does. The session stays usable for later requests, or, if it cannot be, closes in a way that fails pending requests right away instead of leaving them to time out.

Activity

  1. AnvitDevadiga commented on Dec 1, 2026

    @AnvitDevadiga

    I reproduced this on current main (77001c9) with your script: the small call works, the 5 MB call gets a 413 that is only logged, it never resolves, and the next call fails with Connection closed.

    The cause is in post_writer in src/mcp/client/sse.py. _send_message calls response.raise_for_status(), so the HTTPStatusError escapes the per-message task group and ends the async for loop. The outer except Exception logs it and the writer stops, so the rejected request gets no reply and nothing reads the write stream after that.

    The streamable HTTP client already handles this case: for a status of 400 or more on a request, it sends a JSONRPCError with the request's id to the read stream and carries on. I'd do the same in the SSE post_writer: answer a rejected request with an error that carries the HTTP status, only log a rejected notification or response, and keep the writer running. The test would use a server that answers one POST with 413 and check that the request fails promptly and that a later request still succeeds.

    If you'd take an outside PR for this, I'm happy to write it. I used Opus 5.5 to analyze the issue and reviewed the code myself.

  2. PChanduSaiReddy commented on Dec 1, 2026

    @PChanduSaiReddy

    Hi, I'd like to work on this issue
    I've identified that the problem appears to be related to how the SSE client's post_writer handles non-2xx HTTP responses during message delivery. The HTTP exception is raised, but it doesn't appear to be propagated correctly to the corresponding pending request, potentially leaving it unresolved and causing subsequent requests to fail.

    My proposed approach is to:

    1. Investigate the exception-handling and message propagation flow in post_writer and _send_message.
    2. Ensure HTTP transport errors are properly propagated to the associated pending request.
    3. Handle pending request cleanup and task lifecycle management to prevent indefinite waits and dangling requests.
    4. Add regression tests covering HTTP 413 and other non-2xx responses, verifying that subsequent requests within the same session behave correctly.
      I'd also verify that the fix doesn't introduce regressions in existing SSE transport behaviour.

    Would it be possible to assign this issue to me? I'm happy to submit a PR following the project's contribution guidelines.

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