pi-mcp-extension 1.11.8 → 1.11.10

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.
Files changed (3) hide show
  1. package/README.md +111 -72
  2. package/package.json +3 -2
  3. package/src/auth-lock.ts +129 -24
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 credential: OAuth tokens, codes, and PKCE verifiers, plus API keys and other key/value or JSON secrets (`api_key`, `x-api-key`, `private_key`, `password`, `secret`, `token`, and prefixed forms such as `db_password`), credential-bearing query parameters on a server URL (`?api_key=…`, `?token=…`), `Authorization` headers in any scheme and quoting (including the JSON `"Authorization": "…"` form), and URL userinfo passwords (`https://user:password@host`). A value is masked up to its own delimiter, so a quoted secret keeps its quotes, an object value is masked whole, and text after a closing bracket (`… [REDACTED]) 401`, `… [REDACTED]] 401`) survives. The mask is idempotent and never touches a sentence that merely mentions a credential word (`Unexpected token <`); a word directly after a credential key is masked, because the redactor cannot tell a value from prose and masks on the safe side. The same mask applies to the per-server stderr buffer, the `Last error:` line that `/mcp <name>` shows and `getServerLogs` returns, and user-facing start/auth/recovery failure notifications.
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,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-mcp-extension",
3
- "version": "1.11.8",
4
- "description": "MCP (Model Context Protocol) client extension for the Pi coding agent — connect Pi to any MCP server",
3
+ "version": "1.11.10",
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": [
7
7
  "pi-package",
@@ -28,6 +28,7 @@
28
28
  "LICENSE"
29
29
  ],
30
30
  "pi": {
31
+ "image": "https://raw.githubusercontent.com/irahardianto/pi-mcp-extension/main/docs/icon-preview.png",
31
32
  "extensions": [
32
33
  "./src/index.ts"
33
34
  ]
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;