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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +309 -0
  2. package/LICENSE +201 -201
  3. package/README.md +150 -126
  4. package/dist/bin/mcp.js +42 -3
  5. package/dist/chunk-BTAIZKYT.js +3800 -0
  6. package/dist/index.d.ts +118 -5
  7. package/dist/index.js +7 -3
  8. package/package.json +10 -7
  9. package/src/__tests__/channel-e2ee.test.ts +62 -0
  10. package/src/__tests__/golden-path.test.ts +139 -137
  11. package/src/__tests__/integration.test.ts +182 -178
  12. package/src/__tests__/knowledge-ingest.test.ts +114 -0
  13. package/src/__tests__/mdm-e2ee.test.ts +212 -178
  14. package/src/__tests__/mirc-invite.test.ts +112 -0
  15. package/src/__tests__/mtalk.test.ts +122 -122
  16. package/src/__tests__/presence.test.ts +199 -0
  17. package/src/__tests__/server.test.ts +71 -67
  18. package/src/__tests__/serverJsonVersion.test.ts +45 -0
  19. package/src/__tests__/tool-count-consistency.test.ts +199 -0
  20. package/src/bin/login.ts +138 -138
  21. package/src/bin/mcp.ts +145 -97
  22. package/src/config.ts +66 -66
  23. package/src/crypto/channel-e2ee.ts +288 -0
  24. package/src/crypto/mdm-session.ts +502 -403
  25. package/src/index.ts +19 -17
  26. package/src/observability/sentry.ts +79 -79
  27. package/src/providers/blob-upload.ts +116 -0
  28. package/src/providers/memory-voice.ts +79 -79
  29. package/src/providers/supabase-dm.ts +122 -117
  30. package/src/providers/supabase-voice.ts +91 -91
  31. package/src/providers/supabase.ts +231 -96
  32. package/src/server.ts +162 -105
  33. package/src/tools/__tests__/ragDeleteFoldsSourceId.test.ts +67 -0
  34. package/src/tools/actions.ts +166 -0
  35. package/src/tools/attachments.ts +276 -0
  36. package/src/tools/capabilities.ts +70 -68
  37. package/src/tools/embed.ts +110 -0
  38. package/src/tools/index.ts +181 -51
  39. package/src/tools/knowledge-graph.ts +186 -0
  40. package/src/tools/knowledge.ts +344 -132
  41. package/src/tools/mail-agentbox.ts +155 -0
  42. package/src/tools/mail-aliases.ts +25 -0
  43. package/src/tools/mail-provenance.ts +137 -0
  44. package/src/tools/mail.ts +403 -157
  45. package/src/tools/mcall.ts +216 -216
  46. package/src/tools/mdm-as-agent.ts +126 -0
  47. package/src/tools/mdm-voice.ts +220 -206
  48. package/src/tools/mdm.ts +73 -26
  49. package/src/tools/mirc-edge.ts +196 -190
  50. package/src/tools/mirc-members.ts +287 -177
  51. package/src/tools/mirc-messages.ts +76 -27
  52. package/src/tools/mirc.ts +308 -170
  53. package/src/tools/mroom-messages.ts +142 -142
  54. package/src/tools/mroom.ts +221 -221
  55. package/src/tools/mtalk.ts +131 -121
  56. package/src/tools/murl.ts +314 -0
  57. package/src/tools/presence.ts +442 -0
  58. package/src/tools/ptt-ingest.ts +99 -0
  59. package/src/tools/threat.ts +123 -0
  60. package/src/tools/voice-format.ts +28 -0
  61. package/src/types.ts +121 -85
  62. package/src/version.ts +8 -0
  63. package/src/voice/floor.ts +132 -132
  64. package/dist/chunk-4C36JDTJ.js +0 -1836
package/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,12 +226,85 @@ declare function createMosaddServer(options?: MosaddServerOptions): McpServer;
186
226
  /**
187
227
  * Tool registry. Each m* module contributes a set of tools.
188
228
  *
189
- * Live modules (6): mDM, mIRC, mROOM, mTALK, mAIL, mRAG — 52 tools + comms_capabilities.
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
+ * 85 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-09-03, from allTools in this tree; the live tools/list on mcp.mosadd.com catches up
243
+ * when the alpha carrying mIRC_invite is published and the gateway redeployed):
244
+ * modules mDM 16 · mIRC 25 · mURL 7 · mAYL 16 = 64; capabilities mTALK 6 · mRAG 8 ·
245
+ * comms 5 (action_create/action_frame_get/embed_create/capabilities/session_attach) · Irondome/threat 2
246
+ * = 21. 64 + 21 = 85. (mIRC 25 = 24 + mIRC_invite added 2026-09-03 (LINEAR-5870): mIRC_join adds the KEY's
247
+ * identity while channel posts are signed by the AGENT, so every channel created from the toolkit was mute
248
+ * until its agent was added from the app — mIRC_invite wraps channel-members-manage `invite`: own agent →
249
+ * auto_joined, anyone else → invite code. mDM 16 = 14 + mDM_send_as_agent/mDM_list_my_agents added 2026-08-17: an MCP key
250
+ * is bound to a USER, so an agent runtime wired up with its owner's key spoke AS THE OWNER — these
251
+ * 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.
252
+ * comms_session_attach added 2026-08-14: a live agent session claims the account's reply lane so
253
+ * the cloud stand-in defers to it — the front door that used to be a script on one PC.)
254
+ * (History of this line drifting: the 2026-07-17 breakdown ended "= 69"
255
+ * — wrong twice over, its own terms summed to 71; the 07-30 rewrite said 73 and still had
256
+ * mAYL at 12 after mAYL_send_as_agent had been re-registered, so it stayed wrong through the
257
+ * four mAYL_agentbox_* tools landing on 08-06. Arithmetic in comments drifts; TOOL_COUNT
258
+ * doesn't — and since 08-11 the anti-drift gate checks the PER-MODULE numbers too, not just
259
+ * the total, so this comment cannot rot alone any more.)
260
+ * (mDM/mIRC each include their 2 attachment tools from attachments.ts.)
261
+ * Modules (4): mDM, mIRC, mURL, mAYL. Capabilities: mTALK (voice/PTT), mRAG, comms_, Irondome (threat_*).
262
+ * mp0st_* stay as DEPRECATED back-compat aliases for mAYL_* (removed in a later alpha).
263
+ * mAYL_send_as_agent + mTALK_ingest_ptt were RE-REGISTERED 2026-07-29: both had been disabled
264
+ * on 07-14 notes that had since become false, and both were re-verified on authenticated calls.
265
+ * comms_embed_create RE-REGISTERED 2026-07-17 (embed.mosadd.com/v1.js live — P3 of mURL→mIRC).
266
+ * mROOM was KILLED (LINEAR-3414, channel re-cut → ephemeral private mIRC): its tools
267
+ * live in tools/mroom.ts + mroom-messages.ts but are NOT registered here.
268
+ * Plus action links: comms_action_create (agent → user one-link browser action,
269
+ * incl. screen_share) + comms_action_frame_get (see the recipient's shared screen).
270
+ * mURL is a FULL registered dev module (revived, founder 2026-06-27) — IRC-for-URLs,
271
+ * agent-native; backends live (mosadd-edge + murl-channels EF). tools/murl.ts.
272
+ * mURL now has full lifecycle: read/post/presence/list_channels (hub-key) PLUS owner-side
273
+ * create/claim + update(branding/status) + delete (mURL_create/update/delete → murl-manage
274
+ * EF, owner-scoped via user JWT — same auth as mURL_list_channels action='mine').
190
275
  * mCALL is carrier-pending (no telephony carrier live yet): its tools live in
191
276
  * tools/mcall.ts but are NOT registered here, so an agent only ever discovers
192
277
  * tools that actually work. Re-register the one line below when a carrier ships.
193
278
  */
194
279
 
195
280
  declare const allTools: MosaddTool[];
281
+ /**
282
+ * The exact, live number of callable tools this server registers. Reference THIS
283
+ * (import { TOOL_COUNT }) in any code/doc surface that shows a tool count, instead
284
+ * of hard-coding a number that silently drifts (the "70+/65/68" inconsistency that
285
+ * bit us). Mirrors @mosadd/threat-engine's THREAT_EVENT_COUNT pattern.
286
+ */
287
+ declare const TOOL_COUNT: number;
288
+
289
+ /**
290
+ * Supabase provider for the alpha MCP server.
291
+ *
292
+ * Local BYOK mode: user supplies their own Supabase URL + anon key + user JWT
293
+ * via env vars. The MCP server creates a per-request Supabase client and
294
+ * invokes the mosadd Edge Functions on the user's behalf.
295
+ *
296
+ * In Phase 2 this is replaced by the hosted gateway (mcp.mosadd.com) which
297
+ * holds keys server-side via the BYOK broker.
298
+ */
299
+
300
+ interface SupabaseEnv {
301
+ url: string;
302
+ anonKey: string;
303
+ userJwt?: string;
304
+ /** Stabilna tożsamość sesji dla bramy hostowanej (per klucz API) — patrz sessionId(). */
305
+ sessionKey?: string;
306
+ }
307
+ /** Run `fn` (and every tool call it triggers) with a per-request Supabase session. */
308
+ declare function runWithSupabaseEnv<T>(env: SupabaseEnv, fn: () => T): T;
196
309
 
197
- export { type MosaddServerOptions, type MosaddTool, type MosaddToolContext, type ProviderRegistry, allTools, createMosaddServer, defaultProviders };
310
+ 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-4C36JDTJ.js";
5
+ defaultProviders,
6
+ runWithSupabaseEnv
7
+ } from "./chunk-BTAIZKYT.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,11 +1,12 @@
1
1
  {
2
2
  "name": "@mosadd/mcp",
3
- "version": "3.0.0-alpha.5",
4
- "description": "Model Context Protocol server for mosadd. Exposes the 6 live m* modules (mDM, mIRC, mROOM, mTALK, mAIL, mRAG) — 52 tools — to any agent runtime (Claude Code, Cursor, Windsurf, Cline, ChatGPT Apps, Lovable, Bolt, Goose, Manus, custom).",
5
- "homepage": "https://github.com/Hei33enberg/mosadd-os/tree/main/packages/mcp",
3
+ "version": "3.0.0-alpha.51",
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 — 85 tools — to any agent runtime (Claude Code, Cursor, Windsurf, Cline, ChatGPT Apps, Lovable, Bolt, Goose, Manus, custom).",
6
+ "homepage": "https://github.com/Hei33enberg/mosADD-OS/tree/main/packages/mcp",
6
7
  "repository": {
7
8
  "type": "git",
8
- "url": "https://github.com/Hei33enberg/mosadd-os.git",
9
+ "url": "https://github.com/Hei33enberg/mosADD-OS.git",
9
10
  "directory": "packages/mcp"
10
11
  },
11
12
  "license": "Apache-2.0",
@@ -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/providers": "3.0.0-alpha.4",
41
- "@mosadd/protocol": "3.0.0-alpha.4"
41
+ "@mosadd/protocol": "3.0.0-alpha.28",
42
+ "@mosadd/crypto": "3.0.0-alpha.27",
43
+ "@mosadd/providers": "3.0.0-alpha.27",
44
+ "@mosadd/threat-engine": "3.0.0-alpha.28"
42
45
  },
43
46
  "devDependencies": {
44
47
  "tsup": "^8.3.5",
@@ -0,0 +1,62 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { generateGroupKey } from "@mosadd/crypto";
3
+ import {
4
+ decryptWithGroupKey,
5
+ encryptWithGroupKey,
6
+ signCiphertext,
7
+ unwrapEnvelopeText,
8
+ } from "../crypto/channel-e2ee.js";
9
+
10
+ const envelope = (text: string) =>
11
+ JSON.stringify({ v: "mosadd.chat.v1", type: "text", text, reply_to: null, sent_at: new Date().toISOString() });
12
+
13
+ describe("channel-e2ee pure core", () => {
14
+ it("roundtrip: encrypt → decrypt returns the original text", async () => {
15
+ const key = generateGroupKey();
16
+ const plain = envelope("Fala 4 żyje");
17
+ const payload = await encryptWithGroupKey(key, plain);
18
+ expect(typeof payload).toBe("string");
19
+ const out = await decryptWithGroupKey(key, payload);
20
+ expect(out).toBe(plain);
21
+ });
22
+
23
+ it("decrypt of a legacy (non-JSON) payload returns null", async () => {
24
+ const key = generateGroupKey();
25
+ const legacy = Buffer.from(envelope("stara wiadomość"), "utf8").toString("base64");
26
+ expect(await decryptWithGroupKey(key, legacy)).toBeNull();
27
+ });
28
+
29
+ it("tampered ciphertext fails the HMAC check and returns null", async () => {
30
+ const key = generateGroupKey();
31
+ const payload = await encryptWithGroupKey(key, envelope("nie ruszaj"));
32
+ const parsed = JSON.parse(Buffer.from(payload, "base64").toString("utf8")) as {
33
+ iv: string;
34
+ ciphertext: string;
35
+ hmac: string;
36
+ };
37
+ // flip one character of the ciphertext
38
+ parsed.ciphertext = (parsed.ciphertext[0] === "A" ? "B" : "A") + parsed.ciphertext.slice(1);
39
+ const tampered = Buffer.from(JSON.stringify(parsed), "utf8").toString("base64");
40
+ expect(await decryptWithGroupKey(key, tampered)).toBeNull();
41
+ });
42
+
43
+ it("wrong key does not decrypt", async () => {
44
+ const keyA = generateGroupKey();
45
+ const keyB = generateGroupKey();
46
+ const payload = await encryptWithGroupKey(keyA, envelope("sekret"));
47
+ expect(await decryptWithGroupKey(keyB, payload)).toBeNull();
48
+ });
49
+
50
+ it("HMAC is over the base64 ciphertext string (app parity 2C)", async () => {
51
+ const key = generateGroupKey();
52
+ const payload = await encryptWithGroupKey(key, "abc");
53
+ const parsed = JSON.parse(Buffer.from(payload, "base64").toString("utf8")) as { ciphertext: string; hmac: string };
54
+ expect(parsed.hmac).toBe(signCiphertext(key, parsed.ciphertext));
55
+ });
56
+
57
+ it("unwrapEnvelopeText unwraps toolkit envelopes and leaves raw text", () => {
58
+ expect(unwrapEnvelopeText(envelope("witaj"))).toBe("witaj");
59
+ expect(unwrapEnvelopeText("zwykły tekst")).toBe("zwykły tekst");
60
+ expect(unwrapEnvelopeText('{"audio":"AAAA"}')).toBe('{"audio":"AAAA"}');
61
+ });
62
+ });
@@ -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
+ });