@jangmanj/mcp-client 0.2.0 → 0.4.0

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
@@ -8,6 +8,34 @@ MCP 2026-07-28 client library: core protocol/lifecycle, stdio and HTTP transport
8
8
  npm install @jangmanj/mcp-client
9
9
  ```
10
10
 
11
+ ## Quickstart
12
+
13
+ ```ts
14
+ import { McpClient } from "@jangmanj/mcp-client";
15
+ import { createOps } from "@jangmanj/mcp-client/ops";
16
+ import { StdioTransport } from "@jangmanj/mcp-client/transport-stdio";
17
+
18
+ const client = new McpClient({
19
+ transport: new StdioTransport({ command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", "."] }),
20
+ server: { key: "filesystem" },
21
+ });
22
+
23
+ const ops = createOps(client);
24
+ const tools = await ops.tools.listAll();
25
+ if (tools.kind === "ok") {
26
+ console.log(tools.value.items.map((t) => t.name));
27
+ const result = await ops.tools.call("list_allowed_directories");
28
+ if (result.kind === "ok") console.log(result.value.content);
29
+ }
30
+
31
+ await client.close();
32
+ ```
33
+
34
+ Every call returns a discriminated `Outcome` (`ok` / `jsonrpc-error` / `transport-failure` /
35
+ `mrtr-interim` / …) instead of throwing — pattern-match on `kind`. HTTP servers use
36
+ `HttpTransport` from `/transport-http`; OAuth, bearer, and client-credentials live in
37
+ `/auth` (`OAuthAuthorization`, `ConfiguredBearer`, `ClientCredentialsAuth`).
38
+
11
39
  ## Subpath exports
12
40
 
13
41
  - `@jangmanj/mcp-client` (re-exports `./core`)
@@ -49,9 +77,18 @@ patterns). `/mcp` lists server states; `/mcp reconnect <name>` restarts one.
49
77
  Servers registered by other extensions via `pi.registerMcpServer()` are connected
50
78
  too, with file configuration taking precedence.
51
79
 
52
- Not supported yet: OAuth flows (`oauth` entries connect unauthenticated and will
53
- fail on servers that require it — use `headers` with a token instead), MCP
54
- prompts/resources, elicitations, and task-based tool calls.
80
+ Not supported yet: MCP prompts/resources exposure to Pi (servers offering only prompts or
81
+ resources connect but register nothing), elicitation UI (consent prompts decline by
82
+ default), and task-based tool calls.
83
+
84
+ OAuth works out of the box for HTTP servers without a static `Authorization` header: the
85
+ first 401 marks the server "needs sign-in" in `/mcp`, and `/mcp login <name>` runs the
86
+ authorization-code + PKCE flow with CIMD/DCR registration through the system browser.
87
+ Credentials persist in `$PI_CODING_AGENT_DIR/mcp-client-oauth.json` (issuer-keyed);
88
+ `/mcp logout <name>` deletes them. The full `oauth` config shape is supported:
89
+ `clientId`, `clientSecret`, `clientName`, `callbackPort`, `callbackUrl` (loopback HTTP),
90
+ `scope` (space-separated, merged with advertised scopes), and `authServerMetadataUrl`
91
+ (trusted as configured, skips PRM discovery).
55
92
 
56
93
  A running Pi session picks the extension up on `/reload`; fresh starts load it
57
94
  automatically.
@@ -61,4 +98,10 @@ automatically.
61
98
  ```sh
62
99
  npm run check
63
100
  npm run smoke:pack
101
+ npm run gen:spec-matrix # regenerate SPEC.md (requirement ID -> source -> tests)
102
+ npm run check:spec-drift # compare the vendored schema + spec prose against upstream
64
103
  ```
104
+
105
+ SPEC.md is the generated traceability matrix; CI fails when it is stale or a source
106
+ requirement ID is cited by no test and not exempted. `spec-drift.yml` (daily cron)
107
+ opens an issue when the upstream MCP 2026-07-28 schema or spec prose moves.
@@ -16,6 +16,8 @@ export interface DiscoveryOptions {
16
16
  readonly allowInsecureDev?: boolean;
17
17
  readonly onDiagnostic?: (message: string) => void;
18
18
  readonly chooseAuthorizationServer?: (candidates: readonly string[]) => string | Promise<string>;
19
+ /** Skip PRM/issuer discovery: fetch this AS metadata document and trust it as configured. */
20
+ readonly authServerMetadataUrl?: string;
19
21
  }
20
22
  export declare function getDocument(fetcher: FetchPort, url: string, signal: AbortSignal): Promise<JsonObject | undefined>;
21
23
  export declare function discover(fetcher: FetchPort, resource: string, requestUrl: string, location: string | undefined, options: DiscoveryOptions, signal: AbortSignal): Promise<{
@@ -32,6 +32,16 @@ export async function getDocument(fetcher, url, signal) {
32
32
  }
33
33
  export async function discover(fetcher, resource, requestUrl, location, options, signal) {
34
34
  const url = secureUrl(resource, options.allowInsecureDev);
35
+ if (options.authServerMetadataUrl !== undefined) {
36
+ const metadataUrl = secureUrl(options.authServerMetadataUrl, options.allowInsecureDev);
37
+ const doc = await getDocument(fetcher, metadataUrl.href, signal);
38
+ if (!doc)
39
+ fail('as-metadata-missing');
40
+ const issuer = doc['issuer'];
41
+ if (typeof issuer !== 'string' || !issuer)
42
+ fail('as-issuer-invalid');
43
+ return { resource: url.href, metadata: await discoverIssuer(fetcher, issuer, options, signal), scopes: [] };
44
+ }
35
45
  const root = `${url.origin}/.well-known/oauth-protected-resource`;
36
46
  const locations = location !== undefined ? [secureUrl(location, options.allowInsecureDev).href] :
37
47
  [...new Set([`${root}${url.pathname === '/' ? '' : url.pathname}${url.search}`, root])];
@@ -71,8 +81,10 @@ export async function discoverIssuer(fetcher, issuer, options, signal) {
71
81
  if (url.search || url.hash || /[?#]/u.test(issuer))
72
82
  fail('as-issuer-invalid');
73
83
  const path = url.pathname === '/' ? '' : url.pathname.replace(/\/$/u, '');
74
- const candidates = [`${url.origin}/.well-known/oauth-authorization-server${path}`, `${url.origin}/.well-known/openid-configuration${path}`];
75
- if (path)
84
+ const candidates = options.authServerMetadataUrl !== undefined
85
+ ? [secureUrl(options.authServerMetadataUrl, options.allowInsecureDev).href]
86
+ : [`${url.origin}/.well-known/oauth-authorization-server${path}`, `${url.origin}/.well-known/openid-configuration${path}`];
87
+ if (!options.authServerMetadataUrl && path)
76
88
  candidates.push(`${url.origin}${path}/.well-known/openid-configuration`);
77
89
  for (const candidate of candidates) {
78
90
  const doc = await getDocument(fetcher, candidate, signal);
@@ -86,6 +86,8 @@ export interface OAuthOptions extends ResourceOptions, DiscoveryOptions {
86
86
  readonly flowTimeoutMs?: number;
87
87
  readonly stepUpLimit?: number;
88
88
  readonly offlineAccess?: boolean;
89
+ /** Space-separated scopes requested when the server does not advertise required scopes. */
90
+ readonly scope?: string;
89
91
  readonly onDiagnostic?: (message: string) => void;
90
92
  }
91
93
  export declare class OAuthAuthorization implements AuthProvider {
@@ -153,6 +153,7 @@ export class OAuthAuthorization {
153
153
  this.#grant = undefined;
154
154
  const selected = [...new Set([...(step && sameBinding ? previous.scopes : []),
155
155
  ...(bearer?.scope !== undefined ? scopesOf(bearer.scope) : step && sameBinding ? [] : scopes.flatMap(scopesOf)),
156
+ ...scopesOf(this.#options.scope),
156
157
  ])].filter(scope => scope !== 'offline_access');
157
158
  if (this.#options.offlineAccess && metadata.scopes.includes('offline_access'))
158
159
  selected.push('offline_access');
@@ -1,5 +1,5 @@
1
1
  /**
2
- * AUTO-GENERATED from packages/core/src/schema/schema.json (MCP 2026-07-28, tag 5f5440bb).
2
+ * AUTO-GENERATED from packages/core/src/schema/schema.json (MCP 2026-07-28, tag 2bbace55).
3
3
  * Do not edit manually; regenerate with `npm run gen:schema`.
4
4
  */
5
5
  /**
@@ -49,8 +49,8 @@ export type InputRequest = CreateMessageRequest | ListRootsRequest | ElicitReque
49
49
  */
50
50
  export type ElicitRequestParams = ElicitRequestFormParams | ElicitRequestURLParams;
51
51
  /**
52
- * Restricted schema definitions that only allow primitive types
53
- * without nested objects or arrays.
52
+ * Restricted schema definitions for strings, numbers, booleans, and enums,
53
+ * without nested objects. The only arrays allowed are multi-select enums.
54
54
  *
55
55
  * This interface was referenced by `McpSchema20260728`'s JSON-Schema
56
56
  * via the `definition` "PrimitiveSchemaDefinition".
@@ -1523,6 +1523,11 @@ export interface Tool {
1523
1523
  * (`if`/`then`/`else`), reference keywords (`$ref`, `$defs`, `$anchor`), and any other
1524
1524
  * standard validation or annotation keywords.
1525
1525
  *
1526
+ * When using composition keywords, declare `properties` at the schema root and keep the
1527
+ * branches to presence assertions such as `required`. A subschema that fails on a type
1528
+ * error is indistinguishable from one that does not apply, so type constraints placed
1529
+ * inside `oneOf` branches are not enforced for whichever branch does not match.
1530
+ *
1526
1531
  * Property schemas may carry an `x-mcp-header` annotation to mirror the
1527
1532
  * argument value into an HTTP header on the Streamable HTTP transport. See
1528
1533
  * the Streamable HTTP transport specification for the validity and
@@ -2727,12 +2732,12 @@ export interface InternalError {
2727
2732
  *
2728
2733
  * In MCP, this error is returned in various contexts when request parameters fail validation:
2729
2734
  *
2730
- * - **Tools**: Unknown tool name or invalid tool arguments
2735
+ * - **Tools**: Unknown tool name, or a request that does not satisfy the `CallToolRequest` schema. Invalid tool arguments are instead reported as tool execution errors, with `isError` set to true
2731
2736
  * - **Prompts**: Unknown prompt name or missing required arguments
2732
2737
  * - **Pagination**: Invalid or expired cursor values
2733
- * - **Logging**: Invalid log level
2738
+ * - **Logging** (deprecated): Invalid log level
2734
2739
  * - **Elicitation**: Server requests an elicitation mode not declared in client capabilities
2735
- * - **Sampling**: Missing tool result or tool results mixed with other content
2740
+ * - **Sampling** (deprecated): Missing tool result or tool results mixed with other content
2736
2741
  *
2737
2742
  * This interface was referenced by `McpSchema20260728`'s JSON-Schema
2738
2743
  * via the `definition` "InvalidParamsError".
@@ -1,6 +1,6 @@
1
1
  /* eslint-disable */
2
2
  /**
3
- * AUTO-GENERATED from packages/core/src/schema/schema.json (MCP 2026-07-28, tag 5f5440bb).
3
+ * AUTO-GENERATED from packages/core/src/schema/schema.json (MCP 2026-07-28, tag 2bbace55).
4
4
  * Do not edit manually; regenerate with `npm run gen:schema`.
5
5
  */
6
6
  export {};
@@ -18,6 +18,11 @@ import { StdioTransport } from "../dist/transport-stdio/index.js";
18
18
  import type { Outcome } from "../dist/index.js";
19
19
  import type { Exposure, ResolvedServerConfig } from "./config.ts";
20
20
  import { convertBlocks } from "./content.ts";
21
+ import {
22
+ canonicalResource,
23
+ createOAuthProvider,
24
+ FileCredentialStore,
25
+ } from "./oauth.ts";
21
26
  import type { ExtensionAPI, ToolAnnotations, ToolResult } from "./pi-api.ts";
22
27
 
23
28
  export type ServerStatus = "connecting" | "connected" | "error" | "disabled";
@@ -33,6 +38,10 @@ export interface ServerState {
33
38
  instructions?: string | undefined;
34
39
  client?: McpClient | undefined;
35
40
  ops?: Ops | undefined;
41
+ /** Set when the server rejected unauthenticated requests. */
42
+ authRequired?: boolean | undefined;
43
+ /** Closes the loopback redirect listener of an OAuth provider, if any. */
44
+ closeRedirect?: (() => void) | undefined;
36
45
  /** Pi tool names registered for this server (persist across reconnects). */
37
46
  readonly registeredTools: Set<string>;
38
47
  /** Exposures this server's tools were registered with. */
@@ -117,6 +126,14 @@ function inputSchemaOf(entry: ToolEntry): Record<string, unknown> {
117
126
  /** Transport-failure kinds worth one reconnect + retry. */
118
127
  const RETRY_KINDS = new Set(["connect", "closed", "stream-broken", "process-exit"]);
119
128
 
129
+ function isAuthOutcome(outcome: Outcome<unknown>): boolean {
130
+ if (outcome.kind === "auth-failure" || outcome.kind === "auth-unavailable") return true;
131
+ return (
132
+ outcome.kind === "transport-failure" &&
133
+ (outcome.failure.kind === "auth-failure" || outcome.failure.kind === "auth-unavailable")
134
+ );
135
+ }
136
+
120
137
  export function describeOutcome(outcome: Exclude<Outcome<unknown>, { kind: "ok" }>): string {
121
138
  switch (outcome.kind) {
122
139
  case "jsonrpc-error":
@@ -143,6 +160,14 @@ export interface BridgeOptions {
143
160
  readonly notify: (message: string, level: "info" | "warning" | "error") => void;
144
161
  /** Bound for connection waits from tool_call / before_agent_start. */
145
162
  readonly waitMs?: number;
163
+ /** Path of the OAuth credential store file; enables OAuth for HTTP servers. */
164
+ readonly credentialStorePath?: string;
165
+ /** Host confirm dialog for OAuth consent prompts. */
166
+ readonly confirm?: (title: string, message: string) => Promise<boolean>;
167
+ /** Browser opener override (tests); defaults to the system browser. */
168
+ readonly browserOpen?: (url: string, signal: AbortSignal) => Promise<void>;
169
+ /** Allow OAuth against insecure loopback HTTP (local dev servers, tests). */
170
+ readonly allowInsecureAuth?: boolean;
146
171
  }
147
172
 
148
173
  export class McpBridge {
@@ -151,11 +176,23 @@ export class McpBridge {
151
176
  private readonly waitMs: number;
152
177
  private readonly states = new Map<string, ServerState>();
153
178
  private readonly pending = new Map<string, Promise<void>>();
179
+ private readonly credentials: FileCredentialStore | undefined;
180
+ private readonly confirm: BridgeOptions["confirm"];
181
+ private readonly browserOpen: BridgeOptions["browserOpen"];
182
+ private readonly allowInsecureAuth: boolean;
183
+ /** Server name for which an interactive login (/mcp login) is armed. */
184
+ private loginArmed: string | undefined;
154
185
 
155
186
  constructor(opts: BridgeOptions) {
156
187
  this.pi = opts.pi;
157
188
  this.notify = opts.notify;
158
189
  this.waitMs = opts.waitMs ?? 10_000;
190
+ this.credentials = opts.credentialStorePath !== undefined
191
+ ? new FileCredentialStore(opts.credentialStorePath)
192
+ : undefined;
193
+ this.confirm = opts.confirm;
194
+ this.browserOpen = opts.browserOpen;
195
+ this.allowInsecureAuth = opts.allowInsecureAuth ?? false;
159
196
  }
160
197
 
161
198
  get(name: string): ServerState | undefined {
@@ -242,6 +279,34 @@ export class McpBridge {
242
279
  return state;
243
280
  }
244
281
 
282
+ /** Interactive OAuth sign-in: arms the consent gate and reconnects. */
283
+ async login(name: string): Promise<ServerState> {
284
+ const state = this.states.get(name);
285
+ if (!state) throw new Error(`unknown server: ${name}`);
286
+ if (state.config.kind !== "http") {
287
+ throw new Error(`mcp "${name}": OAuth applies to HTTP servers only`);
288
+ }
289
+ if (!this.credentials) throw new Error("OAuth is not available (no credential store)");
290
+ this.loginArmed = name;
291
+ try {
292
+ await this.reconnect(name);
293
+ } finally {
294
+ this.loginArmed = undefined;
295
+ }
296
+ return state;
297
+ }
298
+
299
+ /** Delete stored credentials for the server's resource and reconnect. */
300
+ async logout(name: string): Promise<ServerState> {
301
+ const state = this.states.get(name);
302
+ if (!state) throw new Error(`unknown server: ${name}`);
303
+ if (this.credentials && state.config.url !== undefined) {
304
+ await this.credentials.deleteResource(canonicalResource(state.config.url));
305
+ }
306
+ await this.reconnect(name);
307
+ return state;
308
+ }
309
+
245
310
  async closeAll(): Promise<void> {
246
311
  await Promise.allSettled([...this.pending.values()]);
247
312
  await Promise.allSettled([...this.states.values()].map((s) => this.teardown(s)));
@@ -252,6 +317,8 @@ export class McpBridge {
252
317
  const client = state.client;
253
318
  state.client = undefined;
254
319
  state.ops = undefined;
320
+ state.closeRedirect?.();
321
+ state.closeRedirect = undefined;
255
322
  if (client) {
256
323
  try {
257
324
  await client.close({ graceMs: 500 });
@@ -261,19 +328,40 @@ export class McpBridge {
261
328
  }
262
329
  }
263
330
 
264
- private buildClient(config: ResolvedServerConfig): McpClient {
265
- const transport =
266
- config.kind === "stdio"
267
- ? new StdioTransport({
268
- command: config.command as string,
269
- args: config.args ?? [],
270
- ...(config.cwd !== undefined ? { cwd: config.cwd } : {}),
271
- ...(config.env !== undefined ? { env: config.env } : {}),
272
- })
273
- : new HttpTransport({
274
- url: config.url as string,
275
- ...(config.headers !== undefined ? { extraHeaders: config.headers } : {}),
276
- });
331
+ private async buildClient(config: ResolvedServerConfig, state: ServerState): Promise<McpClient> {
332
+ let transport: StdioTransport | HttpTransport;
333
+ if (config.kind === "stdio") {
334
+ transport = new StdioTransport({
335
+ command: config.command as string,
336
+ args: config.args ?? [],
337
+ ...(config.cwd !== undefined ? { cwd: config.cwd } : {}),
338
+ ...(config.env !== undefined ? { env: config.env } : {}),
339
+ });
340
+ } else {
341
+ // OAuth attaches when no static Authorization header is configured
342
+ // (mirrors Pi's rule); the flow itself runs on the first 401.
343
+ const hasStaticAuth = Object.keys(config.headers ?? {}).some(
344
+ (k) => k.toLowerCase() === "authorization",
345
+ );
346
+ let authProvider;
347
+ if (!hasStaticAuth && this.credentials) {
348
+ const handle = await createOAuthProvider({
349
+ config,
350
+ store: this.credentials,
351
+ interactive: () => this.loginArmed === config.name,
352
+ ...(this.confirm !== undefined ? { confirm: this.confirm } : {}),
353
+ ...(this.browserOpen !== undefined ? { browserOpen: this.browserOpen } : {}),
354
+ allowInsecureAuth: this.allowInsecureAuth,
355
+ });
356
+ authProvider = handle.provider;
357
+ state.closeRedirect = handle.closeRedirect;
358
+ }
359
+ transport = new HttpTransport({
360
+ url: config.url as string,
361
+ ...(config.headers !== undefined ? { extraHeaders: config.headers } : {}),
362
+ ...(authProvider !== undefined ? { authProvider } : {}),
363
+ });
364
+ }
277
365
  return new McpClient({
278
366
  transport,
279
367
  server: { key: config.name, label: config.name },
@@ -285,13 +373,7 @@ export class McpBridge {
285
373
  private async connect(state: ServerState): Promise<void> {
286
374
  const { config } = state;
287
375
  try {
288
- if (config.wantsOAuth) {
289
- this.notify(
290
- `mcp "${state.name}": oauth config is not supported by this bridge yet; connect may fail with 401`,
291
- "warning",
292
- );
293
- }
294
- const client = this.buildClient(config);
376
+ const client = await this.buildClient(config, state);
295
377
  const ops = createOps(client);
296
378
  state.client = client;
297
379
  state.ops = ops;
@@ -324,11 +406,15 @@ export class McpBridge {
324
406
  (listed.kind === "jsonrpc-error" && listed.code === -32601)
325
407
  ) {
326
408
  // Server without a tools capability: valid, just nothing to register.
409
+ } else if (isAuthOutcome(listed)) {
410
+ state.authRequired = true;
411
+ throw new Error(`authentication required — sign in with /mcp login ${state.name}`);
327
412
  } else {
328
413
  throw new Error(describeOutcome(listed));
329
414
  }
330
415
  state.status = "connected";
331
416
  state.error = undefined;
417
+ state.authRequired = undefined;
332
418
  } catch (err) {
333
419
  state.status = "error";
334
420
  state.error = err instanceof Error ? err.message : String(err);
@@ -479,7 +565,9 @@ export class McpBridge {
479
565
  case "disabled":
480
566
  return `${base}: disabled${s.error ? ` (${s.error})` : ""}`;
481
567
  case "error":
482
- return `${base}: error: ${s.error ?? "unknown"}`;
568
+ return s.authRequired
569
+ ? `${base}: needs sign-in — /mcp login ${s.name}`
570
+ : `${base}: error: ${s.error ?? "unknown"}`;
483
571
  }
484
572
  });
485
573
  }
@@ -14,6 +14,20 @@ import type { McpServerEntry } from "./pi-api.ts";
14
14
 
15
15
  export type Exposure = "direct" | "codemode" | "deferred" | "hidden";
16
16
 
17
+ export interface OAuthConfig {
18
+ readonly clientId?: string;
19
+ readonly clientSecret?: string;
20
+ readonly clientName?: string;
21
+ /** Fixed loopback callback port (http://127.0.0.1:<port>/callback). */
22
+ readonly callbackPort?: number;
23
+ /** Full loopback redirect URI; takes precedence over callbackPort. */
24
+ readonly callbackUrl?: string;
25
+ /** Space-separated scopes requested when the server does not advertise them. */
26
+ readonly scope?: string;
27
+ /** Use this AS metadata document instead of discovery; trusted as configured. */
28
+ readonly authServerMetadataUrl?: string;
29
+ }
30
+
17
31
  export interface ResolvedServerConfig {
18
32
  readonly name: string;
19
33
  readonly source: "user" | "project" | "extension";
@@ -29,7 +43,9 @@ export interface ResolvedServerConfig {
29
43
  readonly toolExposure?: Record<string, string>;
30
44
  readonly description?: string;
31
45
  readonly timeoutMs: number;
32
- /** Present when the entry sets `oauth`: not supported by this bridge yet. */
46
+ /** Static client credentials / naming for the OAuth flow, when configured. */
47
+ readonly oauth?: OAuthConfig;
48
+ /** Present when the entry sets `oauth`. */
33
49
  readonly wantsOAuth: boolean;
34
50
  }
35
51
 
@@ -153,6 +169,32 @@ function isPartialOverride(raw: McpServerEntry): boolean {
153
169
  return raw.command === undefined && raw.url === undefined && raw.type === undefined;
154
170
  }
155
171
 
172
+ function resolveOAuth(
173
+ raw: McpServerEntry,
174
+ env: Record<string, string | undefined>,
175
+ exec: (command: string) => string,
176
+ warnings: string[],
177
+ where: string,
178
+ ): OAuthConfig | undefined {
179
+ if (raw.oauth === undefined) return undefined;
180
+ const out: { clientId?: string; clientSecret?: string; clientName?: string; callbackPort?: number; callbackUrl?: string; scope?: string; authServerMetadataUrl?: string } = {};
181
+ for (const key of ["clientId", "clientSecret", "clientName", "callbackUrl", "scope", "authServerMetadataUrl"] as const) {
182
+ const v = raw.oauth[key];
183
+ if (v === undefined) continue;
184
+ if (typeof v !== "string") {
185
+ warnings.push(`${where}: oauth.${key} must be a string`);
186
+ continue;
187
+ }
188
+ out[key] = key === "clientName" ? v : interpolate(v, env, exec, warnings, `${where}.oauth.${key}`);
189
+ }
190
+ if (raw.oauth.callbackPort !== undefined) {
191
+ const p = raw.oauth.callbackPort;
192
+ if (typeof p === "number" && Number.isInteger(p) && p > 0 && p < 65536) out.callbackPort = p;
193
+ else warnings.push(`${where}: oauth.callbackPort must be an integer port`);
194
+ }
195
+ return out;
196
+ }
197
+
156
198
  function resolveEntry(
157
199
  entry: RawEntry,
158
200
  opts: LoadOptions,
@@ -180,6 +222,8 @@ function resolveEntry(
180
222
  const env = opts.env ?? process.env;
181
223
  const exec = opts.exec ?? defaultExec;
182
224
 
225
+ const oauth = resolveOAuth(raw, env, exec, warnings, where);
226
+
183
227
  const base = {
184
228
  name,
185
229
  source,
@@ -187,6 +231,7 @@ function resolveEntry(
187
231
  exposure: normalizeExposure(raw.exposure),
188
232
  timeoutMs: raw.timeout !== undefined && raw.timeout > 0 ? raw.timeout * 1000 : DEFAULT_TIMEOUT_MS,
189
233
  wantsOAuth: raw.oauth !== undefined,
234
+ ...(oauth !== undefined ? { oauth } : {}),
190
235
  ...(raw.toolExposure !== undefined ? { toolExposure: raw.toolExposure } : {}),
191
236
  ...(raw.description !== undefined ? { description: raw.description } : {}),
192
237
  };
@@ -8,8 +8,9 @@
8
8
  */
9
9
 
10
10
  import { homedir } from "node:os";
11
+ import { join } from "node:path";
11
12
  import { McpBridge } from "./bridge.ts";
12
- import { loadServerConfigs, type ResolvedServerConfig } from "./config.ts";
13
+ import { agentDir, loadServerConfigs, type ResolvedServerConfig } from "./config.ts";
13
14
  import type { ExtensionAPI, McpServerEntry, SessionContext, Ui } from "./pi-api.ts";
14
15
 
15
16
  /** Tolerantly unwrap pi.getMcpServers() / mcp_servers_change event shapes. */
@@ -43,20 +44,27 @@ export default function (pi: ExtensionAPI) {
43
44
  const bridge = new McpBridge({
44
45
  pi,
45
46
  notify: (message, level) => currentUi?.notify(message, level),
47
+ credentialStorePath: join(agentDir(process.env, homedir()), "mcp-client-oauth.json"),
48
+ confirm: (title, message) => currentUi?.confirm?.(title, message) ?? Promise.resolve(false),
46
49
  });
47
50
 
48
51
  // Registering /mcp replaces built-in MCP support for sessions.
49
52
  pi.registerCommand("mcp", {
50
- description: "MCP servers (mcp-client bridge): /mcp [list] | /mcp reconnect <name>",
53
+ description: "MCP (mcp-client bridge): /mcp [list] | /mcp reconnect|login|logout <name>",
51
54
  handler: async (args, ctx) => {
52
55
  const [sub, ...rest] = args.trim().split(/\s+/).filter(Boolean);
53
56
  if (sub === undefined || sub === "list") {
54
57
  ctx.ui.notify(bridge.statusLines().join("\n"), "info");
55
58
  return;
56
59
  }
57
- if (sub === "reconnect" && rest[0] !== undefined) {
60
+ if ((sub === "reconnect" || sub === "login" || sub === "logout") && rest[0] !== undefined) {
58
61
  try {
59
- const state = await bridge.reconnect(rest[0]);
62
+ const state =
63
+ sub === "login"
64
+ ? await bridge.login(rest[0])
65
+ : sub === "logout"
66
+ ? await bridge.logout(rest[0])
67
+ : await bridge.reconnect(rest[0]);
60
68
  ctx.ui.notify(
61
69
  state.status === "connected"
62
70
  ? `mcp "${state.name}": connected, ${state.toolCount} tools`
@@ -68,7 +76,7 @@ export default function (pi: ExtensionAPI) {
68
76
  }
69
77
  return;
70
78
  }
71
- ctx.ui.notify("Usage: /mcp [list] | /mcp reconnect <name>", "info");
79
+ ctx.ui.notify("Usage: /mcp [list] | /mcp reconnect|login|logout <name>", "info");
72
80
  },
73
81
  });
74
82
 
@@ -0,0 +1,219 @@
1
+ /**
2
+ * OAuth wiring for the Pi bridge: a file-backed CredentialStore (so sign-ins
3
+ * survive restarts, keyed by issuer per SEP-2352) and a per-server
4
+ * OAuthAuthorization factory wired to the host's consent UI and browser.
5
+ *
6
+ * The library (packages/auth) owns the protocol: discovery, CIMD/DCR, PKCE,
7
+ * iss validation, step-up. This module only connects ports to Pi.
8
+ */
9
+
10
+ import { createServer, type Server } from "node:http";
11
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
12
+ import { dirname } from "node:path";
13
+ import {
14
+ canonicalResource,
15
+ OAuthAuthorization,
16
+ openSystemBrowser,
17
+ SafeFetch,
18
+ startLoopbackRedirect,
19
+ type AuthorizationConsent,
20
+ type ClientRegistration,
21
+ } from "../dist/auth/index.js";
22
+ import type { ResolvedServerConfig } from "./config.ts";
23
+
24
+ export {
25
+ canonicalResource,
26
+ OAuthAuthorization,
27
+ openSystemBrowser,
28
+ startLoopbackRedirect,
29
+ };
30
+ export type { AuthorizationConsent, ClientRegistration };
31
+
32
+ /** JSON-file CredentialStore: write-through, atomic rename, single-process. */
33
+ export class FileCredentialStore {
34
+ readonly #path: string;
35
+ #values: Map<string, string> | undefined;
36
+ #writing: Promise<void> = Promise.resolve();
37
+
38
+ constructor(path: string) {
39
+ this.#path = path;
40
+ }
41
+
42
+ async #load(): Promise<Map<string, string>> {
43
+ if (this.#values) return this.#values;
44
+ try {
45
+ const parsed = JSON.parse(await readFile(this.#path, "utf8"));
46
+ this.#values = new Map(Object.entries(parsed));
47
+ } catch {
48
+ this.#values = new Map();
49
+ }
50
+ return this.#values;
51
+ }
52
+
53
+ async #flush(): Promise<void> {
54
+ const snapshot = JSON.stringify(Object.fromEntries(this.#values ?? new Map()));
55
+ this.#writing = this.#writing.then(async () => {
56
+ await mkdir(dirname(this.#path), { recursive: true });
57
+ const tmp = `${this.#path}.${process.pid}.tmp`;
58
+ await writeFile(tmp, snapshot, { mode: 0o600 });
59
+ await rename(tmp, this.#path);
60
+ });
61
+ return this.#writing;
62
+ }
63
+
64
+ async get(key: string): Promise<string | undefined> {
65
+ return (await this.#load()).get(key);
66
+ }
67
+
68
+ async set(key: string, value: string): Promise<void> {
69
+ (await this.#load()).set(key, value);
70
+ await this.#flush();
71
+ }
72
+
73
+ async delete(key: string): Promise<void> {
74
+ if ((await this.#load()).delete(key)) await this.#flush();
75
+ }
76
+
77
+ /** Delete every entry whose key mentions the resource (logout). */
78
+ async deleteResource(resource: string): Promise<number> {
79
+ const values = await this.#load();
80
+ let n = 0;
81
+ for (const key of [...values.keys()]) {
82
+ if (key.includes(resource)) {
83
+ values.delete(key);
84
+ n++;
85
+ }
86
+ }
87
+ if (n > 0) await this.#flush();
88
+ return n;
89
+ }
90
+ }
91
+
92
+ export interface OAuthProviderOptions {
93
+ readonly config: ResolvedServerConfig;
94
+ readonly store: FileCredentialStore;
95
+ /** Gate: consent prompts proceed only when this returns true (e.g. /mcp login armed). */
96
+ readonly interactive: () => boolean;
97
+ /** Host confirm dialog; when absent all prompts decline. */
98
+ readonly confirm?: (title: string, message: string) => Promise<boolean>;
99
+ readonly browserOpen?: (url: string, signal: AbortSignal) => Promise<void>;
100
+ readonly allowInsecureAuth?: boolean;
101
+ }
102
+
103
+ export interface OAuthProviderHandle {
104
+ readonly provider: OAuthAuthorization;
105
+ readonly closeRedirect: () => void;
106
+ }
107
+
108
+ /** Loopback redirect listener bound to a fixed URI (callbackPort/callbackUrl). */
109
+ async function startFixedRedirect(redirectUri: string): Promise<{ close: () => void; waitForCallback: (opts: { redirectUri: string; state: string; signal: AbortSignal }) => Promise<URLSearchParams> }> {
110
+ const url = new URL(redirectUri);
111
+ if (url.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname)) {
112
+ throw new Error(`oauth callback must be loopback HTTP: ${redirectUri}`);
113
+ }
114
+ const path = url.pathname || "/callback";
115
+ let pending: { resolve: (v: URLSearchParams) => void; reject: (e: Error) => void } | undefined;
116
+ const server: Server = createServer((request, response) => {
117
+ const target = request.url ?? "";
118
+ if (request.method !== "GET" || !target.startsWith(`${path}?`) || !pending) {
119
+ response.writeHead(404, { Connection: "close" }).end();
120
+ return;
121
+ }
122
+ const resolve = pending.resolve;
123
+ pending = undefined;
124
+ response
125
+ .writeHead(200, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store", Connection: "close" })
126
+ .end("Authorization response received. You can close this tab.");
127
+ resolve(new URLSearchParams(target.slice(path.length + 1)));
128
+ server.close();
129
+ });
130
+ server.requestTimeout = 10_000;
131
+ await new Promise<void>((resolve, reject) => {
132
+ server.once("error", reject);
133
+ server.listen(Number(url.port || 80), "127.0.0.1", resolve);
134
+ });
135
+ return {
136
+ close: () => {
137
+ pending?.reject(new Error("cancelled"));
138
+ pending = undefined;
139
+ server.close();
140
+ server.closeAllConnections();
141
+ },
142
+ waitForCallback: async (opts) => {
143
+ if (opts.redirectUri !== redirectUri) throw new Error("invalid-redirect-uri");
144
+ const work = new Promise<URLSearchParams>((resolve, reject) => {
145
+ pending = { resolve, reject };
146
+ });
147
+ opts.signal.addEventListener("abort", () => pending?.reject(new Error("cancelled")), { once: true });
148
+ return work;
149
+ },
150
+ };
151
+ }
152
+
153
+ export async function createOAuthProvider(opts: OAuthProviderOptions): Promise<OAuthProviderHandle> {
154
+ const { config } = opts;
155
+ // callbackUrl wins; callbackPort fixes the port of /callback; otherwise an
156
+ // ephemeral loopback listener from the library.
157
+ const redirectUri =
158
+ config.oauth?.callbackUrl ??
159
+ (config.oauth?.callbackPort !== undefined
160
+ ? `http://127.0.0.1:${config.oauth.callbackPort}/callback`
161
+ : undefined);
162
+ const redirect = redirectUri !== undefined
163
+ ? await startFixedRedirect(redirectUri)
164
+ : await startLoopbackRedirect("/callback");
165
+ const effectiveRedirectUri = redirectUri ?? ("redirectUri" in redirect ? redirect.redirectUri : undefined);
166
+ if (typeof effectiveRedirectUri !== "string") throw new Error("oauth redirect URI unavailable");
167
+
168
+ const consent: AuthorizationConsent = {
169
+ request: async (prompt, signal) => {
170
+ if (!opts.interactive() || signal.aborted) return { decision: "decline" };
171
+ if (prompt.kind === "client-info") {
172
+ // No CIMD/DCR available: supply a statically configured client, if any.
173
+ const oauth = config.oauth;
174
+ if (oauth?.clientId) {
175
+ const registration: ClientRegistration = {
176
+ clientId: oauth.clientId,
177
+ redirectUris: [effectiveRedirectUri],
178
+ ...(oauth.clientSecret !== undefined ? { clientSecret: oauth.clientSecret } : {}),
179
+ };
180
+ return { decision: "accept", registration };
181
+ }
182
+ return { decision: "decline" };
183
+ }
184
+ const ok = await (opts.confirm?.(
185
+ `Authorize MCP server "${prompt.serverLabel}"?`,
186
+ `${prompt.issuerHost} will open in your browser to grant access to ${prompt.resource}.` +
187
+ (prompt.scopes.length > 0 ? ` Scopes: ${prompt.scopes.join(" ")}.` : "") +
188
+ (prompt.localhostWarning ? "\nWarning: the authorization server is on localhost." : ""),
189
+ ) ?? Promise.resolve(false));
190
+ if (signal.aborted) return { decision: "cancel" };
191
+ return ok ? { decision: "accept" } : { decision: "decline" };
192
+ },
193
+ };
194
+
195
+ const provider = new OAuthAuthorization({
196
+ resource: config.url as string,
197
+ redirectUri: effectiveRedirectUri,
198
+ redirect,
199
+ browser: { open: opts.browserOpen ?? openSystemBrowser },
200
+ credentials: opts.store,
201
+ consent,
202
+ serverLabel: config.name,
203
+ dynamicRegistration: { clientName: config.oauth?.clientName ?? "pi" },
204
+ ...(config.oauth?.scope !== undefined ? { scope: config.oauth.scope } : {}),
205
+ ...(config.oauth?.authServerMetadataUrl !== undefined
206
+ ? { authServerMetadataUrl: config.oauth.authServerMetadataUrl }
207
+ : {}),
208
+ fetch: new SafeFetch({
209
+ allowInsecureDev: opts.allowInsecureAuth ?? false,
210
+ // Insecure-dev mode also permits loopback targets (local dev servers,
211
+ // tests); production keeps SafeFetch's SSRF address blocks.
212
+ ...(opts.allowInsecureAuth
213
+ ? { allowAddress: (hostname: string) => ["127.0.0.1", "localhost", "::1"].includes(hostname) }
214
+ : {}),
215
+ }),
216
+ ...(opts.allowInsecureAuth !== undefined ? { allowInsecureDev: opts.allowInsecureAuth } : {}),
217
+ });
218
+ return { provider, closeRedirect: redirect.close };
219
+ }
@@ -74,6 +74,7 @@ export interface McpServerEntry {
74
74
 
75
75
  export interface Ui {
76
76
  notify(message: string, level?: "info" | "warning" | "error"): void;
77
+ confirm?(title: string, message: string): Promise<boolean>;
77
78
  }
78
79
 
79
80
  export interface SessionContext {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jangmanj/mcp-client",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "MCP 2026-07-28 client library: core, transports, auth, ops, MRTR/cache, OTEL telemetry, and extensions.",
5
5
  "license": "MIT",
6
6
  "author": "JangMan-J",
@@ -87,9 +87,12 @@
87
87
  "typecheck": "tsc -b tsconfig.json && tsc --noEmit -p tsconfig.test.json && tsc --noEmit -p tsconfig.extensions.json",
88
88
  "test": "vitest run",
89
89
  "gen:schema": "node scripts/gen-schema-types.mjs",
90
+ "gen:spec-matrix": "node scripts/gen-spec-matrix.mjs",
90
91
  "check:deps": "node scripts/check-deps.mjs",
91
92
  "check:forbidden": "node scripts/check-forbidden.mjs",
92
- "check": "npm run build && npm run typecheck && npm run check:deps && npm run check:forbidden && npm test",
93
+ "check:spec-matrix": "node scripts/gen-spec-matrix.mjs --check",
94
+ "check:spec-drift": "node scripts/check-spec-drift.mjs",
95
+ "check": "npm run build && npm run typecheck && npm run check:deps && npm run check:forbidden && npm run check:spec-matrix && npm test",
93
96
  "smoke:pack": "node scripts/smoke-pack.mjs",
94
97
  "bootstrap:npm": "bash scripts/npm-bootstrap.sh",
95
98
  "prepublishOnly": "npm run check"