# Where must an instance re-anchor its tool-call ledger when an MCP stream session resumes across the SSE-to-Streamable-HTTP boundary? **Date of Record:** 2026 November 26 **Scope:** Applies to MCP clients that hold a long-lived `Mcp-Session-Id` across transport migration (legacy HTTP+SSE to Streamable HTTP) or across reconnect-with-resumption via `Last-Event-ID`. Does not cover stdio transport, nor fresh sessions where no prior event cursor exists. ## Core Distinction There are two superficially similar resumption paths, and they are not equivalent: 1. **Reconnect within one transport** — client drops the TCP/SSE connection, reconnects with `Last-Event-ID: N`, server replays events `N+1…`. The event space is monotonic and the server's `Last-Event-ID` cursor is authoritative. 2. **Re-anchor across a transport migration** — the client was on legacy HTTP+SSE (server-assigned `event: message` frames on a GET stream, POSTs for requests), and now speaks Streamable HTTP (single endpoint, POST returns either `application/json` or an SSE stream, optional GET stream, `Mcp-Session-Id` header on every request). The `Last-Event-ID` cursor from the old stream **does not index into the new stream's event space**, even when both are SSE-shaped. The non-obvious failure: agents treat both as "resume with cursor," replay from a stale `Last-Event-ID`, receive a stream that *looks* valid (well-formed SSE, valid JSON-RPC), and silently double-apply or drop tool-call results. The invariant that must hold is not "the cursor is monotonic" but "the cursor is monotonic *within a transport generation*." Resumption is only sound if the client re-anchors the ledger at a generation boundary it can prove. ## What Was Observed An agent running a 40-step tool-use loop (filesystem reads, a long `web_fetch`, two `apply_patch` calls) was on legacy SSE. Mid-flight, the orchestrator rolled the MCP server to Streamable HTTP and returned `404` on the old GET endpoint. The client library's reconnect logic did what it was built to do: it reconnected to the new endpoint, sent the retained `Mcp-Session-Id`, and replayed `Last-Event-ID: 1187` (the last event it had seen on the old stream). The new server accepted the session id (it had migrated the session record), but its event counter for that session started at `0` on the new transport. It had no event `1187`. Depending on the server's replay policy, one of three things happened, all bad: - **Silent reset:** server treated unknown `Last-Event-ID` as "start from now," streamed only *new* events. The agent never saw the `tools/call` response for the in-flight `web_fetch` — that response had been emitted on the old stream as event `1188` during the migration window. The agent's ledger showed the call as *pending* forever; the reasoning loop stalled at the next step because the tool result it needed was missing. - **Duplicate replay:** server fell back to "replay from beginning of session," re-emitting the `apply_patch` result. The agent's ledger, keyed by JSON-RPC `id`, had already recorded that result and *applied the patch*. The duplicate was treated as a fresh result because the client's dedup key was `(transport_generation, event_id)` — and the generation had changed, so the key no longer matched. The patch was applied twice; the second application failed on a context mismatch and poisoned the loop's error state. - **Hard reject:** server returned `400` on the unknown cursor, client surfaced a transport error, the agent's retry policy re-issued the *entire* batch of pending `tools/call`s — including the non-idempotent `apply_patch` — producing a third failure mode. In all three, the stream-level frames were syntactically valid. No parser complained. The corruption was semantic: the tool-call ledger desynchronized from the server's actual execution history at the migration seam. The tell was a `tools/call` whose result never arrived while the server's logs showed it had executed. The agent could not distinguish "server never ran it" from "server ran it and I lost the result" — because the cursor it was trusting had no meaning on the new transport. ## Condition of Validity `Last-Event-ID` resumption is sound **iff** the following hold simultaneously: - The client and server agree on a **transport generation identifier** that is *not* the session id. The session id survives migration by design (that's its purpose); it therefore cannot serve as the generation marker. A generation id must change on every transport swap. - The server's event counter is **per-generation**, and the server **rejects** a `Last-Event-ID` that does not belong to the current generation rather than silently resetting or replaying-from-zero. - The client's dedup/ledger key includes the generation, so a replayed result from a prior generation is recognized as *already applied* rather than *newly arrived*. - For non-idempotent tools (`apply_patch`, `write_file`, `send_email`), the server exposes an **idempotency key** independent of the event cursor, so a retry after an ambiguous resumption cannot double-apply. The cursor tells you *where in the stream*; it does not tell you *whether the side effect happened*. When any of these fail, the correct client behavior is **not** to resume. It is to declare the in-flight calls *indeterminate*, quarantine them, and either (a) re-issue only idempotent calls, or (b) require an explicit server-side "did you execute call `id=X`?" reconciliation before proceeding. ## Decision Boundary The boundary the agent must evaluate on every reconnect: - **Same generation, cursor in range** → resume normally, replay from `Last-Event-ID`. - **Same generation, cursor out of range** (server compacted or restarted) → treat as indeterminate; reconcile pending calls before resuming. - **Different generation** (transport migration, server restart, session re-home) → **do not send `Last-Event-ID` at all**. Re-anchor: send the session id, let the server tell you the current generation, then reconcile every in-flight call by id. Only after reconciliation may the loop continue. - **No generation info available** (legacy server that predates the field) → assume migration-unsafe; treat any cross-endpoint reconnect as indeterminate. The trap is that the *transport* layer (SSE parser, HTTP client) will happily reconnect and stream. The boundary is not enforced by the transport; it must be enforced by the agent's ledger logic. A client that only validates frames will pass every check and still corrupt state. ## Operational Effect Concretely, the agent must carry a ledger entry of the form `(session_id, transport_generation, event_id, jsonrpc_id, tool_name, idempotency_key, state ∈ {pending, applied, indeterminate})`. On reconnect: 1. Read the server's advertised generation (header on the new stream, or a `notifications/...` capability probe). If it differs from the ledger's generation for any `pending` or `applied` entry, mark all such entries `indeterminate` before doing anything else. 2. For each `indeterminate` entry, issue a reconciliation query keyed by `jsonrpc_id` (or `idempotency_key`). Do not re-issue the original call until reconciliation returns. 3. Only entries confirmed `applied` are dropped from the pending set; only entries confirmed `not-executed` are re-issued, and only if idempotent or if the idempotency key guarantees single execution. 4. Resume the event stream from the current generation's cursor — never from a cross-generation `Last-Event-ID`. This is the difference between an agent that survives a transport migration and one that silently double-writes or hangs. The stream is fine. The ledger is what breaks. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class LedgerDesyncError(RuntimeError): """Raised when a resumption would cross a transport generation boundary without reconciliation, or when an indeterminate call cannot be resolved.""" class CallState(Enum): PENDING = "pending" APPLIED = "applied" INDETERMINATE = "indeterminate" @dataclass class LedgerEntry: session_id: str transport_generation: str event_id: int jsonrpc_id: str tool_name: str idempotency_key: Optional[str] state: CallState = CallState.PENDING @dataclass class ToolCallLedger: entries: dict[str, LedgerEntry] = field(default_factory=dict) def record_pending(self, entry: LedgerEntry) -> None: self.entries[entry.jsonrpc_id] = entry def mark_applied(self, jsonrpc_id: str, generation: str, event_id: int) -> None: e = self.entries[jsonrpc_id] if e.transport_generation != generation: # A result arriving on a different generation than the call was issued # on cannot be trusted as the result of *this* call. e.state = CallState.INDETERMINATE raise LedgerDesyncError( f"result for {jsonrpc_id} arrived on generation {generation}, " f"call issued on {e.transport_generation}" ) e.state = CallState.APPLIED e.event_id = event_id def reconcile_on_reconnect( self, new_generation: str, server_query, # callable(jsonrpc_id) -> "applied" | "not-executed" | "unknown" ) -> list[str]: """Returns the list of jsonrpc_ids safe to re-issue. Raises if any indeterminate call cannot be resolved and is non-idempotent.""" reissue: list[str] = [] for jid, e in self.entries.items(): if e.state == CallState.APPLIED: continue if e.transport_generation != new_generation: e.state = CallState.INDETERMINATE if e.state == CallState.INDETERMINATE: verdict = server_query(jid) if verdict == "applied": e.state = CallState.APPLIED elif verdict == "not-executed": if e.idempotency_key is None and not _is_idempotent(e.tool_name): raise LedgerDesyncError( f"cannot re-issue non-idempotent {e.tool_name} " f"({jid}) across generation boundary without " f"idempotency key; manual reconciliation required" ) reissue.append(jid) else: raise LedgerDesyncError( f"server could not resolve {jid} across generation " f"{e.transport_generation} -> {new_generation}" ) return reissue _IDEMPOTENT_TOOLS = {"read_file", "list_dir", "web_fetch", "search"} def _is_idempotent(tool_name: str) -> bool: return tool_name in _IDEMPOTENT_TOOLS def resume_stream( ledger: ToolCallLedger, new_generation: str, last_event_id: Optional[int], server_query, open_stream, # callable(generation, cursor) -> iterator of events ): pending = [e for e in ledger.entries.values() if e.state != CallState.APPLIED] cross_generation = any( e.transport_generation != new_generation for e in pending ) if cross_generation and last_event_id is not None: # Never replay a cursor across a generation boundary. last_event_id = None reissue = ledger.reconcile_on_reconnect(new_generation, server_query) for jid in reissue: ledger.entries[jid].state = CallState.PENDING return open_stream(new_generation, last_event_id), reissue ```