pi-mcp-extension 1.14.1 → 1.14.3
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 +3 -3
- package/package.json +1 -1
- package/src/debug-log.ts +100 -23
- package/src/tool-bridge.ts +68 -1
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
|
|
@@ -325,7 +325,7 @@ The log is written to `<agent dir>/logs/pi-mcp.log` (JSON Lines, one event per l
|
|
|
325
325
|
|
|
326
326
|
- **Off by default.** Without `PI_MCP_DEBUG=1` no log file is created.
|
|
327
327
|
- **Private.** The directory is `0o700` and the file is `0o600`, like the OAuth credential files.
|
|
328
|
-
- **Bounded.** The file is rotated to `pi-mcp.log.1` at ~2 MB; a single backup is kept.
|
|
328
|
+
- **Bounded.** The file is rotated to `pi-mcp.log.1` at ~2 MB; a single backup is kept. Concurrent Pi processes share the log without locking: a rotation that loses that race is not an error (the entry is still appended), and re-checking the size before `rename` skips rotating when the file shrank or disappeared so a peer's freshly rotated backup is not overwritten while still rotating when a peer merely appended.
|
|
329
329
|
- **Redacted.** Only allow-listed field names are recorded, and a delimiter-aware pass masks anything that looks like a credential:
|
|
330
330
|
- OAuth tokens, authorization codes, and PKCE verifiers
|
|
331
331
|
- 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`)
|
|
@@ -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.
|
|
3
|
+
"version": "1.14.3",
|
|
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/debug-log.ts
CHANGED
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
* mistake.
|
|
21
21
|
*/
|
|
22
22
|
|
|
23
|
-
import { appendFile, chmod, mkdir, rename, stat
|
|
23
|
+
import { appendFile, chmod, mkdir, rename, stat } from "node:fs/promises";
|
|
24
24
|
import { join } from "node:path";
|
|
25
25
|
import {
|
|
26
26
|
buildLogEntry,
|
|
@@ -76,7 +76,6 @@ export interface DebugLogFs {
|
|
|
76
76
|
stat(path: string): Promise<{ size: number }>;
|
|
77
77
|
rename(oldPath: string, newPath: string): Promise<void>;
|
|
78
78
|
chmod(path: string, mode: number): Promise<void>;
|
|
79
|
-
unlink(path: string): Promise<void>;
|
|
80
79
|
}
|
|
81
80
|
|
|
82
81
|
export interface DebugLogDeps {
|
|
@@ -92,7 +91,6 @@ export function createDefaultDebugLogDeps(): DebugLogDeps {
|
|
|
92
91
|
stat: (path) => stat(path),
|
|
93
92
|
rename: (oldPath, newPath) => rename(oldPath, newPath),
|
|
94
93
|
chmod: (path, mode) => chmod(path, mode),
|
|
95
|
-
unlink: (path) => unlink(path),
|
|
96
94
|
},
|
|
97
95
|
now: () => new Date(),
|
|
98
96
|
};
|
|
@@ -146,37 +144,116 @@ export class DebugLog {
|
|
|
146
144
|
}
|
|
147
145
|
|
|
148
146
|
private async _append(line: string): Promise<void> {
|
|
149
|
-
|
|
150
|
-
if (!this.dirReady) {
|
|
151
|
-
await fs.mkdir(this.dir, { recursive: true, mode: DEBUG_LOG_DIR_MODE });
|
|
152
|
-
await fs.chmod(this.dir, DEBUG_LOG_DIR_MODE);
|
|
153
|
-
this.dirReady = true;
|
|
154
|
-
}
|
|
147
|
+
await this._ensureDir();
|
|
155
148
|
await this._rotateIfNeeded(Buffer.byteLength(line, "utf8"));
|
|
156
|
-
|
|
157
|
-
|
|
149
|
+
try {
|
|
150
|
+
await this.deps.fs.appendFile(this.filePath, line, { mode: DEBUG_LOG_FILE_MODE });
|
|
151
|
+
} catch (err) {
|
|
152
|
+
// WHY: `ENOENT` on `appendFile` means `<agentDir>/logs` disappeared after
|
|
153
|
+
// it was created. Recreating the directory and retrying once keeps that
|
|
154
|
+
// from dropping the entry or tripping the once-per-process failure latch;
|
|
155
|
+
// a second failure is a real one.
|
|
156
|
+
if (!isErrnoException(err, "ENOENT")) throw err;
|
|
157
|
+
this.dirReady = false;
|
|
158
|
+
this.fileModeEnsured = false;
|
|
159
|
+
await this._ensureDir();
|
|
160
|
+
await this.deps.fs.appendFile(this.filePath, line, { mode: DEBUG_LOG_FILE_MODE });
|
|
161
|
+
}
|
|
162
|
+
await this._ensureFileMode();
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
private async _ensureDir(): Promise<void> {
|
|
166
|
+
if (this.dirReady) return;
|
|
167
|
+
try {
|
|
168
|
+
await this._createDir();
|
|
169
|
+
} catch (err) {
|
|
170
|
+
// WHY: Something removed `<agentDir>/logs` between the mkdir and the chmod
|
|
171
|
+
// (a peer Pi process pruning an agent dir, a sandbox reset). Recreating it
|
|
172
|
+
// keeps that from dropping the entry; a second failure is a real one.
|
|
173
|
+
if (!isErrnoException(err, "ENOENT")) throw err;
|
|
174
|
+
await this._createDir();
|
|
175
|
+
}
|
|
176
|
+
this.dirReady = true;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
private async _createDir(): Promise<void> {
|
|
180
|
+
const fs = this.deps.fs;
|
|
181
|
+
await fs.mkdir(this.dir, { recursive: true, mode: DEBUG_LOG_DIR_MODE });
|
|
182
|
+
await fs.chmod(this.dir, DEBUG_LOG_DIR_MODE);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
private async _ensureFileMode(): Promise<void> {
|
|
186
|
+
if (this.fileModeEnsured) return;
|
|
187
|
+
try {
|
|
158
188
|
// WHY: `mode` only applies when the file is created; an existing file may
|
|
159
189
|
// have looser permissions, so the mode is enforced once per logger.
|
|
160
|
-
await fs.chmod(this.filePath, DEBUG_LOG_FILE_MODE);
|
|
190
|
+
await this.deps.fs.chmod(this.filePath, DEBUG_LOG_FILE_MODE);
|
|
161
191
|
this.fileModeEnsured = true;
|
|
192
|
+
} catch (err) {
|
|
193
|
+
// WHY: A peer Pi process sharing this log rotated `pi-mcp.log` between the
|
|
194
|
+
// append and this chmod, so it already holds the line. Leaving the flag
|
|
195
|
+
// false re-applies the mode on the file the next write creates instead of
|
|
196
|
+
// reporting a logger failure for a race that lost nothing.
|
|
197
|
+
if (!isErrnoException(err, "ENOENT")) throw err;
|
|
162
198
|
}
|
|
163
199
|
}
|
|
164
200
|
|
|
165
201
|
private async _rotateIfNeeded(incomingBytes: number): Promise<void> {
|
|
166
|
-
const
|
|
167
|
-
|
|
202
|
+
const size = await this._logSize();
|
|
203
|
+
if (size === null || size <= 0) return;
|
|
204
|
+
if (size + incomingBytes <= DEBUG_LOG_MAX_BYTES) return;
|
|
205
|
+
// WHY: Re-read immediately before renaming to narrow the lock-free race
|
|
206
|
+
// window: if the log vanished or shrank (`currentSize < size`), a peer
|
|
207
|
+
// process already rotated it (and possibly recreated a smaller one), so
|
|
208
|
+
// renaming again would overwrite the backup that peer just produced. A plain
|
|
209
|
+
// peer append (`currentSize >= size`) leaves the file over the cap and still
|
|
210
|
+
// rotates. Either way, `pi-mcp.log` is no longer the pre-rotation file, so
|
|
211
|
+
// `0o600` must be re-enforced after the append.
|
|
212
|
+
const currentSize = await this._logSize();
|
|
213
|
+
if (currentSize === null) return;
|
|
214
|
+
this.fileModeEnsured = false;
|
|
215
|
+
if (currentSize < size) return;
|
|
216
|
+
await this._rotate();
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Size of the log file: `0` when it is absent, `null` when it is unknown. */
|
|
220
|
+
private async _logSize(): Promise<number | null> {
|
|
168
221
|
try {
|
|
169
|
-
|
|
170
|
-
} catch {
|
|
171
|
-
|
|
172
|
-
|
|
222
|
+
return (await this.deps.fs.stat(this.filePath)).size;
|
|
223
|
+
} catch (err) {
|
|
224
|
+
if (isErrnoException(err, "ENOENT")) {
|
|
225
|
+
// WHY: An absent file means the initial write has not run yet or a peer
|
|
226
|
+
// rotated `pi-mcp.log` away since this logger last ensured `0o600`.
|
|
227
|
+
this.fileModeEnsured = false;
|
|
228
|
+
return 0;
|
|
229
|
+
}
|
|
230
|
+
// WHY: Any other stat failure leaves the size unknown. Rotation is only an
|
|
231
|
+
// optimization — the caller appends anyway rather than dropping the line,
|
|
232
|
+
// and the cap is re-checked on the next write that can read the size.
|
|
233
|
+
return null;
|
|
173
234
|
}
|
|
174
|
-
if (size <= 0 || size + incomingBytes <= DEBUG_LOG_MAX_BYTES) return;
|
|
175
|
-
await fs.unlink(this.rotatedFilePath).catch(() => {
|
|
176
|
-
// WHY: No previous backup to remove — the rename below creates the only one.
|
|
177
|
-
});
|
|
178
|
-
await fs.rename(this.filePath, this.rotatedFilePath);
|
|
179
235
|
}
|
|
236
|
+
|
|
237
|
+
private async _rotate(): Promise<void> {
|
|
238
|
+
this.fileModeEnsured = false;
|
|
239
|
+
try {
|
|
240
|
+
// WHY: One rename, no unlink: `rename` replaces the previous backup
|
|
241
|
+
// directly (POSIX `rename(2)`, Windows `MoveFileExW`), so there is no
|
|
242
|
+
// unlink-before-rename gap in which a peer process that rotated in the
|
|
243
|
+
// meantime loses the 2 MB of history its backup just preserved.
|
|
244
|
+
await this.deps.fs.rename(this.filePath, this.rotatedFilePath);
|
|
245
|
+
} catch (err) {
|
|
246
|
+
// WHY: A peer Pi process sharing this log rotated `pi-mcp.log` first, so
|
|
247
|
+
// there is nothing to move — its backup is the one that stays. The append
|
|
248
|
+
// below recreates the file and writes the incoming line into it.
|
|
249
|
+
if (!isErrnoException(err, "ENOENT")) throw err;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** True when `err` is a Node.js errno exception carrying `code`. */
|
|
255
|
+
function isErrnoException(err: unknown, code: string): boolean {
|
|
256
|
+
return (err as NodeJS.ErrnoException | null)?.code === code;
|
|
180
257
|
}
|
|
181
258
|
|
|
182
259
|
// ─── Diagnostic Sink ──────────────────────────────────────────────────────────
|
package/src/tool-bridge.ts
CHANGED
|
@@ -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
|
-
|
|
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);
|