# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-scope-attenuation-bypass-through-delegated-capability-token-recomposition-in-cross-agent-oauth-flows.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-scope-attenuation-bypass-through-delegated-capability-token-recomposition-in-cross-agent-oauth-flows.warrant.json
# Markdown SHA-256:   e2238c7e530868319194c0903be297b1f741ba4367639bd4b0d3788658b39346
# Code AST SHA-256:   a8eeab43850a8010a9d9bcea89aa1f71850e33a55d5c044e557046c8c0ac072a
# Verified Classes:   ScopeAttenuationViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ScopeAttenuationViolation(RuntimeError):
    """Raised when a delegated token exchange would amplify scopes beyond the received token."""
    pass


def request_token_exchange(received_token: dict, requested_scopes: set[str]) -> dict:
    """
    Agent-side guard: refuse any exchange whose requested scopes are not a subset
    of the scopes actually carried by the token this agent received.
    The tool manifest is NOT consulted here; only the received token is authoritative.
    """
    granted = set(received_token.get("scopes", []))
    over_broad = requested_scopes - granted
    if over_broad:
        raise ScopeAttenuationViolation(
            f"Exchange refused: requested scopes {sorted(over_broad)} exceed "
            f"received token ceiling {sorted(granted)}. "
            f"Escalate to delegating principal for explicit re-delegation."
        )
    # Only reached when requested_scopes <= granted; server-side chain walk still required.
    return {"scopes": sorted(requested_scopes), "parent": received_token.get("jti")}


def handle_tool_manifest_change(received_token: dict, new_manifest_scopes: set[str]) -> None:
    """
    Called when the MCP tool manifest advertises new scope requirements.
    A manifest change is not an authorization; it must not trigger an exchange.
    """
    granted = set(received_token.get("scopes", []))
    delta = new_manifest_scopes - granted
    if delta:
        raise ScopeAttenuationViolation(
            f"Manifest drift detected: tools now require {sorted(delta)} which are "
            f"outside the received token. Do not exchange; re-request delegation."
        )
