# In what scenarios must an instance treat MCP Streamable HTTP `Last-Event-ID` resumption as a replay hazard rather than a recovery guarantee **Date of Record:** 2026 December 4 **Scope:** Applies to MCP clients using the Streamable HTTP transport (single POST endpoint returning either `application/json` or `text/event-stream`, with optional `GET` SSE stream and `Last-Event-ID` resumption) where the client is a stateless agent process that may be restarted, horizontally scaled, or re-instantiated between tool calls. Does not apply to stdio transport, nor to in-process session managers that retain the full SSE buffer in memory across reconnects. ## Core Distinction The MCP Streamable HTTP spec offers `Last-Event-ID` as a resumption primitive: a client that loses an SSE stream reconnects with `GET` and the last `id` field it observed, and the server is expected to replay events after that point. Operators routinely conflate this with *exactly-once delivery of tool results*. It is not. It is *at-least-once replay of a bounded, server-retained event log*, and the retention window, event-ID monotonicity, and the mapping between SSE events and side-effecting tool invocations are all server-discretionary. The boundary condition is this: **a stateless agent that resumes a stream and treats replayed events as fresh observations will double-execute any tool call whose side effect is not idempotent, and will silently drop any event that fell outside the server's retention window.** The invariant that must hold is *event-ID continuity plus side-effect deduplication*, and neither is guaranteed by the transport alone. ## What Was Observed A research agent orchestrating a `web.search` → `web.fetch` → `file.write` chain over an MCP server behind a load balancer. The agent runs as a stateless worker: each tool call is a fresh HTTP POST, and the client keeps only `(session_id, last_event_id)` in external storage. The server retains SSE events for 60 seconds or 1,000 events, whichever comes first, in a per-session ring buffer keyed by a process-local counter. Trace of the failure: 1. Agent issues `tools/call` for `file.write` (non-idempotent: appends a line to a report). Server accepts, begins streaming progress events `id=41`, `id=42`, then the tool result `id=43`. 2. The response stream stalls after `id=42` (server GC pause, or proxy idle timeout at 30s). The agent's read times out. The agent has persisted `last_event_id=42`. 3. Agent reconnects with `GET /mcp` and `Last-Event-ID: 42`. The server, having already committed the `file.write` side effect, replays events `43` onward — *including the result of the write it already performed*. 4. But the agent's stateless client cannot distinguish "event 43 is a replay of a result I never saw" from "event 43 is a result of a call I am about to re-issue." Because the agent's POST for `file.write` had *also* been retried by the client's HTTP layer (a separate retry policy), the server received two `tools/call` requests. The second produced events `id=44` (a second `file.write` result). The agent, resuming from 42, saw `43` and `44` as two distinct results and recorded two writes. 5. Result: the report contains the line twice. The agent's ledger believes one write occurred. The divergence is invisible until a downstream reader deduplicates. A second, quieter failure in the same session: the agent was restarted 90 seconds later (after the 60-second retention window). It reconnected with `Last-Event-ID: 44`. The server had evicted the ring buffer and returned `200` with an empty stream and no error. The agent interpreted "no events after 44" as "stream is current," missing that events `45`–`47` (a tool error and a partial result) had been evicted. The agent proceeded as if the call had succeeded. ## Condition of Validity The `Last-Event-ID` resumption contract is only sound under a conjunction of conditions, none of which the transport enforces: - **Event-ID monotonicity per session.** If the server restarts and resets its counter, a resumed client's `Last-Event-ID: 44` may match a *new* event 44 from a different logical stream. The spec does not require globally unique or epoch-tagged IDs. - **Retention window ≥ client's maximum reconnect latency.** A stateless client with no local buffer has no way to detect eviction: the server is permitted to return an empty stream, and there is no "gap" signal in the SSE framing. - **One-to-one mapping between SSE events and side-effecting tool invocations.** If a single `tools/call` emits progress events and a terminal result event, replay of the terminal event is indistinguishable from a fresh result unless the event carries the original request ID. - **Client-side idempotency keys.** The spec's `tools/call` does not mandate a client-supplied idempotency token. Without one, the server cannot deduplicate a retried POST against a prior accepted call. When any of these fails, `Last-Event-ID` degrades from a recovery guarantee to a *replay hazard*: it can cause duplicate side effects (retention intact, retry duplicate) or silent gaps (retention evicted, empty stream returned). ## Decision Boundary The agent must classify its resumption path before acting on any replayed event: - **If the server advertises an idempotency mechanism** (a documented `Idempotency-Key` header honored on `tools/call`, or event payloads carrying the originating `request_id`), the agent MAY treat replay as safe *provided* it re-derives tool results from the event's `request_id` rather than from arrival order. - **If the server does not advertise idempotency**, the agent MUST treat every resumed event whose `id` is greater than `last_event_id` but whose originating request is unknown as *unverified*, and MUST NOT re-issue the corresponding `tools/call` until it has queried a side-effect ledger (a read-only `tools/call` to a resource the server exposes, e.g. `resources/read` of the target file) to confirm whether the effect landed. - **If the reconnect returns `200` with zero events and the session's last known event was within the retention window's expected horizon**, the agent MUST treat this as an *eviction gap*, not a *current stream*, and MUST fall back to full state re-derivation (re-read all resources the session touched) rather than assuming continuity. - **If the server's event IDs are not epoch-tagged** (no session-generation prefix), the agent MUST invalidate `last_event_id` on any reconnect that crosses a server restart boundary (detectable via a changed `Mcp-Session-Id` or a server-provided generation token) and MUST NOT resume across it. The boundary is sharp: resumption is a *hint*, not a *commitment*. The agent's correctness rests on its own idempotency discipline, not on the transport's replay semantics. ## Operational Effect Teams that treat `Last-Event-ID` as a durable cursor see two failure signatures in production: (1) duplicate side effects clustered around proxy idle-timeouts (30s, 60s, 100s — the common LB defaults), and (2) silent data loss clustered around server restarts and ring-buffer evictions, where the agent's ledger diverges from ground truth without any error surfaced. The remediation is architectural, not transport-level: stateless agents must carry an idempotency key per logical `tools/call`, persist the *request→event* mapping (not just the last event ID), and on any resumption gap, re-derive state from authoritative resources rather than trusting the stream. The transport's replay window is a performance optimization; the agent's ledger is the source of truth. Conflating the two is the failure. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class ResumptionReplayHazard(RuntimeError): """Raised when a stateless MCP client cannot safely resume an SSE stream.""" @dataclass class ResumptionState: session_id: str last_event_id: Optional[int] server_generation: str retention_window_seconds: int pending_calls: dict = field(default_factory=dict) # idempotency_key -> request_id def resume_stream( state: ResumptionState, reconnect_generation: str, seconds_since_last_event: int, replayed_event_ids: list[int], idempotency_supported: bool, ) -> list[int]: """ Decide which replayed events a stateless agent may act on. Returns the subset of event IDs that are safe to treat as fresh observations. """ if reconnect_generation != state.server_generation: # Event-ID counter may have reset; last_event_id is not a valid cursor. raise ResumptionReplayHazard( f"server generation changed {state.server_generation!r} -> " f"{reconnect_generation!r}; last_event_id={state.last_event_id} " f"is not a valid resumption cursor" ) if seconds_since_last_event > state.retention_window_seconds: # Ring buffer almost certainly evicted; empty replay is a gap, not continuity. raise ResumptionReplayHazard( f"reconnect after {seconds_since_last_event}s exceeds retention " f"window {state.retention_window_seconds}s; replay may be silently " f"truncated" ) if not replayed_event_ids and state.last_event_id is not None: # 200 with zero events inside the retention horizon is ambiguous. raise ResumptionReplayHazard( "empty replay inside retention window: cannot distinguish " "'stream is current' from 'events evicted'; re-derive state" ) if not idempotency_supported and state.pending_calls: # Replayed events may correspond to side-effecting calls we already # dispatched; acting on them risks duplicate execution. raise ResumptionReplayHazard( f"{len(state.pending_calls)} side-effecting call(s) in flight and " f"server does not honor idempotency keys; replay is unsafe" ) # Safe path: monotonic IDs, within retention, idempotency enforced. return [eid for eid in replayed_event_ids if eid > (state.last_event_id or -1)] def make_idempotency_key(session_id: str, tool_name: str, args: dict) -> str: material = f"{session_id}:{tool_name}:{sorted(args.items())!r}".encode() return hashlib.sha256(material).hexdigest() ```