pi-mcp-extension 1.15.3 → 1.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -28,6 +28,7 @@
28
28
  - **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_tool` wins over `my-tool`), remaining ties break by raw-name order, and the names that server's tools get never depend on `tools/list` order
29
29
  - **Stable tool order** — Active MCP tools keep one deterministic order across session starts, `/tree` navigation, and idle or mid-turn `setActiveTools` updates (including `tool_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-level `tools`, AWS Bedrock Converse `toolConfig.tools`, Google/Vertex `config.tools[].functionDeclarations`, and `pi-messages` `context.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
30
30
  - **No tool churn** — Activate/deactivate pattern ensures tools don't flicker during reconnection
31
+ - **Tool exposure control** — Honor Pi 1.3.0's `exposure` / `toolExposure`: declare only the handful of tools a task needs `direct`, leave the rest to Pi's `tool_search` and 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
31
32
  - **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()`)
32
33
  - **Rich tool results & annotations** — MCP `text`, `image` (`ImageContent`), `structuredContent`, embedded `resource` text/images/binary blobs, `resource_link` hints, and `audio` fallback descriptions, plus `readOnlyHint`, `destructiveHint`, `idempotentHint`, and `openWorldHint` surfaced in tool descriptions and passed to Pi as structured tool `annotations` (boolean hints only), so permission extensions can inspect them
33
34
  - **On-demand agent tools & commands** — `mcp_status`, `mcp_connect`, `mcp_list_resources`, and `mcp_read_resource` agent tools plus `/mcp`, `/mcp <name>` (with config provenance and failure hints), `/mcp:start`, `/mcp:stop`, `/mcp:auth`, and `/mcp:resources` slash commands with server-name autocomplete
@@ -171,6 +172,8 @@ In project-level `.pi/mcp.json`, `settings` keys carry no defaults — only the
171
172
  | `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 |
172
173
  | `maxRetries` | `number` | `5` | Max reconnection attempts (0–10) before giving up |
173
174
 
175
+ 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.
176
+
174
177
  ### Per-Server Config
175
178
 
176
179
  For Pi 1.x / 1.3.0 compatibility, server entries also accept:
@@ -192,11 +195,53 @@ For Pi 1.x / 1.3.0 compatibility, server entries also accept:
192
195
  | `url` | `string` | — | Server URL (**required** for `streamable-http` and `sse`) |
193
196
  | `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) |
194
197
  | `auth` (or `oauth`) | `object` | — | OAuth 2.1 configuration described below and in [OAUTH.md](./OAUTH.md) (`streamable-http` / `sse` only) |
198
+ | `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) |
195
199
  | `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` |
196
200
  | `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) |
201
+ | `exposure` | `"direct" \| "deferred" \| "codemode" \| "hidden"` | `"direct"` | Pi 1.3.0 tool exposure for every tool of this server (see [Tool exposure](#tool-exposure)). `"codemode-deferred"` is accepted as an alias for `"codemode"` |
202
+ | `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` |
197
203
  | `requestTimeoutMs` (or `timeout`) | `number` | global setting | Per-server timeout override in ms (`timeout` is specified in seconds and multiplied by `1000`) |
198
204
  | `healthCheckIntervalMs` | `number` | disabled | Opt-in ping interval in ms for proactive connection health monitoring |
199
205
 
206
+ ### Tool exposure
207
+
208
+ 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:
209
+
210
+ ```jsonc
211
+ {
212
+ "mcpServers": {
213
+ "github": {
214
+ "command": "npx",
215
+ "args": ["-y", "@modelcontextprotocol/server-github"],
216
+ "description": "GitHub repository and pull-request read tools",
217
+ // Hide everything, then expose only the read-only tools the agent needs directly:
218
+ "exposure": "hidden",
219
+ "toolExposure": {
220
+ "get_*": "direct",
221
+ "list_*": "direct",
222
+ "search_*": "direct"
223
+ }
224
+ }
225
+ }
226
+ }
227
+ ```
228
+
229
+ | Exposure | What Pi does with the tool |
230
+ |---|---|
231
+ | `direct` | Registers it active: declared to the model like any other tool (this is the default here) |
232
+ | `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 |
233
+ | `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 |
234
+ | `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 |
235
+
236
+ 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.
237
+
238
+ **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.
239
+
240
+ > [!NOTE]
241
+ > Pi 1.3.0's `--tools` CLI allowlist only auto-exempts `mcp__*` (double-underscore) identifiers. Because this extension names tools `<toolPrefix>_<server>_<tool>` (`mcp_*` by default), include `mcp_*` (or `<toolPrefix>_*`) when passing `--tools` on the CLI so deferred and codemode MCP tools remain registered for `tool_search` and `codemode` (for example: `--tools read,codemode,mcp_*`).
242
+
243
+ 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.
244
+
200
245
  ### Project Override Entries
201
246
 
202
247
  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.
@@ -209,7 +254,7 @@ A trusted project's `.pi/mcp.json` may carry a Pi 1.3.0 **partial override** for
209
254
  { "mcpServers": { "internal-tools": { "enabled": false } } }
210
255
  ```
211
256
 
212
- An override may set `enabled`, `lifecycle`, and Pi's `exposure` / `toolExposure` (the two Pi-native exposure keys are accepted for Pi compatibility and ignored, because this extension decides tool activation itself). 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.
257
+ 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.
213
258
 
214
259
  ### OAuth Config
215
260
 
@@ -240,12 +285,12 @@ Server-name arguments provide autocomplete suggestions from the configured MCP s
240
285
  | `/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 |
241
286
  | `/mcp:resources <name> <uri>` | Read one resource (template URIs filled in) and preview its text or image summary in a notification |
242
287
 
243
- In addition to user slash commands, built-in **agent tools** let the LLM inspect servers, connect them, and read their resources directly:
288
+ 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):
244
289
 
245
290
  | Agent Tool | Parameters | Description |
246
291
  |---|---|---|
247
- | `mcp_status` | `{}` | List configured servers with `lifecycle`, `state`, `tools` (`discovered` / `active`), `auth` credential summary, `source` (`"global"` / `"project"` / `"extension"` / `"unknown"`), optional `instructions` (when connected), and safe `error` action hints (never returns tokens, headers, or authorization URLs) |
248
- | `mcp_connect` | `{ name: string }` | Connect one named server, run interactive OAuth if needed, and verify that discovered tools are active before returning success (includes sanitized server `instructions` when provided; returns fixed actionable categories on failure instead of raw server response text) |
292
+ | `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) |
293
+ | `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) |
249
294
  | `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) |
250
295
  | `mcp_read_resource` | `{ server: string, uri: string }` | Read one resource with `resources/read`: text resources return their text (including empty text), `image/*` blobs return an image block, and other binary blobs return a `[Binary resource: uri (mimeType, N bytes)]` summary instead of filling the context window; a server without the `resources` capability is reported as such rather than as a protocol error (read-only) |
251
296
 
@@ -264,7 +309,7 @@ These are server-provided usage hints, not trusted local policy.
264
309
  "name": "supabase",
265
310
  "lifecycle": "eager",
266
311
  "state": "ready",
267
- "tools": { "discovered": 12, "active": 12 },
312
+ "tools": { "discovered": 12, "active": 12, "expected": 12 },
268
313
  "auth": "credentials stored",
269
314
  "source": "global"
270
315
  }
@@ -293,7 +338,7 @@ Recent output:
293
338
 
294
339
  - `Source` is the entry that won: `global` (`<agent dir>/mcp.json`), `project` (`<cwd>/.pi/mcp.json`), or `extension` (`pi.registerMcpServer()`). `mcp_status` reports the same value as `source` on each row (or `"unknown"` if unrecorded).
295
340
  - When the project is untrusted, `Source` never says `project` and a `Project config: not loaded (<path>)` line explains why `mcp.json` in the workspace is not in effect.
296
- - `Tools` compares discovered tools with the ones Pi has active; a server can be `ready` with `0/N active` when another extension restricts tools.
341
+ - `Tools` compares discovered tools with the ones Pi has active; a server can be `ready` with `0/N active` when another extension restricts tools, and a server whose `exposure` / `toolExposure` keeps some tools deferred, codemode-only, or hidden adds `(N configured direct)` so a deliberate `0/N` is not read as a failure.
297
342
  - `OAuth` appears only for servers with an `auth` config: `credentials stored`, `authorization may be required`, or `corrupt state file backed up (re-auth required)` (the corrupt file is backed up and the view still renders; `mcp_status` reports `"not configured"` when `auth` is unset).
298
343
  - A failed server adds one `Hint:` line: `/mcp:auth <name>` (plus `--reset` when stored credentials expired) for a missing/expired authorization, waiting for another Pi process holding the auth lock, or `PI_MCP_DEBUG=1 pi` plus the issue tracker for a connection failure.
299
344
 
@@ -307,11 +352,11 @@ Recent output:
307
352
 
308
353
  ### Connection readiness and active tools
309
354
 
310
- `mcp_status` reports `tools.discovered` and `tools.active` for each server. Connection state `ready` means the MCP handshake and discovery completed. It does not mean that another Pi extension has kept every discovered tool active.
355
+ `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.
311
356
 
312
- `mcp_connect` checks current tool activation before reporting success, including when the server is already connected. If discovered tools are inactive, it reports that condition instead of overriding another extension's tool restrictions. 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.
357
+ `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.
313
358
 
314
- Tool discovery follows the same rule. When a connected server announces `notifications/tools/list_changed`, only the tools it newly exposes 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, and a refresh that discovers nothing new does not touch the active set at all. Stopping a connected server (`/mcp:stop`, background recovery, or session teardown) deactivates its tools and forgets those remembered states, so the next connect or reconnect activates the whole discovered set again.
359
+ 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).
315
360
 
316
361
  ## Debug log
317
362
 
@@ -451,12 +496,12 @@ npm pack --dry-run
451
496
  ### Testing
452
497
 
453
498
  The test suite includes:
454
- - **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_DIR` resolution, global/project merge, project trust boundary (`ctx.isProjectTrusted()`), Pi 1.3.0 `enabled: false` and partial project overrides, `stdio` `cwd`, `oauth.clientName`, Pi 1.x schema aliases (`type: "http"`, URL-only HTTP, `oauth`, `timeout`), and dynamic `pi.getMcpServers()` / `mcp_servers_change`
499
+ - **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_DIR` resolution, global/project merge, project trust boundary (`ctx.isProjectTrusted()`), Pi 1.3.0 `enabled: false`, `autoEnableCodemode`, `exposure` / `toolExposure`, and partial project overrides, `stdio` `cwd`, `oauth.clientName`, Pi 1.x schema aliases (`type: "http"`, URL-only HTTP, `oauth`, `timeout`), and dynamic `pi.getMcpServers()` / `mcp_servers_change`
455
500
  - **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 PID `SIGKILL` safety net, health check, concurrent connect/reset coordination, and cancellation
456
501
  - **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
457
- - **Tool bridge, status diagnostics & debug log** (`tests/tool-bridge.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 (`allOf` object inference, `$ref` cycle protection, union `null` ordering), name sanitization, image content passthrough, `isError` filtering, activate/deactivate, `notifications/progress` forwarding (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 redacted `PI_MCP_DEBUG=1` JSONL logging
502
+ - **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 (`allOf` object inference, `$ref` cycle protection, union `null` ordering), name sanitization, Pi 1.3.0 `exposure` / `toolExposure` resolution, peer-disambiguated namespaces, `<mcp_servers>` prompt rendering, `_pendingToolNames` and `/reload` session preservation, image content passthrough, `isError` filtering and Pi 1.3.0+ structured error outcomes, activate/deactivate, `notifications/progress` forwarding (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 redacted `PI_MCP_DEBUG=1` JSONL logging
458
503
  - **Resource bridge** (`tests/resource-bridge.test.ts`) — paginated `resources/list` / `resources/templates/list`, `-32601` degradation, catalog caching with `notifications/resources/list_changed` invalidation, stale in-flight discard, text/image/binary `resources/read` conversion, abort/timeout/401 mapping, `mcp_list_resources` / `mcp_read_resource`, and `/mcp:resources`
459
- - **Property-based fuzzing** (`tests/fuzz.test.ts`) — `fast-check` properties covering JSONC comment stripping, callback/redirect URL validation, `WWW-Authenticate` challenge parsing, JSON Schema → TypeBox conversion, tool naming, terminal/log secret sanitization, custom header merging, and read-batch transport message/close ordering
504
+ - **Property-based fuzzing** (`tests/fuzz.test.ts`) — `fast-check` properties covering JSONC comment stripping, callback/redirect URL validation, `WWW-Authenticate` challenge 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
460
505
  - **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
461
506
  - **End-to-end integration** — Real mock MCP and OAuth servers over `stdio` and HTTP with tool discovery and execution
462
507
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mcp-extension",
3
- "version": "1.15.3",
3
+ "version": "1.16.1",
4
4
  "description": "Full-featured, lightweight MCP extension for the Pi coding agent: stdio, SSE & Streamable HTTP transports, OAuth 2.1 (PKCE + DCR), lazy/eager lifecycles — minimal dependencies, zero bloat.",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -5,13 +5,13 @@
5
5
  */
6
6
 
7
7
  import { McpError } from "./errors.js";
8
+ import { normalizeExposureAlias } from "./tool-exposure.js";
8
9
 
9
10
  /**
10
11
  * Keys a Pi 1.3.0 project entry may override on the global entry of the same name (`/mcp` writes
11
12
  * such an entry as soon as a global server is disabled or its exposure is changed for one project).
12
- * `exposure` / `toolExposure` are Pi-native tool-exposure settings: they are accepted so a shared
13
- * `mcp.json` loads, and ignored because this extension decides tool activation itself. `lifecycle`
14
- * is this extension's equivalent of `enabled`.
13
+ * `exposure` / `toolExposure` are Pi-native tool-exposure settings and are honored by the tool
14
+ * bridge; `lifecycle` is this extension's equivalent of `enabled`.
15
15
  */
16
16
  export const PROJECT_OVERRIDE_KEYS = ["enabled", "exposure", "toolExposure", "lifecycle"] as const;
17
17
 
@@ -91,6 +91,21 @@ function normalizeTimeoutAlias(obj: Record<string, unknown>): void {
91
91
  obj.requestTimeoutMs = obj.timeout * 1000;
92
92
  }
93
93
 
94
+ /**
95
+ * Map Pi's retired `codemode-deferred` exposure alias onto `codemode`, on the server `exposure`
96
+ * and on every `toolExposure` value. Pi accepts the alias in shared configs, so a config Pi
97
+ * wrote must not fail validation here.
98
+ */
99
+ function normalizeExposureAliases(obj: Record<string, unknown>): void {
100
+ if (obj.exposure !== undefined) {
101
+ obj.exposure = normalizeExposureAlias(obj.exposure);
102
+ }
103
+ if (!isPlainObject(obj.toolExposure)) return;
104
+ obj.toolExposure = Object.fromEntries(
105
+ Object.entries(obj.toolExposure).map(([tool, value]) => [tool, normalizeExposureAlias(value)]),
106
+ );
107
+ }
108
+
94
109
  /** Rewrite Pi 1.x config aliases (`type`, `oauth`, `timeout`, `enabled`) before schema validation. */
95
110
  export function normalizeServerConfigAliases(raw: unknown): unknown {
96
111
  if (!isPlainObject(raw)) return raw;
@@ -99,6 +114,7 @@ export function normalizeServerConfigAliases(raw: unknown): unknown {
99
114
  normalizeAuthAlias(obj);
100
115
  normalizeTimeoutAlias(obj);
101
116
  normalizeEnabledAlias(obj);
117
+ normalizeExposureAliases(obj);
102
118
  return obj;
103
119
  }
104
120
 
@@ -138,7 +154,7 @@ function mergeProjectOverride(
138
154
  globalServers: Record<string, unknown>,
139
155
  projectPath: string,
140
156
  ): Record<string, unknown> {
141
- const base = globalServers[name];
157
+ const base = Object.hasOwn(globalServers, name) ? globalServers[name] : undefined;
142
158
  if (!isPlainObject(base)) {
143
159
  throw invalidProjectConfig(
144
160
  projectPath,
package/src/config.ts CHANGED
@@ -25,6 +25,7 @@ import {
25
25
  } from "./config-compat.js";
26
26
  import { McpError } from "./errors.js";
27
27
  import { stripJsonComments } from "./jsonc.js";
28
+ import { MCP_EXPOSURES } from "./tool-exposure.js";
28
29
 
29
30
  // ─── Zod Schemas ──────────────────────────────────────────────────────────────
30
31
 
@@ -139,6 +140,33 @@ const ServerConfigObjectSchema = z.object({
139
140
  * `lifecycle: "lazy"`). Default: `true`.
140
141
  */
141
142
  enabled: z.boolean().optional(),
143
+ /**
144
+ * Pi 1.3.0 tool exposure for every tool this server advertises.
145
+ *
146
+ * `direct` — registered and activated, so the model sees the declaration.
147
+ * `deferred` — registered inactive; `tool_search` can load it on demand.
148
+ * `codemode` — registered inactive; callable from codemode scripts, and loadable by
149
+ * `tool_search` (which then declares it).
150
+ * `hidden` — registered but not exposed to the model at all.
151
+ *
152
+ * Default: `"direct"` (unlike Pi's own `codemode`, so an existing config keeps every
153
+ * discovered tool active).
154
+ */
155
+ exposure: z.enum(MCP_EXPOSURES).optional(),
156
+ /**
157
+ * Pi 1.3.0 per-tool exposure overrides, keyed by the raw MCP tool name (`tools/list`
158
+ * name, not the Pi tool identifier) or a `*` wildcard pattern. An exact key wins, then
159
+ * the first matching pattern in declaration order, then `exposure`.
160
+ *
161
+ * The canonical way to expose only a few tools of a large server:
162
+ * `{ "exposure": "hidden", "toolExposure": { "search_*": "direct" } }`.
163
+ */
164
+ toolExposure: z.record(z.string(), z.enum(MCP_EXPOSURES)).optional(),
165
+ /**
166
+ * Short summary of what the server offers (Pi 1.3.0 `description`). Forwarded on the tool
167
+ * `namespace` for `tool_search` ranking and codemode's `describeNamespace()`.
168
+ */
169
+ description: z.string().optional(),
142
170
  /** Per-request timeout in ms. Overrides global setting. Default: 30000. */
143
171
  requestTimeoutMs: z.number().positive().optional(),
144
172
  /**
@@ -213,6 +241,11 @@ const SettingsSchema = z.object({
213
241
  const McpConfigSchema = z.object({
214
242
  settings: SettingsSchema.default(() => ({ ...DEFAULT_SETTINGS })),
215
243
  mcpServers: z.record(z.string(), ServerConfigSchema).default({}),
244
+ /**
245
+ * Pi 1.3.0 top-level switch (default `true` when omitted): activate the built-in `codemode`
246
+ * tool automatically when a server with `"codemode"` exposure connects.
247
+ */
248
+ autoEnableCodemode: z.boolean().optional(),
216
249
  });
217
250
 
218
251
  /**
@@ -231,6 +264,7 @@ const ProjectSettingsSchema = z.object({
231
264
  const ProjectConfigSchema = z.object({
232
265
  settings: ProjectSettingsSchema.default({}),
233
266
  mcpServers: z.record(z.string(), ServerConfigSchema).default({}),
267
+ autoEnableCodemode: z.boolean().optional(),
234
268
  });
235
269
  type ProjectConfig = z.output<typeof ProjectConfigSchema>;
236
270
 
@@ -350,11 +384,13 @@ function mergeConfigs(
350
384
  const stated = Object.fromEntries(
351
385
  Object.entries(projectCfg.settings).filter(([, v]) => v !== undefined),
352
386
  ) as Partial<Settings>;
387
+ const autoEnableCodemode = projectCfg.autoEnableCodemode ?? globalCfg.autoEnableCodemode;
353
388
  return {
354
389
  // Shallow spread: project settings override global settings per key
355
390
  settings: { ...globalCfg.settings, ...stated },
356
391
  // Per-server override: project server entry completely replaces global entry with same name
357
392
  mcpServers: { ...globalCfg.mcpServers, ...projectCfg.mcpServers },
393
+ ...(autoEnableCodemode === undefined ? {} : { autoEnableCodemode }),
358
394
  };
359
395
  }
360
396
 
@@ -107,6 +107,10 @@ export class ConnectionCoordinator {
107
107
  this.activeCtx = ctx;
108
108
  }
109
109
 
110
+ getActiveContext(): ExtensionContext | undefined {
111
+ return this.activeCtx;
112
+ }
113
+
110
114
  hasConnectAttempt(serverName: string): boolean {
111
115
  return this.connectAttempts.has(serverName);
112
116
  }
package/src/index.ts CHANGED
@@ -29,8 +29,19 @@ import { authorize as runAuthorize } from "./authorize-flow.js";
29
29
  import {
30
30
  DebugLog,
31
31
  isDebugLogEnabled,
32
+ reportDiagnostic,
32
33
  setDebugLog,
33
34
  } from "./debug-log.js";
35
+ import {
36
+ MCP_SERVERS_SECTION,
37
+ renderMcpServersSection,
38
+ type McpPromptServerEntry,
39
+ } from "./mcp-servers-prompt.js";
40
+ import { readClientInstructions } from "./tool-discovery.js";
41
+ import {
42
+ collectConfiguredExposures,
43
+ collectRequiredDiscoveryExposures,
44
+ } from "./tool-exposure.js";
34
45
 
35
46
  export {
36
47
  startupAuthNowOption,
@@ -50,7 +61,11 @@ export default async function (pi: ExtensionAPI, paths: { bootstrapCwd?: string;
50
61
 
51
62
  // ── 2. Initialize bridge components ──────────────────────────────────────
52
63
  const manager = new ServerManager(initialState.config, paths.authStorageDir);
53
- const bridge = new ToolBridge(initialState.config.settings, pi);
64
+ const bridge = new ToolBridge(
65
+ initialState.config.settings,
66
+ pi,
67
+ initialState.config.autoEnableCodemode,
68
+ );
54
69
  const resources = new ResourceBridge();
55
70
  const callbackServer = paths.callbackServer ?? new CallbackServer();
56
71
  const coordinator: ConnectionCoordinator = new ConnectionCoordinator({
@@ -76,6 +91,9 @@ export default async function (pi: ExtensionAPI, paths: { bootstrapCwd?: string;
76
91
  options?.requestTimeoutMs ??
77
92
  server?.config.requestTimeoutMs ??
78
93
  lifecycle.getConfig().settings.requestTimeoutMs;
94
+ // WHY: exposure lives on the server entry, and the manager's refresh options carry only
95
+ // timeouts — resolve it here so a config reload that changes `exposure` / `toolExposure`
96
+ // takes effect on the next discovery instead of being frozen at construction.
79
97
  await bridge.refreshTools(
80
98
  serverName,
81
99
  client,
@@ -83,6 +101,10 @@ export default async function (pi: ExtensionAPI, paths: { bootstrapCwd?: string;
83
101
  {
84
102
  ...options,
85
103
  requestTimeoutMs,
104
+ exposure: server?.config.exposure,
105
+ toolExposure: server?.config.toolExposure,
106
+ description: server?.config.description,
107
+ peerServerNames: manager.getAllServers().map((entry) => entry.name),
86
108
  },
87
109
  );
88
110
  });
@@ -114,12 +136,29 @@ export default async function (pi: ExtensionAPI, paths: { bootstrapCwd?: string;
114
136
  }
115
137
  };
116
138
  bridge.setAuthErrorCallback(handleAuthError);
139
+ const seenDiscoveryWarnings = new Set<string>();
140
+ bridge.setDiscoveryWarningCallback((warning) => {
141
+ if (seenDiscoveryWarnings.has(warning)) return;
142
+ seenDiscoveryWarnings.add(warning);
143
+ reportDiagnostic({
144
+ level: "info",
145
+ event: "tools.discovery_unreachable",
146
+ message: warning,
147
+ });
148
+ const ctx = coordinator.getActiveContext();
149
+ if (ctx?.hasUI) {
150
+ ctx.ui.notify(`pi-mcp: ${warning}`, "warning");
151
+ }
152
+ });
117
153
  // WHY: a resources/* request can be the first call to hit an expired token, so it needs
118
154
  // the same re-authorization path as tools/call.
119
155
  resources.setAuthErrorCallback(handleAuthError);
120
156
 
121
157
  // ── 3. Session lifecycle ──────────────────────────────────────────────────
122
- pi.on("session_start", (_event, ctx: ExtensionContext) => lifecycle.handleSessionStart(ctx));
158
+ pi.on("session_start", (_event, ctx: ExtensionContext) => {
159
+ seenDiscoveryWarnings.clear();
160
+ return lifecycle.handleSessionStart(ctx);
161
+ });
123
162
  // Connect or disconnect MCP servers registered dynamically via pi.registerMcpServer().
124
163
  pi.on("mcp_servers_change", (event, ctx: ExtensionContext) =>
125
164
  lifecycle.handleServersChange(event, ctx),
@@ -132,15 +171,28 @@ export default async function (pi: ExtensionAPI, paths: { bootstrapCwd?: string;
132
171
  const normalizeActiveTools = (): void => {
133
172
  bridge.orderActiveTools();
134
173
  };
135
- pi.on("session_tree", normalizeActiveTools);
174
+ pi.on("session_tree", () => {
175
+ restoreSessionTreeTools(manager, bridge);
176
+ });
136
177
  pi.on("input", normalizeActiveTools);
137
- pi.on("before_agent_start", normalizeActiveTools);
178
+ pi.on("before_agent_start", (event) => {
179
+ bridge.orderActiveTools();
180
+ // WHY: read `pi.getActiveTools()` rather than `event.systemPromptOptions?.selectedTools` — an
181
+ // earlier `before_agent_start` handler may have called `pi.setActiveTools(...)`, which Pi only
182
+ // folds back into `systemPromptOptions.selectedTools` after all handlers finish.
183
+ syncMcpServersPromptSection(event?.systemPromptOptions?.sections, manager, bridge, pi);
184
+ });
138
185
  pi.on("tool_execution_end", normalizeActiveTools);
139
186
  pi.on("before_provider_request", (event) => bridge.orderPayloadTools(event.payload));
140
187
 
141
- pi.on("session_shutdown", (_event, ctx: ExtensionContext) =>
142
- lifecycle.handleSessionShutdown(ctx),
143
- );
188
+ pi.on("session_shutdown", async (event, ctx: ExtensionContext) => {
189
+ bridge.setReloadShutdown(event?.reason === "reload");
190
+ try {
191
+ await lifecycle.handleSessionShutdown(ctx);
192
+ } finally {
193
+ bridge.setReloadShutdown(false);
194
+ }
195
+ });
144
196
 
145
197
  // ── 4. Slash commands ───────────────────────────────────────────────────
146
198
  const getProvenance = (): ConfigProvenance => lifecycle.getProvenance();
@@ -164,6 +216,56 @@ export default async function (pi: ExtensionAPI, paths: { bootstrapCwd?: string;
164
216
  registerManagementTools(pi, { manager, coordinator, bridge, resources, getProvenance });
165
217
  }
166
218
 
219
+ function restoreSessionTreeTools(manager: ServerManager, bridge: ToolBridge): void {
220
+ // WHY: `/tree` runs `AgentSession._restoreToolsFromTranscript()`, which resets `activeTools` to
221
+ // the target turn's declared loadout. If an indirect (`codemode` / `deferred`) server was added
222
+ // or started after that turn, re-ensuring reaching discovery tools keeps its tools reachable
223
+ // without re-activating `direct` tools that the restored branch did not declare (#257, #278).
224
+ bridge.ensureDiscoveryTools(
225
+ collectRequiredDiscoveryExposures(
226
+ manager.getAllServers().map((server) => server.config),
227
+ bridge.getConnectedExposures(),
228
+ ),
229
+ );
230
+ bridge.orderActiveTools();
231
+ }
232
+
233
+ function buildPromptServerEntry(server: ManagedServer, bridge: ToolBridge): McpPromptServerEntry {
234
+ const connected = server.state === "ready" && bridge.isServerActive(server.name);
235
+ const instructions = connected && server.client ? readClientInstructions(server.client) : undefined;
236
+ return {
237
+ name: server.name,
238
+ enabled: server.config.enabled,
239
+ connected,
240
+ exposures: connected
241
+ ? bridge.getServerExposures(server.name)
242
+ : collectConfiguredExposures([server.config]),
243
+ description: server.config.description,
244
+ instructions,
245
+ };
246
+ }
247
+
248
+ function syncMcpServersPromptSection(
249
+ sections: Record<string, string> | undefined,
250
+ manager: ServerManager,
251
+ bridge: ToolBridge,
252
+ pi: ExtensionAPI,
253
+ ): void {
254
+ if (!sections) return;
255
+ const allTools = typeof pi.getAllTools === "function" ? pi.getAllTools() : undefined;
256
+ const section = renderMcpServersSection({
257
+ servers: manager.getAllServers().map((server) => buildPromptServerEntry(server, bridge)),
258
+ toolPrefix: bridge.getToolPrefix(),
259
+ activeTools: pi.getActiveTools(),
260
+ allTools,
261
+ });
262
+ if (section !== undefined) {
263
+ sections[MCP_SERVERS_SECTION] = section;
264
+ } else {
265
+ delete sections[MCP_SERVERS_SECTION];
266
+ }
267
+ }
268
+
167
269
  function isClientActive(
168
270
  manager: ServerManager,
169
271
  serverName: string,