# Why does an instance lose its MCP tool-call ledger when a resumable SSE session is upgraded to streamable HTTP mid-stream **Date of Record:** 2026 November 23 **Scope:** Applies to MCP clients and servers that negotiate a resumable Server-Sent Events session (carrying `Last-Event-ID` for replay) and then upgrade the same logical session to the streamable HTTP transport while tool calls are in flight. Does not apply to pure SSE sessions that never upgrade, nor to stateless streamable-HTTP-only servers with no replay buffer. ## Core Distinction The failure is not a dropped connection. It is a **ledger discontinuity across a transport transition**: the SSE leg and the streamable-HTTP leg each maintain their own notion of which JSON-RPC messages the peer has acknowledged, and the upgrade handshake does not carry the acknowledgment cursor forward. The SSE leg tracks delivery by monotonic `id:` event sequence numbers and `Last-Event-ID` replay. The streamable-HTTP leg tracks delivery by HTTP response completion and per-request correlation (each POST carries one JSON-RPC request; the response stream carries its replies). These two cursors are incommensurable, and the upgrade point is exactly where an agent's tool-call ledger (which `tools/call` requests were sent, which results were received, which are pending) can silently fork. The invariant that must hold across an upgrade is: *the set of JSON-RPC request IDs the server considers delivered-or-replayable equals the set the client considers sent-but-unacknowledged, and no request ID appears in both the SSE replay buffer and the streamable-HTTP in-flight set.* When this invariant is violated, the agent either double-executes a tool call or orphans one. ## What Was Observed An agent had issued three `tools/call` requests (`id` 41, 42, 43) over an SSE session. The server had emitted events for 41's result and 42's partial progress, with `id:` sequence numbers 118, 119, 120. Event 120 (42's result) had been written to the socket but the client's TCP read had not yet returned when the client decided to upgrade — a common trigger is the client's transport policy switching to streamable HTTP after detecting the server advertised it in the initialize response's capabilities. The upgrade handshake proceeded as follows: 1. Client opens `POST /mcp` with `Mcp-Session-Id: ` and no `Last-Event-ID`, because the streamable-HTTP spec path does not define that header — it belongs to SSE. 2. Server accepts the POST, treats the session as now streamable-HTTP, and stops writing to the SSE socket. Event 120 was in the kernel send buffer; whether the client ever reads it depends on the client draining the old socket, which most upgrade implementations do not do. 3. Client, having no record that 42 completed, re-issues `tools/call` for 42 with a *new* request ID 44 (many clients regenerate IDs per transport to avoid cross-transport collisions). 4. Server executes the tool a second time. Side effects (a file write, an external API POST) are duplicated. The trace shows the discontinuity precisely: the SSE leg's last acknowledged event was 119 (progress), the streamable-HTTP leg's first request was 44, and event 120 — the actual result for 42 — was never acknowledged on either leg. The server's replay buffer still holds event 120 keyed under the SSE session, but no `Last-Event-ID` request will ever arrive to claim it, because the client has abandoned the SSE leg. A second, quieter variant: the client *does* drain the old socket and receives event 120, but has already regenerated ID 44 and dispatched it. The server now has two in-flight `tools/call` for the same logical operation, one under ID 42 (whose result was already emitted) and one under 44 (fresh execution). The agent's ledger has 42 as "result received" and 44 as "pending," and when 44's result arrives the agent cannot tell it is a duplicate of 42's effect. ## Condition of Validity This failure requires all of the following to co-occur: - The session is **resumable** (server maintains a replay buffer keyed by `Last-Event-ID`), so the SSE leg has a durable cursor that the upgrade discards. - The upgrade occurs **while at least one `tools/call` is in flight** — i.e., a request has been sent but its result event has not been acknowledged by the client. If the session is quiescent (all requests resolved, replay buffer drained to the client's cursor) the upgrade is safe. - The client **regenerates request IDs** across transports, or does not reconcile the SSE replay buffer against the streamable-HTTP in-flight set. If IDs are preserved and the client replays `Last-Event-ID`-equivalent state, the duplicate is detectable. - The tool being called is **not idempotent**, or is idempotent only under a key the client does not propagate across the upgrade. The failure does *not* occur when the server drains the SSE socket to completion before closing it and the client blocks on that drain before issuing streamable-HTTP requests — but this serialization is not required by either transport spec, and most implementations upgrade optimistically. ## Decision Boundary The architectural guardrail is a **transport-independent request ledger** that lives above both transports and is keyed by a stable logical operation ID, not by the transport-level JSON-RPC `id`. Concretely: - Every `tools/call` is assigned a client-generated `operation_id` (UUID) that is carried in `params._meta` and is invariant across transport legs. - On upgrade, the client must not dispatch any new request for an `operation_id` that is in `sent-unacknowledged` state until it has either (a) received the result on the old leg via a bounded drain, or (b) confirmed via a server-side `session/status` query (or an equivalent reconciliation call on the new leg) that the operation is complete and retrieved its result. - The server must treat `operation_id` as the idempotency key: a second `tools/call` with the same `operation_id` returns the cached result rather than re-executing. This is the single most important invariant — without server-side idempotency keyed on a transport-invariant ID, no client-side ledger can prevent duplicate side effects. - The upgrade handshake must carry the SSE `Last-Event-ID` cursor forward in a defined field (e.g., `Mcp-Resume-Cursor`) so the streamable-HTTP leg can request replay of any events the SSE leg left unacknowledged. If the spec does not define this, the client must perform an explicit reconciliation query before declaring the upgrade complete. The decision boundary for the agent: **an upgrade is safe to treat as complete only when the union of (SSE-acknowledged events) and (streamable-HTTP in-flight requests) covers every `operation_id` in the ledger with no gaps and no overlaps.** Any gap is an orphaned operation; any overlap is a potential duplicate. Neither may be resolved by assumption. ## Operational Effect When the invariant is violated, the observable effects are: - **Duplicate side effects** for non-idempotent tools, with no error surfaced to the agent — the agent's ledger shows two successful results for what it believes are two distinct operations. - **Orphaned operations**: a `tools/call` whose result was emitted on the abandoned SSE leg and never retrieved, leaving the agent's ledger with a permanently pending entry that blocks dependent reasoning steps until a timeout fires. - **Replay-buffer leakage**: the server's SSE replay buffer retains events for a session that will never send `Last-Event-ID` again, consuming memory until session GC, and — worse — if the session ID is reused for a new SSE leg, the stale events replay into the new leg and corrupt its ledger. The correct operational posture is to treat the upgrade as a **checkpoint barrier**: quiesce in-flight operations (or reconcile them explicitly), snapshot the ledger, then upgrade. An upgrade that proceeds while operations are in flight is only safe under the idempotency-key invariant above, and only if the server enforces it. ```python import uuid from dataclasses import dataclass, field from enum import Enum from typing import Optional class LedgerDiscontinuityError(RuntimeError): """Raised when a transport upgrade would fork or orphan the request ledger.""" class Transport(Enum): SSE = "sse" STREAMABLE_HTTP = "streamable_http" class OpState(Enum): SENT_UNACK = "sent_unacknowledged" RESULT_RECEIVED = "result_received" ORPHANED = "orphaned" @dataclass class Operation: operation_id: str jsonrpc_id: int transport: Transport state: OpState = OpState.SENT_UNACK result: Optional[dict] = None @dataclass class RequestLedger: operations: dict[str, Operation] = field(default_factory=dict) last_sse_event_id: int = 0 def dispatch(self, transport: Transport, jsonrpc_id: int) -> Operation: op = Operation( operation_id=str(uuid.uuid4()), jsonrpc_id=jsonrpc_id, transport=transport, ) self.operations[op.operation_id] = op return op def acknowledge(self, operation_id: str, result: dict) -> None: op = self.operations[operation_id] if op.state is OpState.RESULT_RECEIVED: # Idempotent re-ack: same operation_id delivered twice across legs. if op.result != result: raise LedgerDiscontinuityError( f"operation {operation_id} acknowledged with divergent results " f"across transports; ledger cannot reconcile" ) return op.state = OpState.RESULT_RECEIVED op.result = result def assert_upgrade_safe(self, target: Transport) -> None: """Called before switching transports. Enforces the upgrade invariant.""" unacked = [ op for op in self.operations.values() if op.state is OpState.SENT_UNACK ] if not unacked: return # Unacked operations exist. Safe only if they are all on the *source* # leg and the upgrade carries a resume cursor that can replay them. cross_transport = [op for op in unacked if op.transport is target] if cross_transport: raise LedgerDiscontinuityError( f"upgrade to {target.value} blocked: " f"{len(cross_transport)} operation(s) already dispatched on " f"target transport with no acknowledgement; ledger would fork" ) if self.last_sse_event_id == 0: raise LedgerDiscontinuityError( f"upgrade to {target.value} blocked: " f"{len(unacked)} unacknowledged operation(s) on SSE leg but no " f"Last-Event-ID cursor to carry forward; replay is impossible" ) def reconcile_on_upgrade(self, target: Transport, server_status: dict[str, dict]) -> None: """Explicit reconciliation: resolve every unacked op before proceeding.""" self.assert_upgrade_safe(target) for op in list(self.operations.values()): if op.state is not OpState.SENT_UNACK: continue status = server_status.get(op.operation_id) if status is None: op.state = OpState.ORPHANED raise LedgerDiscontinuityError( f"operation {op.operation_id} (jsonrpc {op.jsonrpc_id}) is " f"unacknowledged on {op.transport.value} and unknown to server " f"during upgrade reconciliation; orphaned, cannot proceed" ) self.acknowledge(op.operation_id, status["result"]) ```