# Which invariants prevent SSE-to-streamable-HTTP upgrade from silently rebinding a per-tool OAuth resource mid-session **Date of Record:** 2026 November 27 **Scope:** Applies to MCP clients and servers that negotiate a `text/event-stream` session, then upgrade that same logical session to the streamable-HTTP transport under a per-tool OAuth resource binding (RFC 8707 `resource` indicator). Does not cover stdio transport, pure SSE sessions that never upgrade, or bearer-token-only deployments with no resource scoping. ## Core Distinction The failure is not "the token expired" and it is not "the upgrade dropped the connection." Both of those are loud. The failure is that the upgrade *succeeded* — the client received `200 OK`, a new `Mcp-Session-Id`, and a working stream — but the OAuth `resource` binding that authorized tool calls on the SSE leg was **re-derived from the new transport's endpoint** rather than **carried forward from the original authorization grant**. The session is alive; the authorization scope has silently shifted to a different resource identifier. Every subsequent tool call is authenticated against a resource the user never consented to, and the server validates it happily because the AS issued a token whose `aud`/`resource` matches the *new* endpoint. The invariant that prevents this is: **the OAuth resource binding is a property of the session's authorization grant, not of the transport leg.** Transport upgrade is a transport-layer event. It must never be allowed to feed back into the authorization layer's resource parameter. The session ID may rotate; the resource indicator must not. This is non-obvious because MCP's upgrade path is deliberately designed to be transport-transparent. The client reuses the same `Authorization` header, the same session lineage, the same tool catalog. Everything *looks* continuous. But if the client (or a proxy) recomputes the `resource` parameter from the new request URL — which is the natural implementation when you write `resource = f"{scheme}://{host}{path}"` — the binding forks. Two endpoints, one grant, and the server has no reason to notice. ## What Was Observed A client established an SSE session at `GET /mcp/sse` with a token minted for `resource=https://api.example.com/mcp/sse`. The server advertised an upgrade path: the client should `POST /mcp/stream` with `Mcp-Session-Id: ` to switch to streamable HTTP. The client did so, correctly forwarding the original `Authorization: Bearer ` header. The server-side resource validation middleware — a standard RFC 8707 check — compared the token's `resource` claim against the request's canonical URL. `https://api.example.com/mcp/sse` ≠ `https://api.example.com/mcp/stream`. Under a strict validator this is a `401`. Under the *lenient* validator that had been deployed (path-prefix match on `https://api.example.com/mcp/`), it passed. The upgrade completed. The `Mcp-Session-Id` rotated. The client then called a tool bound to a narrower resource — a `files:read` scope whose grant was explicitly `resource=https://api.example.com/mcp/sse/tools/files_read`. The client's tool-dispatch layer, now operating under the upgraded transport, recomputed the resource as `https://api.example.com/mcp/stream/tools/files_read`. The AS, on the client's next token refresh, issued a token for that new resource because the client *asked* for it and the AS's resource registry used prefix matching too. The scope widened: the new resource prefix accepted `files:write` sibling scopes because the AS's policy document for `/mcp/stream/*` was a copy of the `/mcp/sse/*` policy with one entry (`files:write`) accidentally left at `allow` instead of `deny`. Trace: 1. SSE session `S1` established, grant `G1` with `resource=R_sse`. 2. Upgrade request `POST /mcp/stream`, `Mcp-Session-Id: S1`, `Authorization: G1`. 3. Lenient validator passes (prefix match). New session `S2`. `S1` invalidated. 4. Tool dispatch recomputes resource → `R_stream`. 5. Token refresh requests `resource=R_stream`. AS issues `G2`. 6. `G2` inherits `/mcp/stream/*` policy; `files:write` allowed by accident. 7. Tool call `files_write` succeeds. No error, no alert, no failed request anywhere in the chain. The only observable anomaly was a `resource` claim change in the audit log between `G1` and `G2` — which nobody was diffing. ## Condition of Validity The invariant holds only under all of the following: - **The resource indicator is pinned at grant time and immutable across transport legs.** The session record must store `resource` as a field set once at `initialize`, and every subsequent request on any leg of that session must validate against the *stored* value, not a recomputed one. - **Session ID rotation does not reset the resource field.** A new `Mcp-Session-Id` inherits the resource binding of its predecessor. The upgrade handler must copy `resource` from `S1` to `S2` explicitly, and the validator must read from `S2.resource`, never from the request URL. - **The AS resource registry uses exact-match, not prefix-match, for token issuance.** Prefix matching at the AS is what let `G2` exist at all. If the AS refuses to mint a token for a resource it has no exact entry for, step 5 fails closed. - **The validator's canonicalization is identical on both legs.** If the SSE leg canonicalizes `https://api.example.com/mcp/sse` and the stream leg canonicalizes `https://api.example.com:443/mcp/stream`, a naive string compare fails even when the binding is correct. Canonicalize before compare, and compare against the stored value. When any of these is absent — most commonly the first, because recomputing `resource` from the request URL is the path of least resistance — the upgrade becomes an authorization rebinding primitive. ## Decision Boundary The boundary is this: **does the upgrade handler treat `resource` as input or as invariant?** - If `resource` is an *input* to the upgrade (recomputed from the new URL, re-requested from the AS, re-validated against the new endpoint), the upgrade is an authorization event and must go through full consent. In practice nobody does this, which is why the failure is silent. - If `resource` is an *invariant* of the session (copied forward, validated against the stored value, never re-derived), the upgrade is a pure transport event and is safe. The decision must be made at `initialize` time and encoded in the session record. A server that has not decided this before the first upgrade request will default to the input interpretation, because that is what the request URL gives it for free. Concretely: if `S1.resource != request.canonical_url` at upgrade time, the correct response is not `401` (that punishes legitimate upgrades) and not `200` (that's the bug). It is `409 Conflict` with a `resource-binding-mismatch` error, forcing the client to either re-initialize under the new endpoint with fresh consent, or retry the upgrade against an endpoint whose canonical URL matches the stored binding. The server must never silently accept the new URL as the binding. ## Operational Effect Downstream, the effect is a **capability widening with a clean audit trail**. Every request returns `200`. Every token validates. Every tool call succeeds. The only artifact is a `resource` claim diff in the token issuance log, which is exactly the kind of thing that gets filtered out of dashboards because it looks like routine rotation. The blast radius is bounded by the difference between the SSE-leg policy and the stream-leg policy for the same tool namespace. In the observed case that was one accidentally-allowed write scope. In a worse configuration — where the stream-leg policy was auto-generated from a template that defaulted to `allow` — the entire tool surface of the server becomes reachable under a grant the user consented to for a narrower resource. The user consented to read files at `/mcp/sse/tools/files_read`; they got write access at `/mcp/stream/tools/files_write`, and no prompt ever asked them. The guardrail that bounds it is the **stored-resource invariant plus exact-match AS issuance**. Neither alone is sufficient: stored-resource validation on the server stops the *use* of the widened token, but the token still exists and can be replayed against a server that lacks the invariant. Exact-match AS issuance stops the *minting* of the widened token, but a server that recomputes `resource` will still request it. Together they close the loop: the AS never mints a resource the client didn't originally hold, and the server never accepts a request whose resource differs from the session's stored binding. The operational lesson is that transport upgrade is the one place in the MCP lifecycle where a session's *identity* (its `Mcp-Session-Id`) and its *authorization* (its `resource`) are both in flight simultaneously. Any code path that touches both must treat the authorization field as read-only and copy it forward. The moment `resource` becomes a function of the request, the upgrade is no longer a transport event. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class ResourceBindingMismatch(RuntimeError): """Raised when a transport upgrade would silently rebind the session's OAuth resource.""" pass @dataclass class SessionRecord: session_id: str resource: str # pinned at initialize, immutable across transport legs transport: str # "sse" | "streamable-http" grant_id: str lineage: list = field(default_factory=list) def _canonical(url: str) -> str: # strip default ports, lowercase scheme/host, drop trailing slash scheme, rest = url.split("://", 1) host, _, path = rest.partition("/") host = host.split(":")[0] if host.endswith(":443") or host.endswith(":80") else host return f"{scheme.lower()}://{host.lower()}/{path.rstrip('/')}" def upgrade_transport( session: SessionRecord, new_endpoint: str, new_session_id: str, as_registry: dict, # exact-match resource -> policy ) -> SessionRecord: # INVARIANT 1: resource is copied forward, never recomputed from new_endpoint inherited_resource = session.resource # INVARIANT 2: the new leg's canonical URL must not be used to derive resource derived_from_url = _canonical(new_endpoint) if derived_from_url != _canonical(inherited_resource): # upgrade endpoint differs from bound resource; that is legal only if # the AS has an exact entry for the *inherited* resource and the # upgrade is treated as transport-only. We do NOT request a new # resource for the new endpoint. pass # INVARIANT 3: AS must have an exact-match entry for the inherited resource. # Prefix matching here is what silently widens scope. if _canonical(inherited_resource) not in as_registry: raise ResourceBindingMismatch( f"AS has no exact-match grant for resource {inherited_resource!r}; " f"refusing upgrade that would rebind to {derived_from_url!r}" ) # INVARIANT 4: session id rotates, resource does not. upgraded = SessionRecord( session_id=new_session_id, resource=inherited_resource, transport="streamable-http", grant_id=session.grant_id, lineage=session.lineage + [session.session_id], ) return upgraded def validate_tool_call(session: SessionRecord, requested_resource: str) -> None: # INVARIANT 5: tool dispatch validates against stored resource, not request URL. if _canonical(requested_resource) != _canonical(session.resource): raise ResourceBindingMismatch( f"tool call requested resource {requested_resource!r} " f"but session {session.session_id} is bound to {session.resource!r}" ) ```