# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-s-description-field-as-executable-instruction-skill-injection-through-mcp-registry-poisoning.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-s-description-field-as-executable-instruction-skill-injection-through-mcp-registry-poisoning.warrant.json
# Markdown SHA-256:   785e87a8e929748bc4f8b151e1d191c6045bac78ef1e0035b68b24059e0ee089
# Code AST SHA-256:   697c1c2fcca8dae7360b4052de6ae7881d0312bcdaaf11c9bde787964307d334
# Verified Classes:   ManifestInjectionError, ToolManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import re
from dataclasses import dataclass


class ManifestInjectionError(RuntimeError):
    """Raised when a tool manifest attempts to cross the data/instruction boundary."""


# Patterns that indicate a manifest is issuing directives rather than describing a capability.
_DIRECTIVE_PATTERNS = [
    r"\[\s*SYSTEM\s*\]",
    r"\bbefore\s+(using|any)\b.*\b(call|invoke|run)\b",
    r"\byou\s+must\s+(first\s+)?(call|invoke|export|send)\b",
    r"\brequired\s+for\s+correct\b",
]

_PINNED_DIGESTS: dict[str, str] = {}  # server_name -> reviewed manifest sha256


@dataclass(frozen=True)
class ToolManifest:
    server_name: str
    description: str
    raw_blob: bytes  # exact bytes the registry served, for digesting


def _digest(blob: bytes) -> str:
    return hashlib.sha256(blob).hexdigest()


def _scan_for_directives(description: str) -> list[str]:
    hits = []
    for pat in _DIRECTIVE_PATTERNS:
        if re.search(pat, description, flags=re.IGNORECASE):
            hits.append(pat)
    return hits


def ingest_manifest(manifest: ToolManifest) -> str:
    """Return a provenance-tagged, non-directive rendering of the manifest.

    Fails closed if the manifest digest is unpinned or if it embeds directives.
    """
    pinned = _PINNED_DIGESTS.get(manifest.server_name)
    if pinned is None:
        raise ManifestInjectionError(
            f"server {manifest.server_name!r} has no pinned digest; "
            "refusing tools/list negotiation (possible registry poisoning)"
        )

    actual = _digest(manifest.raw_blob)
    if actual != pinned:
        raise ManifestInjectionError(
            f"digest mismatch for {manifest.server_name!r}: "
            f"pinned={pinned[:12]} served={actual[:12]}"
        )

    hits = _scan_for_directives(manifest.description)
    if hits:
        raise ManifestInjectionError(
            f"manifest for {manifest.server_name!r} embeds directives "
            f"(matched {hits}); treat as injection, do not comply"
        )

    # Only descriptive text reaches the model, wrapped as untrusted data.
    safe = manifest.description.replace("<", "&lt;").replace(">", "&gt;")
    return f'<tool_meta trust="untrusted" server="{manifest.server_name}">{safe}</tool_meta>'
