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