pi-mcp-extension 1.14.0 → 1.14.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mcp-extension",
3
- "version": "1.14.0",
3
+ "version": "1.14.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/index.ts CHANGED
@@ -114,10 +114,15 @@ export default async function (pi: ExtensionAPI, paths: { bootstrapCwd?: string;
114
114
  });
115
115
  }
116
116
 
117
+ // WHY: deciding this once keeps the "can we read the live registry?" answer stable; a
118
+ // reconcile turn that falls back to a stale event payload would apply superseded state.
119
+ const hasRegisteredServersSource =
120
+ typeof (pi as { getMcpServers?: () => RegisteredMcpServer[] }).getMcpServers === "function";
121
+ let latestEventEntries: RegisteredMcpServer[] = [];
117
122
  const getRegisteredEntries = (): RegisteredMcpServer[] =>
118
- typeof (pi as { getMcpServers?: () => RegisteredMcpServer[] }).getMcpServers === "function"
119
- ? pi.getMcpServers()
120
- : [];
123
+ hasRegisteredServersSource
124
+ ? (pi as { getMcpServers: () => RegisteredMcpServer[] }).getMcpServers()
125
+ : latestEventEntries;
121
126
 
122
127
  let extensionServers = collectRegisteredServers(
123
128
  getRegisteredEntries(),
@@ -156,10 +161,7 @@ export default async function (pi: ExtensionAPI, paths: { bootstrapCwd?: string;
156
161
  await bridge.refreshTools(
157
162
  serverName,
158
163
  client,
159
- () => {
160
- const current = manager.getServer(serverName);
161
- return current?.client === client && current.state !== "stopped";
162
- },
164
+ () => isClientActive(manager, serverName, client),
163
165
  {
164
166
  ...options,
165
167
  requestTimeoutMs,
@@ -199,158 +201,218 @@ export default async function (pi: ExtensionAPI, paths: { bootstrapCwd?: string;
199
201
  resources.setAuthErrorCallback(handleAuthError);
200
202
 
201
203
  // ── 3. Session lifecycle ──────────────────────────────────────────────────
202
- pi.on("session_start", async (_event, ctx: ExtensionContext) => {
203
- coordinator.setActiveContext(ctx);
204
- // WHY: While a UI is active, the extension never writes to Pi's stderr —
205
- // the TUI owns that stream. Diagnostics go to the debug log instead, and
206
- // user-actionable ones are surfaced through ctx.ui.notify(...).
207
- setDiagnosticUi(ctx.ui, ctx.hasUI);
208
- reportDiagnostic({
209
- level: "info",
210
- event: "session.started",
211
- message: `pi-mcp session started in ${ctx.cwd}`,
212
- fields: { outcome: "started" },
213
- });
214
- // Only load project-level <cwd>/.pi/mcp.json when the project is trusted.
215
- const includeProjectConfig =
216
- typeof (ctx as { isProjectTrusted?: () => boolean }).isProjectTrusted === "function"
217
- ? (ctx as { isProjectTrusted: () => boolean }).isProjectTrusted()
218
- : true;
204
+ // WHY: Pi's MCP registry emits `mcp_servers_change` synchronously for every register() and
205
+ // unregister() (`void this.emit(...)` in the runner, which does not wait for earlier
206
+ // listeners), so a burst of registrations runs concurrent reconciles. Each reconcile awaits
207
+ // process teardown, so the second one sees a half-shut-down server, finishes first, and the
208
+ // first one's resume then resurrects an unregistered server — or deletes a server the second
209
+ // one just registered, orphaning its stdio child. One serialized queue whose turns re-read the
210
+ // live registry collapses a burst into the state that is current when the turn runs.
211
+ let sessionActive = false;
212
+ let sessionEpoch = 0;
213
+ // Counts every `mcp_servers_change` notification and the latest count already reconciled,
214
+ // so a burst of events collapses into one turn and session_start can tell whether a
215
+ // registration landed after it snapshotted the registry.
216
+ let changeEventCount = 0;
217
+ let appliedChangeCount = 0;
218
+ let reconcileQueue: Promise<void> = Promise.resolve();
219
+ let activeSessionStart: Promise<void> = Promise.resolve();
220
+ // Eager servers currently inside a startEagerServers call, so a superseding
221
+ // mcp_servers_change can abort and remove extension servers immediately, and a session
222
+ // transition can stop still-connecting servers without dropping them from config.
223
+ const inFlightEager = new Map<string, ServerConfig>();
224
+ const inFlightEagerBatch: Array<[string, ServerConfig]> = [];
225
+ const pendingEagerOps: Array<Promise<void>> = [];
226
+
227
+ const applyServers = (next: Record<string, ServerConfig>, snapshotCount: number): void => {
228
+ extensionServers = next;
229
+ config = mergeWithRegisteredServers(fileConfig, next);
230
+ appliedChangeCount = snapshotCount;
231
+ };
232
+
233
+ const removeAppliedServer = (name: string): void => {
234
+ const { [name]: _removed, ...remaining } = extensionServers;
235
+ extensionServers = remaining;
236
+ config = mergeWithRegisteredServers(fileConfig, remaining);
237
+ };
238
+
239
+ const abortEagerStart = (name: string): void => {
240
+ inFlightEager.delete(name);
241
+ removeFromEagerBatch(inFlightEagerBatch, name);
242
+ coordinator.cancelServer(name);
243
+ bridge.removeServer(name);
244
+ resources.forget(name);
245
+ removeAppliedServer(name);
246
+ pendingEagerOps.push(manager.removeServer(name));
247
+ coordinator.syncStatus();
248
+ };
249
+
250
+ const stopInFlightEagerStarts = (): void => {
251
+ inFlightEager.clear();
252
+ for (const [name] of inFlightEagerBatch.splice(0)) {
253
+ coordinator.cancelServer(name);
254
+ if (manager.getServer(name)?.state === "starting") {
255
+ pendingEagerOps.push(manager.stopServer(name));
256
+ }
257
+ }
258
+ };
219
259
 
220
- let nextLoaded: LoadedConfig;
260
+ const runEagerStarts = async (
261
+ eagerServers: Array<[string, ServerConfig]>,
262
+ ctx: ExtensionContext,
263
+ ): Promise<void> => {
264
+ inFlightEagerBatch.splice(0, inFlightEagerBatch.length, ...eagerServers);
265
+ for (const [name, cfg] of eagerServers) {
266
+ if (Object.prototype.hasOwnProperty.call(extensionServers, name)) {
267
+ inFlightEager.set(name, cfg);
268
+ }
269
+ }
221
270
  try {
222
- nextLoaded = await loadConfigWithOrigins(ctx.cwd, paths.globalConfigPath, { includeProjectConfig });
223
- } catch (err) {
224
- const msg = formatErrorMessage(err);
225
- ctx.ui.notify(`pi-mcp: Config error — ${msg}`, "error");
226
- // WHY: A config that failed to parse still supplies no server origins, so the
227
- // provenance must not keep pointing at the previous session's file entries.
228
- fileProvenance = {
229
- origins: {},
230
- projectConfigPath: join(ctx.cwd, ".pi", "mcp.json"),
231
- projectConfigIncluded: includeProjectConfig,
232
- };
233
- // WHY: Switching sessions into a directory with an invalid config must tear down stale
234
- // servers, tools, prompts, and status from the previous session rather than leaving them active.
235
- await coordinator.teardown(ctx);
236
- fileConfig = {
237
- settings: { ...DEFAULT_SETTINGS },
238
- mcpServers: {},
239
- };
240
- extensionServers = collectRegisteredServers(
241
- getRegisteredEntries(),
242
- fileConfig.mcpServers,
243
- (regErr) => {
244
- const regMsg = formatErrorMessage(regErr);
245
- ctx.ui.notify(`pi-mcp: Config error — ${regMsg}`, "error");
246
- },
247
- );
248
- config = mergeWithRegisteredServers(fileConfig, extensionServers);
249
- bridge.updateSettings(config.settings);
250
- manager.rebuildServers(config);
251
- if (Object.keys(extensionServers).length > 0) {
252
- const eagerServers = Object.entries(config.mcpServers).filter(
253
- ([, cfg]) => cfg.lifecycle === "eager",
271
+ if (changeEventCount !== appliedChangeCount) {
272
+ abortSupersededEagerStarts(
273
+ inFlightEager,
274
+ getRegisteredEntries(),
275
+ fileConfig.mcpServers,
276
+ abortEagerStart,
254
277
  );
255
- await coordinator.startEagerServers(eagerServers, ctx);
256
278
  }
257
- return;
279
+ if (inFlightEagerBatch.length > 0) {
280
+ await coordinator.startEagerServers(inFlightEagerBatch, ctx);
281
+ }
282
+ } finally {
283
+ inFlightEager.clear();
284
+ inFlightEagerBatch.length = 0;
285
+ if (pendingEagerOps.length > 0) {
286
+ await Promise.allSettled(pendingEagerOps.splice(0));
287
+ }
258
288
  }
289
+ };
259
290
 
260
- fileConfig = nextLoaded.config;
261
- fileProvenance = nextLoaded;
262
- extensionServers = collectRegisteredServers(
263
- getRegisteredEntries(),
264
- fileConfig.mcpServers,
265
- (err) => {
266
- const msg = formatErrorMessage(err);
267
- ctx.ui.notify(`pi-mcp: Config error — ${msg}`, "error");
268
- },
291
+ const enqueueServerReconcile = (ctx: ExtensionContext): Promise<void> => {
292
+ const epoch = sessionEpoch;
293
+ // WHY: Pi's registry announces every register()/unregister(), including during extension
294
+ // loading (before session_start has checked trust and read <cwd>/.pi/mcp.json) and after
295
+ // session_shutdown. Spawning servers then attaches child processes to no session; the
296
+ // built-in MCP extension ignores those events the same way (its session signal starts
297
+ // aborted). session_start reads the registry itself, so the turn just no-ops instead.
298
+ const isCurrent = () => sessionActive && epoch === sessionEpoch;
299
+ const turn = reconcileQueue.then(() =>
300
+ reconcileRegisteredServers(
301
+ {
302
+ manager,
303
+ coordinator,
304
+ bridge,
305
+ resources,
306
+ fileConfig,
307
+ appliedServers: extensionServers,
308
+ registeredEntries: getRegisteredEntries(),
309
+ appliedChangeCount,
310
+ getChangeCount: () => changeEventCount,
311
+ isCurrent,
312
+ removeAppliedServer,
313
+ applyServers,
314
+ runEagerStarts,
315
+ },
316
+ ctx,
317
+ ),
269
318
  );
270
- const sessionConfig = mergeWithRegisteredServers(fileConfig, extensionServers);
271
-
272
- // If config changed (different cwd with project-level overrides or registered servers),
273
- // shut down old servers and rebuild the manager's server list
274
- if (JSON.stringify(sessionConfig) !== JSON.stringify(config)) {
319
+ // WHY: the emitter is fire-and-forget, so a rejected turn would become an unhandled
320
+ // rejection; report it instead and keep the queue usable for later registrations.
321
+ reconcileQueue = turn.catch((err: unknown) => {
322
+ const { kind, message } = describeError(err);
275
323
  reportDiagnostic({
276
- level: "info",
277
- event: "session.reload",
278
- message: "MCP configuration changed; reloading servers and tools",
279
- fields: { outcome: "config_changed" },
324
+ level: "error",
325
+ event: "servers.change_error",
326
+ message: `Failed to apply MCP server registration change: ${message}`,
327
+ fields: { kind },
280
328
  });
281
- await coordinator.teardown(ctx);
282
- // Rebuild server entries from new config
283
- bridge.updateSettings(sessionConfig.settings);
284
- manager.rebuildServers(sessionConfig);
285
- config = sessionConfig;
286
- } else {
287
- // WHY: Even when config is identical across session switches, update running servers'
288
- // cwd and emit notifications/roots/list_changed if the workspace directory changed.
289
- manager.updateCwd(ctx.cwd);
290
- coordinator.syncStatus(ctx);
291
- }
292
-
293
- const eagerServers = Object.entries(sessionConfig.mcpServers).filter(
294
- ([, cfg]) => cfg.lifecycle === "eager",
295
- );
296
-
297
- await coordinator.startEagerServers(eagerServers, ctx);
298
- });
299
-
300
- // Connect or disconnect MCP servers registered dynamically via pi.registerMcpServer().
301
- pi.on("mcp_servers_change", async (event, ctx: ExtensionContext) => {
302
- coordinator.setActiveContext(ctx);
303
- setDiagnosticUi(ctx.ui, ctx.hasUI);
304
- const entries = Array.isArray((event as { servers?: unknown })?.servers)
305
- ? ((event as { servers: RegisteredMcpServer[] }).servers)
306
- : getRegisteredEntries();
307
-
308
- const nextExtensionServers = collectRegisteredServers(
309
- entries,
310
- fileConfig.mcpServers,
311
- (err) => {
312
- const msg = formatErrorMessage(err);
313
- ctx.ui.notify(`pi-mcp: Config error — ${msg}`, "error");
314
- },
315
- );
316
-
317
- const removedOrChanged: string[] = [];
318
- for (const [name, prevCfg] of Object.entries(extensionServers)) {
319
- const nextCfg = nextExtensionServers[name];
320
- if (!nextCfg || JSON.stringify(prevCfg) !== JSON.stringify(nextCfg)) {
321
- removedOrChanged.push(name);
329
+ if (isCurrent()) {
330
+ ctx.ui.notify(`pi-mcp: Failed to apply server registration change — ${message}`, "error");
322
331
  }
323
- }
332
+ });
333
+ return reconcileQueue;
334
+ };
324
335
 
325
- for (const name of removedOrChanged) {
326
- coordinator.cancelServer(name);
327
- bridge.removeServer(name);
328
- resources.forget(name);
329
- await manager.removeServer(name);
330
- }
331
- if (removedOrChanged.length > 0) {
332
- coordinator.syncStatus(ctx);
333
- }
336
+ const sessionStartDeps: SessionStartDeps = {
337
+ globalConfigPath: paths.globalConfigPath,
338
+ manager,
339
+ coordinator,
340
+ bridge,
341
+ getCurrentConfig: () => config,
342
+ getRegisteredEntries,
343
+ setSessionConfigState: (nextFileConfig, nextProvenance, nextExtensionServers, nextConfig) => {
344
+ fileConfig = nextFileConfig;
345
+ fileProvenance = nextProvenance;
346
+ appliedChangeCount = changeEventCount;
347
+ extensionServers = nextExtensionServers;
348
+ config = nextConfig;
349
+ },
350
+ runEagerStarts,
351
+ };
334
352
 
335
- const addedEager: Array<[string, ServerConfig]> = [];
336
- for (const [name, nextCfg] of Object.entries(nextExtensionServers)) {
337
- if (!manager.getServer(name)) {
338
- manager.setServer(name, nextCfg);
339
- if (nextCfg.lifecycle === "eager") {
340
- addedEager.push([name, nextCfg]);
353
+ pi.on("session_start", async (_event, ctx: ExtensionContext) => {
354
+ // WHY: a queued reconcile or earlier startup belongs to the session that started it;
355
+ // marking the session inactive, bumping the epoch, stopping any in-flight eager starts,
356
+ // and draining both the previous startup and reconcileQueue ensures earlier work has
357
+ // settled before runSessionStart diffs sessionConfig against config.
358
+ sessionActive = false;
359
+ const epoch = ++sessionEpoch;
360
+ const isCurrent = () => epoch === sessionEpoch;
361
+ stopInFlightEagerStarts();
362
+ const previousStart = activeSessionStart;
363
+ const turn = (async () => {
364
+ await previousStart;
365
+ await reconcileQueue;
366
+ try {
367
+ if (isCurrent()) {
368
+ await runSessionStart(sessionStartDeps, ctx, isCurrent);
369
+ }
370
+ } finally {
371
+ // WHY: only activate the session if neither session_shutdown nor a newer session_start
372
+ // superseded this startup while runSessionStart was awaiting config I/O or eager connects.
373
+ if (isCurrent()) {
374
+ sessionActive = true;
375
+ // WHY: reconcile only when a registration landed after runSessionStart snapshotted
376
+ // the registry. An unconditional turn would re-collect the registry on every session
377
+ // start and repeat the per-entry config-error notification runSessionStart already
378
+ // surfaced. Looping drains any registration that arrives mid-reconcile too.
379
+ while (isCurrent() && changeEventCount !== appliedChangeCount) {
380
+ await enqueueServerReconcile(ctx);
381
+ }
341
382
  }
342
383
  }
343
- }
344
-
345
- extensionServers = nextExtensionServers;
346
- config = mergeWithRegisteredServers(fileConfig, extensionServers);
384
+ })();
385
+ activeSessionStart = turn.catch(() => {
386
+ // WHY: keep activeSessionStart resolved so a later session_start or session_shutdown never rejects.
387
+ });
388
+ await turn;
389
+ });
347
390
 
348
- if (addedEager.length > 0) {
349
- await coordinator.startEagerServers(addedEager, ctx);
391
+ // Connect or disconnect MCP servers registered dynamically via pi.registerMcpServer().
392
+ pi.on("mcp_servers_change", (event, ctx: ExtensionContext) => {
393
+ if (Array.isArray((event as { servers?: unknown })?.servers)) {
394
+ latestEventEntries = (event as { servers: RegisteredMcpServer[] }).servers;
350
395
  }
396
+ changeEventCount += 1;
397
+ abortSupersededEagerStarts(
398
+ inFlightEager,
399
+ getRegisteredEntries(),
400
+ fileConfig.mcpServers,
401
+ abortEagerStart,
402
+ );
403
+ return enqueueServerReconcile(ctx);
351
404
  });
352
405
 
353
406
  pi.on("session_shutdown", async (_event, ctx: ExtensionContext) => {
407
+ // WHY: invalidate before tearing down so an in-flight startup or queued reconcile
408
+ // observes a dead session and bails, then drain both after teardown so shutdown never
409
+ // returns while a turn is still mutating state or spawning children. Teardown runs first
410
+ // because it aborts any eager start the in-flight turn is waiting on while keeping
411
+ // configured servers in ServerManager in "stopped" state (removeServers: false).
412
+ sessionActive = false;
413
+ sessionEpoch += 1;
414
+ inFlightEager.clear();
415
+ inFlightEagerBatch.length = 0;
354
416
  reportDiagnostic({
355
417
  level: "info",
356
418
  event: "session.teardown",
@@ -358,6 +420,8 @@ export default async function (pi: ExtensionAPI, paths: { bootstrapCwd?: string;
358
420
  fields: { outcome: "shutdown" },
359
421
  });
360
422
  await coordinator.teardown(ctx, { removeServers: false });
423
+ await activeSessionStart;
424
+ await reconcileQueue;
361
425
  coordinator.setActiveContext(undefined);
362
426
  setDiagnosticUi(null, false);
363
427
  // WHY: Flush the queued debug-log writes before the process may exit, so a
@@ -388,6 +452,337 @@ export default async function (pi: ExtensionAPI, paths: { bootstrapCwd?: string;
388
452
  registerManagementTools(pi, { manager, coordinator, bridge, resources, getProvenance });
389
453
  }
390
454
 
455
+ function isClientActive(
456
+ manager: ServerManager,
457
+ serverName: string,
458
+ client: ManagedServer["client"],
459
+ ): boolean {
460
+ const current = manager.getServer(serverName);
461
+ return current?.client === client && current.state !== "stopped";
462
+ }
463
+
464
+ function isProjectTrusted(ctx: ExtensionContext): boolean {
465
+ return typeof (ctx as { isProjectTrusted?: () => boolean }).isProjectTrusted === "function"
466
+ ? (ctx as { isProjectTrusted: () => boolean }).isProjectTrusted()
467
+ : true;
468
+ }
469
+
470
+ function filterEagerServers(
471
+ servers: Record<string, ServerConfig>,
472
+ ): Array<[string, ServerConfig]> {
473
+ return Object.entries(servers).filter(([, cfg]) => cfg.lifecycle === "eager");
474
+ }
475
+
476
+ function removeFromEagerBatch(
477
+ batch: Array<[string, ServerConfig]>,
478
+ name: string,
479
+ ): void {
480
+ const index = batch.findIndex(([entryName]) => entryName === name);
481
+ if (index !== -1) {
482
+ batch.splice(index, 1);
483
+ }
484
+ }
485
+
486
+ interface SessionStartDeps {
487
+ globalConfigPath: string | undefined;
488
+ manager: ServerManager;
489
+ coordinator: ConnectionCoordinator;
490
+ bridge: ToolBridge;
491
+ getCurrentConfig: () => McpConfig;
492
+ getRegisteredEntries: () => readonly RegisteredMcpServer[];
493
+ setSessionConfigState: (
494
+ nextFileConfig: McpConfig,
495
+ nextProvenance: ConfigProvenanceInput,
496
+ nextExtensionServers: Record<string, ServerConfig>,
497
+ nextConfig: McpConfig,
498
+ ) => void;
499
+ runEagerStarts: (
500
+ eagerServers: Array<[string, ServerConfig]>,
501
+ ctx: ExtensionContext,
502
+ ) => Promise<void>;
503
+ }
504
+
505
+ function applyFailedConfigFallback(
506
+ deps: SessionStartDeps,
507
+ ctx: ExtensionContext,
508
+ includeProjectConfig: boolean,
509
+ ): Array<[string, ServerConfig]> {
510
+ // WHY: A config that failed to parse still supplies no server origins, so the
511
+ // provenance must not keep pointing at the previous session's file entries.
512
+ const fallbackProvenance: ConfigProvenanceInput = {
513
+ origins: {},
514
+ projectConfigPath: join(ctx.cwd, ".pi", "mcp.json"),
515
+ projectConfigIncluded: includeProjectConfig,
516
+ };
517
+ const fallbackFileConfig: McpConfig = {
518
+ settings: { ...DEFAULT_SETTINGS },
519
+ mcpServers: {},
520
+ };
521
+ const nextExtensionServers = collectRegisteredServers(
522
+ deps.getRegisteredEntries(),
523
+ fallbackFileConfig.mcpServers,
524
+ (regErr) => {
525
+ const regMsg = formatErrorMessage(regErr);
526
+ ctx.ui.notify(`pi-mcp: Config error — ${regMsg}`, "error");
527
+ },
528
+ );
529
+ const nextConfig = mergeWithRegisteredServers(fallbackFileConfig, nextExtensionServers);
530
+ deps.setSessionConfigState(
531
+ fallbackFileConfig,
532
+ fallbackProvenance,
533
+ nextExtensionServers,
534
+ nextConfig,
535
+ );
536
+ deps.bridge.updateSettings(nextConfig.settings);
537
+ deps.manager.rebuildServers(nextConfig);
538
+ return Object.keys(nextExtensionServers).length > 0
539
+ ? filterEagerServers(nextConfig.mcpServers)
540
+ : [];
541
+ }
542
+
543
+ function hasSessionConfigChanged(
544
+ deps: SessionStartDeps,
545
+ nextLoaded: LoadedConfig,
546
+ ): boolean {
547
+ const previewExtensionServers = collectRegisteredServers(
548
+ deps.getRegisteredEntries(),
549
+ nextLoaded.config.mcpServers,
550
+ );
551
+ const previewConfig = mergeWithRegisteredServers(
552
+ nextLoaded.config,
553
+ previewExtensionServers,
554
+ );
555
+ return JSON.stringify(previewConfig) !== JSON.stringify(deps.getCurrentConfig());
556
+ }
557
+
558
+ function commitLoadedConfig(
559
+ deps: SessionStartDeps,
560
+ ctx: ExtensionContext,
561
+ nextLoaded: LoadedConfig,
562
+ rebuild: boolean,
563
+ ): Array<[string, ServerConfig]> {
564
+ const nextExtensionServers = collectRegisteredServers(
565
+ deps.getRegisteredEntries(),
566
+ nextLoaded.config.mcpServers,
567
+ (err) => {
568
+ const msg = formatErrorMessage(err);
569
+ ctx.ui.notify(`pi-mcp: Config error — ${msg}`, "error");
570
+ },
571
+ );
572
+ const sessionConfig = mergeWithRegisteredServers(nextLoaded.config, nextExtensionServers);
573
+ deps.setSessionConfigState(
574
+ nextLoaded.config,
575
+ nextLoaded,
576
+ nextExtensionServers,
577
+ rebuild ? sessionConfig : deps.getCurrentConfig(),
578
+ );
579
+ if (rebuild) {
580
+ deps.bridge.updateSettings(sessionConfig.settings);
581
+ deps.manager.rebuildServers(sessionConfig);
582
+ } else {
583
+ // WHY: Even when config is identical across session switches, update running servers'
584
+ // cwd and emit notifications/roots/list_changed if the workspace directory changed.
585
+ deps.manager.updateCwd(ctx.cwd);
586
+ deps.coordinator.syncStatus(ctx);
587
+ }
588
+ return filterEagerServers(sessionConfig.mcpServers);
589
+ }
590
+
591
+ async function handleSessionConfigLoadError(
592
+ deps: SessionStartDeps,
593
+ ctx: ExtensionContext,
594
+ includeProjectConfig: boolean,
595
+ isCurrent: () => boolean,
596
+ err: unknown,
597
+ ): Promise<void> {
598
+ if (!isCurrent()) return;
599
+ const msg = formatErrorMessage(err);
600
+ ctx.ui.notify(`pi-mcp: Config error — ${msg}`, "error");
601
+ // WHY: Switching sessions into a directory with an invalid config must tear down stale
602
+ // servers, tools, prompts, and status from the previous session rather than leaving them active.
603
+ await deps.coordinator.teardown(ctx);
604
+ if (!isCurrent()) return;
605
+ const eagerServers = applyFailedConfigFallback(deps, ctx, includeProjectConfig);
606
+ if (!isCurrent() || eagerServers.length === 0) return;
607
+ await deps.runEagerStarts(eagerServers, ctx);
608
+ }
609
+
610
+ async function applyLoadedSessionConfig(
611
+ deps: SessionStartDeps,
612
+ ctx: ExtensionContext,
613
+ nextLoaded: LoadedConfig,
614
+ isCurrent: () => boolean,
615
+ ): Promise<void> {
616
+ const configChanged = hasSessionConfigChanged(deps, nextLoaded);
617
+ if (configChanged) {
618
+ reportDiagnostic({
619
+ level: "info",
620
+ event: "session.reload",
621
+ message: "MCP configuration changed; reloading servers and tools",
622
+ fields: { outcome: "config_changed" },
623
+ });
624
+ await deps.coordinator.teardown(ctx);
625
+ if (!isCurrent()) return;
626
+ }
627
+ const eagerServers = commitLoadedConfig(deps, ctx, nextLoaded, configChanged);
628
+ if (!isCurrent() || eagerServers.length === 0) return;
629
+ await deps.runEagerStarts(eagerServers, ctx);
630
+ }
631
+
632
+ async function runSessionStart(
633
+ deps: SessionStartDeps,
634
+ ctx: ExtensionContext,
635
+ isCurrent: () => boolean,
636
+ ): Promise<void> {
637
+ deps.coordinator.setActiveContext(ctx);
638
+ // WHY: While a UI is active, the extension never writes to Pi's stderr —
639
+ // the TUI owns that stream. Diagnostics go to the debug log instead, and
640
+ // user-actionable ones are surfaced through ctx.ui.notify(...).
641
+ setDiagnosticUi(ctx.ui, ctx.hasUI);
642
+ reportDiagnostic({
643
+ level: "info",
644
+ event: "session.started",
645
+ message: `pi-mcp session started in ${ctx.cwd}`,
646
+ fields: { outcome: "started" },
647
+ });
648
+ const includeProjectConfig = isProjectTrusted(ctx);
649
+
650
+ let nextLoaded: LoadedConfig;
651
+ try {
652
+ nextLoaded = await loadConfigWithOrigins(ctx.cwd, deps.globalConfigPath, {
653
+ includeProjectConfig,
654
+ });
655
+ } catch (err) {
656
+ await handleSessionConfigLoadError(deps, ctx, includeProjectConfig, isCurrent, err);
657
+ return;
658
+ }
659
+ if (!isCurrent()) return;
660
+ await applyLoadedSessionConfig(deps, ctx, nextLoaded, isCurrent);
661
+ }
662
+
663
+ interface RegistrationReconcileDeps {
664
+ manager: ServerManager;
665
+ coordinator: ConnectionCoordinator;
666
+ bridge: ToolBridge;
667
+ resources: ResourceBridge;
668
+ /** File-backed config; extension registrations are merged on top of it. */
669
+ fileConfig: McpConfig;
670
+ /** Registrations currently in effect, diffed against the new snapshot. */
671
+ appliedServers: Record<string, ServerConfig>;
672
+ /** The registry as it is when the turn runs; an event's own snapshot is already stale. */
673
+ registeredEntries: readonly RegisteredMcpServer[];
674
+ /** Change counter already applied when this turn begins. */
675
+ appliedChangeCount: number;
676
+ /** Live change counter, re-read after each async teardown step to detect supersession. */
677
+ getChangeCount: () => number;
678
+ /** False once the session that queued this turn has switched or shut down. */
679
+ isCurrent: () => boolean;
680
+ /** Drops a single removed server from the applied state before awaiting its teardown. */
681
+ removeAppliedServer: (name: string) => void;
682
+ /** Publishes the applied registrations and merged config before eager servers start. */
683
+ applyServers: (next: Record<string, ServerConfig>, snapshotCount: number) => void;
684
+ /** Starts newly staged eager servers while tracking them so superseding events can abort them. */
685
+ runEagerStarts: (addedEager: Array<[string, ServerConfig]>, ctx: ExtensionContext) => Promise<void>;
686
+ }
687
+
688
+ function abortSupersededEagerStarts(
689
+ inFlightEager: ReadonlyMap<string, ServerConfig>,
690
+ registeredEntries: readonly RegisteredMcpServer[],
691
+ fileServers: Record<string, ServerConfig>,
692
+ abortEagerStart: (name: string) => void,
693
+ ): void {
694
+ if (inFlightEager.size === 0) return;
695
+ const nextPreview = collectRegisteredServers(registeredEntries, fileServers);
696
+ for (const name of findRemovedOrChangedServers(
697
+ Object.fromEntries(inFlightEager),
698
+ nextPreview,
699
+ )) {
700
+ abortEagerStart(name);
701
+ }
702
+ }
703
+
704
+ function findRemovedOrChangedServers(
705
+ appliedServers: Record<string, ServerConfig>,
706
+ nextServers: Record<string, ServerConfig>,
707
+ ): string[] {
708
+ const removedOrChanged: string[] = [];
709
+ for (const [name, prevCfg] of Object.entries(appliedServers)) {
710
+ const nextCfg = nextServers[name];
711
+ if (!nextCfg || JSON.stringify(prevCfg) !== JSON.stringify(nextCfg)) {
712
+ removedOrChanged.push(name);
713
+ }
714
+ }
715
+ return removedOrChanged;
716
+ }
717
+
718
+ function stageAddedServers(
719
+ manager: ServerManager,
720
+ nextServers: Record<string, ServerConfig>,
721
+ ): Array<[string, ServerConfig]> {
722
+ const addedEager: Array<[string, ServerConfig]> = [];
723
+ for (const [name, nextCfg] of Object.entries(nextServers)) {
724
+ if (manager.getServer(name)) continue;
725
+ manager.setServer(name, nextCfg);
726
+ if (nextCfg.lifecycle === "eager") {
727
+ addedEager.push([name, nextCfg]);
728
+ }
729
+ }
730
+ return addedEager;
731
+ }
732
+
733
+ /**
734
+ * Bring the manager, bridge, and config in line with the current registrations.
735
+ *
736
+ * `isCurrent` and `getChangeCount` are checked at entry and after each removal await, so a
737
+ * session switch/shutdown or a newer registration that arrived while a teardown was in flight
738
+ * stops the turn before it re-adds or starts superseded servers. An eager start already running
739
+ * when a newer registration or session transition arrives is aborted via `runEagerStarts`.
740
+ */
741
+ async function reconcileRegisteredServers(
742
+ deps: RegistrationReconcileDeps,
743
+ ctx: ExtensionContext,
744
+ ): Promise<void> {
745
+ const snapshotCount = deps.getChangeCount();
746
+ if (!deps.isCurrent() || deps.appliedChangeCount === snapshotCount) return;
747
+
748
+ deps.coordinator.setActiveContext(ctx);
749
+ setDiagnosticUi(ctx.ui, ctx.hasUI);
750
+
751
+ const configErrors: string[] = [];
752
+ const nextExtensionServers = collectRegisteredServers(
753
+ deps.registeredEntries,
754
+ deps.fileConfig.mcpServers,
755
+ (err) => {
756
+ configErrors.push(formatErrorMessage(err));
757
+ },
758
+ );
759
+
760
+ const removedOrChanged = findRemovedOrChangedServers(deps.appliedServers, nextExtensionServers);
761
+ for (const name of removedOrChanged) {
762
+ deps.coordinator.cancelServer(name);
763
+ deps.bridge.removeServer(name);
764
+ deps.resources.forget(name);
765
+ deps.removeAppliedServer(name);
766
+ await deps.manager.removeServer(name);
767
+ deps.coordinator.syncStatus(ctx);
768
+ // WHY: the next step re-adds and starts servers, which must never happen when the
769
+ // session went away or a newer registration superseded this snapshot during teardown.
770
+ if (!deps.isCurrent() || deps.getChangeCount() !== snapshotCount) return;
771
+ }
772
+
773
+ for (const msg of configErrors) {
774
+ ctx.ui.notify(`pi-mcp: Config error — ${msg}`, "error");
775
+ }
776
+
777
+ const addedEager = stageAddedServers(deps.manager, nextExtensionServers);
778
+ deps.applyServers(nextExtensionServers, snapshotCount);
779
+ deps.coordinator.syncStatus(ctx);
780
+
781
+ if (addedEager.length > 0) {
782
+ await deps.runEagerStarts(addedEager, ctx);
783
+ }
784
+ }
785
+
391
786
  interface ManagementToolDeps {
392
787
  manager: ServerManager;
393
788
  coordinator: ConnectionCoordinator;
@@ -462,7 +462,13 @@ export class ServerManager {
462
462
  const server = this.servers.get(name);
463
463
  if (!server) return;
464
464
  await this._shutdown(server);
465
- this.servers.delete(name);
465
+ // WHY: _shutdown awaits child-process teardown, and the registration reconcile installs a
466
+ // replacement right after removing the changed entry — it can land in that window. Deleting
467
+ // by name alone would drop that live entry and orphan its stdio child, which nothing can
468
+ // then terminate.
469
+ if (this.servers.get(name) === server) {
470
+ this.servers.delete(name);
471
+ }
466
472
  }
467
473
 
468
474
  /**