4 秒起一台 TPU:把 Colab 变成 Claude Code 里的工具调用
AI Summary (BLUF)
本文逐步指导你使用Google Colab API和托管的MCP端点:获取凭证、在Claude Code中注册、测试,并构建一个工具,通过该工具在全新的Colab TPU v5e-1上运行笔记本,完成后删除运行时。
核心洞察
Colab 这次放出的 API 和 MCP 端点,真正有意思的地方在于它把“开一台带 TPU 的机器”这件事变成了一个工具调用。4 秒起一台 v5e-1,跑完 26 个 cell 再删掉,整个过程不需要人盯着浏览器。如果你之前被 Colab 的交互式界面绑住过,这套东西值得花半小时试一下。
这篇文章是一份分步指南,讲怎么用 Google 新的 Colab APIGoogle Colab的REST API(v1beta),用于以编程方式管理Colab运行时。 和托管 MCP 端点:拿到它认的凭证、在 Claude CodeAn AI coding assistant developed by Anthropic that provides code completion and explanations. 里注册、测试、然后做一个工具,通过它在一台全新的 Colab TPU v5e-1Google Cloud的Tensor Processing Unit,用于加速机器学习工作负载。 上跑 notebook,跑完把 runtime 删掉。
代码仓库在 github.com/xbill9/colab。
先看结果:create_runtime 之后 4 秒,一台全新的 Colab TPU v5e-1 就绪;一个 26 个 cell 的 notebook 通过 execute_code 在上面跑完,耗时 901 秒,最后 runtime 被删除。这个 notebook 在 TPU 上跑 Gemma 4 E2B 推理服务。同一个 notebook 走 Colab CLIGoogle Colab的命令行工具,用于登录和获取具有正确作用域的令牌。 跑出来的答案完全一致:
| Gemma 4 E2B 推理 notebook,Colab v5e-1,2026-11-17 | Colab CLI | MCP 端点 |
|---|---|---|
| 第一个 cell 之后几秒,服务和聊天页面就起来了 | 117 | 123 |
| 关闭/开启思考,completion token 数 | 391 / 857 | 391 / 857 |
| 贪心解码,256 token 请求,tok/s | 124.6 | 122.0 |
| 宿主机 CPU 上的 llama.cpp,tok/s | 4.0 | 4.3 |
核心结论
Colab API 将 TPU 环境创建变成工具调用:通过
create_runtime调用,4 秒内即可就绪一台全新的 Colab TPU v5e-1,全程无需人工操作浏览器。MCP 端点与 Colab CLI 执行结果一致:同一个 26 个 cell 的 Gemma 4 E2B 推理 notebook,通过 MCP 端点与 Colab CLI 跑出的答案完全相同,贪心解码 256 token 请求的吞吐分别为 122.0 tok/s 和 124.6 tok/s。
MCP 端点提供 10 个工具:包括
create_runtime、create_session、execute_code、delete_runtime、get_subscription、list_runtime_specs等,覆盖 runtime 生命周期管理与代码执行。认证需要
colaboratoryscope 和 quota project:普通 ADC 登录的 token 缺少所需 scope 会返回 403,需通过 Colab CLI 登录获取,并通过x-goog-user-project头传入已启用 API 的 GCP 项目。免费账号可申请 TPU v5e-1 和 v6e-1 规格:
list_runtime_specs显示免费层级对这两种 TPU 规格均为 eligible,但实际能否开出取决于创建时的空闲容量,无容量时返回FAILED_PRECONDITION。
Colab API 是什么
Google 宣布了 Colab API 和一个托管 MCP 端点,可以从代码里创建、查看、删除 Colab runtime。REST API 是 v1beta,它的 discovery 文档列了六个方法:
rootUrl https://colaboratory.googleapis.com/ version v1beta revision 20261116
scope https://www.googleapis.com/auth/colaboratory - Read, write, and delete your Colab resources
scope https://www.googleapis.com/auth/colaboratory.readonly - Read-only access to your Colab resources
method GET v1beta/{+name} -> v1beta.getSubscription
method GET v1beta/runtimespecs -> runtimespecs.list
method GET v1beta/{+name} -> runtimes.get
method DELETE v1beta/{+name} -> runtimes.delete
method GET v1beta/runtimes -> runtimes.list
method POST v1beta/runtimes -> runtimes.create
ConnectionInfo fields: ['url', 'token', 'expireTime']
一个 runtime 就是一个 Jupyter server。ConnectionInfo 里带着它的 URL 和一个短期代理 token。MCP 端点 https://colaboratory.googleapis.com/mcp 把这些方法包成工具,另外加了 session 管理和代码执行。
开始之前你需要准备
- 一个能访问 Colab 的 Google 账号。
- 一个可以在里面启用 API 的 Google Cloud 项目。
- Python 3,装了
google-auth和requests,另外pip install google-colab-cli用于第 2 步的登录。 - Claude Code,用于第 5、6 步。
第 1 步:列出工具
tools/list 不需要 token 就能返回,所以拿它来快速确认端点通不通最方便:
curl -s -X POST https://colaboratory.googleapis.com/mcp \
-H 'content-type: application/json' -H 'accept: application/json, text/event-stream' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
返回的工具列表:
create_runtime 创建 Colab runtime 并等到就绪。
create_session 在 runtime(runtimes/{runtime_id})上开一个 Jupyter kernel session,返回它的名字(runtimes/{runtime_id}/sessions/{session_id})。
delete_session 关闭 session(runtimes/{runtime_id}/sessions/{session_id}),丢弃 kernel 状态并中止其中正在跑的 execute_code。它写过的文件留在 runtime 上,runtime 继续运行。
execute_code 在 Colab runtime 的 Jupyter kernel 里跑 Python。返回 stdout、stderr、最后一个表达式的值(result)以及异常(executionError)。只返回文本,不返回图片或图表。超过大小限制的输出会被截断并标记 outputTruncated。
get_subscription 获取用户的 Colab 订阅等级:free、Pro 或 Pro+。https://colab.research.google.com/signup 有各等级对比。
list_sessions 列出 runtime(runtimes/{runtime_id})上打开的 session,包括不是你开的,比如用户自己的 notebook。用它找一个自己的 session 来复用或关闭。只关自己开的。它只返回名字,不返回里面在跑什么。
delete_runtime 删除 runtime(runtimes/{runtime_id})以及上面的一切:文件、session 及其状态。不可撤销。
get_runtime 获取 runtime(runtimes/{runtime_id}),包括它的 spec 和 connectionInfo。
list_runtimes 列出用户的 Colab runtime,带 spec 和 connectionInfo。调 create_runtime 之前先在这里看看有没有能复用的。
list_runtime_specs 列出 runtime spec(variant、accelerator、shape)以及用户是否有资格用。调 create_runtime 之前先调它选 spec。
10 tools
这些描述是写给 agent 看的:什么时候复用 runtime、什么时候重试、哪些调用不可撤销,都写清楚了。
第 2 步:拿一个带 colaboratory scope 的 token
每次工具调用都需要一个带 https://www.googleapis.com/auth/colaboratory 的 access token。普通的 gcloud auth application-default login 拿到的 token 没有这个 scope:
token scopes: email https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/sqlservice.login https://www.googleapis.com/auth/userinfo.email openid
403 PERMISSION_DENIED Request had insufficient authentication scopes. ACCESS_TOKEN_SCOPE_INSUFFICIENT
Colab CLI 自己的登录流程会申请这个 scope。登录一次:
pip install google-colab-cli
colab --auth oauth2 sessions
它会把一个可刷新的 token 存到 ~/.config/colab-cli/token.json。tools/colab_token.py 在内存里刷新它并打印一个新的 access token,不会回写文件:
def access_token() -> str:
creds = Credentials.from_authorized_user_file(str(TOKEN_FILE))
if SCOPE not in (creds.scopes or []):
sys.exit(f"{TOKEN_FILE} lacks the {SCOPE} scope; run: colab --auth oauth2 sessions")
creds.refresh(google.auth.transport.requests.Request())
return creds.token
小技巧:调试 403 之前先看 token 的 scope
Google 的 tokeninfo 端点会列出 token 带的 scope,一次调用就能分清是 scope 问题还是权限问题:
curl -s "https://oauth2.googleapis.com/tokeninfo?access_token=$(python3 tools/colab_token.py)"
上一步解决了 scope 的问题,但下一个调用马上又撞上第二道门槛:
ToolError: HTTP 403: {"id":1,"jsonrpc":"2.0","result":{"content":[{"text":"Your application is authenticating by using local Application Default Credentials. The colaboratory.googleapis.com API requires a quota project, which is not set by default...
ADC 认证需要一个 quota project,默认没有。解决办法是在你自己的项目里启用 API,然后把这个项目通过 x-goog-user-project 头传过去:
gcloud services enable colaboratory.googleapis.com --project <your-project>
export COLAB_QUOTA_PROJECT=<your-project>
colab_token.py --header 会把两个头一起打成 JSON:
def headers() -> dict:
"""Authorization plus, when COLAB_QUOTA_PROJECT is set, the quota project the endpoint requires."""
h = {"Authorization": f"Bearer {access_token()}"}
if QUOTA_PROJECT:
h["x-goog-user-project"] = QUOTA_PROJECT
return h
Step 4 — 测一下:你的等级和能开的运行时
tools/colab_mcp.py 是个很小的 JSON-RPC 客户端。make specs 会调 get_subscription 和 list_runtime_specs:
COLAB_QUOTA_PROJECT=<your-project> make specs
输出大概长这样:
subscription: SUBSCRIPTION_TIER_FREE
VARIANT_CPU NONE SHAPE_HIGHMEM not eligible
VARIANT_CPU NONE SHAPE_STANDARD eligible
VARIANT_GPU A100 SHAPE_HIGHMEM not eligible
VARIANT_GPU T4 SHAPE_HIGHMEM not eligible
VARIANT_GPU A100 SHAPE_STANDARD eligible
VARIANT_GPU G4 SHAPE_STANDARD eligible
VARIANT_GPU H100 SHAPE_STANDARD not eligible
VARIANT_GPU L4 SHAPE_STANDARD eligible
VARIANT_GPU T4 SHAPE_STANDARD eligible
VARIANT_TPU V5E1 SHAPE_STANDARD eligible
VARIANT_TPU V6E1 SHAPE_STANDARD eligible
eligible 只代表你的账号有资格申请这个规格。真正能不能开出来,得看 create_runtime 那一刻有没有空闲容量,没有的话它直接返回 FAILED_PRECONDITION。
Step 5 — 在 Claude Code 里注册端点
Claude Code 连远程 MCP 服务器时,内置的 OAuth 流程会临时注册一个客户端,Google 的授权服务器不支持这个:
plugin:google-cloud-developer:developer-knowledge: https://developerknowledge.googleapis.com/mcp (HTTP) - ✘ Failed to connect — Incompatible auth server: does not support dynamic client registration
用 headersHelper 绕过去。Claude Code 在连接时执行一条命令,把它打印出来的 JSON 当作请求头发出去。colab_token.py --header 就是这条命令:
claude mcp add-json colab --scope user '{"type": "http",
"url": "https://colaboratory.googleapis.com/mcp",
"headersHelper": "COLAB_QUOTA_PROJECT=<your-project> python3 /path/to/colab/tools/colab_token.py --header",
"timeout": 700000}'
claude mcp get colab
连上之后是这样:
colab:
Scope: User config (available in all your projects)
Status: ✔ Connected
Type: http
URL: https://colaboratory.googleapis.com/mcp
Timeout: 700000ms
工具描述里说 execute_code 一次调用最多挂 600 秒,所以 timeout 设得比它大。实测的上限在 Step 8 的提示里。
Step 6 — 问问 Claude Code
新开一个会话就能看到这些工具了。只放开只读工具试一下:
claude -p "Using the colab MCP server, tell me my Colab subscription tier and which TPU runtime specs I am eligible for. Call the tools; do not guess." \
--allowedTools mcp__colab__get_subscription mcp__colab__list_runtime_specs mcp__colab__list_runtimes
回答:
**Subscription tier:** Free (`SUBSCRIPTION_TIER_FREE`).
**TPU runtime specs:** the list has two, and you're eligible for both.
| Variant | Accelerator | Shape | Eligible |
|---|---|---|---|
| TPU | V5E1 (v5e, 1 chip) | Standard | ✅ |
| TPU | V6E1 (v6e, 1 chip) | Standard | ✅ |
create_runtime、execute_code、delete_runtime 都没放进 --allowedTools,所以 Claude Code 在花算力或者删东西之前会先问你。
Step 7 — 写一个扛得住长调用的客户端
端点返回一个调用时,可能是普通 JSON,也可能是一个 server-sent event 流。客户端要读最后一个带 result 的 data 事件:
流式响应这块还有个细节要处理。有些调用返回的不是普通 JSON,而是 text/event-stream,得逐行解析,最后一个 data 事件才带着结果:
if r.headers.get("content-type", "").startswith("text/event-stream"):
for line in r.text.splitlines(): # the last data event carries the result
if line.startswith("data:"):
event = json.loads(line[5:])
if "result" in event or "error" in event:
msg = event
接下来是两个工具的重连语义。create_runtime 带同一个 requestId、execute_code 带同一个 session 和 executionId,在遇到 DEADLINE_EXCEEDED 或 UNAVAILABLE 时重复完全相同的调用。注意是重连,不是重做。客户端只在这两种情况下重试:
REATTACH = ("DEADLINE_EXCEEDED", "UNAVAILABLE")
def call_reattaching(self, name: str, arguments: dict, attempts: int = 20) -> dict:
"""Repeat an identical call while the endpoint says the work is still in progress."""
for attempt in range(1, attempts + 1):
try:
return self.call(name, arguments)
except ToolError as e:
if not e.reattach or attempt == attempts:
raise
Step 8 — 构建:在全新的 v5e-1 上跑一个 Notebook
tools/run_on_colab.py 通过端点跑 notebook:挑一个合规的 spec,创建 runtime,开一个 session,把每个代码单元发给 execute_code,记录输出,最后在 finally 里删掉 runtime:
runtime = mcp.call_reattaching("create_runtime", {"requestId": str(uuid.uuid4()), "runtime": {"runtimeSpec": key}})
name = runtime["name"]
try:
session = mcp.call("create_session", {"parent": name, "sessionId": "verify"})["name"]
for cell in cells:
res = mcp.call_reattaching(
"execute_code", {"session": session, "code": cell.source, "executionId": str(uuid.uuid4())}
)
cell.outputs = outputs_of(res)
finally:
mcp.call("delete_runtime", {"name": name, "allowMissing": True})
这个 notebook 就是同一个仓库里的 Gemma 4 E2B 推理演示:6.56 GB 的下载、JAX 引擎、OpenAI 兼容服务、若干样例,外加一个 llama.cpp 的对比。make verify 负责跑它:
COLAB_QUOTA_PROJECT=<your-project> make verify
=== gemma4_e2b_serving_v5e1 on {'accelerator': 'V5E1', 'shape': 'SHAPE_STANDARD', 'variant': 'VARIANT_TPU'} ===
runtime runtimes/r-508e423c-84f3-4398-9cc3-44216293a093 ready in 4 s
[1/26] # Cell 1.1: start the checkpoint download in the background
1 s
[4/26] # Cell 2.1: the engine, pinned, and the checkpoint on the chip
85 s
[9/26] # Cell 3.1: the client and the measuring helper
177 s
[17/26] # Cell 3.9: first-token time against prompt length
159 s
[23/26] # Cell 5.3: thinking on (about four minutes at CPU speed)
211 s
[26/26] # Cell 7.1: stop the servers and free the chip
2 s
runtime runtimes/r-508e423c-84f3-4398-9cc3-44216293a093 deleted
total 901 s from create_runtime to delete_runtime
OK: gemma4_e2b_serving_v5e1 ran clean on v5e1 -> runs/2026-11-17/gemma4_e2b_serving_v5e1_mcp_output.ipynb
上面摘的是耗时最长的几个单元,完整日志在仓库的 evidence 目录里。执行完的 notebook 会把每个单元的 stdout、stderr 和错误写回去,再扫一遍有没有报错和意外的 stderr。
提示:每个单元控制在 300 秒以内
execute_code 的描述里写的是 600 秒截止,超时后代码继续跑,相同的调用会重连上去。实际在 CPU runtime 上从这个客户端测,一个每 30 秒打一行的调用:
COLAB_QUOTA_PROJECT=<your-project> python3 tools/check_long_call.py 420
call 1: stream dropped after 300 s (ChunkedEncodingError)
call 2: returned after 2 s
stdout: ['30', 's', '60', 's', '90', 's', '120', 's', '150', 's', '180', 's', '210', 's', '240', 's', '270', 's', '300', 's']
result: None error: KeyboardInterrupt
流在 300 秒时断了,kernel 也在那一刻被中断,重连拿回来的是中断后的结果。通过端点驱动的 notebook,每个单元都得在 300 秒内跑完。演示 notebook 里那个 CPU 对比拆成三个单元就是这个原因,最长的一个大约四分钟。单元撞上限制时,run_on_colab.py 会把原因标出来。
提示:一个 session 承载 notebook 的状态
(下一节继续)
同一个 session 下每次 execute_code 调用共用一个 kernel,所以前一个 cell 里的变量、import 和后台线程,下一个 cell 直接就能用,跟 Colab 自己的 notebook 视图一样。某个 cell 在 thread 里起的服务,调用结束后还在跑,后面的 cell 通过 127.0.0.1 就能访问到。输出只回文本:如果 cell 显示的是 HTML,比如 notebook 里的聊天页面,那这部分什么都不会返回。
Step 9 — 清理
delete_runtime 放在 finally 里执行,所以从创建到销毁之间就算抛异常或者按了 Ctrl-C,芯片照样会被释放。用 list_runtimes 确认一下:
COLAB_QUOTA_PROJECT=<your-project> python3 tools/colab_mcp.py call list_runtimes
<svg xmlns="http://www.w3.org/2000/svg" width="20px" height="20px" viewBox="0 0 24 24"><title>Exit fullscreen mode</title>
<path d="M18 7h4v2h-6V3h2v4zM8 9H2V7h4V3h2v6zm10 8v4h-2v-6h6v2h-4zM8 15v6H6v-4H2v-2h6z"></path>
{}
<svg xmlns="http://www.w3.org/2000/svg" width="20px" height="20px" viewBox="0 0 24 24"><title>Exit fullscreen mode</title>
<path d="M18 7h4v2h-6V3h2v4zM8 9H2V7h4V3h2v6zm10 8v4h-2v-6h6v2h-4zM8 15v6H6v-4H2v-2h6z"></path>
返回空对象,说明这个账号名下已经没有 runtime 了。
对比一下
Colab CLI(colab exec) |
Colab MCP endpoint | |
|---|---|---|
| 跑 notebook | 整个文件,一条命令 | 一个 cell 一次 execute_code |
| 长 cell | 按 cell 设 --timeout
|
每次调用 300 秒,实测的;更长的 cell 得拆开 |
| 认证 | CLI 登录或 ADC | 带 colaboratory scope 的 token 加一个 quota project |
| 能找到你名下所有 runtime | 只能找到它自己创建的 session |
list_runtimes 🥇 |
| agent 能直接调 | 得通过 shell | 本身就是 MCP 工具 🥇 |
那到底用哪个
给 agent 用,就走 MCP endpoint:工具描述本来就是写给 agent 看的,起一个 runtime 就一次调用的事,而且 list_runtimes 和 delete_runtime 能触达账号下所有 runtime。
如果只是写个一次性脚本跑完整个 notebook 文件,Colab CLI 一条命令就够了。另外 CLI 登录也是拿到 colaboratory scope token 最快的路子。
总结
这篇文章的目标是搭好 Google 的 Colab MCP endpoint,从 Claude Code 里测通,再做一个工具通过它在托管的 TPU 上跑 notebook。方案的关键有三样:从 Colab CLI 登录拿到的带 colaboratory scope 的 token、一个启用了 API 的 quota project,以及一个把这两样交给 Claude Code 的 headersHelper。结果如下:
- 🟢
tools/list不带 token 也能应答;但每次工具调用都需要colaboratoryscope 和 quota project - 🟢 Colab CLI 登录能提供这个 scope,
headersHelper把 token 递给 Claude Code - 🟢 Claude Code 从一句大白话 prompt 里就能列出 tier 和可选的 TPU 规格
- 🟢
create_runtime之后 4 秒,v5e-1 就绪 - 🟢 一个 26 个 cell 的 Gemma 4 notebook 通过
execute_code跑完,用了 901 秒,答案和 Colab CLI 跑出来的一致 - 🟢
delete_runtime放在finally里,没留下任何 runtime - ⚠️
execute_code的流在 300 秒时关闭并打断 kernel,所以 cell 必须控制在这个时间内 - ⚠️
execute_code只回文本;HTML 输出比如聊天页面拿不回来 - ❌
gcloud auth application-default login拿到的 token 因为缺 scope 被拒
范围说明:一个 Google 账号,免费 tier,quota project 在一个 Google Cloud 项目里,Claude Code 2.1.326,Colab API v1beta revision 20261116,2026-11-17 当天通过 endpoint 跑了一次 notebook、通过 Colab CLI 跑了一次,300 秒的测量是在一个 CPU runtime 上做的。runtime 容量和 endpoint 的速率限制没有测。
用 MCP 操作托管 Colab runtime 这套思路,是通过一步步增量验证走通的。
参考
- 仓库:https://github.com/xbill9/colab
- 公告:https://medium.com/google-colab/the-google-colab-api-and-mcp-endpoint-for-developers-and-agents-65cfef497056
- MCP 参考:https://developers.google.com/colab/api/reference/mcp
- REST 参考:https://developers.google.com/colab/api/reference/rest
- Colab CLI:https://github.com/googlecolab/google-colab-cli
- 跑的那个 notebook:https://github.com/xbill9/colab/blob/main/notebooks/gemma4_e2b_advanced_v5e1.ipynb
常见问题(FAQ)
Colab API 和 MCP 端点能用来做什么?
可以在代码里创建、查看、删除 Colab runtime,把开一台带 TPU 的机器变成一次工具调用。4 秒起一台 v5e-1,跑完 notebook 再删掉,全程无需盯着浏览器。
调用 Colab MCP 端点需要什么凭证?
每次工具调用都需要一个带 colaboratory scope 的 access token。普通的 gcloud auth application-default login 拿到的 token 没有这个 scope,会报 403 ACCESS_TOKEN_SCOPE_INSUFFICIENT,调试前先看 token 的 scope。
Colab MCP 端点提供哪些工具?
共 10 个工具,包括 create_runtime、create_session、execute_code、delete_session、delete_runtime、get_runtime、list_runtimes、list_runtime_specs、get_subscription、list_sessions,描述里写清了何时复用 runtime、哪些调用不可撤销。
版权与免责声明:本文仅用于信息分享与交流,不构成任何形式的法律、投资、医疗或其他专业建议,也不构成对任何结果的承诺或保证。
文中提及的商标、品牌、Logo、产品名称及相关图片/素材,其权利归各自合法权利人所有。本站内容可能基于公开资料整理,亦可能使用 AI 辅助生成或润色;我们尽力确保准确与合规,但不保证完整性、时效性与适用性,请读者自行甄别并以官方信息为准。
若本文内容或素材涉嫌侵权、隐私不当或存在错误,请相关权利人/当事人联系本站,我们将及时核实并采取删除、修正或下架等处理措施。也请勿在评论或联系信息中提交身份证号、手机号、住址等个人敏感信息。




