# Why does an instance replay a stale event cursor after MCP Streamable-HTTP session resumption and silently diverge from the server's tool-call ledger **Date of Record:** 2026 December 3 **Scope:** Applies to MCP clients using the Streamable HTTP transport with `Last-Event-ID`-based SSE resumption and server-issued session tokens (`Mcp-Session-Id`). Does not cover pure stdio transports or stateless one-shot JSON-RPC POSTs without a session. ## Core Distinction The failure is not a dropped connection. Dropped connections are expected and handled. The failure is a **cursor/ledger divergence**: the client resumes an SSE stream with a `Last-Event-ID` that the server can no longer reconcile against its per-session event ledger, and the server — instead of rejecting the resume — replays from a *coarser* boundary (a snapshot, or the earliest retained event) while the client believes it has achieved exact-once continuation. The client's local ledger of tool results now contains events the server considers already-delivered, or misses events the server considers already-acked. Both sides report "resumed successfully." The state transition is silent. The non-obvious part: the invariant that must hold is *not* "the stream reconnects." It is **"the resumed cursor is a total order position that the server can prove it has not truncated below."** Streamable HTTP makes resumption *look* like a transport concern (reconnect + replay), but the `Last-Event-ID` is actually a *distributed commit index*. Treating it as a transport hint rather than a ledger position is the root cause of every downstream divergence. ## What Was Observed A tool-using agent (file-search + shell execution MCP server) runs over Streamable HTTP. The server retains a bounded per-session event log — say the last 512 events, evicted FIFO — because unbounded retention is unacceptable at scale. The client maintains its own append-only log of `(event_id, tool_call_id, result_digest)`. Trigger condition, in order: 1. The agent issues a long-running `shell_exec` tool call. The server emits `event_id=1000` (call accepted) and, 40 seconds later, `event_id=1041` (result). In between, the client's SSE connection drops at the TCP layer (NAT rebind, load-balancer idle timeout) — a routine event. 2. The client reconnects with `Mcp-Session-Id: S` and `Last-Event-ID: 1000`. It expects replay of `1041` onward. 3. Meanwhile the session has been *busy*: the agent's parallel sub-agent issued 600 additional tool calls on the same session, pushing the retained window to `[1041 … 1552]`. Event `1000` has been evicted. The server cannot honor `Last-Event-ID: 1000`. 4. **The failure point:** the server's resume handler, rather than returning a terminal `409 Cursor-Expired` (or an explicit `resume_rejected` event), falls back to its snapshot path: it replays from the *oldest retained event* (`1041`) and prepends a synthetic `session_resumed` event carrying the current server-side cursor. The client accepts the stream, sees `1041` (the shell result it was waiting for), and marks resumption complete. 5. But the client's local log was truncated-and-rewritten at `1000`; it now re-appends `1041…1552`, including *tool calls it already executed and whose side effects it already committed* (e.g., a `file_write` at `1103`, a `git_commit` at `1187`). The agent, seeing "new" tool-call results it does not recognize as duplicates, re-executes the corresponding actions. The server's ledger and the client's ledger are now two different total orders over the same logical operations. The tell is subtle: the client never sees an error. `session_resumed` is a success-shaped event. The divergence is only detectable when a downstream `file_write` produces a "file already exists with different content" or a `git_commit` produces an empty commit — i.e., *after* the side effects. ## Condition of Validity The safe-resumption invariant is: > A resume with `Last-Event-ID = C` is valid **iff** the server can prove `C >= min_retained_event_id(session)` **and** the client's local ledger is a prefix-consistent subsequence of the server's ledger up to `C`. If either is false, resumption MUST be rejected terminally; the client MUST perform a full session re-establishment (new session token, fresh ledger, no replay). This holds only when: - The server exposes its retained-window lower bound (e.g., `Mcp-Retained-From` header on every response, or a `cursor_expired` error code) rather than silently substituting a snapshot. - The client treats `Last-Event-ID` as a **commit index it must validate**, not a hint. On resume it must compare the server's advertised retained-from against its own last-acked cursor *before* accepting any replayed event. - Tool calls are idempotent or carry a client-generated idempotency key (`tool_call_id`) that the server deduplicates against its ledger. Without this, replay is indistinguishable from new work. - The session token is bound to the ledger generation. A session token that survives ledger truncation is a token that lies about what it can resume. It does **not** hold when the transport is treated as best-effort (reconnect-and-hope), when the server's retention is shorter than the client's reconnect backoff window, or when the client auto-acks replayed events without deduplicating against `tool_call_id`. ## Decision Boundary The decision the client must make on every resume, expressed as a guard the transport layer must enforce before handing events to the reasoning loop: | Server signals | Client action | |---|---| | `retained_from <= last_acked_cursor`, no snapshot marker | Accept replay; dedupe by `tool_call_id`; advance cursor monotonically. | | `retained_from > last_acked_cursor` (cursor evicted) | **Reject.** Do not accept the stream. Tear down session, re-establish, re-derive intent from durable task state — never re-execute replayed tool calls. | | Snapshot/synthetic `session_resumed` present | Treat as a *new session*: cursor resets, ledger is authoritative from server snapshot, client reconciles by diffing `tool_call_id` sets, not by replaying. | | No retention metadata at all | Fail closed. Absence of the lower bound is indistinguishable from an evicted cursor. | The boundary is between "replay is a continuation" and "replay is a fresh epoch." The server must make this explicit; the client must never infer it from the shape of the first replayed event. ## Operational Effect When the invariant is violated and undetected, the agent exhibits **duplicate side effects under a success-shaped resume** — the worst class of failure because it defeats both the agent's self-check (it believes it resumed correctly) and most observability (no error was raised). Symptoms downstream: non-idempotent tool calls applied twice, verification replays that disagree with the server's ledger, and baton-passing races where a sub-agent's committed result is re-derived as new. The blast radius scales with how long the session was busy during the disconnect — a busy session evicts the cursor faster, which is precisely when the agent has the most in-flight state to lose. The architectural guardrail is to **make the cursor a first-class, validated commit index**: servers advertise `retained_from` on every response and return a terminal `cursor_expired` error (never a silent snapshot); clients refuse any resume where `retained_from > last_acked`; and every tool call carries a client idempotency key the server deduplicates. Under those three conditions, resumption is exact-once. Without them, it is at-most-once with silent duplication — the agent cannot tell which. ```python from __future__ import annotations from dataclasses import dataclass class CursorDivergenceError(RuntimeError): """Raised when an MCP SSE resume would replay events the client cannot reconcile against its local ledger. Fail closed: never accept the stream.""" @dataclass(frozen=True) class ResumeContext: session_id: str last_acked_cursor: int # client's Last-Event-ID server_retained_from: int | None # server's advertised lower bound snapshot_marker: bool # server substituted a snapshot for replay def validate_resume(ctx: ResumeContext) -> int: """Return the cursor the client may safely advance to, or raise. Invariant: resume is valid iff the server can prove it has not truncated below the client's last-acked cursor. Absence of the bound is a failure. """ if ctx.server_retained_from is None: # No retention metadata: indistinguishable from an evicted cursor. raise CursorDivergenceError( f"session {ctx.session_id}: server advertised no retained_from; " f"cannot prove cursor {ctx.last_acked_cursor} is replayable" ) if ctx.server_retained_from > ctx.last_acked_cursor: # The exact boundary failure: cursor evicted, server would replay from # a coarser boundary while the client believes it resumed exactly. raise CursorDivergenceError( f"session {ctx.session_id}: cursor {ctx.last_acked_cursor} evicted " f"(retained_from={ctx.server_retained_from}); replay would duplicate " f"committed tool calls -- require full re-establishment, not resume" ) if ctx.snapshot_marker: # Snapshot is a new epoch, not a continuation. Caller must reconcile by # tool_call_id diff, not by replaying events into the reasoning loop. raise CursorDivergenceError( f"session {ctx.session_id}: snapshot resume is a new epoch; " f"must reconcile by tool_call_id set-difference before advancing" ) return ctx.last_acked_cursor def resume_stream(ctx: ResumeContext, events: list[dict]) -> list[dict]: """Deliver only events strictly past the validated cursor, deduped by tool_call_id. Any event at or below the cursor is a divergence.""" cursor = validate_resume(ctx) seen: set[str] = set() out: list[dict] = [] for ev in events: if ev["event_id"] <= cursor: raise CursorDivergenceError( f"session {ctx.session_id}: server replayed event " f"{ev['event_id']} at/below acked cursor {cursor}" ) tcid = ev.get("tool_call_id") if tcid is not None: if tcid in seen: continue seen.add(tcid) out.append(ev) return out ```