pi-mcp-extension 1.11.6 → 1.11.8

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
@@ -274,7 +274,7 @@ The log is written to `<agent dir>/logs/pi-mcp.log` (JSON Lines, one event per l
274
274
  - **Off by default.** Without `PI_MCP_DEBUG=1` no log file is created.
275
275
  - **Private.** The directory is `0o700` and the file is `0o600`, like the OAuth credential files.
276
276
  - **Bounded.** The file is rotated to `pi-mcp.log.1` at ~2 MB; a single backup is kept.
277
- - **Redacted.** Only allow-listed field names are recorded, and a final pass masks anything that looks like a token (`access_token`, `refresh_token`, `client_secret`, `code=`, `code_verifier`, `Authorization:` / `Bearer …`).
277
+ - **Redacted.** Only allow-listed field names are recorded, and a final pass masks anything that looks like a credential: OAuth tokens, codes, and PKCE verifiers, plus API keys and other key/value or JSON secrets (`api_key`, `x-api-key`, `private_key`, `password`, `secret`, `token`, and prefixed forms such as `db_password`), credential-bearing query parameters on a server URL (`?api_key=…`, `?token=…`), `Authorization` headers in any scheme and quoting (including the JSON `"Authorization": "…"` form), and URL userinfo passwords (`https://user:password@host`). A value is masked up to its own delimiter, so a quoted secret keeps its quotes, an object value is masked whole, and text after a closing bracket (`… [REDACTED]) 401`, `… [REDACTED]] 401`) survives. The mask is idempotent and never touches a sentence that merely mentions a credential word (`Unexpected token <`); a word directly after a credential key is masked, because the redactor cannot tell a value from prose and masks on the safe side. The same mask applies to the per-server stderr buffer, the `Last error:` line that `/mcp <name>` shows and `getServerLogs` returns, and user-facing start/auth/recovery failure notifications.
278
278
  - **Best-effort.** A failed log write never breaks a connection or a tool call.
279
279
 
280
280
  Attach the file to a bug report. It contains no credentials.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mcp-extension",
3
- "version": "1.11.6",
3
+ "version": "1.11.8",
4
4
  "description": "MCP (Model Context Protocol) client extension for the Pi coding agent — connect Pi to any MCP server",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -335,6 +335,26 @@ export class ConnectionCoordinator {
335
335
  turn.release();
336
336
  }
337
337
 
338
+ private async _startEagerServer(
339
+ name: string,
340
+ cfg: ServerConfig,
341
+ ctx: ExtensionContext,
342
+ authRequiredServers: Set<string>,
343
+ ): Promise<void> {
344
+ try {
345
+ await this.deps.manager.startServer(name, ctx.cwd);
346
+ } catch (err) {
347
+ if (err instanceof AuthRequiredError && cfg.auth && ctx.hasUI) {
348
+ authRequiredServers.add(name);
349
+ return;
350
+ }
351
+ // WHY: A cancelled start means the user stopped the server (/mcp:stop) or the
352
+ // session is tearing down; _notifyStartupFailure ignores AuthCancelledError so
353
+ // it is not reported as a bogus start failure.
354
+ this._notifyStartupFailure(name, ctx, err);
355
+ }
356
+ }
357
+
338
358
  async startEagerServers(
339
359
  serversToStart: Array<[string, ServerConfig]>,
340
360
  ctx: ExtensionContext,
@@ -344,21 +364,7 @@ export class ConnectionCoordinator {
344
364
 
345
365
  // Start all eager servers concurrently
346
366
  await Promise.allSettled(
347
- serversToStart.map(async ([name, cfg]) => {
348
- try {
349
- await this.deps.manager.startServer(name, ctx.cwd);
350
- } catch (err) {
351
- // WHY: A cancelled start means the user stopped the server (/mcp:stop) or the
352
- // session is tearing down; reporting it as a start failure would be a bogus error.
353
- if (err instanceof AuthCancelledError) return;
354
- if (err instanceof AuthRequiredError && cfg.auth && ctx.hasUI) {
355
- authRequiredServers.add(name);
356
- return;
357
- }
358
- const msg = formatErrorMessage(err);
359
- ctx.ui.notify(`pi-mcp: Failed to start ${name} — ${msg}`, "error");
360
- }
361
- }),
367
+ serversToStart.map(([name, cfg]) => this._startEagerServer(name, cfg, ctx, authRequiredServers)),
362
368
  );
363
369
 
364
370
  // WHY: Reconcile the footer hint once every eager start has settled — a declined
@@ -58,21 +58,236 @@ const SAFE_FIELD_NAME_SET = new Set(SAFE_FIELD_NAMES);
58
58
 
59
59
  // ─── Redaction ────────────────────────────────────────────────────────────────
60
60
 
61
- /** `access_token=…`, `"refresh_token":"…"`, `clientSecret: …`, `code_verifier=…`. */
62
- const SECRET_KEY_PATTERN =
63
- /("?\b(?:access_token|accessToken|refresh_token|refreshToken|client_secret|clientSecret|code_verifier|codeVerifier|id_token|idToken|authorization_code|authorizationCode|registration_access_token)\b"?\s*[:=]\s*"?)[^"\s,;&}]*/gi;
61
+ /** Credential names that appear before `:`/`=` in JSON, key-value, or header text. */
62
+ const SECRET_KEY_NAME =
63
+ "access[_-]?token|refresh[_-]?token|id[_-]?token|registration[_-]?access[_-]?token" +
64
+ "|authorization[_-]?code|code[_-]?verifier|client[_-]?secret|x[_-]?api[_-]?key" +
65
+ "|api[_-]?key|private[_-]?key|secret[_-]?key|secret[_-]?access[_-]?key" +
66
+ "|password|passwd|secret|token";
64
67
 
65
- /** `?code=…`, `&access_token=…` — query parameters of an OAuth redirect. */
66
- const QUERY_SECRET_PATTERN =
67
- /([?&](?:code|code_verifier|codeVerifier|client_secret|access_token|refresh_token)=)[^&\s"']*/gi;
68
+ /** Credential-bearing query parameters on a server URL. */
69
+ const QUERY_SECRET_NAME =
70
+ "access[_-]?token|refresh[_-]?token|id[_-]?token|client[_-]?secret|code[_-]?verifier" +
71
+ "|api[_-]?key|x[_-]?api[_-]?key|token|key|secret|password|passwd|auth(?:orization)?|code";
68
72
 
69
- /** `Authorization: Bearer …` / `authorization=Basic …`. */
70
- const AUTHORIZATION_PATTERN =
71
- /(\bauthorization\b\s*[:=]\s*)((?:bearer|basic|digest)\s+)[^\s,;"']*/gi;
73
+ /** An optional quote — `"`, `'`, or the JSON-escaped form — around a key name. */
74
+ const QUOTE = String.raw`(?:\\?["'])?`;
75
+
76
+ /**
77
+ * A credential key and its separator. A key may be a compound name (`db_password`,
78
+ * `aws_secret_access_key`), so the leading boundary rejects only an alphanumeric
79
+ * predecessor — `\b` also rejects `_` and would miss every prefixed name.
80
+ *
81
+ * The value is deliberately not part of the match: `maskCredentialValues` reads it from the
82
+ * text so the mask can honour the value's own delimiter (see `readCredentialValue`).
83
+ */
84
+ const SECRET_KEY_PATTERN = new RegExp(
85
+ String.raw`(${QUOTE}(?<![A-Za-z0-9])(?:${SECRET_KEY_NAME})\b${QUOTE}\s*[:=]\s*)`,
86
+ "gi",
87
+ );
88
+
89
+ /**
90
+ * `?code=…`, `&api_key=…`, `?token=…` — query parameters on a server URL. Matched as a
91
+ * key/separator prefix so `maskCredentialValues` applies the same delimiter-aware value reader
92
+ * as `SECRET_KEY_PATTERN` (preserving apostrophes inside a secret and stopping before closing
93
+ * quotes, brackets, or the next `&name=` parameter).
94
+ */
95
+ const QUERY_SECRET_PATTERN = new RegExp(
96
+ String.raw`([?&](?:[A-Za-z0-9_.\-]*[_-])?(?:${QUERY_SECRET_NAME})=)`,
97
+ "gi",
98
+ );
99
+
100
+ /**
101
+ * `Authorization: Bearer …`, `authorization=Basic …`, `"Authorization":"Token …"`, and the
102
+ * scheme-less `Authorization: …` form. A known scheme name is kept; any other leading token
103
+ * is masked together with the value, because a scheme-less credential may contain spaces.
104
+ */
105
+ const AUTHORIZATION_PATTERN = new RegExp(
106
+ String.raw`(${QUOTE}(?<![A-Za-z0-9])authorization\b${QUOTE}\s*[:=]\s*(?:(?:bearer|basic|digest|token|apikey|dpop|oauth|negotiate)\s+)?)`,
107
+ "gi",
108
+ );
72
109
 
73
110
  /** A bare `Bearer <token>` anywhere in the text. */
74
111
  const BEARER_PATTERN = /\b(bearer|basic)\s+[A-Za-z0-9\-._~+/=]{8,}/gi;
75
112
 
113
+ /** `https://user:password@mcp.example.com/mcp` — userinfo credentials in a URL. */
114
+ const URL_CREDENTIALS_PATTERN = /(https?:\/\/[^/\s?#@:"']+:)[^/\s?#@]+(@)/gi;
115
+
116
+ /**
117
+ * Characters that end an unquoted credential value. Brackets (`()`, `{}`, `[]`), double quotes,
118
+ * and backslash escapes (`\"`) terminate so a mask never swallows an enclosing JSON string or
119
+ * bracketed clause.
120
+ */
121
+ const UNQUOTED_VALUE_TERMINATORS = new Set([
122
+ " ",
123
+ "\t",
124
+ "\n",
125
+ "\r",
126
+ "\f",
127
+ "\v",
128
+ ";",
129
+ ",",
130
+ "{",
131
+ "}",
132
+ "(",
133
+ ")",
134
+ "[",
135
+ "]",
136
+ '"',
137
+ "\\",
138
+ ]);
139
+
140
+ /**
141
+ * Characters that end an unquoted Authorization value. Whitespace is not a terminator: an
142
+ * unknown scheme's value can contain spaces, and stopping at the first one would mask the
143
+ * scheme token and leave the credential behind it in the log. Brackets and quotes still
144
+ * terminate, so `(Authorization: ApiKey …) 401` and `[Authorization: Bearer …] 401` keep the
145
+ * status code that follows the credential.
146
+ */
147
+ const AUTHORIZATION_VALUE_TERMINATORS = new Set([
148
+ "\n",
149
+ "\r",
150
+ ";",
151
+ ",",
152
+ "(",
153
+ ")",
154
+ "{",
155
+ "}",
156
+ "[",
157
+ "]",
158
+ '"',
159
+ "\\",
160
+ ]);
161
+
162
+ /** `&name=` — a query separator rather than part of an unquoted value. */
163
+ const QUERY_SEPARATOR_PATTERN = /&[A-Za-z0-9_.\-]+=/y;
164
+
165
+ /** A credential value located in the text: where it ends and the delimiter to re-emit. */
166
+ interface CredentialValue {
167
+ end: number;
168
+ delimiter: string;
169
+ }
170
+
171
+ /**
172
+ * Return the quote delimiter (`"`, `'`, `\"`, or `\'`) that opens at `index`, or `undefined`
173
+ * when `index` does not start a quoted string.
174
+ */
175
+ function openingQuoteAt(text: string, index: number): string | undefined {
176
+ const char = text.charAt(index);
177
+ if (char === '"' || char === "'") return char;
178
+ const next = char === "\\" ? text.charAt(index + 1) : "";
179
+ return next === '"' || next === "'" ? text.slice(index, index + 2) : undefined;
180
+ }
181
+
182
+ /**
183
+ * A quoted value runs from its opening delimiter (`"`, `'`, `\"`, or `\'`) to the matching one,
184
+ * or to the end of the text when unterminated. Backslash escapes inside the string are skipped.
185
+ */
186
+ function readQuotedValue(text: string, start: number, opening: string): CredentialValue {
187
+ let index = start + opening.length;
188
+ while (index < text.length) {
189
+ if (text.startsWith(opening, index)) return { end: index + opening.length, delimiter: opening };
190
+ index += text.charAt(index) === "\\" ? 2 : 1;
191
+ }
192
+ return { end: text.length, delimiter: opening };
193
+ }
194
+
195
+ /**
196
+ * A `{`/`[` value runs to its matching bracket, so a nested credential object or array is masked
197
+ * as one unit. Quoted strings (including JSON-escaped `\"...\"`) inside it are skipped, or a
198
+ * bracket inside a string value would close the structure early and leave the rest of the secret
199
+ * in the log.
200
+ */
201
+ function readStructuredValue(text: string, start: number, opening: string): CredentialValue {
202
+ const closing = opening === "{" ? "}" : "]";
203
+ let depth = 0;
204
+ let index = start;
205
+ while (index < text.length) {
206
+ const quote = openingQuoteAt(text, index);
207
+ if (quote) {
208
+ index = readQuotedValue(text, index, quote).end;
209
+ continue;
210
+ }
211
+ const char = text.charAt(index);
212
+ if (char === opening) {
213
+ depth += 1;
214
+ } else if (char === closing) {
215
+ depth -= 1;
216
+ if (depth === 0) return { end: index + 1, delimiter: "" };
217
+ }
218
+ index += 1;
219
+ }
220
+ return { end: text.length, delimiter: "" };
221
+ }
222
+
223
+ /** An unquoted value runs to the next separator; `undefined` when there is nothing to mask. */
224
+ function readBareValue(
225
+ text: string,
226
+ start: number,
227
+ terminators: Set<string>,
228
+ ): CredentialValue | undefined {
229
+ let end = start;
230
+ while (end < text.length) {
231
+ const char = text.charAt(end);
232
+ if (terminators.has(char)) break;
233
+ if (char === "&") {
234
+ QUERY_SEPARATOR_PATTERN.lastIndex = end;
235
+ if (QUERY_SEPARATOR_PATTERN.test(text)) break;
236
+ }
237
+ end += 1;
238
+ }
239
+ return end > start ? { end, delimiter: "" } : undefined;
240
+ }
241
+
242
+ /**
243
+ * Read the credential value that starts at `start`, honouring its opening delimiter: a quoted
244
+ * value runs to its matching quote, a `{`/`[` value runs to its matching bracket, and an
245
+ * unquoted value runs to the next separator. Returns `undefined` when there is no value to mask.
246
+ */
247
+ function readCredentialValue(
248
+ text: string,
249
+ start: number,
250
+ terminators: Set<string> = UNQUOTED_VALUE_TERMINATORS,
251
+ ): CredentialValue | undefined {
252
+ // An out-of-range start yields an empty opening and falls through to `readBareValue`, which
253
+ // returns `undefined` for an empty value.
254
+ const quote = openingQuoteAt(text, start);
255
+ if (quote) return readQuotedValue(text, start, quote);
256
+ const opening = text.charAt(start);
257
+ if (opening === "{" || opening === "[") return readStructuredValue(text, start, opening);
258
+ return readBareValue(text, start, terminators);
259
+ }
260
+
261
+ /**
262
+ * Mask every credential value that follows a key/separator prefix matched by `pattern`.
263
+ *
264
+ * WHY a hand-written scan instead of one regex replacement: the mask has to stop where the
265
+ * value's delimiter says it stops. A single character class cannot tell an apostrophe inside an
266
+ * unquoted secret (`it's …`) from the closing quote of a quoted one, and it cannot consume a
267
+ * nested credential object (`{"token":{"value":"…"}}`) as one unit — both mistakes leave the
268
+ * tail of the secret in the log.
269
+ */
270
+ function maskCredentialValues(
271
+ text: string,
272
+ pattern: RegExp,
273
+ terminators: Set<string> = UNQUOTED_VALUE_TERMINATORS,
274
+ ): string {
275
+ pattern.lastIndex = 0;
276
+ let masked = "";
277
+ let cursor = 0;
278
+ let match: RegExpExecArray | null;
279
+ while ((match = pattern.exec(text)) !== null) {
280
+ const prefix = match[0];
281
+ const value = readCredentialValue(text, match.index + prefix.length, terminators);
282
+ if (!value) continue;
283
+ const mask = value.delimiter === "" ? "[REDACTED]" : `${value.delimiter}[REDACTED]${value.delimiter}`;
284
+ masked += text.slice(cursor, match.index) + prefix + mask;
285
+ cursor = value.end;
286
+ pattern.lastIndex = value.end;
287
+ }
288
+ return cursor === 0 ? text : masked + text.slice(cursor);
289
+ }
290
+
76
291
  /**
77
292
  * Mask token-like substrings in an already sanitized string.
78
293
  *
@@ -82,9 +297,14 @@ const BEARER_PATTERN = /\b(bearer|basic)\s+[A-Za-z0-9\-._~+/=]{8,}/gi;
82
297
  */
83
298
  export function redactSecrets(text: string): string {
84
299
  let out = text;
85
- out = out.replace(SECRET_KEY_PATTERN, "$1[REDACTED]");
86
- out = out.replace(QUERY_SECRET_PATTERN, "$1[REDACTED]");
87
- out = out.replace(AUTHORIZATION_PATTERN, "$1$2[REDACTED]");
300
+ out = out.replace(URL_CREDENTIALS_PATTERN, "$1[REDACTED]$2");
301
+ // WHY: `AUTHORIZATION_PATTERN` must run before `SECRET_KEY_PATTERN` because scheme names
302
+ // like `ApiKey` and `Token` are also in `SECRET_KEY_NAME`; if a credential after
303
+ // `Authorization: ApiKey ` starts with `=` or `:`, running `SECRET_KEY_PATTERN` first
304
+ // would treat `ApiKey =…` as a key/value pair and leave a double `[REDACTED][REDACTED]`.
305
+ out = maskCredentialValues(out, AUTHORIZATION_PATTERN, AUTHORIZATION_VALUE_TERMINATORS);
306
+ out = maskCredentialValues(out, SECRET_KEY_PATTERN);
307
+ out = maskCredentialValues(out, QUERY_SECRET_PATTERN);
88
308
  out = out.replace(BEARER_PATTERN, "$1 [REDACTED]");
89
309
  return out;
90
310
  }
@@ -14,6 +14,7 @@ import {
14
14
  type ConnectionCoordinator,
15
15
  formatErrorMessage,
16
16
  } from "./connection-coordinator.js";
17
+ import { sanitizeLogText } from "./debug-log.js";
17
18
  import { AuthCancelledError } from "./errors.js";
18
19
  import type { ManagedServer, ServerManager } from "./server-manager.js";
19
20
  import { lookupServerSource, type ConfigProvenance } from "./server-provenance.js";
@@ -136,7 +137,7 @@ async function handleMcpAuth(
136
137
  ctx.ui.notify(`pi-mcp: ${name} ready`, "info");
137
138
  } catch (err) {
138
139
  ctx.ui.notify(
139
- `pi-mcp: ${sanitizeTerminalText(err instanceof Error ? err.message : String(err))}`,
140
+ `pi-mcp: ${sanitizeLogText(err instanceof Error ? err.message : String(err), 500)}`,
140
141
  err instanceof AuthCancelledError ? "info" : "error",
141
142
  );
142
143
  }
@@ -27,7 +27,7 @@ import type { McpConfig, ServerConfig, Settings } from "./config.js";
27
27
  import { AuthRequiredError, getAuthStatus, resetAuth, invalidateStoredTokens } from "./oauth-provider.js";
28
28
  import type { ToolRefreshOptions } from "./tool-bridge.js";
29
29
  import { sanitizeTerminalText, type SanitizeTerminalTextOptions } from "./terminal-text.js";
30
- import { describeError, reportDiagnostic } from "./debug-log.js";
30
+ import { describeError, redactSecrets, reportDiagnostic, sanitizeLogText } from "./debug-log.js";
31
31
  import {
32
32
  destroyStdioStreams,
33
33
  ensurePidTerminated,
@@ -320,7 +320,7 @@ export class ServerManager {
320
320
  if (all.length === 0) return "pi-mcp: No servers configured (create ~/.pi/agent/mcp.json)";
321
321
  const lines = all.map((s) => {
322
322
  const icon = s.state === "ready" ? "✓" : s.state === "starting" ? "⟳" : "✗";
323
- const err = s.lastError ? ` — ${sanitizeTerminalText(s.lastError.message)}` : "";
323
+ const err = s.lastError ? ` — ${sanitizeLogText(s.lastError.message, 500)}` : "";
324
324
  return ` ${icon} ${s.name} (${s.state})${err}`;
325
325
  });
326
326
  const ready = all.filter((s) => s.state === "ready").length;
@@ -508,7 +508,11 @@ export class ServerManager {
508
508
  }
509
509
 
510
510
  private _appendStderr(server: ManagedServer, line: string): void {
511
- server.stderrLog.push(line);
511
+ // WHY: this buffer is what `/mcp <name>` prints as "Recent output" and what
512
+ // `getServerLogs` returns — text users paste into bug reports. A child server that echoes
513
+ // its own key on stderr must not surface it there, so mask credentials exactly as the
514
+ // debug log does. Redacting twice is a no-op.
515
+ server.stderrLog.push(redactSecrets(line));
512
516
  if (server.stderrLog.length > STDERR_BUFFER_SIZE) {
513
517
  server.stderrLog.shift();
514
518
  }
@@ -8,7 +8,7 @@
8
8
  */
9
9
 
10
10
  import type { ServerConfig } from "./config.js";
11
- import { describeError, reportDiagnostic } from "./debug-log.js";
11
+ import { describeError, reportDiagnostic, sanitizeLogText } from "./debug-log.js";
12
12
  import { McpError } from "./errors.js";
13
13
  import { AuthLockError, AuthRequiredError } from "./oauth-provider.js";
14
14
  import type { ManagedServer } from "./server-manager.js";
@@ -123,7 +123,9 @@ export function formatServerDetail(snapshot: ServerStatusSnapshot, provenance: C
123
123
  `Tools: ${snapshot.tools.active}/${snapshot.tools.discovered} active`,
124
124
  snapshot.auth === undefined ? undefined : `OAuth: ${snapshot.auth}`,
125
125
  formatProjectConfigNote(provenance),
126
- snapshot.lastError === null ? undefined : `Last error: ${sanitizeTerminalText(snapshot.lastError.message)}`,
126
+ // WHY: a connect/stream failure usually quotes the request URL, and that URL can carry a
127
+ // credential. This view is what users paste into an issue, so mask it like the log does.
128
+ snapshot.lastError === null ? undefined : `Last error: ${sanitizeLogText(snapshot.lastError.message, 500)}`,
127
129
  formatFailureHint(classifyFailure(snapshot.lastError), snapshot.name),
128
130
  ];
129
131
  return `${lines.filter(isDefined).join("\n")}\n\nRecent output:\n${snapshot.recentOutput}`;
@@ -8,6 +8,7 @@
8
8
  */
9
9
 
10
10
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
11
+ import { redactSecrets } from "./debug-log.js";
11
12
  import { McpError, AuthCancelledError } from "./errors.js";
12
13
  import { sanitizeTerminalText } from "./terminal-text.js";
13
14
 
@@ -16,7 +17,7 @@ export const startupAuthLaterOption = "Not now";
16
17
 
17
18
  export function formatErrorMessage(err: unknown): string {
18
19
  const msg = err instanceof McpError ? err.userMessage : err instanceof Error ? err.message : String(err);
19
- return sanitizeTerminalText(msg.replace(/^AuthRequiredError:\s*/, ""));
20
+ return redactSecrets(sanitizeTerminalText(msg.replace(/^AuthRequiredError:\s*/, "")));
20
21
  }
21
22
 
22
23
  // WHY: Allow an aborted waiter on authQueue to wake up and reject immediately without breaking
@@ -21,17 +21,33 @@ const execFileAsync = promisify(execFile);
21
21
 
22
22
  export interface LineSplitter {
23
23
  write(chunk: Buffer): void;
24
+ /** Emit the decoded remainder without finalising the decoder (teardown paths). */
25
+ flush(): void;
26
+ /** Finalise the decoder (real EOF) and emit whatever is left. Idempotent. */
24
27
  end(): void;
25
28
  }
26
29
 
27
30
  /**
28
- * Create a pure UTF-8 `StringDecoder`-based line splitter with idempotent `end()`.
31
+ * Create a pure UTF-8 `StringDecoder`-based line splitter with an idempotent `end()`.
32
+ *
33
+ * `flush()` and `end()` differ on purpose: `flush()` emits what has already been decoded and
34
+ * leaves an incomplete UTF-8 sequence buffered inside the decoder, while `end()` is terminal
35
+ * and replaces such a sequence with U+FFFD. Teardown uses `flush()` because bytes can still
36
+ * arrive after a forced close, and finalising the decoder first would turn a character split
37
+ * across that boundary into replacement characters.
29
38
  */
30
39
  export function createLineSplitter(onLine: (line: string) => void): LineSplitter {
31
40
  const decoder = new StringDecoder("utf8");
32
41
  let remainder = "";
33
42
  let flushed = false;
34
43
 
44
+ const emitRemainder = (): void => {
45
+ if (!remainder) return;
46
+ const trailing = remainder;
47
+ remainder = "";
48
+ onLine(trailing);
49
+ };
50
+
35
51
  return {
36
52
  write(chunk: Buffer): void {
37
53
  flushed = false;
@@ -42,15 +58,14 @@ export function createLineSplitter(onLine: (line: string) => void): LineSplitter
42
58
  onLine(rawLine);
43
59
  }
44
60
  },
61
+ flush(): void {
62
+ emitRemainder();
63
+ },
45
64
  end(): void {
46
65
  if (flushed) return;
47
66
  flushed = true;
48
67
  remainder += decoder.end();
49
- if (remainder) {
50
- const trailing = remainder;
51
- remainder = "";
52
- onLine(trailing);
53
- }
68
+ emitRemainder();
54
69
  },
55
70
  };
56
71
  }
@@ -60,6 +75,16 @@ export function createLineSplitter(onLine: (line: string) => void): LineSplitter
60
75
  /** Grace window for an exited child's pipes to drain naturally before force-destroying them. */
61
76
  const PIPE_DRAIN_GRACE_MS = 100;
62
77
 
78
+ /**
79
+ * How long a closed transport's stderr stream must stay quiet before its unterminated remainder
80
+ * is emitted.
81
+ *
82
+ * WHY: nothing ends the SDK's stderr `PassThrough` after close, so the last line has to be
83
+ * released by us; waiting for silence instead of flushing each chunk keeps a line whole when its
84
+ * bytes arrive across several ticks, and still surfaces the last one promptly.
85
+ */
86
+ export const POST_CLOSE_FLUSH_DELAY_MS = 100;
87
+
63
88
  interface StdioChildRecord {
64
89
  process: ChildProcess;
65
90
  closed: boolean;
@@ -76,6 +101,81 @@ interface StdioChildRecord {
76
101
  */
77
102
  const childRecords = new WeakMap<object, StdioChildRecord>();
78
103
 
104
+ /** A transport whose child stderr can be wired and whose `close()` can be wrapped. */
105
+ interface StderrCarrier {
106
+ stderr?: unknown;
107
+ close(): Promise<void>;
108
+ }
109
+
110
+ /**
111
+ * Split a stdio transport's stderr into lines and make them survive `close()`.
112
+ *
113
+ * Returns the provisional flush that teardown paths call before destroying the pipes, or
114
+ * `null` when the transport has no stderr stream to read.
115
+ *
116
+ * WHY: `StdioClientTransport.close()` never ends its stderr `PassThrough` — it only waits
117
+ * (bounded) for the child's `'close'` event — and a descendant that inherited the stderr write
118
+ * end keeps that event from firing. A line written without a trailing newline would then stay
119
+ * in the splitter's remainder forever. Flushing when close settles, and again after
120
+ * `POST_CLOSE_FLUSH_DELAY_MS` of silence for any chunks that arrive afterwards (nothing will
121
+ * emit `'end'` to do it), keeps the child's last words.
122
+ * Both flushes are provisional: they must not finalise the decoder, because the bytes of a
123
+ * character can be split across the close boundary; only the stream's own `'end'`/`'close'`
124
+ * finalises it.
125
+ */
126
+ export function instrumentStderr(
127
+ transport: StderrCarrier,
128
+ onLine: (line: string) => void,
129
+ ): (() => void) | null {
130
+ const stream = transport.stderr as NodeJS.EventEmitter | null | undefined;
131
+ if (!stream || typeof stream.on !== "function") return null;
132
+
133
+ const splitter = createLineSplitter(onLine);
134
+ let closed = false;
135
+ let idleFlush: NodeJS.Timeout | null = null;
136
+ const cancelIdleFlush = (): void => {
137
+ if (idleFlush) {
138
+ clearTimeout(idleFlush);
139
+ idleFlush = null;
140
+ }
141
+ };
142
+ const flush = (): void => {
143
+ cancelIdleFlush();
144
+ splitter.flush();
145
+ };
146
+ // WHY: after close settles nothing emits 'end', so a remainder nobody else will flush has to be
147
+ // released — but a single chunk boundary is not the end of a line. Waiting for the stream to go
148
+ // quiet keeps a line whose chunks straddle several ticks whole, while still surfacing the last
149
+ // unterminated one within POST_CLOSE_FLUSH_DELAY_MS.
150
+ const scheduleIdleFlush = (): void => {
151
+ cancelIdleFlush();
152
+ idleFlush = setTimeout(() => {
153
+ idleFlush = null;
154
+ splitter.flush();
155
+ }, POST_CLOSE_FLUSH_DELAY_MS);
156
+ idleFlush.unref();
157
+ };
158
+
159
+ stream.on("data", (chunk: Buffer) => {
160
+ splitter.write(chunk);
161
+ if (closed) scheduleIdleFlush();
162
+ });
163
+ const onStreamEnd = (): void => {
164
+ cancelIdleFlush();
165
+ splitter.end();
166
+ };
167
+ stream.on("end", onStreamEnd);
168
+ stream.on("close", onStreamEnd);
169
+
170
+ const origClose = transport.close.bind(transport);
171
+ transport.close = (): Promise<void> =>
172
+ origClose().finally(() => {
173
+ closed = true;
174
+ flush();
175
+ });
176
+ return flush;
177
+ }
178
+
79
179
  export interface InstrumentStdioTransportOptions {
80
180
  onPid(pid: number): void;
81
181
  onStderrLine(line: string): void;
@@ -83,8 +183,7 @@ export interface InstrumentStdioTransportOptions {
83
183
 
84
184
  /**
85
185
  * Wrap a `StdioClientTransport` to capture its child PID as soon as it spawns,
86
- * memoize `close()` across duplicate calls, and wire `stderr` through
87
- * `createLineSplitter`.
186
+ * memoize `close()` across duplicate calls, and wire `stderr` through `instrumentStderr`.
88
187
  */
89
188
  export function instrumentStdioTransport(
90
189
  transport: StdioClientTransport,
@@ -96,7 +195,9 @@ export function instrumentStdioTransport(
96
195
  const spawnedProcess = (): ChildProcess | undefined =>
97
196
  (transport as unknown as { _process?: ChildProcess })._process;
98
197
 
99
- let flushStderr: (() => void) | null = null;
198
+ // Wire stderr first: `instrumentStderr` wraps `close()` with the flush, and the memoization
199
+ // below has to sit on top of that wrapper.
200
+ const flushStderr = instrumentStderr(transport, onStderrLine);
100
201
 
101
202
  const recordProcess = (proc: ChildProcess | undefined): void => {
102
203
  if (!proc?.pid) return;
@@ -138,19 +239,6 @@ export function instrumentStdioTransport(
138
239
  }
139
240
  return closePromise;
140
241
  };
141
-
142
- if (transport.stderr) {
143
- const splitter = createLineSplitter(onStderrLine);
144
- transport.stderr.on("data", (chunk: Buffer) => {
145
- splitter.write(chunk);
146
- });
147
- const flush = (): void => {
148
- splitter.end();
149
- };
150
- flushStderr = flush;
151
- transport.stderr.on("end", flush);
152
- transport.stderr.on("close", flush);
153
- }
154
242
  }
155
243
 
156
244
  /**
@@ -464,9 +464,12 @@ export class ToolBridge {
464
464
  ): void {
465
465
  const annotations = tool.annotations;
466
466
  const description = buildToolDescription(tool, annotations);
467
- const notifyAuthError = (err: unknown) => this.onAuthError?.(serverName, err);
468
467
  const runTool = (params: unknown, signal: AbortSignal | undefined) =>
469
468
  this._executeToolCall(serverName, tool.name, client, params, signal);
469
+ // WHY: `execute` runs with `this` bound to the registered-tool literal rather than the
470
+ // bridge, so the rethrow helper is reached through a captured closure.
471
+ const rethrowToolCallError = (err: unknown): Promise<never> =>
472
+ this._rethrowToolCallError(serverName, err);
470
473
 
471
474
  this.pi.registerTool({
472
475
  name: piName,
@@ -479,24 +482,34 @@ export class ToolBridge {
479
482
  try {
480
483
  return await runTool(params, signal);
481
484
  } catch (err) {
482
- if (err instanceof McpError) throw err;
483
- if (isOAuthUnauthorizedError(err)) {
484
- await notifyAuthError(err);
485
- }
486
- // Protocol-level errors (JSON-RPC error response, malformed payload) keep
487
- // "protocol"; an SDK request timeout keeps its own code so callers can tell
488
- // "the server answered badly" from "the server did not answer in time" (#209).
489
- throw new McpError(
490
- err instanceof Error ? err.message : String(err),
491
- serverName,
492
- isSdkTimeoutError(err) ? "timeout" : "protocol",
493
- err,
494
- );
485
+ return await rethrowToolCallError(err);
495
486
  }
496
487
  },
497
488
  });
498
489
  }
499
490
 
491
+ /**
492
+ * Normalize a `tools/call` failure into the `McpError` callers see, after notifying the
493
+ * OAuth handler when the failure means the server needs authorization.
494
+ */
495
+ private async _rethrowToolCallError(serverName: string, err: unknown): Promise<never> {
496
+ if (err instanceof McpError) throw err;
497
+ if (isOAuthUnauthorizedError(err)) {
498
+ // WHY: read the handler through `this` at call time — src/index.ts installs it after the
499
+ // bridge is constructed, and it is the caller for every server, so it takes the name.
500
+ await this.onAuthError?.(serverName, err);
501
+ }
502
+ // Protocol-level errors (JSON-RPC error response, malformed payload) keep
503
+ // "protocol"; an SDK request timeout keeps its own code so callers can tell
504
+ // "the server answered badly" from "the server did not answer in time" (#209).
505
+ throw new McpError(
506
+ err instanceof Error ? err.message : String(err),
507
+ serverName,
508
+ isSdkTimeoutError(err) ? "timeout" : "protocol",
509
+ err,
510
+ );
511
+ }
512
+
500
513
  /**
501
514
  * Run one `tools/call`: dispatch through the SDK client, convert the result
502
515
  * into Pi content blocks, and surface `isError` as `McpError(..., "tool")`.
@@ -18,7 +18,7 @@ import type { ServerConfig } from "./config.js";
18
18
  import { McpOAuthProvider } from "./oauth-provider.js";
19
19
  import { isAuthorizationHeader, stripAuthorizationHeader } from "./auth-challenge.js";
20
20
  import { reportDiagnostic } from "./debug-log.js";
21
- import { createLineSplitter } from "./stdio-process.js";
21
+ import { instrumentStderr } from "./stdio-process.js";
22
22
  import { sanitizeTerminalText } from "./terminal-text.js";
23
23
 
24
24
  function resolveEnv(extra?: Record<string, string>): Record<string, string> {
@@ -55,20 +55,18 @@ function createOAuthProvider(
55
55
  });
56
56
  }
57
57
 
58
+ /**
59
+ * Route a `createTransport(..., onStderr)` caller's stderr through the shared instrumentation.
60
+ *
61
+ * WHY: this used to keep its own line splitter that only flushed on the stream's 'end'/'close',
62
+ * so on this path a partial line written before a close was dropped — the same defect
63
+ * `instrumentStderr` fixes for `ServerManager` (#206).
64
+ */
58
65
  function wireStdioStderr(transport: StdioClientTransport, onStderr: (line: string) => void): void {
59
- if (!transport.stderr) return;
60
- const splitter = createLineSplitter((rawLine) => {
66
+ instrumentStderr(transport, (rawLine) => {
61
67
  const clean = sanitizeTerminalText(rawLine);
62
68
  if (clean) onStderr(clean);
63
69
  });
64
- transport.stderr.on("data", (chunk: Buffer) => {
65
- splitter.write(chunk);
66
- });
67
- const flush = (): void => {
68
- splitter.end();
69
- };
70
- transport.stderr.on("end", flush);
71
- transport.stderr.on("close", flush);
72
70
  }
73
71
 
74
72
  /** Expand a leading `~` / `~/` / `~\` to the home directory, the way Pi resolves a config `cwd`. */