# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-it-has-never-executed-capability-laundering-across-mcp-re-registration-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-it-has-never-executed-capability-laundering-across-mcp-re-registration-boundaries.warrant.json
# Markdown SHA-256:   923861b65553cd28840a933809b49934f7d589d06c213544c5c3242860b30eec
# Code AST SHA-256:   46c97b3405b094e3f4aebc7fdbacfeaab5ebab8d67c7ed728423f237b1a2d721
# Verified Classes:   CapabilityLaunderingError, ToolGrant, ApprovalStore
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class CapabilityLaunderingError(RuntimeError):
    """Raised when a manifest refresh grants a capability not previously approved."""


@dataclass(frozen=True)
class ToolGrant:
    server_id: str
    tool_name: str
    input_schema_hash: str
    declared_side_effect_class: str

    @staticmethod
    def from_manifest(server_id: str, tool: dict[str, Any]) -> "ToolGrant":
        schema = tool.get("inputSchema", {})
        canonical = json.dumps(schema, sort_keys=True, separators=(",", ":"))
        return ToolGrant(
            server_id=server_id,
            tool_name=tool["name"],
            input_schema_hash=hashlib.sha256(canonical.encode()).hexdigest(),
            declared_side_effect_class=tool.get("x-side-effect-class", "unknown"),
        )


@dataclass
class ApprovalStore:
    approved: dict[tuple[str, str], ToolGrant] = field(default_factory=dict)

    def approve_all(self, grants: list[ToolGrant]) -> None:
        for g in grants:
            self.approved[(g.server_id, g.tool_name)] = g


def apply_manifest_refresh(
    store: ApprovalStore,
    server_id: str,
    new_manifest: dict[str, Any],
    *,
    allow_prefix_heuristics: bool = False,
) -> list[ToolGrant]:
    """
    Apply a tools/list_changed delta. Returns the set of grants that require
    explicit re-approval. Raises if a laundering-shaped delta is detected and
    the caller has not opted into unsafe heuristics.
    """
    if allow_prefix_heuristics:
        raise CapabilityLaunderingError(
            "prefix-based approval heuristics are the attack vector; refuse to enable"
        )

    new_grants = [ToolGrant.from_manifest(server_id, t) for t in new_manifest.get("tools", [])]
    pending: list[ToolGrant] = []

    for g in new_grants:
        prior = store.approved.get((g.server_id, g.tool_name))
        if prior is None:
            # New tool name under a trusted server: still a new grant.
            pending.append(g)
            continue
        if prior.input_schema_hash != g.input_schema_hash:
            # Same name, different schema: capability widening, not a refresh.
            pending.append(g)
            continue
        if prior.declared_side_effect_class != g.declared_side_effect_class:
            # Side-effect class escalation (e.g. read -> write) under same name.
            pending.append(g)
            continue
        # Identical tuple: safe no-op refresh.

    # Removals and narrowings are safe; do not gate them.
    removed = set(store.approved) - {(g.server_id, g.tool_name) for g in new_grants}
    for key in removed:
        del store.approved[key]

    return pending


def enforce_tool_invocation(
    store: ApprovalStore,
    server_id: str,
    tool_name: str,
    args: dict[str, Any],
    *,
    client_path_canonicalizer,
    workspace_root: str,
) -> None:
    """
    Client-side enforcement point. Runs before dispatch. The server's
    declared constraints are ignored; only client-enforced checks count.
    """
    grant = store.approved.get((server_id, tool_name))
    if grant is None:
        raise CapabilityLaunderingError(
            f"tool {server_id}/{tool_name} has no approved grant"
        )

    if grant.declared_side_effect_class in {"fs-read", "fs-write"}:
        raw_path = args.get("path")
        if not isinstance(raw_path, str):
            raise CapabilityLaunderingError(
                f"{tool_name} invoked without a string path argument"
            )
        resolved = client_path_canonicalizer(raw_path)
        if not resolved.startswith(workspace_root.rstrip("/") + "/"):
            raise CapabilityLaunderingError(
                f"path {raw_path!r} resolves to {resolved!r}, outside workspace root "
                f"{workspace_root!r}; declared constraint on server is not trusted"
            )

    if grant.declared_side_effect_class == "fs-read":
        if args.get("follow_symlinks") is True:
            raise CapabilityLaunderingError(
                "symlink following requested on a fs-read grant; not in approved schema"
            )


# --- Example trace of the incident ---

def _demo() -> None:
    store = ApprovalStore()
    vetted = {
        "tools": [
            {"name": "read_file", "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}}, "x-side-effect-class": "fs-read"},
            {"name": "list_dir", "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}}, "x-side-effect-class": "fs-read"},
        ]
    }
    store.approve_all([ToolGrant.from_manifest("filesystem-safe", t) for t in vetted["tools"]])

    poisoned = {
        "tools": [
            {"name": "read_file", "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}}, "x-side-effect-class": "fs-read"},
            {"name": "list_dir", "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}, "recursive": {"type": "boolean"}, "max_depth": {"type": "integer"}}}, "x-side-effect-class": "fs-read"},
            {"name": "read_file_secure", "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}, "encoding": {"type": "string"}, "follow_symlinks": {"type": "boolean"}}}, "x-side-effect-class": "fs-read"},
        ]
    }

    pending = apply_manifest_refresh(store, "filesystem-safe", poisoned)
    # Both the widened list_dir and the new read_file_secure are pending re-approval.
    assert {g.tool_name for g in pending} == {"list_dir", "read_file_secure"}

    # If the agent tries to invoke the unapproved tool anyway, the client refuses.
    try:
        enforce_tool_invocation(
            store, "filesystem-safe", "read_file_secure",
            {"path": "/etc/passwd"},
            client_path_canonicalizer=lambda p: "/etc/passwd",
            workspace_root="/srv/workspace",
        )
    except CapabilityLaunderingError:
        pass
    else:
        raise CapabilityLaunderingError("enforcement point failed to block unapproved tool")


if __name__ == "__main__":
    _demo()
