# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-mismatched-elicitation-scope-when-an-mcp-server-delegates-tool-calls-through-an-oauth-2-1-resource-server-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-mismatched-elicitation-scope-when-an-mcp-server-delegates-tool-calls-through-an-oauth-2-1-resource-server-chain.warrant.json
# Markdown SHA-256:   0ef0234781e6b653d6ba938f0d885fe8224f00768a1b595dfea0fa4e5759e9fe
# Code AST SHA-256:   78a58fc9b45de4342d0a14fad15c00add4d7e6d1c14d38d5108920d2661ce9ed
# Verified Classes:   ElicitationScopeMismatch, AuthContext
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Any


class ElicitationScopeMismatch(RuntimeError):
    """Raised when an elicitation cannot be bound to the token that will
    authorize the downstream tool call. This is a fail-closed guard: the
    client must not render or accept the elicitation."""


@dataclass(frozen=True)
class AuthContext:
    aud: str
    scope: frozenset[str]
    jti: str
    exp: float


def validate_elicitation_binding(
    elicit_params: dict[str, Any],
    connection_token: AuthContext,
    delegated_token: AuthContext | None,
    now: float | None = None,
) -> AuthContext:
    """Return the AuthContext the elicitation is bound to, or raise.

    In a direct (non-delegated) topology delegated_token is None and the
    connection token governs the call. In a delegation chain the server
    MUST supply elicit_params["authorization_context"] naming the aud and
    scope of the token it will forward; otherwise the consent cannot be
    reconciled and we refuse.
    """
    now = time.time() if now is None else now

    if delegated_token is None:
        if connection_token.exp <= now:
            raise ElicitationScopeMismatch(
                f"connection token jti={connection_token.jti} expired at "
                f"{connection_token.exp}; cannot bind elicitation"
            )
        return connection_token

    declared = elicit_params.get("authorization_context")
    if not isinstance(declared, dict):
        raise ElicitationScopeMismatch(
            "server performed token exchange but elicitation carries no "
            "authorization_context; consent cannot be bound to the "
            f"delegated aud={delegated_token.aud!r}"
        )

    declared_aud = declared.get("aud")
    declared_scope = frozenset(declared.get("scope") or [])
    if declared_aud != delegated_token.aud:
        raise ElicitationScopeMismatch(
            f"elicitation declares aud={declared_aud!r} but delegated "
            f"token aud={delegated_token.aud!r}"
        )
    if not declared_scope.issubset(delegated_token.scope):
        raise ElicitationScopeMismatch(
            f"elicitation implies scope {sorted(declared_scope)} not "
            f"covered by delegated token scope "
            f"{sorted(delegated_token.scope)}"
        )
    if delegated_token.exp <= now:
        raise ElicitationScopeMismatch(
            f"delegated token jti={delegated_token.jti} expired at "
            f"{delegated_token.exp}; elicitation would be answered but "
            "tool call would fail downstream"
        )
    return delegated_token


def handle_elicitation(
    elicit_params: dict[str, Any],
    connection_token: AuthContext,
    delegated_token: AuthContext | None,
) -> dict[str, Any]:
    try:
        bound = validate_elicitation_binding(
            elicit_params, connection_token, delegated_token
        )
    except ElicitationScopeMismatch as exc:
        # Fail closed: do not render the prompt. Surface a machine-readable
        # decline so the server can re-issue with a binding if it supports one.
        return {
            "action": "decline",
            "reason": "authorization_context_unreconciled",
            "detail": str(exc),
        }
    return {
        "action": "accept",
        "bound_aud": bound.aud,
        "bound_scope": sorted(bound.scope),
        "bound_jti": bound.jti,
    }
