pi-mcp-extension 1.15.1 → 1.15.3
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 +12 -6
- package/package.json +1 -1
- package/src/auth-lock.ts +4 -24
- package/src/authorize-browser.ts +167 -0
- package/src/authorize-flow.ts +23 -122
- package/src/connect-policy.ts +1 -2
- package/src/connection-coordinator.ts +1 -2
- package/src/debug-log-format.ts +27 -301
- package/src/debug-log.ts +1 -1
- package/src/errors.ts +22 -0
- package/src/index.ts +1 -1
- package/src/oauth-policy.ts +45 -5
- package/src/oauth-provider.ts +3 -4
- package/src/oauth-state-store.ts +8 -42
- package/src/oauth-status.ts +2 -1
- package/src/register-commands.ts +3 -5
- package/src/register-tools.ts +3 -6
- package/src/resource-bridge.ts +2 -1
- package/src/secret-redaction.ts +304 -0
- package/src/server-manager.ts +5 -3
- package/src/server-status.ts +4 -3
- package/src/session-lifecycle.ts +1 -1
- package/src/startup-auth.ts +1 -1
- package/src/tool-bridge.ts +1 -1
- package/src/transport-factory.ts +2 -245
- package/src/transport-order.ts +258 -0
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
|
|
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
|
-
|
|
363
|
-
|
|
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`),
|
|
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.
|
|
3
|
+
"version": "1.15.3",
|
|
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
|
|
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
|
-
|
|
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,167 @@
|
|
|
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
|
+
serverName?: string | undefined;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface BrowserLauncherContext {
|
|
47
|
+
ui: Pick<ExtensionUIContext, "notify">;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface BrowserLauncherParams {
|
|
51
|
+
serverName: string;
|
|
52
|
+
port: number;
|
|
53
|
+
ctx: BrowserLauncherContext;
|
|
54
|
+
browserOpener: (url: string) => void | Promise<void>;
|
|
55
|
+
isInactive: () => boolean;
|
|
56
|
+
onUrlRecorded: (url: URL) => void;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function browserOpenCommand(
|
|
60
|
+
url: string,
|
|
61
|
+
platform: NodeJS.Platform = process.platform,
|
|
62
|
+
): BrowserOpenCommand {
|
|
63
|
+
if (platform === "darwin") {
|
|
64
|
+
return { command: "open", args: [url] };
|
|
65
|
+
}
|
|
66
|
+
if (platform === "win32") {
|
|
67
|
+
return { command: "rundll32", args: ["url.dll,FileProtocolHandler", url] };
|
|
68
|
+
}
|
|
69
|
+
return { command: "xdg-open", args: [url] };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Open a URL in the user's default browser.
|
|
74
|
+
* Works on macOS, Linux, and Windows.
|
|
75
|
+
*/
|
|
76
|
+
export function openBrowser(url: string, deps?: OpenBrowserDeps): Promise<void> {
|
|
77
|
+
// WHY: This public entry point must enforce the URL policy independently of its callers,
|
|
78
|
+
// and require a string primitive so a non-string object with a stateful `toString()`
|
|
79
|
+
// cannot pass validation and mutate before `new URL(url)`.
|
|
80
|
+
if (typeof url !== "string" || !isSafeAuthorizationUrl(url)) {
|
|
81
|
+
return Promise.reject(
|
|
82
|
+
new McpError(
|
|
83
|
+
"Refusing to open unsafe authorization URL: only HTTPS (or loopback HTTP) URLs are allowed",
|
|
84
|
+
deps?.serverName ?? "<oauth>",
|
|
85
|
+
"protocol",
|
|
86
|
+
),
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
const safeHref = new URL(url).toString();
|
|
90
|
+
const spawnProcess: BrowserSpawn = deps?.spawnProcess ?? spawn;
|
|
91
|
+
const { command, args } = browserOpenCommand(safeHref, deps?.platform);
|
|
92
|
+
return new Promise<void>((resolve, reject) => {
|
|
93
|
+
const child = spawnProcess(command, args, {
|
|
94
|
+
detached: true,
|
|
95
|
+
stdio: "ignore",
|
|
96
|
+
windowsHide: true,
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
child.once("error", (err) => {
|
|
100
|
+
reportDiagnostic({
|
|
101
|
+
level: "error",
|
|
102
|
+
event: "auth.browser_open_failed",
|
|
103
|
+
message: `Failed to open browser: ${sanitizeTerminalText(err.message)}`,
|
|
104
|
+
});
|
|
105
|
+
reject(err);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
child.once("spawn", () => {
|
|
109
|
+
child.unref();
|
|
110
|
+
resolve();
|
|
111
|
+
});
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Build the `onAuthRequired` hook: refuse unsafe URLs, remember the last URL for
|
|
117
|
+
* "Retry", open the browser, and tell the user how to finish on a remote host.
|
|
118
|
+
*/
|
|
119
|
+
export function createAuthorizationBrowserLauncher(
|
|
120
|
+
params: BrowserLauncherParams,
|
|
121
|
+
): (url: URL) => Promise<void> {
|
|
122
|
+
const { serverName, port, ctx, browserOpener, isInactive, onUrlRecorded } = params;
|
|
123
|
+
return async (url: URL): Promise<void> => {
|
|
124
|
+
if (!isSafeAuthorizationUrl(url)) {
|
|
125
|
+
throw new McpError(
|
|
126
|
+
`Refusing to open unsafe authorization URL for "${serverName}": only HTTPS (or loopback HTTP) URLs are allowed`,
|
|
127
|
+
serverName,
|
|
128
|
+
"protocol",
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
const href = url.toString();
|
|
132
|
+
onUrlRecorded(new URL(href));
|
|
133
|
+
if (isInactive()) return;
|
|
134
|
+
try {
|
|
135
|
+
await browserOpener(href);
|
|
136
|
+
ctx.ui.notify(
|
|
137
|
+
`pi-mcp: Authorize ${serverName}: ${href} (On SSH, forward the callback with ssh -L ${port}:127.0.0.1:${port}, or choose "${authPasteOption}".)`,
|
|
138
|
+
"info",
|
|
139
|
+
);
|
|
140
|
+
} catch (err) {
|
|
141
|
+
const detail = sanitizeTerminalText(err instanceof Error ? err.message : String(err));
|
|
142
|
+
ctx.ui.notify(
|
|
143
|
+
`pi-mcp: Failed to open browser for ${serverName} (${detail}). Open ${href} manually or choose "${authPasteOption}".`,
|
|
144
|
+
"error",
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Re-open the last authorization URL when the user retries from the dialog.
|
|
152
|
+
*/
|
|
153
|
+
export function reopenAuthorizationBrowser(
|
|
154
|
+
launchAuthorizationBrowser: (url: URL) => Promise<void>,
|
|
155
|
+
getLatestAuthorizationUrl: () => URL | undefined,
|
|
156
|
+
serverName: string,
|
|
157
|
+
): Promise<void> {
|
|
158
|
+
const latestAuthorizationUrl = getLatestAuthorizationUrl();
|
|
159
|
+
if (!latestAuthorizationUrl) {
|
|
160
|
+
throw new McpError(
|
|
161
|
+
`Authorization URL is not available for ${serverName}`,
|
|
162
|
+
serverName,
|
|
163
|
+
"protocol",
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
return launchAuthorizationBrowser(latestAuthorizationUrl);
|
|
167
|
+
}
|
package/src/authorize-flow.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
} from "./
|
|
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: () =>
|
|
566
|
+
reopenBrowser: () =>
|
|
567
|
+
reopenAuthorizationBrowser(
|
|
568
|
+
launchAuthorizationBrowser,
|
|
569
|
+
() => state.latestAuthorizationUrl,
|
|
570
|
+
serverName,
|
|
571
|
+
),
|
|
671
572
|
onPasteResolved: cancel,
|
|
672
573
|
assertActive,
|
|
673
574
|
});
|
package/src/connect-policy.ts
CHANGED
|
@@ -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,
|