# Which invariants prevent MCP resumable-SSE replay from silently duplicating tool side-effects across a session resume **Date of Record:** 2026 December 3 **Scope:** Applies to MCP servers exposing the HTTP-native streamable transport with `Last-Event-ID` resumption and `Mcp-Session-Id` session continuity, where a client reconnects mid-stream after a transport drop. Does not apply to stdio transport, to stateless SSE endpoints without event IDs, or to servers that never emit resumable event IDs. ## Core Distinction The resumable-SSE contract conflates two different guarantees that agents routinely treat as one: *delivery continuity* (the client sees every SSE event exactly once, in order) and *execution continuity* (the server-side tool invocation happened exactly once). The streamable transport only ever promises the former. The `Last-Event-ID` header is a *replay cursor over a server-side event log*, not a transaction token for the tool call that produced those events. When an agent reconnects and replays from `Last-Event-ID: N`, the server re-emits buffered events `N+1..`, but it does **not** re-run the tool — unless the server's event buffer was never persisted, in which case it re-runs the whole call and the client sees a *fresh* event stream whose IDs restart or skip. The invariant that matters is not "events are durable" but "the mapping from `(session_id, tool_call_id)` to exactly one executed side-effect is durable and is checked *before* replay." Without that mapping, resumption is indistinguishable from a new request, and an agent that retries on transport error will double-invoke non-idempotent tools. ## What Was Observed A tool-calling agent issued `tools/call` for `transfer_funds(amount=500, to="acct_9")` over streamable HTTP. The server executed the transfer, emitted event `id=41` (`progress`), then `id=42` (`result`), and the connection dropped at the TCP layer before the client's SSE parser flushed `id=42`. The client's transport layer, seeing a socket reset, reconnected and sent `Last-Event-ID: 41` with the same `Mcp-Session-Id`. Two server behaviors were observed across deployments: - **Buffer-backed server (correct):** replayed `id=42` from an in-memory ring buffer keyed by session. One transfer. Client received the result and acked. - **Stateless-edge server (incorrect):** the edge proxy that terminated TLS had no session affinity, so the reconnect landed on a different worker whose event buffer was empty for that session. The worker, seeing `Last-Event-ID: 41` for a session it did not own, fell back to treating the request as a fresh `tools/call` (the `Last-Event-ID` was ignored because no matching log existed) and re-executed `transfer_funds`. Two transfers. The client received `id=42'` (a new event ID from the new worker) and had no way to distinguish it from a replay. The failure is silent: both paths return a syntactically valid `result` event. The agent's loop has no signal that the side-effect count diverged from the event count. ## Condition of Validity The replay-is-safe invariant holds only when **all three** of the following are true simultaneously: 1. **Session affinity or shared event log.** The `Mcp-Session-Id` routes to a worker that can resolve `Last-Event-ID` against a durable (or at least session-pinned) event log. If the log is per-worker and the reconnect can land elsewhere, `Last-Event-ID` degrades to a hint. 2. **A deduplication key on the tool invocation.** The server must persist `(session_id, tool_call_id) → execution_status` *before* emitting the first event, and on any replay request must check it before re-executing. The `tool_call_id` (or an equivalent client-supplied idempotency key in `_meta`) is the only thing that distinguishes "replay this stream" from "run this again." 3. **Monotonic, non-resetting event IDs.** Event IDs must be strictly increasing across the session lifetime and must not restart at 1 on a new worker. A reset makes `Last-Event-ID: 41` ambiguous — it could mean "after 41" or "after the 41 that no longer exists." The invariant fails the moment any one is dropped. The most common real-world failure is (1) and (2) together: a horizontally scaled server behind a load balancer where the session ID is present but the dedup table is per-worker. ## Decision Boundary The agent-side decision that determines whether this becomes a duplicate is: **on transport error mid-`tools/call`, does the client retry with `Last-Event-ID` set, or does it re-issue the call?** - If the client retries with `Last-Event-ID` **and** the server honors the dedup key, the call is safe regardless of idempotency. - If the client re-issues the call (because it cannot determine whether the prior call reached the server), the call is safe **only if the tool is idempotent** or the client supplies a stable idempotency key the server enforces. - If the client retries with `Last-Event-ID` **and** the server ignores it (no matching log), the call is **unsafe for non-idempotent tools** — this is the silent-duplicate path. The boundary is therefore not "is the transport resumable" but "on resume, who owns the exactly-once guarantee." The transport cannot own it; only the server's dedup table can. An agent that assumes the transport owns it will double-invoke. ## Operational Effect The practical consequence: any `tools/call` whose side-effect is not idempotent (payments, file writes, message sends, state mutations) must carry a client-generated idempotency key in `_meta`, and the server must reject a second execution for the same key with a distinguishable error or a replayed result — not a fresh execution. Agents that rely solely on `Last-Event-ID` for safety will, under worker-failover or buffer-eviction, execute the tool twice and receive two valid-looking result events with no error surfaced. The guardrail is a server-side `(session_id, idempotency_key)` uniqueness constraint checked *before* the tool runs, plus client-side refusal to re-issue a `tools/call` without either a `Last-Event-ID` it can verify was honored or a fresh idempotency key it knows the server enforces. Detection of the silent path requires the server to log replays that fell back to re-execution; without that log, the duplicate is invisible to both sides. ```python from dataclasses import dataclass, field from typing import Optional class ResumptionInvariantViolation(RuntimeError): """Raised when a resumable-SSE reconnect cannot guarantee exactly-once execution.""" @dataclass class ToolCallRecord: session_id: str idempotency_key: str executed: bool = False result_event_id: Optional[int] = None class ResumableSessionServer: """Enforces (session_id, idempotency_key) -> exactly one execution across resumes.""" def __init__(self): # Durable dedup table. Must survive worker failover for the invariant to hold. self._dedup: dict[tuple[str, str], ToolCallRecord] = {} # Per-session event log. If this is worker-local, Last-Event-ID degrades to a hint. self._event_log: dict[str, list[tuple[int, str]]] = {} self._next_event_id: dict[str, int] = {} def _emit(self, session_id: str, payload: str) -> int: eid = self._next_event_id.get(session_id, 40) + 1 self._next_event_id[session_id] = eid self._event_log.setdefault(session_id, []).append((eid, payload)) return eid def handle_tools_call( self, session_id: str, idempotency_key: str, last_event_id: Optional[int], tool_fn, ) -> tuple[int, str]: # Step 1: resolve replay cursor. If the log is missing, we MUST NOT silently re-execute. log = self._event_log.get(session_id) if last_event_id is not None: if log is None: raise ResumptionInvariantViolation( f"session {session_id!r} has no event log for Last-Event-ID=" f"{last_event_id}; replay cannot be honored, refusing to re-execute " f"non-idempotent call with key {idempotency_key!r}" ) for eid, payload in log: if eid > last_event_id: return eid, payload # pure replay, no execution # Step 2: dedup check BEFORE execution. key = (session_id, idempotency_key) record = self._dedup.get(key) if record is not None and record.executed: # Already ran; replay its terminal event rather than re-running. if record.result_event_id is None: raise ResumptionInvariantViolation( f"call {key!r} marked executed but has no terminal event; " f"state is inconsistent, refusing to proceed" ) return record.result_event_id, dict(self._event_log[session_id])[ record.result_event_id ] # Step 3: first execution. Record intent, run, then emit. record = ToolCallRecord(session_id=session_id, idempotency_key=idempotency_key) self._dedup[key] = record self._emit(session_id, "progress") result = tool_fn() record.executed = True record.result_event_id = self._emit(session_id, str(result)) return record.result_event_id, str(result) ```