pi-mcp-extension 1.14.5 → 1.15.0

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
@@ -20,11 +20,13 @@
20
20
  - **Multi-transport** — `stdio` subprocesses, `streamable-http` (including `"http"` and URL-only shorthand), and legacy `sse` out of the box
21
21
  - **Auto-discovery** — Paginated `tools/list` with cursor following (MCP 2025-03-26 spec)
22
22
  - **Live tool refresh** — `notifications/tools/list_changed` triggers re-discovery without restart
23
+ - **Live tool progress** — a server's `notifications/progress` events stream into Pi as live tool-call updates (server text is sanitized and secret-redacted, repeated lines are collapsed), and every notification restarts the per-request timeout, so a long-running tool that keeps reporting — a browser flow, migration, or test runner — is no longer killed at `requestTimeoutMs` while it is demonstrably working
23
24
  - **Clean cancellation** — `AbortSignal` propagation via `notifications/cancelled`
24
25
  - **Smart reconnection** — Fixed delay retry schedule (1s → 3s → 5s → 10s → 30s), configurable max retries, automatic recovery when a server transport closes or errors unexpectedly, and mid-session HTTP `401` / `403 insufficient_scope` detection that invalidates stale tokens and prompts for re-authorization
25
26
  - **Health checks** — Opt-in periodic pings to detect stale connections
26
27
  - **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
28
  - **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
29
+ - **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
30
  - **No tool churn** — Activate/deactivate pattern ensures tools don't flicker during reconnection
29
31
  - **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
32
  - **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
@@ -166,7 +168,7 @@ In project-level `.pi/mcp.json`, `settings` keys carry no defaults — only the
166
168
  | Field | Type | Default | Description |
167
169
  |---|---|---|---|
168
170
  | `toolPrefix` | `string` | `"mcp"` | Prefix for registered tools: `<prefix>_<server>_<tool>`. Must match `^[a-zA-Z][a-zA-Z0-9_]*$`. |
169
- | `requestTimeoutMs` | `number` | `30000` | Default per-request timeout in milliseconds |
171
+ | `requestTimeoutMs` | `number` | `30000` | Default per-request timeout in milliseconds. For `tools/call` this is an inactivity deadline: every `notifications/progress` event from the server restarts it, so page-by-page work is not cut off mid-flight. A server that reports progress indefinitely has no wall-clock cap — cancel the tool to stop it |
170
172
  | `maxRetries` | `number` | `5` | Max reconnection attempts (0–10) before giving up |
171
173
 
172
174
  ### Per-Server Config
@@ -333,7 +335,7 @@ The log is written to `<agent dir>/logs/pi-mcp.log` (JSON Lines, one event per l
333
335
  - API keys and other JSON or key/value secrets (`api_key`, `x-api-key`, `private_key`, `password`, `secret`, `token`, and prefixed forms such as `db_password` or `aws_secret_access_key`)
334
336
  - Credential-bearing query parameters on a server URL (`?api_key=…`, `?token=…`, `?code=…`)
335
337
  - `Authorization` headers in any scheme or quoting, and URL userinfo passwords (`https://user:password@host`)
336
- - The same redactor protects the per-server `Recent output:` (`stderr`) buffer, the `Last error:` line in `/mcp` and `/mcp <name>`, and user-facing start/auth/recovery failure notifications.
338
+ - The same redactor protects the per-server `Recent output:` (`stderr`) buffer, handshake `instructions`, `notifications/progress` tool updates, the `Last error:` line in `/mcp` and `/mcp <name>`, and user-facing start/auth/recovery failure notifications.
337
339
  - **Best-effort.** A failed log write never breaks a connection or a tool call.
338
340
 
339
341
  Attach the file to a bug report. It contains no credentials.
@@ -376,8 +378,8 @@ flowchart TD
376
378
  3. **Tools are discovered** via paginated `tools/list` calls (cursor-based, up to 100 pages) before a server enters `ready`
377
379
  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)
378
380
  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.
379
- 6. **Tools activate/deactivate** automatically as servers connect/disconnect
380
- 7. **AbortSignal** is wired through to `notifications/cancelled` for clean cancellation
381
+ 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
382
+ 7. **AbortSignal and progress** are wired through to `notifications/cancelled` for clean cancellation and `notifications/progress` for live sanitized tool updates plus inactivity-timeout resets
381
383
  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
382
384
  9. **`list_changed` notifications** trigger re-discovery, deactivating stale tools automatically and invalidating the cached resource catalog
383
385
  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)
@@ -401,6 +403,7 @@ Implements the **MCP 2025-03-26** specification for tool and resource clients:
401
403
  | `roots/list` capability (workspace root) | ✅ |
402
404
  | `notifications/tools/list_changed` (live refresh) | ✅ |
403
405
  | `notifications/cancelled` (AbortSignal) | ✅ |
406
+ | `notifications/progress` (live sanitized tool updates + inactivity timeout reset) | ✅ |
404
407
  | `notifications/message` (structured logging) | ✅ |
405
408
  | `isError: true` distinction (protocol vs tool errors, non-text filtered on error) | ✅ |
406
409
  | Tool annotations (`readOnlyHint`, `destructiveHint`, etc.) in descriptions and as structured Pi `annotations` | ✅ |
@@ -442,7 +445,7 @@ The test suite includes:
442
445
  - **Config & Pi 1.x / 1.3.0 compatibility** (`tests/config.test.ts`, `tests/pi-1x-compat.test.ts`) — Zod schema, JSONC comments, `$PI_CODING_AGENT_DIR` resolution, global/project merge, project trust boundary (`ctx.isProjectTrusted()`), Pi 1.3.0 `enabled: false` and partial project overrides, `stdio` `cwd`, `oauth.clientName`, Pi 1.x schema aliases (`type: "http"`, URL-only HTTP, `oauth`, `timeout`), and dynamic `pi.getMcpServers()` / `mcp_servers_change`
443
446
  - **Server lifecycle & coordination** (`tests/server-manager.test.ts`, `tests/stdio-process.test.ts`, `tests/transport-factory.test.ts`, `tests/connection-coordinator.test.ts`, `tests/connection-coordination.test.ts`) — Connect, retry, unexpected close recovery, shutdown with PID `SIGKILL` safety net, health check, concurrent connect/reset coordination, and cancellation
444
447
  - **OAuth 2.1 & auth locks** (`tests/oauth-fixes.test.ts`, `tests/authorize-flow.test.ts`, `tests/auth-lock.test.ts`, `tests/auth-commands.test.ts`, `tests/auth-arguments.test.ts`, `tests/fake-oauth-server.test.ts`) — Challenge discovery, PKCE, Dynamic Client Registration, origin and issuer binding, startup authorization prompts, headless/SSH redirect URL paste-back, URL scheme validation, cross-process lock heartbeat, and stale lock reclamation
445
- - **Tool bridge, status diagnostics & debug log** (`tests/tool-bridge.test.ts`, `tests/management-tools.test.ts`, `tests/server-status.test.ts`, `tests/status-commands.test.ts`, `tests/completions.test.ts`, `tests/debug-log.test.ts`) — JSON Schema → TypeBox conversion (`allOf` object inference, `$ref` cycle protection, union `null` ordering), name sanitization, image content passthrough, `isError` filtering, activate/deactivate, `mcp_status` / `mcp_connect`, `/mcp <name>` config provenance and failure hints, slash command completions, and redacted `PI_MCP_DEBUG=1` JSONL logging
448
+ - **Tool bridge, status diagnostics & debug log** (`tests/tool-bridge.test.ts`, `tests/tool-progress.test.ts`, `tests/management-tools.test.ts`, `tests/server-status.test.ts`, `tests/status-commands.test.ts`, `tests/completions.test.ts`, `tests/debug-log.test.ts`) — JSON Schema → TypeBox conversion (`allOf` object inference, `$ref` cycle protection, union `null` ordering), name sanitization, image content passthrough, `isError` filtering, activate/deactivate, `notifications/progress` forwarding (sanitizing, redaction, dedupe, and the timeout reset over a real stdio server), `mcp_status` / `mcp_connect`, `/mcp <name>` config provenance and failure hints, slash command completions, and redacted `PI_MCP_DEBUG=1` JSONL logging
446
449
  - **Resource bridge** (`tests/resource-bridge.test.ts`) — paginated `resources/list` / `resources/templates/list`, `-32601` degradation, catalog caching with `notifications/resources/list_changed` invalidation, stale in-flight discard, text/image/binary `resources/read` conversion, abort/timeout/401 mapping, `mcp_list_resources` / `mcp_read_resource`, and `/mcp:resources`
447
450
  - **Property-based fuzzing** (`tests/fuzz.test.ts`) — `fast-check` properties covering JSONC comment stripping, callback/redirect URL validation, `WWW-Authenticate` challenge parsing, JSON Schema → TypeBox conversion, tool naming, terminal/log secret sanitization, and custom header merging
448
451
  - **Release flow & repository policy** (`tests/release.test.ts`, `tests/ruleset-audit.test.ts`, `tests/repo-policy.test.ts`) — Release PR orchestration and npm/git self-healing (`scripts/release.ts`), live GitHub ruleset drift auditing (`scripts/ruleset-audit.ts`), and CI/ESLint/Qlty policy invariants
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mcp-extension",
3
- "version": "1.14.5",
3
+ "version": "1.15.0",
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": [
@@ -193,6 +193,34 @@ export function isCancellationError(err: unknown, signal?: AbortSignal | undefin
193
193
  return err.name === "AbortError" || ((err as { code?: unknown }).code === -32001 && /abort/i.test(err.message));
194
194
  }
195
195
 
196
+ /**
197
+ * Whether a `client.onerror` message came from `Protocol._onnotification` rejecting an
198
+ * incoming notification (for example `notifications/progress` carrying `total: null` once
199
+ * `tools/call` attaches `_meta.progressToken`, or a throwing notification callback).
200
+ */
201
+ export function isNotificationHandlerError(rawMsg: string): boolean {
202
+ return /^Uncaught error in notification handler:/i.test(rawMsg);
203
+ }
204
+
205
+ /**
206
+ * Whether a `client.onerror` message is non-fatal protocol noise rather than a broken
207
+ * SSE / Streamable HTTP transport stream.
208
+ *
209
+ * Late responses or `notifications/progress` events for an already-settled or cancelled
210
+ * request report `unknown message ID` / `unknown token`, and malformed notifications or
211
+ * throwing notification callbacks report `Uncaught error in notification handler: …`.
212
+ * Reconnecting on any of these would close a healthy HTTP/SSE session and abort in-flight
213
+ * `tools/call` requests with `Connection closed`.
214
+ */
215
+ export function isNonFatalClientError(rawMsg: string): boolean {
216
+ return (
217
+ isNotificationHandlerError(rawMsg) ||
218
+ /unknown message ID|Received a response for an unknown message ID|notifications\/progress|unknown token/i.test(
219
+ rawMsg,
220
+ )
221
+ );
222
+ }
223
+
196
224
  export type TransportType = ServerConfig["transport"];
197
225
 
198
226
  export type ConnectFailureAction =
@@ -239,6 +239,46 @@ function readBareValue(
239
239
  return end > start ? { end, delimiter: "" } : undefined;
240
240
  }
241
241
 
242
+ const REDACTED_MASKS: readonly string[] = [
243
+ "[REDACTED]",
244
+ '"[REDACTED]"',
245
+ "'[REDACTED]'",
246
+ '\\"[REDACTED]\\"',
247
+ "\\'[REDACTED]\\'",
248
+ ];
249
+
250
+ const AUTH_SCHEME_NAMES: readonly string[] = [
251
+ "bearer",
252
+ "basic",
253
+ "digest",
254
+ "token",
255
+ "apikey",
256
+ "dpop",
257
+ "oauth",
258
+ "negotiate",
259
+ ];
260
+
261
+ /**
262
+ * True when `text.slice(start)` is an already-redacted mask (or known `Authorization` scheme
263
+ * prefix) that post-redaction length capping sliced with a trailing `…` (`[REDACTED…`,
264
+ * `"[RED…`, `Authorization: Bea…`, `token=…`). Skipping it keeps `redactSecrets` + truncation
265
+ * idempotent without sparing any free secret characters.
266
+ */
267
+ function isTruncatedRedactedTail(
268
+ text: string,
269
+ start: number,
270
+ terminators: Set<string>,
271
+ ): boolean {
272
+ if (!text.endsWith("…")) return false;
273
+ const body = text.slice(start, -1);
274
+ if (REDACTED_MASKS.some((mask) => mask.startsWith(body))) return true;
275
+ const lower = body.toLowerCase();
276
+ return (
277
+ terminators === AUTHORIZATION_VALUE_TERMINATORS &&
278
+ AUTH_SCHEME_NAMES.some((scheme) => scheme.startsWith(lower))
279
+ );
280
+ }
281
+
242
282
  /**
243
283
  * Read the credential value that starts at `start`, honouring its opening delimiter: a quoted
244
284
  * value runs to its matching quote, a `{`/`[` value runs to its matching bracket, and an
@@ -249,6 +289,7 @@ function readCredentialValue(
249
289
  start: number,
250
290
  terminators: Set<string> = UNQUOTED_VALUE_TERMINATORS,
251
291
  ): CredentialValue | undefined {
292
+ if (isTruncatedRedactedTail(text, start, terminators)) return undefined;
252
293
  // An out-of-range start yields an empty opening and falls through to `readBareValue`, which
253
294
  // returns `undefined` for an empty value.
254
295
  const quote = openingQuoteAt(text, start);
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
@@ -38,6 +38,8 @@ import {
38
38
  import { createTransport } from "./transport-factory.js";
39
39
  import {
40
40
  classifyConnectFailure,
41
+ isNonFatalClientError,
42
+ isNotificationHandlerError,
41
43
  isOAuthUnauthorizedError,
42
44
  isSdkTimeoutError,
43
45
  type ConnectFailureAction,
@@ -869,14 +871,19 @@ export class ServerManager {
869
871
  return;
870
872
  }
871
873
  const rawMsg = err instanceof Error ? err.message : String(err);
872
- if (
873
- /unknown message ID|Received a response for an unknown message ID|notifications\/progress|unknown token/i.test(
874
- rawMsg,
875
- )
876
- ) {
874
+ const msg = sanitizeTerminalText(rawMsg);
875
+ if (isNonFatalClientError(rawMsg)) {
876
+ if (isNotificationHandlerError(rawMsg)) {
877
+ reportDiagnostic({
878
+ level: "info",
879
+ event: "server.notification_error",
880
+ server: server.name,
881
+ message: msg,
882
+ fields: { transport: server.config.transport },
883
+ });
884
+ }
877
885
  return;
878
886
  }
879
- const msg = sanitizeTerminalText(rawMsg);
880
887
  if (server.config.transport === "sse") {
881
888
  reportDiagnostic({
882
889
  level: "warn",
@@ -7,6 +7,7 @@
7
7
  * - Tool name sanitization (Pi-compatible identifiers)
8
8
  * - Tool annotations → description hints + structured Pi `annotations`
9
9
  * - AbortSignal → SDK's built-in cancellation (notifications/cancelled)
10
+ * - notifications/progress → sanitized, redacted live tool updates + inactivity timeout reset
10
11
  * - Protocol error vs tool execution error distinction
11
12
  * - Activate/deactivate pattern (register once, toggle on server state change)
12
13
  * - Images and embedded image resources → ImageContent; resource links → read hints
@@ -14,14 +15,22 @@
14
15
 
15
16
  import { createHash } from "node:crypto";
16
17
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
17
- import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js";
18
+ import { CallToolResultSchema, type Progress } from "@modelcontextprotocol/sdk/types.js";
18
19
  import type { ExtensionAPI, ToolAnnotations } from "@earendil-works/pi-coding-agent";
19
20
  import { McpError, AuthCancelledError } from "./errors.js";
21
+ import { redactSecrets } from "./debug-log.js";
22
+ import { sanitizeTerminalText } from "./terminal-text.js";
20
23
  import type { Settings } from "./config.js";
21
24
  import { isCancellationError, isOAuthUnauthorizedError, isSdkTimeoutError } from "./connect-policy.js";
22
25
  import { convertJsonSchemaToTypebox } from "./schema-convert.js";
23
26
  import { listAllTools, type McpToolDefinition } from "./tool-discovery.js";
24
27
  import { convertResourceContent } from "./resource-bridge.js";
28
+ import {
29
+ compareCodePoints,
30
+ orderOwnedEntries,
31
+ orderPayloadToolEntries,
32
+ sameToolList,
33
+ } from "./tool-order.js";
25
34
 
26
35
  // ─── Types ────────────────────────────────────────────────────────────────────
27
36
 
@@ -70,18 +79,6 @@ function isLosslessToolName(rawToolName: string): boolean {
70
79
  return /^[a-zA-Z0-9_]+$/.test(rawToolName);
71
80
  }
72
81
 
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
82
  /**
86
83
  * Order a server's tools so Pi-name assignment depends only on the tool set and never on
87
84
  * the order `tools/list` happened to return (#213): a lossless raw name wins the unhashed
@@ -99,10 +96,10 @@ function compareToolsForNameAssignment(a: McpToolDefinition, b: McpToolDefinitio
99
96
 
100
97
  /**
101
98
  * 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).
99
+ * so registration order only moves where it must — except that tools competing for the same
100
+ * unhashed identifier are emitted as one deterministic group in the position of the group's
101
+ * first member. Which tool the server listed first is not part of the MCP contract, so it must
102
+ * not decide who wins that identifier (#213).
106
103
  */
107
104
  function orderToolsForNameAssignment(
108
105
  prefix: string,
@@ -208,6 +205,15 @@ interface ToolCallOutcome {
208
205
  details: Record<string, never>;
209
206
  }
210
207
 
208
+ /** Pi's partial-result callback — the `onUpdate` argument of a tool's `execute`. */
209
+ export type ToolUpdateCallback = (update: ToolCallOutcome) => void;
210
+
211
+ /** Per-call streaming and cancellation options for one `tools/call`. */
212
+ interface ToolCallOptions {
213
+ signal: AbortSignal | undefined;
214
+ onUpdate: ToolUpdateCallback | undefined;
215
+ }
216
+
211
217
  /**
212
218
  * The subset of an SDK `tools/call` response the bridge consumes.
213
219
  * Legacy servers answer with `toolResult` instead of `content`, so every field
@@ -260,19 +266,81 @@ function buildToolAnnotations(
260
266
  return Object.keys(result).length > 0 ? result : undefined;
261
267
  }
262
268
 
269
+ /** Character budget for one progress line; Pi renders the latest line while the tool runs. */
270
+ const PROGRESS_MESSAGE_MAX_LENGTH = 200;
271
+
272
+ /**
273
+ * Render one MCP `notifications/progress` payload as a single Pi-visible line.
274
+ *
275
+ * `message` is server-controlled and lands in Pi's UI stream, so it is sanitized (ANSI and
276
+ * control sequences stripped, length bounded) and stripped of token-like substrings first.
277
+ * A server that sends no usable text gets a numeric `Progress 3/10` line instead.
278
+ *
279
+ * WHY: sanitize before redacting, as `sanitizeLogText` does — the sanitizer deletes escape
280
+ * sequences, and an escape *inside* a credential (`\u001b[1mtoken\u001b[0m=sk-…`) hides the
281
+ * `key=value` shape from `redactSecrets`, which would then pass the token through verbatim.
282
+ */
283
+ export function formatProgressText(progress: Progress): string {
284
+ const rawMessage = typeof progress.message === "string" ? progress.message : "";
285
+ // WHY: decide usability on the full text (`maxLength` = its own length disables truncation) and
286
+ // trim surrounding whitespace first. `sanitizeTerminalText` appends `…` when it truncates and
287
+ // turns trailing newlines into spaces, so untrimmed padding would either defeat the fallback,
288
+ // consume the 200-char budget into a blank ` …` row, or split dedupe across `msg` vs `msg\n`.
289
+ const message = sanitizeTerminalText(rawMessage, { maxLength: rawMessage.length }).trim();
290
+ if (message.length > 0) {
291
+ // WHY: bound after redaction — a `[REDACTED]` mask is longer than the value it replaces, so
292
+ // capping first would let the emitted line grow past the budget (or slice a token before the
293
+ // redactor can recognise it).
294
+ return sanitizeTerminalText(redactSecrets(message), {
295
+ maxLength: PROGRESS_MESSAGE_MAX_LENGTH,
296
+ });
297
+ }
298
+ const current = Number.isFinite(progress.progress) ? String(progress.progress) : "?";
299
+ const total = Number.isFinite(progress.total) ? `/${progress.total}` : "";
300
+ return `Progress ${current}${total}`;
301
+ }
302
+
303
+ /**
304
+ * Build the SDK `onprogress` handler for one `tools/call`.
305
+ *
306
+ * WHY: the handler is installed even when Pi passes no `onUpdate` callback. The SDK attaches
307
+ * `_meta.progressToken` only when `onprogress` is set, and the timer reset that keeps a long,
308
+ * actively-reporting tool alive (`resetTimeoutOnProgress`) hangs off that token (#254).
309
+ *
310
+ * Consecutive identical lines are dropped: some servers repeat one message on every tick, and
311
+ * each emission re-renders Pi's in-progress tool row.
312
+ */
313
+ function createProgressReporter(
314
+ onUpdate: ToolUpdateCallback | undefined,
315
+ ): (progress: Progress) => void {
316
+ let lastText: string | undefined;
317
+ return (progress: Progress): void => {
318
+ if (!onUpdate) return;
319
+ const text = formatProgressText(progress);
320
+ if (text === lastText) return;
321
+ lastText = text;
322
+ onUpdate({ content: [{ type: "text", text }], details: {} });
323
+ };
324
+ }
325
+
263
326
  /** Call tools/call through the typed helper when present, else a raw JSON-RPC request. */
264
327
  function callToolWithClient(
265
328
  client: Client,
266
329
  toolName: string,
267
330
  params: unknown,
268
331
  timeoutMs: number,
269
- signal: AbortSignal | undefined,
332
+ options: ToolCallOptions,
270
333
  ): Promise<ToolCallResponse> {
271
334
  const requestOptions = {
272
335
  timeout: timeoutMs,
336
+ // WHY: without these two the SDK never attaches a progress token, so it drops the server's
337
+ // `notifications/progress` as an unknown token and keeps the original inactivity deadline —
338
+ // a tool that reports progress every few seconds was still killed at `requestTimeoutMs` (#254).
339
+ resetTimeoutOnProgress: true,
340
+ onprogress: createProgressReporter(options.onUpdate),
273
341
  // Pass AbortSignal to SDK — it will automatically send
274
342
  // notifications/cancelled when the signal fires
275
- ...(signal ? { signal } : {}),
343
+ ...(options.signal ? { signal: options.signal } : {}),
276
344
  };
277
345
  if (typeof client.callTool === "function") {
278
346
  return client.callTool(
@@ -324,12 +392,6 @@ function normalizeRefreshArgs(
324
392
  return { isCurrent, options };
325
393
  }
326
394
 
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
-
333
395
  // ─── Tool Listing ─────────────────────────────────────────────────────────────
334
396
 
335
397
  export { listAllTools, type McpToolDefinition } from "./tool-discovery.js";
@@ -430,6 +492,47 @@ export class ToolBridge {
430
492
  return { discovered: names.size, active: [...names].filter((name) => active.has(name)).length };
431
493
  }
432
494
 
495
+ /**
496
+ * Re-apply this bridge's deterministic tool order to Pi's active list when owned tools have
497
+ * been reordered externally, and do nothing when already ordered.
498
+ *
499
+ * WHY: `/tree` navigation (`session_tree`) restores active tools from the transcript's
500
+ * first-appearance order without re-running `refreshTools`, and another extension or tool
501
+ * (e.g. `tool_search`) may call `pi.setActiveTools` idle or mid-turn; re-normalizing on
502
+ * `session_tree`, `input`, `before_agent_start`, and `tool_execution_end` keeps `sections.tools`
503
+ * in the system prompt aligned with `orderPayloadTools` without re-activating inactive tools (#278).
504
+ */
505
+ orderActiveTools(): void {
506
+ const current = this.pi.getActiveTools();
507
+ const ordered = orderOwnedEntries(
508
+ current,
509
+ (name) => name,
510
+ (name) => this.toolOwners.has(name),
511
+ );
512
+ if (ordered === undefined) return;
513
+ this.pi.setActiveTools(ordered);
514
+ }
515
+
516
+ /**
517
+ * Order this bridge's tools in an outgoing provider payload the same way they are ordered in
518
+ * Pi's active list — across top-level `tools` (Anthropic, OpenAI Chat Completions & Responses,
519
+ * Mistral), AWS Bedrock Converse `toolConfig.tools`, Google/Vertex
520
+ * `config.tools[].functionDeclarations`, and `pi-messages` `context.messages[].toolsAdded` —
521
+ * and return the payload untouched when they already are. Only entries this bridge owns move,
522
+ * and only among the slots they already occupy: another extension's tool and Pi's reserved
523
+ * trailing declarations (`__pi_deferred_placeholder__`, `cachePoint`, non-function Gemini tool
524
+ * groups, non-system messages) keep their positions.
525
+ *
526
+ * WHY: request tool arrays are not built from the active list — Pi replays the transcript's
527
+ * tool declarations in first-appearance order and emits no delta for a pure reorder, so a
528
+ * server that connects after the first turn leaves its tools at the end, in connect order.
529
+ * Sorting the payload makes the declared tools a function of the tool set, so the prompt head
530
+ * stays stable across sessions and a server-side prefix cache keeps its KV entries (#278).
531
+ */
532
+ orderPayloadTools(payload: unknown): unknown {
533
+ return orderPayloadToolEntries(payload, (name) => this.toolOwners.has(name));
534
+ }
535
+
433
536
  /** Deactivate all Pi tools belonging to a server (called on disconnect). */
434
537
  deactivateServer(serverName: string): void {
435
538
  this._bumpRefreshGeneration(serverName);
@@ -622,8 +725,11 @@ export class ToolBridge {
622
725
  const annotations = tool.annotations;
623
726
  const description = buildToolDescription(tool, annotations);
624
727
  const toolAnnotations = buildToolAnnotations(annotations);
625
- const runTool = (params: unknown, signal: AbortSignal | undefined) =>
626
- this._executeToolCall(serverName, tool.name, client, params, signal);
728
+ const runTool = (
729
+ params: unknown,
730
+ signal: AbortSignal | undefined,
731
+ onUpdate: ToolUpdateCallback | undefined,
732
+ ) => this._executeToolCall(serverName, tool.name, client, params, { signal, onUpdate });
627
733
  // WHY: `execute` runs with `this` bound to the registered-tool literal rather than the
628
734
  // bridge, so the rethrow helper is reached through a captured closure.
629
735
  const rethrowToolCallError = (err: unknown): Promise<never> =>
@@ -637,9 +743,9 @@ export class ToolBridge {
637
743
  parameters: convertJsonSchemaToTypebox(tool.inputSchema),
638
744
  ...(toolAnnotations ? { annotations: toolAnnotations } : {}),
639
745
 
640
- async execute(_toolCallId, params, signal, _onUpdate, _ctx) {
746
+ async execute(_toolCallId, params, signal, onUpdate, _ctx) {
641
747
  try {
642
- return await runTool(params, signal);
748
+ return await runTool(params, signal, onUpdate);
643
749
  } catch (err) {
644
750
  return await rethrowToolCallError(err);
645
751
  }
@@ -678,9 +784,9 @@ export class ToolBridge {
678
784
  toolName: string,
679
785
  client: Client,
680
786
  params: unknown,
681
- signal: AbortSignal | undefined,
787
+ options: ToolCallOptions,
682
788
  ): Promise<ToolCallOutcome> {
683
- if (signal?.aborted) {
789
+ if (options.signal?.aborted) {
684
790
  throw new McpError("Tool execution cancelled", serverName, "protocol");
685
791
  }
686
792
 
@@ -691,13 +797,13 @@ export class ToolBridge {
691
797
  toolName,
692
798
  params,
693
799
  this.serverTimeouts.get(serverName) ?? this.settings.requestTimeoutMs,
694
- signal,
800
+ options,
695
801
  );
696
802
  } catch (err) {
697
803
  // WHY: an abort mid-call is rejected by the SDK with its RequestTimeout error, so the
698
804
  // cancellation has to be recognised here — otherwise a caller cancellation is reported
699
805
  // as a server timeout, and blamed on the server (#209).
700
- if (isCancellationError(err, signal)) {
806
+ if (isCancellationError(err, options.signal)) {
701
807
  throw new McpError("Tool execution cancelled", serverName, "protocol");
702
808
  }
703
809
  throw err;
@@ -799,7 +905,8 @@ export class ToolBridge {
799
905
  /**
800
906
  * Reconcile a server's active tools in Pi in one write: drop any previously owned Pi tool
801
907
  * 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.
908
+ * order the result, and skip `pi.setActiveTools` altogether when the active list already
909
+ * holds exactly that set in that order.
803
910
  */
804
911
  private _reconcileActiveTools(
805
912
  ownedPreviousNames: ReadonlySet<string>,
@@ -811,14 +918,30 @@ export class ToolBridge {
811
918
  (name) => !ownedPreviousNames.has(name) || desiredActive.has(name),
812
919
  );
813
920
  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;
820
-
821
- this.pi.setActiveTools(Array.from(new Set([...remaining, ...newlyActive])));
921
+ const nextActive = this._orderActiveTools(new Set([...remaining, ...newlyActive]));
922
+ // WHY: `pi.registerTool()` inside the loop may have auto-activated a newly registered hashed
923
+ // Pi name or a `--tools` allowlist entry, and a resumed session restores the order it ended
924
+ // with — so compare against a fresh read and write whenever the set *or* the order differs.
925
+ if (sameToolList(this.pi.getActiveTools(), nextActive)) return;
926
+
927
+ this.pi.setActiveTools(nextActive);
928
+ }
929
+
930
+ /**
931
+ * Order the active set so this bridge's tools are a pure function of the tool set: they are
932
+ * sorted by Pi name among the positions they already occupy, while every entry another
933
+ * extension owns keeps its position.
934
+ *
935
+ * WHY: a server's tools are registered as its connection completes, and `desiredActive`
936
+ * follows `tools/list` order, which the MCP spec does not define. Without a fixed order the
937
+ * active list — and with it the system prompt's tool section and the tools declared to the
938
+ * provider — depends on eager-connect timing, so a server-side prefix cache keyed on the
939
+ * prompt head misses on every session start or resume (#278).
940
+ */
941
+ private _orderActiveTools(active: ReadonlySet<string>): string[] {
942
+ const names = [...active];
943
+ const ordered = orderOwnedEntries(names, (name) => name, (name) => this.toolOwners.has(name));
944
+ return ordered ?? names;
822
945
  }
823
946
 
824
947
  private _deactivateServerTools(serverName: string): void {
@@ -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
+ }