@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
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  import { z } from 'zod';
3
3
  import { DmProvider, VoiceProvider } from '@mosadd/providers';
4
- import { RatchetState, SessionRole } from '@mosadd/crypto';
4
+ import { RatchetState, DhRatchetState, SessionRole } from '@mosadd/crypto';
5
5
 
6
6
  /**
7
7
  * mDM end-to-end encryption — session layer (LINEAR-2357).
@@ -53,9 +53,14 @@ interface OwnPrekeyMaterial {
53
53
  pair: X25519Pair;
54
54
  }>;
55
55
  }
56
- /** Persisted per-peer ratchet session. Plain data → trivially serializable. */
56
+ /**
57
+ * Persisted per-peer ratchet session. Plain data → trivially serializable.
58
+ * A session is either v1 (`ratchet`, symmetric) or v2 (`ratchet2`, DH ratchet /
59
+ * PCS). New sessions are v2; an existing v1 session keeps running v1.
60
+ */
57
61
  interface MdmSessionRecord {
58
- ratchet: RatchetState;
62
+ ratchet?: RatchetState;
63
+ ratchet2?: DhRatchetState;
59
64
  role: SessionRole;
60
65
  /** Handshake header still owed to the peer (initiator only, until first send). */
61
66
  pendingHandshake?: {
@@ -131,6 +136,15 @@ interface MosaddServerOptions {
131
136
  * network adapter. A carrier-aware host supplies e.g. a radio DmProvider here.
132
137
  */
133
138
  providers?: Partial<ProviderRegistry>;
139
+ /**
140
+ * When true, publish this identity's mDM prekey bundle once on startup
141
+ * (best-effort, non-fatal) so peers can open an E2EE session without the user
142
+ * manually running mDM_publish_keys first. Fixes the cold-start where mDM_send
143
+ * fails for every recipient because nobody has published keys. Used by the
144
+ * stdio binary; the hosted per-request transport leaves this off (it publishes
145
+ * per authenticated session instead).
146
+ */
147
+ autoPublishKeys?: boolean;
134
148
  }
135
149
  interface MosaddToolContext {
136
150
  options: Required<Pick<MosaddServerOptions, "mode" | "hubUrl">> & MosaddServerOptions;
@@ -153,11 +167,37 @@ interface MosaddToolContext {
153
167
  * join links, bridges). NOT available off-grid.
154
168
  */
155
169
  type CapabilityRequirement = "any" | "radio" | "network";
170
+ /**
171
+ * MCP tool annotations (spec `ToolAnnotations`, minus `title` which lives on the
172
+ * tool itself). Connector UIs — Claude's included — group and gate tools by these
173
+ * hints: `readOnlyHint: true` lands the tool in the read-only bucket (bulk-approvable),
174
+ * `destructiveHint: true` marks it as destroying/overwriting user data at approval
175
+ * time, and tools with NO annotations all fall into one flat "Other tools" bucket —
176
+ * which is exactly how the mosADD connector looked until 2026-08-26 (84 tools, one
177
+ * undifferentiated list; founder order: fix it).
178
+ */
179
+ interface MosaddToolAnnotations {
180
+ /** Tool does not mutate anything. list/get/search/state/metrics class. */
181
+ readOnlyHint?: boolean;
182
+ /** Tool destroys or irreversibly overwrites data (delete/ban/revoke/edit-in-place). */
183
+ destructiveHint?: boolean;
184
+ /** Calling twice with the same args has no additional effect. */
185
+ idempotentHint?: boolean;
186
+ /** Tool reaches outside the mosADD closed world (e.g. sends external email). */
187
+ openWorldHint?: boolean;
188
+ }
156
189
  interface MosaddTool<TInput = unknown, TOutput = unknown> {
157
190
  /** Tool name. MUST follow the m{MODULE}_{operation} convention. */
158
191
  name: string;
192
+ /**
193
+ * Human title for connector UIs (e.g. "Send encrypted DM"). The `name` stays the
194
+ * model-facing handle; this is what a PERSON sees in the permissions list.
195
+ */
196
+ title?: string;
159
197
  /** Short human-readable description. Shown to the model. */
160
198
  description: string;
199
+ /** MCP annotations; see MosaddToolAnnotations. Every registered tool SHOULD set them. */
200
+ annotations?: MosaddToolAnnotations;
161
201
  /**
162
202
  * Transport this tool requires. Consuming hosts read this to gate tools by
163
203
  * available carriers. Every tool MUST declare it explicitly.
@@ -186,10 +226,79 @@ declare function createMosaddServer(options?: MosaddServerOptions): McpServer;
186
226
  /**
187
227
  * Tool registry. Each m* module contributes a set of tools.
188
228
  *
189
- * Phase 1 MVP (shipped): mDM, mIRC, mROOM, mAIL.
190
- * Phase 1 full: + mTALK, mCALL, mIRL, plus bridges (mMATRIX, mDISCORD, mTELEGRAM, mSLACK, mSIGNAL).
229
+ * User-facing modules (4): mDM, mIRC, mURL, mAYL — the re-arch (LINEAR-3938)
230
+ * mAYL replaces the old mp0st name (mp0st_* still registered as back-compat
231
+ * aliases via mail-aliases.ts; will be removed in a later alpha).
232
+ *
233
+ * Capabilities (not modules — cross-cutting agent tooling): mRAG, comms_.
234
+ * mTALK = voice tier inside mIRC, still its own tools for now; folding into
235
+ * mIRC_voice_* in a follow-up release. threat_* (threat_catalog + threat_classify)
236
+ * are REGISTERED (2026-07-15, founder directive + LINEAR-3498): pure/offline
237
+ * defensive classification over the threat taxonomy — the surveillance-era
238
+ * *marketing* was killed, the classification engine is real and wanted.
239
+ *
240
+ * 84 callable tools registered — the exact live count is exported as TOOL_COUNT
241
+ * (= allTools.length) below; ALWAYS reference that, never re-hard-code a number that drifts.
242
+ * Breakdown (2026-08-17, measured from a live tools/list on the built server):
243
+ * modules mDM 16 · mIRC 24 · mURL 7 · mAYL 16 = 63; capabilities mTALK 6 · mRAG 8 ·
244
+ * comms 5 (action_create/action_frame_get/embed_create/capabilities/session_attach) · Irondome/threat 2
245
+ * = 21. 63 + 21 = 84. (mDM 16 = 14 + mDM_send_as_agent/mDM_list_my_agents added 2026-08-17: an MCP key
246
+ * is bound to a USER, so an agent runtime wired up with its owner's key spoke AS THE OWNER — these
247
+ * let it speak as an agent it OWNS instead, checked server-side. mRAG 8 = 4 search/ingest + 4 mRAG_graph_* traversal tools added 2026-08-11.
248
+ * comms_session_attach added 2026-08-14: a live agent session claims the account's reply lane so
249
+ * the cloud stand-in defers to it — the front door that used to be a script on one PC.)
250
+ * (History of this line drifting: the 2026-07-17 breakdown ended "= 69"
251
+ * — wrong twice over, its own terms summed to 71; the 07-30 rewrite said 73 and still had
252
+ * mAYL at 12 after mAYL_send_as_agent had been re-registered, so it stayed wrong through the
253
+ * four mAYL_agentbox_* tools landing on 08-06. Arithmetic in comments drifts; TOOL_COUNT
254
+ * doesn't — and since 08-11 the anti-drift gate checks the PER-MODULE numbers too, not just
255
+ * the total, so this comment cannot rot alone any more.)
256
+ * (mDM/mIRC each include their 2 attachment tools from attachments.ts.)
257
+ * Modules (4): mDM, mIRC, mURL, mAYL. Capabilities: mTALK (voice/PTT), mRAG, comms_, Irondome (threat_*).
258
+ * mp0st_* stay as DEPRECATED back-compat aliases for mAYL_* (removed in a later alpha).
259
+ * mAYL_send_as_agent + mTALK_ingest_ptt were RE-REGISTERED 2026-07-29: both had been disabled
260
+ * on 07-14 notes that had since become false, and both were re-verified on authenticated calls.
261
+ * comms_embed_create RE-REGISTERED 2026-07-17 (embed.mosadd.com/v1.js live — P3 of mURL→mIRC).
262
+ * mROOM was KILLED (LINEAR-3414, channel re-cut → ephemeral private mIRC): its tools
263
+ * live in tools/mroom.ts + mroom-messages.ts but are NOT registered here.
264
+ * Plus action links: comms_action_create (agent → user one-link browser action,
265
+ * incl. screen_share) + comms_action_frame_get (see the recipient's shared screen).
266
+ * mURL is a FULL registered dev module (revived, founder 2026-06-27) — IRC-for-URLs,
267
+ * agent-native; backends live (mosadd-edge + murl-channels EF). tools/murl.ts.
268
+ * mURL now has full lifecycle: read/post/presence/list_channels (hub-key) PLUS owner-side
269
+ * create/claim + update(branding/status) + delete (mURL_create/update/delete → murl-manage
270
+ * EF, owner-scoped via user JWT — same auth as mURL_list_channels action='mine').
271
+ * mCALL is carrier-pending (no telephony carrier live yet): its tools live in
272
+ * tools/mcall.ts but are NOT registered here, so an agent only ever discovers
273
+ * tools that actually work. Re-register the one line below when a carrier ships.
191
274
  */
192
275
 
193
276
  declare const allTools: MosaddTool[];
277
+ /**
278
+ * The exact, live number of callable tools this server registers. Reference THIS
279
+ * (import { TOOL_COUNT }) in any code/doc surface that shows a tool count, instead
280
+ * of hard-coding a number that silently drifts (the "70+/65/68" inconsistency that
281
+ * bit us). Mirrors @mosadd/threat-engine's THREAT_EVENT_COUNT pattern.
282
+ */
283
+ declare const TOOL_COUNT: number;
284
+
285
+ /**
286
+ * Supabase provider for the alpha MCP server.
287
+ *
288
+ * Local BYOK mode: user supplies their own Supabase URL + anon key + user JWT
289
+ * via env vars. The MCP server creates a per-request Supabase client and
290
+ * invokes the mosadd Edge Functions on the user's behalf.
291
+ *
292
+ * In Phase 2 this is replaced by the hosted gateway (mcp.mosadd.com) which
293
+ * holds keys server-side via the BYOK broker.
294
+ */
295
+
296
+ interface SupabaseEnv {
297
+ url: string;
298
+ anonKey: string;
299
+ userJwt?: string;
300
+ }
301
+ /** Run `fn` (and every tool call it triggers) with a per-request Supabase session. */
302
+ declare function runWithSupabaseEnv<T>(env: SupabaseEnv, fn: () => T): T;
194
303
 
195
- export { type MosaddServerOptions, type MosaddTool, type MosaddToolContext, type ProviderRegistry, allTools, createMosaddServer, defaultProviders };
304
+ export { type MosaddServerOptions, type MosaddTool, type MosaddToolContext, type ProviderRegistry, type SupabaseEnv, TOOL_COUNT, allTools, createMosaddServer, defaultProviders, runWithSupabaseEnv };
package/dist/index.js CHANGED
@@ -1,11 +1,15 @@
1
1
  import {
2
+ TOOL_COUNT,
2
3
  allTools,
3
4
  createMosaddServer,
4
- defaultProviders
5
- } from "./chunk-YDFU6S5E.js";
5
+ defaultProviders,
6
+ runWithSupabaseEnv
7
+ } from "./chunk-SS6UVKSB.js";
6
8
  import "./chunk-Z7WR52GE.js";
7
9
  export {
10
+ TOOL_COUNT,
8
11
  allTools,
9
12
  createMosaddServer,
10
- defaultProviders
13
+ defaultProviders,
14
+ runWithSupabaseEnv
11
15
  };
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "@mosadd/mcp",
3
- "version": "3.0.0-alpha.4",
4
- "description": "Model Context Protocol server for mosadd. Exposes m* OS modules (mDM, mTALK, mAIL, mCALL, mIRC, mIRL, mROOM, and bridges) as MCP tools to any agent runtime (Claude Code, Cursor, Windsurf, Cline, ChatGPT Apps, Lovable, Bolt, Goose, Manus, custom).",
3
+ "version": "3.0.0-alpha.41",
4
+ "mcpName": "io.github.hei33enberg/mosadd-mcp",
5
+ "description": "Model Context Protocol server for mosadd. Exposes 4 modules (mDM, mIRC, mURL, mAYL) and capabilities (mTALK, mRAG) plus comms agent-actions — 84 tools — to any agent runtime (Claude Code, Cursor, Windsurf, Cline, ChatGPT Apps, Lovable, Bolt, Goose, Manus, custom).",
5
6
  "homepage": "https://github.com/Hei33enberg/mosADD-OS/tree/main/packages/mcp",
6
7
  "repository": {
7
8
  "type": "git",
@@ -27,6 +28,7 @@
27
28
  "dist",
28
29
  "src",
29
30
  "README.md",
31
+ "CHANGELOG.md",
30
32
  "LICENSE"
31
33
  ],
32
34
  "publishConfig": {
@@ -36,9 +38,10 @@
36
38
  "@modelcontextprotocol/sdk": "^1.0.4",
37
39
  "@supabase/supabase-js": "^2.48.0",
38
40
  "zod": "^4.3.6",
39
- "@mosadd/crypto": "3.0.0-alpha.4",
40
- "@mosadd/protocol": "3.0.0-alpha.4",
41
- "@mosadd/providers": "3.0.0-alpha.4"
41
+ "@mosadd/providers": "3.0.0-alpha.27",
42
+ "@mosadd/crypto": "3.0.0-alpha.27",
43
+ "@mosadd/threat-engine": "3.0.0-alpha.28",
44
+ "@mosadd/protocol": "3.0.0-alpha.28"
42
45
  },
43
46
  "devDependencies": {
44
47
  "tsup": "^8.3.5",
@@ -1,137 +1,139 @@
1
- /**
2
- * Golden-path E2E: the day-1 "done" bar for the provider-abstraction seam.
3
- *
4
- * Proves a carrier-aware HOST (e.g. cymru-os) can inject its own transport
5
- * under mDM without mosadd-os knowing anything about that transport:
6
- * 1. host learns capabilities (comms_capabilities) and sees mDM_send = "any"
7
- * (usable off-grid over radio),
8
- * 2. host injects a fake RadioProvider,
9
- * 3. agent calls mDM_send,
10
- * 4. the opaque payload bytes actually arrive at the injected provider,
11
- * 5. they round-trip back out via mDM_list.
12
- *
13
- * This is the "is it sp, not just written" check the whole 2144 task hinges on.
14
- */
15
-
16
- import { describe, expect, it } from "vitest";
17
- import type {
18
- DmProvider,
19
- DmSendArgs,
20
- DmListArgs,
21
- DmSendResult,
22
- DmListResult,
23
- } from "@mosadd/providers";
24
- import { mdmTools } from "../tools/mdm.js";
25
- import { makeCapabilitiesTool } from "../tools/capabilities.js";
26
- import { allTools } from "../tools/index.js";
27
- import { createMosaddServer } from "../server.js";
28
- import { InMemoryMdmKeyStore } from "../crypto/mdm-session.js";
29
- import { InMemoryVoiceProvider } from "../providers/memory-voice.js";
30
- import type { MosaddToolContext, ProviderRegistry } from "../types.js";
31
-
32
- /** Stand-in for a host-supplied radio transport: captures the bytes it's asked
33
- * to send, and replays them on list — i.e. "the message reached the link". */
34
- class FakeRadioDmProvider implements DmProvider {
35
- public readonly sent: DmSendArgs[] = [];
36
- private bundle: Uint8Array | null = null;
37
- async selfId(): Promise<string> {
38
- return "radio:self-callsign";
39
- }
40
- async send(args: DmSendArgs): Promise<DmSendResult> {
41
- this.sent.push(args);
42
- return { id: `radio-${this.sent.length}`, deliveredAt: new Date(0).toISOString() };
43
- }
44
- async list(args: DmListArgs): Promise<DmListResult> {
45
- return {
46
- messages: this.sent
47
- .filter((s) => s.threadId === args.threadId)
48
- .map((s, i) => ({
49
- id: `radio-${i + 1}`,
50
- senderId: "radio:self-callsign",
51
- payload: s.payload,
52
- timestamp: new Date(0).toISOString(),
53
- threadId: s.threadId,
54
- })),
55
- nextCursor: null,
56
- };
57
- }
58
- async publishPrekeyBundle(bundle: Uint8Array): Promise<void> {
59
- this.bundle = bundle;
60
- }
61
- async fetchPrekeyBundle(): Promise<Uint8Array | null> {
62
- return this.bundle;
63
- }
64
- }
65
-
66
- function makeCtx(providers: { dm: DmProvider; keys?: ProviderRegistry["keys"] }): MosaddToolContext {
67
- return {
68
- options: { mode: "local", hubUrl: "https://mcp.mosadd.com" },
69
- providers: {
70
- dm: providers.dm,
71
- keys: providers.keys ?? new InMemoryMdmKeyStore(),
72
- voice: new InMemoryVoiceProvider("radio:self-callsign"),
73
- },
74
- log: () => {},
75
- };
76
- }
77
-
78
- const getTool = (name: string) => {
79
- const t = mdmTools.find((x) => x.name === name);
80
- if (!t) throw new Error(`tool ${name} not found`);
81
- return t;
82
- };
83
-
84
- describe("golden path — host injects transport under mDM", () => {
85
- it("step 1: comms_capabilities reports mDM_send usable over any carrier", async () => {
86
- const capTool = makeCapabilitiesTool(allTools);
87
- const manifest = (await capTool.handler({}, makeCtx({ dm: new FakeRadioDmProvider() }))) as {
88
- by_requirement: Record<string, string[]>;
89
- };
90
- expect(manifest.by_requirement.any).toContain("mDM_send");
91
- });
92
-
93
- it("steps 2-4: the deprecated plaintext path delivers opaque bytes to the injected provider", async () => {
94
- // This proves the TRANSPORT seam (2144): mDM_send_unencrypted packs a
95
- // plaintext envelope and the bytes reach the injected provider verbatim.
96
- // (mDM_send is now E2EE — its own round-trip is covered in mdm-e2ee.test.ts.)
97
- const radio = new FakeRadioDmProvider();
98
- const ctx = makeCtx({ dm: radio });
99
-
100
- const send = getTool("mDM_send_unencrypted");
101
- const result = (await send.handler(
102
- { to: "bob-callsign", text: "rendezvous at grid 4471, 0600" },
103
- ctx,
104
- )) as { message_id: string; thread_id: string };
105
-
106
- // The bytes actually reached the transport.
107
- expect(radio.sent).toHaveLength(1);
108
- expect(radio.sent[0]!.to).toBe("bob-callsign");
109
- expect(radio.sent[0]!.payload).toBeInstanceOf(Uint8Array);
110
- expect(radio.sent[0]!.payload.byteLength).toBeGreaterThan(0);
111
- expect(result.message_id).toBe("radio-1");
112
-
113
- // The payload is opaque to the provider but carries our text under the hood.
114
- const decoded = JSON.parse(Buffer.from(radio.sent[0]!.payload).toString("utf8"));
115
- expect(decoded.text).toBe("rendezvous at grid 4471, 0600");
116
- });
117
-
118
- it("step 5: mDM_list round-trips the message back through the same provider", async () => {
119
- const radio = new FakeRadioDmProvider();
120
- const ctx = makeCtx({ dm: radio });
121
-
122
- await getTool("mDM_send_unencrypted").handler({ to: "bob-callsign", text: "ack" }, ctx);
123
- const listed = (await getTool("mDM_list").handler({ contact_id: "bob-callsign" }, ctx)) as {
124
- messages: Array<{ text: string }>;
125
- };
126
-
127
- expect(listed.messages).toHaveLength(1);
128
- expect(listed.messages[0]!.text).toBe("ack");
129
- });
130
-
131
- it("default server wires a DmProvider without a host override (no throw)", () => {
132
- // Network default path: constructing the server must not require a host to
133
- // inject anything (it falls back to the Supabase adapter).
134
- expect(() => createMosaddServer()).not.toThrow();
135
- expect(() => createMosaddServer({ providers: { dm: new FakeRadioDmProvider() } })).not.toThrow();
136
- });
137
- });
1
+ /**
2
+ * Golden-path E2E: the day-1 "done" bar for the provider-abstraction seam.
3
+ *
4
+ * Proves a carrier-aware HOST (e.g. cymru-os) can inject its own transport
5
+ * under mDM without mosadd-os knowing anything about that transport:
6
+ * 1. host learns capabilities (comms_capabilities) and sees mDM_send = "any"
7
+ * (usable off-grid over radio),
8
+ * 2. host injects a fake RadioProvider,
9
+ * 3. agent calls mDM_send,
10
+ * 4. the opaque payload bytes actually arrive at the injected provider,
11
+ * 5. they round-trip back out via mDM_list.
12
+ *
13
+ * This is the "is it sp, not just written" check the whole 2144 task hinges on.
14
+ */
15
+
16
+ import { describe, expect, it } from "vitest";
17
+ import type {
18
+ DmProvider,
19
+ DmSendArgs,
20
+ DmListArgs,
21
+ DmSendResult,
22
+ DmListResult,
23
+ } from "@mosadd/providers";
24
+ import { mdmTools } from "../tools/mdm.js";
25
+ import { makeCapabilitiesTool } from "../tools/capabilities.js";
26
+ import { allTools } from "../tools/index.js";
27
+ import { createMosaddServer } from "../server.js";
28
+ import { InMemoryMdmKeyStore } from "../crypto/mdm-session.js";
29
+ import { InMemoryVoiceProvider } from "../providers/memory-voice.js";
30
+ import type { MosaddToolContext, ProviderRegistry } from "../types.js";
31
+
32
+ /** Stand-in for a host-supplied radio transport: captures the bytes it's asked
33
+ * to send, and replays them on list — i.e. "the message reached the link". */
34
+ class FakeRadioDmProvider implements DmProvider {
35
+ public readonly sent: DmSendArgs[] = [];
36
+ private bundle: Uint8Array | null = null;
37
+ async selfId(): Promise<string> {
38
+ return "radio:self-callsign";
39
+ }
40
+ async send(args: DmSendArgs): Promise<DmSendResult> {
41
+ this.sent.push(args);
42
+ return { id: `radio-${this.sent.length}`, deliveredAt: new Date(0).toISOString() };
43
+ }
44
+ async list(args: DmListArgs): Promise<DmListResult> {
45
+ return {
46
+ messages: this.sent
47
+ .filter((s) => s.threadId === args.threadId)
48
+ .map((s, i) => ({
49
+ id: `radio-${i + 1}`,
50
+ senderId: "radio:self-callsign",
51
+ payload: s.payload,
52
+ timestamp: new Date(0).toISOString(),
53
+ threadId: s.threadId,
54
+ })),
55
+ nextCursor: null,
56
+ };
57
+ }
58
+ async publishPrekeyBundle(bundle: Uint8Array): Promise<void> {
59
+ this.bundle = bundle;
60
+ }
61
+ async fetchPrekeyBundle(): Promise<Uint8Array | null> {
62
+ return this.bundle;
63
+ }
64
+ }
65
+
66
+ function makeCtx(providers: { dm: DmProvider; keys?: ProviderRegistry["keys"] }): MosaddToolContext {
67
+ return {
68
+ options: { mode: "local", hubUrl: "https://mcp.mosadd.com" },
69
+ providers: {
70
+ dm: providers.dm,
71
+ keys: providers.keys ?? new InMemoryMdmKeyStore(),
72
+ voice: new InMemoryVoiceProvider("radio:self-callsign"),
73
+ },
74
+ log: () => {},
75
+ };
76
+ }
77
+
78
+ const getTool = (name: string) => {
79
+ const t = mdmTools.find((x) => x.name === name);
80
+ if (!t) throw new Error(`tool ${name} not found`);
81
+ return t;
82
+ };
83
+
84
+ describe("golden path — host injects transport under mDM", () => {
85
+ it("step 1: comms_capabilities reports mDM_send usable over any carrier", async () => {
86
+ const capTool = makeCapabilitiesTool(allTools);
87
+ const manifest = (await capTool.handler({}, makeCtx({ dm: new FakeRadioDmProvider() }))) as {
88
+ by_requirement: Record<string, string[]>;
89
+ };
90
+ expect(manifest.by_requirement.any).toContain("mDM_send");
91
+ });
92
+
93
+ it("steps 2-4: the deprecated plaintext path delivers opaque bytes to the injected provider", async () => {
94
+ // This proves the TRANSPORT seam (2144): mDM_send_unencrypted packs a
95
+ // plaintext envelope and the bytes reach the injected provider verbatim.
96
+ // (mDM_send is now E2EE — its own round-trip is covered in mdm-e2ee.test.ts.)
97
+ const radio = new FakeRadioDmProvider();
98
+ const ctx = makeCtx({ dm: radio });
99
+
100
+ const send = getTool("mDM_send_unencrypted");
101
+ const result = (await send.handler(
102
+ { to: "bob-callsign", text: "rendezvous at grid 4471, 0600" },
103
+ ctx,
104
+ )) as { message_id: string; thread_id: string };
105
+
106
+ // The bytes actually reached the transport.
107
+ expect(radio.sent).toHaveLength(1);
108
+ expect(radio.sent[0]!.to).toBe("bob-callsign");
109
+ expect(radio.sent[0]!.payload).toBeInstanceOf(Uint8Array);
110
+ expect(radio.sent[0]!.payload.byteLength).toBeGreaterThan(0);
111
+ expect(result.message_id).toBe("radio-1");
112
+
113
+ // The payload is opaque to the provider but carries our text under the hood.
114
+ // 2026-08-25: plaintext lane is RAW utf8 text (native app format), not a JSON
115
+ // envelope — packPlaintextPayload change, unpack tolerates both shapes.
116
+ const decoded = Buffer.from(radio.sent[0]!.payload).toString("utf8");
117
+ expect(decoded).toBe("rendezvous at grid 4471, 0600");
118
+ });
119
+
120
+ it("step 5: mDM_list round-trips the message back through the same provider", async () => {
121
+ const radio = new FakeRadioDmProvider();
122
+ const ctx = makeCtx({ dm: radio });
123
+
124
+ await getTool("mDM_send_unencrypted").handler({ to: "bob-callsign", text: "ack" }, ctx);
125
+ const listed = (await getTool("mDM_list").handler({ contact_id: "bob-callsign" }, ctx)) as {
126
+ messages: Array<{ text: string }>;
127
+ };
128
+
129
+ expect(listed.messages).toHaveLength(1);
130
+ expect(listed.messages[0]!.text).toBe("ack");
131
+ });
132
+
133
+ it("default server wires a DmProvider without a host override (no throw)", () => {
134
+ // Network default path: constructing the server must not require a host to
135
+ // inject anything (it falls back to the Supabase adapter).
136
+ expect(() => createMosaddServer()).not.toThrow();
137
+ expect(() => createMosaddServer({ providers: { dm: new FakeRadioDmProvider() } })).not.toThrow();
138
+ });
139
+ });