# What happens when an instance resumes an MCP stream after a session-rebind and silently replays a truncated JSON-RPC frame **Date of Record:** 2026 November 29 **Scope:** Applies to MCP servers/clients using the HTTP-native streaming transport (SSE-over-POST, per-stream `Last-Event-ID` resumption, and `Mcp-Session-Id` rebinding). Does not apply to stdio transport, nor to stateless request/response MCP over plain JSON POST where no event stream is held open. ## Core Distinction The failure here is not "the stream dropped." Streams drop constantly and the transport is designed for it. The failure is the **resumption contract being satisfied at the transport layer while violated at the framing layer**: the client presents a valid `Last-Event-ID`, the server honors it and replays from the next event, the HTTP 200 + `text/event-stream` handshake succeeds, and yet the reassembled JSON-RPC message is corrupt because the replay boundary fell *inside* a single SSE `data:` event that had been split across multiple TCP writes (or multiple logical chunks) before the drop. Transport-level resumption is idempotent on *events*. JSON-RPC is idempotent on *messages*. These are not the same boundary, and the MCP session-rebind path lets a client re-enter the stream at an event boundary that the server considers "the last delivered event" but which the client had only *partially* consumed. The subtle part: the event ID the client echoes back is often the ID of the event it was *in the middle of receiving*, because SSE assigns the `id:` field at the top of the event and the client library records it on first sight, not on `\n\n` terminator. ## What Was Observed A tool-calling agent issued `tools/call` for a long-running operation. The server streamed progress notifications as separate SSE events, then began emitting the final `result` as one large event whose `data:` line carried a ~180 KB JSON-RPC response (a serialized document graph). The event was written in three TCP segments. After segment two, the connection reset (idle proxy timeout at 60 s, mid-write). The client's SSE reader had already parsed `id: 4471` from the event header and persisted it as `lastEventId` in the resumption state *before* the `data:` payload was complete. On reconnect it sent `Last-Event-ID: 4471`. The server's replay buffer keyed on event ID and, seeing 4471 as "already dispatched," resumed at 4472 — the *next* event, which was a small `notifications/message` heartbeat. The partial `result` event was never re-sent. The client, meanwhile, had buffered the first two segments of 4471 in its incremental parser. On the new connection it appended the 4472 payload to that orphaned buffer, producing a `data:` block that was valid UTF-8, parseable as JSON *up to the truncation point*, and terminated by the `\n\n` of the *next* event. The resulting frame deserialized successfully into a `JSONRPCResponse` whose `result` object was missing its trailing `content` array — but the object was still a syntactically valid dict. The agent's response validator did not check for required fields on the tool result; it treated the truncated result as authoritative. The agent then acted on an incomplete document graph for the next eleven turns before a downstream schema check on a *different* tool surfaced the inconsistency. Two invariants were violated simultaneously: 1. **Event-ID assignment is not a consumption acknowledgment.** SSE `id:` is a producer-side label; treating it as a consumer-side cursor conflates "sent" with "received." 2. **JSON-RPC framing must be atomic across resumption.** The transport resumed at an event boundary; the message boundary was mid-event, so the message was split and never rejoined. ## Condition of Validity The guardrail below is required *if and only if* all of the following hold: - The transport is HTTP-native streaming with `Last-Event-ID` resumption (not a request-scoped stream that dies with the response). - Events can exceed one TCP segment / one server write, so a single JSON-RPC message may span multiple `data:` lines or be split mid-payload. - The server's replay buffer is bounded (it must be — unbounded replay is a memory DoS), so replay cannot guarantee re-delivery of an arbitrarily old event. - The client persists `lastEventId` incrementally rather than committing it only after the full event terminator. If the server emits one JSON-RPC message per event and each event fits in a single small write, the window is narrow but nonzero (a reset between the header write and the data write still opens it). If the client commits `lastEventId` only on `\n\n`, the failure collapses to a benign duplicate delivery. The dangerous configuration is the common one: incremental cursor persistence + multi-segment payloads + bounded replay. ## Decision Boundary The boundary is: **does the resumption cursor advance on event-header sighting or on message-completion?** A client that advances on header sighting optimizes for at-most-once delivery of events and accepts message truncation. A client that advances on message completion optimizes for at-least-once delivery of *messages* and accepts duplicate events, which JSON-RPC tolerates only if the server deduplicates by request `id` and the client discards duplicate responses. The correct invariant is: **`Last-Event-ID` must reference the last event whose terminating `\n\n` was fully consumed AND whose JSON-RPC message was successfully framed and dispatched.** Anything earlier is a truncation hazard; anything later is a lost-message hazard. The server must additionally guarantee that replay from any ID in its buffer re-emits the *entire* event from its first byte, never a suffix — a "resume mid-event" server behavior is unimplementable correctly and must be rejected at negotiation. This must be enforced at session-rebind negotiation: when the client reconnects with a `Mcp-Session-Id` and a `Last-Event-ID`, the server must either (a) replay the full event at that ID (idempotent re-delivery) or (b) reject resumption with a `409`/`410` and force a fresh `initialize`, never (c) silently advance to the next event while the client holds a partial buffer. ## Operational Effect Without the guardrail, the failure is silent and *plausible*: a truncated tool result that deserializes cleanly, passes shallow validators, and poisons downstream reasoning for many turns. The agent has no signal that anything is wrong — the transport reported success, the JSON parsed, the schema was "close enough." Recovery requires an out-of-band consistency check (re-issuing the `tools/call` and diffing, or a required-field validator on every tool result) rather than anything the transport can surface. The concrete mitigations, in order of strength: 1. **Commit the cursor only on message completion.** Persist `lastEventId` as the ID of the last *fully framed and dispatched* JSON-RPC message, not the last event header seen. On reconnect, request replay from that ID inclusive. 2. **Idempotent full-event replay.** Server replay buffer stores complete serialized events; replay from ID `N` re-sends event `N` in full, then `N+1`, etc. Never partial. 3. **Framing checksum.** Each event carries a `data-checksum` or the JSON-RPC envelope carries a length prefix; the client rejects any frame whose reassembled length ≠ declared length. This catches mid-event truncation even if the cursor logic is wrong. 4. **Bounded-replay rejection.** If the requested `Last-Event-ID` is older than the replay buffer's floor, respond `410 Gone` and force full session re-initialization — do not silently resume from the buffer floor, which would drop messages invisibly. 5. **Required-field validation on tool results.** The last line of defense: a tool result missing fields its declared output schema requires is a hard error, not a warning. The Python below encodes the client-side cursor and framing invariant as an explicit state machine, raising on the exact condition observed: a resume that would append a new event's payload to an unterminated prior buffer, or a replay that returns a suffix rather than a full event. ```python from __future__ import annotations import json from dataclasses import dataclass, field from typing import Optional class StreamResumeTruncationError(RuntimeError): """Raised when MCP stream resumption would frame a truncated JSON-RPC message.""" @dataclass class EventFrame: event_id: str data: str complete: bool = False @dataclass class ResumeCursor: # Cursor MUST only advance on fully-consumed, fully-framed messages. last_complete_event_id: Optional[str] = None # Partial buffer for an event we have begun but not terminated. partial: Optional[EventFrame] = None seen_ids: set[str] = field(default_factory=set) class McpStreamClient: def __init__(self) -> None: self.cursor = ResumeCursor() def begin_event(self, event_id: str) -> None: if self.cursor.partial is not None: raise StreamResumeTruncationError( f"new event {event_id!r} began while event " f"{self.cursor.partial.event_id!r} was still unterminated; " f"framing would concatenate payloads" ) if event_id in self.cursor.seen_ids: # Duplicate re-delivery is legal under at-least-once; ignore payload. self.cursor.partial = EventFrame(event_id=event_id, data="", complete=True) return self.cursor.partial = EventFrame(event_id=event_id, data="") def append_data(self, chunk: str) -> None: if self.cursor.partial is None: raise StreamResumeTruncationError("data chunk with no open event") self.cursor.partial.data += chunk def terminate_event(self) -> dict: frame = self.cursor.partial if frame is None: raise StreamResumeTruncationError("terminator with no open event") if frame.complete: # duplicate; discard self.cursor.partial = None return {} try: msg = json.loads(frame.data) except json.JSONDecodeError as exc: raise StreamResumeTruncationError( f"event {frame.event_id!r} data is not valid JSON after termination: {exc}" ) from exc # COMMIT POINT: only now is the cursor allowed to advance. self.cursor.last_complete_event_id = frame.event_id self.cursor.seen_ids.add(frame.event_id) self.cursor.partial = None return msg def resume_request(self) -> dict: """Build the reconnect request. Refuses to resume mid-event.""" if self.cursor.partial is not None: raise StreamResumeTruncationError( f"cannot resume: event {self.cursor.partial.event_id!r} " f"is partially buffered; must re-request from last complete " f"event {self.cursor.last_complete_event_id!r} inclusive" ) return {"Last-Event-ID": self.cursor.last_complete_event_id} def accept_replay(self, frames: list[EventFrame]) -> list[dict]: """Server must replay FULL events from the cursor inclusive.""" out: list[dict] = [] for f in frames: if not f.complete: raise StreamResumeTruncationError( f"server replayed partial event {f.event_id!r}; " f"full-event replay is required" ) self.begin_event(f.event_id) self.append_data(f.data) out.append(self.terminate_event()) return out ```