# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-rising-mcp-registry-trust-score-as-evidence-of-integrity-when-the-score-is-computed-from-attestation-metadata-the-serve.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-rising-mcp-registry-trust-score-as-evidence-of-integrity-when-the-score-is-computed-from-attestation-metadata-the-serve.warrant.json
# Markdown SHA-256:   ea762158c45a7cdc69213008d44244ba0de897a631c372bcf5f4289cd0e6718d
# Code AST SHA-256:   ddeb973eaabf7aab2b620d00302878e7173ca42a4668fa500bc0e86d2bffb899
# Verified Classes:   AttestationIntegrityError, TrustDecomposition, ToolManifest, ServerCandidate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Iterable


class AttestationIntegrityError(RuntimeError):
    """Raised when an MCP server's admission decision rests on self-emitted evidence."""


# Parameters whose presence in an inputSchema implies mutation or egress,
# regardless of what the tool's free-text tags claim.
MUTATION_PARAMS = frozenset(
    {"append", "write", "overwrite", "truncate", "exec", "command", "shell", "url", "endpoint", "egress"}
)


@dataclass(frozen=True)
class TrustDecomposition:
    witnessed: float          # third-party verified: build hashes, SBOMs, incident reports
    self_emitted: float       # server-authored: security.txt, tags, version bumps, descriptions


@dataclass(frozen=True)
class ToolManifest:
    name: str
    tags: frozenset[str]
    input_schema_params: frozenset[str]


@dataclass(frozen=True)
class ServerCandidate:
    server_id: str
    score: TrustDecomposition
    tools: tuple[ToolManifest, ...]
    attestation_age_seconds: int


def schema_capabilities(tool: ToolManifest) -> frozenset[str]:
    """Derive capabilities from the schema, not from annotations."""
    return frozenset(p for p in tool.input_schema_params if p in MUTATION_PARAMS)


def admit(
    candidate: ServerCandidate,
    *,
    witnessed_threshold: float,
    max_attestation_age_seconds: int,
    allowed_capability_params: Iterable[str] = (),
) -> None:
    allowed = frozenset(allowed_capability_params)

    # 1. Score must be witnessed-only. A high total score driven by self-emission
    #    is not evidence of integrity.
    if candidate.score.witnessed < witnessed_threshold:
        raise AttestationIntegrityError(
            f"{candidate.server_id}: witnessed sub-score {candidate.score.witnessed:.2f} "
            f"< {witnessed_threshold:.2f}; total score {candidate.score.witnessed + candidate.score.self_emitted:.2f} "
            f"is inflated by {candidate.score.self_emitted:.2f} of self-emitted metadata"
        )

    # 2. Stale witnessed evidence is treated as absent.
    if candidate.attestation_age_seconds > max_attestation_age_seconds:
        raise AttestationIntegrityError(
            f"{candidate.server_id}: witnessed attestation age {candidate.attestation_age_seconds}s "
            f"exceeds {max_attestation_age_seconds}s; score is stale"
        )

    # 3. Schema-derived capabilities must be within the allowlist, and must agree
    #    with tags. A read-only tag over a mutating schema is unclassified, not read-only.
    for tool in candidate.tools:
        caps = schema_capabilities(tool)
        if not caps:
            continue
        if not caps.issubset(allowed):
            raise AttestationIntegrityError(
                f"{candidate.server_id}.{tool.name}: schema admits capabilities {sorted(caps)} "
                f"outside allowlist {sorted(allowed)}"
            )
        if "read-only" in tool.tags:
            raise AttestationIntegrityError(
                f"{candidate.server_id}.{tool.name}: tagged read-only but schema admits "
                f"{sorted(caps)}; tag/schema disagreement is an injection surface"
            )


def admit_batch(candidates: Iterable[ServerCandidate], **kwargs) -> list[str]:
    admitted: list[str] = []
    for c in candidates:
        admit(c, **kwargs)  # raises AttestationIntegrityError on any conjunct failure
        admitted.append(c.server_id)
    return admitted
