@mosadd/mcp 3.0.0-alpha.7 → 3.0.0

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 (66) hide show
  1. package/CHANGELOG.md +410 -0
  2. package/README.md +79 -40
  3. package/dist/bin/mcp.js +132 -8
  4. package/dist/chunk-VMMJJYXF.js +4233 -0
  5. package/dist/index.d.ts +110 -6
  6. package/dist/index.js +3 -1
  7. package/package.json +19 -16
  8. package/src/__tests__/blob-upload.test.ts +93 -0
  9. package/src/__tests__/channel-e2ee.test.ts +62 -0
  10. package/src/__tests__/cli.test.ts +47 -0
  11. package/src/__tests__/flota-jawnie.test.ts +244 -0
  12. package/src/__tests__/golden-path.test.ts +4 -2
  13. package/src/__tests__/integration.test.ts +50 -11
  14. package/src/__tests__/knowledge-ingest.test.ts +114 -0
  15. package/src/__tests__/label-room-owner.test.ts +22 -0
  16. package/src/__tests__/mdm-e2ee.test.ts +35 -1
  17. package/src/__tests__/mdm-mcp-readable.test.ts +390 -0
  18. package/src/__tests__/mirc-invite.test.ts +112 -0
  19. package/src/__tests__/mrag-search-answer.test.ts +42 -0
  20. package/src/__tests__/no-dead-host.test.ts +37 -0
  21. package/src/__tests__/presence.test.ts +199 -0
  22. package/src/__tests__/server.test.ts +11 -7
  23. package/src/__tests__/serverJsonVersion.test.ts +45 -0
  24. package/src/__tests__/tool-count-consistency.test.ts +259 -0
  25. package/src/__tests__/voice-fields.test.ts +24 -0
  26. package/src/bin/mcp.ts +71 -6
  27. package/src/cli.ts +100 -0
  28. package/src/crypto/channel-e2ee.ts +288 -0
  29. package/src/crypto/mdm-session.ts +476 -37
  30. package/src/index.ts +2 -2
  31. package/src/providers/blob-upload.ts +162 -0
  32. package/src/providers/supabase-dm.ts +102 -7
  33. package/src/providers/supabase-voice.ts +13 -1
  34. package/src/providers/supabase.ts +121 -10
  35. package/src/server.ts +102 -12
  36. package/src/tools/__tests__/ragDeleteFoldsSourceId.test.ts +67 -0
  37. package/src/tools/actions.ts +166 -0
  38. package/src/tools/attachments.ts +276 -0
  39. package/src/tools/capabilities.ts +2 -0
  40. package/src/tools/channel-payload.ts +69 -0
  41. package/src/tools/embed.ts +110 -0
  42. package/src/tools/index.ts +136 -6
  43. package/src/tools/knowledge-graph.ts +186 -0
  44. package/src/tools/knowledge.ts +351 -191
  45. package/src/tools/mail-agentbox.ts +155 -0
  46. package/src/tools/mail-aliases.ts +25 -0
  47. package/src/tools/mail-provenance.ts +137 -0
  48. package/src/tools/mail.ts +214 -60
  49. package/src/tools/mdm-as-agent.ts +138 -0
  50. package/src/tools/mdm-voice.ts +17 -3
  51. package/src/tools/mdm.ts +303 -57
  52. package/src/tools/mirc-edge.ts +8 -2
  53. package/src/tools/mirc-members.ts +130 -20
  54. package/src/tools/mirc-messages.ts +80 -35
  55. package/src/tools/mirc.ts +149 -11
  56. package/src/tools/mroom-messages.ts +4 -12
  57. package/src/tools/mtalk.ts +11 -1
  58. package/src/tools/murl.ts +314 -0
  59. package/src/tools/presence.ts +442 -0
  60. package/src/tools/ptt-ingest.ts +99 -0
  61. package/src/tools/threat.ts +123 -0
  62. package/src/tools/voice-format.ts +43 -0
  63. package/src/types.ts +36 -0
  64. package/src/version.ts +8 -0
  65. package/LICENSE +0 -201
  66. package/dist/chunk-EFTB743G.js +0 -1924
package/src/server.ts CHANGED
@@ -4,9 +4,16 @@
4
4
 
5
5
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
6
6
  import { allTools } from "./tools/index.js";
7
+ import { autoBeatFromActivity } from "./tools/presence.js";
8
+ import { PKG_VERSION } from "./version.js";
7
9
  import { SupabaseDmProvider } from "./providers/supabase-dm.js";
8
10
  import { SupabaseVoiceProvider } from "./providers/supabase-voice.js";
9
- import { InMemoryMdmKeyStore } from "./crypto/mdm-session.js";
11
+ import {
12
+ InMemoryMdmKeyStore,
13
+ SecretMdmKeyStore,
14
+ bundlePolicyForKind,
15
+ ensureOwnBundlePublished,
16
+ } from "./crypto/mdm-session.js";
10
17
  import type { MosaddServerOptions, MosaddToolContext, ProviderRegistry } from "./types.js";
11
18
 
12
19
  /**
@@ -16,21 +23,40 @@ import type { MosaddServerOptions, MosaddToolContext, ProviderRegistry } from ".
16
23
  * adapters are named — both `createMosaddServer` and the `@mosadd/ai` adapters
17
24
  * build their context through it so they stay in lockstep.
18
25
  */
19
- export function defaultProviders(injected?: Partial<ProviderRegistry>): ProviderRegistry {
26
+ export function defaultProviders(
27
+ injected?: Partial<ProviderRegistry>,
28
+ opts: { mdmSecret?: string } = {},
29
+ ): ProviderRegistry {
20
30
  return {
21
31
  dm: injected?.dm ?? new SupabaseDmProvider(),
22
- keys: injected?.keys ?? new InMemoryMdmKeyStore(),
32
+ keys: injected?.keys ?? defaultKeyStore(opts.mdmSecret),
23
33
  voice: injected?.voice ?? new SupabaseVoiceProvider(),
24
34
  };
25
35
  }
26
36
 
37
+ /**
38
+ * ⛔ ONE IDENTITY PER LOGIN SECRET, NOT ONE PER CALL (27.09.2026). With an API key the mDM
39
+ * identity is derived from it (SecretMdmKeyStore → SeededMdmKeyStore): the hosted gateway builds
40
+ * a new server per HTTP request, and with a random in-memory keystore every mDM_send was sealed
41
+ * by an identity that lived for one request. Without any secret (BYOK JWT only) there is nothing
42
+ * stable to derive from, so the old per-process random keystore remains.
43
+ *
44
+ * ⛔ STABLE PER KEY, NOT PER IDENTITY. One identity holds many keys (each OAuth connector mints
45
+ * its own), so this seed never publishes on its own authority: agent lines send in the clear and
46
+ * people keep the app's bundle (bundlePolicyForKind in crypto/mdm-session.ts).
47
+ */
48
+ function defaultKeyStore(secret?: string) {
49
+ const s = (secret ?? "").trim();
50
+ return s ? new SecretMdmKeyStore(s) : new InMemoryMdmKeyStore();
51
+ }
52
+
27
53
  export function createMosaddServer(options: MosaddServerOptions = {}) {
28
54
  const mode = options.mode ?? (options.apiKey ? "cloud" : "local");
29
55
  const hubUrl = options.hubUrl ?? "https://mcp.mosadd.com";
30
56
  const logLevel = options.logLevel ?? "info";
31
57
 
32
58
  // DI seam: default network adapters, overridden by anything the host injects.
33
- const providers = defaultProviders(options.providers);
59
+ const providers = defaultProviders(options.providers, { mdmSecret: options.apiKey });
34
60
 
35
61
  const ctx: MosaddToolContext = {
36
62
  options: { ...options, mode, hubUrl },
@@ -45,10 +71,42 @@ export function createMosaddServer(options: MosaddServerOptions = {}) {
45
71
  },
46
72
  };
47
73
 
74
+ // Cold-start fix: make this identity reachable for inbound E2EE DMs the moment
75
+ // the server is up, so mDM_send works without every recipient first running
76
+ // mDM_publish_keys. Best-effort and non-fatal — it needs an authenticated
77
+ // session, so it silently skips when there is none (BYOK without a JWT, offline,
78
+ // etc.) and never blocks startup. Uses the SAME keystore the tools use, so the
79
+ // published identity matches what mDM_send/encryptForPeer will use this process.
80
+ //
81
+ // ⛔ ENSURE, NOT BLIND PUBLISH (27.09.2026, poprawka po weryfikacji): the policy is
82
+ // bundlePolicyForKind — the SAME one mDM_send uses. Agent line: writes NOTHING (it sends in the
83
+ // clear, rozkaz Krola 20.09; a per-key bundle from each of its keys only made the directory flap).
84
+ // Human: writes NOTHING (the app owns that bundle). Unknown kind (e.g. radio): empty -> publish.
85
+ if (options.autoPublishKeys) {
86
+ void (async () => {
87
+ const selfId = await providers.dm.selfId();
88
+ const kind = await (providers.dm as { selfKind?: () => Promise<string | null> }).selfKind?.();
89
+ return ensureOwnBundlePublished(providers.keys, providers.dm, selfId, bundlePolicyForKind(kind, { explicit: false }));
90
+ })()
91
+ .then((state) => ctx.log("debug", "auto-ensure mDM prekeys", { state }))
92
+ .catch((err) => ctx.log("debug", "auto-publish mDM prekeys skipped", { error: String(err) }));
93
+ }
94
+
48
95
  const server = new McpServer(
49
96
  {
50
97
  name: "mosadd",
51
- version: "3.0.0-alpha.0",
98
+ // Human-facing identity of the server itself (initialize result). The icon URLs
99
+ // point at the LIVE gateway origin on purpose: clients that honour serverInfo.icons
100
+ // get the brand mark without scraping the favicon, and the files ship with
101
+ // the gateway's public/ folder (canon 08-26 — generated by m0ssad-3 scripts/
102
+ // generate-brand-icons.py, never hand-edited).
103
+ title: "mosADD — omnichannel messenger for agents",
104
+ websiteUrl: "https://mosadd.com",
105
+ icons: [
106
+ { src: "https://mcp.mosadd.com/favicon.svg", mimeType: "image/svg+xml", sizes: ["any"] },
107
+ { src: "https://mcp.mosadd.com/pwa-192.png", mimeType: "image/png", sizes: ["192x192"] },
108
+ ],
109
+ version: PKG_VERSION,
52
110
  },
53
111
  {
54
112
  capabilities: {
@@ -66,14 +124,30 @@ export function createMosaddServer(options: MosaddServerOptions = {}) {
66
124
  ? (tool.inputSchema as { shape: Record<string, unknown> }).shape
67
125
  : (tool.inputSchema as unknown as Record<string, unknown>);
68
126
 
69
- server.tool(
70
- tool.name,
71
- tool.description,
72
- shape as Parameters<typeof server.tool>[2],
73
- async (input: unknown) => {
127
+ // Tool annotations ride the 5-arg overload (SDK ≥1.12 serialises them into
128
+ // tools/list verbatim). Without them EVERY tool lands in the connector UI's flat
129
+ // "Other tools" bucket — the exact founder complaint this fixes. `title` is spec'd
130
+ // inside ToolAnnotations, so it travels in the same object.
131
+ const annotations =
132
+ tool.title || tool.annotations
133
+ ? { ...(tool.title ? { title: tool.title } : {}), ...(tool.annotations ?? {}) }
134
+ : undefined;
135
+
136
+ const toolCallback = async (input: unknown) => {
74
137
  const parsed = tool.inputSchema.parse(input);
75
138
  try {
76
139
  const result = await tool.handler(parsed as never, ctx);
140
+ // AUTO-PAROWANIE (08-26): a LIVE session that is actually WORKING holds its line —
141
+ // the founder spent a week talking to cloud stand-ins because models never
142
+ // remembered the attach handshake. Fire-and-forget, throttled inside, never blocks
143
+ // the tool's own response; see autoBeatFromActivity for which line gets the beat.
144
+ void autoBeatFromActivity(ctx);
145
+ // A tool may return rich MCP content (e.g. an image frame from
146
+ // comms_action_frame_get) via `mcpContent`; pass it through verbatim.
147
+ const rich = result as { mcpContent?: unknown[] } | null;
148
+ if (rich && Array.isArray(rich.mcpContent)) {
149
+ return { content: rich.mcpContent as never[] };
150
+ }
77
151
  return {
78
152
  content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }],
79
153
  };
@@ -92,8 +166,24 @@ export function createMosaddServer(options: MosaddServerOptions = {}) {
92
166
  ],
93
167
  };
94
168
  }
95
- },
96
- );
169
+ };
170
+
171
+ if (annotations) {
172
+ server.tool(
173
+ tool.name,
174
+ tool.description,
175
+ shape as Parameters<typeof server.tool>[2],
176
+ annotations,
177
+ toolCallback,
178
+ );
179
+ } else {
180
+ server.tool(
181
+ tool.name,
182
+ tool.description,
183
+ shape as Parameters<typeof server.tool>[2],
184
+ toolCallback,
185
+ );
186
+ }
97
187
  }
98
188
 
99
189
  return server;
@@ -0,0 +1,67 @@
1
+ /**
2
+ * mRAG_delete MUSI foldować source_id dokładnie tak, jak robi to mRAG_ingest.
3
+ *
4
+ * ⛔ ZMIERZONA AWARIA (2026-08-28). `mRAG_ingest` przepuszczał nie-UUID przez `uuidV5`, a
5
+ * `mRAG_delete` wysyłał SUROWY napis prosto do kolumny UUID. Efekt na żywo:
6
+ *
7
+ * mRAG_ingest { source_id: "DIAG-GENERAL-2026-08-28-a1b2c3" } → { indexed: 1 } ✅
8
+ * mRAG_delete { source_id: "DIAG-GENERAL-2026-08-28-a1b2c3" } → 500
9
+ * "invalid input syntax for type uuid" ❌
10
+ *
11
+ * Czyli: dokument zaindeksowany pod NATURALNYM kluczem (numer sprawy, ścieżka pliku, threadId
12
+ * Gmaila) dawało się dodać, ale **nigdy nie dawało się go usunąć tym samym identyfikatorem**.
13
+ * Dwie połowy tej samej rury nie zgadzały się ze sobą.
14
+ *
15
+ * I to nie było niedopatrzenie w cieniu — obietnica stała w DWÓCH miejscach, a implementacja
16
+ * w jednym: komentarz przy foldowaniu mówi „so grouping and mRAG_delete keep working on natural
17
+ * keys", a opis narzędzia obiecuje userowi „can later be removed with mRAG_delete".
18
+ *
19
+ * Boli najbardziej przy korpusie, bo tam naturalne klucze są jedynym sposobem na dedup przy
20
+ * ponownym wczytaniu — a właśnie tak mielone są akta.
21
+ *
22
+ * Ten test pilnuje INWARIANTU, nie implementacji: cokolwiek robi ingest ze swoim `source_id`,
23
+ * delete ma zrobić to samo. Gdyby ktoś kiedyś zmienił namespace albo wersję UUID, obie strony
24
+ * muszą pojechać razem — i to złapie każdy rozjazd.
25
+ */
26
+ import { describe, it, expect } from "vitest";
27
+ import { readFileSync } from "node:fs";
28
+ import { dirname, join } from "node:path";
29
+ import { fileURLToPath } from "node:url";
30
+
31
+ const HERE = dirname(fileURLToPath(import.meta.url));
32
+ const SRC = readFileSync(join(HERE, "..", "knowledge.ts"), "utf8");
33
+
34
+ /** Ciało funkcji o danej nazwie — od jej deklaracji do następnej deklaracji `async function`. */
35
+ function bodyOf(name: string): string {
36
+ const start = SRC.indexOf(`async function ${name}(`);
37
+ expect(start, `nie znaleziono funkcji ${name} w knowledge.ts`).toBeGreaterThan(-1);
38
+ const next = SRC.indexOf("\nasync function ", start + 1);
39
+ return SRC.slice(start, next === -1 ? SRC.length : next);
40
+ }
41
+
42
+ describe("mRAG_delete — zgodność foldowania z mRAG_ingest", () => {
43
+ it("delete folduje source_id przez uuidV5, tak samo jak ingest", () => {
44
+ const del = bodyOf("mRAG_delete");
45
+ expect(del, "mRAG_delete musi wołać uuidV5 — inaczej naturalny klucz da 500 na kolumnie uuid")
46
+ .toContain("uuidV5(");
47
+ expect(del, "mRAG_delete musi używać TEGO SAMEGO namespace co ingest")
48
+ .toContain("SOURCE_ID_NAMESPACE");
49
+ expect(del, "mRAG_delete musi rozpoznawać gotowy UUID i go NIE przerabiać")
50
+ .toContain("UUID_RE");
51
+ });
52
+
53
+ it("delete NIE wysyła surowego input.source_id do rag-sources", () => {
54
+ const del = bodyOf("mRAG_delete");
55
+ expect(
56
+ /source_id:\s*input\.source_id\s*\?\?\s*null/.test(del),
57
+ "regresja: surowy input.source_id znowu leci do rag-sources — to jest dokładnie ten błąd 500",
58
+ ).toBe(false);
59
+ });
60
+
61
+ it("obie strony dzielą jedną definicję namespace i jedną funkcję uuidV5", () => {
62
+ // Po jednej definicji każdej — dwie kopie to dwie prawdy, a na tym już się przejechaliśmy
63
+ // przy trasach modeli (FALLBACK_ROUTES vs ai_routes).
64
+ expect(SRC.match(/const SOURCE_ID_NAMESPACE\s*=/g)?.length ?? 0).toBe(1);
65
+ expect(SRC.match(/function uuidV5\(/g)?.length ?? 0).toBe(1);
66
+ });
67
+ });
@@ -0,0 +1,166 @@
1
+ /**
2
+ * Action links — agent → user one-link actions (Tier 1).
3
+ *
4
+ * Mint a single-use, expiring link (`https://mosadd.com/do/<token>`) that asks a
5
+ * human to DO something in their browser — confirm, pick a file, fill a form, or
6
+ * open a vetted URL — with explicit consent. Send the returned `link` to the
7
+ * person via any channel (mDM/mIRC/mp0st). They open it, see what's asked, consent,
8
+ * and the browser performs the action IN ITS SANDBOX, then the result is recorded
9
+ * against the action. No install, no OS access, nothing runs without a user gesture.
10
+ *
11
+ * Backend: mosadd `action-create` Edge Function. The action is owned by the
12
+ * calling user (user-JWT scoped — `mosadd login` / MOSADD_USER_JWT), so only you
13
+ * can later read its result.
14
+ *
15
+ * Result read-back (an `action_status` tool) is a follow-up — it needs a small
16
+ * creator-scoped read Edge Function (`action-status`). For now, the recipient's
17
+ * outcome is recorded on the action row; surface it once that EF ships.
18
+ */
19
+
20
+ import { z } from "zod";
21
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
22
+ import { invokeFunction, readSupabaseEnv, getSupabase } from "../providers/supabase.js";
23
+
24
+ const formField = z.object({
25
+ name: z.string().min(1).max(60).describe("Field key — returned verbatim in the result."),
26
+ label: z.string().max(120).optional().describe("Human label shown to the recipient. Defaults to `name`."),
27
+ type: z.enum(["text", "email", "number", "textarea", "tel", "url"]).optional().describe("Input type. Default 'text'."),
28
+ required: z.boolean().optional().describe("Whether the recipient must fill this field."),
29
+ });
30
+
31
+ const action_create_input = z.object({
32
+ action_type: z.enum(["confirm", "file_request", "form", "open_url", "screen_share"]).describe(
33
+ "What you want the recipient to do: 'confirm' (yes/no), 'file_request' (pick a file from their computer), 'form' (fill fields), 'open_url' (open a vetted https URL), 'screen_share' (recipient shares their screen so you can SEE it via comms_action_frame_get — view only).",
34
+ ),
35
+ message: z.string().min(1).max(2000).describe("What you're asking — shown on the consent screen above the action UI."),
36
+ creator_label: z.string().max(80).optional().describe("How you're identified to the recipient (e.g. your agent name). Default 'Agent'."),
37
+ // confirm
38
+ yes_label: z.string().max(40).optional().describe("[confirm] Affirmative button label. Default 'Tak'."),
39
+ no_label: z.string().max(40).optional().describe("[confirm] Negative button label. Default 'Nie'."),
40
+ // file_request
41
+ accept: z.string().max(200).optional().describe("[file_request] Accepted file types (HTML accept attr, e.g. 'image/*,.pdf')."),
42
+ max_bytes: z.number().int().positive().max(5_242_880).optional().describe("[file_request] Max file size in bytes (≤ 5 MB). NOTE: the returned file is NOT yet end-to-end encrypted — do not request sensitive files until Tier 1.1 ships."),
43
+ // form
44
+ fields: z.array(formField).min(1).max(20).optional().describe("[form] Fields to collect from the recipient."),
45
+ // open_url
46
+ url: z.string().url().optional().describe("[open_url] The https URL to open. The full URL is shown to the recipient before they open it."),
47
+ // screen_share
48
+ max_width: z.number().int().positive().max(1920).optional().describe("[screen_share] Max captured frame width in px (default 1280). Frames are downscaled JPEGs."),
49
+ // lifecycle
50
+ ttl_ms: z.number().int().positive().optional().describe("Link lifetime in milliseconds. Default 24h, capped at 7d."),
51
+ max_uses: z.number().int().min(1).max(50).optional().describe("How many times the link can be redeemed. Default 1 (single-use)."),
52
+ });
53
+
54
+ function buildParams(input: z.infer<typeof action_create_input>): Record<string, unknown> {
55
+ switch (input.action_type) {
56
+ case "confirm":
57
+ return { message: input.message, yesLabel: input.yes_label, noLabel: input.no_label };
58
+ case "file_request":
59
+ return { message: input.message, accept: input.accept, maxBytes: input.max_bytes };
60
+ case "form":
61
+ if (!input.fields?.length) throw new Error("action_type 'form' requires a non-empty `fields` array.");
62
+ return { message: input.message, fields: input.fields };
63
+ case "open_url":
64
+ if (!input.url) throw new Error("action_type 'open_url' requires `url`.");
65
+ return { message: input.message, url: input.url };
66
+ case "screen_share":
67
+ return { message: input.message, maxWidth: input.max_width };
68
+ default:
69
+ return { message: input.message };
70
+ }
71
+ }
72
+
73
+ interface ActionCreateResult {
74
+ action_id: string;
75
+ token: string;
76
+ link: string;
77
+ action_type: string;
78
+ expires_at: string;
79
+ }
80
+
81
+ async function action_create(
82
+ input: z.infer<typeof action_create_input>,
83
+ ctx: MosaddToolContext,
84
+ ): Promise<ActionCreateResult> {
85
+ readSupabaseEnv();
86
+ ctx.log("debug", "action_create invoking action-create", { action_type: input.action_type });
87
+
88
+ const body: Record<string, unknown> = {
89
+ action_type: input.action_type,
90
+ params: buildParams(input),
91
+ };
92
+ if (input.creator_label !== undefined) body.creator_label = input.creator_label;
93
+ if (input.ttl_ms !== undefined) body.ttl_ms = input.ttl_ms;
94
+ if (input.max_uses !== undefined) body.max_uses = input.max_uses;
95
+
96
+ const res = await invokeFunction<Partial<ActionCreateResult> & { error?: string }>("action-create", body);
97
+ if (res.error) throw new Error(res.error);
98
+ if (!res.link || !res.token) throw new Error("action-create returned a malformed response (missing link/token).");
99
+
100
+ return {
101
+ action_id: res.action_id ?? "",
102
+ token: res.token,
103
+ link: res.link,
104
+ action_type: res.action_type ?? input.action_type,
105
+ expires_at: res.expires_at ?? "",
106
+ };
107
+ }
108
+
109
+ // ── comms_action_frame_get — read the latest screen frame (Tier 1.5) ──────────
110
+ const action_frame_get_input = z.object({
111
+ action_id: z.string().min(1).describe("The action_id returned by comms_action_create for a 'screen_share' action you created."),
112
+ });
113
+
114
+ async function action_frame_get(
115
+ input: z.infer<typeof action_frame_get_input>,
116
+ ctx: MosaddToolContext,
117
+ ): Promise<{ mcpContent: Array<Record<string, unknown>> }> {
118
+ readSupabaseEnv();
119
+ ctx.log("debug", "action_frame_get reading frame", { action_id: input.action_id });
120
+ // Read directly via RLS ("creators read own frames") — the agent's JWT gates it
121
+ // to screen_share actions it created. No edge function needed.
122
+ const sb = getSupabase();
123
+ const { data, error } = await sb
124
+ .from("action_screen_frames")
125
+ .select("image_jpeg, width, seq, updated_at")
126
+ .eq("action_id", input.action_id)
127
+ .maybeSingle();
128
+ if (error) throw new Error(error.message);
129
+ if (!data) {
130
+ return { mcpContent: [{ type: "text", text: "No frame yet — the recipient hasn't started sharing their screen (or you don't own this action)." }] };
131
+ }
132
+ const row = data as { image_jpeg: string; width: number | null; seq: number; updated_at: string };
133
+ const ageSec = Math.round((Date.now() - new Date(row.updated_at).getTime()) / 1000);
134
+ return {
135
+ mcpContent: [
136
+ { type: "text", text: `Latest screen frame — seq ${row.seq}, ${row.width ?? "?"}px wide, ${ageSec}s old.` },
137
+ { type: "image", data: row.image_jpeg, mimeType: "image/jpeg" },
138
+ ],
139
+ };
140
+ }
141
+
142
+ export const actionTools: MosaddTool[] = [
143
+ {
144
+ // RFC 0001: channel-agnostic capability (link is sent over ANY channel), so it
145
+ // lives in the `comms_` namespace rather than a channel `m<MODULE>_` prefix.
146
+ // A dedicated `mACT` module (create/get/status) is a possible RFC follow-up.
147
+ name: "comms_action_create",
148
+ title: "Create one-click action link",
149
+ annotations: { readOnlyHint: false },
150
+ requires: "network",
151
+ description:
152
+ "Mint a single-use, expiring action link (https://mosadd.com/do/<token>) that asks a human to DO something in their browser, with explicit consent. action_type: 'confirm' (yes/no) | 'file_request' (recipient picks a file from their computer) | 'form' (recipient fills fields you define) | 'open_url' (recipient opens a vetted https URL). Returns { action_id, token, link, expires_at }. Send the `link` to the person via mDM/mIRC/mp0st; they open it, consent, and the browser performs the action in its sandbox (no install, no OS access). The action is owned by you (the calling user). HONEST LIMITS: this is browser-sandbox only — it cannot click other apps, run programs, or read files the user didn't pick; and file_request payloads are not yet end-to-end encrypted (don't request sensitive files until Tier 1.1).",
153
+ inputSchema: action_create_input,
154
+ handler: action_create as MosaddTool["handler"],
155
+ },
156
+ {
157
+ name: "comms_action_frame_get",
158
+ title: "View shared screen frame",
159
+ annotations: { readOnlyHint: true },
160
+ requires: "network",
161
+ description:
162
+ "See the LATEST screen frame from a 'screen_share' action you created (pass the action_id from comms_action_create). Returns the current screenshot AS AN IMAGE you can look at, plus how old it is. The recipient must have opened the link and clicked 'share screen' first. Poll this every few seconds to watch live. VIEW ONLY — you cannot click or control their screen. Returns a 'no frame yet' note until they start sharing.",
163
+ inputSchema: action_frame_get_input,
164
+ handler: action_frame_get as MosaddTool["handler"],
165
+ },
166
+ ];
@@ -0,0 +1,276 @@
1
+ /**
2
+ * Symmetric voice + file attachments across channels (mDM, mIRC).
3
+ *
4
+ * GOAL (Lane C): an AGENT must be able to participate in every channel the same
5
+ * way a human does — including sending VOICE notes and FILES, not just text.
6
+ * Today only mDM has a half-measure (`mDM_voice_note`, which takes a pre-uploaded
7
+ * URL and posts a control envelope, NOT a first-class `voice` message via the
8
+ * `message-send` attachments contract). mIRC has no voice/file send at all
9
+ * from the toolkit.
10
+ *
11
+ * These tools accept the blob as base64 (MCP is JSON-only), upload it to Storage
12
+ * via the shared `uploadBlob` helper, then call `message-send` with
13
+ * `message_type: 'voice' | 'file'` and the `attachments[]` descriptor.
14
+ *
15
+ * STATUS: scaffold against the Lane A contract. Compiles and uploads, but the
16
+ * `message-send` call is the not-yet-final shape — see TODO(Lane A) markers.
17
+ * mDM voice additionally needs client-side E2EE sealing before upload (TODO).
18
+ */
19
+
20
+ import { z } from "zod";
21
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
22
+ import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
23
+ import { uploadBlob, decodeBase64Body, type AttachmentDescriptor } from "../providers/blob-upload.js";
24
+
25
+ const PROTOCOL_VERSION = "mosadd.chat.v1";
26
+
27
+ // ---- Shared schema fragments ----
28
+
29
+ const Base64Body = z
30
+ .string()
31
+ .min(1)
32
+ .max(20_000_000)
33
+ .describe("Attachment bytes as base64 (or a data: URL). MCP is JSON-only, so binary is base64-encoded. Max ~15 MB decoded.");
34
+
35
+ const Mime = z.string().min(1).max(120).describe("MIME type, e.g. audio/ogg, application/pdf, image/png.");
36
+ const DurationMs = z.number().int().positive().optional().describe("Audio clip length in ms (voice only), if known.");
37
+ const Filename = z.string().min(1).max(255).optional().describe("Original filename (file only).");
38
+ const ReplyTo = z.string().optional().describe("Optional id of the message being replied to.");
39
+
40
+ const ContactRef = z.string().min(1).describe("Recipient identity id (UUID). Use mDM_list_contacts to find it.");
41
+ const RoomId = z.string().min(1).describe("Room/channel id (UUID).");
42
+
43
+ const ThreadLabel = z
44
+ .string()
45
+ .max(120)
46
+ .regex(/^[a-zA-Z0-9._-]+$/)
47
+ .optional()
48
+ .describe("Optional thread label within the conversation (mDM USP: multiple threads per contact).");
49
+
50
+ // ---- Helpers ----
51
+
52
+ /** Deterministic DM thread id (sorted pair) — must match mdm.ts dmThreadId. */
53
+ function dmThreadId(selfId: string, otherId: string, label?: string): string {
54
+ const [a, b] = [selfId, otherId].sort();
55
+ return label ? `dm:${a}:${b}:${label}` : `dm:${a}:${b}`;
56
+ }
57
+
58
+ /**
59
+ * Post an attachment message through `message-send`.
60
+ *
61
+ * TODO(Lane A): lock the exact body shape. Current best-guess from the contract:
62
+ * { space_id, thread_id, message_type: 'voice'|'file', attachments: [desc],
63
+ * encrypted_payload: <caption envelope>, protocol_version, reply_to_id }
64
+ * Open questions for Lane A:
65
+ * - is `attachments` a top-level field on message-send, or nested under the
66
+ * payload? (assumed top-level here)
67
+ * - does voice/file still require a (possibly empty) encrypted_payload caption?
68
+ * - mDM: who seals the blob + mints key_ref — this tool, or the EF?
69
+ */
70
+ async function sendAttachmentMessage(
71
+ ctx: MosaddToolContext,
72
+ args: {
73
+ space_id: string;
74
+ thread_id: string;
75
+ message_type: "voice" | "file";
76
+ attachment: AttachmentDescriptor;
77
+ caption?: string;
78
+ reply_to_id?: string;
79
+ recipient_account_id?: string;
80
+ },
81
+ ): Promise<{ message_id: string; delivered_at: string; thread_id: string }> {
82
+ readSupabaseEnv();
83
+ const captionEnvelope = {
84
+ v: PROTOCOL_VERSION,
85
+ type: args.message_type,
86
+ text: args.caption ?? "",
87
+ sent_at: new Date().toISOString(),
88
+ };
89
+ const encrypted_payload = Buffer.from(JSON.stringify(captionEnvelope), "utf8").toString("base64");
90
+
91
+ ctx.log("debug", "sendAttachmentMessage", {
92
+ thread_id: args.thread_id,
93
+ message_type: args.message_type,
94
+ bucket: args.attachment.bucket,
95
+ });
96
+
97
+ const data = await invokeFunction<{ message?: { id: string; created_at: string } }>("message-send", {
98
+ space_id: args.space_id,
99
+ thread_id: args.thread_id,
100
+ message_type: args.message_type,
101
+ attachments: [args.attachment], // TODO(Lane A): confirm field placement
102
+ encrypted_payload,
103
+ protocol_version: PROTOCOL_VERSION,
104
+ recipient_account_id: args.recipient_account_id ?? null,
105
+ reply_to_id: args.reply_to_id ?? null,
106
+ });
107
+
108
+ if (!data?.message?.id) throw new Error("message-send returned no message id (attachment)");
109
+ return {
110
+ message_id: data.message.id,
111
+ delivered_at: data.message.created_at ?? new Date().toISOString(),
112
+ thread_id: args.thread_id,
113
+ };
114
+ }
115
+
116
+ /** Resolve a channel's backing space id — mirrors mirc-messages.ts. */
117
+ async function resolveLinkedSpaceId(channelId: string): Promise<string> {
118
+ type GetResponse = { channel?: { metadata?: { linked_space_id?: string } | null }; linked_space_id?: string };
119
+ const data = await invokeFunction<GetResponse>("channel-manage", { action: "get", channel_id: channelId });
120
+ const spaceId = data?.linked_space_id ?? data?.channel?.metadata?.linked_space_id;
121
+ if (!spaceId) throw new Error(`Channel ${channelId} has no linked space yet — run mIRC_join/mIRC_list first or pass space_id.`);
122
+ return spaceId;
123
+ }
124
+
125
+ // ====================================================================
126
+ // mDM voice/file
127
+ // ====================================================================
128
+
129
+ const mDM_send_voice_input = z.object({
130
+ to: ContactRef,
131
+ audio_base64: Base64Body,
132
+ mime: Mime.default("audio/ogg"),
133
+ duration_ms: DurationMs,
134
+ caption: z.string().max(2_000).optional(),
135
+ thread_label: ThreadLabel,
136
+ reply_to_id: ReplyTo,
137
+ });
138
+
139
+ const mDM_send_file_input = z.object({
140
+ to: ContactRef,
141
+ file_base64: Base64Body,
142
+ filename: Filename,
143
+ mime: Mime,
144
+ caption: z.string().max(2_000).optional(),
145
+ thread_label: ThreadLabel,
146
+ reply_to_id: ReplyTo,
147
+ });
148
+
149
+ async function mDM_send_voice(input: z.infer<typeof mDM_send_voice_input>, ctx: MosaddToolContext) {
150
+ const dm = ctx.providers.dm;
151
+ const selfId = await dm.selfId();
152
+ const thread_id = dmThreadId(selfId, input.to, input.thread_label);
153
+ // TODO(Lane A/E2EE): mDM is client-encrypted — seal these bytes per-recipient
154
+ // via @mosadd/crypto and pass the wrapped content key as key_ref BEFORE upload.
155
+ // Uploading plaintext here is a scaffold-only shortcut.
156
+ const attachment = await uploadBlob({
157
+ kind: "voice",
158
+ bytes: decodeBase64Body(input.audio_base64),
159
+ mime: input.mime,
160
+ prefix: thread_id,
161
+ duration_ms: input.duration_ms,
162
+ });
163
+ return sendAttachmentMessage(ctx, {
164
+ space_id: "dm",
165
+ thread_id,
166
+ message_type: "voice",
167
+ attachment,
168
+ caption: input.caption,
169
+ reply_to_id: input.reply_to_id,
170
+ recipient_account_id: input.to,
171
+ });
172
+ }
173
+
174
+ async function mDM_send_file(input: z.infer<typeof mDM_send_file_input>, ctx: MosaddToolContext) {
175
+ const dm = ctx.providers.dm;
176
+ const selfId = await dm.selfId();
177
+ const thread_id = dmThreadId(selfId, input.to, input.thread_label);
178
+ // TODO(Lane A/E2EE): seal as above for mDM.
179
+ const attachment = await uploadBlob({
180
+ kind: "file",
181
+ bytes: decodeBase64Body(input.file_base64),
182
+ mime: input.mime,
183
+ prefix: thread_id,
184
+ filename: input.filename,
185
+ });
186
+ return sendAttachmentMessage(ctx, {
187
+ space_id: "dm",
188
+ thread_id,
189
+ message_type: "file",
190
+ attachment,
191
+ caption: input.caption,
192
+ reply_to_id: input.reply_to_id,
193
+ recipient_account_id: input.to,
194
+ });
195
+ }
196
+
197
+ // ====================================================================
198
+ // mIRC voice/file
199
+ // ====================================================================
200
+
201
+ const mIRC_send_voice_input = z.object({
202
+ channel_id: RoomId,
203
+ audio_base64: Base64Body,
204
+ mime: Mime.default("audio/ogg"),
205
+ duration_ms: DurationMs,
206
+ caption: z.string().max(2_000).optional(),
207
+ reply_to_id: ReplyTo,
208
+ space_id: z.string().optional().describe("Backing space id. Resolved automatically if omitted."),
209
+ });
210
+
211
+ const mIRC_send_file_input = z.object({
212
+ channel_id: RoomId,
213
+ file_base64: Base64Body,
214
+ filename: Filename,
215
+ mime: Mime,
216
+ caption: z.string().max(2_000).optional(),
217
+ reply_to_id: ReplyTo,
218
+ space_id: z.string().optional(),
219
+ });
220
+
221
+ async function mIRC_send_voice(input: z.infer<typeof mIRC_send_voice_input>, ctx: MosaddToolContext) {
222
+ const space_id = input.space_id ?? (await resolveLinkedSpaceId(input.channel_id));
223
+ const thread_id = `chat:${input.channel_id}`;
224
+ const attachment = await uploadBlob({ kind: "voice", bytes: decodeBase64Body(input.audio_base64), mime: input.mime, prefix: thread_id, duration_ms: input.duration_ms });
225
+ return sendAttachmentMessage(ctx, { space_id, thread_id, message_type: "voice", attachment, caption: input.caption, reply_to_id: input.reply_to_id });
226
+ }
227
+
228
+ async function mIRC_send_file(input: z.infer<typeof mIRC_send_file_input>, ctx: MosaddToolContext) {
229
+ const space_id = input.space_id ?? (await resolveLinkedSpaceId(input.channel_id));
230
+ const thread_id = `chat:${input.channel_id}`;
231
+ const attachment = await uploadBlob({ kind: "file", bytes: decodeBase64Body(input.file_base64), mime: input.mime, prefix: thread_id, filename: input.filename });
232
+ return sendAttachmentMessage(ctx, { space_id, thread_id, message_type: "file", attachment, caption: input.caption, reply_to_id: input.reply_to_id });
233
+ }
234
+
235
+ // ---- Registration ----
236
+
237
+ export const attachmentTools: MosaddTool[] = [
238
+ {
239
+ name: "mDM_send_voice",
240
+ title: "Send a voice message",
241
+ annotations: { readOnlyHint: false },
242
+ requires: "network",
243
+ description:
244
+ "Send a VOICE note to a contact as a first-class mDM `voice` message (not a URL stub). Pass audio bytes as base64; the tool uploads to Storage and posts via message-send with the voice attachment descriptor. SCAFFOLD: mDM is client-encrypted — until the seal step ships, bytes are uploaded unsealed (TODO Lane A).",
245
+ inputSchema: mDM_send_voice_input,
246
+ handler: mDM_send_voice as MosaddTool["handler"],
247
+ },
248
+ {
249
+ name: "mDM_send_file",
250
+ title: "Send a file in DM",
251
+ annotations: { readOnlyHint: false },
252
+ requires: "network",
253
+ description:
254
+ "Send a FILE to a contact as a first-class mDM `file` message. Base64 bytes → Storage → message-send file attachment. SCAFFOLD: mDM E2EE seal is TODO (Lane A).",
255
+ inputSchema: mDM_send_file_input,
256
+ handler: mDM_send_file as MosaddTool["handler"],
257
+ },
258
+ {
259
+ name: "mIRC_send_voice",
260
+ title: "Send voice note to channel",
261
+ annotations: { readOnlyHint: false },
262
+ requires: "network",
263
+ description: "Send a VOICE note into a persistent channel as a first-class `voice` message. Base64 audio → Storage → message-send (backing space resolved automatically).",
264
+ inputSchema: mIRC_send_voice_input,
265
+ handler: mIRC_send_voice as MosaddTool["handler"],
266
+ },
267
+ {
268
+ name: "mIRC_send_file",
269
+ title: "Send file to channel",
270
+ annotations: { readOnlyHint: false },
271
+ requires: "network",
272
+ description: "Send a FILE into a persistent channel as a first-class `file` message. Base64 bytes → Storage → message-send.",
273
+ inputSchema: mIRC_send_file_input,
274
+ handler: mIRC_send_file as MosaddTool["handler"],
275
+ },
276
+ ];