# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-mcp-tool-scope-attenuation-when-a-server-s-auth-token-outlives-the-per-call-capability-grant.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-mcp-tool-scope-attenuation-when-a-server-s-auth-token-outlives-the-per-call-capability-grant.warrant.json
# Markdown SHA-256:   abd161bbd128ddf3a9d6e973e363ec88300d168ecee0f08e1353c10df5368c8e
# Code AST SHA-256:   a46f99d1996db7c689e5f7ae61b396bb91029d8967e7a15dc9986a21020eedf4
# Verified Classes:   ScopeAttenuationError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ScopeAttenuationError(RuntimeError):
    """Raised when a tools/call would execute with authority exceeding the task grant."""
    pass


def dispatch_tool_call(session_principal_scope: set[str],
                       task_grant: set[str],
                       tool_name: str,
                       per_call_token_scope: set[str] | None) -> str:
    """
    Enforce the invariant: server-checked authority <= task-granted authority.

    session_principal_scope: full scope bound to the MCP session token (long-lived).
    task_grant:               scope the current task was authorized for (narrow).
    per_call_token_scope:     scope on a downscoped per-call token, if the server
                              supports token exchange; None means client-gate only.
    """
    # The tool must be inside the task grant regardless of what the token allows.
    if tool_name not in task_grant:
        raise ScopeAttenuationError(
            f"tool {tool_name!r} outside task grant {sorted(task_grant)}; "
            f"session token would have permitted it via {sorted(session_principal_scope)}"
        )

    if per_call_token_scope is not None:
        # Server-enforced path: the per-call token is what the server validates.
        if tool_name not in per_call_token_scope:
            raise ScopeAttenuationError(
                f"per-call token scope {sorted(per_call_token_scope)} excludes {tool_name!r}; "
                "exchange did not downscope correctly"
            )
        if not per_call_token_scope.issubset(task_grant):
            raise ScopeAttenuationError(
                f"per-call token {sorted(per_call_token_scope)} exceeds task grant "
                f"{sorted(task_grant)}; attenuation failed"
            )
        return f"dispatched {tool_name!r} under downscoped token"

    # Client-gate fallback: weaker, trusts the agent process. Must gate on the wire path.
    if not task_grant.issubset(session_principal_scope):
        raise ScopeAttenuationError(
            f"task grant {sorted(task_grant)} not reachable under session scope "
            f"{sorted(session_principal_scope)}; cannot dispatch"
        )
    return f"dispatched {tool_name!r} under client-side gate (no server attenuation)"
