Skip to main content
Glama
README.md
# Google Colab MCP Server (`colabmcp`)

[![MCP Version](https://img.shields.io/badge/MCP-2024--11--05-blue.svg)](https://modelcontextprotocol.io/)
[![Python Version](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue)](https://www.python.org/)
[![License](https://img.shields.io/badge/license-Apache--2.0-green.svg)](LICENSE)

A production-grade **Model Context Protocol (MCP)** server bridging autonomous AI coding assistants (Claude Desktop, Cursor, Antigravity, Cline, Roo-Code, Windsurf) with **consumer Google Colab** (`colab.research.google.com`).

Run Python code, train deep learning models, execute complete Jupyter notebooks, and inspect multimodal visualizations (Matplotlib/Seaborn plots) directly in Google's cloud GPU and TPU environments without manual browser intervention.

---

## 🌟 Key Features

- **Consumer Colab Automation:** Connects directly to Google Colab's Tunnel Frontend (TFE) without requiring enterprise GCP / Vertex AI configurations.
- **Hardware Acceleration on Demand:** Provision and switch between standard CPU, NVIDIA GPUs (Tesla T4, L4, A100, H100), and Google Cloud TPUs (v5e, v6e). High-RAM shapes (~51 GB) supported for Pro/Pro+ accounts.
- **Pre-Assignment Session Re-attachment:** Enumerates active sessions (`/tun/m/assignments`) to re-attach to existing VMs matching requested accelerators, preventing HTTP 412 quota rejection on Free Tier accounts.
- **Multi-Account Support:** Seamless switching and parameterization via `auth_user_index` (default: 0) mapped to `?authuser=N` query parameters and `X-Goog-AuthUser: N` headers.
- **Robust Google Authentication:**
  - **OAuth 2.0 Remote Flow:** Copy-paste authorization code for headless and remote terminal setups.
  - **Local Loopback Flow:** Seamless local browser authorization.
  - **Ambient ADC:** Automatic reuse of existing `gcloud auth application-default login` credentials.
  - **Chrome CDP Fallback:** Real Chrome automation via Chrome DevTools Protocol with subprocess `DEVNULL` stdout isolation (preventing JSON-RPC framing corruption) and OSID cookie verification.
- **OS-Native Keystore Storage:** Credentials securely encrypted via Windows DPAPI, macOS Keychain, or Linux Secret Service (with AES-256-GCM file fallback).
- **Persistent Keep-Alive Daemon & 30-Min Watchdog:** Background heartbeat pinging `/tun/m/{endpoint}/keep-alive/` every 35s with an in-memory activity watchdog that automatically invokes `unassign_runtime` after 30 minutes of inactivity to protect paid compute units.
- **Full Jupyter Messaging Protocol v5.3:** Direct WebSocket communication with intermediate kernel discovery/creation (`GET`/`POST /api/kernels`), RFC 6455 compliant handshake (`subprotocols=None`), dynamic header fallback (`additional_headers`/`extra_headers` for `websockets` v13+/v16.0), and SIGINT / kernel restart distinction (`state_reset`, `kernel_restarted`).
- **Chronological Multimodal MIME Translation:** Matplotlib and Seaborn plots are interleaved chronologically with stdout/stderr as MCP `ImageContent` and `TextContent` blocks, protected by head-tail truncation safety bounds (`max_text_lines`, `max_output_bytes`, `max_images`).
- **ECMA-48 Compliant ANSI Sanitizer:** Complete stripping of CSI, OSC (with multiline `(?s:\].*?(?:\x1b\\|\x07))` support), VT100, and Fe control sequences from execution traces.
- **Complete Notebook (`.ipynb`) Engine:** Load, validate, execute (sequentially or by 0-based absolute cell index in `nb.cells`), optional kernel reset before run, structured failure diagnostics (`error_name`, `error_value`, `traceback`), and save notebooks back to disk using `nbformat` v4.
- **Dual Transports:** Standard I/O (`stdio`) JSON-RPC with strict stdout isolation, plus Server-Sent Events (`sse`) for remote or multi-agent hub deployments.
- **Compute Unit Runaway Protection & Free Tier Quotas:** Explicit error handling distinguishing `HighRamNotAvailableError` (HTTP 400), `TOO_MANY_ASSIGNMENTS`, `CCU_EXHAUSTED`, and `FREE_TIER_QUOTA_EXCEEDED` (HTTP 412).

---

## 🏗️ Architecture

```
+-----------------------------------------------------------------------------------------+
|                                    AI AGENT HOST                                        |
|             (Claude Desktop / Cursor / Antigravity / Windsurf / VS Code Cline)          |
+-----------------------------------------------------------------------------------------+
                                             |
                                             | MCP Protocol (JSON-RPC 2.0)
                                             v
+=========================================================================================+
|                              COLAB MCP SERVER ENGINE                                    |
|                                                                                         |
|  +-----------------------------+               +-------------------------------------+  |
|  |     stdio Transport         |               |       SSE Transport (HTTP)          |  |
|  |  - JSON-RPC over stdin/out  |               |  - GET /sse (Event Stream)          |  |
|  |  - Stderr logger isolation  |               |  - POST /messages (RPC Dispatch)    |  |
|  +-----------------------------+               +-------------------------------------+  |
|                 |                                                 |                     |
|                 +------------------------+------------------------+                     |
|                                          |                                              |
|                                          v                                              |
|  +-----------------------------------------------------------------------------------+  |
|  |                             FastMCP Tool Dispatcher                               |  |
|  |   - Pydantic v2 schema validation & Credential Redaction Filter                   |  |
|  +-----------------------------------------------------------------------------------+  |
|            |                                |                               |           |
|            v                                v                               v           |
|  +--------------------+          +--------------------+          +--------------------+ |
|  |    Auth Module     |          |   Runtime Engine   |          |   Kernel Engine    | |
|  | - OAuth 2.0 Client |          | - TFE REST Client  |          | - WebSocket Client | |
|  | - CDP Automation   |          | - Session Manager  |          | - Jupyter v5.3 Wire| |
|  | - OS Keyring Store |          | - Keep-Alive Task  |          | - MIME Converter   | |
|  +--------------------+          +--------------------+          +--------------------+ |
+=========================================================================================+
            |                                           |                     |
            | Bearer Token                              | HTTPS TFE REST      | WSS Proxy
            v                                           v                     v
+------------------------+                 +------------------------+   +-----------------+
|  Google Accounts /     |                 |  Colab Tunnel Frontend |   | Remote Colab VM |
|  OAuth 2.0 Endpoint    |                 |  (TFE /tun/m/...)      |   | Jupyter Kernel  |
|  (accounts.google.com) |                 |  (Allocation & Status) |   | (IPython Core)  |
+------------------------+                 +------------------------+   +-----------------+
```

---

## 🚀 Installation & Quick Start

### 1. Installation

Install via `pip` or run directly with `uvx` / `pipx`:

```bash
# Using pip
pip install colab-mcp

# Or install with Playwright browser dependencies (for CDP fallback)
pip install "colab-mcp[browser]"
playwright install chromium
```

### 2. Configuration with AI Agent Hosts

#### Claude Desktop Configuration
Add `colab-mcp` to your `claude_desktop_config.json`:

- **macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Windows:** `%APPDATA%\Claude\claude_desktop_config.json`
- **Linux:** `~/.config/Claude/claude_desktop_config.json`

```json
{
  "mcpServers": {
    "colab": {
      "command": "uvx",
      "args": ["colab-mcp", "run"]
    }
  }
}
```

Or using an explicit Python virtual environment:

```json
{
  "mcpServers": {
    "colab": {
      "command": "python",
      "args": ["-m", "colab_mcp", "run"]
    }
  }
}
```

#### Cursor / Antigravity / Windsurf Configuration
In your client's MCP configuration settings (`Settings` ➔ `Features` ➔ `MCP Servers`), add:
- **Server Name:** `colab`
- **Transport:** `stdio`
- **Command:** `colab-mcp`
- **Arguments:** `["run"]`

---

## 🔑 Authentication Guide

Before provisioning runtimes, authenticate your Google account using one of the following methods:

### Method A: Remote OAuth 2.0 Flow (Recommended for CLI & Agents)
1. Ask your agent to call `colab_login(method="oauth_remote")` or run in terminal:
   ```bash
   colab-mcp login --method oauth_remote
   ```
2. The server outputs a Google authorization URL. Open the link in any browser, log in with your Google account, and grant access.
3. Copy the resulting authorization code from `https://sdk.cloud.google.com/applicationdefaultauthcode.html`.
4. Provide the code back to the agent or paste into the terminal prompt.
5. Tokens are securely encrypted into your OS Keyring.

### Method B: Local Loopback OAuth (Desktop Environments)
```bash
colab-mcp login --method oauth_loopback
```
Spawns your local system browser, receives the OAuth callback on `http://127.0.0.1:<port>`, and securely saves the token.

### Method C: Chrome CDP Browser Fallback
For environments where OAuth apps are restricted by Google Workspace policies:
```bash
colab-mcp login --method cdp_browser
```
Launches an authentic Google Chrome window with remote debugging enabled (`--remote-debugging-port=9222`), allowing you to complete standard login and 2FA. Session cookies are automatically extracted and encrypted.

---

## 🛠️ Complete MCP Tool Reference

`colabmcp` provides 13 granular tools across three functional categories:

### 1. Authentication Tools

| Tool Name | Parameters | Description |
|---|---|---|
| `colab_login` | `method` (`oauth_remote` \| `oauth_loopback` \| `oauth_adc` \| `cdp_browser` \| `cookie_import`), `auth_user_index`, `auth_code`, `cookies`, `timeout_seconds` | Authenticate with Google Colab and store encrypted credentials in OS keystore. Supports multi-account user indexing. |
| `colab_get_auth_status` | `auth_user_index` (integer, default 0), `force_refresh` (boolean) | Query active account identity, token validity, and Colab Compute Unit (CCU) balance. |
| `colab_logout` | `auth_user_index` (integer, default 0), `terminate_active_runtimes` (boolean) | Wipe stored credentials from OS keystore and optionally terminate cloud runtimes. |

### 2. Runtime Management Tools

| Tool Name | Parameters | Description |
|---|---|---|
| `colab_list_runtime_types` | `auth_user_index` (integer, default 0) | Query available accelerators (CPU, T4, L4, A100, TPU), RAM shapes, and hourly compute unit costs. |
| `colab_list_sessions` | `auth_user_index` (integer, default 0), `probe_kernels` (boolean, default true) | List all active remote and locally tracked Colab VM sessions (including browser or prior-run sessions) and live kernel states. |
| `colab_connect_runtime` | `accelerator` (`NONE` \| `T4` \| `L4` \| `A100` \| `H100` \| `V5E1` \| `V6E1`), `high_ram` (boolean), `reuse_existing` (boolean), `auth_user_index` (integer, default 0), `timeout_seconds` | Provision or re-attach to a Colab container VM and initialize kernel WebSocket. Re-attaches to active matching sessions (`reuse_existing=True`) to prevent HTTP 412 quota rejection on Free Tier. High-RAM strictly requires Pro/Pro+. |
| `colab_get_runtime_status` | `runtime_id` (optional string) | Check VM health, live CPU/RAM/VRAM/disk utilization, kernel state, and idle timer. |
| `colab_disconnect_runtime` | `runtime_id` (optional string), `disconnect_all` (boolean, default false), `auth_user_index` (integer, default 0) | Release one or all local/remote Colab VMs via `/unassign` to immediately halt compute unit consumption. |

### 3. Execution & Output Monitoring Tools

| Tool Name | Parameters | Description |
|---|---|---|
| `colab_execute_code` | `code` (string), `runtime_id`, `timeout_seconds`, `wait_for_completion`, `store_history`, `max_text_lines`, `max_output_bytes`, `max_images` | Execute Python code snippet; returns chronological multimodal content (`[TextContent, ImageContent, TextContent]`) with head-tail truncation safety bounds. |
| `colab_execute_notebook` | `notebook_path` \| `notebook_content`, `reset_kernel_before_run` (boolean, default true), `cell_indices` (0-based absolute in `nb.cells`), `stop_on_error`, `timeout_per_cell_seconds`, `output_save_path` | Execute complete `.ipynb` notebook sequentially or selectively; captures structured failure diagnostics (`error_name`, `error_value`, `traceback`) and writes outputs back to disk. |
| `colab_get_execution_status`| `execution_id` (string) | Poll execution progress, elapsed time, and partial stdout for asynchronous jobs. |
| `colab_get_cell_output` | `execution_id` (string), `include_images`, `max_text_lines`, `max_output_bytes`, `max_images` | Retrieve full buffered outputs in strict chronological kernel emission order for an execution ID. |
| `colab_interrupt_execution`| `runtime_id` (optional string) | Dispatch SIGINT interrupt; escalates to kernel restart if unhalted within 5.0s. Returns `state_reset` and `kernel_restarted` status flags. |

---

## ⚡ Hardware Accelerators & Pricing

Colab provides various hardware tiers depending on account subscription:

| Accelerator ID | Hardware Device | VRAM / HBM | High-RAM (~51 GB) | Free Tier | Approx. Cost |
|---|---|---|---|---|---|
| `NONE` | 2 vCPU Intel Xeon | None | ❌ Pro/Pro+ only (Not on Free Tier) | ✅ Yes | 0.00 CCU/hr |
| `T4` | NVIDIA Tesla T4 | 16 GB GDDR6 | ❌ Pro/Pro+ only (Not on Free Tier) | ✅ Yes (Dynamic) | ~1.96 CCU/hr |
| `L4` | NVIDIA L4 Tensor Core | 24 GB GDDR6 | Supported | ❌ Pro/Pro+ | ~3.84 CCU/hr |
| `A100` | NVIDIA A100-SXM4 | 40 GB / 80 GB | Supported | ❌ Pro/Pro+ | ~5.42 - 11.2 CCU/hr |
| `H100` | NVIDIA H100-SXM5 | 80 GB HBM3 | Supported | ❌ Pro+ | ~13.50 CCU/hr |
| `V5E1` | Cloud TPU v5e | 16 GB HBM | Standard Shape | ❌ Pro/Pro+ | ~1.96 CCU/hr |
| `V6E1` | Cloud TPU v6e | 32 GB HBM | Standard Shape | ❌ Pro+ | ~4.50 CCU/hr |

> **Important Note on Free Tier Restrictions:**
> 1. High-RAM shapes (`shape=hm`, ~51.0 GB RAM) are strictly restricted to paid Colab Pro/Pro+ tiers. Free Tier requests for High-RAM return HTTP 400 Bad Request (`HighRamNotAvailableError`).
> 2. Free Tier allows only 1 concurrent GPU container VM. `colab_connect_runtime` defaults to `reuse_existing=True` to query active sessions via `GET /tun/m/assignments` and re-attach rather than attempting duplicate allocations that trigger HTTP 412 (`TooManyAssignmentsError` or `FreeTierQuotaExceededError`).

---

## 🛡️ Security Architecture

1. **Credential Isolation & Redaction:** OAuth access tokens (`ya29...`), refresh tokens (`1//0...`), and full Google session cookies (`SAPISID`, `OSID`, etc.) are stripped by a global egress redaction filter before payloads reach LLM context.
2. **Encrypted Storage:** Secrets are managed via OS-native vaults (Windows DPAPI, macOS Keychain, Linux Secret Service). Headless servers utilize AES-256-GCM encryption with `0600` file permissions.
3. **Execution Sandbox:** All code execution occurs **inside Google's cloud containers**. No arbitrary code is evaluated locally on the host machine.
4. **Compute Unit Protection & 30-Min Inactivity Watchdog:** Mandatory execution timeouts and an active keep-alive watchdog automatically deallocate runtimes (`unassign_runtime`) after 30 minutes of inactivity to prevent runaway credit depletion.
5. **ECMA-48 ANSI Traceback Sanitization:** All terminal escape sequences (CSI, OSC via `r'|(?s:\].*?(?:\x1b\\|\x07))'`, VT100, and Fe control characters) are stripped to prevent context bloat and terminal emulation exploits.
6. **CDP Subprocess Stdout Isolation:** Chrome automation launches with `stdout=subprocess.DEVNULL` and `stderr=subprocess.DEVNULL` to prevent browser diagnostics from corrupting `stdio` JSON-RPC transport framing.

---

## 🗓️ Phased Implementation Roadmap

- **Milestone 1 (M1):** Authentication & Credential Storage (OAuth 2.0 remote/loopback/ADC, CDP browser fallback, OS keyring).
- **Milestone 2 (M2):** Runtime Lifecycle & Provisioning Engine (TFE client, hardware selector, keep-alive heartbeat).
- **Milestone 3 (M3):** Kernel WebSocket Bridge & Output Pipeline (Jupyter protocol v5.3, multimodal MIME parser, SIGINT interrupt).
- **Milestone 4 (M4):** Notebook Orchestration Engine (`nbformat` v4 loader, sequential/selective runner, serialization).
- **Milestone 5 (M5):** Dual Transports (`stdio`/`sse`), Typer CLI, Packaging (`uvx`/`pipx`), and Security Hardening.

For the exhaustive engineering architecture, refer to [COLAB_MCP_TECHNICAL_SPECIFICATION.md](COLAB_MCP_TECHNICAL_SPECIFICATION.md).

---

## 📄 License

Apache License 2.0. See [LICENSE](LICENSE) for details.