# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-negotiate-its-oauth-2-1-resource-indicator-when-resuming-an-mcp-session-across-the-sse-to-streamable-http-transport-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-negotiate-its-oauth-2-1-resource-indicator-when-resuming-an-mcp-session-across-the-sse-to-streamable-http-transport-boundary.warrant.json
# Markdown SHA-256:   664044a988d0d6812aa8bb18c92d590c2f2d07e6241e99c4516fe27c3a77d7d8
# Code AST SHA-256:   7514c9dcec162d839d79ed4f8e27ed36e46556b24e1fee2c5531f07de75d4a01
# Verified Classes:   ResourceIndicatorMismatch, SessionBinding
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import dataclasses
from typing import Optional


class ResourceIndicatorMismatch(RuntimeError):
    """Raised when a session resume crosses a resource-indicator boundary
    without re-scoping the OAuth 2.1 token (RFC 8707)."""


@dataclasses.dataclass(frozen=True)
class SessionBinding:
    session_id: str
    resource_indicator: str  # canonical URI the token is audience-bound to
    access_token: str


def resume_session(
    binding: SessionBinding,
    redirect_target: str,
    token_resource_claim: str,
    handshake_returns_200: bool,
) -> SessionBinding:
    """
    Enforce the invariant: session continuity is (session_id, resource_indicator).
    A 200 from the resume handshake is necessary but NOT sufficient.
    """
    if not handshake_returns_200:
        raise ResourceIndicatorMismatch(
            f"resume handshake failed for session {binding.session_id!r}"
        )

    # The dangerous case: transport resumed cleanly, but the redirect target
    # changed the canonical resource URI relative to the token's audience.
    if redirect_target != token_resource_claim:
        raise ResourceIndicatorMismatch(
            "SSE->streamable-HTTP migration changed resource indicator: "
            f"token bound to {token_resource_claim!r}, "
            f"endpoint now serves {redirect_target!r}. "
            "Re-run OAuth 2.1 authorization-code flow with "
            f"resource={redirect_target!r} before reattaching "
            f"Mcp-Session-Id={binding.session_id!r}."
        )

    # Safe to reattach: audience matches, session buffer survived.
    return dataclasses.replace(binding, resource_indicator=redirect_target)


def guarded_tool_call(
    binding: SessionBinding,
    redirect_target: Optional[str],
    token_resource_claim: str,
) -> SessionBinding:
    """Resume-then-call path used by agents; refuses zombie-resume states."""
    if redirect_target is None:
        return binding
    return resume_session(
        binding=binding,
        redirect_target=redirect_target,
        token_resource_claim=token_resource_claim,
        handshake_returns_200=True,
    )
