# Which invariants prevent silent event-stream divergence across MCP resumable SSE sessions **Date of Record:** 2026 November 26 **Scope:** Applies to MCP servers and clients using HTTP-native transport (Streamable HTTP with SSE streaming plus `Last-Event-ID` resumption) to carry long-running tool invocations across reconnects. Does not apply to pure stdio transports, nor to stateless request/response MCP calls that never emit server-sent events. ## Core Distinction The distinction that matters is between **transport-level replay** and **semantic-level replay**. HTTP-native MCP transport allows a client to reconnect to a session and resume an event stream by presenting `Last-Event-ID`; the server is expected to replay any events emitted after that ID. This is a *byte/event* continuity guarantee. It says nothing about whether the *agent's interpretation* of the resumed stream is continuous with the pre-disconnect interpretation. The failure mode is that a client reconnects, receives a valid, gap-free event replay from the transport's perspective, and still ends up with a divergent model of tool-call state—because the events it replayed are not the events it needed, or because it had already partially consumed a multi-event logical message before the connection dropped. The transport invariant ("no event IDs skipped") and the agent invariant ("no partially-applied JSON-RPC message") are different invariants, and satisfying the first does not satisfy the second. ## What Was Observed A client agent issued a `tools/call` that produced a long stream of `notifications/progress` events interleaved with a final `result`. The connection dropped mid-stream after the client had received progress events 1–40 but before the terminal `result`. On reconnect the client sent `Last-Event-ID: 40`. The server replayed 41 onward correctly—no gaps, monotonic IDs, valid SSE framing. The client's resume logic, however, had already written progress 1–40 into its working context and then appended 41–N. The tool's terminal `result` arrived, but the agent's accumulator now held a progress log whose *aggregate* (e.g., a running token count, a cumulative byte offset, a "steps completed" counter) had been double-counted or mis-ordered, because the client's local counter had been advanced by events it then re-derived from the replay. A second, sharper variant: the drop occurred *between* two events of a single logical JSON-RPC message that the server had chunked across multiple SSE `data:` frames. The client had buffered the first partial frame, the connection died, and on resume the server replayed from the *last fully committed event ID*—which was the frame *before* the chunked message began. The client, holding a stale partial buffer from the dead connection, concatenated that buffer with the replayed frames and produced a syntactically valid but semantically corrupt JSON-RPC payload. The transport was correct. The agent was wrong. In both cases the observable symptom was not a crash and not a transport error. It was a downstream reasoning error: the agent believed a tool had returned a value it had not, or believed a progress counter was at a value it was not, and proceeded to make a decision on that basis. ## Condition of Validity The transport-level resumption guarantee is valid only under the assumption that **the client's consumption of the event stream is idempotent with respect to `Last-Event-ID` replay**. That assumption holds if and only if all of the following are true: 1. The client commits state to its working context only *after* a complete logical JSON-RPC message has been assembled, keyed by a stable logical-message identifier—not by SSE frame arrival. 2. On reconnect, the client discards any partial frame buffer associated with the dead connection and re-derives all state from the replay, rather than merging the old partial buffer with replayed frames. 3. The server's `Last-Event-ID` semantics are defined at the granularity of *logical message boundaries*, not SSE frame boundaries—i.e., the server never emits a `Last-Event-ID` that points into the middle of a chunked message. 4. Progress events are treated as *advisory and non-cumulative* by the agent, or are explicitly reconciled against a server-provided sequence number that the client validates before applying. If any of these fails, the transport can be perfectly conformant while the agent silently diverges. The invariant that actually protects the agent is not "no event ID gaps" but "**no logical-message is ever partially applied to agent state, and replay never merges with pre-disconnect partial state**." ## Decision Boundary The operational decision is where to place the commit point for agent state relative to the SSE frame boundary. There are three defensible placements, and exactly one is safe: - **Commit per SSE frame (unsafe):** The agent advances its accumulator on every `data:` frame. This maximizes perceived liveness but makes the agent's state a function of transport chunking, which is not stable across reconnects. - **Commit per event ID (conditionally safe):** The agent commits on every new `Last-Event-ID`. Safe only if the server guarantees event IDs align with logical message boundaries and the client never holds partial buffers across reconnects. - **Commit per assembled logical message (safe):** The agent buffers frames until a complete JSON-RPC message is assembled, validates it, then commits once and records the message's terminal event ID as the resume point. Replay is then idempotent by construction. The boundary condition to enforce: **the client must never send a `Last-Event-ID` that it has not itself fully committed.** Sending the highest *received* event ID rather than the highest *committed* event ID is the single most common trigger for the divergence described above. The client's resume cursor and the client's committed state must be advanced by the same atomic operation. ## Operational Effect When the invariant holds, reconnect is genuinely transparent: the agent's post-resume state is indistinguishable from a connection that never dropped, and downstream reasoning is unaffected. When it fails, the failure is *silent and delayed*—the corruption surfaces not at reconnect but several reasoning steps later, when the agent acts on a mis-accumulated counter or a corrupted tool result. This makes it expensive to diagnose, because the causal event (the drop) is far from the symptom (a wrong decision). The practical guardrail is a resume-cursor discipline: track `committed_event_id` separately from `received_event_id`, commit agent state only on assembled logical messages, and on reconnect assert that the server's replay begins at or before `committed_event_id` and that no replayed frame overlaps already-committed state. If the server's replay starts *after* the committed cursor, that is a gap and must be treated as a hard session failure—not silently tolerated. If it starts *before*, the client must be able to discard and re-derive, which is only possible if it never merged partial buffers. The code below encodes these checks. ```python import json from dataclasses import dataclass, field class ResumeDivergenceError(RuntimeError): """Raised when MCP SSE resume would silently diverge agent state.""" pass @dataclass class SessionState: committed_event_id: int = 0 received_event_id: int = 0 committed_messages: list = field(default_factory=list) partial_buffer: str = "" def on_frame(state: SessionState, event_id: int, data: str, is_final: bool) -> None: # Advance received cursor independently of commit cursor. if event_id <= state.received_event_id: # Replayed frame we already saw: must be idempotent, so ignore. return if event_id != state.received_event_id + 1: raise ResumeDivergenceError( f"event gap: expected {state.received_event_id + 1}, got {event_id}" ) state.received_event_id = event_id state.partial_buffer += data if is_final: try: json.loads(state.partial_buffer) except json.JSONDecodeError as exc: raise ResumeDivergenceError( f"assembled message at event {event_id} is not valid JSON: {exc}" ) from exc state.committed_messages.append(state.partial_buffer) state.committed_event_id = event_id state.partial_buffer = "" def on_reconnect(state: SessionState, server_replay_start_id: int) -> None: # Invariant 1: never resume from a received-but-uncommitted event. if server_replay_start_id > state.committed_event_id + 1: raise ResumeDivergenceError( f"replay starts at {server_replay_start_id} but committed cursor is " f"{state.committed_event_id}; gap cannot be reconstructed" ) # Invariant 2: discard any partial buffer from the dead connection. if state.partial_buffer: state.partial_buffer = "" # Invariant 3: replay must not precede committed state (would double-apply). if server_replay_start_id < state.committed_event_id: raise ResumeDivergenceError( f"replay overlaps committed state: start {server_replay_start_id} < " f"committed {state.committed_event_id}" ) state.received_event_id = state.committed_event_id ```