Colab2API MCP Server
README.md
# Colab2API
> **English** | [简体中文](./README_CN.md)
**Headless-Ready Google Colab GPU Pool & Multi-Protocol AI Gateway (`OpenAI /v1` · `Gemini /v1beta` · `MCP /mcp`)**
Orchestrate multiple Google Colab GPU runtimes (`G4` RTX PRO 6000 96GB, `L4` 24GB, `A100` 80GB, `H100` 80GB, `T4` 16GB) or external ComfyUI / Diffusers / vLLM endpoints behind a single production-grade gateway — complete with per-account OAuth2 credential vaults, 5 enterprise routing strategies, 3-state circuit breakers, Recipe Studio + ComfyUI Workflow JSON auto-importer, optional Admin Password Protection, and a Dual Light/Dark Precision Studio Web Console.
---
## Key Capabilities
- **Built-in & Custom Model Recipes (Recipe Studio)**:
- `minimax-h3`: ComfyUI + `Comfy-Org/MiniMax-H3` (BF16/INT8 video + 32kHz stereo audio, T2V / I2V / FL2V, 4-step / 8-step Turbo LoRA + native 20-step).
- `qwen-image-2.1`: Native FastAPI + Diffusers (`Qwen/Qwen-Image-2.1-Turbo` 8-step & `Qwen/Qwen-Image-2.1` 40-step) unified image generation + multi-image instruction editing + batch `n=1..4`.
- `flux-2`: High-fidelity FLUX.2 image generation (`flux-2`, `flux-2-dev`, `flux-2-schnell`) with Google Drive staged weight cache & `HF_TOKEN` support.
- `vllm-openai`: Launch vLLM OpenAI-compatible LLM server on Colab (`L4`/`A100`/`G4`/`H100`) with real upstream SSE token streaming through `POST /v1/chat/completions`.
- `comfyui-base`: Clean ComfyUI + Cloudflare Tunnel environment on any GPU.
- **Custom Recipes & ComfyUI Workflow JSON Importer**: Clone any recipe, author custom Git/HF scripts, or upload/paste any ComfyUI API-format workflow JSON to auto-detect `prompt` / `seed` / `steps` / `width` / `height` bindings and expose it directly as a `/v1/*` model.
- **Multi-Protocol AI Gateway**:
- **OpenAI `/v1/*`**: `GET /v1/models`, `POST /v1/images/generations`, `POST /v1/images/edits`, `POST /v1/videos/generations`, `GET /v1/videos/generations/{job_id}`, `POST /v1/chat/completions` (streaming SSE & non-streaming).
- **Gemini `/v1beta/*`**: `GET /v1beta/models`, `POST /v1beta/models/{model}:generateContent`, `POST /v1beta/models/{model}:predict` (`x-goog-api-key`, `?key=`, or Bearer).
- **Streamable HTTP MCP `/mcp`**: Pure-FastAPI JSON-RPC 2.0 MCP server exposing 7 tools (`list_models`, `list_gpu_nodes`, `get_cu_balance`, `generate_image`, `generate_video`, `get_job_status`, `stop_gpu_node`) for Claude Desktop, Cursor, and Antigravity.
- **Enterprise Routing, Reliability & Cost Protection**:
- **5 Routing Strategies**: `least-busy`, `round-robin`, `weighted-priority`, `fill-first` (CU bin-packing), and `sticky-session` (fallback-safe affinity).
- **Model Mappings & Aliases**: Exact, prefix, and wildcard redirects (e.g. `dall-e-3 -> qwen-image-2.1-turbo`, `sora-2 -> minimax-h3`).
- **3-State Circuit Breaker** (`closed` / `open` / `half_open`), per-key RPM + concurrency slots + expiry + IP allowlist, Async Task Queue & Batch Submit, and Outbound Webhooks (Feishu / Slack / Discord / Generic HMAC).
- **CU Billing Protection**: Live Compute Unit telemetry, Orphan `[?]` session detection/unassign, per-node Auto-Idle Shutdown Watchdog, and Emergency Stop All.
- **Precision Studio Web Console**:
- Zero-build, zero-CDN offline-capable SPA with **Mineral Light** & **Obsidian Precision Dark** dual themes, `Ctrl/Cmd+K` Command Palette, 4 zero-CDN SVG analytics charts, 3-tab Node Workbench Drawer (Live SSE Logs, Remote Bash/Python Terminal, Remote `/content` File Explorer), Audit Log Payload Inspector & 1-click Replay, Config Backup/Restore with Dry-Run Diff Preview, and optional `scrypt` + `HttpOnly` Admin Password Lock.
---
## Linux Server Production Deployment
### Option 1: Docker Compose (Recommended)
```bash
git clone https://github.com/googxi1310328414-afk/colab2api.git
cd colab2api
cp .env.example .env
# Strongly recommended on internet/LAN servers: set an admin password
# Edit .env and set COLAB2API_ADMIN_PASSWORD=<strong-password>
# (if left empty, a random one is generated on first start: see `docker compose logs colab2api`)
docker compose up -d --build
# Verify gateway health
curl -fsS http://127.0.0.1:7860/health
```
Persistent state is stored in `./data` (SQLite database, per-account OAuth vault JSON files, Ed25519 SSH fallback keys) and `./outputs` (generated MP4/PNG media).
### Option 2: Native Linux + `start_gateway.sh`
```bash
python3 -m venv .venv
.venv/bin/pip install --upgrade pip
.venv/bin/pip install -r requirements.txt
cp .env.example .env
chmod +x start_gateway.sh
# Foreground mode (waits for GET /health == 200 and prints live endpoints)
./start_gateway.sh --host 0.0.0.0 --port 7860
# Background daemon mode (logs -> data/colab2api.log, PID -> data/colab2api.pid)
./start_gateway.sh --daemon --port 7860
./start_gateway.sh --status
./start_gateway.sh --stop
```
### Option 3: `systemd` Service + Nginx HTTPS Reverse Proxy
```bash
sudo useradd --system --create-home --shell /usr/sbin/nologin colab2api
sudo mkdir -p /opt/colab2api
sudo cp -r . /opt/colab2api
sudo chown -R colab2api:colab2api /opt/colab2api
sudo -u colab2api python3 -m venv /opt/colab2api/.venv
sudo -u colab2api /opt/colab2api/.venv/bin/pip install -r /opt/colab2api/requirements.txt
sudo -u colab2api cp /opt/colab2api/.env.example /opt/colab2api/.env
sudo cp deploy/colab2api.service /etc/systemd/system/colab2api.service
sudo systemctl daemon-reload
sudo systemctl enable --now colab2api
sudo systemctl status colab2api
```
Then place Nginx in front of `127.0.0.1:7860` using [`deploy/nginx.conf.example`](deploy/nginx.conf.example) (`proxy_buffering off` for SSE live deploy logs and vLLM streaming, `X-Forwarded-Proto https` for `Secure` Admin cookies, `client_max_body_size 50m`).
### Option 4: Windows Local Quick Start
Double-click [`start_gateway.bat`](start_gateway.bat) (auto-detects `.venv` / Miniconda / PATH Python, verifies `fastapi`/`uvicorn`, checks port availability, waits for `GET /health` HTTP `200`, and only then opens the browser).
---
## Headless Linux OAuth Onboarding
Colab2API stores every Google Colab account in an isolated vault file (`data/credentials/<account_id>.json`, mode `0600`) without requiring a desktop OS keyring:
1. Open **账号池 (Accounts)** -> **接入 Colab 账号**.
2. Click **生成 Google 授权链接** (uses Google Cloud SDK remote redirect URI with PKCE — works identically on headless VPS, Docker, and LAN servers).
3. Open the URL in your local browser, approve Google Colab access, copy the returned authorization code, paste it into Step 2, and click **完成授权并同步配额**.
4. Alternatively, upload an existing authorized-user credential JSON file or mount a server ADC path.
---
## Security & Admin Lock
- Local development (bound to `127.0.0.1`, no password): the Admin Console works without a password, but **only for direct requests from the gateway host**. Remote clients, requests that carry reverse-proxy headers (`X-Forwarded-*`, `X-Real-IP`, `Forwarded`), DNS-rebinding `Host` headers and cross-site `Origin`s get `403`, so neither another machine nor a web page you visit can use or claim the console.
- **Exposed gateways** (non-loopback bind such as `0.0.0.0`, or `COLAB2API_ENV=production`, the Docker/systemd default) never run without a password: if `COLAB2API_ADMIN_PASSWORD` is empty, a random password is generated on first start and **printed once to the log** (`docker compose logs colab2api`, `journalctl -u colab2api`, or `data/colab2api.log`). Only its scrypt hash is stored; setting `COLAB2API_ADMIN_PASSWORD` always overrides it.
- Set or rotate the password via `COLAB2API_ADMIN_PASSWORD=<strong-password>` in `.env`, or Web Console -> **日志与设置 (Logs & Settings)** -> **控制台安全锁 (Admin Auth)**. Disabling it is refused on exposed gateways.
- Once enabled, all `/admin/api/*` requests require either the signed `HttpOnly` cookie (`colab2api_admin_session`, automatically marked `Secure` behind HTTPS reverse proxies via `X-Forwarded-Proto: https`) or the `X-Admin-Token` header for CLI/CI scripts.
- CORS automatically tightens when Admin Auth is enabled or `COLAB2API_ENV=production` / `COLAB2API_ALLOWED_ORIGINS` is set.
- Optional `COLAB2API_ALLOWED_HOSTS=gpu.example.com,*.corp.example` rejects any other `Host` header (loopback and the `COLAB2API_PUBLIC_BASE_URL` host are always accepted).
- Only if an external auth gate (Cloudflare Access, oauth2-proxy, ...) protects the gateway: `COLAB2API_INSECURE_NO_ADMIN_AUTH=1` serves the admin API without a password to every client.
- Built-in ComfyUI recipes (`minimax-h3`, `comfyui-base`, imported workflows) run ComfyUI on `127.0.0.1:8187` only, behind a token-checking proxy on `:8188` (the port the Cloudflare tunnel and SSH fallback use). Requests need the node's worker token (`Authorization: Bearer ...`, sent by the gateway automatically); to open the ComfyUI UI in a browser, visit `<tunnel-url>/?c2a_token=<token>` once (the token is the node's `extra_config.auth_token`, also in `/content/comfyui_worker_token.txt` on the VM). Nodes deployed before this change keep their old layout until redeployed.
---
## Client Integration Examples
### OpenAI Python SDK (Images, Video & vLLM Streaming)
```python
from openai import OpenAI
client = OpenAI(
base_url="https://gpu.example.com/v1",
api_key="sk-colab2api-default-...",
)
# 1. Generate image via Qwen-Image-2.1-Turbo or FLUX.2
img = client.images.generate(
model="qwen-image-2.1-turbo",
prompt="Minimalist architectural concrete studio in alpine mist, medium format",
size="1344x768",
)
print(img.data[0].url)
# 2. Stream LLM tokens from a vllm-openai Colab node
stream = client.chat.completions.create(
model="vllm-openai",
messages=[{"role": "user", "content": "Explain speculative decoding concisely."}],
stream=True,
)
for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
print(delta, end="", flush=True)
```
### Gemini `/v1beta` REST Adapter
```bash
curl -X POST "https://gpu.example.com/v1beta/models/qwen-image-2.1-turbo:generateContent" \
-H "x-goog-api-key: sk-colab2api-default-..." \
-H "Content-Type: application/json" \
-d '{"contents":[{"role":"user","parts":[{"text":"Precision anodized synthesizer macro"}]}]}'
```
### MCP Server (`/mcp` — Claude Desktop / Cursor / Antigravity)
```json
{
"mcpServers": {
"colab2api": {
"type": "streamable-http",
"url": "https://gpu.example.com/mcp",
"headers": {
"Authorization": "Bearer sk-colab2api-default-..."
}
}
}
}
```
---
## Project Architecture
```text
colab2api/
├── main.py # FastAPI entrypoint, AdminAuth + DynamicCORS middleware, /health
├── start_gateway.sh # Headless Linux/macOS launcher (foreground & --daemon)
├── start_gateway.bat # Windows smart launcher (Python probe + /health wait)
├── Dockerfile # Slim Python 3.12 non-root container + HEALTHCHECK
├── docker-compose.yml # Production Compose with ./data & ./outputs persistence
├── requirements.txt # Clean Linux server Python dependencies
├── .env.example # Environment variable configuration template
├── deploy/
│ ├── colab2api.service # Hardened systemd unit
│ └── nginx.conf.example # HTTPS reverse proxy with SSE & WebSocket tuning
├── colab2api/
│ ├── db.py / schemas.py # SQLite WAL + Schema v2 additive migrations + Pydantic v2
│ ├── oauth_vault.py # Per-account JSON token vault & PKCE Web OAuth
│ ├── colab_engine.py # Python-native Colab SDK, JWT refresh, Drive hook, terminal/files
│ ├── colab_manager.py # Deploy orchestrator, SSE log broadcaster, idle watchdog
│ ├── recipes.py # Built-in recipes (MiniMax-H3, Qwen-Image-2.1, FLUX.2, vLLM, ComfyUI)
│ ├── recipe_studio.py # Custom recipe CRUD, cloning & ComfyUI Workflow JSON auto-importer
│ ├── router.py / rate_limiter.py # 5 strategies, model mappings, 3-state circuit breaker, tasks
│ ├── routes_openai.py # /v1/* gateway + vLLM SSE passthrough + custom workflow execution
│ ├── routes_protocols.py # Gemini /v1beta/* + Streamable HTTP MCP /mcp
│ ├── routes_admin.py # Admin APIs, log inspector/replay, config export/import, auth
│ ├── config_io.py # Sanitized JSON config backup/restore with dry-run diff
│ ├── admin_auth.py # scrypt + HMAC HttpOnly session / X-Admin-Token + dynamic CORS
│ └── webhooks.py # Feishu / Slack / Discord / Generic HMAC alert dispatcher
├── web/
│ ├── index.html / styles.css / app.js # Zero-build Dual Light/Dark Precision Studio SPA
│ └── js/
│ ├── charts.js # Zero-CDN theme-aware SVG telemetry charts
│ ├── vm_drawer.js # 3-tab Node Workbench (SSE Logs / Terminal / Files)
│ ├── routing_views.js # Routing, Model Mappings, Task Queue & Webhooks views
│ ├── recipe_studio.js # Recipe Studio, ComfyUI Importer, Backup/Restore, Admin Gate
│ ├── command_palette.js # Ctrl/Cmd+K fuzzy command palette & styled confirm modal
│ └── log_inspector.js # Audit Log Payload Inspector, cURL builder, Replay & Export
└── tests/ # 4 automated regression & stress suites (zero billable VM calls)
```
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues