# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-auto-discovers-a-tool-whose-inputschema-declares-a-hidden-required-property-that-the-planner-never-intends-to-populate-c.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-auto-discovers-a-tool-whose-inputschema-declares-a-hidden-required-property-that-the-planner-never-intends-to-populate-c.warrant.json
# Markdown SHA-256:   8b6442325b436233fda4a3e990490c0cdc8ac211aa75b8e3ffad78cd5e8deb27
# Code AST SHA-256:   436a171b7b9a96d7662081e1a478cbce3731553e0ac15e99e27b6843183d6639
# Verified Classes:   SchemaPoisoningError, ToolParam, RegisteredTool
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Literal


class SchemaPoisoningError(RuntimeError):
    """Raised when a dynamically-registered tool schema forces the planner to emit
    an argument the runtime cannot source from a principal-authorized origin."""


ArgSource = Literal["user", "tool_output", "runtime", "context_mined"]


@dataclass(frozen=True)
class ToolParam:
    name: str
    required: bool
    source: ArgSource


@dataclass
class RegisteredTool:
    name: str
    params: list[ToolParam]
    description: str
    schema_hash: str
    authorized_params: frozenset[str] = field(default_factory=frozenset)


def build_planner_grammar(tool: RegisteredTool) -> list[str]:
    """Return the parameter names the planner is permitted to emit.

    The grammar is the intersection of schema-required params and the runtime's
    capability manifest. A required param with no authorized source is a
    schema-poisoning condition, not a coercion opportunity.
    """
    grammar: list[str] = []
    for p in tool.params:
        if not p.required:
            continue
        if p.name not in tool.authorized_params:
            raise SchemaPoisoningError(
                f"tool {tool.name!r} declares required param {p.name!r} "
                f"with no principal-authorized source; refusing to coerce planner"
            )
        if p.source == "context_mined":
            raise SchemaPoisoningError(
                f"tool {tool.name!r} param {p.name!r} would be sourced from "
                f"context (potential secret exfiltration); quarantining tool"
            )
        grammar.append(p.name)
    return grammar


def register_from_mcp_listing(listing: dict, manifest: dict[str, frozenset[str]]) -> RegisteredTool:
    name = listing["name"]
    schema = listing["inputSchema"]
    required = set(schema.get("required", []))
    params = [
        ToolParam(
            name=pname,
            required=pname in required,
            source="context_mined" if pname not in manifest.get(name, frozenset()) else "user",
        )
        for pname in schema.get("properties", {})
    ]
    tool = RegisteredTool(
        name=name,
        params=params,
        description=listing.get("description", ""),
        schema_hash=hash(frozenset(required)),
        authorized_params=manifest.get(name, frozenset()),
    )
    # Fail-closed at registration time, not at first invocation.
    build_planner_grammar(tool)
    return tool
