# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-mcp-tool-call-authority-when-the-sandbox-s-capability-check-and-the-tool-s-actual-effect-diverge-at-the-argument-resoluti.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-mcp-tool-call-authority-when-the-sandbox-s-capability-check-and-the-tool-s-actual-effect-diverge-at-the-argument-resoluti.warrant.json
# Markdown SHA-256:   fe4d28fa2bf9e66afdc32c66f3da63d5d0c9b63cbb7fae3be9560905530b56af
# Code AST SHA-256:   5aa1c0236eab3cd9a48552bb7748984763a4840075822395cd4a3e091e089033
# Verified Classes:   CapabilityResolutionError, Capability
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import os
from dataclasses import dataclass
from typing import Iterable


class CapabilityResolutionError(RuntimeError):
    """Raised when a tool-call argument cannot be safely canonicalized
    to the same object the server's effect layer will operate on."""
    pass


@dataclass(frozen=True)
class Capability:
    tool: str
    prefix: str  # canonical, absolute, no trailing slash


def authorize_tool_call(
    tool: str,
    arguments: dict,
    path_keys: Iterable[str],
    warrants: Iterable[Capability],
    root: str,
) -> dict:
    """Authorize an MCP tool call by canonicalizing path-keyed arguments
    to the SAME form the effect layer uses, then matching the capability
    predicate against the canonical object. Fail-closed on any
    non-canonicalizable input.

    Returns an audit record carrying BOTH raw and canonical forms so the
    authorization predicate and the effect predicate are provably
    evaluated over the same object.
    """
    root_real = os.path.realpath(root)
    record = {"tool": tool, "raw": dict(arguments), "canonical": {}, "matched": []}

    for key in path_keys:
        if key not in arguments:
            continue
        raw = arguments[key]
        if not isinstance(raw, str):
            raise CapabilityResolutionError(
                f"path-keyed argument {key!r} is not a string: {type(raw).__name__}"
            )
        # Join under root, then resolve strictly. strict=True fails closed
        # on nonexistent parents and unresolvable symlinks rather than
        # silently lexically matching.
        joined = os.path.join(root_real, raw)
        try:
            canonical = os.path.realpath(joined, strict=True)
        except (OSError, ValueError) as exc:
            raise CapabilityResolutionError(
                f"cannot canonicalize {key!r}={raw!r} under root {root_real!r}: {exc}"
            ) from exc

        # Containment check on the RESOLVED object, not the raw string.
        if canonical != root_real and not canonical.startswith(root_real + os.sep):
            raise CapabilityResolutionError(
                f"canonical path {canonical!r} escapes root {root_real!r} "
                f"(raw was {raw!r})"
            )
        record["canonical"][key] = canonical

    # Capability predicate evaluated over canonical forms only.
    for cap in warrants:
        if cap.tool != tool:
            continue
        if all(
            record["canonical"][k] == cap.prefix
            or record["canonical"][k].startswith(cap.prefix + os.sep)
            for k in record["canonical"]
        ):
            record["matched"].append(cap.prefix)

    if not record["matched"]:
        raise CapabilityResolutionError(
            f"no warrant covers tool {tool!r} over canonical args "
            f"{record['canonical']!r}"
        )
    return record
