# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-mcp-server-trust-decay-before-tool-call-corruption-surfaces.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-mcp-server-trust-decay-before-tool-call-corruption-surfaces.warrant.json
# Markdown SHA-256:   a0e6b9245f11ce329f8e48e2756940e7921b2edfa81ef813466926eb3cc164b1
# Code AST SHA-256:   b54804828d691a67d945264e091b16faa2e5d4049cb521f957561a36e0fa57b0
# Verified Classes:   TrustDecayError, ServerBaseline, SignalWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TrustDecayError(RuntimeError):
    """Raised when a server's structural signals cross the demotion boundary."""
    pass


@dataclass
class ServerBaseline:
    tool_descriptions: dict[str, str]
    latency_p50_ms: float
    latency_p99_ms: float
    coverage_entropy: float
    sessions_observed: int = 1


@dataclass
class SignalWindow:
    description_drift: bool = False
    latency_ratio_excursion: bool = False
    coverage_entropy_decline: bool = False
    schema_violation: bool = False
    fired: list[str] = field(default_factory=list)


LATENCY_RATIO_THRESHOLD = 8.0
ENTROPY_DECLINE_THRESHOLD = 0.15


def score_server(
    baseline: Optional[ServerBaseline],
    current_descriptions: dict[str, str],
    current_p50_ms: float,
    current_p99_ms: float,
    current_coverage_entropy: float,
    schema_violated: bool,
) -> SignalWindow:
    if baseline is None:
        # Refuse to score without a baseline; a neutral default is the bug.
        raise TrustDecayError(
            "no baseline for server; cannot score unbaselined provider"
        )

    window = SignalWindow(schema_violation=schema_violated)

    for name, desc in current_descriptions.items():
        prior = baseline.tool_descriptions.get(name)
        if prior is not None and prior != desc:
            window.description_drift = True
            window.fired.append(f"description_drift:{name}")

    ratio = current_p99_ms / max(current_p50_ms, 1e-6)
    baseline_ratio = baseline.latency_p99_ms / max(baseline.latency_p50_ms, 1e-6)
    if ratio > LATENCY_RATIO_THRESHOLD and ratio > baseline_ratio * 1.5:
        window.latency_ratio_excursion = True
        window.fired.append(f"latency_ratio:{ratio:.2f}")

    if (baseline.coverage_entropy - current_coverage_entropy) > ENTROPY_DECLINE_THRESHOLD:
        window.coverage_entropy_decline = True
        window.fired.append(
            f"coverage_entropy_decline:{baseline.coverage_entropy - current_coverage_entropy:.3f}"
        )

    if schema_violated:
        raise TrustDecayError(
            f"schema violation: immediate quarantine; signals={window.fired}"
        )

    structural_hits = sum([
        window.description_drift,
        window.latency_ratio_excursion,
        window.coverage_entropy_decline,
    ])
    if structural_hits >= 2:
        raise TrustDecayError(
            f"demotion boundary crossed with {structural_hits} co-occurring signals: {window.fired}"
        )

    return window
