# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-mcp-capability-negotiation-drift-from-silently-re-binding-a-stateless-edge-tool-call-to-a-stale-server-revision.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-mcp-capability-negotiation-drift-from-silently-re-binding-a-stateless-edge-tool-call-to-a-stale-server-revision.warrant.json
# Markdown SHA-256:   e981dd0a833b3c44f901940d685bdfff42e194b45315b1857ab7921a5b83f3f2
# Code AST SHA-256:   34407202a31ee0899e95a9232187d787b2e23447685cfe24560f3a2aff85c938
# Verified Classes:   SchemaDriftError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SchemaDriftError(RuntimeError):
    """Raised when a stateless MCP invocation's declared schema hash
    does not match the live server revision, or when a backward-compat
    coercion produces a value outside the live validator's domain."""
    pass


def assert_schema_binding(
    declared_hash: str | None,
    live_hash: str,
    tool_name: str,
) -> None:
    if declared_hash is None:
        # Stateless transport with no assertion: cannot prove the client's
        # cached snapshot matches the live revision. Fail closed.
        raise SchemaDriftError(
            f"tool={tool_name!r}: invocation carried no Mcp-Schema-Hash; "
            f"live revision is {live_hash!r}. Refusing to execute against "
            f"an unverified contract."
        )
    if declared_hash != live_hash:
        raise SchemaDriftError(
            f"tool={tool_name!r}: client negotiated {declared_hash!r} but "
            f"live revision is {live_hash!r}. Re-negotiate via tools/list "
            f"before invoking."
        )


def coerce_and_validate(
    raw: dict,
    live_bounds: tuple[int, int],
    tool_name: str,
) -> dict:
    # Backward-compat shim: percent -> percent_bp. The critical rule is
    # that coercion happens BEFORE validation, never after, so the
    # post-coercion value is what the live bound is checked against.
    if "percent" in raw and "percent_bp" not in raw:
        raw = {**raw, "percent_bp": raw["percent"] * 100}
        del raw["percent"]

    value = raw.get("percent_bp")
    lo, hi = live_bounds
    if value is None or not (lo <= value <= hi):
        raise SchemaDriftError(
            f"tool={tool_name!r}: post-coercion percent_bp={value!r} "
            f"outside live bounds [{lo}, {hi}]. Rejecting before side effect."
        )
    return raw
