pi-mcp-extension 1.11.5 → 1.11.7

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
@@ -163,7 +163,7 @@ For Pi 1.x compatibility, server entries also accept `type` as an alias for `tra
163
163
  | `cwd` | `string` | session working directory | Working directory for a `stdio` server (rejected on `streamable-http` / `sse`). A relative path resolves against the session working directory and a leading `~` expands to your home directory |
164
164
  | `env` | `Record<string, string>` | — | Extra environment variables for the child process (literal values, no `${VAR}` interpolation) |
165
165
  | `url` | `string` | — | Server URL (**required** for `streamable-http` and `sse`) |
166
- | `headers` | `Record<string, string>` | — | Static headers sent with `streamable-http` and `sse` requests |
166
+ | `headers` | `Record<string, string>` | — | Static headers sent with `streamable-http` and `sse` requests. When `auth` is set, OAuth owns `Authorization`, so an `Authorization` entry here is ignored (other headers still apply) |
167
167
  | `auth` (or `oauth`) | `object` | — | OAuth 2.1 configuration described below and in [OAUTH.md](./OAUTH.md) (`streamable-http` / `sse` only) |
168
168
  | `lifecycle` | `"eager" \| "lazy"` | `"lazy"` (`"eager"` for `pi.registerMcpServer()` unless `enabled: false`) | `eager` = auto-start on `session_start`, `lazy` = connect on request via `mcp_connect`, `/mcp:start`, or `/mcp:auth` |
169
169
  | `enabled` | `boolean` | `true` | Pi 1.3.0 switch: `false` keeps the entry configured but out of the eager set (normalized to `lifecycle: "lazy"`, even when `lifecycle: "eager"` is also set) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mcp-extension",
3
- "version": "1.11.5",
3
+ "version": "1.11.7",
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": [
@@ -20,6 +20,31 @@ export interface ManualAuthChallengeOptions {
20
20
  signal?: AbortSignal | undefined;
21
21
  }
22
22
 
23
+ /**
24
+ * Drop any `Authorization` header (any casing) from a configured static header set.
25
+ *
26
+ * WHY: `Authorization` is the one header an OAuth server owns. The MCP SDK builds it from the
27
+ * OAuth provider's access token and then spreads `requestInit.headers` on top, so an exact-case
28
+ * `Authorization` key silently replaces the token, while `authorization` in any other casing
29
+ * survives as a second entry that `new Headers()` comma-joins into one malformed value. The same
30
+ * static value would also ride along on the OAuth discovery, registration, and token requests
31
+ * made through `createHeadersFetch`, leaking a resource-server credential to the authorization
32
+ * server. Drop it (and only it) whenever OAuth is configured; every other static header
33
+ * (tenant keys, gateways) still applies.
34
+ */
35
+ export function stripAuthorizationHeader(
36
+ headers: Record<string, string> | undefined,
37
+ ): Record<string, string> | undefined {
38
+ if (!headers) return undefined;
39
+ const kept = Object.entries(headers).filter(([name]) => !isAuthorizationHeader(name));
40
+ return kept.length > 0 ? Object.fromEntries(kept) : undefined;
41
+ }
42
+
43
+ /** Case-insensitive test for the single header an OAuth server owns. */
44
+ export function isAuthorizationHeader(name: string): boolean {
45
+ return name.toLowerCase() === "authorization";
46
+ }
47
+
23
48
  /**
24
49
  * Wrap a fetch implementation so configured server headers are attached as
25
50
  * defaults on every request (e.g. during SDK OAuth metadata discovery and
@@ -9,6 +9,7 @@ import { isSafeAuthorizationUrl } from "./callback-url.js";
9
9
  import {
10
10
  discoverManualAuthChallenge,
11
11
  createHeadersFetch,
12
+ stripAuthorizationHeader,
12
13
  type ManualAuthChallenge,
13
14
  } from "./auth-challenge.js";
14
15
  import {
@@ -629,16 +630,22 @@ export async function authorize(
629
630
  // if empty, which the callback server then rejects as a CSRF error.
630
631
  authProvider.setState(oauthState);
631
632
 
633
+ // WHY: `Authorization` belongs to the OAuth flow here. Filter the same set the transport
634
+ // uses, so this flow's own challenge probe and its SDK `fetchFn` (metadata, registration,
635
+ // token) never carry a static credential that was configured for the MCP server — the
636
+ // authorization server is usually a different origin.
637
+ const staticHeaders = stripAuthorizationHeader(config.headers);
638
+
632
639
  const authChallenge = await discoverChallengeWithFallback({
633
640
  serverName,
634
641
  serverUrl,
635
- headers: config.headers,
642
+ headers: staticHeaders,
636
643
  signal,
637
644
  });
638
645
  assertActive();
639
646
 
640
647
  const callbackPromise = registerCallbackPromise(callbackServer, oauthState);
641
- const customFetch = config.headers ? createHeadersFetch(config.headers) : undefined;
648
+ const customFetch = staticHeaders ? createHeadersFetch(staticHeaders) : undefined;
642
649
 
643
650
  const authResult = await runInitialSdkAuth(
644
651
  authProvider,
package/src/config.ts CHANGED
@@ -187,7 +187,9 @@ export const ServerConfigSchema = z.preprocess(
187
187
  /**
188
188
  * Static HTTP headers to include with every request (streamable-http / sse only).
189
189
  * Useful for API-key-based auth (e.g. { "Authorization": "Bearer <key>" }).
190
- * For OAuth2, use the "auth" field instead.
190
+ * For OAuth2, use the "auth" field instead: when "auth" is set, OAuth owns the
191
+ * Authorization header and any Authorization entry here is ignored (other headers
192
+ * still apply).
191
193
  */
192
194
  headers: z.record(z.string(), z.string()).optional(),
193
195
  /**
@@ -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
@@ -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
  /**
@@ -16,7 +16,9 @@ import type { OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.
16
16
  import { McpError } from "./errors.js";
17
17
  import type { ServerConfig } from "./config.js";
18
18
  import { McpOAuthProvider } from "./oauth-provider.js";
19
- import { createLineSplitter } from "./stdio-process.js";
19
+ import { isAuthorizationHeader, stripAuthorizationHeader } from "./auth-challenge.js";
20
+ import { reportDiagnostic } from "./debug-log.js";
21
+ import { instrumentStderr } from "./stdio-process.js";
20
22
  import { sanitizeTerminalText } from "./terminal-text.js";
21
23
 
22
24
  function resolveEnv(extra?: Record<string, string>): Record<string, string> {
@@ -32,9 +34,9 @@ function resolveEnv(extra?: Record<string, string>): Record<string, string> {
32
34
  return env;
33
35
  }
34
36
 
35
- function createRequestInit(config: ServerConfig): RequestInit | undefined {
37
+ function createRequestInit(headers: Record<string, string> | undefined): RequestInit | undefined {
36
38
  // Build requestInit for static headers (API keys, etc.)
37
- return config.headers ? { headers: config.headers } : undefined;
39
+ return headers ? { headers } : undefined;
38
40
  }
39
41
 
40
42
  function createOAuthProvider(
@@ -53,20 +55,18 @@ function createOAuthProvider(
53
55
  });
54
56
  }
55
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
+ */
56
65
  function wireStdioStderr(transport: StdioClientTransport, onStderr: (line: string) => void): void {
57
- if (!transport.stderr) return;
58
- const splitter = createLineSplitter((rawLine) => {
66
+ instrumentStderr(transport, (rawLine) => {
59
67
  const clean = sanitizeTerminalText(rawLine);
60
68
  if (clean) onStderr(clean);
61
69
  });
62
- transport.stderr.on("data", (chunk: Buffer) => {
63
- splitter.write(chunk);
64
- });
65
- const flush = (): void => {
66
- splitter.end();
67
- };
68
- transport.stderr.on("end", flush);
69
- transport.stderr.on("close", flush);
70
70
  }
71
71
 
72
72
  /** Expand a leading `~` / `~/` / `~\` to the home directory, the way Pi resolves a config `cwd`. */
@@ -188,7 +188,18 @@ export function createTransport(
188
188
  ): Transport {
189
189
  const cwd = typeof cwdOrOnStderr === "string" ? cwdOrOnStderr : cwdArg;
190
190
  const onStderr = typeof cwdOrOnStderr === "function" ? cwdOrOnStderr : undefined;
191
- const requestInit = createRequestInit(config);
191
+ // WHY: with OAuth configured the SDK owns `Authorization` (see stripAuthorizationHeader);
192
+ // a leftover static header is a migration artifact, so drop it and record that we did.
193
+ const staticHeaders = config.auth ? stripAuthorizationHeader(config.headers) : config.headers;
194
+ if (config.auth && config.headers && Object.keys(config.headers).some(isAuthorizationHeader)) {
195
+ reportDiagnostic({
196
+ level: "info",
197
+ event: "config.static_authorization_ignored",
198
+ server: serverName,
199
+ message: `Ignoring the static Authorization header for "${serverName}": OAuth is configured, so requests carry the OAuth access token instead.`,
200
+ });
201
+ }
202
+ const requestInit = createRequestInit(staticHeaders);
192
203
  const authProvider = createOAuthProvider(serverName, config, storageDir);
193
204
 
194
205
  switch (config.transport) {