# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-description-that-mutates-between-capability-negotiation-and-first-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-description-that-mutates-between-capability-negotiation-and-first-invocation.warrant.json
# Markdown SHA-256:   793819968269f56bd5f1f7755410ba0f7448e6b3e268a37f690a655b0b2fa90b
# Code AST SHA-256:   3a5d599db9c2df41d7c19d90aa2acc12d4a4b067dab71aa7e4b8c644a85e62d6
# Verified Classes:   DescriptionIntegrityError, ClassifiedTool
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class DescriptionIntegrityError(RuntimeError):
    """Raised when a tool description reaching prompt assembly no longer
    matches the byte-string that was classified at negotiation time."""


@dataclass(frozen=True)
class ClassifiedTool:
    server_id: str
    tool_name: str
    description: str
    sha256: str


def classify_tool(server_id: str, tool_name: str, description: str) -> ClassifiedTool:
    digest = hashlib.sha256(description.encode("utf-8")).hexdigest()
    # scanner approves `description` here; we bind the approval to the hash
    return ClassifiedTool(server_id, tool_name, description, digest)


def project_tool_record(raw: dict) -> dict:
    """Closed-schema projection: drop every field not in the declared contract
    so response-envelope extensions (_meta, annotations, vendor keys) cannot
    leak into the tool record that reaches prompt assembly."""
    allowed = {"name", "description", "input_schema"}
    return {k: v for k, v in raw.items() if k in allowed}


def assemble_description(classified: ClassifiedTool, raw_record: dict) -> str:
    projected = project_tool_record(raw_record)
    candidate = projected.get("description", "")
    candidate_hash = hashlib.sha256(candidate.encode("utf-8")).hexdigest()
    if candidate_hash != classified.sha256:
        raise DescriptionIntegrityError(
            f"tool {classified.server_id}/{classified.tool_name} description "
            f"mutated after classification: expected {classified.sha256[:12]}, "
            f"got {candidate_hash[:12]}; quarantining for session"
        )
    return candidate
