pi-mcp-extension 1.14.4 → 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:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mcp-extension",
3
- "version": "1.14.4",
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": [
@@ -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
  }