# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-per-tool-least-privilege-scopes-from-silently-widening-across-mcp-sessions.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-per-tool-least-privilege-scopes-from-silently-widening-across-mcp-sessions.warrant.json
# Markdown SHA-256:   7776ec9e00316189c311d62245abe2d5238e11035ed86b2d4335344cb5a1220d
# Code AST SHA-256:   fcd72e807426fab1b9d7e28c7c2f0c777a4355cef9c0d67fdfb13441c864ad6b
# Verified Classes:   ScopeAccumulationError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ScopeAccumulationError(RuntimeError):
    """Raised when an authorization decision would depend on prior-call scope state."""


def authorize_call(
    asserted_scope: str,
    required_scopes: list[str],
    resource: str,
    session_scope_cache: dict | None,
) -> str:
    """
    Pure authorization for a single tools/call.

    Invariant: the decision MUST be a function of (asserted_scope, required_scopes, resource)
    only. Any presence of session-scoped mutable authorization state is a violation.
    """
    if session_scope_cache is not None and len(session_scope_cache) > 0:
        # The server is about to consult accumulated per-session scopes.
        # This is the exact condition that widens least-privilege.
        raise ScopeAccumulationError(
            "authorization path consulted session-scoped scope cache "
            f"({sorted(session_scope_cache.keys())}); decision would depend on call history"
        )

    if asserted_scope not in required_scopes:
        raise ScopeAccumulationError(
            f"asserted scope {asserted_scope!r} not in tool required_scopes {required_scopes!r}"
        )

    # Pattern match: asserted scope must cover the resource argument.
    prefix, _, pattern = asserted_scope.partition(":")
    if not resource.startswith(pattern.rstrip("*")):
        raise ScopeAccumulationError(
            f"resource {resource!r} outside asserted scope pattern {asserted_scope!r}"
        )

    return asserted_scope


def emit_audit(call_id: str, asserted_scope: str, evaluated_scopes: list[str]) -> dict:
    if not evaluated_scopes:
        raise ScopeAccumulationError(
            f"audit record {call_id} lacks evaluated scope set; trail cannot distinguish "
            "correct authorization from accumulation"
        )
    return {
        "call_id": call_id,
        "asserted_scope": asserted_scope,
        "evaluated_scopes": list(evaluated_scopes),
    }
