# In what scenarios must an instance treat MCP SSE `Last-Event-ID` resumption as a replay-consistency problem rather than a transport-reconnect problem **Date of Record:** 2026 November 22 **Scope:** Applies to MCP servers exposing the HTTP-native streamable transport (POST for client→server messages, GET SSE stream for server→client messages) with resumable event streams keyed by `Last-Event-ID` and session resumption keyed by `Mcp-Session-Id`. Does not apply to stdio transports, to stateless HTTP servers that never emit `id:` fields, or to purely unidirectional streaming without client-side tool-call replay. ## Core Distinction The MCP streamable HTTP transport advertises two superficially similar recovery mechanisms that fail in fundamentally different ways: 1. **Session resumption** (`Mcp-Session-Id` on reconnect): the server rehydrates a *session object* — its tool registry view, negotiated capabilities, and any server-side state keyed to that ID. This is a *state identity* problem. 2. **Stream resumption** (`Last-Event-ID` on the GET SSE stream): the server replays *events* after a sequence cursor. This is a *replay consistency* problem. Operators routinely conflate these and treat `Last-Event-ID` as "reconnect and keep reading." That framing is wrong for any agent that has *already acted on partially observed events*. The SSE `id:` cursor is a position in the server's event log, not a position in the client's *effect log*. When the two diverge — because the client applied a tool result, mutated its own context, or issued a dependent POST — replaying from the cursor re-delivers events whose effects are already committed. The transport is resumable; the *semantics* are not idempotent by default. The invariant that must hold: **for any event `e` with `id = k`, replay after `Last-Event-ID = j < k` must be safe iff the client can prove no action was taken on any event in `(j, k]` that is not idempotent under re-delivery.** The streamable transport specification provides the cursor but does *not* provide the idempotency proof. That gap is the failure mode. ## What Was Observed A coding agent (instance A) connected to an MCP server exposing a `run_tests` tool over streamable HTTP. The server pushed tool-call *invocations* as SSE events with monotonic `id:` values. Sequence observed: - Server emits `id: 41` — `tool_call` for `write_file(path="src/x.py", ...)`. Client POSTs the result back; server acknowledges. - Server emits `id: 42` — `tool_call` for `run_tests(suite="unit")`. Client begins execution; the subprocess is long-running. - Network partition at t+90s. Client's SSE connection drops mid-flight. Client has *already spawned* `run_tests` and is polling it via a separate POST. - Client reconnects with `Mcp-Session-Id: sess-7f2a` and `Last-Event-ID: 41` (its last *fully processed* event; it never marked 42 as processed because the tool result hadn't returned). - Server, honoring `Last-Event-ID: 41`, replays `id: 42` — a *second* `tool_call` for `run_tests(suite="unit")`. - Client, following the MCP client contract literally ("execute tool calls received on the stream"), spawns a *second* test run. Two concurrent subprocesses now contend for the same build directory and the same test-database lock. One corrupts the other's fixture teardown. - Worse: the server had, in the interim, emitted `id: 43` (a `notifications/cancelled` for the *original* 42, triggered by the client's POST timeout). The replay delivered 42 but the client's cursor logic, on reconnect, requested `>= 41` and the server's event log had *pruned* 43 under its retention window. The cancellation was silently lost. Two distinct defects surfaced: (a) non-idempotent replay of an in-flight tool call, and (b) cursor-window mismatch where the client's `Last-Event-ID` predated a pruned cancellation, so the replay set was both *too large* (re-delivered 42) and *incomplete* (missed 43). ## Condition of Validity `Last-Event-ID` resumption is safe **only** under the conjunction of: 1. **Effect-idempotency**: every event in the replay window `(Last-Event-ID, head]` is either (i) a pure notification with no client-side side effect, or (ii) a tool invocation whose re-execution is idempotent under a stable idempotency key carried in the event payload. The MCP spec does *not* require servers to attach such keys, so this must be negotiated or assumed per-tool. 2. **Retention monotonicity**: the server's event log retention window strictly contains `Last-Event-ID` at the moment of reconnect. If the cursor has fallen off the tail, the server MUST reject with a distinguishable error (not silently replay from head, and not silently truncate). The spec permits either; only explicit rejection preserves the invariant. 3. **Cancellation visibility**: any `notifications/cancelled` targeting an event in the replay window must itself be within the retention window and delivered *after* the replayed event, so the client can retract. A pruned cancellation is a silent correctness hole. 4. **Cursor fidelity**: the client's `Last-Event-ID` must reflect the last event whose *effects were durably committed*, not the last event whose *bytes were received*. These differ whenever a tool call is in flight. When any conjunct fails, `Last-Event-ID` is a *hint*, not a guarantee, and the instance must fall back to session-level reconciliation (re-query server state for in-flight tool calls by ID) rather than trusting replay. ## Decision Boundary The instance must branch on **whether it holds uncommitted effects at the cursor**: - **No in-flight effects, retention window intact** → treat `Last-Event-ID` as a pure transport reconnect. Replay is safe. Proceed. - **In-flight effects exist** (a tool call was dispatched but not acknowledged) → do *not* reconnect with the pre-dispatch cursor. Either (a) advance the cursor past the in-flight event only after confirming the tool's terminal state via a separate `tools/status`-style query, or (b) reconnect with the cursor but *suppress execution* of any replayed event whose `id` matches a locally tracked in-flight dispatch, reconciling via the idempotency key. - **Cursor predates retention floor** → the server must reject; if it does not, the client must detect the gap (first replayed `id` > `Last-Event-ID + 1`) and treat the session as *desynchronized*, forcing a full session re-establishment (`DELETE` + new `Mcp-Session-Id`), never a partial replay. - **Cancellation for a replayed event is missing** → the client cannot distinguish "still valid" from "cancelled but pruned." Conservative default: treat any replayed tool invocation older than a configured staleness bound as suspect and re-validate against server state before executing. The boundary is sharp: replay is a *transport* operation only when the effect log and the event log are provably aligned up to the cursor. The moment they can diverge, replay becomes a *semantic* operation requiring reconciliation, and the transport's guarantees no longer suffice. ## Operational Effect Agents that treat `Last-Event-ID` as "resume reading" exhibit three recurring pathologies: duplicate tool side effects (double file writes, double test runs, double payments), lost cancellations (work continues after the orchestrator believed it stopped), and cursor-gap blindness (silent skips when the server prunes). The fix is architectural, not a retry policy: the client must maintain a **dispatch ledger** keyed by event `id` and idempotency key, advance `Last-Event-ID` only on *durable effect commit*, and treat any replay whose first `id` exceeds `Last-Event-ID + 1` as a hard desynchronization requiring session re-establishment. Servers must expose an explicit retention-floor error and must retain cancellations at least as long as the events they cancel. Without both, resumable SSE is a correctness liability disguised as a reliability feature. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Dict, Optional class ReplayConsistencyError(RuntimeError): """Raised when Last-Event-ID replay cannot be proven safe.""" @dataclass class DispatchRecord: event_id: int idempotency_key: str committed: bool = False @dataclass class StreamCursor: last_committed_event_id: int = 0 ledger: Dict[int, DispatchRecord] = field(default_factory=dict) retention_floor: int = 0 def record_dispatch(self, event_id: int, idempotency_key: str) -> None: self.ledger[event_id] = DispatchRecord(event_id, idempotency_key) def commit(self, event_id: int) -> None: rec = self.ledger.get(event_id) if rec is None: raise ReplayConsistencyError( f"commit for unknown event {event_id}; ledger desynchronized" ) rec.committed = True # Advance cursor only past contiguous committed events. nxt = self.last_committed_event_id + 1 while nxt in self.ledger and self.ledger[nxt].committed: self.last_committed_event_id = nxt nxt += 1 def plan_resume(self, server_head: int, first_replayed_id: Optional[int]) -> int: """Return a safe Last-Event-ID, or raise if replay cannot be proven safe.""" if self.last_committed_event_id < self.retention_floor: raise ReplayConsistencyError( f"cursor {self.last_committed_event_id} below retention floor " f"{self.retention_floor}; session must be re-established, not replayed" ) in_flight = [ r for r in self.ledger.values() if not r.committed and r.event_id > self.last_committed_event_id ] if in_flight: # Cannot safely replay past an uncommitted dispatch without reconciliation. raise ReplayConsistencyError( "in-flight dispatches present at cursor: " + ", ".join(str(r.event_id) for r in in_flight) + "; reconcile via idempotency key before resuming stream" ) if first_replayed_id is not None and first_replayed_id > self.last_committed_event_id + 1: raise ReplayConsistencyError( f"replay gap: server resumed at {first_replayed_id} but cursor is " f"{self.last_committed_event_id}; events were pruned" ) return self.last_committed_event_id def handle_replayed_event(cursor: StreamCursor, event_id: int, idempotency_key: str) -> str: existing = cursor.ledger.get(event_id) if existing is not None and existing.committed: return "suppressed-duplicate" if existing is not None and not existing.committed: # Re-delivery of an in-flight dispatch: must reconcile, not re-execute. return f"reconcile:{existing.idempotency_key}" cursor.record_dispatch(event_id, idempotency_key) return "execute" ```