# Under what conditions must an instance treat MCP resumable-stream `Last-Event-ID` replay as a session-continuity hazard rather than a recovery mechanism **Date of Record:** 2026 November 25 **Scope:** Applies to MCP servers exposing streamable HTTP transport with SSE-based resumable streaming (`Last-Event-ID` replay) where a single logical MCP session spans multiple tool calls whose results mutate server-side state. Does not apply to stateless request/response MCP transports or to SSE streams carrying only idempotent, side-effect-free notifications. ## Core Distinction The resumable-stream contract in MCP's streamable HTTP transport is borrowed from SSE: a client that loses its connection reconnects with `Last-Event-ID: ` and the server replays events `n+1` onward. This is a *transport-level* invariant — it guarantees the byte stream resumes without a gap. It is **not** a *session-level* invariant. The distinction that matters operationally: replay reconstructs the event sequence, but it does not reconstruct the *causal state* the client's LLM already acted on. An agent that consumed events up to `n`, took an irreversible action (wrote a file, called a downstream tool, committed a plan step) based on event `n`, then reconnected and received a replay starting at `n+1`, is fine. An agent that consumed events up to `n`, *partially* acted, crashed before recording that it acted, and reconnects to a server that replays from `n+1` — or worse, from `n` because the server's cursor is coarser than the client's — is now in a state where the LLM's belief about the world and the server's replayed facts have silently diverged. The transport says "continuous." The session says "forked." The non-obvious part: the hazard is not the replay itself. It is the *granularity mismatch* between the server's event cursor and the client's action cursor. SSE event IDs are assigned by the server at emission time. The client's action cursor advances at LLM-decision time. These two clocks are not synchronized, and nothing in the MCP spec requires them to be. A server may emit events `n+1`, `n+2`, `n+3` in one batch before the client's LLM has finished reasoning about event `n`. If the connection drops after the server assigned IDs but before the client durably recorded which events it had *acted upon*, replay will re-deliver events the LLM has already reasoned over — and the LLM, lacking an action-cursor, will reason over them again, potentially taking a second irreversible action. ## What Was Observed A single-agent coding workflow over streamable HTTP MCP. The server emits `notifications/progress` and tool-result events with monotonically increasing SSE IDs. The agent's client library persists `Last-Event-ID` on every received event (standard SSE client behavior). The LLM consumes events into its context and, on each tool result, decides the next tool call. Trace of the failure: 1. Server emits event `id=41` (`tool_result` for `write_file("/src/a.py")`, success). Client receives, persists `Last-Event-ID: 41`, appends to LLM context. 2. LLM reasons over event 41 and issues `tools/call` for `run_tests`. The call is *in flight* — the client has sent the request but not yet received the response, and critically has *not* persisted any record that it issued this call against event 41. 3. Network drops. The in-flight `tools/call` is lost at the transport layer; the server may or may not have executed it (the server executed it — `run_tests` ran and mutated a cache directory). 4. Client reconnects with `Last-Event-ID: 41`. Server replays from `id=42`. Event 42 is the `tools/call` *response* for `run_tests`, which the client never saw and for which it has no matching request record. 5. The LLM now receives an unsolicited tool result for a call it does not believe it made. Depending on the client's request/response correlation logic, this is either (a) dropped as an orphan, leaving the LLM believing `run_tests` never ran, or (b) injected into context as a free-floating result, causing the LLM to re-issue `run_tests` — a second mutation of the cache directory. 6. Separately, the server's session state now records `run_tests` as executed once, while the LLM's episodic memory records it as never executed. On the next `write_file` to the same path, the LLM's staleness assumptions are wrong. The invariant that broke: **`Last-Event-ID` replay guarantees event-stream continuity, not action-stream continuity.** The client persisted the transport cursor but had no durable action cursor. The two are not the same number and cannot be derived from each other. ## Condition of Validity Resumable replay is safe as a session-continuity mechanism only when all of the following hold: - **Idempotent event semantics.** Every replayed event is either a pure notification (no side effect when re-consumed by the LLM) or carries an idempotency key the LLM/client deduplicates against. Progress notifications qualify; tool results do not, because a tool result can trigger a fresh irreversible tool call. - **Action cursor ≥ transport cursor, durably.** The client must persist, atomically with issuing any `tools/call`, the transport `Last-Event-ID` at the moment of issue. On reconnect, it requests replay from `min(persisted_action_cursor, persisted_transport_cursor)`, not from the transport cursor alone. If action cursor > transport cursor, the client must *not* replay past the action cursor without first reconciling in-flight calls. - **In-flight call reconciliation before replay consumption.** Before feeding replayed events to the LLM, the client must resolve every `tools/call` that was in flight at disconnect: query the server for its status by a client-generated request ID, and synthesize a definitive result (executed / not executed / unknown) into the LLM context. Replay is consumed only after this reconciliation, and only for events not covered by the reconciliation. - **Server-side event IDs are per-session and monotonic across reconnects.** If the server resets or reuses IDs on reconnect (some implementations restart the counter), replay is meaningless and the client must fall back to full session re-establishment. When any of these is absent — and in the common case of a stock SSE client plus a naive MCP server, all four are absent — replay is a hazard. The failure is silent: no error is raised, the stream resumes, the agent continues, and the corruption surfaces later as a stale-state bug ("the file I thought I wrote isn't there") or a double-mutation bug ("the test ran twice and the cache is inconsistent"). ## Decision Boundary The boundary is drawn at the point where the client must choose between replay and re-establishment: - **Replay** (send `Last-Event-ID`) is correct when the last event the client *acted upon* is known and durable, and the gap contains only notifications or idempotent results. This is the case for long-running progress streams where the LLM is a passive observer. - **Re-establishment** (new session, full state re-sync) is required when the gap may contain tool results for calls the client cannot prove it did not act upon, or when the server cannot answer "did you execute request R?" definitively. Re-establishment costs a cold-start re-sync (the agent loses its episodic context for the session and must rebuild from server-side state), but it is the only correct choice when action-cursor durability is not guaranteed. - **The forbidden middle** — replaying from the transport cursor while the action cursor is unknown — is the exact condition that produces the fork. It is forbidden not because replay is wrong, but because the client is asserting a continuity it cannot prove. The decision is per-reconnect, not per-session. A single session may correctly replay across three reconnects (progress-only gaps) and must re-establish on the fourth (a gap spanning an in-flight tool call). The client must evaluate the gap contents, not the session's history. ## Operational Effect Architecturally, this forces a **dual-cursor model** into any MCP client that drives an agent: a transport cursor (SSE `Last-Event-ID`, cheap, persisted on every event) and an action cursor (persisted atomically with tool-call issuance, expensive, must survive process crash). The action cursor is the authoritative one for continuity decisions; the transport cursor is an optimization that lets the client avoid re-fetching events it has provably already processed. The observable effect on agent behavior: without the dual cursor, agents exhibit *phantom completion* — the LLM's context asserts a tool succeeded (from a pre-crash event) while server state says it never ran, or the reverse (double execution). These manifest as non-deterministic test failures, "file not found" errors on paths the agent believes it created, and duplicate side effects in downstream systems. With the dual cursor and in-flight reconciliation, the agent's post-reconnect context is *reconstructed from server truth*, not from replayed events, and the replay is used only to fill notification gaps. The cost is one extra round-trip per reconnect (the in-flight status query) and the requirement that the server expose a request-status endpoint keyed by client-generated ID — which the MCP spec permits but does not mandate. That server-side endpoint is the load-bearing element: without it, the client cannot distinguish "not executed" from "executed, result lost," and must conservatively re-establish the session. ## Code ```python class SessionContinuityForkError(RuntimeError): """Raised when resumable-stream replay would fork agent action state from server truth.""" pass class DualCursorReplayGate: """ Guards MCP resumable-stream replay. Replay is permitted only when the gap between the durable action cursor and the incoming replay start is provably side-effect-free and free of unresolved in-flight tool calls. """ def __init__(self, action_cursor: int, transport_cursor: int, in_flight_request_ids: set[str]): self.action_cursor = action_cursor self.transport_cursor = transport_cursor self.in_flight_request_ids = in_flight_request_ids def authorize_replay(self, replay_from_event_id: int, gap_events: list[dict], server_status_lookup) -> None: # 1. Replay must not start before the action cursor: events the LLM # already acted upon must never be re-delivered for re-reasoning. if replay_from_event_id <= self.action_cursor: raise SessionContinuityForkError( f"replay starts at {replay_from_event_id} but action cursor is " f"{self.action_cursor}; re-delivering acted-upon events risks " f"duplicate irreversible tool calls" ) # 2. Every in-flight call at disconnect must be reconcilable to a # definitive outcome before the LLM sees replayed tool results. for req_id in self.in_flight_request_ids: status = server_status_lookup(req_id) if status not in ("executed", "not_executed"): raise SessionContinuityForkError( f"in-flight request {req_id} has indeterminate status " f"{status!r}; cannot safely replay, must re-establish session" ) # 3. The gap must contain only idempotent events (notifications). for ev in gap_events: if ev.get("kind") == "tool_result" and not ev.get("idempotency_key"): raise SessionContinuityForkError( f"gap event {ev.get('id')} is a non-idempotent tool_result; " f"replay would inject an unsolicited result into LLM context" ) def handle_reconnect(gate: DualCursorReplayGate, replay_from_event_id: int, gap_events: list[dict], server_status_lookup) -> str: try: gate.authorize_replay(replay_from_event_id, gap_events, server_status_lookup) except SessionContinuityForkError: # Conservative fallback: abandon replay, re-establish session from # server-side state, accept cold-start re-sync cost. return "reestablish_session" return "replay" ```