# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-an-mcp-server-has-re-expanded-its-own-attenuated-capability-set-across-a-session-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-an-mcp-server-has-re-expanded-its-own-attenuated-capability-set-across-a-session-boundary.warrant.json
# Markdown SHA-256:   6bb5f19d95349abbd2432bed0a0c069263d2cfd3b2dd83bcc87b53320e4e8171
# Code AST SHA-256:   6d79174afceed04fb18914d7c80b1989119fe2a87d66ff577941e049498450a7
# Verified Classes:   AttenuationBypassError, AttenuationRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AttenuationBypassError(RuntimeError):
    """Raised when a resumed/re-initialized MCP mount would exceed its recorded envelope."""
    pass


@dataclass(frozen=True)
class AttenuationRecord:
    session_id: str
    server_id: str
    tool_manifest_hash: str
    allowed_tools: frozenset
    argument_constraints: dict  # tool -> callable(arg) -> bool


def manifest_hash(manifest: dict) -> str:
    canonical = repr(sorted((t, repr(sorted(s.items()))) for t, s in manifest.items()))
    return hashlib.sha256(canonical.encode()).hexdigest()


def authorize_dispatch(record: AttenuationRecord, current_manifest: dict, tool: str, args: dict) -> None:
    if record is None:
        raise AttenuationBypassError(
            "no durable attenuation record on resume; refusing to adopt server self-description"
        )
    presented_hash = manifest_hash(current_manifest)
    if presented_hash != record.tool_manifest_hash:
        # Server re-declared its manifest across the session boundary.
        extra = set(current_manifest) - set(record.allowed_tools)
        if extra:
            raise AttenuationBypassError(
                f"manifest widened on re-init for {record.server_id}: "
                f"unauthorized tools {sorted(extra)} presented under hash {presented_hash[:12]}"
            )
        # Narrowing is a continuity event, not a security event, but still blocks dispatch
        # of a pending call referencing a vanished tool.
        if tool not in current_manifest:
            raise AttenuationBypassError(
                f"pending tool {tool!r} no longer offered by {record.server_id} after re-init"
            )
    if tool not in record.allowed_tools:
        raise AttenuationBypassError(f"tool {tool!r} outside attenuated set for {record.server_id}")
    constraint = record.argument_constraints.get(tool)
    if constraint is not None and not constraint(args):
        raise AttenuationBypassError(
            f"args for {tool!r} violate recorded constraint on {record.server_id}: {args!r}"
        )
