# How does an instance detect a torn SSE event-stream boundary during MCP HTTP-native transport session resumption **Date of Record:** 2026 December 2 **Scope:** Applies to MCP servers/clients using the HTTP-native transport with `text/event-stream` responses and `Last-Event-ID`-based resumption (Streamable HTTP, single-stream or multiplexed). Does not apply to stdio transports, nor to transports that carry whole-message framing (e.g., WebSocket frames or length-prefixed pipes) where partial reads are impossible. ## Core Distinction The failure this record isolates is not "connection dropped." It is the distinction between **a resumable gap** and a **silently truncated event**. On an SSE stream, an event is only a valid unit once its terminating `\n\n` has been observed and its `data:` lines have been joined. A TCP/HTTP read that returns mid-event is normal and expected; the client must buffer. The dangerous boundary is different: the client resumes with `Last-Event-ID: N`, the server replays from `N+1`, and the client now has a *buffer containing the tail half of event N* from before the drop, immediately followed by the *head of event N+1* from the replay. If the client appends replay bytes onto the stale partial buffer without discarding it, the two fragments fuse into a single malformed event whose `data:` payload is a concatenation of the truncated `N` and the leading bytes of `N+1`. The event ID attached to that fused blob is `N+1`, so the corruption is *forward-labeled*: it looks like a legitimate future event and the dedup logic (which keys on ID) will never flag it. The non-obvious part: the SSE spec's `Last-Event-ID` semantics are defined on the *last fully dispatched event*, not on the last byte received. A naive client that tracks "highest byte offset" or "last partial line seen" as its resume cursor will resume at the wrong place. The invariant is: **the resume cursor must be the ID of the last event whose terminator was consumed, and any un-terminated tail buffer must be discarded at resume time, not merged.** Violating it produces a class of corruption that is invisible to ID-based dedup and only surfaces as a downstream JSON parse failure — or worse, as a valid-but-wrong tool result if the fused payload happens to parse. ## What Was Observed A client agent was mid-`tools/call` over Streamable HTTP. The server was emitting progress notifications and then the final result as separate SSE events with monotonically increasing `id:` fields. At event id 47 (a large `notifications/progress` payload, ~9 KB, split across multiple `data:` lines), the underlying connection was reset by a middlebox after ~200 ms of idle. The client's read loop had consumed roughly 6 KB of event 47's `data:` lines but had not yet seen the `\n\n` terminator. The client's reconnect logic did the following, in order: 1. Reconnected and sent `Last-Event-ID: 47` — because it had recorded "last event id seen" as 47 the moment the `id:` line of event 47 was parsed, *before* the event body completed. 2. Received replay beginning at event 48 (server honored `47` as "resume after 47"). 3. Appended the replay bytes to its existing read buffer, which still held the 6 KB partial body of event 47. Resulting buffer: `data: {...truncated event 47 JSON...` immediately followed by `id: 48\ndata: {...event 48 JSON...}\n\n`. The SSE parser, scanning for `\n\n`, found the first terminator at the end of event 48 and dispatched a single event whose `data:` was `{...truncated 47...id: 48\ndata: {...48...}`. That blob is not valid JSON, so the JSON-RPC layer raised a parse error and the client aborted the whole session — losing the in-flight tool result. In a second reproduction, event 47 was a short progress ping and the fused payload *did* parse as JSON (the truncation happened to land on a comma), producing a progress notification with a corrupted `progress` value that the agent then used to recompute an ETA and mis-schedule a retry. Two distinct downstream symptoms, one root cause: resume cursor advanced past the last *dispatched* event, and the partial tail was not discarded. ## Condition of Validity The guardrail below is valid only when all of the following hold: - The transport is SSE over HTTP and the server honors `Last-Event-ID` with "resume strictly after the given ID" semantics. If the server replays *inclusive* of the given ID, the client must dedup the replayed event by ID before dispatch — and the discard-partial rule still applies, because the partial tail is still not a dispatched event. - Event IDs are monotonic and unique within the session. If the server can reuse IDs across reconnects, ID-based resume is unsound regardless of buffering discipline. - The client's SSE parser is a streaming parser that emits events only on a full `\n\n` terminator. A parser that emits on `\n` or on connection close will violate the invariant before the resume logic is even reached. - The reconnect path is the *only* writer to the read buffer between drop and replay. If a background reader thread can still append bytes from the old socket after the new socket is attached, the discard must be atomic with respect to both. It does not hold when the server multiplexes multiple logical streams onto one SSE connection with per-stream IDs; in that case the resume cursor must be per-stream, and the discard-partial step must discard only the partial for the stream being resumed. ## Decision Boundary At reconnect, the client has two candidate buffers: the stale partial tail (bytes after the last `\n\n`) and the fresh replay bytes. The decision is binary and must be made *before* the parser sees the concatenation: - **Discard the partial tail.** Correct. The last dispatched event is the resume anchor; its ID goes in `Last-Event-ID`; the partial tail belongs to an event the server will re-send (if it resumes from before that event) or has already been superseded (if it resumes after). Either way the tail is not authoritative. - **Merge the partial tail with replay.** Incorrect in every case. It fuses two events, forward-labels the corruption with the replayed event's ID, and defeats ID-based dedup. The boundary is sharp because the two options are indistinguishable from the buffer's byte content alone — both produce a byte stream that the parser will happily dispatch. The discriminator is *provenance*: bytes from before the drop must never be concatenated with bytes from after the drop. The invariant to enforce is a buffer generation counter: increment on every reconnect, tag every buffered byte with its generation, and refuse to let the parser consume a buffer spanning two generations. A second boundary: the resume cursor must be updated *only* on dispatch, never on `id:` line parse. The `id:` line of an event is visible before its body is complete; a client that latches the cursor there will resume past an event it never fully received. This is the exact trigger in the observed incident. ## Operational Effect Enforcing the invariant changes the failure mode from silent corruption to a bounded, observable gap. When the partial tail is discarded and the cursor is the last dispatched ID, a reconnect either (a) replays the in-flight event cleanly, or (b) if the server has already advanced past it, surfaces a genuine missing-event condition that the client can detect by comparing the first replayed ID to `last_dispatched_id + 1`. That gap check is the second half of the guardrail: if the first replayed ID is not `last_dispatched_id + 1`, the client knows it lost an event and must fail the in-flight request rather than proceed with a hole in the notification stream. The cost is a small amount of re-delivery (the in-flight event is re-sent) and one extra comparison per reconnect. The benefit is that the fused-payload corruption class — which is invisible to ID dedup, can parse as valid JSON, and can silently poison agent reasoning — is eliminated at the transport layer rather than being chased downstream in the JSON-RPC or tool-result layer. ```python import json from dataclasses import dataclass, field class TornStreamResumeError(RuntimeError): """Raised when a resume would fuse a pre-drop partial event with replayed bytes.""" @dataclass class SseResumeState: last_dispatched_id: int = 0 generation: int = 0 partial_tail: bytes = field(default=b"") def begin_resume(state: SseResumeState, first_replayed_id: int) -> int: """ Prepare a resume. Enforces two invariants: 1. The partial tail from before the drop is discarded, never merged. 2. The resume cursor is the last *dispatched* event id, and the first replayed id must be exactly last_dispatched_id + 1 (no silent gap). Returns the id to send in Last-Event-ID. """ if state.partial_tail: # Bytes after the last terminator belong to an event we never fully # received. Merging them with replay fuses two events and forward-labels # the corruption with the replayed event's id. state.partial_tail = b"" state.generation += 1 expected_next = state.last_dispatched_id + 1 if first_replayed_id != expected_next: raise TornStreamResumeError( f"resume gap: last dispatched id={state.last_dispatched_id}, " f"expected replay to start at {expected_next}, got {first_replayed_id}; " f"refusing to resume with a hole in the event stream" ) return state.last_dispatched_id def dispatch_event(state: SseResumeState, raw_event: bytes) -> dict: """ Dispatch a fully-terminated SSE event. The cursor advances only here, never on id-line parse. """ if not raw_event.endswith(b"\n\n"): raise TornStreamResumeError( "dispatch called on un-terminated event; parser must emit only on \\n\\n" ) event_id = None data_lines = [] for line in raw_event.decode("utf-8").splitlines(): if line.startswith("id:"): event_id = int(line[3:].strip()) elif line.startswith("data:"): data_lines.append(line[5:].lstrip()) payload = json.loads("\n".join(data_lines)) if event_id is not None: if event_id <= state.last_dispatched_id: raise TornStreamResumeError( f"non-monotonic event id {event_id} after {state.last_dispatched_id}" ) state.last_dispatched_id = event_id return payload ```