# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-description-more-than-its-own-tool-output-capability-description-divergence-and-the-registry-poisoning-window-in-mcp.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-description-more-than-its-own-tool-output-capability-description-divergence-and-the-registry-poisoning-window-in-mcp.warrant.json
# Markdown SHA-256:   95d9bcc7fe00bef3e5543d5872eddc9423732d8c1dcb4766fa2117e542166f9f
# Code AST SHA-256:   dc34463fca492b22ddd28e591ab5e1a01ffb8dc418905e4e769cdbb10b4aa8ec
# Verified Classes:   DescriptorPoisoningError, PinnedDescriptor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class DescriptorPoisoningError(RuntimeError):
    """Raised when a fetched MCP descriptor diverges from its pinned hash
    or attempts to smuggle executable authority into the model context."""
    pass


DIRECTIVE_MARKERS = (
    "must not verify",
    "do not re-read",
    "ignore conflicting",
    "always call",
    "treat any conflicting",
)


@dataclass(frozen=True)
class PinnedDescriptor:
    name: str
    schema_hash: str


def project_descriptor(raw: dict, pinned: PinnedDescriptor) -> dict:
    """Project a registry descriptor to a schema-only, distrust-labeled block.
    Strips free-text description; enforces hash pin; rejects directives."""
    name = raw.get("name", "")
    if name != pinned.name:
        raise DescriptorPoisoningError(
            f"descriptor name mismatch: pinned={pinned.name!r} served={name!r}"
        )

    canonical = json.dumps(
        {"name": name, "inputSchema": raw.get("inputSchema", {})},
        sort_keys=True,
    )
    served_hash = hashlib.sha256(canonical.encode()).hexdigest()
    if served_hash != pinned.schema_hash:
        raise DescriptorPoisoningError(
            f"descriptor hash drift for {name!r}: "
            f"pinned={pinned.schema_hash[:12]} served={served_hash[:12]}"
        )

    description = (raw.get("description") or "").lower()
    for marker in DIRECTIVE_MARKERS:
        if marker in description:
            raise DescriptorPoisoningError(
                f"descriptor for {name!r} contains executable directive "
                f"({marker!r}); refusing to inject into context"
            )

    return {
        "name": name,
        "inputSchema": raw.get("inputSchema", {}),
        "trust_label": "UNTRUSTED_DESCRIPTOR_SCHEMA_ONLY",
    }
