# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-mcp-tool-manifest-is-already-resident-in-the-agent-s-tool-namespace.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-mcp-tool-manifest-is-already-resident-in-the-agent-s-tool-namespace.warrant.json
# Markdown SHA-256:   5cd83046a88c680b743470d9bffee1002f5542d945d248da89de56084c075f3d
# Code AST SHA-256:   496b0909cd0015747e0a2d32cd88f2d059e847aca5b1e9a0443343ec6f49b6aa
# Verified Classes:   DescriptorDriftError, ReservedSchemaKeyError, ToolNamespace
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class DescriptorDriftError(RuntimeError):
    """Raised when a re-advertised tool descriptor diverges from its authorized hash."""


class ReservedSchemaKeyError(ValueError):
    """Raised when a tool inputSchema declares a key outside the authorized surface."""


def canonical_descriptor(tool: dict) -> str:
    # Only the fields the model actually reads. Order-stable.
    payload = {
        "name": tool.get("name", ""),
        "description": tool.get("description", ""),
        "inputSchema": tool.get("inputSchema", {}),
        "annotations": tool.get("annotations", {}),
    }
    return json.dumps(payload, sort_keys=True, separators=(",", ":"))


def descriptor_hash(tool: dict) -> str:
    return hashlib.sha256(canonical_descriptor(tool).encode("utf-8")).hexdigest()


@dataclass
class ToolNamespace:
    authorized: dict[str, str] = field(default_factory=dict)  # tool_name -> hash

    def authorize(self, tool: dict) -> None:
        self.authorized[tool["name"]] = descriptor_hash(tool)

    def reconcile(self, advertised: list[dict]) -> list[dict]:
        """Return only tools whose content matches authorization. Quarantine the rest."""
        clean: list[dict] = []
        for tool in advertised:
            name = tool.get("name", "<unnamed>")
            if name not in self.authorized:
                # First observation: must go through provenance gate, not admitted here.
                continue
            current = descriptor_hash(tool)
            if current != self.authorized[name]:
                raise DescriptorDriftError(
                    f"tool '{name}' descriptor changed post-authorization: "
                    f"authorized={self.authorized[name][:12]} "
                    f"advertised={current[:12]}"
                )
            _reject_reserved_keys(tool)
            clean.append(tool)
        return clean


def _reject_reserved_keys(tool: dict) -> None:
    props = tool.get("inputSchema", {}).get("properties", {})
    for key in props:
        if key.startswith("_") or key in {"__proto__", "constructor"}:
            raise ReservedSchemaKeyError(
                f"tool '{tool.get('name')}' declares reserved schema key '{key}'"
            )


def admit_turn(namespace: ToolNamespace, tools_list_response: dict) -> list[dict]:
    advertised = tools_list_response.get("tools", [])
    return namespace.reconcile(advertised)
