Pi Agent 源码级教程
M13

扩展入口 —— MCP 连出去,codemode 收进来

11,367 字 · 含 924 行代码 · 约 56 分钟

你接了八个 MCP 服务器。GitHub、Playwright、Postgres、Filesystem、Slack、 Sentry、Notion、一个自己写的内部工具。

每个服务器平均十四个工具。系统提示词里多出一百一十二份工具声明—— 每一份都是一段 JSON Schema、一句描述、几个字段说明。你还没问任何问题, 上下文已经被吃掉一大块;模型从一百一十二个选项里挑一个,准确率反而不如 只给它二十个。

更糟的是调用方式:要读三个文件、grep 一个符号、把那几处改掉,模型得走五轮。 每一轮的代价不是工具执行,而是上下文里多出一整轮历史。

两个包,一共 35 个文件、6,359 行。

包 文件 行数 运行时依赖 exports 入口
packages/mcp 18 3,305 cross-spawn 3 个
packages/codemode 17 3,054 quickjs-wasi 6 个

放在 50,101 行的 chord、33,728 行的 durable 旁边,这是仓库里最小的一对。

但它们是十二个包里唯一朝相反方向做同一件事的两个:一个把外面的能力拉进 Agent,一个把 Agent 的调用压缩成一段代码送出去。上面那两个问题,正好一人一个。

pi-mcp 的名片是一句话:

Standalone Model Context Protocol client for pi and other applications

pi-codemode 的名片也只有一句话,但更锋利:

Sandboxed JavaScript execution where the only capability is calling injected tools

两句话合起来就是这一章:

  • MCP 决定"能力从哪来"——协议、传输、鉴权,都在边界上。
  • codemode 决定"能力怎么用"——把 N 次模型往返换成 1 次脚本执行。

它们不是替代关系。coding-agent 把它们接成了一个连续谱,而且默认档位可能 和你想的相反(§11.1)。

一句结论先放这里:能力从外面进来不是问题,怎么进来、进来之后占多少上下文才是问题。 MCP 那一半解决"协议与信任边界",codemode 那一半解决"一次往返能带多少活"。


零、读这章之前,你需要先知道一件事

OAuth 五步:谁要 token → 给谁 → 换什么 → 存哪 → 何时过期。 它不是"填个 apiKey":应用拿到的是一个有时限的通行证,到期得换。

没有它会怎样:以为 apiKey 和 OAuth token 能互换;接远端 MCP 服务器时 反复 401,却去 auth.json 里找根本不存在的字段。

本书哪里用到:§二.2(199 行,占全章 8.4%,与 MCP 主体无依赖,可跳过)。


一、一次调用最贵的是什么

先不谈协议,看两个数字。

假设模型要做一件事:读三个文件、grep 一个符号、把那几处都改掉。用普通工具 调用,模型至少要走五轮循环: think → call read(a) → result → think → … → call edit → result。

每一轮的代价不是那一次工具执行,而是上下文里多出的四样东西:助手的调用 意图、参数 JSON、工具结果全文、以及下一轮模型必须重新读一遍的完整历史。

codemode 把这个过程压成一轮:

js
const a = await tools.read({ path: "a.ts" });const b = await tools.read({ path: "b.ts" });const hits = await tools.grep({ pattern: "loadConfig" });text(`a: ${a.length} chars, b: ${b.length} chars, hits: ${hits}`);

五轮往返变成一次往返。中间那两个文件的全文从来没进过上下文,只在沙箱的 堆里存在过。

这就是 coding-agent 里 codemode 工具的系统提示词说的那句:

Use codemode to batch independent tool calls (Promise.allSettled), chain them, or filter large output, instead of many separate calls.

(coding-agent/src/extensions/codemode/tool.ts:108-113)

一句话总结两个包的分工:

pi-mcp pi-codemode
解决的问题 能力从哪来 能力怎么用
边界在哪 进程/网络(JSON-RPC 2.0) 同一个 wasm 实例(JS 调用)
谁定义工具 外部 server(tools/list) 宿主注入(CodemodeTool)
一次往返 1 请求 / 1 结果 N 次调用 / 1 条结果
模型看到什么 工具声明 一段脚本 + 一段输出

二、MCP:一次会话的骨架

先对齐一个词:MCP 是什么

如果是第一次听这个词,先读这四段,后面会顺很多。

MCP = Model Context Protocol,一份开放协议,规定"Agent"和"工具服务器" 怎么说话。它不规定模型怎么想,只规定消息长什么样。

三个角色,各在一侧:

角色 在 pi 里是谁 干什么
host coding-agent 决定要连哪些 server
client packages/mcp 一次连接一个 server,管握手、请求、鉴权
server 外部进程或 HTTP 服务 报出自己有哪些工具,被调用时执行

协议上的能力原语有三个:tools、resources、prompts。pi-mcp 只实现了 前两个——client.ts 里有 listTools() 和 listResources(),protocol/types.ts 里也只有这两种的形状。没实现的那一个不影响读代码,但它提醒你:协议比实现大。

消息格式是 JSON-RPC 2.0,传输有 stdio(子进程)和 HTTP 两类,后者又分 streamable 与 SSE。§三 各有一节。

packages/mcp 的结构很干净,四层:

text
mcp/src/├── client.ts          564  会话状态机、请求/通知/响应分发├── protocol/│   ├── jsonrpc.ts      93  JSON-RPC 2.0 的三类消息、五个错误码│   ├── types.ts       113  initialize、tools、resources 的形状│   └── content.ts     106  五种内容块,以及到 LlmContent 的翻译├── transports/│   ├── transport.ts    53  接口 + 监听器簿记│   ├── stdio.ts       201  子进程 + 换行分帧│   ├── streamable-http.ts  479  一个端点两种响应形态│   └── in-memory.ts    43  测试用└── oauth/           1,258  鉴权发现与 PKCE(§五展开)

client.ts 的全部状态只有四个字(client.ts:41): type ClientState = "idle" | "connecting" | "connected" | "closed";

四个状态,四条合法边:idle → connecting(connect)、connecting → connected(initialize 成功)、任意 → closed(close 或传输断开)。 在 connecting 期间只允许发 initialize 和 notifications/initialized, 由 requireTransport(allowConnecting) 这个布尔参数把住(client.ts:458-463)。

2.1 版本协商:服务器说自己的,客户端负责接受

ts
// protocol/types.ts:4-10export const LATEST_PROTOCOL_VERSION = "2025-11-25";/** * Versions the client accepts from a server. Servers that do not support the * requested version answer with their own latest one, so older versions stay * accepted for servers built on older SDKs. */export const SUPPORTED_PROTOCOL_VERSIONS =  [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05"] as const;

这段注释说清了 MCP 的版本规则:不是"客户端要求哪个版本就用哪个",而是 客户端报一个,服务器可以回它自己的最新版。所以客户端要维护一个接受集合, 而不是比对相等。

client.ts:235-237 就是那个检查:

ts
if (!(SUPPORTED_PROTOCOL_VERSIONS as readonly string[])  .includes(result.protocolVersion)) {  throw new Error("MCP server selected unsupported protocol version "    + result.protocolVersion);}

一旦接受,就要把这个版本号回填给传输层(transport.setProtocolVersion?.()), 因为 HTTP 传输每次请求都要带 MCP-Protocol-Version 头(§3.2)。

2.2 双向:客户端也可以是服务端

这是 MCP 和大多数 RPC 协议不一样的地方。看 McpClient 的两个字段:

ts
// client.ts:167-168private requestHandlers = new Map<string, RequestHandler>();private notificationListeners = new Map<string, Set<NotificationListener>>();

pending 是"我发出去等回答的请求",requestHandlers 是"别人发给我、我要 回答的请求"。同一个连接上两个方向同时存在。

构造函数里默认注册了一个:

ts
// client.ts:173-182constructor(options: McpClientOptions) {  this.options = Object.freeze({ ...options });  this.requestHandlers.set("ping", () => ({}));  const roots = options.roots;  if (roots) {    this.requestHandlers.set("roots/list", async () => ({      roots: [...(typeof roots === "function" ? await roots() : roots)],    }));  }}

ping 永远可用;roots/list 只有配了 options.roots 才注册——服务器会问 "你能访问哪些目录",客户端按自己配置的边界回答。这就是服务器侧沙箱的实现 方式:由客户端声明可访问范围,而不是服务器去猜。

收到一个不认识的请求,回 -32601:

ts
// client.ts:495-505const handler = this.requestHandlers.get(message.method);if (!handler) {  await transport    .send({      jsonrpc: "2.0",      id: message.id,      error: {        code: JSON_RPC_ERROR_CODES.methodNotFound,        message: `Method not found: ${message.method}`,      },    })    .catch((error) => this.emitError(error));  return;}

2.3 宽容解析:规范说必须有,现实里常常没有

client.ts 里最值得抄走的是三个校验函数。它们都做同一件事:把"规范要求" 降级成"现实可用"。

ts
// client.ts:105-108(分页游标)// Some servers end pagination with `null` or `""` instead of omitting the// cursor.const nextCursor =  value.nextCursor === null || value.nextCursor === ""    ? undefined    : value.nextCursor;
ts
// client.ts:112-119(资源名)// `name` is required by the spec, but some servers omit it; the URI stands in.const isResource = (resource: Record<string, unknown>) =>  typeof resource.uri === "string" &&  (resource.name === undefined || typeof resource.name === "string");function toResource(item: Record<string, unknown>): Resource {  return { ...item, name: item.name ?? item.uri } as Resource;}
ts
// client.ts:144-153(工具结果)/** * `content` is required by the spec, but servers that only return * `structuredContent` omit it (the SDK defaults it too). */function validateCallToolResult(value: unknown): CallToolResult {  if (    !isObject(value) ||    (value.content !== undefined && !Array.isArray(value.content))  ) {    throw new McpError(      JSON_RPC_ERROR_CODES.invalidRequest, "Invalid MCP tools/call result",    );  }  return (value.content === undefined    ? { ...value, content: [] }    : value) as unknown as CallToolResult;}

三处都选择了补而不是拒。理由很实际:MCP 的服务器生态由几十种语言的 SDK 写出来,规范里的 required 在实现里经常是 optional。客户端如果严格, 失败的不是那个服务器,而是用这个客户端的人。

但宽容有边界。分页那里另外加了两条硬约束(client.ts:364-375):

ts
const cursors = new Set<string>();let cursor: string | undefined;for (let pageNumber = 0; pageNumber < MAX_LIST_PAGES; pageNumber++) {  const page = await this.listPage(method, key, isItem, cursor, options);  items.push(...page.items);  if (page.nextCursor === undefined) return items;  if (cursors.has(page.nextCursor))    throw new Error(      `MCP ${method} returned duplicate cursor: ${page.nextCursor}`,    );  cursors.add(page.nextCursor);  cursor = page.nextCursor;}throw new Error(`MCP ${method} exceeded ${MAX_LIST_PAGES} pages`);

MAX_LIST_PAGES = 1_000。重复游标和超页数都会抛——因为这两种情况意味着 服务器在无限分页,宽容下去就是一个死循环。

2.4 超时、取消、和不许取消的那一个

请求的超时默认 30 秒(client.ts:38): const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;

但真正有意思的是超时和进度的关系。看 armTimeout 被调用的第二处:

ts
// client.ts:536-547private handleProgress(params: unknown): void {  if (!isObject(params) || !isJsonRpcId(params.progressToken)    || typeof params.progress !== "number") return;  const requestId = this.progressRequests.get(params.progressToken);  const entry =    requestId === undefined ? undefined : this.pending.get(requestId);  if (requestId === undefined || !entry) return;  this.armTimeout(requestId, entry);   // 收到进度就重新计时  try {    entry.onProgress?.(params as unknown as ProgressNotification);  } catch (error) {    this.emitError(error);  }}

进度通知会重置超时。否则一个跑了 5 分钟的构建工具,无论如何都会在 30 秒 时被客户端判死——即使它一直在报进度。这把"超时"从"总耗时"改成了"多久没 动静",语义才对。

取消也有例外:

ts
// client.ts:423-432// The spec forbids cancelling `initialize`.onAbort: () =>  this.cancelPending(id, new McpAbortError(), method !== "initialize",    String(options.signal?.reason ?? "Aborted")),sendController: new AbortController(),cancellable: method !== "initialize",

initialize 不可取消,因为取消一个握手中的连接没有明确语义:服务器可能已经 建好了会话,客户端却不知道它的 Mcp-Session-Id。

最后一个细节是 sendController:

ts
// transports/transport.ts:9-16export interface McpTransportSendOptions {  /**   * Aborted once the sender no longer waits for a reply (the request was   * cancelled, timed out, answered, or the client closed). A transport must   * not dispatch the message after that, for example when retrying it after   * an authorization refresh. It does not undo a message already dispatched.   */  signal?: AbortSignal;}

每个待处理请求带一个自己的 AbortController,请求一落定就 abort 它 (client.ts:582)。用途只有一个:HTTP 传输在刷新 token 之后不能重发一个 已经没人等的请求。这是"至多一次"和"至少一次"的边界,写得很克制——注释 最后那句 "It does not undo a message already dispatched" 是在说:我们只能 保证不再发第二次,不能保证第一次没生效。


三、三种传输,一个接口

McpTransport 有七个成员,前六个必须实现,最后一个可选:

ts
// transports/transport.ts:18-26export interface McpTransport {  start(): Promise<void>;  send(    message: JsonRpcMessage, options?: McpTransportSendOptions,  ): Promise<void>;  close(): Promise<void>;  onMessage(listener: McpTransportMessageListener): () => void;  onError(listener: McpTransportErrorListener): () => void;  onClose(listener: McpTransportCloseListener): () => void;  setProtocolVersion?(version: string): void;}

send 收一个 JSON-RPC 消息,三个 on* 注册监听器并返回取消函数,close 关掉。所有"消息怎么变成字节"的差别,全在实现里。

3.1 stdio:换行就是帧

MCP 的 stdio 传输用 NDJSON——一行一个 JSON,没有长度头,没有分帧协议。

ts
// transports/stdio.ts:181-207private handleStdout(chunk: Buffer | string): void {  this.stdoutBuffer = Buffer.concat([this.stdoutBuffer,    Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)]);  const maxMessageBytes =    this.options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES;  while (true) {    const newline = this.stdoutBuffer.indexOf(0x0a);    if (newline < 0) {      if (this.stdoutBuffer.length > maxMessageBytes) {        this.stdoutBuffer = Buffer.alloc(0);        this.emitError(          new Error(`MCP stdio message exceeds ${maxMessageBytes} bytes`),        );      }      return;    }    const line = this.stdoutBuffer.subarray(0, newline);    this.stdoutBuffer = this.stdoutBuffer.subarray(newline + 1);    if (line.length > maxMessageBytes) {      this.emitError(        new Error(`MCP stdio message exceeds ${maxMessageBytes} bytes`),      );      continue;    }    const text = line.toString("utf8").replace(/\r$/, "");    if (!text.trim()) continue;    try {      this.emitMessage(parseJsonRpcMessage(JSON.parse(text)));    } catch (error) {      this.emitError(error);    }  }}

三个容易被忽略的处理:

  1. 缓冲区无上限会 OOM:如果服务器一直不发换行、只发字节,indexOf 永远 返回 -1,stdoutBuffer 会一直长。所以超限就清空并报错——宁可丢一条消息, 也不要吃掉宿主的内存。DEFAULT_MAX_MESSAGE_BYTES = 16 MiB。
  2. \r 要剥:Windows 上的服务器会输出 CRLF(stdio.ts:199)。
  3. 空行要跳过,但要先 trim() 判断——有些服务器在启动时打 banner。

关停是一条三级阶梯(stdio.ts:152-179):

ts
// Shutdown per the spec: close stdin and let the server exit, then SIGTERM,// then SIGKILL.const closeTimeoutMs = this.options.closeTimeoutMs ?? DEFAULT_CLOSE_TIMEOUT_MS;await new Promise<void>((resolve) => {  const timers: ReturnType<typeof setTimeout>[] = [];  child.once("close", () => {    for (const timer of timers) clearTimeout(timer);    // Children of the server that ignored stdin closing would otherwise    // outlive it.    killProcessTree(child, "SIGTERM");    resolve();  });  const grace = Math.min(STDIN_CLOSE_GRACE_MS, closeTimeoutMs);  timers.push(setTimeout(() => killProcessTree(child, "SIGTERM"), grace));  timers.push(setTimeout(    () => killProcessTree(child, "SIGKILL"), grace + closeTimeoutMs,  ));  child.stdin?.end();});

先关 stdin 让服务器自己退(500ms 宽限),然后 SIGTERM,再 2000ms 后 SIGKILL。 而且服务器退出后还要再杀一次进程树——因为 npx、uvx 这类包装器会留下 子进程。

killProcessTree 本身是一段平台差异的教科书(stdio.ts:17-41):

ts
function killProcessTree(child: ChildProcess, signal: NodeJS.Signals): void {  const pid = child.pid;  if (process.platform === "win32" && pid !== undefined) {    if (child.exitCode !== null) return;    // Windows has no graceful signals, and cross-spawn runs `.cmd` shims    // through cmd.exe; killing only that would leave the server running.    spawn(      "taskkill", ["/pid", String(pid), "/T", "/F"],      { stdio: "ignore", windowsHide: true },    ).on("error", () => {});    return;  }  if (USE_PROCESS_GROUPS && pid !== undefined) {    try {      // Negative pid: the whole group, so wrappers like `npx` or `uvx` do not      // leave the server behind.      process.kill(-pid, signal);      return;    } catch {      // The group is gone or was never created; fall back to the direct child.    }  }  try {    child.kill(signal);  } catch {}}

Windows 上没有"优雅信号",只能 taskkill /T /F(/T 是连同子树,/F 是 强制)。POSIX 上则要先试 process.kill(-pid)——负 pid 表示整个进程组, 这要求 spawn 时带 detached: true(stdio.ts:101)。

还有一层兜底:宿主进程如果自己崩了,跑着的服务器会变成孤儿。所以有一个 全局集合加一个退出钩子(stdio.ts:13-53):

ts
/** Process groups of running servers, killed if the host exits early. */const liveProcessGroups = new Set<number>();let exitHookInstalled = false;function installExitHook(): void {  if (exitHookInstalled) return;  exitHookInstalled = true;  process.once("exit", () => {    for (const pid of liveProcessGroups) {      try {        process.kill(-pid, "SIGTERM");      } catch {}    }  });}

3.2 streamable HTTP:一个端点,两种响应

这是 MCP 里最反直觉的一条设计:同一个 POST 端点,可能回 JSON,也可能回 SSE 流。

ts
// transports/streamable-http.ts:231-266async send(  message: JsonRpcMessage, { signal }: McpTransportSendOptions = {},): Promise<void> {  if (!this.started || this.closed) throw new McpConnectionClosedError();  const response = await this.authorizedFetch(    "POST",    {      headers: {        accept: "application/json, text/event-stream",        "content-type": "application/json",      },      body: JSON.stringify(message),    },    signal,  );  await this.checkResponse(response);  this.captureSession(response);  if (!isJsonRpcRequest(message)) {    // Notifications and responses are acknowledged with 202 and carry no    // reply; ignore any body.    await discard(response);    // The server-to-client stream may only open once the session is    // initialized.    const initialized = "method" in message      && message.method === "notifications/initialized";    if (initialized) this.startGetStream();    return;  }  if (response.status === 202 || response.status === 204) {    throw new McpHttpError(      response.status,      `MCP server accepted request ${message.method} without a response`,    );  }  const type = contentType(response);  if (type === "application/json") {    const body: unknown = await response.json();    const items = Array.isArray(body) ? body : [body];    for (const item of items) this.emitMessage(parseJsonRpcMessage(item));    return;  }  if (type === "text/event-stream" && response.body) {    void this.consumeResponseStream(response.body, message.id);    return;  }  await discard(response);  throw new McpHttpError(    response.status,    `Unsupported MCP response content type: ${type ?? "missing"}`,  );}

Accept 头同时列了两种类型,服务器选一个回。三条分支各有其坑:

  • 通知(无 id)回 202、没有 body,直接丢弃。但 notifications/initialized 是个特殊时刻——它是"会话建好了"的信号,服务端到客户端的 GET 流只在这之后 才允许打开(streamable-http.ts:248)。
  • 请求回 202/204 是错误。202 的意思是"我收到了但没结果",对一个请求来说 就是永远不会到来。
  • JSON 响应可能是单个对象,也可能是批处理数组(Array.isArray(body))。

会话 ID 从响应头里捞(streamable-http.ts:334-337):

ts
private captureSession(response: Response): void {  const sessionId = response.headers.get("mcp-session-id");  if (sessionId) this.sessionIdValue = sessionId;}

之后每个请求都带回去(buildHeaders,streamable-http.ts:325-332),同时带 上 MCP-Protocol-Version 和 Authorization。

404 的语义在这个协议里被重载了:

ts
// streamable-http.ts:339-346private async checkResponse(response: Response): Promise<void> {  if (response.ok) return;  // A copy, not a slice: V8 slices keep the whole body alive, and the  // error keeps this excerpt.  const text = await response.text().catch(() => "");  const body = `${text.slice(0, MAX_ERROR_BODY_BYTES)} `.slice(0, -1);  if (response.status === 401) throw new McpAuthRequiredError(response, body);  if (response.status === 404 && this.sessionIdValue)    throw new McpSessionExpiredError(body);  throw new McpHttpError(    response.status, describeHttpFailure(response.status, body), body,  );}

带着会话 ID 收到 404 = 会话已过期(服务器重启或重新部署)。这个错误类型 后面会被 withClient 单独认出来,做一次无副作用的重试(§11.4)。

3.3 SSE:为什么自己写解析器

streamable-http.ts 里有一个 100 行的 SSE 解析器(consumeSseStream)。为什么 不装 eventsource?答案在 pi-mcp 的依赖表里:这个包总共只有 cross-spawn 一个依赖。

手写的状态机只处理四个字段,但每个都有细节:

ts
// streamable-http.ts:67-87const processLine = (rawLine: string) => {  const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;  if (line === "") {    dispatch();    return;  }  if (line.startsWith(":")) return;  const colon = line.indexOf(":");  const field = colon < 0 ? line : line.slice(0, colon);  let value = colon < 0 ? "" : line.slice(colon + 1);  if (value.startsWith(" ")) value = value.slice(1);  if (field === "data") {    dataBytes += Buffer.byteLength(value) + (dataLines.length > 0 ? 1 : 0);    if (dataBytes > maxEventBytes)      throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);    dataLines.push(value);  } else if (field === "event") eventName = value;  else if (field === "id" && !value.includes("\0")) {    eventId = value;    options.onId?.(value);  } else if (field === "retry" && /^\d+$/.test(value)) {    options.onRetry?.(Number(value));  }};
  • 空行是事件边界,不是空事件。
  • : 开头是注释(很多服务器用它做心跳)。
  • 一个事件可以有多行 data:,最后 join("\n")。
  • id 里含 \0 要忽略——SPEC 规定,因为 Last-Event-ID 要放进 HTTP 头。
  • retry 只能是纯数字。

dataBytes 的累加逻辑值得单独看一眼(streamable-http.ts:48-50 的注释):

ts
// Bytes of the pending event's data, including the "\n" joins, so events// streamed as many short `data:` lines without a terminating blank line// cannot grow without bound.

不设上限的话,"一直发 data: 行但永远不空行"就能把宿主的内存吃光。同样, buffered 也有字节上限(streamable-http.ts:100-101)。

3.4 断流续传

服务器可以随意关闭一个响应流。如果它给了事件 ID,客户端就能续上:

ts
// streamable-http.ts:383-421private async consumeResponseStream(  body: ReadableStream<Uint8Array>, requestId: JsonRpcId,): Promise<void> {  const cursor: StreamCursor = {    lastEventId: undefined, retryMs: undefined, received: false,  };  let answered = false;  const onMessage = (message: JsonRpcMessage) => {    if (isJsonRpcResponse(message) && message.id === requestId)      answered = true;  };  let stream: ReadableStream<Uint8Array> | undefined = body;  let failure: unknown;  for (let attempt = 0; ; ) {    if (stream) {      try {        await this.consumeSse(stream, cursor, onMessage);        failure = undefined;      } catch (error) {        failure = error;      }    }    if (answered || this.closed) return;    if (failure !== undefined && !this.isRetryable(failure)) break;    if (cursor.lastEventId === undefined || attempt >= this.maxRetries())      break;    if (cursor.received) attempt = 0;    cursor.received = false;    const delay = this.reconnectDelay(attempt++, cursor.retryMs);    if (!(await this.sleep(delay))) return;    try {      stream = await this.openSseStream(cursor.lastEventId);    } catch (error) {      failure = error;      if (!this.isRetryable(error)) break;      stream = undefined;    }  }  if (this.closed) return;  const reason = failure === undefined    ? "stream ended without a response"    : toError(failure).message;  this.emitMessage({    jsonrpc: "2.0",    id: requestId,    error: {      code: JSON_RPC_ERROR_CODES.internalError,      message: `MCP response stream failed: ${reason}`,    },  });}

这段里有四个决策:

  1. 没拿到事件 ID 就不重连(cursor.lastEventId === undefined)。没有 ID 就无法告诉服务器"从哪继续",重来一次只能得到重复事件或丢失事件。
  2. 收到过事件就重置计数(if (cursor.received) attempt = 0)。一个能持续 吐事件的流,虽然断了,但它是健康的。
  3. 重连用 GET,不是重发 POST。工具调用可能已经执行了,重发就是重复执行。 所以续传是"继续收结果",不是"重做请求"。
  4. 彻底失败时伪造一个 JSON-RPC 错误响应(最后那个 emitMessage),而不是 抛异常。因为 send 早已返回,只有一个假的 error 响应能让等待中的 pending 请求落定。

退避时间优先听服务器的:

ts
// streamable-http.ts:490-494private reconnectDelay(  attempt: number, serverDelayMs: number | undefined,): number {  if (serverDelayMs !== undefined) return serverDelayMs;  const initial = this.options.reconnect?.initialDelayMs    ?? DEFAULT_RECONNECT_INITIAL_DELAY_MS;  return Math.min(initial * 2 ** attempt, this.maxDelay());}

服务器发过 retry: 3000 就用 3000,否则 1s / 2s / 4s / 8s / 16s,上限 30s, 最多 5 次。

isRetryable 有一处 Node 特有的判断(streamable-http.ts:483-488):

ts
private isRetryable(error: unknown): boolean {  if (error instanceof McpHttpError) return isTransientStatus(error.status);  if (error instanceof TypeError) return true;  const code = (error as { code?: unknown } | undefined)?.code;  return typeof code === "string"    && (code.startsWith("E") || code.startsWith("UND_ERR"));}

fetch 把连接中途断开报成一个没有 status 的 TypeError。所以"网络故障" 和"服务器返回 500"要分两条路判断:前者看异常类型,后者看状态码 (408 / 429 / 5xx)。

3.5 一个 Cloudflare 相关的坑

ts
// streamable-http.ts:211-215const fetch = options.fetch ?? globalThis.fetch;// Call fetch without a receiver. `this.fetch(...)` and `context.fetch(...)`// would pass the transport or the auth context as `this`, which Cloudflare// Workers reject for the platform fetch ("Illegal invocation").this.fetch = (input, init) => fetch(input, init);

在 Workers 里,fetch 是一个绑定到全局对象的方法,用错 this 就会抛 "Illegal invocation"。包一层箭头函数是最便宜的解。这类坑不改代码就永远 只在生产环境出现。


四、从 ContentBlock 到 LlmContent

MCP 定义了五种内容块,模型的 API 只认两种。

ts
// protocol/content.ts:63export type ContentBlock =  | TextContent | ImageContent | AudioContent  | ResourceLinkContent | EmbeddedResourceContent;
ts
// protocol/content.ts:73-77/** * Tool result content in the shape LLM APIs accept: text and base64 * images. Matches the `TextContent` and `ImageContent` types of * `@earendil-works/pi-ai`. */export type LlmContent =  | { type: "text"; text: string }  | { type: "image"; data: string; mimeType: string };

翻译函数是一个 switch(protocol/content.ts:79-103):

MCP 块 变成 理由
text 文本 原样
image 图片 原样
audio [audio <mime> omitted] 没有模型接口收音频
resource_link name: uri 链接本身就是一条信息
resource(文本) 文本 内联的资源就是文本
resource(图片) 图片 mimeType 以 image/ 开头
resource(其他二进制) [binary resource <uri> (...) omitted] 同上

toLlmContent 还有一个兜底(protocol/content.ts:105-118):

ts
/** * A result without content blocks but with `structuredContent` becomes its * JSON, since servers should, but do not always, mirror structured results * as text. */export function toLlmContent(  result: Pick<CallToolResult, "content" | "structuredContent">,): LlmContent[] {  const content = (result.content ?? []).map(blockToLlmContent);  if (content.length === 0 && result.structuredContent !== undefined) {    content.push({      type: "text", text: JSON.stringify(result.structuredContent, null, 2),    });  }  return content;}

这里有一个设计判断值得记下来:翻译是有损的,而且是有意有损的。音频块变成 一行占位文本,不是 bug——模型看不见的东西,最好明确告诉它"我没看见",而不是 静默丢掉。占位符里带上 MIME 类型和 URI,模型至少还能知道"这里有个音频"。


五、OAuth:MCP 里最长的一条路

packages/mcp 一共 3,305 行,其中 1,365 行在 src/oauth/ 下——占 41%。

text
mcp/src/oauth/├── flow.ts       486  授权码流程、PKCE、令牌刷新├── discovery.ts  216  四个 well-known 地址的探测├── types.ts      216  元数据、令牌、客户端信息的形状├── provider.ts   169  AuthProvider 的实现骨架├── callback.ts   165  本地回环回调服务器├── index.ts       57  独立入口 `@earendil-works/pi-mcp/oauth`└── errors.ts      56  授权、注册、issuer 不匹配

这一节与 MCP 主体没有依赖:不做远程服务器鉴权,§三 的三种传输照样成立。 只用 stdio 的读者可以从这里直接跳到 §六。三个 RFC 的分工一表看完:

RFC 管什么 书里哪用
9728 资源服务器元数据 §5.1 第一层探测
8414 授权服务器元数据 §5.1 第二层探测
6750 Bearer 令牌与 insufficient_scope §5.2 的 401/403 分流

为什么一个"工具协议"要带这么重的鉴权?因为 MCP 的远程服务器就是普通的 HTTP 服务,而远程 HTTP 服务几乎都要求 OAuth。MCP 规范把这件事标准化了, 客户端不实现就没法连需要登录的服务器。

flow.ts 开头有一段出处声明:

ts
/* * Adapted from modelcontextprotocol/typescript-sdk v1.29.0 src/client/auth.ts. * Copyright (c) 2024 Anthropic, PBC. Licensed under MIT; see LICENSES/. * Modified to remove SDK/Zod dependencies and use WebCrypto for PKCE. */

一句话讲清了取舍:照抄逻辑,重写依赖。官方 SDK 的 auth 模块依赖 zod,而这个包只有一个依赖(cross-spawn)。为了不为了 200 行的校验链 引入一棵依赖树,他们把文件搬过来,校验改成手写的类型判断,PKCE 改用 WebCrypto(flow.ts:165-168):

ts
const bytes = crypto.getRandomValues(new Uint8Array(32));const verifier = Buffer.from(bytes).toString("base64url");const digest = await crypto.subtle.digest(  "SHA-256", new TextEncoder().encode(verifier),);return { verifier, challenge: Buffer.from(digest).toString("base64url") };

32 字节随机 → base64url 的 verifier → SHA-256 → challenge。S256 是唯一 支持的算法,服务器不支持就直接失败(flow.ts:186-188):

ts
if (metadata?.code_challenge_methods_supported  && !metadata.code_challenge_methods_supported.includes("S256")) {  throw new Error("Authorization server does not support PKCE S256");}

这不是苛刻。plain 模式的 PKCE 等于没有 PKCE——verifier 直接出现在授权 请求里,中间人看得见。

5.1 四个地址的探测顺序

MCP 的鉴权发现是两层 RFC 拼起来的:先找资源服务器(RFC 9728),再找 授权服务器(RFC 8414 或 OIDC)。

ts
// discovery.ts:82-96let response = await fetchMetadata(  options.resourceMetadataUrl    ? new URL(options.resourceMetadataUrl)    : new URL(        `/.well-known/oauth-protected-resource${pathSuffix(server.pathname)}`,        server.origin,      ),  ...);// 4xx 或 502 时退回根路径再试一次

拿到资源元数据后,里面会指向 authorization_servers,然后是三条候选:

ts
// discovery.ts:109-116const issuer = new URL(authorizationServerUrl);const path = pathSuffix(issuer.pathname);const urls: { url: URL; type: "oauth" | "oidc" }[] = [  {    url: new URL(      `/.well-known/oauth-authorization-server${path}`, issuer.origin,    ),    type: "oauth",  },  {    url: new URL(      `/.well-known/openid-configuration${path}`, issuer.origin,    ),    type: "oidc",  },];if (path) {  urls.push({    url: new URL(`${path}/.well-known/openid-configuration`, issuer.origin),    type: "oidc",  });}

为什么前两个要插在 origin 和 path 中间、第三个却要拼在后面?因为 RFC 8414 规定前者,而 OIDC 的历史实现常用后者。规范没统一,客户端就得两个都试。

「发现失败」的判定也很讲究:

ts
// discovery.ts:25return (status >= 400 && status < 500) || status === 502;

4xx 是"这个地址没有",502 是"中间网关没配好"——两种都值得换下一个地址。 但 401/403 不在里面(虽然也是 4xx):那是"有,但你没权限",换地址没用。

5.2 401 之后只试一次

传输层把 401(以及带 insufficient_scope 的 403)交给 authProvider, 拿到新凭据后重试一次(streamable-http.ts:295-317):

ts
private async authorizedFetch(  method: "GET" | "POST",  init: { headers: Record<string, string>; body?: string },  signal?: AbortSignal,): Promise<Response> {  const onUnauthorized = this.options.authProvider?.onUnauthorized    ?.bind(this.options.authProvider);  for (let attempt = 0; ; attempt++) {    const { headers, token } = await this.headers(init.headers);    if (signal?.aborted) throw new McpAbortError();    const response = await this.fetch(this.url, {      method, headers, body: init.body, signal: this.controller.signal,    });    if (attempt > 0 || !onUnauthorized || !needsAuthorization(response))      return response;    try {      await onUnauthorized({        response, serverUrl: this.url, fetch: this.fetch, token,      });    } finally {      await discard(response);    }  }}

attempt > 0 就返回,意味着只重试一次。如果刷新过的令牌还是被拒,那 就不是刷新能解决的问题,直接把 401 抛上去(checkResponse 会变成 McpAuthRequiredError)。

needsAuthorization 判断两种状态(streamable-http.ts:165-170):

ts
/** 401, or 403 asking for more scope (step-up authorization). */function needsAuthorization(response: Response): boolean {  if (response.status === 401) return true;  if (response.status !== 403) return false;  return /(?:^|[\s,])error="?insufficient_scope"?/i    .test(response.headers.get("www-authenticate") ?? "");}

403 要读 WWW-Authenticate 头里的 error="insufficient_scope"——这是 RFC 6750 的「权限不够,请申请更大范围」,和「你没登录」是两件事。前者可以 一次变强,后者只能重新登录。

5.3 需要人来的那一刻

OAuth 里有一类问题机器解决不了:用户必须在浏览器里点「同意」。这时 pi-mcp 抛 McpOAuthAuthorizationRequiredError,coding-agent 侧的 McpServerConnection 认出来,把连接置成 needs-auth 并提示用户 (coding-agent/src/extensions/mcp/runtime.ts:317-329):

ts
/** A server that still rejects after a refresh needs a new sign-in. */private needsSignIn(error: unknown): boolean {  return (    error instanceof McpOAuthAuthorizationRequiredError ||    (this.authProvider !== undefined && error instanceof McpAuthRequiredError)  );}private markNeedsAuth(): void {  this.state = "needs-auth";  this.error = undefined;  this.changed();}

然后 /mcp login <server> 打开浏览器,回调走 oauth/callback.ts(本地 回环服务器),oauth.ts 把令牌存进 mcp-auth.json。

这条链有七个文件、一千多行,但只有一处判断真正属于「业务」:能不能 在不问用户的情况下继续。其余全是规范和平台差异。


六、codemode:能力只有一条

现在换一个方向。pi-codemode 的名片值得再读一遍:

Sandboxed JavaScript execution where the only capability is calling injected tools

关键词是 only。脚本不是「能访问很多东西但被限制」,而是「除了调工具, 什么都没有」。

这句话不是宣传,是代码结构。execution.ts 开头写着:

ts
/** * The host owns everything the script must not influence: the tool table, * call records, output, the deadline, the caller's abort signal, and the * decoding of what the VM reports. */

(runtime/execution.ts:4-6)

工具表、调用记录、输出、截止时间、调用方的取消信号、以及VM 上报内容的 解码——六样东西都在宿主这一侧。脚本能做的只有发消息。

6.1 脚本看到的世界

内置 global 就这么多(execution.ts:51-61):

ts
const RESERVED_GLOBALS: ReadonlySet<string> = new Set([  "tools", "ALL_TOOLS", "console", "text", "image", "exit",  "globalThis", "store", "load",]);

九个名字里有四个是输出(text / image / console / exit),两个是 跨调用状态(store / load),两个是工具入口(tools / ALL_TOOLS)。

没有:setTimeout、fetch、process、require、import、Buffer、 文件系统。

没有定时器这件事,比看起来重要得多。它是下面三个设计的根:

  1. 脚本永远不会「自己醒过来」——它只在宿主投递结果时往前走(§7)。
  2. 死锁可判——没有待处理调用时还没结束,就是永远结束了(§9.3)。
  3. 确定性可能——时间只能由宿主推进(§10)。

6.2 沙箱防的不是恶意,是跑飞

一个脚本能做的事被限制到「调工具」,恶意空间几乎为零:它连文件都读不到。 真正的风险是另外两种。

第一种:跑飞。while (true) {} 或者一次算出 3 GB 的值。这不需要恶意, 模型写错一个循环条件就够了。

第二种:状态污染。上一次执行留下的全局变量、改过的内置对象、没关掉的 句柄,影响下一次执行。

两者的解法在 host.ts 的一句注释里:

ts
/** * Each execution gets its own worker thread and QuickJS VM. A fresh worker * per run keeps termination simple: a runaway script, including one that * only spins the microtask queue, is killed with `terminate()` and cannot * poison a later run. */

(runtime/host.ts:12-19)

一次执行一个 VM。不是「一个沙箱复用 VM」,是每次 execute() 新开一个 wasm 实例。代价是启动开销,换来的是:终止就是销毁,隔离不需要靠清理。

6.3 execute 和 start 是两条路

CodemodeSandboxBase 只有两个公开方法(execution.ts:501 和 :530):

execute(code, options) start(code, options)
谁回答工具调用 沙箱自己的工具表 调用方,逐条 deliver()
结果 Promise<CodemodeResult> CodemodeRun(可交互)
时钟 真实时间 虚拟时间,由 now 推进
随机 Math.random 由 seed 决定的 PRNG
默认超时 300,000 ms 无
用途 Agent 调用工具时 宿主要重放一次执行时

execute 是产品功能,start 是可靠性设施。后者的存在理由只有一句: 重启之后能把上一次没跑完的脚本原样再跑一遍(§10)。


七、桥:七个消息,全走 JSON 字符串

宿主和 VM 之间的全部协议在 runtime/protocol.ts,94 行。

ts
// protocol.ts:43-60(VM → 宿主,六种)export type WorkerToHostMessage =  | { type: "call"; id: number; target: "tool" | "global";      name: string; args: string | undefined }  | { type: "output"; item: CodemodeOutputItem }  | { type: "done"; ok: true; value: string | undefined;      writes: string; during?: CodemodeDuring }  | { type: "done"; ok: false; error: ScriptErrorJson;      during?: CodemodeDuring }  | { type: "crash"; message: string }  | { type: "started"; fingerprint: string }  | { type: "idle"; seq: number; issued: number };

反方向只有一种(protocol.ts:62-76):

ts
export type HostToWorkerMessage = {  type: "result";  id: number;  ok: boolean;  payload: string | undefined;  seq?: number;  now?: number;  properties?: string;};

7.1 为什么参数和结果都是字符串

protocol.ts:4-8 的注释:

Messages between the host (main thread) and the worker. Tool arguments, results, and values cross as JSON strings: the worker passes them into and out of the QuickJS VM as strings and never builds structured values itself.

三个理由叠在一起:

  1. 跨越了三个边界:宿主线程 → worker 线程(postMessage)→ wasm 内存 → QuickJS 堆。「结构化克隆」只在第一个边界有效,后面两个都得手动搬运。
  2. 避免二次序列化:如果传对象,worker 要先 JSON.stringify 再塞进 VM;直接传字符串,VM 里的 JSON.parse 就是唯一一次解析。
  3. 桥的失败面变窄:字符串要么是合法 JSON 要么不是,没有「一个字段是 Map」这种中间态。

第 3 点不是理论。看 execution.ts:97-102:

ts
/** * The prelude that serializes values for the host runs in the same VM as the * script, so a script that patches built-ins (for example * `Array.prototype.toJSON`) can make it send malformed data. Payloads that do * not decode throw this error, and the execution fails as a sandbox error. */class BridgeError extends Error {}

脚本和序列化代码在同一个堆里跑。脚本改一下 Array.prototype.toJSON, 所有 JSON.stringify 的输出就都变形了。桥接层不能假设「对面是良性的」, 只能假设「对面可能发出任何字节」然后逐字段校验。

parseStoreWrites 就是这样写的(execution.ts:112-129)——它把一个 JSON 字符串解析成 { set, delete },每个条目都检查是不是数组、第一个元素是不是 字符串、长度是不是 1 或 2。全部检查完才认。

7.2 生命周期:第一条终态消息胜出

execution.ts:11-22 把一次执行的时序写成了三步:

text
1. 构造:装上定时器和 abort 监听,向 launcher 要一条通道。2. 消息:从 VM 来的消息进 message(),工具在这里执行,结果经 post() 回去。   通道还没到之前产生的回复排队,到了再冲。3. 终态:done / crash / launcher 失败 / 到期 / 取消,谁先到谁算。   finish() 取消挂起的工具调用,请求通道停止,等停止完成再落定结果。

「谁先到谁算」在代码里就是一个布尔量:

ts
private finish(  error: CodemodeError | undefined,  value?: unknown,  writes?: CodemodeStoreWrites,  during?: CodemodeDuring,): void {  if (this.finished) return;  this.finished = true;  ...}

(execution.ts:410-417)

if (this.finished) return 是所有竞态的收敛点。到期定时器、abort 监听、 VM 的 done、worker 的 crash——四路并发,都走这一个入口。

落定还有一个顺序要求:

ts
if (!this.channel) {  this.resolveResult(result);  return;}this.channel  .stop()  .catch(() => undefined)  .then(() => this.resolveResult(result));

(execution.ts:440-447)

先停 VM,再落定 Promise。反过来的话,调用方拿到结果就开始下一件事, 而 VM 还在跑——在那个空隙里它可能已经又发起了一次工具调用。

7.3 宿主侧的排队

通道是异步拿到的(launch 返回 Promise),但 VM 可能在拿到通道之前就发消息 了。所以有一个 unsent 队列(execution.ts:192-193),字段注释就是全部说明: private unsent: HostToWorkerMessage[] = [];

发消息的那三行是: if (this.channel) this.channel.post(message); else this.unsent.push(message);

通道到达时一次性冲掉(execution.ts:251-252)。这个队列在 finish() 里 会被清空——终态之后不再需要投递任何东西。


八、三种沙箱,一个接口

CodemodeSandboxBase 是抽象的:它管工具表、默认值、在飞的执行,把「VM 跑 在哪」交给一个函数(execution.ts:82):

ts
export type VmLauncher = (  data: VmStartData, events: VmEvents,) => VmChannel | Promise<VmChannel>;

三个实现,差别只在 launch 传什么。

8.1 CodemodeSandbox:一个执行一个 worker

ts
// host.ts:28-37const interrupt = new SharedArrayBuffer(4);const workerData: WorkerData = { ...data, wasm: module, interrupt };const releaseWorker = options.acquireWorker?.();let worker: Worker;try {  worker = new Worker(options.workerUrl ?? defaultWorkerUrl(), { workerData });} catch (error) {  releaseWorker?.();  throw new Error(`Failed to start worker: ${errorMessage(error)}`);}

SharedArrayBuffer(4) 是一个中断标志。为什么需要它?因为 terminate() 在某些运行时停不住一个卡在 wasm 里自旋的线程:

ts
// host.ts:12-19/** * Before terminating, the host sets a shared interrupt flag that the VM polls, * because Bun's `terminate()` cannot stop a thread that is spinning in wasm. * Stopping requests termination without waiting for exit: some built-ins * do not poll the flag, so on Bun a worker can outlive the script's result. */

所以停止是两步(host.ts:59-66):

ts
const stop = async (): Promise<void> => {  Atomics.store(new Int32Array(interrupt), 0, 1);  // A non-interruptible built-in can delay Bun's terminate() until it  // returns (#10748). Do not hold up the result while that worker exits.  void worker.terminate().catch(() => undefined);  // terminate() refs the worker internally; unref it after requesting  // termination.  worker.unref();};

先竖旗(Atomics.store),再 terminate(),然后 unref() 让进程不必等它。 三步缺一不可:只 terminate 在 Bun 上停不住自旋;只竖旗在 Node 上要等太久; 不 unref 则一条跑飞的脚本能拖住整个进程退出。

这里还有一个 Node 的坑,写在消息监听里(host.ts:39-48):

ts
worker.on("message", (message: unknown) => {  // Node 24/26 --watch leaks dependency reports onto the worker channel  // (nodejs/node#65044).  if (    typeof message === "object" && message !== null &&    ("watch:import" in message || "watch:require" in message)  )    return;  events.message(message);});

node --watch 会把依赖加载报告混进 worker 通道。不挡掉的话,宿主会收到一条 既没有 type 也没有 id 的对象,然后把它当成「桥接破裂」。这类问题的 特点是:只在开发模式下出现,测试和生产都正常。

8.2 InlineCodemodeSandbox:和调用方共享一个线程

给没有 worker 的运行时用——Cloudflare Workers、浏览器。

问题写得很直白(inline.ts:5-9):

QuickJS runs synchronously. While a script computes, the host's event loop does not run, so neither the deadline timer nor an abort signal can fire. On Workers even Date.now() is frozen during synchronous execution.

同步执行的 JS 期间,定时器、abort 信号、甚至 Date.now() 全部停摆。所以 「超时」在这个环境里根本不可用——超时检测器自己也在等待事件循环。

解法是中断预算:不按时间限制,按「被检查的次数」限制。

ts
// inline.ts:77-82shouldInterrupt: () => {  if (stopped || settled || exhausted) return true;  if (++polls <= interruptBudget) return false;  exhausted = true;  return true;},

QuickJS 会周期性地调用这个回调。数到第 interruptBudget 次就返回 true, VM 内部抛一个脚本捕获不到的中断。

默认值和实测速率都写在注释里(inline.ts:16-20):

Measured with a tight loop: about 50,000 per second of CPU on an Apple M-series laptop and about 10,000 per second on Cloudflare Durable Objects (October 2026). The default of 100,000 allows roughly 2 to 10 seconds of uninterrupted computation; keep it well below the platform's own CPU limit, because hitting that limit resets a Durable Object instead of failing one script.

算一下:默认 100,000 次 ÷ 50,000 次/秒 = 2 秒(笔记本),÷ 10,000 次/秒 = 10 秒(Durable Object)。同一份预算,两种机器的实际时长差 5 倍。这就是 为什么它叫「预算」而不叫「超时」——它约束的是计算量,不是时间。

最后那句更关键:必须远低于平台的 CPU 上限。因为撞上平台上限的后果是 整个 Durable Object 被重置,而不是「这一个脚本失败」。一个脚本的错误 变成整个会话的故障。

栈大小也要跟着调(inline.ts:41-42):

ts
/** Allows ~1,000 frames deep and trips before a 1 MB host stack overflows. */export const INLINE_MAX_STACK_SIZE = 256 * 1024;

worker 里用默认的 512 KiB(Node 的 worker 线程有 4 MB 栈),主线程只有 1 MB, 所以压到 256 KiB。QuickJS 的栈保护必须在宿主栈溢出之前触发——否则一个深递归 会直接杀掉进程,而不是抛出可捕获的 RangeError。

8.3 RemoteCodemodeSandbox:VM 在另一个 isolate

Cloudflare 上的正确做法。原因是一个实测数字(remote.ts:5-10):

Measured on Cloudflare (October 2026), a script that computed for 10 seconds delayed the session's other requests by 10 seconds when it ran in the session object or in a Dynamic Worker, but by about 50 ms when it ran in a Durable Object of a separately deployed Worker.

10 秒 vs 50 毫秒,差 200 倍。同样叫「Durable Object」,部署在另一个 Worker 里才有隔离效果——同一个 Worker 里的不同 Durable Object 可能共用一个 isolate,也就是一条线程。

这也是 cloudflare.ts 里那句警告的由来:

ts
/** * Deploy it as its own Worker and bind it from the Worker that runs your agent * with `script_name`. A separate Worker is what keeps scripts off the agent's * thread: a class in the same Worker can share an isolate, and therefore a * thread, with the objects that call it. */

(cloudflare.ts:42-49)

协议是一次 RPC 调用的来回(remote.ts:16-36):

text
client                                remoteexecute(request, exchange) ─────────▶ start VM (in-thread, budget)                           ◀───────── exchange([...outputs, call])  run the tool, reply ──────────────▶ VM continues                           ◀───────── exchange([...outputs, done]) terminalexecute() resolves ◀────────────────── VM disposed

三个设计点值得记住。

输出要攒。exchange 一次带一条调用,但输出可能是几百行,所以远端先攒:

ts
// remote.ts:87-89/** Output buffered on the remote, flushed without waiting for a call. */const FLUSH_ITEMS = 1_000;const FLUSH_CHARS = 1 << 20;

攒到 1,000 条或 1 MB 就主动发一次(remote.ts:158-164)。否则一脚本里 一万次 console.log 就是一万次 RPC。

停止只能靠回话。客户端无法中断一个正在计算的远端 VM:

Termination: the client cannot interrupt a remote VM that is computing. When the client finishes first (deadline, abort, close()), it answers every pending and later exchange with { type: "stop" }, and the remote stops the VM at that point. A script that computes without calling a tool runs until its interrupt budget is used up.

所以远端沙箱的 timeoutMs 对「纯计算脚本」是无效的,真正起作用的是远端的 中断预算。这一点写在类注释里作为已知差异(remote.ts:266-272)。

上限由服务端定,客户端只能要更小:

ts
// remote.ts:109-118(服务端裁剪)const maxBudget = options.maxInterruptBudget ?? DEFAULT_INTERRUPT_BUDGET;const budget = Math.min(request.interruptBudget ?? maxBudget, maxBudget);const memoryLimitBytes = requestedMemory === undefined  ? maxMemory  : maxMemory === undefined    ? requestedMemory    : Math.min(requestedMemory, maxMemory);

客户端要 10 MB 内存,服务端配了 32 MB,给 10 MB;客户端要 1 GB,给 32 MB。 Math.min 两行,把「谁能说要多少」这条边界钉死了。

8.4 三者对照

CodemodeSandbox InlineCodemodeSandbox RemoteCodemodeSandbox
VM 在哪 worker 线程 调用线程 另一个 isolate
依赖 node:worker_threads 只需 WebAssembly 只需 RPC
跑飞怎么停 terminate() + 共享标志 中断预算 中断预算(服务端)
栈上限 512 KiB 256 KiB 256 KiB
阻塞调用方 否 是 否
典型场景 Node / Bun CLI 浏览器、Workers 会话型 Durable Object
入口 pi-codemode pi-codemode/portable pi-codemode/portable

portable.ts 的存在理由只有一句话(portable.ts:1-6):

Sandboxes that need no Node built-ins: InlineCodemodeSandbox runs the VM on the calling thread and RemoteCodemodeSandbox runs it in another isolate. Neither imports node:* modules, so this entry works in Cloudflare Workers, Durable Objects, and browsers. CodemodeSandbox, which uses worker threads, stays in the main entry.

入口即契约:pi-codemode 可以 import "node:worker_threads", pi-codemode/portable 不可以。用打包器的解析规则,把运行时约束变成 模块边界。


九、QuickJS 里抠出来的五个细节

prelude-source.ts 523 行,是整章最不"框架"的一段代码:一段跑在 VM 里的 字符串。它处理的全是"脚本能黑你"这件事。

9.1 lockdown():冻结整个内置图

第一件事是把所有内置对象冻死。理由写在文件头(prelude-source.ts:30-32):

Before anything else the prelude freezes the built-ins and makes the built-in globals read-only. The prelude shares them with the script, so a script that patched one (for example Array.prototype.toJSON) could otherwise corrupt what the prelude reports to the host.

注意这个理由和前文的 BridgeError 是同一件事:序列化代码和脚本在同一个堆。

但直接 Object.freeze 会遇到一个著名的陷阱:

text
// prelude-source.ts:51-57// Freezing alone breaks ordinary code through the "override mistake": a// data property that is read-only on a prototype cannot be assigned on an// instance either, so this.name = "MyError" in an Error subclass would// throw. Commonly overridden properties become accessors whose setter// defines an own property on the instance instead.

翻译一下:Object.prototype.toString 被冻结后,obj.toString = f 也会抛错 ——因为赋值会走原型的只读数据属性。而 class MyError extends Error { constructor() { this.name = "MyError"; } } 这种代码到处都是。

解法是把 7 个"常被覆盖"的属性从数据属性换成存取器:

js
// prelude-source.ts:59-61const OVERRIDABLE = new Set([  "constructor", "name", "message", "toString",  "toLocaleString", "valueOf", "toJSON",]);

存取器的 setter 分两种情况(prelude-source.ts:79-89):

js
set accessor(next) {  if (this === object) {    throw new TypeError(      "Cannot assign to read only property '"        + String(key) + "' of a built-in",    );  }  if (    (typeof this !== "object" || this === null) && typeof this !== "function"  ) return;  Object.defineProperty(this, key, {    value: next, writable: true, enumerable: true, configurable: true,  });}
  • 在原型自己身上赋值:抛错("你不能改内置")。
  • 在实例上赋值:定义成一个自有属性,合法。

一个 freeze 换成一个 defineProperty,语义上就等价于"只能遮蔽,不能修改"。 代价是每个属性多一层存取器,而收益是整个前奏不用再担心原型污染。

9.2 guard():工具名打错时告诉模型正确的名字

脚本要调 tools.readFile,但工具其实叫 read。直接让它抛 undefined is not a function,模型下一轮只能猜。所以 tools 是一个 Proxy:

js
// prelude-source.ts:230-247(节选)const wanted = comparable(property);const exact = names.filter((name) => comparable(name) === wanted);let message = label + "." + property + " does not exist.";if (close.length > 0)  message += " Did you mean " + close.slice(0, 5)    .map((name) => label + "." + name).join(", ") + "?";else if (names.length <= 20) {  message += " Available: " + names.join(", ") + ".";}if (hint) message += " " + hint;message += ' Check for a member with "' + property + '" in ' + label + ".";throw new TypeErrorCtor(message);

实际抛出来是这样一句话:

text
tools.readFile does not exist. Did you mean tools.read, tools.readdir?ALL_TOOLS lists every tool; searchTools(query) finds tools by topic.Check for a member with "readFile" in tools.

四句话,四个作用:错在哪、应该是哪个、去哪找全量、怎么自己确认。这四句 是给模型看的,写得不好就是白浪费一次往返。

comparable 把名字归一化(小写、去掉非字母数字)再比较(prelude-source.ts:229): const comparable = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, "");

所以 read_file、readFile、READ-FILE 会归到同一个键。这对 MCP 工具 尤其重要:服务器名里的 -、_、. 都不能进 JS 标识符,toCodemodeIdentifier 会把它们都换成 _(§11.1)。

9.3 stalled():等一个永远不会来的 promise

没有定时器带来一个副产品:某些"卡住"是可以证明的。

如果脚本在等一个 Promise,而没有任何一个工具调用在飞,那么它永远等不到。 理由很简单:能让它继续的只有两件事——工具结果,或定时器;前一个不存在, 后一个根本没提供。

drain() 每清空一次任务队列就调一次 stalled()(vm.ts:249)。 一句 vm.callFunction(stalled, api).dispose(); 而已。

命中的话,前奏直接结掉这次执行(prelude-source.ts:509-519):

js
stalled() {  if (finished || pending.size > 0) return false;  done(false, stringify({    name: "Error",    message:      "The script is waiting on a promise that can never settle: "      + "no tool call is pending, and timers do not exist here.",  }));  return true;}

这句错误文本本身就是文档:它告诉模型"你以为在等,其实死锁了,而且这里 没有定时器"。比一句干巴巴的 timeout 有用得多。

9.4 image():只收 base64,并且验魔数

image() 拒绝三种输入,每种有自己的理由(prelude-source.ts:403-429):

拒绝什么 错误文本 为什么
http(s):// URL remote image URLs are not supported 工具输出要能存进会话
非 data URI invalid image output 同上
base64 坏了 truncated or corrupted? 提供商会拒整个请求
不是四种格式 not a PNG, JPEG, GIF, or WebP 同上

第一条背后的推理写在注释里(prelude-source.ts:416-418):

Providers reject the whole request on a bad image, and a persisted image block would be resent on every later turn.

一个坏图片不是"这个工具失败",而是后面每一轮请求都失败。所以在写入 之前验,比在发送时验便宜得多。

验魔数的写法有点巧妙:签名是在 base64 空间里做前缀匹配(prelude-source.ts:394-401):

js
// Base64 of the signatures of the formats providers accept inline// (PNG, JPEG except JPEG-LS, GIF, "RIFF....WEBP"). Signatures start at// byte 0, so their encodings are prefixes.const IMAGE_SIGNATURES = [  ["image/png", /^iVBORw0KGg/],  ["image/jpeg", /^[/]9j[/](?!9)/],  ["image/gif", /^R0lGOD[dl]h/],  ["image/webp", /^UklG.{8}RUJQ/],];

iVBORw0KGg 就是 \x89PNG 的 base64。因为签名在字节 0 上,它的 base64 编码就一定是整个 base64 字符串的前缀,所以不用先解码再比对。JPEG 那里的 (?!9) 是在排除 JPEG-LS(\xFF\xD9\xFF 前面的 FF D9 不合法)。

9.5 四道输出上限

ts
// prelude-source.ts:34-43export const MAX_STORE_VALUE_CHARS = 256 * 1024;export const MAX_STORE_TOTAL_CHARS = 1024 * 1024;export const MAX_OUTPUT_CHARS = 16 * 1024 * 1024;export const MAX_OUTPUT_ITEMS = 100_000;

四个数背后是一句注释(prelude-source.ts:37-40):

The host keeps all output until the script ends, so without a limit a script that prints in a loop grows the host's memory until it crashes. The item limit covers loops that print empty strings.

两两成对:

  • 字符数限总量(16 MB),条数限频次(100,000)。只有字符数的话, 一个打十万行空字符串的循环就能把 output 数组撑爆。
  • 单值限 256 KB,总和限 1 MB。只有总和的话,一个 3 MB 的值就能进去。

超限抛的也是 RangeError,并且带着建议(prelude-source.ts:346-350):

js
"script output exceeded the limit of ... text(), image(), and console calls. "+ "Print a summary instead, or write large data to a file with a tool."

"打摘要"和"用工具写文件"——两个具体的下一步。这是同一个原则的第四次出现: 错要错得可行动。


十、确定性重放

start() 这个名字很平淡,但它是两个包中唯一为"会话恢复"服务的机制。

10.1 问题是什么

Agent 在跑一段脚本,中途进程挂了。会话恢复后,这段脚本怎么接着跑?

两条路:

  • 重放工具结果。把已经发生的工具调用结果从日志里读出来,再往里倒。
  • 重跑脚本。让脚本从头再跑一遭,但这次工具调用不真执行,直接给记录的 结果。

第二条简单得多,前提是:脚本在相同输入下必须产生相同输出。而 JS 不是 默认确定的——时间、随机数、时区、GC 都能悄悄改结果。

10.2 四件事被钉死

vm.ts:23-36 把清单列了出来:

不确定性 怎么固定
时间 WASI 时钟读虚拟时间,从 startedAt 开始,只随 now 前进
随机 random_get 改走 seed 的 PRNG,不用真随机
时区 强制 UTC,timezoneOffset: 0
GC 不提供 WeakRef 和 FinalizationRegistry
投递顺序 结果带 seq,严格按序应用,早到的先缓冲

前四项靠 WASI 层和 Intrinsics 完成:

ts
// vm.ts:170-179const vm = await QuickJS.create({  wasm: options.wasm,  memoryLimit: data.memoryLimitBytes,  // Without a guard, deep recursion overflows the wasm stack and traps  // instead of throwing a catchable RangeError.  maxStackSize,  interruptHandler: options.shouldInterrupt,  wasi: clock ? deterministicWasi(clock) : discardOutput,  ...(clock ? {    timezoneOffset: 0, intrinsics: Intrinsics.ALL & ~Intrinsics.WEAK_REF,  } : {}),});

第五项是整章最刺眼的一个细节:

ts
// vm.ts:107-115clock_time_get(  clockId: number, _precision: bigint, resultPtr: number,): number {  let nanoseconds: bigint;  // QuickJS seeds Math.random() from this reading in microseconds and  // turns 0 into 1, so seed s reads s + 1.  if (clock.creating) {    const seeded = BigInt(clock.seed + 1) * 1000n;    nanoseconds = clockId === 0 ? seeded : 0n;  }  else if (clockId === 0) {    nanoseconds = BigInt(Math.round(clock.now)) * 1_000_000n;  }  else {    nanoseconds =      BigInt(Math.round(clock.now - clock.startedAt)) * 1_000_000n;  }  new DataView(memory.buffer).setBigUint64(resultPtr, nanoseconds, true);  return 0;}

Math.random() 的种子是 QuickJS 从第一次读时钟的值里派生的。这意味着 "随机"和"时间"不是两个独立的不确定性,而是一个。所以创建上下文那一段 (clock.creating)必须读一个从 seed 派生的值——否则你发了 seed, 但 Math.random 根本没用它。

注释里还记了一个具体的坑:QuickJS 把微秒读数转成种子时,0 会被当成 1, 所以"种子 s 实际读到 s + 1"。这种偏移不写下来,以后没人能重现。

10.3 为什么结果要编号

因为跨进程传输不保证顺序。RPC 回复可能乱序到达,而脚本的语义要求"第 2 个 结果在第 1 个之后生效"。

ts
// vm.ts:210-223const { seq } = message;if (  seq === undefined || !Number.isInteger(seq)  || seq < nextSeq || early.has(seq)) {  throw new Error(    `Result ${message.id} has sequence number ${seq},`    + ` expected ${nextSeq} or later, once`,  );}early.set(seq, message);for (  let next = early.get(nextSeq);  next !== undefined;  next = early.get(nextSeq)) {  early.delete(nextSeq);  // Never backwards: a resumed host's clock may be behind the one that  // started the run.  if (next.now !== undefined && Number.isFinite(next.now)) {    clock.now = Math.max(clock.now, next.now);  }  current = nextSeq;  apply(next);  post({ type: "idle", seq: nextSeq, issued });  nextSeq++;}

两个约束:seq 不能重、不能回头;clock.now 只能增。后者是因为重放的 宿主时钟可能比原宿主慢——比如原进程在 10:05 挂掉,现在 10:03 重放。 时钟倒退会让脚本里的"耗时"变成负数。

10.4 指纹

重放不能盲目。同一个脚本在不同版本的引擎里可能走不同分支,所以 VM 报一个 指纹(vm.ts:314-321):

ts
const budget = options.interruptBudget ?? "none";post({  type: "started",  fingerprint: `quickjs-wasi ${versions["quickjs-wasi"]},`    + ` quickjs ${versions.quickjs},`    + ` prelude ${PRELUDE_HASH}, deterministic ${DETERMINISTIC_VERSION},`    + ` stack ${maxStackSize},`    + ` heap ${data.memoryLimitBytes ?? "none"}, budget ${budget}`,});

七个成分:两个引擎版本、前奏的 FNV-1a 哈希、确定性协议版本、栈上限、堆上限、 中断预算。最后一个能影响结果——因为预算不同会让不同的脚本在不同点被中断。

DETERMINISTIC_VERSION 的注释把意图说得很清楚(vm.ts:65-69):

Bumped whenever this module or the prelude changes what a deterministic script observes, beyond what the fingerprint's other parts (engine versions, prelude hash, limits) already capture.

它在说:指纹覆盖不到的东西,靠人手动报版本号。这是一个不得不接受的 漏洞,但至少它被写在了代码里。

10.5 during:脚本结束的那一刻在处理什么

确定性运行里有一个只有重放才关心的状态(types.ts:200-204):

ts
/** In a start() run: the result the VM was processing when the script * first run, and the calls issued by then. */export interface CodemodeDuring {  seq: number;  issued: number;}

脚本可能在"处理第 3 个结果"的中途结束(返回、报错、exit())。重放时必须 知道停在哪,否则下一次 deliver 会从错的位置接上。

这个信息藏在 done 里(vm.ts:278-293),因为当宿主收到 done 就会停掉 VM,那次 drain 的 idle 永远不会到达:

ts
case "done": {  // The host stops the VM on `done`, so the `idle` of this drain never  // arrives: report its numbers here.  const during = clock ? { during: { seq: current, issued } } : {};  ...}

一个"消息不会到达"的推理,换成一个字段。


十一、两条入口怎么接在一起

前八节讲的是两个包各自长什么样。现在讲 coding-agent 怎么把它们接起来。

11.1 四档暴露,默认是最省上下文的那档

MCP 服务器的 exposure 有四个值(coding-agent/src/core/mcp-servers.ts:52): export type McpExposure = "codemode" | "deferred" | "direct" | "hidden";

每档的含义,mcp/index.ts:117-121 给了一行定义:

档位 模型看到什么 怎么调
direct 每个工具都是一条普通工具声明 直接调
deferred 不进声明,靠 tool_search 加载 加载后直接调
codemode 不进声明,只能从脚本里调 searchTools() 找,tools.x() 调
hidden 什么都不露 不可调

默认是 codemode(mcp/index.ts:135-137): return entry.config.exposure ?? "codemode";

这个默认值很能说明设计取向。一个装了十个 MCP 服务器的人,如果默认 direct, 系统提示词里立刻多出百十来个工具定义;默认 codemode 则一条也不多——模型 只知道"有这么几个服务器,要用就写脚本"。

而且可以逐工具覆盖(toolExposure)。所以真实的配置可能是: 常用的那几个 direct,剩下几十个 codemode。

11.2 嵌套调用走同一条管道

这是两张图合成一张的地方。codemode 脚本调 tools.x() 时,不是直接调 工具对象,而是穿过 ctx.executeTool(codemode/execute.ts:540): const outcome = await ctx.executeTool(tool.name, args, { signal: callSignal });

tool.ts:7-10 把后果说全了:

Scripts can call the agent loop's nested tools: active direct tools and every codemode or deferred tool. Nested calls run through the agent loop's tool pipeline (ctx.executeTool), so validation, tool_call/tool_result hooks, and permission checks apply exactly as for direct calls. Only the script's output reaches the model; nested results do not.

三句话,三个约束:

  1. 可调的范围:所有 direct(包括内置工具)+ 所有 codemode/deferred 工具。所以脚本里可以 await tools.bash(...)——但只有它自己被声明时。
  2. 同一管道:参数校验、tool_call/tool_result 钩子、权限检查,一条不少。 M05 里那句"否则权限检查就能被套一层工具调用绕过去",在这里被落实了。
  3. 只有脚本输出进模型:嵌套结果全部留在沙箱里。这是整章的性价比所在。

11.3 一条结果里有一棵调用树

既然嵌套调用走管道,它们就会产生 tool_call / tool_result 事件。不加 处理的话,模型会看到"我调了一次 codemode,却产生了七次工具调用"的混乱 历史。

所以结果是嵌套的(codemode/tool.ts:88-106):

ts
/** Tool call id of the nested call, `<codemode call id>/<n>`. */export interface CodemodeNestedCall {  id: string;  name: string;  args: string;  status: CodemodeNestedCallStatus;   // running | ok | error | cancelled  durationMs?: number;  error?: string;  cost?: number;}

id 的形式 "<codemode call id>/<n>" 是关键:它让一个嵌套调用既属于自己 (可单独引用),又属于父调用(可以整树折叠)。

M09 讲上下文压缩时提过一句"codemode 的嵌套调用也要算"。这里能看全: 成本、时长、错误、状态都记在嵌套节点上,但只有父调用的输出进上下文。

11.4 声明也要预算

direct 档也有代价:工具声明本身占 token。所以 codemode 工具的描述也是 有预算的(codemode/tool.ts:136-139):

ts
/** Default for CodemodeDescriptionOptions.inlineBudget, in estimated * tokens. */export const DEFAULT_CODEMODE_INLINE_BUDGET =  SETTINGS_DEFAULTS.codemode.inlineBudget;/** Characters per token when estimating the cost of a tool section. */const CHARS_PER_TOKEN = 4;

默认是 3000,即约 12,000 字符的工具声明。超了就按"最便宜的优先"逐个 淘汰(tool.ts:197-200 的注释叫它 "like OpenCode's catalog"),没进目录的 工具依然可调,只是不再出现在声明里——模型的退路是 searchTools()。

同理,codemode/deferred 档的服务器需要专门告知存在。这就是 mcp_servers 系统提示词段(mcp/index.ts:190-221)。它的预算很硬:

ts
// mcp/index.ts:157-163const MAX_SERVER_DESCRIPTION_CHARS = 250;export const MAX_SERVERS_SECTION_CHARS = 4096;

4096 字符装下所有服务器,每个描述最多 250 字,装不下就截描述,再装不下就 把最后几个服务器折叠成一行"还有 N 个,用 searchTools() 找"。

11.5 一张对比表

现在可以回答开头那个问题了。两个包不是"两个功能",而是一条链的 两段:能力从外面进来(MCP),使用方式被压成脚本(codemode)。

维度 pi-mcp pi-codemode
解决的问题 能力从哪来 能力怎么用
边界 进程 / 网络 同一个 wasm 实例
协议 JSON-RPC 2.0 over stdio/HTTP VM 里的 7 种消息
工具来源 外部 server(tools/list) 宿主注入(CodemodeTool)
谁写调用逻辑 模型(每次一轮) 模型(一次一段脚本)
一次往返 1 请求 / 1 结果 N 调用 / 1 条输出
模型上下文里多出 工具声明 脚本 + 输出
失败面 传输、鉴权、会话过期 脚本错误、超时、桥接破裂
沙箱 无(工具跑在宿主里) QuickJS + 四种限制
能不能组合 不能(每次一个调用) 能(Promise.allSettled、循环、过滤)
运行时依赖 cross-spawn quickjs-wasi

最后一列那两行值得再读一遍:整个扩展生态只靠两个依赖支撑。MCP 那边是 "起一个子进程",codemode 那边是"跑一个 wasm"。两个都是最小的可移植假设。

回到开头那八个服务器:默认 codemode 档位下,一百一十二份声明会变成系统提示词 里的几行,剩下全部沉进脚本里按需取。这不是"性能优化",是让装得起和用得好 不再是一件事。


十二、完整链路

把两个包拼起来,一次"在脚本里调一个 MCP 工具"的完整链路:

text
模型 | |  { name: "codemode", args: { code: "..." } } vcoding-agent 的工具管道(校验 / 钩子 / 权限) | vCodemodeSandbox.execute(source) | +-> Worker 线程 + 一个新 QuickJS wasm 实例 |     | |     +-> 装载 prelude:lockdown() -> tools -> ALL_TOOLS |     +-> run(fn)                   脚本开始,返回一个 Promise | |  script: const issue = await tools.github_issue_read({ number: 42 }) |     | |     +-> caller("call", ...) -> bridge("call", id, name, argsJson) |           | |           v |       postMessage(JSON 字符串) | +-> 宿主线程收到 type: "call"       |       +-> ctx.executeTool(name, args)   与直接调用同一条管道             |             +-> 这个工具来自 MCP? -> McpClient.callTool                   |                   +-> requireTransport().send(...)   四个状态之一                         |  stdio: 一行 JSON 到子进程 stdin                         |  HTTP:  一个 POST,接两种响应                         v                     外部 MCP server                         |                         v                     结果原路回来(ContentBlock[])                   +-> toLlmContent()   五种内容块 -> 两种             |             +-> outcome { ok, value } 或 { ok: false, error }       |       +-> deliver(seq, now, id, outcome)   先序列化再记账             |             v       postMessage({ type: "result", seq, ... }) | vVM 里 settle(id, ok, payload) -> 那个 await 落定 | |  脚本继续:可能又是 N 次 tools.x(),也可能 allSettled 并发 vdone(ok, outputJson)            <- 只有脚本自己的输出 | v模型看到一段文本,一次往返

图上有一条最容易看漏的边:ctx.executeTool 之后的分叉。同一个 tools.x(),目标是内置工具还是 MCP 工具,走的是完全不同的两段代码—— 但校验、钩子、权限在分叉之前就跑完了。这就是 §11.2 那句"同一条管道" 在图上的样子。

还有一条边可以数:从模型到模型,经过了几次序列化。

位置 形式上是什么
模型 -> 工具参数 JSON(模型的 tool call)
宿主 -> VM 的 call JSON 字符串(§7.1)
McpClient.callTool 传输层 JSON-RPC
VM -> 宿主的 result JSON 字符串
脚本输出 -> 模型 字符串(text() 拼出来的)

五次。其中两次是"字符串套 JSON",因为它必须在 VM 的消息通道里过一遍。 这两次序列化换来的是什么:脚本能改的一切都改不了宿主(§7.1 的 BridgeError)。


十三、工程暗坑

1. Math.random 的种子是时钟读数的 +1。 vm.ts:107-115 注释里那句 "so seed s reads s + 1" 不是笔误:QuickJS 把 微秒读数当种子,还会把 0 当成 1。改 deterministicWasi 的返回值必须同步 改种子语义,否则 deterministic.test.ts 会挂在一个看起来无关的地方。

2. 中断有两个入口,不是一个。 interruptHandler: options.shouldInterrupt(vm.ts:170-179)由 QuickJS 在 字节码层调用;vm.ts:247 的 if (++jobs % JOBS_PER_POLL === 0 && ...) 是 宿主 drain 循环的兜底,管的是"脚本在等 promise、什么都不干"的那段时间。 只留一个,另一类跑飞就掐不住。

3. Bun 的 worker.terminate() 停不住在 wasm 里自旋的线程。 所以顺序是先置中断标志,再 terminate(host.ts:60-65):

ts
Atomics.store(new Int32Array(interrupt), 0, 1);// A non-interruptible built-in can delay Bun's terminate() until it// returns (#10748).void worker.terminate().catch(() => undefined);worker.unref();

反过来写,那个线程会一直转到 wasm 自己退出。protocol.ts:35 把这句话 原样又说了一遍,因为它太容易写错。

4. terminate() 之后必须 unref()。 host.ts:64-65 的注释:terminate() 内部会让 worker 保持被引用,不 unref,主进程跑完不退出。这个 bug 的表现是"测试全绿,进程不结束", 很难往沙箱上想。

5. Node 24/26 的 --watch 会污染 worker 的消息通道。 host.ts:40:--watch 把 watch:import / watch:require 混进 worker 的 message 事件(nodejs/node#65044),所以这里必须按形状过滤,而不是 按类型。只在开发模式复现的 bug,靠这段注释才追得回来。

6. guard() 必须放行 then 和 toJSON。 prelude-source.ts:233 那个判断里有三个成员是硬编码的。不放行 then, await tools.read(...) 在等待前会先读一次 tools.then,直接抛 "does not exist"——而用户的代码完全正确。

7. Cloudflare 里 fetch 不能直接当方法用。 streamable-http.ts:213 把 this.fetch 抽成一个包了一层的字段: (input, init) => fetch(input, init)。直接 this.fetch = fetch 会让 this 变成 auth context,Workers 报 "Illegal invocation"。这个错在本地 Node 里 永远不出现。

8. 401 之后的重试不会重发已经发出去的请求。 sendController 在请求落定时 abort(client.ts:582),而 transport.ts:9-16 的注释明说 "It does not undo a message already dispatched"。所以"刷完 token 重试"只对还没发的请求成立。幂等的读能 重试,写不能。

9. 会话过期和鉴权失败是两个错,处理方向相反。 404 + 有 Mcp-Session-Id 是 McpSessionExpiredError (streamable-http.ts:154),解法是换一个新 session 重来;401/403 是去 刷新 token。把它们合并成一个 "unauthorized" 会让两种恢复路径都失效。

10. 同一个 isolate 里的秒级脚本会卡住整个 Durable Object。 实测:10 秒的脚本,和请求共享 isolate 时延迟就是 10 秒;放进独立 Worker 的 DO,只多 50 ms。这是 remote.ts 存在的原因,也是"沙箱要不要独立部署" 这个问题的答案——看你的 CPU 预算愿不愿意和网络共享。

11. 16 MB 的上限是"累计持有",不是"单条"。 MAX_OUTPUT_CHARS 限制的是脚本从开始到结束总共能产出多少,因为宿主一直 留着(prelude-source.ts:37-40)。一条 1 MB 的 text() 不违规,一百条 就违规。

12. stalled() 只在"没有 pending 调用"时成立。 prelude-source.ts:509-510 的第一行是 if (finished || pending.size > 0) return false;。所以脚本等一个永不返回 的工具调用时,这个检测救不了它——那要靠 execute() 的超时(默认 300 秒)。两个机制管两个方向,别指望一个。


十四、自己动手验证

环境:v1.4.0 / node v24.12.0 / Windows 24H2。每条判据都是这一版实跑的输出。

两个包各自 npx vitest --run 就能跑,不需要网络:MCP 的用例走 in-memory 传输,codemode 用本地 wasm。六个实验,都不用改生产代码。

实验 1:看 stdio 的换行分帧

bash
cd packages/mcpnpx vitest --run test/stdio.test.ts

判据:用例里会出现"一次 chunk 里塞两行"和"半个 JSON 卡在缓冲区"两种输入。 把它们和 §3.1 那个 while (true) 循环对着看。

实验 2:看 401 只重试一次

bash
npx vitest --run test/streamable-http.test.ts

判据:数一下 mock server 收到几次请求。第一次 401、onUnauthorized 被调 一次、然后只有一次重试。

实验 3:看五种内容块怎么变成两种

bash
npx vitest --run test/content.test.ts

判据:音频变成 [audio X omitted]、resource_link 变成 name: uri。 这一条决定了 MCP 返回的东西能不能进模型上下文。

实验 4:同一段脚本跑两遍

bash
cd packages/codemodenpx vitest --run test/deterministic.test.ts

判据:两遍的指纹一样、seq 序列一样、输出逐字节一样。把 seed 改一个 数,指纹和 Math.random() 一起变——但其余部分不变。

实验 5:看 worker 能不能被停干净

bash
npx vitest --run test/worker-lifetime.test.ts

判据:跑完之后进程能退出。这一条直接对应 §13 的第 4 条(unref)。

实验 6:自己触发一次死锁检测

在 test/sandbox.test.ts 里加一条用例,脚本体只写一行:

js
await new Promise(() => {});

判据:execute() 立刻返回错误,不是等 300 秒。错误文本里有 "no tool call is pending, and timers do not exist here"(§9.3)。

再补一个反向实验:脚本体换成 await tools.slow(),而这个工具返回一个永不 resolve 的 Promise。这条检测就失效了——你只能等到超时。见 §13 第 12 条。


五句话

如果只记五句:

  1. 沙箱不靠黑名单,靠只给一条能力。 九个全局名,没有 fetch、setTimeout、process。
  2. 一次执行一个 VM。 终止就是销毁,隔离不靠清理。
  3. 桥只有七个消息,全走 JSON 字符串。 串行化代码和脚本在同一个堆,不能信任对面。
  4. 没有定时器,所以死锁可判。 无待处理调用却未结束,就是永远结束。
  5. 远端不阻塞本地,上限由服务端定。 客户端只能要更小,Math.min 两行就够。

本章小结

  1. MCP 管"能力从哪来",codemode 管"能力怎么用"。
  2. 沙箱安全不靠黑名单,靠"只给一条能力":只放 tools 进去。
  3. 三种传输一个接口;五种内容块降成两种再进上下文。
  4. 确定性重放要钉五件事:时间、随机、时区、GC、投递顺序。
  5. 桥只有七个消息,全走 JSON 字符串。

概念回顾

术语 一句话 在哪
MCP 能力提供方,三种传输同一个接口 §二、§三
内容降级 五种 ContentBlock 变两种 LlmContent §四
codemode 脚本执行方,能力只有 tools 一条 §六
桥 七个消息,全走 JSON 字符串 §七
确定性重放 五件事钉死 + 一个指纹 §十

练习

练习 1(读):§十四 实验 6 的反向实验里,await tools.slow() 永不 resolve 时死锁检测失效。为什么"没有待决工具调用"这个判据会漏掉它? → 回 §9.3 与 §十三 第 12 条。

练习 2(改):照 §十四 实验 4 把 seed 改一个数再跑。 预期:指纹与 Math.random() 一起变,其余输出逐字节不变; 回滚:把 seed 改回原值。

常见误区

  1. 你会以为 沙箱靠黑名单挡危险 API;实际是 只给它一条能力; 证据 §6.1。
  2. 你会以为 401 会一直重试;实际是 只重试一次;证据 §十四 实验 2。
  3. 你会以为 五种内容块都能进上下文;实际是 先降成两种;证据 §四。

读完自检

三条,能不能不看稿说出来?

自检 一句话答案 不会就去
两个包的分工一句话说清? MCP 管"能力从哪来",codemode 管"能力怎么用" §一
沙箱的安全性来自哪? 不是黑名单,是"只有一条能力"——只放进去 tools §6.1
要重放,得钉死几件事? 五件:时间、随机、时区、GC、投递顺序,外加一个指纹 §10.2、§10.4

十五、收束

15.1 三个可迁移的方法

一、"能力"和"编排"分开。 MCP 管能力怎么进来,codemode 管能力怎么被组合。两个包各自三千行上下, 因为它们只回答一个问题。写成一个包,就得同时背协议兼容和沙箱语义两套 复杂度。

二、沙箱的安全性来自"只有一条能力",不来自"过滤了很多危险 API"。 codemode 脚本里没有 fetch、没有 process、没有 setTimeout(§6.1)。 它不是把危险的东西挑出来禁掉,而是只放进去一个 tools。前者是一张 永远补不完的黑名单。

三、要重放,就把不确定性一次性钉死,并留指纹。 时间、随机、时区、GC、投递顺序(§10.2),五个一起固定才有意义。固定完 还要报一个指纹(§10.4),因为"固定了"和"固定得一样"是两件事。

15.2 这章的边界

没讲的部分:

  • streamable-http.ts(523 行):只讲了 401、session、续传三条主线。SSE 状态机里 : 注释行、id 含 \0、retry 只认纯数字这些细节留给源码。
  • oauth/flow.ts(486 行):只讲了顺序和 PKCE。RFC 里的 state 校验、 resource 参数、scope 收窄都没展开。
  • declarations.ts(341 行):schemaToType 是一个 JSON Schema 到 TS 类型的迷你编译器,本章只提了它的预算(§11.4)。
  • remote.ts(278 行)的部署侧:Cloudflare Worker 与 Durable Object 的 绑定配置、getByName 的命名。
  • coding-agent/src/extensions/mcp/cli.ts(626 行):命令行子命令。

一个值得记住的数字:两个包 6,359 行,把它们接进 Agent 循环的那一层 17 个文件、5,826 行——差不多一样多。协议是便宜的,把协议变成"模型能用 的东西"是贵的。mcp 里 41% 是 OAuth,codemode 里 68% 是 VM 桥和三个 沙箱实现,这两块恰好都不在"扩展能力"的主线上,但都躲不开。

15.3 下一站

M14 讲 tui:46 文件、19,971 行。那里换一个方向——前面十三章都在讲"怎么 让模型跑起来",M14 讲"怎么让人看见它在跑",以及一次重绘到底要写多少 字节。

下一章:M14 tui——从"让它跑"换到"让人看见它在跑"。


本章源码索引

文件 行数 职责
mcp/src/client.ts 622 会话状态机、双向请求、宽容解析、超时与取消
mcp/src/transports/streamable-http.ts 523 一个端点两种响应、SSE、续传、401
mcp/src/oauth/flow.ts 486 PKCE 与授权码流程(改编自官方 SDK)
mcp/src/transports/stdio.ts 217 换行分帧、三级关停、进程树
mcp/src/oauth/discovery.ts 216 RFC 9728 / RFC 8414 的四个探测地址
mcp/src/oauth/types.ts 216 OAuth 的请求与响应形状
mcp/src/oauth/callback.ts 165 本地回调服务器
mcp/src/protocol/types.ts 132 版本协商、initialize、tools 形状
mcp/src/protocol/content.ts 119 五种 ContentBlock -> 两种 LlmContent
mcp/src/protocol/jsonrpc.ts 114 三类消息、五个错误码
codemode/src/runtime/execution.ts 574 执行生命周期、unsent 队列、终态唯一
codemode/src/runtime/prelude-source.ts 523 跑在 VM 里的前奏:lockdown / guard / output
codemode/src/runtime/vm.ts 342 QuickJS 实例、确定性 WASI、seq 排序
codemode/src/declarations.ts 341 JSON Schema -> TS 类型、声明预算
codemode/src/runtime/remote.ts 278 独立 isolate 沙箱与批量回传
codemode/src/types.ts 255 全部对外类型,含 during
codemode/src/runtime/inline.ts 127 同线程沙箱与中断预算
codemode/src/runtime/protocol.ts 94 七种消息与 Atomics 中断标志
codemode/src/runtime/host.ts 89 worker 生命周期、terminate 与 unref
coding-agent/src/extensions/mcp/index.ts 1,348 四档 exposure 与 mcp_servers 段
coding-agent/src/extensions/codemode/execute.ts 851 CodemodeSandbox 接线与嵌套调用
coding-agent/src/extensions/codemode/tool.ts 435 工具描述、声明预算、嵌套调用树