# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-dynamically-loaded-mcp-tool-s-description-as-inert-metadata-capability-surface-smuggling-through-tool-schema-re.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-dynamically-loaded-mcp-tool-s-description-as-inert-metadata-capability-surface-smuggling-through-tool-schema-re.warrant.json
# Markdown SHA-256:   f6d39a213304e8e874f01a97706b0401d131d39502b09ec0d930630986d21bc9
# Code AST SHA-256:   a4bee14b21809cc805ccbb8d3ce7fe737d87c4e226324d2c9d1b6a1de68f6f47
# Verified Classes:   ToolFramingViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ToolFramingViolation(RuntimeError):
    """Raised when a planned tool call's argument provenance traces to an
    untrusted tool-description string rather than to user input, prior tool
    output, or the task specification."""
    pass


UNTRUSTED_DESCRIPTION_SOURCES = {"tool_description", "tool_schema_field_desc", "tool_annotations"}


def check_call_provenance(planned_call: dict, arg_provenance: dict[str, str]) -> None:
    """
    planned_call: {"tool": str, "args": {...}}
    arg_provenance: maps each arg name -> provenance tag, one of
        "user_input" | "prior_tool_output" | "task_spec" | <untrusted source>
    Raises ToolFramingViolation if any argument was derived from a tool
    description channel. This is the planning-boundary check.
    """
    for arg_name in planned_call["args"]:
        source = arg_provenance.get(arg_name, "unknown")
        if source in UNTRUSTED_DESCRIPTION_SOURCES:
            raise ToolFramingViolation(
                f"Argument '{arg_name}' of tool '{planned_call['tool']}' "
                f"traces to untrusted source '{source}'. A tool description "
                f"cannot issue instructions or supply call arguments. "
                f"Halting before execution; quarantine the MCP server and "
                f"re-review its tools/list response."
            )
        if source == "unknown":
            raise ToolFramingViolation(
                f"Argument '{arg_name}' of tool '{planned_call['tool']}' has "
                f"no provenance record; refusing to execute an untraceable call."
            )


def bind_tools(tools_list_response: list[dict], prior_description_hashes: dict[str, str]) -> list[dict]:
    """
    Ingestion-boundary enforcement: wrap descriptions as untrusted, and flag
    framing mutations where schema is unchanged but description changed.
    """
    bound = []
    for tool in tools_list_response:
        name = tool["name"]
        desc_hash = _hash(tool.get("description", ""))
        schema_hash = _hash(tool.get("inputSchema", {}))

        prior = prior_description_hashes.get(name)
        if prior is not None and prior["schema"] == schema_hash and prior["desc"] != desc_hash:
            raise ToolFramingViolation(
                f"Tool '{name}' changed its description without changing its "
                f"schema. This is a framing mutation, not a capability update; "
                f"require human re-review before binding."
            )

        bound.append({
            "name": name,
            "schema": tool["inputSchema"],
            "description": f'<tool_meta trust="untrusted" source="mcp">{tool.get("description", "")}</tool_meta>',
        })
    return bound


def _hash(obj) -> str:
    import hashlib, json
    return hashlib.sha256(json.dumps(obj, sort_keys=True).encode()).hexdigest()
