# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-per-tool-consent-enforcement-when-mcp-scope-grants-are-cached-at-the-transport-session-instead-of-the-tool-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-per-tool-consent-enforcement-when-mcp-scope-grants-are-cached-at-the-transport-session-instead-of-the-tool-invocation.warrant.json
# Markdown SHA-256:   7dd01d4e6dc702e9a59e02e968fd93a80649e9034d2e8ab2e25180b43089abb7
# Code AST SHA-256:   414dc0e489ec8a543afef0b6492fad0195b675134ab3fe211d3016923878bce0
# Verified Classes:   ConsentGranularityViolation, SessionScopeCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ConsentGranularityViolation(RuntimeError):
    """Raised when a tool dispatch authorizes against a session-scoped cache
    while consent is revocable at a finer (per-invocation / per-principal) granularity."""
    pass


class SessionScopeCache:
    def __init__(self, conn_id: str, principal: str, scopes: set[str]):
        self.conn_id = conn_id
        self.principal = principal
        self.scopes = set(scopes)


def dispatch_tool_call(
    tool_name: str,
    required_scope: str,
    session: SessionScopeCache,
    auth_service,
    revocation_granularity: str,  # "session" | "invocation" | "principal"
    pooled: bool,
) -> None:
    # Invariant 1: enforcement point must be at or below revocation granularity.
    if revocation_granularity in ("invocation", "principal"):
        # The session cache is too coarse to be authoritative. Re-evaluate.
        live = auth_service.evaluate(principal=session.principal, scope=required_scope)
        if not live.granted:
            raise ConsentGranularityViolation(
                f"tool={tool_name} scope={required_scope} principal={session.principal} "
                f"denied by auth-service at invocation time; session cache "
                f"(conn={session.conn_id}) was stale and must not authorize."
            )
        # Audit must record the auth-service verdict, not the cache boolean.
        auth_service.audit(tool=tool_name, principal=session.principal,
                           verdict=live.verdict, source="auth_service")
        return

    # Invariant 2: pooled sessions must not carry shared scope blobs.
    if pooled and revocation_granularity == "principal":
        raise ConsentGranularityViolation(
            f"pooled session conn={session.conn_id} cannot enforce per-principal "
            f"consent; session-scoped grant is not a valid identity unit."
        )

    # Only safe path: consent is session-scoped and non-revocable mid-session.
    if required_scope not in session.scopes:
        raise ConsentGranularityViolation(
            f"tool={tool_name} requires {required_scope}; not in session scopes "
            f"{sorted(session.scopes)} for conn={session.conn_id}."
        )
    auth_service.audit(tool=tool_name, principal=session.principal,
                       verdict="granted_by_session_cache", source="session_cache")
