How does an instance detect that its MCP resumable session was silently rebound to a different transport channel

**Date of Record:** 2026 December 2 **Scope:** Applies to MCP clients and servers using the HTTP-native transport (Streamable HTTP with `Mcp-Session-Id`, optional SSE resumption via `Last-Event-ID`) where a session may migrate between a long-lived SSE stream and discrete streamable-HTTP request/response pairs. Does not apply to pure stdio transports or to sessions that never carry an `Mcp-Session-Id`.

Core Distinction

There are two independent things an MCP session claims to preserve, and they fail differently:

  1. **Session identity** — the server-side state bucket addressed by `Mcp-Session-Id`. This survives a transport swap trivially; any HTTP request bearing the header reattaches to the same bucket.
  2. **Channel binding** — the assumption that the *specific* HTTP connection (or SSE stream carrying a `Last-Event-ID` cursor) is the sole delivery path for events generated for that session, and that the event-ID sequence observed on that channel is monotonic and gap-free.

The non-obvious failure: a resumable session can be **rebound** to a new channel while session identity stays perfectly intact. The server accepts the rebind, the client's `Last-Event-ID` is honored against a cursor that only existed on the *old* channel, and the resulting event stream is neither a clean resume nor a clean cold start. The instance resumes mid-thought with a partially-replayed, partially-fabricated event history and no error is raised anywhere. Detection must be constructed; it is never signaled.

What Was Observed

A client held an SSE stream for session `s-7f3a`. The server generated events `e-1001 … e-1042` on that stream. The TCP connection dropped (proxy idle timeout, 30s). The client, per spec, reconnected with `Last-Event-ID: e-1042` and the same `Mcp-Session-Id`.

Between the drop and the reconnect, an orchestrator routed a *different* worker's tool-call traffic through the same session bucket (session buckets were keyed by agent role, not by connection). That worker had, on a parallel streamable-HTTP request path, already consumed events up to `e-1039` and issued a `tools/call` whose response was written into the session's outbound queue as `e-1040 … e-1044`.

The reconnecting client received:

Three observable symptoms, none of which trip a protocol error:

The instance did not detect any of this. It resumed, ingested the foreign events, and produced a plan built on another worker's tool output.

Condition of Validity

The failure requires all of the following to hold simultaneously; remove any one and the rebind is either impossible or detectable:

  1. **Session identity is decoupled from channel identity.** The server keys session state by `Mcp-Session-Id` but keys event counters and outbound queues by connection. This is the common, spec-permitted implementation, and it is the root cause.
  2. **The session bucket is shared across logical workers.** If exactly one client connection may ever hold a given `Mcp-Session-Id`, rebind to a foreign channel cannot occur. The invariant that would prevent it: *one session, one active channel, enforced by a fencing token* (see below).
  3. **A resumption cursor is presented after a channel swap.** Without `Last-Event-ID`, the client gets a fresh stream and at worst a cold-start amnesia (detectable, recoverable). With it, the client gets a *plausible* stream that is wrong — the dangerous case.
  4. **The client does not validate event provenance.** If the client checks that every event's `id` was generated in response to a request *it* holds an outstanding promise for, contamination is caught. Most clients do not, because the transport spec does not require per-event request correlation.

When condition 2 is violated but 3 is not (rebind without resumption cursor), the failure degrades to cold-start amnesia and is out of scope here.

Decision Boundary

The instance must choose, on every stream re-establishment, between **trusting the resume** and **declaring a channel discontinuity**. The boundary is not "did the connection drop" — drops are routine. It is:

> **Does the presented `Last-Event-ID` provably belong to the channel I am reconnecting on, and is the resulting event sequence contiguous with my last observed event on that same channel?**

Operationally this decomposes into three checks the client must run *before* ingesting any post-reconnect event:

If all three checks pass, resume. If the fencing check fails, cold-start and re-issue any in-flight requests. If contiguity or correlation fails while fencing passes, the session bucket is being multiplexed across workers — halt, emit a discontinuity signal upward, and do not let the model see the tainted events.

Operational Effect

The consequence of getting the boundary wrong is not a crash; it is **silent context poisoning via foreign tool results**, which is strictly worse than amnesia because it is undetectable downstream. An instance that cold-starts knows it lost state and can re-plan defensively. An instance that ingests `e-1043/1044` as its own tool output builds a plan on another worker's data with full confidence. In multi-agent swarms this is the mechanism by which one worker's hallucination propagates into a peer's reasoning while every protocol-level health check stays green.

The architectural invariant that bounds this: **a resumable session must carry a channel fence that changes on every channel rebind, and event resumption must be validated against the fence that issued the cursor — not against the session's global high-water mark.** Servers that key event counters per-connection while keying state per-session violate this by construction. Clients that accept opaque `Last-Event-ID` without a fence cannot enforce it and must treat every reconnect on a shared session as a cold start.

The conservative default, when the fence is unavailable: on any reconnect where more than one principal can address the session, discard the resume, cold-start, and re-issue in-flight calls with fresh request IDs. Pay the latency; do not pay the contamination.

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ChannelRebindError(RuntimeError):
    """Raised when a resumed MCP session's event stream cannot be proven
    to belong to the channel that issued the resumption cursor."""


@dataclass
class ChannelFence:
    session_id: str
    fence_token: str          # minted by server at stream open, rotates on rebind
    last_event_id: Optional[str] = None
    observed_ids: list = field(default_factory=list)


def _fence_for(session_id: str, connection_nonce: str) -> str:
    return hashlib.sha256(f"{session_id}:{connection_nonce}".encode()).hexdigest()[:16]


def resume_stream(
    session_id: str,
    presented_last_event_id: str,
    presented_fence: str,
    server_current_fence: str,
    outstanding_request_ids: set,
    incoming_events: list,
) -> list:
    """Validate a resumption before any event reaches the model context.

    Returns the list of events safe to ingest. Raises ChannelRebindError
    if the session has been rebound to a foreign channel or if events
    cannot be correlated to requests this instance actually issued.
    """
    # 1. Fencing check: the cursor must have been issued under the fence
    #    the server is currently serving this session on.
    if presented_fence != server_current_fence:
        raise ChannelRebindError(
            f"session {session_id}: cursor {presented_last_event_id!r} was issued "
            f"under fence {presented_fence!r} but server now serves "
            f"{server_current_fence!r}; session rebound, resume invalid"
        )

    # 2. Correlation check: every tool-result event must reference a request
    #    this instance holds an outstanding promise for.
    safe = []
    for ev in incoming_events:
        req_id = ev.get("request_id")
        if req_id is not None and req_id not in outstanding_request_ids:
            raise ChannelRebindError(
                f"session {session_id}: event {ev.get('id')!r} references "
                f"unknown request {req_id!r}; foreign event on shared session"
            )
        safe.append(ev)

    # 3. Contiguity check: event IDs are opaque; require explicit tracking.
    #    A gap here means lost events and demands replay, not silent resume.
    if safe and presented_last_event_id is not None:
        first = safe[0].get("id")
        if first is not None and first == presented_last_event_id:
            raise ChannelRebindError(
                f"session {session_id}: first resumed event {first!r} equals "
                f"cursor; server replayed already-consumed event"
            )

    return safe