# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-it-fetched-rather-than-one-it-pinned-the-description-field-injection-surface-in-mcp-server-supply.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-it-fetched-rather-than-one-it-pinned-the-description-field-injection-surface-in-mcp-server-supply.warrant.json
# Markdown SHA-256:   21aba7cac2ba290bcc1bc0bc3e836c2f026669f3db9a2b61985758f40a917431
# Code AST SHA-256:   20cb0db344c182a6e14f7ad7b0b347b4146125f788e4bf8e4f6aa874956fa260
# Verified Classes:   ManifestIntegrityError, ManifestTrustWindowError, ToolManifest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestIntegrityError(RuntimeError):
    """Raised when a fetched tool manifest does not match its pinned digest."""
    pass


class ManifestTrustWindowError(RuntimeError):
    """Raised when a manifest has no pin and cannot be authenticated out-of-band."""
    pass


@dataclass(frozen=True)
class ToolManifest:
    name: str
    description: str
    input_schema: dict

    def digest(self) -> str:
        # Canonicalize: order-independent, description included because it is
        # the injection channel. Hashing only name+schema misses the attack.
        payload = json.dumps(
            {
                "name": self.name,
                "description": self.description,
                "input_schema": self.input_schema,
            },
            sort_keys=True,
            separators=(",", ":"),
        ).encode("utf-8")
        return hashlib.sha256(payload).hexdigest()


def load_tool(manifest: ToolManifest, pinned: dict[str, str],
              first_fetch_authenticated: bool = False) -> ToolManifest:
    """Load a tool only if its manifest digest matches the pin.

    The digest is verified at the moment of use, not at fetch time, so a
    manifest mutated between fetch and load is still caught.
    """
    actual = manifest.digest()
    expected = pinned.get(manifest.name)

    if expected is None:
        if not first_fetch_authenticated:
            raise ManifestTrustWindowError(
                f"tool {manifest.name!r} has no pin and first-fetch channel "
                f"is unauthenticated; refusing to load"
            )
        return manifest  # caller must advance the pin out-of-band

    if actual != expected:
        # Hard stop. Do NOT log-and-continue: the description field is an
        # instruction channel and may already have poisoned the plan.
        raise ManifestIntegrityError(
            f"manifest digest mismatch for {manifest.name!r}: "
            f"pinned={expected[:12]} fetched={actual[:12]}; "
            f"tool quarantined, session continues with pinned set"
        )

    return manifest


def build_tool_context(manifests: list[ToolManifest],
                       pinned: dict[str, str]) -> str:
    """Serialize only verified manifests into the model's tool context."""
    verified: list[ToolManifest] = []
    for m in manifests:
        try:
            verified.append(load_tool(m, pinned))
        except (ManifestIntegrityError, ManifestTrustWindowError):
            # Quarantine, do not abort the whole session.
            continue
    return "\n".join(
        f"- {m.name}: {m.description}" for m in verified
    )
