# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-audience-mismatched-mcp-tokens-before-tool-dispatch-under-http-native-transport.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-audience-mismatched-mcp-tokens-before-tool-dispatch-under-http-native-transport.warrant.json
# Markdown SHA-256:   760ff95ec21143c554652daa9f97c237c1dc24e448dcb46a443324eff8ff45f5
# Code AST SHA-256:   8ef17f3548e3f81f5496f91fb104e8e2137fb1b6c839cb98386f6c41eef83eab
# Verified Classes:   AudienceMismatchError, NonRefreshableAuthError, Token, Challenge
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class AudienceMismatchError(RuntimeError):
    """Raised when a bearer token's `aud` does not include the target MCP resource."""
    pass

class NonRefreshableAuthError(RuntimeError):
    """Raised when a 401 cannot be resolved by token refresh alone (needs re-auth)."""
    pass


@dataclass
class Token:
    issuer: str
    audience: str          # the `aud` claim
    scope: str
    raw: str


@dataclass
class Challenge:
    error: str             # "invalid_token" | "insufficient_scope"
    resource_metadata: Optional[str]


def resolve_token_for_resource(
    cache: dict,                # keyed by (issuer, resource)
    issuer: str,
    target_resource: str,       # e.g. "https://mcp.internal/retrieval"
    required_scope: str,
    challenge: Challenge,
) -> Token:
    """
    Decide how to obtain a token valid for target_resource, given a 401 challenge.
    Enforces the invariant: returned token.audience == target_resource.
    """
    if challenge.error == "insufficient_scope":
        # refreshable: request expanded scope against the SAME resource
        tok = reauthorize(issuer, resource=target_resource, scope=required_scope)
    elif challenge.error == "invalid_token":
        # NOT refreshable by retry. Must re-authorize with correct resource.
        if challenge.resource_metadata is None:
            raise NonRefreshableAuthError(
                f"invalid_token from {target_resource} with no resource_metadata; "
                f"cannot determine expected audience"
            )
        canonical = fetch_protected_resource_metadata(challenge.resource_metadata)
        if canonical.resource != target_resource:
            raise AudienceMismatchError(
                f"server at {target_resource} advertises canonical resource "
                f"{canonical.resource}; client dialed the wrong endpoint"
            )
        # invalidate any stale entry under the issuer-only assumption
        cache.pop((issuer, canonical.resource), None)
        tok = reauthorize(issuer, resource=canonical.resource, scope=required_scope)
    else:
        raise NonRefreshableAuthError(f"unknown challenge error={challenge.error!r}")

    # The invariant check — the whole point.
    if target_resource not in tok.audience.split():
        raise AudienceMismatchError(
            f"token audience {tok.audience!r} does not include {target_resource!r} "
            f"after re-authorization; cache key or AS config is wrong"
        )
    cache[(issuer, target_resource)] = tok
    return tok


def dispatch_tool_call(
    cache: dict, issuer: str, target_resource: str, required_scope: str,
    tool_name: str, args: dict,
) -> dict:
    tok = cache.get((issuer, target_resource))
    if tok is None:
        # cold path: must authorize with explicit resource, never default audience
        tok = reauthorize(issuer, resource=target_resource, scope=required_scope)
        if target_resource not in tok.audience.split():
            raise AudienceMismatchError(
                f"cold-start token for {target_resource} has aud={tok.audience!r}"
            )
        cache[(issuer, target_resource)] = tok
    return mcp_post(target_resource, tool_name, args, bearer=tok.raw)
