Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/googlecolab/colab-mcp/llms.txt

Use this file to discover all available pages before exploring further.

ColabWebSocketServer is the core networking component of Colab MCP. It runs a local WebSocket server that accepts exactly one authenticated connection at a time from a Google Colab browser tab, then bridges MCP protocol messages between that tab and the rest of the Colab MCP stack via in-process memory streams. The server enforces origin restrictions, token-based authentication, and single-client exclusivity to ensure that only a trusted Colab session can inject tool calls into the agent’s environment.

Class: ColabWebSocketServer

Module: colab_mcp.websocket_server ColabWebSocketServer is used as an async context manager. The underlying WebSocket server starts on __aenter__ and is shut down on __aexit__.
from colab_mcp.websocket_server import ColabWebSocketServer

async with ColabWebSocketServer() as server:
    print(f"ws://localhost:{server.port}?access_token={server.token}")
    await server.connection_live.wait()
    # server.read_stream and server.write_stream are now active

Constructor

ColabWebSocketServer(host="localhost")
host
str
default:"localhost"
The network interface to bind the WebSocket server to. Defaults to "localhost", which means the server only accepts connections from the local machine.
The server binds to port 0 on startup, meaning the operating system assigns a free port dynamically. The assigned port is accessible via the port attribute after __aenter__ completes. On construction (before entering the context), the server:
  • Creates the in-process read_stream / write_stream memory object stream pair.
  • Generates a cryptographically random URL-safe token via secrets.token_urlsafe(16).

Attributes

port
int
The dynamically assigned port the server is listening on. Available after __aenter__ is called. Determined from server.sockets[0].getsockname()[1].
token
str
A cryptographically random URL-safe token generated with secrets.token_urlsafe(16). Used to authenticate incoming WebSocket connections. This token must be included in every connection attempt, either as a Bearer token in the Authorization header or as the access_token URL query parameter.
connection_live
asyncio.Event
Set when a client is actively connected; cleared when the client disconnects. Awaiting connection_live.wait() blocks until a Colab tab establishes a WebSocket connection.
connection_lock
asyncio.Lock
Held for the full duration of a client connection. Because only one connection is permitted at a time, this lock prevents a second WebSocket client from interfering with an active session.
read_stream
MemoryObjectReceiveStream[SessionMessage | Exception]
Receive end of the in-process stream. Messages sent by the Colab browser tab over the WebSocket are parsed and forwarded here as SessionMessage objects. If a message cannot be parsed as valid JSON-RPC, a ValidationError (an Exception subclass) is forwarded instead.
write_stream
MemoryObjectSendStream[SessionMessage]
Send end of the in-process stream. Any SessionMessage placed here is serialised to JSON and sent to the connected Colab WebSocket client.
allowed_origins
list[str]
The list of WebSocket Origin header values that are permitted to connect. Fixed to:
["https://colab.research.google.com", "https://colab.google.com"]
Connections from any other origin are rejected by the underlying websockets library before the authentication handler is invoked.

Authentication

Every connection attempt must supply the server’s token. Two methods are accepted:

Bearer token in the Authorization header

Authorization: Bearer <token>
The server parses the header, checks the scheme is bearer (case-insensitive), and compares the token value.

Token in the URL query string

ws://localhost:<port>?access_token=<token>
If the access_token=<token> string is present anywhere in the request path, the Authorization header check is skipped entirely.

HTTP error responses

CodeResponse textCondition
401Missing authorizationNo Authorization header was provided and no access_token URL parameter was present.
400Invalid authorization headerThe Authorization header was present but the scheme was not bearer.
400Invalid header formatThe Authorization header value could not be split into two parts (no space separator).
403Bad authorization tokenThe header was well-formed but the token value did not match.

WebSocket close code 1013

If a second WebSocket client attempts to connect while connection_lock is already held (i.e. a Colab tab is already connected), the server immediately closes the new connection with WebSocket close code 1013 (“Try Again Later” / “Server is busy”) without acquiring the lock.

Subprotocol

The server negotiates the mcp WebSocket subprotocol. Clients should include mcp in their Sec-WebSocket-Protocol header:
websockets.connect(uri, subprotocols=["mcp"])
read_stream may yield Exception objects, not just SessionMessage instances. When the connected Colab tab sends a WebSocket message that cannot be parsed as a valid JSONRPCMessage, the resulting ValidationError is sent directly into read_stream. Consumers of read_stream must check the type of each received item before treating it as a SessionMessage.

Build docs developers (and LLMs) love