# Which invariants prevent SSE `Last-Event-ID` resumption from silently duplicating tool side-effects across an MCP session reconnect **Date of Record:** 2026 December 2 **Scope:** Applies to MCP servers using the HTTP-native transport (Streamable HTTP + SSE) where a client reconnects with a `Last-Event-ID` header and a `Mcp-Session-Id` to resume an interrupted tool-call stream. Does not cover stdio transport, nor pure request/response MCP without server-push streams, nor idempotent read-only tools. ## Core Distinction There are two things a client can resume, and they are not the same thing: - **Stream resumption** — re-attaching to the SSE byte stream at event ID `N+1` so the client sees every event it missed. - **Execution resumption** — whether the *server-side* tool invocation that produced those events continues, restarts, or was already committed to its side effect. The `Last-Event-ID` header only ever negotiates the first. The MCP transport spec is deliberately silent on the second, and that silence is where side effects get duplicated. A resumption token proves *where in the event log* the client was; it proves nothing about *where in the tool's execution* the server was. Conflating the two is the failure mode. The invariant that must hold: **the event log is a replay buffer, not an execution ledger.** Resumption replays events; it must never re-run the handler that emitted them. ## What Was Observed An agent invoked a mutating tool (`create_ticket`, `transfer_funds`, `send_email`-class) over Streamable HTTP. The tool took longer than the client's idle read timeout (~30s), so the SSE connection dropped mid-stream. The client, following the resumability contract, reconnected with: ``` GET /mcp Mcp-Session-Id: 7f3a... Last-Event-ID: 12 Accept: text/event-stream ``` The server had, at the moment of the drop, already executed the tool and emitted events `1..12` (progress, partial result). Event `13` (final result) had been generated but the write to the dead socket failed. Two distinct server implementations produced two distinct wrong outcomes: 1. **Replay-only server (the "safe" bug):** it correctly replayed events `13..` from the buffer and did *not* re-execute. This is the correct behavior — but it only worked because the handler had finished. If the drop had happened at event `6` while the handler was still running, the server had no live handler to attach the new socket to, so it returned `404` on the resume and the client retried the *whole* `tools/call` — duplicate side effect. The buffer replay was fine; the *live-handler reattachment* was missing. 2. **Re-execute-on-resume server (the "obvious" bug):** it treated `Last-Event-ID` as a checkpoint into the request and re-invoked the handler, replaying `1..12` from buffer then continuing from `13` by running the tool again. Two tickets created. The client saw a clean, gap-free, monotonic event stream and had no way to detect the duplicate — the event IDs were contiguous and the final result was well-formed. The tell in case 2: the event ID sequence was *not* actually monotonic across the seam. The buffer's event `12` had `id: 12`; the re-executed handler's first fresh event also minted `id: 13` but with a different `data` payload hash than the one the original run had generated before dying. A client that hashes `(id, data)` pairs would catch it. A client that trusts `Last-Event-ID` as a cursor would not. ## Condition of Validity Resumption is *safe* (no duplicated side effect) only when **all** of the following hold: 1. The server maintains a **per-stream event buffer keyed by a session-scoped monotonic event ID**, and the buffer is retained for at least the client's maximum reconnect window (the spec's resumability is best-effort; retention is an operational choice the server must make explicitly). 2. The server distinguishes **"handler still running"** from **"handler finished, buffer retained."** On resume: - handler finished → replay buffer tail, close stream. **Never** re-invoke. - handler still running → *reattach* the new socket to the live handler's emitter (fan-out), do not spawn a second handler. - handler unknown (buffer evicted, session expired) → return a **terminal** error (`410 Gone` or a JSON-RPC error with a distinct code), and the client must treat the `tools/call` as **indeterminate**, not retryable-with-same-id. 3. Every event carries a **stable ID minted once at emit time**, not re-derived on replay. Re-execution cannot fake this because a fresh run mints fresh IDs whose payloads won't match the buffered prefix. 4. The client, on `Last-Event-ID` resume, verifies the first replayed event's `id` equals `Last-Event-ID + 1` **and** that any overlap region matches previously-seen `(id, payload-hash)` pairs. If any of (1)–(4) is absent, the transport still "works" — streams resume, the client sees a continuous event log — but side-effect exactly-once is not guaranteed. ## Decision Boundary The boundary is **where the handler's lifetime ends relative to the socket's lifetime**, and there are three regimes: - **Socket dies after handler commits, buffer retained:** resumption is a pure read of the buffer. Safe. This is the regime everyone tests, and it is why the bug hides. - **Socket dies while handler runs:** the server must reattach, not restart. This is the regime that breaks. The trigger is a slow tool (LLM-generated plan, external API call, long file write) crossing the client's idle timeout. The probability of hitting it scales with `tool_latency / client_idle_timeout` and is therefore *high* for agentic tools, which are exactly the ones with side effects. - **Socket dies after handler commits, buffer evicted / session expired:** the client cannot know whether the side effect happened. This is *indeterminate*, and the only correct transport response is a terminal, non-retryable signal. Returning `404 Not Found` on the resume (which many servers do, treating an unknown `Last-Event-ID` as a bad request) invites the client's generic retry logic to re-issue the `tools/call` — the worst outcome, because it looks like a fresh request. The decision rule: **`Last-Event-ID` is a cursor, never a checkpoint.** The server may use it to decide *what to replay*; it must never use it to decide *what to re-execute*. Execution identity (a request-scoped idempotency key, distinct from the event cursor) is the only thing allowed to gate re-execution, and it must be minted by the client *before* the first attempt and carried in the `tools/call` params — not in the transport headers, where it can be lost on reconnect. ## Operational Effect Concretely, for an agent runtime: - **Duplicate side effects on reconnect** are the default unless the server reattaches live handlers. Agents that retry on `404`-on-resume will double-write. The event stream looks perfect; the ledger is wrong. - **The client cannot detect the duplicate from the stream alone** in the re-execute case, because the server re-mints contiguous IDs. Detection requires the client to hash `(id, data)` and reject a resume whose overlap prefix doesn't match — a check almost no MCP client performs today. - **Indeterminate outcomes must be surfaced as indeterminate.** If the server returns a terminal error on an evicted buffer, the agent layer must *not* auto-retry the tool; it must escalate (query the side-effect target, or fail the task with a "may have partially executed" state). Auto-retry here is the compounding-error path: one duplicate ticket becomes three across two reconnects. - **The idempotency key must live in the request body, not the headers.** Transport headers are re-derived on reconnect; body params are the only thing the client can guarantee it resends identically. A server that keys idempotency off `Last-Event-ID` will treat a resumed stream and a fresh call as different executions of the same intent — or, worse, the same execution of two different intents if the client reuses the header. Guardrail: the server should refuse to start a `tools/call` whose `idempotency_key` (body param) it has already seen *and* whose prior run is still live or whose buffer is retained, returning the buffered result instead of re-running. The `Last-Event-ID` header then becomes purely advisory for the replay cursor. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class ResumptionIntegrityError(RuntimeError): """Raised when an SSE resume cannot be proven side-effect-safe.""" pass @dataclass class BufferedEvent: event_id: int payload: str def fingerprint(self) -> str: return hashlib.sha256(f"{self.event_id}:{self.payload}".encode()).hexdigest() @dataclass class StreamState: # execution identity, minted by client in tools/call params -- NOT the cursor idempotency_key: str handler_running: bool committed: bool buffer: list[BufferedEvent] = field(default_factory=list) class ResumableSession: def __init__(self) -> None: self._streams: dict[str, StreamState] = {} def resume( self, idempotency_key: str, last_event_id: int, client_seen: dict[int, str], ) -> list[BufferedEvent]: state: Optional[StreamState] = self._streams.get(idempotency_key) # Regime 3: buffer evicted / unknown session -> INDETERMINATE, never retry. if state is None: raise ResumptionIntegrityError( f"no retained buffer for idempotency_key={idempotency_key!r}; " "side effect is indeterminate -- do not auto-retry tools/call" ) # Regime 2: handler still running -> reattach, do NOT re-execute. # Regime 1: handler finished -> pure replay of buffer tail. # Either way we replay from the buffer; we never re-invoke the handler here. tail = [e for e in state.buffer if e.event_id > last_event_id] # Invariant: first replayed id must be last_event_id + 1 (no gap, no reseed). if tail and tail[0].event_id != last_event_id + 1: raise ResumptionIntegrityError( f"event-id discontinuity: expected {last_event_id + 1}, " f"got {tail[0].event_id} -- server may have re-executed the handler" ) # Invariant: overlap region must match what the client already saw. for ev in state.buffer: if ev.event_id in client_seen: if client_seen[ev.event_id] != ev.fingerprint(): raise ResumptionIntegrityError( f"payload mismatch at event {ev.event_id}: " "replayed bytes differ from first delivery (re-execution detected)" ) if not state.handler_running and state.committed and not tail: # Fully drained and committed; resume is a no-op close. return [] return tail def handle_resume( session: ResumableSession, idempotency_key: str, last_event_id: int, client_seen: dict[int, str], ) -> list[BufferedEvent]: events = session.resume(idempotency_key, last_event_id, client_seen) if events and events[0].event_id != last_event_id + 1: # Defensive re-check; resume() already enforces this. raise ResumptionIntegrityError("post-resume cursor invariant violated") return events ```