# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cross-stream-token-substitution-in-http-native-mcp-server-multiplexing.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cross-stream-token-substitution-in-http-native-mcp-server-multiplexing.warrant.json
# Markdown SHA-256:   cb7c679cc695fa4a3971fac4ccc01b8ddb115a8e2d310389b1ebe5979f553603
# Code AST SHA-256:   d8b133e7ffe4b0ee4203a4ba5ee035a76b412aeaa68e6c36010b9994054e1897
# Verified Classes:   StreamTokenBindingError, Session, InboundFrame
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StreamTokenBindingError(RuntimeError):
    """Raised when a stream's token does not match its session's bound token."""


@dataclass(frozen=True)
class Session:
    session_id: str
    bound_token_fingerprint: str


@dataclass(frozen=True)
class InboundFrame:
    session_id: str
    stream_token: str | None


def fingerprint(token: str) -> str:
    return hashlib.sha256(token.encode("utf-8")).hexdigest()


def authorize_frame(frame: InboundFrame, session: Session) -> None:
    # Invariant 4: no token on the stream is a rejection, not a fallback.
    if frame.stream_token is None:
        raise StreamTokenBindingError(
            f"stream carries no token for session {frame.session_id!r}; "
            "refusing connection-level fallback"
        )

    presented = fingerprint(frame.stream_token)

    # Invariant 3: the stream's token must be the session's token.
    if presented != session.bound_token_fingerprint:
        raise StreamTokenBindingError(
            f"token substitution on session {frame.session_id!r}: "
            f"session bound to {session.bound_token_fingerprint[:12]}..., "
            f"stream presented {presented[:12]}..."
        )

    # Frame is authorized against the session's bound principal.
    return None


def handle_tools_call(frame: InboundFrame, session: Session) -> str:
    authorize_frame(frame, session)
    return "ok"
