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