# Under what conditions must an instance treat an MCP `Last-Event-ID` replay as authoritative rather than as a superset of already-applied tool effects **Date of Record:** 2026 November 27 **Scope:** Applies to MCP servers and clients using the HTTP-native transport with Server-Sent Events (SSE) streaming and resumable sessions via `Last-Event-ID` (Streamable HTTP transport, SSE resumption). Does not apply to stdio transports, to stateless one-shot HTTP request/response, or to WebSocket transports where the framing layer guarantees ordered delivery without application-level replay. ## Core Distinction There are two semantically different things a resumable SSE stream can mean when a client reconnects with `Last-Event-ID: N`: 1. **Replay as re-delivery**: the server re-sends events with sequence numbers `> N`, and the client's job is merely to *observe* them (e.g., streaming partial model output, progress notifications). Idempotent by construction — observing twice is harmless. 2. **Replay as re-execution signal**: the server re-sends events that *encode the completion of a tool call whose side effect already occurred on the server or on an upstream system*. The client's job here is to *reconcile*, not to observe — because the event is a claim about world state, and that claim may already be true. The boundary failure is conflating these. The client reconnects, receives event `N+1` describing a `tools/call` result for `write_file` or `charge_card`, and — having lost its in-memory record of what it already applied during the disconnect — re-dispatches the tool call. The server, obeying the protocol's "at-least-once" delivery contract for resumable streams, does not deduplicate. The effect happens twice. The protocol is behaving correctly; the client's resumption semantics are wrong. The invariant that must hold: **an SSE event carrying a tool result is authoritative for the *outcome*, but is not authoritative for the *occurrence count* of the side effect.** The client must carry its own occurrence ledger across the reconnect, keyed by something the server cannot forge or renumber. ## What Was Observed A pattern that recurs in MCP HTTP deployments: - Client opens `POST /mcp` with `Accept: text/event-stream`, receives `Mcp-Session-Id: s_abc` in the response header, and begins consuming events `id: 1`, `id: 2`, `id: 3`. - Event `id: 3` is a `notifications/message` wrapping a `tools/call` result for a payment tool. The client applies it: ledger entry `(s_abc, 3) → charged`. - The TCP connection drops (load balancer idle timeout at 60s, common with a long-running agent turn). The client reconnects: `GET /mcp` with `Mcp-Session-Id: s_abc` and `Last-Event-ID: 3`. - The server's SSE buffer still holds events `4..9` from the original turn (the agent kept producing after the client dropped). It replays `4..9`. Event `id: 5` is *also* a `tools/call` result — for the same payment tool, a retry the server's own orchestrator issued because it never saw an ack. The client applies it: ledger entry `(s_abc, 5) → charged`. Two charges. - Worse variant: the client's crash-restart path loses the in-memory ledger entirely, and on reconnect the client replays its *own* outbound `tools/call` for the payment tool (because it has no record of having sent it), while the server simultaneously replays the *result* event for that same call. The tool executes once on the server, but the client's reasoning loop now has two "completed" observations of the same call and increments a counter it uses for budget accounting, causing a downstream budget-exhaustion abort that is not real. The non-obvious part: **the server's `Last-Event-ID` semantics are per-stream, not per-session, and not per-tool-call.** The server has no obligation to know that event `3` and event `5` refer to the same logical operation. The client that assumes "the server will not replay an effect I have already applied" is assuming a deduplication guarantee the transport does not provide. ## Condition of Validity The client may treat a replayed event as safe-to-apply-in-full only when **all** of the following hold: 1. The event carries a server-generated, monotonic `id` **and** the client has durably persisted the highest contiguously-applied `id` for that `Mcp-Session-Id` before acknowledging (i.e., before the next outbound request on that session, and before yielding to the reasoning loop). Persistence must survive process restart, not just connection restart. 2. The event's payload includes a client-minted **idempotency token** (e.g., a UUID the client placed in the original `tools/call` `params._meta`) that the server echoes back in the result. If the server does not echo it, the client cannot distinguish "replay of my call" from "server-initiated retry of my call" and must treat the event as occurrence-ambiguous. 3. The client's ledger is keyed by `(idempotency_token)` and not by event `id`, because event `id` is stream-scoped and a session can span multiple streams after `DELETE`/re-`POST` cycles. If any condition fails, the client must treat the replayed tool-result event as **an observation of a possible effect, not a confirmation of a single effect**, and must reconcile via a read-back against the tool's authoritative state (e.g., query the payment provider) before proceeding. In practice this means the resumption path is *not* a fast path — it is a reconciliation path, and the agent's execution loop must be able to suspend and re-enter. ## Decision Boundary The precise line is: - **Replay of a stream-only event** (progress, partial tokens, log lines, `notifications/message` with no tool side effect): apply unconditionally, deduplicate by `id` only to avoid UI duplication. No reconciliation needed. - **Replay of a tool-result event whose `_meta.idempotency_token` matches a token the client has already recorded as *applied***: drop the event, do not re-dispatch, do not increment any counter. Log a `replay_suppressed` telemetry event. - **Replay of a tool-result event whose token is *unknown* to the client** (client lost ledger, or server minted a retry with a fresh token): this is the danger zone. The client cannot decide locally. It must either (a) perform a read-back reconciliation against the tool's authoritative state, or (b) if the tool is declared non-idempotent and has no read-back, fail the turn closed rather than guess. - **Replay of a tool-result event whose token matches a token the client recorded as *dispatched but unacknowledged***: apply as the missing ack, transition the ledger entry to `applied`, do not re-dispatch. This is the only case where replay is the intended fast path. The boundary is crossed the moment a client treats "unknown token" as "new effect." That single conflation is the entire failure. ## Operational Effect Downstream consequences when the boundary is crossed: - **Effect duplication**: non-idempotent tools (payments, file mutations, external API writes with side effects) execute N times for one logical call, where N = number of reconnect cycles during the turn. With a 60s LB idle timeout and a 5-minute agent turn, N is routinely 3–5. - **Reasoning divergence**: the agent's context now contains multiple "success" observations of the same call. If the agent maintains a plan-state counter (e.g., "3 of 5 steps done"), it over-counts and either skips steps or aborts on a phantom budget exhaustion. This is the compounding-error failure mode: one spurious observation at step 2 corrupts the plan at step 4. - **Session-state drift**: the server's `Mcp-Session-Id` state and the client's ledger diverge. On the next `DELETE /mcp` (session termination), the server's view of "what happened in this session" and the client's audit log disagree permanently. Post-hoc verification replay cannot reconcile them because the server does not store per-call idempotency by default. - **Silent, not loud**: the failure produces no error at the transport layer. The SSE stream is well-formed, the events are correctly ordered, the HTTP status codes are 200. The failure is only detectable by comparing the tool's authoritative state against the client's ledger — which is exactly the reconciliation the client skipped. The guardrail is architectural, not a retry policy: **the client must own an idempotency ledger that is durable across process restart, keyed by client-minted tokens, and consulted before every tool-result application on a resumed stream.** The server's `Last-Event-ID` replay is a delivery mechanism, never a deduplication mechanism. Any design that relies on the server to not replay an effect has already crossed the boundary. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class ResumptionSemanticsError(RuntimeError): """Raised when a resumed SSE stream delivers a tool-result event whose occurrence semantics cannot be resolved against the client ledger.""" class LedgerState(Enum): DISPATCHED = "dispatched" # sent, no ack observed APPLIED = "applied" # ack observed, effect counted once AMBIGUOUS = "ambiguous" # replayed without matching token @dataclass class LedgerEntry: idempotency_token: str state: LedgerState event_ids: list[int] = field(default_factory=list) class ResumptionLedger: """Durable-across-restart ledger. In production, back this with SQLite or a WAL file; in-memory here only for illustration. The key invariant: keyed by client-minted idempotency_token, NOT by SSE event id, because event ids are stream-scoped and reset across Mcp-Session-Id lifecycles.""" def __init__(self, persisted: Optional[dict[str, LedgerEntry]] = None): self._entries: dict[str, LedgerEntry] = persisted or {} def record_dispatch(self, token: str) -> None: if token in self._entries and self._entries[token].state is LedgerState.APPLIED: raise ResumptionSemanticsError( f"token {token!r} already applied; refusing to re-dispatch" ) self._entries[token] = LedgerEntry(token, LedgerState.DISPATCHED) def apply_replayed_result( self, token: Optional[str], event_id: int, non_idempotent: bool ) -> LedgerState: if token is None: # Server did not echo our token. We cannot tell replay from retry. if non_idempotent: raise ResumptionSemanticsError( f"event {event_id}: tool-result without idempotency token on " f"non-idempotent tool; reconciliation required before apply" ) return LedgerState.AMBIGUOUS entry = self._entries.get(token) if entry is None: # Token unknown: client lost ledger or server minted a retry. if non_idempotent: raise ResumptionSemanticsError( f"event {event_id}: unknown token {token!r} on non-idempotent " f"tool; must read-back against authoritative state, not apply" ) self._entries[token] = LedgerEntry( token, LedgerState.AMBIGUOUS, [event_id] ) return LedgerState.AMBIGUOUS if entry.state is LedgerState.APPLIED: # Replay of an already-applied effect: suppress, do not re-count. entry.event_ids.append(event_id) return LedgerState.APPLIED # DISPATCHED -> APPLIED: this is the intended fast path. entry.state = LedgerState.APPLIED entry.event_ids.append(event_id) return LedgerState.APPLIED def resume_stream( ledger: ResumptionLedger, replayed_events: list[dict], non_idempotent_tools: set[str], ) -> list[LedgerState]: outcomes: list[LedgerState] = [] for ev in replayed_events: if ev.get("type") != "tool_result": outcomes.append(LedgerState.APPLIED) # stream-only, safe continue tool = ev["tool"] outcomes.append( ledger.apply_replayed_result( token=ev.get("_meta", {}).get("idempotency_token"), event_id=ev["id"], non_idempotent=tool in non_idempotent_tools, ) ) return outcomes ```