pi-mcp-extension 1.15.0 → 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,21 +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 & mcp_* agent tools)"]
351
- Cmds["register-commands (/mcp, :start, :stop, :auth)"]
350
+ Entry["index.ts (extension entry)"]
351
+ Life["session-lifecycle (bootstrap, reload, mcp_servers_change)"]
352
+ Cmds["register-commands (/mcp, :start, :stop, :auth, :resources)"]
353
+ Tools["register-tools (mcp_* agent tools)"]
352
354
  Config["config (Zod + JSONC)"]
353
355
  Coord["connection-coordinator (in-flight connects, authQueue, teardown)"]
354
356
  Mgr["server-manager (stopped -> starting -> ready lifecycle)"]
355
357
  Bridge["tool-bridge (MCP -> Pi tools)"]
358
+ Res["resource-bridge (MCP resources & catalog cache)"]
356
359
  Schema["schema-convert (JSON Schema -> TypeBox)"]
357
360
  Transport["transport-factory & oauth-provider (MCP SDK)"]
358
361
 
362
+ Entry --> Life
359
363
  Entry --> Cmds
360
- Entry --> Config
361
- Entry --> Coord
364
+ Entry --> Tools
365
+ Life --> Config
366
+ Life --> Coord
362
367
  Cmds --> Coord
368
+ Cmds --> Res
369
+ Tools --> Coord
370
+ Tools --> Res
363
371
  Coord --> Mgr
364
372
  Mgr --> Bridge
373
+ Mgr --> Res
365
374
  Bridge --> Schema
366
375
  Mgr --> Transport
367
376
  end
@@ -443,12 +452,12 @@ npm pack --dry-run
443
452
 
444
453
  The test suite includes:
445
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`
446
- - **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, shutdown with PID `SIGKILL` safety net, health check, concurrent connect/reset coordination, and cancellation
447
- - **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
448
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
449
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`
450
- - **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, and custom header merging
451
- - **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
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
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
452
461
  - **End-to-end integration** — Real mock MCP and OAuth servers over `stdio` and HTTP with tool discovery and execution
453
462
 
454
463
  ## Security
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mcp-extension",
3
- "version": "1.15.0",
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
  });
@@ -8,7 +8,12 @@
8
8
  import { createServer, type Server, type IncomingMessage, type ServerResponse } from "http";
9
9
  import type { Socket } from "net";
10
10
  import { URL } from "url";
11
- import { CallbackUrlValidationError, isLocalCallbackHost, parseCallbackUrl } from "./callback-url.js";
11
+ import {
12
+ CallbackUrlValidationError,
13
+ DEFAULT_HOST,
14
+ DEFAULT_PORT,
15
+ parseCallbackUrl,
16
+ } from "./callback-url.js";
12
17
 
13
18
  interface PendingAuth {
14
19
  resolve: (code: string) => void;
@@ -16,10 +21,6 @@ interface PendingAuth {
16
21
  timeout: ReturnType<typeof setTimeout>;
17
22
  }
18
23
 
19
- const DEFAULT_PORT = 19876;
20
- const DEFAULT_HOST = "127.0.0.1";
21
- const CALLBACK_PATH = "/callback";
22
-
23
24
  export interface CallbackServerOptions {
24
25
  /** Host to bind. Defaults to 127.0.0.1 for local-only callbacks. */
25
26
  host?: string | undefined;
@@ -27,11 +28,6 @@ export interface CallbackServerOptions {
27
28
  allowPortFallback?: boolean | undefined;
28
29
  }
29
30
 
30
- export interface CallbackServerConfig {
31
- preferredPort: number;
32
- host: string;
33
- allowPortFallback: boolean;
34
- }
35
31
  const TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
36
32
 
37
33
  const HTML_SUCCESS = `<!DOCTYPE html>
@@ -71,58 +67,6 @@ function isAddressInUseError(error: unknown): boolean {
71
67
  return (error as NodeJS.ErrnoException).code === "EADDRINUSE";
72
68
  }
73
69
 
74
- /**
75
- * Build callback server settings from the configured OAuth redirect URL.
76
- *
77
- * Local HTTP redirect URLs must use a fixed listener port because OAuth
78
- * providers require exact redirect URI registration. When no local redirect URL
79
- * is configured, the callback server keeps the historical default behavior and
80
- * scans forward from the default port if needed.
81
- */
82
- export function callbackServerConfigFromRedirectUrl(redirectUrl?: string): CallbackServerConfig {
83
- // WHY: Only treat `undefined` (omitted) as default; an explicit empty string `""`
84
- // must fall through to `new URL("")` and throw a validation error.
85
- if (redirectUrl === undefined) {
86
- return {
87
- preferredPort: DEFAULT_PORT,
88
- host: DEFAULT_HOST,
89
- allowPortFallback: true,
90
- };
91
- }
92
-
93
- const url = new URL(redirectUrl);
94
- if (url.protocol !== "http:" || !isLocalCallbackHost(url.hostname)) {
95
- throw new Error("Manual OAuth redirect URL must use HTTP with localhost, 127.0.0.1, or ::1");
96
- }
97
-
98
- if (url.hash) {
99
- throw new Error("Manual OAuth redirect URL must not include a fragment");
100
- }
101
-
102
- if (url.username || url.password) {
103
- throw new Error("Manual OAuth redirect URL must not include credentials");
104
- }
105
-
106
- if (url.pathname !== CALLBACK_PATH) {
107
- throw new Error(`Local OAuth redirect URL must use path ${CALLBACK_PATH}`);
108
- }
109
-
110
- if (!url.port) {
111
- throw new Error("Manual OAuth redirect URL must include an explicit port (e.g. http://127.0.0.1:19876/callback)");
112
- }
113
-
114
- const preferredPort = Number(url.port);
115
- if (preferredPort === 0) {
116
- throw new Error("Manual OAuth redirect URL must use a fixed non-zero port");
117
- }
118
-
119
- return {
120
- preferredPort,
121
- host: url.hostname === "[::1]" ? "::1" : url.hostname,
122
- allowPortFallback: false,
123
- };
124
- }
125
-
126
70
  /**
127
71
  * Instance-scoped HTTP server that handles OAuth callbacks from the authorization server.
128
72
  */
@@ -385,5 +329,6 @@ export class CallbackServer {
385
329
  }
386
330
  }
387
331
 
388
- // Export constants for testing/config
389
- export { DEFAULT_PORT, DEFAULT_HOST, CALLBACK_PATH, TIMEOUT_MS };
332
+ // Export constants and pure redirect-URL config builder for backwards compatibility
333
+ export { DEFAULT_PORT, DEFAULT_HOST, TIMEOUT_MS };
334
+ export { CALLBACK_PATH, callbackServerConfigFromRedirectUrl, type CallbackServerConfig } from "./callback-url.js";
@@ -2,6 +2,16 @@
2
2
  * Pure URL validation and parsing helpers for MCP OAuth authorization and callbacks.
3
3
  */
4
4
 
5
+ export const DEFAULT_PORT = 19876;
6
+ export const DEFAULT_HOST = "127.0.0.1";
7
+ export const CALLBACK_PATH = "/callback";
8
+
9
+ export interface CallbackServerConfig {
10
+ preferredPort: number;
11
+ host: string;
12
+ allowPortFallback: boolean;
13
+ }
14
+
5
15
  export type CallbackUrlValidationReason =
6
16
  | "invalid_url"
7
17
  | "wrong_origin"
@@ -34,6 +44,58 @@ export function isLocalCallbackHost(hostname: string): boolean {
34
44
  );
35
45
  }
36
46
 
47
+ /**
48
+ * Build callback server settings from the configured OAuth redirect URL.
49
+ *
50
+ * Local HTTP redirect URLs must use a fixed listener port because OAuth
51
+ * providers require exact redirect URI registration. When no local redirect URL
52
+ * is configured, the callback server keeps the historical default behavior and
53
+ * scans forward from the default port if needed.
54
+ */
55
+ export function callbackServerConfigFromRedirectUrl(redirectUrl?: string): CallbackServerConfig {
56
+ // WHY: Only treat `undefined` (omitted) as default; an explicit empty string `""`
57
+ // must fall through to `new URL("")` and throw a validation error.
58
+ if (redirectUrl === undefined) {
59
+ return {
60
+ preferredPort: DEFAULT_PORT,
61
+ host: DEFAULT_HOST,
62
+ allowPortFallback: true,
63
+ };
64
+ }
65
+
66
+ const url = new URL(redirectUrl);
67
+ if (url.protocol !== "http:" || !isLocalCallbackHost(url.hostname)) {
68
+ throw new Error("Manual OAuth redirect URL must use HTTP with localhost, 127.0.0.1, or ::1");
69
+ }
70
+
71
+ if (url.hash) {
72
+ throw new Error("Manual OAuth redirect URL must not include a fragment");
73
+ }
74
+
75
+ if (url.username || url.password) {
76
+ throw new Error("Manual OAuth redirect URL must not include credentials");
77
+ }
78
+
79
+ if (url.pathname !== CALLBACK_PATH) {
80
+ throw new Error(`Local OAuth redirect URL must use path ${CALLBACK_PATH}`);
81
+ }
82
+
83
+ if (!url.port) {
84
+ throw new Error("Manual OAuth redirect URL must include an explicit port (e.g. http://127.0.0.1:19876/callback)");
85
+ }
86
+
87
+ const preferredPort = Number(url.port);
88
+ if (preferredPort === 0) {
89
+ throw new Error("Manual OAuth redirect URL must use a fixed non-zero port");
90
+ }
91
+
92
+ return {
93
+ preferredPort,
94
+ host: url.hostname === "[::1]" ? "::1" : url.hostname,
95
+ allowPortFallback: false,
96
+ };
97
+ }
98
+
37
99
  /**
38
100
  * Validate that an OAuth authorization URL is safe to pass to a system browser opener.
39
101
  * Only allows `https:` URLs or loopback `http:` URLs (`localhost`, `127.0.0.1`, `::1`, `[::1]`).
@@ -72,8 +134,8 @@ function expectedRedirectUrl(redirectUrl: string | URL): URL {
72
134
  /** Reject a callback URL whose origin or path differs from the configured redirect URL. */
73
135
  function assertRedirectTargetMatches(url: URL, redirectUrl: string | URL | undefined): void {
74
136
  if (redirectUrl === undefined) {
75
- if (url.pathname !== "/callback") {
76
- throw new CallbackUrlValidationError("wrong_path", "Redirect URL path must be /callback");
137
+ if (url.pathname !== CALLBACK_PATH) {
138
+ throw new CallbackUrlValidationError("wrong_path", `Redirect URL path must be ${CALLBACK_PATH}`);
77
139
  }
78
140
  return;
79
141
  }