@mosadd/mcp 3.0.0-alpha.5 → 3.0.0-alpha.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +309 -0
  2. package/LICENSE +201 -201
  3. package/README.md +150 -126
  4. package/dist/bin/mcp.js +42 -3
  5. package/dist/chunk-BTAIZKYT.js +3800 -0
  6. package/dist/index.d.ts +118 -5
  7. package/dist/index.js +7 -3
  8. package/package.json +10 -7
  9. package/src/__tests__/channel-e2ee.test.ts +62 -0
  10. package/src/__tests__/golden-path.test.ts +139 -137
  11. package/src/__tests__/integration.test.ts +182 -178
  12. package/src/__tests__/knowledge-ingest.test.ts +114 -0
  13. package/src/__tests__/mdm-e2ee.test.ts +212 -178
  14. package/src/__tests__/mirc-invite.test.ts +112 -0
  15. package/src/__tests__/mtalk.test.ts +122 -122
  16. package/src/__tests__/presence.test.ts +199 -0
  17. package/src/__tests__/server.test.ts +71 -67
  18. package/src/__tests__/serverJsonVersion.test.ts +45 -0
  19. package/src/__tests__/tool-count-consistency.test.ts +199 -0
  20. package/src/bin/login.ts +138 -138
  21. package/src/bin/mcp.ts +145 -97
  22. package/src/config.ts +66 -66
  23. package/src/crypto/channel-e2ee.ts +288 -0
  24. package/src/crypto/mdm-session.ts +502 -403
  25. package/src/index.ts +19 -17
  26. package/src/observability/sentry.ts +79 -79
  27. package/src/providers/blob-upload.ts +116 -0
  28. package/src/providers/memory-voice.ts +79 -79
  29. package/src/providers/supabase-dm.ts +122 -117
  30. package/src/providers/supabase-voice.ts +91 -91
  31. package/src/providers/supabase.ts +231 -96
  32. package/src/server.ts +162 -105
  33. package/src/tools/__tests__/ragDeleteFoldsSourceId.test.ts +67 -0
  34. package/src/tools/actions.ts +166 -0
  35. package/src/tools/attachments.ts +276 -0
  36. package/src/tools/capabilities.ts +70 -68
  37. package/src/tools/embed.ts +110 -0
  38. package/src/tools/index.ts +181 -51
  39. package/src/tools/knowledge-graph.ts +186 -0
  40. package/src/tools/knowledge.ts +344 -132
  41. package/src/tools/mail-agentbox.ts +155 -0
  42. package/src/tools/mail-aliases.ts +25 -0
  43. package/src/tools/mail-provenance.ts +137 -0
  44. package/src/tools/mail.ts +403 -157
  45. package/src/tools/mcall.ts +216 -216
  46. package/src/tools/mdm-as-agent.ts +126 -0
  47. package/src/tools/mdm-voice.ts +220 -206
  48. package/src/tools/mdm.ts +73 -26
  49. package/src/tools/mirc-edge.ts +196 -190
  50. package/src/tools/mirc-members.ts +287 -177
  51. package/src/tools/mirc-messages.ts +76 -27
  52. package/src/tools/mirc.ts +308 -170
  53. package/src/tools/mroom-messages.ts +142 -142
  54. package/src/tools/mroom.ts +221 -221
  55. package/src/tools/mtalk.ts +131 -121
  56. package/src/tools/murl.ts +314 -0
  57. package/src/tools/presence.ts +442 -0
  58. package/src/tools/ptt-ingest.ts +99 -0
  59. package/src/tools/threat.ts +123 -0
  60. package/src/tools/voice-format.ts +28 -0
  61. package/src/types.ts +121 -85
  62. package/src/version.ts +8 -0
  63. package/src/voice/floor.ts +132 -132
  64. package/dist/chunk-4C36JDTJ.js +0 -1836
package/src/tools/mdm.ts CHANGED
@@ -10,12 +10,13 @@
10
10
  * their own Supabase URL + anon key + a session JWT via env vars (BYOK).
11
11
  *
12
12
  * Phase 2 will route through the hosted gateway (mcp.mosadd.com) with the
13
- * 167-event radar middleware in front, and replace the plaintext
13
+ * threat-radar middleware in front, and replace the plaintext
14
14
  * encrypted_payload with real X3DH + Double Ratchet via @mosadd/crypto.
15
15
  */
16
16
 
17
17
  import { z } from "zod";
18
18
  import type { MosaddTool, MosaddToolContext } from "../types.js";
19
+ import { formatVoiceIfAny } from "./voice-format.js";
19
20
  import { invokeFunction, getSupabase, readSupabaseEnv } from "../providers/supabase.js";
20
21
  import {
21
22
  encryptForPeer,
@@ -115,24 +116,21 @@ async function resolveSelfIdentityId(): Promise<string> {
115
116
  * Receivers in the mosadd consumer app understand this `mosadd.chat.v1` shape.
116
117
  * V0.2: replace with @mosadd/crypto Double Ratchet wrap.
117
118
  */
118
- function packPlaintextPayload(text: string, replyToId?: string): Uint8Array {
119
- const envelope = {
120
- v: PROTOCOL_VERSION,
121
- type: "text",
122
- text,
123
- reply_to: replyToId ?? null,
124
- sent_at: new Date().toISOString(),
125
- };
126
- // OPAQUE bytes handed to the DmProvider — the provider does not interpret
127
- // them. Today: utf8 JSON. V0.2: @mosadd/crypto Double Ratchet ciphertext.
128
- return new Uint8Array(Buffer.from(JSON.stringify(envelope), "utf8"));
119
+ function packPlaintextPayload(text: string): Uint8Array {
120
+ // Pure text bytes so the consumer app displays clean message text directly
121
+ return new Uint8Array(Buffer.from(text, "utf8"));
129
122
  }
130
123
 
131
124
  function unpackPayload(payload: Uint8Array): { text: string; sent_at?: string; reply_to?: string | null } {
132
125
  try {
133
- const json = Buffer.from(payload).toString("utf8");
134
- const obj = JSON.parse(json);
135
- if (typeof obj?.text === "string") return obj;
126
+ const raw = Buffer.from(payload).toString("utf8");
127
+ try {
128
+ const obj = JSON.parse(raw);
129
+ if (typeof obj?.text === "string") return obj;
130
+ } catch {
131
+ return { text: raw };
132
+ }
133
+ return { text: raw };
136
134
  } catch {
137
135
  /* fall through */
138
136
  }
@@ -153,7 +151,9 @@ async function mDM_send(
153
151
  const selfId = await dm.selfId();
154
152
  const threadId = dmThreadId(selfId, input.to, input.thread_label);
155
153
 
156
- const inner = packPlaintextPayload(input.text, input.reply_to_id);
154
+ // reply-linkage jedzie w dm.send({replyToId}) — surowy tekst nie ma koperty, w którą
155
+ // można by go wpakować (zmiana formatu 2026-08-25, patrz packPlaintextPayload).
156
+ const inner = packPlaintextPayload(input.text);
157
157
  const sealed = await encryptForPeer(ctx.providers.keys, dm, input.to, inner);
158
158
 
159
159
  ctx.log("debug", "mDM_send E2EE via DmProvider", { thread_id: threadId, bytes: sealed.byteLength });
@@ -190,7 +190,7 @@ async function mDM_send_unencrypted(
190
190
  const dm = ctx.providers.dm;
191
191
  const selfId = await dm.selfId();
192
192
  const threadId = dmThreadId(selfId, input.to, input.thread_label);
193
- const payload = packPlaintextPayload(input.text, input.reply_to_id);
193
+ const payload = packPlaintextPayload(input.text);
194
194
 
195
195
  ctx.log("warn", "mDM_send_unencrypted (deprecated, plaintext) via DmProvider", {
196
196
  thread_id: threadId,
@@ -256,7 +256,7 @@ async function mDM_list(
256
256
  };
257
257
  // Legacy plaintext envelope (deprecated path) — unpack directly.
258
258
  if (!isE2eeEnvelope(m.payload)) {
259
- return { ...base, text: unpackPayload(m.payload).text, encrypted: false };
259
+ return { ...base, text: formatVoiceIfAny(unpackPayload(m.payload).text), encrypted: false };
260
260
  }
261
261
  // Our own outgoing ratchet messages aren't decryptable from our own
262
262
  // ratchet on read. Recover the plaintext from the local sent-items cache
@@ -265,13 +265,13 @@ async function mDM_list(
265
265
  if (m.senderId === selfId) {
266
266
  const cached = await ctx.providers.keys.getSentMessage?.(m.id);
267
267
  if (cached) {
268
- return { ...base, text: unpackPayload(cached).text, encrypted: true };
268
+ return { ...base, text: formatVoiceIfAny(unpackPayload(cached).text), encrypted: true };
269
269
  }
270
270
  return { ...base, text: "<encrypted · sent by you>", encrypted: true };
271
271
  }
272
272
  try {
273
273
  const inner = await decryptFromPeer(ctx.providers.keys, m.senderId, m.payload);
274
- return { ...base, text: unpackPayload(inner).text, encrypted: true };
274
+ return { ...base, text: formatVoiceIfAny(unpackPayload(inner).text), encrypted: true };
275
275
  } catch (err) {
276
276
  ctx.log("warn", "mDM_list failed to decrypt a message", { id: m.id, error: String(err) });
277
277
  return { ...base, text: "<undecryptable>", encrypted: true };
@@ -329,9 +329,12 @@ async function mDM_respond_request(
329
329
  ): Promise<{ ok: true }> {
330
330
  readSupabaseEnv();
331
331
  ctx.log("debug", "mDM_respond_request invoking message-request-respond", input);
332
+ // message-request-respond expects action:"respond" + status accepted/rejected
333
+ // (not action:"accept"/"reject"). Map it.
332
334
  await invokeFunction<{ ok: boolean }>("message-request-respond", {
335
+ action: "respond",
333
336
  request_id: input.request_id,
334
- action: input.action,
337
+ status: input.action === "accept" ? "accepted" : "rejected",
335
338
  });
336
339
  return { ok: true };
337
340
  }
@@ -339,8 +342,12 @@ async function mDM_respond_request(
339
342
  const mDM_publish_keys_input = z.object({});
340
343
 
341
344
  const mDM_edit_input = z.object({
345
+ to: ContactRef.describe(
346
+ "Recipient identity id of the conversation the message is in (needed to locate it and verify the edit won't break E2EE).",
347
+ ),
342
348
  message_id: z.string().min(1).describe("Id of the message to edit (from mDM_list)."),
343
349
  new_text: z.string().min(1).max(64_000).describe("Replacement message body (UTF-8). Max 64 KB."),
350
+ thread_label: ThreadSuffix.optional(),
344
351
  });
345
352
 
346
353
  const mDM_delete_input = z.object({
@@ -352,9 +359,33 @@ async function mDM_edit(
352
359
  ctx: MosaddToolContext,
353
360
  ): Promise<{ message_id: string; edited: true }> {
354
361
  readSupabaseEnv();
355
- // Wire format = base64(JSON envelope), matching the EF (which atob()s it).
356
- // NOTE: stored server-readable (like mDM_send_unencrypted). On an E2EE thread
357
- // this does NOT re-seal the message — prefer delete + re-send for ciphertext.
362
+ const dm = ctx.providers.dm;
363
+ const selfId = await dm.selfId();
364
+ const threadId = dmThreadId(selfId, input.to, input.thread_label);
365
+
366
+ // Locate the target message before editing. mDM is E2EE by default and the
367
+ // Double Ratchet is FORWARD-ONLY (strict in-order, no skipped keys) — an edit
368
+ // cannot be re-sealed (the recipient's ratchet has already advanced past this
369
+ // message, so a re-encrypt would decrypt as <undecryptable>), and writing a
370
+ // fresh plaintext body would SILENTLY STRIP E2EE. So only legacy plaintext
371
+ // messages are editable; E2EE messages must be deleted + re-sent.
372
+ const recent = await dm.list({ threadId, limit: 100 });
373
+ const target = recent.messages.find((m) => m.id === input.message_id);
374
+ if (!target) {
375
+ throw new Error(
376
+ `mDM_edit could not find message ${input.message_id} in the recent history of this thread. ` +
377
+ `Pass the 'to' (and 'thread_label') of the conversation the message belongs to.`,
378
+ );
379
+ }
380
+ if (isE2eeEnvelope(target.payload)) {
381
+ throw new Error(
382
+ "mDM_edit cannot edit an end-to-end-encrypted message: the Double Ratchet is forward-only, so the edit " +
383
+ "can't be re-sealed and storing a new body would strip E2EE. Delete it with mDM_delete and send a " +
384
+ "replacement with mDM_send instead.",
385
+ );
386
+ }
387
+
388
+ // Legacy plaintext message — a plaintext edit matches its (non-E2EE) storage.
358
389
  const envelope = {
359
390
  v: PROTOCOL_VERSION,
360
391
  type: "text",
@@ -363,7 +394,7 @@ async function mDM_edit(
363
394
  sent_at: new Date().toISOString(),
364
395
  };
365
396
  const encrypted_payload = Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
366
- ctx.log("debug", "mDM_edit via message-edit", { message_id: input.message_id });
397
+ ctx.log("debug", "mDM_edit via message-edit (legacy plaintext only)", { message_id: input.message_id });
367
398
  await invokeFunction("message-edit", { message_id: input.message_id, encrypted_payload });
368
399
  return { message_id: input.message_id, edited: true };
369
400
  }
@@ -383,6 +414,8 @@ async function mDM_delete(
383
414
  export const mdmTools: MosaddTool[] = [
384
415
  {
385
416
  name: "mDM_list_contacts",
417
+ title: "List contacts",
418
+ annotations: { readOnlyHint: true },
386
419
  requires: "any",
387
420
  description:
388
421
  "List the user's mosadd contacts. Returns identity_id (use this for mDM_send / mDM_list), account handle, display name, and contact state (pending, accepted, blocked).",
@@ -391,6 +424,8 @@ export const mdmTools: MosaddTool[] = [
391
424
  },
392
425
  {
393
426
  name: "mDM_publish_keys",
427
+ title: "Publish encryption keys",
428
+ annotations: { readOnlyHint: false },
394
429
  requires: "any",
395
430
  description:
396
431
  "Publish your mDM prekey bundle so other people can start an end-to-end-encrypted conversation with you. Run this once after sign-in (and to replenish one-time prekeys). Rides the same transport as messages, so it works over network or off-grid radio.",
@@ -399,6 +434,8 @@ export const mdmTools: MosaddTool[] = [
399
434
  },
400
435
  {
401
436
  name: "mDM_send",
437
+ title: "Send encrypted DM",
438
+ annotations: { readOnlyHint: false },
402
439
  requires: "any",
403
440
  description:
404
441
  "Send an END-TO-END-ENCRYPTED direct message via mosadd mDM. Pass `to` as the recipient's mosadd identity_id (look it up with mDM_list_contacts). Establishes an X3DH + Double Ratchet session on first contact (the recipient must have run mDM_publish_keys). Optional thread_label puts the message in a named thread — mosadd USP: multiple threads per contact, unlike WhatsApp/Telegram. If the recipient has no published keys yet, use mDM_send_unencrypted.",
@@ -407,6 +444,8 @@ export const mdmTools: MosaddTool[] = [
407
444
  },
408
445
  {
409
446
  name: "mDM_send_unencrypted",
447
+ title: "Send unencrypted DM",
448
+ annotations: { readOnlyHint: false },
410
449
  requires: "any",
411
450
  description:
412
451
  "DEPRECATED migration-window fallback: send a direct message WITHOUT end-to-end encryption (plaintext envelope). Only use when the recipient has not yet published prekeys (mDM_send fails with that hint). Prefer mDM_send. Will be removed once E2EE is universal.",
@@ -415,6 +454,8 @@ export const mdmTools: MosaddTool[] = [
415
454
  },
416
455
  {
417
456
  name: "mDM_list",
457
+ title: "Read direct messages",
458
+ annotations: { readOnlyHint: true },
418
459
  requires: "any",
419
460
  description:
420
461
  "List recent direct messages with a specific contact. Pass contact_id as the identity_id from mDM_list_contacts. Decrypts end-to-end-encrypted messages from the contact automatically; legacy plaintext messages are shown as-is. Optionally filter to a single thread_label.",
@@ -423,6 +464,8 @@ export const mdmTools: MosaddTool[] = [
423
464
  },
424
465
  {
425
466
  name: "mDM_respond_request",
467
+ title: "Accept or decline contact request",
468
+ annotations: { readOnlyHint: false },
426
469
  requires: "any",
427
470
  description:
428
471
  "Accept or reject an incoming DM request from a contact who is not yet in the user's whitelist.",
@@ -431,14 +474,18 @@ export const mdmTools: MosaddTool[] = [
431
474
  },
432
475
  {
433
476
  name: "mDM_edit",
477
+ title: "Edit a DM",
478
+ annotations: { destructiveHint: true },
434
479
  requires: "any",
435
480
  description:
436
- "Edit a direct message you sent — replace its body by message_id (from mDM_list). Stores a server-readable edited body; on an end-to-end-encrypted thread this does not re-encrypt, so for E2EE prefer deleting and re-sending.",
481
+ "Edit a direct message you sent — replace its body by message_id (pass the conversation's `to` so it can be located). NOTE: end-to-end-encrypted messages CANNOT be edited (the ratchet is forward-only) — mDM_edit refuses them and you should mDM_delete + mDM_send a replacement instead. Only legacy non-E2EE messages are editable.",
437
482
  inputSchema: mDM_edit_input,
438
483
  handler: mDM_edit as MosaddTool["handler"],
439
484
  },
440
485
  {
441
486
  name: "mDM_delete",
487
+ title: "Delete a DM",
488
+ annotations: { destructiveHint: true },
442
489
  requires: "any",
443
490
  description:
444
491
  "Delete a direct message you sent by message_id (from mDM_list). Soft-deletes server-side so it stops showing in mDM_list for both sides.",
@@ -1,190 +1,196 @@
1
- /**
2
- * mIRC edge — Cloudflare Worker + Durable Object backend (LINEAR-2675/2680).
3
- *
4
- * Parallel to mirc-messages.ts (Supabase path). These tools talk directly to
5
- * the mosadd-edge Worker → ChannelDO via REST. Use them when you want:
6
- * - sub-100ms global fan-out (DO broadcasts WS),
7
- * - to skip the Supabase write hot path (DO async-flushes to messages_meta
8
- * anyway, so the message still appears via the existing mIRC_list_messages
9
- * / message-list path),
10
- * - to scale to thousands of writers per channel without contention.
11
- *
12
- * Auth: a `mosadd_sk_live_…` hub API key (Bearer). Free plan = text is free
13
- * (the paid gates live where the paid product is). Set the edge URL via
14
- * MOSADD_EDGE_URL (defaults to the prod Worker).
15
- *
16
- * For native WebSocket subscription, MCP stdio is request/response — so live
17
- * fan-out isn't a fit for a stdio MCP server. Two paths exist for browsers /
18
- * external apps:
19
- *
20
- * - DEPRECATED, server-side only: `wss://${EDGE}/c/${channelId}/ws?k=<hub_key>`.
21
- * Don't use from a browser — `?k=` lands in CF access logs.
22
- * - RECOMMENDED (LINEAR-2675/E6): server calls `mIRC_mint_channel_token` to
23
- * exchange the hub key for a 5-min channel-scoped JWT, then the browser
24
- * opens the WS with `Sec-WebSocket-Protocol: mosadd.v1, bearer.<jwt>`.
25
- * The hub key never leaves the server. Recipe: `apps/edge/README.md`.
26
- */
27
-
28
- import { z } from "zod";
29
- import type { MosaddTool, MosaddToolContext } from "../types.js";
30
-
31
- const DEFAULT_EDGE_URL = "https://mosadd-edge.mr-brics-33.workers.dev";
32
- const DEFAULT_SUPABASE_URL = "https://rooffhgbxafyjcwmwpsy.supabase.co";
33
-
34
- function edgeUrl(): string {
35
- return process.env.MOSADD_EDGE_URL?.replace(/\/$/, "") ?? DEFAULT_EDGE_URL;
36
- }
37
-
38
- /** Where to call `hub-mint-channel-token`. Defaults to the prod Supabase project
39
- * but can be overridden with MOSADD_SUPABASE_URL for staging/self-host. */
40
- function supabaseUrl(): string {
41
- return (
42
- process.env.MOSADD_SUPABASE_URL?.replace(/\/$/, "") ??
43
- process.env.SUPABASE_URL?.replace(/\/$/, "") ??
44
- DEFAULT_SUPABASE_URL
45
- );
46
- }
47
-
48
- /** Resolve the hub key from env. Same convention as the rest of the toolkit:
49
- * MOSADD_API_KEY is the standard, with MOSADD_HUB_KEY as a friendly alias. */
50
- function hubKey(): string {
51
- const key = process.env.MOSADD_API_KEY ?? process.env.MOSADD_HUB_KEY ?? "";
52
- if (!key) throw new Error("MOSADD_API_KEY required for mIRC edge tools (see mosadd login or hub-keys).");
53
- return key;
54
- }
55
-
56
- // ── send_edge ────────────────────────────────────────────────────────────────
57
-
58
- const mIRC_send_edge_input = z.object({
59
- channel_id: z.string().min(1).max(128).describe("Channel id (UUID). Same as mIRC_create / mIRC_list."),
60
- text: z.string().min(1).max(64_000).describe("Message body (UTF-8, max 64 KB)."),
61
- from: z.string().max(120).optional().describe("Sender hint shown to other clients (defaults to the hub-key owner)."),
62
- });
63
-
64
- async function mIRC_send_edge(
65
- input: z.infer<typeof mIRC_send_edge_input>,
66
- ctx: MosaddToolContext,
67
- ): Promise<{ message_id: string; delivered_at: number; channel_id: string }> {
68
- ctx.log("debug", "mIRC_send_edge", { channel_id: input.channel_id });
69
- const r = await fetch(`${edgeUrl()}/c/${input.channel_id}/send`, {
70
- method: "POST",
71
- headers: {
72
- "Content-Type": "application/json",
73
- Authorization: `Bearer ${hubKey()}`,
74
- },
75
- body: JSON.stringify({ text: input.text, from: input.from }),
76
- });
77
- if (!r.ok) {
78
- const errBody = await r.text().catch(() => "");
79
- throw new Error(`mosadd-edge ${r.status}: ${errBody.slice(0, 200)}`);
80
- }
81
- const data = await r.json() as { id?: string; ts?: number };
82
- if (!data?.id) throw new Error("mosadd-edge: send returned no id");
83
- return { message_id: data.id, delivered_at: data.ts ?? Date.now(), channel_id: input.channel_id };
84
- }
85
-
86
- // ── history_edge ─────────────────────────────────────────────────────────────
87
-
88
- const mIRC_history_edge_input = z.object({
89
- channel_id: z.string().min(1).max(128).describe("Channel id (UUID)."),
90
- limit: z.number().int().min(1).max(100).default(50).optional()
91
- .describe("How many recent messages to return (max 100, the DO ring size)."),
92
- });
93
-
94
- async function mIRC_history_edge(
95
- input: z.infer<typeof mIRC_history_edge_input>,
96
- ctx: MosaddToolContext,
97
- ): Promise<{ messages: Array<{ id: string; from: string | null; text: string; timestamp: number }>; channel_id: string }> {
98
- const limit = input.limit ?? 50;
99
- ctx.log("debug", "mIRC_history_edge", { channel_id: input.channel_id, limit });
100
- const r = await fetch(`${edgeUrl()}/c/${input.channel_id}/history?limit=${limit}`, {
101
- headers: { Authorization: `Bearer ${hubKey()}` },
102
- });
103
- if (!r.ok) {
104
- const errBody = await r.text().catch(() => "");
105
- throw new Error(`mosadd-edge ${r.status}: ${errBody.slice(0, 200)}`);
106
- }
107
- const data = await r.json() as { messages?: Array<{ id: string; ts: number; from?: string | null; text: string }> };
108
- return {
109
- channel_id: input.channel_id,
110
- messages: (data.messages ?? []).map((m) => ({
111
- id: m.id,
112
- from: m.from ?? null,
113
- text: m.text,
114
- timestamp: m.ts,
115
- })),
116
- };
117
- }
118
-
119
- // ── mint_channel_token (LINEAR-2675/E6) ─────────────────────────────────────
120
- //
121
- // Server-side helper: exchange the long-lived hub key for a short-lived,
122
- // channel-scoped JWT that's safe to ship to a browser. The Worker validates
123
- // these via `Sec-WebSocket-Protocol`, so the hub key never leaves the server.
124
- // Typical use: a Next.js / Express `/api/chat-token` route calls this tool to
125
- // mint a token, returns it to the browser, browser opens the WS.
126
-
127
- const mIRC_mint_channel_token_input = z.object({
128
- channel_id: z.string().min(1).max(128)
129
- .describe("Channel id — the JWT will be scoped to this channel only. Must match the WS upgrade path."),
130
- user_id: z.string().min(1).max(120).optional()
131
- .describe("Optional end-user id. Stamped onto messages as 'from'. Useful when one hub key fronts many end-users (relay topology)."),
132
- });
133
-
134
- interface MintTokenResult {
135
- token: string;
136
- expires_in: number;
137
- channel_id: string;
138
- scope: string;
139
- }
140
-
141
- async function mIRC_mint_channel_token(
142
- input: z.infer<typeof mIRC_mint_channel_token_input>,
143
- ctx: MosaddToolContext,
144
- ): Promise<MintTokenResult> {
145
- ctx.log("debug", "mIRC_mint_channel_token", { channel_id: input.channel_id });
146
- const r = await fetch(`${supabaseUrl()}/functions/v1/hub-mint-channel-token`, {
147
- method: "POST",
148
- headers: {
149
- "Content-Type": "application/json",
150
- Authorization: `Bearer ${hubKey()}`,
151
- },
152
- body: JSON.stringify({ channel_id: input.channel_id, user_id: input.user_id }),
153
- });
154
- if (!r.ok) {
155
- const errBody = await r.text().catch(() => "");
156
- throw new Error(`hub-mint-channel-token ${r.status}: ${errBody.slice(0, 200)}`);
157
- }
158
- const data = await r.json() as Partial<MintTokenResult>;
159
- if (!data?.token || !data?.expires_in || !data?.channel_id || !data?.scope) {
160
- throw new Error("hub-mint-channel-token: malformed response");
161
- }
162
- return data as MintTokenResult;
163
- }
164
-
165
- export const mircEdgeTools: MosaddTool[] = [
166
- {
167
- name: "mIRC_mint_channel_token",
168
- requires: "network",
169
- description:
170
- "Exchange the hub key (MOSADD_API_KEY) for a short-lived (5min), channel-scoped JWT. Returns { token, expires_in, channel_id, scope }. The token is safe to hand to a browser to open a WS via `Sec-WebSocket-Protocol: mosadd.v1, bearer.<token>`. The hub key NEVER leaves the server. Use this from any server-side route (Next.js /api/chat-token, Express, etc.) before showing chat in a browser. Required by LINEAR-2675/E6 to avoid leaking the hub key into CDN access logs.",
171
- inputSchema: mIRC_mint_channel_token_input,
172
- handler: mIRC_mint_channel_token as MosaddTool["handler"],
173
- },
174
- {
175
- name: "mIRC_send_edge",
176
- requires: "network",
177
- description:
178
- "Send a text message into a persistent channel via the mosadd-edge Cloudflare Worker (Durable Object backend). Sub-100ms global fan-out to all WebSocket subscribers of the channel + async flush to Supabase as system-of-record (idempotent). Use this when you want native realtime push without polling. Parallel to mIRC_post_message (Supabase path); pick one per channel. Auth: MOSADD_API_KEY env (hub key).",
179
- inputSchema: mIRC_send_edge_input,
180
- handler: mIRC_send_edge as MosaddTool["handler"],
181
- },
182
- {
183
- name: "mIRC_history_edge",
184
- requires: "network",
185
- description:
186
- "Read the last N (max 100) messages held in the channel's Durable Object ring buffer at the edge. Hot path is the DO, not Supabase — same data lands in messages_meta via async flush, so cold reads / pagination beyond 100 should use mIRC_list_messages.",
187
- inputSchema: mIRC_history_edge_input,
188
- handler: mIRC_history_edge as MosaddTool["handler"],
189
- },
190
- ];
1
+ /**
2
+ * mIRC edge — Cloudflare Worker + Durable Object backend (LINEAR-2675/2680).
3
+ *
4
+ * Parallel to mirc-messages.ts (Supabase path). These tools talk directly to
5
+ * the mosadd-edge Worker → ChannelDO via REST. Use them when you want:
6
+ * - sub-100ms global fan-out (DO broadcasts WS),
7
+ * - to skip the Supabase write hot path (DO async-flushes to messages_meta
8
+ * anyway, so the message still appears via the existing mIRC_list_messages
9
+ * / message-list path),
10
+ * - to scale to thousands of writers per channel without contention.
11
+ *
12
+ * Auth: a `mosadd_sk_live_…` hub API key (Bearer). Free plan = text is free
13
+ * (the paid gates live where the paid product is). Set the edge URL via
14
+ * MOSADD_EDGE_URL (defaults to the prod Worker).
15
+ *
16
+ * For native WebSocket subscription, MCP stdio is request/response — so live
17
+ * fan-out isn't a fit for a stdio MCP server. Two paths exist for browsers /
18
+ * external apps:
19
+ *
20
+ * - DEPRECATED, server-side only: `wss://${EDGE}/c/${channelId}/ws?k=<hub_key>`.
21
+ * Don't use from a browser — `?k=` lands in CF access logs.
22
+ * - RECOMMENDED (LINEAR-2675/E6): server calls `mIRC_mint_channel_token` to
23
+ * exchange the hub key for a 5-min channel-scoped JWT, then the browser
24
+ * opens the WS with `Sec-WebSocket-Protocol: mosadd.v1, bearer.<jwt>`.
25
+ * The hub key never leaves the server. Recipe: `apps/edge/README.md`.
26
+ */
27
+
28
+ import { z } from "zod";
29
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
30
+
31
+ const DEFAULT_EDGE_URL = "https://mosadd-edge.mr-brics-33.workers.dev";
32
+ const DEFAULT_SUPABASE_URL = "https://rooffhgbxafyjcwmwpsy.supabase.co";
33
+
34
+ function edgeUrl(): string {
35
+ return process.env.MOSADD_EDGE_URL?.replace(/\/$/, "") ?? DEFAULT_EDGE_URL;
36
+ }
37
+
38
+ /** Where to call `hub-mint-channel-token`. Defaults to the prod Supabase project
39
+ * but can be overridden with MOSADD_SUPABASE_URL for staging/self-host. */
40
+ function supabaseUrl(): string {
41
+ return (
42
+ process.env.MOSADD_SUPABASE_URL?.replace(/\/$/, "") ??
43
+ process.env.SUPABASE_URL?.replace(/\/$/, "") ??
44
+ DEFAULT_SUPABASE_URL
45
+ );
46
+ }
47
+
48
+ /** Resolve the hub key from env. Same convention as the rest of the toolkit:
49
+ * MOSADD_API_KEY is the standard, with MOSADD_HUB_KEY as a friendly alias. */
50
+ function hubKey(): string {
51
+ const key = process.env.MOSADD_API_KEY ?? process.env.MOSADD_HUB_KEY ?? "";
52
+ if (!key) throw new Error("MOSADD_API_KEY required for mIRC edge tools (see mosadd login or hub-keys).");
53
+ return key;
54
+ }
55
+
56
+ // ── send_edge ────────────────────────────────────────────────────────────────
57
+
58
+ const mIRC_send_edge_input = z.object({
59
+ channel_id: z.string().min(1).max(128).describe("Channel id (UUID). Same as mIRC_create / mIRC_list."),
60
+ text: z.string().min(1).max(64_000).describe("Message body (UTF-8, max 64 KB)."),
61
+ from: z.string().max(120).optional().describe("Sender hint shown to other clients (defaults to the hub-key owner)."),
62
+ });
63
+
64
+ async function mIRC_send_edge(
65
+ input: z.infer<typeof mIRC_send_edge_input>,
66
+ ctx: MosaddToolContext,
67
+ ): Promise<{ message_id: string; delivered_at: number; channel_id: string }> {
68
+ ctx.log("debug", "mIRC_send_edge", { channel_id: input.channel_id });
69
+ const r = await fetch(`${edgeUrl()}/c/${input.channel_id}/send`, {
70
+ method: "POST",
71
+ headers: {
72
+ "Content-Type": "application/json",
73
+ Authorization: `Bearer ${hubKey()}`,
74
+ },
75
+ body: JSON.stringify({ text: input.text, from: input.from }),
76
+ });
77
+ if (!r.ok) {
78
+ const errBody = await r.text().catch(() => "");
79
+ throw new Error(`mosadd-edge ${r.status}: ${errBody.slice(0, 200)}`);
80
+ }
81
+ const data = await r.json() as { id?: string; ts?: number };
82
+ if (!data?.id) throw new Error("mosadd-edge: send returned no id");
83
+ return { message_id: data.id, delivered_at: data.ts ?? Date.now(), channel_id: input.channel_id };
84
+ }
85
+
86
+ // ── history_edge ─────────────────────────────────────────────────────────────
87
+
88
+ const mIRC_history_edge_input = z.object({
89
+ channel_id: z.string().min(1).max(128).describe("Channel id (UUID)."),
90
+ limit: z.number().int().min(1).max(100).default(50).optional()
91
+ .describe("How many recent messages to return (max 100, the DO ring size)."),
92
+ });
93
+
94
+ async function mIRC_history_edge(
95
+ input: z.infer<typeof mIRC_history_edge_input>,
96
+ ctx: MosaddToolContext,
97
+ ): Promise<{ messages: Array<{ id: string; from: string | null; text: string; timestamp: number }>; channel_id: string }> {
98
+ const limit = input.limit ?? 50;
99
+ ctx.log("debug", "mIRC_history_edge", { channel_id: input.channel_id, limit });
100
+ const r = await fetch(`${edgeUrl()}/c/${input.channel_id}/history?limit=${limit}`, {
101
+ headers: { Authorization: `Bearer ${hubKey()}` },
102
+ });
103
+ if (!r.ok) {
104
+ const errBody = await r.text().catch(() => "");
105
+ throw new Error(`mosadd-edge ${r.status}: ${errBody.slice(0, 200)}`);
106
+ }
107
+ const data = await r.json() as { messages?: Array<{ id: string; ts: number; from?: string | null; text: string }> };
108
+ return {
109
+ channel_id: input.channel_id,
110
+ messages: (data.messages ?? []).map((m) => ({
111
+ id: m.id,
112
+ from: m.from ?? null,
113
+ text: m.text,
114
+ timestamp: m.ts,
115
+ })),
116
+ };
117
+ }
118
+
119
+ // ── mint_channel_token (LINEAR-2675/E6) ─────────────────────────────────────
120
+ //
121
+ // Server-side helper: exchange the long-lived hub key for a short-lived,
122
+ // channel-scoped JWT that's safe to ship to a browser. The Worker validates
123
+ // these via `Sec-WebSocket-Protocol`, so the hub key never leaves the server.
124
+ // Typical use: a Next.js / Express `/api/chat-token` route calls this tool to
125
+ // mint a token, returns it to the browser, browser opens the WS.
126
+
127
+ const mIRC_mint_channel_token_input = z.object({
128
+ channel_id: z.string().min(1).max(128)
129
+ .describe("Channel id — the JWT will be scoped to this channel only. Must match the WS upgrade path."),
130
+ user_id: z.string().min(1).max(120).optional()
131
+ .describe("Optional end-user id. Stamped onto messages as 'from'. Useful when one hub key fronts many end-users (relay topology)."),
132
+ });
133
+
134
+ interface MintTokenResult {
135
+ token: string;
136
+ expires_in: number;
137
+ channel_id: string;
138
+ scope: string;
139
+ }
140
+
141
+ async function mIRC_mint_channel_token(
142
+ input: z.infer<typeof mIRC_mint_channel_token_input>,
143
+ ctx: MosaddToolContext,
144
+ ): Promise<MintTokenResult> {
145
+ ctx.log("debug", "mIRC_mint_channel_token", { channel_id: input.channel_id });
146
+ const r = await fetch(`${supabaseUrl()}/functions/v1/hub-mint-channel-token`, {
147
+ method: "POST",
148
+ headers: {
149
+ "Content-Type": "application/json",
150
+ Authorization: `Bearer ${hubKey()}`,
151
+ },
152
+ body: JSON.stringify({ channel_id: input.channel_id, user_id: input.user_id }),
153
+ });
154
+ if (!r.ok) {
155
+ const errBody = await r.text().catch(() => "");
156
+ throw new Error(`hub-mint-channel-token ${r.status}: ${errBody.slice(0, 200)}`);
157
+ }
158
+ const data = await r.json() as Partial<MintTokenResult>;
159
+ if (!data?.token || !data?.expires_in || !data?.channel_id || !data?.scope) {
160
+ throw new Error("hub-mint-channel-token: malformed response");
161
+ }
162
+ return data as MintTokenResult;
163
+ }
164
+
165
+ export const mircEdgeTools: MosaddTool[] = [
166
+ {
167
+ name: "mIRC_mint_channel_token",
168
+ title: "Mint channel token",
169
+ annotations: { readOnlyHint: false },
170
+ requires: "network",
171
+ description:
172
+ "Exchange the hub key (MOSADD_API_KEY) for a short-lived (5min), channel-scoped JWT. Returns { token, expires_in, channel_id, scope }. The token is safe to hand to a browser to open a WS via `Sec-WebSocket-Protocol: mosadd.v1, bearer.<token>`. The hub key NEVER leaves the server. Use this from any server-side route (Next.js /api/chat-token, Express, etc.) before showing chat in a browser. Required by LINEAR-2675/E6 to avoid leaking the hub key into CDN access logs.",
173
+ inputSchema: mIRC_mint_channel_token_input,
174
+ handler: mIRC_mint_channel_token as MosaddTool["handler"],
175
+ },
176
+ {
177
+ name: "mIRC_send_edge",
178
+ title: "Send message (low-latency edge)",
179
+ annotations: { readOnlyHint: false },
180
+ requires: "network",
181
+ description:
182
+ "Send a text message into a persistent channel via the mosadd-edge Cloudflare Worker (Durable Object backend). Sub-100ms global fan-out to all WebSocket subscribers of the channel + async flush to Supabase as system-of-record (idempotent). Use this when you want native realtime push without polling. Parallel to mIRC_post_message (Supabase path); pick one per channel. Auth: MOSADD_API_KEY env (hub key).",
183
+ inputSchema: mIRC_send_edge_input,
184
+ handler: mIRC_send_edge as MosaddTool["handler"],
185
+ },
186
+ {
187
+ name: "mIRC_history_edge",
188
+ title: "Read channel history (edge)",
189
+ annotations: { readOnlyHint: true },
190
+ requires: "network",
191
+ description:
192
+ "Read the last N (max 100) messages held in the channel's Durable Object ring buffer at the edge. Hot path is the DO, not Supabase — same data lands in messages_meta via async flush, so cold reads / pagination beyond 100 should use mIRC_list_messages.",
193
+ inputSchema: mIRC_history_edge_input,
194
+ handler: mIRC_history_edge as MosaddTool["handler"],
195
+ },
196
+ ];