pi-mcp-extension 1.11.7 → 1.11.9

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
@@ -1,10 +1,11 @@
1
- # pi-mcp-extension
1
+ # <img src="https://raw.githubusercontent.com/irahardianto/pi-mcp-extension/main/docs/icon.svg" width="32" height="32" align="top" alt="" /> pi-mcp-extension
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/pi-mcp-extension.svg)](https://www.npmjs.com/package/pi-mcp-extension)
4
+ [![npm downloads](https://img.shields.io/npm/dm/pi-mcp-extension.svg)](https://www.npmjs.com/package/pi-mcp-extension)
4
5
  [![license](https://img.shields.io/npm/l/pi-mcp-extension.svg)](https://github.com/irahardianto/pi-mcp-extension/blob/main/LICENSE)
5
- [![CI](https://github.com/irahardianto/pi-mcp-extension/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/irahardianto/pi-mcp-extension/actions/workflows/ci.yml)
6
+ [![CI](https://github.com/irahardianto/pi-mcp-extension/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/irahardianto/pi-mcp-extension/actions/workflows/ci.yml)<br>
6
7
  [![Code Coverage](https://qlty.sh/gh/irahardianto/projects/pi-mcp-extension/coverage.svg)](https://qlty.sh/gh/irahardianto/projects/pi-mcp-extension)
7
- [![Maintainability](https://qlty.sh/gh/irahardianto/projects/pi-mcp-extension/maintainability.svg)](https://qlty.sh/gh/irahardianto/projects/pi-mcp-extension)<br>
8
+ [![Maintainability](https://qlty.sh/gh/irahardianto/projects/pi-mcp-extension/maintainability.svg)](https://qlty.sh/gh/irahardianto/projects/pi-mcp-extension)
8
9
  [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/irahardianto/pi-mcp-extension/badge)](https://scorecard.dev/viewer/?uri=github.com/irahardianto/pi-mcp-extension)
9
10
  [![OpenSSF Best Practices](https://www.bestpractices.dev/projects/15659/badge)](https://www.bestpractices.dev/projects/15659)
10
11
 
@@ -12,44 +13,36 @@
12
13
 
13
14
  `pi-mcp-extension` is a production-ready [Model Context Protocol](https://modelcontextprotocol.io/) client extension for the [Pi coding agent](https://pi.dev). It manages server connections, discovers tools, and bridges them into Pi so the LLM can call them directly.
14
15
 
16
+ [Quick Start](#quick-start) · [Configuration](#configuration) · [OAuth 2.1](#oauth-config) · [Commands & Agent Tools](#commands) · [Debug Log](#debug-log) · [How It Works](#how-it-works) · [MCP Spec Compliance](#mcp-spec-compliance)
17
+
15
18
  ## Features
16
19
 
17
20
  - **Multi-transport** — `stdio` subprocesses, `streamable-http` (including `"http"` and URL-only shorthand), and legacy `sse` out of the box
18
21
  - **Auto-discovery** — Paginated `tools/list` with cursor following (MCP 2025-03-26 spec)
19
22
  - **Live tool refresh** — `notifications/tools/list_changed` triggers re-discovery without restart
20
23
  - **Clean cancellation** — `AbortSignal` propagation via `notifications/cancelled`
21
- - **Smart reconnection** — Fixed delay retry schedule (1s → 3s → 5s → 10s → 30s), configurable max retries, and automatic recovery when a server transport closes unexpectedly
24
+ - **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_scope` detection that invalidates stale tokens and prompts for re-authorization
22
25
  - **Health checks** — Opt-in periodic pings to detect stale connections
23
- - **Safe process lifecycle** — Child PID tracking (`StdioClientTransport.pid`) 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
24
- - **Stable tool names** — Sanitized, collision-avoiding names (max 64 chars) that stay constant across reconnects
26
+ - **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
27
+ - **Stable tool names** — Sanitized, collision-avoiding names (`<prefix>_<server>_<tool>`, max 64 chars) that stay constant across reconnects
25
28
  - **No tool churn** — Activate/deactivate pattern ensures tools don't flicker during reconnection
26
- - **Layered config & trust boundary** — Global `<agent dir>/mcp.json`, project `.pi/mcp.json` (loaded only in trusted projects via `ctx.isProjectTrusted()`, including Pi 1.3.0 partial overrides), and Pi 1.x extension-registered servers (`pi.registerMcpServer()`)
27
- - **Rich tool results & annotations** — MCP `image` content passthrough (`ImageContent`), plus `readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint` surfaced in tool descriptions
29
+ - **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()`)
30
+ - **Rich tool results & annotations** — MCP `text`, `image` (`ImageContent`), `structuredContent`, embedded `resource` text/blobs, and `audio` fallback descriptions, plus `readOnlyHint`, `destructiveHint`, `idempotentHint`, and `openWorldHint` surfaced in tool descriptions
28
31
  - **On-demand agent tools & commands** — `mcp_status` and `mcp_connect` agent tools plus `/mcp`, `/mcp <name>` (with config provenance and failure hints), `/mcp:start`, `/mcp:stop`, and `/mcp:auth` slash commands with server-name autocomplete
29
32
  - **Structured error handling** — Distinct error codes (`config`, `connection`, `auth`, `timeout`, `protocol`, `tool`) and actionable failure hints
30
33
  - **Redacted debug logging** — Opt-in `PI_MCP_DEBUG=1` JSON Lines log (`<agent dir>/logs/pi-mcp.log`, `0600`, ~2 MB rotation) with automatic secret masking and zero TUI `stderr` noise
31
34
  - **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](./OAUTH.md))
32
35
 
33
- ## Installation
34
-
35
- ```bash
36
- pi install npm:pi-mcp-extension
37
- ```
38
-
39
- Or try without installing:
40
-
41
- ```bash
42
- pi -e npm:pi-mcp-extension
43
- ```
44
-
45
36
  ## Quick Start
46
37
 
47
- 1. Install the extension:
38
+ > **Prerequisite:** Node.js 22+ and the [Pi coding agent](https://pi.dev).
39
+
40
+ 1. **Install the extension** (or run once without installing via `pi -e npm:pi-mcp-extension`):
48
41
  ```bash
49
42
  pi install npm:pi-mcp-extension
50
43
  ```
51
44
 
52
- 2. *(Pi 1.x)* Disable Pi's built-in `mcp` extension so Pi does not warn that both extensions are enabled at the same time — either run `pi config` and uncheck `mcp` under **Built-in extensions**, or add `"extensions": ["-builtin:mcp"]` to `~/.pi/agent/settings.json`:
45
+ 2. *(Pi 1.x)* **Disable Pi's built-in `mcp` extension** so Pi does not warn that both extensions are enabled at the same time — either run `pi config` and uncheck `mcp` under **Built-in extensions**, or add `"extensions": ["-builtin:mcp"]` to `~/.pi/agent/settings.json`:
53
46
  ```jsonc
54
47
  {
55
48
  "extensions": [
@@ -58,20 +51,30 @@ pi -e npm:pi-mcp-extension
58
51
  }
59
52
  ```
60
53
 
61
- 3. Create a config file at `~/.pi/agent/mcp.json` (global) or `.pi/mcp.json` (project-level). Both files support **JSONC** (`//` line and `/* ... */` block comments):
54
+ 3. **Create a config file** at `~/.pi/agent/mcp.json` (global) or `.pi/mcp.json` (trusted project). Both files support **JSONC** (`//` line and `/* ... */` block comments):
62
55
  ```jsonc
63
56
  {
64
57
  "mcpServers": {
58
+ // Remote HTTP server with OAuth 2.1 (prompts "Authorize now" on startup)
65
59
  "supabase": {
66
60
  "transport": "streamable-http",
67
61
  "url": "https://mcp.supabase.com/mcp",
62
+ "auth": {
63
+ "type": "oauth"
64
+ },
68
65
  "lifecycle": "eager"
66
+ },
67
+ // Local stdio subprocess server (connects on demand via /mcp:start or mcp_connect)
68
+ "context7": {
69
+ "command": "npx",
70
+ "args": ["-y", "@context7/mcp"],
71
+ "lifecycle": "lazy"
69
72
  }
70
73
  }
71
74
  }
72
75
  ```
73
76
 
74
- 4. Start Pi — your MCP tools are ready. Use `/mcp` to check all servers or `/mcp <name>` to inspect one in detail.
77
+ 4. **Start Pi** — your MCP tools are ready. Use `/mcp` to check all servers or `/mcp <name>` to inspect one in detail.
75
78
 
76
79
  ## Configuration
77
80
 
@@ -85,6 +88,8 @@ Servers can be configured via JSON/JSONC files (`//` and `/* */` comments are su
85
88
 
86
89
  ### Full Example
87
90
 
91
+ See also [`examples/mcp.json.example`](./examples/mcp.json.example) for a copy-ready template.
92
+
88
93
  ```jsonc
89
94
  {
90
95
  "settings": {
@@ -94,7 +99,7 @@ Servers can be configured via JSON/JSONC files (`//` and `/* */` comments are su
94
99
  },
95
100
  "mcpServers": {
96
101
 
97
- // ── HTTP-based servers ───────────────────────────────────────────────────
102
+ // ── HTTP servers with OAuth 2.1 ──────────────────────────────────────────
98
103
  "supabase": {
99
104
  "transport": "streamable-http",
100
105
  "url": "https://mcp.supabase.com/mcp",
@@ -105,9 +110,22 @@ Servers can be configured via JSON/JSONC files (`//` and `/* */` comments are su
105
110
  },
106
111
  "deepsource": {
107
112
  "url": "https://mcp.deepsource.com/mcp", // "transport" defaults to "streamable-http" when "url" is set
113
+ "auth": {
114
+ "type": "oauth"
115
+ },
108
116
  "lifecycle": "eager"
109
117
  },
110
118
 
119
+ // ── HTTP servers with static API key / Bearer headers ────────────────────
120
+ "zai-web-search": {
121
+ "transport": "streamable-http",
122
+ "url": "https://api.z.ai/api/mcp/web_search_prime/mcp",
123
+ "headers": {
124
+ "Authorization": "Bearer YOUR_ZAI_API_KEY"
125
+ },
126
+ "lifecycle": "lazy"
127
+ },
128
+
111
129
  // ── Legacy SSE servers ───────────────────────────────────────────────────
112
130
  "legacy-server": {
113
131
  "transport": "sse",
@@ -153,7 +171,14 @@ In project-level `.pi/mcp.json`, `settings` keys carry no defaults — only the
153
171
 
154
172
  ### Per-Server Config
155
173
 
156
- For Pi 1.x compatibility, server entries also accept `type` as an alias for `transport`, `"http"` as an alias for `"streamable-http"`, `oauth` as an alias for `auth`, `timeout` (in seconds) as an alias for `requestTimeoutMs`, and `enabled: false` as a request to keep the server out of the eager set (`lifecycle: "lazy"`). Pi's `auth.provider` (`/login` provider token) is **rejected** at load time instead of being silently downgraded to OAuth 2.1 — use `auth` (OAuth) or static `headers`.
174
+ For Pi 1.x / 1.3.0 compatibility, server entries also accept:
175
+ - `type` as an alias for `transport`, and `"http"` as an alias for `"streamable-http"`
176
+ - `oauth` as an alias for `auth`
177
+ - `timeout` (in seconds) as an alias for `requestTimeoutMs`
178
+ - `enabled: false` to keep the server configured but out of the eager set (normalized to `lifecycle: "lazy"`, even if `lifecycle: "eager"` is also set)
179
+
180
+ > [!NOTE]
181
+ > Pi's `auth.provider` (`/login` provider token) is **rejected** at load time with a `config` error instead of being silently downgraded to OAuth 2.1 — use `auth` (OAuth 2.1) or static `headers`.
157
182
 
158
183
  | Field | Type | Default | Description |
159
184
  |---|---|---|---|
@@ -207,16 +232,31 @@ Server-name arguments provide autocomplete suggestions from the configured MCP s
207
232
  | `/mcp <name>` | Show detailed status for one server: config source, transport/lifecycle, tool activation, OAuth credential status, failure hint, and stderr log |
208
233
  | `/mcp:start <name>` | Connect a server and wait for tool discovery |
209
234
  | `/mcp:stop <name>` | Cancel a pending connection, startup prompt, or authorization, or stop a running server and deactivate its tools |
210
- | `/mcp:auth <name>` | Connect with stored OAuth credentials and client registration; request browser authorization only if needed |
211
- | `/mcp:auth <name> --reset` | Discard stored tokens and client registration (re-running Dynamic Client Registration) and request fresh authorization |
235
+ | `/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 |
236
+ | `/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>`) |
212
237
 
213
238
  In addition to user slash commands, two built-in **agent tools** let the LLM inspect and connect configured servers directly:
214
239
 
215
240
  | Agent Tool | Parameters | Description |
216
241
  |---|---|---|
217
- | `mcp_status` | `{}` | List configured servers with `lifecycle`, `state`, `tools` (`discovered` / `active`), `auth` credential presence, `source` (`global` / `project` / `extension`), and safe `error` action hints (never returns tokens, headers, or authorization URLs) |
242
+ | `mcp_status` | `{}` | List configured servers with `lifecycle`, `state`, `tools` (`discovered` / `active`), `auth` credential summary, `source` (`"global"` / `"project"` / `"extension"` / `"unknown"`), and safe `error` action hints (never returns tokens, headers, or authorization URLs) |
218
243
  | `mcp_connect` | `{ name: string }` | Connect one named server, run interactive OAuth if needed, and verify that discovered tools are active before returning success (returns fixed actionable categories on failure instead of raw server response text) |
219
244
 
245
+ `mcp_status` returns a JSON array of [`ServerStatusRow`](./src/server-status.ts) objects:
246
+
247
+ ```json
248
+ [
249
+ {
250
+ "name": "supabase",
251
+ "lifecycle": "eager",
252
+ "state": "ready",
253
+ "tools": { "discovered": 12, "active": 12 },
254
+ "auth": "credentials stored",
255
+ "source": "global"
256
+ }
257
+ ]
258
+ ```
259
+
220
260
  ### Inspecting one server (`/mcp <name>`)
221
261
 
222
262
  `/mcp <name>` answers "why is this server in this state?" without leaving Pi:
@@ -237,10 +277,10 @@ Recent output:
237
277
  (no stderr output from supabase)
238
278
  ```
239
279
 
240
- - `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.
280
+ - `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).
241
281
  - 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.
242
282
  - `Tools` compares discovered tools with the ones Pi has active; a server can be `ready` with `0/N active` when another extension restricts tools.
243
- - `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).
283
+ - `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).
244
284
  - 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.
245
285
 
246
286
  ### OAuth startup, headless/SSH, and concurrency behavior
@@ -274,7 +314,12 @@ The log is written to `<agent dir>/logs/pi-mcp.log` (JSON Lines, one event per l
274
314
  - **Off by default.** Without `PI_MCP_DEBUG=1` no log file is created.
275
315
  - **Private.** The directory is `0o700` and the file is `0o600`, like the OAuth credential files.
276
316
  - **Bounded.** The file is rotated to `pi-mcp.log.1` at ~2 MB; a single backup is kept.
277
- - **Redacted.** Only allow-listed field names are recorded, and a final pass masks anything that looks like a token (`access_token`, `refresh_token`, `client_secret`, `code=`, `code_verifier`, `Authorization:` / `Bearer …`).
317
+ - **Redacted.** Only allow-listed field names are recorded, and a delimiter-aware pass masks anything that looks like a credential:
318
+ - OAuth tokens, authorization codes, and PKCE verifiers
319
+ - API keys and other JSON or key/value secrets (`api_key`, `x-api-key`, `private_key`, `password`, `secret`, `token`, and prefixed forms such as `db_password` or `aws_secret_access_key`)
320
+ - Credential-bearing query parameters on a server URL (`?api_key=…`, `?token=…`, `?code=…`)
321
+ - `Authorization` headers in any scheme or quoting, and URL userinfo passwords (`https://user:password@host`)
322
+ - The same redactor protects the per-server `Recent output:` (`stderr`) buffer, the `Last error:` line in `/mcp` and `/mcp <name>`, and user-facing start/auth/recovery failure notifications.
278
323
  - **Best-effort.** A failed log write never breaks a connection or a tool call.
279
324
 
280
325
  Attach the file to a bug report. It contains no credentials.
@@ -283,53 +328,45 @@ While a Pi UI is active, the extension never writes diagnostics to Pi's stderr (
283
328
 
284
329
  ## How It Works
285
330
 
286
- ```text
287
- ┌─────────────────────────────────────────────────────────────────────────┐
288
- │ Pi Agent (TUI / RPC, ExtensionAPI) │
289
- │ │
290
- │ ┌────────────────────┐ ┌────────────────────────┐ │
291
- │ │ index.ts │───▶│ register-commands │ (/mcp, :start, │
292
- │ │ (entry & mcp_* │ │ (/mcp* slash commands) │ :stop, :auth) │
293
- │ │ agent tools) │ └───────────┬────────────┘ │
294
- │ └────┬──────────┬────┘ │ │
295
- │ │ └──────────────┐ │ │
296
- │ │ ▼ ▼ │
297
- │ │ ┌────────────────────────┐ │
298
- │ │ │ connection-coordinator │ │
299
- │ │ │ (in-flight connects, │ │
300
- │ │ │ authQueue, teardown) │ │
301
- │ │ └───────────┬────────────┘ │
302
- │ │ │ │
303
- │ │ ▼ │
304
- │ │ ┌────────────────────────┐ ┌───────────┐ │
305
- │ │ │ server-manager │───▶│tool-bridge│ │
306
- │ │ │ (stopped → starting │ │(MCP → Pi) │ │
307
- │ │ │ → ready lifecycle) │ └─────┬─────┘ │
308
- │ ▼ └───────────┬────────────┘ │ │
309
- │ ┌────────────────────┐ ▼ ▼ │
310
- │ │ config │ ┌────────────────────────┐ ┌───────────┐ │
311
- │ │ (Zod + JSONC) │ │ transport-factory & │ │ TypeBox │ │
312
- │ └────────┬───────────┘ │ oauth-provider (SDK) │ │ (schema) │ │
313
- │ │ └───────────┬────────────┘ └───────────┘ │
314
- └───────────┼────────────────────────────┼────────────────────────────────┘
315
- │ │
316
- ▼ ▼
317
- Global/Project mcp.json ┌──────────────┐
318
- + Registered Extensions │ MCP Servers │
319
- │ (stdio/http) │
320
- └──────────────┘
331
+ ```mermaid
332
+ flowchart TD
333
+ subgraph Pi["Pi Coding Agent (TUI / RPC, ExtensionAPI)"]
334
+ Entry["index.ts (entry & mcp_* agent tools)"]
335
+ Cmds["register-commands (/mcp, :start, :stop, :auth)"]
336
+ Config["config (Zod + JSONC)"]
337
+ Coord["connection-coordinator (in-flight connects, authQueue, teardown)"]
338
+ Mgr["server-manager (stopped -> starting -> ready lifecycle)"]
339
+ Bridge["tool-bridge (MCP -> Pi tools)"]
340
+ Schema["schema-convert (JSON Schema -> TypeBox)"]
341
+ Transport["transport-factory & oauth-provider (MCP SDK)"]
342
+
343
+ Entry --> Cmds
344
+ Entry --> Config
345
+ Entry --> Coord
346
+ Cmds --> Coord
347
+ Coord --> Mgr
348
+ Mgr --> Bridge
349
+ Bridge --> Schema
350
+ Mgr --> Transport
351
+ end
352
+
353
+ Sources[("Global & Project mcp.json + Registered Extensions")]
354
+ Servers["MCP Servers (stdio / streamable-http / sse)"]
355
+
356
+ Config --> Sources
357
+ Transport <--> Servers
321
358
  ```
322
359
 
323
360
  1. **Config is loaded** from global `<agent dir>/mcp.json`, trusted project `.pi/mcp.json` (checked via `ctx.isProjectTrusted()` on `session_start`), and extension-registered servers (`pi.getMcpServers()` / `mcp_servers_change`), with `mcp.json` taking precedence over extension-registered servers and project entries overriding global ones
324
361
  2. **Eager servers connect** at `session_start` via `ConnectionCoordinator` (offering a sequential `Authorize now` / `Not now` prompt when an eager OAuth server needs authorization in an interactive session); lazy servers wait for `mcp_connect`, `/mcp:start`, or `/mcp:auth`
325
362
  3. **Tools are discovered** via paginated `tools/list` calls (cursor-based, up to 100 pages) before a server enters `ready`
326
363
  4. **JSON Schema → TypeBox** conversion registers tools with Pi-compatible parameter schemas (preserving nullable union ordering, resolving `$ref`s cycle-safely, and inferring/flattening `allOf` object schemas)
327
- 5. **Pi tools are registered** as `<prefix>_<server>_<tool>` (sanitized, max 64 chars with hash suffix) and pass through text and `image` content blocks (`ImageContent`)
364
+ 5. **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 MCP `text`, `image` (`ImageContent`), `structuredContent`, `resource`, and `audio` results
328
365
  6. **Tools activate/deactivate** automatically as servers connect/disconnect
329
366
  7. **AbortSignal** is wired through to `notifications/cancelled` for clean cancellation
330
- 8. **Reconnection & recovery** uses a fixed delay schedule with configurable max retries on initial failure, health check failure, or unexpected transport close (`client.onclose`)
367
+ 8. **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 HTTP `401` / `403 insufficient_scope` invalidates stale tokens and surfaces a re-authorization hint
331
368
  9. **`list_changed` notifications** trigger re-discovery, deactivating stale tools automatically
332
- 10. **Session shutdown** cancels pending auth/connection flows, stops the callback server, deactivates all tools, flushes the debug log, and cleanly stops all servers (with a `SIGKILL` safety net for `stdio` child processes)
369
+ 10. **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` and pipe cleanup for `stdio` child processes)
333
370
 
334
371
  ## MCP Spec Compliance
335
372
 
@@ -343,7 +380,7 @@ Implements the **MCP 2025-03-26** specification for tool clients:
343
380
  | `sse` transport (legacy backwards compat) | ✅ |
344
381
  | OAuth 2.1 authorization (PKCE S256, RFC 9728 Protected Resource Metadata, RFC 7591 DCR) | ✅ |
345
382
  | Cursor-based `tools/list` pagination | ✅ |
346
- | `tools/call` with parameters & `image` content (`ImageContent`) passthrough | ✅ |
383
+ | `tools/call` with parameters, `image` (`ImageContent`), `structuredContent`, and `resource` conversion | ✅ |
347
384
  | `roots/list` capability (workspace root) | ✅ |
348
385
  | `notifications/tools/list_changed` (live refresh) | ✅ |
349
386
  | `notifications/cancelled` (AbortSignal) | ✅ |
@@ -360,6 +397,8 @@ See [CONTRIBUTING.md](./CONTRIBUTING.md) for setup, workflow, and the pre-merge
360
397
 
361
398
  ## Development
362
399
 
400
+ Requires **Node.js 22+**.
401
+
363
402
  ```bash
364
403
  # Install dependencies (clean lockfile install)
365
404
  npm ci
@@ -376,7 +415,7 @@ npm test
376
415
  # Run all test suites with coverage floor (95% lines / 85% branches / 83% functions)
377
416
  npm run test:coverage
378
417
 
379
- # Run integration tests only (real stdio server)
418
+ # Run a single test suite (e.g. server lifecycle & stdio integration)
380
419
  npm run test:integration
381
420
 
382
421
  # Verify npm tarball contents
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mcp-extension",
3
- "version": "1.11.7",
3
+ "version": "1.11.9",
4
4
  "description": "MCP (Model Context Protocol) client extension for the Pi coding agent — connect Pi to any MCP server",
5
5
  "type": "module",
6
6
  "keywords": [
package/src/auth-lock.ts CHANGED
@@ -23,6 +23,7 @@ import { hostname as osHostname } from "node:os";
23
23
  import { join } from "node:path";
24
24
  import { createHash, randomUUID } from "node:crypto";
25
25
  import { agentDir } from "./config.js";
26
+ import { describeError, reportDiagnostic } from "./debug-log.js";
26
27
  import {
27
28
  formatHolderDetails,
28
29
  HEARTBEAT_MS,
@@ -157,29 +158,37 @@ export function createDefaultAuthLockDeps(): AuthLockDeps {
157
158
 
158
159
  const MAX_ACQUIRE_ATTEMPTS = 3;
159
160
 
161
+ /** Yield across microtasks (and briefly on the real fs) while a peer finishes its restore. */
162
+ async function yieldForPeerRestore(usingRealFs: boolean, attempt: number): Promise<void> {
163
+ await Promise.resolve();
164
+ await Promise.resolve();
165
+ if (usingRealFs && attempt === 1) {
166
+ await new Promise<void>((resolve) => setTimeout(resolve, 5));
167
+ }
168
+ }
169
+
170
+ /** Read the lock record, retrying while a peer may have the file briefly out of place. */
160
171
  async function readLockRecordWithRetry(
161
172
  fs: AuthLockFs,
162
173
  path: string,
163
174
  usingRealFs = false,
164
175
  ): Promise<LockRecord | null> {
165
176
  for (let i = 0; i < 3; i++) {
177
+ let record: LockRecord | null = null;
166
178
  try {
167
- const raw = await fs.readFile(path, "utf8");
168
- return parseLockRecord(raw);
169
- } catch (err) {
170
- if ((err as NodeJS.ErrnoException).code === "ENOENT" && i < 2) {
171
- // WHY: During stale-lock inspection, a contender briefly renames `path` to
172
- // `movedPath` and restores it via `link(movedPath, path)` on nonce mismatch.
173
- // Yield across microtasks (and a brief macrotask on real fs) before treating ENOENT as genuine lock loss.
174
- await Promise.resolve();
175
- await Promise.resolve();
176
- if (usingRealFs && i === 1) {
177
- await new Promise<void>((resolve) => setTimeout(resolve, 5));
178
- }
179
- continue;
180
- }
181
- return null;
179
+ record = parseLockRecord(await fs.readFile(path, "utf8"));
180
+ } catch {
181
+ // WHY: A missing or unreadable file is indistinguishable from a peer's in-flight restore
182
+ // on a single read; the retry below decides whether the lock is really gone.
182
183
  }
184
+ if (record !== null) return record;
185
+ if (i === 2) return null;
186
+ // WHY: During stale-lock inspection a contender briefly renames `path` to `movedPath` and
187
+ // restores it via `link()` — or, where hard links are unsupported, re-creates it with an
188
+ // exclusive write that publishes the file empty for an instant. Both read as "no lock"
189
+ // here, so retry across microtasks (and a brief macrotask on the real fs) before
190
+ // concluding the lock is genuinely gone.
191
+ await yieldForPeerRestore(usingRealFs, i);
183
192
  }
184
193
  return null;
185
194
  }
@@ -395,16 +404,112 @@ async function isSameStaleCandidate(
395
404
  }
396
405
  }
397
406
 
398
- /** Restore a contender's fresh lock file, then clean up the temporary candidate path. */
399
- async function restoreCandidate(movedPath: string, path: string, deps: AuthLockDeps): Promise<void> {
400
- await deps.fs.link(movedPath, path).catch(() => {
401
- // WHY: Best-effort restore of contender's fresh lock file if path was not already recreated.
402
- });
407
+ /** Remove the temporary stale-check file; an already-removed candidate is not a failure. */
408
+ async function unlinkCandidate(movedPath: string, deps: AuthLockDeps): Promise<void> {
403
409
  await deps.fs.unlink(movedPath).catch(() => {
404
410
  // WHY: Best-effort cleanup of temporary stale-check file.
405
411
  });
406
412
  }
407
413
 
414
+ /**
415
+ * Give up on a candidate that cannot be put back, and say so.
416
+ *
417
+ * The displaced holder finds out on its next heartbeat and aborts with `Authorization lock
418
+ * lost`; nothing in this module ever reads a `<path>.stale-*` file again, so leaving the
419
+ * candidate behind would only accumulate orphans in the auth directory.
420
+ */
421
+ async function abandonCandidate(
422
+ serverName: string,
423
+ movedPath: string,
424
+ err: unknown,
425
+ deps: AuthLockDeps,
426
+ ): Promise<void> {
427
+ const { kind, message } = describeError(err);
428
+ reportDiagnostic({
429
+ level: "warn",
430
+ event: "auth.lock_restore_failed",
431
+ server: serverName,
432
+ message: `Could not restore the authorization lock file for "${serverName}": ${message}`,
433
+ fields: { kind },
434
+ });
435
+ await unlinkCandidate(movedPath, deps);
436
+ }
437
+
438
+ /**
439
+ * Re-create `path` from the candidate when hard links are unavailable.
440
+ *
441
+ * Uses the same exclusive-create write as lock acquisition, so a lock another process acquired
442
+ * while `path` was free is never overwritten; `EEXIST` means that process now holds the lock.
443
+ */
444
+ async function restoreCandidateByWrite(
445
+ serverName: string,
446
+ movedPath: string,
447
+ path: string,
448
+ deps: AuthLockDeps,
449
+ ): Promise<void> {
450
+ let data: string;
451
+ try {
452
+ data = await deps.fs.readFile(movedPath, "utf8");
453
+ } catch (readErr) {
454
+ await abandonCandidate(serverName, movedPath, readErr, deps);
455
+ return;
456
+ }
457
+ try {
458
+ await writeExclusiveLockFile(deps.fs, path, data);
459
+ } catch (writeErr) {
460
+ if (errnoCode(writeErr) === "EEXIST") {
461
+ // WHY: Another process acquired the lock while `path` was free; its record wins and the
462
+ // displaced holder detects the loss itself.
463
+ await unlinkCandidate(movedPath, deps);
464
+ return;
465
+ }
466
+ await abandonCandidate(serverName, movedPath, writeErr, deps);
467
+ return;
468
+ }
469
+ await unlinkCandidate(movedPath, deps);
470
+ }
471
+
472
+ /**
473
+ * Restore the contender's fresh lock file, then clean up the temporary candidate path.
474
+ *
475
+ * Reached only when `isSameStaleCandidate` found the moved file carries a *different* nonce:
476
+ * the reclaim race was lost and this record is that process's only copy of its lock. Both
477
+ * restore primitives refuse to replace an existing lock — `link` fails `EEXIST`, and the
478
+ * fallback write is exclusive-create — because a filesystem that refuses hard links
479
+ * (`ENOTSUP`/`EOPNOTSUPP` on FAT/exFAT/SMB/SSHFS/FUSE, `EPERM` under `fs.protected_hardlinks`
480
+ * or seccomp) says nothing about whether `path` is free. Overwriting there would destroy the
481
+ * live lock of whichever process acquired it in the meantime, which is the very failure this
482
+ * path exists to prevent.
483
+ *
484
+ * At most one holder survives: if `path` is taken, the displaced holder's record is dropped
485
+ * and it aborts on its next heartbeat, exactly as if the reclaim had never restored it.
486
+ */
487
+ async function restoreCandidate(
488
+ serverName: string,
489
+ movedPath: string,
490
+ path: string,
491
+ deps: AuthLockDeps,
492
+ ): Promise<void> {
493
+ try {
494
+ await deps.fs.link(movedPath, path);
495
+ } catch (linkErr) {
496
+ const code = errnoCode(linkErr);
497
+ if (code === "EEXIST") {
498
+ // WHY: `path` holds a lock another process acquired while it was free, so restoring this
499
+ // record would delete a live lock. Keep that lock; the displaced holder detects the loss.
500
+ await unlinkCandidate(movedPath, deps);
501
+ return;
502
+ }
503
+ if (code === "ENOENT") {
504
+ await abandonCandidate(serverName, movedPath, linkErr, deps);
505
+ return;
506
+ }
507
+ await restoreCandidateByWrite(serverName, movedPath, path, deps);
508
+ return;
509
+ }
510
+ await unlinkCandidate(movedPath, deps);
511
+ }
512
+
408
513
  async function inspectAndReclaimStaleLock(
409
514
  serverName: string,
410
515
  path: string,
@@ -443,7 +548,7 @@ async function inspectAndReclaimStaleLock(
443
548
  return;
444
549
  }
445
550
 
446
- await restoreCandidate(movedPath, path, deps);
551
+ await restoreCandidate(serverName, movedPath, path, deps);
447
552
  throw new AuthLockError(serverName, formatHolderDetails(movedRecord));
448
553
  }
449
554
 
@@ -473,11 +578,11 @@ async function prepareAuthDirectory(
473
578
  async function writeExclusiveLockFile(
474
579
  fs: AuthLockFs,
475
580
  path: string,
476
- record: LockRecord,
581
+ data: string,
477
582
  ): Promise<void> {
478
583
  const file = await fs.open(path, "wx", 0o600);
479
584
  try {
480
- await file.writeFile(JSON.stringify(record));
585
+ await file.writeFile(data);
481
586
  await file.sync();
482
587
  } catch (writeErr) {
483
588
  await file.close().catch(() => {
@@ -506,7 +611,7 @@ type LockAcquisitionContext = Omit<LockContext, "myRecord">;
506
611
  async function tryCreateLock(ctx: LockAcquisitionContext): Promise<AuthLockHandle | null> {
507
612
  const myRecord = createLockRecord(ctx.deps);
508
613
  try {
509
- await writeExclusiveLockFile(ctx.deps.fs, ctx.path, myRecord);
614
+ await writeExclusiveLockFile(ctx.deps.fs, ctx.path, JSON.stringify(myRecord));
510
615
  return createLockHandle({ ...ctx, myRecord });
511
616
  } catch (err) {
512
617
  if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
@@ -58,21 +58,236 @@ const SAFE_FIELD_NAME_SET = new Set(SAFE_FIELD_NAMES);
58
58
 
59
59
  // ─── Redaction ────────────────────────────────────────────────────────────────
60
60
 
61
- /** `access_token=…`, `"refresh_token":"…"`, `clientSecret: …`, `code_verifier=…`. */
62
- const SECRET_KEY_PATTERN =
63
- /("?\b(?:access_token|accessToken|refresh_token|refreshToken|client_secret|clientSecret|code_verifier|codeVerifier|id_token|idToken|authorization_code|authorizationCode|registration_access_token)\b"?\s*[:=]\s*"?)[^"\s,;&}]*/gi;
61
+ /** Credential names that appear before `:`/`=` in JSON, key-value, or header text. */
62
+ const SECRET_KEY_NAME =
63
+ "access[_-]?token|refresh[_-]?token|id[_-]?token|registration[_-]?access[_-]?token" +
64
+ "|authorization[_-]?code|code[_-]?verifier|client[_-]?secret|x[_-]?api[_-]?key" +
65
+ "|api[_-]?key|private[_-]?key|secret[_-]?key|secret[_-]?access[_-]?key" +
66
+ "|password|passwd|secret|token";
64
67
 
65
- /** `?code=…`, `&access_token=…` — query parameters of an OAuth redirect. */
66
- const QUERY_SECRET_PATTERN =
67
- /([?&](?:code|code_verifier|codeVerifier|client_secret|access_token|refresh_token)=)[^&\s"']*/gi;
68
+ /** Credential-bearing query parameters on a server URL. */
69
+ const QUERY_SECRET_NAME =
70
+ "access[_-]?token|refresh[_-]?token|id[_-]?token|client[_-]?secret|code[_-]?verifier" +
71
+ "|api[_-]?key|x[_-]?api[_-]?key|token|key|secret|password|passwd|auth(?:orization)?|code";
68
72
 
69
- /** `Authorization: Bearer …` / `authorization=Basic …`. */
70
- const AUTHORIZATION_PATTERN =
71
- /(\bauthorization\b\s*[:=]\s*)((?:bearer|basic|digest)\s+)[^\s,;"']*/gi;
73
+ /** An optional quote — `"`, `'`, or the JSON-escaped form — around a key name. */
74
+ const QUOTE = String.raw`(?:\\?["'])?`;
75
+
76
+ /**
77
+ * A credential key and its separator. A key may be a compound name (`db_password`,
78
+ * `aws_secret_access_key`), so the leading boundary rejects only an alphanumeric
79
+ * predecessor — `\b` also rejects `_` and would miss every prefixed name.
80
+ *
81
+ * The value is deliberately not part of the match: `maskCredentialValues` reads it from the
82
+ * text so the mask can honour the value's own delimiter (see `readCredentialValue`).
83
+ */
84
+ const SECRET_KEY_PATTERN = new RegExp(
85
+ String.raw`(${QUOTE}(?<![A-Za-z0-9])(?:${SECRET_KEY_NAME})\b${QUOTE}\s*[:=]\s*)`,
86
+ "gi",
87
+ );
88
+
89
+ /**
90
+ * `?code=…`, `&api_key=…`, `?token=…` — query parameters on a server URL. Matched as a
91
+ * key/separator prefix so `maskCredentialValues` applies the same delimiter-aware value reader
92
+ * as `SECRET_KEY_PATTERN` (preserving apostrophes inside a secret and stopping before closing
93
+ * quotes, brackets, or the next `&name=` parameter).
94
+ */
95
+ const QUERY_SECRET_PATTERN = new RegExp(
96
+ String.raw`([?&](?:[A-Za-z0-9_.\-]*[_-])?(?:${QUERY_SECRET_NAME})=)`,
97
+ "gi",
98
+ );
99
+
100
+ /**
101
+ * `Authorization: Bearer …`, `authorization=Basic …`, `"Authorization":"Token …"`, and the
102
+ * scheme-less `Authorization: …` form. A known scheme name is kept; any other leading token
103
+ * is masked together with the value, because a scheme-less credential may contain spaces.
104
+ */
105
+ const AUTHORIZATION_PATTERN = new RegExp(
106
+ String.raw`(${QUOTE}(?<![A-Za-z0-9])authorization\b${QUOTE}\s*[:=]\s*(?:(?:bearer|basic|digest|token|apikey|dpop|oauth|negotiate)\s+)?)`,
107
+ "gi",
108
+ );
72
109
 
73
110
  /** A bare `Bearer <token>` anywhere in the text. */
74
111
  const BEARER_PATTERN = /\b(bearer|basic)\s+[A-Za-z0-9\-._~+/=]{8,}/gi;
75
112
 
113
+ /** `https://user:password@mcp.example.com/mcp` — userinfo credentials in a URL. */
114
+ const URL_CREDENTIALS_PATTERN = /(https?:\/\/[^/\s?#@:"']+:)[^/\s?#@]+(@)/gi;
115
+
116
+ /**
117
+ * Characters that end an unquoted credential value. Brackets (`()`, `{}`, `[]`), double quotes,
118
+ * and backslash escapes (`\"`) terminate so a mask never swallows an enclosing JSON string or
119
+ * bracketed clause.
120
+ */
121
+ const UNQUOTED_VALUE_TERMINATORS = new Set([
122
+ " ",
123
+ "\t",
124
+ "\n",
125
+ "\r",
126
+ "\f",
127
+ "\v",
128
+ ";",
129
+ ",",
130
+ "{",
131
+ "}",
132
+ "(",
133
+ ")",
134
+ "[",
135
+ "]",
136
+ '"',
137
+ "\\",
138
+ ]);
139
+
140
+ /**
141
+ * Characters that end an unquoted Authorization value. Whitespace is not a terminator: an
142
+ * unknown scheme's value can contain spaces, and stopping at the first one would mask the
143
+ * scheme token and leave the credential behind it in the log. Brackets and quotes still
144
+ * terminate, so `(Authorization: ApiKey …) 401` and `[Authorization: Bearer …] 401` keep the
145
+ * status code that follows the credential.
146
+ */
147
+ const AUTHORIZATION_VALUE_TERMINATORS = new Set([
148
+ "\n",
149
+ "\r",
150
+ ";",
151
+ ",",
152
+ "(",
153
+ ")",
154
+ "{",
155
+ "}",
156
+ "[",
157
+ "]",
158
+ '"',
159
+ "\\",
160
+ ]);
161
+
162
+ /** `&name=` — a query separator rather than part of an unquoted value. */
163
+ const QUERY_SEPARATOR_PATTERN = /&[A-Za-z0-9_.\-]+=/y;
164
+
165
+ /** A credential value located in the text: where it ends and the delimiter to re-emit. */
166
+ interface CredentialValue {
167
+ end: number;
168
+ delimiter: string;
169
+ }
170
+
171
+ /**
172
+ * Return the quote delimiter (`"`, `'`, `\"`, or `\'`) that opens at `index`, or `undefined`
173
+ * when `index` does not start a quoted string.
174
+ */
175
+ function openingQuoteAt(text: string, index: number): string | undefined {
176
+ const char = text.charAt(index);
177
+ if (char === '"' || char === "'") return char;
178
+ const next = char === "\\" ? text.charAt(index + 1) : "";
179
+ return next === '"' || next === "'" ? text.slice(index, index + 2) : undefined;
180
+ }
181
+
182
+ /**
183
+ * A quoted value runs from its opening delimiter (`"`, `'`, `\"`, or `\'`) to the matching one,
184
+ * or to the end of the text when unterminated. Backslash escapes inside the string are skipped.
185
+ */
186
+ function readQuotedValue(text: string, start: number, opening: string): CredentialValue {
187
+ let index = start + opening.length;
188
+ while (index < text.length) {
189
+ if (text.startsWith(opening, index)) return { end: index + opening.length, delimiter: opening };
190
+ index += text.charAt(index) === "\\" ? 2 : 1;
191
+ }
192
+ return { end: text.length, delimiter: opening };
193
+ }
194
+
195
+ /**
196
+ * A `{`/`[` value runs to its matching bracket, so a nested credential object or array is masked
197
+ * as one unit. Quoted strings (including JSON-escaped `\"...\"`) inside it are skipped, or a
198
+ * bracket inside a string value would close the structure early and leave the rest of the secret
199
+ * in the log.
200
+ */
201
+ function readStructuredValue(text: string, start: number, opening: string): CredentialValue {
202
+ const closing = opening === "{" ? "}" : "]";
203
+ let depth = 0;
204
+ let index = start;
205
+ while (index < text.length) {
206
+ const quote = openingQuoteAt(text, index);
207
+ if (quote) {
208
+ index = readQuotedValue(text, index, quote).end;
209
+ continue;
210
+ }
211
+ const char = text.charAt(index);
212
+ if (char === opening) {
213
+ depth += 1;
214
+ } else if (char === closing) {
215
+ depth -= 1;
216
+ if (depth === 0) return { end: index + 1, delimiter: "" };
217
+ }
218
+ index += 1;
219
+ }
220
+ return { end: text.length, delimiter: "" };
221
+ }
222
+
223
+ /** An unquoted value runs to the next separator; `undefined` when there is nothing to mask. */
224
+ function readBareValue(
225
+ text: string,
226
+ start: number,
227
+ terminators: Set<string>,
228
+ ): CredentialValue | undefined {
229
+ let end = start;
230
+ while (end < text.length) {
231
+ const char = text.charAt(end);
232
+ if (terminators.has(char)) break;
233
+ if (char === "&") {
234
+ QUERY_SEPARATOR_PATTERN.lastIndex = end;
235
+ if (QUERY_SEPARATOR_PATTERN.test(text)) break;
236
+ }
237
+ end += 1;
238
+ }
239
+ return end > start ? { end, delimiter: "" } : undefined;
240
+ }
241
+
242
+ /**
243
+ * Read the credential value that starts at `start`, honouring its opening delimiter: a quoted
244
+ * value runs to its matching quote, a `{`/`[` value runs to its matching bracket, and an
245
+ * unquoted value runs to the next separator. Returns `undefined` when there is no value to mask.
246
+ */
247
+ function readCredentialValue(
248
+ text: string,
249
+ start: number,
250
+ terminators: Set<string> = UNQUOTED_VALUE_TERMINATORS,
251
+ ): CredentialValue | undefined {
252
+ // An out-of-range start yields an empty opening and falls through to `readBareValue`, which
253
+ // returns `undefined` for an empty value.
254
+ const quote = openingQuoteAt(text, start);
255
+ if (quote) return readQuotedValue(text, start, quote);
256
+ const opening = text.charAt(start);
257
+ if (opening === "{" || opening === "[") return readStructuredValue(text, start, opening);
258
+ return readBareValue(text, start, terminators);
259
+ }
260
+
261
+ /**
262
+ * Mask every credential value that follows a key/separator prefix matched by `pattern`.
263
+ *
264
+ * WHY a hand-written scan instead of one regex replacement: the mask has to stop where the
265
+ * value's delimiter says it stops. A single character class cannot tell an apostrophe inside an
266
+ * unquoted secret (`it's …`) from the closing quote of a quoted one, and it cannot consume a
267
+ * nested credential object (`{"token":{"value":"…"}}`) as one unit — both mistakes leave the
268
+ * tail of the secret in the log.
269
+ */
270
+ function maskCredentialValues(
271
+ text: string,
272
+ pattern: RegExp,
273
+ terminators: Set<string> = UNQUOTED_VALUE_TERMINATORS,
274
+ ): string {
275
+ pattern.lastIndex = 0;
276
+ let masked = "";
277
+ let cursor = 0;
278
+ let match: RegExpExecArray | null;
279
+ while ((match = pattern.exec(text)) !== null) {
280
+ const prefix = match[0];
281
+ const value = readCredentialValue(text, match.index + prefix.length, terminators);
282
+ if (!value) continue;
283
+ const mask = value.delimiter === "" ? "[REDACTED]" : `${value.delimiter}[REDACTED]${value.delimiter}`;
284
+ masked += text.slice(cursor, match.index) + prefix + mask;
285
+ cursor = value.end;
286
+ pattern.lastIndex = value.end;
287
+ }
288
+ return cursor === 0 ? text : masked + text.slice(cursor);
289
+ }
290
+
76
291
  /**
77
292
  * Mask token-like substrings in an already sanitized string.
78
293
  *
@@ -82,9 +297,14 @@ const BEARER_PATTERN = /\b(bearer|basic)\s+[A-Za-z0-9\-._~+/=]{8,}/gi;
82
297
  */
83
298
  export function redactSecrets(text: string): string {
84
299
  let out = text;
85
- out = out.replace(SECRET_KEY_PATTERN, "$1[REDACTED]");
86
- out = out.replace(QUERY_SECRET_PATTERN, "$1[REDACTED]");
87
- out = out.replace(AUTHORIZATION_PATTERN, "$1$2[REDACTED]");
300
+ out = out.replace(URL_CREDENTIALS_PATTERN, "$1[REDACTED]$2");
301
+ // WHY: `AUTHORIZATION_PATTERN` must run before `SECRET_KEY_PATTERN` because scheme names
302
+ // like `ApiKey` and `Token` are also in `SECRET_KEY_NAME`; if a credential after
303
+ // `Authorization: ApiKey ` starts with `=` or `:`, running `SECRET_KEY_PATTERN` first
304
+ // would treat `ApiKey =…` as a key/value pair and leave a double `[REDACTED][REDACTED]`.
305
+ out = maskCredentialValues(out, AUTHORIZATION_PATTERN, AUTHORIZATION_VALUE_TERMINATORS);
306
+ out = maskCredentialValues(out, SECRET_KEY_PATTERN);
307
+ out = maskCredentialValues(out, QUERY_SECRET_PATTERN);
88
308
  out = out.replace(BEARER_PATTERN, "$1 [REDACTED]");
89
309
  return out;
90
310
  }
@@ -14,6 +14,7 @@ import {
14
14
  type ConnectionCoordinator,
15
15
  formatErrorMessage,
16
16
  } from "./connection-coordinator.js";
17
+ import { sanitizeLogText } from "./debug-log.js";
17
18
  import { AuthCancelledError } from "./errors.js";
18
19
  import type { ManagedServer, ServerManager } from "./server-manager.js";
19
20
  import { lookupServerSource, type ConfigProvenance } from "./server-provenance.js";
@@ -136,7 +137,7 @@ async function handleMcpAuth(
136
137
  ctx.ui.notify(`pi-mcp: ${name} ready`, "info");
137
138
  } catch (err) {
138
139
  ctx.ui.notify(
139
- `pi-mcp: ${sanitizeTerminalText(err instanceof Error ? err.message : String(err))}`,
140
+ `pi-mcp: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 500)}`,
140
141
  err instanceof AuthCancelledError ? "info" : "error",
141
142
  );
142
143
  }
@@ -27,7 +27,7 @@ import type { McpConfig, ServerConfig, Settings } from "./config.js";
27
27
  import { AuthRequiredError, getAuthStatus, resetAuth, invalidateStoredTokens } from "./oauth-provider.js";
28
28
  import type { ToolRefreshOptions } from "./tool-bridge.js";
29
29
  import { sanitizeTerminalText, type SanitizeTerminalTextOptions } from "./terminal-text.js";
30
- import { describeError, reportDiagnostic } from "./debug-log.js";
30
+ import { describeError, redactSecrets, reportDiagnostic, sanitizeLogText } from "./debug-log.js";
31
31
  import {
32
32
  destroyStdioStreams,
33
33
  ensurePidTerminated,
@@ -320,7 +320,7 @@ export class ServerManager {
320
320
  if (all.length === 0) return "pi-mcp: No servers configured (create ~/.pi/agent/mcp.json)";
321
321
  const lines = all.map((s) => {
322
322
  const icon = s.state === "ready" ? "✓" : s.state === "starting" ? "⟳" : "✗";
323
- const err = s.lastError ? ` — ${sanitizeTerminalText(s.lastError.message)}` : "";
323
+ const err = s.lastError ? ` — ${sanitizeLogText(s.lastError.message, 500)}` : "";
324
324
  return ` ${icon} ${s.name} (${s.state})${err}`;
325
325
  });
326
326
  const ready = all.filter((s) => s.state === "ready").length;
@@ -508,7 +508,11 @@ export class ServerManager {
508
508
  }
509
509
 
510
510
  private _appendStderr(server: ManagedServer, line: string): void {
511
- server.stderrLog.push(line);
511
+ // WHY: this buffer is what `/mcp <name>` prints as "Recent output" and what
512
+ // `getServerLogs` returns — text users paste into bug reports. A child server that echoes
513
+ // its own key on stderr must not surface it there, so mask credentials exactly as the
514
+ // debug log does. Redacting twice is a no-op.
515
+ server.stderrLog.push(redactSecrets(line));
512
516
  if (server.stderrLog.length > STDERR_BUFFER_SIZE) {
513
517
  server.stderrLog.shift();
514
518
  }
@@ -8,7 +8,7 @@
8
8
  */
9
9
 
10
10
  import type { ServerConfig } from "./config.js";
11
- import { describeError, reportDiagnostic } from "./debug-log.js";
11
+ import { describeError, reportDiagnostic, sanitizeLogText } from "./debug-log.js";
12
12
  import { McpError } from "./errors.js";
13
13
  import { AuthLockError, AuthRequiredError } from "./oauth-provider.js";
14
14
  import type { ManagedServer } from "./server-manager.js";
@@ -123,7 +123,9 @@ export function formatServerDetail(snapshot: ServerStatusSnapshot, provenance: C
123
123
  `Tools: ${snapshot.tools.active}/${snapshot.tools.discovered} active`,
124
124
  snapshot.auth === undefined ? undefined : `OAuth: ${snapshot.auth}`,
125
125
  formatProjectConfigNote(provenance),
126
- snapshot.lastError === null ? undefined : `Last error: ${sanitizeTerminalText(snapshot.lastError.message)}`,
126
+ // WHY: a connect/stream failure usually quotes the request URL, and that URL can carry a
127
+ // credential. This view is what users paste into an issue, so mask it like the log does.
128
+ snapshot.lastError === null ? undefined : `Last error: ${sanitizeLogText(snapshot.lastError.message, 500)}`,
127
129
  formatFailureHint(classifyFailure(snapshot.lastError), snapshot.name),
128
130
  ];
129
131
  return `${lines.filter(isDefined).join("\n")}\n\nRecent output:\n${snapshot.recentOutput}`;
@@ -8,6 +8,7 @@
8
8
  */
9
9
 
10
10
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
11
+ import { redactSecrets } from "./debug-log.js";
11
12
  import { McpError, AuthCancelledError } from "./errors.js";
12
13
  import { sanitizeTerminalText } from "./terminal-text.js";
13
14
 
@@ -16,7 +17,7 @@ export const startupAuthLaterOption = "Not now";
16
17
 
17
18
  export function formatErrorMessage(err: unknown): string {
18
19
  const msg = err instanceof McpError ? err.userMessage : err instanceof Error ? err.message : String(err);
19
- return sanitizeTerminalText(msg.replace(/^AuthRequiredError:\s*/, ""));
20
+ return redactSecrets(sanitizeTerminalText(msg.replace(/^AuthRequiredError:\s*/, "")));
20
21
  }
21
22
 
22
23
  // WHY: Allow an aborted waiter on authQueue to wake up and reject immediately without breaking
@@ -464,9 +464,12 @@ export class ToolBridge {
464
464
  ): void {
465
465
  const annotations = tool.annotations;
466
466
  const description = buildToolDescription(tool, annotations);
467
- const notifyAuthError = (err: unknown) => this.onAuthError?.(serverName, err);
468
467
  const runTool = (params: unknown, signal: AbortSignal | undefined) =>
469
468
  this._executeToolCall(serverName, tool.name, client, params, signal);
469
+ // WHY: `execute` runs with `this` bound to the registered-tool literal rather than the
470
+ // bridge, so the rethrow helper is reached through a captured closure.
471
+ const rethrowToolCallError = (err: unknown): Promise<never> =>
472
+ this._rethrowToolCallError(serverName, err);
470
473
 
471
474
  this.pi.registerTool({
472
475
  name: piName,
@@ -479,24 +482,34 @@ export class ToolBridge {
479
482
  try {
480
483
  return await runTool(params, signal);
481
484
  } catch (err) {
482
- if (err instanceof McpError) throw err;
483
- if (isOAuthUnauthorizedError(err)) {
484
- await notifyAuthError(err);
485
- }
486
- // Protocol-level errors (JSON-RPC error response, malformed payload) keep
487
- // "protocol"; an SDK request timeout keeps its own code so callers can tell
488
- // "the server answered badly" from "the server did not answer in time" (#209).
489
- throw new McpError(
490
- err instanceof Error ? err.message : String(err),
491
- serverName,
492
- isSdkTimeoutError(err) ? "timeout" : "protocol",
493
- err,
494
- );
485
+ return await rethrowToolCallError(err);
495
486
  }
496
487
  },
497
488
  });
498
489
  }
499
490
 
491
+ /**
492
+ * Normalize a `tools/call` failure into the `McpError` callers see, after notifying the
493
+ * OAuth handler when the failure means the server needs authorization.
494
+ */
495
+ private async _rethrowToolCallError(serverName: string, err: unknown): Promise<never> {
496
+ if (err instanceof McpError) throw err;
497
+ if (isOAuthUnauthorizedError(err)) {
498
+ // WHY: read the handler through `this` at call time — src/index.ts installs it after the
499
+ // bridge is constructed, and it is the caller for every server, so it takes the name.
500
+ await this.onAuthError?.(serverName, err);
501
+ }
502
+ // Protocol-level errors (JSON-RPC error response, malformed payload) keep
503
+ // "protocol"; an SDK request timeout keeps its own code so callers can tell
504
+ // "the server answered badly" from "the server did not answer in time" (#209).
505
+ throw new McpError(
506
+ err instanceof Error ? err.message : String(err),
507
+ serverName,
508
+ isSdkTimeoutError(err) ? "timeout" : "protocol",
509
+ err,
510
+ );
511
+ }
512
+
500
513
  /**
501
514
  * Run one `tools/call`: dispatch through the SDK client, convert the result
502
515
  * into Pi content blocks, and surface `isError` as `McpError(..., "tool")`.