pi-mcp-extension 1.14.6 → 1.15.1
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 +13 -8
- package/package.json +1 -1
- package/src/callback-server.ts +9 -64
- package/src/callback-url.ts +64 -2
- package/src/commands.ts +2 -41
- package/src/config-compat.ts +187 -0
- package/src/config.ts +153 -306
- package/src/connect-policy.ts +127 -1
- package/src/debug-log-format.ts +63 -3
- package/src/index.ts +31 -884
- package/src/mcp-client.ts +423 -0
- package/src/oauth-policy.ts +327 -0
- package/src/oauth-provider.ts +140 -378
- package/src/oauth-state-store.ts +1 -16
- package/src/register-tools.ts +257 -0
- package/src/schema-allof.ts +272 -0
- package/src/schema-convert.ts +9 -245
- package/src/server-manager.ts +96 -341
- package/src/session-lifecycle.ts +705 -0
- package/src/stdio-process.ts +66 -0
- package/src/tool-bridge.ts +99 -280
- package/src/tool-content.ts +158 -0
- package/src/tool-names.ts +146 -0
- package/src/transport-factory.ts +257 -4
package/README.md
CHANGED
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
- **Multi-transport** — `stdio` subprocesses, `streamable-http` (including `"http"` and URL-only shorthand), and legacy `sse` out of the box
|
|
21
21
|
- **Auto-discovery** — Paginated `tools/list` with cursor following (MCP 2025-03-26 spec)
|
|
22
22
|
- **Live tool refresh** — `notifications/tools/list_changed` triggers re-discovery without restart
|
|
23
|
+
- **Live tool progress** — a server's `notifications/progress` events stream into Pi as live tool-call updates (server text is sanitized and secret-redacted, repeated lines are collapsed), and every notification restarts the per-request timeout, so a long-running tool that keeps reporting — a browser flow, migration, or test runner — is no longer killed at `requestTimeoutMs` while it is demonstrably working
|
|
23
24
|
- **Clean cancellation** — `AbortSignal` propagation via `notifications/cancelled`
|
|
24
25
|
- **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
|
|
25
26
|
- **Health checks** — Opt-in periodic pings to detect stale connections
|
|
@@ -167,7 +168,7 @@ In project-level `.pi/mcp.json`, `settings` keys carry no defaults — only the
|
|
|
167
168
|
| Field | Type | Default | Description |
|
|
168
169
|
|---|---|---|---|
|
|
169
170
|
| `toolPrefix` | `string` | `"mcp"` | Prefix for registered tools: `<prefix>_<server>_<tool>`. Must match `^[a-zA-Z][a-zA-Z0-9_]*$`. |
|
|
170
|
-
| `requestTimeoutMs` | `number` | `30000` | Default per-request timeout in milliseconds |
|
|
171
|
+
| `requestTimeoutMs` | `number` | `30000` | Default per-request timeout in milliseconds. For `tools/call` this is an inactivity deadline: every `notifications/progress` event from the server restarts it, so page-by-page work is not cut off mid-flight. A server that reports progress indefinitely has no wall-clock cap — cancel the tool to stop it |
|
|
171
172
|
| `maxRetries` | `number` | `5` | Max reconnection attempts (0–10) before giving up |
|
|
172
173
|
|
|
173
174
|
### Per-Server Config
|
|
@@ -334,7 +335,7 @@ The log is written to `<agent dir>/logs/pi-mcp.log` (JSON Lines, one event per l
|
|
|
334
335
|
- 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`)
|
|
335
336
|
- Credential-bearing query parameters on a server URL (`?api_key=…`, `?token=…`, `?code=…`)
|
|
336
337
|
- `Authorization` headers in any scheme or quoting, and URL userinfo passwords (`https://user:password@host`)
|
|
337
|
-
- 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.
|
|
338
|
+
- The same redactor protects the per-server `Recent output:` (`stderr`) buffer, handshake `instructions`, `notifications/progress` tool updates, the `Last error:` line in `/mcp` and `/mcp <name>`, and user-facing start/auth/recovery failure notifications.
|
|
338
339
|
- **Best-effort.** A failed log write never breaks a connection or a tool call.
|
|
339
340
|
|
|
340
341
|
Attach the file to a bug report. It contains no credentials.
|
|
@@ -346,8 +347,9 @@ While a Pi UI is active, the extension never writes diagnostics to Pi's stderr (
|
|
|
346
347
|
```mermaid
|
|
347
348
|
flowchart TD
|
|
348
349
|
subgraph Pi["Pi Coding Agent (TUI / RPC, ExtensionAPI)"]
|
|
349
|
-
Entry["index.ts (entry &
|
|
350
|
-
Cmds["register-commands (/mcp, :start, :stop, :auth)"]
|
|
350
|
+
Entry["index.ts (entry & session lifecycle)"]
|
|
351
|
+
Cmds["register-commands (/mcp, :start, :stop, :auth, :resources)"]
|
|
352
|
+
Tools["register-tools (mcp_* agent tools)"]
|
|
351
353
|
Config["config (Zod + JSONC)"]
|
|
352
354
|
Coord["connection-coordinator (in-flight connects, authQueue, teardown)"]
|
|
353
355
|
Mgr["server-manager (stopped -> starting -> ready lifecycle)"]
|
|
@@ -356,9 +358,11 @@ flowchart TD
|
|
|
356
358
|
Transport["transport-factory & oauth-provider (MCP SDK)"]
|
|
357
359
|
|
|
358
360
|
Entry --> Cmds
|
|
361
|
+
Entry --> Tools
|
|
359
362
|
Entry --> Config
|
|
360
363
|
Entry --> Coord
|
|
361
364
|
Cmds --> Coord
|
|
365
|
+
Tools --> Coord
|
|
362
366
|
Coord --> Mgr
|
|
363
367
|
Mgr --> Bridge
|
|
364
368
|
Bridge --> Schema
|
|
@@ -378,7 +382,7 @@ flowchart TD
|
|
|
378
382
|
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)
|
|
379
383
|
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`, `resource_link`, and `audio` results. When one server exposes two tools that sanitize to the same identifier, the name that needed no substitution keeps the unhashed form (`my_tool` over `my-tool`), remaining ties break by the raw name's code-point order, and the assignment does not depend on `tools/list` order — so a reconnect cannot swap which MCP tool a Pi name executes. Embedded image resources become image blocks, binary resources include MIME type and byte count, and resource links include a `mcp_read_resource` hint.
|
|
380
384
|
6. **Tools activate/deactivate** automatically as servers connect/disconnect, always in one deterministic order — the bridge's tools are sorted by Pi name among the slots they occupy, and other extensions' tools keep their positions — so connect timing and `tools/list` order cannot change the prompt head
|
|
381
|
-
7. **AbortSignal**
|
|
385
|
+
7. **AbortSignal and progress** are wired through to `notifications/cancelled` for clean cancellation and `notifications/progress` for live sanitized tool updates plus inactivity-timeout resets
|
|
382
386
|
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
|
|
383
387
|
9. **`list_changed` notifications** trigger re-discovery, deactivating stale tools automatically and invalidating the cached resource catalog
|
|
384
388
|
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` — a PID the kernel refuses to signal is left alone instead of being polled — and pipe cleanup for `stdio` child processes)
|
|
@@ -402,6 +406,7 @@ Implements the **MCP 2025-03-26** specification for tool and resource clients:
|
|
|
402
406
|
| `roots/list` capability (workspace root) | ✅ |
|
|
403
407
|
| `notifications/tools/list_changed` (live refresh) | ✅ |
|
|
404
408
|
| `notifications/cancelled` (AbortSignal) | ✅ |
|
|
409
|
+
| `notifications/progress` (live sanitized tool updates + inactivity timeout reset) | ✅ |
|
|
405
410
|
| `notifications/message` (structured logging) | ✅ |
|
|
406
411
|
| `isError: true` distinction (protocol vs tool errors, non-text filtered on error) | ✅ |
|
|
407
412
|
| Tool annotations (`readOnlyHint`, `destructiveHint`, etc.) in descriptions and as structured Pi `annotations` | ✅ |
|
|
@@ -441,11 +446,11 @@ npm pack --dry-run
|
|
|
441
446
|
|
|
442
447
|
The test suite includes:
|
|
443
448
|
- **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`
|
|
444
|
-
- **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
|
|
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
|
|
445
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
|
|
446
|
-
- **Tool bridge, status diagnostics & debug log** (`tests/tool-bridge.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, `mcp_status` / `mcp_connect`, `/mcp <name>` config provenance and failure hints, slash command completions, and redacted `PI_MCP_DEBUG=1` JSONL logging
|
|
451
|
+
- **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
|
|
447
452
|
- **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`
|
|
448
|
-
- **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,
|
|
453
|
+
- **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
|
|
449
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
|
|
450
455
|
- **End-to-end integration** — Real mock MCP and OAuth servers over `stdio` and HTTP with tool discovery and execution
|
|
451
456
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-mcp-extension",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.15.1",
|
|
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/callback-server.ts
CHANGED
|
@@ -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 {
|
|
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
|
|
389
|
-
export { DEFAULT_PORT, DEFAULT_HOST,
|
|
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";
|
package/src/callback-url.ts
CHANGED
|
@@ -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 !==
|
|
76
|
-
throw new CallbackUrlValidationError("wrong_path",
|
|
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
|
}
|
package/src/commands.ts
CHANGED
|
@@ -1,11 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Command argument parsing
|
|
3
|
-
* config merging helpers for `/mcp*` commands.
|
|
2
|
+
* Command argument parsing and tab completions for `/mcp*` commands.
|
|
4
3
|
*/
|
|
5
4
|
|
|
6
|
-
import type { RegisteredMcpServer } from "@earendil-works/pi-coding-agent";
|
|
7
|
-
import { parseRegisteredServerConfig, type McpConfig, type ServerConfig } from "./config.js";
|
|
8
|
-
|
|
9
5
|
function stripResetFlag(name: string): { name: string; reset: boolean } {
|
|
10
6
|
// WHY: Support standalone `--reset` as well as leading (`--reset <name>`) and trailing (`<name> --reset`)
|
|
11
7
|
// flag positions so `/mcp:auth --reset` prints the usage message rather than looking up a server named "--reset".
|
|
@@ -92,39 +88,4 @@ export function serverNameCompletions(
|
|
|
92
88
|
return completions.length > 0 ? completions : null;
|
|
93
89
|
}
|
|
94
90
|
|
|
95
|
-
export
|
|
96
|
-
entries: readonly RegisteredMcpServer[],
|
|
97
|
-
fileServers: Record<string, ServerConfig>,
|
|
98
|
-
onError?: (err: unknown) => void,
|
|
99
|
-
): Record<string, ServerConfig> {
|
|
100
|
-
const registered: Record<string, ServerConfig> = {};
|
|
101
|
-
for (const entry of entries) {
|
|
102
|
-
// Servers configured in mcp.json take precedence over extension-registered servers.
|
|
103
|
-
if (Object.prototype.hasOwnProperty.call(fileServers, entry.name)) {
|
|
104
|
-
continue;
|
|
105
|
-
}
|
|
106
|
-
try {
|
|
107
|
-
registered[entry.name] = parseRegisteredServerConfig(
|
|
108
|
-
entry.name,
|
|
109
|
-
entry.config,
|
|
110
|
-
entry.extensionPath || "<extension>",
|
|
111
|
-
);
|
|
112
|
-
} catch (err) {
|
|
113
|
-
onError?.(err);
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
return registered;
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
export function mergeWithRegisteredServers(
|
|
120
|
-
fileConfig: McpConfig,
|
|
121
|
-
registeredServers: Record<string, ServerConfig>,
|
|
122
|
-
): McpConfig {
|
|
123
|
-
return {
|
|
124
|
-
settings: fileConfig.settings,
|
|
125
|
-
mcpServers: {
|
|
126
|
-
...registeredServers,
|
|
127
|
-
...fileConfig.mcpServers,
|
|
128
|
-
},
|
|
129
|
-
};
|
|
130
|
-
}
|
|
91
|
+
export { collectRegisteredServers, mergeWithRegisteredServers } from "./session-lifecycle.js";
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure Pi 1.x / Pi 1.3.0 raw configuration alias normalization and partial project override
|
|
3
|
+
* merging. Runs on unvalidated JSON structures prior to Zod schema parsing, with zero dependency
|
|
4
|
+
* on `zod`, `node:fs`, or `node:http`.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { McpError } from "./errors.js";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Keys a Pi 1.3.0 project entry may override on the global entry of the same name (`/mcp` writes
|
|
11
|
+
* such an entry as soon as a global server is disabled or its exposure is changed for one project).
|
|
12
|
+
* `exposure` / `toolExposure` are Pi-native tool-exposure settings: they are accepted so a shared
|
|
13
|
+
* `mcp.json` loads, and ignored because this extension decides tool activation itself. `lifecycle`
|
|
14
|
+
* is this extension's equivalent of `enabled`.
|
|
15
|
+
*/
|
|
16
|
+
export const PROJECT_OVERRIDE_KEYS = ["enabled", "exposure", "toolExposure", "lifecycle"] as const;
|
|
17
|
+
|
|
18
|
+
export function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
19
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Rewrite Pi 1.x OAuth config aliases (`callbackUrl`, `callbackPort`) onto `redirectUrl` before
|
|
24
|
+
* schema validation.
|
|
25
|
+
*/
|
|
26
|
+
export function normalizeAuthConfigAliases(raw: unknown): unknown {
|
|
27
|
+
if (!isPlainObject(raw)) return raw;
|
|
28
|
+
const obj: Record<string, unknown> = { ...raw };
|
|
29
|
+
if (obj.redirectUrl === undefined) {
|
|
30
|
+
if (typeof obj.callbackUrl === "string") {
|
|
31
|
+
obj.redirectUrl = obj.callbackUrl;
|
|
32
|
+
} else if (typeof obj.callbackPort === "number") {
|
|
33
|
+
obj.redirectUrl = `http://127.0.0.1:${obj.callbackPort}/callback`;
|
|
34
|
+
} else if (obj.callbackUrl !== undefined) {
|
|
35
|
+
obj.redirectUrl = obj.callbackUrl;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
delete obj.callbackUrl;
|
|
39
|
+
delete obj.callbackPort;
|
|
40
|
+
return obj;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Map legacy `type`/`url`-only entries onto an explicit `transport`. */
|
|
44
|
+
function normalizeTransportAlias(obj: Record<string, unknown>): void {
|
|
45
|
+
const rawTransport = obj.transport ?? obj.type;
|
|
46
|
+
if (rawTransport === "http") {
|
|
47
|
+
obj.transport = "streamable-http";
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (obj.transport !== undefined) {
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
if (rawTransport !== undefined) {
|
|
54
|
+
obj.transport = rawTransport;
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (obj.url !== undefined && obj.command === undefined) {
|
|
58
|
+
obj.transport = "streamable-http";
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Map the legacy `oauth` object onto `auth`. */
|
|
63
|
+
function normalizeAuthAlias(obj: Record<string, unknown>): void {
|
|
64
|
+
if (obj.auth !== undefined) {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (isPlainObject(obj.oauth)) {
|
|
68
|
+
obj.auth = obj.oauth;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Map Pi 1.3.0 `enabled: false` onto `lifecycle: "lazy"`. Pi keeps a disabled entry configured but
|
|
74
|
+
* out of the connect set; the closest behavior here is the lazy lifecycle (manual `/mcp:start`).
|
|
75
|
+
* An explicit `lifecycle: "eager"` never wins over `enabled: false`, which is what Pi does too.
|
|
76
|
+
*/
|
|
77
|
+
function normalizeEnabledAlias(obj: Record<string, unknown>): void {
|
|
78
|
+
if (obj.enabled === false) {
|
|
79
|
+
obj.lifecycle = "lazy";
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Map legacy `timeout` (seconds) onto `requestTimeoutMs` (milliseconds). */
|
|
84
|
+
function normalizeTimeoutAlias(obj: Record<string, unknown>): void {
|
|
85
|
+
if (obj.requestTimeoutMs !== undefined) {
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (typeof obj.timeout !== "number" || obj.timeout <= 0) {
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
obj.requestTimeoutMs = obj.timeout * 1000;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Rewrite Pi 1.x config aliases (`type`, `oauth`, `timeout`, `enabled`) before schema validation. */
|
|
95
|
+
export function normalizeServerConfigAliases(raw: unknown): unknown {
|
|
96
|
+
if (!isPlainObject(raw)) return raw;
|
|
97
|
+
const obj: Record<string, unknown> = { ...raw };
|
|
98
|
+
normalizeTransportAlias(obj);
|
|
99
|
+
normalizeAuthAlias(obj);
|
|
100
|
+
normalizeTimeoutAlias(obj);
|
|
101
|
+
normalizeEnabledAlias(obj);
|
|
102
|
+
return obj;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Default extension-registered servers (`pi.registerMcpServer()`) to `lifecycle: "eager"` unless
|
|
107
|
+
* `lifecycle` is explicitly specified or `enabled` is `false`.
|
|
108
|
+
*/
|
|
109
|
+
export function withRegisteredServerLifecycle(raw: unknown): unknown {
|
|
110
|
+
if (!isPlainObject(raw) || raw.lifecycle !== undefined) {
|
|
111
|
+
return raw;
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
...raw,
|
|
115
|
+
lifecycle: raw.enabled === false ? "lazy" : "eager",
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** A project entry without a transport definition only overrides the global server of that name. */
|
|
120
|
+
export function isProjectOverrideEntry(value: unknown): value is Record<string, unknown> {
|
|
121
|
+
if (!isPlainObject(value)) return false;
|
|
122
|
+
return (
|
|
123
|
+
value.command === undefined &&
|
|
124
|
+
value.url === undefined &&
|
|
125
|
+
value.type === undefined &&
|
|
126
|
+
value.transport === undefined
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function invalidProjectConfig(projectPath: string, detail: string): McpError {
|
|
131
|
+
return new McpError(`Invalid mcp.json at ${projectPath}:\n ${detail}`, "<config>", "config");
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Merge a partial project override onto the raw global entry, keeping the global credentials. */
|
|
135
|
+
function mergeProjectOverride(
|
|
136
|
+
name: string,
|
|
137
|
+
override: Record<string, unknown>,
|
|
138
|
+
globalServers: Record<string, unknown>,
|
|
139
|
+
projectPath: string,
|
|
140
|
+
): Record<string, unknown> {
|
|
141
|
+
const base = globalServers[name];
|
|
142
|
+
if (!isPlainObject(base)) {
|
|
143
|
+
throw invalidProjectConfig(
|
|
144
|
+
projectPath,
|
|
145
|
+
`mcpServers.${name}: a project override needs "command" or "url" in this file, or a global server of that name`,
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
const unsupported = Object.keys(override).filter(
|
|
149
|
+
(key) => !(PROJECT_OVERRIDE_KEYS as readonly string[]).includes(key),
|
|
150
|
+
);
|
|
151
|
+
if (unsupported.length > 0) {
|
|
152
|
+
throw invalidProjectConfig(
|
|
153
|
+
projectPath,
|
|
154
|
+
`mcpServers.${name}: a project override can only set ${PROJECT_OVERRIDE_KEYS.join(", ")} (found ${unsupported.join(", ")})`,
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
const merged: Record<string, unknown> = { ...base };
|
|
158
|
+
if (override.lifecycle !== undefined && override.enabled === undefined) {
|
|
159
|
+
delete merged.enabled;
|
|
160
|
+
}
|
|
161
|
+
for (const key of PROJECT_OVERRIDE_KEYS) {
|
|
162
|
+
if (override[key] !== undefined) {
|
|
163
|
+
merged[key] = override[key];
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return merged;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Resolve Pi 1.3.0 partial project entries (`{ "<server>": { "enabled": false } }`) against the raw
|
|
171
|
+
* global file *before* validation, so `ProjectConfigSchema` sees a complete entry instead of
|
|
172
|
+
* failing with `"command" is required for stdio transport` (which tore down every global server on
|
|
173
|
+
* `session_start`).
|
|
174
|
+
*/
|
|
175
|
+
export function applyProjectOverrides(projectRaw: unknown, globalRaw: unknown, projectPath: string): unknown {
|
|
176
|
+
if (!isPlainObject(projectRaw) || !isPlainObject(projectRaw.mcpServers)) return projectRaw;
|
|
177
|
+
const globalServers = isPlainObject(globalRaw) && isPlainObject(globalRaw.mcpServers)
|
|
178
|
+
? globalRaw.mcpServers
|
|
179
|
+
: {};
|
|
180
|
+
const servers: Record<string, unknown> = {};
|
|
181
|
+
for (const [name, value] of Object.entries(projectRaw.mcpServers)) {
|
|
182
|
+
servers[name] = isProjectOverrideEntry(value)
|
|
183
|
+
? mergeProjectOverride(name, value, globalServers, projectPath)
|
|
184
|
+
: value;
|
|
185
|
+
}
|
|
186
|
+
return { ...projectRaw, mcpServers: servers };
|
|
187
|
+
}
|