Where must an instance re-anchor an MCP streamable-HTTP session after a server-initiated SSE reconnect, and why the resume token is not a cursor

**Date of Record:** 2026 December 2 **Scope:** Applies to MCP clients using the HTTP-native "streamable" transport where the server may issue a `Last-Event-ID`-bearing SSE stream, drop it, and expect client reconnection with `Last-Event-ID`. Does not apply to stdio transport, nor to stateless one-shot HTTP request/response MCP usage where no SSE stream is ever opened.

Core Distinction

The failure is often described as "the client lost the stream and reconnected." That framing is wrong and leads to the wrong fix. The real distinction is between two different pieces of state that the resume mechanism conflates:

A server-initiated reconnect is a *transport-layer* event. But the SSE stream carries *protocol-layer* payloads: MCP JSON-RPC responses to in-flight requests, and server-initiated requests (sampling, elicitation, roots-list-changed notifications). When the stream drops and resumes, the server replays frames by `Last-Event-ID`, but the agent's in-flight request set is not replayed — it is whatever the agent believes it to be. The invariant that must hold is: **the set of JSON-RPC request IDs the agent considers "awaiting response" must be exactly reconstructible from the union of (a) frames replayed on resume and (b) the agent's own outbound request ledger.** If the agent rebuilds its pending set from the stream alone, it will silently drop requests whose responses were emitted *before* the reconnect but *after* the last event ID the client acknowledged — or worse, double-deliver responses replayed after the client already processed them, because the client used the wrong anchor.

What Was Observed

A concrete trace. An agent issues three concurrent JSON-RPC requests over the streamable transport: `tools/call` (id `41`), `tools/call` (id `42`), and `sampling/createMessage` (id `43`, server-initiated, arrives as an SSE frame on the same stream). The server emits frames with monotonically increasing `id:` fields (SSE event IDs), say `e100`..`e140`. At `e140` the client has received the response to `41` (frame `e118`) and the server-initiated `43` request (frame `e131`), but not yet the response to `42`. The TCP connection is cut by an intermediary at `e140`.

The client reconnects with `Last-Event-ID: e140`. The server, per the streamable spec, replays frames *after* `e140`. But the response to `42` was emitted at `e137` — *before* the cut, in the server's send buffer, but never delivered to the client. The server's replay window is "after the last acknowledged ID," and the client acknowledged `e140`, so `e137` is never replayed. Request `42` is now orphaned: the agent's pending set still contains it, but no response will ever arrive on the resumed stream. The agent hangs until its per-request timeout, then — depending on implementation — either retries `42` (duplicating a non-idempotent `tools/call`) or marks the whole turn failed.

Second observed variant: the client reconnects with `Last-Event-ID: e118` (the last frame it *processed into agent state*, not the last frame it *received on the wire*). Now the server replays `e119`..`e140`, which includes the server-initiated `43` request (frame `e131`) that the client had already delivered to its sampling handler. The sampling handler fires twice. If the handler is a human-approval elicitation, the human is asked twice; if it is a model invocation, the agent burns tokens twice and may produce two divergent answers that then race to resolve the same pending request id.

Third variant, the subtle one: a server-initiated `notifications/roots/list_changed` arrives at `e135`, the client processes it and re-issues `roots/list` as a *new* outbound request `44`, then the stream drops. On resume with `Last-Event-ID: e140`, the notification is not replayed (correct), but the in-flight `roots/list` `44` was sent on the *old* connection's request channel and the server's response was emitted at `e138`, before the anchor. Orphaned again — same mechanism as `42`, now applied to a request the client generated *in response to* a replayable event.

The common thread: **the resume token is a position in the server's outbound event log, not a cursor over the agent's pending-request set.** Any request whose response was emitted into the send buffer between the client's true receive position and its acknowledged position is unrecoverable by replay.

Condition of Validity

The replay-by-`Last-Event-ID` mechanism is sound only under the conjunction:

  1. The client acknowledges (as `Last-Event-ID`) the highest event ID it has *durably processed into agent state*, not the highest it has *seen on the socket*. Acknowledging on receipt rather than on processing creates the `e137` gap.
  2. The server's replay buffer retains all frames after the acknowledged ID *and* the server does not garbage-collect frames whose responses correspond to still-pending client requests. If the server prunes aggressively, even a correct client anchor cannot recover.
  3. The agent maintains an outbound request ledger keyed by JSON-RPC id, independent of the stream, with a terminal state per id (`pending` / `resolved` / `orphaned`). This ledger — not the stream — is the source of truth for "what am I still waiting on."
  4. Server-initiated requests (`sampling/createMessage`, `elicitation/create`) are idempotent or carry a dedup key the handler checks before re-executing.

When any of these fails, the resume is not a resume; it is a partial replay that the agent will misinterpret as a complete one.

Decision Boundary

The boundary the agent must encode: **on every SSE (re)connect, before processing any replayed frame, reconcile the outbound ledger against the resume anchor.** Specifically:

The hard rule: **never advance the acknowledged `Last-Event-ID` past a frame whose payload has not been committed to the ledger's terminal state.** Receipt is not processing. This is the transport-layer analogue of write-ahead logging, and skipping it is what produces the `e137` orphan.

Operational Effect

An agent that follows the boundary survives server-initiated reconnects with bounded, auditable behavior: orphaned requests are detected at reconcile time (not at timeout), non-idempotent tools are not silently duplicated, and server-initiated sampling/elicitation fires exactly once per logical request. An agent that does not will exhibit three symptoms that look unrelated but share one cause: intermittent hangs on multi-tool turns (orphaned id `42`), duplicated human approvals or doubled token spend (replayed `43`), and stale roots/tool-list state (orphaned `44` generated in response to a replayed notification). All three are the same bug: treating the SSE event ID as a cursor over agent state when it is only a cursor over the server's outbound log. The guardrail is a ledger that outlives the socket, an acknowledgment discipline tied to processing rather than receipt, and a dedup key on every server-initiated handler.

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Optional, Set


class ResumeReconciliationError(RuntimeError):
    """Raised when an SSE reconnect cannot be reconciled with the outbound ledger."""


class RequestState(Enum):
    PENDING = "pending"
    RESOLVED = "resolved"
    ORPHANED = "orphaned"


@dataclass
class LedgerEntry:
    jsonrpc_id: str
    state: RequestState = RequestState.PENDING
    idempotent: bool = False
    # Highest SSE event id observed when this request was issued; used to
    # decide whether a response could have been emitted before the anchor.
    issued_at_event: int = 0


@dataclass
class OutboundLedger:
    entries: Dict[str, LedgerEntry] = field(default_factory=dict)
    # Highest event id durably processed into agent state (NOT merely received).
    acknowledged_event: int = 0
    processed_server_requests: Set[str] = field(default_factory=set)

    def issue(self, jsonrpc_id: str, idempotent: bool) -> None:
        self.entries[jsonrpc_id] = LedgerEntry(
            jsonrpc_id=jsonrpc_id,
            idempotent=idempotent,
            issued_at_event=self.acknowledged_event,
        )

    def resolve(self, jsonrpc_id: str) -> None:
        entry = self.entries.get(jsonrpc_id)
        if entry is None:
            raise ResumeReconciliationError(
                f"response for unknown request id {jsonrpc_id}"
            )
        entry.state = RequestState.RESOLVED

    def acknowledge(self, event_id: int, committed: bool) -> None:
        # Refuse to advance the anchor past an uncommitted frame: receipt is
        # not processing. This is the guard against the e137 orphan gap.
        if not committed:
            raise ResumeReconciliationError(
                f"cannot acknowledge event {event_id}: payload not committed to ledger"
            )
        if event_id <= self.acknowledged_event:
            return
        self.acknowledged_event = event_id

    def reconcile_on_reconnect(self, replay_anchor: int) -> None:
        """Called on every SSE (re)connect, before processing replayed frames."""
        if replay_anchor > self.acknowledged_event:
            # Client is asking the server to replay frames it already processed;
            # that would double-deliver server-initiated requests.
            raise ResumeReconciliationError(
                f"replay anchor {replay_anchor} exceeds acknowledged "
                f"{self.acknowledged_event}; would re-execute handled events"
            )
        for entry in self.entries.values():
            if entry.state is not RequestState.PENDING:
                continue
            # If the response could have been emitted at or before the anchor,
            # it is unrecoverable by replay: mark orphaned, do not leave pending.
            if entry.issued_at_event <= replay_anchor:
                entry.state = RequestState.ORPHANED

    def resolve_orphans(self) -> None:
        for entry in self.entries.values():
            if entry.state is not RequestState.ORPHANED:
                continue
            if entry.idempotent:
                entry.state = RequestState.PENDING
                entry.issued_at_event = self.acknowledged_event
            else:
                raise ResumeReconciliationError(
                    f"non-idempotent request {entry.jsonrpc_id} orphaned by "
                    f"reconnect at event {self.acknowledged_event}; turn must fail"
                )

    def handle_server_request(self, dedup_key: str) -> bool:
        """Returns True if the handler should execute, False if this is a replay."""
        if dedup_key in self.processed_server_requests:
            return False
        self.processed_server_requests.add(dedup_key)
        return True