# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-dynamically-loaded-tool-description-as-untrusted-executable-policy-rather-than-inert-metadata.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-dynamically-loaded-tool-description-as-untrusted-executable-policy-rather-than-inert-metadata.warrant.json
# Markdown SHA-256:   b24e0781f897eef3658f536252f1affc7092680d12e326239bcdf199540fb2f1
# Code AST SHA-256:   d730ac4da82e9b2ea5d911975c7a9ce5e095caf4ccfb2c9d5f3a61333dc42830
# Verified Classes:   ManifestPolicyViolation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ManifestPolicyViolation(RuntimeError):
    """Raised when a dynamically loaded tool manifest attempts to carry behavioral authority."""
    pass


TRUSTED_BEHAVIORAL_FIELDS = frozenset()  # no remote field may alter the call graph


def load_tool_manifest(manifest: dict, known_tool_names: set[str]) -> dict:
    """Load a remote MCP manifest, quarantining any field that could alter the call graph.

    Returns a sanitized descriptor safe to place in the planner context.
    Raises ManifestPolicyViolation if the manifest cannot be safely loaded.
    """
    name = manifest.get("name")
    if not name:
        raise ManifestPolicyViolation("manifest missing 'name'")

    schema = manifest.get("schema", {})
    if not isinstance(schema, dict):
        raise ManifestPolicyViolation(f"{name}: schema must be an object")

    description = manifest.get("description", "")
    examples = manifest.get("examples", [])

    # Condition 3: a manifest may not name another tool.
    for tool in known_tool_names:
        if tool != name and tool in description:
            raise ManifestPolicyViolation(
                f"{name}: description references foreign tool '{tool}' — "
                "cross-tool behavioral authority is not permitted"
            )

    # Condition 4: defaults may not instruct omission.
    for prop, spec in schema.get("properties", {}).items():
        if "default" in spec and "omit" in str(spec.get("default", "")).lower():
            raise ManifestPolicyViolation(
                f"{name}.{prop}: default encodes an omission directive"
            )

    # Condition 2: prose is dropped from the planner context; schema is retained.
    # Only schema-constraining fields survive; description/examples are display-only
    # and are NOT rendered into the reasoning prompt.
    sanitized = {
        "name": name,
        "schema": schema,
        "display_description": description,  # for UI only, never planner context
        "trust_class": "schema-constraining",
    }
    return sanitized


def register_tool(manifest: dict, registry: dict[str, dict]) -> None:
    known = set(registry.keys())
    try:
        sanitized = load_tool_manifest(manifest, known)
    except ManifestPolicyViolation:
        raise
    registry[sanitized["name"]] = sanitized
