Google Colab MCP: Run a Notebook With Claude Code
Connect Claude Code to Google Colab GPUs using Google's official colab-mcp server, run a PyTorch example, and learn when Colab CLI is a better fit.
Google Colab MCP (googlecolab/colab-mcp) lets Claude Code provision remote Google Colab runtimes, execute Python cells on cloud GPUs, inspect tracebacks, and iterate on ML code directly from your local terminal without browser copy-pasting. Register the official open-source server via uvx in your MCP configuration, authenticate once via Google OAuth, and Claude Code gains stateful create_runtime and execute_code tools.
For terminal-first AI engineers, this closes the gap between local repository editing and cloud CUDA compute. Yet MCP is only half of Google’s developer toolkit: knowing when to drive Colab interactively via Colab MCP versus running headless jobs with the Google Colab CLI saves both compute units and debugging time.
Key Takeaways
- Zero-Copy Remote GPU Execution: Google’s official
googlecolab/colab-mcpserver connects Claude Code to remote Colab CPU, GPU, and TPU kernels over stdio viauvx.- Stateful Kernel Loops: Core MCP primitives (
list_runtimes,create_runtime,create_session,execute_code) preserve Python memory across iterations so Claude Code can fix CUDA or shape errors without reloading datasets.- Reproducible PyTorch Workflow: Claude Code can push a compact PyTorch training script straight to a Colab GPU, parse
stdout/stderr, and verify loss convergence automatically.- MCP vs Colab CLI: Choose Colab MCP for interactive, exploratory agent debugging inside Claude Code; choose Google Colab CLI (
colab run --gpu A100 train.py,colab ssh) for headless CI/CD pipelines, deterministic batch scripts, and direct terminal SSH.
How Google Colab MCP Connects Claude Code to Remote GPUs
Google Colab MCP bridges a local MCP client (such as Claude Code) to Google’s managed Jupyter runtime APIs using standard JSON-RPC tool calls. Introduced in the Google Developers Blog announcement for the Colab MCP Server, the server eliminates manual browser tab switching when agents need CUDA hardware.
Figure 1: End-to-end execution flow from Claude Code through the local uvx colab-mcp server to a stateful remote Google Colab GPU kernel.
Under-the-Hood Tool Surface in googlecolab/colab-mcp
If you are new to how tool discovery and stdio transport work, read our Model Context Protocol (MCP) explained guide first. Inside the Google Colab MCP Server GitHub repository, the server exposes four primary primitives that Claude Code chains together automatically:
list_runtimes: Audits active Colab VMs on your Google account so the agent reuses an existing GPU instead of hitting concurrent session limits.create_runtime: Provisions a new remote runtime with a unique UUIDrequestIdand an acceleratorruntimeSpec(such as T4, L4, A100, or TPU, subject to your account tier).create_session: Attaches a persistent Jupyter kernel session inside the active runtime so imported libraries and loaded tensors remain in memory.execute_code: Sends a Python code block to the remote kernel and returns structuredstdout,stderr, the final evaluatedresult, and anyexecutionErrortraceback directly to Claude Code.
Why Stateful Remote Kernels Matter for Agentic ML
Running isolated stateless scripts forces an agent to reinstall packages and reload datasets on every retry. Because colab-mcp keeps the Jupyter kernel alive across execute_code calls, Claude Code can load a PyTorch dataset once in cell 1, hit a tensor dimension mismatch in cell 2, patch the model class locally, and re-run only the training step in seconds.
Step-by-Step Setup: Connecting Claude Code to Google Colab MCP
Setting up colab-mcp with Claude Code requires Python 3, the uv package runner, and a single JSON block in your MCP configuration. No manual virtual environment creation or repo cloning is required because uvx resolves and caches the package on demand.
Step 1: Install uv and Register colab-mcp
Install uv if it is not already on your PATH, then add colab-mcp to your Claude Code MCP configuration (either project-scoped .mcp.json or your user Claude Code config). For broader client configuration patterns across servers, see our best MCP servers for Claude guide.
# Install uv if not already available
pip install --upgrade uv
# Verify uvx is ready
uvx --version
Add the official colab-mcp entry to your .mcp.json file with a 30-second startup timeout so cold uvx package resolution never aborts early:
{
"mcpServers": {
"colab-mcp": {
"command": "uvx",
"args": [
"git+https://github.com/googlecolab/colab-mcp"
],
"timeout": 30000
}
}
}
If you work behind a corporate Python registry, append "--index", "https://pypi.org/simple" inside args so uvx resolves public dependencies cleanly.
Step 2: Authenticate via OAuth and Verify Tool Discovery
Launch Claude Code in your project directory and check /mcp to confirm colab-mcp shows a connected status. The first time Claude Code invokes list_runtimes or create_runtime, colab-mcp opens a standard Google OAuth consent screen in your local browser.
Sign in with the Google account that holds your Colab Free, Pro ($9.99/month for 100 compute units), Pro+, or Google AI plan. Once authorized, Claude Code can query and provision 16 GB T4 or 80 GB A100/H100 runtimes for the remainder of the session with a 30,000 ms startup timeout buffer and zero repeated browser logins.
Walkthrough: Running a Small PyTorch Example From Claude Code
To verify the full loop from local editor to remote CUDA execution, save a small, self-contained PyTorch MLP training script in your local repo and instruct Claude Code to run and verify it on a Colab GPU.
The Local PyTorch Script (train_mlp_colab.py)
This compact script builds a synthetic classification dataset, confirms CUDA placement per the PyTorch CUDA Semantics Documentation, trains a two-layer network for 10 epochs, and prints structured JSON metrics that Claude Code can parse cleanly.
import json
import time
import torch
import torch.nn as nn
def run_tiny_mlp_experiment(epochs: int = 10, samples: int = 4096) -> dict[str, object]:
"""Train a tiny PyTorch MLP on Colab CUDA and return structured metrics."""
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
torch.manual_seed(42)
x = torch.randn(samples, 64, device=device)
weights_true = torch.randn(64, 1, device=device)
y = (x @ weights_true > 0).float()
model = nn.Sequential(
nn.Linear(64, 128),
nn.ReLU(),
nn.Linear(128, 1),
).to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-2)
loss_fn = nn.BCEWithLogitsLoss()
start = time.perf_counter()
final_loss = 0.0
for _ in range(epochs):
optimizer.zero_grad(set_to_none=True)
logits = model(x)
loss = loss_fn(logits, y)
loss.backward()
optimizer.step()
final_loss = float(loss.item())
if device.type == "cuda":
torch.cuda.synchronize()
with torch.no_grad():
preds = (torch.sigmoid(model(x)) > 0.5).float()
accuracy = float((preds == y).float().mean().item())
metrics = {
"device": torch.cuda.get_device_name(0) if device.type == "cuda" else "cpu",
"epochs": epochs,
"final_loss": round(final_loss, 4),
"train_accuracy": round(accuracy, 4),
"elapsed_sec": round(time.perf_counter() - start, 3),
}
print(json.dumps(metrics))
return metrics
if __name__ == "__main__":
run_tiny_mlp_experiment()
Prompting Claude Code to Provision, Execute, and Clean Up
Give Claude Code explicit instructions to check for existing runtimes first so it does not spin up duplicate VMs:
[!TIP] Copy-Paste Claude Code Prompt: “Use the
colab-mcpserver to calllist_runtimesfirst and reuse an active GPU runtime if present, or callcreate_runtimefor a 16 GB T4 GPU. Open a session, runtrain_mlp_colab.pyviaexecute_code, verify that CUDA is active andtrain_accuracyexceeds 90%, and report the JSON metrics plus anystderrerrors.”
Claude Code executes the tool chain, inspects the returned JSON (final_loss, train_accuracy, elapsed_sec), and fixes any local bug automatically if executionError is non-empty. For teams comparing how different terminal coding agents orchestrate MCP tools, see our Claude Code vs Codex comparison.
Colab MCP vs Google Colab CLI: When Each Tool Fits Better
Google also released the official Google Colab CLI (google-colab-cli), which overlaps with colab-mcp on remote GPU execution but targets a different operational layer. Use Colab MCP for stateful, cell-by-cell agent exploration inside Claude Code (see our Claude Code subscription plans breakdown for rolling pool limits), and use Colab CLI for headless batch scripts, CI/CD jobs, and direct SSH access.
Figure 2: Choose Colab MCP for stateful interactive agent loops in Claude Code, and Colab CLI for ephemeral batch runs, CI/CD, and SSH.
Side-by-Side Comparison: Colab MCP vs Colab CLI
| Criterion | Google Colab MCP (colab-mcp) |
Google Colab CLI (google-colab-cli) |
|---|---|---|
| Primary Interface | Structured JSON-RPC MCP tools (create_runtime, execute_code) |
Shell commands (colab new, colab run, colab exec, colab ssh) |
| Best Execution Pattern | Stateful, iterative cell-by-cell debugging with an AI agent | Ephemeral fire-and-forget jobs (colab run --gpu A100 train.py) |
| Notebook Execution | Agent sends individual Python cells and inspects live kernel state | Executes full local notebooks headlessly (colab exec -f report.ipynb) |
| File & IDE Workflows | Best paired with local repo edits + small code payloads | Built-in colab download, colab drivemount, and colab ssh over WebSockets |
| CI/CD & Cron Automation | Awkward (requires running an MCP client runner) | Native fit for GitHub Actions, cron jobs, and shell scripts |
| Compute Unit Cleanup | Requires remembering to close idle runtimes after agent chat ends | colab run automatically tears down the VM as soon as the script exits |
When the Colab CLI Is Clearly the Better Fit
Switch from colab-mcp to google-colab-cli in three concrete engineering scenarios:
# 1. Provision an A100, run train.py, stream logs, retrieve artifacts, and auto-terminate VM
colab run --gpu A100 train.py
# 2. Execute a local Jupyter notebook headlessly against a remote Colab kernel
colab exec -f eval_suite.ipynb
# 3. Open a WebSocket SSH tunnel for remote IDE debugging or download output checkpoints
colab ssh
colab download /content/checkpoints/best.pt ./local_checkpoints/
- Automated Teardown to Protect Compute Units:
colab runprovisions a VM, streams logs, pulls outputs, and terminates the runtime automatically when the script finishes, eliminating forgotten idle sessions. - Headless Notebook Regression Tests: Running
colab exec -f notebook.ipynbinside CI validates that your research notebooks still run cleanly after library upgrades without involving an LLM agent. - Interactive Terminal & SSH Workflows: If you want a remote TTY (
colab console), directuv-backed package installs (colab install -r requirements.txt), or SSH tunneling into a GPU container, the CLI gives you direct shell control without MCP serialization overhead.
Security Guardrails and Troubleshooting colab-mcp
Connecting a coding agent to remote cloud compute introduces two practical risks: accidentally leaking local credentials into remote notebook cells and silently burning paid Colab Compute Units on forgotten runtimes. Apply basic guardrails before automating heavy loops, aligning with our MCP enterprise security guide.
| Failure Mode | Root Cause | Remediation |
|---|---|---|
uvx times out on first launch |
Cold dependency download exceeds default MCP startup window | Set "timeout": 30000 in .mcp.json or pre-warm with uvx git+https://github.com/googlecolab/colab-mcp --help |
| OAuth login window never opens | Headless SSH environment without local browser forwarding | Authenticate once on a desktop session or forward the localhost OAuth callback port |
| Duplicate GPU runtimes spawned | Agent calls create_runtime on every prompt turn |
Add a rule in CLAUDE.md requiring list_runtimes before create_runtime |
Secret leakage in execute_code |
Agent embeds .env tokens directly inside Python strings |
Keep .env out of agent context and read API keys from Colab Secrets or Drive-isolated configs |
Controlling Runtime Idle Burn and Session Concurrency
Remote A100 and H100 runtimes can burn 6 to 15+ compute units per hour if left attached after an interactive coding session ends. Always add a closing step in your CLAUDE.md workspace rules telling Claude Code to verify active runtimes via list_runtimes before exiting a task.
When running multi-step experiments that download datasets larger than 2 GB, mount Google Drive once or cache archives inside /content so iterative execute_code retries avoid repeated network pulls. Keeping payload sizes compact also keeps execute_code round-trip latency under 2 seconds for fast unit-test loops.
Frequently Asked Questions About Google Colab MCP
How do you install and register Google Colab MCP in Claude Code?
Install uv locally and register colab-mcp in your Claude Code .mcp.json using "command": "uvx" with "args": ["git+https://github.com/googlecolab/colab-mcp"]. On the first tool call, Google opens a browser OAuth prompt to link your Colab account.
Does Google Colab MCP work on a free Google Colab account?
Yes, colab-mcp connects to your standard Google account and can provision available free-tier runtimes subject to Colab’s dynamic usage limits. Paid Colab Pro, Pro+, or Google AI plans unlock higher-tier GPUs like L4, A100, and H100 through the same MCP tools.
What tools does the official googlecolab/colab-mcp server expose?
The server exposes runtime and kernel lifecycle tools including create_runtime, list_runtimes, create_session, and execute_code. Each execute_code call returns structured stdout, stderr, the evaluated result, and executionError details to the agent.
When should you use Google Colab CLI instead of Colab MCP?
Use Google Colab CLI when running headless CI/CD pipelines, cron jobs, SSH IDE sessions, or deterministic one-shot scripts via colab run --gpu A100 train.py. Use Colab MCP when an agent like Claude Code needs interactive, stateful cell-by-cell debugging.
How do you prevent Claude Code from spinning up duplicate Colab runtimes?
Instruct Claude Code to call list_runtimes before calling create_runtime, and reuse an existing session ID across iterative execute_code calls. Reusing the same runtime preserves loaded datasets in VRAM and avoids exhausting concurrent session caps.
Is Google Colab MCP safe to use with sensitive local repositories?
Only code blocks and files explicitly transmitted via execute_code or uploaded to the remote kernel leave your laptop. Never paste raw API keys into notebook cells; store secrets in Colab Secrets or short-lived environment variables and revoke OAuth tokens when finished.
Choosing Your Agentic Colab Workflow
Wire colab-mcp into your .mcp.json today and add a two-line rule in your project’s CLAUDE.md telling Claude Code to check list_runtimes first and shut down runtimes when experiments conclude. That single guardrail prevents accidental quota burn while giving your terminal agent direct access to cloud CUDA hardware.
Keep google-colab-cli installed alongside MCP for the production half of the loop. Prototype and debug models interactively with Claude Code over colab-mcp, then promote finalized training scripts to colab run --gpu A100 train.py for clean, reproducible, auto-terminating batch runs.
Before scaling up to L4, A100, or H100 runtimes across daily agent workflows, compare standalone Compute Unit packs against bundled Google AI Pro and Ultra tiers in our Google Colab pricing and Google AI plans guide.