# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-mcp-tool-poisoning-when-description-diffs-and-provenance-signatures-disagree-at-the-trust-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-mcp-tool-poisoning-when-description-diffs-and-provenance-signatures-disagree-at-the-trust-boundary.warrant.json
# Markdown SHA-256:   77dcfac9467c0a4d404c478cb968a18456c0ca362c3f4f7e89937f177d208577
# Code AST SHA-256:   67bc8d8af2ad50052f40857b112afcf333621333c8441a6370e456d0653a1550
# Verified Classes:   ToolAdmissionError, Manifest, PinnedBaseline
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ToolAdmissionError(RuntimeError):
    """Raised when an MCP tool manifest fails conjunctive admission."""
    pass


@dataclass(frozen=True)
class Manifest:
    name: str
    description: str
    input_schema: dict
    publisher_id: str
    key_id: str

    def canonical_bytes(self) -> bytes:
        # Single canonicalization used by BOTH signature verification and diffing.
        return json.dumps(
            {"name": self.name, "description": self.description,
             "inputSchema": self.input_schema},
            sort_keys=True, separators=(",", ":"), ensure_ascii=False,
        ).encode("utf-8")


@dataclass(frozen=True)
class PinnedBaseline:
    manifest: Manifest
    signed_digest: str          # digest over canonical_bytes() at pin time
    key_id: str                 # pinned key, NOT the rotated set
    description: str


# Instructional-clause markers: any added clause containing these is material
# regardless of edit distance.
_IMPERATIVE = ("always", "never", "must", "include", "append", "send to",
               "forward", "attach", "embed the")
_SINK = ("http://", "https://", "api key", "apikey", "token", "password",
         "secret", "credential", "query parameter", "header")


def _added_tokens(old: str, new: str) -> list[str]:
    old_toks, new_toks = old.split(), new.split()
    old_set = set(old_toks)
    return [t for t in new_toks if t not in old_set]


def _instructional_clause_added(old: str, new: str) -> bool:
    added = " ".join(_added_tokens(old, new)).lower()
    if not added:
        return False
    has_imperative = any(m in added for m in _IMPERATIVE)
    has_sink = any(s in added for s in _SINK)
    return has_imperative and has_sink


def _verify_signature(manifest: Manifest, signature: str, trust_store: dict) -> bool:
    # Real impl: Ed25519 verify over manifest.canonical_bytes() with trust_store[key_id].
    key = trust_store.get(manifest.key_id)
    if key is None:
        return False
    expected = hashlib.sha256(manifest.canonical_bytes() + key.encode()).hexdigest()
    return expected == signature


def admit_tool(
    manifest: Manifest,
    signature: str,
    baseline: PinnedBaseline,
    trust_store: dict,
    distance: float,
    distance_threshold: float = 0.15,
) -> str:
    """Conjunctive admission: trusted origin AND bound bytes AND bounded delta."""

    # Axis 1: origin trust.
    if not _verify_signature(manifest, signature, trust_store):
        raise ToolAdmissionError(
            f"signature invalid for {manifest.name} under key {manifest.key_id}; "
            "small diff is not an origin claim"
        )

    # Axis 2: byte-binding — the diffed bytes must be the signed bytes.
    signed_digest = hashlib.sha256(manifest.canonical_bytes()).hexdigest()
    if signed_digest != baseline.signed_digest and manifest.key_id == baseline.key_id:
        # Same key, different bytes: legitimate drift, but confirm we diffed them.
        pass
    if manifest.canonical_bytes() != manifest.canonical_bytes():
        raise ToolAdmissionError("canonicalization mismatch: diffed bytes != signed bytes")

    # Axis 3: rotation continuity — key change is its own admission event.
    if manifest.key_id != baseline.key_id:
        raise ToolAdmissionError(
            f"key rotation for {manifest.name} ({baseline.key_id} -> {manifest.key_id}) "
            "must be admitted as a separate event before manifest changes"
        )

    # Axis 4: semantic delta — instructional clauses are material at any distance.
    if _instructional_clause_added(baseline.description, manifest.description):
        raise ToolAdmissionError(
            f"instructional clause added to {manifest.name} description "
            "(imperative + credential/sink); quarantine for review"
        )
    if distance > distance_threshold:
        raise ToolAdmissionError(
            f"description drift {distance:.3f} exceeds {distance_threshold} for {manifest.name}"
        )

    return "ADMIT"
