MCP, Codemode, Tool Search, virtual model, custom Provider and Pi package installation and distribution.
Difficulty: ★★★★★ | Prerequisites:03、04、05、06 | This article covers the main new features introduced since 0.99 (0.99.0, 2026-09-29: Codemode and MCP, virtual model, classifier model), and is updated according to subsequent changes in 1.x.
1. MCP(Model Context Protocol)
Pi passed stdio or streamable HTTP Connect to the MCP server and provide its tools and resources to the model. (Old SSE transport is not supported;The documentation suggests that many services that provide SSE endpoints also provide streamable HTTP, usually in /mcp rather than /sse。)
1.1 Quick configuration (official)
# Local stdio server
pi mcp add filesystem -- npx -y @modelcontextprotocol/server-filesystem .
pi mcp list
pi
# Remote HTTP server
pi mcp add docs --url https://example.com/mcp --bearer-token-env-var DOCS_TOKEN
pi mcp list
#Write project configuration (.pi/mcp.json)
pi mcp add -l tools --env API_KEY='${TOOLS_KEY}' -- uvx tools-mcp
Used in interaction /mcp Check the connection, log in, reconnect, modify the exposure method, start and stop the server; modify the configuration outside the session and run it /reload。
1.2 mcp.json Format
user level ~/.pi/agent/mcp.json, project level .pi/mcp.json(Project trust required; entries with the same name replace user-level entries). The format is consistent with other MCP clients:
{
"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"
}
}
}
Configuration rules:
- stdio:
command、args、env、cwd;commandYes single executable file, not a shell string; - HTTP:
url、headers、oauth; - General:
timeout(seconds, default 60),enabled: false、exposure、toolExposure、description; env/headersvalue available${GITHUB_TOKEN}, integer values can also be used!command, for example"Authorization": "!echo Bearer $(gh auth token)";- The tool is named
mcp__<server>__<tool>; - Project entries only write
enabled/exposure/toolExposureOnly these fields are overridden for user-level servers with the same name, for example, if disabled in a project:
{ "mcpServers": { "internal-tools": { "enabled": false } } }
Migration: Claude Desktop / Claude Code / Cursor mcpServers Entries can be copied directly; VS Code, Codex, and OpenCode need to convert fields according to the official form.
1.3 OAuth authentication
A remote server using OAuth (such as Sentry) in mcp.json in No need to write credentials:
{ "mcpServers": { "sentry": { "url": "https://mcp.sentry.dev/mcp" } } }
When the server rejects unauthenticated connections,/mcp Display requires login; select "Sign in" and run /mcp login sentry or pi mcp login sentry. The token is saved in ~/.pi/agent/mcp-auth.json and refresh automatically. Configurable for servers that do not support dynamic registration oauth.clientId/clientSecret/callbackPort; also clientName、scope、clientRegistration: "cimd"、authServerMetadataUrl and other options (1.0 enhancement).
1.4 Tool exposure - the most critical concept
codemode(Default)- behavior
- Can be called by the codemode script, but Not declared to the model, is not listed in the codemode description; the script uses
searchTools()/describeTool()/ALL_TOOLSFind - Typical uses
- General MCP server, especially when combining or filtering calls is required
deferred- behavior
- until
tool_searchNot declared before loading matches for next call - Typical uses
- There are many tools, but you want to call the server directly after discovering it.
direct- behavior
- Declare to model like built-in tool, also callable from codemode
- Typical uses
- Small but commonly used toolset
hidden- behavior
- Registered but unreachable
- Typical uses
- Tools that should remain unavailable
| exposure | behavior | Typical uses |
|---|---|---|
codemode(Default) | Can be called by the codemode script, but Not declared to the model, is not listed in the codemode description; the script uses searchTools()/describeTool()/ALL_TOOLS Find | General MCP server, especially when combining or filtering calls is required |
deferred | until tool_search Not declared before loading matches for next call | There are many tools, but you want to call the server directly after discovering it. |
direct | Declare to model like built-in tool, also callable from codemode | Small but commonly used toolset |
hidden | Registered but unreachable | Tools that should remain unavailable |
- Yes
codemodePi automatically activates when connecting to an exposed servercodemode; Yesdeferredautomatically activated whentool_search(available"autoEnableCodemode": falseTurn off automatic activation); toolExposureCan be overridden by tool (exact name takes precedence, the first match in the pattern takes effect):
{
"mcpServers": {
"github": {
"url": "https://api.githubcopilot.com/mcp/",
"exposure": "deferred",
"toolExposure": {
"search_code": "direct",
"get_*": "codemode",
"delete_*": "hidden"
}
}
}
}
- Text results exceeding 20 KB will be cut off in the middle when they are given to the model, and the complete text will be stored in a temporary file; the codemode script will get the complete results, which can be filtered first and then output;
- When the server provides resources, Pi is added
list_mcp_resources、list_mcp_resource_templates、read_mcp_resourceThree tools.
0.99.2 change:Default
codemodeExposed servers are no longer listed in the codemode description and no longer block the first prompt; they appear in the brief system promptmcp_serversin paragraph.codemode-deferredbecomecodemodealias.
1.5 Permissions and Extensions
- Each MCP call goes through the tool pipeline of Pi, so
tool_call/tool_resultThe same applies to processors (including permission gates); the call band in the codemode scriptparentToolCallId; pi.getAllTools()reported by serverreadOnlyHint/destructiveHintand other comments, you can decide whether to confirm based on this (see 05 Extension development annotations example);- Extensions available
pi.registerMcpServer(name, config)Add a server for the current session (not persistent, needs to be re-registered for each load):
pi.registerMcpServer("jira", { url: "https://mcp.example.com/jira", exposure: "codemode" });
pi.unregisterMcpServer("jira");
- Installed and registered
/mcpextensions (such aspi-mcp-adapter) will replace built-in MCP support; disable built-in MCP:"extensions": ["-builtin:mcp"]or single--no-mcp。
2. Codemode
2.1 What is
codemode tools to model Write a JavaScript script, call other tools of Pi in the script, and run non-LLM models (classifiers, image models).Only the output of the script goes into the model context, so the script can Parallel Call the tool, before the model sees it Filter large results。
2.2 Enable
{ "defaultTools": ["+codemode"] }
or single:`pi --tools +codemode`。No need MCP Also very useful.
2.3 Script running environment
- The input is Original JS source code(not JSON, not markdown code blocks), as an async function body runs in QuickJS sandbox Medium, supports top-level
awaitandreturn; - sandbox No Node API, file system, network, timer - only available via tools and
modelsinteract with the outside world; - The first line of writable options:
// @options: {"max_output_tokens": 2000, "timeout_ms": 60000}
`max_output_tokens` Default 10000;`timeout_ms` Not set by default.
2.4 Global objects
tools.<name>(args)- function
- Call tool
text(value)- function
- Add text output
image(value)- function
- Add image output
console.log(...)- function
- write
<console_output>block
return value- function
- Equivalent
text()
exit()- function
- ended successfully
store(key, value)/load(key)- function
- Save small JSON values across multiple codemode calls (persisted with session branches)
ALL_TOOLS- function
- All callable tools
{ name, description }
searchTools(query, { limit?, namespace? })- function
- BM25 sorting search tool (default 8)
describeTool(name)- function
- Tool description and TypeScript declaration
describeNamespace(name)- function
- Description, description, and tool name of the namespace (such as MCP server)
models- function
- List and run non-LLM models
| overall situation | function |
|---|---|
tools.<name>(args) | Call tool |
text(value) | Add text output |
image(value) | Add image output |
console.log(...) | write <console_output> block |
return value | Equivalent text() |
exit() | ended successfully |
store(key, value) / load(key) | Save small JSON values across multiple codemode calls (persisted with session branches) |
ALL_TOOLS | All callable tools { name, description } |
searchTools(query, { limit?, namespace? }) | BM25 sorting search tool (default 8) |
describeTool(name) | Tool description and TypeScript declaration |
describeNamespace(name) | Description, description, and tool name of the namespace (such as MCP server) |
models | List and run non-LLM models |
2.5 Return value of calling tool
- Tools that output schema return structured values.
bashReturn{ output, truncated, full_output_path?, exit_code, wall_time_seconds },outputUp to 1 MiB (not subject to the 2000 row/50KB limit given to models); - The MCP tool returns its
CallToolResult(IncludingisError、structuredContent); readReturns file text, and pictures returns picture blocks;- Other tools (such as
edit、write) returns text output; - Failed or blocked calls will reject, use
Promise.allSettled()Success results are retained.
MCP Illegal JS identifier characters in tool name become _:mcp__dev-radius__search → tools.mcp__dev_radius__search。
2.6 Sample script (written according to official API)
Read multiple files in parallel and return only the summary:
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) },
);
Use bash and filter large output:
const r = await tools.bash({ command: "git log --oneline -n 500" });
const fixes = r.output.split("\n").filter((l) => /fix/i.test(l));
text(`total ${fixes.length} Article fix Submitted, recently 5 Article:`);
return fixes.slice(0, 5);
Find the MCP tool:
const found = await searchTools("create issue", { limit: 3 });
for (const t of found) text(await describeTool(t.name));
2.7 Classifier and image model
Classifier models don't chat, they answer questions about JSON status Typing issues(choice/score/bool) and give the probability. Jev with built-in TypeSafe, Clef of Cloudflare, GPT-6 Luna (Decisions API) of OpenAI, etc.; they not present now /model, used by codemode. Official example:
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"],
},
},
}),
),
);
image generation (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 error encountered Don't throw exception, please check stopReason and errorMessage; use models.getAvailableOfType(type) Find the model ID for which the current credentials are available. Usage is included in session charges.
2.8 Limitations and Settings
- 256 MB memory per script VM; one Pi process can have up to 2 codemode workers at the same time; scripts can no longer start codemode scripts;
- settings
codemode.mode:"on"(default, declared tools remain declared) or"only"(Other tools are hidden from the model and can only be called through scripts); codemode.inlineBudget:codemode The token budget declared by the tool in the description (default 3000).
3. Tool Search
tool_search Off by default ("defaultTools": ["+tool_search"] turned on), it is Not yet declared tools (codemode/deferred exposed) use with searchTools() Sort the same and put the matches Declare for next model call. Loaded tools are logged in the session, maintaining declarations on that branch.
4. Virtual Models
A virtual model is an optional model that Pick a physics model for each request. Routing can be done by task, cost, or session state—for example, simple questions go to small models, hard questions go to large models, and the user only has to select one model.
4.1 Registration (official example)
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" };
},
});
}
After registration it will appear in /model、--model, scope models and settings (such as router/auto). The bottom bar will display the routing results, for example auto • high → gpt-5.6-luna • medium。
4.2 route(request, ctx) input
model、thinkingLevel- meaning
- The selected virtual model and level (the meaning of the level is customized by the router)
reason- meaning
user(The first request after the user message),continuation(Wait after tool results),retry、direct(out-of-loop requests such as compressed digests)
previous- meaning
- The most recent successfully restored physical model and level
failed- meaning
- Information about failed requests during retry
state- meaning
- The last status returned by the router on this branch
messages、signal- meaning
- Dialog and abort signals for this request
| Field | meaning |
|---|---|
model、thinkingLevel | The selected virtual model and level (the meaning of the level is customized by the router) |
reason | user(The first request after the user message),continuation(Wait after tool results),retry、direct(out-of-loop requests such as compressed digests) |
previous | The most recent successfully restored physical model and level |
failed | Information about failed requests during retry |
state | The last status returned by the router on this branch |
messages、signal | Dialog and abort signals for this request |
Best practices:continuation return when previous、retry return when failed, can Keep prompt cache and think signature valid;Cache will be lost when switching models.
4.3 Routing status
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 };
},
});
The state must be JSON serializable, following the session tree (fork and /tree see the status of their respective branches) and can withstand compression. Complete router example:examples/extensions/jev-router.ts(Use the Jev classifier to select the strong model for planning, and switch to the cheap model after the first edit). Available in SDK modelRuntime.registerVirtualModel(definition)。
5. Custom Provider
Choose minimal integration first:
Add models after supported APIs
- Use
models.json
Modify the endpoint or request header of an existing Provider
- Use
models.jsonor a small Provider extension
dynamic discovery model
- Use
- bring
refreshModelsProvider
add
/loginprocess- Use
- Provider with OAuth configuration
Implementing an unsupported protocol
- Use
- bring
stream/streamSimpleProvider
| demand | Use |
|---|---|
| Add models after supported APIs | models.json |
| Modify the endpoint or request header of an existing Provider | models.json or a small Provider extension |
| dynamic discovery model | bring refreshModels Provider |
add /login process | Provider with OAuth configuration |
| Implementing an unsupported protocol | bring stream/streamSimple Provider |
Redirect an existing Provider (preserving built-in directories and authentication):
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",
},
});
}
Register compatible endpoints:
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,
},
],
});
}
Don't copy the built-in model list into the extension: that turns a small endpoint override into a drifting directory replacement. Complete OAuth + custom streaming example:
examples/extensions/custom-provider-gitlab-duo/、custom-provider-anthropic/。
6. Pi package: installation and distribution
Pi bag handle Extensions, skills, prompts templates and themes Distributed as a unit via npm or git.
6.1 Installation and management
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 # Write project .pi/settings.json
pi -e npm:@example/pi-tools # Only for this trial, no settings are required.
pi list
pi remove npm:@example/pi-tools
pi update --extensions # Update all packages
pi config # Interactively start and stop package resources and built-in extensions
npm
- Example
npm:@example/pi-tools@1.0.0- behavior
- Installed into the npm directory of Pi; with version, it is locked
git
- Example
git:github.com/example/pi-tools@v1- behavior
- Clone and align to selected ref; tag/commit locked
URL
- Example
https://github.com/example/pi-tools- behavior
- treated as git
local
- Example
./pi-tools- behavior
- Load from parsed path, don't copy
| Source | Example | behavior |
|---|---|---|
| npm | npm:@example/pi-tools@1.0.0 | Installed into the npm directory of Pi; with version, it is locked |
| git | git:github.com/example/pi-tools@v1 | Clone and align to selected ref; tag/commit locked |
| URL | https://github.com/example/pi-tools | treated as git |
| local | ./pi-tools | Load from parsed path, don't copy |
Package Gallery:https://pi.dev/packages (npm package adds pi-package Keywords can be included;pi.image/pi.video Field added preview).
6.2 Create package
Agreed directory (no list required):
my-pi-package/
├── package.json
├── extensions/
├── skills/
├── prompts/
└── themes/
Explicit list:
{
"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 Dependency declaration (error-prone point)
- Extension of imported runtime packages
dependencies; - Pi host provides:
@earendil-works/pi-ai、@earendil-works/pi-agent-core、@earendil-works/pi-coding-agent、@earendil-works/pi-tui、typebox——These should be placedpeerDependencies, range"*", don’t pack; - Don't Include host package
dependencies: Physical copies bypass Pi's module mapping, causing class and registry duplication (Pi will issue a warning).
{
"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 Select resources in the package
{
"packages": [
{
"source": "npm:@example/pi-tools",
"extensions": ["extensions/*.ts", "!extensions/legacy.ts"],
"skills": [],
"prompts": ["prompts/review.md"]
}
]
}
omit=all;[]=Do not load this type;!pattern exclude; exclude;+path/-path Precise inclusion/exclusion. Project entries usually replace personal entries;autoload: false as filter increment.
Security: Packages can execute extension code and contain skills that instruct the model runner. Please review the source code before installing third-party packages.
7. Small exercises
- Getting started with MCP:
pi mcp add filesystem -- npx -y @modelcontextprotocol/server-filesystem ., runpi mcp list, enter Pi and use/mcpView tools and default exposure; ask Pi to list files with that server and watch if it goes to codemode. - exposure contrast: Set the same server to
direct、deferred、codemode, compare the model calling method and the request token (/session)。 - Codemode Parallel: On
+codemode, requesting Pi "Use codemode to read all .ts files under src in parallel, and only return the 5 files with the largest number of lines and the number of lines." View script content and output. - store/load: Let Pi in one codemode
store("lastScan", ...), next round of reading; reuse/treeGo back to the previous branch and verify that the value changes with the branch. - virtual model: implement a
router/cheap-firstVirtual model:reason === "user"And when the user message is shorter than 200 words, use the small model, otherwise use the large model; continuation remainsprevious。 - Publish a Pi package: Organize the permission-gate written in 05, the review template and changelog skills written in 04 into packages. First
pi install ./my-pi-packageTest locally, then (optionally) publish to npm and addpi-packageKeywords. - Thinking questions:Why the default MCP exposure is
codemodeinstead ofdirect? Analysis from the perspective of context token and prompt cache stability.
8. Official sources
- 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 (Classifier vs. Image 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 (from 0.99.0):https://github.com/earendil-works/pi/blob/main/packages/coding-agent/CHANGELOG.md
- Example:
examples/sdk/14-codemode-mcp.ts、examples/extensions/jev-router.ts