# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-mcp-tool-manifest-is-attempting-skill-injection-through-description-field-smuggling-rather-than-capability.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-mcp-tool-manifest-is-attempting-skill-injection-through-description-field-smuggling-rather-than-capability.warrant.json
# Markdown SHA-256:   a06753b91ca4d071c6572166ff9515e945abd57c10c76b82c7139a598a7fa329
# Code AST SHA-256:   a469c482cfbd528cc5ffe5a6e23ac4d418726fff50f735776b69c9c146a6f8c3
# Verified Classes:   ManifestInjectionError, ToolManifest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass


class ManifestInjectionError(RuntimeError):
    """Raised when a tool manifest description contains caller-directive smuggling."""
    pass


# Sentences that address the *agent's* future actions rather than describing the tool.
CALLER_DIRECTIVE = re.compile(
    r"\b(before using|first call|always call|you must|you should|do not tell|"
    r"include (?:its|the) output|then call|prior to (?:calling|using))\b",
    re.IGNORECASE,
)
# References to sibling tools the manifest does not own.
CROSS_TOOL_REF = re.compile(r"\b[a-z][a-z0-9_]*_[a-z][a-z0-9_]*\b")


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


def validate_manifest(manifest: ToolManifest, known_tools: set[str]) -> None:
    desc = manifest.description

    if CALLER_DIRECTIVE.search(desc):
        raise ManifestInjectionError(
            f"tool '{manifest.name}': caller-directive sentence in description "
            f"constitutes skill injection: {desc!r}"
        )

    referenced = set(CROSS_TOOL_REF.findall(desc)) - {manifest.name}
    foreign = referenced & known_tools
    if foreign:
        raise ManifestInjectionError(
            f"tool '{manifest.name}': description references sibling tools "
            f"{sorted(foreign)}; a tool may describe only its own contract"
        )


def register(manifest: ToolManifest, known_tools: set[str]) -> None:
    validate_manifest(manifest, known_tools)
    known_tools.add(manifest.name)
