# Which invariants prevent MCP stream resumption from silently replaying a divergent tool-call prefix **Date of Record:** 2026 December 4 **Scope:** Applies to MCP servers exposed over HTTP-native transport (SSE-framed `text/event-stream` responses with `Last-Event-ID` resumption, per the Streamable HTTP transport) where a client agent may reconnect mid-turn and request continuation of a partially consumed event stream. Does not apply to stdio transport, nor to stateless request/response MCP endpoints that never emit resumable streams. ## Core Distinction The failure is not "the connection dropped." Connection loss is expected and recoverable. The failure is that **resumption is treated as a byte-offset replay problem when it is actually a semantic-continuity problem**. An SSE `Last-Event-ID` tells the server *which event the client last saw*, but it says nothing about *which side effects the client already committed based on that event*. When an MCP server serves `tools/call` results on a resumable stream, the event ID is a transport cursor, not an idempotency token. The two are conflated the moment the server reconstructs state by replaying from the cursor. The invariant that must hold: **for any resumed stream, the set of tool-call results the client observes after resume must be exactly the suffix of the original logical turn that the client has not yet acted upon — and no result may be delivered twice with a different payload.** Event-ID monotonicity alone does not guarantee this, because the server's event buffer and the client's committed-action frontier advance independently. ## What Was Observed A client agent issued a `tools/call` for a paginated retrieval tool. The server streamed intermediate progress events (`event: progress`, `id: 41..47`) followed by the terminal result (`event: result`, `id: 48`). The client's SSE reader consumed through `id: 45`, dispatched the tool-call side effect (a downstream write keyed on the partial payload), then the TCP connection reset before `id: 46` arrived. The client reconnected with `Last-Event-ID: 45`. The server, holding a bounded ring buffer of 100 events, replayed from `id: 46`. This is the *correct* transport behavior. But between the disconnect and the reconnect, the server had **re-executed the tool** because the original handler had not been marked complete — the ring buffer retained the *old* events 46–48, but the handler's internal counter had advanced and the re-execution produced *new* events 49–51 with a payload that differed (the paginated source had shifted). The client now received `id: 46, 47, 48` (stale, from buffer) *followed by* `id: 49, 50, 51` (fresh, from re-execution). Two terminal `result` events with divergent payloads for the same logical `tools/call`. The agent's reasoning loop, seeing two results, treated the second as a correction and overwrote state — but the first had already been committed downstream. The trace shape: 1. `id: 45` delivered → client commits side effect S1. 2. Disconnect at `id: 46`. 3. Server handler re-enters, re-executes tool, emits `id: 49..51` into the same buffer namespace. 4. Client resumes at `Last-Event-ID: 45`. 5. Server replays buffer: `46, 47, 48` (stale) then live `49, 50, 51` (fresh). 6. Client receives two `result` events for one call. Divergence undetected because event IDs are monotonic and the client has no call-level identity to dedupe against. ## Condition of Validity Resumption is only safe when **all three** of the following hold simultaneously: - **Call-scoped idempotency key.** Every `tools/call` carries a client-generated `call_id` that is stable across reconnects and is echoed on every event belonging to that call. Without it, the client cannot distinguish "suffix of the same call" from "a new call's events." - **Server-side execution memoization.** The server must persist the *result* of a completed tool execution keyed by `call_id`, and on resume serve the memoized result rather than re-executing. Re-execution is permitted only if the tool is declared idempotent *and* the client's committed frontier is known to be behind the re-execution point. - **Frontier-explicit resumption.** The client's `Last-Event-ID` must be accompanied by the highest `call_id`/sequence it has *committed*, not merely *received*. Receipt ≠ commitment; the gap between them is where duplicate side effects live. If any one is absent, the resume path is unsound and must fail closed rather than replay. ## Decision Boundary The boundary between safe replay and unsafe replay is drawn at the **commit frontier**, not the **delivery frontier**: - If `Last-Event-ID` ≥ the last event of a *completed and memoized* call → safe to replay suffix from memoized buffer; no re-execution. - If `Last-Event-ID` falls *inside* an in-flight call whose handler has since re-executed → **unsafe**; the server must reject resumption with a session-invalid signal and force the client to re-issue the `tools/call` under a new `call_id`, discarding the partial result. - If the ring buffer has evicted events beyond `Last-Event-ID` → resumption is impossible; the server must not silently jump forward, because the client's committed frontier may be arbitrarily behind the eviction point. The non-obvious part: a server that "helpfully" replays what it still has in the buffer, when the buffer has been partially evicted *and* the handler re-executed, produces a stream that is monotonic in ID but semantically forked. Monotonicity is a necessary but grossly insufficient invariant. ## Operational Effect Agents that treat `Last-Event-ID` resumption as transparent will, under this condition, commit duplicate or contradictory side effects and — worse — *believe* the reconciliation succeeded because the second result arrived later and looked authoritative. The reasoning loop has no signal that the two results belong to the same call; it sees a sequence, and sequences are assumed coherent. The guardrail is to make the fork *loud*: on any resume where the server cannot prove a contiguous, non-re-executed suffix exists for the client's committed frontier, it must emit a terminal `session.invalidated` event and close the stream. The client then re-issues under a fresh `call_id`, and the old partial result is tombstoned. This converts a silent divergence into an explicit, recoverable retry — at the cost of discarding partial work, which is the correct trade. ```python class StreamResumeDivergence(RuntimeError): """Raised when a resumed MCP stream cannot prove suffix continuity.""" pass class EventBuffer: def __init__(self, capacity: int = 100): self.capacity = capacity self.events: dict[int, dict] = {} self.min_id: int | None = None self.max_id: int | None = None self.re_executed_calls: set[str] = set() def append(self, event_id: int, call_id: str, payload: dict) -> None: self.events[event_id] = {"call_id": call_id, "payload": payload} self.max_id = event_id if self.max_id is None else max(self.max_id, event_id) if self.min_id is None: self.min_id = event_id while len(self.events) > self.capacity: oldest = min(self.events) del self.events[oldest] self.min_id = oldest + 1 def resume_stream( buf: EventBuffer, last_event_id: int, committed_call_id: str, handler_re_executed: bool, ) -> list[dict]: """ Reconstruct the suffix a client may safely consume after reconnect. Fails closed on any condition that would fork the logical turn. """ if buf.min_id is None or buf.max_id is None: raise StreamResumeDivergence("empty buffer; cannot resume") # Eviction check: if the client's cursor predates what we still hold, # we cannot know what it missed. Do not silently jump forward. if last_event_id < buf.min_id - 1: raise StreamResumeDivergence( f"cursor {last_event_id} predates buffer floor {buf.min_id}; " "missing events are unrecoverable" ) # Re-execution check: if the handler re-ran, buffered events and live # events may describe the same call with divergent payloads. if handler_re_executed and committed_call_id in buf.re_executed_calls: raise StreamResumeDivergence( f"call {committed_call_id} re-executed after cursor {last_event_id}; " "replay would fork the turn" ) suffix = [ {"id": eid, **buf.events[eid]} for eid in sorted(buf.events) if eid > last_event_id ] # Contiguity check: a gap means the suffix is not a true continuation. expected = last_event_id + 1 for ev in suffix: if ev["id"] != expected: raise StreamResumeDivergence( f"non-contiguous suffix: expected {expected}, got {ev['id']}" ) expected += 1 # Single-result invariant: at most one terminal result per call in suffix. terminal = [ev for ev in suffix if ev["payload"].get("kind") == "result"] seen: set[str] = set() for ev in terminal: cid = ev["call_id"] if cid in seen: raise StreamResumeDivergence( f"duplicate terminal result for call {cid} in suffix" ) seen.add(cid) return suffix ```