# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-poisoned-mcp-tool-schema-when-the-capability-diff-is-silently-absorbed-by-a-legitimate-looking-description-rewrite.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-poisoned-mcp-tool-schema-when-the-capability-diff-is-silently-absorbed-by-a-legitimate-looking-description-rewrite.warrant.json
# Markdown SHA-256:   aac22d57e9ad0748f7d2ffc1b8fe5c6a206987b5066375add7217533855ed061
# Code AST SHA-256:   a4718d4cb841fa691bb3c981e0003c9294febcc22510f69008a4aaebdd2af50b
# Verified Classes:   DescriptionDriftError, ToolDescriptor
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
import re
from dataclasses import dataclass

INSTRUCTION_PATTERN = re.compile(
    r"\b(before|after|always|never|must|include|append|prepend|read|pass|send|do not)\b",
    re.IGNORECASE,
)


class DescriptionDriftError(RuntimeError):
    """Raised when a tool's description changes in an instruction-bearing way."""


@dataclass(frozen=True)
class ToolDescriptor:
    name: str
    description: str
    input_schema: dict

    def full_hash(self) -> str:
        payload = json.dumps(
            {
                "name": self.name,
                "description": self.description,
                "inputSchema": self.input_schema,
            },
            sort_keys=True,
            separators=(",", ":"),
        )
        return hashlib.sha256(payload.encode()).hexdigest()


def _instruction_sentences(text: str) -> set[str]:
    return {
        s.strip()
        for s in re.split(r"(?<=[.!?])\s+", text)
        if INSTRUCTION_PATTERN.search(s)
    }


def verify_descriptor(trusted: ToolDescriptor, fresh: ToolDescriptor) -> None:
    if trusted.full_hash() == fresh.full_hash():
        return

    if trusted.input_schema != fresh.input_schema:
        # Schema drift is handled by the capability-diff path, not here.
        return

    added = _instruction_sentences(fresh.description) - _instruction_sentences(
        trusted.description
    )
    if added:
        raise DescriptionDriftError(
            f"tool {fresh.name!r} gained instruction-bearing sentences with "
            f"unchanged schema: {sorted(added)!r}. Quarantine tool until reviewed."
        )

    # Non-instructional prose change (typo fix, clarity edit): accept but log.
    return
