@open-wa/mcp 5.5.0 → 5.6.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 +13 -0
- package/dist/index.cjs +539 -103
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -2
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +3 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +517 -104
- package/dist/index.mjs.map +1 -1
- package/package.json +8 -6
package/dist/index.mjs
CHANGED
|
@@ -1,9 +1,17 @@
|
|
|
1
1
|
import { getHttpMethodDefinitions } from "@open-wa/schema/http-manifest";
|
|
2
|
-
import { normalizeParameterKeys, z } from "@open-wa/schema";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
2
|
+
import { eventJsonSchema, getEventContract, getHttpMethodDefinitions as getHttpMethodDefinitions$1, getMcpEventDefinitions, normalizeParameterKeys, z } from "@open-wa/schema";
|
|
3
|
+
import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { ProtocolError, ProtocolErrorCode, Server, createMcpHandler } from "@modelcontextprotocol/server";
|
|
6
|
+
import { z as z$1 } from "zod";
|
|
7
|
+
import { ScopedTaskQueue } from "@open-wa/runtime-core";
|
|
8
|
+
import { Webhook } from "standardwebhooks";
|
|
9
|
+
import { lookup } from "node:dns/promises";
|
|
10
|
+
import { request } from "node:https";
|
|
11
|
+
import { isIP } from "node:net";
|
|
12
|
+
import ipaddr from "ipaddr.js";
|
|
13
|
+
import { chmodSync, mkdirSync } from "node:fs";
|
|
14
|
+
import { DatabaseSync } from "node:sqlite";
|
|
7
15
|
//#region src/tool-naming.ts
|
|
8
16
|
/**
|
|
9
17
|
* Logic for stable, namespaced MCP tool names.
|
|
@@ -187,122 +195,527 @@ var AuthenticationError = class extends ToolExecutionError {
|
|
|
187
195
|
}
|
|
188
196
|
};
|
|
189
197
|
//#endregion
|
|
198
|
+
//#region src/events/callback.ts
|
|
199
|
+
function callbackUrl(value) {
|
|
200
|
+
const url = new URL(value);
|
|
201
|
+
if (url.protocol !== "https:" || url.username || url.password || url.hash) throw new Error("Callbacks require public HTTPS URLs without credentials or fragments");
|
|
202
|
+
return url;
|
|
203
|
+
}
|
|
204
|
+
function publicAddress(value) {
|
|
205
|
+
if (!ipaddr.isValid(value)) return false;
|
|
206
|
+
let address = ipaddr.parse(value);
|
|
207
|
+
if (address.kind() === "ipv6" && address.isIPv4MappedAddress()) address = address.toIPv4Address();
|
|
208
|
+
return address.range() === "unicast";
|
|
209
|
+
}
|
|
210
|
+
/** DNS resolution happens inside each connection; TLS still verifies the original hostname. */
|
|
211
|
+
function postCallback(urlString, body, headers, signal) {
|
|
212
|
+
const url = callbackUrl(urlString);
|
|
213
|
+
const hostname = url.hostname.replace(/^\[|\]$/g, "");
|
|
214
|
+
if (isIP(hostname) && !publicAddress(hostname)) return Promise.reject(/* @__PURE__ */ new Error("Callback destination is not a public address"));
|
|
215
|
+
return new Promise((resolve, reject) => {
|
|
216
|
+
const req = request(url, {
|
|
217
|
+
method: "POST",
|
|
218
|
+
agent: false,
|
|
219
|
+
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4),
|
|
220
|
+
headers: {
|
|
221
|
+
"Content-Type": "application/json",
|
|
222
|
+
"Content-Length": String(Buffer.byteLength(body)),
|
|
223
|
+
...headers
|
|
224
|
+
},
|
|
225
|
+
lookup: (_hostname, options, callback) => {
|
|
226
|
+
(isIP(hostname) ? Promise.resolve([{
|
|
227
|
+
address: hostname,
|
|
228
|
+
family: isIP(hostname)
|
|
229
|
+
}]) : lookup(hostname, {
|
|
230
|
+
all: true,
|
|
231
|
+
verbatim: true
|
|
232
|
+
})).then((addresses) => {
|
|
233
|
+
if (!addresses.length || addresses.some((address) => !publicAddress(address.address))) throw new Error("Callback destination is not a public address");
|
|
234
|
+
const selected = addresses[0];
|
|
235
|
+
if (options.all) callback(null, [selected]);
|
|
236
|
+
else callback(null, selected.address, selected.family);
|
|
237
|
+
}).catch((error) => callback(error, ""));
|
|
238
|
+
}
|
|
239
|
+
}, (response) => {
|
|
240
|
+
const chunks = [];
|
|
241
|
+
let length = 0;
|
|
242
|
+
response.on("data", (chunk) => {
|
|
243
|
+
length += chunk.length;
|
|
244
|
+
if (length > 16384) {
|
|
245
|
+
response.destroy(/* @__PURE__ */ new Error("Callback response exceeds 16 KiB"));
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
chunks.push(Buffer.from(chunk));
|
|
249
|
+
});
|
|
250
|
+
response.on("error", reject);
|
|
251
|
+
response.on("end", () => resolve({
|
|
252
|
+
status: response.statusCode ?? 0,
|
|
253
|
+
body: Buffer.concat(chunks).toString("utf8")
|
|
254
|
+
}));
|
|
255
|
+
});
|
|
256
|
+
req.on("error", reject);
|
|
257
|
+
req.end(body);
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
//#endregion
|
|
261
|
+
//#region src/events/protocol.ts
|
|
262
|
+
const argumentsSchema = z$1.record(z$1.string(), z$1.unknown());
|
|
263
|
+
const deliverySchema = z$1.object({
|
|
264
|
+
mode: z$1.literal("webhook"),
|
|
265
|
+
url: z$1.string().url(),
|
|
266
|
+
secret: z$1.string()
|
|
267
|
+
});
|
|
268
|
+
const subscribeSchema = z$1.object({
|
|
269
|
+
name: z$1.string(),
|
|
270
|
+
arguments: argumentsSchema.default({}),
|
|
271
|
+
delivery: deliverySchema,
|
|
272
|
+
cursor: z$1.string().nullable().optional(),
|
|
273
|
+
ttlMs: z$1.number().int().positive().nullable().optional()
|
|
274
|
+
});
|
|
275
|
+
const unsubscribeSchema = subscribeSchema.pick({
|
|
276
|
+
name: true,
|
|
277
|
+
arguments: true
|
|
278
|
+
}).extend({ delivery: deliverySchema.omit({ secret: true }) });
|
|
279
|
+
const subscriptionResultSchema = z$1.object({
|
|
280
|
+
id: z$1.string(),
|
|
281
|
+
refreshBefore: z$1.string().datetime().nullable(),
|
|
282
|
+
cursor: z$1.null(),
|
|
283
|
+
truncated: z$1.boolean()
|
|
284
|
+
});
|
|
285
|
+
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
|
+
})) });
|
|
293
|
+
function canonicalJson(value) {
|
|
294
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
295
|
+
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
|
+
return JSON.stringify(value) ?? "null";
|
|
297
|
+
}
|
|
298
|
+
//#endregion
|
|
299
|
+
//#region src/events/store.ts
|
|
300
|
+
/** Secrets and payloads stay in a private local journal, never discovery or logs. */
|
|
301
|
+
var McpEventStore = class {
|
|
302
|
+
constructor(path) {
|
|
303
|
+
mkdirSync(dirname(path), {
|
|
304
|
+
recursive: true,
|
|
305
|
+
mode: 448
|
|
306
|
+
});
|
|
307
|
+
this.db = new DatabaseSync(path);
|
|
308
|
+
chmodSync(path, 384);
|
|
309
|
+
this.db.exec(`
|
|
310
|
+
PRAGMA journal_mode=WAL;
|
|
311
|
+
PRAGMA synchronous=FULL;
|
|
312
|
+
PRAGMA foreign_keys=ON;
|
|
313
|
+
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
|
|
316
|
+
);
|
|
317
|
+
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)
|
|
321
|
+
);
|
|
322
|
+
CREATE INDEX IF NOT EXISTS mcp_event_pending ON mcp_event_deliveries(next_attempt_at);
|
|
323
|
+
`);
|
|
324
|
+
}
|
|
325
|
+
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);
|
|
328
|
+
}
|
|
329
|
+
get(id, owner) {
|
|
330
|
+
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 ? {
|
|
332
|
+
id: String(row.id),
|
|
333
|
+
owner: String(row.owner),
|
|
334
|
+
name: String(row.name),
|
|
335
|
+
arguments: JSON.parse(String(row.arguments)),
|
|
336
|
+
url: String(row.url),
|
|
337
|
+
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
|
+
});
|
|
346
|
+
}
|
|
347
|
+
remove(id, owner) {
|
|
348
|
+
this.db.prepare("DELETE FROM mcp_event_subscriptions WHERE id=? AND owner=?").run(id, owner);
|
|
349
|
+
}
|
|
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());
|
|
352
|
+
}
|
|
353
|
+
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) => ({
|
|
356
|
+
id: Number(row.id),
|
|
357
|
+
subscriptionId: String(row.subscription_id),
|
|
358
|
+
eventId: String(row.event_id),
|
|
359
|
+
body: String(row.body),
|
|
360
|
+
attempts: Number(row.attempts),
|
|
361
|
+
nextAttemptAt: Number(row.next_attempt_at)
|
|
362
|
+
}));
|
|
363
|
+
}
|
|
364
|
+
retry(id, nextAttemptAt) {
|
|
365
|
+
this.db.prepare("UPDATE mcp_event_deliveries SET attempts=attempts+1,next_attempt_at=? WHERE id=?").run(nextAttemptAt, id);
|
|
366
|
+
}
|
|
367
|
+
complete(id) {
|
|
368
|
+
this.db.prepare("DELETE FROM mcp_event_deliveries WHERE id=?").run(id);
|
|
369
|
+
}
|
|
370
|
+
close() {
|
|
371
|
+
this.db.close();
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
//#endregion
|
|
375
|
+
//#region src/events/service.ts
|
|
376
|
+
const MAX_BODY_BYTES = 262144;
|
|
377
|
+
const MAX_ATTEMPTS = 4;
|
|
378
|
+
const error = (message) => new ProtocolError(ProtocolErrorCode.InvalidParams, message);
|
|
379
|
+
const object = (value) => value && typeof value === "object" ? value : {};
|
|
380
|
+
var McpEventsService = class {
|
|
381
|
+
constructor(options) {
|
|
382
|
+
this.options = options;
|
|
383
|
+
this.controller = new AbortController();
|
|
384
|
+
this.active = /* @__PURE__ */ new Map();
|
|
385
|
+
this.deliveries = /* @__PURE__ */ new Map();
|
|
386
|
+
this.verified = /* @__PURE__ */ new Map();
|
|
387
|
+
this.closing = false;
|
|
388
|
+
this.store = new McpEventStore(options.storePath);
|
|
389
|
+
this.queue = ScopedTaskQueue.make({
|
|
390
|
+
name: "mcp.events",
|
|
391
|
+
capacity: 100,
|
|
392
|
+
concurrency: 4,
|
|
393
|
+
overload: "dropping"
|
|
394
|
+
});
|
|
395
|
+
this.timer = setInterval(() => this.pump(), 1e3);
|
|
396
|
+
this.timer.unref?.();
|
|
397
|
+
this.queue.then(() => this.pump()).catch(() => this.log("mcp_event_queue_unavailable"));
|
|
398
|
+
}
|
|
399
|
+
list(cursor) {
|
|
400
|
+
if (cursor !== void 0) throw error("The event catalog fits in one page; omit cursor");
|
|
401
|
+
return { events: getMcpEventDefinitions() };
|
|
402
|
+
}
|
|
403
|
+
principal() {
|
|
404
|
+
const owner = this.options.owner();
|
|
405
|
+
if (!owner || this.closing) throw new ProtocolError(-32001, "MCP access is unavailable");
|
|
406
|
+
return owner;
|
|
407
|
+
}
|
|
408
|
+
validated(name, args) {
|
|
409
|
+
const contract = getEventContract(name);
|
|
410
|
+
if (!contract?.mcp) throw error("Unknown or unavailable MCP event");
|
|
411
|
+
const parsed = contract.mcp.inputSchema.safeParse(args);
|
|
412
|
+
if (!parsed.success) throw error("Invalid subscription filters");
|
|
413
|
+
return {
|
|
414
|
+
contract,
|
|
415
|
+
arguments: parsed.data
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
identity(owner, name, args, url) {
|
|
419
|
+
return `sub_${createHash("sha256").update(canonicalJson({
|
|
420
|
+
owner,
|
|
421
|
+
name,
|
|
422
|
+
arguments: args,
|
|
423
|
+
url
|
|
424
|
+
})).digest("hex")}`;
|
|
425
|
+
}
|
|
426
|
+
async subscribe(params) {
|
|
427
|
+
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");
|
|
430
|
+
let url;
|
|
431
|
+
try {
|
|
432
|
+
url = callbackUrl(params.delivery.url).href;
|
|
433
|
+
} catch {
|
|
434
|
+
throw error("Callback must be a public HTTPS URL without credentials or fragments");
|
|
435
|
+
}
|
|
436
|
+
const encodedKey = params.delivery.secret.slice(6);
|
|
437
|
+
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");
|
|
439
|
+
const id = this.identity(owner, params.name, args, url);
|
|
440
|
+
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({
|
|
445
|
+
id,
|
|
446
|
+
owner,
|
|
447
|
+
name: params.name,
|
|
448
|
+
arguments: args,
|
|
449
|
+
url,
|
|
450
|
+
secret: params.delivery.secret,
|
|
451
|
+
expiresAt
|
|
452
|
+
});
|
|
453
|
+
return {
|
|
454
|
+
id,
|
|
455
|
+
refreshBefore: new Date(expiresAt).toISOString(),
|
|
456
|
+
cursor: null,
|
|
457
|
+
truncated: false
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
unsubscribe(params) {
|
|
461
|
+
const owner = this.principal();
|
|
462
|
+
const { arguments: args } = this.validated(params.name, params.arguments);
|
|
463
|
+
let url;
|
|
464
|
+
try {
|
|
465
|
+
url = callbackUrl(params.delivery.url).href;
|
|
466
|
+
} catch {
|
|
467
|
+
throw error("Invalid callback URL");
|
|
468
|
+
}
|
|
469
|
+
const id = this.identity(owner, params.name, args, url);
|
|
470
|
+
this.store.remove(id, owner);
|
|
471
|
+
for (const controller of this.deliveries.get(id) ?? []) controller.abort();
|
|
472
|
+
return {};
|
|
473
|
+
}
|
|
474
|
+
async verify(owner, id, url, secret) {
|
|
475
|
+
const now = Date.now();
|
|
476
|
+
for (const [cacheKey, expiry] of this.verified) if (expiry <= now) this.verified.delete(cacheKey);
|
|
477
|
+
const cacheKey = canonicalJson({
|
|
478
|
+
owner,
|
|
479
|
+
url
|
|
480
|
+
});
|
|
481
|
+
if ((this.verified.get(cacheKey) ?? 0) > now) return;
|
|
482
|
+
const challenge = randomUUID();
|
|
483
|
+
const eventId = `verification_${randomUUID()}`;
|
|
484
|
+
const body = JSON.stringify({
|
|
485
|
+
type: "verification",
|
|
486
|
+
challenge
|
|
487
|
+
});
|
|
488
|
+
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" });
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
headers(secret, subscriptionId, eventId, body) {
|
|
501
|
+
const at = /* @__PURE__ */ new Date();
|
|
502
|
+
return {
|
|
503
|
+
"webhook-id": eventId,
|
|
504
|
+
"webhook-timestamp": String(Math.floor(at.getTime() / 1e3)),
|
|
505
|
+
"webhook-signature": new Webhook(secret).sign(eventId, at, body),
|
|
506
|
+
"X-MCP-Subscription-Id": subscriptionId
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
publish(name, payload) {
|
|
510
|
+
const owner = this.options.owner();
|
|
511
|
+
const contract = getEventContract(name);
|
|
512
|
+
if (this.closing || !owner || !contract?.mcp) return;
|
|
513
|
+
const projected = contract.mcp.payloadSchema.safeParse(contract.mcp.project(payload, this.options.sessionId));
|
|
514
|
+
if (!projected.success) {
|
|
515
|
+
this.log("mcp_event_payload_unavailable", name);
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
const data = projected.data;
|
|
519
|
+
const runtime = object(payload);
|
|
520
|
+
const occurredAt = object(runtime.ctx).ts ?? runtime.ts;
|
|
521
|
+
if (typeof occurredAt !== "number" || !Number.isFinite(occurredAt)) {
|
|
522
|
+
this.log("mcp_event_timestamp_unavailable", name);
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
const date = new Date(occurredAt);
|
|
526
|
+
if (!Number.isFinite(date.getTime())) return;
|
|
527
|
+
const eventId = `evt_${randomUUID()}`;
|
|
528
|
+
const body = JSON.stringify({
|
|
529
|
+
eventId,
|
|
530
|
+
name,
|
|
531
|
+
timestamp: date.toISOString(),
|
|
532
|
+
data,
|
|
533
|
+
cursor: null
|
|
534
|
+
});
|
|
535
|
+
if (Buffer.byteLength(body) > MAX_BODY_BYTES) {
|
|
536
|
+
this.log("mcp_event_payload_too_large", name);
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
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
|
+
}
|
|
543
|
+
this.pump();
|
|
544
|
+
}
|
|
545
|
+
pump() {
|
|
546
|
+
if (this.closing) return;
|
|
547
|
+
try {
|
|
548
|
+
for (const job of this.store.pending()) {
|
|
549
|
+
if (this.active.size >= 100) break;
|
|
550
|
+
if (this.active.has(job.id)) continue;
|
|
551
|
+
const pending = this.queue.then((queue) => queue.submit(() => this.deliver(job), `event.${job.id}`)).catch(() => this.log("mcp_event_delivery_deferred")).finally(() => this.active.delete(job.id));
|
|
552
|
+
this.active.set(job.id, pending);
|
|
553
|
+
}
|
|
554
|
+
} catch {
|
|
555
|
+
this.log("mcp_event_journal_unavailable");
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
async deliver(job) {
|
|
559
|
+
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;
|
|
565
|
+
}
|
|
566
|
+
const controller = new AbortController();
|
|
567
|
+
const signals = this.deliveries.get(subscription.id) ?? /* @__PURE__ */ new Set();
|
|
568
|
+
signals.add(controller);
|
|
569
|
+
this.deliveries.set(subscription.id, signals);
|
|
570
|
+
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]));
|
|
572
|
+
if (response.status >= 200 && response.status < 300) {
|
|
573
|
+
this.store.complete(job.id);
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
if (response.status === 410 || response.status === 413 || response.status < 500 && response.status !== 408 && response.status !== 429) {
|
|
577
|
+
this.store.complete(job.id);
|
|
578
|
+
this.log("mcp_event_delivery_rejected", subscription.name);
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
this.retry(job, subscription);
|
|
582
|
+
} catch {
|
|
583
|
+
if (!this.closing && !controller.signal.aborted) this.retry(job, subscription);
|
|
584
|
+
} finally {
|
|
585
|
+
signals.delete(controller);
|
|
586
|
+
if (!signals.size) this.deliveries.delete(subscription.id);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
retry(job, subscription) {
|
|
590
|
+
if (job.attempts + 1 >= MAX_ATTEMPTS) {
|
|
591
|
+
this.store.complete(job.id);
|
|
592
|
+
this.log("mcp_event_delivery_exhausted", subscription.name);
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
this.store.retry(job.id, Date.now() + 1e3 * 2 ** job.attempts);
|
|
596
|
+
}
|
|
597
|
+
log(message, event) {
|
|
598
|
+
this.options.log?.({
|
|
599
|
+
level: "warn",
|
|
600
|
+
component: "mcp.events",
|
|
601
|
+
message,
|
|
602
|
+
event
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
async close() {
|
|
606
|
+
if (this.closing) return;
|
|
607
|
+
this.closing = true;
|
|
608
|
+
clearInterval(this.timer);
|
|
609
|
+
this.controller.abort();
|
|
610
|
+
await (await this.queue).close();
|
|
611
|
+
await Promise.allSettled([...this.active.values()]);
|
|
612
|
+
this.store.close();
|
|
613
|
+
}
|
|
614
|
+
};
|
|
615
|
+
//#endregion
|
|
616
|
+
//#region package.json
|
|
617
|
+
var version = "5.6.0";
|
|
618
|
+
//#endregion
|
|
190
619
|
//#region src/adapter/hono-mcp.ts
|
|
191
|
-
/**
|
|
192
|
-
* Creates an MCP adapter using the Streamable HTTP transport (single-endpoint).
|
|
193
|
-
*
|
|
194
|
-
* open-wa product decision:
|
|
195
|
-
* hosted MCP is Easy API-only and unavailable through createClient()
|
|
196
|
-
*
|
|
197
|
-
* This adapter:
|
|
198
|
-
* - Uses WebStandardStreamableHTTPServerTransport for a single-endpoint /mcp shape
|
|
199
|
-
* - Enforces Easy API API-key auth on every request
|
|
200
|
-
* - Gates tool execution on session readiness (parity with HTTP transport)
|
|
201
|
-
* - Returns protocol errors for malformed protocol requests
|
|
202
|
-
* - Returns tool-level errors for open-wa execution failures
|
|
203
|
-
*/
|
|
620
|
+
/** Easy API's authenticated MCP 2.0 tools and webhook event endpoint. */
|
|
204
621
|
function createHonoMcpAdapter(options) {
|
|
205
622
|
const { config, clientSource, elasticEmitter, basePath = "/api", isSessionConnected } = options;
|
|
623
|
+
if (!config.apiKey) throw new Error("MCP requires an Easy API apiKey");
|
|
206
624
|
const toolDefinitions = getMcpToolDefinitions(basePath);
|
|
207
|
-
const toolMap = new Map(toolDefinitions.map((
|
|
208
|
-
const
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
})) };
|
|
625
|
+
const toolMap = new Map(toolDefinitions.map((def) => [def.toolName, def]));
|
|
626
|
+
const executionDefinitions = new Map(getHttpMethodDefinitions$1(basePath).map((def) => [def.functionName, def]));
|
|
627
|
+
const owner = () => config.apiKey ? createHash("sha256").update(`${config.sessionId ?? ""}\0${config.apiKey}`).digest("hex") : void 0;
|
|
628
|
+
const eventConfig = config.mcp?.events;
|
|
629
|
+
const events = eventConfig?.enabled === false ? void 0 : new McpEventsService({
|
|
630
|
+
sessionId: config.sessionId ?? "",
|
|
631
|
+
owner,
|
|
632
|
+
storePath: eventConfig?.storePath ?? join(".open-wa", `mcp-events-${owner().slice(0, 24)}.sqlite`),
|
|
633
|
+
lifetimeMs: eventConfig?.lifetimeMs ?? 864e5,
|
|
634
|
+
log: (data) => elasticEmitter?.log(data)
|
|
218
635
|
});
|
|
219
|
-
|
|
220
|
-
const
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
isError: true,
|
|
224
|
-
content: [{
|
|
225
|
-
type: "text",
|
|
226
|
-
text: `Unknown tool: ${name}. Use tools/list to discover available tools.`
|
|
227
|
-
}]
|
|
636
|
+
const handler = createMcpHandler(() => {
|
|
637
|
+
const capabilities = {
|
|
638
|
+
tools: {},
|
|
639
|
+
...events ? { events: {} } : {}
|
|
228
640
|
};
|
|
229
|
-
|
|
230
|
-
|
|
641
|
+
const server = new Server({
|
|
642
|
+
name: "open-wa",
|
|
643
|
+
version
|
|
644
|
+
}, { capabilities });
|
|
645
|
+
server.setRequestHandler("tools/list", async () => ({ tools: toolDefinitions.map((def) => ({
|
|
646
|
+
name: def.toolName,
|
|
647
|
+
description: def.description,
|
|
648
|
+
inputSchema: eventJsonSchema(def.inputSchema),
|
|
649
|
+
annotations: def.annotations
|
|
650
|
+
})) }));
|
|
651
|
+
server.setRequestHandler("tools/call", async (request) => {
|
|
652
|
+
const { name, arguments: args } = request.params;
|
|
653
|
+
const definition = toolMap.get(name);
|
|
654
|
+
const failure = (text) => ({
|
|
231
655
|
isError: true,
|
|
232
656
|
content: [{
|
|
233
657
|
type: "text",
|
|
234
|
-
text
|
|
658
|
+
text
|
|
235
659
|
}]
|
|
236
|
-
};
|
|
237
|
-
}
|
|
238
|
-
const result = await executeCapability({
|
|
239
|
-
client: clientSource(),
|
|
240
|
-
definition,
|
|
241
|
-
payload: args || {},
|
|
242
|
-
elasticEmitter,
|
|
243
|
-
sessionId: config.sessionId
|
|
244
|
-
});
|
|
245
|
-
if (result.success) return { content: [{
|
|
246
|
-
type: "text",
|
|
247
|
-
text: JSON.stringify(result.data, null, 2)
|
|
248
|
-
}] };
|
|
249
|
-
return {
|
|
250
|
-
isError: true,
|
|
251
|
-
content: [{
|
|
252
|
-
type: "text",
|
|
253
|
-
text: result.error || "Internal Execution Error"
|
|
254
|
-
}]
|
|
255
|
-
};
|
|
256
|
-
});
|
|
257
|
-
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
258
|
-
sessionIdGenerator: () => crypto.randomUUID(),
|
|
259
|
-
onsessioninitialized: (sessionId) => {
|
|
260
|
-
elasticEmitter?.log({
|
|
261
|
-
level: "info",
|
|
262
|
-
component: "mcp",
|
|
263
|
-
message: `MCP session initialized: ${sessionId}`,
|
|
264
|
-
sessionId: config.sessionId
|
|
265
660
|
});
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
661
|
+
if (!definition) return failure(`Unknown tool: ${name}. Use tools/list to discover available tools.`);
|
|
662
|
+
if (isSessionConnected && !isSessionConnected() && config.apiLifecycle !== "immediate") return failure("Session is not connected or ready. Tool execution is blocked until the session is fully ready.");
|
|
663
|
+
const result = await executeCapability({
|
|
664
|
+
client: clientSource(),
|
|
665
|
+
definition: executionDefinitions.get(definition.functionName),
|
|
666
|
+
payload: args || {},
|
|
667
|
+
elasticEmitter,
|
|
272
668
|
sessionId: config.sessionId
|
|
273
669
|
});
|
|
670
|
+
return result.success ? { content: [{
|
|
671
|
+
type: "text",
|
|
672
|
+
text: JSON.stringify(result.data ?? null, null, 2)
|
|
673
|
+
}] } : failure(result.error || "Internal Execution Error");
|
|
674
|
+
});
|
|
675
|
+
if (events) {
|
|
676
|
+
server.setRequestHandler("events/list", {
|
|
677
|
+
params: eventListParamsSchema,
|
|
678
|
+
result: eventListResultSchema
|
|
679
|
+
}, async (params) => events.list(params.cursor));
|
|
680
|
+
server.setRequestHandler("events/subscribe", {
|
|
681
|
+
params: subscribeSchema,
|
|
682
|
+
result: subscriptionResultSchema
|
|
683
|
+
}, (params) => events.subscribe(params));
|
|
684
|
+
server.setRequestHandler("events/unsubscribe", {
|
|
685
|
+
params: unsubscribeSchema,
|
|
686
|
+
result: z$1.object({})
|
|
687
|
+
}, async (params) => events.unsubscribe(params));
|
|
274
688
|
}
|
|
275
|
-
|
|
276
|
-
|
|
689
|
+
return server;
|
|
690
|
+
}, { legacy: "reject" });
|
|
277
691
|
return {
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
* API-key auth is enforced on every request before delegation to MCP.
|
|
287
|
-
*/
|
|
288
|
-
mount: (app, path) => {
|
|
289
|
-
app.all(`${path}`, async (c) => {
|
|
290
|
-
if (config.apiKey) {
|
|
291
|
-
const resolvedKey = c.req.header("X-API-Key") || c.req.header("api_key") || c.req.header("key");
|
|
292
|
-
if (!resolvedKey || resolvedKey !== config.apiKey) return c.json({
|
|
293
|
-
error: "Unauthorized",
|
|
294
|
-
details: "Invalid or missing API key for MCP endpoint"
|
|
295
|
-
}, 401);
|
|
296
|
-
}
|
|
297
|
-
return await transport.handleRequest(c.req.raw);
|
|
692
|
+
mount(app, path) {
|
|
693
|
+
app.all(path, async (c) => {
|
|
694
|
+
const key = c.req.header("X-API-Key") || c.req.header("api_key") || c.req.header("key");
|
|
695
|
+
if (!config.apiKey || key !== config.apiKey) return c.json({
|
|
696
|
+
error: "Unauthorized",
|
|
697
|
+
details: "Invalid or missing API key for MCP endpoint"
|
|
698
|
+
}, 401);
|
|
699
|
+
return handler.fetch(c.req.raw);
|
|
298
700
|
});
|
|
299
701
|
},
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
702
|
+
publishEvent(name, payload) {
|
|
703
|
+
try {
|
|
704
|
+
events?.publish(name, payload);
|
|
705
|
+
} catch {
|
|
706
|
+
elasticEmitter?.log({
|
|
707
|
+
level: "error",
|
|
708
|
+
component: "mcp.events",
|
|
709
|
+
message: "mcp_event_journal_write_failed"
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
},
|
|
713
|
+
async close() {
|
|
714
|
+
try {
|
|
715
|
+
await handler.close();
|
|
716
|
+
} finally {
|
|
717
|
+
await events?.close();
|
|
718
|
+
}
|
|
306
719
|
}
|
|
307
720
|
};
|
|
308
721
|
}
|