# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-capability-descriptor-tampering-from-silently-rewriting-an-agent-s-tool-contract-at-mcp-handshake-time.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-capability-descriptor-tampering-from-silently-rewriting-an-agent-s-tool-contract-at-mcp-handshake-time.warrant.json
# Markdown SHA-256:   559df001834f9355d6c388e506b7d361cfa963efff07aa86373874ffb0139609
# Code AST SHA-256:   52b6e8d8718b5b4a0f0e6c38393d2042be2aa314eb44e7312fd748282b93cab4
# Verified Classes:   DescriptorTamperError, PinnedTool
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class DescriptorTamperError(RuntimeError):
    """Raised when a re-fetched capability descriptor diverges from the pinned contract."""
    pass


@dataclass(frozen=True)
class PinnedTool:
    name: str
    descriptor_hash: str


def _hash_descriptor(tool: dict) -> str:
    # Hash only the semantic contract fields; volatile fields like timestamps are excluded.
    contract = {
        "name": tool["name"],
        "inputSchema": tool.get("inputSchema", {}),
        "description": tool.get("description", ""),
    }
    blob = json.dumps(contract, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


def pin_manifest(tools: list[dict]) -> dict[str, PinnedTool]:
    return {t["name"]: PinnedTool(t["name"], _hash_descriptor(t)) for t in tools}


def rebind_tools(fresh_tools: list[dict], pinned: dict[str, PinnedTool]) -> list[dict]:
    """Rebind only descriptors whose hash matches the pinned contract.

    A silent rebind on hash mismatch is the capability-descriptor tampering failure:
    the model would then reason against attacker-rewritten semantics.
    """
    authorized: list[dict] = []
    for tool in fresh_tools:
        name = tool["name"]
        if name not in pinned:
            # New capability not present at trust establishment -> requires explicit authorization.
            raise DescriptorTamperError(
                f"Tool {name!r} appeared after trust establishment; refusing implicit bind."
            )
        current = _hash_descriptor(tool)
        if current != pinned[name].descriptor_hash:
            raise DescriptorTamperError(
                f"Descriptor for {name!r} changed since pinning "
                f"(pinned={pinned[name].descriptor_hash[:12]}, now={current[:12]}); "
                "contract change requires re-authorization, not silent rebind."
            )
        authorized.append(tool)
    return authorized


def enforce_argument_shape(tool_name: str, schema: dict, args: dict) -> None:
    """Reject argument shapes that smuggle a second payload through a scalar field.

    The model cannot be trusted to honor a schema whose description it just read,
    because that description is the attack surface.
    """
    path = args.get("path")
    if isinstance(path, str) and path.count("/") > 0:
        # A path argument that embeds a second absolute path or a delimiter is a smuggling shape.
        if "/proc/" in path or path.count("://") > 0 or "\x00" in path:
            raise DescriptorTamperError(
                f"Argument for {tool_name!r} carries an embedded payload in a scalar field: {path!r}"
            )
