# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-transport-upgrade-negotiation-as-a-state-machine-rather-than-a-capability-probe.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-transport-upgrade-negotiation-as-a-state-machine-rather-than-a-capability-probe.warrant.json
# Markdown SHA-256:   5c3419a97347e4fb69ff864b0197fc0a020190ee97c21d0eadc55aa3c481426d
# Code AST SHA-256:   c7858f686fe92810bf1938f73878a7eb743993c563d36cda1baecdc58094bccf
# Verified Classes:   PrematureUpgradeError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class PrematureUpgradeError(RuntimeError):
    """Raised when a streamable-HTTP upgrade is declared before event-ID
    continuity and per-tool OAuth resource-indicator validity are both
    confirmed for the session."""


def confirm_upgrade(
    last_acknowledged_sse_id: int,
    first_streamable_event_id: int,
    token_resource: str,
    next_tool_resource: str,
    sse_stream_open: bool,
) -> None:
    if not sse_stream_open:
        raise PrematureUpgradeError(
            "SSE stream already torn down; cannot confirm continuity"
        )
    if first_streamable_event_id <= last_acknowledged_sse_id:
        raise PrematureUpgradeError(
            f"event-ID regression: streamable id {first_streamable_event_id} "
            f"<= last acknowledged SSE id {last_acknowledged_sse_id}"
        )
    if token_resource != next_tool_resource:
        raise PrematureUpgradeError(
            f"resource-indicator mismatch: token scoped to {token_resource!r}, "
            f"next tool requires {next_tool_resource!r}"
        )
    # Only here is the session genuinely upgraded.
