# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-tools-list-capability-snapshot-as-non-authoritative-before-consuming-a-notifications-progress-stre.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-tools-list-capability-snapshot-as-non-authoritative-before-consuming-a-notifications-progress-stre.warrant.json
# Markdown SHA-256:   9ec96cc29eb3396dd06d1f43472aa1f227208b1b1fe93b1a7f0f579d21d4e493
# Code AST SHA-256:   b6bdce02486dc7586df28225205c7d73189fc2ff900b04d9b751989a7f5ea35c
# Verified Classes:   StreamSchemaMisapplication, CachedToolEntry, CallContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any


class StreamSchemaMisapplication(RuntimeError):
    """Raised when a client applies a terminal outputSchema to a progress-channel payload,
    or coerces a stale tools/list snapshot onto a live stream instead of failing closed."""


@dataclass
class CachedToolEntry:
    name: str
    output_schema: dict[str, Any]
    partial_schema: dict[str, Any] | None = None
    version: int = 1


@dataclass
class CallContext:
    tool: str
    progress_token: str | None
    server_declares_progress: bool
    server_tool_version: int
    partials: list[dict[str, Any]] = field(default_factory=list)


def route_and_validate_partial(
    entry: CachedToolEntry,
    ctx: CallContext,
    payload: dict[str, Any],
) -> None:
    """Route a notifications/progress payload to the correct validator.

    Invariant: outputSchema bounds the terminal result ONLY. If a progressToken
    is in play and the server declares progress support, the cached outputSchema
    is non-authoritative for partials. Fail closed on staleness; never coerce.
    """
    progress_channel_active = ctx.progress_token is not None and ctx.server_declares_progress

    if not progress_channel_active:
        # No partial channel: this payload should not exist. Treat as protocol error.
        raise StreamSchemaMisapplication(
            f"progress payload for {ctx.tool!r} but no progressToken/capability negotiated"
        )

    # Staleness gate: fail closed, do not coerce the snapshot onto the live stream.
    if ctx.server_tool_version > entry.version:
        raise StreamSchemaMisapplication(
            f"stale snapshot for {ctx.tool!r}: cached v{entry.version}, "
            f"server v{ctx.server_tool_version}; re-fetch tools/list or abort"
        )

    if entry.partial_schema is None:
        # No explicit partial schema: partials are opaque. Buffer only.
        ctx.partials.append(payload)
        return

    # Validate against the partial schema, NOT output_schema.
    required = entry.partial_schema.get("required", [])
    missing = [k for k in required if k not in payload]
    if missing:
        raise StreamSchemaMisapplication(
            f"partial for {ctx.tool!r} missing required fields {missing} "
            f"per x-partialSchema; refusing to validate against outputSchema"
        )
    ctx.partials.append(payload)


def validate_terminal_result(entry: CachedToolEntry, result: dict[str, Any]) -> None:
    """Only the terminal result is governed by outputSchema."""
    required = entry.output_schema.get("required", [])
    missing = [k for k in required if k not in result]
    if missing:
        raise StreamSchemaMisapplication(
            f"terminal result for {entry.name!r} missing {missing} per outputSchema"
        )
