# Where must an instance treat MCP resumable-stream replay as authoritative over its own cached tool-result state **Date of Record:** 2026 November 22 **Scope:** Applies to MCP clients using the HTTP-native (Streamable HTTP) transport with `Last-Event-ID`-based resumption against a remote tool server, where the client caches tool-call results across a reconnection. Does not apply to stdio transport, to servers that disable resumability, or to stateless one-shot `POST`-only interactions with no SSE stream. ## Core Distinction There are two distinct notions of "the result of tool call `T`" that a resumable MCP session can carry, and they are not the same object: 1. **The client's cached result** — what the agent's executor recorded when it first saw a `tools/call` response, bound to the request `id`. 2. **The server's replayed result** — what the server re-emits on stream resumption, keyed by SSE event `id`, after the client reconnects with `Last-Event-ID`. The failure lives in the gap between these. The MCP Streamable HTTP transport lets a server assign monotonic event IDs to every SSE message and replay *all events after a given ID* when a client reconnects. Crucially, replay is keyed by **event ID**, not by **JSON-RPC request ID**. A client that assumes "I already have the response for `id=7`, so I can drop any replayed message for `id=7`" is applying the wrong deduplication key. The server may replay an event that carries a *different* result for the same request ID than the one the client cached — because the original attempt was retried server-side, because a long-running tool emitted progress and then a terminal result the client never received, or because the client's cache entry was written from a *partial* stream that ended in a transport error rather than a JSON-RPC terminal frame. The invariant that must hold: **for any event ID greater than the last event ID the client has durably acknowledged, the replayed payload is authoritative and must overwrite, not merge with, any cached state for the referenced request ID.** ## What Was Observed A remote agent invoked a tool server over Streamable HTTP. The server streamed a `tools/call` for a long-running operation (a code-execution sandbox returning incremental `notifications/progress` frames followed by a terminal `result`). The sequence that produced the divergence: 1. Client sends `POST /mcp` with `tools/call`, `id=7`. Server responds `200` with `Content-Type: text/event-stream` and begins streaming. Event IDs `1001` (progress 10%), `1002` (progress 40%), `1003` (progress 90%). 2. The TCP connection is severed by an intermediate proxy idle-timeout at 90%. The client's SSE reader raises a read error **after** it has already dispatched events `1001`–`1003` to the executor. The executor, treating progress frames as non-terminal, holds `id=7` in a "pending" state but has *also* optimistically written a partial artifact to its scratch state from the 90% frame. 3. Client reconnects: `GET /mcp` with `Last-Event-ID: 1003`. Server replays from `1004` onward: `1004` (progress 99%), `1005` (terminal `result` with the *final, corrected* artifact — the 90% frame's artifact was a provisional snapshot the tool later overwrote). 4. **The failure:** the client's executor, on receiving `1005`, matched it to `id=7`, saw that `id=7` was already present in its pending map (from the aborted attempt), and applied a *merge* policy: "terminal result supersedes pending, but preserve scratch artifacts written during the attempt." The stale 90%-frame artifact survived alongside the authoritative final artifact. The agent's subsequent reasoning step read both, treated them as two versions of the same output, and produced a diff against itself — silently corrupting downstream tool calls. The non-obvious part: the client did everything "right" by ordinary reconnection logic. It resumed with the correct `Last-Event-ID`. It received the authoritative terminal frame. It failed only because its cache-merge policy treated a *previously-seen* request ID as ground truth and a *replayed* event as an incremental update. The event ID ordering (`1005 > 1003`) was the only signal that the replayed payload should have unconditionally won. A second, sharper variant: if the server had, between the disconnect and the reconnect, retried the tool call internally (allowed — the server owns execution), the terminal frame for `id=7` on replay could carry a *different* result than any the client ever saw, with no progress frames in between. A client that deduplicates by request ID would drop it entirely, leaving the agent to reason over a result that the server had already superseded. ## Condition of Validity The "replay is authoritative" invariant is valid precisely when all of the following hold: - The transport is Streamable HTTP with SSE and the server advertises resumability (assigns event IDs). - The client reconnects with a `Last-Event-ID` that the server recognizes and can replay from. - The replayed stream is **monotonic in event ID** and the client has not already processed an event ID ≥ the first replayed ID. It is **invalid** (and the client must fall back to a full re-request, not a merge) when: - The server cannot honor the `Last-Event-ID` (returns a fresh stream from a new ID space, or `400`). In this case the client has no ordering guarantee and must discard all cached state for any request ID whose terminal frame it did not *durably* observe, then re-issue the `tools/call` with a new request ID. - The client's last durable acknowledgment is *ahead* of the server's replay point (server restarted, event ID space reset). Replayed IDs would then be lower than cached IDs; the client must detect the non-monotonic ID and treat the entire session as reset. - The tool is declared non-idempotent **and** the server does not deduplicate by request ID. Here replay may re-execute side effects; the client must not trust the replayed result as a *continuation* but must treat it as a fresh outcome and reconcile explicitly. ## Decision Boundary The decision the client must make on every inbound SSE event during resumption is a three-way branch keyed on **event ID relative to the durable high-water mark**, not on request ID presence: - **Event ID ≤ high-water mark:** duplicate, drop. (Only reachable if the server over-replays; safe to ignore.) - **Event ID > high-water mark AND references a request ID with no cached terminal frame:** accept, this is the authoritative continuation. - **Event ID > high-water mark AND references a request ID with a cached terminal frame:** **the replayed event wins; evict the cached terminal frame and all scratch state derived from the aborted attempt before applying the replayed payload.** This is the boundary most implementations get wrong — they invert it, letting the cache win because "we already have an answer." The boundary is sharp because the high-water mark is the *only* monotonic quantity in the system. Request IDs are chosen by the client and reused across retries; event IDs are chosen by the server and are the server's statement about causal order. When they conflict, the server's ordering is the ground truth for what the agent should believe. ## Operational Effect Agents that violate this boundary exhibit a characteristic corruption signature: **self-contradicting tool outputs within a single reasoning turn**, where the same logical artifact appears in two versions and the model reasons over both. This is not a crash — it is silent. The agent completes, emits a plausible final answer, and the divergence only surfaces when a downstream verifier replays the tool call and gets a single authoritative result that matches neither cached version. The guardrail is a **resumable-session state machine** with an explicit high-water mark and an eviction-on-replay rule, plus a hard failure when the server's replay is non-monotonic (a signal that the session identity has been lost and the agent is reasoning over a phantom continuity). The code below encodes that machine and raises on the two unrecoverable conditions: non-monotonic replay (session reset) and replay of a terminal frame for a request the client never durably acknowledged as pending (orphaned continuation). ```python from dataclasses import dataclass, field from typing import Dict, Optional class ResumableSessionViolation(RuntimeError): """Raised when an MCP resumable SSE replay cannot be safely reconciled with the client's cached tool-call state.""" pass @dataclass class CachedCall: request_id: int terminal: bool = False payload: Optional[dict] = None scratch_artifacts: list = field(default_factory=list) class ResumableSession: """Tracks the durable high-water mark of SSE event IDs and reconciles replayed events against cached tool-call results. Invariant: any event with id > high_water_mark is authoritative and evicts cached terminal state for the referenced request_id. """ def __init__(self) -> None: self.high_water_mark: int = -1 self.calls: Dict[int, CachedCall] = {} def observe(self, event_id: int, request_id: int, is_terminal: bool, payload: Optional[dict] = None) -> None: # Non-monotonic replay: server reset its event ID space or we are # replaying from a stale checkpoint. Session identity is lost. if event_id <= self.high_water_mark: # Duplicate within the same ID space is a benign drop ONLY if # the ID equals the mark; anything strictly below means the # server rewound, which invalidates the whole cache. if event_id < self.high_water_mark: raise ResumableSessionViolation( f"non-monotonic replay: event {event_id} < " f"high-water mark {self.high_water_mark}; session reset" ) return # exact duplicate, drop existing = self.calls.get(request_id) if existing is None: # Continuation of a request we never saw begin. Cannot safely # bind it to prior scratch state. if not is_terminal: self.calls[request_id] = CachedCall(request_id=request_id) else: raise ResumableSessionViolation( f"orphaned terminal replay for request {request_id} " f"at event {event_id}: no pending call to continue" ) else: # THE BOUNDARY: replayed event past the mark is authoritative. # Evict any cached terminal frame and scratch derived from an # aborted attempt before applying the replayed payload. if existing.terminal: existing.terminal = False existing.payload = None existing.scratch_artifacts.clear() if is_terminal: self.calls[request_id].terminal = True self.calls[request_id].payload = payload self.high_water_mark = event_id def last_event_id_header(self) -> str: if self.high_water_mark < 0: raise ResumableSessionViolation("no events observed; cannot resume") return str(self.high_water_mark) def resume_stream(session: ResumableSession, replayed_events: list) -> None: """Apply a server replay. Raises if the replay cannot be trusted as a monotonic continuation of the durable high-water mark.""" if not replayed_events: return first_id = replayed_events[0][0] if first_id <= session.high_water_mark and first_id != session.high_water_mark + 1: # Server did not resume from our mark; ordering guarantee is void. raise ResumableSessionViolation( f"replay starts at {first_id}, expected > {session.high_water_mark}" ) for event_id, request_id, is_terminal, payload in replayed_events: session.observe(event_id, request_id, is_terminal, payload) ```