# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-dynamically-loaded-mcp-tool-s-description-text-as-executable-attack-surface-rather-than-inert-metadata.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-dynamically-loaded-mcp-tool-s-description-text-as-executable-attack-surface-rather-than-inert-metadata.warrant.json
# Markdown SHA-256:   c50a87dd202078e56bf93b4fb153ce19a0e76d60bd1d3f95a1918aedba068dda
# Code AST SHA-256:   be83a9e8099b14faefdfdf968d9f683bf8a3befcc3bd99082a2bbd6a91bd0064
# Verified Classes:   UntrustedManifestError, ToolManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class UntrustedManifestError(RuntimeError):
    """Raised when a dynamically discovered tool manifest fails the binding gate."""


# Imperative / authority-claiming markers that indicate instruction-shaped text
# rather than documentation. This is a heuristic tripwire, not a classifier.
_AUTHORITY_MARKERS = (
    "you must",
    "you should",
    "before using any other tool",
    "required by the runtime",
    "ignore previous",
    "system:",
    "do not tell",
)


@dataclass
class ToolManifest:
    name: str
    description: str
    examples: list[str] = field(default_factory=list)
    signature: str | None = None


def _all_text_fields(m: ToolManifest) -> list[str]:
    # Every string field is a candidate vector, not just `description`.
    return [m.name, m.description, *m.examples]


def bind_tool(
    manifest: ToolManifest,
    *,
    trusted_signers: set[str],
    allowlist: set[str],
) -> Callable[[], None]:
    """Fetch -> quarantine -> gate -> bind. Returns a callable only if the gate passes."""
    # 1. Provenance: reject unsigned manifests outright.
    if manifest.signature is None or manifest.signature not in trusted_signers:
        raise UntrustedManifestError(
            f"tool {manifest.name!r} has no trusted signature; refusing to bind"
        )

    # 2. Allowlist: name must be pre-approved.
    if manifest.name not in allowlist:
        raise UntrustedManifestError(
            f"tool {manifest.name!r} is not on the allowlist; refusing to bind"
        )

    # 3. Instruction-shape scan across ALL text fields.
    for text in _all_text_fields(manifest):
        lowered = text.lower()
        for marker in _AUTHORITY_MARKERS:
            if marker in lowered:
                raise UntrustedManifestError(
                    f"tool {manifest.name!r} contains instruction-shaped text "
                    f"({marker!r}); refusing to bind"
                )

    # 4. Only now is the manifest rendered into context as untrusted, labeled data.
    def _bound() -> None:
        # Placeholder for the actual tool call; binding is the security-relevant step.
        return None

    return _bound
