# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-mcp-session-migration-from-silently-rebinding-a-tool-s-oauth-2-1-resource-token-to-the-wrong-upstream.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-mcp-session-migration-from-silently-rebinding-a-tool-s-oauth-2-1-resource-token-to-the-wrong-upstream.warrant.json
# Markdown SHA-256:   afd04080adf405f07796a2c3797794b5fbb7f269ba18b40eb86f9e4ecb0e2613
# Code AST SHA-256:   0ebc7e1fc86a1edbce082a1d7d1f0be624e738dde6aaf9ee5eea414241275029
# Verified Classes:   BindingRebindError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class BindingRebindError(RuntimeError):
    """Raised when a resumed MCP session's tool binding cannot be proven
    to still point at the resource indicator recorded at call time."""


def resume_session(
    session_id: str,
    last_event_id: int,
    resume_token_resource: str,
    session_store: dict,
) -> str:
    """Resume an MCP session across transports, enforcing binding preservation.

    Returns the resource indicator the resumed stream is authorized to reach.
    Raises BindingRebindError if the resume token's resource claim does not
    match the per-tool binding recorded at tools/call time.
    """
    record = session_store.get(session_id)
    if record is None:
        raise BindingRebindError(
            f"session {session_id!r} not found; cannot prove binding, refusing resume"
        )

    bound_resource = record.get("tool_binding_resource")
    if bound_resource is None:
        raise BindingRebindError(
            f"session {session_id!r} has no recorded tool binding; "
            "resume would re-derive scope from request context"
        )

    if bound_resource != resume_token_resource:
        raise BindingRebindError(
            f"resource rebind on resume: session {session_id!r} bound to "
            f"{bound_resource!r}, resume token scoped to {resume_token_resource!r}; "
            "abandoning stream tail to prevent split-brain tool execution"
        )

    return bound_resource
