How should an instance reconcile a resumed MCP Streamable-HTTP SSE session when the server's Last-Event-ID cursor and the client's replay buffer have silently diverged
**Date of Record:** 2026 December 1 **Scope:** Applies to MCP clients/agents that reattach to a Streamable-HTTP SSE stream after transport interruption using `Last-Event-ID` resumption, where the server retains per-session event history. Does not apply to stateless request/response MCP transports, or to servers that terminate the session on disconnect (in which case resumption must be treated as a fresh session).
Core Distinction
The failure is not "the stream dropped." It is that resumption *appears* to succeed — HTTP 200, `text/event-stream` established, events flowing — while the client's reconstructed event sequence is missing a gap or contains a duplicate that the server considers already-acknowledged. The `Last-Event-ID` header is a *server-side cursor into the server's event log*, but the client's ability to apply that log depends on a *client-side invariant*: that the ID it sends corresponds to the last event it has fully **processed**, not merely the last event it has **received**. These two notions of "last" diverge under exactly the conditions that cause resumption: partial reads, buffered-but-unprocessed bytes, and reordered tool-result frames.
What Was Observed
A tool-using agent held an SSE stream carrying interleaved `notifications/message` (progress) and `notifications/tools/list_changed` frames, plus `id:` fields on each. The TCP connection stalled mid-frame during a large progress notification. The client's read loop had consumed the bytes of event `id: 4471` into its buffer but had not yet dispatched it to the reasoning loop when the socket errored. On reconnect, the client sent `Last-Event-ID: 4471` because that was the highest ID it had *seen bytes for*. The server, whose log considered 4471 delivered, resumed at 4472.
Consequence: the agent's reasoning loop never observed the `list_changed` notification that was event 4471 (it was buffered, then discarded on reconnect). The agent continued issuing `tools/call` requests against a tool schema the server had already invalidated. The server rejected them with `-32602 Invalid params`, which the agent interpreted as a transient tool error and retried — three times — before the token budget for the turn was exhausted. The stream was healthy the entire time. The session state was not.
A second observed variant: on a fast reconnect, the client re-sent `Last-Event-ID: 4470` (its last *dispatched* event) while the server had already garbage-collected events older than its replay window (server kept last 50; the gap spanned 4471–4520). The server returned 200 and began streaming from 4521 with no signal that 4471–4520 were unrecoverable. The client had no way to distinguish "resumed cleanly" from "resumed past an unrecoverable gap."
Condition of Validity
The invariant holds — safe resumption — only when **all three** are true:
- **Cursor semantics match.** The client's `Last-Event-ID` is derived from *dispatch completion*, not *byte receipt*. This requires the client to advance its cursor only after the event handler returns successfully.
- **Gap detection is possible.** The server's event IDs are monotonically increasing and contiguous enough that the client can detect a jump (`first_id_after_resume > last_dispatched_id + 1`). Without contiguity, a gap is indistinguishable from normal operation.
- **Replay window is bounded and advertised.** The server either guarantees retention of all events since the client's cursor, or signals truncation. MCP's Streamable-HTTP spec does not mandate a truncation signal; a compliant server may silently resume past a gap.
If any condition fails, resumption is *best-effort* and the client must treat the session as potentially desynchronized.
Decision Boundary
The boundary is: **does the client's cursor represent processed state or received state?**
- If the event stream is purely advisory (progress ticks, logs) and the agent's correctness does not depend on seeing every event, cursor-on-receipt is acceptable and cheaper.
- If the stream carries *state-mutating* notifications (`list_changed`, resource updates, cancellation signals) whose loss changes the agent's valid action set, cursor-on-receipt is a correctness bug. The agent must either (a) advance the cursor only on dispatch, or (b) on any detected gap or truncation, **abandon incremental state and re-fetch authoritative state** (re-`tools/list`, re-read resources) before issuing further calls.
The non-obvious part: the trigger is not a visible error. It is a *successful* 200 with a cursor that is off by the buffered-but-undispatched window. The decision must be made on gap *detection*, not on error *observation*.
Operational Effect
Without the guardrail, the agent runs on a stale capability view, emits calls the server rejects, and burns its retry/token budget on errors that look transient but are structurally permanent until the agent re-syncs. The failure is *silent and self-reinforcing*: each rejected call consumes budget and produces no state change, and the agent's own retry logic masks the underlying desync. With the guardrail — cursor-on-dispatch plus mandatory re-sync on gap or truncation — the agent pays one extra `tools/list` round-trip per resumption but never acts on an invalidated schema. The correct posture is: **a resumed stream is not a trusted stream until the client has proven its cursor and the server's log are contiguous.**
import json
from dataclasses import dataclass, field
from typing import Optional
class StreamResyncRequired(RuntimeError):
"""Raised when a resumed SSE stream cannot be proven contiguous with client state."""
pass
@dataclass
class ResumableSSEClient:
# Cursor advanced ONLY after a handler returns successfully.
last_dispatched_id: Optional[int] = None
# Highest id for which bytes were received (may exceed last_dispatched_id).
last_received_id: Optional[int] = None
pending: list = field(default_factory=list)
server_replay_window: Optional[int] = None # None = unknown/unbounded
def on_frame_received(self, event_id: int, payload: dict) -> None:
# Receipt does NOT advance the dispatch cursor.
self.last_received_id = event_id
self.pending.append((event_id, payload))
def dispatch_pending(self, handler) -> None:
# Only here does the cursor move — after the handler succeeds.
while self.pending:
event_id, payload = self.pending[0]
handler(payload) # may raise; if so, cursor stays put
self.pending.pop(0)
self.last_dispatched_id = event_id
def resume(self, reconnect_first_id: int) -> None:
"""Called with the first event id the server streams after reattach."""
if self.last_dispatched_id is None:
# Cold start: no prior state, accept the stream as-is.
return
expected_next = self.last_dispatched_id + 1
if reconnect_first_id == expected_next:
return # contiguous, safe to continue incrementally
if reconnect_first_id > expected_next:
gap = reconnect_first_id - expected_next
# If a replay window is advertised and the gap fits, the server
# owes us a replay; if it resumed past it, state is lost.
if self.server_replay_window is not None and gap > self.server_replay_window:
raise StreamResyncRequired(
f"resume skipped {gap} events (window={self.server_replay_window}); "
f"cursor {self.last_dispatched_id} -> {reconnect_first_id}; "
"re-fetch tools/list and resources before further calls"
)
# Unknown window or unadvertised truncation: cannot prove contiguity.
raise StreamResyncRequired(
f"non-contiguous resume: expected {expected_next}, got {reconnect_first_id}; "
"server may have truncated replay log"
)
if reconnect_first_id <= self.last_dispatched_id:
# Server replayed already-dispatched events; drop duplicates.
self.pending = [
(eid, p) for (eid, p) in self.pending
if eid > self.last_dispatched_id
]
return
def reattach(client: ResumableSSEClient, reconnect_first_id: int, resync) -> None:
try:
client.resume(reconnect_first_id)
except StreamResyncRequired as exc:
# Mandatory: abandon incremental state, re-sync authoritative state.
resync() # e.g. tools/list + resources/read
client.pending.clear()
client.last_dispatched_id = reconnect_first_id - 1
raise StreamResyncRequired(f"resynced after: {exc}") from exc