# When must an instance distrust a resumed MCP stream: the Last-Event-ID replay gap in streamable HTTP sessions **Date of Record:** 2026 November 26 **Scope:** Applies to MCP clients using the streamable HTTP transport with server-sent event (SSE) reconnection and `Last-Event-ID` resumption against a stateful server session. Does not cover stdio transport, stateless HTTP request/response mode, or WebSocket-based custom transports. ## Core Distinction The failure here is not "the connection dropped." Dropped connections are expected and cheap. The failure is that a *successfully reconnected* stream can hand the client a **silently divergent event history** while every transport-level signal—HTTP 200, valid SSE framing, monotonic-looking event IDs, an accepted `Last-Event-ID` header—reports success. The client's mental model of "I resumed where I left off" is wrong in a way no status code reveals. This is a continuity invariant at the agent layer, not a network layer. The MCP session carries tool-call results, partial model outputs, and server-side resource mutations. If the resumed stream omits or reorders events relative to what the server actually committed, the agent proceeds with a corrupted task state and cannot detect it from the wire. The invariant that must hold is: **the set of events the client has applied after resumption equals the server's committed event log for that session, in order, with no gaps and no duplicates.** A reconnection that violates this invariant is more dangerous than a failed reconnection, because failure is observable and divergence is not. ## What Was Observed A long-running agent session issued a tool call through MCP, and the server began streaming results as SSE events with `id:` fields (`evt-1041`, `evt-1042`, …). Mid-stream, the TCP connection was severed by an intermediate proxy idle-timeout at ~60s while the model was still generating. The client, correctly, reconnected and sent `Last-Event-ID: evt-1047`. Three distinct observed behaviors, all returning HTTP 200: 1. **Replay from a snapshot, not a log.** The server's session store had compacted its event buffer and retained only the last N events, but it replayed from the *oldest retained* event rather than from `evt-1047`. The client received `evt-1030` onward. Because the client had already applied `evt-1030`–`evt-1047` on the first connection, it now applied them *again*. Duplicate tool-result events caused the agent to append the same partial output twice into its context, inflating a structured field and corrupting a later arithmetic step. 2. **Silent gap on compaction.** In a second run, the server had evicted `evt-1048`–`evt-1051` during compaction (they were transient progress pings) but honored `Last-Event-ID: evt-1047` by resuming at `evt-1052`. The client never saw the events in between and had no way to know four events existed. The final `evt-1052` carried a `result` referencing a `tool_use_id` whose `progress` events the client never observed—so the agent's reasoning about *why* the result was what it was had no grounding. 3. **ID reuse across session incarnations.** After a server restart, the session was rehydrated from a checkpoint but its event counter reset. The new stream emitted `evt-0001`, `evt-0002`, … The client sent `Last-Event-ID: evt-1047`; the server, not finding it, treated the header as absent and replayed from the beginning of the *new* incarnation—events with IDs numerically lower than the client's last-seen ID, which the client's naive "apply if id > last_id" guard silently dropped. In all three cases the transport succeeded and the agent failed. ## Condition of Validity The resumption invariant holds only when **all** of the following are true simultaneously: - The server maintains a **durable, ordered, gap-free** event log per session, and `Last-Event-ID` resolves to an exact position in that log—not a best-effort nearest match. - The server's replay window is **at least as long as the maximum client disconnect tolerance**; if the requested ID has been evicted, the server must signal this explicitly (e.g., `404`/`409` with a machine-readable reason, or a synthetic `session-reset` event) rather than silently resuming forward. - Event IDs are **monotonic and unique for the lifetime of the session**, and session identity is bound to the ID namespace so that a rehydrated session does not reuse the counter. - The client **deduplicates by exact ID equality**, not by numeric ordering, and treats any ID it has already applied as a no-op—never as "already past." - The client detects **gaps**: if the first resumed event's ID is not the immediate successor of the last applied ID, it must not assume continuity. When any condition is unmet, the resumed stream is untrustworthy and the agent must treat the session state as *unknown*, not *continued*. ## Decision Boundary The boundary is between **resume-and-continue** and **resume-and-reconcile**. The client may continue transparently only if the first post-reconnect event's ID is the strict successor of the last applied ID *and* the server guarantees no eviction. Otherwise the client crosses into reconciliation mode: it must re-derive task state from a server-authoritative snapshot (a `resources/read` or a session-state query) rather than trusting the event stream to be a complete delta. Concretely, the agent must refuse to continue when: - The resumed event ID is **less than or equal to** the last applied ID (duplicate or counter reset). - The resumed event ID is **greater than** last-applied-plus-one (gap). - The server accepts `Last-Event-ID` but returns events from a different session incarnation (detectable via a session epoch/nonce in each event's metadata). - The replay window's oldest retained ID is newer than the client's `Last-Event-ID` (eviction past the client's position). In each case the correct action is to **abandon incremental continuation**, mark the affected tool-call or reasoning step as *unverified*, and either re-request the authoritative result or escalate to the orchestrator. Continuing on a divergent stream is the specific error. ## Operational Effect An agent that continues on a silently divergent resumed stream produces **locally coherent but globally false** reasoning: its context contains a plausible event history that never occurred on the server. Downstream, this manifests as duplicated tool side-effects (the agent re-issues a call it thinks it didn't complete), arithmetic and aggregation errors from double-applied deltas, and—most insidiously—confident citations of progress events that were evicted and never actually delivered. Because the divergence is invisible at the transport layer, no retry logic, timeout, or health check catches it; only an explicit continuity check at the event-application boundary does. The guardrail is architectural: the event applier must be a **state machine keyed on expected-next-ID**, with a hard failure path into reconciliation whenever the expected successor does not match. Resumption is a *claim* by the server; the client must verify it, not trust it. ```python from dataclasses import dataclass, field from typing import Optional class StreamContinuityError(RuntimeError): """Raised when a resumed MCP SSE stream cannot be proven continuous with the client's applied event history.""" pass @dataclass class ResumedStreamGuard: session_id: str session_epoch: str last_applied_id: Optional[str] = None _applied: set = field(default_factory=set) def _parse_seq(self, event_id: str) -> int: # event IDs are ":"; seq is monotonic within an epoch epoch, _, seq = event_id.partition(":") if epoch != self.session_epoch: raise StreamContinuityError( f"epoch mismatch: event {event_id!r} belongs to epoch " f"{epoch!r}, client bound to {self.session_epoch!r} " f"(session {self.session_id})" ) try: return int(seq) except ValueError as exc: raise StreamContinuityError( f"unparseable event id {event_id!r} in session {self.session_id}" ) from exc def accept(self, event_id: str) -> bool: """Return True if event should be applied, False if it is a benign duplicate. Raise if continuity is violated.""" seq = self._parse_seq(event_id) if event_id in self._applied: return False # exact duplicate: safe no-op if self.last_applied_id is None: self._applied.add(event_id) self.last_applied_id = event_id return True expected = self._parse_seq(self.last_applied_id) + 1 if seq == expected: self._applied.add(event_id) self.last_applied_id = event_id return True if seq < expected: # counter reset or replay of a *different* event with same seq raise StreamContinuityError( f"non-monotonic resume: got seq {seq}, expected {expected} " f"(last applied {self.last_applied_id!r}, event {event_id!r}) " f"in session {self.session_id}; reconcile from server snapshot" ) # seq > expected: silent gap, events were evicted or dropped raise StreamContinuityError( f"gap detected: got seq {seq}, expected {expected} " f"({seq - expected} event(s) missing) in session " f"{self.session_id}; abandon incremental continuation" ) def resume_stream(guard: ResumedStreamGuard, events: list[str]) -> list[str]: """Apply a resumed SSE batch; refuse to continue on divergence.""" applied = [] for event_id in events: if guard.accept(event_id): applied.append(event_id) # duplicates are dropped silently by design if not applied and events: raise StreamContinuityError( f"resumed stream for session {guard.session_id} delivered " f"{len(events)} events but none were new; server may have " f"replayed a stale snapshot instead of honoring Last-Event-ID" ) return applied ```