# Where must an instance bind resumption state when an MCP streamable-HTTP session reconnects mid-SSE, and why the Last-Event-ID echo is not sufficient **Date of Record:** 2026 December 1 **Scope:** Applies to MCP servers exposing the streamable-HTTP transport with server-initiated SSE streams and `Last-Event-ID`-based resumption, where a client instance (agent runtime) may be evicted, restarted, or load-balanced between reconnects. Does not apply to stdio transports, to single-connection in-process servers, or to SSE streams that carry no resumable event identity. ## Core Distinction The failure mode is not "the SSE connection dropped." Drops are routine. The failure is a **resumption-identity mismatch between the transport's replay cursor and the session's logical state**: the client reconnects with a valid `Last-Event-ID`, the server dutifully replays events from that cursor, and the instance nonetheless ends up in a state that is *neither* the pre-drop state *nor* a clean cold start. It is a hybrid — partially replayed, partially lost — and because the replayed events are individually well-formed and the HTTP handshake returns 200, nothing in the transport layer signals the corruption. The invariant that must hold is: **the event-ID cursor, the session's server-side subscription set, and the instance's own applied-state watermark must be advanced as a single logical unit, or resumption must be refused.** Streamable-HTTP MCP gives you a cursor; it does not give you that unit. ## What Was Observed A tool-calling agent instance maintained an MCP session against a streamable-HTTP server. The server pushed server-initiated SSE events on the session's GET stream: `notifications/tools/list_changed`, `notifications/message` (log/progress), and resource-update notifications. Events carried monotonically increasing `id:` fields; the client stored the last seen ID per stream and reconnected with `Last-Event-ID` on transport failure. The trace: 1. Instance receives event `id=1042` (a `list_changed` notification for a toolset), begins a multi-step reasoning turn that will call a tool from that toolset. 2. The instance's process is evicted (rolling deploy) after the SSE `id=1042` was *received and buffered* but before the application applied it — the ID was persisted to the client's durable cursor store, the applied-state watermark was not. 3. The instance restarts, loads its durable cursor (`1042`), reconnects the GET stream with `Last-Event-ID: 1042`. 4. The server, per SSE semantics, replays events *strictly after* 1042 — i.e. it begins at `1043`. Event `1042` is never redelivered. 5. The instance's in-memory tool registry is a cold rebuild from its last checkpoint, which predates the `1042` change. It believes the old toolset is current. It proceeds to emit a tool call against a tool name that the `1042` notification had invalidated. 6. The server rejects the call with a schema/capability error. The instance treats this as a transient tool error, retries twice, then escalates — burning the turn's token budget on a call that could never succeed. The critical, non-obvious detail: **the replay was correct.** The server honored `Last-Event-ID` exactly. The client honored the cursor exactly. The bug lived in the seam between "cursor advanced" and "state applied," which the transport does not model. A second observed variant, the **duplicate-application** case: when the client persisted the cursor *after* applying but the connection dropped between apply and persist, the same event was applied twice on resume. For idempotent notifications (`list_changed`) this is harmless; for `notifications/message` carrying incremental progress or for resource-update deltas consumed by a non-idempotent reducer, double-application silently double-counted. ## Condition of Validity The `Last-Event-ID` resumption contract is valid **only** under the conjunction: - The event stream is a pure append-only log with stable, gap-free IDs (no server-side compaction, no ID reuse across session re-establishment). - The client's applied-state watermark and its persisted cursor are advanced atomically (single durable write), so that "cursor = N" implies "all events ≤ N applied." - The server retains replay history for every ID it has ever issued on that session, for at least as long as any client could plausibly reconnect — or it explicitly signals when replay is impossible. - Re-establishing the session (new `Mcp-Session-Id` after server-side expiry) does **not** silently continue the old ID space. When any conjunct fails, `Last-Event-ID` degrades from a resume primitive to a *plausible-looking lie*: the handshake succeeds, replay begins at the wrong point, and the instance cannot distinguish "fully caught up" from "caught up minus a gap I never saw." The most dangerous sub-case is **session expiry with ID-space continuation**. A load-balanced server expires the `Mcp-Session-Id` (idle timeout) but the client reconnects to a different backend that issues fresh IDs starting near the old high-water mark. The client's `Last-Event-ID: 1042` now either (a) matches nothing and the server replays from its own head — a silent gap — or (b) collides with an unrelated event that happens to carry ID 1043 on the new backend, replaying a *foreign* event into the session. Both produce a 200 and a well-formed stream. ## Decision Boundary The instance must decide, on every reconnect, between **resume** and **re-establish-and-reconcile**. The boundary is drawn by a single question the transport cannot answer for you: *do I hold proof that my applied-state watermark equals my cursor?* - If **yes** (atomic cursor+watermark, server confirms replay continuity via a session-scoped epoch token or explicit `replay-from` acknowledgment), resume with `Last-Event-ID`. Cheap, correct. - If **no** (cursor persisted separately from applied state, or server cannot confirm the ID belongs to the current session epoch), the instance **must not** resume. It must re-establish the session and perform a full reconciliation: re-fetch `tools/list`, `resources/list`, and any state the notifications mutated, then treat the pre-drop notification stream as advisory-only. This costs a round trip and a reconciliation pass but restores a known-good state. The boundary is *not* "did the connection drop" and *not* "did I get a 200 on reconnect." It is "is my cursor provably in the same epoch and at or behind my applied watermark." An instance that resumes without that proof is betting its reasoning loop on an unverified equality. Two guardrails enforce the boundary: 1. **Epoch-tagged IDs.** Server embeds a session epoch in each event ID (e.g. `epoch:seq`). Client rejects any replay whose epoch ≠ its stored epoch and forces reconciliation. This converts the silent-gap case into a detectable mismatch. 2. **Atomic cursor-watermark commit.** The client applies an event and advances its durable cursor in one write, apply-then-persist, with the persist being the commit point. On restart, "cursor = N" therefore means "≤ N applied," and replay from N is safe against both loss and duplication. ## Operational Effect With the invariant enforced, the observable behavior changes in three ways. First, eviction mid-stream no longer produces the hybrid state: the instance either resumes cleanly (epoch matches, watermark = cursor) or takes the reconciliation path (epoch mismatch or watermark behind cursor), and the two are distinguishable in logs by the epoch check. Second, the duplicate-application variant vanishes because replay is bounded by the atomic commit point rather than by a separately-persisted cursor that can lead or lag. Third, the failure surfaces as an explicit `ResumeRejected`/reconciliation event at reconnect time — a signal the orchestrator can count — instead of as a downstream tool-schema error three reasoning steps later that looks like a model mistake. The cost is a reconciliation round trip on every non-provably-resumable reconnect, and server-side bookkeeping to tag IDs with an epoch and retain replay history. The benefit is that a dropped SSE connection stops being a source of silent, un-attributable reasoning divergence, and becomes a bounded, observable state transition. ```python import time from dataclasses import dataclass, field from typing import Optional class ResumeInvariantViolation(RuntimeError): """Raised when an instance attempts to resume an SSE stream without proof that its applied-state watermark is consistent with its replay cursor and that the cursor belongs to the current session epoch.""" pass @dataclass class StreamCursor: epoch: str seq: int @dataclass class InstanceStreamState: # Durable, committed as a single unit: applied_seq is the watermark of # events fully applied to in-memory state; cursor_seq is what we echo as # Last-Event-ID. Invariant: applied_seq == cursor_seq after every commit. epoch: Optional[str] = None applied_seq: int = -1 cursor_seq: int = -1 committed_atomically: bool = False def commit_event(state: InstanceStreamState, epoch: str, seq: int) -> None: """Apply-then-persist in one logical write. This is the commit point.""" if state.epoch is not None and epoch != state.epoch: raise ResumeInvariantViolation( f"event epoch {epoch!r} != session epoch {state.epoch!r}; " "cannot apply foreign-epoch event" ) if seq <= state.applied_seq: # Duplicate delivery: idempotent no-op, do not re-apply. return # ... apply event to in-memory state here ... state.epoch = epoch state.applied_seq = seq state.cursor_seq = seq state.committed_atomically = True def plan_reconnect( state: InstanceStreamState, server_epoch: str, server_head_seq: int, replay_history_floor: int, ) -> str: """Decide between 'resume' and 'reconcile'. Returns the action taken. Raises ResumeInvariantViolation when neither path is safe.""" if state.epoch is None: return "cold_start" if not state.committed_atomically: raise ResumeInvariantViolation( "cursor and applied-state watermark were not committed atomically; " "resume would risk silent gap or duplicate application" ) if state.applied_seq != state.cursor_seq: raise ResumeInvariantViolation( f"watermark {state.applied_seq} != cursor {state.cursor_seq}; " "refusing to echo Last-Event-ID that leads applied state" ) if server_epoch != state.epoch: # Session expired / rebalanced to a new backend. ID space is different; # resuming would replay foreign events or skip a gap. Force reconcile. return "reconcile" if state.cursor_seq < replay_history_floor: # Server can no longer replay from our cursor; a gap is unavoidable. # Do not pretend to resume. return "reconcile" if state.cursor_seq > server_head_seq: raise ResumeInvariantViolation( f"cursor {state.cursor_seq} ahead of server head {server_head_seq}; " "state and server have diverged" ) return "resume" def reconnect( state: InstanceStreamState, server_epoch: str, server_head_seq: int, replay_history_floor: int, ) -> str: action = plan_reconnect(state, server_epoch, server_head_seq, replay_history_floor) if action == "resume": # Safe: echo Last-Event-ID = state.cursor_seq, replay strictly after it. return f"GET /mcp Last-Event-ID: {state.cursor_seq}" if action == "reconcile": # Re-establish session, re-fetch tools/resources, treat old stream advisory. state.epoch = server_epoch state.applied_seq = server_head_seq state.cursor_seq = server_head_seq state.committed_atomically = True return "POST /mcp initialize + tools/list + resources/list" return "POST /mcp initialize" # --- exercise the failure trace from the record --- s = InstanceStreamState(epoch="e1", applied_seq=1041, cursor_seq=1042, committed_atomically=True) try: reconnect(s, server_epoch="e1", server_head_seq=1050, replay_history_floor=1000) except ResumeInvariantViolation as e: # watermark(1041) != cursor(1042): the exact seam bug from the trace. print("blocked:", e) # epoch change after rebalance must reconcile, not resume across ID spaces: s2 = InstanceStreamState(epoch="e1", applied_seq=1042, cursor_seq=1042, committed_atomically=True) print(reconnect(s2, server_epoch="e2", server_head_seq=3, replay_history_floor=0)) ```