Google Colab GPU MCP Bridge
by birdbike
README.md
# Colab4WebGemini
**English** | [简体中文](README.zh-CN.md)
Turn your local authenticated [`google-colab-cli`](https://github.com/googlecolab/google-colab-cli) into a **Streamable HTTP MCP server** so the **Gemini Web App** (Gemini Apps Developer Mode) can directly provision and control remote Google Colab **GPUs (T4, L4, G4, A100, H100)** and **TPUs (v5e1, v6e1)**, run Python/Bash, install packages, and manage files — with optional single-tunnel proxying for [`gflow-cli`](https://github.com/ffroliva/gflow-cli).
---
## Architecture
```mermaid
flowchart LR
GW["Gemini Web App<br/>(Custom MCP Connector)"] -- "HTTPS POST<br/>Streamable HTTP" --> TN["HTTPS Tunnel<br/>(Cloudflare Named / Quick<br/>or localhost.run fallback)"]
TN --> AG["Colab4WebGemini Gateway<br/>(Starlette + MCP 2.3.0)"]
AG -- "/<secret>/colab/mcp<br/>Per-session Queue Lock" --> CLI["google-colab-cli<br/>(Local OAuth2 / ADC)"]
CLI --> VM["Google Colab Cloud VM<br/>(T4 / L4 / A100 / H100 / TPU)"]
AG -. "/<secret>/gflow/mcp<br/>Optional Stream Proxy" .-> GF["gflow serve<br/>(Optional Companion)"]
```
---
## Why a Dedicated Bridge for Gemini Web?
Exposing `google-colab-cli` to the Gemini Web App is not just wrapping `stdio` over HTTP. **Colab4WebGemini** solves the four real-world protocol and runtime pitfalls verified against live Gemini Web traffic:
1. **Gemini-Clean Tool Schemas**: All 15 tools expose pure scalar parameters (`string`, `number`, `boolean`) with `structured_output=False` — zero `anyOf`, `oneOf`, `additionalProperties`, `null`, or `outputSchema` fields that cause Gemini's tool converter to silently drop the entire toolset.
2. **Stateless Multi-Node Streamable HTTP**: Gemini Web dispatches requests from distributed backend IPs. The gateway uses `stateless_http=True`, `json_response=True`, disables loopback-only DNS rebinding rejection behind tunnels, and returns spec-compliant `405 Method Not Allowed` on `GET` probes instead of hanging idle SSE streams.
3. **Per-Session Concurrency Lock & Proxy-Safe Timeouts**: When Gemini emits parallel tool calls against the same Colab session, an `asyncio.Lock` per `(profile, session)` serializes access to the remote Jupyter kernel WebSocket (eliminating deadlocks) while capping per-call timeout under Cloudflare's 100s edge timeout so the UI never hangs on `"Connecting..."`.
4. **Reduced Confirmation Prompts (`ToolAnnotations`)**: Unannotated MCP tools default to `readOnlyHint: false, destructiveHint: true`, causing Gemini Web to repeatedly ask for confirmation or reset "Always allow". `auto_approve_hints: true` (configurable in `config.json`) annotates tools with `readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false`.
Additional quality-of-life features:
* **Auto-Fallback HTTPS Tunnel**: `Cloudflare Named Tunnel` -> `Cloudflare Quick Tunnel` -> `localhost.run` SSH reverse tunnel (automatically recovers from `trycloudflare.com` `429` rate limits).
* **Hot-Reload Without Rotating Tunnel URL**: Restarting `gateway.py` preserves the running tunnel process and its public HTTPS URL.
* **Multi-Account Support**: Every tool accepts an optional `profile` argument forwarded via `COLAB_PROFILE`.
* **Built-in JSON-RPC Trace Log**: Full request/response diagnostics written to `logs/mcp_trace.log`.
---
## Prerequisites
1. **Python 3.12+** and [`uv`](https://docs.astral.sh/uv/) (recommended) or `pip`.
2. **[`google-colab-cli`](https://github.com/googlecolab/google-colab-cli)** installed and authenticated locally:
```bash
uv tool install google-colab-cli
colab whoami
colab usage
```
3. *(Optional)* **`cloudflared`** in `PATH` or `./bin/cloudflared[.exe]` for Cloudflare Tunnels. Without it (or if Quick Tunnel hits rate limit `429`), the supervisor automatically falls back to OpenSSH (`localhost.run`).
---
## Quick Start
### 1. Clone and install dependencies
```bash
git clone https://github.com/birdbike/Colab4WebGemini.git
cd Colab4WebGemini
uv venv --python 3.12
uv pip install -e .
```
### 2. Configure (optional)
On first run, `config.json` is auto-generated with a 32-hex high-entropy `secret_path` and auto-discovered `colab` binary. You can also copy `config.example.json` to `config.json` to customize:
* `colab_exe`: Explicit path to `colab` / `colab.exe` if it is inside a separate virtualenv instead of `PATH`.
* `enable_gflow` / `gflow_exe`: Set `true` to also proxy a local `gflow serve` instance at `/<secret_path>/gflow/mcp`.
* `auto_approve_hints`: `true` by default to prevent repeated confirmation dialogs in Gemini Web; set `false` for strict read/write/destructive annotations.
* `tunnel_provider`: `"auto"` (default), `"cloudflared"`, `"localhost.run"`, or `"none"`.
### 3. Start the bridge
**Windows (PowerShell background scripts):**
```powershell
powershell -ExecutionPolicy Bypass -File .\start.ps1
powershell -ExecutionPolicy Bypass -File .\status.ps1
powershell -ExecutionPolicy Bypass -File .\stop.ps1
```
**Linux / macOS / Cross-platform (foreground):**
```bash
python run_stack.py
# Or using the installed console entry point:
colab4webgemini
```
The console prints your ready-to-paste HTTPS endpoint:
```text
================ MCP BRIDGE READY ================
Tunnel Provider : cloudflared-quick
Colab GPU MCP (Web Gemini) : https://<random>.trycloudflare.com/mcp-<32hex>/colab/mcp
Local Health : http://127.0.0.1:8765/health
==================================================
```
### 4. Verify end-to-end over public HTTPS
```bash
python verify.py
```
### 5. Connect in Gemini Web App
1. Open Gemini Web App -> **Settings -> Gemini Apps Developer Mode** -> **Connect to an MCP server**.
2. Paste the **Colab GPU MCP** `https://...` URL into **MCP Server URL**.
3. Leave **OAuth Client ID** and **Client Secret** empty and click **Next**.
4. Start a chat and test:
> Call `@Google Colab GPU MCP Bridge` `colab_usage` to check my compute unit balance.
---
## Built-in MCP Tools (15)
Every tool accepts an optional `profile` parameter to switch `COLAB_PROFILE`.
| Tool | Description |
| --- | --- |
| `colab_usage` | Show compute-unit balance, hourly burn rate, and active assignments |
| `colab_whoami` | Show authenticated account email, token expiry, and OAuth scopes |
| `colab_sessions` | List all active backend Colab sessions |
| `colab_status` | Show hardware type, shape, IDLE/BUSY status, and last execution |
| `colab_new` | Provision a VM (`CPU`, `T4`, `L4`, `G4`, `A100`, `H100`, or TPU `V5E1`/`V6E1`, optional `high_mem`) |
| `colab_exec` | Execute Python code on the persistent Jupyter kernel (`/content` cwd, optional `env_vars_json`) |
| `colab_shell` | Execute Bash commands/scripts via `%%bash` over the Jupyter kernel (no SSH key required) |
| `colab_install` | Install Python packages on the VM via `uv` / `pip` |
| `colab_ls` | List remote directory contents on the Colab VM |
| `colab_rm` | Delete a remote file on the Colab VM |
| `colab_write_file` | Upload UTF-8 text (scripts, configs, JSON) directly to the Colab VM |
| `colab_read_file` | Download and read UTF-8 text files/logs from the Colab VM |
| `colab_restart_kernel` | Restart the Jupyter kernel (keeps VM, clears RAM/VRAM) |
| `colab_url` | Print the Colab browser URL attached to an active CLI session |
| `colab_stop` | Stop and release a VM session (or all sessions with `all_sessions=true`) |
---
## Permanent Custom Domain (Recommended for Daily Use)
Quick tunnels rotate hostnames on restart. To keep a permanent URL in Gemini Web:
1. Create a Named Tunnel in **Cloudflare Zero Trust** pointing to `http://127.0.0.1:8765`.
2. Fill `cf_tunnel_token` and `cf_public_url` (e.g. `"https://mcp.yourdomain.com"`) in `config.json`.
3. Restart the bridge — your endpoint stays permanently at `https://mcp.yourdomain.com/<secret_path>/colab/mcp`.
---
## Security Notes
* **Never share your full MCP URL** — the unauthenticated quick-start mode relies on the high-entropy `secret_path` to guard remote code execution on your Colab runtime.
* **`config.json` and `logs/` are gitignored** by default. Keep them local.
* Stop idle GPUs via `colab_stop` when finished to avoid burning compute units.
---
## License
[MIT](LICENSE)
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues