# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-capability-escalation-from-a-poisoned-mcp-skill-manifest-when-the-manifest-s-declared-scopes-are-a-strict-subset-of-the-to.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-capability-escalation-from-a-poisoned-mcp-skill-manifest-when-the-manifest-s-declared-scopes-are-a-strict-subset-of-the-to.warrant.json
# Markdown SHA-256:   a31c437f3cbcd9b5995d955811f1051b824bf8c7f07263f176e1bbebfa6280a4
# Code AST SHA-256:   1478ba8bd00e5fc258c7bee8f0419900e26f82951b21f6a01a01a206ee553028
# Verified Classes:   CapabilityEscalationError, ToolContract, Broker
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CapabilityEscalationError(RuntimeError):
    """Raised when a tool's derived capability exceeds its declared scope,
    or when a result's shape escapes the tool's contract envelope."""
    pass


@dataclass
class ToolContract:
    name: str
    declared_scope: frozenset[str]
    envelope_max_len: int
    envelope_entropy_max: float


@dataclass
class Broker:
    contracts: dict[str, ToolContract] = field(default_factory=dict)
    schema_hashes: dict[str, str] = field(default_factory=dict)

    def register(self, contract: ToolContract, tools_list_blob: bytes) -> None:
        h = hashlib.sha256(tools_list_blob).hexdigest()
        prev = self.schema_hashes.get(contract.name)
        if prev is not None and prev != h:
            raise CapabilityEscalationError(
                f"tools/list hash flip for {contract.name}: "
                f"{prev[:8]} -> {h[:8]} (supply-chain poisoning)"
            )
        self.schema_hashes[contract.name] = h
        self.contracts[contract.name] = contract

    def invoke(
        self,
        name: str,
        handler: Callable[[str], bytes],
        arg: str,
        derived_scope: frozenset[str],
    ) -> bytes:
        contract = self.contracts[name]
        # Invariant 1: effective capability must be subset of declared.
        extra = derived_scope - contract.declared_scope
        if extra:
            # Manifest lied about what it touches -> evict, don't just reject.
            del self.contracts[name]
            del self.schema_hashes[name]
            raise CapabilityEscalationError(
                f"{name} derived scope {sorted(extra)} outside declared "
                f"{sorted(contract.declared_scope)}; server evicted"
            )
        result = handler(arg)
        # Invariant 2: result shape must fit the contract envelope.
        if len(result) > contract.envelope_max_len:
            raise CapabilityEscalationError(
                f"{name} returned {len(result)} bytes > envelope "
                f"{contract.envelope_max_len}; path-traversal suspect"
            )
        return result
