Skip to content

The agent that grows with you

fix(mcp): count SSE events across boundaries split between chunks

beardthelionb1dfaf40b077
diff --git a/tests/tools/test_mcp_http_body_cap.py b/tests/tools/test_mcp_http_body_cap.py
index 0f57d9aedca..7d1f709fa84 100644
--- a/tests/tools/test_mcp_http_body_cap.py
+++ b/tests/tools/test_mcp_http_body_cap.py
@@ -130,3 +130,94 @@ async def test_sse_event_split_across_chunks_counts_prefix():
async with client.stream("GET", "http://mcp.test/sse") as resp:
async for _ in resp.aiter_bytes():
pass
+
+
+def _sse_client(chunks, limit=64):
+ class _Stream(httpx.AsyncByteStream):
+ async def __aiter__(self):
+ for c in chunks:
+ yield c
+
+ async def handler(request):
+ return httpx.Response(
+ 200, stream=_Stream(),
+ headers={"content-type": "text/event-stream"},
+ )
+ return _client_for(handler, limit=limit)
+
+
[email protected]("sep,cut", [
+ (b"\n\n", 1), # ...\n | \n...
+ (b"\r\n\r\n", 1), # ...\r | \n\r\n...
+ (b"\r\n\r\n", 2), # ...\r\n | \r\n...
+ (b"\r\n\r\n", 3), # ...\r\n\r | \n...
+ # The spec also allows CR terminators and mixed styles; every pairing is a boundary.
+ (b"\r\r", 1), # ...\r | \r...
+ (b"\n\r", 1), # ...\n | \r...
+ (b"\n\r\n", 1), # ...\n | \r\n...
+ (b"\n\r\n", 2), # ...\n\r | \n...
+ (b"\r\n\n", 1), # ...\r\n | \n...
+ (b"\r\n\n", 2), # ...\r\n\n | ...
+ (b"\r\n\r", 1), # ...\r\n | \r...
+ (b"\r\n\r", 2), # ...\r\n\r | ...
+ (b"\r\r\n", 1), # ...\r | \r\n...
+ (b"\r\r\n", 2), # ...\r\r | \n...
+])
+async def test_sse_boundary_split_across_chunks_still_resets(sep, cut):
+ # A completed event boundary straddling two chunks must still reset the
+ # per-event counter; otherwise the finished event's bytes are charged to
+ # the next event and the cap trips early.
+ event1 = b"data: " + b"a" * 40 + sep[:cut]
+ event2 = sep[cut:] + b"data: " + b"b" * 40 + sep
+ chunks = [event1, event2]
+ async with _sse_client(chunks) as client:
+ async with client.stream("GET", "http://mcp.test/sse") as resp:
+ async for _ in resp.aiter_bytes():
+ pass
+
+
+async def test_sse_crlf_inside_event_is_not_a_boundary():
+ # A lone CRLF ends a line, not the event. If \r\n could split the count, a
+ # multi-line event over the cap would evade it.
+ chunks = [b"data: " + b"a" * 40 + b"\r\ndata: " + b"b" * 40 + b"\r\n\r\n"]
+ async with _sse_client(chunks) as client:
+ 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
+
+
+async def test_sse_crlf_split_across_chunks_inside_event_is_not_a_boundary():
+ # Same check with the \r and \n straddling the chunk seam: the carry must not
+ # turn a mid-event line ending into a boundary.
+ chunks = [b"data: " + b"a" * 40 + b"\r", b"\ndata: " + b"b" * 40 + b"\r\n\r\n"]
+ async with _sse_client(chunks) as client:
+ 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
+
+
+async def test_sse_split_boundary_over_cap_event_still_rejected():
+ # The carry must not weaken the cap: an event genuinely over the limit is
+ # still rejected even when its preceding boundary straddled chunks.
+ chunks = [b"data: ok\n", b"\ndata: " + b"z" * 80 + b"\n\n"]
+ async with _sse_client(chunks) as client:
+ 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
+
+
+async def test_sse_boundary_split_three_ways():
+ # A \r\n\r\n boundary dribbled across three chunks still resets the count.
+ chunks = [b"data: " + b"a" * 40 + b"\r", b"\n\r", b"\ndata: " + b"b" * 40 + b"\r\n\r\n"]
+ async with _sse_client(chunks) as client:
+ async with client.stream("GET", "http://mcp.test/sse") as resp:
+ async for _ in resp.aiter_bytes():
+ pass
diff --git a/tools/mcp_tool_errors.py b/tools/mcp_tool_errors.py
index a70dac9aa8e..d74bdbb0507 100644
--- a/tools/mcp_tool_errors.py
+++ b/tools/mcp_tool_errors.py
@@ -240,7 +240,12 @@ def _make_redirect_header_stripper(original_url, *, strict: bool = False,
# 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).
_MCP_HTTP_MAX_BODY_BYTES = 10 * 1024 * 1024
-_SSE_EVENT_BOUNDARIES = (b"\n\n", b"\r\n\r\n")
+# 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,
+# \n\r, \r\n\r\n, \r\n\n, \r\n\r, \n\r\n, \r\r\n. "\r\n" alone is ONE terminator, not two:
+# the lookahead keeps a plain CRLF line ending from backtracking into a \r + \n boundary.
+_SSE_BOUNDARY_RE = re.compile(rb"(?:\r\n|\r(?!\n)|\n){2}")
+_SSE_BOUNDARY_CARRY = 3 # longest boundary ("\r\n\r\n") minus one byte
def _make_mcp_body_cap_transport(httpx_mod, inner_transport, limit: int = _MCP_HTTP_MAX_BODY_BYTES):
@@ -256,18 +261,24 @@ def _make_mcp_body_cap_transport(httpx_mod, inner_transport, limit: int = _MCP_H
async def __aiter__(self):
counted = 0
+ tail = b"" # last _SSE_BOUNDARY_CARRY stream bytes; a boundary can straddle chunks
async for chunk in self._inner:
if self._is_sse:
- # Bytes up to the last completed event boundary belong to finished events (they must
- # still fit the per-event cap together with the carried prefix); the remainder starts
- # the next event's budget.
- boundary_end = max(chunk.rfind(sep) + len(sep) if sep in chunk else -1 for sep in _SSE_EVENT_BOUNDARIES)
- if boundary_end != -1:
- if counted + boundary_end > limit:
+ # Charge each completed event once: the carried prefix plus bytes up to its
+ # boundary must fit the cap, then the next event starts after it. Scan the
+ # carried suffix plus this chunk so a boundary split across chunks is still
+ # seen; bytes before len(tail) were already counted into `counted`.
+ window = tail + chunk
+ pos = 0
+ for match in _SSE_BOUNDARY_RE.finditer(window):
+ end = match.end()
+ if end <= len(tail):
+ continue # boundary completed inside the carried suffix: already counted
+ if counted + end - max(pos, len(tail)) > limit:
raise self._reject("SSE event")
- counted = len(chunk) - boundary_end
- else:
- counted += len(chunk)
+ counted, pos = 0, end
+ counted += len(window) - max(pos, len(tail))
+ tail = window[-_SSE_BOUNDARY_CARRY:]
else:
counted += len(chunk)
if counted > limit: