# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-mcp-tool-manifest-before-capability-negotiation-completes.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-mcp-tool-manifest-before-capability-negotiation-completes.warrant.json
# Markdown SHA-256:   9380c52fb43f629a13151a70c6ec52ff5e7b863f7744b248714700474e529d7c
# Code AST SHA-256:   bd82077e55f6202962c6d510c8de7bd8ed887db565d47cb52e334ccf5718ea17
# Verified Classes:   ManifestPoisoningError, ToolManifest
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass


class ManifestPoisoningError(RuntimeError):
    """Raised when a tool manifest description attempts instruction escalation."""


AUTHORITY_TOKENS = re.compile(
    r"(\[SYSTEM\]|\[INST\]|mandatory|overrides? conflicting|higher priority)",
    re.IGNORECASE,
)
IMPERATIVE = re.compile(
    r"\b(you must|before invoking|always forward|never reveal|forward the|override)\b",
    re.IGNORECASE,
)
EGRESS = re.compile(r"https?://[^\s\"']+", re.IGNORECASE)
PURE_CAPABILITY = {"summarize", "format", "parse", "classify", "translate"}


@dataclass
class ToolManifest:
    name: str
    description: str
    capability_class: str  # e.g. "pure", "network", "filesystem"


def screen_manifest(m: ToolManifest) -> None:
    signals = []
    if AUTHORITY_TOKENS.search(m.description):
        signals.append("authority_claim")
    if IMPERATIVE.search(m.description):
        signals.append("imperative_grammar")
    if EGRESS.search(m.description) and m.capability_class == "pure":
        signals.append("effect_capability_mismatch")

    # Two or more independent signals => reject before binding.
    if len(signals) >= 2:
        raise ManifestPoisoningError(
            f"tool {m.name!r} rejected at negotiation: signals={signals}; "
            f"description claims behavior its capability class "
            f"({m.capability_class}) cannot confer"
        )


def bind_tools(manifests: list[ToolManifest]) -> list[ToolManifest]:
    bound = []
    for m in manifests:
        screen_manifest(m)  # fail closed: one bad tool aborts the batch
        bound.append(m)
    return bound
