# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-tool-call-authorization-as-a-decision-made-over-the-arguments-not-the-tool-name-because-the-middlewar.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-tool-call-authorization-as-a-decision-made-over-the-arguments-not-the-tool-name-because-the-middlewar.warrant.json
# Markdown SHA-256:   3801493332a6240a8e9fe2d5165c14f7d19bf611f1864fe2e341dfd5b6b611b3
# Code AST SHA-256:   7332ada60b7fc86aed6160cd7f6ccde9457e6b05db2619fd1ceba5d7bca21bf6
# Verified Classes:   UnboundedSelectorError, ToolSpec, NameKeyedACL
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any, Callable


class UnboundedSelectorError(PermissionError):
    """Raised when a multiplexing tool is registered or invoked under a
    name-keyed ACL that cannot see the argument that determines its effect."""
    pass


# Arguments whose values select the resource the call actually touches.
SELECTOR_PARAMS = frozenset({
    "path", "host", "url", "database", "db", "namespace", "tenant",
    "repo", "channel", "command", "table", "bucket",
})


@dataclass
class ToolSpec:
    name: str
    input_schema: dict[str, Any]
    handler: Callable[..., Any]


@dataclass
class NameKeyedACL:
    # ACL keyed only on tool name -> the exact defect this record describes.
    grants: dict[str, set[str]] = field(default_factory=dict)
    # Optional per-selector allowlists: tool -> {param: allowed_values}
    selector_bounds: dict[str, dict[str, frozenset[str]]] = field(default_factory=dict)

    def _unbounded_selectors(self, spec: ToolSpec) -> list[str]:
        props = spec.input_schema.get("properties", {})
        bounds = self.selector_bounds.get(spec.name, {})
        unbounded = []
        for pname, pschema in props.items():
            if pname not in SELECTOR_PARAMS:
                continue
            # A selector is bounded only if it is an enum pinned server-side
            # OR the middleware holds an explicit allowlist for it.
            is_enum = isinstance(pschema.get("enum"), list)
            has_bound = pname in bounds
            if not (is_enum or has_bound):
                unbounded.append(pname)
        return unbounded

    def register(self, spec: ToolSpec) -> None:
        unbounded = self._unbounded_selectors(spec)
        if unbounded:
            # Refuse to register a multiplexing tool under a name-only ACL:
            # the ACL cannot prove effect ⊆ capability for these parameters.
            raise UnboundedSelectorError(
                f"tool {spec.name!r} exposes unbounded selector(s) {unbounded}; "
                f"name-keyed ACL cannot enforce least-privilege over its effects. "
                f"Pin via enum or selector_bounds, or key the ACL on arguments."
            )

    def authorize(self, spec: ToolSpec, args: dict[str, Any]) -> dict[str, Any]:
        # Re-validate at call time: a defaulted selector can slip past a
        # registration that only inspected required fields.
        unbounded = self._unbounded_selectors(spec)
        if unbounded:
            raise UnboundedSelectorError(
                f"call to {spec.name!r} carries unbounded selector(s) {unbounded}; "
                f"effect cannot be bounded by tool-name grant"
            )
        if spec.name not in self.grants:
            raise PermissionError(f"no grant for tool {spec.name!r}")
        # Enforce selector bounds against the *actual* argument values.
        bounds = self.selector_bounds.get(spec.name, {})
        for pname, allowed in bounds.items():
            if pname in args and args[pname] not in allowed:
                raise PermissionError(
                    f"{spec.name}.{pname}={args[pname]!r} outside bound {sorted(allowed)}"
                )
        # Effect-bearing audit record: name AND selector arguments.
        return {"tool": spec.name, "args": dict(args), "decision": "allow"}


def dispatch(acl: NameKeyedACL, spec: ToolSpec, args: dict[str, Any]) -> Any:
    record = acl.authorize(spec, args)  # raises before any side effect
    _ = record  # emit to effect-scoped audit sink here
    return spec.handler(**args)
