colab-mcp
repository·main·Indexed 20 days ago
https://github.com/googlecolab/colab-mcpAn MCP (Model Context Protocol) server that enables local AI agents, such as Claude Code, Gemini CLI, and Windsurf, to interact with Google Colab sessions running in a web browser. It provides a bridge via ColabSessionProxy and ColabWebSocketServer to manage connectivity, authenticate sessions, and inject tools like open_colab_browser_connection for notebook editing.
What's inside colab-mcp
- Colab-mcp is an MCP (Model Context Protocol) server designed to bridge a local AI agent to a Google Colab session running in your web browser. This allows local agents to interact with your Colab environment.
Supported MCP Clients for Colab-mcp
mainTo use Colab-mcp, your MCP client must meet two requirements:
- Support for
notifications/tools/list_changed. - The client must be running locally on your device.
Compatible clients include:
- Gemini CLI
- Claude Code
- Windsurf
- Support for
Install and Configure Colab-mcp via uvx
mainTo use Colab-mcp with an MCP configuration file (such as
mcp.json), follow these steps:Install
uvusing pip:pip install uvAdd the following configuration to your
mcpServerssection:
"mcpServers": { "colab-mcp": { "command": "uvx", "args": ["git+https://github.com/googlecolab/colab-mcp"], "timeout": 30000 } }Note: If you are using a non-standard default package index, you may need to add the
--index https://pypi.org/simpleflag to the arguments.Monitor Colab connectivity state via ColabProxyMiddleware
mainThe
ColabProxyMiddlewaretracks the connection status between the MCP server and the Colab UI. It updates thefastmcp_contextstate on every message and whenever the connection status changes.Developers can access the following state keys within the MCP context:
fe_connected: A boolean indicating if the frontend is connected.proxy_token: The token used for the proxy connection.proxy_port: The port used for the proxy connection.
When the connection status changes (e.g., from disconnected to connected), the middleware triggers
send_tool_list_changed()to notify the client.How ColabWebSocketServer handles communication
mainThe server acts as a bridge between an application and a Google Colab frontend using
anyiomemory streams.- Inbound (Client to App): The server listens to the WebSocket. When a JSON-RPC message arrives, it is validated and placed into the
read_stream. If validation fails or the client disconnects, anExceptionis sent into theread_stream. - Outbound (App to Client): The application writes
SessionMessageobjects to thewrite_stream. The server picks these up, serializes them to JSON, and sends them over the WebSocket. - Concurrency: The server uses an
asyncio.Lockto ensure only one client can be connected at a time. If a second connection attempt is made while a client is active, the server rejects it with code1013(Service Unavailable/Server Busy).
- Inbound (Client to App): The server listens to the WebSocket. When a JSON-RPC message arrives, it is validated and placed into the
Initialize and use ColabWebSocketServer
mainThe
ColabWebSocketServeris an asynchronous context manager used to host a WebSocket server that accepts connections specifically from Google Colab sessions. It enforces origin validation (allowing onlyhttps://colab.research.google.comandhttps://colab.google.com) and single-client exclusivity.To use it, wrap the server in an
async withblock. Once active, you interact with the server using twoanyiomemory streams:read_stream: ReceiveSessionMessageobjects orExceptionobjects sent from the Colab client.write_stream: SendSessionMessageobjects to the Colab client.
The server automatically generates a secure
tokenused for authorization.from colab_mcp.websocket_server import ColabWebSocketServer async def main(): async with ColabWebSocketServer(host="localhost") as server: # Access the streams to communicate with Colab # server.read_stream # server.write_stream print(f"Server running on port: {server.port}") print(f"Authorization token: {server.token}") # Keep the server running await asyncio.sleep(3600) import asyncio asyncio.run(main())Manage Colab session connections with ColabSessionProxy
mainThe
ColabSessionProxyis the primary orchestrator for managing the connection between an MCP server and a Google Colab browser session. It manages aColabWebSocketServerand aFastMCPProxy.To use it, you must call
start_proxy_server()to initialize the WebSocket server, the proxy client, and the necessary middleware. The middleware stack includesColabProxyMiddleware(to track connectivity state) andToolInjectionMiddleware(to provide the connection tool). Always ensureColabProxyMiddlewareis the first middleware in the list to ensure connectivity state is available to subsequent middleware.Use
cleanup()to properly close theAsyncExitStackand shut down the proxy server.proxy = ColabSessionProxy() await proxy.start_proxy_server() # ... use the proxy ... await proxy.cleanup()Configure ColabMCP CLI arguments
mainWhen running the ColabMCP server, you can use the following arguments to configure its behavior:
Flag Long Flag Description -l--logSpecifies the directory for log files. If unset, it defaults to a temporary directory prefixed with colab-mcp-logs-inside the system temp folder.-p--enable-proxyEnables or disables the runtime proxy. This is enabled by default. If enabled, the server mounts ColabSessionProxytools and middleware.Authenticate with ColabWebSocketServer
mainThe server requires authorization to prevent unauthorized connections. It supports two methods of authentication:
- URL Query Parameter: Include the server's generated token in the WebSocket URL as a query parameter:
access_token=<token>. - Bearer Token: Include the token in the
AuthorizationHTTP header:Authorization: Bearer <token>.
If the authorization fails, the server returns standard HTTP error codes:
401(Missing authorization),400(Invalid format), or403(Bad authorization token).# Method 1: Query Parameter ws://localhost:PORT/?access_token=YOUR_TOKEN # Method 2: Authorization Header Authorization: Bearer YOUR_TOKEN- URL Query Parameter: Include the server's generated token in the WebSocket URL as a query parameter:
Reference: ColabProxyMiddleware state keys
mainThe following keys are used by
ColabProxyMiddlewareto communicate connection status to the MCP client via thefastmcp_contextstate.FE_CONNECTED_KEY = "fe_connected" PROXY_TOKEN_KEY = "proxy_token" PROXY_PORT_KEY = "proxy_port"Run the ColabMCP server via CLI
mainColabMCP is an MCP server that allows interaction with Google Colab. It can be executed as a standalone process. By default, it enables a runtime proxy that provides session proxy tools. You can control the logging directory and the proxy status using command-line flags.
# Basic execution python -m colab_mcp # Specify a custom log directory python -m colab_mcp --log /path/to/logs # Disable the runtime proxy python -m colab_mcp --enable-proxyUse the injected connection tool to unlock Colab notebook editing
mainThe
ColabSessionProxyautomatically injects a tool namedopen_colab_browser_connectioninto the MCP server viaToolInjectionMiddleware.This tool performs the following:
- Checks if a connection to the Colab UI is already active.
- If not connected, it attempts to open a new browser tab to the Colab scratch path using the required
mcpProxyTokenandmcpProxyPortparameters. - It waits up to 60 seconds (
UI_CONNECTION_TIMEOUT) for the user to establish the connection in the browser. - Returns a
ToolResultcontaining a booleanresultindicating success or failure.
# The tool is automatically available in the MCP server's tool list # name: "open_colab_browser_connection" # description: "Opens a connection to a Google Colab browser session and unlocks notebook editing tools. Returns a boolean representing whether the connection attempt succeeded"