# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-continuity-when-an-mcp-streamable-http-sse-stream-resumes-under-a-rotated-oauth-2-1-access-token.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-continuity-when-an-mcp-streamable-http-sse-stream-resumes-under-a-rotated-oauth-2-1-access-token.warrant.json
# Markdown SHA-256:   18441c1f79c9cbe15b7ca19771e989f8ecb87c0aabc57bc93b960ce22633956c
# Code AST SHA-256:   5cbbf63543f07b682856ae4b25ca3301467af35cafccfbe1efe891ba17989128
# Verified Classes:   StreamResumptionAuthMismatch
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class StreamResumptionAuthMismatch(RuntimeError):
    """Raised when an SSE resumption request cannot be authorized against the
    session's original authorization context, or when a stream closes without
    a terminal JSON-RPC message."""
    pass


def resume_stream(
    session_id: str,
    last_event_id: str,
    presenting_token: dict,
    session_store: dict,
    event_store: dict,
) -> list:
    """
    Resume an MCP Streamable HTTP SSE stream.

    presenting_token: decoded claims of the bearer token on the resumption request.
    session_store:    session_id -> {"aud", "scope", "stream_id", "authorization_context"}
    event_store:      (session_id, stream_id) -> list of events with monotonic ids.

    Invariant: event-ID namespace is the session, not the token.
    """
    session = session_store.get(session_id)
    if session is None:
        raise StreamResumptionAuthMismatch(
            f"unknown session {session_id!r}; cannot resume across token rotation"
        )

    # 1. Audience binding: the presenting token must target this resource server.
    if presenting_token.get("aud") != session["aud"]:
        raise StreamResumptionAuthMismatch(
            f"aud mismatch on resumption: token aud={presenting_token.get('aud')!r} "
            f"!= session aud={session['aud']!r}"
        )

    # 2. Scope monotonicity: the new token must not be weaker than the session's
    #    original authorization, or pending events become a confused deputy.
    new_scope = set(presenting_token.get("scope", "").split())
    original_scope = set(session["scope"].split())
    if not original_scope.issubset(new_scope):
        raise StreamResumptionAuthMismatch(
            f"scope downgrade on resumption: original={sorted(original_scope)} "
            f"new={sorted(new_scope)}; refusing to replay pending events"
        )

    # 3. Event-ID lookup must be session-scoped, not token-scoped.
    stream = event_store.get((session_id, session["stream_id"]))
    if stream is None:
        raise StreamResumptionAuthMismatch(
            f"no event stream for session={session_id!r} stream={session['stream_id']!r}"
        )

    pending = [e for e in stream if e["id"] > last_event_id]
    if not pending and not session.get("terminal_emitted"):
        raise StreamResumptionAuthMismatch(
            f"resumption at {last_event_id!r} yields no pending events and no terminal "
            f"message was emitted; stream close would be misread as success"
        )
    return pending


def close_stream(session: dict, terminal_emitted: bool) -> None:
    """Enforce the terminal-response invariant at stream close."""
    if not terminal_emitted:
        raise StreamResumptionAuthMismatch(
            "stream closed without terminal JSON-RPC result/error; "
            "client must map this to a retryable transport error, not success"
        )
