pi-mcp-extension 1.14.3 → 1.14.5

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
@@ -309,6 +309,8 @@ Recent output:
309
309
 
310
310
  `mcp_connect` checks current tool activation before reporting success, including when the server is already connected. If discovered tools are inactive, it reports that condition instead of overriding another extension's tool restrictions. Check the active tool policy or conflicting extension. A reconnect is not a substitute for fixing an extension that removes tools at each user turn.
311
311
 
312
+ Tool discovery follows the same rule. When a connected server announces `notifications/tools/list_changed`, only the tools it newly exposes are activated; tools Pi currently has inactive stay inactive, a tool the server dropped and then advertises again comes back in the state it left in, and a refresh that discovers nothing new does not touch the active set at all. Stopping a connected server (`/mcp:stop`, background recovery, or session teardown) deactivates its tools and forgets those remembered states, so the next connect or reconnect activates the whole discovered set again.
313
+
312
314
  ## Debug log
313
315
 
314
316
  Set `PI_MCP_DEBUG=1` before starting Pi to record what the extension itself is doing — server state transitions, retries and backoff, OAuth refresh and cross-process lock contention, 401/403 classification, and session reloads:
@@ -378,7 +380,7 @@ flowchart TD
378
380
  7. **AbortSignal** is wired through to `notifications/cancelled` for clean cancellation
379
381
  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
380
382
  9. **`list_changed` notifications** trigger re-discovery, deactivating stale tools automatically and invalidating the cached resource catalog
381
- 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` and pipe cleanup for `stdio` child processes)
383
+ 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)
382
384
 
383
385
  ## MCP Spec Compliance
384
386
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mcp-extension",
3
- "version": "1.14.3",
3
+ "version": "1.14.5",
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": [
@@ -450,63 +450,105 @@ function resolveDeps(deps?: Partial<StdioProcessDeps>): StdioProcessDeps {
450
450
  };
451
451
  }
452
452
 
453
- export function isPidAlive(
454
- pid: number,
455
- deps?: Partial<Pick<StdioProcessDeps, "kill">>,
456
- ): boolean {
457
- const kill = deps?.kill ?? defaultDeps.kill;
458
- try {
459
- kill(pid, 0);
460
- return true;
461
- } catch (err) {
462
- if ((err as NodeJS.ErrnoException).code === "ESRCH") {
463
- return false;
464
- }
465
- return true;
466
- }
453
+ /** What one `kill(2)` attempt reported about a PID. */
454
+ type PidSignalOutcome =
455
+ /** The signal was delivered: the PID resolves to a process this caller may signal. */
456
+ | "signalled"
457
+ /** ESRCH: nothing holds this PID any more. */
458
+ | "gone"
459
+ /** EPERM or another platform refusal: the PID is not this caller's to signal. */
460
+ | "denied";
461
+
462
+ /**
463
+ * POSIX liveness: a PID is alive while `kill(pid, 0)` fails with anything but ESRCH.
464
+ *
465
+ * WHY: EPERM means the PID is taken but belongs to a process this caller may not signal (a
466
+ * recycled PID under another uid, a sandboxed child, PID 1). A caller that asks only whether the
467
+ * PID is *occupied* must read that as occupied, not free; teardown asks the stricter
468
+ * `isPidSignalable` instead. Auth-lock's staleness check needs this reading too and keeps its own
469
+ * probe (`defaultIsPidAlive` in `src/auth-lock.ts`), so it does not call this one.
470
+ */
471
+ export function isPidAlive(pid: number, deps?: Partial<Pick<StdioProcessDeps, "kill">>): boolean {
472
+ return signalPid(pid, 0, resolveDeps(deps)) !== "gone";
467
473
  }
468
474
 
469
- /** Send `signal` to one PID; `false` when the PID was already gone (ESRCH). */
470
- function signalPid(pid: number, signal: NodeJS.Signals, d: StdioProcessDeps): boolean {
475
+ function signalPid(
476
+ pid: number,
477
+ signal: NodeJS.Signals | number,
478
+ d: StdioProcessDeps,
479
+ ): PidSignalOutcome {
471
480
  try {
472
481
  d.kill(pid, signal);
473
- return true;
482
+ return "signalled";
474
483
  } catch (err) {
475
484
  if ((err as NodeJS.ErrnoException).code === "ESRCH") {
476
- return false;
485
+ return "gone";
477
486
  }
478
487
  // WHY: EPERM and platform refusals mean this PID cannot be signalled (a recycled PID
479
488
  // or a sandboxed process). Teardown still has to signal the rest of the tree within
480
489
  // the bounded wait instead of rejecting the caller's shutdown path.
481
- return true;
490
+ return "denied";
482
491
  }
483
492
  }
484
493
 
494
+ /**
495
+ * A PID this teardown can still act on: alive *and* signalable.
496
+ *
497
+ * WHY: a PID the caller cannot signal is not one a bounded wait can make progress on. `EPERM`
498
+ * means no signal of ours reaches that PID — the child has exited and the PID was recycled to a
499
+ * process under another uid, the child changed credentials (a wrapper that `setuid`s), or a
500
+ * policy layer refuses the signal — so polling it re-reads the same `EPERM` every 25ms until
501
+ * the timeout, and escalating to SIGKILL only buys a second refused signal.
502
+ *
503
+ * This answers "can we still reach it", never "is it our child": a PID recycled to another
504
+ * process of the *same* uid stays signalable and is signalled, exactly as before this guard
505
+ * existed. Identity would need the child's start time compared against `/proc/<pid>/stat`, and
506
+ * the `ChildProcess` handle is gone by the time teardown runs.
507
+ */
508
+ function isPidSignalable(pid: number, d: StdioProcessDeps): boolean {
509
+ return signalPid(pid, 0, d) === "signalled";
510
+ }
511
+
485
512
  function allExited(pids: readonly number[], d: StdioProcessDeps): boolean {
486
- return pids.every((pid) => !isPidAlive(pid, d));
513
+ return pids.every((pid) => !isPidSignalable(pid, d));
487
514
  }
488
515
 
516
+ /**
517
+ * Send `signal` to the PIDs that accept it, then wait only for those to exit.
518
+ *
519
+ * Resolves `true` when nothing that could still be running is left, which is what gates the
520
+ * SIGKILL escalation. A PID that reported ESRCH is gone, and one that reported EPERM is not
521
+ * ours to wait for — but it is not assumed dead either.
522
+ */
489
523
  async function signalAndWaitForExit(
490
524
  pids: readonly number[],
491
525
  signal: NodeJS.Signals,
492
526
  timeoutMs: number,
493
527
  d: StdioProcessDeps,
494
528
  ): Promise<boolean> {
495
- const attempted = pids.map((pid) => signalPid(pid, signal, d));
496
- // Every target reported ESRCH: the tree is already gone, so there is nothing to wait for.
497
- if (!attempted.some(Boolean)) {
498
- return true;
499
- }
500
-
501
- const deadline = d.now() + timeoutMs;
502
- while (d.now() < deadline) {
503
- if (allExited(pids, d)) {
504
- return true;
529
+ const attempts = pids.map((pid) => ({ pid, outcome: signalPid(pid, signal, d) }));
530
+ const signalled = attempts.filter((a) => a.outcome === "signalled").map((a) => a.pid);
531
+ const refused = attempts.filter((a) => a.outcome === "denied").map((a) => a.pid);
532
+
533
+ // A window can only be ended by a signal that was actually delivered, so nothing is waited
534
+ // for when nothing was. (The refused targets still decide the result below.)
535
+ if (signalled.length > 0) {
536
+ const deadline = d.now() + timeoutMs;
537
+ while (d.now() < deadline && !allExited(signalled, d)) {
538
+ await d.sleep(25);
505
539
  }
506
- await d.sleep(25);
507
540
  }
508
541
 
509
- return allExited(pids, d);
542
+ // WHY: a refused signal is not proof of a dead target. Permission is mediated per signal on
543
+ // some systems — SELinux keeps separate `sigterm`/`sigkill` permissions, AppArmor matches a
544
+ // signal set, and a seccomp filter can match the signal argument — so SIGTERM can be refused
545
+ // while SIGKILL is allowed. A refused target that a liveness probe still finds signalable
546
+ // therefore keeps the tree alive and sends the caller straight to the SIGKILL escalation,
547
+ // without paying for a wait window this signal can never end; one that is no longer
548
+ // signalable is out of reach (recycled to another uid, or the child changed credentials) and
549
+ // counts as gone. ESRCH targets are never re-probed: that verdict is final, and re-probing a
550
+ // recycled PID could sign it up for a SIGKILL it has nothing to do with.
551
+ return allExited(signalled, d) && !refused.some((pid) => isPidSignalable(pid, d));
510
552
  }
511
553
 
512
554
  /**
@@ -523,9 +565,9 @@ async function escalateToSigkill(
523
565
  ): Promise<void> {
524
566
  const rescanned = await d.listDescendantPids(rootPid);
525
567
  const survivors = [...new Set([...rescanned, ...descendants])].filter((candidate) =>
526
- isPidAlive(candidate, d),
568
+ isPidSignalable(candidate, d),
527
569
  );
528
- const targets = [...survivors, rootPid].filter((candidate) => isPidAlive(candidate, d));
570
+ const targets = [...survivors, rootPid].filter((candidate) => isPidSignalable(candidate, d));
529
571
  if (targets.length === 0) return;
530
572
  await signalAndWaitForExit(targets, "SIGKILL", 200, d);
531
573
  }
@@ -535,16 +577,25 @@ export async function ensurePidTerminated(
535
577
  deps?: Partial<StdioProcessDeps>,
536
578
  ): Promise<void> {
537
579
  const d = resolveDeps(deps);
538
- if (!pid || !isPidAlive(pid, d)) {
539
- return;
540
- }
580
+ if (!pid) return;
581
+ const root = signalPid(pid, 0, d);
582
+ // WHY: ESRCH is the only verdict that says the PID is free — nothing to snapshot, nothing to
583
+ // signal. EPERM does not describe the tree: the root may be out of reach while descendants
584
+ // are ours (a privileged wrapper that dropped to our uid for the real server), so they are
585
+ // still signalled below.
586
+ if (root === "gone") return;
541
587
 
542
588
  // WHY: Snapshot before signalling any PID: a wrapper that exits first re-parents its
543
- // children to init, after which they can no longer be found by parent PID.
589
+ // children to init, after which they can no longer be found by parent PID. The snapshot runs
590
+ // even for an out-of-reach root, because that root may still own signalable descendants.
544
591
  const descendants = await d.listDescendantPids(pid);
545
- if (await signalAndWaitForExit([...descendants, pid], "SIGTERM", 500, d)) {
546
- return;
547
- }
592
+ const targets = descendants.filter((candidate) => isPidSignalable(candidate, d));
593
+ // WHY: a root nobody can signal is skipped as a target — no wait window can end it — but it
594
+ // must not hide the descendants that a signal can still reach.
595
+ if (root === "signalled") targets.push(pid);
596
+ if (targets.length === 0) return;
597
+
598
+ if (await signalAndWaitForExit(targets, "SIGTERM", 500, d)) return;
548
599
 
549
600
  await escalateToSigkill(pid, descendants, d);
550
601
  }
@@ -324,6 +324,12 @@ function normalizeRefreshArgs(
324
324
  return { isCurrent, options };
325
325
  }
326
326
 
327
+ /** True when two tool-name lists have the same length and the same entries in order. */
328
+ function sameToolList(left: readonly string[], right: readonly string[]): boolean {
329
+ if (left.length !== right.length) return false;
330
+ return left.every((name, index) => name === right[index]);
331
+ }
332
+
327
333
  // ─── Tool Listing ─────────────────────────────────────────────────────────────
328
334
 
329
335
  export { listAllTools, type McpToolDefinition } from "./tool-discovery.js";
@@ -341,6 +347,25 @@ export class ToolBridge {
341
347
  private readonly serverToolNames = new Map<string, Set<string>>();
342
348
  /** Tracks which MCP server owns each registered Pi tool name. */
343
349
  private readonly toolOwners = new Map<string, string>();
350
+ /**
351
+ * Servers whose tools this bridge has activated and not deactivated since.
352
+ * A server that is still in this set may have had individual tools removed from Pi's
353
+ * active set by another extension or a user policy, and a refresh must not undo that.
354
+ */
355
+ private readonly activeServers = new Set<string>();
356
+ /**
357
+ * Per server, whether each raw MCP tool name was active in Pi when the current connection
358
+ * stopped advertising it. A re-advertised tool is not "new", so it must come back in the
359
+ * state it left in — a tool a policy had deactivated stays inactive; one the bridge
360
+ * deactivated when the server dropped it returns active.
361
+ */
362
+ private readonly droppedToolState = new Map<string, Map<string, boolean>>();
363
+ /**
364
+ * Per server, the raw MCP tool name behind each Pi tool name in the latest snapshot, so
365
+ * tool state follows the MCP tool's identity even when a colliding sibling shifts its Pi
366
+ * name or a new tool recycles a dropped tool's Pi name.
367
+ */
368
+ private readonly rawToolNames = new Map<string, Map<string, string>>();
344
369
  /** Monotonic per-server generation counter to discard out-of-order refreshTools responses. */
345
370
  private readonly refreshGenerations = new Map<string, number>();
346
371
  /** Per-server request timeout overrides resolved during refreshTools. */
@@ -408,6 +433,11 @@ export class ToolBridge {
408
433
  /** Deactivate all Pi tools belonging to a server (called on disconnect). */
409
434
  deactivateServer(serverName: string): void {
410
435
  this._bumpRefreshGeneration(serverName);
436
+ this.activeServers.delete(serverName);
437
+ // WHY: stopping the server turns every tool off, so what each one "left in" belongs to a
438
+ // connection that no longer exists; a fresh connect rediscovers the state from scratch.
439
+ this.droppedToolState.delete(serverName);
440
+ this.rawToolNames.delete(serverName);
411
441
  this._deactivateServerTools(serverName);
412
442
  }
413
443
 
@@ -420,6 +450,9 @@ export class ToolBridge {
420
450
  removeServerTools(serverName: string): void {
421
451
  this._bumpRefreshGeneration(serverName);
422
452
  this.serverTimeouts.delete(serverName);
453
+ this.activeServers.delete(serverName);
454
+ this.droppedToolState.delete(serverName);
455
+ this.rawToolNames.delete(serverName);
423
456
  this._deactivateServerTools(serverName);
424
457
  const existing = this.serverToolNames.get(serverName);
425
458
  if (existing) {
@@ -432,11 +465,6 @@ export class ToolBridge {
432
465
  }
433
466
  }
434
467
 
435
- /** Re-activate all Pi tools belonging to a server (called on reconnect). */
436
- activateServer(serverName: string): void {
437
- this._activateServerTools(serverName);
438
- }
439
-
440
468
  // ─── Internal ───────────────────────────────────────────────────────────────
441
469
 
442
470
  /** Advance the per-server refresh generation so in-flight refreshes are discarded. */
@@ -493,14 +521,23 @@ export class ToolBridge {
493
521
  }
494
522
 
495
523
  /**
496
- * Register the freshly discovered tools, deactivate the ones the server
497
- * dropped, then activate the server's current set.
524
+ * Register the freshly discovered tools, release ownership of any Pi names the
525
+ * server no longer uses, and reconcile Pi's active tool set.
498
526
  */
499
527
  private _reconcileTools(serverName: string, tools: McpToolDefinition[], client: Client): void {
500
528
  const registeredForServer = this.serverToolNames.get(serverName) ?? new Set<string>();
529
+ const ownedPreviousNames = this._ownedTools(serverName, registeredForServer);
530
+ // WHY: Copy before calling `this._registerTool` — Pi's `registerTool()` runs
531
+ // `_refreshToolRegistry()`, which auto-activates newly registered tool names and
532
+ // `--tools` allowlist matches while the registration loop is still running.
533
+ const activeBefore = [...this.pi.getActiveTools()];
534
+ const isLiveRefresh = this.activeServers.has(serverName);
535
+ const previousStateByRawName = isLiveRefresh
536
+ ? this._snapshotActiveStateByRawName(serverName, ownedPreviousNames, new Set(activeBefore))
537
+ : undefined;
501
538
 
502
- // Build the set of currently valid Pi tool names for this server
503
539
  const currentToolNames = new Set<string>();
540
+ const currentRawNames = new Map<string, string>();
504
541
  // WHY: `tools/list` order carries no meaning (a server may reorder it freely), so colliding
505
542
  // names are assigned over a deterministic order of the tool set — otherwise the exact-match
506
543
  // tool could lose the unhashed name to a lossy one and a later refresh would swap which MCP
@@ -508,23 +545,32 @@ export class ToolBridge {
508
545
  for (const tool of orderToolsForNameAssignment(this.settings.toolPrefix, serverName, tools)) {
509
546
  const piName = this._resolveUniqueToolName(serverName, tool.name, currentToolNames);
510
547
  currentToolNames.add(piName);
548
+ currentRawNames.set(piName, tool.name);
511
549
  this.toolOwners.set(piName, serverName);
512
550
  // Always re-register — on reconnect the client reference changes and
513
551
  // Pi's registerTool overwrites by name, so this is idempotent.
514
552
  this._registerTool(piName, serverName, tool, client);
515
553
  }
516
554
 
517
- // Deactivate tools that were removed from the server (no longer in tools/list)
518
- for (const existingName of registeredForServer) {
519
- if (currentToolNames.has(existingName)) continue;
520
- this._deactivateServerTool(serverName, existingName);
521
- if (this.toolOwners.get(existingName) === serverName) {
555
+ for (const existingName of ownedPreviousNames) {
556
+ if (!currentToolNames.has(existingName)) {
522
557
  this.toolOwners.delete(existingName);
523
558
  }
524
559
  }
525
560
 
561
+ // WHY: `pi.setActiveTools` is shared with every other extension and the user, so an already
562
+ // connected server's tool set may have been narrowed on purpose. A live `tools/list_changed`
563
+ // therefore preserves each raw tool's active/inactive state (including across collision
564
+ // re-settlement and drop/re-advertisement), while a first connect or a reconnect after
565
+ // `deactivateServer` activates the whole discovered set (#214).
566
+ const desiredActive = previousStateByRawName
567
+ ? this._resolveLiveDesiredActive(serverName, currentRawNames, previousStateByRawName)
568
+ : currentToolNames;
569
+
526
570
  this.serverToolNames.set(serverName, currentToolNames);
527
- this._activateServerTools(serverName);
571
+ this.rawToolNames.set(serverName, currentRawNames);
572
+ this.activeServers.add(serverName);
573
+ this._reconcileActiveTools(ownedPreviousNames, desiredActive, activeBefore);
528
574
  }
529
575
 
530
576
  private _isToolNameTaken(name: string, serverName: string, seenInBatch: ReadonlySet<string>): boolean {
@@ -666,39 +712,122 @@ export class ToolBridge {
666
712
  return { content, details: {} };
667
713
  }
668
714
 
669
- private _activateServerTools(serverName: string): void {
670
- const serverTools = this.serverToolNames.get(serverName);
671
- if (!serverTools || serverTools.size === 0) return;
715
+ /** Filter a set of Pi tool names to those still owned by `serverName`. */
716
+ private _ownedTools(serverName: string, toolNames: ReadonlySet<string>): Set<string> {
717
+ const owned = new Set<string>();
718
+ for (const toolName of toolNames) {
719
+ const owner = this.toolOwners.get(toolName);
720
+ if (owner === undefined || owner === serverName) {
721
+ owned.add(toolName);
722
+ }
723
+ }
724
+ return owned;
725
+ }
672
726
 
673
- const currentActive = new Set(this.pi.getActiveTools());
674
- for (const name of serverTools) currentActive.add(name);
675
- this.pi.setActiveTools(Array.from(currentActive));
727
+ /**
728
+ * Map each raw MCP tool name from the previous snapshot to whether Pi currently has
729
+ * its assigned tool name active.
730
+ */
731
+ private _snapshotActiveStateByRawName(
732
+ serverName: string,
733
+ ownedPreviousNames: ReadonlySet<string>,
734
+ activeBefore: ReadonlySet<string>,
735
+ ): Map<string, boolean> {
736
+ const rawNamesBefore = this.rawToolNames.get(serverName);
737
+ const stateByRawName = new Map<string, boolean>();
738
+ for (const piName of ownedPreviousNames) {
739
+ const rawName = rawNamesBefore?.get(piName) ?? piName;
740
+ stateByRawName.set(rawName, activeBefore.has(piName));
741
+ }
742
+ return stateByRawName;
676
743
  }
677
744
 
678
- private _deactivateServerTools(serverName: string): void {
679
- const serverTools = this.serverToolNames.get(serverName);
680
- if (!serverTools || serverTools.size === 0) return;
745
+ /**
746
+ * Compute which Pi tool names in `currentRawNames` should be active after a live refresh,
747
+ * and update the server's dropped-tool memory.
748
+ *
749
+ * A tool present in the previous snapshot keeps the active/inactive state Pi currently
750
+ * reports for it (even if a colliding sibling shifted its Pi name). A tool absent from the
751
+ * previous snapshot restores the state it left in when dropped on this connection, or
752
+ * activates as newly discovered.
753
+ */
754
+ private _resolveLiveDesiredActive(
755
+ serverName: string,
756
+ currentRawNames: ReadonlyMap<string, string>,
757
+ previousStateByRawName: ReadonlyMap<string, boolean>,
758
+ ): Set<string> {
759
+ const dropped = this.droppedToolState.get(serverName);
760
+ const desiredActive = new Set<string>();
761
+ const seenRawNames = new Set<string>();
762
+ for (const [piName, rawName] of currentRawNames) {
763
+ seenRawNames.add(rawName);
764
+ const shouldActivate =
765
+ previousStateByRawName.get(rawName) ?? dropped?.get(rawName) ?? true;
766
+ if (shouldActivate) {
767
+ desiredActive.add(piName);
768
+ }
769
+ }
770
+ this._updateDroppedTools(serverName, previousStateByRawName, seenRawNames);
771
+ return desiredActive;
772
+ }
681
773
 
682
- const ownedByServer = new Set<string>();
683
- for (const toolName of serverTools) {
684
- const owner = this.toolOwners.get(toolName);
685
- if (owner !== undefined && owner !== serverName) continue;
686
- ownedByServer.add(toolName);
774
+ /**
775
+ * Record the active state of tools dropped in this live refresh and forget tools that are
776
+ * currently advertised.
777
+ */
778
+ private _updateDroppedTools(
779
+ serverName: string,
780
+ previousStateByRawName: ReadonlyMap<string, boolean>,
781
+ currentRawNames: ReadonlySet<string>,
782
+ ): void {
783
+ const dropped = this.droppedToolState.get(serverName) ?? new Map<string, boolean>();
784
+ for (const [rawName, wasActive] of previousStateByRawName) {
785
+ if (!currentRawNames.has(rawName)) {
786
+ dropped.set(rawName, wasActive);
787
+ }
687
788
  }
688
- if (ownedByServer.size === 0) return;
789
+ for (const rawName of currentRawNames) {
790
+ dropped.delete(rawName);
791
+ }
792
+ if (dropped.size > 0) {
793
+ this.droppedToolState.set(serverName, dropped);
794
+ } else {
795
+ this.droppedToolState.delete(serverName);
796
+ }
797
+ }
798
+
799
+ /**
800
+ * Reconcile a server's active tools in Pi in one write: drop any previously owned Pi tool
801
+ * names that are not in `desiredActive`, append any `desiredActive` names not yet active,
802
+ * and skip `pi.setActiveTools` altogether when the active set is unchanged.
803
+ */
804
+ private _reconcileActiveTools(
805
+ ownedPreviousNames: ReadonlySet<string>,
806
+ desiredActive: ReadonlySet<string>,
807
+ activeBefore: readonly string[],
808
+ ): void {
809
+ const activeSet = new Set(activeBefore);
810
+ const remaining = activeBefore.filter(
811
+ (name) => !ownedPreviousNames.has(name) || desiredActive.has(name),
812
+ );
813
+ const newlyActive = [...desiredActive].filter((name) => !activeSet.has(name));
814
+ const unchangedBeforeLoop =
815
+ remaining.length === activeBefore.length && newlyActive.length === 0;
816
+ // WHY: Even when `desiredActive` leaves `activeBefore` unchanged, `pi.registerTool()`
817
+ // inside the loop may have auto-activated a newly registered hashed Pi name or a
818
+ // `--tools` allowlist entry; re-read `getActiveTools()` before skipping the write.
819
+ if (unchangedBeforeLoop && sameToolList(this.pi.getActiveTools(), activeBefore)) return;
689
820
 
690
- const currentActive = this.pi.getActiveTools();
691
- const remaining = currentActive.filter((n) => !ownedByServer.has(n));
692
- this.pi.setActiveTools(remaining);
821
+ this.pi.setActiveTools(Array.from(new Set([...remaining, ...newlyActive])));
693
822
  }
694
823
 
695
- /** Deactivate a single tool by Pi name (used when a tool is removed on list_changed). */
696
- private _deactivateServerTool(serverName: string, piName: string): void {
697
- const owner = this.toolOwners.get(piName);
698
- if (owner !== undefined && owner !== serverName) return;
824
+ private _deactivateServerTools(serverName: string): void {
825
+ const serverTools = this.serverToolNames.get(serverName);
826
+ if (!serverTools || serverTools.size === 0) return;
827
+
828
+ const ownedByServer = this._ownedTools(serverName, serverTools);
829
+ if (ownedByServer.size === 0) return;
699
830
 
700
- const currentActive = this.pi.getActiveTools();
701
- const remaining = currentActive.filter((n) => n !== piName);
702
- this.pi.setActiveTools(remaining);
831
+ this._reconcileActiveTools(ownedByServer, new Set(), this.pi.getActiveTools());
703
832
  }
704
833
  }