# Why does an instance resume an MCP streamable session against a replayed SSE event log and silently double-apply the last tool call? **Date of Record:** 2026 November 25 **Scope:** Applies to MCP clients using the HTTP-native streamable transport (SSE server-push with `Last-Event-ID` resumption) when a session is re-established after transport interruption. Does not apply to stdio transports, nor to stateless HTTP request/response MCP servers that never emit resumable event streams. ## Core Distinction The failure is not "the connection dropped." Connections drop constantly and that is a solved problem. The distinction that matters is between **transport-level replay** and **semantic-level re-execution**. The MCP streamable transport contract says: on reconnect, the client sends `Last-Event-ID`, and the server replays every SSE event with an ID strictly greater than that value. This guarantees the *byte stream* is contiguous. It guarantees nothing about the *side effects* the agent already committed to based on events it received before the drop but whose acknowledgements never made it back. An instance that treats "I received event #47 again after resume" as "I should process event #47 again" will re-execute the tool call embedded in that event. The event ID is a deduplication key for the *stream*, not for the *agent's action ledger*. Conflating the two produces exactly-once-violating double application, and because tool calls are frequently non-idempotent (file appends, `git commit`, `POST /charges`, `send_email`), the second application is not a no-op — it is a second real-world effect. ## What Was Observed A research agent drove a long-running task across an MCP server exposing `append_to_notes`, `run_shell`, and `fetch_url`. The server used server-push SSE: it emitted `event: message` frames carrying JSON-RPC responses and notifications, each with a monotonically increasing `id:` field. The client persisted `last_event_id` to disk after each *received* frame. The trace: 1. Agent issues `tools/call` for `append_to_notes` with body `"step 12\n"`. The server executes it (file now contains `step 12`), then emits the JSON-RPC response as SSE event `id: 47`. 2. The SSE frame reaches the client's socket buffer. The client's `on_event` handler begins processing. Before it can persist `last_event_id = 47` and before the response is handed to the reasoning loop, the TCP connection is reset (idle-timeout on an intermediate proxy, 90s). 3. Client reconnects. It reads its persisted `last_event_id`, which is still `46`. It sends `Last-Event-ID: 46`. 4. Server, per spec, replays all events with ID > 46, i.e. event `47` again. The server does **not** re-run `append_to_notes` — replay is from an event buffer, not from re-execution. 5. Client's `on_event` fires for event `47` a second time. The reasoning loop, which has no memory of having seen 47 (it never committed the response to its context — that's the whole reason it resumed), treats this as the tool result for a call it now believes is outstanding, and — because its own local call-ledger was also lost — re-issues `append_to_notes` with the same body to "retry the interrupted call." 6. File now contains `step 12\nstep 12\n`. The agent's subsequent reasoning is built on a corrupted artifact, and downstream steps that parse line counts diverge. The non-obvious part: **the stream replay was correct and the server was spec-compliant.** The server did exactly what `Last-Event-ID` demands. The bug lived entirely in the client's decision to map "replayed stream event" onto "re-issue the originating request," when the correct mapping was "replayed stream event → this is the response to a request I already sent; adopt it, do not resend it." ## Condition of Validity The double-apply only occurs when all of the following hold simultaneously, which is why it is rare enough to escape testing but common enough to hit in production: - The server-push transport is used with resumable event IDs (SSE `id:` field present), and the server retains an event buffer (required for `Last-Event-ID` to return anything). - The client persists `last_event_id` **after** event processing rather than atomically with receipt, OR the process crashes between receipt and persistence. Either way the persisted cursor lags the actually-delivered stream by at least one event. - The interrupted event carried a **request-correlated response** (a `tools/call` result) rather than a pure notification. Notifications replayed are usually harmless; responses replayed are the dangerous class because they imply a caller waiting. - The client's request ledger (outstanding call IDs) is **not** durable across the reconnect — i.e. the client cannot answer "have I already sent request with id X?" after resume. - The tool is non-idempotent. Remove any one condition and the failure collapses. The invariant that bounds it: **the agent's action ledger and the transport's event cursor must be committed in the same durable transaction, and resumption must reconcile the ledger against replayed events before any request is re-issued.** If they are two separate writes, there is a window where the stream cursor and the "what have I actually done" record disagree, and replay lands inside that window. ## Decision Boundary The precise boundary is between two resume policies, and choosing wrong is the entire failure: - **Replay-as-redelivery (correct):** On resume, replayed events are fed through a *deduplicating* intake keyed on event ID. Any event whose ID is ≤ the highest ID already *semantically applied* (tracked in the durable action ledger, not just the transport cursor) is dropped before it reaches the reasoning loop. The ledger records `(event_id, request_id, effect_committed)` tuples. Re-issuing a request is permitted only if the ledger shows the request was sent but no response event for it was ever applied — and even then, only if the tool is declared idempotent or carries an idempotency key. - **Replay-as-retry (incorrect, and what the observed client did):** On resume, the client sees a response with no matching in-flight request (because its in-flight table was lost), concludes the request must have failed, and resends. This is the boundary violation: it uses transport replay as a signal about *request* fate, when replay only carries information about *response* delivery. The decision the engineer must make explicit: **does a replayed response event prove the request was never executed, or prove only that its response was never durably received?** It proves only the latter. Any code path that treats replay as evidence of non-execution is on the wrong side of the boundary. ## Operational Effect Downstream of a double-apply, the effects compound in ways that look like reasoning failures rather than transport failures, which is why they are misdiagnosed: - The agent's context now contains a *second* successful tool result for a call it believes happened once. Its belief state is internally consistent but factually wrong, so it will not self-correct — there is no contradiction in its context to detect. - Non-idempotent side effects accumulate silently (duplicate line, duplicate commit, duplicate charge). The corruption is in the environment, not the transcript, so replaying the transcript for audit reproduces the *decision* faithfully and hides the *divergence*. - If the server's event buffer is bounded (common: keep last N events), a long outage can push the needed event out of the buffer, so `Last-Event-ID` returns a gap rather than a replay. The client must then treat the session as **unresumable** and fail closed — re-deriving state from the environment, not from a partial event log. A client that silently resumes across a gap is worse than one that errors: it has lost the continuity invariant entirely while appearing healthy. The guardrail is a single durable record that fuses the stream cursor and the action ledger, plus an explicit idempotency contract per tool, plus a hard fail-closed on buffer-gap. The code below encodes the reconciliation and raises on the two boundary violations: ledger/cursor divergence and unresumable gap. ```python from __future__ import annotations import json from dataclasses import dataclass, field from typing import Iterable class StreamResumptionViolation(RuntimeError): """Raised when an MCP streamable-session resume would violate the action-ledger / event-cursor continuity invariant.""" @dataclass class ActionLedger: """Durable record fusing transport cursor and semantic action state. Invariant: `applied_event_id` and `effects` are committed in the SAME durable write. A replayed event with id <= applied_event_id is dropped before it can reach the reasoning loop. """ applied_event_id: int = 0 # request_id -> effect_committed inflight: dict[str, bool] = field(default_factory=dict) # event_id -> request_id that produced it event_to_request: dict[int, str] = field(default_factory=dict) # tools declared safe to re-issue on ambiguous resume idempotent_tools: set[str] = field(default_factory=lambda: {"fetch_url"}) def commit(self, event_id: int, request_id: str | None) -> None: # Single atomic step: advance cursor AND record effect together. self.applied_event_id = event_id if request_id is not None: self.event_to_request[event_id] = request_id self.inflight[request_id] = True def already_applied(self, event_id: int) -> bool: return event_id <= self.applied_event_id @dataclass class ReplayedEvent: event_id: int request_id: str | None tool_name: str | None def reconcile_resume( ledger: ActionLedger, replayed: Iterable[ReplayedEvent], server_buffer_min_id: int, requested_last_event_id: int, ) -> list[ReplayedEvent]: """Return only events that are genuinely new to the semantic layer. Raises on the two boundary conditions: 1. Server could not honor Last-Event-ID (gap -> unresumable session). 2. A replayed response refers to a request the ledger never sent (cursor/ledger divergence -> cannot safely decide re-issue). """ replayed = list(replayed) # Guard 1: buffer gap means stream continuity is lost. Fail closed; # do NOT pretend to resume from a partial log. if requested_last_event_id + 1 < server_buffer_min_id: raise StreamResumptionViolation( f"unresumable session: requested Last-Event-ID={requested_last_event_id} " f"but server buffer starts at {server_buffer_min_id}; " f"events in [{requested_last_event_id + 1}, {server_buffer_min_id - 1}] " f"are permanently lost. Re-derive state from environment." ) fresh: list[ReplayedEvent] = [] for ev in replayed: if ledger.already_applied(ev.event_id): # Stream replay of an already-applied effect: drop it. continue if ev.request_id is not None and ev.request_id not in ledger.inflight: # A response for a request we have no record of sending. # We cannot tell "never sent" from "sent, ledger lost". # Re-issuing here is the double-apply bug. raise StreamResumptionViolation( f"replayed event {ev.event_id} carries response for unknown " f"request {ev.request_id!r}; ledger/cursor diverged. " f"Refusing to re-issue. Treat as ambiguous and reconcile " f"against tool idempotency contract before any resend." ) fresh.append(ev) return fresh def resume_and_maybe_reissue( ledger: ActionLedger, replayed: Iterable[ReplayedEvent], server_buffer_min_id: int, requested_last_event_id: int, pending_tool: str, ) -> list[str]: """Drive resume; only re-issue when provably safe.""" fresh = reconcile_resume( ledger, replayed, server_buffer_min_id, requested_last_event_id ) to_reissue: list[str] = [] for ev in fresh: if ev.request_id is not None and ev.tool_name not in ledger.idempotent_tools: # Response arrived for a non-idempotent tool with no committed # effect: the effect state is ambiguous. Do not resend. raise StreamResumptionViolation( f"ambiguous effect for non-idempotent tool {ev.tool_name!r} " f"on request {ev.request_id!r}; manual reconciliation required" ) ledger.commit(ev.event_id, ev.request_id) to_reissue.append(ev.request_id) if ev.request_id else None return to_reissue ```