# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-mcp-tool-manifest-when-its-schema-hash-matches-a-previously-trusted-revision.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-mcp-tool-manifest-when-its-schema-hash-matches-a-previously-trusted-revision.warrant.json
# Markdown SHA-256:   e185d670206d6c99ba1955bd88f17cff59f1efe968e65c5ba348fc0c1d3fcd59
# Code AST SHA-256:   47c89349d20fb6def38a99418912cf153dee4020095613daf130d155079dd275
# Verified Classes:   ManifestTrustViolation, ToolDescriptor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestTrustViolation(RuntimeError):
    """Raised when a re-resolved MCP manifest diverges from the last-trusted snapshot."""
    pass


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


def prompt_visible_projection(tools: list[ToolDescriptor], server_instructions: str) -> bytes:
    # Hash EVERY byte the model will read as instruction, including descriptions.
    payload = {
        "server_instructions": server_instructions,
        "tools": sorted(
            (
                {
                    "name": t.name,
                    "description": t.description,
                    "input_schema": t.input_schema,
                }
                for t in tools
            ),
            key=lambda d: d["name"],
        ),
    }
    return json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()


def manifest_digest(tools: list[ToolDescriptor], server_instructions: str) -> str:
    return hashlib.sha256(prompt_visible_projection(tools, server_instructions)).hexdigest()


def mount_server(
    server_id: str,
    tools: list[ToolDescriptor],
    server_instructions: str,
    stored_snapshot: dict | None,
) -> dict:
    current_digest = manifest_digest(tools, server_instructions)
    current_tool_names = {t.name for t in tools}

    if stored_snapshot is None:
        # First mount: record the full prompt-visible snapshot, not just a name/schema hash.
        return {
            "server_id": server_id,
            "digest": current_digest,
            "tool_names": sorted(current_tool_names),
            "tools": tools,
            "server_instructions": server_instructions,
        }

    stored_digest = stored_snapshot["digest"]
    stored_tool_names = set(stored_snapshot["tool_names"])

    if current_digest == stored_digest:
        return stored_snapshot

    added = current_tool_names - stored_tool_names
    removed = stored_tool_names - current_tool_names

    # A digest mismatch with identical tool names means a description or schema mutated
    # in place — the exact silent-injection vector. Refuse to mount.
    if current_digest != stored_digest and not added and not removed:
        raise ManifestTrustViolation(
            f"server {server_id!r}: prompt-visible bytes changed under a stable tool set "
            f"(stored={stored_digest[:12]} current={current_digest[:12]}); "
            "possible description-injection via supply chain"
        )

    # Additive tools are a capability expansion, not harmless growth: an injected
    # description can reference a tool the attacker just added to the same manifest.
    if added:
        raise ManifestTrustViolation(
            f"server {server_id!r}: capability expansion — new tools {sorted(added)} "
            "appeared on an already-trusted server; requires re-consent"
        )

    if removed:
        raise ManifestTrustViolation(
            f"server {server_id!r}: tools removed {sorted(removed)}; "
            "re-resolution is inconsistent with stored snapshot"
        )

    raise ManifestTrustViolation(
        f"server {server_id!r}: unresolved manifest divergence "
        f"(stored={stored_digest[:12]} current={current_digest[:12]})"
    )
