# Which invariants prevent stream-resumption replay from duplicating tool side effects across MCP HTTP-native sessions **Date of Record:** 2026 November 25 **Scope:** Applies to MCP servers exposing HTTP-native transports (Streamable HTTP / SSE-over-POST) where a client may reconnect with `Last-Event-ID` to resume a broken stream, and where tools invoked during that stream carry non-idempotent side effects. Does not apply to stdio transports, nor to stateless HTTP endpoints that never emit resumable event IDs. ## Core Distinction There are two distinct notions of "resumption" that get conflated in MCP HTTP-native transport, and the conflation is where the failure lives: - **Stream resumption** — the transport-layer guarantee that a reconnecting client, presenting `Last-Event-ID: N`, receives every SSE event with id `> N` that the server emitted after the disconnect. This is a *delivery* invariant: it says nothing about whether the work described by those events was already performed. - **Effect resumption** — the semantic guarantee that a tool call whose result the client never observed is either not re-executed, or is re-executed idempotently. A conformant MCP server can satisfy stream resumption perfectly while violating effect resumption catastrophically. The boundary condition is precisely this: the client received the `tools/call` *request* event, the server *executed* the tool (side effect committed), but the `tools/call` *result* event was emitted into a stream buffer that the client never drained because the TCP connection died mid-flush. On reconnect with `Last-Event-ID` pointing at the request event, a naive replay re-emits the request — and the client, seeing no result, re-issues the call. The tool runs twice. The invariant that must hold is: **the event id is a monotonic position in a durable, ordered log, and every event's id is assigned at the moment of emission, not at the moment of computation; reconnection replays from the log, never re-derives from computation.** If the server reconstructs the stream by re-running the handler instead of reading the log, stream resumption is a lie. ## What Was Observed A tool server backed by a queue-and-worker design: the HTTP handler accepted `tools/call`, enqueued the work, and streamed progress events (`queued`, `started`, `progress`, `result`) back over SSE, each with a monotonically increasing `id`. The `result` event carried the tool output. Workers committed side effects (a database write, an outbound webhook) before the `result` event was enqueued. Failure trace: 1. Client POSTs `tools/call` for a `charge_card` tool. Server assigns event id `41` to the request echo, enqueues work, returns `202`-style streaming response. 2. Worker executes: commits the charge, then pushes `result` event as id `44` into the session's event log. 3. Network drops after the client drained id `43` (`progress: 100%`) but before id `44` reached the socket. Client's last seen id is `43`. 4. Client reconnects with `Last-Event-ID: 43`. Server, correctly per the spec, replays events `> 43` from its log — including `44`. **This path is safe.** The bug appears in the *other* code path. 5. In the observed incident, the server's session store had evicted the event log for id `44` after a 60-second TTL (log retention shorter than the session's tool timeout). On reconnect, the server found no events `> 43`, concluded the stream was "complete with nothing pending," and closed the stream with a `200` and an empty body. The client, having no `result` and no error, treated the call as *not executed* and re-issued it. The card was charged twice. The second, subtler variant: some clients don't trust an empty resume and re-issue the `tools/call` anyway, relying on the server to dedupe. The server had no dedupe key — `tools/call` had no idempotency token — so every reconnect after a mid-flush drop produced a duplicate side effect. The retry amplification was 1.9× average across the incident window (some calls re-issued twice before a result landed). The core observation: **an empty replay set was indistinguishable from "the work never happened."** The transport had no way to express "events `> 43` existed but are no longer retained," so it silently degraded to "no events," and the client's recovery policy — re-issue on silence — turned a retention gap into a duplicate charge. ## Condition of Validity Stream resumption with `Last-Event-ID` is only a valid recovery primitive when all four of the following hold simultaneously: 1. **Durable, ordered log with ids assigned at emission.** The event log for a session is append-only and survives at least as long as the session's maximum tool timeout plus the client's maximum reconnect backoff. If the log TTL is shorter than the tool timeout, resumption is unsound — this is the exact configuration that produced the incident. 2. **Retention gap is explicit, not silent.** If a client presents `Last-Event-ID: N` and the server cannot serve `> N` (log truncated, session expired, id unknown), the server MUST respond with a distinguishable error (e.g., `410 Gone` or a structured `resume_failed` event), never an empty `200`. An empty `200` asserts "nothing happened after N," which is a factual claim the server cannot make when it has discarded the evidence. 3. **Effect identity is carried end-to-end.** Every `tools/call` carries a client-generated idempotency key that the server records *before* executing the side effect and checks before re-executing. Stream resumption alone cannot prevent duplicate effects; it can only prevent duplicate *delivery*. The two guarantees are orthogonal and both are required. 4. **The client's recovery policy is keyed on the server's explicit signal, not on silence.** A client that re-issues on an empty resume is safe only if the server dedupes by idempotency key; a client that re-issues on a `resume_failed` error is safe only if the server also dedupes. Silence must never be a valid input to a retry decision. When any of these fails, the boundary is crossed: the system will, under mid-flush disconnection, either lose a result (client waits forever, token budget burns on a hung call) or duplicate a side effect (charge twice, send twice, mutate twice). Both are worse than a clean failure. ## Decision Boundary The architectural decision is where to place the idempotency boundary relative to the stream boundary: - **Stream-boundary idempotency (insufficient):** dedupe on `(session_id, Last-Event-ID)`. Fails because the client's recovery attempt may present a *different* last-event-id (it may have drained one more event before the second drop), so the dedupe key differs and the duplicate slips through. - **Effect-boundary idempotency (required):** dedupe on a client-supplied `idempotency_key` scoped to the logical operation, recorded in the same transaction as the side effect. The key is stable across reconnects and re-issues; the stream position is not. The invariant: *the idempotency key is generated once per logical tool invocation and reused verbatim on every retry, and the server's dedupe record is committed atomically with the side effect.* The decision boundary for the server implementer: if you cannot commit the dedupe record atomically with the side effect (e.g., the side effect is an outbound HTTP call to a third party that has no idempotency support), you must not claim effect resumption. In that case the correct behavior on a retention gap is to return `resume_failed` and let the client surface the ambiguity to the orchestrator — never to silently re-execute. The decision boundary for the client implementer: on `resume_failed` or on any resume that yields no terminal event within the tool's declared timeout, the client must escalate to the orchestrator with the idempotency key and the last-seen event id, and must not auto-retry without a dedupe-capable server. Auto-retry-on-silence is the anti-pattern. ## Operational Effect After the incident, the server was changed along three axes, each mapping to one of the invariants above: 1. Event log TTL was decoupled from session TTL and set to `max_tool_timeout + max_reconnect_backoff + safety_margin`, with a hard assertion at startup that `log_ttl > tool_timeout` (the misconfiguration that caused the incident was a 60s log TTL against a 120s tool timeout — the assertion would have refused to boot). 2. A `Last-Event-ID` that the server cannot satisfy now returns a structured `410` with `resume_failed` and the highest id the server *can* still serve, so the client can distinguish "nothing pending" from "evidence discarded." 3. Every `tools/call` now requires an `idempotency_key`; the server writes `(key, status=in_flight)` before dispatch and `(key, status=committed, result)` in the same transaction as the side effect. A re-issued call with a known key either returns the cached result (committed) or attaches to the in-flight operation (in_flight) rather than re-executing. The retry amplification dropped from 1.9× to 1.0× over the following week; the residual 1.0× is the correct behavior — reconnects replay events, they do not replay effects. The durable lesson: **in MCP HTTP-native transport, `Last-Event-ID` is a delivery cursor, not a transaction log. Treating it as a transaction log — by inferring "no events after N" means "no work after N" — is the boundary at which stream resumption silently becomes effect duplication.** ```python from __future__ import annotations import time from dataclasses import dataclass, field from typing import Optional class ResumeInvariantViolation(RuntimeError): """Raised when stream resumption would silently degrade into effect duplication.""" @dataclass class EventLog: """Append-only, ordered event log with ids assigned at emission.""" events: list[tuple[int, str]] = field(default_factory=list) next_id: int = 1 log_ttl_seconds: float = 0.0 created_at: float = field(default_factory=time.monotonic) def append(self, payload: str) -> int: eid = self.next_id self.next_id += 1 self.events.append((eid, payload)) return eid def replay_after(self, last_event_id: int) -> list[tuple[int, str]]: if time.monotonic() - self.created_at > self.log_ttl_seconds: # Evidence discarded. We cannot assert "nothing happened after N". raise ResumeInvariantViolation( f"event log expired (ttl={self.log_ttl_seconds}s); " f"cannot serve resume for Last-Event-ID={last_event_id}" ) return [(eid, p) for (eid, p) in self.events if eid > last_event_id] @dataclass class IdempotencyRecord: status: str # "in_flight" | "committed" result: Optional[str] = None class ToolServer: def __init__(self, log_ttl_seconds: float, tool_timeout_seconds: float) -> None: if log_ttl_seconds <= tool_timeout_seconds: raise ResumeInvariantViolation( "log_ttl must exceed tool_timeout; otherwise a mid-flush drop " "produces a silent retention gap and duplicate side effects" ) self.log_ttl_seconds = log_ttl_seconds self.tool_timeout_seconds = tool_timeout_seconds self.sessions: dict[str, EventLog] = {} self.idempotency: dict[str, IdempotencyRecord] = {} def _log(self, session_id: str) -> EventLog: if session_id not in self.sessions: self.sessions[session_id] = EventLog(log_ttl_seconds=self.log_ttl_seconds) return self.sessions[session_id] def resume(self, session_id: str, last_event_id: int) -> list[tuple[int, str]]: log = self._log(session_id) # Raises ResumeInvariantViolation on retention gap -> caller must # surface 410 resume_failed, never an empty 200. return log.replay_after(last_event_id) def call_tool(self, session_id: str, idempotency_key: str, side_effect) -> str: log = self._log(session_id) existing = self.idempotency.get(idempotency_key) if existing is not None: if existing.status == "committed": return existing.result # type: ignore[return-value] # in_flight: attach to the running operation rather than re-execute. return f"attached:{idempotency_key}" # Claim the key BEFORE executing the side effect. self.idempotency[idempotency_key] = IdempotencyRecord(status="in_flight") log.append(f"request:{idempotency_key}") try: result = side_effect() except Exception: # Side effect failed; release the claim so a retry may proceed. del self.idempotency[idempotency_key] raise # Commit dedupe record and result event together. self.idempotency[idempotency_key] = IdempotencyRecord( status="committed", result=result ) log.append(f"result:{idempotency_key}:{result}") return result def demo() -> None: server = ToolServer(log_ttl_seconds=60.0, tool_timeout_seconds=120.0) # raises if __name__ == "__main__": demo() ```