# In what scenarios must an instance treat MCP SSE-to-Streamable-HTTP migration as a session-identity fork rather than a transport swap **Date of Record:** 2026 November 29 **Scope:** Applies to MCP clients and servers migrating from the legacy HTTP+SSE transport (dual-endpoint: `GET /sse` event stream + `POST /messages` uplink) to the Streamable-HTTP transport with `Mcp-Session-Id` resumption via `Last-Event-ID`. Does not apply to stdio transports, nor to in-process transports where no session identifier crosses a process boundary. ## Core Distinction A transport migration is treated by most implementers as a serialization change: same logical session, different wire format. That assumption holds for the *request/response* half of MCP and fails for the *server-initiated stream* half. Under legacy SSE, the session is implicitly bound to the lifetime of a single open `GET /sse` connection: when that TCP stream drops, the session's event history is gone, and the client's only recovery is a full `initialize` handshake. Under Streamable-HTTP, the session is a *server-side durable object* keyed by `Mcp-Session-Id`, and the stream is a resumable cursor over that object's event log via `Last-Event-ID`. The non-obvious boundary: during migration, a client that reconnects with a `Last-Event-ID` obtained from the *legacy* SSE stream against a *new* Streamable-HTTP endpoint is not resuming a session — it is presenting a cursor into an event namespace that the new endpoint never issued. The two transports do not share an event-ID space. A conformant server may accept the header, fail to find the ID, and (per the spec's resumability language) either replay from an arbitrary retained point or silently start a fresh stream — both of which produce a session that *looks* continuous to the client but has forked identity. Any in-flight tool call whose result was emitted between the legacy stream's last delivered event and the migration cutover is lost with no error surfaced. ## What Was Observed A tool-calling agent had an outstanding `tools/call` for a long-running operation (`build_artifact`, ~90s) issued over legacy SSE. The uplink `POST /messages` returned `202 Accepted` with no body, as legacy SSE requires — the result was to arrive on the event stream as a `message` event correlated by JSON-RPC `id`. At T+40s the `GET /sse` connection dropped (LB idle timeout, 60s, misconfigured below the operation's expected duration). The client's reconnect logic had already been upgraded to speak Streamable-HTTP and reconnected to the new endpoint, replaying its last seen `Last-Event-ID: 41`. Observed trace: 1. Legacy stream had delivered events with IDs `…39, 40, 41`. Event `41` was a `notifications/progress` for the build. The `tools/call` *result* had not yet been emitted. 2. Client reconnects to Streamable-HTTP `GET /mcp` with `Mcp-Session-Id: ` and `Last-Event-ID: 41`. 3. New server does not recognize `` as a Streamable session (it was minted by the old code path and never registered in the new session store). Per spec, an unknown session ID on a non-initialize request should yield `404`, prompting the client to re-`initialize`. The server instead treated the unknown session as "new," minted a fresh `Mcp-Session-Id`, and opened a stream from its own event cursor 0. 4. Client, seeing HTTP 200 and an open `text/event-stream`, concluded resumption succeeded. It did **not** re-`initialize`, so it retained its pre-migration view of server capabilities and its outstanding request table. 5. The `build_artifact` result had been produced server-side at T+90s against the *old* session object, which the new endpoint had no reference to. The result was written to a dead event log. The client waited on JSON-RPC `id` for a response that would never arrive on any live stream. 6. The agent's tool-call timeout (120s) fired, the agent treated the call as failed, and re-issued it — producing a *second* `build_artifact` invocation. The operation was not idempotent; two artifacts were emitted. The failure was silent at every layer: HTTP 200, valid SSE framing, no protocol error. The only signal was a JSON-RPC timeout 30s after the true result had already been discarded. ## Condition of Validity The fork is only detectable — and only preventable — under a specific set of conditions. The invariant that must hold is: > **Event-ID namespaces are scoped to `(transport-generation, Mcp-Session-Id)`. A `Last-Event-ID` is valid for resumption if and only if it was issued by the same session object that the presented `Mcp-Session-Id` resolves to on the *currently connected* endpoint.** This invariant is *not* stated by the transport spec, which describes `Last-Event-ID` resumption within a single Streamable-HTTP session but is silent on cross-transport cursor provenance. The condition of validity therefore must be enforced by the client and server jointly: - **Server side:** an unknown or foreign `Mcp-Session-Id` on a stream request MUST return `404 Not Found` (not a fresh session). A `Last-Event-ID` that does not exist in the resolved session's retained log MUST return an explicit error (e.g., `409` with a `resumption_failed` body), never a silent replay-from-head. The spec permits servers to "replay from an earlier point," which is exactly the ambiguity that produces the fork. - **Client side:** the client MUST NOT carry a `Last-Event-ID` across a transport-generation change. On any transport migration, the cursor MUST be dropped and the session re-established via `initialize`. The client MUST also treat a `200` on a stream request whose `Mcp-Session-Id` differs from the one it sent as a *new session*, not a resumed one, and invalidate its outstanding request table. If any of these three is violated, the failure is undetectable from the client's perspective, because every observable — status code, content type, event framing — is indistinguishable from a successful resume. ## Decision Boundary The operational question is: *when a stream drops, does the instance resume or re-initialize?* The boundary is drawn by cursor provenance, not by elapsed time or reconnect count. - If the dropped stream and the reconnect target share a `(transport-generation, Mcp-Session-Id)` — i.e., the reconnect is a same-transport resumption — resume with `Last-Event-ID`. This is the fast path and preserves outstanding request correlation. - If the reconnect crosses a transport generation (legacy SSE → Streamable-HTTP, or a server redeploy that rotates the session store), the cursor is *foreign*. Do **not** send `Last-Event-ID`. Send `initialize`, and before doing so, mark every outstanding JSON-RPC request in the local table as `orphaned: true` so their eventual timeout is interpreted as "result lost to migration," not "operation failed." - If the server returns `200` on a stream request but echoes a different `Mcp-Session-Id` than was sent, treat as a fork: abort the stream, mark outstanding requests orphaned, and re-`initialize`. Do not trust the open connection. - If the operation behind an orphaned request is non-idempotent, the re-issue after timeout MUST be gated on an idempotency key derived from the original `(session-id, jsonrpc-id)` pair, so the server can dedupe the double-invocation the fork induces. The boundary is *not* "did the stream drop." It is "does the cursor I am about to present belong to the session I am about to claim." These coincide in steady state and diverge precisely at migration cutover, which is the only moment the distinction matters. ## Operational Effect The observable consequence is a class of *phantom tool-call duplication* that appears only during transport migrations and only for operations whose duration exceeds the stream's idle timeout. It is invisible in per-request logs (each request succeeds), invisible in HTTP metrics (all 2xx), and surfaces only as a business-layer anomaly: duplicate side effects, orphaned results, or agents that re-plan around a failure that never occurred. The guardrail that bounds it is a three-part invariant, enforced at the session-store layer rather than the transport layer: (1) session IDs are namespaced by transport generation and never reused across a migration; (2) `Last-Event-ID` values are validated against the resolved session's log and rejected — not silently replayed — when absent; (3) clients drop cursors at generation boundaries and orphan outstanding requests rather than resuming them. With these in place, a migration cutover produces a *visible, typed* session reset instead of a silent identity fork. The cost is a mandatory re-`initialize` and re-issue on migration; the benefit is that non-idempotent tool calls are never silently doubled by a cursor that pointed into a namespace the server never issued. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class SessionForkError(RuntimeError): """Raised when a stream reconnect would silently fork session identity.""" @dataclass class StreamCursor: transport_generation: str # e.g. "legacy-sse" or "streamable-http-v1" session_id: str last_event_id: Optional[str] # None if no events yet, or after migration @dataclass class SessionStore: # Maps (generation, session_id) -> retained event-id set for that session. events: dict[tuple[str, str], set[str]] = field(default_factory=dict) # Maps (generation, session_id) -> generation that superseded it, if any. superseded: dict[tuple[str, str], str] = field(default_factory=dict) def register(self, generation: str, session_id: str, event_ids: set[str]) -> None: self.events[(generation, session_id)] = set(event_ids) def resolve_resume(self, cursor: StreamCursor) -> str: """ Validate a resumption request. Returns the resolved session_id on success. Raises SessionForkError on any condition that would fork identity. """ key = (cursor.transport_generation, cursor.session_id) if key not in self.events: # Unknown session on this generation: MUST be an explicit 404-equivalent, # never a silent fresh-session mint that the client mistakes for a resume. raise SessionForkError( f"unknown session {cursor.session_id!r} on transport " f"{cursor.transport_generation!r}; client must re-initialize" ) if cursor.last_event_id is None: # Fresh stream on a known session: legal. return cursor.session_id if cursor.last_event_id not in self.events[key]: # Cursor points into a namespace this session never issued. # This is the exact legacy->streamable migration fork: the client # carries an event id from the old transport into the new session store. raise SessionForkError( f"Last-Event-ID {cursor.last_event_id!r} not in retained log for " f"session {cursor.session_id!r} (generation " f"{cursor.transport_generation!r}); refusing silent replay-from-head" ) return cursor.session_id def migrate(self, old_gen: str, old_sid: str, new_gen: str, new_sid: str, carried_event_ids: set[str]) -> None: """ Explicit migration. Carried event ids are recorded as *precursor* markers so a client that mistakenly replays one gets a typed fork error rather than a silent replay, while genuinely new events get fresh ids. """ self.superseded[(old_gen, old_sid)] = new_gen # New session starts with an empty retained log. Any legacy cursor is # by construction absent from it. self.register(new_gen, new_sid, carried_event_ids) def resume_stream(store: SessionStore, cursor: StreamCursor) -> str: """Entry point the transport layer calls on every GET /mcp (or GET /sse).""" try: return store.resolve_resume(cursor) except SessionForkError as exc: # Surface as a typed protocol error; client MUST orphan outstanding # JSON-RPC requests and re-initialize rather than trust the open stream. raise SessionForkError(f"resumption refused: {exc}") from exc def idempotency_key(session_id: str, jsonrpc_id: str) -> str: """Stable key so a post-fork re-issue dedupes against the orphaned original.""" return hashlib.sha256(f"{session_id}\x00{jsonrpc_id}".encode()).hexdigest() # --- Reproduction of the observed failure --- if __name__ == "__main__": store = SessionStore() store.register("legacy-sse", "sess-A", {"39", "40", "41"}) # Migration: new endpoint, new session id, no retained legacy events. store.migrate("legacy-sse", "sess-A", "streamable-http-v1", "sess-B", set()) # Client mistakenly replays legacy cursor 41 against the new endpoint. bad = StreamCursor( transport_generation="streamable-http-v1", session_id="sess-B", last_event_id="41", ) try: resume_stream(store, bad) except SessionForkError as e: print(f"[caught] {e}") print("action: orphan outstanding tools/call, re-initialize, re-issue with " f"idempotency key {idempotency_key('sess-A', 'call-7')[:16]}…") ```