@jangmanj/mcp-client 0.4.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`
@@ -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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jangmanj/mcp-client",
3
- "version": "0.4.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"