@jangmanj/mcp-client 0.3.0 → 0.5.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
@@ -10,6 +10,82 @@ npm install @jangmanj/mcp-client
10
10
 
11
11
  ## Quickstart
12
12
 
13
+ ```ts
14
+ import { connect } from "@jangmanj/mcp-client/client";
15
+
16
+ const connection = await connect({
17
+ stdio: { command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", "."] },
18
+ reconnectOnDrop: true, // optional: rebuild + retry once after a dropped connection
19
+ });
20
+
21
+ try {
22
+ const tools = await connection.tools.list();
23
+ console.log(tools.map((t) => t.name));
24
+ const result = await connection.tools.call("list_allowed_directories");
25
+ console.log(result.content);
26
+ } finally {
27
+ await connection.close();
28
+ }
29
+ ```
30
+
31
+ `tools.list()` / `tools.call()` return values or throw `McpOutcomeError` — no `Outcome`
32
+ matching required. For the full protocol surface (MRTR, tasks, uncertain writes), use
33
+ `connection.ops` directly and match on `Outcome.kind`.
34
+
35
+ HTTP servers use `http:` instead of `stdio:`:
36
+
37
+ ```ts
38
+ import { ConfiguredBearer } from "@jangmanj/mcp-client/auth";
39
+
40
+ const connection = await connect({
41
+ http: {
42
+ url: "https://mcp.example.com/mcp",
43
+ authProvider: new ConfiguredBearer({
44
+ resource: "https://mcp.example.com/mcp",
45
+ token: process.env.MCP_TOKEN!,
46
+ }),
47
+ },
48
+ });
49
+ ```
50
+
51
+ For interactive OAuth (discovery, PKCE, CIMD/DCR), construct `OAuthAuthorization` from
52
+ `/auth` with your consent/browser/redirect ports and pass it as `authProvider`.
53
+
54
+ ## Errors, cancellation, progress
55
+
56
+ - **Simple mode** (`/client`): failures throw `McpOutcomeError`; inspect `error.outcome.kind`
57
+ for `jsonrpc-error`, `transport-failure`, `tool-isError`, etc.
58
+ - **Full mode** (`/ops` + `/core`): every call returns a discriminated `Outcome` instead of
59
+ throwing. `unwrapOutcome(outcome)` converts to throw-style.
60
+ - Pass `signal` (AbortSignal) and `timeoutMs` in request options to cancel or bound a call;
61
+ pass `onProgress` to receive progress notifications. Cancellation is cooperative and
62
+ sends `notifications/cancelled` when the request is already on the wire.
63
+ - `listAll()` follows cursors for you; single-page `list({ cursor })` is available when you
64
+ need manual pagination. Cursors are opaque strings — never parse them.
65
+
66
+ ## Testing your own tools
67
+
68
+ `@jangmanj/mcp-client/testing` provides an in-memory transport and a scriptable tool
69
+ server — no child processes or sockets:
70
+
71
+ ```ts
72
+ import { connect } from "@jangmanj/mcp-client/client";
73
+ import { createToolServer } from "@jangmanj/mcp-client/testing";
74
+
75
+ const connection = await connect({
76
+ transport: createToolServer({
77
+ echo: { handler: (args) => ({ content: [{ type: "text", text: String(args.message) }] }) },
78
+ }),
79
+ });
80
+ ```
81
+
82
+ Throw `FakeJsonRpcError(code, message)` from a handler to simulate protocol errors.
83
+
84
+ ## Low-level API
85
+
86
+ The quickstart above is a thin wrapper. The underlying pieces remain available when you
87
+ need them:
88
+
13
89
  ```ts
14
90
  import { McpClient } from "@jangmanj/mcp-client";
15
91
  import { createOps } from "@jangmanj/mcp-client/ops";
@@ -19,27 +95,23 @@ const client = new McpClient({
19
95
  transport: new StdioTransport({ command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", "."] }),
20
96
  server: { key: "filesystem" },
21
97
  });
22
-
23
98
  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();
99
+ // ... await ops.tools.listAll() / ops.tools.call(...), then await client.close()
32
100
  ```
33
101
 
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`).
102
+ ## Compatibility expectations
103
+
104
+ - This library targets **MCP 2026-07-28** (stateless, per-request `_meta`). Older servers
105
+ are detected and diagnosed via era probing; it is not a full 2025-style `initialize` client.
106
+ - Node **>= 22.19**, ESM-first (CJS `require(esm)` works on supported Node versions).
107
+ - Roots, sampling, and logging are deprecated upstream and intentionally not implemented.
38
108
 
39
109
  ## Subpath exports
40
110
 
41
111
  - `@jangmanj/mcp-client` (re-exports `./core`)
42
112
  - `@jangmanj/mcp-client/core`
113
+ - `@jangmanj/mcp-client/client` (high-level `connect()` API)
114
+ - `@jangmanj/mcp-client/testing` (in-memory transport / fake tool server)
43
115
  - `@jangmanj/mcp-client/auth`
44
116
  - `@jangmanj/mcp-client/ops`
45
117
  - `@jangmanj/mcp-client/mrtr-cache`
@@ -79,16 +151,16 @@ too, with file configuration taking precedence.
79
151
 
80
152
  Not supported yet: MCP prompts/resources exposure to Pi (servers offering only prompts or
81
153
  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).
154
+ default), and task-based tool calls.
85
155
 
86
156
  OAuth works out of the box for HTTP servers without a static `Authorization` header: the
87
157
  first 401 marks the server "needs sign-in" in `/mcp`, and `/mcp login <name>` runs the
88
158
  authorization-code + PKCE flow with CIMD/DCR registration through the system browser.
89
159
  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": "..." }`.
160
+ `/mcp logout <name>` deletes them. The full `oauth` config shape is supported:
161
+ `clientId`, `clientSecret`, `clientName`, `callbackPort`, `callbackUrl` (loopback HTTP),
162
+ `scope` (space-separated, merged with advertised scopes), and `authServerMetadataUrl`
163
+ (trusted as configured, skips PRM discovery).
92
164
 
93
165
  A running Pi session picks the extension up on `/reload`; fresh starts load it
94
166
  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');
@@ -0,0 +1,54 @@
1
+ /**
2
+ * High-level consumer API: connect to an MCP server and call tools without
3
+ * assembling McpClient/ops/transports or matching on Outcome for every call.
4
+ *
5
+ * Simple mode (this module): list()/call() return values or throw
6
+ * McpOutcomeError. Full mode: use `connection.ops` directly and match on
7
+ * Outcome kinds (mrtr-interim, task-handle, uncertain-write, ...).
8
+ */
9
+ import { McpClient, type McpClientOptions, type ServerRef, type Transport } from "../core/index.js";
10
+ import { type Ops, type ToolCallOptions, type ToolCallResult, type ToolEntry } from "../ops/index.js";
11
+ import { type HttpTransportOptions } from "../transport-http/index.js";
12
+ import { type StdioTransportOptions } from "../transport-stdio/index.js";
13
+ export interface ConnectBaseOptions {
14
+ /** Server identity; defaults to the command or URL. */
15
+ readonly server?: ServerRef;
16
+ readonly clientInfo?: McpClientOptions["clientInfo"];
17
+ /** Per-request timeout; defaults to the library default. */
18
+ readonly timeoutMs?: number;
19
+ /** Probe server/discover during connect and throw on failure. Default false. */
20
+ readonly discover?: boolean;
21
+ /**
22
+ * Rebuild the connection and retry once after a dropped connection
23
+ * (connect/closed/stream-broken/process-exit). Requires a transport factory
24
+ * or stdio/http options; a bare Transport instance cannot be rebuilt.
25
+ */
26
+ readonly reconnectOnDrop?: boolean;
27
+ }
28
+ export type ConnectOptions = ConnectBaseOptions & ({
29
+ readonly transport: Transport | (() => Transport);
30
+ } | {
31
+ readonly stdio: StdioTransportOptions;
32
+ } | {
33
+ readonly http: HttpTransportOptions;
34
+ });
35
+ export interface SimpleTools {
36
+ /** All tools, following pagination. Throws McpOutcomeError on failure. */
37
+ list(): Promise<ToolEntry[]>;
38
+ /** Call a tool. Throws McpOutcomeError on protocol/transport failure or isError. */
39
+ call(name: string, args?: unknown, opts?: ToolCallOptions): Promise<ToolCallResult>;
40
+ }
41
+ export interface Connection {
42
+ readonly client: McpClient;
43
+ readonly ops: Ops;
44
+ readonly tools: SimpleTools;
45
+ /** Tear down and rebuild the underlying client (new transport). */
46
+ reconnect(): Promise<void>;
47
+ close(opts?: {
48
+ readonly graceMs?: number;
49
+ }): Promise<void>;
50
+ }
51
+ /** Connect to an MCP server over stdio, streamable HTTP, or a custom transport. */
52
+ export declare function connect(options: ConnectOptions): Promise<Connection>;
53
+ export { McpOutcomeError, unwrapOutcome } from "../core/index.js";
54
+ export type { ToolCallOptions, ToolCallResult, ToolEntry } from "../ops/index.js";
@@ -0,0 +1,99 @@
1
+ /**
2
+ * High-level consumer API: connect to an MCP server and call tools without
3
+ * assembling McpClient/ops/transports or matching on Outcome for every call.
4
+ *
5
+ * Simple mode (this module): list()/call() return values or throw
6
+ * McpOutcomeError. Full mode: use `connection.ops` directly and match on
7
+ * Outcome kinds (mrtr-interim, task-handle, uncertain-write, ...).
8
+ */
9
+ import { McpClient, unwrapOutcome, } from "../core/index.js";
10
+ import { createOps, } from "../ops/index.js";
11
+ import { HttpTransport } from "../transport-http/index.js";
12
+ import { StdioTransport } from "../transport-stdio/index.js";
13
+ const RETRY_KINDS = new Set(["connect", "closed", "stream-broken", "process-exit"]);
14
+ class ConnectionImpl {
15
+ #current;
16
+ #options;
17
+ constructor(options) {
18
+ this.#options = options;
19
+ this.#current = this.#build();
20
+ }
21
+ get client() {
22
+ return this.#current.client;
23
+ }
24
+ get ops() {
25
+ return this.#current.ops;
26
+ }
27
+ #transport() {
28
+ if ("transport" in this.#options) {
29
+ const t = this.#options.transport;
30
+ return typeof t === "function" ? t() : t;
31
+ }
32
+ if ("stdio" in this.#options)
33
+ return new StdioTransport(this.#options.stdio);
34
+ return new HttpTransport(this.#options.http);
35
+ }
36
+ #build() {
37
+ const transport = this.#transport();
38
+ const server = this.#options.server ??
39
+ ("stdio" in this.#options
40
+ ? { key: this.#options.stdio.command }
41
+ : "http" in this.#options
42
+ ? { key: this.#options.http.url }
43
+ : { key: "mcp" });
44
+ const client = new McpClient({
45
+ transport,
46
+ server,
47
+ ...(this.#options.clientInfo !== undefined ? { clientInfo: this.#options.clientInfo } : {}),
48
+ ...(this.#options.timeoutMs !== undefined
49
+ ? { defaults: { timeoutMs: this.#options.timeoutMs } }
50
+ : {}),
51
+ });
52
+ return { client, ops: createOps(client) };
53
+ }
54
+ async reconnect() {
55
+ const previous = this.#current;
56
+ this.#current = this.#build();
57
+ try {
58
+ await previous.client.close({ graceMs: 500 });
59
+ }
60
+ catch {
61
+ // best-effort close of the dropped connection
62
+ }
63
+ }
64
+ async close(opts) {
65
+ await this.#current.client.close(opts);
66
+ }
67
+ tools = {
68
+ list: async () => {
69
+ const outcome = await this.ops.tools.listAll();
70
+ return unwrapOutcome(outcome).items;
71
+ },
72
+ call: async (name, args, opts) => {
73
+ let outcome = await this.ops.tools.call(name, args, opts);
74
+ if (this.#options.reconnectOnDrop &&
75
+ outcome.kind === "transport-failure" &&
76
+ RETRY_KINDS.has(outcome.failure.kind) &&
77
+ !(opts?.signal?.aborted ?? false)) {
78
+ await this.reconnect();
79
+ outcome = await this.ops.tools.call(name, args, opts);
80
+ }
81
+ return unwrapOutcome(outcome);
82
+ },
83
+ };
84
+ }
85
+ /** Connect to an MCP server over stdio, streamable HTTP, or a custom transport. */
86
+ export async function connect(options) {
87
+ const connection = new ConnectionImpl(options);
88
+ if (options.discover) {
89
+ try {
90
+ unwrapOutcome(await connection.client.discover());
91
+ }
92
+ catch (error) {
93
+ await connection.close().catch(() => { });
94
+ throw error;
95
+ }
96
+ }
97
+ return connection;
98
+ }
99
+ export { McpOutcomeError, unwrapOutcome } from "../core/index.js";
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Consumer test utilities: an in-memory Transport and a tiny scriptable MCP
3
+ * tool server. No processes, sockets, or fixtures required.
4
+ *
5
+ * const transport = createToolServer({
6
+ * echo: { handler: (args) => ({ content: [{ type: "text", text: String(args.message) }] }) },
7
+ * });
8
+ * const connection = await connect({ transport });
9
+ */
10
+ import type { Exchange, JsonRpcNotification, JsonRpcRequest, Transport, TransportCall, TransportDiagnostic } from "../core/index.js";
11
+ /** Throw from a handler to return a JSON-RPC error instead of a result. */
12
+ export declare class FakeJsonRpcError extends Error {
13
+ readonly code: number;
14
+ readonly data?: unknown;
15
+ constructor(code: number, message: string, data?: unknown);
16
+ }
17
+ export type InMemoryHandler = (msg: JsonRpcRequest) => unknown | Promise<unknown>;
18
+ export declare class InMemoryTransport implements Transport {
19
+ #private;
20
+ readonly binding = "in-memory";
21
+ constructor(handler: InMemoryHandler);
22
+ start(msg: JsonRpcRequest, _ctx: TransportCall): Exchange;
23
+ notify(_msg: JsonRpcNotification, _ctx: TransportCall): Promise<void>;
24
+ close(): Promise<void>;
25
+ get diagnostics(): AsyncIterable<TransportDiagnostic>;
26
+ }
27
+ export interface FakeTool {
28
+ readonly description?: string;
29
+ readonly inputSchema?: Record<string, unknown>;
30
+ /** Return a CallToolResult-shaped object, or any value to wrap as text content. */
31
+ readonly handler: (args: unknown) => unknown | Promise<unknown>;
32
+ }
33
+ /** A minimal MCP server exposing only tools, suitable for consumer unit tests. */
34
+ export declare function createToolServer(tools: Record<string, FakeTool>): InMemoryTransport;
@@ -0,0 +1,101 @@
1
+ /** Throw from a handler to return a JSON-RPC error instead of a result. */
2
+ export class FakeJsonRpcError extends Error {
3
+ code;
4
+ data;
5
+ constructor(code, message, data) {
6
+ super(message);
7
+ this.code = code;
8
+ this.data = data;
9
+ this.name = "FakeJsonRpcError";
10
+ }
11
+ }
12
+ async function* emptyNotifications() {
13
+ // no notifications in the in-memory transport
14
+ }
15
+ async function* emptyDiagnostics() {
16
+ // no diagnostics in the in-memory transport
17
+ }
18
+ export class InMemoryTransport {
19
+ binding = "in-memory";
20
+ #handler;
21
+ constructor(handler) {
22
+ this.#handler = handler;
23
+ }
24
+ start(msg, _ctx) {
25
+ const done = (async () => {
26
+ try {
27
+ const result = await this.#handler(msg);
28
+ return {
29
+ kind: "response",
30
+ message: { jsonrpc: "2.0", id: msg.id, result: result },
31
+ };
32
+ }
33
+ catch (error) {
34
+ if (error instanceof FakeJsonRpcError) {
35
+ return {
36
+ kind: "response",
37
+ message: {
38
+ jsonrpc: "2.0",
39
+ id: msg.id,
40
+ error: { code: error.code, message: error.message, ...(error.data !== undefined ? { data: error.data } : {}) },
41
+ },
42
+ };
43
+ }
44
+ return {
45
+ kind: "failure",
46
+ failure: {
47
+ kind: "stream-broken",
48
+ message: error instanceof Error ? error.message : String(error),
49
+ },
50
+ delivery: "delivered-no-response",
51
+ };
52
+ }
53
+ })();
54
+ return { notifications: emptyNotifications(), done };
55
+ }
56
+ async notify(_msg, _ctx) {
57
+ // notifications are accepted and ignored
58
+ }
59
+ async close() {
60
+ // nothing to close
61
+ }
62
+ get diagnostics() {
63
+ return emptyDiagnostics();
64
+ }
65
+ }
66
+ /** A minimal MCP server exposing only tools, suitable for consumer unit tests. */
67
+ export function createToolServer(tools) {
68
+ return new InMemoryTransport(async (msg) => {
69
+ switch (msg.method) {
70
+ case "server/discover":
71
+ return {
72
+ cacheScope: "public",
73
+ capabilities: { tools: {} },
74
+ supportedVersions: ["2026-07-28"],
75
+ serverInfo: { name: "in-memory", version: "0.0.0" },
76
+ };
77
+ case "tools/list":
78
+ return {
79
+ tools: Object.entries(tools).map(([name, tool]) => ({
80
+ name,
81
+ description: tool.description ?? "",
82
+ inputSchema: tool.inputSchema ?? { type: "object", properties: {} },
83
+ })),
84
+ };
85
+ case "tools/call": {
86
+ const params = (msg.params ?? {});
87
+ const tool = params.name !== undefined ? tools[params.name] : undefined;
88
+ if (!tool)
89
+ throw new FakeJsonRpcError(-32602, `unknown tool: ${String(params.name)}`);
90
+ const result = await tool.handler(params.arguments);
91
+ if (typeof result === "object" && result !== null && "content" in result)
92
+ return result;
93
+ return {
94
+ content: [{ type: "text", text: typeof result === "string" ? result : JSON.stringify(result) }],
95
+ };
96
+ }
97
+ default:
98
+ throw new FakeJsonRpcError(-32601, `method not found: ${msg.method}`);
99
+ }
100
+ });
101
+ }
@@ -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.5.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",
@@ -44,6 +44,14 @@
44
44
  "types": "./dist/core/index.d.ts",
45
45
  "default": "./dist/core/index.js"
46
46
  },
47
+ "./client": {
48
+ "types": "./dist/client/index.d.ts",
49
+ "default": "./dist/client/index.js"
50
+ },
51
+ "./testing": {
52
+ "types": "./dist/testing/index.d.ts",
53
+ "default": "./dist/testing/index.js"
54
+ },
47
55
  "./auth": {
48
56
  "types": "./dist/auth/index.d.ts",
49
57
  "default": "./dist/auth/index.js"