@open-wa/mcp 5.10.0 → 5.11.1

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/dist/index.mjs CHANGED
@@ -1,15 +1,15 @@
1
1
  import { getHttpMethodDefinitions } from "@open-wa/schema/http-manifest";
2
2
  import { eventJsonSchema, getEventContract, getHttpMethodDefinitions as getHttpMethodDefinitions$1, getMcpEventDefinitions, normalizeParameterKeys, z } from "@open-wa/schema";
3
- import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
3
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
4
4
  import { dirname, join } from "node:path";
5
- import { ProtocolError, ProtocolErrorCode, Server, createMcpHandler } from "@modelcontextprotocol/server";
6
- import { z as z$1 } from "zod";
5
+ import { ProtocolError, Server, createMcpHandler } from "@modelcontextprotocol/server";
7
6
  import { ScopedTaskQueue } from "@open-wa/runtime-core";
8
7
  import { Webhook } from "standardwebhooks";
9
8
  import { lookup } from "node:dns/promises";
10
9
  import { request } from "node:https";
11
10
  import { isIP } from "node:net";
12
11
  import ipaddr from "ipaddr.js";
12
+ import { z as z$1 } from "zod";
13
13
  import { chmodSync, mkdirSync } from "node:fs";
14
14
  import { DatabaseSync } from "node:sqlite";
15
15
  //#region src/tool-naming.ts
@@ -257,9 +257,24 @@ function postCallback(urlString, body, headers, signal) {
257
257
  req.end(body);
258
258
  });
259
259
  }
260
+ /** Maps a failed callback attempt to a spec category; raw endpoint output never leaves this module. */
261
+ function callbackFailure(error, status) {
262
+ if (status !== void 0) return status >= 500 ? "http_5xx" : "http_4xx";
263
+ const value = error;
264
+ const code = String(value?.code ?? (value?.cause)?.code ?? "");
265
+ if (value?.name === "TimeoutError" || code === "ETIMEDOUT" || code === "ESOCKETTIMEDOUT" || code === "ABORT_ERR") return "timeout";
266
+ if (/^(ERR_TLS|ERR_SSL|CERT_|UNABLE_TO|DEPTH_ZERO|SELF_SIGNED|ERR_OSSL)/.test(code) || code.includes("CERT")) return "tls_error";
267
+ return "connection_refused";
268
+ }
260
269
  //#endregion
261
270
  //#region src/events/protocol.ts
271
+ /** Extension identifier from SEP-3415, advertised under `capabilities.extensions`. */
272
+ const EVENTS_EXTENSION = "io.modelcontextprotocol/events";
273
+ const SUBSCRIPTION_META = "io.modelcontextprotocol/subscriptionId";
262
274
  const argumentsSchema = z$1.record(z$1.string(), z$1.unknown());
275
+ const cursorSchema = z$1.string().nullable().optional();
276
+ const maxAgeSchema = z$1.number().int().positive().optional();
277
+ const complete = { resultType: z$1.literal("complete") };
263
278
  const deliverySchema = z$1.object({
264
279
  mode: z$1.literal("webhook"),
265
280
  url: z$1.string().url(),
@@ -269,35 +284,114 @@ const subscribeSchema = z$1.object({
269
284
  name: z$1.string(),
270
285
  arguments: argumentsSchema.default({}),
271
286
  delivery: deliverySchema,
272
- cursor: z$1.string().nullable().optional(),
287
+ cursor: cursorSchema,
288
+ maxAgeMs: maxAgeSchema,
273
289
  ttlMs: z$1.number().int().positive().nullable().optional()
274
290
  });
275
291
  const unsubscribeSchema = subscribeSchema.pick({
276
292
  name: true,
277
293
  arguments: true
278
- }).extend({ delivery: deliverySchema.omit({ secret: true }) });
294
+ }).extend({ delivery: z$1.object({
295
+ mode: z$1.literal("webhook").optional(),
296
+ url: z$1.string().url()
297
+ }) });
298
+ const pollSchema = z$1.object({
299
+ name: z$1.string(),
300
+ arguments: argumentsSchema.default({}),
301
+ cursor: cursorSchema,
302
+ maxAgeMs: maxAgeSchema,
303
+ maxEvents: z$1.number().int().positive().optional()
304
+ });
305
+ const streamSchema = z$1.object({
306
+ name: z$1.string(),
307
+ arguments: argumentsSchema.default({}),
308
+ cursor: cursorSchema,
309
+ maxAgeMs: maxAgeSchema,
310
+ heartbeatMs: z$1.number().int().positive().optional()
311
+ });
312
+ const occurrenceSchema = z$1.object({
313
+ eventId: z$1.string(),
314
+ name: z$1.string(),
315
+ timestamp: z$1.string(),
316
+ data: argumentsSchema,
317
+ cursor: z$1.string().nullable().optional()
318
+ });
279
319
  const subscriptionResultSchema = z$1.object({
320
+ ...complete,
280
321
  id: z$1.string(),
281
322
  refreshBefore: z$1.string().datetime().nullable(),
282
- cursor: z$1.null(),
283
- truncated: z$1.boolean()
323
+ cursor: z$1.string().nullable(),
324
+ truncated: z$1.boolean(),
325
+ deliveryStatus: z$1.object({
326
+ active: z$1.boolean(),
327
+ lastDeliveryAt: z$1.string().datetime().nullable(),
328
+ lastError: z$1.string().nullable()
329
+ }).optional()
330
+ });
331
+ const pollResultSchema = z$1.object({
332
+ ...complete,
333
+ events: z$1.array(occurrenceSchema),
334
+ cursor: z$1.string().nullable(),
335
+ truncated: z$1.boolean(),
336
+ hasMore: z$1.boolean(),
337
+ nextPollMs: z$1.number().int()
284
338
  });
339
+ const streamResultSchema = z$1.object({
340
+ ...complete,
341
+ _meta: argumentsSchema.optional()
342
+ });
343
+ const emptyResultSchema = z$1.object({ ...complete });
285
344
  const eventListParamsSchema = z$1.object({ cursor: z$1.string().optional() }).default({});
286
- const eventListResultSchema = z$1.object({ events: z$1.array(z$1.object({
287
- name: z$1.string(),
288
- description: z$1.string(),
289
- delivery: z$1.array(z$1.literal("webhook")),
290
- inputSchema: argumentsSchema,
291
- payloadSchema: argumentsSchema
292
- })) });
345
+ const eventListResultSchema = z$1.object({
346
+ ...complete,
347
+ events: z$1.array(z$1.object({
348
+ name: z$1.string(),
349
+ description: z$1.string(),
350
+ delivery: z$1.array(z$1.enum([
351
+ "poll",
352
+ "push",
353
+ "webhook"
354
+ ])).min(1),
355
+ inputSchema: argumentsSchema,
356
+ payloadSchema: argumentsSchema
357
+ }))
358
+ });
359
+ /** SEP-3415 error codes. */
360
+ const eventErrors = {
361
+ invalidParams: (message, data) => new ProtocolError(-32602, message, data),
362
+ notFound: (kind) => new ProtocolError(-32023, "NotFound", { kind }),
363
+ forbidden: (reason) => new ProtocolError(-32024, "Forbidden", { reason }),
364
+ exhausted: (limit, max) => new ProtocolError(-32025, "ResourceExhausted", {
365
+ limit,
366
+ max
367
+ }),
368
+ callback: (reason) => new ProtocolError(-32027, "CallbackEndpointError", { reason })
369
+ };
370
+ const errorBody = (code, message, data) => ({
371
+ code,
372
+ message,
373
+ ...data ? { data } : {}
374
+ });
293
375
  function canonicalJson(value) {
294
376
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
295
377
  if (value && typeof value === "object") return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(",")}}`;
296
378
  return JSON.stringify(value) ?? "null";
297
379
  }
380
+ /** Every subscription argument is an exact-match filter on the projected payload. */
381
+ function matchesArguments(args, data) {
382
+ return Object.entries(args).every(([key, value]) => value === void 0 || data[key] === value);
383
+ }
384
+ /** Decodes an `Mcp-Name` header, including the transport's `=?base64?…?=` sentinel. */
385
+ function decodeHeaderValue(value) {
386
+ const sentinel = /^=\?base64\?([A-Za-z0-9+/=]*)\?=$/i.exec(value.trim());
387
+ if (!sentinel) return value.trim();
388
+ const decoded = Buffer.from(sentinel[1], "base64");
389
+ return decoded.toString("base64") === sentinel[1] ? decoded.toString("utf8") : void 0;
390
+ }
298
391
  //#endregion
299
392
  //#region src/events/store.ts
300
- /** Secrets and payloads stay in a private local journal, never discovery or logs. */
393
+ const SCHEMA_VERSION = 2;
394
+ /** Secrets, payloads and the short replay log stay in a private local journal, never discovery or logs. */
301
395
  var McpEventStore = class {
302
396
  constructor(path) {
303
397
  mkdirSync(dirname(path), {
@@ -306,58 +400,141 @@ var McpEventStore = class {
306
400
  });
307
401
  this.db = new DatabaseSync(path);
308
402
  chmodSync(path, 384);
403
+ this.db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;");
404
+ if (Number(this.db.prepare("PRAGMA user_version").get().user_version) !== SCHEMA_VERSION) this.db.exec(`
405
+ DROP TABLE IF EXISTS mcp_event_deliveries; DROP TABLE IF EXISTS mcp_event_subscriptions;
406
+ DROP TABLE IF EXISTS mcp_event_log; DROP TABLE IF EXISTS mcp_event_meta;
407
+ PRAGMA user_version=${SCHEMA_VERSION};
408
+ `);
309
409
  this.db.exec(`
310
- PRAGMA journal_mode=WAL;
311
- PRAGMA synchronous=FULL;
312
- PRAGMA foreign_keys=ON;
410
+ CREATE TABLE IF NOT EXISTS mcp_event_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
411
+ CREATE TABLE IF NOT EXISTS mcp_event_log (
412
+ seq INTEGER PRIMARY KEY AUTOINCREMENT, owner TEXT NOT NULL, name TEXT NOT NULL, event_id TEXT NOT NULL,
413
+ timestamp TEXT NOT NULL, data TEXT NOT NULL, recorded_at INTEGER NOT NULL
414
+ );
415
+ CREATE INDEX IF NOT EXISTS mcp_event_log_name ON mcp_event_log(owner, name, seq);
313
416
  CREATE TABLE IF NOT EXISTS mcp_event_subscriptions (
314
- id TEXT PRIMARY KEY, owner TEXT NOT NULL, name TEXT NOT NULL,
315
- arguments TEXT NOT NULL, url TEXT NOT NULL, secret TEXT NOT NULL, expires_at INTEGER NOT NULL
417
+ id TEXT PRIMARY KEY, owner TEXT NOT NULL, name TEXT NOT NULL, arguments TEXT NOT NULL, url TEXT NOT NULL,
418
+ secret TEXT NOT NULL, previous_secret TEXT, previous_secret_until INTEGER, expires_at INTEGER NOT NULL,
419
+ last_delivery_at INTEGER, last_error TEXT
316
420
  );
317
421
  CREATE TABLE IF NOT EXISTS mcp_event_deliveries (
318
- id INTEGER PRIMARY KEY, subscription_id TEXT NOT NULL REFERENCES mcp_event_subscriptions(id) ON DELETE CASCADE,
319
- event_id TEXT NOT NULL, body TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0,
320
- next_attempt_at INTEGER NOT NULL, UNIQUE(subscription_id,event_id)
422
+ id INTEGER PRIMARY KEY, subscription_id TEXT NOT NULL, webhook_id TEXT NOT NULL UNIQUE, seq INTEGER,
423
+ body TEXT NOT NULL, url TEXT, secret TEXT, attempts INTEGER NOT NULL DEFAULT 0,
424
+ first_attempt_at INTEGER NOT NULL, next_attempt_at INTEGER NOT NULL, UNIQUE(subscription_id, seq)
321
425
  );
322
426
  CREATE INDEX IF NOT EXISTS mcp_event_pending ON mcp_event_deliveries(next_attempt_at);
323
427
  `);
428
+ const existing = this.db.prepare("SELECT value FROM mcp_event_meta WHERE key='epoch'").get();
429
+ this.epoch = existing?.value ?? randomBytes(6).toString("hex");
430
+ if (!existing) this.db.prepare("INSERT INTO mcp_event_meta VALUES ('epoch', ?)").run(this.epoch);
431
+ }
432
+ append(event) {
433
+ const recordedAt = Date.now();
434
+ const result = this.db.prepare("INSERT INTO mcp_event_log(owner,name,event_id,timestamp,data,recorded_at) VALUES (?,?,?,?,?,?)").run(event.owner, event.name, event.eventId, event.timestamp, JSON.stringify(event.data), recordedAt);
435
+ return {
436
+ ...event,
437
+ seq: Number(result.lastInsertRowid),
438
+ recordedAt
439
+ };
440
+ }
441
+ /** Highest sequence ever assigned, including pruned events. */
442
+ head() {
443
+ const row = this.db.prepare("SELECT seq FROM sqlite_sequence WHERE name='mcp_event_log'").get();
444
+ return Number(row?.seq ?? 0);
445
+ }
446
+ prunedThrough() {
447
+ const row = this.db.prepare("SELECT value FROM mcp_event_meta WHERE key='pruned'").get();
448
+ return Number(row?.value ?? 0);
449
+ }
450
+ /** The newest sequence recorded before `before`, so replay can start after it. */
451
+ lastBefore(before) {
452
+ const row = this.db.prepare("SELECT MAX(seq) AS seq FROM mcp_event_log WHERE recorded_at < ?").get(before);
453
+ return Math.max(Number(row.seq ?? 0), this.prunedThrough());
454
+ }
455
+ events(owner, name, after, limit) {
456
+ return this.db.prepare("SELECT * FROM mcp_event_log WHERE owner=? AND name=? AND seq>? ORDER BY seq LIMIT ?").all(owner, name, after, limit).map((row) => ({
457
+ seq: Number(row.seq),
458
+ owner: String(row.owner),
459
+ name: String(row.name),
460
+ eventId: String(row.event_id),
461
+ timestamp: String(row.timestamp),
462
+ data: JSON.parse(String(row.data)),
463
+ recordedAt: Number(row.recorded_at)
464
+ }));
465
+ }
466
+ prune(retentionMs, maxEvents) {
467
+ const row = this.db.prepare("SELECT MAX(seq) AS seq FROM mcp_event_log WHERE recorded_at < ? OR seq <= ?").get(Date.now() - retentionMs, this.head() - maxEvents);
468
+ if (row.seq == null) return;
469
+ this.db.prepare("DELETE FROM mcp_event_log WHERE seq <= ?").run(row.seq);
470
+ this.db.prepare("INSERT INTO mcp_event_meta VALUES ('pruned', ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(String(Math.max(row.seq, this.prunedThrough())));
324
471
  }
325
472
  save(subscription) {
326
- this.db.prepare(`INSERT INTO mcp_event_subscriptions VALUES (?,?,?,?,?,?,?)
327
- ON CONFLICT(id) DO UPDATE SET secret=excluded.secret, expires_at=excluded.expires_at`).run(subscription.id, subscription.owner, subscription.name, JSON.stringify(subscription.arguments), subscription.url, subscription.secret, subscription.expiresAt);
473
+ this.db.prepare(`INSERT INTO mcp_event_subscriptions(id,owner,name,arguments,url,secret,previous_secret,previous_secret_until,expires_at)
474
+ VALUES (?,?,?,?,?,?,?,?,?)
475
+ ON CONFLICT(id) DO UPDATE SET secret=excluded.secret, previous_secret=excluded.previous_secret,
476
+ previous_secret_until=excluded.previous_secret_until, expires_at=excluded.expires_at`).run(subscription.id, subscription.owner, subscription.name, JSON.stringify(subscription.arguments), subscription.url, subscription.secret, subscription.previousSecret ?? null, subscription.previousSecretUntil ?? null, subscription.expiresAt);
328
477
  }
329
478
  get(id, owner) {
330
479
  const row = this.db.prepare("SELECT * FROM mcp_event_subscriptions WHERE id=? AND owner=? AND expires_at>?").get(id, owner, Date.now());
331
- return row ? {
480
+ return row ? this.subscription(row) : void 0;
481
+ }
482
+ matching(name, owner) {
483
+ return this.db.prepare("SELECT * FROM mcp_event_subscriptions WHERE name=? AND owner=? AND expires_at>?").all(name, owner, Date.now()).map((row) => this.subscription(row));
484
+ }
485
+ /** Subscriptions that can no longer be served: another principal, or an event type that is gone. */
486
+ orphaned(owner, available) {
487
+ return this.db.prepare("SELECT * FROM mcp_event_subscriptions WHERE expires_at>?").all(Date.now()).map((row) => this.subscription(row)).filter((sub) => sub.owner !== owner || !available(sub.name));
488
+ }
489
+ count(owner) {
490
+ return Number(this.db.prepare("SELECT COUNT(*) AS n FROM mcp_event_subscriptions WHERE owner=? AND expires_at>?").get(owner, Date.now()).n);
491
+ }
492
+ remove(id) {
493
+ this.db.prepare("DELETE FROM mcp_event_subscriptions WHERE id=?").run(id);
494
+ this.db.prepare("DELETE FROM mcp_event_deliveries WHERE subscription_id=? AND url IS NULL").run(id);
495
+ }
496
+ recordAttempt(id, error) {
497
+ if (error) this.db.prepare("UPDATE mcp_event_subscriptions SET last_error=? WHERE id=?").run(error, id);
498
+ else this.db.prepare("UPDATE mcp_event_subscriptions SET last_delivery_at=?, last_error=NULL WHERE id=?").run(Date.now(), id);
499
+ }
500
+ subscription(row) {
501
+ return {
332
502
  id: String(row.id),
333
503
  owner: String(row.owner),
334
504
  name: String(row.name),
335
505
  arguments: JSON.parse(String(row.arguments)),
336
506
  url: String(row.url),
337
507
  secret: String(row.secret),
338
- expiresAt: Number(row.expires_at)
339
- } : void 0;
340
- }
341
- matching(name, owner) {
342
- return this.db.prepare("SELECT id FROM mcp_event_subscriptions WHERE name=? AND owner=? AND expires_at>?").all(name, owner, Date.now()).flatMap((row) => {
343
- const sub = this.get(row.id, owner);
344
- return sub ? [sub] : [];
345
- });
508
+ expiresAt: Number(row.expires_at),
509
+ previousSecret: row.previous_secret == null ? void 0 : String(row.previous_secret),
510
+ previousSecretUntil: row.previous_secret_until == null ? void 0 : Number(row.previous_secret_until),
511
+ lastDeliveryAt: row.last_delivery_at == null ? void 0 : Number(row.last_delivery_at),
512
+ lastError: row.last_error == null ? void 0 : String(row.last_error)
513
+ };
346
514
  }
347
- remove(id, owner) {
348
- this.db.prepare("DELETE FROM mcp_event_subscriptions WHERE id=? AND owner=?").run(id, owner);
515
+ enqueue(job) {
516
+ const now = Date.now();
517
+ this.db.prepare("INSERT OR IGNORE INTO mcp_event_deliveries(subscription_id,webhook_id,seq,body,url,secret,first_attempt_at,next_attempt_at) VALUES(?,?,?,?,?,?,?,?)").run(job.subscriptionId, job.webhookId, job.seq, job.body, job.url ?? null, job.secret ?? null, now, now);
349
518
  }
350
- enqueue(sub, eventId, body) {
351
- this.db.prepare("INSERT OR IGNORE INTO mcp_event_deliveries(subscription_id,event_id,body,next_attempt_at) VALUES(?,?,?,?)").run(sub.id, eventId, body, Date.now());
519
+ /** Lowest sequence still awaiting delivery for a subscription. */
520
+ oldestPending(subscriptionId) {
521
+ const row = this.db.prepare("SELECT MIN(seq) AS seq FROM mcp_event_deliveries WHERE subscription_id=? AND seq IS NOT NULL").get(subscriptionId);
522
+ return row.seq == null ? void 0 : Number(row.seq);
352
523
  }
353
524
  pending(limit = 100) {
354
- this.db.prepare("DELETE FROM mcp_event_subscriptions WHERE expires_at<=?").run(Date.now());
355
- return this.db.prepare("SELECT * FROM mcp_event_deliveries WHERE next_attempt_at<=? ORDER BY id LIMIT ?").all(Date.now(), limit).map((row) => ({
525
+ const now = Date.now();
526
+ const expired = this.db.prepare("SELECT id FROM mcp_event_subscriptions WHERE expires_at<=?").all(now);
527
+ for (const { id } of expired) this.remove(id);
528
+ return this.db.prepare("SELECT * FROM mcp_event_deliveries WHERE next_attempt_at<=? ORDER BY id LIMIT ?").all(now, limit).map((row) => ({
356
529
  id: Number(row.id),
357
530
  subscriptionId: String(row.subscription_id),
358
- eventId: String(row.event_id),
531
+ webhookId: String(row.webhook_id),
532
+ seq: row.seq == null ? null : Number(row.seq),
359
533
  body: String(row.body),
534
+ url: row.url == null ? null : String(row.url),
535
+ secret: row.secret == null ? null : String(row.secret),
360
536
  attempts: Number(row.attempts),
537
+ firstAttemptAt: Number(row.first_attempt_at),
361
538
  nextAttemptAt: Number(row.next_attempt_at)
362
539
  }));
363
540
  }
@@ -374,9 +551,32 @@ var McpEventStore = class {
374
551
  //#endregion
375
552
  //#region src/events/service.ts
376
553
  const MAX_BODY_BYTES = 262144;
377
- const MAX_ATTEMPTS = 4;
378
- const error = (message) => new ProtocolError(ProtocolErrorCode.InvalidParams, message);
554
+ /** Five attempts in about 14 minutes, inside the spec's 10–15 minute retry window. */
555
+ const RETRY_DELAYS_MS = [
556
+ 3e4,
557
+ 12e4,
558
+ 3e5,
559
+ 42e4
560
+ ];
561
+ const ROTATION_GRACE_MS = 6e5;
562
+ const MAX_SUBSCRIPTIONS = 1e3;
563
+ const MAX_STREAMS = 100;
564
+ const MAX_LOGGED_EVENTS = 1e4;
565
+ const NEXT_POLL_MS = 5e3;
566
+ const POLL_EVENTS = {
567
+ default: 100,
568
+ max: 500
569
+ };
570
+ const HEARTBEAT_MS = {
571
+ min: 5e3,
572
+ default: 3e4,
573
+ max: 6e4
574
+ };
575
+ const VERIFICATIONS_PER_HOST_PER_MINUTE = 10;
576
+ const MAINTENANCE_MS = 3e4;
379
577
  const object = (value) => value && typeof value === "object" ? value : {};
578
+ const messageId = (kind) => `msg_${kind ? `${kind}_` : ""}${randomBytes(16).toString("hex")}`;
579
+ const iso = (ms) => ms === void 0 ? null : new Date(ms).toISOString();
380
580
  var McpEventsService = class {
381
581
  constructor(options) {
382
582
  this.options = options;
@@ -384,8 +584,12 @@ var McpEventsService = class {
384
584
  this.active = /* @__PURE__ */ new Map();
385
585
  this.deliveries = /* @__PURE__ */ new Map();
386
586
  this.verified = /* @__PURE__ */ new Map();
587
+ this.verificationBudget = /* @__PURE__ */ new Map();
588
+ this.streams = /* @__PURE__ */ new Set();
589
+ this.lastMaintenance = 0;
387
590
  this.closing = false;
388
591
  this.store = new McpEventStore(options.storePath);
592
+ this.post = options.post ?? postCallback;
389
593
  this.queue = ScopedTaskQueue.make({
390
594
  name: "mcp.events",
391
595
  capacity: 100,
@@ -396,23 +600,167 @@ var McpEventsService = class {
396
600
  this.timer.unref?.();
397
601
  this.queue.then(() => this.pump()).catch(() => this.log("mcp_event_queue_unavailable"));
398
602
  }
399
- list(cursor) {
400
- if (cursor !== void 0) throw error("The event catalog fits in one page; omit cursor");
401
- return { events: getMcpEventDefinitions() };
603
+ list() {
604
+ return {
605
+ resultType: "complete",
606
+ events: getMcpEventDefinitions()
607
+ };
402
608
  }
403
609
  principal() {
404
610
  const owner = this.options.owner();
405
- if (!owner || this.closing) throw new ProtocolError(-32001, "MCP access is unavailable");
611
+ if (!owner || this.closing) throw eventErrors.forbidden("MCP access is unavailable");
406
612
  return owner;
407
613
  }
408
614
  validated(name, args) {
409
615
  const contract = getEventContract(name);
410
- if (!contract?.mcp) throw error("Unknown or unavailable MCP event");
616
+ if (!contract?.mcp) throw eventErrors.notFound("event");
411
617
  const parsed = contract.mcp.inputSchema.safeParse(args);
412
- if (!parsed.success) throw error("Invalid subscription filters");
618
+ if (!parsed.success) throw eventErrors.invalidParams("Invalid subscription arguments");
619
+ return parsed.data;
620
+ }
621
+ cursor(seq) {
622
+ return `${this.store.epoch}.${seq}`;
623
+ }
624
+ /** Resolves a client cursor to the sequence delivery starts after, per the spec's cursor lifecycle. */
625
+ start(cursor, maxAgeMs) {
626
+ const head = this.store.head();
627
+ if (cursor == null) return {
628
+ after: head,
629
+ truncated: false
630
+ };
631
+ const match = /^([0-9a-f]+)\.(\d+)$/.exec(cursor);
632
+ if (!match) throw eventErrors.invalidParams("Unrecognised cursor");
633
+ const seq = Number(match[2]);
634
+ if (match[1] !== this.store.epoch || seq > head) return {
635
+ after: head,
636
+ truncated: true
637
+ };
638
+ let after = seq;
639
+ let truncated = false;
640
+ const pruned = this.store.prunedThrough();
641
+ if (after < pruned) {
642
+ after = pruned;
643
+ truncated = true;
644
+ }
645
+ if (maxAgeMs !== void 0) {
646
+ const floor = this.store.lastBefore(Date.now() - maxAgeMs);
647
+ if (floor > after) {
648
+ after = floor;
649
+ truncated = true;
650
+ }
651
+ }
413
652
  return {
414
- contract,
415
- arguments: parsed.data
653
+ after,
654
+ truncated
655
+ };
656
+ }
657
+ /** Calls `visit` for each logged event after `after` that this subscription would receive. */
658
+ scan(owner, name, args, after, visit) {
659
+ let position = after;
660
+ for (;;) {
661
+ const batch = this.store.events(owner, name, position, 500);
662
+ for (const event of batch) {
663
+ if (matchesArguments(args, event.data) && visit(event) === false) return position;
664
+ position = event.seq;
665
+ }
666
+ if (batch.length < 500) return this.store.head();
667
+ }
668
+ }
669
+ occurrence(event, cursor) {
670
+ return {
671
+ eventId: event.eventId,
672
+ name: event.name,
673
+ timestamp: event.timestamp,
674
+ data: event.data,
675
+ ...cursor ? { cursor } : {}
676
+ };
677
+ }
678
+ poll(params) {
679
+ const owner = this.principal();
680
+ const args = this.validated(params.name, params.arguments);
681
+ const limit = Math.min(params.maxEvents ?? POLL_EVENTS.default, POLL_EVENTS.max);
682
+ const { after, truncated } = this.start(params.cursor, params.maxAgeMs);
683
+ const events = [];
684
+ let hasMore = false;
685
+ const position = this.scan(owner, params.name, args, after, (event) => {
686
+ if (events.length === limit) {
687
+ hasMore = true;
688
+ return false;
689
+ }
690
+ events.push(this.occurrence(event));
691
+ return true;
692
+ });
693
+ return {
694
+ resultType: "complete",
695
+ events,
696
+ cursor: this.cursor(position),
697
+ truncated,
698
+ hasMore,
699
+ nextPollMs: NEXT_POLL_MS
700
+ };
701
+ }
702
+ async stream(params, ctx) {
703
+ const owner = this.principal();
704
+ const args = this.validated(params.name, params.arguments);
705
+ if (this.streams.size >= MAX_STREAMS) throw eventErrors.exhausted("streams", MAX_STREAMS);
706
+ const { after, truncated } = this.start(params.cursor, params.maxAgeMs);
707
+ const heartbeatMs = Math.min(Math.max(params.heartbeatMs ?? HEARTBEAT_MS.default, HEARTBEAT_MS.min), HEARTBEAT_MS.max);
708
+ const meta = { [SUBSCRIPTION_META]: ctx.requestId };
709
+ if (ctx.signal.aborted) return {
710
+ resultType: "complete",
711
+ _meta: meta
712
+ };
713
+ let chain = Promise.resolve();
714
+ let lastSent = 0;
715
+ let closed = false;
716
+ let resolveDone;
717
+ const done = new Promise((resolve) => {
718
+ resolveDone = resolve;
719
+ });
720
+ const send = (method, body) => {
721
+ if (closed) return;
722
+ lastSent = Date.now();
723
+ chain = chain.then(() => ctx.signal.aborted ? void 0 : ctx.notify(method, {
724
+ ...body,
725
+ _meta: meta
726
+ })).catch(() => stream.end());
727
+ };
728
+ const heartbeat = setInterval(() => {
729
+ if (this.options.owner() !== owner) {
730
+ stream.end(errorBody(-32024, "Forbidden", { reason: "Access revoked" }));
731
+ return;
732
+ }
733
+ if (Date.now() - lastSent >= heartbeatMs) send("notifications/events/heartbeat", { cursor: this.cursor(this.store.head()) });
734
+ }, Math.min(1e3, heartbeatMs));
735
+ heartbeat.unref?.();
736
+ const stream = {
737
+ owner,
738
+ name: params.name,
739
+ arguments: args,
740
+ offer: (event) => send("notifications/events/event", this.occurrence(event, this.cursor(event.seq))),
741
+ end: (error) => {
742
+ if (closed) return;
743
+ if (error) send("notifications/events/terminated", { error });
744
+ closed = true;
745
+ clearInterval(heartbeat);
746
+ this.streams.delete(stream);
747
+ chain.finally(resolveDone);
748
+ }
749
+ };
750
+ ctx.signal.addEventListener("abort", () => stream.end(), { once: true });
751
+ send("notifications/events/active", {
752
+ cursor: this.cursor(after),
753
+ truncated,
754
+ heartbeatMs
755
+ });
756
+ this.scan(owner, params.name, args, after, (event) => {
757
+ stream.offer(event);
758
+ });
759
+ this.streams.add(stream);
760
+ await done;
761
+ return {
762
+ resultType: "complete",
763
+ _meta: meta
416
764
  };
417
765
  }
418
766
  identity(owner, name, args, url) {
@@ -421,55 +769,80 @@ var McpEventsService = class {
421
769
  name,
422
770
  arguments: args,
423
771
  url
424
- })).digest("hex")}`;
772
+ })).digest("hex").slice(0, 32)}`;
773
+ }
774
+ watermark(subscriptionId) {
775
+ const oldest = this.store.oldestPending(subscriptionId);
776
+ return this.cursor(oldest === void 0 ? this.store.head() : oldest - 1);
425
777
  }
426
778
  async subscribe(params) {
427
779
  const owner = this.principal();
428
- const { arguments: args } = this.validated(params.name, params.arguments);
429
- if (params.cursor != null) throw error("These events do not support history replay; use cursor:null");
780
+ const args = this.validated(params.name, params.arguments);
430
781
  let url;
431
782
  try {
432
783
  url = callbackUrl(params.delivery.url).href;
433
784
  } catch {
434
- throw error("Callback must be a public HTTPS URL without credentials or fragments");
785
+ throw eventErrors.invalidParams("Callback must be a public HTTPS URL without credentials or fragments");
435
786
  }
436
787
  const encodedKey = params.delivery.secret.slice(6);
437
788
  const key = Buffer.from(encodedKey, "base64");
438
- if (!params.delivery.secret.startsWith("whsec_") || key.length < 24 || key.length > 64 || key.toString("base64") !== encodedKey) throw error("Signing secret must be whsec_ followed by a base64 key of 24–64 bytes");
789
+ if (!params.delivery.secret.startsWith("whsec_") || key.length < 24 || key.length > 64 || key.toString("base64") !== encodedKey) throw eventErrors.invalidParams("Signing secret must be whsec_ followed by a base64 key of 24–64 bytes");
439
790
  const id = this.identity(owner, params.name, args, url);
791
+ const existing = this.store.get(id, owner);
792
+ if (!existing && this.store.count(owner) >= MAX_SUBSCRIPTIONS) throw eventErrors.exhausted("subscriptions", MAX_SUBSCRIPTIONS);
793
+ const start = existing ? {
794
+ after: 0,
795
+ truncated: false
796
+ } : this.start(params.cursor, params.maxAgeMs);
440
797
  await this.verify(owner, id, url, params.delivery.secret);
441
- if (this.principal() !== owner) throw new ProtocolError(-32001, "MCP access changed during subscription");
442
- const lifetime = Math.min(params.ttlMs ?? this.options.lifetimeMs, this.options.lifetimeMs);
443
- const expiresAt = Date.now() + lifetime;
444
- this.store.save({
798
+ if (this.principal() !== owner) throw eventErrors.forbidden("MCP access changed during subscription");
799
+ const expiresAt = Date.now() + Math.min(params.ttlMs ?? this.options.lifetimeMs, this.options.lifetimeMs);
800
+ const rotated = existing !== void 0 && existing.secret !== params.delivery.secret;
801
+ const subscription = {
445
802
  id,
446
803
  owner,
447
804
  name: params.name,
448
805
  arguments: args,
449
806
  url,
450
807
  secret: params.delivery.secret,
451
- expiresAt
452
- });
808
+ expiresAt,
809
+ previousSecret: rotated ? existing.secret : existing?.previousSecret,
810
+ previousSecretUntil: rotated ? Date.now() + ROTATION_GRACE_MS : existing?.previousSecretUntil
811
+ };
812
+ this.store.save(subscription);
813
+ if (!existing) {
814
+ this.scan(owner, params.name, args, start.after, (event) => {
815
+ this.enqueueEvent(subscription, event);
816
+ });
817
+ this.pump();
818
+ }
453
819
  return {
820
+ resultType: "complete",
454
821
  id,
455
822
  refreshBefore: new Date(expiresAt).toISOString(),
456
- cursor: null,
457
- truncated: false
823
+ cursor: this.watermark(id),
824
+ truncated: start.truncated,
825
+ ...existing ? { deliveryStatus: {
826
+ active: true,
827
+ lastDeliveryAt: iso(existing.lastDeliveryAt),
828
+ lastError: existing.lastError ?? null
829
+ } } : {}
458
830
  };
459
831
  }
460
832
  unsubscribe(params) {
461
833
  const owner = this.principal();
462
- const { arguments: args } = this.validated(params.name, params.arguments);
834
+ const args = this.validated(params.name, params.arguments);
463
835
  let url;
464
836
  try {
465
837
  url = callbackUrl(params.delivery.url).href;
466
838
  } catch {
467
- throw error("Invalid callback URL");
839
+ throw eventErrors.invalidParams("Invalid callback URL");
468
840
  }
469
841
  const id = this.identity(owner, params.name, args, url);
470
- this.store.remove(id, owner);
842
+ if (!this.store.get(id, owner)) throw eventErrors.notFound("subscription");
843
+ this.store.remove(id);
471
844
  for (const controller of this.deliveries.get(id) ?? []) controller.abort();
472
- return {};
845
+ return { resultType: "complete" };
473
846
  }
474
847
  async verify(owner, id, url, secret) {
475
848
  const now = Date.now();
@@ -479,33 +852,55 @@ var McpEventsService = class {
479
852
  url
480
853
  });
481
854
  if ((this.verified.get(cacheKey) ?? 0) > now) return;
482
- const challenge = randomUUID();
483
- const eventId = `verification_${randomUUID()}`;
855
+ const host = new URL(url).host;
856
+ const recent = (this.verificationBudget.get(host) ?? []).filter((at) => at > now - 6e4);
857
+ if (recent.length >= VERIFICATIONS_PER_HOST_PER_MINUTE) throw eventErrors.exhausted("verifications", VERIFICATIONS_PER_HOST_PER_MINUTE);
858
+ this.verificationBudget.set(host, [...recent, now]);
859
+ if (this.verificationBudget.size > 1e3) this.verificationBudget.delete(this.verificationBudget.keys().next().value);
860
+ const challenge = randomBytes(24).toString("base64url");
484
861
  const body = JSON.stringify({
485
862
  type: "verification",
486
863
  challenge
487
864
  });
865
+ let failure;
488
866
  try {
489
- const response = await postCallback(url, body, this.headers(secret, id, eventId, body), this.controller.signal);
490
- const reply = JSON.parse(response.body);
491
- const actual = typeof reply.challenge === "string" ? Buffer.from(reply.challenge) : Buffer.alloc(0);
492
- const expected = Buffer.from(challenge);
493
- if (response.status < 200 || response.status >= 300 || actual.length !== expected.length || !timingSafeEqual(actual, expected)) throw new Error("challenge_failed");
494
- if (this.verified.size >= 1e3) this.verified.delete(this.verified.keys().next().value);
495
- this.verified.set(cacheKey, Date.now() + 9e5);
496
- } catch {
497
- throw new ProtocolError(-32015, "Callback verification failed", { reason: "challenge_failed" });
867
+ const response = await this.post(url, body, this.headers([secret], id, messageId("verification"), body), this.controller.signal);
868
+ if (response.status < 200 || response.status >= 300) failure = callbackFailure(void 0, response.status);
869
+ else {
870
+ let echoed;
871
+ try {
872
+ echoed = JSON.parse(response.body).challenge;
873
+ } catch {
874
+ echoed = void 0;
875
+ }
876
+ const actual = typeof echoed === "string" ? Buffer.from(echoed) : Buffer.alloc(0);
877
+ const expected = Buffer.from(challenge);
878
+ if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) failure = "challenge_failed";
879
+ }
880
+ } catch (error) {
881
+ failure = callbackFailure(error);
498
882
  }
883
+ if (failure) throw eventErrors.callback(failure);
884
+ if (this.verified.size >= 1e3) this.verified.delete(this.verified.keys().next().value);
885
+ this.verified.set(cacheKey, Date.now() + 9e5);
499
886
  }
500
- headers(secret, subscriptionId, eventId, body) {
887
+ headers(secrets, subscriptionId, webhookId, body) {
501
888
  const at = /* @__PURE__ */ new Date();
502
889
  return {
503
- "webhook-id": eventId,
890
+ "webhook-id": webhookId,
504
891
  "webhook-timestamp": String(Math.floor(at.getTime() / 1e3)),
505
- "webhook-signature": new Webhook(secret).sign(eventId, at, body),
892
+ "webhook-signature": secrets.map((secret) => new Webhook(secret).sign(webhookId, at, body)).join(" "),
506
893
  "X-MCP-Subscription-Id": subscriptionId
507
894
  };
508
895
  }
896
+ enqueueEvent(subscription, event) {
897
+ this.store.enqueue({
898
+ subscriptionId: subscription.id,
899
+ webhookId: messageId(),
900
+ seq: event.seq,
901
+ body: JSON.stringify(this.occurrence(event))
902
+ });
903
+ }
509
904
  publish(name, payload) {
510
905
  const owner = this.options.owner();
511
906
  const contract = getEventContract(name);
@@ -524,27 +919,58 @@ var McpEventsService = class {
524
919
  }
525
920
  const date = new Date(occurredAt);
526
921
  if (!Number.isFinite(date.getTime())) return;
527
- const eventId = `evt_${randomUUID()}`;
528
- const body = JSON.stringify({
922
+ const eventId = contract.mcp.eventId?.(data) ?? `evt_${randomBytes(16).toString("hex")}`;
923
+ const timestamp = date.toISOString();
924
+ const sized = JSON.stringify({
529
925
  eventId,
530
926
  name,
531
- timestamp: date.toISOString(),
927
+ timestamp,
532
928
  data,
533
- cursor: null
929
+ cursor: this.cursor(Number.MAX_SAFE_INTEGER)
534
930
  });
535
- if (Buffer.byteLength(body) > MAX_BODY_BYTES) {
931
+ if (Buffer.byteLength(sized) > MAX_BODY_BYTES) {
536
932
  this.log("mcp_event_payload_too_large", name);
537
933
  return;
538
934
  }
539
- for (const subscription of this.store.matching(name, owner)) {
540
- if (subscription.arguments.chatId !== void 0 && subscription.arguments.chatId !== data.chatId) continue;
541
- this.store.enqueue(subscription, eventId, body);
542
- }
935
+ const event = this.store.append({
936
+ owner,
937
+ name,
938
+ eventId,
939
+ timestamp,
940
+ data
941
+ });
942
+ for (const subscription of this.store.matching(name, owner)) if (matchesArguments(subscription.arguments, data)) this.enqueueEvent(subscription, event);
943
+ for (const stream of this.streams) if (stream.owner === owner && stream.name === name && matchesArguments(stream.arguments, data)) stream.offer(event);
543
944
  this.pump();
544
945
  }
946
+ maintain() {
947
+ const now = Date.now();
948
+ if (now - this.lastMaintenance < MAINTENANCE_MS) return;
949
+ this.lastMaintenance = now;
950
+ this.store.prune(this.options.retentionMs, MAX_LOGGED_EVENTS);
951
+ const owner = this.options.owner();
952
+ for (const subscription of this.store.orphaned(owner, (name) => Boolean(getEventContract(name)?.mcp))) {
953
+ const error = subscription.owner !== owner ? errorBody(-32024, "Forbidden", { reason: "Access revoked" }) : errorBody(-32023, "NotFound", { kind: "event" });
954
+ this.store.enqueue({
955
+ subscriptionId: subscription.id,
956
+ webhookId: messageId("terminated"),
957
+ seq: null,
958
+ body: JSON.stringify({
959
+ type: "terminated",
960
+ error
961
+ }),
962
+ url: subscription.url,
963
+ secret: subscription.secret
964
+ });
965
+ this.store.remove(subscription.id);
966
+ }
967
+ for (const stream of this.streams) if (stream.owner !== owner) stream.end(errorBody(-32024, "Forbidden", { reason: "Access revoked" }));
968
+ else if (!getEventContract(stream.name)?.mcp) stream.end(errorBody(-32023, "NotFound", { kind: "event" }));
969
+ }
545
970
  pump() {
546
971
  if (this.closing) return;
547
972
  try {
973
+ this.maintain();
548
974
  for (const job of this.store.pending()) {
549
975
  if (this.active.size >= 100) break;
550
976
  if (this.active.has(job.id)) continue;
@@ -557,42 +983,62 @@ var McpEventsService = class {
557
983
  }
558
984
  async deliver(job) {
559
985
  if (this.closing) return;
560
- const owner = this.options.owner();
561
- const subscription = owner ? this.store.get(job.subscriptionId, owner) : void 0;
562
- if (!subscription || !getEventContract(subscription.name)?.mcp) {
563
- this.store.complete(job.id);
564
- return;
986
+ let url;
987
+ let secrets;
988
+ let subscription;
989
+ if (job.url && job.secret) {
990
+ url = job.url;
991
+ secrets = [job.secret];
992
+ } else {
993
+ const owner = this.options.owner();
994
+ subscription = owner ? this.store.get(job.subscriptionId, owner) : void 0;
995
+ if (!subscription) {
996
+ this.store.complete(job.id);
997
+ return;
998
+ }
999
+ url = subscription.url;
1000
+ secrets = [subscription.secret];
1001
+ if (subscription.previousSecret && (subscription.previousSecretUntil ?? 0) > Date.now()) secrets.push(subscription.previousSecret);
565
1002
  }
1003
+ const body = job.seq === null ? job.body : JSON.stringify({
1004
+ ...JSON.parse(job.body),
1005
+ cursor: this.watermark(job.subscriptionId)
1006
+ });
566
1007
  const controller = new AbortController();
567
- const signals = this.deliveries.get(subscription.id) ?? /* @__PURE__ */ new Set();
1008
+ const signals = this.deliveries.get(job.subscriptionId) ?? /* @__PURE__ */ new Set();
568
1009
  signals.add(controller);
569
- this.deliveries.set(subscription.id, signals);
1010
+ this.deliveries.set(job.subscriptionId, signals);
570
1011
  try {
571
- const response = await postCallback(subscription.url, job.body, this.headers(subscription.secret, subscription.id, job.eventId, job.body), AbortSignal.any([this.controller.signal, controller.signal]));
1012
+ const response = await this.post(url, body, this.headers(secrets, job.subscriptionId, job.webhookId, body), AbortSignal.any([this.controller.signal, controller.signal]));
572
1013
  if (response.status >= 200 && response.status < 300) {
573
1014
  this.store.complete(job.id);
1015
+ if (subscription) this.store.recordAttempt(subscription.id);
574
1016
  return;
575
1017
  }
576
- if (response.status === 410 || response.status === 413 || response.status < 500 && response.status !== 408 && response.status !== 429) {
1018
+ if (subscription) this.store.recordAttempt(subscription.id, callbackFailure(void 0, response.status));
1019
+ if (response.status === 410 || response.status === 413 || response.status < 500 && response.status !== 408 && response.status !== 425 && response.status !== 429) {
577
1020
  this.store.complete(job.id);
578
- this.log("mcp_event_delivery_rejected", subscription.name);
1021
+ this.log("mcp_event_delivery_rejected");
579
1022
  return;
580
1023
  }
581
- this.retry(job, subscription);
582
- } catch {
583
- if (!this.closing && !controller.signal.aborted) this.retry(job, subscription);
1024
+ this.retry(job);
1025
+ } catch (error) {
1026
+ if (this.closing || controller.signal.aborted) return;
1027
+ if (subscription) this.store.recordAttempt(subscription.id, callbackFailure(error));
1028
+ this.retry(job);
584
1029
  } finally {
585
1030
  signals.delete(controller);
586
- if (!signals.size) this.deliveries.delete(subscription.id);
1031
+ if (!signals.size) this.deliveries.delete(job.subscriptionId);
587
1032
  }
588
1033
  }
589
- retry(job, subscription) {
590
- if (job.attempts + 1 >= MAX_ATTEMPTS) {
1034
+ retry(job) {
1035
+ const delay = RETRY_DELAYS_MS[job.attempts];
1036
+ if (delay === void 0) {
591
1037
  this.store.complete(job.id);
592
- this.log("mcp_event_delivery_exhausted", subscription.name);
1038
+ this.log("mcp_event_delivery_exhausted");
593
1039
  return;
594
1040
  }
595
- this.store.retry(job.id, Date.now() + 1e3 * 2 ** job.attempts);
1041
+ this.store.retry(job.id, Date.now() + delay);
596
1042
  }
597
1043
  log(message, event) {
598
1044
  this.options.log?.({
@@ -607,6 +1053,7 @@ var McpEventsService = class {
607
1053
  this.closing = true;
608
1054
  clearInterval(this.timer);
609
1055
  this.controller.abort();
1056
+ for (const stream of this.streams) stream.end();
610
1057
  await (await this.queue).close();
611
1058
  await Promise.allSettled([...this.active.values()]);
612
1059
  this.store.close();
@@ -614,7 +1061,7 @@ var McpEventsService = class {
614
1061
  };
615
1062
  //#endregion
616
1063
  //#region package.json
617
- var version = "5.10.0";
1064
+ var version = "5.11.1";
618
1065
  //#endregion
619
1066
  //#region src/adapter/hono-mcp.ts
620
1067
  /** Easy API's authenticated MCP 2.0 tools and webhook event endpoint. */
@@ -631,12 +1078,16 @@ function createHonoMcpAdapter(options) {
631
1078
  owner,
632
1079
  storePath: eventConfig?.storePath ?? join(".open-wa", `mcp-events-${owner().slice(0, 24)}.sqlite`),
633
1080
  lifetimeMs: eventConfig?.lifetimeMs ?? 864e5,
1081
+ retentionMs: eventConfig?.retentionMs ?? 9e5,
634
1082
  log: (data) => elasticEmitter?.log(data)
635
1083
  });
636
1084
  const handler = createMcpHandler(() => {
637
1085
  const capabilities = {
638
1086
  tools: {},
639
- ...events ? { events: {} } : {}
1087
+ ...events ? {
1088
+ events: {},
1089
+ extensions: { [EVENTS_EXTENSION]: {} }
1090
+ } : {}
640
1091
  };
641
1092
  const server = new Server({
642
1093
  name: "open-wa",
@@ -676,14 +1127,29 @@ function createHonoMcpAdapter(options) {
676
1127
  server.setRequestHandler("events/list", {
677
1128
  params: eventListParamsSchema,
678
1129
  result: eventListResultSchema
679
- }, async (params) => events.list(params.cursor));
1130
+ }, async () => events.list());
1131
+ server.setRequestHandler("events/poll", {
1132
+ params: pollSchema,
1133
+ result: pollResultSchema
1134
+ }, async (params) => events.poll(params));
1135
+ server.setRequestHandler("events/stream", {
1136
+ params: streamSchema,
1137
+ result: streamResultSchema
1138
+ }, (params, ctx) => events.stream(params, {
1139
+ requestId: ctx.mcpReq.id,
1140
+ signal: ctx.mcpReq.signal,
1141
+ notify: (method, notificationParams) => ctx.mcpReq.notify({
1142
+ method,
1143
+ params: notificationParams
1144
+ })
1145
+ }));
680
1146
  server.setRequestHandler("events/subscribe", {
681
1147
  params: subscribeSchema,
682
1148
  result: subscriptionResultSchema
683
1149
  }, (params) => events.subscribe(params));
684
1150
  server.setRequestHandler("events/unsubscribe", {
685
1151
  params: unsubscribeSchema,
686
- result: z$1.object({})
1152
+ result: emptyResultSchema
687
1153
  }, async (params) => events.unsubscribe(params));
688
1154
  }
689
1155
  return server;
@@ -696,6 +1162,16 @@ function createHonoMcpAdapter(options) {
696
1162
  error: "Unauthorized",
697
1163
  details: "Invalid or missing API key for MCP endpoint"
698
1164
  }, 401);
1165
+ const mismatch = await eventNameMismatch(c.req.raw);
1166
+ if (mismatch) return c.json({
1167
+ jsonrpc: "2.0",
1168
+ id: mismatch.id,
1169
+ error: {
1170
+ code: -32020,
1171
+ message: "HeaderMismatch",
1172
+ data: { header: "Mcp-Name" }
1173
+ }
1174
+ }, 400);
699
1175
  return handler.fetch(c.req.raw);
700
1176
  });
701
1177
  },
@@ -719,6 +1195,22 @@ function createHonoMcpAdapter(options) {
719
1195
  }
720
1196
  };
721
1197
  }
1198
+ /**
1199
+ * The SDK checks `Mcp-Name` only for core methods. For `events/*` requests that carry the header, it must
1200
+ * match `params.name`. A missing header is tolerated because ChatGPT's webhook client does not send it.
1201
+ */
1202
+ async function eventNameMismatch(request) {
1203
+ const method = request.headers.get("mcp-method");
1204
+ const header = request.headers.get("mcp-name");
1205
+ if (request.method !== "POST" || header === null || !method?.startsWith("events/") || method === "events/list") return;
1206
+ let body;
1207
+ try {
1208
+ body = await request.clone().json();
1209
+ } catch {
1210
+ return;
1211
+ }
1212
+ return decodeHeaderValue(header) === body?.params?.name ? void 0 : { id: body?.id ?? null };
1213
+ }
722
1214
  //#endregion
723
1215
  export { AuthenticationError, SessionNotReadyError, ToolExecutionError, ToolValidationError, createHonoMcpAdapter, executeCapability, getCanonicalToolName, getMcpToolDefinitions, invokeClientMethod, normalizeMethodPayload };
724
1216