# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-resumable-mcp-stream-has-silently-lost-its-per-tool-oauth-resource-binding.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-resumable-mcp-stream-has-silently-lost-its-per-tool-oauth-resource-binding.warrant.json
# Markdown SHA-256:   a9e079a5bf7e8cde9a40a4e83edd25d66d2b2e4ce189558323b656b084ad5b29
# Code AST SHA-256:   106f98df3a09979222c91295ce443749993a06a820de8c02a4826688a6a644ac
# Verified Classes:   ResourceBindingDriftError, Session, Token
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class ResourceBindingDriftError(RuntimeError):
    """Raised when a resumed MCP stream carries a token whose resource
    indicator no longer matches the per-tool resource required for a call."""
    pass


@dataclass
class Session:
    session_id: str
    created_at: float
    bound_resources: set[str]


@dataclass
class Token:
    iat: float
    resource: str | None


def assert_tool_resource_valid(session: Session, token: Token, tool_resource: str) -> None:
    # A resumed session whose token postdates session creation may have
    # refreshed against a default resource. Do not trust session continuity.
    if token.iat > session.created_at:
        if token.resource is None:
            raise ResourceBindingDriftError(
                f"session {session.session_id}: refreshed token (iat={token.iat}) "
                f"has no resource claim; refusing to infer {tool_resource!r} "
                f"from session continuity"
            )
        if token.resource != tool_resource:
            raise ResourceBindingDriftError(
                f"session {session.session_id}: token resource {token.resource!r} "
                f"does not match required tool resource {tool_resource!r}"
            )
    elif tool_resource not in session.bound_resources:
        raise ResourceBindingDriftError(
            f"session {session.session_id}: tool resource {tool_resource!r} "
            f"was never bound at session creation"
        )
