@mosadd/mcp 3.0.0-alpha.52 → 3.0.0-alpha.54

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 (58) hide show
  1. package/CHANGELOG.md +363 -309
  2. package/README.md +150 -150
  3. package/dist/bin/mcp.js +1 -1
  4. package/dist/{chunk-KVN7LZFW.js → chunk-3PUOM4R5.js} +470 -112
  5. package/dist/index.d.ts +11 -1
  6. package/dist/index.js +1 -1
  7. package/package.json +9 -9
  8. package/src/__tests__/golden-path.test.ts +139 -139
  9. package/src/__tests__/integration.test.ts +182 -182
  10. package/src/__tests__/knowledge-ingest.test.ts +114 -114
  11. package/src/__tests__/mdm-e2ee.test.ts +212 -212
  12. package/src/__tests__/mdm-mcp-readable.test.ts +386 -0
  13. package/src/__tests__/mirc-invite.test.ts +112 -112
  14. package/src/__tests__/mtalk.test.ts +122 -122
  15. package/src/__tests__/server.test.ts +71 -71
  16. package/src/__tests__/serverJsonVersion.test.ts +45 -45
  17. package/src/__tests__/tool-count-consistency.test.ts +199 -199
  18. package/src/bin/login.ts +138 -138
  19. package/src/bin/mcp.ts +145 -145
  20. package/src/config.ts +66 -66
  21. package/src/crypto/mdm-session.ts +842 -502
  22. package/src/index.ts +19 -19
  23. package/src/observability/sentry.ts +79 -79
  24. package/src/providers/memory-voice.ts +79 -79
  25. package/src/providers/supabase-dm.ts +202 -122
  26. package/src/providers/supabase-voice.ts +91 -91
  27. package/src/providers/supabase.ts +231 -231
  28. package/src/server.ts +195 -162
  29. package/src/tools/__tests__/ragDeleteFoldsSourceId.test.ts +67 -67
  30. package/src/tools/actions.ts +166 -166
  31. package/src/tools/attachments.ts +276 -276
  32. package/src/tools/capabilities.ts +70 -70
  33. package/src/tools/embed.ts +110 -110
  34. package/src/tools/index.ts +181 -181
  35. package/src/tools/knowledge-graph.ts +186 -186
  36. package/src/tools/knowledge.ts +344 -344
  37. package/src/tools/mail-agentbox.ts +155 -155
  38. package/src/tools/mail-aliases.ts +25 -25
  39. package/src/tools/mail-provenance.ts +137 -137
  40. package/src/tools/mail.ts +403 -403
  41. package/src/tools/mcall.ts +216 -216
  42. package/src/tools/mdm-as-agent.ts +126 -126
  43. package/src/tools/mdm-voice.ts +220 -220
  44. package/src/tools/mdm.ts +211 -29
  45. package/src/tools/mirc-edge.ts +196 -196
  46. package/src/tools/mirc-members.ts +287 -287
  47. package/src/tools/mirc.ts +308 -308
  48. package/src/tools/mroom-messages.ts +142 -142
  49. package/src/tools/mroom.ts +221 -221
  50. package/src/tools/mtalk.ts +131 -131
  51. package/src/tools/murl.ts +314 -314
  52. package/src/tools/presence.ts +442 -442
  53. package/src/tools/ptt-ingest.ts +99 -99
  54. package/src/tools/threat.ts +123 -123
  55. package/src/types.ts +121 -121
  56. package/src/version.ts +8 -8
  57. package/src/voice/floor.ts +132 -132
  58. package/LICENSE +0 -201
package/src/tools/mdm.ts CHANGED
@@ -21,9 +21,23 @@ import { invokeFunction, getSupabase, readSupabaseEnv } from "../providers/supab
21
21
  import {
22
22
  encryptForPeer,
23
23
  decryptFromPeer,
24
- publishOwnPrekeys,
25
24
  isE2eeEnvelope,
25
+ ensureOwnBundlePublished,
26
+ bundlePolicyForKind,
27
+ fetchVerifiedBundle,
28
+ sealForSelf,
29
+ sealForPeerRecoverable,
30
+ openSelfSealed,
31
+ openPeerRecoverable,
32
+ type OwnBundleState,
33
+ type PublicPrekeyBundle,
26
34
  } from "../crypto/mdm-session.js";
35
+ import {
36
+ MDM_TEXT_MESSAGE_TYPE,
37
+ MDM_MCP_SEALED_MESSAGE_TYPE,
38
+ type DmSendArgsExt,
39
+ type DmMessageExt,
40
+ } from "../providers/supabase-dm.js";
27
41
 
28
42
  // ---- Constants ----
29
43
 
@@ -139,37 +153,148 @@ function unpackPayload(payload: Uint8Array): { text: string; sent_at?: string; r
139
153
 
140
154
  // ---- Handlers ----
141
155
 
156
+ /** Does this provider know the caller's identity kind (Supabase lane)? */
157
+ async function selfKindOf(dm: MosaddToolContext["providers"]["dm"]): Promise<string | null> {
158
+ const f = (dm as { selfKind?: () => Promise<string | null> }).selfKind;
159
+ return typeof f === "function" ? await f.call(dm) : null;
160
+ }
161
+
162
+ /** A peer's identity kind when the provider can tell (Supabase lane); null = unknown. */
163
+ async function peerKindOf(dm: MosaddToolContext["providers"]["dm"], peerId: string): Promise<string | null> {
164
+ const f = (dm as { peerKind?: (id: string) => Promise<string | null> }).peerKind;
165
+ if (typeof f !== "function") return null;
166
+ try {
167
+ return await f.call(dm, peerId);
168
+ } catch {
169
+ return null;
170
+ }
171
+ }
172
+
173
+ type MdmSendResultOut = {
174
+ message_id: string;
175
+ delivered_at: string;
176
+ thread_id: string;
177
+ encrypted: boolean;
178
+ /**
179
+ * "plaintext_agent_lane": an agent line is a party, so the DM goes in the clear (rozkaz Krola
180
+ * 20.09, same rule as the app's peerIsAgent). "e2ee": human to human, X3DH + Double Ratchet.
181
+ */
182
+ mode: "plaintext_agent_lane" | "e2ee";
183
+ /** the sender can read this message back from ANY process / ANY key of the same identity */
184
+ sender_copy: boolean;
185
+ /** the recipient can read it without a ratchet session */
186
+ recipient_copy: boolean;
187
+ /** state of this identity in the key directory (E2EE only; the plaintext lane never touches it) */
188
+ identity: OwnBundleState | "untouched";
189
+ };
190
+
142
191
  async function mDM_send(
143
192
  input: z.infer<typeof mDM_send_input>,
144
193
  ctx: MosaddToolContext,
145
- ): Promise<{ message_id: string; delivered_at: string; thread_id: string; encrypted: true }> {
146
- // E2EE path (default). The plaintext is packed into the inner mosadd.chat.v1
147
- // envelope, then SEALED via X3DH + Double Ratchet into an opaque envelope the
148
- // DmProvider moves without understanding. First contact fetches the peer's
149
- // published prekey bundle through the same provider (decision "1a").
194
+ ): Promise<MdmSendResultOut> {
150
195
  const dm = ctx.providers.dm;
151
196
  const selfId = await dm.selfId();
152
197
  const threadId = dmThreadId(selfId, input.to, input.thread_label);
198
+ const keys = ctx.providers.keys;
199
+
200
+ // ⛔ POPRAWKA 27.09.2026 (niezalezna weryfikacja toru mdm-brama). The first fix seeded the mDM
201
+ // identity from ONE API key and let an agent line (re)publish it. An identity holds MANY keys
202
+ // (general@: 8 active), so the directory flapped between per-key identities and every copy
203
+ // sealed under the previous key stopped opening. The source answer is the King's rule, not a
204
+ // better key: an agent line NEVER uses E2EE (DECYZJE-KROLA 20.09 12:56Z: linie<->linie,
205
+ // linie<->Krol, czlowiek->linia: jawnie). Plaintext is readable by every key of the line and by
206
+ // the recipient's app on every device, and no bundle is needed, so nothing can flap.
207
+ const selfKind = await selfKindOf(dm);
208
+ const peerKind = selfKind === "agent" || input.to === selfId ? selfKind : await peerKindOf(dm, input.to);
209
+ if (selfKind === "agent" || peerKind === "agent") {
210
+ const payload = packPlaintextPayload(input.text);
211
+ ctx.log("debug", "mDM_send plaintext agent lane (rozkaz Krola 20.09)", {
212
+ thread_id: threadId,
213
+ self_kind: selfKind,
214
+ peer_kind: peerKind,
215
+ });
216
+ const plainArgs: DmSendArgsExt = {
217
+ to: input.to,
218
+ threadId,
219
+ payload,
220
+ replyToId: input.reply_to_id,
221
+ messageType: MDM_TEXT_MESSAGE_TYPE,
222
+ };
223
+ const result = await dm.send(plainArgs);
224
+ return {
225
+ message_id: result.id,
226
+ delivered_at: result.deliveredAt,
227
+ thread_id: threadId,
228
+ encrypted: false,
229
+ mode: "plaintext_agent_lane",
230
+ sender_copy: true,
231
+ recipient_copy: true,
232
+ identity: "untouched",
233
+ };
234
+ }
235
+
236
+ // E2EE path (human to human, or a lane that cannot tell kinds). The plaintext is packed into
237
+ // the inner envelope, then SEALED via X3DH + Double Ratchet into an opaque envelope the
238
+ // DmProvider moves without understanding. First contact fetches the peer's published prekey
239
+ // bundle through the same provider (decision "1a").
240
+ //
241
+ // On a PERSON's key MCP writes nothing to the key directory (bundlePolicyForKind: the app owns
242
+ // a human's bundle) and no "s1." self copy: the app opens only copies sealed under its own seed,
243
+ // and an unopenable "s1." makes it state a FALSE reason ("device"/"key") for the bubble. The
244
+ // envelope is typed `text` so the app states the true one: sent by MCP, no copy for this device.
245
+ let identity: OwnBundleState = "foreign";
246
+ try {
247
+ identity = await ensureOwnBundlePublished(keys, dm, selfId, bundlePolicyForKind(selfKind, { explicit: false }));
248
+ } catch (err) {
249
+ // Directory unreachable: the ratchet envelope still carries its own handshake, so the send
250
+ // proceeds; only the recipient copy is skipped (it would be sealed under an unverified identity).
251
+ ctx.log("warn", "mDM_send could not reconcile own prekey bundle", { error: String(err) });
252
+ }
253
+ const ourIdentityIsPublished = identity === "consistent" || identity === "published";
153
254
 
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).
255
+ // reply-linkage jedzie w dm.send({replyToId}) — surowy tekst nie ma koperty, w ktora
256
+ // mozna by go wpakowac (zmiana formatu 2026-08-25, patrz packPlaintextPayload).
156
257
  const inner = packPlaintextPayload(input.text);
157
- const sealed = await encryptForPeer(ctx.providers.keys, dm, input.to, inner);
258
+ const sealed = await encryptForPeer(keys, dm, input.to, inner);
259
+
260
+ // "s1." only where the reader of that copy is MCP itself: never on a human key (see above).
261
+ const selfPayload = selfKind !== "human" && ourIdentityIsPublished ? await sealForSelf(keys, inner) : null;
262
+ let recipientSelfPayload: string | null = null;
263
+ // The recipient opens "r1." with OUR PUBLISHED identity, so it is written only when the
264
+ // directory holds exactly our key. A note-to-self needs none.
265
+ if (ourIdentityIsPublished && input.to !== selfId) {
266
+ try {
267
+ const peer = await fetchVerifiedBundle(dm, input.to);
268
+ if (peer) recipientSelfPayload = await sealForPeerRecoverable(keys, peer, inner);
269
+ } catch (err) {
270
+ ctx.log("warn", "mDM_send skipped the recipient copy", { error: String(err) });
271
+ }
272
+ }
158
273
 
159
- ctx.log("debug", "mDM_send E2EE via DmProvider", { thread_id: threadId, bytes: sealed.byteLength });
274
+ ctx.log("debug", "mDM_send E2EE via DmProvider", {
275
+ thread_id: threadId,
276
+ bytes: sealed.byteLength,
277
+ identity,
278
+ sender_copy: !!selfPayload,
279
+ recipient_copy: !!recipientSelfPayload,
280
+ });
160
281
 
161
- const result = await dm.send({
282
+ const sendArgs: DmSendArgsExt = {
162
283
  to: input.to,
163
284
  threadId,
164
285
  payload: sealed,
165
286
  replyToId: input.reply_to_id,
166
- });
287
+ messageType: MDM_MCP_SEALED_MESSAGE_TYPE,
288
+ selfPayload,
289
+ recipientSelfPayload,
290
+ };
291
+ const result = await dm.send(sendArgs);
167
292
 
168
293
  // Keep a LOCAL copy of our own outgoing plaintext so mDM_list can show it
169
294
  // back to the sender (the ratchet can't re-derive it on read). Best-effort:
170
295
  // only if the keystore offers the optional sent-items cache.
171
- if (ctx.providers.keys.putSentMessage) {
172
- await ctx.providers.keys.putSentMessage(result.id, inner);
296
+ if (keys.putSentMessage) {
297
+ await keys.putSentMessage(result.id, inner);
173
298
  }
174
299
 
175
300
  return {
@@ -177,6 +302,10 @@ async function mDM_send(
177
302
  delivered_at: result.deliveredAt,
178
303
  thread_id: threadId,
179
304
  encrypted: true,
305
+ mode: "e2ee",
306
+ sender_copy: !!selfPayload,
307
+ recipient_copy: !!recipientSelfPayload,
308
+ identity,
180
309
  };
181
310
  }
182
311
 
@@ -197,12 +326,14 @@ async function mDM_send_unencrypted(
197
326
  bytes: payload.byteLength,
198
327
  });
199
328
 
200
- const result = await dm.send({
329
+ const plainArgs: DmSendArgsExt = {
201
330
  to: input.to,
202
331
  threadId,
203
332
  payload,
204
333
  replyToId: input.reply_to_id,
205
- });
334
+ messageType: MDM_TEXT_MESSAGE_TYPE,
335
+ };
336
+ const result = await dm.send(plainArgs);
206
337
 
207
338
  return {
208
339
  message_id: result.id,
@@ -215,12 +346,34 @@ async function mDM_send_unencrypted(
215
346
  async function mDM_publish_keys(
216
347
  _input: Record<string, never>,
217
348
  ctx: MosaddToolContext,
218
- ): Promise<{ published: true; one_time_prekeys: number }> {
349
+ ): Promise<{ published: boolean; identity: OwnBundleState; one_time_prekeys: number; note?: string }> {
219
350
  // Publish the local prekey bundle so peers can start encrypted sessions with
220
351
  // us. Rides the same provider as messages (network row / radio announce).
221
- const { oneTimePrekeyCount } = await publishOwnPrekeys(ctx.providers.keys, ctx.providers.dm);
222
- ctx.log("debug", "mDM_publish_keys", { one_time_prekeys: oneTimePrekeyCount });
223
- return { published: true, one_time_prekeys: oneTimePrekeyCount };
352
+ //
353
+ // ⛔ 27.09.2026: never over a PERSON's app-anchored bundle. The MCP identity is seeded from the
354
+ // API key, the app's from the login secret; replacing the app's bundle breaks every DM to that
355
+ // person on every device (bundlePolicyForKind, explicit). An empty directory may be filled.
356
+ const dm = ctx.providers.dm;
357
+ const keys = ctx.providers.keys;
358
+ const selfId = await dm.selfId();
359
+ const identity = await ensureOwnBundlePublished(
360
+ keys,
361
+ dm,
362
+ selfId,
363
+ bundlePolicyForKind(await selfKindOf(dm), { explicit: true }),
364
+ );
365
+ const { oneTimePrekeys } = await keys.getOwnMaterial();
366
+ ctx.log("debug", "mDM_publish_keys", { identity, one_time_prekeys: oneTimePrekeys.length });
367
+ if (identity === "foreign") {
368
+ return {
369
+ published: false,
370
+ identity,
371
+ one_time_prekeys: 0,
372
+ note:
373
+ "This identity already has keys published by the mosADD app. They were left untouched: replacing them from an API key would make every conversation with you unreadable in the app.",
374
+ };
375
+ }
376
+ return { published: identity === "published", identity, one_time_prekeys: oneTimePrekeys.length };
224
377
  }
225
378
 
226
379
  async function mDM_list(
@@ -246,8 +399,21 @@ async function mDM_list(
246
399
 
247
400
  const result = await dm.list({ threadId, limit: input.limit ?? 50, cursor: input.cursor });
248
401
 
402
+ const keys = ctx.providers.keys;
403
+ // One verified bundle per sender for the "r1." copies (usually just the contact).
404
+ const bundleBySender = new Map<string, Promise<PublicPrekeyBundle | null>>();
405
+ const senderBundle = (id: string) => {
406
+ let p = bundleBySender.get(id);
407
+ if (!p) {
408
+ p = fetchVerifiedBundle(dm, id).catch(() => null);
409
+ bundleBySender.set(id, p);
410
+ }
411
+ return p;
412
+ };
413
+
249
414
  const messages = await Promise.all(
250
- result.messages.map(async (m) => {
415
+ result.messages.map(async (raw) => {
416
+ const m = raw as DmMessageExt;
251
417
  const base = {
252
418
  id: m.id,
253
419
  sender_identity_id: m.senderId,
@@ -258,17 +424,33 @@ async function mDM_list(
258
424
  if (!isE2eeEnvelope(m.payload)) {
259
425
  return { ...base, text: formatVoiceIfAny(unpackPayload(m.payload).text), encrypted: false };
260
426
  }
261
- // Our own outgoing ratchet messages aren't decryptable from our own
262
- // ratchet on read. Recover the plaintext from the local sent-items cache
263
- // (this process). If absent (e.g. a different device/process), fall back
264
- // to a marker instead of failing.
427
+ // Our own outgoing ratchet messages aren't decryptable from our own ratchet on read.
428
+ // 1) the "s1." self copy (any process holding the same key), 2) this process's sent cache,
429
+ // 3) a note-to-self is sealed to our own bundle, so our own key opens it.
265
430
  if (m.senderId === selfId) {
266
- const cached = await ctx.providers.keys.getSentMessage?.(m.id);
267
- if (cached) {
268
- return { ...base, text: formatVoiceIfAny(unpackPayload(cached).text), encrypted: true };
431
+ const own = (await openSelfSealed(keys, m.selfPayload)) ?? (await keys.getSentMessage?.(m.id));
432
+ if (own) {
433
+ return { ...base, text: formatVoiceIfAny(unpackPayload(own).text), encrypted: true };
434
+ }
435
+ if (input.contact_id === selfId) {
436
+ try {
437
+ const inner = await decryptFromPeer(keys, selfId, m.payload);
438
+ return { ...base, text: formatVoiceIfAny(unpackPayload(inner).text), encrypted: true };
439
+ } catch { /* fall through to the marker */ }
269
440
  }
270
441
  return { ...base, text: "<encrypted · sent by you>", encrypted: true };
271
442
  }
443
+ // Recipient side: the sender's "r1." copy, or our own "s1." backfill in the same column
444
+ // (the app writes it after a successful read) — neither needs a live ratchet session.
445
+ if (m.recipientSelfPayload) {
446
+ const bundle = await senderBundle(m.senderId);
447
+ const copy =
448
+ (bundle ? await openPeerRecoverable(keys, bundle, m.recipientSelfPayload) : null) ??
449
+ (await openSelfSealed(keys, m.recipientSelfPayload));
450
+ if (copy) {
451
+ return { ...base, text: formatVoiceIfAny(unpackPayload(copy).text), encrypted: true };
452
+ }
453
+ }
272
454
  try {
273
455
  const inner = await decryptFromPeer(ctx.providers.keys, m.senderId, m.payload);
274
456
  return { ...base, text: formatVoiceIfAny(unpackPayload(inner).text), encrypted: true };
@@ -438,7 +620,7 @@ export const mdmTools: MosaddTool[] = [
438
620
  annotations: { readOnlyHint: false },
439
621
  requires: "any",
440
622
  description:
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.",
623
+ "Send a direct message via mosadd mDM. Between two PEOPLE it is END-TO-END-ENCRYPTED; when either side is an agent line it goes in the clear (mosadd rule: agents must read their DMs), exactly like the mosadd app. 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.",
442
624
  inputSchema: mDM_send_input,
443
625
  handler: mDM_send as MosaddTool["handler"],
444
626
  },