# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-after-a-crash-mid-notifications-tools-list-changed-and-replays-a-stale-session.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-stream-after-a-crash-mid-notifications-tools-list-changed-and-replays-a-stale-session.warrant.json
# Markdown SHA-256:   31caa8b2637f9df353ec1c27e7e7942f5e3f796425dd9ce0db968a9c6c52a56a
# Code AST SHA-256:   6cc5b3fef0c47fd259c55c80c7175545500563f73b087b89344b9ceeb5ba6bec
# Verified Classes:   StreamResumeGapError, PersistedStreamState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass


class StreamResumeGapError(RuntimeError):
    """Raised when an MCP SSE resume cannot prove event-stream continuity."""
    pass


@dataclass
class PersistedStreamState:
    session_id: str
    last_event_id: int


def reconcile_resume(
    persisted: PersistedStreamState,
    first_replayed_event_id: int,
    server_session_id: str,
    fetch_tools_list,
) -> dict:
    """
    Enforce the invariant: a session-ID match is NOT event-stream continuity.
    If the first replayed event ID is not exactly last_event_id + 1, or the
    server handed back a different session, the client MUST treat all mutable
    list state as dirty and re-fetch before any dependent tools/call.
    """
    session_reset = server_session_id != persisted.session_id
    gap = first_replayed_event_id != persisted.last_event_id + 1

    if session_reset:
        # New session grafted onto old identity: full cache discard.
        tools = fetch_tools_list(server_session_id)
        return {"session_reset": True, "gap": True, "tools": tools}

    if gap:
        # Silent drop-gap or replay-from-start: re-fetch to bound staleness.
        tools = fetch_tools_list(server_session_id)
        if first_replayed_event_id < persisted.last_event_id:
            raise StreamResumeGapError(
                f"server replayed event {first_replayed_event_id} older than "
                f"persisted {persisted.last_event_id}; ordering violated, "
                f"refusing to trust stream"
            )
        return {"session_reset": False, "gap": True, "tools": tools}

    # Exact continuation: cache is provably current up to last_event_id.
    return {"session_reset": False, "gap": False, "tools": None}


def guarded_tools_call(
    persisted: PersistedStreamState,
    first_replayed_event_id: int,
    server_session_id: str,
    fetch_tools_list,
    tool_name: str,
    arguments: dict,
    invoke,
):
    recon = reconcile_resume(
        persisted, first_replayed_event_id, server_session_id, fetch_tools_list
    )
    if recon["gap"] and recon["tools"] is None:
        raise StreamResumeGapError(
            "resume reported a gap but no refreshed tool schema was produced; "
            "refusing to issue tools/call against a possibly stale schema"
        )
    schema = None
    if recon["tools"] is not None:
        schema = next((t for t in recon["tools"] if t["name"] == tool_name), None)
        if schema is None:
            raise StreamResumeGapError(
                f"tool {tool_name!r} absent from reconciled tools/list; "
                f"client cache was stale across resume"
            )
    return invoke(server_session_id, tool_name, arguments, schema)
