# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-an-mcp-oauth-access-token-whose-rfc-8707-resource-binding-survives-schema-re-negotiation-but-not-capability-drift.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-an-mcp-oauth-access-token-whose-rfc-8707-resource-binding-survives-schema-re-negotiation-but-not-capability-drift.warrant.json
# Markdown SHA-256:   8010096c838e3c772161424900ac931d8610cd28fa90e5132c089958ee4091bf
# Code AST SHA-256:   1e2bf653cbb7bff28ca7c318eb4672a34be33a54614a98fbccc27f1d070f29ba
# Verified Classes:   SchemaCurrencyError, McpResourceServer
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SchemaCurrencyError(RuntimeError):
    """Raised when a token is audience-valid but its capability is stale
    relative to the server's current tool surface. Distinct from auth errors:
    must NOT be routed to auth-retry paths."""
    pass


class McpResourceServer:
    def __init__(self, resource_id: str, surface: dict[str, dict]):
        # surface: tool_name -> {"schema_epoch": int, "required": set[str]}
        self.resource_id = resource_id
        self.surface = surface

    def validate_token(self, token: dict) -> None:
        # RFC 8707 / OAuth 2.1 resource-server check. Monotone.
        if token.get("resource") != self.resource_id:
            raise PermissionError("audience mismatch")
        if token.get("exp", 0) <= 0:
            raise PermissionError("expired")
        # NOTE: no schema-version check is possible here. The token has no such field.

    def dispatch(self, token: dict, tool: str, args: dict) -> dict:
        self.validate_token(token)  # passes even for stale capability

        # Two-key check: scope AND current-surface presence, atomic.
        if tool not in self.surface:
            # de-advertised tool must NOT resurrect via dispatch table
            raise SchemaCurrencyError(
                f"tool {tool!r} absent from current tools/list; "
                f"token scope alone is insufficient"
            )
        required = self.surface[tool]["required"]
        missing = required - set(args)
        if missing:
            # stale-schema call from memory-cached agent
            raise SchemaCurrencyError(
                f"tool {tool!r} missing required params {sorted(missing)}; "
                f"client must re-fetch tools/list (epoch "
                f"{self.surface[tool]['schema_epoch']}) before retry"
            )
        return {"ok": True, "tool": tool, "epoch": self.surface[tool]["schema_epoch"]}
