pi-mcp-extension 1.16.4 → 1.16.6

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
@@ -351,7 +351,8 @@ Recent output:
351
351
 
352
352
  ### OAuth startup, headless/SSH, and concurrency behavior
353
353
 
354
- - **Interactive sessions required for browser auth**: Print and RPC sessions fail promptly when interactive authorization is required.
354
+ - **Authorization by Pi mode**: TUI and RPC (`--mode rpc`) support interactive OAuth authorization. In RPC mode, Pi sends `extension_ui_request` (`select` / `input`) events that the RPC host must answer or cancel via `extension_ui_response` (`{"value": "..."}` or `{"cancelled": true}`). Print (`-p` / `--print`) and JSON (`--mode json`) cannot show interactive dialogs and fail promptly when browser authorization is required.
355
+ - **Serialized OAuth dialogs in RPC**: An unanswered startup prompt holds the interactive authorization queue for subsequent OAuth flows until the RPC host answers or cancels the dialog, or stops that server with `/mcp:stop <name>`; non-OAuth servers and OAuth servers with valid stored tokens can connect without waiting.
355
356
  - **Startup prompt for eager OAuth servers**: Silent startup and background reconnects never open a browser unprompted or trigger Dynamic Client Registration when no client credentials are stored. When an `eager` OAuth server needs interactive authorization at startup in an interactive Pi session, Pi presents a sequential `<name> needs authorization` prompt (`Authorize now` / `Not now`). Choosing `Authorize now` runs the interactive OAuth flow; choosing `Not now` leaves the server stopped, shows a `run /mcp:auth <name>` footer hint, and remembers the decline for the rest of the session.
356
357
  - **Headless and SSH support**: While authorization is pending, Pi displays the authorization URL and offers `Retry: open browser again`, `Paste redirect URL`, and `Cancel authentication`. On remote/SSH or headless machines, open the URL locally and either forward the callback port (`ssh -L <port>:127.0.0.1:<port>`) or paste the browser's final `http://127.0.0.1:<port>/callback?code=...&state=...` redirect URL into `Paste redirect URL`. Only `https:` (or loopback `http:`) authorization URLs are passed to the system browser opener.
357
358
  - **Coordinated connects and cross-process locks**: Concurrent connect requests join an in-flight attempt, while `--reset` supersedes a normal connect and shares one pending reset. Cross-process interactive flows are serialized per server via `<agent dir>/mcp-auth/<hash>.json.lock` with a 30s heartbeat and automatic reclamation of locks from dead local PIDs or stale heartbeats (>90s), while allowing silent token refreshes to persist rotated tokens.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mcp-extension",
3
- "version": "1.16.4",
3
+ "version": "1.16.6",
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": [
@@ -188,28 +188,52 @@ function invalidProjectConfig(projectPath: string, detail: string): McpError {
188
188
  return new McpError(`Invalid mcp.json at ${projectPath}:\n ${detail}`, "<config>", "config");
189
189
  }
190
190
 
191
- /** Merge a partial project override onto the raw global entry, keeping the global credentials. */
192
- function mergeProjectOverride(
191
+ export type ProjectOverrideResolution =
192
+ | { ok: true; value: Record<string, unknown> }
193
+ | { ok: false; error: McpError };
194
+
195
+ /**
196
+ * Return a config `McpError` when a partial project override sets keys outside
197
+ * `PROJECT_OVERRIDE_KEYS`, or `undefined` when all keys are allowed.
198
+ */
199
+ export function validateProjectOverrideKeys(
200
+ name: string,
201
+ override: Record<string, unknown>,
202
+ projectPath: string,
203
+ ): McpError | undefined {
204
+ const unsupported = Object.keys(override).filter(
205
+ (key) => !(PROJECT_OVERRIDE_KEYS as readonly string[]).includes(key),
206
+ );
207
+ if (unsupported.length === 0) return undefined;
208
+ return invalidProjectConfig(
209
+ projectPath,
210
+ `mcpServers.${name}: a project override can only set ${PROJECT_OVERRIDE_KEYS.join(", ")} (found ${unsupported.join(", ")})`,
211
+ );
212
+ }
213
+
214
+ /**
215
+ * Resolve a partial project override onto the raw global entry, returning either the merged
216
+ * candidate or a config `McpError` without throwing.
217
+ */
218
+ export function resolveProjectOverride(
193
219
  name: string,
194
220
  override: Record<string, unknown>,
195
221
  globalServers: Record<string, unknown>,
196
222
  projectPath: string,
197
- ): Record<string, unknown> {
223
+ ): ProjectOverrideResolution {
198
224
  const base = Object.hasOwn(globalServers, name) ? globalServers[name] : undefined;
199
225
  if (!isPlainObject(base)) {
200
- throw invalidProjectConfig(
201
- projectPath,
202
- `mcpServers.${name}: a project override needs "command" or "url" in this file, or a global server of that name`,
203
- );
226
+ return {
227
+ ok: false,
228
+ error: invalidProjectConfig(
229
+ projectPath,
230
+ `mcpServers.${name}: a project override needs "command" or "url" in this file, or a global server of that name`,
231
+ ),
232
+ };
204
233
  }
205
- const unsupported = Object.keys(override).filter(
206
- (key) => !(PROJECT_OVERRIDE_KEYS as readonly string[]).includes(key),
207
- );
208
- if (unsupported.length > 0) {
209
- throw invalidProjectConfig(
210
- projectPath,
211
- `mcpServers.${name}: a project override can only set ${PROJECT_OVERRIDE_KEYS.join(", ")} (found ${unsupported.join(", ")})`,
212
- );
234
+ const keyError = validateProjectOverrideKeys(name, override, projectPath);
235
+ if (keyError) {
236
+ return { ok: false, error: keyError };
213
237
  }
214
238
  const merged: Record<string, unknown> = { ...base };
215
239
  if (override.lifecycle !== undefined && override.enabled === undefined) {
@@ -220,7 +244,21 @@ function mergeProjectOverride(
220
244
  merged[key] = override[key];
221
245
  }
222
246
  }
223
- return merged;
247
+ return { ok: true, value: merged };
248
+ }
249
+
250
+ /** Merge a partial project override onto the raw global entry, keeping the global credentials. */
251
+ function mergeProjectOverride(
252
+ name: string,
253
+ override: Record<string, unknown>,
254
+ globalServers: Record<string, unknown>,
255
+ projectPath: string,
256
+ ): Record<string, unknown> {
257
+ const resolution = resolveProjectOverride(name, override, globalServers, projectPath);
258
+ if (!resolution.ok) {
259
+ throw resolution.error;
260
+ }
261
+ return resolution.value;
224
262
  }
225
263
 
226
264
  /**
@@ -236,9 +274,15 @@ export function applyProjectOverrides(projectRaw: unknown, globalRaw: unknown, p
236
274
  : {};
237
275
  const servers: Record<string, unknown> = {};
238
276
  for (const [name, value] of Object.entries(projectRaw.mcpServers)) {
239
- servers[name] = isProjectOverrideEntry(value)
277
+ const resolved = isProjectOverrideEntry(value)
240
278
  ? mergeProjectOverride(name, value, globalServers, projectPath)
241
279
  : value;
280
+ Object.defineProperty(servers, name, {
281
+ value: resolved,
282
+ enumerable: true,
283
+ writable: true,
284
+ configurable: true,
285
+ });
242
286
  }
243
287
  return { ...projectRaw, mcpServers: servers };
244
288
  }
package/src/config.ts CHANGED
@@ -19,8 +19,12 @@ import { z } from "zod";
19
19
  import { callbackServerConfigFromRedirectUrl } from "./callback-url.js";
20
20
  import {
21
21
  applyProjectOverrides,
22
+ isPlainObject,
23
+ isProjectOverrideEntry,
22
24
  normalizeAuthConfigAliases,
23
25
  normalizeServerConfigAliases,
26
+ resolveProjectOverride,
27
+ validateProjectOverrideKeys,
24
28
  withRegisteredServerLifecycle,
25
29
  } from "./config-compat.js";
26
30
  import { McpError } from "./errors.js";
@@ -249,15 +253,18 @@ const SettingsSchema = z.object({
249
253
  maxRetries: z.number().int().min(0).max(10).default(DEFAULT_SETTINGS.maxRetries),
250
254
  });
251
255
 
252
- const McpConfigSchema = z.object({
256
+ const McpConfigEnvelopeSchema = z.object({
253
257
  settings: SettingsSchema.default(() => ({ ...DEFAULT_SETTINGS })),
254
- mcpServers: z.record(z.string(), ServerConfigSchema).default({}),
258
+ mcpServers: z.record(z.string(), z.unknown()).default({}),
255
259
  /**
256
260
  * Pi 1.3.0 top-level switch (default `true` when omitted): activate the built-in `codemode`
257
261
  * tool automatically when a server with `"codemode"` exposure connects.
258
262
  */
259
263
  autoEnableCodemode: z.boolean().optional(),
260
264
  });
265
+ const McpConfigSchema = McpConfigEnvelopeSchema.extend({
266
+ mcpServers: z.record(z.string(), ServerConfigSchema).default({}),
267
+ });
261
268
 
262
269
  /**
263
270
  * Project-level file: `settings` keys are optional and carry NO defaults, so a project file
@@ -272,13 +279,26 @@ const ProjectSettingsSchema = z.object({
272
279
  requestTimeoutMs: z.number().positive().optional(),
273
280
  maxRetries: z.number().int().min(0).max(10).optional(),
274
281
  });
275
- const ProjectConfigSchema = z.object({
282
+ const ProjectConfigEnvelopeSchema = z.object({
276
283
  settings: ProjectSettingsSchema.default({}),
277
- mcpServers: z.record(z.string(), ServerConfigSchema).default({}),
284
+ mcpServers: z.record(z.string(), z.unknown()).default({}),
278
285
  autoEnableCodemode: z.boolean().optional(),
279
286
  });
287
+ const ProjectConfigSchema = ProjectConfigEnvelopeSchema.extend({
288
+ mcpServers: z.record(z.string(), ServerConfigSchema).default({}),
289
+ });
280
290
  type ProjectConfig = z.output<typeof ProjectConfigSchema>;
281
291
 
292
+ const ProjectOverrideFieldsSchema = z.preprocess(
293
+ normalizeServerConfigAliases,
294
+ ServerConfigObjectSchema.pick({
295
+ enabled: true,
296
+ lifecycle: true,
297
+ exposure: true,
298
+ toolExposure: true,
299
+ }),
300
+ );
301
+
282
302
  // ─── Public Types ─────────────────────────────────────────────────────────────
283
303
 
284
304
  export type AuthConfig = z.output<typeof AuthConfigSchema>;
@@ -310,6 +330,20 @@ export interface LoadConfigOptions {
310
330
  includeProjectConfig?: boolean;
311
331
  }
312
332
 
333
+ /** Result of fault-tolerant session config loading with isolated per-server errors. */
334
+ export interface SessionConfigLoadResult {
335
+ loaded: LoadedConfig;
336
+ serverErrors: McpError[];
337
+ /**
338
+ * Server names rejected from `mcp.json` that must not fall back to global or
339
+ * extension-registered entries of the same name (failed global entries, broken
340
+ * project overrides of global entries, and broken full project entries).
341
+ * Partial project overrides targeting a name absent from global `mcp.json` are
342
+ * excluded so an extension-registered server of that name stays active.
343
+ */
344
+ suppressedServers: ReadonlySet<string>;
345
+ }
346
+
313
347
  // ─── Loader ───────────────────────────────────────────────────────────────────
314
348
 
315
349
  async function readJsonFile(path: string): Promise<unknown> {
@@ -420,21 +454,265 @@ export function agentDir(env: NodeJS.ProcessEnv = process.env): string {
420
454
  return join(homedir(), ".pi", "agent");
421
455
  }
422
456
 
457
+ const EMPTY_STRING_SET: ReadonlySet<string> = new Set();
458
+
459
+ function setOwnProperty<T>(target: Record<string, T>, key: string, value: T): void {
460
+ Object.defineProperty(target, key, {
461
+ value,
462
+ enumerable: true,
463
+ writable: true,
464
+ configurable: true,
465
+ });
466
+ }
467
+
423
468
  /** Winning file origin per server name: a project entry replaces a global entry of the same name. */
424
469
  function originsOf(
425
470
  globalCfg: McpConfig,
426
471
  projectCfg: ProjectConfig | undefined,
472
+ droppedNames: ReadonlySet<string> = EMPTY_STRING_SET,
427
473
  ): Record<string, FileConfigOrigin> {
428
474
  const origins: Record<string, FileConfigOrigin> = {};
429
475
  for (const name of Object.keys(globalCfg.mcpServers)) {
430
- origins[name] = "global";
476
+ if (!droppedNames.has(name)) {
477
+ setOwnProperty(origins, name, "global");
478
+ }
431
479
  }
432
480
  for (const name of Object.keys(projectCfg?.mcpServers ?? {})) {
433
- origins[name] = "project";
481
+ setOwnProperty(origins, name, "project");
434
482
  }
435
483
  return origins;
436
484
  }
437
485
 
486
+ function extractRawServers(raw: unknown): Record<string, unknown> {
487
+ return isPlainObject(raw) && isPlainObject(raw.mcpServers) ? raw.mcpServers : {};
488
+ }
489
+
490
+ function formatServerValidationError(
491
+ name: string,
492
+ issues: z.ZodError["issues"],
493
+ sourcePath: string,
494
+ ): McpError {
495
+ const formatted = issues
496
+ .map((i) => ` mcpServers.${name}${i.path.length > 0 ? `.${i.path.join(".")}` : ""}: ${i.message}`)
497
+ .join("\n");
498
+ return new McpError(`Invalid mcp.json at ${sourcePath}:\n${formatted}`, "<config>", "config");
499
+ }
500
+
501
+ function parseGlobalServersTolerant(
502
+ rawServers: Record<string, unknown>,
503
+ sourcePath: string,
504
+ ): { servers: Record<string, ServerConfig>; invalidNames: Set<string>; errors: McpError[] } {
505
+ const servers: Record<string, ServerConfig> = {};
506
+ const invalidNames = new Set<string>();
507
+ const errors: McpError[] = [];
508
+ for (const [name, entry] of Object.entries(rawServers)) {
509
+ const result = ServerConfigSchema.safeParse(entry);
510
+ if (result.success) {
511
+ setOwnProperty(servers, name, result.data);
512
+ } else {
513
+ invalidNames.add(name);
514
+ errors.push(formatServerValidationError(name, result.error.issues, sourcePath));
515
+ }
516
+ }
517
+ return { servers, invalidNames, errors };
518
+ }
519
+
520
+ type ProjectServerEntryResult =
521
+ | { ok: true; value: ServerConfig }
522
+ | { ok: false; error?: McpError; suppressFallback: boolean };
523
+
524
+ function parseValidatedProjectCandidate(
525
+ name: string,
526
+ candidate: unknown,
527
+ sourcePath: string,
528
+ ): ProjectServerEntryResult {
529
+ const parsed = ServerConfigSchema.safeParse(candidate);
530
+ if (!parsed.success) {
531
+ return {
532
+ ok: false,
533
+ error: formatServerValidationError(name, parsed.error.issues, sourcePath),
534
+ suppressFallback: true,
535
+ };
536
+ }
537
+ return { ok: true, value: parsed.data };
538
+ }
539
+
540
+ function parseOverrideForInvalidGlobal(
541
+ name: string,
542
+ override: Record<string, unknown>,
543
+ sourcePath: string,
544
+ ): ProjectServerEntryResult {
545
+ const keyError = validateProjectOverrideKeys(name, override, sourcePath);
546
+ if (keyError) {
547
+ return { ok: false, error: keyError, suppressFallback: true };
548
+ }
549
+ const fields = ProjectOverrideFieldsSchema.safeParse(override);
550
+ if (!fields.success) {
551
+ return {
552
+ ok: false,
553
+ error: formatServerValidationError(name, fields.error.issues, sourcePath),
554
+ suppressFallback: true,
555
+ };
556
+ }
557
+ // WHY: global validation already reported the broken base server against the global file;
558
+ // drop the server without emitting a duplicate error falsely attributed to .pi/mcp.json.
559
+ return { ok: false, suppressFallback: true };
560
+ }
561
+
562
+ function parseProjectServerEntry(
563
+ name: string,
564
+ entry: unknown,
565
+ globalContext: {
566
+ rawServers: Record<string, unknown>;
567
+ invalidNames: ReadonlySet<string>;
568
+ },
569
+ sourcePath: string,
570
+ ): ProjectServerEntryResult {
571
+ if (!isProjectOverrideEntry(entry)) {
572
+ return parseValidatedProjectCandidate(name, entry, sourcePath);
573
+ }
574
+ if (globalContext.invalidNames.has(name)) {
575
+ return parseOverrideForInvalidGlobal(name, entry, sourcePath);
576
+ }
577
+ const resolved = resolveProjectOverride(name, entry, globalContext.rawServers, sourcePath);
578
+ if (!resolved.ok) {
579
+ return {
580
+ ok: false,
581
+ error: resolved.error,
582
+ suppressFallback: Object.hasOwn(globalContext.rawServers, name),
583
+ };
584
+ }
585
+ return parseValidatedProjectCandidate(name, resolved.value, sourcePath);
586
+ }
587
+
588
+ function parseProjectServersTolerant(
589
+ rawServers: Record<string, unknown>,
590
+ globalContext: {
591
+ rawServers: Record<string, unknown>;
592
+ invalidNames: ReadonlySet<string>;
593
+ },
594
+ sourcePath: string,
595
+ ): {
596
+ servers: Record<string, ServerConfig>;
597
+ droppedNames: Set<string>;
598
+ suppressedNames: Set<string>;
599
+ errors: McpError[];
600
+ } {
601
+ const servers: Record<string, ServerConfig> = {};
602
+ const droppedNames = new Set<string>();
603
+ const suppressedNames = new Set<string>();
604
+ const errors: McpError[] = [];
605
+ for (const [name, entry] of Object.entries(rawServers)) {
606
+ const parsed = parseProjectServerEntry(name, entry, globalContext, sourcePath);
607
+ if (parsed.ok) {
608
+ setOwnProperty(servers, name, parsed.value);
609
+ } else {
610
+ droppedNames.add(name);
611
+ if (parsed.suppressFallback) suppressedNames.add(name);
612
+ if (parsed.error) errors.push(parsed.error);
613
+ }
614
+ }
615
+ return { servers, droppedNames, suppressedNames, errors };
616
+ }
617
+
618
+ function filterDroppedServers(
619
+ servers: Record<string, ServerConfig>,
620
+ droppedNames: ReadonlySet<string>,
621
+ ): Record<string, ServerConfig> {
622
+ if (droppedNames.size === 0) return servers;
623
+ const filtered: Record<string, ServerConfig> = {};
624
+ for (const [name, cfg] of Object.entries(servers)) {
625
+ if (!droppedNames.has(name)) {
626
+ setOwnProperty(filtered, name, cfg);
627
+ }
628
+ }
629
+ return filtered;
630
+ }
631
+
632
+ function mergeSessionConfigs(
633
+ globalCfg: McpConfig,
634
+ projectCfg: ProjectConfig,
635
+ droppedNames: ReadonlySet<string>,
636
+ ): McpConfig {
637
+ // WHY: a broken project override or replacement must drop the global server of that name
638
+ // rather than silently falling back to un-overridden global settings or credentials.
639
+ const keptGlobal: McpConfig = droppedNames.size === 0
640
+ ? globalCfg
641
+ : { ...globalCfg, mcpServers: filterDroppedServers(globalCfg.mcpServers, droppedNames) };
642
+ return mergeConfigs(keptGlobal, projectCfg);
643
+ }
644
+
645
+ function applyProjectSuppressedNames(
646
+ suppressedServers: Set<string>,
647
+ validProjectServers: Record<string, ServerConfig>,
648
+ projectSuppressedNames: ReadonlySet<string>,
649
+ ): void {
650
+ for (const name of Object.keys(validProjectServers)) {
651
+ suppressedServers.delete(name);
652
+ }
653
+ for (const name of projectSuppressedNames) {
654
+ suppressedServers.add(name);
655
+ }
656
+ }
657
+
658
+ /**
659
+ * Load and merge global and project configs for a session, isolating per-server validation errors
660
+ * and invalid project overrides so healthy sibling servers stay loaded. Whole-file errors (I/O,
661
+ * JSON syntax, non-object root/`mcpServers`, invalid `settings` or `autoEnableCodemode`) still
662
+ * throw `McpError("config")`.
663
+ */
664
+ export async function loadSessionConfigWithOrigins(
665
+ cwd: string,
666
+ globalPath = join(agentDir(), "mcp.json"),
667
+ options?: LoadConfigOptions,
668
+ ): Promise<SessionConfigLoadResult> {
669
+ const projectConfigIncluded = options?.includeProjectConfig !== false;
670
+ const projectConfigPath = join(cwd, ".pi", "mcp.json");
671
+
672
+ const [globalRaw, projectRaw] = await Promise.all([
673
+ readJsonFile(globalPath),
674
+ projectConfigIncluded ? readJsonFile(projectConfigPath) : Promise.resolve(undefined),
675
+ ]);
676
+
677
+ const serverErrors: McpError[] = [];
678
+ const globalEnvelope = globalRaw !== undefined
679
+ ? parseWith(McpConfigEnvelopeSchema, globalRaw, globalPath)
680
+ : McpConfigEnvelopeSchema.parse({});
681
+ const globalRawServers = extractRawServers(globalRaw);
682
+ const globalParsed = parseGlobalServersTolerant(globalRawServers, globalPath);
683
+ serverErrors.push(...globalParsed.errors);
684
+ const globalCfg: McpConfig = { ...globalEnvelope, mcpServers: globalParsed.servers };
685
+ const suppressedServers = new Set<string>(globalParsed.invalidNames);
686
+
687
+ let projectCfg: ProjectConfig | undefined;
688
+ let droppedNames: ReadonlySet<string> = EMPTY_STRING_SET;
689
+ if (projectRaw !== undefined) {
690
+ const projectEnvelope = parseWith(ProjectConfigEnvelopeSchema, projectRaw, projectConfigPath);
691
+ const projectParsed = parseProjectServersTolerant(
692
+ extractRawServers(projectRaw),
693
+ { rawServers: globalRawServers, invalidNames: globalParsed.invalidNames },
694
+ projectConfigPath,
695
+ );
696
+ serverErrors.push(...projectParsed.errors);
697
+ droppedNames = projectParsed.droppedNames;
698
+ applyProjectSuppressedNames(suppressedServers, projectParsed.servers, projectParsed.suppressedNames);
699
+ projectCfg = { ...projectEnvelope, mcpServers: projectParsed.servers };
700
+ }
701
+
702
+ return {
703
+ loaded: {
704
+ config: projectCfg === undefined
705
+ ? globalCfg
706
+ : mergeSessionConfigs(globalCfg, projectCfg, droppedNames),
707
+ origins: originsOf(globalCfg, projectCfg, droppedNames),
708
+ projectConfigPath,
709
+ projectConfigIncluded,
710
+ },
711
+ serverErrors,
712
+ suppressedServers,
713
+ };
714
+ }
715
+
438
716
  /**
439
717
  * Load and merge global and project configs, reporting where every server entry came from.
440
718
  * Same validation, precedence, and error behavior as `loadConfig`.
@@ -351,6 +351,40 @@ export interface ClassifyConnectFailureInput {
351
351
  serverName?: string;
352
352
  }
353
353
 
354
+ /**
355
+ * Local OS spawn errnos on `stdio` that cannot succeed on retry without user intervention
356
+ * (missing binary/cwd, missing execute permission, invalid binary format, or bad path type).
357
+ */
358
+ const NON_RETRYABLE_STDIO_SPAWN_CODES = new Set([
359
+ "ENOENT",
360
+ "EACCES",
361
+ "ENOEXEC",
362
+ "ENOTDIR",
363
+ "EISDIR",
364
+ ]);
365
+
366
+ /**
367
+ * Whether `error` is a deterministic local OS spawn failure on `stdio` that cannot
368
+ * succeed on retry without user intervention.
369
+ */
370
+ export function isNonRetryableStdioSpawnError(
371
+ transport: TransportType,
372
+ error: unknown,
373
+ ): boolean {
374
+ if (transport !== "stdio" || typeof error !== "object" || error === null) {
375
+ return false;
376
+ }
377
+ const code = (error as { code?: unknown }).code;
378
+ return typeof code === "string" && NON_RETRYABLE_STDIO_SPAWN_CODES.has(code);
379
+ }
380
+
381
+ function isFastFailConnectError(input: ClassifyConnectFailureInput, error: Error): boolean {
382
+ if (error instanceof McpError) {
383
+ return error.code === "protocol" || error.code === "config";
384
+ }
385
+ return isNonRetryableStdioSpawnError(input.transport, input.error);
386
+ }
387
+
354
388
  function classifyOAuthFailure(
355
389
  input: ClassifyConnectFailureInput,
356
390
  error: Error,
@@ -387,7 +421,7 @@ function classifyPreRetryFailure(
387
421
  const oauthAction = classifyOAuthFailure(input, error);
388
422
  if (oauthAction) return oauthAction;
389
423
 
390
- if (error instanceof McpError && (error.code === "protocol" || error.code === "config")) {
424
+ if (isFastFailConnectError(input, error)) {
391
425
  return { kind: "fail", error };
392
426
  }
393
427
 
package/src/mcp-client.ts CHANGED
@@ -19,6 +19,7 @@
19
19
  */
20
20
 
21
21
  import { basename } from "node:path";
22
+ import { getStdioSpawnError } from "./stdio-process.js";
22
23
  import { pathToFileURL } from "node:url";
23
24
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
24
25
  import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
@@ -188,7 +189,12 @@ export async function connectClientWithTimeout(
188
189
  try {
189
190
  await Promise.race([connectPromise, guard.outcome]);
190
191
  } catch (err) {
191
- rethrowNormalizedConnectError(err, signal, serverName, timeoutMs);
192
+ rethrowNormalizedConnectError(
193
+ getStdioSpawnError(transport) ?? err,
194
+ signal,
195
+ serverName,
196
+ timeoutMs,
197
+ );
192
198
  } finally {
193
199
  guard.dispose();
194
200
  }
@@ -13,11 +13,11 @@ import type {
13
13
  } from "@earendil-works/pi-coding-agent";
14
14
  import { join } from "node:path";
15
15
  import {
16
- loadConfigWithOrigins,
16
+ loadSessionConfigWithOrigins,
17
17
  parseRegisteredServerConfig,
18
- type LoadedConfig,
19
18
  type McpConfig,
20
19
  type ServerConfig,
20
+ type SessionConfigLoadResult,
21
21
  } from "./config.js";
22
22
  import {
23
23
  withExtensionServers,
@@ -46,6 +46,8 @@ export const DEFAULT_SETTINGS = {
46
46
  maxRetries: 5,
47
47
  } as const;
48
48
 
49
+ const EMPTY_STRING_SET: ReadonlySet<string> = new Set();
50
+
49
51
  export type SessionProvenance = ConfigProvenance;
50
52
 
51
53
  export interface BootstrapConfigPaths {
@@ -56,6 +58,7 @@ export interface BootstrapConfigPaths {
56
58
  export interface BootstrapConfigState {
57
59
  fileConfig: McpConfig;
58
60
  fileProvenance: ConfigProvenanceInput;
61
+ suppressedFileServers?: ReadonlySet<string> | undefined;
59
62
  extensionServers: Record<string, ServerConfig>;
60
63
  config: McpConfig;
61
64
  }
@@ -95,11 +98,16 @@ export function collectRegisteredServers(
95
98
  entries: readonly RegisteredMcpServer[],
96
99
  fileServers: Record<string, ServerConfig>,
97
100
  onError?: (err: unknown) => void,
101
+ suppressedFileServers?: ReadonlySet<string>,
98
102
  ): Record<string, ServerConfig> {
99
103
  const registered: Record<string, ServerConfig> = {};
100
104
  for (const entry of entries) {
101
- // Servers configured in mcp.json take precedence over extension-registered servers.
102
- if (Object.prototype.hasOwnProperty.call(fileServers, entry.name)) {
105
+ // Servers configured in mcp.json (including broken file entries that must not fall back
106
+ // to extension registrations) take precedence over extension-registered servers.
107
+ if (
108
+ Object.prototype.hasOwnProperty.call(fileServers, entry.name) ||
109
+ suppressedFileServers?.has(entry.name)
110
+ ) {
103
111
  continue;
104
112
  }
105
113
  try {
@@ -155,12 +163,17 @@ export async function loadBootstrapConfigState(
155
163
  projectConfigPath: join(bootstrapCwd, ".pi", "mcp.json"),
156
164
  projectConfigIncluded: false,
157
165
  };
166
+ let suppressedFileServers: ReadonlySet<string> = EMPTY_STRING_SET;
158
167
  try {
159
- const loaded = await loadConfigWithOrigins(bootstrapCwd, paths.globalConfigPath, {
168
+ const result = await loadSessionConfigWithOrigins(bootstrapCwd, paths.globalConfigPath, {
160
169
  includeProjectConfig: false,
161
170
  });
162
- fileConfig = loaded.config;
163
- fileProvenance = loaded;
171
+ fileConfig = result.loaded.config;
172
+ fileProvenance = result.loaded;
173
+ suppressedFileServers = result.suppressedServers;
174
+ for (const err of result.serverErrors) {
175
+ reportBootstrapConfigError(err);
176
+ }
164
177
  } catch (err) {
165
178
  // Can't notify yet (no ctx), so the diagnostic goes to stderr (and to the
166
179
  // debug log when it is enabled). The session_start handler will re-try with
@@ -173,11 +186,13 @@ export async function loadBootstrapConfigState(
173
186
  initialEntries,
174
187
  fileConfig.mcpServers,
175
188
  reportBootstrapConfigError,
189
+ suppressedFileServers,
176
190
  );
177
191
  const config = mergeWithRegisteredServers(fileConfig, extensionServers);
178
192
  return {
179
193
  fileConfig,
180
194
  fileProvenance,
195
+ suppressedFileServers,
181
196
  extensionServers,
182
197
  config,
183
198
  };
@@ -210,9 +225,15 @@ export function abortSupersededEagerStarts(
210
225
  registeredEntries: readonly RegisteredMcpServer[],
211
226
  fileServers: Record<string, ServerConfig>,
212
227
  abortEagerStart: (name: string) => void,
228
+ suppressedFileServers?: ReadonlySet<string>,
213
229
  ): void {
214
230
  if (inFlightEager.size === 0) return;
215
- const nextPreview = collectRegisteredServers(registeredEntries, fileServers);
231
+ const nextPreview = collectRegisteredServers(
232
+ registeredEntries,
233
+ fileServers,
234
+ undefined,
235
+ suppressedFileServers,
236
+ );
216
237
  for (const name of findRemovedOrChangedServers(
217
238
  Object.fromEntries(inFlightEager),
218
239
  nextPreview,
@@ -266,6 +287,7 @@ export class SessionLifecycle {
266
287
  private readonly hasRegisteredServersSource: boolean;
267
288
  private fileConfig: McpConfig;
268
289
  private fileProvenance: ConfigProvenanceInput;
290
+ private suppressedFileServers: ReadonlySet<string>;
269
291
  private extensionServers: Record<string, ServerConfig>;
270
292
  private config: McpConfig;
271
293
  private latestEventEntries: RegisteredMcpServer[] = [];
@@ -292,6 +314,7 @@ export class SessionLifecycle {
292
314
  this.hasRegisteredServersSource = hasRegisteredServersApi(deps.pi);
293
315
  this.fileConfig = deps.initialState.fileConfig;
294
316
  this.fileProvenance = deps.initialState.fileProvenance;
317
+ this.suppressedFileServers = deps.initialState.suppressedFileServers ?? EMPTY_STRING_SET;
295
318
  this.extensionServers = deps.initialState.extensionServers;
296
319
  this.config = deps.initialState.config;
297
320
  }
@@ -330,6 +353,7 @@ export class SessionLifecycle {
330
353
  this.getRegisteredEntries(),
331
354
  this.fileConfig.mcpServers,
332
355
  (name) => this.abortEagerStart(name),
356
+ this.suppressedFileServers,
333
357
  );
334
358
  return this.enqueueServerReconcile(ctx);
335
359
  }
@@ -378,17 +402,19 @@ export class SessionLifecycle {
378
402
  return epoch === this.sessionEpoch && this.changeEventCount !== this.appliedChangeCount;
379
403
  }
380
404
 
381
- private setSessionConfigState(
382
- nextFileConfig: McpConfig,
383
- nextProvenance: ConfigProvenanceInput,
384
- nextExtensionServers: Record<string, ServerConfig>,
385
- nextConfig: McpConfig,
386
- ): void {
387
- this.fileConfig = nextFileConfig;
388
- this.fileProvenance = nextProvenance;
405
+ private setSessionConfigState(next: {
406
+ fileConfig: McpConfig;
407
+ fileProvenance: ConfigProvenanceInput;
408
+ suppressedFileServers: ReadonlySet<string>;
409
+ extensionServers: Record<string, ServerConfig>;
410
+ config: McpConfig;
411
+ }): void {
412
+ this.fileConfig = next.fileConfig;
413
+ this.fileProvenance = next.fileProvenance;
414
+ this.suppressedFileServers = next.suppressedFileServers;
389
415
  this.appliedChangeCount = this.changeEventCount;
390
- this.extensionServers = nextExtensionServers;
391
- this.config = nextConfig;
416
+ this.extensionServers = next.extensionServers;
417
+ this.config = next.config;
392
418
  }
393
419
 
394
420
  private syncConfiguredDiscoveryTools(servers: Record<string, ServerConfig>): void {
@@ -452,6 +478,7 @@ export class SessionLifecycle {
452
478
  this.getRegisteredEntries(),
453
479
  this.fileConfig.mcpServers,
454
480
  (name) => this.abortEagerStart(name),
481
+ this.suppressedFileServers,
455
482
  );
456
483
  }
457
484
  if (this.inFlightEagerBatch.length > 0) {
@@ -517,12 +544,13 @@ export class SessionLifecycle {
517
544
  (regErr) => notifySessionConfigError(ctx, regErr),
518
545
  );
519
546
  const nextConfig = mergeWithRegisteredServers(fallbackFileConfig, nextExtensionServers);
520
- this.setSessionConfigState(
521
- fallbackFileConfig,
522
- fallbackProvenance,
523
- nextExtensionServers,
524
- nextConfig,
525
- );
547
+ this.setSessionConfigState({
548
+ fileConfig: fallbackFileConfig,
549
+ fileProvenance: fallbackProvenance,
550
+ suppressedFileServers: EMPTY_STRING_SET,
551
+ extensionServers: nextExtensionServers,
552
+ config: nextConfig,
553
+ });
526
554
  this.deps.bridge.updateSettings(nextConfig.settings);
527
555
  this.deps.bridge.setAutoEnableCodemode(nextConfig.autoEnableCodemode);
528
556
  this.deps.manager.rebuildServers(nextConfig);
@@ -532,13 +560,15 @@ export class SessionLifecycle {
532
560
  : [];
533
561
  }
534
562
 
535
- private hasSessionConfigChanged(nextLoaded: LoadedConfig): boolean {
563
+ private hasSessionConfigChanged(result: SessionConfigLoadResult): boolean {
536
564
  const previewExtensionServers = collectRegisteredServers(
537
565
  this.getRegisteredEntries(),
538
- nextLoaded.config.mcpServers,
566
+ result.loaded.config.mcpServers,
567
+ undefined,
568
+ result.suppressedServers,
539
569
  );
540
570
  const previewConfig = mergeWithRegisteredServers(
541
- nextLoaded.config,
571
+ result.loaded.config,
542
572
  previewExtensionServers,
543
573
  );
544
574
  return JSON.stringify(previewConfig) !== JSON.stringify(this.config);
@@ -546,21 +576,24 @@ export class SessionLifecycle {
546
576
 
547
577
  private commitLoadedConfig(
548
578
  ctx: ExtensionContext,
549
- nextLoaded: LoadedConfig,
579
+ result: SessionConfigLoadResult,
550
580
  rebuild: boolean,
551
581
  ): Array<[string, ServerConfig]> {
582
+ const nextLoaded = result.loaded;
552
583
  const nextExtensionServers = collectRegisteredServers(
553
584
  this.getRegisteredEntries(),
554
585
  nextLoaded.config.mcpServers,
555
586
  (err) => notifySessionConfigError(ctx, err),
587
+ result.suppressedServers,
556
588
  );
557
589
  const sessionConfig = mergeWithRegisteredServers(nextLoaded.config, nextExtensionServers);
558
- this.setSessionConfigState(
559
- nextLoaded.config,
560
- nextLoaded,
561
- nextExtensionServers,
562
- rebuild ? sessionConfig : this.config,
563
- );
590
+ this.setSessionConfigState({
591
+ fileConfig: nextLoaded.config,
592
+ fileProvenance: nextLoaded,
593
+ suppressedFileServers: result.suppressedServers,
594
+ extensionServers: nextExtensionServers,
595
+ config: rebuild ? sessionConfig : this.config,
596
+ });
564
597
  this.deps.bridge.setAutoEnableCodemode(sessionConfig.autoEnableCodemode);
565
598
  if (rebuild) {
566
599
  this.deps.bridge.updateSettings(sessionConfig.settings);
@@ -594,10 +627,10 @@ export class SessionLifecycle {
594
627
 
595
628
  private async applyLoadedSessionConfig(
596
629
  ctx: ExtensionContext,
597
- nextLoaded: LoadedConfig,
630
+ result: SessionConfigLoadResult,
598
631
  epoch: number,
599
632
  ): Promise<void> {
600
- const configChanged = this.hasSessionConfigChanged(nextLoaded);
633
+ const configChanged = this.hasSessionConfigChanged(result);
601
634
  if (configChanged) {
602
635
  reportDiagnostic({
603
636
  level: "info",
@@ -608,7 +641,7 @@ export class SessionLifecycle {
608
641
  await this.deps.coordinator.teardown(ctx);
609
642
  if (!this.isEpochCurrent(epoch)) return;
610
643
  }
611
- const eagerServers = this.commitLoadedConfig(ctx, nextLoaded, configChanged);
644
+ const eagerServers = this.commitLoadedConfig(ctx, result, configChanged);
612
645
  if (!this.isEpochCurrent(epoch) || eagerServers.length === 0) return;
613
646
  await this.runEagerStarts(eagerServers, ctx);
614
647
  }
@@ -630,9 +663,9 @@ export class SessionLifecycle {
630
663
  });
631
664
  const includeProjectConfig = isProjectTrusted(ctx);
632
665
 
633
- let nextLoaded: LoadedConfig;
666
+ let result: SessionConfigLoadResult;
634
667
  try {
635
- nextLoaded = await loadConfigWithOrigins(ctx.cwd, this.deps.globalConfigPath, {
668
+ result = await loadSessionConfigWithOrigins(ctx.cwd, this.deps.globalConfigPath, {
636
669
  includeProjectConfig,
637
670
  });
638
671
  } catch (err) {
@@ -640,7 +673,10 @@ export class SessionLifecycle {
640
673
  return;
641
674
  }
642
675
  if (!this.isEpochCurrent(epoch)) return;
643
- await this.applyLoadedSessionConfig(ctx, nextLoaded, epoch);
676
+ for (const err of result.serverErrors) {
677
+ notifySessionConfigError(ctx, err);
678
+ }
679
+ await this.applyLoadedSessionConfig(ctx, result, epoch);
644
680
  }
645
681
 
646
682
  private handleReconcileError(err: unknown, epoch: number, ctx: ExtensionContext): void {
@@ -697,6 +733,7 @@ export class SessionLifecycle {
697
733
  (err) => {
698
734
  configErrors.push(formatErrorMessage(err));
699
735
  },
736
+ this.suppressedFileServers,
700
737
  );
701
738
 
702
739
  const removedOrChanged = findRemovedOrChangedServers(
@@ -0,0 +1,349 @@
1
+ /**
2
+ * Synchronous process-level `SIGINT` / `exit` safety net for live stdio child trees.
3
+ *
4
+ * In headless Pi modes (`--mode rpc`, `--mode json`, `--print`), Pi binds graceful
5
+ * shutdown only to `SIGTERM` and `SIGHUP`. When `SIGINT` arrives with no active host
6
+ * handler, Node exits via default `SIGINT` disposition without firing `session_shutdown`.
7
+ * This module tracks live stdio root PIDs and terminates their process trees synchronously
8
+ * when unhandled `SIGINT` or unexpected `exit` fires, while yielding to active host
9
+ * handlers (such as interactive TUI `Ctrl+Z` suspend) and ignoring passive `signal-exit`
10
+ * wrappers.
11
+ */
12
+
13
+ import { execFileSync, spawnSync } from "node:child_process";
14
+ import { readdirSync, readFileSync } from "node:fs";
15
+
16
+ const MAX_DESCENDANTS = 256;
17
+ const PS_SYNC_TIMEOUT_MS = 250;
18
+ const TASKKILL_TIMEOUT_MS = 500;
19
+ const SIGNAL_EXIT_V4_SYMBOL = Symbol.for("signal-exit emitter");
20
+
21
+ export interface SignalExitProcess {
22
+ pid: number;
23
+ on(event: "SIGINT", listener: () => void): unknown;
24
+ on(event: "exit", listener: (code: number) => void): unknown;
25
+ off(event: "SIGINT", listener: () => void): unknown;
26
+ off(event: "exit", listener: (code: number) => void): unknown;
27
+ listenerCount(event: "SIGINT" | "exit"): number;
28
+ kill(pid: number, signal?: NodeJS.Signals | number): boolean;
29
+ exit(code?: number): never;
30
+ __signal_exit_emitter__?: unknown;
31
+ [key: symbol]: unknown;
32
+ }
33
+
34
+ export interface SyncTreeTerminationDeps {
35
+ platform: NodeJS.Platform;
36
+ kill: (pid: number, signal?: NodeJS.Signals | number) => void | boolean;
37
+ spawnSync: typeof spawnSync;
38
+ listDescendantPidsSync: (pid: number) => number[];
39
+ }
40
+
41
+ export interface StdioExitGuardDeps {
42
+ proc: SignalExitProcess;
43
+ globalScope?: unknown;
44
+ terminatePidTreeSync: (pid: number) => void;
45
+ }
46
+
47
+ function readPositiveCount(holder: unknown): number {
48
+ const count = (holder as { count?: unknown } | undefined)?.count;
49
+ return typeof count === "number" && Number.isInteger(count) && count > 0 ? count : 0;
50
+ }
51
+
52
+ function resolveGlobalScope(proc: unknown, globalScope?: unknown): unknown {
53
+ if (globalScope !== undefined) return globalScope;
54
+ return proc === process ? globalThis : undefined;
55
+ }
56
+
57
+ /**
58
+ * Count passive `signal-exit` v3/v4 `SIGINT` listeners attached to `proc`.
59
+ *
60
+ * WHY: Pi 1.3.0 bundles `signal-exit` v3 (via `proper-lockfile`), which stores its emitter on
61
+ * `process.__signal_exit_emitter__`, while `signal-exit` v4 stores its emitter on
62
+ * `globalThis[Symbol.for("signal-exit emitter")]`. Both register passive `SIGINT` listeners
63
+ * that only act when `listeners.length === count`. Subtracting those passive wrappers lets our
64
+ * guard detect whether an active host handler (such as Pi TUI's `Ctrl+Z` `ignoreSigint`) owns
65
+ * `SIGINT` without deadlocking in headless `rpc`/`json`/`print` modes.
66
+ */
67
+ export function countPassiveSigintListeners(proc: unknown, globalScope?: unknown): number {
68
+ if (!proc || typeof proc !== "object") return 0;
69
+ const v3 = (proc as { __signal_exit_emitter__?: unknown }).__signal_exit_emitter__;
70
+ const scope = resolveGlobalScope(proc, globalScope);
71
+ const v4 =
72
+ scope && typeof scope === "object"
73
+ ? (scope as Record<symbol, unknown>)[SIGNAL_EXIT_V4_SYMBOL]
74
+ : undefined;
75
+ return readPositiveCount(v3) + readPositiveCount(v4);
76
+ }
77
+
78
+ /** Index `ps -A -o pid=,ppid=` output as a parent PID → child PIDs map. */
79
+ export function indexProcessTable(stdout: string): Map<number, number[]> {
80
+ const childrenOf = new Map<number, number[]>();
81
+ for (const line of stdout.split("\n")) {
82
+ const match = /^\s*(\d+)\s+(\d+)\s*$/.exec(line);
83
+ if (!match) continue;
84
+ const childPid = Number(match[1]);
85
+ const parentPid = Number(match[2]);
86
+ const siblings = childrenOf.get(parentPid);
87
+ if (siblings) {
88
+ siblings.push(childPid);
89
+ } else {
90
+ childrenOf.set(parentPid, [childPid]);
91
+ }
92
+ }
93
+ return childrenOf;
94
+ }
95
+
96
+ function readTaskIdsSync(taskDir: string): string[] {
97
+ try {
98
+ return readdirSync(taskDir);
99
+ } catch {
100
+ // WHY: Best-effort sync /proc walk during signal/exit; a child can exit before its task dir is read.
101
+ return [];
102
+ }
103
+ }
104
+
105
+ function readChildrenFileSync(path: string): string {
106
+ try {
107
+ return readFileSync(path, "utf8");
108
+ } catch {
109
+ // WHY: Best-effort sync /proc walk during signal/exit; a thread or process can exit mid-walk.
110
+ return "";
111
+ }
112
+ }
113
+
114
+ function readProcChildrenSync(pid: number): number[] {
115
+ const taskDir = `/proc/${pid}/task`;
116
+ const tids = readTaskIdsSync(taskDir);
117
+ const children: number[] = [];
118
+ for (const tid of tids) {
119
+ const raw = readChildrenFileSync(`${taskDir}/${tid}/children`);
120
+ for (const token of raw.split(/\s+/)) {
121
+ const childPid = Number(token);
122
+ if (token && Number.isInteger(childPid) && childPid > 0) {
123
+ children.push(childPid);
124
+ }
125
+ }
126
+ }
127
+ return children;
128
+ }
129
+
130
+ function readPsProcessTableSync(): Map<number, number[]> {
131
+ try {
132
+ const stdout = execFileSync("ps", ["-A", "-o", "pid=,ppid="], {
133
+ encoding: "utf8",
134
+ maxBuffer: 16 * 1024 * 1024,
135
+ timeout: PS_SYNC_TIMEOUT_MS,
136
+ });
137
+ return indexProcessTable(stdout);
138
+ } catch {
139
+ // WHY: Best-effort sync discovery during signal/exit; cache an empty table so one missing or
140
+ // slow `ps` does not stall remaining roots, which still receive SIGTERM directly.
141
+ return new Map();
142
+ }
143
+ }
144
+
145
+ function createSyncChildReader(platform: NodeJS.Platform = process.platform): (pid: number) => number[] {
146
+ if (platform === "linux") return readProcChildrenSync;
147
+ if (platform === "win32") return () => [];
148
+ let table: Map<number, number[]> | null = null;
149
+ return (pid: number): number[] => {
150
+ table ??= readPsProcessTableSync();
151
+ return table.get(pid) ?? [];
152
+ };
153
+ }
154
+
155
+ function readChildrenSafe(pid: number, readChildren: (pid: number) => number[]): number[] {
156
+ try {
157
+ return readChildren(pid);
158
+ } catch {
159
+ // WHY: Best-effort sync discovery during signal/exit; one exited child must not abort sibling discovery.
160
+ return [];
161
+ }
162
+ }
163
+
164
+ function walkDescendantsSync(pid: number, readChildren: (pid: number) => number[]): number[] {
165
+ const descendants: number[] = [];
166
+ const seen = new Set<number>([pid]);
167
+ const pending = [...readChildrenSafe(pid, readChildren)];
168
+ while (pending.length > 0 && descendants.length < MAX_DESCENDANTS) {
169
+ const next = pending.shift();
170
+ if (next === undefined || seen.has(next)) continue;
171
+ seen.add(next);
172
+ descendants.push(next);
173
+ pending.push(...readChildrenSafe(next, readChildren));
174
+ }
175
+ return descendants;
176
+ }
177
+
178
+ /**
179
+ * Synchronously snapshot descendant PIDs of `pid`, deepest generation first.
180
+ * Used during `SIGINT` / `exit` cleanup where async awaits cannot run.
181
+ */
182
+ export function listDescendantPidsSync(
183
+ pid: number,
184
+ readChildren?: (pid: number) => number[],
185
+ platform: NodeJS.Platform = process.platform,
186
+ ): number[] {
187
+ const reader = readChildren ?? createSyncChildReader(platform);
188
+ return walkDescendantsSync(pid, reader).reverse();
189
+ }
190
+
191
+ function trySignalSync(
192
+ pid: number,
193
+ signal: NodeJS.Signals,
194
+ kill: SyncTreeTerminationDeps["kill"],
195
+ ): void {
196
+ try {
197
+ kill(pid, signal);
198
+ } catch {
199
+ // WHY: Best-effort teardown during SIGINT/exit; ESRCH/EPERM must not abort sibling cleanup.
200
+ }
201
+ }
202
+
203
+ function killWindowsTreeSync(
204
+ pid: number,
205
+ runSpawnSync: typeof spawnSync,
206
+ kill: SyncTreeTerminationDeps["kill"],
207
+ ): void {
208
+ try {
209
+ const result = runSpawnSync("taskkill", ["/pid", String(pid), "/T", "/F"], {
210
+ stdio: "ignore",
211
+ windowsHide: true,
212
+ timeout: TASKKILL_TIMEOUT_MS,
213
+ });
214
+ if (!result.error) return;
215
+ } catch {
216
+ // WHY: Fall back to signalling the root PID if taskkill cannot be spawned.
217
+ }
218
+ trySignalSync(pid, "SIGTERM", kill);
219
+ }
220
+
221
+ /**
222
+ * Synchronously signal a stdio child process tree (`SIGTERM` deepest-first on POSIX,
223
+ * `taskkill /T /F` with `SIGTERM` fallback on Windows).
224
+ */
225
+ export function terminatePidTreeSync(
226
+ pid: number,
227
+ deps?: Partial<SyncTreeTerminationDeps>,
228
+ ): void {
229
+ const platform = deps?.platform ?? process.platform;
230
+ const kill = deps?.kill ?? ((target, signal) => process.kill(target, signal));
231
+ if (platform === "win32") {
232
+ killWindowsTreeSync(pid, deps?.spawnSync ?? spawnSync, kill);
233
+ return;
234
+ }
235
+ const listDescendants =
236
+ deps?.listDescendantPidsSync ??
237
+ ((root: number) => listDescendantPidsSync(root, undefined, platform));
238
+ const targets = [...listDescendants(pid), pid];
239
+ for (const target of targets) {
240
+ trySignalSync(target, "SIGTERM", kill);
241
+ }
242
+ }
243
+
244
+ function isValidPositivePid(pid: number | null | undefined): pid is number {
245
+ return typeof pid === "number" && Number.isInteger(pid) && pid > 0;
246
+ }
247
+
248
+ /**
249
+ * Reference-counted process-level `SIGINT` / `exit` safety net for live stdio root PIDs.
250
+ *
251
+ * Listeners are attached only while at least one live stdio PID is tracked, and detached
252
+ * immediately when the last PID stops or exits so tests and `/reload` leak no listeners.
253
+ */
254
+ export class StdioExitGuard {
255
+ private readonly pids = new Set<number>();
256
+ private readonly proc: SignalExitProcess;
257
+ private readonly globalScope: unknown;
258
+ private readonly customKillTreeSync: ((pid: number) => void) | undefined;
259
+ private attached = false;
260
+
261
+ private readonly onSigint = (): void => {
262
+ // WHY: Yield whenever Pi (e.g. interactive-mode handleCtrlZ's ignoreSigint) or another
263
+ // active listener owns SIGINT; ignore passive signal-exit wrappers so headless rpc/json/print
264
+ // modes do not deadlock when both listeners are present.
265
+ const otherActive =
266
+ this.proc.listenerCount("SIGINT") -
267
+ 1 -
268
+ countPassiveSigintListeners(this.proc, this.globalScope);
269
+ if (otherActive > 0) return;
270
+ this.terminateAll();
271
+ this.reRaiseSigint();
272
+ };
273
+
274
+ private readonly onExit = (): void => {
275
+ this.terminateAll();
276
+ };
277
+
278
+ constructor(deps?: Partial<StdioExitGuardDeps>) {
279
+ this.proc = deps?.proc ?? (process as unknown as SignalExitProcess);
280
+ this.globalScope =
281
+ deps && "globalScope" in deps
282
+ ? deps.globalScope
283
+ : resolveGlobalScope(this.proc);
284
+ this.customKillTreeSync = deps?.terminatePidTreeSync;
285
+ }
286
+
287
+ track(pid: number): void {
288
+ if (!isValidPositivePid(pid)) return;
289
+ this.pids.add(pid);
290
+ this.syncListeners();
291
+ }
292
+
293
+ untrack(pid: number | null | undefined): void {
294
+ if (!isValidPositivePid(pid)) return;
295
+ this.pids.delete(pid);
296
+ this.syncListeners();
297
+ }
298
+
299
+ trackedCount(): number {
300
+ return this.pids.size;
301
+ }
302
+
303
+ dispose(): void {
304
+ this.pids.clear();
305
+ this.syncListeners();
306
+ }
307
+
308
+ private syncListeners(): void {
309
+ if (this.pids.size > 0 && !this.attached) {
310
+ this.proc.on("SIGINT", this.onSigint);
311
+ this.proc.on("exit", this.onExit);
312
+ this.attached = true;
313
+ return;
314
+ }
315
+ if (this.pids.size === 0 && this.attached) {
316
+ this.proc.off("SIGINT", this.onSigint);
317
+ this.proc.off("exit", this.onExit);
318
+ this.attached = false;
319
+ }
320
+ }
321
+
322
+ private terminateAll(): void {
323
+ const snapshot = [...this.pids];
324
+ this.pids.clear();
325
+ this.syncListeners();
326
+ if (this.customKillTreeSync) {
327
+ for (const pid of snapshot) {
328
+ this.customKillTreeSync(pid);
329
+ }
330
+ return;
331
+ }
332
+ // WHY: Share one sync child reader across every tracked root so macOS/BSD teardown runs
333
+ // at most one bounded `ps` snapshot even when several stdio servers are running.
334
+ const reader = createSyncChildReader();
335
+ const listDescendants = (root: number): number[] => listDescendantPidsSync(root, reader);
336
+ for (const pid of snapshot) {
337
+ terminatePidTreeSync(pid, { listDescendantPidsSync: listDescendants });
338
+ }
339
+ }
340
+
341
+ private reRaiseSigint(): void {
342
+ try {
343
+ this.proc.kill(this.proc.pid, "SIGINT");
344
+ } catch {
345
+ // WHY: Fallback when self-SIGINT is unsupported or refused in a restricted environment.
346
+ this.proc.exit(130);
347
+ }
348
+ }
349
+ }
@@ -8,15 +8,20 @@
8
8
  * cleanup with injectable process/timer dependencies.
9
9
  */
10
10
 
11
- import { execFile } from "node:child_process";
11
+ import { ChildProcess, execFile } from "node:child_process";
12
12
  import { readFile, readdir } from "node:fs/promises";
13
13
  import { StringDecoder } from "node:string_decoder";
14
14
  import { promisify } from "node:util";
15
- import type { ChildProcess } from "node:child_process";
16
15
  import type { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
16
+ import { isNonRetryableStdioSpawnError } from "./connect-policy.js";
17
+ import { indexProcessTable, StdioExitGuard } from "./stdio-exit-guard.js";
18
+
19
+ export { indexProcessTable } from "./stdio-exit-guard.js";
17
20
 
18
21
  const execFileAsync = promisify(execFile);
19
22
 
23
+ const defaultStdioExitGuard = new StdioExitGuard();
24
+
20
25
  // ─── Line Splitting ───────────────────────────────────────────────────────────
21
26
 
22
27
  export interface LineSplitter {
@@ -88,6 +93,7 @@ export const POST_CLOSE_FLUSH_DELAY_MS = 100;
88
93
  interface StdioChildRecord {
89
94
  process: ChildProcess;
90
95
  closed: boolean;
96
+ trackedPid?: number | undefined;
91
97
  /** Flush the buffered partial stderr line before the pipe is destroyed. */
92
98
  flushStderr(): void;
93
99
  }
@@ -100,6 +106,38 @@ interface StdioChildRecord {
100
106
  * keeps both reachable without pinning a closed transport in memory.
101
107
  */
102
108
  const childRecords = new WeakMap<object, StdioChildRecord>();
109
+ const stdioSpawnErrors = new WeakMap<object, Error>();
110
+ const spawnErrorObservedProcs = new WeakSet<object>();
111
+
112
+ function attachSpawnErrorCapture(
113
+ transport: object,
114
+ proc: ChildProcess | undefined,
115
+ ): void {
116
+ if (!proc || typeof proc.once !== "function" || spawnErrorObservedProcs.has(proc)) {
117
+ return;
118
+ }
119
+ spawnErrorObservedProcs.add(proc);
120
+ proc.once("error", (err: unknown) => {
121
+ if (err instanceof Error && isNonRetryableStdioSpawnError("stdio", err)) {
122
+ stdioSpawnErrors.set(transport, err);
123
+ }
124
+ });
125
+ }
126
+
127
+ /**
128
+ * Return any deterministic non-retryable stdio spawn error captured on `transport`'s child process.
129
+ *
130
+ * WHY: On Windows, `StdioClientTransport.start()` uses `cross-spawn`, which wraps
131
+ * non-`.exe`/`.com` commands (like `uvx` or `missing-pi-mcp-executable-335`) in
132
+ * `cmd.exe /d /s /c "..."`. Because `cmd.exe` spawns, `transport.start()` resolves on
133
+ * `'spawn'` and `Client.connect()` sends `initialize`; when `cmd.exe` exits with status 1,
134
+ * `cross-spawn` hooks `'exit'` and emits `'error'` (`ENOENT`) on the `ChildProcess`
135
+ * asynchronously right before `'close'` causes SDK `Protocol._onclose()` to reject
136
+ * `initialize` with `McpError(-32000, "MCP error -32000: Connection closed")`.
137
+ */
138
+ export function getStdioSpawnError(transport: object | null | undefined): Error | undefined {
139
+ return transport ? stdioSpawnErrors.get(transport) : undefined;
140
+ }
103
141
 
104
142
  /** A transport whose child stderr can be wired and whose `close()` can be wrapped. */
105
143
  interface StderrCarrier {
@@ -176,6 +214,43 @@ export function instrumentStderr(
176
214
  return flush;
177
215
  }
178
216
 
217
+ function isLiveChildProcess(
218
+ proc: ChildProcess | undefined,
219
+ ): proc is ChildProcess & { pid: number } {
220
+ if (!(proc instanceof ChildProcess)) {
221
+ return false;
222
+ }
223
+ return (
224
+ asPositivePid(proc.pid) !== null &&
225
+ proc.exitCode === null &&
226
+ proc.signalCode === null
227
+ );
228
+ }
229
+
230
+ function registerChildRecord(
231
+ transport: StdioClientTransport,
232
+ proc: ChildProcess,
233
+ flushStderr: (() => void) | null,
234
+ ): void {
235
+ attachSpawnErrorCapture(transport, proc);
236
+ const trackedPid = isLiveChildProcess(proc) ? proc.pid : undefined;
237
+ const record: StdioChildRecord = {
238
+ process: proc,
239
+ closed: false,
240
+ trackedPid,
241
+ flushStderr: () => flushStderr?.(),
242
+ };
243
+ if (trackedPid !== undefined) {
244
+ defaultStdioExitGuard.track(trackedPid);
245
+ proc.once("exit", () => defaultStdioExitGuard.untrack(trackedPid));
246
+ }
247
+ proc.once?.("close", () => {
248
+ record.closed = true;
249
+ defaultStdioExitGuard.untrack(trackedPid);
250
+ });
251
+ childRecords.set(transport, record);
252
+ }
253
+
179
254
  export interface InstrumentStdioTransportOptions {
180
255
  onPid(pid: number): void;
181
256
  onStderrLine(line: string): void;
@@ -200,17 +275,10 @@ export function instrumentStdioTransport(
200
275
  const flushStderr = instrumentStderr(transport, onStderrLine);
201
276
 
202
277
  const recordProcess = (proc: ChildProcess | undefined): void => {
278
+ attachSpawnErrorCapture(transport, proc);
203
279
  if (!proc?.pid) return;
204
280
  if (!childRecords.has(transport)) {
205
- const record: StdioChildRecord = {
206
- process: proc,
207
- closed: false,
208
- flushStderr: () => flushStderr?.(),
209
- };
210
- proc.once?.("close", () => {
211
- record.closed = true;
212
- });
213
- childRecords.set(transport, record);
281
+ registerChildRecord(transport, proc, flushStderr);
214
282
  }
215
283
  onPid(proc.pid);
216
284
  };
@@ -285,6 +353,7 @@ export function destroyStdioStreams(transport: object | null | undefined): void
285
353
  const record = childRecords.get(transport);
286
354
  if (!record) return;
287
355
  childRecords.delete(transport);
356
+ defaultStdioExitGuard.untrack(record.trackedPid);
288
357
  // WHY: Flush the buffered partial stderr line first. Destroying our read end keeps the
289
358
  // SDK's PassThrough from ever emitting 'end', so without this a forced teardown drops the
290
359
  // server's last words (the buffered remainder of a line with no trailing newline).
@@ -348,24 +417,6 @@ async function readPsProcessTable(): Promise<Map<number, number[]>> {
348
417
  return indexProcessTable(stdout);
349
418
  }
350
419
 
351
- /** Index `ps -A -o pid=,ppid=` output as a parent PID → child PIDs map. */
352
- export function indexProcessTable(stdout: string): Map<number, number[]> {
353
- const childrenOf = new Map<number, number[]>();
354
- for (const line of stdout.split("\n")) {
355
- const match = /^\s*(\d+)\s+(\d+)\s*$/.exec(line);
356
- if (!match) continue;
357
- const childPid = Number(match[1]);
358
- const parentPid = Number(match[2]);
359
- const siblings = childrenOf.get(parentPid);
360
- if (siblings) {
361
- siblings.push(childPid);
362
- } else {
363
- childrenOf.set(parentPid, [childPid]);
364
- }
365
- }
366
- return childrenOf;
367
- }
368
-
369
420
  function createPlatformChildReader(): (pid: number) => Promise<number[]> {
370
421
  if (process.platform === "linux") return readProcChildren;
371
422
  if (process.platform === "win32") {