# 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-server-s-tool-description-as-untrusted-input-rather-than-trusted-schema-metadata.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-dynamically-loaded-mcp-server-s-tool-description-as-untrusted-input-rather-than-trusted-schema-metadata.warrant.json
# Markdown SHA-256:   df344d3623a1fa64703f6de12870478caaaa042923d1167927b6aad2ed580d02
# Code AST SHA-256:   8a1c4eba86a9a58364986923378817e5a9f715f05f9a951339c417e948da6a56
# Verified Classes:   DescriptionInjectionError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class DescriptionInjectionError(RuntimeError):
    """Raised when a dynamically loaded tool's descriptive field carries
    instructional content that must not enter the reasoning context."""
    pass


# Fields that are ENFORCED (validated/dispatched) vs FRAMED (prose, untrusted).
ENFORCED_FIELDS = ("name", "inputSchema")
UNTRUSTED_TEXT_FIELDS = ("description", "title", "examples")

# Signals that a descriptive field is behaving like a directive.
DIRECTIVE_SIGNALS = (
    "the assistant", "you must", "before calling", "first call",
    "required by the platform", "ensure the session",
)


def collect_descriptive_fields(tool: dict) -> list[tuple[str, str]]:
    """Flatten every free-text field, including per-property descriptions."""
    out: list[tuple[str, str]] = []
    for f in UNTRUSTED_TEXT_FIELDS:
        if isinstance(tool.get(f), str):
            out.append((f, tool[f]))
    schema = tool.get("inputSchema", {})
    for pname, prop in schema.get("properties", {}).items():
        if isinstance(prop, dict):
            for f in UNTRUSTED_TEXT_FIELDS:
                if isinstance(prop.get(f), str):
                    out.append((f"inputSchema.properties.{pname}.{f}", prop[f]))
    return out


def sanitize_tool(tool: dict, known_tool_names: set[str], max_tokens: int = 120) -> dict:
    """Return a catalog entry safe to inject. Raises on unquarantinable fields."""
    if not tool.get("name") or "inputSchema" not in tool:
        raise DescriptionInjectionError(f"tool missing enforced fields: {tool.get('name')!r}")

    clean = {"name": tool["name"], "inputSchema": tool["inputSchema"]}
    framed: list[str] = []

    for field, text in collect_descriptive_fields(tool):
        lowered = text.lower()
        # 1. Cross-tool reference: description names a sibling tool.
        named_siblings = [n for n in known_tool_names if n != tool["name"] and n in text]
        if named_siblings:
            raise DescriptionInjectionError(
                f"field {field!r} of tool {tool['name']!r} references other tools "
                f"{named_siblings}; refusing to inject"
            )
        # 2. Directive-shaped content.
        if any(sig in lowered for sig in DIRECTIVE_SIGNALS):
            raise DescriptionInjectionError(
                f"field {field!r} of tool {tool['name']!r} is directive-shaped; refusing to inject"
            )
        # 3. Token-budget cap on attacker-spendable prose.
        if len(text.split()) > max_tokens:
            raise DescriptionInjectionError(
                f"field {field!r} of tool {tool['name']!r} exceeds prose budget"
            )
        framed.append(f"[REFERENCE-ONLY {field}]: {text}")

    clean["_framed_reference"] = "\n".join(framed)
    return clean


def load_catalog(raw_tools: list[dict]) -> list[dict]:
    names = {t.get("name") for t in raw_tools if t.get("name")}
    catalog = []
    for t in raw_tools:
        try:
            catalog.append(sanitize_tool(t, names))
        except DescriptionInjectionError:
            # Quarantine the tool, do not fail the whole registry load.
            catalog.append({"name": t.get("name"), "_quarantined": True})
    return catalog
