# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-dynamically-registered-mcp-tool-description-as-capability-metadata-rather-than-as-untrusted-content.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-dynamically-registered-mcp-tool-description-as-capability-metadata-rather-than-as-untrusted-content.warrant.json
# Markdown SHA-256:   cc49d5ab2aba250ad31a6789aab002c6a1017c9f2e51546ab6adec0204bfc084
# Code AST SHA-256:   357feeeacb8a00895b18321dedcbf3cb33edb3bf65b0289be09eb00a04117e6c
# Verified Classes:   CapabilityAttestationError, FetchedTool, AuthorizedEntry
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import hmac
from dataclasses import dataclass


class CapabilityAttestationError(RuntimeError):
    """Raised when a fetched MCP tool description cannot be bound to an
    operator-authorized, signed manifest entry."""
    pass


@dataclass(frozen=True)
class FetchedTool:
    name: str
    description: str
    schema_hash: str
    peer_identity: str


@dataclass(frozen=True)
class AuthorizedEntry:
    name: str
    schema_hash: str
    description_hash: str
    signature: bytes


def _description_hash(description: str) -> str:
    return hashlib.sha256(description.encode("utf-8")).hexdigest()


def admit_tool(
    fetched: FetchedTool,
    manifest: dict[str, AuthorizedEntry],
    operator_key: bytes,
) -> str:
    """Admit a fetched tool into the planner's actionable set only if its
    (name, schema_hash, description_hash) tuple matches a signed manifest
    entry. Returns the description rendered as inert, quoted data — never
    as instruction-bearing text."""
    entry = manifest.get(fetched.name)
    if entry is None:
        raise CapabilityAttestationError(
            f"tool {fetched.name!r} from peer {fetched.peer_identity!r} "
            f"is not present in the operator manifest"
        )

    if entry.schema_hash != fetched.schema_hash:
        raise CapabilityAttestationError(
            f"schema hash mismatch for {fetched.name!r}: "
            f"manifest={entry.schema_hash} fetched={fetched.schema_hash}"
        )

    observed = _description_hash(fetched.description)
    if entry.description_hash != observed:
        raise CapabilityAttestationError(
            f"description hash mismatch for {fetched.name!r}: "
            f"manifest={entry.description_hash} fetched={observed}; "
            f"description may have been tampered with in transit"
        )

    expected_sig = hmac.new(
        operator_key,
        f"{entry.name}:{entry.schema_hash}:{entry.description_hash}".encode(),
        hashlib.sha256,
    ).digest()
    if not hmac.compare_digest(expected_sig, entry.signature):
        raise CapabilityAttestationError(
            f"manifest signature invalid for {fetched.name!r}"
        )

    # Render as data, not instruction: quoted and explicitly labeled.
    return f"UNTRUSTED_PEER_METADATA[{fetched.name}]: {fetched.description!r}"


def build_plan_step(capability: str, authorized: set[str]) -> dict:
    if capability not in authorized:
        raise CapabilityAttestationError(
            f"plan step names capability {capability!r} absent from "
            f"operator-authorized set; refusing to admit (possible "
            f"skill-injection via tool description)"
        )
    return {"capability": capability}
