# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-an-mcp-oauth-token-whose-aud-claim-binds-to-the-wrong-resource-indicator-after-a-transport-upgrade.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-an-mcp-oauth-token-whose-aud-claim-binds-to-the-wrong-resource-indicator-after-a-transport-upgrade.warrant.json
# Markdown SHA-256:   230d03be434b1e34d6f8d37f8c74c58a367e70552d0383b6a8db9ebf8ee7119d
# Code AST SHA-256:   49f558a70c2416f4e4c3a74ca12e2257608856c484079085216eac1ec7b398b3
# Verified Classes:   AudienceBindingError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class AudienceBindingError(RuntimeError):
    """Raised when an MCP bearer token's audience does not match the
    canonical resource URI of the transport currently in use."""
    pass


def assert_token_audience_bound(
    token_aud: str,
    live_resource_uri: str,
    server_attested_resource: str | None,
) -> None:
    """Enforce the resource-indicator invariant before any tool call.

    The invariant: token_aud == live_resource_uri, AND (if the server
    attests a resource) server_attested_resource == live_resource_uri.
    A server that does not attest its resource identity is treated as
    untrusted for audience purposes; the caller must re-acquire.
    """
    if token_aud != live_resource_uri:
        raise AudienceBindingError(
            f"token audience {token_aud!r} does not match live resource "
            f"{live_resource_uri!r}; re-acquire with resource={live_resource_uri!r}"
        )
    if server_attested_resource is None:
        raise AudienceBindingError(
            f"resource server at {live_resource_uri!r} did not attest its "
            "canonical URI; audience cannot be confirmed, re-acquire required"
        )
    if server_attested_resource != live_resource_uri:
        raise AudienceBindingError(
            f"server attested {server_attested_resource!r} but transport "
            f"resolves to {live_resource_uri!r}; transport/resource mismatch"
        )


def on_transport_successor(
    old_resource_uri: str,
    new_resource_uri: str,
    held_token_aud: str,
) -> bool:
    """Decide whether the held token may be carried across a transport
    upgrade. Returns True if re-acquisition is required."""
    if old_resource_uri == new_resource_uri:
        return False
    if held_token_aud != new_resource_uri:
        return True
    raise AudienceBindingError(
        f"token audience already matches successor {new_resource_uri!r} "
        "but predecessor was {old_resource_uri!r}; state is inconsistent, "
        "re-acquire to reset session resource anchor"
    )
