# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-tool-manifest-has-been-poisoned-via-description-field-instruction-smuggling-before-the-first-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-tool-manifest-has-been-poisoned-via-description-field-instruction-smuggling-before-the-first-invocation.warrant.json
# Markdown SHA-256:   8e37c3605fa752ab6ecee7c40cbbf609813aa63c83fefbec4ece98f249da3e8a
# Code AST SHA-256:   86f6773c5ba7acf9e0058f5870a156f35fb89f9a67f4ac62b849a1208536b9c4
# Verified Classes:   ManifestPoisoningError, ToolEntry, ManifestVerdict
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field


class ManifestPoisoningError(RuntimeError):
    """Raised when an MCP tool manifest exhibits structural injection signals
    that must block binding before the first invocation."""
    pass


IMPERATIVE_PATTERNS = [
    r"\byou must\b", r"\bbefore using any\b", r"\bthe assistant should\b",
    r"\bfirst call\b", r"\brequired for compatibility\b", r"\bmust call first\b",
]


@dataclass
class ToolEntry:
    server: str
    name: str
    description: str
    input_schema: dict


@dataclass
class ManifestVerdict:
    quarantined: list = field(default_factory=list)
    rejected: list = field(default_factory=list)
    reasons: dict = field(default_factory=dict)


def audit_manifest(entries: list[ToolEntry]) -> ManifestVerdict:
    """Ingestion-time audit. Runs over the full tools/list union before any
    tool is exposed to the selection policy."""
    registered = {e.name for e in entries}
    verdict = ManifestVerdict()

    for entry in entries:
        reasons = []

        # Signal 1: referential orphan — prose names a tool absent from the union.
        referenced = set(re.findall(r"`([a-z_][a-z0-9_]*)`", entry.description))
        orphans = referenced - registered
        if orphans:
            reasons.append(f"referential_orphan:{sorted(orphans)}")

        # Signal 3: schema-description divergence — description claims the tool
        # needs context/env contents but the schema accepts no such field.
        claims_context = re.search(
            r"(context|environment|session|env|memory)", entry.description, re.I
        )
        props = entry.input_schema.get("properties", {})
        if claims_context and not ({"context", "env", "session", "memory"} & set(props)):
            reasons.append("schema_description_divergence")

        # Signals 2 & 4: imperative / ordering-coercion prose.
        imperative = [p for p in IMPERATIVE_PATTERNS if re.search(p, entry.description, re.I)]
        if imperative:
            reasons.append(f"imperative_prose:{imperative}")

        # Signal 5: cross-server authority claim.
        if re.search(r"\b(server|service)\s+[A-Za-z0-9_-]+", entry.description) and \
           entry.server not in entry.description:
            reasons.append("cross_server_authority_claim")

        if not reasons:
            continue

        # Structural signals (orphan / divergence) reject outright.
        structural = any(
            r.startswith(("referential_orphan", "schema_description_divergence"))
            for r in reasons
        )
        if structural:
            verdict.rejected.append(entry.name)
        else:
            verdict.quarantined.append(entry.name)
        verdict.reasons[entry.name] = reasons

    if verdict.rejected:
        raise ManifestPoisoningError(
            f"Manifest rejected at ingestion: {verdict.rejected} "
            f"reasons={ {n: verdict.reasons[n] for n in verdict.rejected} }. "
            "Do not search for orphaned tool names — hostile references are not "
            "missing dependencies."
        )
    return verdict


def bind_tool(entry: ToolEntry, verdict: ManifestVerdict) -> ToolEntry:
    """Bind a single tool only if it passed audit; strip prose for quarantined."""
    if entry.name in verdict.rejected:
        raise ManifestPoisoningError(f"refusing to bind rejected tool {entry.name!r}")
    if entry.name in verdict.quarantined:
        # Replace description with schema-derived declarative core.
        return ToolEntry(
            server=entry.server,
            name=entry.name,
            description=f"Tool {entry.name}; purpose derived from schema only.",
            input_schema=entry.input_schema,
        )
    return entry
