# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-negotiate-the-mcp-session-before-resuming-a-tool-call-across-an-http-native-transport-binding.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-negotiate-the-mcp-session-before-resuming-a-tool-call-across-an-http-native-transport-binding.warrant.json
# Markdown SHA-256:   8dbf3790f8f7c8076729e3d376b75889ac45985af8a877e62ae0727db8815e93
# Code AST SHA-256:   83a6459166baaf04778fef28feead37e7ca07acab4f9e87a736435229a1f85b4
# Verified Classes:   UnsafeResumeError, Checkpoint, ServerCapabilities
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class UnsafeResumeError(RuntimeError):
    """Raised when a client attempts to resume a mutating MCP tool call
    without proof of server-side request deduplication."""


@dataclass(frozen=True)
class Checkpoint:
    session_id: str
    last_event_id: int
    request_id: int          # original JSON-RPC id
    tool: str
    args_hash: str
    mutating: bool


@dataclass(frozen=True)
class ServerCapabilities:
    dedup_on_session_request: bool
    dedup_ttl_seconds: int


def resume_tool_call(
    cp: Checkpoint,
    caps: Optional[ServerCapabilities],
    elapsed_since_disconnect: int,
    args: dict,
) -> str:
    """Decide whether to replay the original tools/call or downgrade to reconcile.

    Returns one of: 'replay', 'reconcile', 'reissue'.
    """
    if hashlib.sha256(repr(sorted(args.items())).encode()).hexdigest() != cp.args_hash:
        # The args the agent now holds differ from what it checkpointed.
        # Replaying would execute a *different* call under the old id.
        raise UnsafeResumeError(
            f"args drift for request {cp.request_id}: checkpoint hash mismatch; "
            "context was reconstructed from a lossy summary"
        )

    if not cp.mutating:
        return "replay"

    if caps is None or not caps.dedup_on_session_request:
        # No proof of (session, request_id) dedup. Replay risks double-execution.
        return "reconcile"

    if elapsed_since_disconnect > caps.dedup_ttl_seconds:
        # Dedup window lapsed; the in-flight record may have been evicted.
        # A replay would be accepted as a fresh call.
        return "reconcile"

    # Dedup is proven and within TTL: replaying with the original id is safe;
    # the server will return the retained terminal result or continue the stream.
    return "replay"


def execute_resume(cp: Checkpoint, decision: str) -> None:
    if decision == "replay" and cp.mutating:
        # Guard: replay of a mutating call must be accompanied by the original id.
        if cp.request_id is None:
            raise UnsafeResumeError(
                f"cannot replay mutating tool {cp.tool} without original JSON-RPC id"
            )
    if decision == "reconcile":
        # Issue a read-only query tool to determine whether the side effect landed.
        pass
