# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-it-never-re-validates-the-skill-injection-boundary-in-mcp-registry-supply-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-it-never-re-validates-the-skill-injection-boundary-in-mcp-registry-supply-chains.warrant.json
# Markdown SHA-256:   8f78eec74f57b6e968fc4f5378d3a1019c997d3a20f056ec6416c266904c2718
# Code AST SHA-256:   53ba95e092a40acf22e578be33caf546462bd955a073a424bfd4d85644a0154e
# Verified Classes:   ManifestTrustError, ScopeViolation, ToolManifest, PinnedRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ManifestTrustError(RuntimeError):
    """Raised when a tool manifest cannot be bound under the trust invariant."""


class ScopeViolation(RuntimeError):
    """Raised when a planner-emitted call exceeds the requesting tool's declared scope."""


@dataclass
class ToolManifest:
    name: str
    description: str
    resources: list[str] = field(default_factory=list)
    digest: str | None = None


@dataclass
class PinnedRecord:
    name: str
    digest: str


def bind_manifest(
    manifest: ToolManifest,
    pinned: dict[str, PinnedRecord],
    instruction_region: list[str],
    quarantine_region: list[str],
) -> None:
    """Bind a manifest only if its digest matches the pinned review-time digest.

    On mismatch, the description is quarantined as untrusted data and the
    manifest is bound in restricted mode: the agent may call the tool, but
    may not decompose tasks from its description.
    """
    computed = hashlib.sha256(manifest.description.encode()).hexdigest()
    record = pinned.get(manifest.name)

    if record is None:
        raise ManifestTrustError(
            f"tool {manifest.name!r} has no pinned digest; refusing instruction-region bind"
        )

    if record.digest != computed:
        # Mutable manifest drifted from review-time state. Quarantine, do not trust.
        quarantine_region.append(
            f"[UNTRUSTED MANIFEST {manifest.name}] {manifest.description}"
        )
        manifest.digest = computed
        return

    instruction_region.append(f"[TOOL {manifest.name}] {manifest.description}")
    manifest.digest = computed


def dispatch_call(
    requesting_tool: ToolManifest,
    target_tool: ToolManifest,
    arguments: dict[str, str],
) -> None:
    """Enforce that a call's arguments fall within the *requesting* tool's scope.

    The requesting tool is the one whose description induced the call; the
    target tool is the one being invoked. A summarize tool that induces a
    read_file against ~/.aws is a scope violation even though read_file
    itself is permitted to read it.
    """
    for arg_name, value in arguments.items():
        if not any(value.startswith(scope) for scope in requesting_tool.resources):
            raise ScopeViolation(
                f"tool {requesting_tool.name!r} induced call to "
                f"{target_tool.name!r} with {arg_name}={value!r}, "
                f"outside declared resources {requesting_tool.resources}"
            )
