# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-discover-an-mcp-server-at-well-known-mcp-but-route-to-a-capability-it-cannot-actually-satisfy.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-discover-an-mcp-server-at-well-known-mcp-but-route-to-a-capability-it-cannot-actually-satisfy.warrant.json
# Markdown SHA-256:   609f6d3fa4b99975ae8314110a2dcac181521acd70e57dd14ea8f0edf9ec49a3
# Code AST SHA-256:   ac4f2bb1a0ad4b09dfe327831521fd80c63538df69c28f4754c61886075686d0
# Verified Classes:   CapabilityContractDrift, UnroutableCapability, DiscoveredCapability, RoutingTable
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class CapabilityContractDrift(RuntimeError):
    """Raised when a routed capability's live contract no longer matches the
    schema the agent validated at discovery time."""
    pass


class UnroutableCapability(RuntimeError):
    """Raised when a capability is advertised but no validated schema exists,
    so dispatch would be an unchecked name-based coercion."""
    pass


@dataclass
class DiscoveredCapability:
    name: str
    request_schema: dict | None  # None means the well-known doc omitted it


@dataclass
class RoutingTable:
    # routing key is the schema digest, NOT the capability name
    validated: dict[str, str] = field(default_factory=dict)  # name -> digest

    @staticmethod
    def _digest(schema: dict) -> str:
        canonical = json.dumps(schema, sort_keys=True, separators=(",", ":"))
        return hashlib.sha256(canonical.encode()).hexdigest()


def register_capability(table: RoutingTable, cap: DiscoveredCapability) -> None:
    if cap.request_schema is None:
        # Do not invent a schema from the name. Force a probe.
        raise UnroutableCapability(
            f"capability {cap.name!r} advertised without request schema; "
            "probe introspection before routing"
        )
    table.validated[cap.name] = RoutingTable._digest(cap.request_schema)


def dispatch(table: RoutingTable, cap: DiscoveredCapability, payload: dict) -> None:
    expected = table.validated.get(cap.name)
    if expected is None:
        raise UnroutableCapability(
            f"no validated schema for {cap.name!r}; refusing name-based route"
        )
    live_digest = RoutingTable._digest(cap.request_schema or {})
    if live_digest != expected:
        # Contract drift: invalidate, re-probe, re-validate. Never retry blind.
        table.validated.pop(cap.name, None)
        raise CapabilityContractDrift(
            f"{cap.name!r} schema changed since discovery "
            f"(expected {expected[:12]}, live {live_digest[:12]}); "
            "re-probe and re-validate before re-dispatch"
        )
    # payload validation against cap.request_schema would occur here
    _ = payload
