# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-re-authorize-an-mcp-streamable-http-session-when-the-oauth-2-1-resource-server-token-audience-silently-rotates-mid.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-re-authorize-an-mcp-streamable-http-session-when-the-oauth-2-1-resource-server-token-audience-silently-rotates-mid.warrant.json
# Markdown SHA-256:   e3385cbc5e7452097845031160da8fb8af70f630ef79af523b0727e2886b9d06
# Code AST SHA-256:   f095a4973a96ee32f6f7f13d8b45ecc5fa98b7ad152493a8e5a482704f816ae0
# Verified Classes:   AudienceRotationError, SessionContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class AudienceRotationError(RuntimeError):
    """Raised when a 401 invalid_token carries a resource_metadata pointer
    that no longer matches the resource the MCP session was established under."""
    pass


@dataclass
class SessionContext:
    session_id: str
    established_resource: str          # resource asserted at stream open
    token_audience: str                # aud/resource the current token was minted for
    checkpoint: Optional[dict] = None  # agent's serialized tool-chain state


def handle_tool_error(ctx: SessionContext, error: dict) -> str:
    """
    Decide whether a 401/invalid_token is a tool fault (retry) or a
    session-invalidating audience rotation (re-authorize + resume).
    Returns an action token for the agent loop.
    """
    if error.get("code") != 401 or error.get("error") != "invalid_token":
        return "retry_tool"  # ordinary tool fault, safe to retry

    advertised = error.get("resource_metadata")
    if advertised is None:
        # No metadata pointer: cannot distinguish rotation from revocation.
        # Fail closed to re-authorization; never silently retry.
        return "reauthorize_and_reset"

    if advertised != ctx.established_resource:
        # Audience rotated: the session is now mis-authorized. Do NOT retry
        # on this session — the server may still execute against a stale aud.
        raise AudienceRotationError(
            f"session {ctx.session_id} established under {ctx.established_resource!r} "
            f"but server now advertises {advertised!r}; token aud={ctx.token_audience!r}. "
            f"Checkpoint state, drop session, re-discover, re-authorize."
        )

    # Metadata matches: genuine token expiry/revocation, normal refresh path.
    return "refresh_token_and_retry"


def resume_after_rotation(ctx: SessionContext, new_resource: str) -> dict:
    if ctx.checkpoint is None:
        raise AudienceRotationError(
            f"cannot resume session {ctx.session_id}: audience rotated to "
            f"{new_resource!r} with no checkpointed tool-chain state; "
            f"multi-call transaction state is unrecoverable."
        )
    return {"resource": new_resource, "resume_from": ctx.checkpoint}
