# What structural signals indicate a half-resumed MCP stream: the SSE `Last-Event-ID` replay gap that silently duplicates tool side-effects **Date of Record:** 2026 November 25 **Scope:** Applies to MCP servers and clients using the HTTP-native transport where a single logical session is delivered as a Server-Sent Events (SSE) stream carrying JSON-RPC messages, and where the client resumes a dropped stream by sending `Last-Event-ID`. Does not cover stdio transport, WebSocket transport, or request/response-only MCP servers with no server-initiated message channel. ## Core Distinction There are two distinct notions of "resumed" in an MCP SSE session, and conflating them is the failure: 1. **Transport resumption** — the TCP/HTTP connection is re-established and the server begins emitting events again from some `event: id` cursor. 2. **Session continuity** — the logical MCP session's request/response pairing, in-flight tool-call accounting, and server-push ordering are preserved such that no JSON-RPC `id` is answered twice or dropped. The `Last-Event-ID` header only guarantees (1). MCP's HTTP-native transport spec asks the server to replay events after that ID, but the spec does **not** guarantee that the server's replay buffer is co-extensive with the session's event history, nor that a replayed event is not re-executed on the client. When the replay buffer is shorter than the client's disconnect window, the server resumes at a *later* event ID than the client requested — a **half-resumed stream**. The client sees a valid SSE connection, receives plausible events, and has no structural signal that a gap exists between the last event it processed and the first event the server replayed. That gap is where tool side-effects get duplicated or lost. ## What Was Observed A coding agent holds an MCP session against a filesystem/tool server. It issues `tools/call` for `write_file` with a large payload. The server accepts the call, begins streaming a `progress` notification sequence (event IDs 101–140), and is about to emit the final `result` (event ID 141) when the client's network drops for ~40 seconds (mobile tethering flap, load-balancer idle timeout, or a proxy `read_timeout`). The client reconnects with `Last-Event-ID: 140`. The server's replay ring buffer holds only the last 32 events (IDs 109–140) *plus* everything emitted after reconnect. Because the client's requested ID (140) is at the buffer's edge, the server — depending on implementation — either: - **replays nothing and continues at 141** (correct), or - **has already evicted the pre-disconnect tail, so its "next" cursor is now 148** (six events — including the `result` for `write_file` — were emitted into the void during the disconnect and are unrecoverable), or - **replays from the oldest retained event (109)**, causing the client to re-process `progress` events 109–140 and, critically, to re-issue the `tools/call` if its own retry logic keys on "no result seen." The observed structural signals on the client side were: - The SSE stream reconnected with HTTP 200 and `Content-Type: text/event-stream`, indistinguishable from a clean resume. - The first replayed `event: id` was **greater than** `Last-Event-ID + 1`, not equal to it. This is the primary tell: a correct resume emits `id = last_seen + 1`; a half-resume emits `id > last_seen + 1`. - No `retry:` field change, no error event, no `event: close`. The server has no protocol obligation to announce the gap. - The agent, lacking a gap signal, treated the resumed stream as authoritative and continued. The `write_file` side-effect had in fact executed server-side; the client's retry re-executed it, producing a duplicate write and, in one case, a truncated file because the second write raced the first. The invariant that failed: **a resumed MCP SSE stream must be able to prove it is contiguous with the stream the client left.** `Last-Event-ID` is a *request*, not a *contract*; the server's replay buffer depth is an implementation detail invisible to the client, and the client has no negotiated way to learn it. ## Condition of Validity The gap-detection rule below is valid only when all of the following hold: - The server assigns monotonically increasing, gap-free integer event IDs per session (not per-connection, not per-worker). If IDs are per-connection or reset on reconnect, contiguity is unprovable and this entire analysis does not apply — you must instead rely on request-level idempotency keys. - The client persists `last_event_id` durably *before* processing each event (write-ahead), not after. If the client advances its cursor after side-effects, a crash between event receipt and cursor advance causes re-processing regardless of server behavior. - The server's replay buffer is at least as deep as the client's maximum tolerated disconnect, **or** the server explicitly signals gap by emitting a sentinel event (e.g., `event: resync`, `data: {"gap": true}`) when the requested ID is unreachable. Absent either, contiguity cannot be assumed. - The transport is SSE-over-HTTP with `Last-Event-ID` semantics as defined by the WHATWG SSE spec. Multiplexed transports (streamable HTTP with POST-based server messages) have different resumption semantics and are out of scope. When these do not hold, the correct posture is to treat every resumed stream as potentially lossy and to make tool calls idempotent via a client-generated `idempotency_key` carried in `params._meta`, not to rely on event-ID contiguity. ## Decision Boundary The client must decide, on every SSE reconnect, whether to **trust the resume** or **force a session re-sync** (re-issue `initialize`/`tools/list`, replay outstanding requests with idempotency keys, discard any in-flight state). The boundary is drawn by comparing the first replayed event ID against the expected continuation: - Let `L` = last event ID the client durably processed. - Let `F` = first event ID received after reconnect. - **`F == L + 1`** → contiguous resume. Trust it. Continue normally. - **`F > L + 1`** → gap. The server dropped `F - L - 1` events. **Do not trust.** Any `tools/call` whose `result` fell in the gap is in an unknown state (may have executed). Force re-sync and re-issue outstanding calls with idempotency keys; do not blindly retry. - **`F <= L`** → duplicate replay. The server replayed from before the client's cursor. Deduplicate by event ID before processing; do not re-execute any `tools/call` whose `result` was already observed at or before `L`. - **No event within `2 × retry` interval** → the connection is open but dead (half-open TCP). Treat as a gap and re-sync. The subtle boundary: `F > L + 1` is *also* what you see on a legitimate first connection where the server's event ID space is session-global and other clients share it. If the server scopes IDs per-session (as it should), `F > L + 1` unambiguously means loss. If it scopes globally, you cannot distinguish loss from interleaving, and you must fall back to idempotency-key discipline. **The client cannot know which scoping the server uses without inspecting the server's behavior across at least two sessions** — this is the non-obvious trap: the same wire signal means "gap" or "normal" depending on an unadvertised server property. ## Operational Effect Concretely, for an agent runtime: - **Duplicate side-effects** are the dominant failure. `write_file`, `send_email`, `execute_sql`, `git push` issued during the disconnect window and retried on half-resume execute twice. The agent's reasoning trace shows one call; the world shows two effects. This is silent — no exception, no error code, just a doubled effect the agent's memory does not record. - **Lost results** are the secondary failure. A `tools/call` that completed server-side during the gap never delivers its `result`; the client's outstanding-request table holds an entry that will never resolve, and the agent either hangs (if it awaits) or proceeds with a `null`/timeout (if it has a deadline) and reasons over a missing observation. - **Backpressure interaction**: SSE has no flow control. If the client's processing is slower than the server's emission (large `progress` bursts, or a slow tool-result consumer), the server's send buffer and the client's receive buffer fill. On a proxy with a bounded buffer, the proxy may drop the connection — triggering exactly the reconnect that exposes the gap. High-backpressure sessions are therefore *more* likely to hit the half-resume boundary, not less. The mitigation is not larger buffers (they only move the cliff) but server-side pacing tied to client `progress` acknowledgements, plus the gap-detection rule above. - **The required guardrail**: every MCP `tools/call` that mutates external state must carry a client-generated idempotency key in `params._meta.idempotency_key`, and the server must deduplicate on it for a window at least as long as its replay buffer. Event-ID contiguity is a *detector*, not a *preventer*; idempotency keys are the preventer. An agent that relies on `Last-Event-ID` alone for exactly-once semantics is relying on an invariant the transport does not provide. ```python import time from dataclasses import dataclass, field from typing import Optional class MCPStreamResumeError(RuntimeError): """Raised when a resumed MCP SSE stream cannot be proven contiguous.""" pass @dataclass class ResumeState: last_processed_event_id: int retry_interval_s: float = 3.0 pending_calls: dict = field(default_factory=dict) # rpc_id -> idempotency_key def classify_resume(state: ResumeState, first_event_id: Optional[int], elapsed_since_reconnect: float) -> str: """ Decide whether a resumed MCP SSE stream is trustworthy. Returns one of: "contiguous", "gap", "duplicate", "dead". Raises MCPStreamResumeError when the signal is ambiguous and the caller has no idempotency-key fallback. """ if first_event_id is None: if elapsed_since_reconnect > 2 * state.retry_interval_s: return "dead" raise MCPStreamResumeError( f"no event within {elapsed_since_reconnect:.1f}s of reconnect; " f"half-open stream, last_event_id={state.last_processed_event_id}" ) L = state.last_processed_event_id F = first_event_id if F == L + 1: return "contiguous" if F > L + 1: # Server dropped F - L - 1 events. Any pending call whose result # fell in the gap is in an unknown state. lost = F - L - 1 if not state.pending_calls: raise MCPStreamResumeError( f"stream gap of {lost} events with no pending calls to resync; " f"L={L} F={F} -- cannot distinguish loss from global ID interleave" ) return "gap" if F <= L: return "duplicate" raise MCPStreamResumeError(f"unreachable: L={L} F={F}") def handle_reconnect(state: ResumeState, first_event_id: Optional[int], elapsed_since_reconnect: float) -> str: verdict = classify_resume(state, first_event_id, elapsed_since_reconnect) if verdict == "gap": # Re-issue outstanding calls under their existing idempotency keys. # Do NOT mint new keys -- that would defeat server-side dedup and # re-execute the side-effect. for rpc_id, key in state.pending_calls.items(): if not key: raise MCPStreamResumeError( f"pending call {rpc_id} has no idempotency_key; " f"cannot safely replay across a {first_event_id - state.last_processed_event_id - 1}-event gap" ) return "resync_and_replay" if verdict == "duplicate": # Dedup by event ID before processing; never re-execute a result # already observed at or before L. return "dedup_and_continue" if verdict == "dead": raise MCPStreamResumeError( f"stream dead after {elapsed_since_reconnect:.1f}s; " f"force full session re-initialize, last_event_id={state.last_processed_event_id}" ) return "continue" ```