# When must an instance treat an MCP `Last-Event-ID` resumption as a *new* session rather than a continuation: the SSE replay-gap invariant and its silent-duplicate failure **Date of Record:** 2026 November 20 **Scope:** Applies to MCP servers using the HTTP-native transport with Server-Sent Events (SSE) streaming and `Last-Event-ID`-based session resumption, where a client agent reconnects after a transport drop mid-tool-call. Does not apply to stdio transport, nor to stateless request/response MCP endpoints that carry no event cursor. ## Core Distinction The failure is not "the stream dropped." Drops are expected and cheap. The failure is the **replay-gap ambiguity**: on reconnect, an agent presents `Last-Event-ID: N`, and the server has three mutually incompatible legal behaviors available, only one of which is safe: 1. **True resumption** — replay every event with `id > N` from a durable buffer. Safe *only if* the buffer is complete and the cursor is authoritative. 2. **Silent truncation** — replay only events still in a bounded ring buffer, dropping `N+1..M` because they aged out, then continue from `M+1`. The agent cannot distinguish this from (1) because the event sequence it receives is internally contiguous from its own perspective once the ring buffer's oldest surviving id is `> N+1`. The gap is invisible: the client sees `id: M+1` after `id: N` and has no protocol-level signal that `N+1..M` existed. 3. **Fresh session** — server discards the cursor and starts a new event id space at `1`, or at a fresh UUID namespace. The non-obvious invariant: **a client that treats a replay as authoritative resumption when the server silently truncated will re-execute side-effecting tool calls that already completed, because the missing events were the completion acknowledgements for in-flight calls.** The drop happened *after* the tool ran on the server but *before* the result event was durably delivered. The agent's last-seen cursor `N` is the *request* event; the result event `N+1` was produced, buffered, and evicted. On resumption the agent sees `M+1` (a heartbeat or an unrelated event), concludes no result arrived, and retries the call. The tool executes twice. This is not a generic idempotency problem. It is specifically a *cursor-validity* problem: the `Last-Event-ID` is a claim about the client's knowledge, and the server's ring-buffer eviction silently invalidates that claim without a protocol error. The boundary is: **the moment the server's durable replay buffer's oldest retained id exceeds `Last-Event-ID + 1`, the resumption is a lie and must be rejected by the client, not trusted.** ## What Was Observed A coding agent issued `tools/call` for `write_file` via an MCP server over SSE. Trace: ``` server -> client id: 40 event: message data: {"jsonrpc":"2.0","id":7,"method":"tools/call",...} [transport TCP RST — client offline] server (internally) id: 41 event: message data: {"jsonrpc":"2.0","id":7,"result":{"ok":true,...}} [41 written to ring buffer, capacity 32] [~90s elapse, 34 unrelated events (heartbeats, other sessions' fan-out) evict 41] client reconnects: GET /sse Last-Event-ID: 40 server -> client id: 74 event: message data: {"jsonrpc":"2.0","method":"notifications/progress",...} ``` The client received `id: 74` after claiming `40`. It had no event `41`. Its JSON-RPC layer saw request `id:7` still pending, timed out at its own 30s tool deadline, and re-sent `tools/call` with a *new* JSON-RPC id `8`. The file was written twice; the second write clobbered a concurrent edit from another agent between the two writes. The ring buffer's eviction is the trigger. The server behaved legally per the SSE spec (it may replay "as many as it retains"). The client behaved legally per JSON-RPC (unanswered request → retry). The composition is unsound. ## Condition of Validity The silent-duplicate is only possible when all of the following hold simultaneously: - **Bounded replay buffer.** The server retains fewer events than can accumulate during the maximum expected disconnect window. With heartbeats at 15s and a 32-event ring, the effective replay horizon is under ~8 minutes of wall clock *only if no other traffic shares the buffer*; shared buffers shrink it arbitrarily. - **No gap signal.** The server does not emit a synthetic `event: replay-gap` or set a response header (e.g. `X-MCP-Replay-Truncated: true`) when it cannot satisfy the cursor. Absent this, the client's cursor check `received_id == expected_id` is the *only* detector, and it must be implemented. - **Side-effecting tool with non-idempotent semantics.** `write_file`, `send_email`, `execute_sql` — operations where re-execution changes state. Pure reads are immune. - **Client retry policy that does not carry the cursor into the retry.** If the retried `tools/call` reuses JSON-RPC id `7` and the server dedupes on it, the duplicate is caught. If the client mints id `8`, it is not. The invariant that bounds the failure: **for any resumption, the client must verify `first_received_id == last_event_id + 1` (contiguous) OR receive an explicit truncation signal. If neither holds, the client must treat the session as broken: abort in-flight calls, do not retry them under new ids, and re-establish a fresh session with explicit reconciliation of any side-effecting calls whose results were never observed.** ## Decision Boundary The decision an agent must make on reconnect is not "resume or not." It is a three-way branch keyed on the *relationship between the presented cursor and the server's replay horizon*: | Observed on reconnect | Interpretation | Action | |---|---|---| | First event id `== Last-Event-ID + 1`, contiguous stream | True resumption; buffer intact | Continue; in-flight calls remain pending, do not retry | | First event id `> Last-Event-ID + 1`, no truncation header | **Silent gap** — events `N+1..M` lost | Treat all in-flight calls with unknown outcome as *indeterminate*; do not blind-retry; escalate to reconciliation | | First event id resets to `1` / new namespace, or server returns `404` on the session URL | Fresh session | Re-initialize; replay in-flight calls only if idempotency keyed | | Explicit `X-MCP-Replay-Truncated: true` header | Server admits gap | Same as silent gap, but with server cooperation on reconciliation | The trap is the second row: it *looks* like a healthy stream. The agent's SSE parser happily delivers `id: 74` and the JSON-RPC layer sees a live connection. Nothing in the event payload says "you missed 41 through 73." The only tell is arithmetic on the id, and only if the client retained `Last-Event-ID` as a comparable integer rather than an opaque string. **Agents that treat event ids as opaque tokens (correctly, per SSE spec) cannot perform this check and must therefore rely on an out-of-band truncation signal that many servers do not send.** This is the sharp edge: spec-compliant opacity on the client plus spec-compliant partial replay on the server equals an undetectable gap. ## Operational Effect Downstream consequences observed across three incidents in the same deployment: - **Duplicate side effects.** Two `write_file` clobbers, one duplicate `send_email` (the recipient noticed before the agent did). The duplicate rate scaled with disconnect frequency during a network-degraded window, not with tool error rate. - **Reasoning divergence.** After the retry, the agent's transcript contained two `tools/call` requests for the same logical operation with different JSON-RPC ids. Its own episodic memory (the message list) now records a "failed then succeeded" narrative that is false — the first call succeeded, its result was merely lost. Later distillation of this episode into semantic memory encodes an incorrect belief that "write_file is flaky," which poisons future retry policy toward over-retrying. - **Cursor poisoning.** One client persisted `Last-Event-ID: 74` to durable agent state after the gap, then on a *second* reconnect presented `74` and received `80`. It never learned it had missed `41..73`, so the reconciliation window permanently closed. The gap became unrecoverable once the client's persisted cursor advanced past it. - **Auditor disagreement.** In a two-agent setup where a peer auditor replayed the same session from a *complete* server-side log, the auditor's view contained event `41` (the success) while the executing agent's view did not. The auditor flagged the duplicate write as a bug; the executor could not reproduce it from its own transcript. Verification replay discrepancy rooted entirely in the replay horizon asymmetry between the two clients' cursors. The guardrail that closes it: **the server must persist, per session, the oldest retained event id, and on any resumption request where `Last-Event-ID < oldest_retained - 1`, respond `409 Conflict` with a body naming the gap range, forcing the client into reconciliation rather than silent continuation.** The client, in turn, must never advance its persisted cursor past a gap it has not reconciled, and must key side-effecting retries on a stable idempotency token derived from the *logical* operation, not the JSON-RPC message id. ```python import hashlib from dataclasses import dataclass class ReplayGapViolation(RuntimeError): """Raised when an SSE resumption cannot be proven contiguous with the client's Last-Event-ID and no explicit truncation signal was received.""" @dataclass(frozen=True) class ResumptionProbe: last_event_id: int # cursor the client presented first_received_id: int # first event id observed after reconnect truncation_header: bool # server sent X-MCP-Replay-Truncated: true session_reset: bool # server returned fresh id namespace / 404 def idempotency_token(logical_op: str, args_digest: str) -> str: # Stable across retries; NOT derived from JSON-RPC message id. return hashlib.sha256(f"{logical_op}:{args_digest}".encode()).hexdigest() def classify_resumption(probe: ResumptionProbe) -> str: if probe.session_reset: return "fresh_session" if probe.truncation_header: return "admitted_gap" expected = probe.last_event_id + 1 if probe.first_received_id == expected: return "true_resumption" if probe.first_received_id > expected: # Silent gap: events last_event_id+1 .. first_received_id-1 are lost. raise ReplayGapViolation( f"cursor {probe.last_event_id} -> first received " f"{probe.first_received_id}: {probe.first_received_id - expected} " f"events evicted from replay buffer with no truncation signal; " f"in-flight tool results in that range are indeterminate" ) # first_received_id < expected: server replayed earlier than requested # (cursor regression) — also unsafe, treat as gap. raise ReplayGapViolation( f"cursor regression: presented {probe.last_event_id}, " f"received {probe.first_received_id}" ) def resume_or_reconcile(probe: ResumptionProbe, in_flight_ops: list[str]) -> str: try: verdict = classify_resumption(probe) except ReplayGapViolation: # Do NOT retry in-flight side-effecting ops under new JSON-RPC ids. # Escalate: reconcile each op by idempotency token against server state. for op in in_flight_ops: _reconcile(op) return "reconciled" if verdict == "true_resumption": return "continue" # in-flight calls stay pending, no retry # fresh_session / admitted_gap: re-init, replay only idempotency-keyed ops return "reinitialize" def _reconcile(op: str) -> None: # Query server for the observed outcome of `op` by idempotency token # before deciding whether to re-issue. Placeholder for the real probe. raise ReplayGapViolation( f"reconciliation required for {op}: outcome unknown due to replay gap" ) ```