pi-mcp-extension 1.14.1 → 1.14.2

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
@@ -24,7 +24,7 @@
24
24
  - **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
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
- - **Stable tool names** — Sanitized, collision-avoiding names (`<prefix>_<server>_<tool>`, max 64 chars) that stay constant across reconnects
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
28
  - **No tool churn** — Activate/deactivate pattern ensures tools don't flicker during reconnection
29
29
  - **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
30
  - **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
@@ -373,7 +373,7 @@ flowchart TD
373
373
  2. **Eager servers connect** at `session_start` via `ConnectionCoordinator` (offering a sequential `Authorize now` / `Not now` prompt when an eager OAuth server needs authorization in an interactive session); lazy servers wait for `mcp_connect`, `/mcp:start`, or `/mcp:auth`
374
374
  3. **Tools are discovered** via paginated `tools/list` calls (cursor-based, up to 100 pages) before a server enters `ready`
375
375
  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
- 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. Embedded image resources become image blocks, binary resources include MIME type and byte count, and resource links include a `mcp_read_resource` hint.
376
+ 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
377
  6. **Tools activate/deactivate** automatically as servers connect/disconnect
378
378
  7. **AbortSignal** is wired through to `notifications/cancelled` for clean cancellation
379
379
  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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mcp-extension",
3
- "version": "1.14.1",
3
+ "version": "1.14.2",
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": [
@@ -65,6 +65,69 @@ export function buildToolName(
65
65
  return `${safe.slice(0, MAX_TOOL_NAME_LEN - 9)}_${hash}`;
66
66
  }
67
67
 
68
+ /** True when sanitizing the raw tool name loses nothing (already a valid Pi identifier body). */
69
+ function isLosslessToolName(rawToolName: string): boolean {
70
+ return /^[a-zA-Z0-9_]+$/.test(rawToolName);
71
+ }
72
+
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
+ /**
86
+ * Order a server's tools so Pi-name assignment depends only on the tool set and never on
87
+ * the order `tools/list` happened to return (#213): a lossless raw name wins the unhashed
88
+ * `<prefix>_<server>_<tool>` identifier over one that needs character substitution
89
+ * (`my_tool` over `my-tool`), and remaining ties fall back to code-point order of the raw
90
+ * name. Without a total order here, the first response's order decided which colliding
91
+ * tool owned the unhashed name, so a reconnect could silently swap tool targets.
92
+ */
93
+ function compareToolsForNameAssignment(a: McpToolDefinition, b: McpToolDefinition): number {
94
+ const aLossless = isLosslessToolName(a.name);
95
+ const bLossless = isLosslessToolName(b.name);
96
+ if (aLossless !== bLossless) return aLossless ? -1 : 1;
97
+ return compareCodePoints(a.name, b.name);
98
+ }
99
+
100
+ /**
101
+ * 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).
106
+ */
107
+ function orderToolsForNameAssignment(
108
+ prefix: string,
109
+ serverName: string,
110
+ tools: readonly McpToolDefinition[],
111
+ ): readonly McpToolDefinition[] {
112
+ const groups = new Map<string, McpToolDefinition[]>();
113
+ for (const tool of tools) {
114
+ const baseName = buildToolName(prefix, serverName, tool.name, false);
115
+ const group = groups.get(baseName);
116
+ if (group) group.push(tool);
117
+ else groups.set(baseName, [tool]);
118
+ }
119
+
120
+ const emitted = new Set<string>();
121
+ const ordered: McpToolDefinition[] = [];
122
+ for (const tool of tools) {
123
+ const baseName = buildToolName(prefix, serverName, tool.name, false);
124
+ if (emitted.has(baseName)) continue;
125
+ emitted.add(baseName);
126
+ ordered.push(...(groups.get(baseName) ?? []).sort(compareToolsForNameAssignment));
127
+ }
128
+ return ordered;
129
+ }
130
+
68
131
  // ─── Content Conversion ───────────────────────────────────────────────────────
69
132
 
70
133
  type PiTextContent = { type: "text"; text: string };
@@ -438,7 +501,11 @@ export class ToolBridge {
438
501
 
439
502
  // Build the set of currently valid Pi tool names for this server
440
503
  const currentToolNames = new Set<string>();
441
- for (const tool of tools) {
504
+ // WHY: `tools/list` order carries no meaning (a server may reorder it freely), so colliding
505
+ // names are assigned over a deterministic order of the tool set — otherwise the exact-match
506
+ // tool could lose the unhashed name to a lossy one and a later refresh would swap which MCP
507
+ // tool that name executes (#213).
508
+ for (const tool of orderToolsForNameAssignment(this.settings.toolPrefix, serverName, tools)) {
442
509
  const piName = this._resolveUniqueToolName(serverName, tool.name, currentToolNames);
443
510
  currentToolNames.add(piName);
444
511
  this.toolOwners.set(piName, serverName);