# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-migrates-an-mcp-session-from-resumable-sse-to-streamable-http-mid-tool-call-and-the-negotiated-capability-set-silently-r.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-migrates-an-mcp-session-from-resumable-sse-to-streamable-http-mid-tool-call-and-the-negotiated-capability-set-silently-r.warrant.json
# Markdown SHA-256:   d2ed2f42dcae5fb358040799e0f60b77e57f3cd90b354b73565816be7a119ed0
# Code AST SHA-256:   86d019f391e4e81c787de7aea02168ac21ed689191912ff2e5a2f7ca0451730a
# Verified Classes:   CapabilityTransportDesyncError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CapabilityTransportDesyncError(RuntimeError):
    """Raised when a session's enforced capability tuple diverges from the
    tuple negotiated at initialize, across a transport rebind."""
    pass


DEFAULT_CAPABILITIES = {
    "progressNotifications": False,
    "outputSchema": {"filesystem.read": "v1"},
}


def rebind_transport(session, new_transport: str, last_event_id: str | None):
    """Bind an existing logical session to a new transport.

    Returns the capability tuple the server will enforce on the new binding.
    Raises CapabilityTransportDesyncError if the enforced tuple differs from
    the negotiated tuple and the client has not explicitly accepted a downgrade.
    """
    negotiated = session.capabilities
    enforced = session.server_default_capabilities or DEFAULT_CAPABILITIES

    # A resumption token from one transport binding is not valid on another
    # unless the server explicitly advertises cross-transport replay.
    if last_event_id is not None and new_transport != session.transport:
        if not session.server_supports_cross_transport_replay:
            raise CapabilityTransportDesyncError(
                f"resumption token {last_event_id!r} from {session.transport!r} "
                f"is not valid on {new_transport!r}; server does not advertise "
                f"cross-transport replay"
            )

    if enforced != negotiated:
        if not session.client_accepts_downgrade:
            raise CapabilityTransportDesyncError(
                f"capability tuple regressed on rebind to {new_transport!r}: "
                f"negotiated={negotiated!r} enforced={enforced!r}; "
                f"client must re-initialize or explicitly accept downgrade "
                f"before issuing further tool calls"
            )
        session.capabilities = enforced

    session.transport = new_transport
    return enforced
