# Which invariants prevent MCP streamable-HTTP session resumption from replaying a partial tool-call frame into a fresh SSE stream **Date of Record:** 2026 November 23 **Scope:** Applies to MCP servers and clients using the streamable-HTTP transport (single POST endpoint, optional SSE upgrade, `Mcp-Session-Id` header, `Last-Event-ID` resumption). Does not cover stdio transport, nor WebSocket-based custom transports, nor resumption of *server-to-client* notifications that were never assigned an event ID. ## Core Distinction The failure that matters is not "the SSE connection dropped." That is normal and recoverable. The failure is **resuming a stream at the wrong byte boundary of a JSON-RPC message and treating the replayed fragment as a complete frame**. MCP streamable-HTTP allows a client to reconnect to a session and pass `Last-Event-ID` to ask the server to replay events after that ID. The naive invariant — "replay all events with sequence > Last-Event-ID" — is wrong because a single JSON-RPC response (especially a tool result or a chunked `notifications/progress` sequence) may be split across *multiple* SSE events, and the client may have received and acknowledged event N while event N contained only the first half of a `tools/call` result object. The correct invariant is **event-ID monotonicity is necessary but not sufficient; resumption must be gated on message-completeness, not event-completeness**. An event ID must only be advanced (and only reported back as `Last-Event-ID`) at a JSON-RPC message boundary, or the server must retain enough per-event framing metadata to reconstruct the message from the suffix of events. ## What Was Observed A tool-calling agent issued `tools/call` for a long-running retrieval tool. The server streamed the result as three SSE events because the payload exceeded its internal 8 KB flush threshold: - `id: 41` — `data: {"jsonrpc":"2.0","id":"c7","result":{"content":[{"type":"text","text":"...first 6KB...` - `id: 42` — `data: ...continued 6KB...` - `id: 43` — `data: ...final 2KB..."}]}}` Mid-stream the client's TCP connection reset. The client had processed events 41 and 42 into its SSE buffer but had **not** yet parsed a complete JSON object (the parser was waiting for the closing braces). On reconnect the client sent `Last-Event-ID: 42` — because 42 was the last event it had *received*, which is the natural thing to report. The server, honoring the literal contract, replayed from event 43 onward. The client's SSE layer concatenated the retained buffer (events 41+42) with the replayed event 43 and parsed successfully — in this instance. But in a second incident the client had flushed its buffer between reconnects (context-window pressure evicted the partial frame, or the process restarted), so it received only event 43: a JSON fragment `...final 2KB..."}]}}` with no opening. The JSON parser raised, the client marked the tool call failed, and the agent — reasoning over a "tool error" — retried the call. The tool was non-idempotent (it appended to a store), so the retry duplicated the side effect. The root cause is a **resumption-acknowledgement ambiguity**: "last event ID received" is not the same as "last message ID durably committed." The transport spec permits resumption at event granularity; the JSON-RPC layer requires message granularity. Nothing in the naive implementation reconciles the two. ## Condition of Validity The bug is bounded by three conditions, all of which must hold for the corruption to occur: 1. **Message fragmentation across events.** The server's flush policy splits a single JSON-RPC message across ≥2 SSE events. This happens whenever the message exceeds the server's write buffer, or when the server interleaves `notifications/progress` between chunks of a response. 2. **Client-side partial-frame loss.** The client either (a) does not persist the partial message buffer across the reconnect, or (b) persists it but the server's replay does not align with what the client retained (double-counting or gap). Both arise because the client's durable state is the *event* cursor, while its in-memory state is the *message* buffer, and the two are not checkpointed atomically. 3. **Non-idempotent or state-mutating tool.** If the tool is a pure read, the worst outcome is a wasted retry. If it mutates state, the partial-replay → parse-error → retry path produces duplicate effects, which is the actual operational harm. If any condition fails, the failure does not manifest. A server that never fragments messages (one message = one event, with `id` assigned only at message completion) is immune even with a naive client. A client that atomically persists `(Last-Event-ID, partial_message_buffer)` is immune even against a fragmenting server, provided the server replays strictly after the acknowledged event — but *only if* the client never acknowledges an event whose message is incomplete. That last clause is the invariant. ## Decision Boundary The boundary is: **may the client advance `Last-Event-ID` past an event that belongs to an incomplete JSON-RPC message?** - **No** (correct): the client tracks two cursors — `last_complete_message_event_id` and `last_received_event_id`. On reconnect it resumes from `last_complete_message_event_id` and discards any retained partial buffer for the in-flight message. The server must therefore retain events from the last *completed* message, not merely the last event. This requires the server to keep a replay window keyed on message boundaries. - **Yes, with buffer persistence** (fragile): the client resumes from `last_received_event_id` and *must* atomically persist the partial buffer with that cursor. This is correct only if the persistence is crash-consistent and the server's replay is exactly contiguous. Any gap (server GC'd event 42 but kept 43) produces silent corruption, not a clean error. - **Yes, naively** (the observed failure): resume from `last_received_event_id`, drop the partial buffer. Guaranteed to produce a fragment-without-header on the next message boundary. This is the default behavior of several reference clients and is the specific defect. The guardrail is a **message-boundary acknowledgement protocol**: the server assigns `id` to an event only when that event completes a JSON-RPC message (or, for fragmented messages, marks the final fragment with the resumable ID and earlier fragments with non-resumable IDs). The client's `Last-Event-ID` is then by construction a message boundary, and replay can never begin mid-message. This is the invariant: **resumable event IDs are a subset of event IDs, and the subset is exactly the message-terminating events.** ## Operational Effect Consequences for an agent runtime: - **Duplicate side effects on non-idempotent tools.** The parse-error → retry path is indistinguishable from a genuine tool failure to the reasoning loop. The agent must not treat a stream-resumption parse error as a tool error; it must treat it as a *transport* error and resume rather than re-invoke. This requires the client to distinguish `ResumptionFragmentError` from `ToolExecutionError` and to surface the former to the transport layer, never to the model. - **Silent success corruption.** In the case where the retained buffer happens to complete the message (incident one above), the client reports success — but the server may have replayed events the client already applied, double-counting progress notifications. For `notifications/progress` this inflates the progress counter; for token-budget accounting it can prematurely exhaust or under-count. - **Context-window interaction.** Partial buffers are cheap to keep in memory but are exactly the kind of state that gets evicted under context pressure. The eviction is silent and converts a recoverable resumption into a corrupt one. The buffer must be persisted outside the context window (on disk, keyed by session + message ID), not held in the model's working context. - **Backpressure coupling.** When the server applies backpressure (stops reading, buffers writes), it may coalesce multiple messages into one flush, changing the fragmentation pattern between the original stream and the replay. A client that assumed "event 42 was the last fragment of message c7" may find, on replay, that the server now emits c7 as a single event 42′. The client must key on JSON-RPC `id`, not on event counts, to reconcile. The bounded, safe design: server assigns resumable IDs only at message completion; client persists `(session_id, last_complete_message_event_id)` atomically and never acknowledges a partial message; on any resumption parse anomaly the client raises a transport-level error and reconnects from the last complete message boundary rather than retrying the tool. ```python import json from dataclasses import dataclass, field class ResumptionFragmentError(RuntimeError): """Raised when a resumed SSE stream yields a JSON-RPC fragment that does not begin at a message boundary. Must be handled as a transport error, never surfaced to the reasoning loop as a tool failure.""" @dataclass class MessageBoundaryCursor: session_id: str last_complete_message_event_id: int = 0 _partial_buffer: str = "" _in_flight_message_id: str | None = None def ingest_event(self, event_id: int, data: str) -> dict | None: """Consume one SSE event. Returns a parsed JSON-RPC message only when a complete message has been assembled. Advances the resumable cursor ONLY at message completion — this is the invariant.""" if event_id <= self.last_complete_message_event_id: # Replay of an already-committed message; ignore idempotently. return None self._partial_buffer += data try: message = json.loads(self._partial_buffer) except json.JSONDecodeError: # Incomplete frame: keep buffering, do NOT advance cursor. return None # Message complete: commit boundary atomically. self.last_complete_message_event_id = event_id self._partial_buffer = "" self._in_flight_message_id = message.get("id") return message def resume_from(self) -> int: """The only value a client may send as Last-Event-ID.""" return self.last_complete_message_event_id def assert_resumable(self, first_replayed_event_id: int) -> None: if first_replayed_event_id <= self.last_complete_message_event_id: return # A gap means the server dropped events we needed; we cannot # reconstruct a message boundary. Fail loudly rather than retry. raise ResumptionFragmentError( f"session {self.session_id}: replay starts at event " f"{first_replayed_event_id} but last committed boundary is " f"{self.last_complete_message_event_id}; message " f"{self._in_flight_message_id!r} would be corrupted" ) ```