# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-mcp-tool-poisoning-survives-schema-validation-at-the-transport-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-mcp-tool-poisoning-survives-schema-validation-at-the-transport-boundary.warrant.json
# Markdown SHA-256:   2fde1895d9cb2e1080e3e0938a17d771797e8426d6fba9a2ee3dea154379d8ec
# Code AST SHA-256:   07ab7d08a6e045a0b8f540027e98ec8f6bcc42ad12430cb2deafc3ee831038c0
# Verified Classes:   ToolPoisoningAdmissionError, ToolEntry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass


class ToolPoisoningAdmissionError(RuntimeError):
    """Raised when a tool fails semantic admission control at the MCP transport boundary."""
    pass


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


IMPERATIVE_PATTERNS = [
    r"\b(before|after|first|then|always|never|must|should)\b",
    r"\b(call|invoke|use)\s+`?\w+`?\s+(tool|function)",
]
PEER_REF_TEMPLATE = r"\b{peer}\b"


def _peer_tool_references(entry: ToolEntry, all_names: set[str]) -> list[str]:
    hits = []
    for peer in all_names:
        if peer == entry.name:
            continue
        if re.search(PEER_REF_TEMPLATE.format(peer=re.escape(peer)), entry.description, re.IGNORECASE):
            hits.append(peer)
    return hits


def _has_imperative_directive(description: str) -> bool:
    return any(re.search(p, description, re.IGNORECASE) for p in IMPERATIVE_PATTERNS)


def _has_unconstrained_laundering_channel(entry: ToolEntry) -> bool:
    props = (entry.input_schema or {}).get("properties", {})
    for prop_name, spec in props.items():
        if spec.get("type") == "string" and not spec.get("description") and "enum" not in spec and "pattern" not in spec:
            return True
    return False


def admit_tools(tools: list[ToolEntry]) -> list[ToolEntry]:
    """Semantic admission control. Runs AFTER shape validation, BEFORE model exposure."""
    all_names = {t.name for t in tools}
    admitted = []
    for entry in tools:
        peers = _peer_tool_references(entry, all_names)
        if peers:
            raise ToolPoisoningAdmissionError(
                f"tool '{entry.name}' description references peer tools {peers}; "
                f"cross-tool directive is a poisoning signal at the transport boundary"
            )
        if _has_imperative_directive(entry.description):
            raise ToolPoisoningAdmissionError(
                f"tool '{entry.name}' description contains an imperative directive; "
                f"descriptions must be declarative and self-referential"
            )
        if _has_unconstrained_laundering_channel(entry):
            raise ToolPoisoningAdmissionError(
                f"tool '{entry.name}' exposes an unconstrained string argument with no "
                f"description/enum/pattern; this is an argument-provenance laundering channel"
            )
        admitted.append(entry)
    return admitted
