MCP、Codemode、Tool Search、虚拟模型、自定义 Provider 与 Pi 包安装分发。
难度:★★★★★ | 前置:03、04、05、06 | 本篇覆盖 0.99 起引入的主要新特性(0.99.0,2026-09-29:Codemode 与 MCP、虚拟模型、分类器模型),并根据 1.x 的后续变化更新。
1. MCP(Model Context Protocol)
Pi 通过 stdio 或 streamable HTTP 连接 MCP 服务器,把其工具和资源提供给模型。(不支持旧的 SSE 传输;文档提示,很多提供 SSE 端点的服务也提供 streamable HTTP,通常在 /mcp 而非 /sse。)
1.1 快速配置(官方)
# 本地 stdio 服务器
pi mcp add filesystem -- npx -y @modelcontextprotocol/server-filesystem .
pi mcp list
pi
# 远程 HTTP 服务器
pi mcp add docs --url https://example.com/mcp --bearer-token-env-var DOCS_TOKEN
pi mcp list
# 写入项目配置(.pi/mcp.json)
pi mcp add -l tools --env API_KEY='${TOOLS_KEY}' -- uvx tools-mcp
交互中用 /mcp 查看连接、登录、重连、修改暴露方式、启停服务器;在会话外修改配置后运行 /reload。
1.2 mcp.json 格式
用户级 ~/.pi/agent/mcp.json,项目级 .pi/mcp.json(需项目信任;同名条目会替换用户级条目)。格式与其他 MCP 客户端一致:
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "."]
},
"docs": {
"url": "https://example.com/mcp",
"headers": { "Authorization": "Bearer ${DOCS_TOKEN}" },
"description": "Search and read the product documentation"
}
}
}
配置规则:
- stdio:
command、args、env、cwd;command是 单个可执行文件,不是 shell 字符串; - HTTP:
url、headers、oauth; - 通用:
timeout(秒,默认 60)、enabled: false、exposure、toolExposure、description; env/headers值可用${GITHUB_TOKEN},也可用整值!command,例如"Authorization": "!echo Bearer $(gh auth token)";- 工具命名为
mcp__<server>__<tool>; - 项目条目只写
enabled/exposure/toolExposure时,仅覆盖用户级同名服务器的这些字段,例如在某项目中禁用:
{ "mcpServers": { "internal-tools": { "enabled": false } } }
迁移:Claude Desktop / Claude Code / Cursor 的 mcpServers 条目可以直接复制;VS Code、Codex、OpenCode 需按官方表格转换字段。
1.3 OAuth 认证
使用 OAuth 的远程服务器(如 Sentry)在 mcp.json 中 无需写凭据:
{ "mcpServers": { "sentry": { "url": "https://mcp.sentry.dev/mcp" } } }
服务器拒绝未认证连接时,/mcp 显示需要登录;选 "Sign in"、运行 /mcp login sentry 或 pi mcp login sentry。令牌保存在 ~/.pi/agent/mcp-auth.json 并自动刷新。对不支持动态注册的服务器可配置 oauth.clientId/clientSecret/callbackPort;还有 clientName、scope、clientRegistration: "cimd"、authServerMetadataUrl 等选项(1.0 加强)。
1.4 工具暴露方式(exposure)—— 最关键的概念
codemode(默认)- 行为
- 可被 codemode 脚本调用,但 不声明给模型,也不列在 codemode 描述中;脚本用
searchTools()/describeTool()/ALL_TOOLS查找 - 典型用途
- 一般 MCP 服务器,尤其需要组合或过滤调用时
deferred- 行为
- 直到
tool_search为下一次调用加载匹配项前不声明 - 典型用途
- 工具很多、但希望发现后直接调用的服务器
direct- 行为
- 像内置工具一样声明给模型,也可从 codemode 调用
- 典型用途
- 小而常用的工具集
hidden- 行为
- 注册但不可达
- 典型用途
- 应保持不可用的工具
| exposure | 行为 | 典型用途 |
|---|---|---|
codemode(默认) | 可被 codemode 脚本调用,但 不声明给模型,也不列在 codemode 描述中;脚本用 searchTools()/describeTool()/ALL_TOOLS 查找 | 一般 MCP 服务器,尤其需要组合或过滤调用时 |
deferred | 直到 tool_search 为下一次调用加载匹配项前不声明 | 工具很多、但希望发现后直接调用的服务器 |
direct | 像内置工具一样声明给模型,也可从 codemode 调用 | 小而常用的工具集 |
hidden | 注册但不可达 | 应保持不可用的工具 |
- 有
codemode暴露的服务器连接时,Pi 自动激活codemode;有deferred时自动激活tool_search(可用"autoEnableCodemode": false关闭自动激活); toolExposure可按工具覆盖(精确名优先,模式中首个匹配生效):
{
"mcpServers": {
"github": {
"url": "https://api.githubcopilot.com/mcp/",
"exposure": "deferred",
"toolExposure": {
"search_code": "direct",
"get_*": "codemode",
"delete_*": "hidden"
}
}
}
}
- 超过 20 KB 的文本结果在给模型时会截去中间部分,完整文本存入临时文件;codemode 脚本则拿到完整结果,可以先过滤再输出;
- 服务器提供资源时,Pi 添加
list_mcp_resources、list_mcp_resource_templates、read_mcp_resource三个工具。
0.99.2 变化:默认
codemode暴露的服务器不再列在 codemode 描述中、也不再阻塞第一次提示;它们出现在系统提示的简短mcp_servers段落中。codemode-deferred成为codemode的别名。
1.5 权限与扩展
- 每个 MCP 调用都经过 Pi 的工具管道,所以
tool_call/tool_result处理器(包括权限门禁)同样适用;codemode 脚本中的调用带parentToolCallId; pi.getAllTools()报告服务器声明的readOnlyHint/destructiveHint等注解,可据此决定是否确认(见 05 扩展开发 的 annotations 示例);- 扩展可用
pi.registerMcpServer(name, config)为当前会话添加服务器(不持久化,每次加载需重新注册):
pi.registerMcpServer("jira", { url: "https://mcp.example.com/jira", exposure: "codemode" });
pi.unregisterMcpServer("jira");
- 安装注册了
/mcp的扩展(如pi-mcp-adapter)会替换内置 MCP 支持;禁用内置 MCP:"extensions": ["-builtin:mcp"]或单次--no-mcp。
2. Codemode
2.1 是什么
codemode 工具让模型 编写一段 JavaScript 脚本,在脚本里调用 Pi 的其他工具,并运行非 LLM 模型(分类器、图像模型)。只有脚本的输出会进入模型上下文,因此脚本可以 并行 调用工具、在模型看到之前 过滤大结果。
2.2 启用
{ "defaultTools": ["+codemode"] }
或单次:`pi --tools +codemode`。不需要 MCP 也很有用。
2.3 脚本运行环境
- 输入是 原始 JS 源码(不是 JSON,也不是 markdown 代码块),作为 async 函数体运行在 QuickJS 沙箱 中,支持顶层
await和return; - 沙箱 没有 Node API、文件系统、网络、定时器——只能通过 tools 和
models与外界交互; - 第一行可写选项:
// @options: {"max_output_tokens": 2000, "timeout_ms": 60000}
`max_output_tokens` 默认 10000;`timeout_ms` 默认不设。
2.4 全局对象
tools.<name>(args)- 作用
- 调用工具
text(value)- 作用
- 添加文本输出
image(value)- 作用
- 添加图片输出
console.log(...)- 作用
- 写入
<console_output>块
return value- 作用
- 等同
text()
exit()- 作用
- 成功结束
store(key, value)/load(key)- 作用
- 在多次 codemode 调用间保存小 JSON 值(随会话分支持久化)
ALL_TOOLS- 作用
- 所有可调用工具
{ name, description }
searchTools(query, { limit?, namespace? })- 作用
- BM25 排序搜索工具(默认 8 个)
describeTool(name)- 作用
- 工具描述和 TypeScript 声明
describeNamespace(name)- 作用
- 命名空间(如 MCP 服务器)的描述、说明和工具名
models- 作用
- 列出并运行非 LLM 模型
| 全局 | 作用 |
|---|---|
tools.<name>(args) | 调用工具 |
text(value) | 添加文本输出 |
image(value) | 添加图片输出 |
console.log(...) | 写入 <console_output> 块 |
return value | 等同 text() |
exit() | 成功结束 |
store(key, value) / load(key) | 在多次 codemode 调用间保存小 JSON 值(随会话分支持久化) |
ALL_TOOLS | 所有可调用工具 { name, description } |
searchTools(query, { limit?, namespace? }) | BM25 排序搜索工具(默认 8 个) |
describeTool(name) | 工具描述和 TypeScript 声明 |
describeNamespace(name) | 命名空间(如 MCP 服务器)的描述、说明和工具名 |
models | 列出并运行非 LLM 模型 |
2.5 调用工具的返回值
- 有输出 schema 的工具返回结构化值。
bash返回{ output, truncated, full_output_path?, exit_code, wall_time_seconds },output最多 1 MiB(不受给模型的 2000 行/50KB 限制); - MCP 工具返回其
CallToolResult(含isError、structuredContent); read返回文件文本,图片则返回图片块;- 其他工具(如
edit、write)返回文本输出; - 失败或被阻止的调用会 reject,用
Promise.allSettled()保留成功结果。
MCP 工具名中的非法 JS 标识符字符变为 _:mcp__dev-radius__search → tools.mcp__dev_radius__search。
2.6 示例脚本(按官方 API 编写)
并行读取多个文件并只返回摘要:
const files = ["package.json", "README.md", "tsconfig.json"];
const results = await Promise.allSettled(files.map((path) => tools.read({ path })));
return results.map((r, i) =>
r.status === "fulfilled"
? { file: files[i], chars: r.value.length, firstLine: r.value.split("\n")[0] }
: { file: files[i], error: String(r.reason) },
);
用 bash 并过滤大输出:
const r = await tools.bash({ command: "git log --oneline -n 500" });
const fixes = r.output.split("\n").filter((l) => /fix/i.test(l));
text(`共 ${fixes.length} 条 fix 提交,最近 5 条:`);
return fixes.slice(0, 5);
查找 MCP 工具:
const found = await searchTools("create issue", { limit: 3 });
for (const t of found) text(await describeTool(t.name));
2.7 分类器与图像模型
分类器模型不聊天,它们回答关于 JSON 状态的 类型化问题(choice / score / bool),并给出概率。内置 TypeSafe 的 Jev、Cloudflare 的 Clef、OpenAI 的 GPT-6 Luna(Decisions API)等;它们 不出现在 /model,通过 codemode 使用。官方示例:
const jev = await models.getModelOfType("classifier", "typesafe", "jev-latest");
const results = await Promise.all(
messages.map((message) =>
models.classify(jev, {
state: { message },
questions: {
sentiment: {
type: "choice",
instructions: "How does the user feel about the product?",
criteria: { positive: "Satisfied or happy", negative: "Unhappy or frustrated", neutral: "Neither" },
},
urgency: {
type: "score",
instructions: "How urgently does this need a reply?",
criteria: ["no reply needed", "reply this week", "reply today"],
},
},
}),
),
);
图像生成(1.0+):
// @options: {"timeout_ms": 300000}
const painter = await models.getModelOfType("image", "openrouter", "google/gemini-2.5-flash-image");
const result = await models.generateImages(painter, {
input: [{ type: "text", text: "A red fox in the snow, watercolor" }],
});
if (result.stopReason !== "stop") return result.errorMessage;
for (const block of result.output) {
if (block.type === "image") image(block);
else text(block.text);
}
classify()/generateImages() 遇到 Provider 错误 不抛异常,请检查 stopReason 和 errorMessage;用 models.getAvailableOfType(type) 找到当前凭据可用的模型 ID。用量计入会话费用。
2.8 限制与设置
- 每个脚本 VM 256 MB 内存;一个 Pi 进程最多同时 2 个 codemode worker;脚本不能再启动 codemode 脚本;
- 设置
codemode.mode:"on"(默认,已声明工具保持声明)或"only"(其他工具对模型隐藏,只能通过脚本调用); codemode.inlineBudget:codemode 描述中工具声明的 token 预算(默认 3000)。
3. Tool Search
tool_search 默认关闭("defaultTools": ["+tool_search"] 开启),它对 尚未声明 的工具(codemode/deferred 暴露)使用与 searchTools() 相同的排序,并把匹配项 声明给下一次模型调用。加载的工具会记录在会话中,在该分支上保持声明。
4. 虚拟模型(Virtual Models)
虚拟模型是一个可选择的模型,它 为每次请求挑选一个物理模型。可按任务、成本或会话状态路由——例如简单问题给小模型、难题给大模型,而用户只需选一个模型。
4.1 注册(官方示例)
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
export default function (pi: ExtensionAPI) {
pi.registerVirtualModel({
provider: "router",
id: "auto",
name: "Auto",
thinkingLevels: ["low", "high"],
route(request, ctx) {
// Tool follow-ups and retries stay on the model that handled the turn.
const sticky = request.failed ?? request.previous;
if (request.reason !== "user" && sticky) {
return { model: sticky.model, thinkingLevel: sticky.thinkingLevel ?? "medium" };
}
const id = request.thinkingLevel === "high" ? "claude-sonnet-4-5" : "claude-haiku-4-5";
return { model: ctx.modelRegistry.find("anthropic", id)!, thinkingLevel: "medium" };
},
});
}
注册后它会出现在 /model、--model、作用域模型和设置中(如 router/auto)。底栏会显示路由结果,例如 auto • high → gpt-5.6-luna • medium。
4.2 route(request, ctx) 的输入
model、thinkingLevel- 含义
- 选中的虚拟模型和等级(等级含义由路由器自定义)
reason- 含义
user(用户消息后的首个请求)、continuation(工具结果后等)、retry、direct(压缩摘要等循环外请求)
previous- 含义
- 最近一次成功回复的物理模型与等级
failed- 含义
- retry 时失败请求的信息
state- 含义
- 本分支上路由器上次返回的状态
messages、signal- 含义
- 本次请求的对话和中止信号
| 字段 | 含义 |
|---|---|
model、thinkingLevel | 选中的虚拟模型和等级(等级含义由路由器自定义) |
reason | user(用户消息后的首个请求)、continuation(工具结果后等)、retry、direct(压缩摘要等循环外请求) |
previous | 最近一次成功回复的物理模型与等级 |
failed | retry 时失败请求的信息 |
state | 本分支上路由器上次返回的状态 |
messages、signal | 本次请求的对话和中止信号 |
最佳实践:continuation 时返回 previous、retry 时返回 failed,可 保持 prompt cache 和思考签名有效;切换模型会丢失缓存。
4.3 路由状态
pi.registerVirtualModel<{ phase: "plan" | "build" }>({
provider: "router",
id: "phased",
name: "Phased",
route(request, ctx) {
const state = request.state ?? { phase: "plan" };
const id = state.phase === "plan" ? "claude-opus-4-5" : "claude-haiku-4-5";
return { model: ctx.modelRegistry.find("anthropic", id)!, thinkingLevel: "medium", state };
},
});
状态必须可 JSON 序列化,随会话树走(fork 和 /tree 看到各自分支的状态),并能经受压缩。完整路由器示例:examples/extensions/jev-router.ts(用 Jev 分类器选择强模型做规划,首次编辑后切到便宜模型)。SDK 中可用 modelRuntime.registerVirtualModel(definition)。
5. 自定义 Provider
先选最小集成:
在支持的 API 后面加模型
- 使用
models.json
修改现有 Provider 的端点或请求头
- 使用
models.json或小型 Provider 扩展
动态发现模型
- 使用
- 带
refreshModels的 Provider
添加
/login流程- 使用
- 带 OAuth 配置的 Provider
实现不支持的协议
- 使用
- 带
stream/streamSimple的 Provider
| 需求 | 使用 |
|---|---|
| 在支持的 API 后面加模型 | models.json |
| 修改现有 Provider 的端点或请求头 | models.json 或小型 Provider 扩展 |
| 动态发现模型 | 带 refreshModels 的 Provider |
添加 /login 流程 | 带 OAuth 配置的 Provider |
| 实现不支持的协议 | 带 stream/streamSimple 的 Provider |
重定向现有 Provider(保留内置目录和认证):
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
export default function (pi: ExtensionAPI) {
pi.registerProvider("anthropic", {
baseUrl: "https://gateway.example.com/anthropic",
headers: {
"X-Gateway-Key": "$GATEWAY_API_KEY",
},
});
}
注册兼容端点:
export default function (pi: ExtensionAPI) {
pi.registerProvider("acme", {
name: "Acme AI",
baseUrl: "https://api.acme.example/v1",
apiKey: "$ACME_API_KEY",
api: "openai-completions",
models: [
{
type: "chat",
id: "acme-chat",
name: "Acme Chat",
reasoning: false,
input: ["text"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 128000,
maxTokens: 8192,
},
],
});
}
不要把内置模型列表复制进扩展:那会把一个小的端点覆盖变成会漂移的目录替换。完整 OAuth + 自定义流式示例:
examples/extensions/custom-provider-gitlab-duo/、custom-provider-anthropic/。
6. Pi 包:安装与分发
Pi 包把 扩展、技能、提示模板和主题 作为一个单元通过 npm 或 git 分发。
6.1 安装与管理
pi install npm:@example/pi-tools@1.0.0
pi install git:github.com/example/pi-tools@v1
pi install ./local-package
pi install -l npm:@example/pi-tools # 写入项目 .pi/settings.json
pi -e npm:@example/pi-tools # 只本次试用,不写设置
pi list
pi remove npm:@example/pi-tools
pi update --extensions # 更新所有包
pi config # 交互式启停包内资源和内置扩展
npm
- 示例
npm:@example/pi-tools@1.0.0- 行为
- 装到 Pi 的 npm 目录;带版本即锁定
git
- 示例
git:github.com/example/pi-tools@v1- 行为
- 克隆并对齐到所选 ref;tag/commit 锁定
URL
- 示例
https://github.com/example/pi-tools- 行为
- 视作 git
本地
- 示例
./pi-tools- 行为
- 从解析路径加载,不复制
| 来源 | 示例 | 行为 |
|---|---|---|
| npm | npm:@example/pi-tools@1.0.0 | 装到 Pi 的 npm 目录;带版本即锁定 |
| git | git:github.com/example/pi-tools@v1 | 克隆并对齐到所选 ref;tag/commit 锁定 |
| URL | https://github.com/example/pi-tools | 视作 git |
| 本地 | ./pi-tools | 从解析路径加载,不复制 |
包画廊:https://pi.dev/packages (npm 包加 pi-package 关键字即可被收录;pi.image/pi.video 字段添加预览)。
6.2 创建包
约定目录(无需清单):
my-pi-package/
├── package.json
├── extensions/
├── skills/
├── prompts/
└── themes/
显式清单:
{
"name": "my-pi-package",
"keywords": ["pi-package"],
"pi": {
"extensions": ["./src/extension.ts"],
"skills": ["./resources/skills"],
"prompts": ["./resources/prompts/*.md"],
"themes": ["./resources/themes/*.json"]
}
}
6.3 依赖声明(易错点)
- 扩展导入的运行时包放
dependencies; - Pi 宿主提供:
@earendil-works/pi-ai、@earendil-works/pi-agent-core、@earendil-works/pi-coding-agent、@earendil-works/pi-tui、typebox—— 这些应放在peerDependencies,范围"*",不要打包; - 不要 把宿主包列入
dependencies:物理副本会绕过 Pi 的模块映射,导致类和注册表重复(Pi 会发出警告)。
{
"name": "@me/pi-review-kit",
"version": "0.1.0",
"keywords": ["pi-package"],
"type": "module",
"pi": { "extensions": ["./extensions"], "skills": ["./skills"], "prompts": ["./prompts/*.md"] },
"peerDependencies": {
"@earendil-works/pi-coding-agent": "*",
"@earendil-works/pi-ai": "*",
"typebox": "*"
},
"dependencies": {}
}
6.4 选择包内资源
{
"packages": [
{
"source": "npm:@example/pi-tools",
"extensions": ["extensions/*.ts", "!extensions/legacy.ts"],
"skills": [],
"prompts": ["prompts/review.md"]
}
]
}
省略=全部;[]=不加载该类型;!pattern 排除;+path/-path 精确包含/排除。项目条目通常替换个人条目;autoload: false 时作为过滤增量。
安全:包可以执行扩展代码、包含指示模型运行程序的技能。安装第三方包前请审查源码。
7. 小练习
- MCP 入门:
pi mcp add filesystem -- npx -y @modelcontextprotocol/server-filesystem .,运行pi mcp list,进入 Pi 用/mcp查看工具和默认 exposure;让 Pi 用该服务器列出文件,观察它是否走了 codemode。 - exposure 对比:把同一服务器分别设为
direct、deferred、codemode,比较模型调用方式和请求 token(/session)。 - Codemode 并行:开启
+codemode,要求 Pi "用 codemode 并行读取 src 下所有 .ts 文件,只返回行数最多的 5 个文件及行数"。查看脚本内容和输出。 - store/load:让 Pi 在一次 codemode 中
store("lastScan", ...),下一轮读取;再用/tree回到之前分支,验证值随分支变化。 - 虚拟模型:实现一个
router/cheap-first虚拟模型:reason === "user"且用户消息短于 200 字时用小模型,否则用大模型;continuation 保持previous。 - 发布一个 Pi 包:把 05 中写的 permission-gate、04 中的 review 模板和 changelog 技能组织成包,先
pi install ./my-pi-package本地测试,再(可选)发布到 npm 并加pi-package关键字。 - 思考题:为什么默认 MCP exposure 是
codemode而不是direct?从上下文 token、prompt cache 稳定性角度分析。
8. 官方来源
- MCP Servers:https://pi.dev/docs/latest/mcp
- Codemode:https://pi.dev/docs/latest/codemode
- Command Line(Enable codemode / Tool search):https://pi.dev/docs/latest/cli
- Choose a Model(分类器与图像模型):https://pi.dev/docs/latest/models
- Virtual Models:https://pi.dev/docs/latest/virtual-models
- Custom Providers:https://pi.dev/docs/latest/custom-provider
- Pi Packages:https://pi.dev/docs/latest/packages
- Settings(codemode / resources):https://pi.dev/docs/latest/settings
- CHANGELOG(0.99.0 起):https://github.com/earendil-works/pi/blob/main/packages/coding-agent/CHANGELOG.md
- 示例:
examples/sdk/14-codemode-mcp.ts、examples/extensions/jev-router.ts