pi-mcp-extension 1.14.4 → 1.14.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
@@ -25,6 +25,7 @@
25
25
  - **Health checks** — Opt-in periodic pings to detect stale connections
26
26
  - **Safe process lifecycle** — Child PID tracking with tree-aware cleanup: descendants of wrapper commands (`npx`, `npm exec`, `uvx`, `sh -c`) are terminated too, and inherited pipes are released so teardown never stalls
27
27
  - **Stable tool names** — Sanitized, collision-avoiding names (`<prefix>_<server>_<tool>`, max 64 chars) that stay constant across reconnects, including when one server exposes two tools that sanitize to the same identifier: the name that needs no substitution keeps the unhashed form (`my_tool` wins over `my-tool`), remaining ties break by raw-name order, and the names that server's tools get never depend on `tools/list` order
28
+ - **Stable tool order** — Active MCP tools keep one deterministic order across session starts, `/tree` navigation, and idle or mid-turn `setActiveTools` updates (including `tool_search`): each active owned tool is sorted by Pi name among the slots it occupies, inactive tools stay off, and other extensions' tools never move. The same order is applied to outgoing provider tool declarations (top-level `tools`, AWS Bedrock Converse `toolConfig.tools`, Google/Vertex `config.tools[].functionDeclarations`, and `pi-messages` `context.messages[].toolsAdded`), which Pi otherwise rebuilds from the transcript's first-appearance order, so the system prompt's tool section and the tools this extension declares stay identical across session starts whatever order the eager servers connected in or the servers list their tools in — keeping a server-side prefix cache warm. A server that connects after an earlier turn is announced on that later turn through the provider's mid-conversation tool-addition channel, which cannot move back into earlier turns
28
29
  - **No tool churn** — Activate/deactivate pattern ensures tools don't flicker during reconnection
29
30
  - **Layered config & trust boundary** — Global `<agent dir>/mcp.json`, project `.pi/mcp.json` (loaded only in trusted projects, including Pi 1.3.0 partial overrides), and Pi 1.x extension-registered servers (`pi.registerMcpServer()`)
30
31
  - **Rich tool results & annotations** — MCP `text`, `image` (`ImageContent`), `structuredContent`, embedded `resource` text/images/binary blobs, `resource_link` hints, and `audio` fallback descriptions, plus `readOnlyHint`, `destructiveHint`, `idempotentHint`, and `openWorldHint` surfaced in tool descriptions and passed to Pi as structured tool `annotations` (boolean hints only), so permission extensions can inspect them
@@ -309,6 +310,8 @@ Recent output:
309
310
 
310
311
  `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
312
 
313
+ 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.
314
+
312
315
  ## Debug log
313
316
 
314
317
  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:
@@ -374,7 +377,7 @@ flowchart TD
374
377
  3. **Tools are discovered** via paginated `tools/list` calls (cursor-based, up to 100 pages) before a server enters `ready`
375
378
  4. **JSON Schema → TypeBox** conversion registers tools with Pi-compatible parameter schemas (preserving nullable union ordering, resolving `$ref`s cycle-safely, and inferring/flattening `allOf` object schemas)
376
379
  5. **Pi tools are registered** as `<prefix>_<server>_<tool>` (sanitized `[a-zA-Z0-9_]`, max 64 chars with an 8-char SHA-256 suffix on truncation or collision) and convert MCP `text`, `image` (`ImageContent`), `structuredContent`, `resource`, `resource_link`, and `audio` results. When one server exposes two tools that sanitize to the same identifier, the name that needed no substitution keeps the unhashed form (`my_tool` over `my-tool`), remaining ties break by the raw name's code-point order, and the assignment does not depend on `tools/list` order — so a reconnect cannot swap which MCP tool a Pi name executes. Embedded image resources become image blocks, binary resources include MIME type and byte count, and resource links include a `mcp_read_resource` hint.
377
- 6. **Tools activate/deactivate** automatically as servers connect/disconnect
380
+ 6. **Tools activate/deactivate** automatically as servers connect/disconnect, always in one deterministic order — the bridge's tools are sorted by Pi name among the slots they occupy, and other extensions' tools keep their positions — so connect timing and `tools/list` order cannot change the prompt head
378
381
  7. **AbortSignal** is wired through to `notifications/cancelled` for clean cancellation
379
382
  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
383
  9. **`list_changed` notifications** trigger re-discovery, deactivating stale tools automatically and invalidating the cached resource catalog
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.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": [
package/src/index.ts CHANGED
@@ -403,6 +403,19 @@ export default async function (pi: ExtensionAPI, paths: { bootstrapCwd?: string;
403
403
  return enqueueServerReconcile(ctx);
404
404
  });
405
405
 
406
+ // Keep active and outgoing tool order independent of connect timing, `/tree` transcript
407
+ // restoration, idle/mid-turn external `setActiveTools` reorderings (e.g. `tool_search` before
408
+ // continuation `sections.tools`, or idle shortcuts before `before_agent_start` snapshots
409
+ // `systemPromptOptions`), and first-appearance transcript replay (#278).
410
+ const normalizeActiveTools = (): void => {
411
+ bridge.orderActiveTools();
412
+ };
413
+ pi.on("session_tree", normalizeActiveTools);
414
+ pi.on("input", normalizeActiveTools);
415
+ pi.on("before_agent_start", normalizeActiveTools);
416
+ pi.on("tool_execution_end", normalizeActiveTools);
417
+ pi.on("before_provider_request", (event) => bridge.orderPayloadTools(event.payload));
418
+
406
419
  pi.on("session_shutdown", async (_event, ctx: ExtensionContext) => {
407
420
  // WHY: invalidate before tearing down so an in-flight startup or queued reconcile
408
421
  // observes a dead session and bails, then drain both after teardown so shutdown never
@@ -22,6 +22,12 @@ import { isCancellationError, isOAuthUnauthorizedError, isSdkTimeoutError } from
22
22
  import { convertJsonSchemaToTypebox } from "./schema-convert.js";
23
23
  import { listAllTools, type McpToolDefinition } from "./tool-discovery.js";
24
24
  import { convertResourceContent } from "./resource-bridge.js";
25
+ import {
26
+ compareCodePoints,
27
+ orderOwnedEntries,
28
+ orderPayloadToolEntries,
29
+ sameToolList,
30
+ } from "./tool-order.js";
25
31
 
26
32
  // ─── Types ────────────────────────────────────────────────────────────────────
27
33
 
@@ -70,18 +76,6 @@ function isLosslessToolName(rawToolName: string): boolean {
70
76
  return /^[a-zA-Z0-9_]+$/.test(rawToolName);
71
77
  }
72
78
 
73
- /** Compare strings by Unicode code point, not by UTF-16 code unit. */
74
- function compareCodePoints(a: string, b: string): number {
75
- const left = Array.from(a, (ch) => ch.codePointAt(0) ?? 0);
76
- const right = Array.from(b, (ch) => ch.codePointAt(0) ?? 0);
77
- const shared = Math.min(left.length, right.length);
78
- for (let i = 0; i < shared; i++) {
79
- const diff = (left[i] ?? 0) - (right[i] ?? 0);
80
- if (diff !== 0) return diff;
81
- }
82
- return left.length - right.length;
83
- }
84
-
85
79
  /**
86
80
  * Order a server's tools so Pi-name assignment depends only on the tool set and never on
87
81
  * the order `tools/list` happened to return (#213): a lossless raw name wins the unhashed
@@ -99,10 +93,10 @@ function compareToolsForNameAssignment(a: McpToolDefinition, b: McpToolDefinitio
99
93
 
100
94
  /**
101
95
  * Order a server's tools for Pi-name assignment. The server's own `tools/list` order is kept —
102
- * so registration order, and the tool order Pi shows the model, only move where they must —
103
- * except that tools competing for the same unhashed identifier are emitted as one deterministic
104
- * group in the position of the group's first member. Which tool the server listed first is not
105
- * part of the MCP contract, so it must not decide who wins that identifier (#213).
96
+ * so registration order only moves where it must — except that tools competing for the same
97
+ * unhashed identifier are emitted as one deterministic group in the position of the group's
98
+ * first member. Which tool the server listed first is not part of the MCP contract, so it must
99
+ * not decide who wins that identifier (#213).
106
100
  */
107
101
  function orderToolsForNameAssignment(
108
102
  prefix: string,
@@ -341,6 +335,25 @@ export class ToolBridge {
341
335
  private readonly serverToolNames = new Map<string, Set<string>>();
342
336
  /** Tracks which MCP server owns each registered Pi tool name. */
343
337
  private readonly toolOwners = new Map<string, string>();
338
+ /**
339
+ * Servers whose tools this bridge has activated and not deactivated since.
340
+ * A server that is still in this set may have had individual tools removed from Pi's
341
+ * active set by another extension or a user policy, and a refresh must not undo that.
342
+ */
343
+ private readonly activeServers = new Set<string>();
344
+ /**
345
+ * Per server, whether each raw MCP tool name was active in Pi when the current connection
346
+ * stopped advertising it. A re-advertised tool is not "new", so it must come back in the
347
+ * state it left in — a tool a policy had deactivated stays inactive; one the bridge
348
+ * deactivated when the server dropped it returns active.
349
+ */
350
+ private readonly droppedToolState = new Map<string, Map<string, boolean>>();
351
+ /**
352
+ * Per server, the raw MCP tool name behind each Pi tool name in the latest snapshot, so
353
+ * tool state follows the MCP tool's identity even when a colliding sibling shifts its Pi
354
+ * name or a new tool recycles a dropped tool's Pi name.
355
+ */
356
+ private readonly rawToolNames = new Map<string, Map<string, string>>();
344
357
  /** Monotonic per-server generation counter to discard out-of-order refreshTools responses. */
345
358
  private readonly refreshGenerations = new Map<string, number>();
346
359
  /** Per-server request timeout overrides resolved during refreshTools. */
@@ -405,9 +418,55 @@ export class ToolBridge {
405
418
  return { discovered: names.size, active: [...names].filter((name) => active.has(name)).length };
406
419
  }
407
420
 
421
+ /**
422
+ * Re-apply this bridge's deterministic tool order to Pi's active list when owned tools have
423
+ * been reordered externally, and do nothing when already ordered.
424
+ *
425
+ * WHY: `/tree` navigation (`session_tree`) restores active tools from the transcript's
426
+ * first-appearance order without re-running `refreshTools`, and another extension or tool
427
+ * (e.g. `tool_search`) may call `pi.setActiveTools` idle or mid-turn; re-normalizing on
428
+ * `session_tree`, `input`, `before_agent_start`, and `tool_execution_end` keeps `sections.tools`
429
+ * in the system prompt aligned with `orderPayloadTools` without re-activating inactive tools (#278).
430
+ */
431
+ orderActiveTools(): void {
432
+ const current = this.pi.getActiveTools();
433
+ const ordered = orderOwnedEntries(
434
+ current,
435
+ (name) => name,
436
+ (name) => this.toolOwners.has(name),
437
+ );
438
+ if (ordered === undefined) return;
439
+ this.pi.setActiveTools(ordered);
440
+ }
441
+
442
+ /**
443
+ * Order this bridge's tools in an outgoing provider payload the same way they are ordered in
444
+ * Pi's active list — across top-level `tools` (Anthropic, OpenAI Chat Completions & Responses,
445
+ * Mistral), AWS Bedrock Converse `toolConfig.tools`, Google/Vertex
446
+ * `config.tools[].functionDeclarations`, and `pi-messages` `context.messages[].toolsAdded` —
447
+ * and return the payload untouched when they already are. Only entries this bridge owns move,
448
+ * and only among the slots they already occupy: another extension's tool and Pi's reserved
449
+ * trailing declarations (`__pi_deferred_placeholder__`, `cachePoint`, non-function Gemini tool
450
+ * groups, non-system messages) keep their positions.
451
+ *
452
+ * WHY: request tool arrays are not built from the active list — Pi replays the transcript's
453
+ * tool declarations in first-appearance order and emits no delta for a pure reorder, so a
454
+ * server that connects after the first turn leaves its tools at the end, in connect order.
455
+ * Sorting the payload makes the declared tools a function of the tool set, so the prompt head
456
+ * stays stable across sessions and a server-side prefix cache keeps its KV entries (#278).
457
+ */
458
+ orderPayloadTools(payload: unknown): unknown {
459
+ return orderPayloadToolEntries(payload, (name) => this.toolOwners.has(name));
460
+ }
461
+
408
462
  /** Deactivate all Pi tools belonging to a server (called on disconnect). */
409
463
  deactivateServer(serverName: string): void {
410
464
  this._bumpRefreshGeneration(serverName);
465
+ this.activeServers.delete(serverName);
466
+ // WHY: stopping the server turns every tool off, so what each one "left in" belongs to a
467
+ // connection that no longer exists; a fresh connect rediscovers the state from scratch.
468
+ this.droppedToolState.delete(serverName);
469
+ this.rawToolNames.delete(serverName);
411
470
  this._deactivateServerTools(serverName);
412
471
  }
413
472
 
@@ -420,6 +479,9 @@ export class ToolBridge {
420
479
  removeServerTools(serverName: string): void {
421
480
  this._bumpRefreshGeneration(serverName);
422
481
  this.serverTimeouts.delete(serverName);
482
+ this.activeServers.delete(serverName);
483
+ this.droppedToolState.delete(serverName);
484
+ this.rawToolNames.delete(serverName);
423
485
  this._deactivateServerTools(serverName);
424
486
  const existing = this.serverToolNames.get(serverName);
425
487
  if (existing) {
@@ -432,11 +494,6 @@ export class ToolBridge {
432
494
  }
433
495
  }
434
496
 
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
497
  // ─── Internal ───────────────────────────────────────────────────────────────
441
498
 
442
499
  /** Advance the per-server refresh generation so in-flight refreshes are discarded. */
@@ -493,14 +550,23 @@ export class ToolBridge {
493
550
  }
494
551
 
495
552
  /**
496
- * Register the freshly discovered tools, deactivate the ones the server
497
- * dropped, then activate the server's current set.
553
+ * Register the freshly discovered tools, release ownership of any Pi names the
554
+ * server no longer uses, and reconcile Pi's active tool set.
498
555
  */
499
556
  private _reconcileTools(serverName: string, tools: McpToolDefinition[], client: Client): void {
500
557
  const registeredForServer = this.serverToolNames.get(serverName) ?? new Set<string>();
558
+ const ownedPreviousNames = this._ownedTools(serverName, registeredForServer);
559
+ // WHY: Copy before calling `this._registerTool` — Pi's `registerTool()` runs
560
+ // `_refreshToolRegistry()`, which auto-activates newly registered tool names and
561
+ // `--tools` allowlist matches while the registration loop is still running.
562
+ const activeBefore = [...this.pi.getActiveTools()];
563
+ const isLiveRefresh = this.activeServers.has(serverName);
564
+ const previousStateByRawName = isLiveRefresh
565
+ ? this._snapshotActiveStateByRawName(serverName, ownedPreviousNames, new Set(activeBefore))
566
+ : undefined;
501
567
 
502
- // Build the set of currently valid Pi tool names for this server
503
568
  const currentToolNames = new Set<string>();
569
+ const currentRawNames = new Map<string, string>();
504
570
  // WHY: `tools/list` order carries no meaning (a server may reorder it freely), so colliding
505
571
  // names are assigned over a deterministic order of the tool set — otherwise the exact-match
506
572
  // tool could lose the unhashed name to a lossy one and a later refresh would swap which MCP
@@ -508,23 +574,32 @@ export class ToolBridge {
508
574
  for (const tool of orderToolsForNameAssignment(this.settings.toolPrefix, serverName, tools)) {
509
575
  const piName = this._resolveUniqueToolName(serverName, tool.name, currentToolNames);
510
576
  currentToolNames.add(piName);
577
+ currentRawNames.set(piName, tool.name);
511
578
  this.toolOwners.set(piName, serverName);
512
579
  // Always re-register — on reconnect the client reference changes and
513
580
  // Pi's registerTool overwrites by name, so this is idempotent.
514
581
  this._registerTool(piName, serverName, tool, client);
515
582
  }
516
583
 
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) {
584
+ for (const existingName of ownedPreviousNames) {
585
+ if (!currentToolNames.has(existingName)) {
522
586
  this.toolOwners.delete(existingName);
523
587
  }
524
588
  }
525
589
 
590
+ // WHY: `pi.setActiveTools` is shared with every other extension and the user, so an already
591
+ // connected server's tool set may have been narrowed on purpose. A live `tools/list_changed`
592
+ // therefore preserves each raw tool's active/inactive state (including across collision
593
+ // re-settlement and drop/re-advertisement), while a first connect or a reconnect after
594
+ // `deactivateServer` activates the whole discovered set (#214).
595
+ const desiredActive = previousStateByRawName
596
+ ? this._resolveLiveDesiredActive(serverName, currentRawNames, previousStateByRawName)
597
+ : currentToolNames;
598
+
526
599
  this.serverToolNames.set(serverName, currentToolNames);
527
- this._activateServerTools(serverName);
600
+ this.rawToolNames.set(serverName, currentRawNames);
601
+ this.activeServers.add(serverName);
602
+ this._reconcileActiveTools(ownedPreviousNames, desiredActive, activeBefore);
528
603
  }
529
604
 
530
605
  private _isToolNameTaken(name: string, serverName: string, seenInBatch: ReadonlySet<string>): boolean {
@@ -666,39 +741,139 @@ export class ToolBridge {
666
741
  return { content, details: {} };
667
742
  }
668
743
 
669
- private _activateServerTools(serverName: string): void {
670
- const serverTools = this.serverToolNames.get(serverName);
671
- if (!serverTools || serverTools.size === 0) return;
744
+ /** Filter a set of Pi tool names to those still owned by `serverName`. */
745
+ private _ownedTools(serverName: string, toolNames: ReadonlySet<string>): Set<string> {
746
+ const owned = new Set<string>();
747
+ for (const toolName of toolNames) {
748
+ const owner = this.toolOwners.get(toolName);
749
+ if (owner === undefined || owner === serverName) {
750
+ owned.add(toolName);
751
+ }
752
+ }
753
+ return owned;
754
+ }
672
755
 
673
- const currentActive = new Set(this.pi.getActiveTools());
674
- for (const name of serverTools) currentActive.add(name);
675
- this.pi.setActiveTools(Array.from(currentActive));
756
+ /**
757
+ * Map each raw MCP tool name from the previous snapshot to whether Pi currently has
758
+ * its assigned tool name active.
759
+ */
760
+ private _snapshotActiveStateByRawName(
761
+ serverName: string,
762
+ ownedPreviousNames: ReadonlySet<string>,
763
+ activeBefore: ReadonlySet<string>,
764
+ ): Map<string, boolean> {
765
+ const rawNamesBefore = this.rawToolNames.get(serverName);
766
+ const stateByRawName = new Map<string, boolean>();
767
+ for (const piName of ownedPreviousNames) {
768
+ const rawName = rawNamesBefore?.get(piName) ?? piName;
769
+ stateByRawName.set(rawName, activeBefore.has(piName));
770
+ }
771
+ return stateByRawName;
676
772
  }
677
773
 
678
- private _deactivateServerTools(serverName: string): void {
679
- const serverTools = this.serverToolNames.get(serverName);
680
- if (!serverTools || serverTools.size === 0) return;
774
+ /**
775
+ * Compute which Pi tool names in `currentRawNames` should be active after a live refresh,
776
+ * and update the server's dropped-tool memory.
777
+ *
778
+ * A tool present in the previous snapshot keeps the active/inactive state Pi currently
779
+ * reports for it (even if a colliding sibling shifted its Pi name). A tool absent from the
780
+ * previous snapshot restores the state it left in when dropped on this connection, or
781
+ * activates as newly discovered.
782
+ */
783
+ private _resolveLiveDesiredActive(
784
+ serverName: string,
785
+ currentRawNames: ReadonlyMap<string, string>,
786
+ previousStateByRawName: ReadonlyMap<string, boolean>,
787
+ ): Set<string> {
788
+ const dropped = this.droppedToolState.get(serverName);
789
+ const desiredActive = new Set<string>();
790
+ const seenRawNames = new Set<string>();
791
+ for (const [piName, rawName] of currentRawNames) {
792
+ seenRawNames.add(rawName);
793
+ const shouldActivate =
794
+ previousStateByRawName.get(rawName) ?? dropped?.get(rawName) ?? true;
795
+ if (shouldActivate) {
796
+ desiredActive.add(piName);
797
+ }
798
+ }
799
+ this._updateDroppedTools(serverName, previousStateByRawName, seenRawNames);
800
+ return desiredActive;
801
+ }
681
802
 
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);
803
+ /**
804
+ * Record the active state of tools dropped in this live refresh and forget tools that are
805
+ * currently advertised.
806
+ */
807
+ private _updateDroppedTools(
808
+ serverName: string,
809
+ previousStateByRawName: ReadonlyMap<string, boolean>,
810
+ currentRawNames: ReadonlySet<string>,
811
+ ): void {
812
+ const dropped = this.droppedToolState.get(serverName) ?? new Map<string, boolean>();
813
+ for (const [rawName, wasActive] of previousStateByRawName) {
814
+ if (!currentRawNames.has(rawName)) {
815
+ dropped.set(rawName, wasActive);
816
+ }
687
817
  }
688
- if (ownedByServer.size === 0) return;
818
+ for (const rawName of currentRawNames) {
819
+ dropped.delete(rawName);
820
+ }
821
+ if (dropped.size > 0) {
822
+ this.droppedToolState.set(serverName, dropped);
823
+ } else {
824
+ this.droppedToolState.delete(serverName);
825
+ }
826
+ }
827
+
828
+ /**
829
+ * Reconcile a server's active tools in Pi in one write: drop any previously owned Pi tool
830
+ * names that are not in `desiredActive`, append any `desiredActive` names not yet active,
831
+ * order the result, and skip `pi.setActiveTools` altogether when the active list already
832
+ * holds exactly that set in that order.
833
+ */
834
+ private _reconcileActiveTools(
835
+ ownedPreviousNames: ReadonlySet<string>,
836
+ desiredActive: ReadonlySet<string>,
837
+ activeBefore: readonly string[],
838
+ ): void {
839
+ const activeSet = new Set(activeBefore);
840
+ const remaining = activeBefore.filter(
841
+ (name) => !ownedPreviousNames.has(name) || desiredActive.has(name),
842
+ );
843
+ const newlyActive = [...desiredActive].filter((name) => !activeSet.has(name));
844
+ const nextActive = this._orderActiveTools(new Set([...remaining, ...newlyActive]));
845
+ // WHY: `pi.registerTool()` inside the loop may have auto-activated a newly registered hashed
846
+ // Pi name or a `--tools` allowlist entry, and a resumed session restores the order it ended
847
+ // with — so compare against a fresh read and write whenever the set *or* the order differs.
848
+ if (sameToolList(this.pi.getActiveTools(), nextActive)) return;
849
+
850
+ this.pi.setActiveTools(nextActive);
851
+ }
689
852
 
690
- const currentActive = this.pi.getActiveTools();
691
- const remaining = currentActive.filter((n) => !ownedByServer.has(n));
692
- this.pi.setActiveTools(remaining);
853
+ /**
854
+ * Order the active set so this bridge's tools are a pure function of the tool set: they are
855
+ * sorted by Pi name among the positions they already occupy, while every entry another
856
+ * extension owns keeps its position.
857
+ *
858
+ * WHY: a server's tools are registered as its connection completes, and `desiredActive`
859
+ * follows `tools/list` order, which the MCP spec does not define. Without a fixed order the
860
+ * active list — and with it the system prompt's tool section and the tools declared to the
861
+ * provider — depends on eager-connect timing, so a server-side prefix cache keyed on the
862
+ * prompt head misses on every session start or resume (#278).
863
+ */
864
+ private _orderActiveTools(active: ReadonlySet<string>): string[] {
865
+ const names = [...active];
866
+ const ordered = orderOwnedEntries(names, (name) => name, (name) => this.toolOwners.has(name));
867
+ return ordered ?? names;
693
868
  }
694
869
 
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;
870
+ private _deactivateServerTools(serverName: string): void {
871
+ const serverTools = this.serverToolNames.get(serverName);
872
+ if (!serverTools || serverTools.size === 0) return;
873
+
874
+ const ownedByServer = this._ownedTools(serverName, serverTools);
875
+ if (ownedByServer.size === 0) return;
699
876
 
700
- const currentActive = this.pi.getActiveTools();
701
- const remaining = currentActive.filter((n) => n !== piName);
702
- this.pi.setActiveTools(remaining);
877
+ this._reconcileActiveTools(ownedByServer, new Set(), this.pi.getActiveTools());
703
878
  }
704
879
  }
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Pure deterministic tool-ordering policy and provider-payload transforms (#278).
3
+ *
4
+ * Keeps MCP tool positions in Pi's active list and in outgoing provider requests a pure
5
+ * function of the tool set — independent of eager-connect timing, `tools/list` order,
6
+ * `/tree` transcript restoration, mid-turn `setActiveTools` calls, and first-appearance
7
+ * transcript replay — while leaving non-owned tools and provider-specific markers in place.
8
+ */
9
+
10
+ function isRecord(value: unknown): value is Record<string, unknown> {
11
+ return typeof value === "object" && value !== null && !Array.isArray(value);
12
+ }
13
+
14
+ /** True when two tool-name lists have the same length and the same entries in order. */
15
+ export function sameToolList(left: readonly string[], right: readonly string[]): boolean {
16
+ if (left.length !== right.length) return false;
17
+ return left.every((name, index) => name === right[index]);
18
+ }
19
+
20
+ /** Compare strings by Unicode code point, not by UTF-16 code unit. */
21
+ export function compareCodePoints(a: string, b: string): number {
22
+ const left = Array.from(a, (ch) => ch.codePointAt(0) ?? 0);
23
+ const right = Array.from(b, (ch) => ch.codePointAt(0) ?? 0);
24
+ const shared = Math.min(left.length, right.length);
25
+ for (let i = 0; i < shared; i++) {
26
+ const diff = (left[i] ?? 0) - (right[i] ?? 0);
27
+ if (diff !== 0) return diff;
28
+ }
29
+ return left.length - right.length;
30
+ }
31
+
32
+ /**
33
+ * Sort the entries `isOwned` selects into name order inside the slots they already occupy, and
34
+ * return `undefined` when the result is identical to `entries`.
35
+ *
36
+ * WHY: this bridge cannot move what it does not own — another extension's tools keep the position
37
+ * they were given, and so does Pi's trailing Anthropic `__pi_deferred_placeholder__`, which Pi
38
+ * requires last — while the bridge's own tools, whose insertion order depends on which server
39
+ * connected first and on `tools/list` order, end up in one deterministic order (#278).
40
+ */
41
+ export function orderOwnedEntries<T>(
42
+ entries: readonly T[],
43
+ nameOf: (entry: T) => string | undefined,
44
+ isOwned: (name: string) => boolean,
45
+ ): T[] | undefined {
46
+ const owned: Array<{ slot: number; name: string; entry: T }> = [];
47
+ entries.forEach((entry, slot) => {
48
+ const name = nameOf(entry);
49
+ if (name !== undefined && isOwned(name)) owned.push({ slot, name, entry });
50
+ });
51
+ if (owned.length < 2) return undefined;
52
+
53
+ const slots = owned.map((candidate) => candidate.slot);
54
+ owned.sort((left, right) => compareCodePoints(left.name, right.name));
55
+ const ordered = [...entries];
56
+ owned.forEach((candidate, index) => {
57
+ const slot = slots[index];
58
+ if (slot === undefined) return;
59
+ ordered[slot] = candidate.entry;
60
+ });
61
+ const unchanged = ordered.every((entry, index) => entry === entries[index]);
62
+ return unchanged ? undefined : ordered;
63
+ }
64
+
65
+ function nestedStringField(
66
+ record: Record<string, unknown>,
67
+ key: string,
68
+ field: string,
69
+ ): string | undefined {
70
+ const nested = record[key];
71
+ if (!isRecord(nested)) return undefined;
72
+ const value = nested[field];
73
+ return typeof value === "string" ? value : undefined;
74
+ }
75
+
76
+ /**
77
+ * Name of a provider tool definition: `{ name }` (Anthropic, OpenAI/Azure/Codex Responses,
78
+ * Gemini `functionDeclarations`, `pi-messages` `toolsAdded`), `{ function: { name } }`
79
+ * (OpenAI Chat Completions, Mistral), or `{ toolSpec: { name } }` (AWS Bedrock Converse).
80
+ */
81
+ function payloadToolName(definition: unknown): string | undefined {
82
+ if (!isRecord(definition)) return undefined;
83
+ const name = definition["name"];
84
+ if (typeof name === "string") return name;
85
+ return (
86
+ nestedStringField(definition, "function", "name") ??
87
+ nestedStringField(definition, "toolSpec", "name")
88
+ );
89
+ }
90
+
91
+ /**
92
+ * Keep a slot's `cache_control` breakpoint on that slot when another tool definition moves into
93
+ * it: Pi's Anthropic and OpenAI-completions adapters attach `cache_control` to the last tool
94
+ * slot before `before_provider_request` runs, so moving that object earlier would strand later
95
+ * tools outside the cached prefix and diverge from a session that started in sorted order.
96
+ */
97
+ function withSlotCacheControl(entry: unknown, slotEntry: unknown): unknown {
98
+ const entryRecord = entry as Record<string, unknown>;
99
+ const slotCache = (slotEntry as { cache_control?: unknown }).cache_control;
100
+ if (entryRecord["cache_control"] === slotCache) return entry;
101
+ if (slotCache === undefined) {
102
+ const { cache_control: _dropped, ...rest } = entryRecord;
103
+ return rest;
104
+ }
105
+ return { ...entryRecord, cache_control: slotCache };
106
+ }
107
+
108
+ /** Order one tool-definition array in place of its owned slots, keeping slot `cache_control`. */
109
+ function orderDefinitionList(
110
+ definitions: unknown,
111
+ isOwned: (name: string) => boolean,
112
+ ): unknown[] | undefined {
113
+ if (!Array.isArray(definitions) || definitions.length === 0) return undefined;
114
+ const ordered = orderOwnedEntries(definitions, payloadToolName, isOwned);
115
+ if (ordered === undefined) return undefined;
116
+ return ordered.map((entry, index) =>
117
+ entry === definitions[index] ? entry : withSlotCacheControl(entry, definitions[index]),
118
+ );
119
+ }
120
+
121
+ /** Order one Gemini `Tool` entry's `functionDeclarations` array when present. */
122
+ function orderGoogleToolGroup(
123
+ group: unknown,
124
+ isOwned: (name: string) => boolean,
125
+ ): unknown {
126
+ if (!isRecord(group)) return group;
127
+ const ordered = orderDefinitionList(group["functionDeclarations"], isOwned);
128
+ return ordered === undefined ? group : { ...group, functionDeclarations: ordered };
129
+ }
130
+
131
+ /** Order Gemini / Vertex `config.tools[].functionDeclarations` without mutating untouched groups. */
132
+ function orderGoogleConfigTools(
133
+ config: unknown,
134
+ isOwned: (name: string) => boolean,
135
+ ): Record<string, unknown> | undefined {
136
+ if (!isRecord(config) || !Array.isArray(config["tools"])) return undefined;
137
+ const tools = config["tools"];
138
+ const nextTools = tools.map((group) => orderGoogleToolGroup(group, isOwned));
139
+ const changed = nextTools.some((group, index) => group !== tools[index]);
140
+ return changed ? { ...config, tools: nextTools } : undefined;
141
+ }
142
+
143
+ /** Order Bedrock Converse `toolConfig.tools` (`{ toolSpec: { name } }`) when present. */
144
+ function orderBedrockToolConfig(
145
+ toolConfig: unknown,
146
+ isOwned: (name: string) => boolean,
147
+ ): Record<string, unknown> | undefined {
148
+ if (!isRecord(toolConfig)) return undefined;
149
+ const ordered = orderDefinitionList(toolConfig["tools"], isOwned);
150
+ return ordered === undefined ? undefined : { ...toolConfig, tools: ordered };
151
+ }
152
+
153
+ /** Order `toolsAdded` on one `pi-messages` `system` message while leaving other messages as is. */
154
+ function orderSystemMessageTools(
155
+ message: unknown,
156
+ isOwned: (name: string) => boolean,
157
+ ): unknown {
158
+ if (!isRecord(message) || message["role"] !== "system") return message;
159
+ const ordered = orderDefinitionList(message["toolsAdded"], isOwned);
160
+ return ordered === undefined ? message : { ...message, toolsAdded: ordered };
161
+ }
162
+
163
+ /**
164
+ * Order `pi-messages` `context.messages[].toolsAdded` within each `system` message without
165
+ * moving declarations across turns or mutating untouched messages.
166
+ */
167
+ function orderPiMessagesContext(
168
+ context: unknown,
169
+ isOwned: (name: string) => boolean,
170
+ ): Record<string, unknown> | undefined {
171
+ if (!isRecord(context) || !Array.isArray(context["messages"])) return undefined;
172
+ const messages = context["messages"];
173
+ const nextMessages = messages.map((message) => orderSystemMessageTools(message, isOwned));
174
+ const changed = nextMessages.some((message, index) => message !== messages[index]);
175
+ return changed ? { ...context, messages: nextMessages } : undefined;
176
+ }
177
+
178
+ /**
179
+ * Order nested provider tool containers: Bedrock `toolConfig.tools`, Google `config.tools`,
180
+ * or `pi-messages` `context.messages[].toolsAdded`.
181
+ */
182
+ function orderNestedPayloadTools(
183
+ payload: Record<string, unknown>,
184
+ isOwned: (name: string) => boolean,
185
+ ): Record<string, unknown> | undefined {
186
+ const orderedToolConfig = orderBedrockToolConfig(payload["toolConfig"], isOwned);
187
+ if (orderedToolConfig !== undefined) return { ...payload, toolConfig: orderedToolConfig };
188
+
189
+ const orderedGoogleConfig = orderGoogleConfigTools(payload["config"], isOwned);
190
+ if (orderedGoogleConfig !== undefined) return { ...payload, config: orderedGoogleConfig };
191
+
192
+ const orderedContext = orderPiMessagesContext(payload["context"], isOwned);
193
+ return orderedContext === undefined ? undefined : { ...payload, context: orderedContext };
194
+ }
195
+
196
+ /**
197
+ * Order owned tool definitions in an outgoing provider payload across all 10 built-in Pi API
198
+ * payload shapes, returning `payload` untouched when no owned slots move.
199
+ */
200
+ export function orderPayloadToolEntries(
201
+ payload: unknown,
202
+ isOwned: (name: string) => boolean,
203
+ ): unknown {
204
+ if (!isRecord(payload)) return payload;
205
+ const orderedTopLevel = orderDefinitionList(payload["tools"], isOwned);
206
+ if (orderedTopLevel !== undefined) return { ...payload, tools: orderedTopLevel };
207
+ return orderNestedPayloadTools(payload, isOwned) ?? payload;
208
+ }