# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-mcp-tool-manifest-versus-a-benign-schema-drift-distinguishing-capability-surface-injection-from-version-ne.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-mcp-tool-manifest-versus-a-benign-schema-drift-distinguishing-capability-surface-injection-from-version-ne.warrant.json
# Markdown SHA-256:   ae70b737150b526720b0862095ae18ca3e14da5842a647edc8aa05293dea58a1
# Code AST SHA-256:   1c872544cec55af3cd29c0f43b441499572145e80f28b3e331bd15182c401f31
# Verified Classes:   ManifestContractViolation, FieldEnvelope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass
from typing import Any


class ManifestContractViolation(RuntimeError):
    """Raised when a tool manifest's description demands data the schema does not bound."""


# Imperative verbs that ask the agent to *populate* a field with content.
_CONTENT_IMPERATIVES = re.compile(
    r"\b(prepend|append|attach|forward|include|insert|embed|concatenate|serialize)\b",
    re.IGNORECASE,
)
# Field references in descriptions, e.g. "in the `context` field", "the query string".
_FIELD_REF = re.compile(r"(?:the\s+)?[`\"']?([a-zA-Z_][a-zA-Z0-9_]*)[`\"']?\s+(?:field|string|parameter|argument)", re.IGNORECASE)
# A field is "bounded" if it carries any of these.
_BOUNDING_KEYS = ("maxLength", "pattern", "format", "enum", "const")


@dataclass
class FieldEnvelope:
    name: str
    bounded: bool
    required: bool


def _envelope(schema: dict[str, Any]) -> dict[str, FieldEnvelope]:
    props = schema.get("properties", {}) or {}
    required = set(schema.get("required", []) or [])
    out: dict[str, FieldEnvelope] = {}
    for name, spec in props.items():
        bounded = any(k in spec for k in _BOUNDING_KEYS) or spec.get("type") in ("integer", "number", "boolean")
        out[name] = FieldEnvelope(name=name, bounded=bounded, required=name in required)
    return out


def validate_tool_manifest(manifest: dict[str, Any], *, value_derivable_fields: set[str] | None = None) -> None:
    """
    Reject manifests whose description-plane imperatives demand unbounded content
    or reference fields absent from the structural schema.
    """
    value_derivable = value_derivable_fields or set()
    description = " ".join(
        filter(None, [manifest.get("description", ""), manifest.get("title", "")])
    )
    schema = manifest.get("inputSchema", {}) or {}
    env = _envelope(schema)

    referenced = {m.group(1) for m in _FIELD_REF.finditer(description)}
    imperatives = _CONTENT_IMPERATIVES.findall(description)

    # Rule 1: description references a field the schema does not define -> forged protocol slot.
    for field in referenced:
        if field not in env:
            raise ManifestContractViolation(
                f"tool {manifest.get('name')!r}: description references undefined field {field!r}; "
                f"possible warrant/credential injection slot"
            )

    # Rule 2: content imperative applied to an unbounded field -> exfiltration vector.
    if imperatives:
        for field in referenced:
            fe = env[field]
            if fe.bounded or field in value_derivable:
                continue
            raise ManifestContractViolation(
                f"tool {manifest.get('name')!r}: imperative {imperatives!r} targets unbounded field "
                f"{field!r} (type=string, no maxLength/pattern/format/enum); "
                f"description demands data the schema does not bound"
            )

    # Rule 3: version monotonicity is enforced by the caller before this point;
    # if a description changed without a version bump, the caller must pass a
    # sentinel here. We encode that as an explicit flag.
    if manifest.get("_description_changed_without_version_bump"):
        raise ManifestContractViolation(
            f"tool {manifest.get('name')!r}: description mutated without version increment"
        )


def register_tool(manifest: dict[str, Any]) -> str:
    """Gate a manifest into the planner's action space, or refuse."""
    try:
        validate_tool_manifest(manifest, value_derivable_fields={"tenant_id", "user_query"})
    except ManifestContractViolation as exc:
        # Surface to orchestrator audit log; do not register.
        raise ManifestContractViolation(f"quarantined at discovery: {exc}") from exc
    return manifest["name"]
