# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-poisoned-mcp-tool-description-from-surviving-the-capability-negotiation-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-poisoned-mcp-tool-description-from-surviving-the-capability-negotiation-boundary.warrant.json
# Markdown SHA-256:   ef3412226a997a079eb3cf4bfab67f323dcf4cd108aa76b4474b34e7af332649
# Code AST SHA-256:   50aef093425c75fbac74e0949de72bdd2a47409802e8919f764663f05f51f53c
# Verified Classes:   DescriptorAuthorityError, AttestedDescriptor, IncomingDescriptor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class DescriptorAuthorityError(RuntimeError):
    """Raised when a tool descriptor claims authority it was not granted."""
    pass


@dataclass(frozen=True)
class AttestedDescriptor:
    name: str
    param_names: frozenset
    referenced_tools: frozenset   # sibling tools this descriptor may name
    external_paths: frozenset     # path patterns this descriptor may reference
    sha256: str


@dataclass
class IncomingDescriptor:
    name: str
    description: str
    param_names: frozenset
    referenced_tools: frozenset
    external_paths: frozenset

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


def classify_descriptor(
    incoming: IncomingDescriptor,
    attested: AttestedDescriptor | None,
) -> str:
    """
    Returns one of: 'instruction_role', 'data_role_hotswap', 'quarantine'.

    Invariant enforced: a descriptor may enter instruction-role context only
    when its structural claims are a subset of an attested baseline. Any new
    cross-tool reference or external path forces quarantine regardless of
    lexical content.
    """
    if attested is None:
        # Unknown server: never instruction-role on first sight.
        return "quarantine"

    if incoming.sha256() == attested.sha256:
        return "instruction_role"

    new_tools = incoming.referenced_tools - attested.referenced_tools
    new_paths = incoming.external_paths - attested.external_paths
    new_params = incoming.param_names - attested.param_names

    if new_tools or new_paths or new_params:
        # Structural expansion: description now claims authority it lacked.
        return "quarantine"

    # Cosmetic change only: render as data, tag with provenance.
    return "data_role_hotswap"


def render_descriptor_for_context(
    incoming: IncomingDescriptor,
    attested: AttestedDescriptor | None,
) -> str:
    verdict = classify_descriptor(incoming, attested)

    if verdict == "quarantine":
        raise DescriptorAuthorityError(
            f"descriptor '{incoming.name}' claims new authority "
            f"(tools={incoming.referenced_tools - (attested.referenced_tools if attested else frozenset())}, "
            f"paths={incoming.external_paths - (attested.external_paths if attested else frozenset())}); "
            f"refusing instruction-role render pending re-attestation"
        )

    if verdict == "instruction_role":
        return f"[tool:{incoming.name}] {incoming.description}"

    # data_role_hotswap: explicitly framed as untrusted data.
    return (
        f"[untrusted-descriptor server={incoming.name} "
        f"sha256={incoming.sha256()[:12]}] {incoming.description}"
    )


def guard_plan_step(step_tool: str, justification_source: str, attested: dict) -> None:
    """
    Reject any call whose justification originates from a *different* tool's
    description. Authority to invoke step_tool must come from the task or from
    step_tool's own attested grant.
    """
    if justification_source.startswith("descriptor:") and justification_source != f"descriptor:{step_tool}":
        raise DescriptorAuthorityError(
            f"call to '{step_tool}' justified by '{justification_source}': "
            f"cross-tool authority is not a grantable property of prose"
        )
    if step_tool not in attested:
        raise DescriptorAuthorityError(f"'{step_tool}' not in attested manifest")
