@acid-cat/cli 0.19.0 → 0.21.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.
Files changed (42) hide show
  1. package/README.md +32 -2
  2. package/conformance/fixture.acidcat.json +96 -0
  3. package/dist/conform-LH9KgQ9-.js +5045 -0
  4. package/dist/index.d.ts +164 -4
  5. package/dist/index.js +96 -4
  6. package/dist/main.d.ts +1 -2
  7. package/dist/main.js +1090 -7
  8. package/package.json +4 -3
  9. package/dist/catalog.d.ts +0 -12
  10. package/dist/catalog.js +0 -149
  11. package/dist/conform/check.d.ts +0 -47
  12. package/dist/conform/check.js +0 -178
  13. package/dist/conform/cli.d.ts +0 -5
  14. package/dist/conform/cli.js +0 -721
  15. package/dist/conform/http.d.ts +0 -6
  16. package/dist/conform/http.js +0 -297
  17. package/dist/conform/index.d.ts +0 -69
  18. package/dist/conform/index.js +0 -80
  19. package/dist/conform/mcp-stdio.d.ts +0 -7
  20. package/dist/conform/mcp-stdio.js +0 -291
  21. package/dist/conform/mcp.d.ts +0 -47
  22. package/dist/conform/mcp.js +0 -754
  23. package/dist/conform/poll.d.ts +0 -13
  24. package/dist/conform/poll.js +0 -295
  25. package/dist/conform/properties.d.ts +0 -12
  26. package/dist/conform/properties.js +0 -151
  27. package/dist/conform/serve.d.ts +0 -12
  28. package/dist/conform/serve.js +0 -96
  29. package/dist/conform/server-card.d.ts +0 -5
  30. package/dist/conform/server-card.js +0 -142
  31. package/dist/conform/sse.d.ts +0 -9
  32. package/dist/conform/sse.js +0 -53
  33. package/dist/conform/webhook.d.ts +0 -30
  34. package/dist/conform/webhook.js +0 -481
  35. package/dist/conform/webmcp.d.ts +0 -53
  36. package/dist/conform/webmcp.js +0 -232
  37. package/dist/json/catalog.schema.json.js +0 -170
  38. package/dist/json/fixture.acidcat.json.js +0 -396
  39. package/dist/json/package.json.js +0 -3
  40. package/dist/json/server-card.schema.json.js +0 -281
  41. package/dist/json.d.ts +0 -11
  42. package/dist/json.js +0 -13
@@ -1,754 +0,0 @@
1
- import { isArrayOf, isObject, isStringArray, memberOf, parseJson, readJson } from "../json.js";
2
- import { Checks, FORBIDDEN_ORIGIN, eventIdsOf, expect, expectEqual, expectOccurrence, fixture, idsOf, sorted, until } from "./check.js";
3
- import { checkPoll } from "./poll.js";
4
- import { sseReader } from "./sse.js";
5
- import { checkServerCard, signingKeysOf } from "./server-card.js";
6
- import { checkWebhook } from "./webhook.js";
7
- import { MCP_EVENTS_EXTENSION, MCP_HEADER_MISMATCH, MCP_HEARTBEAT_MAX_MS, MCP_HEARTBEAT_MIN_MS, MCP_PROTOCOL_VERSION_KEY, MCP_SUBSCRIPTION_ID, bundle, encodeMcpHeaderValue, mcpParamHeaders, targetCatalog } from "@acid-cat/spec-ts";
8
- import { randomUUID } from "node:crypto";
9
- import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
10
- // src/conform/mcp.ts
11
- const RULE = "spec/surfaces/mcp.md";
12
- /** Runtimes measure the idle time of a stream with timers of 1 ms resolution, so a heartbeat can come 1 ms early. */
13
- const TIMER_RESOLUTION_MS = 1;
14
- async function mcpClient(url, signal, handshake = false) {
15
- const client = new Client({
16
- name: "acid-cat-conform",
17
- version: "0.1.0"
18
- }, handshake ? { versionNegotiation: { mode: "legacy" } } : { versionNegotiation: { mode: { pin: "2026-07-28" } } });
19
- await client.connect(new StreamableHTTPClientTransport(new URL(url)), signal ? { signal } : void 0);
20
- return client;
21
- }
22
- const textOf = (result) => {
23
- const first = result.content[0];
24
- return parseJson(first?.type === "text" ? first.text : "null");
25
- };
26
- async function checkMcp(url, options) {
27
- const checks = new Checks("mcp", options.deadline, options.signal);
28
- let client;
29
- await checks.run("an MCP client connects with revision 2026-07-28", `${RULE}#http`, async (signal) => {
30
- client = await mcpClient(url, signal);
31
- });
32
- if (client === void 0) return checks;
33
- const mcp = client;
34
- await checkTools(checks, mcp);
35
- await mcp.close();
36
- const post = (signal, { headers = {}, body }) => fetch(url, {
37
- method: "POST",
38
- body,
39
- headers: {
40
- "Content-Type": "application/json",
41
- ...headers
42
- },
43
- signal
44
- });
45
- const rejection = async (response, status, code) => {
46
- expectEqual(response.status, status, "status");
47
- expectEqual(response.headers.get("Cache-Control"), "no-store", "Cache-Control");
48
- if (code !== void 0) expectEqual(memberOf(memberOf(await readJson(response), "error"), "code"), code, "JSON-RPC error code");
49
- };
50
- await checks.run("a method other than POST is rejected with 405", `${RULE}#http`, async (signal) => {
51
- const response = await fetch(url, { signal });
52
- await rejection(response, 405);
53
- expectEqual(response.headers.get("Allow"), "POST", "Allow");
54
- });
55
- await checks.run("an origin that is not allowed is rejected with 403", `${RULE}#http`, async (signal) => {
56
- await rejection(await post(signal, {
57
- headers: { Origin: FORBIDDEN_ORIGIN },
58
- body: "{}"
59
- }), 403);
60
- });
61
- await checks.run("a media type other than JSON is rejected with 415", `${RULE}#http`, async (signal) => {
62
- await rejection(await post(signal, {
63
- headers: { "Content-Type": "text/plain" },
64
- body: "{}"
65
- }), 415);
66
- });
67
- await checks.run("a body over the limit is rejected with 413 and -32600", `${RULE}#http`, async (signal) => {
68
- await rejection(await post(signal, { body: " ".repeat(options.maximumBytes + 1) }), 413, -32600);
69
- });
70
- await checks.run("a body that is not JSON is rejected with 400 and -32700", `${RULE}#http`, async (signal) => {
71
- await rejection(await post(signal, { body: "{" }), 400, -32700);
72
- });
73
- await checks.run("a body that is not UTF-8 is rejected with 400", `${RULE}#http`, async (signal) => {
74
- await rejection(await post(signal, { body: new Uint8Array([
75
- 123,
76
- 255,
77
- 125
78
- ]) }), 400);
79
- });
80
- await checkHeaders(checks, url);
81
- const card = await checkServerCard(checks, url, httpChannel(url));
82
- await checkEvents(checks, httpChannel(url), {
83
- transport: "http",
84
- poll: options.poll,
85
- webhook: options.webhook !== void 0
86
- });
87
- if (options.webhook !== void 0) await checkWebhook(checks, url, options.webhook, card === void 0 ? [] : signingKeysOf(card));
88
- if (options.handshake) await checkHandshake(checks, url, options.deadline);
89
- return checks;
90
- }
91
- const mcpCatalog = targetCatalog(fixture, "mcp");
92
- function inputSchemaOf(method, name) {
93
- if (typeof name !== "string") return void 0;
94
- const entries = method === "tools/call" ? mcpCatalog.capabilities : method.startsWith("events/") ? mcpCatalog.events ?? {} : {};
95
- const input = Object.hasOwn(entries, name) ? entries[name]?.input : void 0;
96
- return input === void 0 ? void 0 : bundle(input, mcpCatalog.$defs ?? {});
97
- }
98
- function mcpRequestHeaders(method, params) {
99
- return {
100
- "Mcp-Method": method,
101
- ...typeof params.name === "string" ? { "Mcp-Name": encodeMcpHeaderValue(params.name) } : {},
102
- ...mcpParamHeaders(inputSchemaOf(method, params.name), params.arguments)
103
- };
104
- }
105
- async function checkHeaders(checks, url) {
106
- const send = (signal, method, params, headers) => fetch(url, {
107
- method: "POST",
108
- headers: {
109
- "Content-Type": "application/json",
110
- Accept: "application/json, text/event-stream",
111
- "MCP-Protocol-Version": EVENTS_REVISION,
112
- ...headers
113
- },
114
- body: JSON.stringify({
115
- jsonrpc: "2.0",
116
- id: `conform-${randomUUID()}`,
117
- method,
118
- params: {
119
- ...params,
120
- _meta: META
121
- }
122
- }),
123
- signal
124
- });
125
- const rejected = async (response, what) => {
126
- expectEqual(response.status, 400, `the status of ${what}`);
127
- expectEqual(memberOf(memberOf(await readJson(response), "error"), "code"), MCP_HEADER_MISMATCH, `the JSON-RPC error code of ${what}`);
128
- };
129
- const accepted = async (response, what) => {
130
- expectEqual(response.status, 200, `the status of ${what}`);
131
- if (response.headers.get("Content-Type")?.startsWith("text/event-stream") === true) {
132
- const reader = sseReader(response);
133
- try {
134
- const first = await reader.next();
135
- expectEqual(memberOf(parseJson(first?.data ?? "null"), "method"), "notifications/events/active", `the first message of ${what}`);
136
- } finally {
137
- await reader.cancel();
138
- }
139
- return;
140
- }
141
- const code = memberOf(memberOf(await readJson(response), "error"), "code");
142
- expect(code !== MCP_HEADER_MISMATCH, `${what} must not be a header mismatch`);
143
- };
144
- const named = (method, name, headers = {}) => ({
145
- "Mcp-Method": method,
146
- "Mcp-Name": name,
147
- ...headers
148
- });
149
- const echo = {
150
- name: "fixture.echo",
151
- arguments: { text: "x" }
152
- };
153
- const ticks = {
154
- name: "fixture.ticks",
155
- arguments: {
156
- count: 1,
157
- key: "k"
158
- }
159
- };
160
- await checks.run("a request whose Mcp-Method header is not its method gets 400 and HeaderMismatch", `${RULE}#http`, async (signal) => {
161
- await rejected(await send(signal, "tools/call", echo, named("tools/list", "fixture.echo")), "tools/call with Mcp-Method: tools/list");
162
- await rejected(await send(signal, "events/stream", ticks, named("events/poll", "fixture.ticks", { "Mcp-Param-Key": "k" })), "events/stream with Mcp-Method: events/poll");
163
- });
164
- await checks.run("tools/call and events/stream with no Mcp-Name header, or another name, get 400 and HeaderMismatch", `${RULE}#http`, async (signal) => {
165
- await rejected(await send(signal, "tools/call", echo, { "Mcp-Method": "tools/call" }), "tools/call with no Mcp-Name");
166
- await rejected(await send(signal, "tools/call", echo, named("tools/call", "fixture.refuse")), "tools/call with another Mcp-Name");
167
- await rejected(await send(signal, "events/stream", ticks, {
168
- "Mcp-Method": "events/stream",
169
- "Mcp-Param-Key": "k"
170
- }), "events/stream with no Mcp-Name");
171
- await rejected(await send(signal, "events/stream", ticks, named("events/stream", "fixture.watch", { "Mcp-Param-Key": "k" })), "events/stream with another Mcp-Name");
172
- });
173
- await checks.run("an Mcp-Name header in the base64 form is decoded before the comparison", `${RULE}#http`, async (signal) => {
174
- const base64 = (text) => `=?base64?${Buffer.from(text).toString("base64")}?=`;
175
- await accepted(await send(signal, "tools/call", echo, named("tools/call", base64("fixture.echo"))), "tools/call with Mcp-Name in the base64 form");
176
- await accepted(await send(signal, "events/stream", ticks, named("events/stream", base64("fixture.ticks"), { "Mcp-Param-Key": "k" })), "events/stream with Mcp-Name in the base64 form");
177
- });
178
- for (const { kind, method, name, args, absent, header, value, other, base64 } of [{
179
- kind: "a tool",
180
- method: "tools/call",
181
- name: "fixture.switch.set",
182
- args: { on: true },
183
- absent: {},
184
- header: "Mcp-Param-On",
185
- value: "true",
186
- other: "false",
187
- base64: "=?base64?dHJ1ZQ==?="
188
- }, {
189
- kind: "an event",
190
- method: "events/stream",
191
- name: "fixture.ticks",
192
- args: {
193
- count: 1,
194
- key: "k"
195
- },
196
- absent: { count: 1 },
197
- header: "Mcp-Param-Key",
198
- value: "k",
199
- other: "j",
200
- base64: "=?base64?aw==?="
201
- }]) await checks.run(`the Mcp-Param header of an annotated argument of ${kind} must agree with the argument, and is not expected for an absent argument`, `${RULE}#http`, async (signal) => {
202
- const params = {
203
- name,
204
- arguments: args
205
- };
206
- await rejected(await send(signal, method, params, named(method, name)), `${method} with no ${header}`);
207
- await rejected(await send(signal, method, params, named(method, name, { [header]: other })), `${method} with another ${header}`);
208
- await accepted(await send(signal, method, params, named(method, name, { [header]: value })), `${method} with ${header}: ${value}`);
209
- await accepted(await send(signal, method, params, named(method, name, { [header]: base64 })), `${method} with ${header} in the base64 form`);
210
- await accepted(await send(signal, method, {
211
- name,
212
- arguments: absent
213
- }, named(method, name)), `${method} with no argument and no ${header}`);
214
- });
215
- await checks.run("a header value in the base64 form keeps a leading U+FEFF", `${RULE}#headers`, async (signal) => {
216
- const header = { "Mcp-Param-Key": "=?base64?77u/aw==?=" };
217
- await accepted(await send(signal, "events/stream", {
218
- name: "fixture.ticks",
219
- arguments: {
220
- count: 1,
221
- key: "k"
222
- }
223
- }, named("events/stream", "fixture.ticks", header)), "events/stream with key U+FEFF k");
224
- await rejected(await send(signal, "events/stream", ticks, named("events/stream", "fixture.ticks", header)), "events/stream with key k and the base64 of U+FEFF k");
225
- });
226
- }
227
- const ANCHOR = `${RULE}#earlier-revisions-through-http`;
228
- async function checkHandshake(checks, url, deadline) {
229
- const handshakeChecks = new Checks("mcp 2025-11-25", deadline, checks.signal);
230
- let client;
231
- await handshakeChecks.run("an MCP client connects with the initialize handshake of revision 2025-11-25", ANCHOR, async (signal) => {
232
- client = await mcpClient(url, signal, true);
233
- expectEqual(client.getNegotiatedProtocolVersion(), "2025-11-25", "the revision of the session");
234
- });
235
- if (client !== void 0) {
236
- await checkTools(handshakeChecks, client);
237
- await client.close();
238
- }
239
- const rpc = (signal, message, version) => fetch(url, {
240
- method: "POST",
241
- body: JSON.stringify({
242
- jsonrpc: "2.0",
243
- ...message
244
- }),
245
- headers: {
246
- "Content-Type": "application/json",
247
- ...version === void 0 ? {} : { "MCP-Protocol-Version": version }
248
- },
249
- signal
250
- });
251
- await handshakeChecks.run("initialize gives the revision of the client, and the server keeps no session", ANCHOR, async (signal) => {
252
- const response = await rpc(signal, {
253
- id: 1,
254
- method: "initialize",
255
- params: {
256
- protocolVersion: "2025-11-25",
257
- capabilities: {},
258
- clientInfo: {
259
- name: "acid-cat-conform",
260
- version: "0.1.0"
261
- }
262
- }
263
- });
264
- expectEqual(response.status, 200, "status");
265
- expectEqual(response.headers.get("Mcp-Session-Id"), null, "Mcp-Session-Id");
266
- const result = memberOf(await readJson(response), "result");
267
- expectEqual(memberOf(result, "protocolVersion"), "2025-11-25", "protocolVersion");
268
- const extensions = memberOf(memberOf(result, "capabilities"), "extensions");
269
- expect(memberOf(extensions, MCP_EVENTS_EXTENSION) === void 0, `the capabilities of initialize must not have the events extension, got ${JSON.stringify(extensions)}`);
270
- });
271
- await handshakeChecks.run("a notification of a revision with a handshake gets 202", ANCHOR, async (signal) => {
272
- expectEqual((await rpc(signal, { method: "notifications/initialized" }, "2025-11-25")).status, 202, "status");
273
- });
274
- checks.results.push(...handshakeChecks.results);
275
- }
276
- async function checkTools(checks, mcp) {
277
- const call = (signal, name, args) => mcp.callTool({
278
- name,
279
- arguments: args
280
- }, { signal });
281
- await checks.run("the instructions are the description of the catalog", `${RULE}#server`, () => {
282
- expectEqual(mcp.getInstructions(), fixture.description, "instructions");
283
- });
284
- await checks.run("tools/list gives each available capability of the target", `${RULE}#tools`, async (signal) => {
285
- const { tools } = await mcp.listTools(void 0, { signal });
286
- expectEqual(sorted(tools.map((tool) => tool.name)), idsOf("mcp"), "tools");
287
- });
288
- await checks.run("tools have their hints and output schemas", `${RULE}#tools`, async (signal) => {
289
- const { tools } = await mcp.listTools(void 0, { signal });
290
- const echo = tools.find((tool) => tool.name === "fixture.echo");
291
- const refuse = tools.find((tool) => tool.name === "fixture.refuse");
292
- const switchSet = tools.find((tool) => tool.name === "fixture.switch.set");
293
- expect(echo?.annotations?.readOnlyHint === true, "fixture.echo must have readOnlyHint: true");
294
- expect(refuse?.annotations?.readOnlyHint !== true, "fixture.refuse must not have readOnlyHint: true");
295
- const signalTool = tools.find((tool) => tool.name === "fixture.signal");
296
- expect(switchSet?.annotations?.destructiveHint === true, "fixture.switch.set must have destructiveHint: true");
297
- expect(switchSet?.annotations?.idempotentHint === true, "fixture.switch.set must have idempotentHint: true");
298
- expect(signalTool?.annotations?.destructiveHint === false, "fixture.signal must have destructiveHint: false");
299
- expect(signalTool?.annotations?.idempotentHint === false, "fixture.signal must have idempotentHint: false");
300
- expect(refuse?.annotations?.destructiveHint !== false, "fixture.refuse has no destructive member, so it must have no destructiveHint or the MCP default true");
301
- expect(refuse?.annotations?.idempotentHint !== true, "fixture.refuse has no idempotent member, so it must have no idempotentHint or the MCP default false");
302
- expect(echo?.outputSchema?.type === "object", "fixture.echo must have an object outputSchema");
303
- expect(refuse?.outputSchema === void 0, "fixture.refuse has no object output, so it must have no outputSchema");
304
- expect(echo?.inputSchema.type === "object", "an inputSchema must be an object");
305
- });
306
- await checks.run("a value is a tool result with structured content", `${RULE}#tools`, async (signal) => {
307
- const result = await call(signal, "fixture.echo", { text: "hello" });
308
- expect(result.isError !== true, "a value must not be an error result");
309
- expectEqual(result.structuredContent, { text: "hello" }, "structuredContent");
310
- expectEqual(textOf(result), { text: "hello" }, "text content");
311
- });
312
- await checks.run("a failure is an error result with ok: false", `${RULE}#tools`, async (signal) => {
313
- const result = await call(signal, "fixture.refuse", {});
314
- expect(result.isError === true, "a failure must be an error result");
315
- const body = textOf(result);
316
- expect(memberOf(body, "ok") === false && memberOf(memberOf(body, "error"), "_tag") === "Refused", `expected { ok: false, error: { _tag: "Refused" } }, got ${JSON.stringify(body)}`);
317
- });
318
- await checks.run("a defect is an internal call failure with no internal details", `${RULE}#tools`, async (signal) => {
319
- const result = await call(signal, "fixture.crash", {});
320
- const body = textOf(result);
321
- expect(isObject(body), `expected an object, got ${JSON.stringify(body)}`);
322
- expect(result.isError === true && body.kind === "internal" && !("ok" in body), `expected { kind: "internal" }, got ${JSON.stringify(body)}`);
323
- const message = typeof body.message === "string" ? body.message : "";
324
- expect(!/\n\s+at /.test(message), "the message must not contain a stack trace");
325
- });
326
- await checks.run("an input that does not agree with its schema is invalid-input", `${RULE}#tools`, async (signal) => {
327
- const result = await call(signal, "fixture.echo", { text: 1 });
328
- expectEqual(memberOf(textOf(result), "kind"), "invalid-input", "kind");
329
- });
330
- await checks.run("a capability outside the target is an unknown tool", `${RULE}#tools`, async (signal) => {
331
- const error = await call(signal, "fixture.hidden", {}).then(() => void 0, (caught) => caught);
332
- expect(memberOf(error, "code") === -32602, `expected the JSON-RPC error -32602, got ${JSON.stringify(error)}`);
333
- });
334
- await checks.run("an unavailable capability is not listed", `${RULE}#tools`, async (signal) => {
335
- await call(signal, "fixture.switch.set", { on: false });
336
- try {
337
- const { tools } = await mcp.listTools(void 0, { signal });
338
- expect(!tools.some((tool) => tool.name === "fixture.toggle"), "fixture.toggle must not be listed while it is unavailable");
339
- } finally {
340
- await call(AbortSignal.timeout(checks.deadline), "fixture.switch.set", { on: true });
341
- }
342
- });
343
- }
344
- const EVENTS_REVISION = "2026-07-28";
345
- const META = {
346
- [MCP_PROTOCOL_VERSION_KEY]: EVENTS_REVISION,
347
- "io.modelcontextprotocol/clientCapabilities": {}
348
- };
349
- function httpChannel(url, headers = {}) {
350
- const post = (id, method, params, signal) => fetch(url, {
351
- method: "POST",
352
- headers: {
353
- ...headers,
354
- "Content-Type": "application/json",
355
- Accept: "application/json, text/event-stream",
356
- "MCP-Protocol-Version": EVENTS_REVISION,
357
- ...mcpRequestHeaders(method, params)
358
- },
359
- body: JSON.stringify({
360
- jsonrpc: "2.0",
361
- id,
362
- method,
363
- params: {
364
- ...params,
365
- _meta: META
366
- }
367
- }),
368
- signal
369
- });
370
- const messagesOf = (response, close) => {
371
- if (response.headers.get("Content-Type")?.startsWith("text/event-stream") !== true) {
372
- let read = false;
373
- return {
374
- next: async () => {
375
- if (read) return void 0;
376
- read = true;
377
- const message = await readJson(response);
378
- expect(isObject(message), `expected a JSON-RPC message, got ${JSON.stringify(message)}`);
379
- return message;
380
- },
381
- cancel: async () => close()
382
- };
383
- }
384
- const reader = sseReader(response);
385
- return {
386
- next: async () => {
387
- const event = await reader.next();
388
- if (event === void 0) return void 0;
389
- const message = parseJson(event.data);
390
- expect(isObject(message), `each server-sent event must hold one JSON-RPC message, got ${JSON.stringify(event.data)}`);
391
- return message;
392
- },
393
- cancel: async () => close()
394
- };
395
- };
396
- let next = 0;
397
- return {
398
- async request(method, params, signal) {
399
- const response = await post(`conform-${next += 1}`, method, params, signal);
400
- const message = await messagesOf(response, () => void 0).next();
401
- if (message === void 0) throw new Error(`the response to ${method} has no message`);
402
- return message;
403
- },
404
- async stream(id, params, signal) {
405
- const controller = new AbortController();
406
- const response = await post(id, "events/stream", params, AbortSignal.any([signal, controller.signal]));
407
- return messagesOf(response, () => controller.abort());
408
- }
409
- };
410
- }
411
- function expectHeartbeatGrant(granted, expected) {
412
- if (expected !== void 0) expectEqual(granted, expected, "the heartbeatMs of notifications/events/active");
413
- else expect(typeof granted === "number" && Number.isSafeInteger(granted) && granted >= 1, `notifications/events/active must grant a heartbeatMs that is a positive integer, got ${JSON.stringify(granted)}`);
414
- }
415
- const subscriptionOf = (message) => memberOf(memberOf(memberOf(message, "params") ?? memberOf(message, "result"), "_meta"), MCP_SUBSCRIPTION_ID);
416
- const paramsOf = (message) => {
417
- const params = memberOf(message, "params");
418
- expect(isObject(params), `expected a notification with params, got ${JSON.stringify(message)}`);
419
- const { _meta: _, ...rest } = params;
420
- return rest;
421
- };
422
- const DELIVERY_ORDER = [
423
- "push",
424
- "poll",
425
- "webhook"
426
- ];
427
- function eventRequests(channel) {
428
- const resultOf = async (method, params, signal) => {
429
- const message = await channel.request(method, params, signal);
430
- const result = memberOf(message, "result");
431
- expect(isObject(result), `${method} must give a result, got ${JSON.stringify(message)}`);
432
- return result;
433
- };
434
- const errorOf = (message) => {
435
- const error = memberOf(message, "error");
436
- expect(isObject(error), `expected a JSON-RPC error, got ${JSON.stringify(message)}`);
437
- return error;
438
- };
439
- const tool = async (name, args, signal) => memberOf(await resultOf("tools/call", {
440
- name,
441
- arguments: args
442
- }, signal), "structuredContent");
443
- const watching = async (signal) => {
444
- const keys = memberOf(await tool("fixture.watching", {}, signal), "keys");
445
- expect(isStringArray(keys), `fixture.watching must give a list of keys, got ${JSON.stringify(keys)}`);
446
- return keys;
447
- };
448
- const signalKey = async (key, value, signal) => memberOf(await tool("fixture.signal", {
449
- key,
450
- value
451
- }, signal), "delivered");
452
- return {
453
- resultOf,
454
- errorOf,
455
- tool,
456
- watching,
457
- signalKey
458
- };
459
- }
460
- const count = (keys, key) => keys.filter((each) => each === key).length;
461
- async function checkEvents(checks, channel, options) {
462
- const RULE_EVENTS = `${RULE}#events`;
463
- const { resultOf, errorOf, watching, signalKey } = eventRequests(channel);
464
- const notification = async (stream, id, method) => {
465
- const message = await stream.next();
466
- expect(message !== void 0 && message.method === method, `expected ${method}, got ${JSON.stringify(message)}`);
467
- expectEqual(subscriptionOf(message), id, `the subscription id of ${method}`);
468
- return message;
469
- };
470
- const occurrence = async (stream, id, name) => expectOccurrence(paramsOf(await notification(stream, id, "notifications/events/event")), name);
471
- const active = async (stream, id, heartbeatMs) => {
472
- const { heartbeatMs: granted, ...rest } = paramsOf(await notification(stream, id, "notifications/events/active"));
473
- expectEqual(rest, { truncated: false }, "the params of notifications/events/active, without heartbeatMs");
474
- expectHeartbeatGrant(granted, heartbeatMs);
475
- };
476
- const complete = async (stream, id) => {
477
- const message = await stream.next();
478
- expect(message !== void 0 && message.id === id, `expected the result of events/stream, got ${JSON.stringify(message)}`);
479
- expectEqual(memberOf(memberOf(message, "result"), "resultType"), "complete", "resultType");
480
- expectEqual(subscriptionOf(message), id, "the subscription id of the result");
481
- expectEqual(await stream.next(), void 0, "the stream after the result");
482
- };
483
- const streamId = () => `conform-${randomUUID()}`;
484
- await checks.run("server/discover declares the events extension", RULE_EVENTS, async (signal) => {
485
- const result = await resultOf("server/discover", {}, signal);
486
- const extensions = memberOf(memberOf(result, "capabilities"), "extensions");
487
- expect(isObject(memberOf(extensions, MCP_EVENTS_EXTENSION)), `the capabilities must have the extension ${MCP_EVENTS_EXTENSION}, got ${JSON.stringify(result)}`);
488
- });
489
- let delivery = [];
490
- await checks.run("events/list gives each event of the target, with the delivery modes of the server and its schemas", RULE_EVENTS, async (signal) => {
491
- const result = await resultOf("events/list", {}, signal);
492
- const entries = result.events;
493
- if (!isArrayOf(entries, isObject)) throw new Error(`events/list must give a list of events, got ${JSON.stringify(result)}`);
494
- expectEqual(sorted(entries.map((entry) => String(entry.name))), eventIdsOf("mcp"), "names");
495
- const first = entries[0]?.delivery;
496
- expect(isStringArray(first), `the delivery of each event must be a list of modes, got ${JSON.stringify(first)}`);
497
- expectEqual(first, DELIVERY_ORDER.filter((mode) => first.includes(mode)), "the delivery modes, in the order push, poll, webhook, each once");
498
- expect(first.includes("push"), `the server must serve push delivery, got ${JSON.stringify(first)}`);
499
- if (options.transport === "stdio") expect(!first.includes("webhook"), "through stdio, the server must not serve webhook delivery");
500
- if (options.webhook) expect(first.includes("webhook"), `webhook delivery is on, so the delivery must have webhook, got ${JSON.stringify(first)}`);
501
- delivery = first;
502
- for (const entry of entries) {
503
- const name = String(entry.name);
504
- expectEqual(entry.description, fixture.events?.[name]?.description, `description of ${name}`);
505
- expectEqual(entry.delivery, first, `delivery of ${name}`);
506
- expectEqual(memberOf(entry.inputSchema, "type"), "object", `the type of the inputSchema of ${name}`);
507
- expectEqual(memberOf(entry.payloadSchema, "type"), "object", `the type of the payloadSchema of ${name}`);
508
- }
509
- expectEqual(result.resultType, "complete", "resultType");
510
- expect(!("nextCursor" in result), "the result must have no nextCursor");
511
- });
512
- for (const [name, params, code, kind] of [
513
- [
514
- "events/stream of an event outside the target is NotFound, with the kind event",
515
- {
516
- name: "fixture.secret",
517
- arguments: {}
518
- },
519
- -32023,
520
- "event"
521
- ],
522
- [
523
- "events/stream of the id of a capability is NotFound",
524
- {
525
- name: "fixture.echo",
526
- arguments: { text: "x" }
527
- },
528
- -32023,
529
- "event"
530
- ],
531
- [
532
- "events/stream with invalid input is the error -32602",
533
- {
534
- name: "fixture.ticks",
535
- arguments: { count: 101 }
536
- },
537
- -32602,
538
- void 0
539
- ],
540
- [
541
- "events/stream with a maxAgeMs that is not valid is the error -32602",
542
- {
543
- name: "fixture.ticks",
544
- arguments: { count: 1 },
545
- maxAgeMs: -1
546
- },
547
- -32602,
548
- void 0
549
- ],
550
- [
551
- "events/stream with a heartbeatMs that is not a positive integer is the error -32602",
552
- {
553
- name: "fixture.ticks",
554
- arguments: { count: 1 },
555
- heartbeatMs: 0
556
- },
557
- -32602,
558
- void 0
559
- ]
560
- ]) await checks.run(name, RULE_EVENTS, async (signal) => {
561
- const stream = await channel.stream(streamId(), params, signal);
562
- try {
563
- const error = errorOf(await stream.next());
564
- expectEqual(error.code, code, "the JSON-RPC error code");
565
- if (kind !== void 0) expectEqual(memberOf(error.data, "kind"), kind, "data.kind");
566
- } finally {
567
- await stream.cancel();
568
- }
569
- });
570
- await checks.run("events/stream gives active, each occurrence in order, then the result", RULE_EVENTS, async (signal) => {
571
- const id = streamId();
572
- const stream = await channel.stream(id, {
573
- name: "fixture.ticks",
574
- arguments: { count: 3 }
575
- }, signal);
576
- try {
577
- await active(stream, id);
578
- for (const n of [
579
- 1,
580
- 2,
581
- 3
582
- ]) {
583
- const each = await occurrence(stream, id, "fixture.ticks");
584
- expectEqual(each.data, { n }, "data");
585
- expectEqual([each.eventId, each.cursor], [String(n), String(n)], "the eventId and the cursor");
586
- }
587
- await complete(stream, id);
588
- } finally {
589
- await stream.cancel();
590
- }
591
- });
592
- await checks.run("before an occurrence after a gap, notifications/events/active has truncated: true and its cursor", RULE_EVENTS, async (signal) => {
593
- const id = streamId();
594
- const stream = await channel.stream(id, {
595
- name: "fixture.ticks",
596
- arguments: {
597
- count: 3,
598
- gap: 2
599
- }
600
- }, signal);
601
- try {
602
- await active(stream, id);
603
- expectEqual((await occurrence(stream, id, "fixture.ticks")).data, { n: 1 }, "data");
604
- const { heartbeatMs, ...gap } = paramsOf(await notification(stream, id, "notifications/events/active"));
605
- expectEqual(gap, {
606
- truncated: true,
607
- cursor: "2"
608
- }, "the params of notifications/events/active before the gap, without heartbeatMs");
609
- expectHeartbeatGrant(heartbeatMs);
610
- const after = paramsOf(await notification(stream, id, "notifications/events/event"));
611
- expect(!("truncated" in after), `the params of notifications/events/event must have no truncated, got ${JSON.stringify(after)}`);
612
- expectEqual(expectOccurrence(after, "fixture.ticks").data, { n: 2 }, "data");
613
- expectEqual((await occurrence(stream, id, "fixture.ticks")).data, { n: 3 }, "data");
614
- await complete(stream, id);
615
- } finally {
616
- await stream.cancel();
617
- }
618
- });
619
- for (const [suggested, granted] of [
620
- [5, MCP_HEARTBEAT_MIN_MS],
621
- [999999, MCP_HEARTBEAT_MAX_MS],
622
- [2500, 2500]
623
- ]) {
624
- const name = `events/stream with heartbeatMs: ${suggested} grants heartbeatMs: ${granted} on notifications/events/active${granted === MCP_HEARTBEAT_MIN_MS ? ", then sends heartbeats at that interval" : ""}`;
625
- await checks.run(name, `${RULE}#push`, async (signal) => {
626
- const id = streamId();
627
- const requested = performance.now();
628
- const stream = await channel.stream(id, {
629
- name: "fixture.watch",
630
- arguments: { key: randomUUID() },
631
- heartbeatMs: suggested
632
- }, signal);
633
- try {
634
- await active(stream, id, granted);
635
- if (granted !== MCP_HEARTBEAT_MIN_MS) return;
636
- expectEqual(paramsOf(await notification(stream, id, "notifications/events/heartbeat")), { cursor: null }, "the params of notifications/events/heartbeat");
637
- const waited = Math.round(performance.now() - requested);
638
- expect(waited >= granted - TIMER_RESOLUTION_MS, `the heartbeat must come when the stream was idle for ${granted} ms, but it came ${waited} ms after the request`);
639
- } finally {
640
- await stream.cancel();
641
- }
642
- });
643
- }
644
- await checks.run("events/stream with a cursor starts after it", RULE_EVENTS, async (signal) => {
645
- const id = streamId();
646
- const stream = await channel.stream(id, {
647
- name: "fixture.ticks",
648
- arguments: { count: 3 },
649
- cursor: "1"
650
- }, signal);
651
- try {
652
- await active(stream, id);
653
- for (const n of [2, 3]) expectEqual((await occurrence(stream, id, "fixture.ticks")).data, { n }, "data");
654
- await complete(stream, id);
655
- } finally {
656
- await stream.cancel();
657
- }
658
- });
659
- await checks.run("a defect after an occurrence sends notifications/events/terminated, then the result", RULE_EVENTS, async (signal) => {
660
- const id = streamId();
661
- const stream = await channel.stream(id, {
662
- name: "fixture.broken",
663
- arguments: {}
664
- }, signal);
665
- try {
666
- await active(stream, id);
667
- expectEqual((await occurrence(stream, id, "fixture.broken")).data, { n: 1 }, "data");
668
- const terminated = paramsOf(await notification(stream, id, "notifications/events/terminated"));
669
- expectEqual(memberOf(terminated.error, "code"), -32603, "the error code of notifications/events/terminated");
670
- expect(!/\n\s+at /.test(String(memberOf(terminated.error, "message"))), "the message must not contain a stack trace");
671
- await complete(stream, id);
672
- } finally {
673
- await stream.cancel();
674
- }
675
- });
676
- await checks.run("two subscriptions at the same time each get their own messages, and cancelling one leaves the other", RULE_EVENTS, async (signal) => {
677
- const key = randomUUID();
678
- const [firstId, secondId] = [streamId(), streamId()];
679
- const first = await channel.stream(firstId, {
680
- name: "fixture.watch",
681
- arguments: { key }
682
- }, signal);
683
- const second = await channel.stream(secondId, {
684
- name: "fixture.watch",
685
- arguments: { key }
686
- }, signal);
687
- try {
688
- await active(first, firstId);
689
- await active(second, secondId);
690
- await until("fixture.watching gives the key of both subscriptions", () => watching(signal), (keys) => count(keys, key) === 2, signal);
691
- expectEqual(await signalKey(key, "both", signal), 2, "the subscriptions that fixture.signal reached");
692
- expectEqual((await occurrence(first, firstId, "fixture.watch")).data, {
693
- key,
694
- value: "both"
695
- }, "data of the first subscription");
696
- expectEqual((await occurrence(second, secondId, "fixture.watch")).data, {
697
- key,
698
- value: "both"
699
- }, "data of the second subscription");
700
- await first.cancel();
701
- await until("the cancelled subscription leaves fixture.watching", () => watching(signal), (keys) => count(keys, key) === 1, signal);
702
- expectEqual(await signalKey(key, "after", signal), 1, "the subscriptions that fixture.signal reached");
703
- expectEqual((await occurrence(second, secondId, "fixture.watch")).data, {
704
- key,
705
- value: "after"
706
- }, "data of the second subscription");
707
- } finally {
708
- await first.cancel();
709
- await second.cancel();
710
- }
711
- });
712
- if (delivery.includes("poll")) await checkPoll(checks, channel, options.poll);
713
- else {
714
- await checks.should("the server serves poll delivery", `${RULE}#events`, () => {
715
- throw new Error("events/list gives no poll delivery. A server that keeps no state between requests serves push only.");
716
- });
717
- await checks.run("events/poll is Unsupported, with the delivery mode poll", RULE_EVENTS, async (signal) => {
718
- const error = errorOf(await channel.request("events/poll", {
719
- name: "fixture.ticks",
720
- arguments: { count: 1 }
721
- }, signal));
722
- expectEqual(error.code, -32026, "the JSON-RPC error code");
723
- expectEqual(error.data, {
724
- feature: "deliveryMode",
725
- value: "poll"
726
- }, "data");
727
- });
728
- }
729
- if (!delivery.includes("webhook")) await checks.run("events/subscribe and events/unsubscribe are Unsupported, with the delivery mode webhook", `${RULE}#webhook`, async (signal) => {
730
- const url = "https://webhook.acid-cat.invalid/hook";
731
- const subscribe = {
732
- name: "fixture.ticks",
733
- arguments: { count: 1 },
734
- delivery: {
735
- mode: "webhook",
736
- url,
737
- secret: `whsec_${"A".repeat(32)}`
738
- }
739
- };
740
- for (const [method, params] of [["events/subscribe", subscribe], ["events/unsubscribe", {
741
- name: "fixture.ticks",
742
- arguments: { count: 1 },
743
- delivery: { url }
744
- }]]) {
745
- const error = errorOf(await channel.request(method, params, signal));
746
- expectEqual(error.code, -32026, `the JSON-RPC error code of ${method}`);
747
- expectEqual(error.data, {
748
- feature: "deliveryMode",
749
- value: "webhook"
750
- }, `the data of ${method}`);
751
- }
752
- });
753
- }
754
- export { EVENTS_REVISION, META, checkEvents, checkMcp, checkTools, count, eventRequests, httpChannel, mcpClient, mcpRequestHeaders, subscriptionOf };