@jangmanj/mcp-client 0.3.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
@@ -79,16 +79,16 @@ too, with file configuration taking precedence.
79
79
 
80
80
  Not supported yet: MCP prompts/resources exposure to Pi (servers offering only prompts or
81
81
  resources connect but register nothing), elicitation UI (consent prompts decline by
82
- default), task-based tool calls, and OAuth options `callbackPort`/`callbackUrl`/
83
- `scope`/`authServerMetadataUrl` (the bridge uses an ephemeral loopback redirect and the
84
- advertised scopes).
82
+ default), and task-based tool calls.
85
83
 
86
84
  OAuth works out of the box for HTTP servers without a static `Authorization` header: the
87
85
  first 401 marks the server "needs sign-in" in `/mcp`, and `/mcp login <name>` runs the
88
86
  authorization-code + PKCE flow with CIMD/DCR registration through the system browser.
89
87
  Credentials persist in `$PI_CODING_AGENT_DIR/mcp-client-oauth.json` (issuer-keyed);
90
- `/mcp logout <name>` deletes them. Static clients can be set with
91
- `"oauth": { "clientId": "...", "clientSecret": "${SECRET}", "clientName": "..." }`.
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).
92
92
 
93
93
  A running Pi session picks the extension up on `/reload`; fresh starts load it
94
94
  automatically.
@@ -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');
@@ -18,6 +18,14 @@ export interface OAuthConfig {
18
18
  readonly clientId?: string;
19
19
  readonly clientSecret?: string;
20
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;
21
29
  }
22
30
 
23
31
  export interface ResolvedServerConfig {
@@ -169,8 +177,8 @@ function resolveOAuth(
169
177
  where: string,
170
178
  ): OAuthConfig | undefined {
171
179
  if (raw.oauth === undefined) return undefined;
172
- const out: { clientId?: string; clientSecret?: string; clientName?: string } = {};
173
- for (const key of ["clientId", "clientSecret", "clientName"] as const) {
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) {
174
182
  const v = raw.oauth[key];
175
183
  if (v === undefined) continue;
176
184
  if (typeof v !== "string") {
@@ -179,6 +187,11 @@ function resolveOAuth(
179
187
  }
180
188
  out[key] = key === "clientName" ? v : interpolate(v, env, exec, warnings, `${where}.oauth.${key}`);
181
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
+ }
182
195
  return out;
183
196
  }
184
197
 
@@ -7,6 +7,7 @@
7
7
  * iss validation, step-up. This module only connects ports to Pi.
8
8
  */
9
9
 
10
+ import { createServer, type Server } from "node:http";
10
11
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
11
12
  import { dirname } from "node:path";
12
13
  import {
@@ -104,10 +105,65 @@ export interface OAuthProviderHandle {
104
105
  readonly closeRedirect: () => void;
105
106
  }
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
+
107
153
  export async function createOAuthProvider(opts: OAuthProviderOptions): Promise<OAuthProviderHandle> {
108
154
  const { config } = opts;
109
- const redirect = await startLoopbackRedirect("/callback");
110
- const redirectUri = redirect.redirectUri;
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");
111
167
 
112
168
  const consent: AuthorizationConsent = {
113
169
  request: async (prompt, signal) => {
@@ -118,7 +174,7 @@ export async function createOAuthProvider(opts: OAuthProviderOptions): Promise<O
118
174
  if (oauth?.clientId) {
119
175
  const registration: ClientRegistration = {
120
176
  clientId: oauth.clientId,
121
- redirectUris: [redirectUri],
177
+ redirectUris: [effectiveRedirectUri],
122
178
  ...(oauth.clientSecret !== undefined ? { clientSecret: oauth.clientSecret } : {}),
123
179
  };
124
180
  return { decision: "accept", registration };
@@ -138,13 +194,17 @@ export async function createOAuthProvider(opts: OAuthProviderOptions): Promise<O
138
194
 
139
195
  const provider = new OAuthAuthorization({
140
196
  resource: config.url as string,
141
- redirectUri,
197
+ redirectUri: effectiveRedirectUri,
142
198
  redirect,
143
199
  browser: { open: opts.browserOpen ?? openSystemBrowser },
144
200
  credentials: opts.store,
145
201
  consent,
146
202
  serverLabel: config.name,
147
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
+ : {}),
148
208
  fetch: new SafeFetch({
149
209
  allowInsecureDev: opts.allowInsecureAuth ?? false,
150
210
  // Insecure-dev mode also permits loopback targets (local dev servers,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jangmanj/mcp-client",
3
- "version": "0.3.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",