# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-an-mcp-streamable-http-tool-result-whose-sse-stream-resumed-under-a-rotated-oauth-scope-after-a-last-event-id-reconnect.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-an-mcp-streamable-http-tool-result-whose-sse-stream-resumed-under-a-rotated-oauth-scope-after-a-last-event-id-reconnect.warrant.json
# Markdown SHA-256:   c18b0807acbecaa28a559a3be0f039f867b8771f9adc6b4e87cdf6b2232e9320
# Code AST SHA-256:   e50f13fc67a4b7763ada0518fcb4685585a2e974b46d949b8745a3315d753f7d
# Verified Classes:   ScopeContinuityError, Credential, StreamOpen
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ScopeContinuityError(RuntimeError):
    """Raised when a resumed MCP SSE stream would deliver a tool result
    under a credential that is not authorized for the originating tool."""


@dataclass(frozen=True)
class Credential:
    subject: str
    scopes: frozenset
    issued_at: int

    def fingerprint(self) -> str:
        material = f"{self.subject}|{','.join(sorted(self.scopes))}|{self.issued_at}"
        return hashlib.sha256(material.encode()).hexdigest()


@dataclass(frozen=True)
class StreamOpen:
    stream_id: str
    tool_name: str
    required_scope: str
    credential_fp: str


def resume_stream(
    opened: StreamOpen,
    last_event_id: int,
    presenting: Credential,
    multiplexed: bool,
    events_tool_tagged: bool,
) -> str:
    """Decide whether a Last-Event-ID resume may be honored.

    Returns the resume disposition. Raises ScopeContinuityError when the
    replay would cross an authorization boundary.
    """
    if opened.required_scope not in presenting.scopes:
        raise ScopeContinuityError(
            f"resume of stream {opened.stream_id} (tool={opened.tool_name}) "
            f"under credential lacking scope {opened.required_scope!r}; "
            f"last acknowledged event id={last_event_id}. Refusing replay."
        )

    if presenting.fingerprint() != opened.credential_fp:
        # Credential changed. Safe only if we can prove the buffered
        # events belong to the originating tool.
        if multiplexed and not events_tool_tagged:
            raise ScopeContinuityError(
                f"credential rotated on stream {opened.stream_id}; "
                f"multiplexed stream without per-event tool tags makes "
                f"replay attribution unprovable. Fail closed."
            )
        return "resume_reauthorized"

    return "resume_transparent"


def handle_resume(opened, last_event_id, presenting, multiplexed, events_tool_tagged):
    try:
        disposition = resume_stream(
            opened, last_event_id, presenting, multiplexed, events_tool_tagged
        )
    except ScopeContinuityError as exc:
        # Abort the logical call; do not assemble partial results.
        return {"action": "abort_call", "reason": str(exc)}
    return {"action": disposition, "from_event": last_event_id}
