# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-mcp-tool-manifest-before-first-invocation-the-tools-list-capability-description-divergence-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-mcp-tool-manifest-before-first-invocation-the-tools-list-capability-description-divergence-boundary.warrant.json
# Markdown SHA-256:   4a5febbce8296a8f39420a532ea62aa7f3407ec7cdea63a651f1b773def6da47
# Code AST SHA-256:   94a36a16257db5c6b9bc1b7b958ef9c2437ac4c893ba8a950f59312e7775a092
# Verified Classes:   ManifestDivergenceError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json


class ManifestDivergenceError(RuntimeError):
    """Raised when an MCP tool manifest is internally inconsistent or has drifted
    from its pinned hash, indicating a possible skill-injection supply-chain attack."""
    pass


NEGATIVE_CAPABILITY_MARKERS = (
    "read-only", "read only", "no network", "no external",
    "local only", "offline", "no egress",
)


def _schema_hash(tool: dict) -> str:
    canonical = json.dumps(tool, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode()).hexdigest()


def validate_manifest(tool: dict, pinned_hash: str | None) -> str:
    """Validate a single tools/list entry before binding it into agent context.

    Returns the (possibly newly pinned) schema hash.
    Raises ManifestDivergenceError on any structural signal of poisoning.
    """
    desc = (tool.get("description") or "").lower()
    schema = tool.get("inputSchema") or {}
    props = schema.get("properties") or {}
    additional = schema.get("additionalProperties", None)

    # Signal 1: negative capability claim with permissive schema.
    claims_negative = any(m in desc for m in NEGATIVE_CAPABILITY_MARKERS)
    if claims_negative and additional is not False:
        raise ManifestDivergenceError(
            f"tool '{tool.get('name')}' disclaims capability in description "
            f"but does not set additionalProperties:false (got {additional!r}); "
            "description and schema diverge — refusing to bind."
        )

    # Signal 2: readOnlyHint trusted alongside unconstrained schema.
    ann = tool.get("annotations") or {}
    if ann.get("readOnlyHint") and additional is not False:
        raise ManifestDivergenceError(
            f"tool '{tool.get('name')}' asserts readOnlyHint:true but its schema "
            "permits undeclared fields; annotation is an untrusted claim."
        )

    # Signal 3: mid-session schema drift.
    current = _schema_hash(tool)
    if pinned_hash is not None and current != pinned_hash:
        raise ManifestDivergenceError(
            f"tool '{tool.get('name')}' tools/list hash drifted "
            f"({pinned_hash[:12]} -> {current[:12]}); freeze and re-authorize."
        )

    return current


def enforce_call_args(tool: dict, args: dict) -> None:
    """Signal 4: reject outbound arguments outside declared properties.

    Called before every tools/call. If the handler later reports consuming
    fields not in args, that is a separate post-call invariant violation.
    """
    declared = set((tool.get("inputSchema") or {}).get("properties") or {})
    undeclared = set(args) - declared
    if undeclared:
        raise ManifestDivergenceError(
            f"tool '{tool.get('name')}' call includes undeclared args "
            f"{sorted(undeclared)}; schema is non-binding — sandbox required."
        )
