@jangmanj/mcp-client 0.4.0 → 0.6.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 +111 -13
- package/dist/client/events.d.ts +33 -0
- package/dist/client/events.js +84 -0
- package/dist/client/index.d.ts +65 -0
- package/dist/client/index.js +128 -0
- package/dist/core/index.d.ts +7 -1
- package/dist/core/index.js +18 -0
- package/dist/testing/index.d.ts +36 -0
- package/dist/testing/index.js +140 -0
- package/package.json +10 -2
package/README.md
CHANGED
|
@@ -10,6 +10,108 @@ npm install @jangmanj/mcp-client
|
|
|
10
10
|
|
|
11
11
|
## Quickstart
|
|
12
12
|
|
|
13
|
+
Push first: subscribe to events and react as they arrive. Pull (tools, resources) is
|
|
14
|
+
there when you need it.
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { connect } from "@jangmanj/mcp-client/client";
|
|
18
|
+
|
|
19
|
+
const connection = await connect({
|
|
20
|
+
stdio: { command: "npx", args: ["-y", "your-mcp-server"] },
|
|
21
|
+
reconnectOnDrop: true,
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
try {
|
|
25
|
+
// Events extension: live occurrences over events/stream (heartbeat + reconnect).
|
|
26
|
+
const mail = await connection.events.subscribe("mail", { folder: "inbox" });
|
|
27
|
+
for await (const event of mail) {
|
|
28
|
+
console.log(event.eventId, event.data);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Standard MCP subscriptions: tools/prompts/resources list_changed, resource updates.
|
|
32
|
+
const changes = connection.listen({ tools: true });
|
|
33
|
+
await changes.acknowledged;
|
|
34
|
+
for await (const change of changes.events) {
|
|
35
|
+
console.log(change.method); // e.g. notifications/tools/list_changed -> re-list tools
|
|
36
|
+
}
|
|
37
|
+
} finally {
|
|
38
|
+
await connection.close();
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`connection.events` uses the optional `io.modelcontextprotocol/events` extension and
|
|
43
|
+
calls `server/discover` lazily to check support; `subscription.poll()` is available
|
|
44
|
+
when you explicitly want pull. `connection.listen()` is the spec-standard
|
|
45
|
+
`subscriptions/listen` stream.
|
|
46
|
+
|
|
47
|
+
Tools work the same connection, without `Outcome` matching:
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
const tools = await connection.tools.list();
|
|
51
|
+
const result = await connection.tools.call("list_allowed_directories");
|
|
52
|
+
console.log(result.content);
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
`tools.list()` / `tools.call()` return values or throw `McpOutcomeError`. For the full
|
|
56
|
+
protocol surface (MRTR, tasks, uncertain writes), use `connection.ops` directly and
|
|
57
|
+
match on `Outcome.kind`.
|
|
58
|
+
|
|
59
|
+
HTTP servers use `http:` instead of `stdio:`:
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
import { ConfiguredBearer } from "@jangmanj/mcp-client/auth";
|
|
63
|
+
|
|
64
|
+
const connection = await connect({
|
|
65
|
+
http: {
|
|
66
|
+
url: "https://mcp.example.com/mcp",
|
|
67
|
+
authProvider: new ConfiguredBearer({
|
|
68
|
+
resource: "https://mcp.example.com/mcp",
|
|
69
|
+
token: process.env.MCP_TOKEN!,
|
|
70
|
+
}),
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
For interactive OAuth (discovery, PKCE, CIMD/DCR), construct `OAuthAuthorization` from
|
|
76
|
+
`/auth` with your consent/browser/redirect ports and pass it as `authProvider`.
|
|
77
|
+
|
|
78
|
+
## Errors, cancellation, progress
|
|
79
|
+
|
|
80
|
+
- **Simple mode** (`/client`): failures throw `McpOutcomeError`; inspect `error.outcome.kind`
|
|
81
|
+
for `jsonrpc-error`, `transport-failure`, `tool-isError`, etc.
|
|
82
|
+
- **Full mode** (`/ops` + `/core`): every call returns a discriminated `Outcome` instead of
|
|
83
|
+
throwing. `unwrapOutcome(outcome)` converts to throw-style.
|
|
84
|
+
- Pass `signal` (AbortSignal) and `timeoutMs` in request options to cancel or bound a call;
|
|
85
|
+
pass `onProgress` to receive progress notifications. Cancellation is cooperative and
|
|
86
|
+
sends `notifications/cancelled` when the request is already on the wire.
|
|
87
|
+
- `listAll()` follows cursors for you; single-page `list({ cursor })` is available when you
|
|
88
|
+
need manual pagination. Cursors are opaque strings — never parse them.
|
|
89
|
+
|
|
90
|
+
## Testing your own tools
|
|
91
|
+
|
|
92
|
+
`@jangmanj/mcp-client/testing` provides an in-memory transport and a scriptable tool
|
|
93
|
+
server — no child processes or sockets:
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
import { connect } from "@jangmanj/mcp-client/client";
|
|
97
|
+
import { createToolServer } from "@jangmanj/mcp-client/testing";
|
|
98
|
+
|
|
99
|
+
const connection = await connect({
|
|
100
|
+
transport: createToolServer({
|
|
101
|
+
echo: { handler: (args) => ({ content: [{ type: "text", text: String(args.message) }] }) },
|
|
102
|
+
}),
|
|
103
|
+
});
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Throw `FakeJsonRpcError(code, message)` from a handler to simulate protocol errors.
|
|
107
|
+
`transport.push(notification, requestId?)` injects notifications into active request
|
|
108
|
+
streams, so you can test pushed events and `list_changed` without a live server.
|
|
109
|
+
|
|
110
|
+
## Low-level API
|
|
111
|
+
|
|
112
|
+
The quickstart above is a thin wrapper. The underlying pieces remain available when you
|
|
113
|
+
need them:
|
|
114
|
+
|
|
13
115
|
```ts
|
|
14
116
|
import { McpClient } from "@jangmanj/mcp-client";
|
|
15
117
|
import { createOps } from "@jangmanj/mcp-client/ops";
|
|
@@ -19,27 +121,23 @@ const client = new McpClient({
|
|
|
19
121
|
transport: new StdioTransport({ command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", "."] }),
|
|
20
122
|
server: { key: "filesystem" },
|
|
21
123
|
});
|
|
22
|
-
|
|
23
124
|
const ops = createOps(client);
|
|
24
|
-
|
|
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();
|
|
125
|
+
// ... await ops.tools.listAll() / ops.tools.call(...), then await client.close()
|
|
32
126
|
```
|
|
33
127
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
128
|
+
## Compatibility expectations
|
|
129
|
+
|
|
130
|
+
- This library targets **MCP 2026-07-28** (stateless, per-request `_meta`). Older servers
|
|
131
|
+
are detected and diagnosed via era probing; it is not a full 2025-style `initialize` client.
|
|
132
|
+
- Node **>= 22.19**, ESM-first (CJS `require(esm)` works on supported Node versions).
|
|
133
|
+
- Roots, sampling, and logging are deprecated upstream and intentionally not implemented.
|
|
38
134
|
|
|
39
135
|
## Subpath exports
|
|
40
136
|
|
|
41
137
|
- `@jangmanj/mcp-client` (re-exports `./core`)
|
|
42
138
|
- `@jangmanj/mcp-client/core`
|
|
139
|
+
- `@jangmanj/mcp-client/client` (high-level `connect()` API)
|
|
140
|
+
- `@jangmanj/mcp-client/testing` (in-memory transport / fake tool server)
|
|
43
141
|
- `@jangmanj/mcp-client/auth`
|
|
44
142
|
- `@jangmanj/mcp-client/ops`
|
|
45
143
|
- `@jangmanj/mcp-client/mrtr-cache`
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Push-first events facade over @mcp-client/ext-events.
|
|
3
|
+
*
|
|
4
|
+
* subscribe() returns an AsyncIterable of occurrences backed by the live
|
|
5
|
+
* events/stream (with heartbeat + reconnect); poll() is available explicitly
|
|
6
|
+
* for servers or callers that prefer pull.
|
|
7
|
+
*/
|
|
8
|
+
import { type McpClient } from "../core/index.js";
|
|
9
|
+
import { EventsClient, type Obj, type Occurrence } from "../ext-events/index.js";
|
|
10
|
+
export type EventsPollResult = Awaited<ReturnType<EventsClient["poll"]>>;
|
|
11
|
+
export interface EventSubscription extends AsyncIterable<Occurrence> {
|
|
12
|
+
readonly name: string;
|
|
13
|
+
/** Explicit pull; the async iterable itself is push-based. */
|
|
14
|
+
poll(): Promise<EventsPollResult>;
|
|
15
|
+
close(): Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
export interface Events {
|
|
18
|
+
/** List event streams offered by the server. */
|
|
19
|
+
list(): Promise<Obj>;
|
|
20
|
+
/** Subscribe to a named event stream; iterate to receive pushed occurrences. */
|
|
21
|
+
subscribe(name: string, args?: Obj): Promise<EventSubscription>;
|
|
22
|
+
}
|
|
23
|
+
export declare class EventsFacade implements Events {
|
|
24
|
+
#private;
|
|
25
|
+
private readonly connection;
|
|
26
|
+
constructor(connection: {
|
|
27
|
+
readonly client: McpClient;
|
|
28
|
+
});
|
|
29
|
+
setCapabilities(capabilities: unknown): void;
|
|
30
|
+
list(): Promise<Obj>;
|
|
31
|
+
subscribe(name: string, args?: Obj): Promise<EventSubscription>;
|
|
32
|
+
dispose(): void;
|
|
33
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Push-first events facade over @mcp-client/ext-events.
|
|
3
|
+
*
|
|
4
|
+
* subscribe() returns an AsyncIterable of occurrences backed by the live
|
|
5
|
+
* events/stream (with heartbeat + reconnect); poll() is available explicitly
|
|
6
|
+
* for servers or callers that prefer pull.
|
|
7
|
+
*/
|
|
8
|
+
import { NotificationQueue } from "../core/index.js";
|
|
9
|
+
import { createEventsExtension, EventsClient, } from "../ext-events/index.js";
|
|
10
|
+
class EventSubscriptionImpl {
|
|
11
|
+
events;
|
|
12
|
+
id;
|
|
13
|
+
name;
|
|
14
|
+
#queue = new NotificationQueue();
|
|
15
|
+
#handle;
|
|
16
|
+
#closed = false;
|
|
17
|
+
constructor(events, id, name) {
|
|
18
|
+
this.events = events;
|
|
19
|
+
this.id = id;
|
|
20
|
+
this.name = name;
|
|
21
|
+
}
|
|
22
|
+
poll() {
|
|
23
|
+
return this.events.poll(this.id);
|
|
24
|
+
}
|
|
25
|
+
#start() {
|
|
26
|
+
if (this.#handle || this.#closed)
|
|
27
|
+
return;
|
|
28
|
+
this.#handle = this.events.push(this.id, (message) => {
|
|
29
|
+
if (message.type === "event")
|
|
30
|
+
this.#queue.push(message.event);
|
|
31
|
+
else if (message.type === "terminated" || message.type === "error")
|
|
32
|
+
this.#queue.close();
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
[Symbol.asyncIterator]() {
|
|
36
|
+
this.#start();
|
|
37
|
+
return this.#queue[Symbol.asyncIterator]();
|
|
38
|
+
}
|
|
39
|
+
async close() {
|
|
40
|
+
if (this.#closed)
|
|
41
|
+
return;
|
|
42
|
+
this.#closed = true;
|
|
43
|
+
this.#handle?.close();
|
|
44
|
+
this.events.forget(this.id);
|
|
45
|
+
this.#queue.close();
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export class EventsFacade {
|
|
49
|
+
connection;
|
|
50
|
+
#events;
|
|
51
|
+
#capabilities;
|
|
52
|
+
constructor(connection) {
|
|
53
|
+
this.connection = connection;
|
|
54
|
+
}
|
|
55
|
+
setCapabilities(capabilities) {
|
|
56
|
+
this.#capabilities = capabilities;
|
|
57
|
+
}
|
|
58
|
+
async #ensure() {
|
|
59
|
+
if (this.#events)
|
|
60
|
+
return this.#events;
|
|
61
|
+
if (this.#capabilities === undefined) {
|
|
62
|
+
const discovered = await this.connection.client.discover();
|
|
63
|
+
this.#capabilities = discovered.kind === "ok" ? discovered.value.capabilities : null;
|
|
64
|
+
}
|
|
65
|
+
this.#events = new EventsClient({
|
|
66
|
+
extension: createEventsExtension({ enabled: true }),
|
|
67
|
+
peerCapabilities: () => this.#capabilities,
|
|
68
|
+
request: (method, params, opts) => this.connection.client.request(method, params, opts),
|
|
69
|
+
openStream: (method, params, opts) => this.connection.client.openStream(method, params, opts),
|
|
70
|
+
});
|
|
71
|
+
return this.#events;
|
|
72
|
+
}
|
|
73
|
+
async list() {
|
|
74
|
+
return (await this.#ensure()).list();
|
|
75
|
+
}
|
|
76
|
+
async subscribe(name, args = {}) {
|
|
77
|
+
const events = await this.#ensure();
|
|
78
|
+
return new EventSubscriptionImpl(events, events.subscription(name, args), name);
|
|
79
|
+
}
|
|
80
|
+
dispose() {
|
|
81
|
+
this.#events?.dispose();
|
|
82
|
+
this.#events = undefined;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
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
|
+
import { type ListenFilter, type Subscription } from "../mrtr-cache/index.js";
|
|
14
|
+
import { type Events } from "./events.js";
|
|
15
|
+
export interface ConnectBaseOptions {
|
|
16
|
+
/** Server identity; defaults to the command or URL. */
|
|
17
|
+
readonly server?: ServerRef;
|
|
18
|
+
readonly clientInfo?: McpClientOptions["clientInfo"];
|
|
19
|
+
/** Per-request timeout; defaults to the library default. */
|
|
20
|
+
readonly timeoutMs?: number;
|
|
21
|
+
/** Probe server/discover during connect and throw on failure. Default false. */
|
|
22
|
+
readonly discover?: boolean;
|
|
23
|
+
/** Declare the events extension and expose connection.events. Default true. */
|
|
24
|
+
readonly events?: boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Rebuild the connection and retry once after a dropped connection
|
|
27
|
+
* (connect/closed/stream-broken/process-exit). Requires a transport factory
|
|
28
|
+
* or stdio/http options; a bare Transport instance cannot be rebuilt.
|
|
29
|
+
*/
|
|
30
|
+
readonly reconnectOnDrop?: boolean;
|
|
31
|
+
}
|
|
32
|
+
export type ConnectOptions = ConnectBaseOptions & ({
|
|
33
|
+
readonly transport: Transport | (() => Transport);
|
|
34
|
+
} | {
|
|
35
|
+
readonly stdio: StdioTransportOptions;
|
|
36
|
+
} | {
|
|
37
|
+
readonly http: HttpTransportOptions;
|
|
38
|
+
});
|
|
39
|
+
export interface SimpleTools {
|
|
40
|
+
/** All tools, following pagination. Throws McpOutcomeError on failure. */
|
|
41
|
+
list(): Promise<ToolEntry[]>;
|
|
42
|
+
/** Call a tool. Throws McpOutcomeError on protocol/transport failure or isError. */
|
|
43
|
+
call(name: string, args?: unknown, opts?: ToolCallOptions): Promise<ToolCallResult>;
|
|
44
|
+
}
|
|
45
|
+
export interface Connection {
|
|
46
|
+
readonly client: McpClient;
|
|
47
|
+
readonly ops: Ops;
|
|
48
|
+
readonly tools: SimpleTools;
|
|
49
|
+
/** Push-based event subscriptions (events extension). */
|
|
50
|
+
readonly events: Events;
|
|
51
|
+
/** Standard MCP subscriptions/listen (list_changed, resource updates). */
|
|
52
|
+
listen(filter: ListenFilter): Subscription;
|
|
53
|
+
/** Tear down and rebuild the underlying client (new transport). */
|
|
54
|
+
reconnect(): Promise<void>;
|
|
55
|
+
close(opts?: {
|
|
56
|
+
readonly graceMs?: number;
|
|
57
|
+
}): Promise<void>;
|
|
58
|
+
}
|
|
59
|
+
/** Connect to an MCP server over stdio, streamable HTTP, or a custom transport. */
|
|
60
|
+
export declare function connect(options: ConnectOptions): Promise<Connection>;
|
|
61
|
+
export { McpOutcomeError, unwrapOutcome } from "../core/index.js";
|
|
62
|
+
export type { ToolCallOptions, ToolCallResult, ToolEntry } from "../ops/index.js";
|
|
63
|
+
export type { Events, EventSubscription, EventsPollResult } from "./events.js";
|
|
64
|
+
export type { Occurrence } from "../ext-events/index.js";
|
|
65
|
+
export type { ListenFilter, Subscription, ChangeEvent, Acknowledgment } from "../mrtr-cache/index.js";
|
|
@@ -0,0 +1,128 @@
|
|
|
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
|
+
import { createEventsExtension } from "../ext-events/index.js";
|
|
14
|
+
import { SubscriptionManager, } from "../mrtr-cache/index.js";
|
|
15
|
+
import { EventsFacade } from "./events.js";
|
|
16
|
+
const RETRY_KINDS = new Set(["connect", "closed", "stream-broken", "process-exit"]);
|
|
17
|
+
class ConnectionImpl {
|
|
18
|
+
#current;
|
|
19
|
+
#options;
|
|
20
|
+
events;
|
|
21
|
+
#binding = "http";
|
|
22
|
+
#manager;
|
|
23
|
+
#subscriptions = new Set();
|
|
24
|
+
constructor(options) {
|
|
25
|
+
this.#options = options;
|
|
26
|
+
this.#current = this.#build();
|
|
27
|
+
this.events = new EventsFacade(this);
|
|
28
|
+
}
|
|
29
|
+
get client() {
|
|
30
|
+
return this.#current.client;
|
|
31
|
+
}
|
|
32
|
+
get ops() {
|
|
33
|
+
return this.#current.ops;
|
|
34
|
+
}
|
|
35
|
+
#transport() {
|
|
36
|
+
if ("transport" in this.#options) {
|
|
37
|
+
const t = this.#options.transport;
|
|
38
|
+
return typeof t === "function" ? t() : t;
|
|
39
|
+
}
|
|
40
|
+
if ("stdio" in this.#options)
|
|
41
|
+
return new StdioTransport(this.#options.stdio);
|
|
42
|
+
return new HttpTransport(this.#options.http);
|
|
43
|
+
}
|
|
44
|
+
listen(filter) {
|
|
45
|
+
this.#manager ??= new SubscriptionManager({
|
|
46
|
+
open: (method, params) => this.client.openStream(method, params),
|
|
47
|
+
binding: this.#binding,
|
|
48
|
+
serverRef: this.client.server.key,
|
|
49
|
+
reconnect: "on-abrupt",
|
|
50
|
+
});
|
|
51
|
+
const subscription = this.#manager.listen(filter);
|
|
52
|
+
this.#subscriptions.add(subscription);
|
|
53
|
+
return subscription;
|
|
54
|
+
}
|
|
55
|
+
#build() {
|
|
56
|
+
const transport = this.#transport();
|
|
57
|
+
this.#binding = transport.binding === "stdio" ? "stdio" : "http";
|
|
58
|
+
const server = this.#options.server ??
|
|
59
|
+
("stdio" in this.#options
|
|
60
|
+
? { key: this.#options.stdio.command }
|
|
61
|
+
: "http" in this.#options
|
|
62
|
+
? { key: this.#options.http.url }
|
|
63
|
+
: { key: "mcp" });
|
|
64
|
+
const client = new McpClient({
|
|
65
|
+
transport,
|
|
66
|
+
server,
|
|
67
|
+
...(this.#options.events === false
|
|
68
|
+
? {}
|
|
69
|
+
: { extensions: [createEventsExtension({ enabled: true })] }),
|
|
70
|
+
...(this.#options.clientInfo !== undefined ? { clientInfo: this.#options.clientInfo } : {}),
|
|
71
|
+
...(this.#options.timeoutMs !== undefined
|
|
72
|
+
? { defaults: { timeoutMs: this.#options.timeoutMs } }
|
|
73
|
+
: {}),
|
|
74
|
+
});
|
|
75
|
+
return { client, ops: createOps(client) };
|
|
76
|
+
}
|
|
77
|
+
async reconnect() {
|
|
78
|
+
const previous = this.#current;
|
|
79
|
+
this.#current = this.#build();
|
|
80
|
+
this.#manager?.reconnected();
|
|
81
|
+
try {
|
|
82
|
+
await previous.client.close({ graceMs: 500 });
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
// best-effort close of the dropped connection
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
async close(opts) {
|
|
89
|
+
this.events.dispose();
|
|
90
|
+
for (const subscription of this.#subscriptions)
|
|
91
|
+
subscription.close();
|
|
92
|
+
this.#subscriptions.clear();
|
|
93
|
+
await this.#current.client.close(opts);
|
|
94
|
+
}
|
|
95
|
+
tools = {
|
|
96
|
+
list: async () => {
|
|
97
|
+
const outcome = await this.ops.tools.listAll();
|
|
98
|
+
return unwrapOutcome(outcome).items;
|
|
99
|
+
},
|
|
100
|
+
call: async (name, args, opts) => {
|
|
101
|
+
let outcome = await this.ops.tools.call(name, args, opts);
|
|
102
|
+
if (this.#options.reconnectOnDrop &&
|
|
103
|
+
outcome.kind === "transport-failure" &&
|
|
104
|
+
RETRY_KINDS.has(outcome.failure.kind) &&
|
|
105
|
+
!(opts?.signal?.aborted ?? false)) {
|
|
106
|
+
await this.reconnect();
|
|
107
|
+
outcome = await this.ops.tools.call(name, args, opts);
|
|
108
|
+
}
|
|
109
|
+
return unwrapOutcome(outcome);
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/** Connect to an MCP server over stdio, streamable HTTP, or a custom transport. */
|
|
114
|
+
export async function connect(options) {
|
|
115
|
+
const connection = new ConnectionImpl(options);
|
|
116
|
+
if (options.discover) {
|
|
117
|
+
try {
|
|
118
|
+
const discovered = unwrapOutcome(await connection.client.discover());
|
|
119
|
+
connection.events.setCapabilities(discovered.capabilities);
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
await connection.close().catch(() => { });
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return connection;
|
|
127
|
+
}
|
|
128
|
+
export { McpOutcomeError, unwrapOutcome } from "../core/index.js";
|
package/dist/core/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { type Disposable, type Extension } from "./extension.js";
|
|
|
2
2
|
import { type IdGenerator } from "./jsonrpc.js";
|
|
3
3
|
import { type EraState, type LifecyclePolicyOptions, type ProbeOptions } from "./lifecycle.js";
|
|
4
4
|
import type { PortRegistry, Transport } from "./ports.js";
|
|
5
|
-
import { type ClientRequest, type Limits, type NotifyOptions, type RequestOptions } from "./request.js";
|
|
5
|
+
import { type ClientRequest, type Limits, type NotifyOptions, type RequestOptions, type StreamHandle } from "./request.js";
|
|
6
6
|
import type { DiscoverResult } from "./schema/index.js";
|
|
7
7
|
export * as McpSchema from "./schema/index.js";
|
|
8
8
|
export type { DiscoverResult } from "./schema/index.js";
|
|
@@ -50,6 +50,12 @@ export declare class McpClient {
|
|
|
50
50
|
constructor(opts: McpClientOptions);
|
|
51
51
|
request<T = Record<string, unknown>>(method: string, params?: Record<string, unknown>, opts?: RequestOptions): ClientRequest<T>;
|
|
52
52
|
notify(method: string, params?: Record<string, unknown>, opts?: NotifyOptions): Promise<void>;
|
|
53
|
+
/**
|
|
54
|
+
* Open a long-lived request stream (subscriptions/listen, events/stream).
|
|
55
|
+
* Uses the same per-request metadata, id allocation, and lifecycle handling
|
|
56
|
+
* as request(); no default request timeout applies to streams.
|
|
57
|
+
*/
|
|
58
|
+
openStream(method: string, params?: Record<string, unknown>, opts?: RequestOptions): StreamHandle;
|
|
53
59
|
discover(opts?: RequestOptions): ClientRequest<DiscoverResult>;
|
|
54
60
|
/**
|
|
55
61
|
* Probes the server era with server/discover once per server key and caches the verdict in
|
package/dist/core/index.js
CHANGED
|
@@ -61,6 +61,24 @@ export class McpClient {
|
|
|
61
61
|
notify(method, params = {}, opts) {
|
|
62
62
|
return this.manager.notify(method, params, opts);
|
|
63
63
|
}
|
|
64
|
+
/**
|
|
65
|
+
* Open a long-lived request stream (subscriptions/listen, events/stream).
|
|
66
|
+
* Uses the same per-request metadata, id allocation, and lifecycle handling
|
|
67
|
+
* as request(); no default request timeout applies to streams.
|
|
68
|
+
*/
|
|
69
|
+
openStream(method, params = {}, opts = {}) {
|
|
70
|
+
const req = this.manager.request(method, params, {
|
|
71
|
+
...opts,
|
|
72
|
+
stream: true,
|
|
73
|
+
idempotent: opts.idempotent ?? true,
|
|
74
|
+
});
|
|
75
|
+
return {
|
|
76
|
+
id: req.id,
|
|
77
|
+
close: () => req.cancel(),
|
|
78
|
+
done: Promise.resolve(req),
|
|
79
|
+
[Symbol.asyncIterator]: () => req.notifications[Symbol.asyncIterator](),
|
|
80
|
+
};
|
|
81
|
+
}
|
|
64
82
|
discover(opts) {
|
|
65
83
|
return this.manager.request("server/discover", {}, { ...opts, idempotent: true });
|
|
66
84
|
}
|
|
@@ -0,0 +1,36 @@
|
|
|
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, type JsonRpcNotification, type JsonRpcRequest, type RequestId, type Transport, type TransportCall, type 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
|
+
/** Push a notification into one active request stream (or all of them). */
|
|
23
|
+
push(notification: JsonRpcNotification, id?: RequestId): boolean;
|
|
24
|
+
start(msg: JsonRpcRequest, ctx: TransportCall): Exchange;
|
|
25
|
+
notify(_msg: JsonRpcNotification, _ctx: TransportCall): Promise<void>;
|
|
26
|
+
close(): Promise<void>;
|
|
27
|
+
get diagnostics(): AsyncIterable<TransportDiagnostic>;
|
|
28
|
+
}
|
|
29
|
+
export interface FakeTool {
|
|
30
|
+
readonly description?: string;
|
|
31
|
+
readonly inputSchema?: Record<string, unknown>;
|
|
32
|
+
/** Return a CallToolResult-shaped object, or any value to wrap as text content. */
|
|
33
|
+
readonly handler: (args: unknown) => unknown | Promise<unknown>;
|
|
34
|
+
}
|
|
35
|
+
/** A minimal MCP server exposing only tools, suitable for consumer unit tests. */
|
|
36
|
+
export declare function createToolServer(tools: Record<string, FakeTool>): InMemoryTransport;
|
|
@@ -0,0 +1,140 @@
|
|
|
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 { NotificationQueue, } from "../core/index.js";
|
|
11
|
+
/** Throw from a handler to return a JSON-RPC error instead of a result. */
|
|
12
|
+
export class FakeJsonRpcError extends Error {
|
|
13
|
+
code;
|
|
14
|
+
data;
|
|
15
|
+
constructor(code, message, data) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.code = code;
|
|
18
|
+
this.data = data;
|
|
19
|
+
this.name = "FakeJsonRpcError";
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
async function* emptyDiagnostics() {
|
|
23
|
+
// no diagnostics in the in-memory transport
|
|
24
|
+
}
|
|
25
|
+
export class InMemoryTransport {
|
|
26
|
+
binding = "in-memory";
|
|
27
|
+
#handler;
|
|
28
|
+
#streams = new Map();
|
|
29
|
+
#closers = new Map();
|
|
30
|
+
constructor(handler) {
|
|
31
|
+
this.#handler = handler;
|
|
32
|
+
}
|
|
33
|
+
/** Push a notification into one active request stream (or all of them). */
|
|
34
|
+
push(notification, id) {
|
|
35
|
+
if (id !== undefined)
|
|
36
|
+
return this.#streams.get(id)?.push(notification) ?? false;
|
|
37
|
+
let delivered = false;
|
|
38
|
+
for (const queue of this.#streams.values())
|
|
39
|
+
delivered = queue.push(notification) || delivered;
|
|
40
|
+
return delivered;
|
|
41
|
+
}
|
|
42
|
+
start(msg, ctx) {
|
|
43
|
+
const notifications = new NotificationQueue();
|
|
44
|
+
this.#streams.set(msg.id, notifications);
|
|
45
|
+
const aborted = () => ({
|
|
46
|
+
kind: "failure",
|
|
47
|
+
failure: { kind: "closed", message: "aborted" },
|
|
48
|
+
delivery: "delivered-no-response",
|
|
49
|
+
});
|
|
50
|
+
const onAbort = new Promise((resolve) => {
|
|
51
|
+
const finish = () => resolve(aborted());
|
|
52
|
+
this.#closers.set(msg.id, finish);
|
|
53
|
+
if (ctx.signal.aborted)
|
|
54
|
+
finish();
|
|
55
|
+
else
|
|
56
|
+
ctx.signal.addEventListener("abort", finish, { once: true });
|
|
57
|
+
});
|
|
58
|
+
const work = (async () => {
|
|
59
|
+
try {
|
|
60
|
+
const result = await this.#handler(msg);
|
|
61
|
+
return {
|
|
62
|
+
kind: "response",
|
|
63
|
+
message: { jsonrpc: "2.0", id: msg.id, result: result },
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
if (error instanceof FakeJsonRpcError) {
|
|
68
|
+
return {
|
|
69
|
+
kind: "response",
|
|
70
|
+
message: {
|
|
71
|
+
jsonrpc: "2.0",
|
|
72
|
+
id: msg.id,
|
|
73
|
+
error: { code: error.code, message: error.message, ...(error.data !== undefined ? { data: error.data } : {}) },
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
kind: "failure",
|
|
79
|
+
failure: {
|
|
80
|
+
kind: "stream-broken",
|
|
81
|
+
message: error instanceof Error ? error.message : String(error),
|
|
82
|
+
},
|
|
83
|
+
delivery: "delivered-no-response",
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
})();
|
|
87
|
+
const done = Promise.race([work, onAbort]).finally(() => {
|
|
88
|
+
this.#streams.delete(msg.id);
|
|
89
|
+
this.#closers.delete(msg.id);
|
|
90
|
+
notifications.close();
|
|
91
|
+
});
|
|
92
|
+
return { notifications, done };
|
|
93
|
+
}
|
|
94
|
+
async notify(_msg, _ctx) {
|
|
95
|
+
// notifications are accepted and ignored
|
|
96
|
+
}
|
|
97
|
+
async close() {
|
|
98
|
+
for (const finish of [...this.#closers.values()])
|
|
99
|
+
finish();
|
|
100
|
+
}
|
|
101
|
+
get diagnostics() {
|
|
102
|
+
return emptyDiagnostics();
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/** A minimal MCP server exposing only tools, suitable for consumer unit tests. */
|
|
106
|
+
export function createToolServer(tools) {
|
|
107
|
+
return new InMemoryTransport(async (msg) => {
|
|
108
|
+
switch (msg.method) {
|
|
109
|
+
case "server/discover":
|
|
110
|
+
return {
|
|
111
|
+
cacheScope: "public",
|
|
112
|
+
capabilities: { tools: {} },
|
|
113
|
+
supportedVersions: ["2026-07-28"],
|
|
114
|
+
serverInfo: { name: "in-memory", version: "0.0.0" },
|
|
115
|
+
};
|
|
116
|
+
case "tools/list":
|
|
117
|
+
return {
|
|
118
|
+
tools: Object.entries(tools).map(([name, tool]) => ({
|
|
119
|
+
name,
|
|
120
|
+
description: tool.description ?? "",
|
|
121
|
+
inputSchema: tool.inputSchema ?? { type: "object", properties: {} },
|
|
122
|
+
})),
|
|
123
|
+
};
|
|
124
|
+
case "tools/call": {
|
|
125
|
+
const params = (msg.params ?? {});
|
|
126
|
+
const tool = params.name !== undefined ? tools[params.name] : undefined;
|
|
127
|
+
if (!tool)
|
|
128
|
+
throw new FakeJsonRpcError(-32602, `unknown tool: ${String(params.name)}`);
|
|
129
|
+
const result = await tool.handler(params.arguments);
|
|
130
|
+
if (typeof result === "object" && result !== null && "content" in result)
|
|
131
|
+
return result;
|
|
132
|
+
return {
|
|
133
|
+
content: [{ type: "text", text: typeof result === "string" ? result : JSON.stringify(result) }],
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
default:
|
|
137
|
+
throw new FakeJsonRpcError(-32601, `method not found: ${msg.method}`);
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jangmanj/mcp-client",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "MCP 2026-07-28 client library: core, transports, auth, ops, MRTR/cache, OTEL telemetry, and extensions.",
|
|
3
|
+
"version": "0.6.0",
|
|
4
|
+
"description": "MCP 2026-07-28 client library: push events/subscriptions, core, transports, auth, ops, MRTR/cache, OTEL telemetry, and extensions.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "JangMan-J",
|
|
7
7
|
"keywords": [
|
|
@@ -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"
|