pi-mcp-extension 1.14.2 → 1.14.4
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 +2 -2
- package/package.json +1 -1
- package/src/debug-log.ts +100 -23
- package/src/stdio-process.ts +92 -41
package/README.md
CHANGED
|
@@ -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`)
|
|
@@ -378,7 +378,7 @@ flowchart TD
|
|
|
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
|
|
380
380
|
9. **`list_changed` notifications** trigger re-discovery, deactivating stale tools automatically and invalidating the cached resource catalog
|
|
381
|
-
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` and pipe cleanup for `stdio` child processes)
|
|
381
|
+
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)
|
|
382
382
|
|
|
383
383
|
## MCP Spec Compliance
|
|
384
384
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-mcp-extension",
|
|
3
|
-
"version": "1.14.
|
|
3
|
+
"version": "1.14.4",
|
|
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/stdio-process.ts
CHANGED
|
@@ -450,63 +450,105 @@ function resolveDeps(deps?: Partial<StdioProcessDeps>): StdioProcessDeps {
|
|
|
450
450
|
};
|
|
451
451
|
}
|
|
452
452
|
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
453
|
+
/** What one `kill(2)` attempt reported about a PID. */
|
|
454
|
+
type PidSignalOutcome =
|
|
455
|
+
/** The signal was delivered: the PID resolves to a process this caller may signal. */
|
|
456
|
+
| "signalled"
|
|
457
|
+
/** ESRCH: nothing holds this PID any more. */
|
|
458
|
+
| "gone"
|
|
459
|
+
/** EPERM or another platform refusal: the PID is not this caller's to signal. */
|
|
460
|
+
| "denied";
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* POSIX liveness: a PID is alive while `kill(pid, 0)` fails with anything but ESRCH.
|
|
464
|
+
*
|
|
465
|
+
* WHY: EPERM means the PID is taken but belongs to a process this caller may not signal (a
|
|
466
|
+
* recycled PID under another uid, a sandboxed child, PID 1). A caller that asks only whether the
|
|
467
|
+
* PID is *occupied* must read that as occupied, not free; teardown asks the stricter
|
|
468
|
+
* `isPidSignalable` instead. Auth-lock's staleness check needs this reading too and keeps its own
|
|
469
|
+
* probe (`defaultIsPidAlive` in `src/auth-lock.ts`), so it does not call this one.
|
|
470
|
+
*/
|
|
471
|
+
export function isPidAlive(pid: number, deps?: Partial<Pick<StdioProcessDeps, "kill">>): boolean {
|
|
472
|
+
return signalPid(pid, 0, resolveDeps(deps)) !== "gone";
|
|
467
473
|
}
|
|
468
474
|
|
|
469
|
-
|
|
470
|
-
|
|
475
|
+
function signalPid(
|
|
476
|
+
pid: number,
|
|
477
|
+
signal: NodeJS.Signals | number,
|
|
478
|
+
d: StdioProcessDeps,
|
|
479
|
+
): PidSignalOutcome {
|
|
471
480
|
try {
|
|
472
481
|
d.kill(pid, signal);
|
|
473
|
-
return
|
|
482
|
+
return "signalled";
|
|
474
483
|
} catch (err) {
|
|
475
484
|
if ((err as NodeJS.ErrnoException).code === "ESRCH") {
|
|
476
|
-
return
|
|
485
|
+
return "gone";
|
|
477
486
|
}
|
|
478
487
|
// WHY: EPERM and platform refusals mean this PID cannot be signalled (a recycled PID
|
|
479
488
|
// or a sandboxed process). Teardown still has to signal the rest of the tree within
|
|
480
489
|
// the bounded wait instead of rejecting the caller's shutdown path.
|
|
481
|
-
return
|
|
490
|
+
return "denied";
|
|
482
491
|
}
|
|
483
492
|
}
|
|
484
493
|
|
|
494
|
+
/**
|
|
495
|
+
* A PID this teardown can still act on: alive *and* signalable.
|
|
496
|
+
*
|
|
497
|
+
* WHY: a PID the caller cannot signal is not one a bounded wait can make progress on. `EPERM`
|
|
498
|
+
* means no signal of ours reaches that PID — the child has exited and the PID was recycled to a
|
|
499
|
+
* process under another uid, the child changed credentials (a wrapper that `setuid`s), or a
|
|
500
|
+
* policy layer refuses the signal — so polling it re-reads the same `EPERM` every 25ms until
|
|
501
|
+
* the timeout, and escalating to SIGKILL only buys a second refused signal.
|
|
502
|
+
*
|
|
503
|
+
* This answers "can we still reach it", never "is it our child": a PID recycled to another
|
|
504
|
+
* process of the *same* uid stays signalable and is signalled, exactly as before this guard
|
|
505
|
+
* existed. Identity would need the child's start time compared against `/proc/<pid>/stat`, and
|
|
506
|
+
* the `ChildProcess` handle is gone by the time teardown runs.
|
|
507
|
+
*/
|
|
508
|
+
function isPidSignalable(pid: number, d: StdioProcessDeps): boolean {
|
|
509
|
+
return signalPid(pid, 0, d) === "signalled";
|
|
510
|
+
}
|
|
511
|
+
|
|
485
512
|
function allExited(pids: readonly number[], d: StdioProcessDeps): boolean {
|
|
486
|
-
return pids.every((pid) => !
|
|
513
|
+
return pids.every((pid) => !isPidSignalable(pid, d));
|
|
487
514
|
}
|
|
488
515
|
|
|
516
|
+
/**
|
|
517
|
+
* Send `signal` to the PIDs that accept it, then wait only for those to exit.
|
|
518
|
+
*
|
|
519
|
+
* Resolves `true` when nothing that could still be running is left, which is what gates the
|
|
520
|
+
* SIGKILL escalation. A PID that reported ESRCH is gone, and one that reported EPERM is not
|
|
521
|
+
* ours to wait for — but it is not assumed dead either.
|
|
522
|
+
*/
|
|
489
523
|
async function signalAndWaitForExit(
|
|
490
524
|
pids: readonly number[],
|
|
491
525
|
signal: NodeJS.Signals,
|
|
492
526
|
timeoutMs: number,
|
|
493
527
|
d: StdioProcessDeps,
|
|
494
528
|
): Promise<boolean> {
|
|
495
|
-
const
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
529
|
+
const attempts = pids.map((pid) => ({ pid, outcome: signalPid(pid, signal, d) }));
|
|
530
|
+
const signalled = attempts.filter((a) => a.outcome === "signalled").map((a) => a.pid);
|
|
531
|
+
const refused = attempts.filter((a) => a.outcome === "denied").map((a) => a.pid);
|
|
532
|
+
|
|
533
|
+
// A window can only be ended by a signal that was actually delivered, so nothing is waited
|
|
534
|
+
// for when nothing was. (The refused targets still decide the result below.)
|
|
535
|
+
if (signalled.length > 0) {
|
|
536
|
+
const deadline = d.now() + timeoutMs;
|
|
537
|
+
while (d.now() < deadline && !allExited(signalled, d)) {
|
|
538
|
+
await d.sleep(25);
|
|
505
539
|
}
|
|
506
|
-
await d.sleep(25);
|
|
507
540
|
}
|
|
508
541
|
|
|
509
|
-
|
|
542
|
+
// WHY: a refused signal is not proof of a dead target. Permission is mediated per signal on
|
|
543
|
+
// some systems — SELinux keeps separate `sigterm`/`sigkill` permissions, AppArmor matches a
|
|
544
|
+
// signal set, and a seccomp filter can match the signal argument — so SIGTERM can be refused
|
|
545
|
+
// while SIGKILL is allowed. A refused target that a liveness probe still finds signalable
|
|
546
|
+
// therefore keeps the tree alive and sends the caller straight to the SIGKILL escalation,
|
|
547
|
+
// without paying for a wait window this signal can never end; one that is no longer
|
|
548
|
+
// signalable is out of reach (recycled to another uid, or the child changed credentials) and
|
|
549
|
+
// counts as gone. ESRCH targets are never re-probed: that verdict is final, and re-probing a
|
|
550
|
+
// recycled PID could sign it up for a SIGKILL it has nothing to do with.
|
|
551
|
+
return allExited(signalled, d) && !refused.some((pid) => isPidSignalable(pid, d));
|
|
510
552
|
}
|
|
511
553
|
|
|
512
554
|
/**
|
|
@@ -523,9 +565,9 @@ async function escalateToSigkill(
|
|
|
523
565
|
): Promise<void> {
|
|
524
566
|
const rescanned = await d.listDescendantPids(rootPid);
|
|
525
567
|
const survivors = [...new Set([...rescanned, ...descendants])].filter((candidate) =>
|
|
526
|
-
|
|
568
|
+
isPidSignalable(candidate, d),
|
|
527
569
|
);
|
|
528
|
-
const targets = [...survivors, rootPid].filter((candidate) =>
|
|
570
|
+
const targets = [...survivors, rootPid].filter((candidate) => isPidSignalable(candidate, d));
|
|
529
571
|
if (targets.length === 0) return;
|
|
530
572
|
await signalAndWaitForExit(targets, "SIGKILL", 200, d);
|
|
531
573
|
}
|
|
@@ -535,16 +577,25 @@ export async function ensurePidTerminated(
|
|
|
535
577
|
deps?: Partial<StdioProcessDeps>,
|
|
536
578
|
): Promise<void> {
|
|
537
579
|
const d = resolveDeps(deps);
|
|
538
|
-
if (!pid
|
|
539
|
-
|
|
540
|
-
|
|
580
|
+
if (!pid) return;
|
|
581
|
+
const root = signalPid(pid, 0, d);
|
|
582
|
+
// WHY: ESRCH is the only verdict that says the PID is free — nothing to snapshot, nothing to
|
|
583
|
+
// signal. EPERM does not describe the tree: the root may be out of reach while descendants
|
|
584
|
+
// are ours (a privileged wrapper that dropped to our uid for the real server), so they are
|
|
585
|
+
// still signalled below.
|
|
586
|
+
if (root === "gone") return;
|
|
541
587
|
|
|
542
588
|
// WHY: Snapshot before signalling any PID: a wrapper that exits first re-parents its
|
|
543
|
-
// children to init, after which they can no longer be found by parent PID.
|
|
589
|
+
// children to init, after which they can no longer be found by parent PID. The snapshot runs
|
|
590
|
+
// even for an out-of-reach root, because that root may still own signalable descendants.
|
|
544
591
|
const descendants = await d.listDescendantPids(pid);
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
592
|
+
const targets = descendants.filter((candidate) => isPidSignalable(candidate, d));
|
|
593
|
+
// WHY: a root nobody can signal is skipped as a target — no wait window can end it — but it
|
|
594
|
+
// must not hide the descendants that a signal can still reach.
|
|
595
|
+
if (root === "signalled") targets.push(pid);
|
|
596
|
+
if (targets.length === 0) return;
|
|
597
|
+
|
|
598
|
+
if (await signalAndWaitForExit(targets, "SIGTERM", 500, d)) return;
|
|
548
599
|
|
|
549
600
|
await escalateToSigkill(pid, descendants, d);
|
|
550
601
|
}
|