pi-mcp-extension 1.11.7 → 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.7",
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": [
@@ -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
@@ -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")`.