# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-discovered-mcp-server-s-advertised-capability-set-as-stale-before-routing-rather-than-after-the-first-f.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-discovered-mcp-server-s-advertised-capability-set-as-stale-before-routing-rather-than-after-the-first-f.warrant.json
# Markdown SHA-256:   15ebfe09c9320a62d052f1a5448a15f8d76a723c7f48f63795f61754b111a697
# Code AST SHA-256:   89ca0aecbecbe737015c3baf522577791dac61487ba5733132fbd265aa26ecb2
# Verified Classes:   StaleCapabilityError, CapabilityBinding
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class StaleCapabilityError(RuntimeError):
    """Raised when a discovered MCP capability cannot be shown fresh at route time."""
    pass


@dataclass(frozen=True)
class CapabilityBinding:
    server_id: str
    tool_name: str
    discovered_at: float          # t_d, monotonic seconds
    server_max_age: float         # from Cache-Control: max-age
    agent_freshness_ceiling: float
    version_token: Optional[str]  # ETag / version / content hash
    schema_advisory: bool         # True if server validator is known-permissive


def assert_routable(
    binding: CapabilityBinding,
    now: float,
    live_version_token: Optional[str],
    non_idempotent: bool,
    downstream_chain_length: int,
) -> None:
    """Enforce the four validity conditions before emitting a routed call.

    Callers must invoke this immediately before the JSON-RPC POST, not at
    discovery time and not after a failed call.
    """
    age = now - binding.discovered_at
    effective_bound = min(binding.server_max_age, binding.agent_freshness_ceiling)

    # Condition 1: temporal bound.
    if age > effective_bound:
        raise StaleCapabilityError(
            f"{binding.server_id}/{binding.tool_name}: age={age:.1f}s exceeds "
            f"bound={effective_bound:.1f}s (server_max_age={binding.server_max_age}, "
            f"ceiling={binding.agent_freshness_ceiling})"
        )

    # Condition 2: version identity must be present for high-stakes routes,
    # and must match the live token if we were able to re-validate.
    high_stakes = non_idempotent or downstream_chain_length > 1
    if high_stakes and binding.version_token is None:
        raise StaleCapabilityError(
            f"{binding.server_id}/{binding.tool_name}: high-stakes route "
            f"(non_idempotent={non_idempotent}, chain={downstream_chain_length}) "
            f"requires a version token; descriptor carried none"
        )
    if live_version_token is not None and binding.version_token is not None:
        if live_version_token != binding.version_token:
            raise StaleCapabilityError(
                f"{binding.server_id}/{binding.tool_name}: version drift "
                f"(cached={binding.version_token}, live={live_version_token}); "
                f"re-plan required"
            )

    # Condition 3: advisory schema cannot back a mutating route.
    if binding.schema_advisory and non_idempotent:
        raise StaleCapabilityError(
            f"{binding.server_id}/{binding.tool_name}: descriptor schema is "
            f"advisory (server coerces) but route is mutating; 200 is not proof "
            f"of intended semantics"
        )


def route(
    binding: CapabilityBinding,
    now: float,
    live_version_token: Optional[str],
    non_idempotent: bool,
    downstream_chain_length: int,
    post_fn,
    payload: dict,
):
    assert_routable(
        binding, now, live_version_token, non_idempotent, downstream_chain_length
    )
    return post_fn(binding.server_id, binding.tool_name, payload)
