@mosadd/mcp 3.0.0-alpha.4 → 3.0.0-alpha.41

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 (57) hide show
  1. package/CHANGELOG.md +298 -0
  2. package/README.md +70 -36
  3. package/dist/bin/mcp.js +42 -3
  4. package/dist/chunk-SS6UVKSB.js +3513 -0
  5. package/dist/index.d.ts +115 -6
  6. package/dist/index.js +7 -3
  7. package/package.json +8 -5
  8. package/src/__tests__/golden-path.test.ts +139 -137
  9. package/src/__tests__/integration.test.ts +179 -178
  10. package/src/__tests__/knowledge-ingest.test.ts +114 -0
  11. package/src/__tests__/mdm-e2ee.test.ts +212 -178
  12. package/src/__tests__/mtalk.test.ts +122 -122
  13. package/src/__tests__/presence.test.ts +178 -0
  14. package/src/__tests__/server.test.ts +71 -67
  15. package/src/__tests__/tool-count-consistency.test.ts +164 -0
  16. package/src/bin/login.ts +138 -138
  17. package/src/bin/mcp.ts +145 -97
  18. package/src/config.ts +66 -66
  19. package/src/crypto/mdm-session.ts +502 -403
  20. package/src/index.ts +19 -17
  21. package/src/observability/sentry.ts +79 -79
  22. package/src/providers/blob-upload.ts +116 -0
  23. package/src/providers/memory-voice.ts +79 -79
  24. package/src/providers/supabase-dm.ts +122 -117
  25. package/src/providers/supabase-voice.ts +91 -91
  26. package/src/providers/supabase.ts +155 -96
  27. package/src/server.ts +66 -9
  28. package/src/tools/actions.ts +166 -0
  29. package/src/tools/attachments.ts +276 -0
  30. package/src/tools/capabilities.ts +70 -68
  31. package/src/tools/embed.ts +110 -0
  32. package/src/tools/index.ts +177 -43
  33. package/src/tools/knowledge-graph.ts +186 -0
  34. package/src/tools/knowledge.ts +327 -91
  35. package/src/tools/mail-agentbox.ts +155 -0
  36. package/src/tools/mail-aliases.ts +25 -0
  37. package/src/tools/mail-provenance.ts +137 -0
  38. package/src/tools/mail.ts +403 -89
  39. package/src/tools/mcall.ts +216 -0
  40. package/src/tools/mdm-as-agent.ts +126 -0
  41. package/src/tools/mdm-voice.ts +220 -0
  42. package/src/tools/mdm.ts +494 -392
  43. package/src/tools/mirc-edge.ts +196 -0
  44. package/src/tools/mirc-members.ts +61 -20
  45. package/src/tools/mirc-messages.ts +185 -151
  46. package/src/tools/mirc.ts +104 -10
  47. package/src/tools/mroom-messages.ts +142 -142
  48. package/src/tools/mroom.ts +221 -189
  49. package/src/tools/mtalk.ts +131 -121
  50. package/src/tools/murl.ts +314 -0
  51. package/src/tools/presence.ts +399 -0
  52. package/src/tools/ptt-ingest.ts +99 -0
  53. package/src/tools/threat.ts +123 -0
  54. package/src/types.ts +121 -85
  55. package/src/version.ts +8 -0
  56. package/src/voice/floor.ts +132 -132
  57. package/dist/chunk-YDFU6S5E.js +0 -1471
@@ -1,1471 +0,0 @@
1
- import {
2
- isSessionExpired,
3
- loadSession
4
- } from "./chunk-Z7WR52GE.js";
5
-
6
- // src/tools/mdm.ts
7
- import { z } from "zod";
8
-
9
- // src/providers/supabase.ts
10
- import { createClient } from "@supabase/supabase-js";
11
- var MissingSupabaseEnvError = class extends Error {
12
- constructor(missing) {
13
- super(
14
- `Missing Supabase credentials: ${missing.join(", ")}. Run \`mosadd login\`, or set MOSADD_SUPABASE_URL, MOSADD_SUPABASE_ANON_KEY and MOSADD_USER_JWT.`
15
- );
16
- this.name = "MissingSupabaseEnvError";
17
- }
18
- };
19
- function readSupabaseEnv() {
20
- const env = (canonical, legacy) => process.env[canonical] ?? process.env[legacy];
21
- const userJwtEnv = env("MOSADD_USER_JWT", "M0SSAD_USER_JWT");
22
- const session = loadSession();
23
- const url = env("MOSADD_SUPABASE_URL", "M0SSAD_SUPABASE_URL") ?? session?.url;
24
- const anonKey = env("MOSADD_SUPABASE_ANON_KEY", "M0SSAD_SUPABASE_ANON_KEY") ?? session?.anonKey;
25
- const userJwt = userJwtEnv ?? session?.accessToken;
26
- const missing = [];
27
- if (!url) missing.push("MOSADD_SUPABASE_URL");
28
- if (!anonKey) missing.push("MOSADD_SUPABASE_ANON_KEY");
29
- if (missing.length) throw new MissingSupabaseEnvError(missing);
30
- if (!userJwtEnv && session && isSessionExpired(session)) {
31
- throw new Error("Your mosadd session has expired. Run `mosadd login` again to refresh it.");
32
- }
33
- return { url, anonKey, userJwt };
34
- }
35
- function getSupabase(env = readSupabaseEnv()) {
36
- return createClient(env.url, env.anonKey, {
37
- auth: {
38
- persistSession: false,
39
- autoRefreshToken: false,
40
- detectSessionInUrl: false
41
- },
42
- global: env.userJwt ? {
43
- headers: { Authorization: `Bearer ${env.userJwt}` }
44
- } : void 0
45
- });
46
- }
47
- async function invokeFunction(fn, body) {
48
- const client = getSupabase();
49
- const { data, error } = await client.functions.invoke(fn, { body });
50
- if (error) {
51
- const msg = error instanceof Error ? error.message : typeof error?.message === "string" ? error.message : `Edge function ${fn} failed`;
52
- throw new Error(msg);
53
- }
54
- if (data == null) {
55
- throw new Error(`Edge function ${fn} returned no data`);
56
- }
57
- return data;
58
- }
59
-
60
- // src/crypto/mdm-session.ts
61
- import {
62
- decryptBytes,
63
- encryptBytes,
64
- generateEd25519KeyPair,
65
- generateX25519KeyPair,
66
- initializeRatchet,
67
- performX3dh,
68
- performX3dhResponder,
69
- ratchetReceive,
70
- ratchetSend,
71
- signEd25519,
72
- verifyEd25519,
73
- toBase64,
74
- fromBase64
75
- } from "@mosadd/crypto";
76
- var PREKEY_BUNDLE_VERSION = "mosadd.prekeys.v1";
77
- var E2EE_ENVELOPE_VERSION = "mosadd.e2ee.v1";
78
- var DEFAULT_ONE_TIME_PREKEYS = 8;
79
- var InMemoryMdmKeyStore = class {
80
- material = null;
81
- oneTimeById = /* @__PURE__ */ new Map();
82
- sessions = /* @__PURE__ */ new Map();
83
- sentMessages = /* @__PURE__ */ new Map();
84
- async getOwnMaterial() {
85
- if (this.material) return this.material;
86
- const identity = await generateX25519KeyPair();
87
- const signingIdentity = await generateEd25519KeyPair();
88
- const signedPrekeyPair = await generateX25519KeyPair();
89
- const signedPrekey = { id: randomId(), pair: signedPrekeyPair };
90
- const oneTimePrekeys = [];
91
- for (let i = 0; i < DEFAULT_ONE_TIME_PREKEYS; i += 1) {
92
- const pair = await generateX25519KeyPair();
93
- const id = randomId();
94
- oneTimePrekeys.push({ id, pair });
95
- this.oneTimeById.set(id, pair.privateKey);
96
- }
97
- this.material = { identity, signingIdentity, signedPrekey, oneTimePrekeys };
98
- return this.material;
99
- }
100
- async takeOneTimePrekey(id) {
101
- const priv = this.oneTimeById.get(id);
102
- if (priv) this.oneTimeById.delete(id);
103
- return priv;
104
- }
105
- async getSession(peerId) {
106
- return this.sessions.get(peerId);
107
- }
108
- async putSession(peerId, record) {
109
- this.sessions.set(peerId, record);
110
- }
111
- async putSentMessage(messageId, plaintext) {
112
- this.sentMessages.set(messageId, plaintext);
113
- }
114
- async getSentMessage(messageId) {
115
- return this.sentMessages.get(messageId);
116
- }
117
- };
118
- function randomId() {
119
- return crypto.getRandomValues(new Uint32Array(1))[0];
120
- }
121
- function bundleSigningMessage(dhIdentityPub, signedPrekeyPub) {
122
- const msg = new Uint8Array(dhIdentityPub.length + signedPrekeyPub.length);
123
- msg.set(dhIdentityPub, 0);
124
- msg.set(signedPrekeyPub, dhIdentityPub.length);
125
- return msg;
126
- }
127
- function serializePublicBundle(material) {
128
- const signature = signEd25519(
129
- material.signingIdentity.privateKey,
130
- bundleSigningMessage(material.identity.publicKey, material.signedPrekey.pair.publicKey)
131
- );
132
- const json = JSON.stringify({
133
- v: PREKEY_BUNDLE_VERSION,
134
- ik: toBase64(material.identity.publicKey),
135
- sik: toBase64(material.signingIdentity.publicKey),
136
- spk: { id: material.signedPrekey.id, pub: toBase64(material.signedPrekey.pair.publicKey) },
137
- opks: material.oneTimePrekeys.map((k) => ({ id: k.id, pub: toBase64(k.pair.publicKey) })),
138
- sig: toBase64(signature)
139
- });
140
- return new Uint8Array(Buffer.from(json, "utf8"));
141
- }
142
- function parsePublicBundle(bytes) {
143
- const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
144
- if (obj?.v !== PREKEY_BUNDLE_VERSION) {
145
- throw new Error(`Unsupported prekey bundle version: ${obj?.v}`);
146
- }
147
- if (typeof obj.sik !== "string" || typeof obj.sig !== "string") {
148
- throw new Error("Prekey bundle is missing its signing identity / signature.");
149
- }
150
- return {
151
- identityPublicKey: fromBase64(obj.ik),
152
- signingIdentityPublicKey: fromBase64(obj.sik),
153
- signedPrekey: { id: obj.spk.id, publicKey: fromBase64(obj.spk.pub) },
154
- oneTimePrekeys: (obj.opks ?? []).map((k) => ({
155
- id: k.id,
156
- publicKey: fromBase64(k.pub)
157
- })),
158
- signature: fromBase64(obj.sig)
159
- };
160
- }
161
- function verifyPublicBundle(bundle) {
162
- return verifyEd25519(
163
- bundle.signature,
164
- bundleSigningMessage(bundle.identityPublicKey, bundle.signedPrekey.publicKey),
165
- bundle.signingIdentityPublicKey
166
- );
167
- }
168
- function isE2eeEnvelope(bytes) {
169
- try {
170
- const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
171
- return obj?.v === E2EE_ENVELOPE_VERSION && typeof obj?.i === "number" && !!obj?.ct;
172
- } catch {
173
- return false;
174
- }
175
- }
176
- function serializeEnvelope(env) {
177
- return new Uint8Array(Buffer.from(JSON.stringify(env), "utf8"));
178
- }
179
- function parseEnvelope(bytes) {
180
- const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
181
- if (obj?.v !== E2EE_ENVELOPE_VERSION) throw new Error(`Unsupported mDM envelope version: ${obj?.v}`);
182
- return obj;
183
- }
184
- async function publishOwnPrekeys(keystore, dm) {
185
- const material = await keystore.getOwnMaterial();
186
- await dm.publishPrekeyBundle(serializePublicBundle(material));
187
- return { oneTimePrekeyCount: material.oneTimePrekeys.length };
188
- }
189
- async function encryptForPeer(keystore, dm, peerId, plaintext) {
190
- let session = await keystore.getSession(peerId);
191
- if (!session) {
192
- const raw = await dm.fetchPrekeyBundle(peerId);
193
- if (!raw) {
194
- throw new Error(
195
- `Peer "${peerId}" has not published a prekey bundle yet, so an encrypted session cannot be established. Ask them to run mDM_publish_keys, or use mDM_send_unencrypted (deprecated) for the migration window.`
196
- );
197
- }
198
- const peer = parsePublicBundle(raw);
199
- if (!verifyPublicBundle(peer)) {
200
- throw new Error(
201
- `Prekey bundle for "${peerId}" failed signature verification \u2014 refusing to start an encrypted session (possible tampering / man-in-the-middle).`
202
- );
203
- }
204
- const own = await keystore.getOwnMaterial();
205
- const ephemeral = await generateX25519KeyPair();
206
- const opk = peer.oneTimePrekeys[0];
207
- const { rootKey } = await performX3dh(own.identity.privateKey, ephemeral.privateKey, {
208
- identityPublicKey: peer.identityPublicKey,
209
- signedPreKeyPublicKey: peer.signedPrekey.publicKey,
210
- oneTimePreKeyPublicKey: opk?.publicKey
211
- });
212
- const ratchet = await initializeRatchet(rootKey, "initiator");
213
- session = {
214
- ratchet,
215
- role: "initiator",
216
- pendingHandshake: { ik: own.identity.publicKey, ek: ephemeral.publicKey, opkId: opk?.id }
217
- };
218
- }
219
- const step = await ratchetSend(session.ratchet);
220
- const ct = await encryptBytes(step.messageKey, plaintext);
221
- const env = { v: E2EE_ENVELOPE_VERSION, i: step.messageIndex, ct };
222
- if (session.pendingHandshake && step.messageIndex === 0) {
223
- env.hdr = {
224
- ik: toBase64(session.pendingHandshake.ik),
225
- ek: toBase64(session.pendingHandshake.ek),
226
- opk: session.pendingHandshake.opkId
227
- };
228
- }
229
- session.pendingHandshake = void 0;
230
- await keystore.putSession(peerId, session);
231
- return serializeEnvelope(env);
232
- }
233
- async function decryptFromPeer(keystore, peerId, envelopeBytes) {
234
- const env = parseEnvelope(envelopeBytes);
235
- let session = await keystore.getSession(peerId);
236
- if (!session) {
237
- if (!env.hdr) {
238
- throw new Error(
239
- `No session with "${peerId}" and the message carries no handshake header \u2014 cannot decrypt.`
240
- );
241
- }
242
- const own = await keystore.getOwnMaterial();
243
- let oneTimePreKeyPrivateKey;
244
- if (env.hdr.opk !== void 0) {
245
- oneTimePreKeyPrivateKey = await keystore.takeOneTimePrekey(env.hdr.opk);
246
- if (!oneTimePreKeyPrivateKey) {
247
- throw new Error(
248
- `Handshake references one-time prekey ${env.hdr.opk} which is unknown or already consumed.`
249
- );
250
- }
251
- }
252
- const { rootKey } = await performX3dhResponder(
253
- {
254
- identityPrivateKey: own.identity.privateKey,
255
- signedPreKeyPrivateKey: own.signedPrekey.pair.privateKey,
256
- oneTimePreKeyPrivateKey
257
- },
258
- {
259
- initiatorIdentityPublicKey: fromBase64(env.hdr.ik),
260
- initiatorEphemeralPublicKey: fromBase64(env.hdr.ek),
261
- usedOneTimePreKeyId: env.hdr.opk
262
- }
263
- );
264
- const ratchet = await initializeRatchet(rootKey, "responder");
265
- session = { ratchet, role: "responder" };
266
- }
267
- const step = await ratchetReceive(session.ratchet);
268
- if (step.messageIndex !== env.i) {
269
- throw new Error(
270
- `Out-of-order mDM message (expected ratchet index ${step.messageIndex}, got ${env.i}). Skipped-key handling is a tracked follow-up (LINEAR-2357).`
271
- );
272
- }
273
- const plaintext = await decryptBytes(step.messageKey, env.ct);
274
- await keystore.putSession(peerId, session);
275
- return plaintext;
276
- }
277
-
278
- // src/tools/mdm.ts
279
- var PROTOCOL_VERSION = "mosadd.chat.v1";
280
- var ContactRef = z.string().min(1).describe(
281
- "Recipient identity id (UUID). Use mDM_list_contacts first to find the right id. Future versions will accept handle/email/phone directly."
282
- );
283
- var ThreadSuffix = z.string().min(1).max(120).regex(/^[a-zA-Z0-9._-]+$/).describe(
284
- "Optional thread label within the conversation with this contact. Defaults to the contact's main thread. mosadd USP: multiple threads per contact."
285
- );
286
- var mDM_send_input = z.object({
287
- to: ContactRef,
288
- text: z.string().min(1).max(64e3).describe("Message body (UTF-8). Max 64 KB."),
289
- thread_label: ThreadSuffix.optional().describe(
290
- "Optional thread label. If omitted, uses the default thread for this contact."
291
- ),
292
- reply_to_id: z.string().optional().describe("Optional id of the message being replied to.")
293
- });
294
- var mDM_list_input = z.object({
295
- contact_id: ContactRef.describe("Identity id of the contact to read messages with."),
296
- thread_label: ThreadSuffix.optional(),
297
- limit: z.number().int().min(1).max(200).default(50).optional(),
298
- cursor: z.string().optional().describe("Opaque pagination cursor from a previous response.")
299
- });
300
- var mDM_list_contacts_input = z.object({
301
- limit: z.number().int().min(1).max(500).default(100).optional()
302
- });
303
- var mDM_respond_request_input = z.object({
304
- request_id: z.string().min(1),
305
- action: z.enum(["accept", "reject"])
306
- });
307
- function dmThreadId(selfId, otherId, label) {
308
- const [a, b] = [selfId, otherId].sort();
309
- return label ? `dm:${a}:${b}:${label}` : `dm:${a}:${b}`;
310
- }
311
- async function resolveSelfIdentityId() {
312
- const sb = getSupabase();
313
- const { data: u, error: ue } = await sb.auth.getUser();
314
- if (ue || !u?.user) {
315
- throw new Error(
316
- "Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token."
317
- );
318
- }
319
- const { data: identity, error } = await sb.from("identities").select("id").eq("user_id", u.user.id).maybeSingle();
320
- if (error || !identity) {
321
- throw new Error("Current user has no mosadd identity row. Sign in to mosadd.com first.");
322
- }
323
- return identity.id;
324
- }
325
- function packPlaintextPayload(text, replyToId) {
326
- const envelope = {
327
- v: PROTOCOL_VERSION,
328
- type: "text",
329
- text,
330
- reply_to: replyToId ?? null,
331
- sent_at: (/* @__PURE__ */ new Date()).toISOString()
332
- };
333
- return new Uint8Array(Buffer.from(JSON.stringify(envelope), "utf8"));
334
- }
335
- function unpackPayload(payload) {
336
- try {
337
- const json = Buffer.from(payload).toString("utf8");
338
- const obj = JSON.parse(json);
339
- if (typeof obj?.text === "string") return obj;
340
- } catch {
341
- }
342
- return { text: "<ciphertext>" };
343
- }
344
- async function mDM_send(input, ctx) {
345
- const dm = ctx.providers.dm;
346
- const selfId = await dm.selfId();
347
- const threadId = dmThreadId(selfId, input.to, input.thread_label);
348
- const inner = packPlaintextPayload(input.text, input.reply_to_id);
349
- const sealed = await encryptForPeer(ctx.providers.keys, dm, input.to, inner);
350
- ctx.log("debug", "mDM_send E2EE via DmProvider", { thread_id: threadId, bytes: sealed.byteLength });
351
- const result = await dm.send({
352
- to: input.to,
353
- threadId,
354
- payload: sealed,
355
- replyToId: input.reply_to_id
356
- });
357
- if (ctx.providers.keys.putSentMessage) {
358
- await ctx.providers.keys.putSentMessage(result.id, inner);
359
- }
360
- return {
361
- message_id: result.id,
362
- delivered_at: result.deliveredAt,
363
- thread_id: threadId,
364
- encrypted: true
365
- };
366
- }
367
- async function mDM_send_unencrypted(input, ctx) {
368
- const dm = ctx.providers.dm;
369
- const selfId = await dm.selfId();
370
- const threadId = dmThreadId(selfId, input.to, input.thread_label);
371
- const payload = packPlaintextPayload(input.text, input.reply_to_id);
372
- ctx.log("warn", "mDM_send_unencrypted (deprecated, plaintext) via DmProvider", {
373
- thread_id: threadId,
374
- bytes: payload.byteLength
375
- });
376
- const result = await dm.send({
377
- to: input.to,
378
- threadId,
379
- payload,
380
- replyToId: input.reply_to_id
381
- });
382
- return {
383
- message_id: result.id,
384
- delivered_at: result.deliveredAt,
385
- thread_id: threadId,
386
- encrypted: false
387
- };
388
- }
389
- async function mDM_publish_keys(_input, ctx) {
390
- const { oneTimePrekeyCount } = await publishOwnPrekeys(ctx.providers.keys, ctx.providers.dm);
391
- ctx.log("debug", "mDM_publish_keys", { one_time_prekeys: oneTimePrekeyCount });
392
- return { published: true, one_time_prekeys: oneTimePrekeyCount };
393
- }
394
- async function mDM_list(input, ctx) {
395
- const dm = ctx.providers.dm;
396
- const selfId = await dm.selfId();
397
- const threadId = dmThreadId(selfId, input.contact_id, input.thread_label);
398
- ctx.log("debug", "mDM_list via DmProvider", { thread_id: threadId });
399
- const result = await dm.list({ threadId, limit: input.limit ?? 50, cursor: input.cursor });
400
- const messages = await Promise.all(
401
- result.messages.map(async (m) => {
402
- const base = {
403
- id: m.id,
404
- sender_identity_id: m.senderId,
405
- timestamp: m.timestamp,
406
- thread_id: m.threadId
407
- };
408
- if (!isE2eeEnvelope(m.payload)) {
409
- return { ...base, text: unpackPayload(m.payload).text, encrypted: false };
410
- }
411
- if (m.senderId === selfId) {
412
- const cached = await ctx.providers.keys.getSentMessage?.(m.id);
413
- if (cached) {
414
- return { ...base, text: unpackPayload(cached).text, encrypted: true };
415
- }
416
- return { ...base, text: "<encrypted \xB7 sent by you>", encrypted: true };
417
- }
418
- try {
419
- const inner = await decryptFromPeer(ctx.providers.keys, m.senderId, m.payload);
420
- return { ...base, text: unpackPayload(inner).text, encrypted: true };
421
- } catch (err) {
422
- ctx.log("warn", "mDM_list failed to decrypt a message", { id: m.id, error: String(err) });
423
- return { ...base, text: "<undecryptable>", encrypted: true };
424
- }
425
- })
426
- );
427
- return {
428
- messages,
429
- next_cursor: result.nextCursor,
430
- threads: [threadId]
431
- };
432
- }
433
- async function mDM_list_contacts(input, ctx) {
434
- readSupabaseEnv();
435
- const selfId = await resolveSelfIdentityId();
436
- const sb = getSupabase();
437
- ctx.log("debug", "mDM_list_contacts querying contacts table", { selfId });
438
- const { data, error } = await sb.from("contacts").select("contact_identity_id, state, identities:contact_identity_id(account_id, display_name)").eq("owner_identity_id", selfId).limit(input.limit ?? 100);
439
- if (error) {
440
- throw new Error(`Failed to list contacts: ${error.message}`);
441
- }
442
- const contacts = data.map((r) => ({
443
- identity_id: r.contact_identity_id,
444
- account_id: r.identities?.account_id ?? null,
445
- display_name: r.identities?.display_name ?? null,
446
- state: r.state
447
- }));
448
- return { contacts };
449
- }
450
- async function mDM_respond_request(input, ctx) {
451
- readSupabaseEnv();
452
- ctx.log("debug", "mDM_respond_request invoking message-request-respond", input);
453
- await invokeFunction("message-request-respond", {
454
- request_id: input.request_id,
455
- action: input.action
456
- });
457
- return { ok: true };
458
- }
459
- var mDM_publish_keys_input = z.object({});
460
- var mdmTools = [
461
- {
462
- name: "mDM_list_contacts",
463
- requires: "any",
464
- description: "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).",
465
- inputSchema: mDM_list_contacts_input,
466
- handler: mDM_list_contacts
467
- },
468
- {
469
- name: "mDM_publish_keys",
470
- requires: "any",
471
- description: "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.",
472
- inputSchema: mDM_publish_keys_input,
473
- handler: mDM_publish_keys
474
- },
475
- {
476
- name: "mDM_send",
477
- requires: "any",
478
- description: "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 \u2014 mosadd USP: multiple threads per contact, unlike WhatsApp/Telegram. If the recipient has no published keys yet, use mDM_send_unencrypted.",
479
- inputSchema: mDM_send_input,
480
- handler: mDM_send
481
- },
482
- {
483
- name: "mDM_send_unencrypted",
484
- requires: "any",
485
- description: "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.",
486
- inputSchema: mDM_send_input,
487
- handler: mDM_send_unencrypted
488
- },
489
- {
490
- name: "mDM_list",
491
- requires: "any",
492
- description: "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.",
493
- inputSchema: mDM_list_input,
494
- handler: mDM_list
495
- },
496
- {
497
- name: "mDM_respond_request",
498
- requires: "any",
499
- description: "Accept or reject an incoming DM request from a contact who is not yet in the user's whitelist.",
500
- inputSchema: mDM_respond_request_input,
501
- handler: mDM_respond_request
502
- }
503
- ];
504
-
505
- // src/tools/mirc.ts
506
- import { z as z2 } from "zod";
507
- var ChannelId = z2.string().min(1).max(120).describe("Channel id (UUID). Use mIRC_list to discover available channels.");
508
- var AccessMode = z2.enum(["open", "password", "private"]).describe("open: anyone can join \xB7 password: join with a shared password \xB7 private: invite-only.");
509
- var Capabilities = z2.object({
510
- txt: z2.boolean().default(true),
511
- ptt: z2.boolean().default(false),
512
- live: z2.boolean().default(false)
513
- }).describe("Which modes are enabled in this channel: txt (text), ptt (push-to-talk voice), live (live stream).").optional();
514
- var mIRC_create_input = z2.object({
515
- name: z2.string().min(1).max(80).describe("Channel display name."),
516
- topic: z2.string().max(500).optional().describe("Optional channel topic/description."),
517
- access_mode: AccessMode.default("open"),
518
- password: z2.string().min(6).max(120).optional().describe("Password (only for access_mode=password)."),
519
- capabilities: Capabilities
520
- });
521
- var mIRC_list_input = z2.object({
522
- limit: z2.number().int().min(1).max(500).default(100).optional(),
523
- offset: z2.number().int().min(0).default(0).optional(),
524
- access_mode: AccessMode.optional().describe("Filter to a single access mode.")
525
- });
526
- var mIRC_get_input = z2.object({
527
- channel_id: ChannelId
528
- });
529
- var mIRC_update_input = z2.object({
530
- channel_id: ChannelId,
531
- name: z2.string().min(1).max(80).optional(),
532
- topic: z2.string().max(500).optional(),
533
- access_mode: AccessMode.optional(),
534
- capabilities: Capabilities
535
- });
536
- var mIRC_delete_input = z2.object({
537
- channel_id: ChannelId
538
- });
539
- async function mIRC_create(input, ctx) {
540
- readSupabaseEnv();
541
- ctx.log("debug", "mIRC_create invoking channel-manage", { name: input.name });
542
- return await invokeFunction("channel-manage", {
543
- action: "create",
544
- ...input
545
- });
546
- }
547
- async function mIRC_list(input, ctx) {
548
- readSupabaseEnv();
549
- ctx.log("debug", "mIRC_list invoking channel-manage");
550
- return await invokeFunction("channel-manage", {
551
- action: "list",
552
- ...input
553
- });
554
- }
555
- async function mIRC_get(input, ctx) {
556
- readSupabaseEnv();
557
- ctx.log("debug", "mIRC_get invoking channel-manage", { channel_id: input.channel_id });
558
- return await invokeFunction("channel-manage", {
559
- action: "get",
560
- channel_id: input.channel_id
561
- });
562
- }
563
- async function mIRC_update(input, ctx) {
564
- readSupabaseEnv();
565
- ctx.log("debug", "mIRC_update invoking channel-manage", { channel_id: input.channel_id });
566
- return await invokeFunction("channel-manage", {
567
- action: "update",
568
- ...input
569
- });
570
- }
571
- async function mIRC_delete(input, ctx) {
572
- readSupabaseEnv();
573
- ctx.log("debug", "mIRC_delete invoking channel-manage", { channel_id: input.channel_id });
574
- await invokeFunction("channel-manage", {
575
- action: "delete",
576
- channel_id: input.channel_id
577
- });
578
- return { deleted: true };
579
- }
580
- var mircTools = [
581
- {
582
- name: "mIRC_create",
583
- requires: "network",
584
- description: "Create a new persistent channel (Discord/Slack-style). Set access_mode to open (anyone joins), password (shared-password gated), or private (invite-only). capabilities controls modes (txt/ptt/live).",
585
- inputSchema: mIRC_create_input,
586
- handler: mIRC_create
587
- },
588
- {
589
- name: "mIRC_list",
590
- requires: "network",
591
- description: "List channels available to the current user. Optionally filter by access_mode.",
592
- inputSchema: mIRC_list_input,
593
- handler: mIRC_list
594
- },
595
- {
596
- name: "mIRC_get",
597
- requires: "network",
598
- description: "Get full details of a single channel by id.",
599
- inputSchema: mIRC_get_input,
600
- handler: mIRC_get
601
- },
602
- {
603
- name: "mIRC_update",
604
- requires: "network",
605
- description: "Update channel metadata (name, topic, access_mode, capabilities). Owner only.",
606
- inputSchema: mIRC_update_input,
607
- handler: mIRC_update
608
- },
609
- {
610
- name: "mIRC_delete",
611
- requires: "network",
612
- description: "Delete a channel and cascade-remove its members. Owner only.",
613
- inputSchema: mIRC_delete_input,
614
- handler: mIRC_delete
615
- }
616
- ];
617
-
618
- // src/tools/mirc-members.ts
619
- import { z as z3 } from "zod";
620
- var ChannelId2 = z3.string().min(1).max(120).describe("Channel id (UUID). From mIRC_list / mIRC_create.");
621
- var MemberIdentity = z3.string().min(1).describe("Target user's identity id (UUID). From mDM_list_contacts or radar logs.");
622
- var Role = z3.enum(["owner", "admin", "moderator", "member", "guest"]).describe("Member role within the channel.");
623
- var mIRC_join_input = z3.object({
624
- channel_id: ChannelId2,
625
- password: z3.string().min(1).optional().describe("Required if the channel is access_mode=private.")
626
- });
627
- var mIRC_request_access_input = z3.object({
628
- channel_id: ChannelId2,
629
- message: z3.string().max(500).optional().describe("Optional note for the channel owner explaining why.")
630
- });
631
- var mIRC_leave_input = z3.object({
632
- channel_id: ChannelId2
633
- });
634
- var mIRC_approve_request_input = z3.object({
635
- channel_id: ChannelId2,
636
- request_id: z3.string().min(1).describe("Pending request id.")
637
- });
638
- var mIRC_reject_request_input = mIRC_approve_request_input;
639
- var mIRC_kick_input = z3.object({
640
- channel_id: ChannelId2,
641
- identity_id: MemberIdentity,
642
- reason: z3.string().max(500).optional()
643
- });
644
- var mIRC_ban_input = z3.object({
645
- channel_id: ChannelId2,
646
- identity_id: MemberIdentity,
647
- reason: z3.string().max(500).optional(),
648
- /** Optional unban deadline (ISO-8601). Omit for permanent ban. */
649
- until: z3.string().optional()
650
- });
651
- var mIRC_unban_input = z3.object({
652
- channel_id: ChannelId2,
653
- identity_id: MemberIdentity
654
- });
655
- var mIRC_set_role_input = z3.object({
656
- channel_id: ChannelId2,
657
- identity_id: MemberIdentity,
658
- role: Role
659
- });
660
- var mIRC_set_ptt_input = z3.object({
661
- channel_id: ChannelId2,
662
- identity_id: MemberIdentity,
663
- ptt_enabled: z3.boolean().describe("Allow this member to hold the PTT floor in voice mode.")
664
- });
665
- async function invokeChannelMembers(action, body, ctx) {
666
- readSupabaseEnv();
667
- ctx.log("debug", `mIRC.${action}`, body);
668
- return await invokeFunction("channel-members-manage", { action, ...body });
669
- }
670
- var mircMembersTools = [
671
- {
672
- name: "mIRC_join",
673
- requires: "network",
674
- description: "Join a channel as the current user. For private channels pass `password`. Returns a membership row or 409 if already a member.",
675
- inputSchema: mIRC_join_input,
676
- handler: ((input, ctx) => invokeChannelMembers("join", input, ctx))
677
- },
678
- {
679
- name: "mIRC_request_access",
680
- requires: "network",
681
- description: "Request access to an invite_only channel. Owner / admins get a notification with the optional message.",
682
- inputSchema: mIRC_request_access_input,
683
- handler: ((input, ctx) => invokeChannelMembers("request-access", input, ctx))
684
- },
685
- {
686
- name: "mIRC_leave",
687
- requires: "network",
688
- description: "Leave a channel as the current user. Owner cannot leave without transferring ownership first.",
689
- inputSchema: mIRC_leave_input,
690
- handler: ((input, ctx) => invokeChannelMembers("leave", input, ctx))
691
- },
692
- {
693
- name: "mIRC_approve_request",
694
- requires: "network",
695
- description: "Approve a pending access request. Admins / moderators / owner only.",
696
- inputSchema: mIRC_approve_request_input,
697
- handler: ((input, ctx) => invokeChannelMembers("approve-request", input, ctx))
698
- },
699
- {
700
- name: "mIRC_reject_request",
701
- requires: "network",
702
- description: "Reject a pending access request. Admins / moderators / owner only.",
703
- inputSchema: mIRC_reject_request_input,
704
- handler: ((input, ctx) => invokeChannelMembers("reject-request", input, ctx))
705
- },
706
- {
707
- name: "mIRC_kick",
708
- requires: "network",
709
- description: "Remove a member from the channel. They can rejoin if not banned. Requires moderator+. `reason` is logged to channel-event-log.",
710
- inputSchema: mIRC_kick_input,
711
- handler: ((input, ctx) => invokeChannelMembers("kick", input, ctx))
712
- },
713
- {
714
- name: "mIRC_ban",
715
- requires: "network",
716
- description: "Ban a member from the channel. They cannot rejoin until unbanned. `until` (ISO-8601) for time-bound ban; omit for permanent. Requires admin+.",
717
- inputSchema: mIRC_ban_input,
718
- handler: ((input, ctx) => invokeChannelMembers("ban", input, ctx))
719
- },
720
- {
721
- name: "mIRC_unban",
722
- requires: "network",
723
- description: "Lift a ban. Requires admin+.",
724
- inputSchema: mIRC_unban_input,
725
- handler: ((input, ctx) => invokeChannelMembers("unban", input, ctx))
726
- },
727
- {
728
- name: "mIRC_set_role",
729
- requires: "network",
730
- description: "Promote / demote a member. Roles: owner > admin > moderator > member > guest. Only owner can promote to admin; only admin+ can promote to moderator.",
731
- inputSchema: mIRC_set_role_input,
732
- handler: ((input, ctx) => invokeChannelMembers("set-role", input, ctx))
733
- },
734
- {
735
- name: "mIRC_set_ptt",
736
- requires: "network",
737
- description: "Grant or revoke PTT floor permission for a member in voice-capable channels (capabilities.ptt=true). Requires moderator+.",
738
- inputSchema: mIRC_set_ptt_input,
739
- handler: ((input, ctx) => invokeChannelMembers("set-ptt", input, ctx))
740
- }
741
- ];
742
-
743
- // src/tools/mirc-messages.ts
744
- import { z as z4 } from "zod";
745
- var PROTOCOL_VERSION2 = "mosadd.chat.v1";
746
- var ChannelId3 = z4.string().min(1).max(120).describe("Channel id (UUID). From mIRC_create / mIRC_list.");
747
- var mIRC_post_message_input = z4.object({
748
- channel_id: ChannelId3,
749
- text: z4.string().min(1).max(64e3).describe("Message body (UTF-8). Max 64 KB."),
750
- reply_to_id: z4.string().optional().describe("Optional id of the message being replied to."),
751
- space_id: z4.string().optional().describe("Optional backing space id. Resolved automatically from the channel if omitted.")
752
- });
753
- var mIRC_list_messages_input = z4.object({
754
- channel_id: ChannelId3,
755
- limit: z4.number().int().min(1).max(200).default(50).optional(),
756
- cursor: z4.string().optional().describe("Opaque pagination cursor from a prior list response."),
757
- space_id: z4.string().optional().describe("Optional backing space id. Resolved automatically if omitted.")
758
- });
759
- function packPlaintextPayload2(text, replyToId) {
760
- const envelope = {
761
- v: PROTOCOL_VERSION2,
762
- type: "text",
763
- text,
764
- reply_to: replyToId ?? null,
765
- sent_at: (/* @__PURE__ */ new Date()).toISOString()
766
- };
767
- return Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
768
- }
769
- function unpackPayload2(payload) {
770
- try {
771
- const obj = JSON.parse(Buffer.from(payload, "base64").toString("utf8"));
772
- if (typeof obj?.text === "string") return obj;
773
- } catch {
774
- }
775
- return { text: "<ciphertext>" };
776
- }
777
- async function resolveLinkedSpaceId(channelId) {
778
- const data = await invokeFunction("channel-manage", { action: "get", channel_id: channelId });
779
- const spaceId = data?.linked_space_id ?? data?.channel?.metadata?.linked_space_id;
780
- if (!spaceId) {
781
- throw new Error(
782
- `Channel ${channelId} has no linked space yet. Run mIRC_list (which repairs linked spaces) or mIRC_join first, or pass space_id explicitly.`
783
- );
784
- }
785
- return spaceId;
786
- }
787
- async function mIRC_post_message(input, ctx) {
788
- readSupabaseEnv();
789
- const space_id = input.space_id ?? await resolveLinkedSpaceId(input.channel_id);
790
- const thread_id = `chat:${input.channel_id}`;
791
- ctx.log("debug", "mIRC_post_message", { thread_id, space_id });
792
- const data = await invokeFunction("message-send", {
793
- space_id,
794
- thread_id,
795
- encrypted_payload: packPlaintextPayload2(input.text, input.reply_to_id),
796
- message_type: "txt",
797
- protocol_version: PROTOCOL_VERSION2,
798
- reply_to_id: input.reply_to_id ?? null
799
- });
800
- if (!data?.message?.id) throw new Error("message-send returned no message id");
801
- return { message_id: data.message.id, delivered_at: data.message.created_at ?? (/* @__PURE__ */ new Date()).toISOString(), thread_id };
802
- }
803
- async function mIRC_list_messages(input, ctx) {
804
- readSupabaseEnv();
805
- const space_id = input.space_id ?? await resolveLinkedSpaceId(input.channel_id);
806
- const thread_id = `chat:${input.channel_id}`;
807
- ctx.log("debug", "mIRC_list_messages", { thread_id, space_id });
808
- const data = await invokeFunction("message-list", {
809
- space_id,
810
- thread_id,
811
- limit: input.limit ?? 50,
812
- cursor: input.cursor
813
- });
814
- return {
815
- messages: (data?.messages ?? []).map((m) => ({
816
- id: m.id,
817
- sender_identity_id: m.sender_identity_id,
818
- text: unpackPayload2(m.encrypted_payload).text,
819
- timestamp: m.created_at
820
- })),
821
- next_cursor: data?.next_cursor ?? null
822
- };
823
- }
824
- var mircMessagesTools = [
825
- {
826
- name: "mIRC_post_message",
827
- requires: "network",
828
- description: "Post a text message into a persistent channel (mIRC). Pass channel_id from mIRC_create / mIRC_list; the backing space is resolved automatically. You must be a member of private channels (use mIRC_join first). This is how an agent actually talks in a channel \u2014 the other mIRC_* tools only manage it.",
829
- inputSchema: mIRC_post_message_input,
830
- handler: mIRC_post_message
831
- },
832
- {
833
- name: "mIRC_list_messages",
834
- requires: "network",
835
- description: "List recent text messages in a persistent channel (mIRC), newest first, cursor-paginated. Pass channel_id; the backing space is resolved automatically.",
836
- inputSchema: mIRC_list_messages_input,
837
- handler: mIRC_list_messages
838
- }
839
- ];
840
-
841
- // src/tools/mroom.ts
842
- import { z as z5 } from "zod";
843
- var RoomId = z5.string().min(1).describe("Private room id (UUID).");
844
- var mROOM_create_input = z5.object({
845
- ttl_seconds: z5.number().int().min(60).max(86400 * 30).default(86400).optional().describe("Time-to-live in seconds. Defaults to 24 h. Max 30 days.")
846
- });
847
- var mROOM_join_input = z5.object({
848
- room_id: RoomId
849
- });
850
- var mROOM_close_input = z5.object({
851
- room_id: RoomId
852
- });
853
- var mROOM_leave_input = z5.object({
854
- room_id: RoomId
855
- });
856
- var mROOM_list_input = z5.object({});
857
- var mROOM_create_guest_link_input = z5.object({
858
- room_id: RoomId,
859
- display_name: z5.string().min(1).max(80).describe("Display name the guest will appear under. They never sign up \u2014 this is the only identifier."),
860
- ttl_seconds: z5.number().int().min(60).max(86400 * 7).default(3600).optional().describe("How long the guest token is valid. Default 1 h, max 7 days.")
861
- });
862
- async function mROOM_create(input, ctx) {
863
- readSupabaseEnv();
864
- const expires_at = new Date(Date.now() + (input.ttl_seconds ?? 86400) * 1e3).toISOString();
865
- ctx.log("debug", "mROOM_create invoking privroom-manage", { expires_at });
866
- return await invokeFunction("privroom-manage", {
867
- action: "create",
868
- expires_at
869
- });
870
- }
871
- async function mROOM_join(input, ctx) {
872
- readSupabaseEnv();
873
- ctx.log("debug", "mROOM_join invoking privroom-manage", { room_id: input.room_id });
874
- return await invokeFunction("privroom-manage", {
875
- action: "join",
876
- room_id: input.room_id
877
- });
878
- }
879
- async function mROOM_close(input, ctx) {
880
- readSupabaseEnv();
881
- ctx.log("debug", "mROOM_close invoking privroom-manage", { room_id: input.room_id });
882
- return await invokeFunction("privroom-manage", {
883
- action: "close",
884
- room_id: input.room_id
885
- });
886
- }
887
- async function mROOM_leave(input, ctx) {
888
- readSupabaseEnv();
889
- ctx.log("debug", "mROOM_leave invoking privroom-manage", { room_id: input.room_id });
890
- return await invokeFunction("privroom-manage", {
891
- action: "leave",
892
- room_id: input.room_id
893
- });
894
- }
895
- async function mROOM_list(_input, ctx) {
896
- readSupabaseEnv();
897
- ctx.log("debug", "mROOM_list invoking privroom-manage");
898
- return await invokeFunction("privroom-manage", { action: "list" });
899
- }
900
- async function mROOM_create_guest_link(input, ctx) {
901
- readSupabaseEnv();
902
- ctx.log("debug", "mROOM_create_guest_link invoking privroom-guest-token", {
903
- room_id: input.room_id
904
- });
905
- const result = await invokeFunction("privroom-guest-token", {
906
- room_id: input.room_id,
907
- display_name: input.display_name,
908
- ttl_seconds: input.ttl_seconds ?? 3600
909
- });
910
- return {
911
- token: result.token,
912
- join_url: `https://mosadd.com/r/${input.room_id}?t=${result.token}`,
913
- expires_at: result.expires_at
914
- };
915
- }
916
- var mroomTools = [
917
- {
918
- name: "mROOM_create",
919
- requires: "network",
920
- description: "Create an ephemeral private room. Auto-joins the creator. Defaults to 24 h TTL \u2014 pass ttl_seconds to override.",
921
- inputSchema: mROOM_create_input,
922
- handler: mROOM_create
923
- },
924
- {
925
- name: "mROOM_create_guest_link",
926
- requires: "network",
927
- description: "USP: Generate a short-lived join link that lets a person enter the room WITHOUT a mosadd account. Returns { token, join_url, expires_at }. Share the join_url out-of-band (email, SMS, QR). Use case: support call, live-stream after-party, anonymous tipline.",
928
- inputSchema: mROOM_create_guest_link_input,
929
- handler: mROOM_create_guest_link
930
- },
931
- {
932
- name: "mROOM_join",
933
- requires: "network",
934
- description: "Join an existing private room (current user, not a guest).",
935
- inputSchema: mROOM_join_input,
936
- handler: mROOM_join
937
- },
938
- {
939
- name: "mROOM_leave",
940
- requires: "network",
941
- description: "Leave a private room.",
942
- inputSchema: mROOM_leave_input,
943
- handler: mROOM_leave
944
- },
945
- {
946
- name: "mROOM_close",
947
- requires: "network",
948
- description: "Close a private room and remove all members. Founder only.",
949
- inputSchema: mROOM_close_input,
950
- handler: mROOM_close
951
- },
952
- {
953
- name: "mROOM_list",
954
- requires: "network",
955
- description: "List private rooms the current user belongs to.",
956
- inputSchema: mROOM_list_input,
957
- handler: mROOM_list
958
- }
959
- ];
960
-
961
- // src/tools/mroom-messages.ts
962
- import { z as z6 } from "zod";
963
- var PROTOCOL_VERSION3 = "mosadd.chat.v1";
964
- var RoomId2 = z6.string().min(1).describe("Private room id (UUID). From mROOM_create / mROOM_list.");
965
- var mROOM_send_message_input = z6.object({
966
- room_id: RoomId2,
967
- text: z6.string().min(1).max(64e3).describe("Message body (UTF-8). Max 64 KB."),
968
- reply_to_id: z6.string().optional().describe("Optional id of the message being replied to.")
969
- });
970
- var mROOM_list_messages_input = z6.object({
971
- room_id: RoomId2,
972
- limit: z6.number().int().min(1).max(200).default(50).optional(),
973
- cursor: z6.string().optional().describe("Opaque pagination cursor from a prior list response.")
974
- });
975
- function packPlaintextPayload3(text, replyToId) {
976
- const envelope = {
977
- v: PROTOCOL_VERSION3,
978
- type: "text",
979
- text,
980
- reply_to: replyToId ?? null,
981
- sent_at: (/* @__PURE__ */ new Date()).toISOString()
982
- };
983
- return Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
984
- }
985
- function unpackPayload3(payload) {
986
- try {
987
- const json = Buffer.from(payload, "base64").toString("utf8");
988
- const obj = JSON.parse(json);
989
- if (typeof obj?.text === "string") return obj;
990
- } catch {
991
- }
992
- return { text: "<ciphertext>" };
993
- }
994
- async function mROOM_send_message(input, ctx) {
995
- readSupabaseEnv();
996
- const thread_id = `privroom:${input.room_id}`;
997
- ctx.log("debug", "mROOM_send_message", { thread_id });
998
- const data = await invokeFunction(
999
- "message-send",
1000
- {
1001
- space_id: "rooms",
1002
- thread_id,
1003
- encrypted_payload: packPlaintextPayload3(input.text, input.reply_to_id),
1004
- message_type: "text",
1005
- protocol_version: PROTOCOL_VERSION3,
1006
- reply_to_id: input.reply_to_id ?? null
1007
- }
1008
- );
1009
- if (!data?.message?.id) {
1010
- throw new Error("message-send returned no message id");
1011
- }
1012
- return {
1013
- message_id: data.message.id,
1014
- delivered_at: data.message.created_at ?? (/* @__PURE__ */ new Date()).toISOString(),
1015
- thread_id
1016
- };
1017
- }
1018
- async function mROOM_list_messages(input, ctx) {
1019
- readSupabaseEnv();
1020
- const thread_id = `privroom:${input.room_id}`;
1021
- ctx.log("debug", "mROOM_list_messages", { thread_id });
1022
- const data = await invokeFunction("message-list", {
1023
- space_id: "rooms",
1024
- thread_id,
1025
- limit: input.limit ?? 50,
1026
- cursor: input.cursor
1027
- });
1028
- return {
1029
- messages: (data?.messages ?? []).map((m) => ({
1030
- id: m.id,
1031
- sender_identity_id: m.sender_identity_id,
1032
- text: unpackPayload3(m.encrypted_payload).text,
1033
- timestamp: m.created_at
1034
- })),
1035
- next_cursor: data?.next_cursor ?? null
1036
- };
1037
- }
1038
- var mroomMessagesTools = [
1039
- {
1040
- name: "mROOM_send_message",
1041
- requires: "network",
1042
- description: "Send a text message into a private room. Authorisation: must be a member (or guest with a valid token). Alpha payload is plaintext base64; v0.2 wraps with Double Ratchet.",
1043
- inputSchema: mROOM_send_message_input,
1044
- handler: mROOM_send_message
1045
- },
1046
- {
1047
- name: "mROOM_list_messages",
1048
- requires: "network",
1049
- description: "List recent text messages in a private room. Cursor-paginated, newest first.",
1050
- inputSchema: mROOM_list_messages_input,
1051
- handler: mROOM_list_messages
1052
- }
1053
- ];
1054
-
1055
- // src/tools/mail.ts
1056
- import { z as z7 } from "zod";
1057
- var EmailAddress = z7.string().email().max(254).describe("RFC 5321 email address.");
1058
- var MessageId = z7.string().min(1).describe("Message id (UUID) from mAIL_send or inbox.");
1059
- var mAIL_send_input = z7.object({
1060
- to: z7.union([EmailAddress, z7.array(EmailAddress).min(1).max(50)]).describe(
1061
- "Recipient(s). Single address or array of up to 50."
1062
- ),
1063
- subject: z7.string().min(1).max(998).describe("Email subject line. Max 998 chars (RFC 5322)."),
1064
- body_text: z7.string().max(1048576).optional().describe("Plain text body. Max 1 MB."),
1065
- body_html: z7.string().max(1048576).optional().describe("HTML body. Max 1 MB."),
1066
- cc: z7.array(EmailAddress).max(50).optional(),
1067
- bcc: z7.array(EmailAddress).max(50).optional(),
1068
- reply_to: EmailAddress.optional()
1069
- });
1070
- var mAIL_view_input = z7.object({
1071
- message_id: MessageId
1072
- });
1073
- async function mAIL_send(input, ctx) {
1074
- readSupabaseEnv();
1075
- if (!input.body_text && !input.body_html) {
1076
- throw new Error("mAIL_send requires at least one of body_text or body_html.");
1077
- }
1078
- ctx.log("debug", "mAIL_send invoking mp0st-send", { to: input.to });
1079
- return await invokeFunction("mp0st-send", input);
1080
- }
1081
- async function mAIL_view(input, ctx) {
1082
- readSupabaseEnv();
1083
- ctx.log("debug", "mAIL_view invoking mp0st-view", { message_id: input.message_id });
1084
- return await invokeFunction("mp0st-view", { message_id: input.message_id });
1085
- }
1086
- var mailTools = [
1087
- {
1088
- name: "mAIL_send",
1089
- requires: "network",
1090
- description: "Send an email from the user's mosadd address (<userId>@mosadd.com). Pass body_text or body_html (or both). Supports cc, bcc, reply_to.",
1091
- inputSchema: mAIL_send_input,
1092
- handler: mAIL_send
1093
- },
1094
- {
1095
- name: "mAIL_view",
1096
- requires: "network",
1097
- description: "Read the full body and metadata of an email by message_id.",
1098
- inputSchema: mAIL_view_input,
1099
- handler: mAIL_view
1100
- }
1101
- ];
1102
-
1103
- // src/tools/mtalk.ts
1104
- import { z as z8 } from "zod";
1105
- var RoomLabel = z8.string().min(1).max(120).regex(/^[a-zA-Z0-9._-]+$/).describe("Human-readable room label (e.g. 'ops', 'field-team'). Used to derive a stable room id.");
1106
- var RoomId3 = z8.string().min(1).describe("Room id returned by mTALK_open.");
1107
- var mTALK_open_input = z8.object({
1108
- label: RoomLabel.optional().describe("Optional label; defaults to a personal room.")
1109
- });
1110
- var mTALK_join_input = z8.object({ room_id: RoomId3 });
1111
- var mTALK_press_input = z8.object({ room_id: RoomId3 });
1112
- var mTALK_release_input = z8.object({ room_id: RoomId3 });
1113
- var mTALK_state_input = z8.object({ room_id: RoomId3 });
1114
- async function mTALK_open(input, ctx) {
1115
- const { roomId } = await ctx.providers.voice.createRoom(input.label);
1116
- ctx.log("debug", "mTALK_open", { room_id: roomId });
1117
- return { room_id: roomId };
1118
- }
1119
- async function mTALK_join(input, ctx) {
1120
- const ticket = await ctx.providers.voice.joinTicket(input.room_id);
1121
- ctx.log("debug", "mTALK_join", { room_id: ticket.roomId, identity: ticket.identity });
1122
- return { room_id: ticket.roomId, token: ticket.token, url: ticket.url, identity: ticket.identity };
1123
- }
1124
- async function mTALK_press(input, ctx) {
1125
- const res = await ctx.providers.voice.requestFloor(input.room_id);
1126
- ctx.log("debug", "mTALK_press", { room_id: input.room_id, granted: res.granted, position: res.position });
1127
- return { granted: res.granted, position: res.position, holder: res.snapshot.holder, queue: res.snapshot.queue };
1128
- }
1129
- async function mTALK_release(input, ctx) {
1130
- const snap = await ctx.providers.voice.releaseFloor(input.room_id);
1131
- ctx.log("debug", "mTALK_release", { room_id: input.room_id, holder: snap.holder });
1132
- return { holder: snap.holder, queue: snap.queue };
1133
- }
1134
- async function mTALK_state(input, ctx) {
1135
- const snap = await ctx.providers.voice.floorState(input.room_id);
1136
- return { holder: snap.holder, since: snap.since, queue: snap.queue };
1137
- }
1138
- var mtalkTools = [
1139
- {
1140
- name: "mTALK_open",
1141
- requires: "any",
1142
- description: "Open (or get) a push-to-talk room. Returns a stable room_id. Pass an optional label to share a named room (e.g. 'ops'); omit it for a personal room. Works over network (LiveKit) or off-grid radio depending on the host.",
1143
- inputSchema: mTALK_open_input,
1144
- handler: mTALK_open
1145
- },
1146
- {
1147
- name: "mTALK_join",
1148
- requires: "network",
1149
- description: "Get credentials (token + media URL) to join a PTT room's audio transport. Hand these to a human or bot client to connect. The agent itself drives the floor with mTALK_press / mTALK_release.",
1150
- inputSchema: mTALK_join_input,
1151
- handler: mTALK_join
1152
- },
1153
- {
1154
- name: "mTALK_press",
1155
- requires: "any",
1156
- description: "Press push-to-talk: request the floor in a room. Half-duplex \u2014 if no one is transmitting you are GRANTED the floor (granted=true) and may speak; otherwise you are queued FIFO and `position` tells you where you are. Call mTALK_release when done. A holder who never releases is auto-bumped after the anti-hog timeout.",
1157
- inputSchema: mTALK_press_input,
1158
- handler: mTALK_press
1159
- },
1160
- {
1161
- name: "mTALK_release",
1162
- requires: "any",
1163
- description: "Release push-to-talk: give up the floor (or cancel your queued request). If you held the floor, the next participant in the queue is promoted automatically. Returns the new holder and queue.",
1164
- inputSchema: mTALK_release_input,
1165
- handler: mTALK_release
1166
- },
1167
- {
1168
- name: "mTALK_state",
1169
- requires: "any",
1170
- description: "Read a PTT room's floor state without changing it: who is currently transmitting (holder), since when, and the waiting queue.",
1171
- inputSchema: mTALK_state_input,
1172
- handler: mTALK_state
1173
- }
1174
- ];
1175
-
1176
- // src/tools/knowledge.ts
1177
- import { z as z9 } from "zod";
1178
- var mKB_search_input = z9.object({
1179
- query: z9.string().min(1).max(2e3).describe("Natural-language question to answer from the user's own indexed messages/emails/calls/notes."),
1180
- top_k: z9.number().int().min(1).max(25).optional().describe("Max number of source chunks to retrieve and ground the answer in. Default 8."),
1181
- source_types: z9.array(z9.enum(["message", "email", "call", "note", "contact"])).optional().describe("Restrict retrieval to these source types. Omit to search everything."),
1182
- thread_id: z9.string().optional().describe("Optional: restrict retrieval to a single thread id (e.g. a dm:/chat: thread).")
1183
- });
1184
- async function mKB_search(input, ctx) {
1185
- readSupabaseEnv();
1186
- ctx.log("debug", "mKB_search via rag-query", { top_k: input.top_k ?? 8 });
1187
- const data = await invokeFunction("rag-query", {
1188
- query: input.query,
1189
- top_k: input.top_k ?? 8,
1190
- source_types: input.source_types ?? null,
1191
- thread_id: input.thread_id ?? null
1192
- });
1193
- return {
1194
- answer: data.answer ?? "",
1195
- sources: data.sources ?? [],
1196
- chunks_found: data.chunks_found ?? (data.sources?.length ?? 0)
1197
- };
1198
- }
1199
- var knowledgeTools = [
1200
- {
1201
- name: "mKB_search",
1202
- requires: "network",
1203
- description: "Search and answer questions over the USER'S OWN mosadd data (messages, emails, calls, notes) with a private RAG index \u2014 hybrid vector + keyword retrieval, reranked, grounded in cited sources (no fabrication). Use it to recall 'what did X say about Y', summarize a thread, or pull facts the user has received. Returns an answer plus the source snippets it used. This is agent memory (mKB = knowledge base) over the user's communications, available outside the mosadd app.",
1204
- inputSchema: mKB_search_input,
1205
- handler: mKB_search
1206
- }
1207
- ];
1208
-
1209
- // src/tools/capabilities.ts
1210
- import { z as z10 } from "zod";
1211
- var CONTRACT_VERSION = "1.0.0";
1212
- var ALL_REQUIREMENTS = ["any", "radio", "network"];
1213
- function buildCapabilityManifest(tools) {
1214
- const entries = tools.map((t) => ({ name: t.name, requires: t.requires }));
1215
- const by_requirement = {
1216
- any: [],
1217
- radio: [],
1218
- network: []
1219
- };
1220
- for (const e of entries) by_requirement[e.requires].push(e.name);
1221
- return {
1222
- contract_version: CONTRACT_VERSION,
1223
- requirements: ALL_REQUIREMENTS,
1224
- tools: entries,
1225
- by_requirement
1226
- };
1227
- }
1228
- function makeCapabilitiesTool(channelTools2) {
1229
- const tool = {
1230
- name: "comms_capabilities",
1231
- requires: "any",
1232
- description: "Discover which mosadd tools are available and what transport each requires (any | radio | network). Carrier-aware hosts (e.g. off-grid radio devices) call this once to gate the tool list to what the current carrier supports. Returns a manifest with per-tool requirements grouped by transport.",
1233
- inputSchema: z10.object({}),
1234
- handler: async () => buildCapabilityManifest([...channelTools2, tool])
1235
- };
1236
- return tool;
1237
- }
1238
-
1239
- // src/tools/index.ts
1240
- var channelTools = [
1241
- ...mdmTools,
1242
- ...mircTools,
1243
- ...mircMembersTools,
1244
- ...mircMessagesTools,
1245
- ...mroomTools,
1246
- ...mroomMessagesTools,
1247
- ...mailTools,
1248
- ...mtalkTools,
1249
- ...knowledgeTools
1250
- // mcallTools, mirlTools,
1251
- // mmatrixTools, mdiscordTools, mtelegramTools, mslackTools, msignalTools,
1252
- //
1253
- // Each m* module registers its tools here as it ships.
1254
- // RFC required to add a new m* module (see docs/rfcs/0001-module-naming.md).
1255
- ];
1256
- var allTools = [
1257
- ...channelTools,
1258
- // comms_capabilities: one-call discovery of every tool's `requires` flag,
1259
- // so carrier-aware hosts (cymru-os) can gate the tool list by transport.
1260
- makeCapabilitiesTool(channelTools)
1261
- ];
1262
-
1263
- // src/server.ts
1264
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
1265
-
1266
- // src/providers/supabase-dm.ts
1267
- var PROTOCOL_VERSION4 = "mosadd.chat.v1";
1268
- var SupabaseDmProvider = class {
1269
- cachedSelfId = null;
1270
- async selfId() {
1271
- if (this.cachedSelfId) return this.cachedSelfId;
1272
- readSupabaseEnv();
1273
- const sb = getSupabase();
1274
- const { data: u, error: ue } = await sb.auth.getUser();
1275
- if (ue || !u?.user) {
1276
- throw new Error(
1277
- "Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token."
1278
- );
1279
- }
1280
- const { data: identity, error } = await sb.from("identities").select("id").eq("user_id", u.user.id).maybeSingle();
1281
- if (error || !identity) {
1282
- throw new Error("Current user has no mosadd identity row. Sign in to mosadd.com first.");
1283
- }
1284
- this.cachedSelfId = identity.id;
1285
- return this.cachedSelfId;
1286
- }
1287
- async send(args) {
1288
- const encrypted_payload = Buffer.from(args.payload).toString("base64");
1289
- const data = await invokeFunction("message-send", {
1290
- space_id: "dm",
1291
- thread_id: args.threadId,
1292
- encrypted_payload,
1293
- message_type: "text",
1294
- protocol_version: PROTOCOL_VERSION4,
1295
- recipient_account_id: args.to,
1296
- reply_to_id: args.replyToId ?? null
1297
- });
1298
- if (!data?.message?.id) {
1299
- throw new Error("message-send returned no message id");
1300
- }
1301
- return {
1302
- id: data.message.id,
1303
- deliveredAt: data.message.created_at ?? (/* @__PURE__ */ new Date()).toISOString()
1304
- };
1305
- }
1306
- async publishPrekeyBundle(bundle) {
1307
- await invokeFunction("prekey-bundle-publish", {
1308
- bundle: Buffer.from(bundle).toString("base64")
1309
- });
1310
- }
1311
- async fetchPrekeyBundle(peerId) {
1312
- const data = await invokeFunction("prekey-bundle-fetch", {
1313
- peer_id: peerId
1314
- });
1315
- if (!data?.bundle) return null;
1316
- return new Uint8Array(Buffer.from(data.bundle, "base64"));
1317
- }
1318
- async list(args) {
1319
- const data = await invokeFunction("message-list", {
1320
- space_id: "dm",
1321
- thread_id: args.threadId,
1322
- limit: args.limit ?? 50,
1323
- cursor: args.cursor
1324
- });
1325
- return {
1326
- messages: (data?.messages ?? []).map((m) => ({
1327
- id: m.id,
1328
- senderId: m.sender_identity_id,
1329
- payload: new Uint8Array(Buffer.from(m.encrypted_payload, "base64")),
1330
- timestamp: m.created_at,
1331
- threadId: m.thread_id
1332
- })),
1333
- nextCursor: data?.next_cursor ?? null
1334
- };
1335
- }
1336
- };
1337
-
1338
- // src/providers/supabase-voice.ts
1339
- var ROOM_PREFIX = "mosadd-room-";
1340
- var SupabaseVoiceProvider = class {
1341
- cachedSelfId = null;
1342
- async selfId() {
1343
- if (this.cachedSelfId) return this.cachedSelfId;
1344
- readSupabaseEnv();
1345
- const sb = getSupabase();
1346
- const { data: u, error: ue } = await sb.auth.getUser();
1347
- if (ue || !u?.user) {
1348
- throw new Error(
1349
- "Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token."
1350
- );
1351
- }
1352
- const { data: identity, error } = await sb.from("identities").select("id").eq("user_id", u.user.id).maybeSingle();
1353
- if (error || !identity) {
1354
- throw new Error("Current user has no mosadd identity row. Sign in to mosadd.com first.");
1355
- }
1356
- this.cachedSelfId = identity.id;
1357
- return this.cachedSelfId;
1358
- }
1359
- async createRoom(label) {
1360
- const self = await this.selfId();
1361
- const roomId = `${ROOM_PREFIX}${label ? slug(label) : self}`;
1362
- return { roomId };
1363
- }
1364
- async joinTicket(roomId) {
1365
- const self = await this.selfId();
1366
- const data = await invokeFunction("livekit-token", {
1367
- roomName: roomId,
1368
- identity: self
1369
- });
1370
- return { token: data.token, url: data.url, identity: data.identity, roomId: data.roomName };
1371
- }
1372
- async requestFloor(roomId) {
1373
- return invokeFunction("mtalk-floor", { action: "request", room_id: roomId });
1374
- }
1375
- async releaseFloor(roomId) {
1376
- const data = await invokeFunction("mtalk-floor", {
1377
- action: "release",
1378
- room_id: roomId
1379
- });
1380
- return data.snapshot;
1381
- }
1382
- async floorState(roomId) {
1383
- const data = await invokeFunction("mtalk-floor", {
1384
- action: "state",
1385
- room_id: roomId
1386
- });
1387
- return data.snapshot;
1388
- }
1389
- };
1390
- function slug(s) {
1391
- return s.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 200);
1392
- }
1393
-
1394
- // src/server.ts
1395
- function defaultProviders(injected) {
1396
- return {
1397
- dm: injected?.dm ?? new SupabaseDmProvider(),
1398
- keys: injected?.keys ?? new InMemoryMdmKeyStore(),
1399
- voice: injected?.voice ?? new SupabaseVoiceProvider()
1400
- };
1401
- }
1402
- function createMosaddServer(options = {}) {
1403
- const mode = options.mode ?? (options.apiKey ? "cloud" : "local");
1404
- const hubUrl = options.hubUrl ?? "https://mcp.mosadd.com";
1405
- const logLevel = options.logLevel ?? "info";
1406
- const providers = defaultProviders(options.providers);
1407
- const ctx = {
1408
- options: { ...options, mode, hubUrl },
1409
- providers,
1410
- log: (level, msg, extra) => {
1411
- if (shouldLog(level, logLevel)) {
1412
- process.stderr.write(
1413
- JSON.stringify({ level, msg, extra, ts: (/* @__PURE__ */ new Date()).toISOString() }) + "\n"
1414
- );
1415
- }
1416
- }
1417
- };
1418
- const server = new McpServer(
1419
- {
1420
- name: "mosadd",
1421
- version: "3.0.0-alpha.0"
1422
- },
1423
- {
1424
- capabilities: {
1425
- tools: {}
1426
- }
1427
- }
1428
- );
1429
- for (const tool of allTools) {
1430
- const shape = tool.inputSchema && typeof tool.inputSchema === "object" && "shape" in tool.inputSchema ? tool.inputSchema.shape : tool.inputSchema;
1431
- server.tool(
1432
- tool.name,
1433
- tool.description,
1434
- shape,
1435
- async (input) => {
1436
- const parsed = tool.inputSchema.parse(input);
1437
- try {
1438
- const result = await tool.handler(parsed, ctx);
1439
- return {
1440
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
1441
- };
1442
- } catch (err) {
1443
- ctx.log("error", `tool ${tool.name} failed`, { error: String(err) });
1444
- return {
1445
- isError: true,
1446
- content: [
1447
- {
1448
- type: "text",
1449
- text: JSON.stringify({
1450
- error: err instanceof Error ? err.message : String(err),
1451
- tool: tool.name
1452
- })
1453
- }
1454
- ]
1455
- };
1456
- }
1457
- }
1458
- );
1459
- }
1460
- return server;
1461
- }
1462
- function shouldLog(level, threshold) {
1463
- const order = { debug: 0, info: 1, warn: 2, error: 3 };
1464
- return (order[level] ?? 1) >= (order[threshold] ?? 1);
1465
- }
1466
-
1467
- export {
1468
- allTools,
1469
- defaultProviders,
1470
- createMosaddServer
1471
- };