@jangmanj/mcp-client 0.6.0 → 0.8.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 +56 -0
- package/dist/ext-server-cards/index.d.ts +28 -0
- package/dist/ext-server-cards/index.js +51 -0
- package/dist/server-events/bus.d.ts +40 -0
- package/dist/server-events/bus.js +84 -0
- package/dist/server-events/events.d.ts +36 -0
- package/dist/server-events/events.js +108 -0
- package/dist/server-events/index.d.ts +6 -0
- package/dist/server-events/index.js +6 -0
- package/dist/server-events/notices.d.ts +24 -0
- package/dist/server-events/notices.js +31 -0
- package/dist/server-events/subscriptions.d.ts +33 -0
- package/dist/server-events/subscriptions.js +77 -0
- package/dist/server-events/tasks.d.ts +43 -0
- package/dist/server-events/tasks.js +92 -0
- package/dist/server-events/types.d.ts +25 -0
- package/dist/server-events/types.js +34 -0
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -75,6 +75,61 @@ const connection = await connect({
|
|
|
75
75
|
For interactive OAuth (discovery, PKCE, CIMD/DCR), construct `OAuthAuthorization` from
|
|
76
76
|
`/auth` with your consent/browser/redirect ports and pass it as `authProvider`.
|
|
77
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
|
+
|
|
115
|
+
For discovery metadata, `@jangmanj/mcp-client/ext-server-cards` also includes a
|
|
116
|
+
card builder for servers you operate:
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
import { buildServerCard, buildAiCatalog } from "@jangmanj/mcp-client/ext-server-cards";
|
|
120
|
+
|
|
121
|
+
const card = buildServerCard({
|
|
122
|
+
name: "roger-wilco",
|
|
123
|
+
version: "0.1.0",
|
|
124
|
+
description: "Durable cross-machine mail with push/poll event streams.",
|
|
125
|
+
remotes: [{ type: "streamable-http", url: "https://roger.example.net/mcp", supportedVersions: ["2026-07-28"] }],
|
|
126
|
+
});
|
|
127
|
+
const catalog = buildAiCatalog([card]); // serve as /.well-known/ai-catalog.json
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Cards are advisory only: primitive capability fields are rejected, and live
|
|
131
|
+
`server/discover` remains authoritative.
|
|
132
|
+
|
|
78
133
|
## Errors, cancellation, progress
|
|
79
134
|
|
|
80
135
|
- **Simple mode** (`/client`): failures throw `McpOutcomeError`; inspect `error.outcome.kind`
|
|
@@ -138,6 +193,7 @@ const ops = createOps(client);
|
|
|
138
193
|
- `@jangmanj/mcp-client/core`
|
|
139
194
|
- `@jangmanj/mcp-client/client` (high-level `connect()` API)
|
|
140
195
|
- `@jangmanj/mcp-client/testing` (in-memory transport / fake tool server)
|
|
196
|
+
- `@jangmanj/mcp-client/server-events` (push-first server building blocks)
|
|
141
197
|
- `@jangmanj/mcp-client/auth`
|
|
142
198
|
- `@jangmanj/mcp-client/ops`
|
|
143
199
|
- `@jangmanj/mcp-client/mrtr-cache`
|
|
@@ -77,3 +77,31 @@ export interface ServerCardsExtension extends Extension {
|
|
|
77
77
|
}
|
|
78
78
|
/** Advertises no client capability (EXT-card-8). */
|
|
79
79
|
export declare function createServerCardsExtension(defaults?: DiscoverCardOptions): ServerCardsExtension;
|
|
80
|
+
export declare const DEFAULT_SERVER_CARD_SCHEMA = "https://modelcontextprotocol.io/schemas/server-card.json";
|
|
81
|
+
export interface ServerCardInput {
|
|
82
|
+
readonly $schema?: string;
|
|
83
|
+
readonly name: string;
|
|
84
|
+
readonly version: string;
|
|
85
|
+
readonly description: string;
|
|
86
|
+
readonly title?: string;
|
|
87
|
+
readonly icons?: unknown;
|
|
88
|
+
readonly repository?: unknown;
|
|
89
|
+
readonly websiteUrl?: string;
|
|
90
|
+
readonly remotes?: readonly ServerCardRemote[];
|
|
91
|
+
readonly _meta?: Record<string, unknown>;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Build an advisory Server Card for a server you operate.
|
|
95
|
+
*
|
|
96
|
+
* Cards are discovery metadata only: tools/resources/prompts primitives are
|
|
97
|
+
* rejected so a card cannot become an inferred capability document. Live
|
|
98
|
+
* server/discover remains authoritative.
|
|
99
|
+
*/
|
|
100
|
+
export declare function buildServerCard(input: ServerCardInput): ServerCard;
|
|
101
|
+
/** Wrap cards in the /.well-known/ai-catalog.json document shape. */
|
|
102
|
+
export declare function buildAiCatalog(cards: readonly ServerCard[]): {
|
|
103
|
+
entries: Array<{
|
|
104
|
+
type: "mcp-server-card";
|
|
105
|
+
data: ServerCard;
|
|
106
|
+
}>;
|
|
107
|
+
};
|
|
@@ -196,3 +196,54 @@ export function createServerCardsExtension(defaults = {}) {
|
|
|
196
196
|
discoverFromDomain: (d, o) => discoverFromDomain(d, { ...defaults, ...o }),
|
|
197
197
|
};
|
|
198
198
|
}
|
|
199
|
+
export const DEFAULT_SERVER_CARD_SCHEMA = "https://modelcontextprotocol.io/schemas/server-card.json";
|
|
200
|
+
function required(value, field) {
|
|
201
|
+
if (typeof value !== "string" || value.trim() === "")
|
|
202
|
+
throw new ServerCardError(`card-field-${field}`);
|
|
203
|
+
return value;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Build an advisory Server Card for a server you operate.
|
|
207
|
+
*
|
|
208
|
+
* Cards are discovery metadata only: tools/resources/prompts primitives are
|
|
209
|
+
* rejected so a card cannot become an inferred capability document. Live
|
|
210
|
+
* server/discover remains authoritative.
|
|
211
|
+
*/
|
|
212
|
+
export function buildServerCard(input) {
|
|
213
|
+
for (const primitive of ["tools", "resources", "prompts"]) {
|
|
214
|
+
if (primitive in input)
|
|
215
|
+
throw new ServerCardError("card-primitives-not-allowed");
|
|
216
|
+
}
|
|
217
|
+
const card = {
|
|
218
|
+
$schema: input.$schema ?? DEFAULT_SERVER_CARD_SCHEMA,
|
|
219
|
+
name: required(input.name, "name"),
|
|
220
|
+
version: required(input.version, "version"),
|
|
221
|
+
description: required(input.description, "description"),
|
|
222
|
+
};
|
|
223
|
+
if (input.title !== undefined)
|
|
224
|
+
card["title"] = input.title;
|
|
225
|
+
if (input.websiteUrl !== undefined)
|
|
226
|
+
card["websiteUrl"] = input.websiteUrl;
|
|
227
|
+
if (input.icons !== undefined)
|
|
228
|
+
card["icons"] = input.icons;
|
|
229
|
+
if (input.repository !== undefined)
|
|
230
|
+
card["repository"] = input.repository;
|
|
231
|
+
if (input.remotes !== undefined) {
|
|
232
|
+
card["remotes"] = input.remotes.map((remote) => {
|
|
233
|
+
const type = required(remote.type, "remote-type");
|
|
234
|
+
const url = required(remote.url, "remote-url");
|
|
235
|
+
const supportedVersions = remote.supportedVersions ?? [];
|
|
236
|
+
if (!Array.isArray(supportedVersions) || supportedVersions.some((v) => typeof v !== "string")) {
|
|
237
|
+
throw new ServerCardError("card-field-supportedVersions");
|
|
238
|
+
}
|
|
239
|
+
return { ...remote, type, url, supportedVersions: [...supportedVersions] };
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
if (input._meta !== undefined)
|
|
243
|
+
card["_meta"] = input._meta;
|
|
244
|
+
return card;
|
|
245
|
+
}
|
|
246
|
+
/** Wrap cards in the /.well-known/ai-catalog.json document shape. */
|
|
247
|
+
export function buildAiCatalog(cards) {
|
|
248
|
+
return { entries: cards.map((card) => ({ type: "mcp-server-card", data: card })) };
|
|
249
|
+
}
|
|
@@ -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,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
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jangmanj/mcp-client",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
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",
|
|
@@ -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"
|