# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-mcp-tool-manifest-after-a-legitimate-server-update-the-descriptor-hash-continuity-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-mcp-tool-manifest-after-a-legitimate-server-update-the-descriptor-hash-continuity-gap.warrant.json
# Markdown SHA-256:   15554bccd759969871ca058a1c8f9a79fd6c939560a8c58714f0f44a748c41b3
# Code AST SHA-256:   d7dea8c6550bfa9ec0011231f1a7f8fe08f9b9bcdaed4d70a7710ac532cec3e5
# Verified Classes:   DescriptorAdmissionError, ApprovedDescriptor, DescriptorAdmissionGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional


class DescriptorAdmissionError(RuntimeError):
    """Raised when a tool descriptor delta violates the admission invariant."""
    pass


@dataclass
class ApprovedDescriptor:
    name: str
    descriptor_hash: str
    approved_by: str


@dataclass
class DescriptorAdmissionGate:
    # Trust is keyed on descriptor hash, NOT on server identity.
    approved: dict[str, ApprovedDescriptor] = field(default_factory=dict)
    # Imperative verbs that should never appear in a tool description as instructions.
    instruction_markers: tuple[str, ...] = (
        "always include", "you must", "before calling",
        "make sure to", "remember to",
    )

    @staticmethod
    def _hash(descriptor: dict) -> str:
        canonical = json.dumps(
            {
                "name": descriptor["name"],
                "description": descriptor.get("description", ""),
                "inputSchema": descriptor.get("inputSchema", {}),
            },
            sort_keys=True,
            separators=(",", ":"),
        )
        return hashlib.sha256(canonical.encode("utf-8")).hexdigest()

    def _scan_for_injection(self, descriptor: dict) -> Optional[str]:
        desc = descriptor.get("description", "").lower()
        for marker in self.instruction_markers:
            if marker in desc:
                return marker
        return None

    def admit(self, descriptor: dict, server_id: str, approver: Optional[str] = None) -> str:
        """
        Decide whether a descriptor may enter the planner action space.
        server_id is recorded for audit only; it does NOT grant trust.
        """
        name = descriptor["name"]
        new_hash = self._hash(descriptor)

        injection = self._scan_for_injection(descriptor)
        if injection is not None:
            raise DescriptorAdmissionError(
                f"Tool '{name}' from server '{server_id}' contains instructional "
                f"marker '{injection}' in its description; descriptor quarantined. "
                f"Descriptor hash {new_hash[:12]} requires manual review."
            )

        prior = self.approved.get(name)

        if prior is None:
            # First-seen tool: full approval flow required.
            if approver is None:
                raise DescriptorAdmissionError(
                    f"Tool '{name}' is new (hash {new_hash[:12]}); "
                    f"no approval on record. Refusing to admit to planner."
                )
            self.approved[name] = ApprovedDescriptor(name, new_hash, approver)
            return new_hash

        if prior.descriptor_hash == new_hash:
            return new_hash  # unchanged, silent reuse

        # Changed hash on a previously-approved tool: the dangerous middle case.
        # A patch bump or same-server origin is NOT evidence of benign delta.
        if approver is None:
            raise DescriptorAdmissionError(
                f"Tool '{name}' descriptor changed on server '{server_id}' "
                f"({prior.descriptor_hash[:12]} -> {new_hash[:12]}). "
                f"Server identity continuity does not authorize descriptor delta. "
                f"Re-approval required; downstream embeddings keyed on old hash "
                f"must be invalidated."
            )

        self.approved[name] = ApprovedDescriptor(name, new_hash, approver)
        return new_hash


def handle_tools_list(gate: DescriptorAdmissionGate, server_id: str, tools: list[dict],
                      approver: Optional[str] = None) -> list[str]:
    admitted = []
    for tool in tools:
        admitted.append(gate.admit(tool, server_id=server_id, approver=approver))
    return admitted
