pi-mcp-extension 1.15.1 → 1.15.2

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
@@ -347,24 +347,30 @@ While a Pi UI is active, the extension never writes diagnostics to Pi's stderr (
347
347
  ```mermaid
348
348
  flowchart TD
349
349
  subgraph Pi["Pi Coding Agent (TUI / RPC, ExtensionAPI)"]
350
- Entry["index.ts (entry & session lifecycle)"]
350
+ Entry["index.ts (extension entry)"]
351
+ Life["session-lifecycle (bootstrap, reload, mcp_servers_change)"]
351
352
  Cmds["register-commands (/mcp, :start, :stop, :auth, :resources)"]
352
353
  Tools["register-tools (mcp_* agent tools)"]
353
354
  Config["config (Zod + JSONC)"]
354
355
  Coord["connection-coordinator (in-flight connects, authQueue, teardown)"]
355
356
  Mgr["server-manager (stopped -> starting -> ready lifecycle)"]
356
357
  Bridge["tool-bridge (MCP -> Pi tools)"]
358
+ Res["resource-bridge (MCP resources & catalog cache)"]
357
359
  Schema["schema-convert (JSON Schema -> TypeBox)"]
358
360
  Transport["transport-factory & oauth-provider (MCP SDK)"]
359
361
 
362
+ Entry --> Life
360
363
  Entry --> Cmds
361
364
  Entry --> Tools
362
- Entry --> Config
363
- Entry --> Coord
365
+ Life --> Config
366
+ Life --> Coord
364
367
  Cmds --> Coord
368
+ Cmds --> Res
365
369
  Tools --> Coord
370
+ Tools --> Res
366
371
  Coord --> Mgr
367
372
  Mgr --> Bridge
373
+ Mgr --> Res
368
374
  Bridge --> Schema
369
375
  Mgr --> Transport
370
376
  end
@@ -446,12 +452,12 @@ npm pack --dry-run
446
452
 
447
453
  The test suite includes:
448
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`
449
- - **Server lifecycle & coordination** (`tests/server-manager.test.ts`, `tests/stdio-process.test.ts`, `tests/transport-factory.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
450
- - **OAuth 2.1 & auth locks** (`tests/oauth-fixes.test.ts`, `tests/authorize-flow.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
455
+ - **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
+ - **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
451
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
452
458
  - **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`
453
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
454
- - **Release flow & repository policy** (`tests/release.test.ts`, `tests/ruleset-audit.test.ts`, `tests/repo-policy.test.ts`) — Release PR orchestration and npm/git self-healing (`scripts/release.ts`), live GitHub ruleset drift auditing (`scripts/ruleset-audit.ts`), and CI/ESLint/Qlty policy invariants
460
+ - **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
455
461
  - **End-to-end integration** — Real mock MCP and OAuth servers over `stdio` and HTTP with tool discovery and execution
456
462
 
457
463
  ## Security
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mcp-extension",
3
- "version": "1.15.1",
3
+ "version": "1.15.2",
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": [
package/src/auth-lock.ts CHANGED
@@ -23,7 +23,9 @@ 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
+ import { describeError } from "./debug-log-format.js";
27
+ import { reportDiagnostic } from "./debug-log.js";
28
+ import { AuthLockError, AuthRequiredError } from "./errors.js";
27
29
  import {
28
30
  formatHolderDetails,
29
31
  HEARTBEAT_MS,
@@ -32,29 +34,7 @@ import {
32
34
  type LockRecord,
33
35
  } from "./auth-lock-policy.js";
34
36
 
35
- // ─── Errors ───────────────────────────────────────────────────────────────────
36
-
37
- export class AuthRequiredError extends Error {
38
- constructor(
39
- serverName: string,
40
- message = `Authorization required for ${serverName}. Connect in an interactive Pi session or use /mcp:auth ${serverName}.`,
41
- ) {
42
- super(message);
43
- this.name = "AuthRequiredError";
44
- }
45
- }
46
-
47
- export class AuthLockError extends AuthRequiredError {
48
- constructor(serverName: string, details?: string) {
49
- const message = details
50
- ? details.startsWith("Authorization lock") || details.startsWith("Another Pi process")
51
- ? details
52
- : `Another Pi process (${details}) is authorizing ${serverName}. Retry after it finishes.`
53
- : `Another Pi process is authorizing ${serverName}. Retry after it finishes.`;
54
- super(serverName, message);
55
- this.name = "AuthLockError";
56
- }
57
- }
37
+ export { AuthLockError, AuthRequiredError };
58
38
 
59
39
  // ─── Dependency Injection Types ───────────────────────────────────────────────
60
40
 
@@ -0,0 +1,153 @@
1
+ /**
2
+ * OS browser process launcher and safe-URL authorization redirect gate.
3
+ *
4
+ * Isolates `node:child_process.spawn` browser invocation, `isSafeAuthorizationUrl`
5
+ * scheme validation, and SSH `-L` / manual paste-back UI notifications from the
6
+ * interactive OAuth flow coordinator (`src/authorize-flow.ts`).
7
+ */
8
+
9
+ import { spawn } from "node:child_process";
10
+ import type { ExtensionUIContext } from "@earendil-works/pi-coding-agent";
11
+ import { authPasteOption } from "./authorize-dialog.js";
12
+ import { isSafeAuthorizationUrl } from "./callback-url.js";
13
+ import { reportDiagnostic } from "./debug-log.js";
14
+ import { McpError } from "./errors.js";
15
+ import { sanitizeTerminalText } from "./terminal-text.js";
16
+
17
+ export interface BrowserOpenCommand {
18
+ command: string;
19
+ args: string[];
20
+ }
21
+
22
+ export interface BrowserSpawnOptions {
23
+ detached: true;
24
+ stdio: "ignore";
25
+ windowsHide: true;
26
+ }
27
+
28
+ export interface BrowserChildProcess {
29
+ once(event: "error", listener: (err: Error) => void): unknown;
30
+ once(event: "spawn", listener: () => void): unknown;
31
+ unref(): void;
32
+ }
33
+
34
+ export type BrowserSpawn = (
35
+ command: string,
36
+ args: readonly string[],
37
+ options: BrowserSpawnOptions,
38
+ ) => BrowserChildProcess;
39
+
40
+ export interface OpenBrowserDeps {
41
+ platform?: NodeJS.Platform | undefined;
42
+ spawnProcess?: BrowserSpawn | undefined;
43
+ }
44
+
45
+ export interface BrowserLauncherContext {
46
+ ui: Pick<ExtensionUIContext, "notify">;
47
+ }
48
+
49
+ export interface BrowserLauncherParams {
50
+ serverName: string;
51
+ port: number;
52
+ ctx: BrowserLauncherContext;
53
+ browserOpener: (url: string) => void | Promise<void>;
54
+ isInactive: () => boolean;
55
+ onUrlRecorded: (url: URL) => void;
56
+ }
57
+
58
+ export function browserOpenCommand(
59
+ url: string,
60
+ platform: NodeJS.Platform = process.platform,
61
+ ): BrowserOpenCommand {
62
+ if (platform === "darwin") {
63
+ return { command: "open", args: [url] };
64
+ }
65
+ if (platform === "win32") {
66
+ return { command: "rundll32", args: ["url.dll,FileProtocolHandler", url] };
67
+ }
68
+ return { command: "xdg-open", args: [url] };
69
+ }
70
+
71
+ /**
72
+ * Open a URL in the user's default browser.
73
+ * Works on macOS, Linux, and Windows.
74
+ */
75
+ export function openBrowser(url: string, deps?: OpenBrowserDeps): Promise<void> {
76
+ const spawnProcess: BrowserSpawn = deps?.spawnProcess ?? spawn;
77
+ const { command, args } = browserOpenCommand(url, deps?.platform);
78
+ return new Promise<void>((resolve, reject) => {
79
+ const child = spawnProcess(command, args, {
80
+ detached: true,
81
+ stdio: "ignore",
82
+ windowsHide: true,
83
+ });
84
+
85
+ child.once("error", (err) => {
86
+ reportDiagnostic({
87
+ level: "error",
88
+ event: "auth.browser_open_failed",
89
+ message: `Failed to open browser: ${sanitizeTerminalText(err.message)}`,
90
+ });
91
+ reject(err);
92
+ });
93
+
94
+ child.once("spawn", () => {
95
+ child.unref();
96
+ resolve();
97
+ });
98
+ });
99
+ }
100
+
101
+ /**
102
+ * Build the `onAuthRequired` hook: refuse unsafe URLs, remember the last URL for
103
+ * "Retry", open the browser, and tell the user how to finish on a remote host.
104
+ */
105
+ export function createAuthorizationBrowserLauncher(
106
+ params: BrowserLauncherParams,
107
+ ): (url: URL) => Promise<void> {
108
+ const { serverName, port, ctx, browserOpener, isInactive, onUrlRecorded } = params;
109
+ return async (url: URL): Promise<void> => {
110
+ if (!isSafeAuthorizationUrl(url)) {
111
+ throw new McpError(
112
+ `Refusing to open unsafe authorization URL for "${serverName}": only HTTPS (or loopback HTTP) URLs are allowed`,
113
+ serverName,
114
+ "protocol",
115
+ );
116
+ }
117
+ const href = url.toString();
118
+ onUrlRecorded(new URL(href));
119
+ if (isInactive()) return;
120
+ try {
121
+ await browserOpener(href);
122
+ ctx.ui.notify(
123
+ `pi-mcp: Authorize ${serverName}: ${href} (On SSH, forward the callback with ssh -L ${port}:127.0.0.1:${port}, or choose "${authPasteOption}".)`,
124
+ "info",
125
+ );
126
+ } catch (err) {
127
+ const detail = sanitizeTerminalText(err instanceof Error ? err.message : String(err));
128
+ ctx.ui.notify(
129
+ `pi-mcp: Failed to open browser for ${serverName} (${detail}). Open ${href} manually or choose "${authPasteOption}".`,
130
+ "error",
131
+ );
132
+ }
133
+ };
134
+ }
135
+
136
+ /**
137
+ * Re-open the last authorization URL when the user retries from the dialog.
138
+ */
139
+ export function reopenAuthorizationBrowser(
140
+ launchAuthorizationBrowser: (url: URL) => Promise<void>,
141
+ getLatestAuthorizationUrl: () => URL | undefined,
142
+ serverName: string,
143
+ ): Promise<void> {
144
+ const latestAuthorizationUrl = getLatestAuthorizationUrl();
145
+ if (!latestAuthorizationUrl) {
146
+ throw new McpError(
147
+ `Authorization URL is not available for ${serverName}`,
148
+ serverName,
149
+ "protocol",
150
+ );
151
+ }
152
+ return launchAuthorizationBrowser(latestAuthorizationUrl);
153
+ }
@@ -1,34 +1,33 @@
1
- import { spawn } from "node:child_process";
2
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
2
  import { auth } from "@modelcontextprotocol/sdk/client/auth.js";
4
- import {
5
- CallbackServer,
6
- callbackServerConfigFromRedirectUrl,
7
- } from "./callback-server.js";
8
- import { isSafeAuthorizationUrl } from "./callback-url.js";
3
+ import { CallbackServer } from "./callback-server.js";
4
+ import { callbackServerConfigFromRedirectUrl } from "./callback-url.js";
9
5
  import {
10
6
  discoverManualAuthChallenge,
11
7
  createHeadersFetch,
12
8
  stripAuthorizationHeader,
13
9
  type ManualAuthChallenge,
14
10
  } from "./auth-challenge.js";
11
+ import { acquireAuthLock, type AuthLockHandle } from "./auth-lock.js";
12
+ import { McpOAuthProvider } from "./oauth-provider.js";
13
+ import { McpError, AuthCancelledError, AuthLockError } from "./errors.js";
14
+ import { describeError } from "./debug-log-format.js";
15
+ import { reportDiagnostic } from "./debug-log.js";
15
16
  import {
16
- McpOAuthProvider,
17
- acquireAuthLock,
18
- AuthLockError,
19
- type AuthLockHandle,
20
- } from "./oauth-provider.js";
21
- import { McpError, AuthCancelledError } from "./errors.js";
22
- import { sanitizeTerminalText } from "./terminal-text.js";
23
- import { describeError, reportDiagnostic } from "./debug-log.js";
24
- import {
25
- authPasteOption,
26
- waitForOAuthCallback,
27
- } from "./authorize-dialog.js";
17
+ createAuthorizationBrowserLauncher,
18
+ openBrowser,
19
+ reopenAuthorizationBrowser,
20
+ } from "./authorize-browser.js";
21
+ import { waitForOAuthCallback } from "./authorize-dialog.js";
28
22
  import type { ServerConfig } from "./config.js";
29
23
  import type { ServerManager } from "./server-manager.js";
30
24
 
31
25
  export { AuthCancelledError } from "./errors.js";
26
+ export {
27
+ browserOpenCommand,
28
+ openBrowser,
29
+ type BrowserOpenCommand,
30
+ } from "./authorize-browser.js";
32
31
  export {
33
32
  authCancelOption,
34
33
  authPasteOption,
@@ -37,51 +36,6 @@ export {
37
36
  type OAuthPasteOptions,
38
37
  } from "./authorize-dialog.js";
39
38
 
40
- export interface BrowserOpenCommand {
41
- command: string;
42
- args: string[];
43
- }
44
-
45
- export function browserOpenCommand(url: string): BrowserOpenCommand {
46
- if (process.platform === "darwin") {
47
- return { command: "open", args: [url] };
48
- }
49
- if (process.platform === "win32") {
50
- return { command: "rundll32", args: ["url.dll,FileProtocolHandler", url] };
51
- }
52
- return { command: "xdg-open", args: [url] };
53
- }
54
-
55
- /**
56
- * Open a URL in the user's default browser.
57
- * Works on macOS, Linux, and Windows.
58
- */
59
- export function openBrowser(url: string): Promise<void> {
60
- return new Promise<void>((resolve, reject) => {
61
- const { command, args } = browserOpenCommand(url);
62
- const child = spawn(command, args, {
63
- detached: true,
64
- stdio: "ignore",
65
- windowsHide: true,
66
- });
67
-
68
- child.once("error", (err) => {
69
- reportDiagnostic({
70
- level: "error",
71
- event: "auth.browser_open_failed",
72
- message: `Failed to open browser: ${sanitizeTerminalText(err.message)}`,
73
- });
74
- reject(err);
75
- });
76
-
77
- child.once("spawn", () => {
78
- child.unref();
79
- resolve();
80
- });
81
- });
82
- }
83
-
84
-
85
39
  export interface AuthorizeDeps {
86
40
  manager: ServerManager;
87
41
  getServerConfig?: ((name: string) => ServerConfig | undefined) | undefined;
@@ -128,15 +82,6 @@ interface StartCallbackServerParams {
128
82
  isLockLost: () => boolean;
129
83
  }
130
84
 
131
- interface BrowserLauncherParams {
132
- serverName: string;
133
- port: number;
134
- ctx: ExtensionContext;
135
- browserOpener: (url: string) => void | Promise<void>;
136
- isInactive: () => boolean;
137
- onUrlRecorded: (url: URL) => void;
138
- }
139
-
140
85
  interface InteractiveAuthProviderParams {
141
86
  serverName: string;
142
87
  config: ServerConfig;
@@ -289,37 +234,6 @@ async function startAuthorizationCallbackServer(params: StartCallbackServerParam
289
234
  return port;
290
235
  }
291
236
 
292
- /**
293
- * Build the `onAuthRequired` hook: refuse unsafe URLs, remember the last URL for
294
- * "Retry", open the browser, and tell the user how to finish on a remote host.
295
- */
296
- function createAuthorizationBrowserLauncher(params: BrowserLauncherParams): (url: URL) => Promise<void> {
297
- const { serverName, port, ctx, browserOpener, isInactive, onUrlRecorded } = params;
298
- return async (url: URL): Promise<void> => {
299
- if (!isSafeAuthorizationUrl(url)) {
300
- throw new McpError(
301
- `Refusing to open unsafe authorization URL for "${serverName}": only HTTPS (or loopback HTTP) URLs are allowed`,
302
- serverName,
303
- "protocol",
304
- );
305
- }
306
- onUrlRecorded(new URL(url.toString()));
307
- if (isInactive()) return;
308
- try {
309
- await browserOpener(url.toString());
310
- ctx.ui.notify(
311
- `pi-mcp: Authorize ${serverName}: ${url.toString()} (On SSH, forward the callback with ssh -L ${port}:127.0.0.1:${port}, or choose "${authPasteOption}".)`,
312
- "info",
313
- );
314
- } catch (err) {
315
- ctx.ui.notify(
316
- `pi-mcp: Failed to open browser for ${serverName} (${sanitizeTerminalText(err instanceof Error ? err.message : String(err))}). Open ${url.toString()} manually or choose "${authPasteOption}".`,
317
- "error",
318
- );
319
- }
320
- };
321
- }
322
-
323
237
  /** Create the interactive-mode OAuth provider wired to the run's lock and signal. */
324
238
  function createInteractiveAuthProvider(params: InteractiveAuthProviderParams): McpOAuthProvider {
325
239
  const { serverName, config, serverUrl, redirectUrl, deps, signal, unlock, onAuthRequired } = params;
@@ -453,24 +367,6 @@ async function runInitialSdkAuth(
453
367
  }
454
368
  }
455
369
 
456
- /**
457
- * Re-open the last authorization URL when the user retries from the dialog.
458
- */
459
- function reopenAuthorizationBrowser(
460
- launchAuthorizationBrowser: (url: URL) => Promise<void>,
461
- state: AuthorizeRunState,
462
- serverName: string,
463
- ): Promise<void> {
464
- if (!state.latestAuthorizationUrl) {
465
- throw new McpError(
466
- `Authorization URL is not available for ${serverName}`,
467
- serverName,
468
- "protocol",
469
- );
470
- }
471
- return launchAuthorizationBrowser(state.latestAuthorizationUrl);
472
- }
473
-
474
370
  /**
475
371
  * Drive the REDIRECT half of the flow: wait for the loopback callback (or a
476
372
  * pasted redirect URL), then exchange the authorization code for tokens.
@@ -667,7 +563,12 @@ export async function authorize(
667
563
  customFetch,
668
564
  callbackPromise,
669
565
  oauthState,
670
- reopenBrowser: () => reopenAuthorizationBrowser(launchAuthorizationBrowser, state, serverName),
566
+ reopenBrowser: () =>
567
+ reopenAuthorizationBrowser(
568
+ launchAuthorizationBrowser,
569
+ () => state.latestAuthorizationUrl,
570
+ serverName,
571
+ ),
671
572
  onPasteResolved: cancel,
672
573
  assertActive,
673
574
  });
@@ -12,8 +12,7 @@
12
12
  */
13
13
 
14
14
  import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js";
15
- import { McpError, AuthCancelledError } from "./errors.js";
16
- import { AuthRequiredError } from "./oauth-provider.js";
15
+ import { McpError, AuthCancelledError, AuthRequiredError } from "./errors.js";
17
16
  import type { ServerConfig } from "./config.js";
18
17
 
19
18
  function isHttpStatusCodeUnauthorized(numericCode: number, error: unknown): boolean {
@@ -10,8 +10,7 @@ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
10
10
  import type { McpConfig, ServerConfig } from "./config.js";
11
11
  import type { ManagedServer, ServerManager } from "./server-manager.js";
12
12
  import type { ToolBridge } from "./tool-bridge.js";
13
- import { McpError, AuthCancelledError } from "./errors.js";
14
- import { AuthRequiredError } from "./oauth-provider.js";
13
+ import { McpError, AuthCancelledError, AuthRequiredError } from "./errors.js";
15
14
  import {
16
15
  formatErrorMessage,
17
16
  promptStartupAuth,