Install
Install with PiG
pig install npm:pi-mcp-extensionInstall with Pi
pi install npm:pi-mcp-extensionPackages run code with your permissions and influence agent behavior. Catalog inclusion is not a security audit. Review the source before installing a third-party package.
Verified with PiG. This package was installed and started with a PiG build. That is not a security audit or a compatibility guarantee.
Pi manifest JSON
The pi field of package.json.
{
"image": "https://raw.githubusercontent.com/irahardianto/pi-mcp-extension/main/docs/icon-preview.png",
"extensions": [
"./src/index.ts"
]
}README
Written by the package's publisher, shown as published in version 1.16.4 (README.md). PiG does not review it.
pi-mcp-extension
Connect Pi to any MCP server. Supabase, DeepSource, Playwright, Context7, filesystem, databases — if it speaks MCP, Pi can use it.
pi-mcp-extension is a production-ready Model Context Protocol client extension for the Pi coding agent. It manages server connections, discovers tools, and bridges them into Pi so the LLM can call them directly.
Quick Start · Configuration · OAuth 2.1 · Commands & Agent Tools · Debug Log · How It Works · MCP Spec Compliance
Features
- Multi-transport —
stdiosubprocesses,streamable-http(including"http"and URL-only shorthand), and legacysseout of the box - Auto-discovery — Paginated
tools/listwith cursor following (MCP 2025-03-26 spec) - Live tool refresh —
notifications/tools/list_changedtriggers re-discovery without restart - Live tool progress — a server's
notifications/progressevents stream into Pi as live tool-call updates (server text is sanitized and secret-redacted, repeated lines are collapsed), and every notification restarts the per-request timeout, so a long-running tool that keeps reporting — a browser flow, migration, or test runner — is no longer killed atrequestTimeoutMswhile it is demonstrably working - Clean cancellation —
AbortSignalpropagation vianotifications/cancelled - Smart reconnection — Fixed delay retry schedule (1s → 3s → 5s → 10s → 30s), configurable max retries, automatic recovery when a server transport closes or errors unexpectedly, and mid-session HTTP
401/403 insufficient_scopedetection that invalidates stale tokens and prompts for re-authorization - Health checks — Opt-in periodic pings to detect stale connections
- Safe process lifecycle — Child PID tracking with tree-aware cleanup: descendants of wrapper commands (
npx,npm exec,uvx,sh -c) are terminated too, and inherited pipes are released so teardown never stalls - Stable tool names — Sanitized, collision-avoiding names (
<prefix>_<server>_<tool>, max 64 chars) that stay constant across reconnects, including when one server exposes two tools that sanitize to the same identifier: the name that needs no substitution keeps the unhashed form (my_toolwins overmy-tool), remaining ties break by raw-name order, and the names that server's tools get never depend ontools/listorder - Stable tool order — Active MCP tools keep one deterministic order across session starts,
/treenavigation, and idle or mid-turnsetActiveToolsupdates (includingtool_search): each active owned tool is sorted by Pi name among the slots it occupies, inactive tools stay off, and other extensions' tools never move. The same order is applied to outgoing provider tool declarations (top-leveltools, AWS Bedrock ConversetoolConfig.tools, Google/Vertexconfig.tools[].functionDeclarations, andpi-messagescontext.messages[].toolsAdded), which Pi otherwise rebuilds from the transcript's first-appearance order, so the system prompt's tool section and the tools this extension declares stay identical across session starts whatever order the eager servers connected in or the servers list their tools in — keeping a server-side prefix cache warm. A server that connects after an earlier turn is announced on that later turn through the provider's mid-conversation tool-addition channel, which cannot move back into earlier turns - No tool churn — Activate/deactivate pattern ensures tools don't flicker during reconnection
- Tool exposure control — Honor Pi 1.3.0's
exposure/toolExposure: declare only the handful of tools a task needsdirect, leave the rest to Pi'stool_searchand codemode on-demand loading, or hide them entirely — so a 30–80-tool server (GitHub, Supabase, Playwright, Notion) no longer spends 10k–30k tokens of tool declarations per turn or degrades tool selection - Layered config & trust boundary — Global
<agent dir>/mcp.json, project.pi/mcp.json(loaded only in trusted projects, including Pi 1.3.0 partial overrides), and Pi 1.x extension-registered servers (pi.registerMcpServer()) - Rich tool results & annotations — MCP
text,image(ImageContent),structuredContent, embeddedresourcetext/images/binary blobs,resource_linkhints, andaudiofallback descriptions, plusreadOnlyHint,destructiveHint,idempotentHint, andopenWorldHintsurfaced in tool descriptions and passed to Pi as structured toolannotations(boolean hints only), so permission extensions can inspect them - On-demand agent tools & commands —
mcp_status,mcp_connect,mcp_list_resources, andmcp_read_resourceagent tools plus/mcp,/mcp <name>(with config provenance and failure hints),/mcp:start,/mcp:stop,/mcp:auth, and/mcp:resourcesslash commands with server-name autocomplete - Structured error handling — Distinct error codes (
config,connection,auth,timeout,protocol,tool) and actionable failure hints - Redacted debug logging — Opt-in
PI_MCP_DEBUG=1JSON Lines log (<agent dir>/logs/pi-mcp.log,0600, ~2 MB rotation) with automatic secret masking and zero TUIstderrnoise - OAuth 2.1 — Browser and headless/SSH authorization with PKCE, protected-resource discovery, Dynamic Client Registration, startup prompts for eager servers, cross-process lock recovery, token refresh, and origin/issuer-bound local persistence (see OAUTH.md)
Quick Start
Prerequisite: Node.js 22+ and the Pi coding agent.
Disable MCP for one run:
pi --no-mcpalso disables this installed extension, even when it replacesbuiltin:mcp. No MCP config is loaded, no servers connect, and no MCP commands or tools are registered. As with Pi,--no-mcphas no effect when it appears after--or is passed as another option's value.
Install the extension (or run once without installing via
pi -e npm:pi-mcp-extension):pi install npm:pi-mcp-extension(Pi 1.x) Disable Pi's built-in
mcpextension so Pi does not warn that both extensions are enabled at the same time — either runpi configand uncheckmcpunder Built-in extensions, or add"extensions": ["-builtin:mcp"]to~/.pi/agent/settings.json:{ "extensions": [ "-builtin:mcp" ] }Create a config file at
~/.pi/agent/mcp.json(global) or.pi/mcp.json(trusted project). Both files support JSONC (//line and/* ... */block comments):{ "mcpServers": { // Remote HTTP server with OAuth 2.1 (prompts "Authorize now" on startup) "supabase": { "transport": "streamable-http", "url": "https://mcp.supabase.com/mcp", "auth": { "type": "oauth" }, "lifecycle": "eager" }, // Local stdio subprocess server (connects on demand via /mcp:start or mcp_connect) "context7": { "command": "npx", "args": ["-y", "@context7/mcp"], "lifecycle": "lazy" } } }Start Pi — your MCP tools are ready. Use
/mcpto check all servers or/mcp <name>to inspect one in detail.
Configuration
Servers can be configured via JSON/JSONC files (// and /* */ comments are supported) or registered programmatically by other Pi 1.x extensions:
| Source | Precedence & Scope |
|---|---|
.pi/mcp.json | Highest — Project-level overrides per server and per explicitly stated setting. Loaded on session_start only when the project is trusted (ctx.isProjectTrusted()); never read at bootstrap or in untrusted projects. |
~/.pi/agent/mcp.json | Global — Applies to all projects (honors $PI_CODING_AGENT_DIR with ~ expansion when set: <agent dir>/mcp.json). |
pi.registerMcpServer() | Extension-registered — Discovered via pi.getMcpServers() and updated live on mcp_servers_change events when replacing builtin:mcp. Any server with the same name in mcp.json takes precedence. |
Full Example
See also examples/mcp.json.example for a copy-ready template.
{
"settings": {
"toolPrefix": "mcp", // Tools appear as mcp_<server>_<tool> (default: "mcp")
"requestTimeoutMs": 30000, // Per-request timeout in ms (default: 30000)
"maxRetries": 5 // Max reconnection attempts, 0-10 (default: 5)
},
"mcpServers": {
// ── HTTP servers with OAuth 2.1 ──────────────────────────────────────────
"supabase": {
"transport": "streamable-http",
"url": "https://mcp.supabase.com/mcp",
"auth": {
"type": "oauth"
},
"lifecycle": "eager"
},
"deepsource": {
"url": "https://mcp.deepsource.com/mcp", // "transport" defaults to "streamable-http" when "url" is set
"auth": {
"type": "oauth"
},
"lifecycle": "eager"
},
// ── HTTP servers with static API key / Bearer headers ────────────────────
"zai-web-search": {
"transport": "streamable-http",
"url": "https://api.z.ai/api/mcp/web_search_prime/mcp",
"headers": {
"Authorization": "Bearer YOUR_ZAI_API_KEY"
},
"lifecycle": "lazy"
},
// ── Legacy SSE servers ───────────────────────────────────────────────────
"legacy-server": {
"transport": "sse",
"url": "https://example.com/sse",
"lifecycle": "lazy"
},
// ── stdio subprocess servers ─────────────────────────────────────────────
"pathfinder": {
"command": "/path/to/pathfinder-mcp",
"transport": "stdio",
"lifecycle": "eager"
},
"context7": {
"command": "npx",
"args": ["-y", "@context7/mcp"],
"cwd": "./",
"transport": "stdio",
"lifecycle": "lazy"
},
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/workspace"],
"transport": "stdio",
"lifecycle": "lazy",
"env": {
"NODE_ENV": "production"
}
}
}
}
Global Settings
In project-level .pi/mcp.json, settings keys carry no defaults — only the keys explicitly stated in the project file override global settings.
| Field | Type | Default | Description |
|---|---|---|---|
toolPrefix | string | "mcp" | Prefix for registered tools: <prefix>_<server>_<tool>. Must match ^[a-zA-Z][a-zA-Z0-9_]*$. |
requestTimeoutMs | number | 30000 | Default per-request timeout in milliseconds. For tools/call this is an inactivity deadline: every notifications/progress event from the server restarts it, so page-by-page work is not cut off mid-flight. A server that reports progress indefinitely has no wall-clock cap — cancel the tool to stop it |
maxRetries | number | 5 | Max reconnection attempts (0–10) before giving up |
At the top level of mcp.json (alongside settings and mcpServers), Pi 1.3.0's autoEnableCodemode (boolean, default true; project .pi/mcp.json overrides global when set) controls whether configuring any "codemode" server or tool automatically activates Pi's built-in codemode tool.
Per-Server Config
For Pi 1.x / 1.3.0 compatibility, server entries also accept:
typeas an alias fortransport, and"http"as an alias for"streamable-http"oauthas an alias forauthtimeout(in seconds) as an alias forrequestTimeoutMsenabled: falseto keep the server configured but out of the eager set (normalized tolifecycle: "lazy", even iflifecycle: "eager"is also set)
[!NOTE] Pi's
auth.provider(/loginprovider token) is rejected at load time with aconfigerror instead of being silently downgraded to OAuth 2.1 — useauth(OAuth 2.1) or staticheaders.
| Field | Type | Default | Description |
|---|---|---|---|
transport (or type) | "stdio" | "streamable-http" | "http" | "sse" | "stdio" ("streamable-http" when url is set without command) | Transport protocol ("http" is normalized to "streamable-http") |
command | string | — | Executable to spawn (required for stdio) |
args | string[] | [] | Arguments for the command |
cwd | string | session working directory | Working directory for a stdio server (rejected on streamable-http / sse). A relative path resolves against the session working directory and a leading ~ expands to your home directory |
env | Record<string, string> | — | Extra environment variables for the child process (literal values, no ${VAR} interpolation) |
url | string | — | Server URL (required for streamable-http and sse) |
headers | Record<string, string> | — | Static headers sent with streamable-http and sse requests. When auth is set, OAuth owns Authorization, so an Authorization entry here is ignored (other headers still apply) |
auth (or oauth) | object | — | OAuth 2.1 configuration described below and in OAUTH.md (streamable-http / sse only) |
description | string | — | Optional server summary attached to each registered tool's namespace and shown in Pi's mcp_servers system-prompt section for indirect servers (sanitized and secret-redacted, bounded to 250 characters; connected servers fall back to the first line of handshake instructions when omitted) |
lifecycle | "eager" | "lazy" | "lazy" ("eager" for pi.registerMcpServer() unless enabled: false) | eager = auto-start on session_start, lazy = connect on request via mcp_connect, /mcp:start, or /mcp:auth |
enabled | boolean | true | Pi 1.3.0 switch: false keeps the entry configured but out of the eager set (normalized to lifecycle: "lazy", even when lifecycle: "eager" is also set) |
exposure | "direct" | "deferred" | "codemode" | "hidden" | "direct" | Pi 1.3.0 tool exposure for every tool of this server (see Tool exposure). "codemode-deferred" is accepted as an alias for "codemode" |
toolExposure | Record<string, "direct" | "deferred" | "codemode" | "hidden"> | — | Per-tool exposure overrides keyed by the raw MCP tool name or a * wildcard pattern; an exact key wins, then the first matching pattern in declaration order, then exposure |
requestTimeoutMs (or timeout) | number | global setting | Per-server timeout override in ms (timeout is specified in seconds and multiplied by 1000) |
healthCheckIntervalMs | number | disabled | Opt-in ping interval in ms for proactive connection health monitoring |
Tool exposure
Large MCP servers advertise 30–80 tools (GitHub, Supabase, Linear, Playwright, Notion, Jira). Declaring all of them to the model on every turn costs 10k–30k tokens of tool declarations and makes tool selection worse when the task needs three of them. Pi 1.3.0's exposure / toolExposure keys scope that declaration, and this extension honors them:
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"description": "GitHub repository and pull-request read tools",
// Hide everything, then expose only the read-only tools the agent needs directly:
"exposure": "hidden",
"toolExposure": {
"get_*": "direct",
"list_*": "direct",
"search_*": "direct"
}
}
}
}
| Exposure | What Pi does with the tool |
|---|---|
direct | Registers it active: declared to the model like any other tool (this is the default here) |
deferred | Registers it inactive with server namespace metadata (description + MCP handshake instructions) and auto-activates Pi's tool_search tool when available so the model can load and call it on demand |
codemode | Registers it as Pi deferred with server namespace metadata and a CallToolResult outputSchema (keeping codemode's own tool description stable across connects for prompt caching) and auto-activates Pi's codemode tool unless autoEnableCodemode: false is set. Reachable from codemode scripts (searchTools() / describeTool() inspect its input and output schemas, and on Pi 1.3.0+ calls — including MCP isError: true tool errors — resolve to { content, structuredContent, isError }) and loadable by tool_search. codemode-deferred is an accepted alias |
hidden | Registers it inactive with exposure: "hidden": it stays in /mcp counts and keeps its Pi tool name, yet neither the model, tool_search, nor codemode can see or call it |
Resolution follows Pi: an exact toolExposure key wins, then the first matching * pattern in declaration order, then the server's exposure, then direct. Patterns are keyed by the raw MCP tool name (tools/list), not the Pi identifier, and * is the only wildcard — get_* matches get_users, while ., +, ( and friends are literal. Matching is linear, so a pathological pattern in a shared mcp.json cannot hang the session.
System-prompt discovery, disconnect hiding, and backwards compatibility. Pi's own MCP client defaults an omitted exposure to codemode; this extension keeps direct, so an existing mcp.json that says nothing about exposure keeps activating every discovered tool (and on Pi < 1.3.0, isError: true continues rejecting with McpError). Because codemode and tool_search do not inline MCP server lists in their own tool descriptions, before_agent_start populates systemPromptOptions.sections["mcp_servers"] (capped at 4,096 characters) with enabled or connected indirect servers, how to reach each (codemode vs tool_search, falling back symmetrically when only one is active and omitting the section when neither is active), not connected — mcp_connect "<name>" hints for lazy/stopped servers (omitting disconnected servers if mcp_connect itself is inactive), and a sanitized one-line summary (description, or the connected server's first handshake instructions line). Server namespace identifiers and <mcp_servers> bullet headers are deterministically disambiguated across peer servers when distinct server names sanitize or project to the same script identifier (for example my-srv vs my_srv, 1srv vs _srv, or a vs _a), while mcp_connect "<name>" hints preserve the raw server name. Reaching discovery tools (codemode / tool_search) are pre-activated at session start for all enabled or connected indirect servers (eager, lazy, and manually started enabled: false) so connecting a lazy server mid-session does not churn active tools, and restored after /tree (session_tree) without re-activating inactive direct tools; indirect tools activated during a session are also preserved across --continue, /resume, /fork, /tree, and /reload. When indirect tools (deferred or codemode) are present and neither tool_search nor codemode ends up active — or when Pi's --tools / --exclude-tools filter removes all of a server's indirect tools — Pi surfaces a session warning. Stopping, removing, or withdrawing a server's tool re-registers it as hidden and rejects stale calls until the server reconnects, so tool_search and codemode never surface disconnected tools. A server whose tools are all deferred or hidden is working as configured, not broken: mcp_connect verifies configured direct tools and rejects if --tools / --exclude-tools filtered out all indirect tools, while /mcp <name> plus mcp_status report tools: { discovered, active, expected, inactiveDirect?, indirectFiltered? } — expected being the number of direct tools, with inactiveDirect set when configured direct tools on a ready server are missing from Pi's active set and indirectFiltered: true when --tools / --exclude-tools filtered out all indirect tools. /mcp <name> appends (N configured direct) — plus , M direct inactive or , indirect filtered by --tools / --exclude-tools when applicable — to the Tools: line whenever exposure narrows the discovered set.
[!NOTE] Pi 1.3.0's
--toolsCLI allowlist only auto-exemptsmcp__*(double-underscore) identifiers. Because this extension names tools<toolPrefix>_<server>_<tool>(mcp_*by default), includemcp_*(or<toolPrefix>_*) when passing--toolson the CLI so deferred and codemode MCP tools remain registered fortool_searchandcodemode(for example:--tools read,codemode,mcp_*).
Not every tool Pi does not declare is free: deferred and codemode tools still live in tool_search / codemode's registry, and hidden tools remain registered — the saving is the per-turn declaration and the model's choice space, not process memory.
Project Override Entries
A trusted project's .pi/mcp.json may carry a Pi 1.3.0 partial override for a global server: an entry with no command, url, type, or transport changes only per-project settings and keeps the rest of the global entry, including credentials the project cannot set itself.
// ~/.pi/agent/mcp.json
{ "mcpServers": { "internal-tools": { "command": "internal-mcp", "lifecycle": "eager" } } }
// <project>/.pi/mcp.json — turn it off for this project only
{ "mcpServers": { "internal-tools": { "enabled": false } } }
An override may set enabled, lifecycle, and Pi's exposure / toolExposure (all honored — a per-project exposure narrows or widens what the agent sees without copying the global server's credentials). Any other key, or an override for a name no global entry defines, is reported as a config error naming the file and the server.
OAuth Config
Configured under auth (or oauth). Token and client state are persisted per server in <agent dir>/mcp-auth/<hash>.json (0700 directory, 0600 files on POSIX) with atomic writes, origin (serverUrl) and authorization-server (issuer) binding, and automatic backup of corrupt state files. See OAUTH.md for architecture and troubleshooting details.
| Field | Type | Default | Description |
|---|---|---|---|
type | "oauth" | "oauth" | Authentication type |
scope | string | discovered | Requested scope when the server does not advertise one in WWW-Authenticate |
clientId | string | dynamic registration | Pre-registered OAuth client ID (skips Dynamic Client Registration) |
clientSecret | string | — | Secret for a pre-registered confidential client (used in memory; never written to disk) |
clientName (or oauth.clientName) | string | pi-mcp/<server name> | client_name sent with Dynamic Client Registration, for servers that only accept known clients |
redirectUrl (or oauth.callbackUrl / oauth.callbackPort) | string | http://127.0.0.1:19876/callback | Local HTTP loopback callback (localhost, 127.0.0.1, or ::1 with path /callback and an explicit non-zero port; callbackPort maps to http://127.0.0.1:<port>/callback). Scans forward from 19876 when omitted; binds the exact host and port when configured. |
When both aliases are set, oauth.callbackPort (an integer from 1 to 65535) fills in a missing
port in oauth.callbackUrl (http://localhost/callback plus 19877 becomes
http://localhost:19877/callback); an invalid callbackPort or a different port in the URL is a
config error. Port 80 is HTTP's default and counts as missing.
Commands
Server-name arguments provide autocomplete suggestions from the configured MCP servers. /mcp:auth suggests only servers configured for OAuth.
| Slash Command | Description |
|---|---|
/mcp | Show status summary of all configured servers |
/mcp <name> | Show detailed status for one server: config source, transport/lifecycle, tool activation, handshake instructions, OAuth credential status, failure hint, and stderr log |
/mcp:start <name> | Connect a server and wait for tool discovery |
/mcp:stop <name> | Cancel a pending connection, startup prompt, or authorization, or stop a running server and deactivate its tools |
/mcp:auth <name> | Connect (or force a fresh reconnect if already ready) using stored OAuth credentials and client registration; request browser authorization only if needed |
/mcp:auth <name> --reset | Discard stored tokens and client registration (re-running Dynamic Client Registration) and request fresh authorization (--reset may appear before or after <name>) |
/mcp:resources | Show resource and template counts for every connected server |
/mcp:resources <name> | List one server's resources (uri, description, MIME type) and URI templates, capped at 50 rows plus an "and N more" line |
/mcp:resources <name> <uri> | Read one resource (template URIs filled in) and preview its text or image summary in a notification |
In addition to user slash commands, built-in agent tools let the LLM inspect servers, connect them, and read their resources directly (mcp_status and mcp_connect register with exposure: "model-only" on Pi 1.3.0 so session-management tools stay out of codemode sandboxes, while mcp_list_resources and mcp_read_resource remain callable from both the model and codemode scripts):
| Agent Tool | Parameters | Description |
|---|---|---|
mcp_status | {} | List configured servers with lifecycle, state, tools (discovered / active / expected, plus optional inactiveDirect / indirectFiltered), auth credential summary, source ("global" / "project" / "extension" / "unknown"), optional instructions (when connected), and safe error action hints (never returns tokens, headers, or authorization URLs) |
mcp_connect | { name: string } | Connect one named server, run interactive OAuth if needed, and verify that the tools configured direct are active before returning success (includes sanitized server instructions when provided; returns fixed actionable categories on failure instead of raw server response text) |
mcp_list_resources | { server?: string } | List resources/list entries (uri, name, description, mimeType) and resources/templates/list URI templates for connected servers, naming configured servers that are stopped (stoppedServers), servers that do not advertise the resources capability (resourcesUnsupported), and servers whose listing failed (error) without dropping the healthy servers' rows (read-only) |
mcp_read_resource | { server: string, uri: string } | Read one resource with resources/read: text resources return their text (including empty text), valid image/svg+xml blobs decode to UTF-8 SVG text, supported image/* raster blobs (png, jpeg, gif, webp, bmp, tiff) return an image block, and other binary blobs (including empty/invalid or unsupported image/* blobs) return a [Binary resource: uri (mimeType, ...)] summary instead of filling the context window or breaking provider adapters; a server without the resources capability is reported as such rather than as a protocol error (read-only) |
mcp_status returns a JSON array of ServerStatusRow objects:
Connected servers that provide MCP handshake instructions also include an optional
instructions string. /mcp <name> displays the same guidance as Instructions:,
and mcp_connect includes it after a successful connection. Instructions are
secret-redacted, stripped of terminal controls, collapsed to one line, and capped
at 500 UTF-16 code units. Blank instructions and stopped servers omit the field.
These are server-provided usage hints, not trusted local policy.
[
{
"name": "supabase",
"lifecycle": "eager",
"state": "ready",
"tools": { "discovered": 12, "active": 12, "expected": 12 },
"auth": "credentials stored",
"source": "global"
}
]
Inspecting one server (/mcp <name>)
/mcp <name> answers "why is this server in this state?" without leaving Pi:
Server: supabase
State: stopped
Retries: 5
Transport: streamable-http
Lifecycle: lazy
Source: global
Tools: 0/0 active
OAuth: credentials stored
Last error: Connection timed out after 30000ms
Hint: run with PI_MCP_DEBUG=1 pi to log redacted diagnostics, or report server issues at https://github.com/irahardianto/pi-mcp-extension/issues
Recent output:
(no stderr output from supabase)
Sourceis the entry that won:global(<agent dir>/mcp.json),project(<cwd>/.pi/mcp.json), orextension(pi.registerMcpServer()).mcp_statusreports the same value assourceon each row (or"unknown"if unrecorded).- When the project is untrusted,
Sourcenever saysprojectand aProject config: not loaded (<path>)line explains whymcp.jsonin the workspace is not in effect. Toolscompares discovered tools with the ones Pi has active; a server can bereadywith0/N activewhen another extension restricts tools, and a server whoseexposure/toolExposurekeeps some tools deferred, codemode-only, or hidden adds(N configured direct)so a deliberate0/Nis not read as a failure.OAuthappears only for servers with anauthconfig:credentials stored,authorization may be required, orcorrupt state file backed up (re-auth required)(the corrupt file is backed up and the view still renders;mcp_statusreports"not configured"whenauthis unset).- A failed server adds one
Hint:line:/mcp:auth <name>(plus--resetwhen stored credentials expired) for a missing/expired authorization, waiting for another Pi process holding the auth lock, orPI_MCP_DEBUG=1 piplus the issue tracker for a connection failure.
OAuth startup, headless/SSH, and concurrency behavior
- Interactive sessions required for browser auth: Print and RPC sessions fail promptly when interactive authorization is required.
- Startup prompt for eager OAuth servers: Silent startup and background reconnects never open a browser unprompted or trigger Dynamic Client Registration when no client credentials are stored. When an
eagerOAuth server needs interactive authorization at startup in an interactive Pi session, Pi presents a sequential<name> needs authorizationprompt (Authorize now/Not now). ChoosingAuthorize nowruns the interactive OAuth flow; choosingNot nowleaves the server stopped, shows arun /mcp:auth <name>footer hint, and remembers the decline for the rest of the session. - Headless and SSH support: While authorization is pending, Pi displays the authorization URL and offers
Retry: open browser again,Paste redirect URL, andCancel authentication. On remote/SSH or headless machines, open the URL locally and either forward the callback port (ssh -L <port>:127.0.0.1:<port>) or paste the browser's finalhttp://127.0.0.1:<port>/callback?code=...&state=...redirect URL intoPaste redirect URL. Onlyhttps:(or loopbackhttp:) authorization URLs are passed to the system browser opener. - Coordinated connects and cross-process locks: Concurrent connect requests join an in-flight attempt, while
--resetsupersedes a normal connect and shares one pending reset. Cross-process interactive flows are serialized per server via<agent dir>/mcp-auth/<hash>.json.lockwith a 30s heartbeat and automatic reclamation of locks from dead local PIDs or stale heartbeats (>90s), while allowing silent token refreshes to persist rotated tokens. - Resetting stale client registrations (
--reset):/mcp:auth <name>reuses the cached Dynamic Client Registration (clientInfo.client_id) stored in<agent dir>/mcp-auth/<hash>.json. If an OAuth provider expires or purges a previously registered client—for example, when the browser displays{"message":"Unrecognized client_id"}orinvalid_clienton the authorization page without redirecting back to the local callback—run/mcp:auth <name> --resetto discard the cachedclient_id, register a new client via Dynamic Client Registration, and start a fresh authorization flow.
Connection readiness and active tools
mcp_status reports tools.discovered, tools.active, and tools.expected for each server — everything registered, everything Pi has active, and how many tools are configured direct (the ones this extension activates) — plus optional tools.inactiveDirect when configured direct tools on a ready server are missing from Pi's active set (even if tool_search-loaded deferred tools keep active >= expected) and tools.indirectFiltered: true when --tools / --exclude-tools dropped all of the server's indirect tools. Connection state ready means the MCP handshake and discovery completed. It does not mean that another Pi extension has kept every direct tool active.
mcp_connect checks current tool activation before reporting success, including when the server is already connected. If any tool configured direct is inactive it reports that condition instead of overriding another extension's tool restrictions; tools hidden or deferred by exposure never count as missing, and the check is per tool name, so a tool_search-loaded non-direct tool cannot mask a direct one that a policy removed. Check the active tool policy or conflicting extension. A reconnect is not a substitute for fixing an extension that removes tools at each user turn.
Tool discovery follows the same rule. When a connected server announces notifications/tools/list_changed, only the newly exposed tools whose exposure is direct are activated; tools Pi currently has inactive stay inactive, a tool the server dropped and then advertises again comes back in the state it left in, a deferred tool that tool_search activated stays active, and a refresh that discovers nothing new does not touch the active set at all. Stopping a connected server (/mcp:stop, background recovery, or non-reload session teardown) deactivates its tools and forgets those remembered states, so the next connect or reconnect derives the active set from exposure again (while preserving any active indirect tools restored from Pi's session/reload state).
Debug log
Set PI_MCP_DEBUG=1 before starting Pi to record what the extension itself is doing — server state transitions, retries and backoff, OAuth refresh and cross-process lock contention, 401/403 classification, and session reloads:
PI_MCP_DEBUG=1 pi
The log is written to <agent dir>/logs/pi-mcp.log (JSON Lines, one event per line):
{"ts":"2026-01-01T00:00:00.000Z","level":"info","event":"server.state","server":"github","message":"Server github state starting -> ready","from":"starting","to":"ready","ms":412}
- Off by default. Without
PI_MCP_DEBUG=1no log file is created. - Private. The directory is
0o700and the file is0o600, like the OAuth credential files. - Bounded. The file is rotated to
pi-mcp.log.1at ~2 MB; a single backup is kept. Concurrent Pi processes share the log without locking: a rotation that loses that race is not an error (the entry is still appended), and re-checking the size beforerenameskips rotating when the file shrank or disappeared so a peer's freshly rotated backup is not overwritten while still rotating when a peer merely appended. - Redacted. Only allow-listed field names are recorded, and a delimiter-aware pass masks anything that looks like a credential:
- OAuth tokens, authorization codes, and PKCE verifiers
- API keys and other JSON or key/value secrets (
api_key,x-api-key,private_key,password,secret,token, and prefixed forms such asdb_passwordoraws_secret_access_key) - Credential-bearing query parameters on a server URL (
?api_key=…,?token=…,?code=…) Authorizationheaders in any scheme or quoting, and URL userinfo passwords (https://user:password@host)- The same redactor protects the per-server
Recent output:(stderr) buffer, handshakeinstructions,notifications/progresstool updates, theLast error:line in/mcpand/mcp <name>, and user-facing start/auth/recovery failure notifications.
- Best-effort. A failed log write never breaks a connection or a tool call.
Attach the file to a bug report. It contains no credentials.
While a Pi UI is active, the extension never writes diagnostics to Pi's stderr (that stream belongs to the TUI): events go to the log file instead, and user-actionable ones are surfaced as Pi notifications. Headless runs without a UI keep the stderr output they have always had — warnings, errors, and child-server output; informational events such as state transitions are recorded only in the debug log.
How It Works
flowchart TD
subgraph Pi["Pi Coding Agent (TUI / RPC, ExtensionAPI)"]
Entry["index.ts (extension entry)"]
Life["session-lifecycle (bootstrap, reload, mcp_servers_change)"]
Cmds["register-commands (/mcp, :start, :stop, :auth, :resources)"]
Tools["register-tools (mcp_* agent tools)"]
Config["config (Zod + JSONC)"]
Coord["connection-coordinator (in-flight connects, authQueue, teardown)"]
Mgr["server-manager (stopped -> starting -> ready lifecycle)"]
Bridge["tool-bridge (MCP -> Pi tools)"]
Res["resource-bridge (MCP resources & catalog cache)"]
Schema["schema-convert (JSON Schema -> TypeBox)"]
Transport["transport-factory & oauth-provider (MCP SDK)"]
Entry --> Life
Entry --> Cmds
Entry --> Tools
Life --> Config
Life --> Coord
Cmds --> Coord
Cmds --> Res
Tools --> Coord
Tools --> Res
Coord --> Mgr
Mgr --> Bridge
Mgr --> Res
Bridge --> Schema
Mgr --> Transport
end
Sources[("Global & Project mcp.json + Registered Extensions")]
Servers["MCP Servers (stdio / streamable-http / sse)"]
Config --> Sources
Transport <--> Servers
- Config is loaded from global
<agent dir>/mcp.json, trusted project.pi/mcp.json(checked viactx.isProjectTrusted()onsession_start), and extension-registered servers (pi.getMcpServers()/mcp_servers_change), withmcp.jsontaking precedence over extension-registered servers and project entries overriding global ones - Eager servers connect at
session_startviaConnectionCoordinator(offering a sequentialAuthorize now/Not nowprompt when an eager OAuth server needs authorization in an interactive session); lazy servers wait formcp_connect,/mcp:start, or/mcp:auth - Tools are discovered via paginated
tools/listcalls (cursor-based, up to 100 pages) before a server entersready - JSON Schema → TypeBox conversion registers tools with Pi-compatible parameter schemas (preserving nullable union ordering, resolving
$refs cycle-safely, and inferring/flatteningallOfobject schemas) - Pi tools are registered as
<prefix>_<server>_<tool>(sanitized[a-zA-Z0-9_], max 64 chars with an 8-char SHA-256 suffix on truncation or collision) and convert MCPtext,image(ImageContent),structuredContent,resource,resource_link, andaudioresults. When one server exposes two tools that sanitize to the same identifier, the name that needed no substitution keeps the unhashed form (my_toolovermy-tool), remaining ties break by the raw name's code-point order, and the assignment does not depend ontools/listorder — so a reconnect cannot swap which MCP tool a Pi name executes. Embedded image resources become image blocks, binary resources include MIME type and byte count, and resource links include amcp_read_resourcehint. - Tools activate/deactivate automatically as servers connect/disconnect, always in one deterministic order — the bridge's tools are sorted by Pi name among the slots they occupy, and other extensions' tools keep their positions — so connect timing and
tools/listorder cannot change the prompt head - AbortSignal and progress are wired through to
notifications/cancelledfor clean cancellation andnotifications/progressfor live sanitized tool updates plus inactivity-timeout resets - Reconnection & recovery uses a fixed delay schedule with configurable max retries on initial failure, health check failure, or unexpected transport close/error (
client.onclose/client.onerror), while mid-session HTTP401/403 insufficient_scopeinvalidates stale tokens and surfaces a re-authorization hint list_changednotifications trigger re-discovery, deactivating stale tools automatically and invalidating the cached resource catalog- Session shutdown cancels pending auth/connection flows, stops the callback server, deactivates all tools, flushes the debug log, and cleanly stops all servers (with process-tree
SIGTERM→SIGKILL— a PID the kernel refuses to signal is left alone instead of being polled — and pipe cleanup forstdiochild processes)
MCP Spec Compliance
Implements the MCP 2025-03-26 specification for tool and resource clients:
| Feature | Status |
|---|---|
Protocol version 2025-03-26 (+ 2024-11-05 fallback) | ✅ |
stdio transport | ✅ |
streamable-http transport (including "http" / URL-only shorthand) | ✅ |
sse transport (legacy backwards compat) | ✅ |
| OAuth 2.1 authorization (PKCE S256, RFC 9728 Protected Resource Metadata, RFC 7591 DCR) | ✅ |
Cursor-based tools/list pagination | ✅ |
Cursor-based resources/list and resources/templates/list pagination | ✅ |
resources/read with text, image blobs, and binary size summaries | ✅ |
notifications/resources/list_changed (catalog invalidation) | ✅ |
tools/call with parameters, image (ImageContent), structuredContent, resource, and resource_link conversion | ✅ |
roots/list capability (workspace root) | ✅ |
notifications/tools/list_changed (live refresh) | ✅ |
notifications/cancelled (AbortSignal) | ✅ |
notifications/progress (live sanitized tool updates + inactivity timeout reset) | ✅ |
notifications/message (structured logging) | ✅ |
isError: true distinction (protocol vs tool errors, non-text filtered on error) | ✅ |
Tool annotations (readOnlyHint, destructiveHint, etc.) in descriptions and as structured Pi annotations | ✅ |
Contributing / Architecture
See CONTRIBUTING.md for setup, workflow, and the pre-merge smoke-test checklist, and docs/ARCHITECTURE.md for a behavioral overview of how the runtime fits together (lifecycle, coordination, config trust, and credential storage).
Development
Requires Node.js 22+.
# Install dependencies (clean lockfile install)
npm ci
# Lint (type-aware ESLint + structural/complexity checks)
npm run lint
# Type check (strict mode)
npm run typecheck
# Run all test suites
npm test
# Run all test suites with coverage floor (95% lines / 85% branches / 83% functions)
npm run test:coverage
# Run a single test suite (e.g. server lifecycle & stdio integration)
npm run test:integration
# Verify npm tarball contents
npm pack --dry-run
Testing
The test suite includes:
- Config & Pi 1.x / 1.3.0 compatibility (
tests/config.test.ts,tests/pi-1x-compat.test.ts) — Zod schema, JSONC comments,$PI_CODING_AGENT_DIRresolution, global/project merge, project trust boundary (ctx.isProjectTrusted()), Pi 1.3.0enabled: false,autoEnableCodemode,exposure/toolExposure, and partial project overrides,stdiocwd,oauth.clientName, Pi 1.x schema aliases (type: "http", URL-only HTTP,oauth,timeout), and dynamicpi.getMcpServers()/mcp_servers_change - Server lifecycle & coordination (
tests/server-manager.test.ts,tests/stdio-process.test.ts,tests/transport-factory.test.ts,tests/transport-order.test.ts,tests/connection-coordinator.test.ts,tests/connection-coordination.test.ts) — Connect, retry, unexpected close recovery, read-batch FIFO message/close ordering and close-queue draining, shutdown with PIDSIGKILLsafety net, health check, concurrent connect/reset coordination, and cancellation - OAuth 2.1 & auth locks (
tests/oauth-fixes.test.ts,tests/authorize-flow.test.ts,tests/authorize-browser.test.ts,tests/auth-lock.test.ts,tests/auth-commands.test.ts,tests/auth-arguments.test.ts,tests/fake-oauth-server.test.ts) — Challenge discovery, PKCE, Dynamic Client Registration, origin and issuer binding, startup authorization prompts, headless/SSH redirect URL paste-back, URL scheme validation, cross-process lock heartbeat, and stale lock reclamation - Tool bridge, exposure, status diagnostics & debug log (
tests/tool-bridge.test.ts,tests/tool-execution.test.ts,tests/tool-reconcile.test.ts,tests/tool-exposure.test.ts,tests/tool-progress.test.ts,tests/management-tools.test.ts,tests/server-status.test.ts,tests/status-commands.test.ts,tests/completions.test.ts,tests/debug-log.test.ts) — JSON Schema → TypeBox conversion (allOfobject inference,$refcycle protection, unionnullordering), name sanitization, Pi 1.3.0exposure/toolExposureresolution, peer-disambiguated namespaces,<mcp_servers>prompt rendering,_pendingToolNamesand/reloadsession preservation, image content passthrough,isErrorfiltering and Pi 1.3.0+ structured error outcomes, activate/deactivate,notifications/progressforwarding (sanitizing, redaction, dedupe, and the timeout reset over a real stdio server),mcp_status/mcp_connect,/mcp <name>config provenance and failure hints, slash command completions, and redactedPI_MCP_DEBUG=1JSONL logging - Resource bridge (
tests/resource-bridge.test.ts) — paginatedresources/list/resources/templates/list,-32601degradation, catalog caching withnotifications/resources/list_changedinvalidation, stale in-flight discard, text/image/binaryresources/readconversion, abort/timeout/401 mapping,mcp_list_resources/mcp_read_resource, and/mcp:resources - Property-based fuzzing (
tests/fuzz.test.ts) —fast-checkproperties covering JSONC comment stripping, callback/redirect URL validation,WWW-Authenticatechallenge parsing, JSON Schema → TypeBox conversion, tool naming and linear*exposure pattern matching,<mcp_servers>budget shrinking, terminal/log secret sanitization, custom header merging, and read-batch transport message/close ordering - Release flow & repository policy (
tests/release.test.ts,tests/ruleset-audit.test.ts,tests/repo-policy.test.ts,tests/esm-boundaries.test.ts) — Release PR orchestration and npm/git self-healing (scripts/release.ts), live GitHub ruleset drift auditing (scripts/ruleset-audit.ts), CI/ESLint/Qlty policy invariants, and pure-module/leaf-import ESM boundary checks - End-to-end integration — Real mock MCP and OAuth servers over
stdioand HTTP with tool discovery and execution
Security
Please report vulnerabilities privately, not in public issues. See SECURITY.md for scope, supported versions, and how to report.
License
MIT