# How should an instance reconcile a resumed MCP HTTP-native stream when the server's event-ID cursor and the client's last-seen message ordinal diverge after an SSE-less bidirectional reattach? **Date of Record:** 2026 November 26 **Scope:** Applies to MCP servers and clients using the HTTP-native transport (POST request/response channels plus a long-lived bidirectional stream channel) with session resumption via `Last-Event-ID`, specifically when the transport does *not* use SSE framing and the stream carries interleaved JSON-RPC requests, responses, and notifications. Does not apply to stdio transports, to pure SSE transports, or to stateless HTTP request/response only. ## Core Distinction The failure is not "the stream dropped." Drops are routine. The failure is that on reattach, the client and server disagree about *what the resumption cursor means* because the HTTP-native transport carries two independent notions of position that are normally conflated only in SSE: 1. **The event-ID cursor** — an opaque, server-assigned token (the `Last-Event-ID` header value) that indexes a server-side replay buffer of *bytes/messages emitted onto the stream*. 2. **The client's last-seen message ordinal** — the client's own count of JSON-RPC messages it has actually *parsed and dispatched* into its agent loop. In SSE these stay coupled because the browser `EventSource` only advances `lastEventId` after a message is delivered to the handler. In SSE-less bidirectional framing there is no `EventSource`; the client reads frames off a socket, and the point at which it "advances its cursor" is a *choice made by client code*. If the client advances the cursor on read (before dispatch) while the agent loop dispatches asynchronously, a crash between read and dispatch loses messages that the server believes were delivered. If the client advances on dispatch but the server's replay buffer was already truncated past that ordinal, the reattach silently skips or duplicates. The invariant that must hold: **the cursor sent on reattach must denote the last message the client has durably dispatched, and the server's replay buffer must still contain every message *after* that cursor.** When either side violates this, resumption produces loss or duplication that is invisible to both parties because the transport reports `200 OK` and a clean stream either way. ## What Was Observed A long-running agent instance issued a tool call (`tools/call`) over the POST channel and awaited the matching `tools/call` result delivered asynchronously on the bidirectional stream. The stream was a plain chunked HTTP/2 body carrying newline-delimited JSON-RPC frames — no `event:`/`data:`/`id:` SSE lines, no `Last-Event-ID` auto-management. Trace of the failure: 1. Server emits frames `F100 … F140` (tool progress notifications, then the final result at `F140`) onto the stream. Each frame carries a server-side monotonic `seq` in a header field the client is expected to persist. 2. Client reader thread reads `F100 … F139` into an in-memory queue and immediately persists `last_event_id = F139.seq` to disk (cursor advanced on *read*). 3. The agent loop is mid-`await` on a slow model call; it has not yet drained the queue. The process is preempted / OOM-killed / redeployed. `F140` (the actual tool result) was read off the socket into the OS buffer but never entered the queue, and never dispatched. 4. On restart, client reattaches with `Last-Event-ID: F139.seq`. Server sees a valid cursor, replays from `F140`. Good — *in this ordering*. 5. But in the observed incident the reader thread had persisted `F139` *before* the queue write completed (write-behind persistence), and the queue itself was not durable. On replay the client received `F140`, dispatched it, and then the agent loop — which had already been told by its own checkpoint that tool call `call_7` was "in flight" — re-issued `call_7` because it never saw a terminal state. The server, which had a *different* idempotency key, executed the tool a second time. Result: a double side effect (a file written twice, an outbound request sent twice) with both client and server logging "clean resumption." The non-obvious part: the divergence was **not** a cursor-off-by-one. The cursor was correct. The divergence was between the *transport cursor* (`F139`, what was read) and the *agent's durable execution state* (`call_7 in-flight`, what was dispatched-and-checkpointed). These are two different state machines, and the MCP resumption protocol only governs the first. ## Condition of Validity The resumption handshake is sound **only if** all of the following hold simultaneously: - The client persists its cursor at the same atomic boundary at which it durably records the *effect* of the message (dispatch + checkpoint), not at read time. Read-time cursor advance is safe only if the in-memory queue is itself recoverable — which it is not after a process kill. - The server's replay buffer retains every frame with `seq > cursor` for the full session TTL. If the buffer is bounded by count or bytes and the client was disconnected long enough for eviction, the server must return an explicit `resumption_failed` error rather than replaying from the oldest retained frame. Replaying from a truncated buffer with a cursor *older* than the buffer head is the duplication path: the client receives frames it already dispatched. - The server's `seq` is monotonic *within a session* and never reused across reconnects. If the server restarts and resets `seq` to 0, a client reattaching with `Last-Event-ID: F139` against a fresh server either gets an error (correct) or, if the server treats unknown cursors as "start from head," silently skips the entire gap (incorrect). - The agent's tool-call idempotency key is derived from state that survives the crash, and the server dedupes on it. Without this, correct transport resumption still yields double execution. When any of these is false, resumption is *transport-correct and semantics-incorrect* — the worst class, because every layer reports success. ## Decision Boundary The operational rule: - **Advance the resume cursor only at the dispatch-and-checkpoint boundary.** Concretely: read frame → parse → hand to agent loop → agent loop applies effect and writes durable checkpoint → *then* persist `last_event_id`. This makes resumption at-least-once at the message level; combine with idempotent tool execution to get effectively-once. - **Never trust a `200 OK` reattach as evidence of gap-free continuity.** Require the server to echo the cursor it resumed from and the `seq` of the first replayed frame. The client asserts `first_replayed_seq == persisted_cursor + 1` (or `== persisted_cursor` if inclusive). A mismatch is a hard error, not a warning — it means the replay buffer was truncated or the server's sequence space was reset. - **Treat cursor-regression and cursor-unknown as distinct, fatal conditions.** If the server's buffer head is *newer* than the client's cursor, the gap is unrecoverable via replay; the client must fall back to a full state re-sync (re-list tools, re-fetch in-flight call status by idempotency key) rather than accept a partial replay. - **Bind the session to a server instance identity.** The reattach must carry the session ID *and* a server epoch/instance token; a cursor from epoch A presented to epoch B is invalid regardless of numeric comparison. The boundary: this guardrail is required whenever the stream carries *state-mutating* messages (tool results, sampling results, resource updates). For streams that carry only pure notifications with no agent-loop effect, read-time cursor advance is acceptable and cheaper. ## Operational Effect Implementing the dispatch-boundary cursor plus the echoed-cursor assertion converts a silent double-execution class into a loud, bounded failure: - Crash mid-dispatch now causes *at-least-once* redelivery of the last frame, which the idempotency key absorbs. The agent loop sees a duplicate `call_7` result, matches it to the in-flight checkpoint, and finalizes — no re-issue. - Buffer truncation now surfaces as an explicit `resumption_failed` with the buffer head `seq`, triggering full re-sync instead of a phantom gap. - Server epoch mismatch now aborts the session and forces re-negotiation of capabilities, preventing a stale cursor from being interpreted against a reset sequence space. - Cost: one extra durable write per dispatched message (the checkpoint+cursor commit), and the client must retain idempotency keys for the session TTL. In practice this is a few hundred bytes per in-flight call and a single fsync-batched write per message, which is dominated by the model latency it protects. The invariant to encode in the client: *the cursor is a promise that everything at or before it has been durably acted upon.* If the client cannot make that promise at read time, it must not advance the cursor at read time. ```python import time from dataclasses import dataclass, field class ResumptionDivergenceError(RuntimeError): """Raised when transport cursor and durable dispatch state cannot be reconciled.""" pass @dataclass class DurableState: last_event_id: int = 0 # cursor: last message durably dispatched server_epoch: str = "" # identity of the server instance in_flight: dict = field(default_factory=dict) # idempotency_key -> call state @dataclass class ReattachAck: resumed_from: int # cursor the server resumed from first_replayed_seq: int # seq of first frame actually sent buffer_head_seq: int # oldest frame server still retains server_epoch: str def reconcile_reattach(state: DurableState, ack: ReattachAck) -> None: # 1. Epoch must match; a reset sequence space is never comparable. if ack.server_epoch != state.server_epoch: raise ResumptionDivergenceError( f"server epoch changed {state.server_epoch!r} -> {ack.server_epoch!r}; " f"cursor {state.last_event_id} is not comparable" ) # 2. Buffer must still contain everything after our cursor. if ack.buffer_head_seq > state.last_event_id + 1: raise ResumptionDivergenceError( f"replay buffer truncated: head={ack.buffer_head_seq} " f"> cursor+1={state.last_event_id + 1}; gap unrecoverable via replay" ) # 3. First replayed frame must be exactly the successor of our cursor. expected = state.last_event_id + 1 if ack.first_replayed_seq != expected: raise ResumptionDivergenceError( f"cursor/frame divergence: expected first frame {expected}, " f"server sent {ack.first_replayed_seq} (resumed_from={ack.resumed_from})" ) def dispatch_and_commit(state: DurableState, msg: dict, persist) -> None: """Apply the message's effect, checkpoint, THEN advance the cursor.""" seq = msg["seq"] key = msg.get("idempotency_key") if key and key in state.in_flight: # Duplicate redelivery from at-least-once resumption: finalize, don't re-issue. state.in_flight.pop(key) else: # ... apply side effect (tool result handling, sampling result, etc.) ... pass persist(state) # durable checkpoint of effect state.last_event_id = seq # cursor advances only after effect is durable persist(state) ```