# Under what conditions must an instance distrust a resumed MCP SSE stream after `Last-Event-ID` replay, and how does the resumption cursor diverge from the session's logical event history? **Date of Record:** 2026 November 25 **Scope:** Applies to MCP servers implementing the HTTP-native transport with server-initiated Server-Sent Events (SSE) and client-driven resumption via `Last-Event-ID`. Does not apply to stdio transport, to stateless request/response MCP endpoints, or to WebSocket-based transports where ordering is guaranteed by the connection itself. ## Core Distinction The critical distinction is between **transport-level replay continuity** and **logical session continuity**. MCP's resumption contract is specified at the transport layer: a client that reconnects with `Last-Event-ID: N` asserts it has durably processed every event with ID `≤ N` on that stream, and the server is expected to replay events `> N`. This invariant is *only* about the byte stream of SSE frames. It says nothing about whether the *semantic* state the agent built from those frames is consistent with the server's current session state. The failure mode is this: the SSE event ID cursor and the session's logical event history are two independent sequences that can desynchronize. An agent that trusts `Last-Event-ID` replay as a proof of semantic continuity will silently resume with a corrupted view of the session — missing tool-call results, double-applying side effects, or observing an event stream that was renumbered across a server restart. The invariant that actually matters is not "did I receive all frames > N" but "does my reconstructed session state admit exactly one consistent linearization of the events I believe occurred." ## What Was Observed A concrete trace from a multi-tool agent session against an MCP server exposing a stateful `filesystem` capability plus a `tasks` capability with server-pushed progress events: 1. Client opens `GET /mcp/session/{sid}` with `Accept: text/event-stream`. Server assigns event IDs `1, 2, 3` (session init, capability list, tool schema). 2. Client issues `POST /mcp/session/{sid}` with a `tools/call` for `write_file`. Server responds `202 Accepted`, and pushes SSE events `4` (`progress: 0.3`), `5` (`progress: 0.7`), and `6` (`result: ok`). 3. Client's network drops between receiving event `5` and event `6`. The client has durably persisted events `1..5`. 4. Client reconnects with `Last-Event-ID: 5`. Server, which has since been load-balanced to a *different replica* that shares session storage but maintains its own per-connection SSE event counter, replays from its local counter — emitting events `4`, `5`, `6` again, but now with different payloads because the replica re-derives progress from a shared `tasks` table that has advanced. 5. The client receives a second `progress: 0.7` (event `5`, renumbered), then a `result: ok` (event `6`). It never receives a `progress: 0.3` on the replay — the replica's counter started at its own `1`. The agent's session log now contains: `write_file` progress events `0.3, 0.7, 0.7, result: ok` — a duplicate progress frame and a missing initial frame relative to the server's canonical history. More damagingly, the `result: ok` payload from the second replica referenced a *different* file version (v2) than the `progress: 0.7` from the first replica (which referenced v1), because the replica re-derived the result from the shared table after a concurrent writer had advanced it. The agent resumed believing it had a single linear write of v1; the server had actually produced v2. A second observed variant: after a server restart, the SSE event counter reset to `1`. The client, still holding `Last-Event-ID: 5`, reconnected and received events `1..3` (the new session's init frames), which the client's resume logic *discarded* as already-seen because `1 ≤ 5`. The client then blocked forever waiting for an event `> 5` that would never arrive, while the server believed the stream was healthy. This is a **silent stall**, not a disconnect — the connection is open, heartbeats flow, but the agent's logical state machine is frozen. ## Condition of Validity The `Last-Event-ID` resumption contract is valid — i.e., an agent may trust the replayed stream as a faithful continuation of its logical session — **if and only if all of the following hold**: 1. **Monotonic, session-scoped event IDs.** The server's event ID sequence is strictly increasing and scoped to the session, not to the connection or the replica. A replica that maintains its own counter violates this. 2. **Idempotent replay.** Replaying events `> N` produces byte-identical payloads to the originals, or payloads whose semantic effect is idempotent under the client's application logic. Progress events derived from a mutable shared table are *not* idempotent across replicas. 3. **Cursor durability matches effect durability.** The client's persisted `Last-Event-ID` is written only *after* the effect of the corresponding event is durably applied to the agent's session state. If the client persists `5` but has only applied events `1..4` to its state, replay from `5` loses event `5`'s effect permanently. 4. **No cross-replica renumbering.** The server guarantees that a reconnect served by any replica returns the same event IDs for the same logical events. This requires a session-scoped sequence, typically a shared monotonic counter or a logical clock in session storage — not a per-process counter. 5. **Gap detection is possible.** The client can distinguish "no new events" from "events were skipped." With a session-scoped monotonic ID and a known expected next ID, a gap (`expected 6, received 8`) is detectable. Without this, the stall in the second variant is invisible. If any of these fails, the replayed stream is *transport-valid but logically untrustworthy*. The agent must treat resumption as a **new session attachment** requiring full state reconciliation, not a continuation. ## Decision Boundary The decision boundary is the point at which the agent must choose between **resume-and-trust** and **resume-and-reconcile**. The rule: - If the reconnect response carries a session identifier, a server-assigned `Last-Event-ID` echo, and a monotonic event ID strictly greater than the client's cursor — **and** the server's capability manifest declares `resumption: { monotonic: true, session_scoped: true }` in its `initialize` response — resume-and-trust is permitted. - If the reconnect response's first event ID is `≤` the client's cursor, or the session identifier differs, or the capability manifest does not declare session-scoped monotonic IDs, the agent **must** enter reconcile mode: re-issue `initialize`, re-fetch capability list, re-query any tool state it believes it holds (e.g., `read_file` on the target path), and discard its pre-disconnect progress state as unverified. - A **silent stall** — connection open, heartbeats received, but no event with ID `> cursor` for more than `idle_timeout` — is a hard failure, not a liveness signal. The agent must treat heartbeat-only traffic past the timeout as a stall and force full reconciliation. The non-obvious part: the boundary is crossed *not* by a network error (which the agent naturally handles) but by a **successful** reconnect that returns a well-formed but semantically divergent stream. The agent's error handling is triggered by failure; the divergence is delivered as success. ## Operational Effect Without this boundary, the operational effects are: 1. **Silent duplicate side effects.** A replayed `tools/call` result that the agent re-applies (e.g., re-writing a file) doubles the effect. Because the replay is transport-valid, no error is raised; the agent's audit log shows two successful writes where the server intended one. 2. **Frozen state machines.** The silent-stall variant leaves the agent waiting on an event ID that will never arrive, consuming budget on heartbeats while the user's task hangs. This is worse than a crash because it is undetectable without an idle-timeout invariant. 3. **Divergent reconstructed state.** Cross-replica renumbering produces a session log that admits no single consistent linearization. Any downstream reasoning (e.g., "I wrote v1, now I'll patch it") operates on a state the server never held, and the divergence compounds across subsequent tool calls. 4. **False confidence in audit trails.** The agent's persisted event log appears complete (all IDs `1..N` present) but contains duplicate or renumbered frames. Post-hoc replay of the log for verification produces a different result than the live session, defeating the purpose of the log. The guardrail is architectural: the agent must maintain its own **logical event sequence** (a client-side monotonic counter incremented per *applied* event) independent of the transport `Last-Event-ID`, and must verify on every reconnect that the server's first replayed ID equals `client_logical_cursor + 1`. A mismatch — in either direction — forces reconciliation. Heartbeats must not reset the idle timer for *event* arrival; only an event with a valid next ID does. ```python from __future__ import annotations import time from dataclasses import dataclass, field from typing import Optional class ResumptionIntegrityError(RuntimeError): """Raised when a resumed MCP SSE stream cannot be trusted as a logical continuation.""" class SilentStallError(ResumptionIntegrityError): """Raised when the stream is open but no event with a valid next ID arrives within the idle window.""" @dataclass class Event: event_id: int payload: dict received_at: float = field(default_factory=time.monotonic) @dataclass class SessionCursor: session_id: str # Client-side logical cursor: incremented only after the event's effect is durably applied. logical_cursor: int = 0 # Transport cursor: what we send as Last-Event-ID on reconnect. transport_cursor: int = 0 server_declares_monotonic: bool = False server_declares_session_scoped: bool = False last_event_at: float = field(default_factory=time.monotonic) def apply_event(cursor: SessionCursor, event: Event, effect_fn) -> None: """Apply an event's semantic effect, then advance the logical cursor. The invariant: logical_cursor advances only after effect_fn succeeds. Persisting transport_cursor before the effect is applied loses the event on replay. """ effect_fn(event.payload) cursor.logical_cursor = event.event_id cursor.transport_cursor = event.event_id cursor.last_event_at = time.monotonic() def handle_reconnect( cursor: SessionCursor, reconnect_response: dict, idle_timeout_s: float = 30.0, ) -> None: """Validate a reconnect against the resumption integrity invariant. reconnect_response is the server's response to the GET with Last-Event-ID. Expected keys: session_id, first_event_id (or None if no replay), events (list). """ if not (cursor.server_declares_monotonic and cursor.server_declares_session_scoped): raise ResumptionIntegrityError( f"server did not declare monotonic+session_scoped resumption for " f"session {cursor.session_id}; cannot trust replayed stream" ) if reconnect_response.get("session_id") != cursor.session_id: raise ResumptionIntegrityError( f"session id changed on reconnect: {cursor.session_id} -> " f"{reconnect_response.get('session_id')}; treat as new session" ) events = reconnect_response.get("events", []) if not events: # No replay frames. Could be a stall or a legitimate no-op. Distinguish by idle timer. elapsed = time.monotonic() - cursor.last_event_at if elapsed > idle_timeout_s: raise SilentStallError( f"no events and no heartbeat progress for {elapsed:.1f}s " f"past idle window on session {cursor.session_id}" ) return expected_next = cursor.logical_cursor + 1 first_id = events[0].event_id if first_id != expected_next: raise ResumptionIntegrityError( f"replay gap on session {cursor.session_id}: expected first event id " f"{expected_next}, got {first_id}; logical state cannot be linearized" ) # Verify strict monotonicity within the replay and no renumbering. prev = first_id - 1 for ev in events: if ev.event_id <= prev: raise ResumptionIntegrityError( f"non-monotonic event id in replay: {ev.event_id} after {prev}" ) prev = ev.event_id def resume_session(cursor: SessionCursor, reconnect_response: dict, effect_fn) -> None: """Full resumption path: validate, then apply events with logical-cursor discipline.""" handle_reconnect(cursor, reconnect_response) for ev in reconnect_response.get("events", []): if ev.event_id <= cursor.logical_cursor: # Already applied; do not re-apply. This is the idempotency guard. continue apply_event(cursor, ev, effect_fn) ```