Skip to content

Tool results over 1 MiB cannot be received over SSE or streamable HTTP, and the limit is not configurable #3803

Open

Description

@gowthamrao

Summary

A tool result larger than 1 MiB can never reach a client on an HTTP transport. The client opens every SSE stream with httpx2's default DEFAULT_MAX_EVENT_SIZE_BYTES = 1024 * 1024:

  • in mcp/client/sse.py, through client.sse(url);
  • in mcp/client/streamable_http.py, through EventSource(response) in _handle_sse_response, the path a POST's response (and so a tools/call result) takes.

Neither sse_client nor streamable_http_client takes a size parameter. A custom http_client cannot change it either, because the size is a per-call argument of client.sse(...) / EventSource(...), not client configuration. The same result is delivered intact over stdio.

The failures also differ by transport:

  • SSE: the call fails with MCPError(-32000, 'Connection closed'), and the transport's task group then dies with SSEError('Server-sent event exceeded the 1048576 byte limit.'), so the whole session is lost.
  • Streamable HTTP: the call fails with MCPError(-32000, 'SSE stream ended without a response'), which does not mention the size limit; the session survives.

Reproducer (self-contained: an MCPServer on loopback and the SDK clients)

import asyncio
import socket
import threading
import time

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

server = MCPServer(name="big-result")

@server.tool()
async def big(megabytes: int) -> str:
    """Return `megabytes` MiB of text."""
    return "x" * (megabytes * 1024 * 1024)

def serve(app) -> int:
    with socket.socket() as sock:
        sock.bind(("127.0.0.1", 0))
        port = sock.getsockname()[1]
    uv = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="error"))
    threading.Thread(target=uv.run, daemon=True).start()
    while not uv.started:
        time.sleep(0.05)
    return port

async def call(label: str, transport_cm) -> None:
    try:
        async with transport_cm as streams, ClientSession(streams[0], streams[1]) as session:
            await session.initialize()
            for mb in (0, 2):
                try:
                    result = await asyncio.wait_for(session.call_tool("big", {"megabytes": mb}), 30)
                    print(f"  {label} {mb} MiB: ok, is_error={result.is_error}")
                except BaseException as exc:
                    print(f"  {label} {mb} MiB: {type(exc).__name__}: {exc!r:.160}")
    except BaseException as exc:
        print(f"  {label} session exit: {type(exc).__name__}: {exc!r:.200}")

async def main() -> None:
    sse_port = serve(server.sse_app())
    http_port = serve(server.streamable_http_app())
    await call("sse", sse_client(f"http://127.0.0.1:{sse_port}/sse"))
    await call("streamable-http", streamable_http_client(f"http://127.0.0.1:{http_port}/mcp"))

asyncio.run(main())

Output:

  sse 0 MiB: ok, is_error=False
  sse 2 MiB: MCPError: MCPError(-32000, 'Connection closed', None)
  sse session exit: ExceptionGroup: ExceptionGroup('unhandled errors in a TaskGroup', [SSEError('Server-sent event exceeded the 1048576 byte limit.')])
  streamable-http 0 MiB: ok, is_error=False
  streamable-http 2 MiB: MCPError: MCPError(-32000, 'SSE stream ended without a response')

Expected vs actual

Expected Actual
Large results delivered up to a size the caller can configure (for example max_event_size on sse_client / streamable_http_client, passed through to client.sse(...) and EventSource(...)) hard 1 MiB cap per SSE event, with no way to change it
When the cap is hit the call fails with an error that names the limit; the session survives SSE: the session dies; streamable HTTP: a generic "stream ended" error with no mention of size

Servers that return documents, graph results or large search results routinely exceed 1 MiB.

Environment

  • mcp 2.0.0, httpx2 2.13.0, anyio 4.14.2, uvicorn (from the SDK's dependency set)
  • CPython 3.14.10
  • Windows 11. Linux not tried; the limit comes from httpx2's default and is platform-independent.

Workaround

None at the transport level. Downstream, the result-size limit is now an explicit host setting: oversized or failed calls are turned into a structured tool error naming the failure class, and each session is isolated so a transport failure cannot cancel the caller.

Activity

  1. added
    bugSomething isn't working
    v2Affects the v2 line (2.x on main)
    on Nov 3, 2026
  2. Shanmukh-l33t commented on Nov 4, 2026

    @Shanmukh-l33t

    Half of this is already fixed upstream — the remaining gap is the legacy SSE transport, and I have a tested fix ready.

    What landed since this report: the Streamable HTTP half shipped in #3600 (merged 2026-10-01, released in v2.3.0 on 2026-10-02): streamable_http_client(url, max_sse_event_size=...) and StreamableHttpParameters.max_sse_event_size, default unchanged at 1 MiB, None disables. The tested version above (2.0.0, 2026-07-28) predates it. On current main (af4c6f4) the reproducer's streamable-http leg passes 2 MiB fine with the limit raised, and with the default the one oversized call fails without killing the session.

    What is still broken (the SSE leg of the repro): mcp/client/sse.py has no size parameter at all — sse_within_origin hardcodes the 1 MiB default (mcp/shared/_httpx_utils.py), so a >1 MiB result still fails with MCPError(-32000, 'Connection closed') and takes the whole session with it. Prior art for the shape: #3338 covered every client SSE reader but was closed by its author after #3600 landed (it wasn't a maintainer rejection — the legacy path was just left out of scope of #3600).

    Fix, tested, on my fork: fix/sse-client-max-event-size (99e6d2d4):

    • sse_client(..., max_sse_event_size: int | None = DEFAULT_MAX_SSE_EVENT_SIZE) — same name, default and None semantics as streamable_http_client; nonpositive values raise ValueError("max_sse_event_size must be positive or None") before any request, matching StreamableHTTPTransport. Passed through sse_within_origin to the EventSource.
    • DEFAULT_MAX_SSE_EVENT_SIZE moves to mcp.shared._httpx_utils as the single definition both transports share (streamable_http keeps re-exporting it).
    • docs/client/transports.md notes the option on sse_client.

    Testing evidence:

    • Regression tests: a 2 MiB tool-result round trip over the in-process SSE app fails pre-fix (TypeError: sse_client() got an unexpected keyword argument 'max_sse_event_size') and delivers intact with the limit raised (sabotage run without the src change: 3 failed / 3 passed — the 3 seam guards pass by design). Seam tests at sse_within_origin pin the unchanged default (oversized event raises httpx2.SSEError, never truncated), a raised limit, and None, plus the ValueError cases.
    • Full suite: 6231 passed, 8 skipped, 1 xfailed — the sole failure is test_permission_error, which fails identically on pristine main in a root environment (unrelated). coverage report: 100.00%, 0 partial branches (fail_under = 100 passes). strict-no-cover clean. ruff check/ruff format --check and pyright clean.

    One observation from the repro: on the SSE death path the transport leaks its internal memory streams (unclosed MemoryObjectSendStream/MemoryObjectReceiveStream warnings at GC time) — consistent with "the whole session is lost" being unclean teardown. Worth folding into whoever takes the error-semantics half (the report's ask that the error name the limit is still open; the streamable side already prefixes SSE stream failed: and lets httpx2's message name the limit).

    I'm not opening a PR here since unassigned-contributor PRs get auto-closed by the repo policy — the branch is ready for a maintainer to take as-is, or I'm happy to open a PR if invited.

    AI disclosure: investigation, fix and tests were produced with AI assistance and reviewed and run by me.

  3. media-ctrl commented on Nov 4, 2026

    @media-ctrl
  4. lennardm commented on Nov 4, 2026

    @lennardm

    Same here on mcp 2.2.0 / httpx2 2.12.0 (Windows 11, Python 3.13): a ~1.19 MB tools/call result from a remote streamable-HTTP MCP server failed deterministically with SSE stream ended without a response. A raw HTTP capture showed the server sent one complete, valid event; the SSEError only shows up with mcp debug logging on.

    We work around it by wrapping mcp.client.streamable_http.EventSource so it defaults to max_event_size=32 * 1024 * 1024. A max_sse_event_size option on streamable_http_client (and surfacing the SSEError text in the synthesized error) would let us drop that monkeypatch.

  5. Shanmukh-l33t commented on Nov 4, 2026

    @Shanmukh-l33t

    @lennardm both of your asks are already on main since 2.2.0 — I diffed v2.2.0 against main to be sure:

    1. streamable_http_client(..., max_sse_event_size=DEFAULT_MAX_SSE_EVENT_SIZE) (src/mcp/client/streamable_http.py:718 on main; None disables the limit) is threaded into every client.sse(...) / EventSource(...) call in the transport, so the EventSource monkeypatch can go as soon as you're past 2.2.0.
    2. The size rejection is surfaced: main has an except httpx2.SSEError as exc: branch synthesizing "SSE stream failed: {exc}" (:503-506), so the waiter learns "Server-sent event exceeded the 1048576 byte limit." In v2.2.0 there is no SSEError branch at all — the stream falls through to the generic handler and the waiter gets the bare "SSE stream ended without a response" (:499 there), which is the confusing failure your capture shows. That matches why it only appeared with debug logging on.

    What's genuinely still open matches @media-ctrl's split:

    • the legacy sse_client (src/mcp/client/sse.py:36) still has no event-size knob on main — that's what my branch adds (fix/sse-client-max-event-size at 99e6d2d4933697942796bdf83118fd9e09eaea2a, compare: main...Shanmukh-l33t:python-sdk:fix/sse-client-max-event-size): the same parameter threaded into client.sse(...), sharing DEFAULT_MAX_SSE_EVENT_SIZE, so both transports accept the same event sizes. The sse_client side kills the session on overflow rather than failing one call, which is the asymmetry worth closing.
    • a named error for size rejection — agreed that a client-side limit deserves more than message text; today catching it means string-matching SSEError text, and the same overflow manifests differently per transport.
    • one docs sentence on the 1 MiB default and the knob. A tool returning a screenshot or a CSV crosses it, and both failure modes read like transport faults.

    (Written with AI assistance; the version diff and line references were re-verified against main and v2.2.0 today.)

  6. SalyyS1 commented on Nov 11, 2026

    @SalyyS1

    While streamable_http_client(..., max_sse_event_size=...) landed on main (and sse_client still needs the same parameter threaded through mcp/client/sse.py), it is worth noting what happens one layer up when a tools/call response actually exceeds 1 MiB:

    A 1.19 MB JSON-RPC tools/call payload corresponds to roughly 280,000 to 320,000 tokens, which will immediately overflow the context window of most LLM providers (128k to 200k tokens) right after the SSE transport delivers it. In practice, payloads over 1 MiB almost always come from pretty-printed JSON arrays with repetitive null/""/[] fields, noisy hypermedia URLs, or un-truncated log output.

    If you are connecting to an MCP server whose tool responses occasionally spike above 1 MiB (or if you are stuck on mcp <= 2.2.0 / legacy SSE), you can place mcp-slim in front of the server command:

    mcp-slim run -- <server-command>

    mcp-slim's OutputSlimmer intercepts tools/call responses on the wire, strips empty/null keys and hypermedia noise, minifies JSON/JSONL/Markdown tables, flattens verbose resource wrappers, and applies head+tail elision on oversized string fields—typically shrinking multi-megabyte JSON tool outputs well below the 1048576-byte SSE event cap while cutting LLM context token consumption by 43% to 75%.

  7. area51tazz commented on Nov 17, 2026

    @area51tazz

    Confirming the SSE half on a real deployment, plus measurements on 2.3.0 and main, in case they help.

    Where we hit it. An agent host on mcp 2.3.0 / httpx2 2.12.0 (CPython 3.14, Linux) talks to a crawl4ai MCP server over transport: sse through a reverse proxy. A tools/call that converted a ~4.3 MB page to markdown failed with httpx2.SSEError: Server-sent event exceeded the 1048576 byte limit., the session was lost, and an immediate retry failed the same way. The server logged a completed fetch both times. Calls in the same deployment returning 323,134 and 645,823 characters succeeded. The host has no way to raise the limit, because sse_client() doesn't take one.

    Measured locally (loopback MCPServer, one fresh session per probe):

    largest result that passes smallest that fails
    text-only result (structured_output=False), SSE and streamable HTTP 1,048,467 B 1,048,468 B
    default str tool, SSE and streamable HTTP 524,216 B 524,217 B
    • Identical on 2.3.0 and on main (77001c9). sse_client on main still has no size parameter.
    • The default str tool sends the payload twice (text content plus structuredContent), so its effective ceiling is about 512 KiB, not 1 MiB. That may be worth noting in the docs whatever happens to this issue.
    • The count is per SSE event, field lines included (httpx2 _sse.py:90). Framing costs 109 bytes for a text-only result and 144 for the structured one.
    • After the failure, SSE loses the session (the next 10-byte call fails Connection closed). Streamable HTTP keeps the session, and on 2.3.0 its error now names the limit (SSE stream failed: Server-sent event exceeded the 1048576 byte limit.).
    • Streamable HTTP with max_sse_event_size=8 << 20 (or None) delivers a 4 MiB result on 2.3.0.

    #3832 fixes the SSE half. I applied its diff to main (77001c9), unchanged. sse_client(url, max_sse_event_size=8 << 20) and =None both deliver a 4 MiB result, and the default boundary is unchanged (1,048,467 passes, 1,048,468 fails). tests/shared/test_sse.py and tests/client/test_session_group.py pass (43, against 40 on main). The change is small because sse_within_origin() already accepts max_event_size. sse_client just never passes it (client/sse.py:70).

    Repro (loopback only, mcp ≥ 2.3.0 + uvicorn; the last line prints whether sse_client has the parameter):

    """#3803: where the 1 MiB SSE event cap bites, per transport, and whether it can be raised."""
    import asyncio, inspect, socket, threading, time
    
    import uvicorn
    from mcp import ClientSession
    from mcp.client.sse import sse_client
    from mcp.client.streamable_http import streamable_http_client
    from mcp.server.mcpserver import MCPServer
    
    server = MCPServer(name="big-result")
    
    
    @server.tool(structured_output=False)
    async def text(n: int) -> str:
        """n bytes, as text content only."""
        return "x" * n
    
    
    @server.tool()
    async def structured(n: int) -> str:
        """n bytes; the default str tool also sends structuredContent, so the payload goes twice."""
        return "x" * n
    
    
    def serve(app) -> str:
        with socket.socket() as s:
            s.bind(("127.0.0.1", 0))
            port = s.getsockname()[1]
        uv = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="critical"))
        threading.Thread(target=uv.run, daemon=True).start()
        while not uv.started:
            time.sleep(0.02)
        return f"http://127.0.0.1:{port}"
    
    
    async def run(label, cm, calls):
        try:
            async with cm as (r, w, *_), ClientSession(r, w) as session:
                await session.initialize()
                for tool, n in calls:
                    try:
                        res = await asyncio.wait_for(session.call_tool(tool, {"n": n}), 60)
                        print(f"{label:28} {tool:10} {n:>9,}: ok ({len(res.content[0].text):,} chars)")
                    except Exception as e:
                        print(f"{label:28} {tool:10} {n:>9,}: {type(e).__name__}: {e}")
        except BaseException as e:
            inner = getattr(e, "exceptions", [e])[0]
            print(f"{label:28} session died: {type(inner).__name__}: {inner}")
    
    
    async def main():
        sse, http = serve(server.sse_app()) + "/sse", serve(server.streamable_http_app()) + "/mcp"
        edge = [("text", 1_048_467), ("text", 1_048_468)]
        half = [("structured", 524_216), ("structured", 524_217)]
        after = [("text", 10)]  # does the session survive the failed call?
        await run("sse, default", sse_client(sse), edge[:1] + half[:1])
        await run("sse, default", sse_client(sse), edge[1:] + after)
        await run("streamable-http, default", streamable_http_client(http), edge + half + after)
        await run("streamable-http, max=8 MiB", streamable_http_client(http, max_sse_event_size=8 << 20),
                  [("text", 4 << 20)])
        if "max_sse_event_size" in inspect.signature(sse_client).parameters:
            await run("sse, max=8 MiB", sse_client(sse, max_sse_event_size=8 << 20), [("text", 4 << 20)])
        else:
            print("sse_client has no max_sse_event_size parameter")
    
    
    asyncio.run(main())

    Output on 2.3.0:

    sse, default                 text       1,048,467: ok (1,048,467 chars)
    sse, default                 structured   524,216: ok (524,216 chars)
    sse, default                 text       1,048,468: MCPError: Connection closed
    sse, default                 text              10: MCPError: Connection closed
    sse, default                 session died: SSEError: Server-sent event exceeded the 1048576 byte limit.
    streamable-http, default     text       1,048,467: ok (1,048,467 chars)
    streamable-http, default     text       1,048,468: MCPError: SSE stream failed: Server-sent event exceeded the 1048576 byte limit.
    streamable-http, default     structured   524,216: ok (524,216 chars)
    streamable-http, default     structured   524,217: MCPError: SSE stream failed: Server-sent event exceeded the 1048576 byte limit.
    streamable-http, default     text              10: ok (10 chars)
    streamable-http, max=8 MiB   text       4,194,304: ok (4,194,304 chars)
    sse_client has no max_sse_event_size parameter
    

    On main with #3832 applied, the last line becomes sse, max=8 MiB text 4,194,304: ok (4,194,304 chars), and every other line is the same.

    Not verified: the byte size of our real failing result (our logs record the limit and the failure, not the size).

    Disclosure: the diagnosis, measurements and this comment were prepared with AI assistance (Claude).

  8. MrGaziz commented on Nov 18, 2026

    @MrGaziz

    Hi, we're hitting the SSE half of this in production too (mcp 2.3.0).
    Our stdio MCP servers are exposed over SSE through supergateway, so any tool result over ~1 MiB fails and the session is lost.
    We've worked around it by patching mcp.client.sse.sse_within_origin with a larger max_event_size, but we'd much rather use a supported option.

    Would a maintainer be open to adding max_sse_event_size to sse_client, the same as streamable_http_client got in #3600?
    There's already a tested change for it (#3832, auto-closed because nobody was assigned).
    Happy to help test it.

    Thanks for all the work on v2!

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

    bugSomething isn't workingv2Affects the v2 line (2.x on main)

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions