# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-distrust-a-tool-manifest-the-descriptor-to-invocation-gap-in-poisoned-mcp-registries.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-distrust-a-tool-manifest-the-descriptor-to-invocation-gap-in-poisoned-mcp-registries.warrant.json
# Markdown SHA-256:   06dc22c7420e7f4cfa9805299679534a6e93168dc171594bc5f9534f236f154f
# Code AST SHA-256:   1cc5452620f7c17fc23539c72d58b9a1cbb40a8b92ca4de83b59e4b9ca6f9398
# Verified Classes:   ManifestBoundaryViolation, BoundTool
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class ManifestBoundaryViolation(RuntimeError):
    """Raised when an untrusted manifest field would enter the argument path."""


# Fields whose *type shape* may be read from an untrusted source.
TYPE_SHAPE_KEYS = {"type", "properties", "required", "items"}

# Fields whose *value space* must never be accepted from an untrusted source.
VALUE_SPACE_KEYS = {"default", "enum", "examples", "const"}


@dataclass
class BoundTool:
    name: str
    schema: dict[str, Any]
    degraded: bool
    dropped_fields: list[str] = field(default_factory=list)


def bind_manifest_tool(name: str, raw_schema: dict[str, Any]) -> BoundTool:
    """Bind a tool from an untrusted manifest, stripping value-space fields.

    The agent authors the value space; the manifest may only contribute the
    type shape. Anything that could inject arguments or constrain the model's
    action space is dropped and the tool is bound in degraded mode.
    """
    if not isinstance(raw_schema, dict):
        raise ManifestBoundaryViolation(
            f"tool {name!r}: manifest schema is not an object"
        )

    dropped: list[str] = []
    stripped: dict[str, Any] = {}

    for key, value in raw_schema.items():
        if key in VALUE_SPACE_KEYS:
            dropped.append(key)
            continue
        if key.startswith("x-") or key.startswith("x_"):
            dropped.append(key)
            continue
        if key == "properties" and isinstance(value, dict):
            clean_props: dict[str, Any] = {}
            for prop_name, prop in value.items():
                if not isinstance(prop, dict):
                    raise ManifestBoundaryViolation(
                        f"tool {name!r}: property {prop_name!r} is not an object"
                    )
                # A permissive object property is an injection surface:
                # arbitrary nested keys can carry payloads the model never emits.
                if prop.get("type") == "object" and prop.get(
                    "additionalProperties", True
                ):
                    dropped.append(f"properties.{prop_name}.additionalProperties")
                    prop = {k: v for k, v in prop.items() if k != "additionalProperties"}
                    prop["additionalProperties"] = False
                clean_props[prop_name] = {
                    k: v for k, v in prop.items() if k in TYPE_SHAPE_KEYS
                }
                for k in prop:
                    if k not in TYPE_SHAPE_KEYS:
                        dropped.append(f"properties.{prop_name}.{k}")
            stripped["properties"] = clean_props
            continue
        if key in TYPE_SHAPE_KEYS:
            stripped[key] = value
            continue
        # Unrecognized top-level key: do not guess, do not carry it forward.
        dropped.append(key)

    if dropped:
        return BoundTool(name=name, schema=stripped, degraded=True, dropped_fields=dropped)
    return BoundTool(name=name, schema=stripped, degraded=False)


def construct_arguments(
    tool: BoundTool, model_emitted: dict[str, Any]
) -> dict[str, Any]:
    """Build the wire arguments from model output only.

    No default is ever merged. If the model omitted a required argument, the
    call fails loudly so the model must reason about the gap rather than
    receive an injected value.
    """
    required = tool.schema.get("required", [])
    missing = [r for r in required if r not in model_emitted]
    if missing:
        raise ManifestBoundaryViolation(
            f"tool {tool.name!r}: model omitted required args {missing}; "
            "refusing to inject manifest defaults"
        )
    allowed = set(tool.schema.get("properties", {}))
    extra = [k for k in model_emitted if k not in allowed]
    if extra:
        raise ManifestBoundaryViolation(
            f"tool {tool.name!r}: model emitted undeclared args {extra}; "
            "possible action-space poisoning"
        )
    return dict(model_emitted)
