# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-poisoned-mcp-tool-manifest-when-the-schema-it-validates-against-is-itself-the-attack-surface.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-poisoned-mcp-tool-manifest-when-the-schema-it-validates-against-is-itself-the-attack-surface.warrant.json
# Markdown SHA-256:   5017ecd65dcfc9bbb416c1fd48ce2a3c573ec3b455145aee239da414a13fd3f4
# Code AST SHA-256:   a791ed635222569856270ceb53e38714c76aba0f89aeb9c0136d47f3ede36d32
# Verified Classes:   ManifestAuthorityViolation, ToolManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)
# Governance:         Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com)

import hashlib
from dataclasses import dataclass


class ManifestAuthorityViolation(RuntimeError):
    """Raised when a tool manifest claims instruction authority it has not been granted."""
    pass


@dataclass(frozen=True)
class ToolManifest:
    registry_id: str
    name: str
    description: str
    schema: dict
    attested: bool
    manifest_hash: str


def compute_hash(manifest: ToolManifest) -> str:
    payload = f"{manifest.registry_id}|{manifest.name}|{manifest.description}|{sorted(manifest.schema)}"
    return hashlib.sha256(payload.encode()).hexdigest()


# Fields whose free-form text is a known context-exfiltration sink.
CONTEXT_SINK_MARKERS = ("context", "notes", "additional info", "surrounding")


def bind_tool(manifest: ToolManifest, pinned_hashes: dict[str, str]) -> ToolManifest:
    """
    Gate a manifest before it enters the selection namespace.
    Enforces: hash pinning, attestation tiering, and context-sink refusal.
    """
    actual = compute_hash(manifest)
    prior = pinned_hashes.get(manifest.name)

    if prior is not None and prior != actual:
        raise ManifestAuthorityViolation(
            f"manifest drift on {manifest.name!r}: pinned {prior[:12]} != {actual[:12]}; "
            "re-review required before re-entry"
        )

    if not manifest.attested:
        # Unattested tools may be selected but never granted override authority.
        # Detect an override claim in the description and refuse binding.
        lowered = manifest.description.lower()
        if "supersede" in lowered or "use this first" in lowered or "override" in lowered:
            raise ManifestAuthorityViolation(
                f"unattested tool {manifest.name!r} claims override authority in description; "
                "authority cannot be self-granted"
            )

    for param, spec in manifest.schema.get("properties", {}).items():
        doc = str(spec.get("description", "")).lower()
        if spec.get("type") == "string" and any(m in doc for m in CONTEXT_SINK_MARKERS):
            raise ManifestAuthorityViolation(
                f"tool {manifest.name!r} exposes context-capture param {param!r}; "
                "refusing to bind — would permit session-state exfiltration"
            )

    return manifest
