# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-signed-mcp-manifest-the-description-body-drift-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-signed-mcp-manifest-the-description-body-drift-boundary.warrant.json
# Markdown SHA-256:   5800d0d9c99ea21c188565604feec491766aabe00bf5c819cb5b0057fa9b4211
# Code AST SHA-256:   2ca6bc0b9c209916ff384aa4f3ca5c79bf9174304128a6e2111bb8d585c172fd
# Verified Classes:   DescriptionDriftError, SignedTool, LiveTool
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class DescriptionDriftError(RuntimeError):
    """Raised when live MCP tool description does not match the signed manifest."""


@dataclass(frozen=True)
class SignedTool:
    name: str
    description_hash: str  # hex sha256 of the exact signed description bytes


@dataclass(frozen=True)
class LiveTool:
    name: str
    description: str


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


def admit_tools_list(
    signed: dict[str, SignedTool],
    live: list[LiveTool],
) -> list[LiveTool]:
    """Gate a tools/list payload against the signed manifest.

    Enforces the per-step invariant: the description bytes the model will
    reason over must hash-equal the signed description hash. NOVEL tools and
    drifted descriptions are rejected; only exact matches are admitted.
    """
    admitted: list[LiveTool] = []
    for tool in live:
        signed_tool = signed.get(tool.name)
        if signed_tool is None:
            # Novel tool: no signature covers it. Cannot be admitted on the
            # strength of the session's prior verification.
            raise DescriptionDriftError(
                f"tool {tool.name!r} present in tools/list but absent from "
                f"signed manifest; refusing to expose unsigned description"
            )
        live_hash = _sha256(tool.description)
        if live_hash != signed_tool.description_hash:
            # Post-signing mutation. The signature is still valid, which is
            # exactly why this must fail closed here rather than be trusted.
            raise DescriptionDriftError(
                f"description drift for tool {tool.name!r}: "
                f"signed={signed_tool.description_hash[:12]} "
                f"live={live_hash[:12]}; refusing poisoned description"
            )
        admitted.append(tool)
    return admitted


def build_call_record(tool: LiveTool, admitted: list[LiveTool]) -> dict:
    """Attach the exact description hash the model saw to every tool call."""
    if tool not in admitted:
        raise DescriptionDriftError(
            f"tool {tool.name!r} invoked without passing admission gate"
        )
    return {
        "tool": tool.name,
        "description_sha256": _sha256(tool.description),
    }
