@jangmanj/mcp-client 0.5.0 → 0.7.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,27 +10,51 @@ 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
+
13
16
  ```ts
14
17
  import { connect } from "@jangmanj/mcp-client/client";
15
18
 
16
19
  const connection = await connect({
17
- stdio: { command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", "."] },
18
- reconnectOnDrop: true, // optional: rebuild + retry once after a dropped connection
20
+ stdio: { command: "npx", args: ["-y", "your-mcp-server"] },
21
+ reconnectOnDrop: true,
19
22
  });
20
23
 
21
24
  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);
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
+ }
26
37
  } finally {
27
38
  await connection.close();
28
39
  }
29
40
  ```
30
41
 
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`.
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`.
34
58
 
35
59
  HTTP servers use `http:` instead of `stdio:`:
36
60
 
@@ -51,6 +75,43 @@ const connection = await connect({
51
75
  For interactive OAuth (discovery, PKCE, CIMD/DCR), construct `OAuthAuthorization` from
52
76
  `/auth` with your consent/browser/redirect ports and pass it as `authProvider`.
53
77
 
78
+ ## Push on the server side
79
+
80
+ `@jangmanj/mcp-client/server-events` is the modular, transport-agnostic server
81
+ companion: event logs with cursors, live `events/stream`, standard
82
+ `subscriptions/listen`, notices, and optional async tasks. It is deliberately
83
+ not a tools/resources/prompts server framework — mount it in your own host and
84
+ let the host own JSON-RPC dispatch and transports.
85
+
86
+ ```ts
87
+ import { EventBus, EventsServer, SubscriptionsServer, TaskCenter, Notices } from "@jangmanj/mcp-client/server-events";
88
+
89
+ const bus = new EventBus();
90
+ const events = new EventsServer({ bus });
91
+ const subscriptions = new SubscriptionsServer({ capabilities: { tools: { listChanged: true } } });
92
+ const tasks = new TaskCenter({ bus });
93
+ const notices = new Notices(bus);
94
+
95
+ // Ordinary requests return plain results for your host to send:
96
+ const page = events.poll({ name: "mail", arguments: {}, cursor: null });
97
+
98
+ // Long-lived requests use a host channel (notify/finish/onClose):
99
+ // events.stream(channel, { name: "mail", arguments: {}, cursor: null });
100
+ // subscriptions.listen(channel, { notifications: { toolsListChanged: true } });
101
+
102
+ // Application code publishes; subscribed clients receive push notices:
103
+ bus.publish("mail", { subject: "hello" });
104
+ subscriptions.notifyToolsChanged();
105
+ notices.info("ready");
106
+ const task = tasks.create({ pollIntervalMs: 1000 });
107
+ tasks.complete(task.taskId, { ok: true });
108
+ ```
109
+
110
+ Scope: `events/list`, `events/poll`, `events/stream`, `subscriptions/listen`,
111
+ `notifications/*` fanout, and `tasks/get`/`tasks/cancel`/`tasks/update` state.
112
+ Webhook delivery and skills are intentionally out of scope; deprecated MCP
113
+ Logging is not used — notices travel as ordinary events.
114
+
54
115
  ## Errors, cancellation, progress
55
116
 
56
117
  - **Simple mode** (`/client`): failures throw `McpOutcomeError`; inspect `error.outcome.kind`
@@ -80,6 +141,8 @@ const connection = await connect({
80
141
  ```
81
142
 
82
143
  Throw `FakeJsonRpcError(code, message)` from a handler to simulate protocol errors.
144
+ `transport.push(notification, requestId?)` injects notifications into active request
145
+ streams, so you can test pushed events and `list_changed` without a live server.
83
146
 
84
147
  ## Low-level API
85
148
 
@@ -112,6 +175,7 @@ const ops = createOps(client);
112
175
  - `@jangmanj/mcp-client/core`
113
176
  - `@jangmanj/mcp-client/client` (high-level `connect()` API)
114
177
  - `@jangmanj/mcp-client/testing` (in-memory transport / fake tool server)
178
+ - `@jangmanj/mcp-client/server-events` (push-first server building blocks)
115
179
  - `@jangmanj/mcp-client/auth`
116
180
  - `@jangmanj/mcp-client/ops`
117
181
  - `@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
+ }
@@ -10,6 +10,8 @@ import { McpClient, type McpClientOptions, type ServerRef, type Transport } from
10
10
  import { type Ops, type ToolCallOptions, type ToolCallResult, type ToolEntry } from "../ops/index.js";
11
11
  import { type HttpTransportOptions } from "../transport-http/index.js";
12
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";
13
15
  export interface ConnectBaseOptions {
14
16
  /** Server identity; defaults to the command or URL. */
15
17
  readonly server?: ServerRef;
@@ -18,6 +20,8 @@ export interface ConnectBaseOptions {
18
20
  readonly timeoutMs?: number;
19
21
  /** Probe server/discover during connect and throw on failure. Default false. */
20
22
  readonly discover?: boolean;
23
+ /** Declare the events extension and expose connection.events. Default true. */
24
+ readonly events?: boolean;
21
25
  /**
22
26
  * Rebuild the connection and retry once after a dropped connection
23
27
  * (connect/closed/stream-broken/process-exit). Requires a transport factory
@@ -42,6 +46,10 @@ export interface Connection {
42
46
  readonly client: McpClient;
43
47
  readonly ops: Ops;
44
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;
45
53
  /** Tear down and rebuild the underlying client (new transport). */
46
54
  reconnect(): Promise<void>;
47
55
  close(opts?: {
@@ -52,3 +60,6 @@ export interface Connection {
52
60
  export declare function connect(options: ConnectOptions): Promise<Connection>;
53
61
  export { McpOutcomeError, unwrapOutcome } from "../core/index.js";
54
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";
@@ -10,13 +10,21 @@ import { McpClient, unwrapOutcome, } from "../core/index.js";
10
10
  import { createOps, } from "../ops/index.js";
11
11
  import { HttpTransport } from "../transport-http/index.js";
12
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";
13
16
  const RETRY_KINDS = new Set(["connect", "closed", "stream-broken", "process-exit"]);
14
17
  class ConnectionImpl {
15
18
  #current;
16
19
  #options;
20
+ events;
21
+ #binding = "http";
22
+ #manager;
23
+ #subscriptions = new Set();
17
24
  constructor(options) {
18
25
  this.#options = options;
19
26
  this.#current = this.#build();
27
+ this.events = new EventsFacade(this);
20
28
  }
21
29
  get client() {
22
30
  return this.#current.client;
@@ -33,8 +41,20 @@ class ConnectionImpl {
33
41
  return new StdioTransport(this.#options.stdio);
34
42
  return new HttpTransport(this.#options.http);
35
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
+ }
36
55
  #build() {
37
56
  const transport = this.#transport();
57
+ this.#binding = transport.binding === "stdio" ? "stdio" : "http";
38
58
  const server = this.#options.server ??
39
59
  ("stdio" in this.#options
40
60
  ? { key: this.#options.stdio.command }
@@ -44,6 +64,9 @@ class ConnectionImpl {
44
64
  const client = new McpClient({
45
65
  transport,
46
66
  server,
67
+ ...(this.#options.events === false
68
+ ? {}
69
+ : { extensions: [createEventsExtension({ enabled: true })] }),
47
70
  ...(this.#options.clientInfo !== undefined ? { clientInfo: this.#options.clientInfo } : {}),
48
71
  ...(this.#options.timeoutMs !== undefined
49
72
  ? { defaults: { timeoutMs: this.#options.timeoutMs } }
@@ -54,6 +77,7 @@ class ConnectionImpl {
54
77
  async reconnect() {
55
78
  const previous = this.#current;
56
79
  this.#current = this.#build();
80
+ this.#manager?.reconnected();
57
81
  try {
58
82
  await previous.client.close({ graceMs: 500 });
59
83
  }
@@ -62,6 +86,10 @@ class ConnectionImpl {
62
86
  }
63
87
  }
64
88
  async close(opts) {
89
+ this.events.dispose();
90
+ for (const subscription of this.#subscriptions)
91
+ subscription.close();
92
+ this.#subscriptions.clear();
65
93
  await this.#current.client.close(opts);
66
94
  }
67
95
  tools = {
@@ -87,7 +115,8 @@ export async function connect(options) {
87
115
  const connection = new ConnectionImpl(options);
88
116
  if (options.discover) {
89
117
  try {
90
- unwrapOutcome(await connection.client.discover());
118
+ const discovered = unwrapOutcome(await connection.client.discover());
119
+ connection.events.setCapabilities(discovered.capabilities);
91
120
  }
92
121
  catch (error) {
93
122
  await connection.close().catch(() => { });
@@ -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
@@ -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,40 @@
1
+ import { type Clock } from "../core/index.js";
2
+ import { type Obj } from "./types.js";
3
+ export interface ServerOccurrence {
4
+ readonly eventId: string;
5
+ readonly name: string;
6
+ readonly timestamp: string;
7
+ readonly data: unknown;
8
+ readonly cursor: string;
9
+ }
10
+ export interface PollPage {
11
+ readonly events: readonly ServerOccurrence[];
12
+ readonly cursor: string;
13
+ readonly truncated: boolean;
14
+ readonly hasMore: boolean;
15
+ }
16
+ export interface EventBusOptions {
17
+ /** Retained occurrences per name+arguments stream. Default 1000. */
18
+ readonly retain?: number;
19
+ readonly clock?: Clock;
20
+ readonly idGenerator?: () => string;
21
+ }
22
+ /**
23
+ * Named, argument-scoped event logs with opaque cursors and bounded retention.
24
+ * Transport-independent: EventsServer and TaskCenter publish into this bus;
25
+ * hosts can also publish directly for application events/notices.
26
+ */
27
+ export declare class EventBus {
28
+ #private;
29
+ constructor(opts?: EventBusOptions);
30
+ list(): Array<{
31
+ name: string;
32
+ arguments: Obj;
33
+ }>;
34
+ publish(name: string, data: unknown, args?: Obj): ServerOccurrence;
35
+ /** Current end cursor: subscribers starting here receive only new events. */
36
+ endCursor(name: string, args?: Obj): string;
37
+ poll(name: string, args: Obj, cursor: string | null, limit: number): PollPage;
38
+ /** Live subscription; returns an unsubscribe function. */
39
+ subscribe(name: string, args: Obj, fn: (event: ServerOccurrence) => void): () => void;
40
+ }
@@ -0,0 +1,84 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { systemClock } from "../core/index.js";
3
+ import { streamKey } from "./types.js";
4
+ /**
5
+ * Named, argument-scoped event logs with opaque cursors and bounded retention.
6
+ * Transport-independent: EventsServer and TaskCenter publish into this bus;
7
+ * hosts can also publish directly for application events/notices.
8
+ */
9
+ export class EventBus {
10
+ #retain;
11
+ #clock;
12
+ #idGenerator;
13
+ #logs = new Map();
14
+ #listeners = new Map();
15
+ constructor(opts = {}) {
16
+ this.#retain = opts.retain ?? 1000;
17
+ this.#clock = opts.clock ?? systemClock;
18
+ this.#idGenerator = opts.idGenerator ?? randomUUID;
19
+ }
20
+ list() {
21
+ return [...this.#logs.values()].map((log) => ({ name: log.name, arguments: log.args }));
22
+ }
23
+ #log(name, args) {
24
+ const key = streamKey(name, args);
25
+ let log = this.#logs.get(key);
26
+ if (!log) {
27
+ log = { name, args, seq: 0, events: [] };
28
+ this.#logs.set(key, log);
29
+ }
30
+ return log;
31
+ }
32
+ publish(name, data, args = {}) {
33
+ const log = this.#log(name, args);
34
+ log.seq += 1;
35
+ const event = {
36
+ eventId: this.#idGenerator(),
37
+ name,
38
+ timestamp: new Date(this.#clock.now()).toISOString(),
39
+ data,
40
+ cursor: String(log.seq),
41
+ };
42
+ log.events.push(event);
43
+ if (log.events.length > this.#retain)
44
+ log.events.splice(0, log.events.length - this.#retain);
45
+ for (const fn of this.#listeners.get(streamKey(name, args)) ?? [])
46
+ fn(event);
47
+ return event;
48
+ }
49
+ /** Current end cursor: subscribers starting here receive only new events. */
50
+ endCursor(name, args = {}) {
51
+ return String(this.#log(name, args).seq);
52
+ }
53
+ poll(name, args, cursor, limit) {
54
+ const log = this.#log(name, args);
55
+ const after = cursor === null ? 0 : Number.parseInt(cursor, 10);
56
+ if (!Number.isSafeInteger(after) || after < 0)
57
+ throw new Error("invalid events cursor");
58
+ const oldest = log.events.length > 0 ? Number.parseInt(log.events[0].cursor, 10) : log.seq + 1;
59
+ const truncated = after > 0 && after + 1 < oldest;
60
+ const matched = log.events.filter((e) => Number.parseInt(e.cursor, 10) > after);
61
+ const events = matched.slice(0, limit);
62
+ return {
63
+ events,
64
+ cursor: events.length > 0 ? events[events.length - 1].cursor : String(log.seq),
65
+ truncated,
66
+ hasMore: matched.length > events.length,
67
+ };
68
+ }
69
+ /** Live subscription; returns an unsubscribe function. */
70
+ subscribe(name, args, fn) {
71
+ const key = streamKey(name, args);
72
+ let set = this.#listeners.get(key);
73
+ if (!set) {
74
+ set = new Set();
75
+ this.#listeners.set(key, set);
76
+ }
77
+ set.add(fn);
78
+ return () => {
79
+ set.delete(fn);
80
+ if (set.size === 0)
81
+ this.#listeners.delete(key);
82
+ };
83
+ }
84
+ }
@@ -0,0 +1,36 @@
1
+ import { type Clock } from "../core/index.js";
2
+ import { EventBus } from "./bus.js";
3
+ import { type Obj, type PushChannel } from "./types.js";
4
+ export declare const EVENTS_EXTENSION_ID = "io.modelcontextprotocol/events";
5
+ export interface EventsServerOptions {
6
+ readonly bus?: EventBus;
7
+ /** Heartbeat interval for live streams. Default 15000ms. */
8
+ readonly heartbeatMs?: number;
9
+ /** Max occurrences returned by one events/poll. Default 100. */
10
+ readonly pageSize?: number;
11
+ /** Suggested delay for empty polls. Default 1000ms. */
12
+ readonly nextPollMs?: number;
13
+ readonly clock?: Clock;
14
+ }
15
+ /**
16
+ * Server side of io.modelcontextprotocol/events: events/list, events/poll,
17
+ * and live events/stream with active/event/heartbeat/terminated notices.
18
+ * Webhook delivery (events/subscribe with a URL) is intentionally out of scope.
19
+ */
20
+ export declare class EventsServer {
21
+ #private;
22
+ readonly bus: EventBus;
23
+ constructor(opts?: EventsServerOptions);
24
+ capabilities(): Obj;
25
+ list(): Obj;
26
+ poll(params: Obj): Obj;
27
+ /** Open a live stream on a host channel. Null cursor means "new events only". */
28
+ stream(channel: PushChannel, params: Obj): void;
29
+ /** Terminate every live stream, optionally only one name+arguments stream. */
30
+ terminate(name?: string, args?: Obj, error?: unknown): void;
31
+ }
32
+ export declare function readSubscription(params: Obj): {
33
+ name: string;
34
+ args: Obj;
35
+ cursor: string | null;
36
+ };
@@ -0,0 +1,108 @@
1
+ import { systemClock } from "../core/index.js";
2
+ import { EventBus } from "./bus.js";
3
+ import { notification, object, ServerError } from "./types.js";
4
+ export const EVENTS_EXTENSION_ID = "io.modelcontextprotocol/events";
5
+ /**
6
+ * Server side of io.modelcontextprotocol/events: events/list, events/poll,
7
+ * and live events/stream with active/event/heartbeat/terminated notices.
8
+ * Webhook delivery (events/subscribe with a URL) is intentionally out of scope.
9
+ */
10
+ export class EventsServer {
11
+ bus;
12
+ #heartbeatMs;
13
+ #pageSize;
14
+ #nextPollMs;
15
+ #clock;
16
+ #live = new Set();
17
+ constructor(opts = {}) {
18
+ this.bus = opts.bus ?? new EventBus();
19
+ this.#heartbeatMs = opts.heartbeatMs ?? 15_000;
20
+ this.#pageSize = opts.pageSize ?? 100;
21
+ this.#nextPollMs = opts.nextPollMs ?? 1000;
22
+ this.#clock = opts.clock ?? systemClock;
23
+ }
24
+ capabilities() {
25
+ return { extensions: { [EVENTS_EXTENSION_ID]: { revision: "2026-07-28", listChanged: true } } };
26
+ }
27
+ list() {
28
+ return { events: this.bus.list() };
29
+ }
30
+ poll(params) {
31
+ const { name, args, cursor } = readSubscription(params);
32
+ const page = this.bus.poll(name, args, cursor, this.#pageSize);
33
+ return {
34
+ events: page.events,
35
+ cursor: page.cursor,
36
+ ...(page.truncated ? { truncated: true } : {}),
37
+ ...(page.hasMore ? { hasMore: true } : {}),
38
+ nextPollMs: page.hasMore ? 0 : this.#nextPollMs,
39
+ };
40
+ }
41
+ /** Open a live stream on a host channel. Null cursor means "new events only". */
42
+ stream(channel, params) {
43
+ const { name, args, cursor } = readSubscription(params);
44
+ const live = {
45
+ channel,
46
+ name,
47
+ args,
48
+ cursor: cursor ?? this.bus.endCursor(name, args),
49
+ unsubscribe: () => { },
50
+ stopHeartbeat: () => { },
51
+ };
52
+ const send = (event) => {
53
+ live.cursor = event.cursor;
54
+ channel.notify(notification("notifications/events/event", { ...event }, channel.id));
55
+ };
56
+ const truncated = cursor !== null && this.bus.poll(name, args, cursor, 1).truncated;
57
+ channel.notify(notification("notifications/events/active", {
58
+ heartbeatMs: this.#heartbeatMs,
59
+ cursor: live.cursor,
60
+ ...(truncated ? { truncated: true } : {}),
61
+ }, channel.id));
62
+ if (cursor !== null) {
63
+ // Replay retained occurrences after the cursor, then continue live.
64
+ let page = this.bus.poll(name, args, cursor, this.#pageSize);
65
+ for (;;) {
66
+ for (const event of page.events)
67
+ send(event);
68
+ if (!page.hasMore)
69
+ break;
70
+ page = this.bus.poll(name, args, live.cursor, this.#pageSize);
71
+ }
72
+ }
73
+ live.unsubscribe = this.bus.subscribe(name, args, send);
74
+ const heartbeat = () => {
75
+ channel.notify(notification("notifications/events/heartbeat", { cursor: live.cursor }, channel.id));
76
+ live.stopHeartbeat = this.#clock.setTimeout(heartbeat, this.#heartbeatMs);
77
+ };
78
+ live.stopHeartbeat = this.#clock.setTimeout(heartbeat, this.#heartbeatMs);
79
+ this.#live.add(live);
80
+ channel.onClose(() => this.#close(live));
81
+ }
82
+ /** Terminate every live stream, optionally only one name+arguments stream. */
83
+ terminate(name, args = {}, error) {
84
+ for (const live of [...this.#live]) {
85
+ if (name !== undefined && (live.name !== name || live.args !== args))
86
+ continue;
87
+ live.channel.notify(notification("notifications/events/terminated", { ...(error !== undefined ? { error } : {}) }, live.channel.id));
88
+ this.#close(live);
89
+ }
90
+ }
91
+ #close(live) {
92
+ live.unsubscribe();
93
+ live.stopHeartbeat();
94
+ this.#live.delete(live);
95
+ }
96
+ }
97
+ export function readSubscription(params) {
98
+ if (typeof params.name !== "string" || params.name === "")
99
+ throw new ServerError(-32602, "events name required");
100
+ const args = params.arguments === undefined ? {} : params.arguments;
101
+ if (!object(args))
102
+ throw new ServerError(-32602, "events arguments must be an object");
103
+ const cursor = params.cursor;
104
+ if (cursor !== undefined && cursor !== null && typeof cursor !== "string") {
105
+ throw new ServerError(-32602, "events cursor must be a string or null");
106
+ }
107
+ return { name: params.name, args, cursor: cursor ?? null };
108
+ }
@@ -0,0 +1,6 @@
1
+ export * from "./types.js";
2
+ export * from "./bus.js";
3
+ export * from "./events.js";
4
+ export * from "./subscriptions.js";
5
+ export * from "./tasks.js";
6
+ export * from "./notices.js";
@@ -0,0 +1,6 @@
1
+ export * from "./types.js";
2
+ export * from "./bus.js";
3
+ export * from "./events.js";
4
+ export * from "./subscriptions.js";
5
+ export * from "./tasks.js";
6
+ export * from "./notices.js";
@@ -0,0 +1,24 @@
1
+ import type { EventBus } from "./bus.js";
2
+ import { type Obj, type PushChannel } from "./types.js";
3
+ /**
4
+ * Notices are application events, not the deprecated MCP Logging feature.
5
+ * Publish them on a named event stream (default "notices") so clients receive
6
+ * them through the same push path as everything else.
7
+ */
8
+ export declare class Notices {
9
+ private readonly bus;
10
+ private readonly stream;
11
+ constructor(bus: EventBus, stream?: string);
12
+ info(message: string, data?: unknown): void;
13
+ warn(message: string, data?: unknown): void;
14
+ error(message: string, data?: unknown): void;
15
+ }
16
+ /** Request-scoped progress notice (not on the subscriptions/listen stream). */
17
+ export declare function sendProgress(channel: PushChannel, progress: {
18
+ readonly progressToken: string | number;
19
+ readonly progress: number;
20
+ readonly total?: number;
21
+ readonly message?: string;
22
+ }): void;
23
+ /** Request-scoped custom notice. Do not use for list_changed or events traffic. */
24
+ export declare function sendNotice(channel: PushChannel, method: string, params?: Obj): void;
@@ -0,0 +1,31 @@
1
+ import { notification } from "./types.js";
2
+ /**
3
+ * Notices are application events, not the deprecated MCP Logging feature.
4
+ * Publish them on a named event stream (default "notices") so clients receive
5
+ * them through the same push path as everything else.
6
+ */
7
+ export class Notices {
8
+ bus;
9
+ stream;
10
+ constructor(bus, stream = "notices") {
11
+ this.bus = bus;
12
+ this.stream = stream;
13
+ }
14
+ info(message, data) {
15
+ this.bus.publish(this.stream, { level: "info", message, ...(data !== undefined ? { data } : {}) });
16
+ }
17
+ warn(message, data) {
18
+ this.bus.publish(this.stream, { level: "warning", message, ...(data !== undefined ? { data } : {}) });
19
+ }
20
+ error(message, data) {
21
+ this.bus.publish(this.stream, { level: "error", message, ...(data !== undefined ? { data } : {}) });
22
+ }
23
+ }
24
+ /** Request-scoped progress notice (not on the subscriptions/listen stream). */
25
+ export function sendProgress(channel, progress) {
26
+ channel.notify(notification("notifications/progress", { ...progress }));
27
+ }
28
+ /** Request-scoped custom notice. Do not use for list_changed or events traffic. */
29
+ export function sendNotice(channel, method, params = {}) {
30
+ channel.notify(notification(method, params));
31
+ }
@@ -0,0 +1,33 @@
1
+ import { type Obj, type PushChannel } from "./types.js";
2
+ export interface SubscriptionCapabilities {
3
+ readonly tools?: {
4
+ readonly listChanged?: boolean;
5
+ };
6
+ readonly prompts?: {
7
+ readonly listChanged?: boolean;
8
+ };
9
+ readonly resources?: {
10
+ readonly listChanged?: boolean;
11
+ readonly subscribe?: boolean;
12
+ };
13
+ }
14
+ /**
15
+ * Standard MCP subscriptions/listen: capability-filtered grants, ack-first,
16
+ * list_changed and resource-updated fanout, and graceful stream completion.
17
+ * The host calls notify* when its own tools/prompts/resources change.
18
+ */
19
+ export declare class SubscriptionsServer {
20
+ #private;
21
+ constructor(opts?: {
22
+ readonly capabilities?: SubscriptionCapabilities;
23
+ });
24
+ capabilities(): Obj;
25
+ listen(channel: PushChannel, params: Obj): void;
26
+ /** Gracefully end a listen stream (server shutdown or filter replacement). */
27
+ end(channel: PushChannel): void;
28
+ notifyToolsChanged(): void;
29
+ notifyPromptsChanged(): void;
30
+ notifyResourcesChanged(): void;
31
+ notifyResourceUpdated(uri: string): void;
32
+ }
33
+ export declare function requireTaskId(params: Obj): string;
@@ -0,0 +1,77 @@
1
+ import { notification, object, ServerError } from "./types.js";
2
+ /**
3
+ * Standard MCP subscriptions/listen: capability-filtered grants, ack-first,
4
+ * list_changed and resource-updated fanout, and graceful stream completion.
5
+ * The host calls notify* when its own tools/prompts/resources change.
6
+ */
7
+ export class SubscriptionsServer {
8
+ #capabilities;
9
+ #listeners = new Map();
10
+ constructor(opts = {}) {
11
+ this.#capabilities = opts.capabilities ?? {};
12
+ }
13
+ capabilities() {
14
+ return { ...this.#capabilities };
15
+ }
16
+ listen(channel, params) {
17
+ const requested = object(params.notifications) ? params.notifications : {};
18
+ const granted = {};
19
+ const offered = {};
20
+ const kinds = ["tools", "prompts", "resources"];
21
+ for (const kind of kinds) {
22
+ const key = `${kind}ListChanged`;
23
+ if (requested[key] !== true)
24
+ continue;
25
+ const supported = this.#capabilities[kind]?.listChanged === true;
26
+ offered[key] = supported;
27
+ if (supported)
28
+ granted[key] = true;
29
+ }
30
+ if (Array.isArray(requested.resourceSubscriptions)) {
31
+ const uris = requested.resourceSubscriptions.filter((u) => typeof u === "string");
32
+ if (this.#capabilities.resources?.subscribe === true) {
33
+ granted.resourceSubscriptions = [...new Set(uris)];
34
+ offered.resourceSubscriptions = granted.resourceSubscriptions;
35
+ }
36
+ else {
37
+ offered.resourceSubscriptions = [];
38
+ }
39
+ }
40
+ this.#listeners.set(channel.id, { channel, granted });
41
+ // Ack is always the first message on a listen stream.
42
+ channel.notify(notification("notifications/subscriptions/acknowledged", { notifications: offered }, channel.id));
43
+ channel.onClose(() => this.#listeners.delete(channel.id));
44
+ }
45
+ /** Gracefully end a listen stream (server shutdown or filter replacement). */
46
+ end(channel) {
47
+ this.#listeners.delete(channel.id);
48
+ channel.finish({ resultType: "complete", _meta: { "io.modelcontextprotocol/subscriptionId": channel.id } });
49
+ }
50
+ notifyToolsChanged() {
51
+ this.#fanout("toolsListChanged", "notifications/tools/list_changed");
52
+ }
53
+ notifyPromptsChanged() {
54
+ this.#fanout("promptsListChanged", "notifications/prompts/list_changed");
55
+ }
56
+ notifyResourcesChanged() {
57
+ this.#fanout("resourcesListChanged", "notifications/resources/list_changed");
58
+ }
59
+ notifyResourceUpdated(uri) {
60
+ for (const listener of this.#listeners.values()) {
61
+ if (listener.granted.resourceSubscriptions?.includes(uri)) {
62
+ listener.channel.notify(notification("notifications/resources/updated", { uri }, listener.channel.id));
63
+ }
64
+ }
65
+ }
66
+ #fanout(grant, method) {
67
+ for (const listener of this.#listeners.values()) {
68
+ if (listener.granted[grant])
69
+ listener.channel.notify(notification(method, {}, listener.channel.id));
70
+ }
71
+ }
72
+ }
73
+ export function requireTaskId(params) {
74
+ if (typeof params.taskId !== "string" || params.taskId === "")
75
+ throw new ServerError(-32602, "taskId required");
76
+ return params.taskId;
77
+ }
@@ -0,0 +1,43 @@
1
+ import { type Clock } from "../core/index.js";
2
+ import type { EventBus } from "./bus.js";
3
+ import { type Obj, type PushChannel } from "./types.js";
4
+ export declare const TASKS_EXTENSION_ID = "io.modelcontextprotocol/tasks";
5
+ export type TaskStatus = "working" | "input_required" | "completed" | "failed" | "cancelled";
6
+ export interface TaskState extends Obj {
7
+ taskId: string;
8
+ status: TaskStatus;
9
+ ttlMs?: number;
10
+ pollIntervalMs?: number;
11
+ inputRequests?: Record<string, {
12
+ method: string;
13
+ params: Obj;
14
+ }>;
15
+ }
16
+ /**
17
+ * Optional async-task companion to the push center: task handles whose state
18
+ * changes are emitted as notifications/tasks and published on the "tasks"
19
+ * event stream. No tools framework — hosts decide which operations start tasks.
20
+ */
21
+ export declare class TaskCenter {
22
+ #private;
23
+ constructor(opts?: {
24
+ readonly bus?: EventBus;
25
+ readonly clock?: Clock;
26
+ });
27
+ capabilities(): Obj;
28
+ /** Attach a push channel (e.g. a subscriptions/listen channel) for notifications/tasks. */
29
+ attach(channel: PushChannel): void;
30
+ create(init?: {
31
+ taskId?: string;
32
+ ttlMs?: number;
33
+ pollIntervalMs?: number;
34
+ inputRequests?: TaskState["inputRequests"];
35
+ }): TaskState;
36
+ get(params: Obj): TaskState;
37
+ cancel(params: Obj): TaskState;
38
+ /** Client input for an input_required task; resumes work. */
39
+ update(params: Obj): TaskState;
40
+ requestInput(taskId: string, inputRequests: NonNullable<TaskState["inputRequests"]>): TaskState;
41
+ complete(taskId: string, result: Obj): TaskState;
42
+ fail(taskId: string, error: Obj): TaskState;
43
+ }
@@ -0,0 +1,92 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { systemClock } from "../core/index.js";
3
+ import { notification, object, ServerError } from "./types.js";
4
+ import { requireTaskId } from "./subscriptions.js";
5
+ export const TASKS_EXTENSION_ID = "io.modelcontextprotocol/tasks";
6
+ const TERMINAL = new Set(["completed", "failed", "cancelled"]);
7
+ /**
8
+ * Optional async-task companion to the push center: task handles whose state
9
+ * changes are emitted as notifications/tasks and published on the "tasks"
10
+ * event stream. No tools framework — hosts decide which operations start tasks.
11
+ */
12
+ export class TaskCenter {
13
+ #tasks = new Map();
14
+ #clock;
15
+ #bus;
16
+ #channels = new Set();
17
+ constructor(opts = {}) {
18
+ this.#bus = opts.bus;
19
+ this.#clock = opts.clock ?? systemClock;
20
+ }
21
+ capabilities() {
22
+ return { extensions: { [TASKS_EXTENSION_ID]: {} } };
23
+ }
24
+ /** Attach a push channel (e.g. a subscriptions/listen channel) for notifications/tasks. */
25
+ attach(channel) {
26
+ this.#channels.add(channel);
27
+ channel.onClose(() => this.#channels.delete(channel));
28
+ }
29
+ create(init = {}) {
30
+ const state = {
31
+ taskId: init.taskId ?? randomUUID(),
32
+ status: init.inputRequests ? "input_required" : "working",
33
+ createdAt: new Date(this.#clock.now()).toISOString(),
34
+ ...(init.ttlMs !== undefined ? { ttlMs: init.ttlMs } : {}),
35
+ ...(init.pollIntervalMs !== undefined ? { pollIntervalMs: init.pollIntervalMs } : {}),
36
+ ...(init.inputRequests !== undefined ? { inputRequests: init.inputRequests } : {}),
37
+ };
38
+ this.#tasks.set(state.taskId, state);
39
+ this.#emit(state);
40
+ return state;
41
+ }
42
+ get(params) {
43
+ return this.#state(requireTaskId(params));
44
+ }
45
+ cancel(params) {
46
+ const state = this.#state(requireTaskId(params));
47
+ if (TERMINAL.has(state.status))
48
+ return state;
49
+ return this.#set(state.taskId, { status: "cancelled" });
50
+ }
51
+ /** Client input for an input_required task; resumes work. */
52
+ update(params) {
53
+ const state = this.#state(requireTaskId(params));
54
+ if (state.status !== "input_required")
55
+ throw new ServerError(-32602, "task is not awaiting input");
56
+ const inputResponses = params.inputResponses;
57
+ if (!object(inputResponses))
58
+ throw new ServerError(-32602, "inputResponses must be an object");
59
+ const next = { ...state, status: "working", inputResponses };
60
+ delete next.inputRequests;
61
+ return this.#set(state.taskId, next);
62
+ }
63
+ requestInput(taskId, inputRequests) {
64
+ this.#state(taskId);
65
+ return this.#set(taskId, { status: "input_required", inputRequests });
66
+ }
67
+ complete(taskId, result) {
68
+ this.#state(taskId);
69
+ return this.#set(taskId, { status: "completed", result });
70
+ }
71
+ fail(taskId, error) {
72
+ this.#state(taskId);
73
+ return this.#set(taskId, { status: "failed", error });
74
+ }
75
+ #state(taskId) {
76
+ const state = this.#tasks.get(taskId);
77
+ if (!state)
78
+ throw new ServerError(-32602, `unknown task: ${taskId}`);
79
+ return state;
80
+ }
81
+ #set(taskId, patch) {
82
+ const state = { ...this.#state(taskId), ...patch, taskId };
83
+ this.#tasks.set(taskId, state);
84
+ this.#emit(state);
85
+ return state;
86
+ }
87
+ #emit(state) {
88
+ for (const channel of this.#channels)
89
+ channel.notify(notification("notifications/tasks", { ...state }, channel.id));
90
+ this.#bus?.publish("tasks", state, {});
91
+ }
92
+ }
@@ -0,0 +1,25 @@
1
+ import type { JsonRpcNotification, RequestId } from "../core/index.js";
2
+ export type Obj = Record<string, unknown>;
3
+ /**
4
+ * Host-owned channel for one long-lived server response stream.
5
+ * The host transport creates one per subscriptions/listen or events/stream
6
+ * request and delivers notifications/final results to the client.
7
+ */
8
+ export interface PushChannel {
9
+ readonly id: RequestId;
10
+ notify(notification: JsonRpcNotification): void;
11
+ /** Final JSON-RPC result for the stream request (graceful close). */
12
+ finish(result: Obj): void;
13
+ /** Register cleanup for client disconnect/cancel. */
14
+ onClose(fn: () => void): void;
15
+ }
16
+ /** Error with a JSON-RPC code, for hosts to map onto error responses. */
17
+ export declare class ServerError extends Error {
18
+ readonly code: number;
19
+ readonly data?: unknown;
20
+ constructor(code: number, message: string, data?: unknown);
21
+ }
22
+ export declare function notification(method: string, params: Obj, subscriptionId?: RequestId): JsonRpcNotification;
23
+ export declare function object(x: unknown): x is Obj;
24
+ /** Deterministic key for name+arguments subscription identity. */
25
+ export declare function streamKey(name: string, args: Obj): string;
@@ -0,0 +1,34 @@
1
+ /** Error with a JSON-RPC code, for hosts to map onto error responses. */
2
+ export class ServerError 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 = "ServerError";
10
+ }
11
+ }
12
+ export function notification(method, params, subscriptionId) {
13
+ return {
14
+ jsonrpc: "2.0",
15
+ method,
16
+ params: subscriptionId === undefined
17
+ ? params
18
+ : { ...params, _meta: { "io.modelcontextprotocol/subscriptionId": subscriptionId } },
19
+ };
20
+ }
21
+ export function object(x) {
22
+ return typeof x === "object" && x !== null && !Array.isArray(x);
23
+ }
24
+ /** Deterministic key for name+arguments subscription identity. */
25
+ export function streamKey(name, args) {
26
+ const stable = (v) => {
27
+ if (Array.isArray(v))
28
+ return v.map(stable);
29
+ if (object(v))
30
+ return Object.fromEntries(Object.keys(v).sort().map((k) => [k, stable(v[k])]));
31
+ return v;
32
+ };
33
+ return JSON.stringify([name, stable(args)]);
34
+ }
@@ -7,7 +7,7 @@
7
7
  * });
8
8
  * const connection = await connect({ transport });
9
9
  */
10
- import type { Exchange, JsonRpcNotification, JsonRpcRequest, Transport, TransportCall, TransportDiagnostic } from "../core/index.js";
10
+ import { type Exchange, type JsonRpcNotification, type JsonRpcRequest, type RequestId, type Transport, type TransportCall, type TransportDiagnostic } from "../core/index.js";
11
11
  /** Throw from a handler to return a JSON-RPC error instead of a result. */
12
12
  export declare class FakeJsonRpcError extends Error {
13
13
  readonly code: number;
@@ -19,7 +19,9 @@ export declare class InMemoryTransport implements Transport {
19
19
  #private;
20
20
  readonly binding = "in-memory";
21
21
  constructor(handler: InMemoryHandler);
22
- start(msg: JsonRpcRequest, _ctx: TransportCall): Exchange;
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;
23
25
  notify(_msg: JsonRpcNotification, _ctx: TransportCall): Promise<void>;
24
26
  close(): Promise<void>;
25
27
  get diagnostics(): AsyncIterable<TransportDiagnostic>;
@@ -1,3 +1,13 @@
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";
1
11
  /** Throw from a handler to return a JSON-RPC error instead of a result. */
2
12
  export class FakeJsonRpcError extends Error {
3
13
  code;
@@ -9,20 +19,43 @@ export class FakeJsonRpcError extends Error {
9
19
  this.name = "FakeJsonRpcError";
10
20
  }
11
21
  }
12
- async function* emptyNotifications() {
13
- // no notifications in the in-memory transport
14
- }
15
22
  async function* emptyDiagnostics() {
16
23
  // no diagnostics in the in-memory transport
17
24
  }
18
25
  export class InMemoryTransport {
19
26
  binding = "in-memory";
20
27
  #handler;
28
+ #streams = new Map();
29
+ #closers = new Map();
21
30
  constructor(handler) {
22
31
  this.#handler = handler;
23
32
  }
24
- start(msg, _ctx) {
25
- const done = (async () => {
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 () => {
26
59
  try {
27
60
  const result = await this.#handler(msg);
28
61
  return {
@@ -51,13 +84,19 @@ export class InMemoryTransport {
51
84
  };
52
85
  }
53
86
  })();
54
- return { notifications: emptyNotifications(), done };
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 };
55
93
  }
56
94
  async notify(_msg, _ctx) {
57
95
  // notifications are accepted and ignored
58
96
  }
59
97
  async close() {
60
- // nothing to close
98
+ for (const finish of [...this.#closers.values()])
99
+ finish();
61
100
  }
62
101
  get diagnostics() {
63
102
  return emptyDiagnostics();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@jangmanj/mcp-client",
3
- "version": "0.5.0",
4
- "description": "MCP 2026-07-28 client library: core, transports, auth, ops, MRTR/cache, OTEL telemetry, and extensions.",
3
+ "version": "0.7.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": [
@@ -52,6 +52,10 @@
52
52
  "types": "./dist/testing/index.d.ts",
53
53
  "default": "./dist/testing/index.js"
54
54
  },
55
+ "./server-events": {
56
+ "types": "./dist/server-events/index.d.ts",
57
+ "default": "./dist/server-events/index.js"
58
+ },
55
59
  "./auth": {
56
60
  "types": "./dist/auth/index.d.ts",
57
61
  "default": "./dist/auth/index.js"