colab-mcp

repository·main·Indexed 20 days ago

https://github.com/googlecolab/colab-mcp

An 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.

Tokens
2.2K
Snippets
7
Records
12
Agent score
71%

What's inside colab-mcp

  1. Supported MCP Clients for Colab-mcp

    main

    To use Colab-mcp, your MCP client must meet two requirements:

    1. Support for notifications/tools/list_changed.
    2. The client must be running locally on your device.

    Compatible clients include:

    • Gemini CLI
    • Claude Code
    • Windsurf
  2. Install and Configure Colab-mcp via uvx

    main

    To use Colab-mcp with an MCP configuration file (such as mcp.json), follow these steps:

    1. Install uv using pip:

      pip install uv
    2. Add the following configuration to your mcpServers section:

    "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/simple flag to the arguments.

  3. Monitor Colab connectivity state via ColabProxyMiddleware

    main

    The ColabProxyMiddleware tracks the connection status between the MCP server and the Colab UI. It updates the fastmcp_context state 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.

  4. How ColabWebSocketServer handles communication

    main

    The server acts as a bridge between an application and a Google Colab frontend using anyio memory 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, an Exception is sent into the read_stream.
    • Outbound (App to Client): The application writes SessionMessage objects to the write_stream. The server picks these up, serializes them to JSON, and sends them over the WebSocket.
    • Concurrency: The server uses an asyncio.Lock to 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 code 1013 (Service Unavailable/Server Busy).
  5. Initialize and use ColabWebSocketServer

    main

    The ColabWebSocketServer is an asynchronous context manager used to host a WebSocket server that accepts connections specifically from Google Colab sessions. It enforces origin validation (allowing only https://colab.research.google.com and https://colab.google.com) and single-client exclusivity.

    To use it, wrap the server in an async with block. Once active, you interact with the server using two anyio memory streams:

    • read_stream: Receive SessionMessage objects or Exception objects sent from the Colab client.
    • write_stream: Send SessionMessage objects to the Colab client.

    The server automatically generates a secure token used 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())
  6. Manage Colab session connections with ColabSessionProxy

    main

    The ColabSessionProxy is the primary orchestrator for managing the connection between an MCP server and a Google Colab browser session. It manages a ColabWebSocketServer and a FastMCPProxy.

    To use it, you must call start_proxy_server() to initialize the WebSocket server, the proxy client, and the necessary middleware. The middleware stack includes ColabProxyMiddleware (to track connectivity state) and ToolInjectionMiddleware (to provide the connection tool). Always ensure ColabProxyMiddleware is the first middleware in the list to ensure connectivity state is available to subsequent middleware.

    Use cleanup() to properly close the AsyncExitStack and shut down the proxy server.

    proxy = ColabSessionProxy()
    await proxy.start_proxy_server()
    # ... use the proxy ...
    await proxy.cleanup()
  7. Configure ColabMCP CLI arguments

    main

    When running the ColabMCP server, you can use the following arguments to configure its behavior:

    FlagLong FlagDescription
    -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 ColabSessionProxy tools and middleware.
  8. Authenticate with ColabWebSocketServer

    main

    The server requires authorization to prevent unauthorized connections. It supports two methods of authentication:

    1. URL Query Parameter: Include the server's generated token in the WebSocket URL as a query parameter: access_token=<token>.
    2. Bearer Token: Include the token in the Authorization HTTP header: Authorization: Bearer <token>.

    If the authorization fails, the server returns standard HTTP error codes: 401 (Missing authorization), 400 (Invalid format), or 403 (Bad authorization token).

    # Method 1: Query Parameter
    ws://localhost:PORT/?access_token=YOUR_TOKEN
    
    # Method 2: Authorization Header
    Authorization: Bearer YOUR_TOKEN
  9. Run the ColabMCP server via CLI

    main

    ColabMCP 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-proxy
  10. Use the injected connection tool to unlock Colab notebook editing

    main

    The ColabSessionProxy automatically injects a tool named open_colab_browser_connection into the MCP server via ToolInjectionMiddleware.

    This tool performs the following:

    1. Checks if a connection to the Colab UI is already active.
    2. If not connected, it attempts to open a new browser tab to the Colab scratch path using the required mcpProxyToken and mcpProxyPort parameters.
    3. It waits up to 60 seconds (UI_CONNECTION_TIMEOUT) for the user to establish the connection in the browser.
    4. Returns a ToolResult containing a boolean result indicating 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"