# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-distrust-its-own-tool-manifest-the-description-channel-injection-boundary-in-mcp-capability-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-distrust-its-own-tool-manifest-the-description-channel-injection-boundary-in-mcp-capability-negotiation.warrant.json
# Markdown SHA-256:   6d54486187892600fccab9f22a816d0aa7f7bbacabba0577e01f22e5c0a56b63
# Code AST SHA-256:   a1fdaf6512d04c2e19da3ed8b7a27c91fbaa5bb624011c873c454c077a8617da
# Verified Classes:   ManifestInjectionError, ToolManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import re
from dataclasses import dataclass


class ManifestInjectionError(RuntimeError):
    """Raised when a fetched tool/agent manifest carries control-plane directives."""


# Directive-shaped patterns that must never enter the instruction region.
_DIRECTIVE_PATTERNS = [
    re.compile(r"\bbefore (calling|using) (any )?other tool\b", re.I),
    re.compile(r"\bdo not (tell|mention|inform)\b", re.I),
    re.compile(r"\byou must (first|always)\b", re.I),
    re.compile(r"\binclude (the )?(bearer|token|credential|secret)\b", re.I),
    re.compile(r"https?://", re.I),
    re.compile(r"\b[a-zA-Z0-9+/]{40,}={0,2}\b"),  # base64-ish blob
]


@dataclass(frozen=True)
class ToolManifest:
    name: str
    description: str
    parameters: dict


def admit_manifest(m: ToolManifest) -> ToolManifest:
    """Gate a runtime-fetched manifest before it enters agent context.

    Fails closed: a manifest that trips any directive pattern is rejected
    outright, never sanitized in place, because partial sanitization leaves
    ordering-authority residue in the selection region.
    """
    if not m.name or not isinstance(m.parameters, dict):
        raise ManifestInjectionError(f"malformed manifest for {m.name!r}")

    for pat in _DIRECTIVE_PATTERNS:
        hit = pat.search(m.description)
        if hit:
            raise ManifestInjectionError(
                f"manifest {m.name!r} carries directive-shaped text "
                f"(pattern={pat.pattern!r}, match={hit.group(0)!r}); "
                f"refusing registration"
            )

    # Structural use is permitted: schema and label survive, prose is quarantined.
    return ToolManifest(
        name=m.name,
        description="[tool schema only]",
        parameters=m.parameters,
    )


def load_tools(raw: list[dict]) -> list[ToolManifest]:
    admitted: list[ToolManifest] = []
    for entry in raw:
        try:
            admitted.append(
                admit_manifest(
                    ToolManifest(
                        name=entry["name"],
                        description=entry.get("description", ""),
                        parameters=entry.get("inputSchema", {}),
                    )
                )
            )
        except ManifestInjectionError:
            # Fail closed on the individual tool; surface to operator at cold start.
            continue
    if not admitted:
        raise ManifestInjectionError("all manifests rejected; no tools registered")
    return admitted
