# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-mcp-tool-poisoning-when-a-server-s-behavioral-fingerprint-drifts-only-inside-the-arguments-it-never-echoes-back.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-mcp-tool-poisoning-when-a-server-s-behavioral-fingerprint-drifts-only-inside-the-arguments-it-never-echoes-back.warrant.json
# Markdown SHA-256:   62d4926949e7d9687da0b03b2ff066835984dafc0eee7dfc9566b1e1a660be50
# Code AST SHA-256:   03b218f327fa6a616d3b550fbeb08d7d35037ed872ea36c5e0ce4a58728feba5
# Verified Classes:   FingerprintCoverageError, ToolFingerprint
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Callable


class FingerprintCoverageError(RuntimeError):
    """Raised when a trust verdict would rest on a response fingerprint
    that has no statistical power over the tool's argument space."""


@dataclass
class ToolFingerprint:
    tool_name: str
    response_stable: bool
    # Fraction of the declared input space actually exercised by probes.
    argument_coverage: float
    # True if any plausible payload effect could leave the response channel.
    has_out_of_band_effect_channel: bool
    side_effect_monitor_active: bool
    exercised_arg_hashes: set[str] = field(default_factory=set)

    def _coverage_threshold(self) -> float:
        # Free-form argument spaces require near-total coverage before a
        # stable response fingerprint can be treated as evidence.
        return 0.98

    def assert_trust_verdict_is_sound(self) -> None:
        if not self.response_stable:
            # Drift is not proof of poisoning, but it blocks a trust verdict.
            raise FingerprintCoverageError(
                f"{self.tool_name}: response fingerprint not stable; "
                "cannot emit trusted verdict without manifest attestation"
            )
        if self.argument_coverage < self._coverage_threshold():
            raise FingerprintCoverageError(
                f"{self.tool_name}: argument coverage {self.argument_coverage:.3f} "
                f"< {self._coverage_threshold():.2f}; stable response fingerprint "
                "has unquantified power over argument-conditioned payloads"
            )
        if self.has_out_of_band_effect_channel and not self.side_effect_monitor_active:
            raise FingerprintCoverageError(
                f"{self.tool_name}: tool can act out-of-band but no side-effect "
                "monitor is active; response fingerprint is blind to "
                "echo-suppressed exfiltration"
            )


def decide_trust(fp: ToolFingerprint) -> str:
    """Return a trust verdict only if the fingerprint's coverage claim holds."""
    try:
        fp.assert_trust_verdict_is_sound()
    except FingerprintCoverageError as exc:
        # Downgrade to review; do NOT report 'trusted' on a blind fingerprint.
        return f"REVIEW_REQUIRED: {exc}"
    return "TRUSTED_WITHIN_FINGERPRINT_COVERAGE"


def record_probe(fp: ToolFingerprint, argument: str, response: str) -> None:
    """Record an exercised argument; coverage is argument-space, not response-space."""
    arg_hash = hashlib.sha256(argument.encode()).hexdigest()
    fp.exercised_arg_hashes.add(arg_hash)
    # NOTE: response is recorded for the response fingerprint only. It carries
    # no information about echo-suppressed effects; those must be caught by the
    # independent side-effect monitor, never inferred from this response.
    if not fp.response_stable:
        raise FingerprintCoverageError(
            f"{fp.tool_name}: probe recorded against unstable baseline; "
            "recompute baseline before drawing coverage conclusions"
        )
