# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-when-a-dynamically-discovered-mcp-server-s-tool-description-is-itself-the-attack-surface.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-when-a-dynamically-discovered-mcp-server-s-tool-description-is-itself-the-attack-surface.warrant.json
# Markdown SHA-256:   7397ece16e7f69b57aebed96ed6ecf82e87820e4f1d49ff9f3c2069fe526e48a
# Code AST SHA-256:   58259a076569d9b4297d35f5bd46e21dede338263c1115fa384d35cacd0b7c4e
# Verified Classes:   CompositeInjectionError, DiscoveredTool, ProvenanceTrustCache
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Sequence


class CompositeInjectionError(RuntimeError):
    """Raised when a discovered tool array violates the composite-provenance invariant."""
    pass


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

    def content_hash(self) -> str:
        canonical = json.dumps(
            {
                "server_id": self.server_id,
                "name": self.name,
                "schema": self.input_schema,
                "description": self.description,
            },
            sort_keys=True,
            separators=(",", ":"),
        )
        return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


class ProvenanceTrustCache:
    """Trust is keyed on content hash, never on (server_id, tool_name)."""

    def __init__(self) -> None:
        self._trusted: set[str] = set()

    def is_trusted(self, tool: DiscoveredTool) -> bool:
        return tool.content_hash() in self._trusted

    def grant(self, tool: DiscoveredTool) -> None:
        self._trusted.add(tool.content_hash())


def validate_discovered_array(
    tools: Sequence[DiscoveredTool],
    cache: ProvenanceTrustCache,
    composite_scanner,
) -> None:
    """
    Enforce the composite-provenance invariant over a full discovered array.

    Steps:
      1. If ANY tool in the array is untrusted (new hash), demote the ENTIRE
         array to untrusted for this cycle. Delta-only validation is forbidden.
      2. Scan the serialized array as a single unit, in discovery order,
         so cross-tool fragment reassembly is visible.
      3. Only grant trust after the composite scan passes.
    """
    if not tools:
        return

    servers = {t.server_id for t in tools}
    any_untrusted = any(not cache.is_trusted(t) for t in tools)

    if any_untrusted:
        # Full-array demotion: a single changed description invalidates
        # every tool from every server in this response.
        composite = json.dumps(
            [{"server": t.server_id, "name": t.name, "desc": t.description} for t in tools],
            separators=(",", ":"),
        )

        verdict = composite_scanner(composite)
        if verdict.blocked:
            raise CompositeInjectionError(
                f"Composite scan blocked array from servers {sorted(servers)}: "
                f"{verdict.reason}. Tools quarantined for this cycle; "
                f"planner must receive re-verification-pending state."
            )

        for t in tools:
            cache.grant(t)
        return

    # All trusted by content hash — no re-scan needed, and no silent extension
    # of trust to altered content is possible because hashes are content-addressed.
    return
