The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(mcp): trim the 1 MiB SSE fix to the transport argument
Tekniuma5a0a4ae3314
diff --git a/hermes_cli/mcp_config.py b/hermes_cli/mcp_config.pyindex 1c9463f93de..3bb246863c3 100644--- a/hermes_cli/mcp_config.py+++ b/hermes_cli/mcp_config.py@@ -827,13 +827,9 @@ def _probe_failure_next_step(name: str, exc: BaseException) -> str:return f"The server rejected the sign-in. Run: hermes mcp login {name}"if isinstance(root, NodeAbiMismatchError):return f"After rebuilding it under Hermes's Node as above, run: hermes mcp test {name}"- reason = _format_connect_error(exc)- if "missing executable" in reason:+ if "missing executable" in _format_connect_error(exc):return (f"Install that command, or set mcp_servers.{name}.command in {display_hermes_home()}/config.yaml ""to its full path.")- if reason.startswith("MCP response exceeded"):- return (f"The server is up but sent one response over that limit. If mcp_servers.{name}.transport is "- "sse, try removing it: Streamable HTTP accepts larger events.")return f"Check the server is running and the URL/command in its config, then run: hermes mcp test {name}"diff --git a/tests/tools/test_mcp_http_body_cap.py b/tests/tools/test_mcp_http_body_cap.pyindex 593fbf93848..8846366365f 100644--- a/tests/tools/test_mcp_http_body_cap.py+++ b/tests/tools/test_mcp_http_body_cap.py@@ -36,7 +36,7 @@ async def test_oversized_body_rejected_via_content_length():async def handler(request):return httpx.Response(200, content=body)async with _client_for(handler) as client:- with pytest.raises(httpx.ReadError, match=r"exceeded \d+ bytes \(declared Content-Length"):+ with pytest.raises(httpx.ReadError, match=r"Content-Length"):await client.get("http://mcp.test/rpc")@@ -55,7 +55,7 @@ async def test_oversized_streamed_body_rejected_without_content_length():async def handler(request):return httpx.Response(200, stream=_Stream())async with _client_for(handler) as client:- with pytest.raises(httpx.ReadError, match=r"exceeded \d+ bytes \(from"):+ with pytest.raises(httpx.ReadError, match=r"HTTP response exceeds"):await client.get("http://mcp.test/rpc")@@ -75,7 +75,7 @@ async def test_sse_event_over_cap_rejected():headers={"content-type": "text/event-stream"},)async with _client_for(handler) as client:- with pytest.raises(httpx.ReadError, match=r"exceeded \d+ bytes in one SSE event"):+ with pytest.raises(httpx.ReadError, match=r"SSE event exceeds"):async with client.stream("GET", "http://mcp.test/sse") as resp:async for _ in resp.aiter_bytes():pass@@ -126,7 +126,7 @@ async def test_sse_event_split_across_chunks_counts_prefix():headers={"content-type": "text/event-stream"},)async with _client_for(handler) as client:- with pytest.raises(httpx.ReadError, match=r"exceeded \d+ bytes in one SSE event"):+ with pytest.raises(httpx.ReadError, match=r"SSE event exceeds"):async with client.stream("GET", "http://mcp.test/sse") as resp:async for _ in resp.aiter_bytes():pass@@ -181,7 +181,7 @@ async def test_sse_crlf_split_across_chunks_inside_event_is_not_a_boundary():# the cap would evade it.chunks = [_EVENT1 + b"\r", b"\n" + _EVENT2 + b"\r\n\r\n"]async with _sse_client(chunks) as client:- with pytest.raises(httpx.ReadError, match=r"exceeded \d+ bytes in one SSE event"):+ with pytest.raises(httpx.ReadError, match=r"SSE event exceeds"):async with client.stream("GET", "http://mcp.test/sse") as resp:async for _ in resp.aiter_bytes():passdiff --git a/tests/tools/test_mcp_large_sse_event.py b/tests/tools/test_mcp_large_sse_event.pyindex 2d7f811dc82..0405ea74c90 100644--- a/tests/tools/test_mcp_large_sse_event.py+++ b/tests/tools/test_mcp_large_sse_event.py@@ -18,7 +18,6 @@ import pytestimport hermes_yaml as yamlfrom hermes_constants import get_hermes_homefrom tests.waiting import wait_until-from tools.mcp_tool_errors import _MCP_HTTP_MAX_BODY_BYTES_SERVER = """import asyncio, socket, sys@@ -95,25 +94,3 @@ def test_streamable_http_tools_list_over_one_mib_connects(catalog_server, capsysassert code == 0, outassert f"Tools discovered: {count}" in out---def test_streamable_http_event_over_hermes_cap_names_the_byte_limit(catalog_server, capsys):- url = catalog_server("http", 2, _MCP_HTTP_MAX_BODY_BYTES // 2 + 1024)-- code, out = _mcp_test(capsys, {"url": url, "connect_timeout": 20})-- assert code == 1- assert f"exceeded {_MCP_HTTP_MAX_BODY_BYTES} bytes" in out, out- assert "SSE stream ended" not in out---def test_legacy_sse_event_over_sdk_limit_names_the_byte_limit(catalog_server, capsys):- # The legacy SSE client exposes no event-size knob, so its SDK default still applies; the- # failure must say so instead of reading as a generic dropped stream.- url = catalog_server("sse", *_JUST_OVER_ONE_MIB)-- code, out = _mcp_test(capsys, {"url": url, "transport": "sse", "connect_timeout": 20})-- assert code == 1- assert f"exceeded {_SDK_DEFAULT_EVENT_LIMIT} bytes" in out, out- assert "mcp_servers.catalog.transport" in out # the next step names the setting that lifts the limitdiff --git a/tools/mcp_tool_errors.py b/tools/mcp_tool_errors.pyindex 5e85b96b051..0d48a0c941c 100644--- a/tools/mcp_tool_errors.py+++ b/tools/mcp_tool_errors.py@@ -328,9 +328,7 @@ def _make_redirect_header_stripper(httpx_mod, original_url, *, strict: bool = Fa# Finite HTTP bodies are capped at this many bytes (a larger Content-Length is rejected up front);# each SSE *event* is capped, with the counter reset at completed event boundaries so a long-lived# stream and its keepalives have no cumulative limit. Violations raise the SDK httpx's ReadError and-# flow through the ordinary transport teardown/reconnect path (#66092). The Streamable HTTP client-# hands this same bound to the SDK's own per-event SSE parser (``max_sse_event_size``), so one limit-# judges an event rather than httpx2's tighter 1 MiB default underneath it.+# flow through the ordinary transport teardown/reconnect path (#66092)._MCP_HTTP_MAX_BODY_BYTES = 10 * 1024 * 1024# An SSE event ends at a blank line: two consecutive line terminators. The spec allows CR,# LF, or CRLF terminators and permits mixing them, so the boundary is any of \n\n, \r\r,@@ -343,21 +341,13 @@ _SSE_BOUNDARY_CARRY = 3 # longest boundary ("\r\n\r\n") minus one bytedef _make_mcp_body_cap_transport(httpx_mod, inner_transport, limit: int = _MCP_HTTP_MAX_BODY_BYTES):"""Wrap ``inner_transport`` so every response body is size-capped. ``httpx_mod`` must be the SDK'sown httpx module (``sdk_httpx()``): the transport is handed to that SDK's ``AsyncClient``."""- # An oversized event is also this httpx's SSEError (httpx2; the plain httpx of mcp 1.x has none):- # the SDK fails the waiting request with an SSEError's message, while any other error mid-event- # reads as "SSE stream ended without a response" or triggers a Last-Event-ID reconnect that- # fetches the same event again.- bases = (httpx_mod.ReadError, httpx_mod.SSEError) if hasattr(httpx_mod, "SSEError") else (httpx_mod.ReadError,)- event_too_large = type("MCPEventTooLarge", bases, {})class _CappedStream(httpx_mod.AsyncByteStream):def __init__(self, inner, is_sse: bool, url: str):self._inner, self._is_sse, self._url = inner, is_sse, url- def _reject(self):- if self._is_sse:- return event_too_large(f"MCP response exceeded {limit} bytes in one SSE event (from {self._url})")- return httpx_mod.ReadError(f"MCP response exceeded {limit} bytes (from {self._url})")+ def _reject(self, kind: str):+ return httpx_mod.ReadError(f"MCP {kind} exceeds {limit} bytes (from {self._url})")async def __aiter__(self):counted = 0@@ -375,14 +365,14 @@ def _make_mcp_body_cap_transport(httpx_mod, inner_transport, limit: int = _MCP_Hif end <= len(tail):continue # boundary completed inside the carried suffix: already countedif counted + end - max(pos, len(tail)) > limit:- raise self._reject()+ raise self._reject("SSE event")counted, pos = 0, endcounted += len(window) - max(pos, len(tail))tail = window[-_SSE_BOUNDARY_CARRY:]else:counted += len(chunk)if counted > limit:- raise self._reject()+ raise self._reject("SSE event" if self._is_sse else "HTTP response")yield chunkasync def aclose(self):@@ -398,8 +388,8 @@ def _make_mcp_body_cap_transport(httpx_mod, inner_transport, limit: int = _MCP_Hwith contextlib.suppress(ValueError): # malformed header: the streamed cap still appliesif declared is not None and int(declared) > limit:await response.aclose()- raise httpx_mod.ReadError(f"MCP response exceeded {limit} bytes (declared Content-Length "- f"{declared}, from {request.url})")+ raise httpx_mod.ReadError(f"MCP HTTP response declares Content-Length {declared} > {limit} "+ f"bytes cap (from {request.url})")is_sse = "text/event-stream" in response.headers.get("content-type", "").lower()response.stream = _CappedStream(response.stream, is_sse, str(request.url))return response@@ -442,30 +432,9 @@ def _iter_exception_nodes(exc: BaseException) -> list[BaseException]:return ordered-# A response over a byte cap, in each cap's words: the wire-body cap above, and httpx2's per-event SSE-# parser limit, which the legacy SSE client cannot raise. Matched as text because on Streamable HTTP the-# SDK returns the failure as a JSON-RPC error message ("SSE stream failed: ..."), not an exception chain.-_OWN_CAP_RE = re.compile(r"MCP response exceeded \d+ bytes.*")-_SDK_EVENT_LIMIT_RE = re.compile(r"Server-sent event exceeded the (\d+) byte limit")---def _oversized_response(nodes: list[BaseException]) -> Optional[str]:- """The cap a response broke, worded alike for either cap; ``None`` when no cap tripped."""- for node in nodes:- text = str(node)- if own := _OWN_CAP_RE.search(text):- return own.group(0)- if sdk := _SDK_EVENT_LIMIT_RE.search(text):- return f"MCP response exceeded {sdk.group(1)} bytes in one SSE event (the MCP SDK's per-event limit)"- return None--def _format_connect_error(exc: BaseException) -> str:"""Render nested MCP connection errors into an actionable short message."""nodes = _iter_exception_nodes(exc)- oversized = _oversized_response(nodes)- if oversized is not None: # the whole story; "SSE stream failed" / "Connection closed" add nothing- return _sanitize_error(oversized)def _find_missing() -> Optional[str]:for current in nodes:diff --git a/tools/mcp_tool_transport.py b/tools/mcp_tool_transport.pyindex 700678d618b..32a70d2869d 100644--- a/tools/mcp_tool_transport.py+++ b/tools/mcp_tool_transport.py@@ -4,7 +4,6 @@ protocol negotiation and initial tool discovery. Split from tools/mcp_tool.py.""import loggingimport asyncio-import inspectimport osimport urllib.parseimport urllib.request@@ -80,19 +79,6 @@ def _mcp_proxy_mounts(httpx_mod, url: str, ssl_verify, client_cert, server_name:return mounts or None-def _sse_event_limit_kwargs(client_fn) -> dict:- """``max_sse_event_size`` at the wire-body cap, for an SDK Streamable HTTP client that takes it.-- Left unset, the SDK parses each SSE event against httpx2's 1 MiB default, a tighter second cap- under the wire cap: a server sending ``tools/list`` as one ~1 MiB event (a 162-tool catalog)- could not connect at all. Older SDKs take no such argument."""- try:- accepted = "max_sse_event_size" in inspect.signature(client_fn).parameters- except (TypeError, ValueError):- accepted = False- return {"max_sse_event_size": _MCP_HTTP_MAX_BODY_BYTES} if accepted else {}--def _pgroup_alive(pgid: Optional[int]) -> bool:"""Signal 0 to the group succeeds iff any member is alive (POSIX only)."""try:@@ -600,12 +586,14 @@ class MCPServerTransportMixin:**_present(mounts=_mcp_proxy_mounts(httpx, url, ssl_verify, client_cert, self.name),auth=oauth_auth)}- sdk_kwargs = _sse_event_limit_kwargs(_core.streamable_http_client)-@asynccontextmanagerasync def _owned_client_streams(): # the SDK skips cleanup when http_client is providedasync with _build_client(**client_kwargs) as http_client:- async with _core.streamable_http_client(url, http_client=http_client, **sdk_kwargs) as streams:+ # Without max_sse_event_size the SDK parses each event against httpx2's 1 MiB default,+ # a tighter second cap under our wire cap: a large tools/list or tool result (an+ # editor screenshot) failed outright.+ async with _core.streamable_http_client(url, http_client=http_client,+ max_sse_event_size=_MCP_HTTP_MAX_BODY_BYTES) as streams:yield streamsreturn _owned_client_streams()diff --git a/website/docs/user-guide/features/mcp.md b/website/docs/user-guide/features/mcp.mdindex 150c7e15d77..754de7fe2d4 100644--- a/website/docs/user-guide/features/mcp.md+++ b/website/docs/user-guide/features/mcp.md@@ -915,11 +915,9 @@ endpoint. `hermes logs --level debug` additionally shows the exact endpoint each### A server's response is too largeHermes accepts up to 10 MiB in one HTTP response, or in one SSE event of a streamed response, so a-large `tools/list` catalog or tool result fits. Anything bigger fails with-`MCP response exceeded 10485760 bytes ...`. On the legacy SSE transport (`transport: sse`) the MCP-SDK caps each event at 1 MiB and offers no way to raise it; that failure reads-`MCP response exceeded 1048576 bytes in one SSE event (the MCP SDK's per-event limit)`. If the-server also serves Streamable HTTP, remove `transport: sse` from its entry.+large `tools/list` catalog or tool result (an editor screenshot, say) fits. On the legacy SSE+transport (`transport: sse`) the MCP SDK caps each event at 1 MiB and offers no way to raise it; if+the server also serves Streamable HTTP, remove `transport: sse` from its entry.### Tools not appearing