@mosadd/mcp 3.0.0-alpha.2 → 3.0.0-alpha.21

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 (48) hide show
  1. package/CHANGELOG.md +131 -0
  2. package/README.md +141 -116
  3. package/dist/bin/mcp.js +70 -3
  4. package/dist/chunk-TNWL6GPV.js +2299 -0
  5. package/dist/index.d.ts +70 -7
  6. package/dist/index.js +5 -3
  7. package/package.json +13 -7
  8. package/src/__tests__/golden-path.test.ts +137 -132
  9. package/src/__tests__/integration.test.ts +178 -175
  10. package/src/__tests__/mdm-e2ee.test.ts +212 -149
  11. package/src/__tests__/mtalk.test.ts +122 -0
  12. package/src/__tests__/server.test.ts +71 -67
  13. package/src/bin/login.ts +138 -138
  14. package/src/bin/mcp.ts +145 -55
  15. package/src/config.ts +66 -66
  16. package/src/crypto/mdm-session.ts +502 -378
  17. package/src/index.ts +19 -17
  18. package/src/observability/sentry.ts +79 -79
  19. package/src/providers/blob-upload.ts +116 -0
  20. package/src/providers/memory-voice.ts +79 -0
  21. package/src/providers/supabase-dm.ts +122 -117
  22. package/src/providers/supabase-voice.ts +91 -0
  23. package/src/providers/supabase.ts +120 -96
  24. package/src/server.ts +123 -103
  25. package/src/tools/actions.ts +162 -0
  26. package/src/tools/attachments.ts +268 -0
  27. package/src/tools/capabilities.ts +68 -68
  28. package/src/tools/embed.ts +108 -0
  29. package/src/tools/index.ts +76 -37
  30. package/src/tools/knowledge.ts +191 -0
  31. package/src/tools/mail-provenance.ts +137 -0
  32. package/src/tools/mail.ts +378 -89
  33. package/src/tools/mcall.ts +216 -0
  34. package/src/tools/mdm-voice.ts +206 -0
  35. package/src/tools/mdm.ts +451 -379
  36. package/src/tools/mirc-edge.ts +190 -0
  37. package/src/tools/mirc-members.ts +188 -177
  38. package/src/tools/mirc-messages.ts +155 -0
  39. package/src/tools/mirc.ts +176 -170
  40. package/src/tools/mroom-messages.ts +142 -142
  41. package/src/tools/mroom.ts +221 -189
  42. package/src/tools/mtalk.ts +121 -0
  43. package/src/tools/murl.ts +195 -0
  44. package/src/tools/ptt-ingest.ts +92 -0
  45. package/src/tools/threat.ts +92 -0
  46. package/src/types.ts +94 -79
  47. package/src/voice/floor.ts +132 -0
  48. package/dist/chunk-HD5RLE5K.js +0 -1193
package/src/tools/mail.ts CHANGED
@@ -1,89 +1,378 @@
1
- /**
2
- * mAIL — Email.
3
- *
4
- * Every mosadd user gets `<userId>@mosadd.com` for free — incoming mail lands
5
- * in their app, outgoing mail flows through the m0ssad-3 mp0st pipeline.
6
- *
7
- * Phase 1 alpha: wired to m0ssad-3 `mp0st-send` + `mp0st-view` Edge Functions.
8
- */
9
-
10
- import { z } from "zod";
11
- import type { MosaddTool, MosaddToolContext } from "../types.js";
12
- import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
13
-
14
- // ---- Schemas ----
15
-
16
- const EmailAddress = z
17
- .string()
18
- .email()
19
- .max(254)
20
- .describe("RFC 5321 email address.");
21
-
22
- const MessageId = z.string().min(1).describe("Message id (UUID) from mAIL_send or inbox.");
23
-
24
- const mAIL_send_input = z.object({
25
- to: z.union([EmailAddress, z.array(EmailAddress).min(1).max(50)]).describe(
26
- "Recipient(s). Single address or array of up to 50.",
27
- ),
28
- subject: z.string().min(1).max(998).describe("Email subject line. Max 998 chars (RFC 5322)."),
29
- body_text: z.string().max(1_048_576).optional().describe("Plain text body. Max 1 MB."),
30
- body_html: z.string().max(1_048_576).optional().describe("HTML body. Max 1 MB."),
31
- cc: z.array(EmailAddress).max(50).optional(),
32
- bcc: z.array(EmailAddress).max(50).optional(),
33
- reply_to: EmailAddress.optional(),
34
- });
35
-
36
- const mAIL_view_input = z.object({
37
- message_id: MessageId,
38
- });
39
-
40
- // ---- Handlers ----
41
-
42
- async function mAIL_send(
43
- input: z.infer<typeof mAIL_send_input>,
44
- ctx: MosaddToolContext,
45
- ): Promise<{ message_id: string; queued_at: string }> {
46
- readSupabaseEnv();
47
- if (!input.body_text && !input.body_html) {
48
- throw new Error("mAIL_send requires at least one of body_text or body_html.");
49
- }
50
- ctx.log("debug", "mAIL_send invoking mp0st-send", { to: input.to });
51
- return await invokeFunction<{ message_id: string; queued_at: string }>("mp0st-send", input);
52
- }
53
-
54
- async function mAIL_view(
55
- input: z.infer<typeof mAIL_view_input>,
56
- ctx: MosaddToolContext,
57
- ): Promise<{
58
- message_id: string;
59
- from: string;
60
- to: string[];
61
- subject: string;
62
- body_text: string | null;
63
- body_html: string | null;
64
- received_at: string;
65
- }> {
66
- readSupabaseEnv();
67
- ctx.log("debug", "mAIL_view invoking mp0st-view", { message_id: input.message_id });
68
- return await invokeFunction("mp0st-view", { message_id: input.message_id });
69
- }
70
-
71
- // ---- Registration ----
72
-
73
- export const mailTools: MosaddTool[] = [
74
- {
75
- name: "mAIL_send",
76
- requires: "network",
77
- description:
78
- "Send an email from the user's mosadd address (<userId>@mosadd.com). Pass body_text or body_html (or both). Supports cc, bcc, reply_to.",
79
- inputSchema: mAIL_send_input,
80
- handler: mAIL_send as MosaddTool["handler"],
81
- },
82
- {
83
- name: "mAIL_view",
84
- requires: "network",
85
- description: "Read the full body and metadata of an email by message_id.",
86
- inputSchema: mAIL_view_input,
87
- handler: mAIL_view as MosaddTool["handler"],
88
- },
89
- ];
1
+ /**
2
+ * mp0st — Email.
3
+ *
4
+ * Every mosadd user gets `<userId>@mosadd.com` for free — incoming mail lands
5
+ * in their app, outgoing mail flows through the mosadd mp0st pipeline.
6
+ *
7
+ * Phase 1 alpha: wired to the mosadd backend's `mp0st-send` + `mp0st-view` Edge Functions.
8
+ */
9
+
10
+ import { z } from "zod";
11
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
12
+ import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
13
+
14
+ // ---- Schemas ----
15
+
16
+ const EmailAddress = z
17
+ .string()
18
+ .email()
19
+ .max(254)
20
+ .describe("RFC 5321 email address.");
21
+
22
+ const MessageId = z.string().min(1).describe("Message id (UUID) from mp0st_send or inbox.");
23
+
24
+ const mp0st_send_input = z.object({
25
+ to: z.union([EmailAddress, z.array(EmailAddress).min(1).max(50)]).describe(
26
+ "Recipient(s). Single address or array of up to 50.",
27
+ ),
28
+ subject: z.string().min(1).max(998).describe("Email subject line. Max 998 chars (RFC 5322)."),
29
+ body_text: z.string().max(1_048_576).optional().describe("Plain text body. Max 1 MB."),
30
+ body_html: z.string().max(1_048_576).optional().describe("HTML body. Max 1 MB."),
31
+ cc: z.array(EmailAddress).max(50).optional(),
32
+ bcc: z.array(EmailAddress).max(50).optional(),
33
+ reply_to: EmailAddress.optional(),
34
+ tracking: z
35
+ .boolean()
36
+ .optional()
37
+ .describe("Open-pixel + link-click tracking. Default true. Set false to send with NO tracking (privacy / GDPR-friendly)."),
38
+ force_reader: z
39
+ .boolean()
40
+ .optional()
41
+ .describe("Default false. If true, the email body is a stub only and the recipient must open it in mosadd's secure reader — maximizes tracking (print/copy/time-on-read become observable). Best for confidential / legal mail."),
42
+ disclose_tracking: z
43
+ .boolean()
44
+ .optional()
45
+ .describe("Default false. If true (and tracking on), append a tracking-disclosure footer to the email — recommended for GDPR/ePrivacy compliance."),
46
+ watermark: z
47
+ .union([z.boolean(), z.string().max(120)])
48
+ .optional()
49
+ .describe("Inject a faint recipient watermark into the secure reader (shows in screenshots/prints). Pass true to watermark with the recipient address, or a custom string."),
50
+ auto_destruct: z
51
+ .enum(["1h", "24h", "7d"])
52
+ .optional()
53
+ .describe("Self-destruct timer: the secure-reader link expires after this window."),
54
+ });
55
+
56
+ const mp0st_view_input = z.object({
57
+ message_id: MessageId,
58
+ });
59
+
60
+ const mp0st_delete_input = z.object({
61
+ message_id: MessageId,
62
+ });
63
+
64
+ const mp0st_list_input = z.object({
65
+ direction: z
66
+ .enum(["inbound", "outbound"])
67
+ .optional()
68
+ .describe("Filter to received (inbound) or sent (outbound) mail. Omit for both."),
69
+ limit: z.number().int().min(1).max(200).optional().describe("Max emails to return. Default 50."),
70
+ before: z
71
+ .string()
72
+ .optional()
73
+ .describe("Pagination cursor: pass the previous response's next_cursor to get the next (older) page."),
74
+ });
75
+
76
+ const mp0st_stats_input = z.object({
77
+ message_id: MessageId,
78
+ });
79
+
80
+ const mp0st_events_input = z.object({
81
+ message_id: MessageId,
82
+ });
83
+
84
+ const mp0st_metrics_input = z.object({});
85
+
86
+ const mp0st_revoke_input = z.object({
87
+ message_id: MessageId,
88
+ restore: z
89
+ .boolean()
90
+ .optional()
91
+ .describe("Set true to UN-revoke (restore access). Default false = revoke."),
92
+ });
93
+
94
+ const mp0st_audit_export_input = z.object({
95
+ message_id: MessageId,
96
+ });
97
+
98
+ const mp0st_consent_input = z.object({
99
+ action: z
100
+ .enum(["list", "check", "optin"])
101
+ .describe("'list' = recipients who opted out of your tracking; 'check' = is one recipient opted out; 'optin' = re-enable tracking for a recipient."),
102
+ recipient: EmailAddress.optional().describe("Required for 'check' and 'optin'."),
103
+ });
104
+
105
+ const mp0st_notify_input = z.object({
106
+ since: z
107
+ .string()
108
+ .optional()
109
+ .describe("ISO-8601 cursor — return only events newer than this. Pass the previous response's `cursor` to poll for new activity."),
110
+ limit: z.number().int().min(1).max(200).optional().describe("Max events. Default 50."),
111
+ });
112
+
113
+ interface MailListItem {
114
+ message_id: string;
115
+ direction: "inbound" | "outbound";
116
+ from: string;
117
+ to: string;
118
+ subject: string;
119
+ priority: string;
120
+ status: string;
121
+ sent_at: string;
122
+ snippet: string;
123
+ }
124
+
125
+ // ---- Handlers ----
126
+
127
+ async function mp0st_send(
128
+ input: z.infer<typeof mp0st_send_input>,
129
+ ctx: MosaddToolContext,
130
+ ): Promise<{ message_id: string; status: string; is_internal: boolean }> {
131
+ readSupabaseEnv();
132
+ if (!input.body_text && !input.body_html) {
133
+ throw new Error("mp0st_send requires at least one of body_text or body_html.");
134
+ }
135
+ ctx.log("debug", "mp0st_send invoking mp0st-send", { to: input.to });
136
+ // mp0st-send returns { ok, email_id, status, is_internal } — remap email_id to the
137
+ // tool's message_id contract (email_id IS the message id). Surface backend errors.
138
+ const res = await invokeFunction<{ ok?: boolean; email_id?: string; status?: string; is_internal?: boolean; error?: string }>("mp0st-send", input);
139
+ if (res.error) throw new Error(res.error);
140
+ return { message_id: res.email_id ?? "", status: res.status ?? "sent", is_internal: res.is_internal ?? false };
141
+ }
142
+
143
+ async function mp0st_view(
144
+ input: z.infer<typeof mp0st_view_input>,
145
+ ctx: MosaddToolContext,
146
+ ): Promise<{
147
+ message_id: string;
148
+ from: string;
149
+ to: string[];
150
+ subject: string;
151
+ body_text: string | null;
152
+ body_html: string | null;
153
+ received_at: string;
154
+ }> {
155
+ readSupabaseEnv();
156
+ // mp0st-get (NOT mp0st-view): mp0st-view is the open-tracking pixel endpoint
157
+ // keyed on ?t=<trackingId> and always 400s "Missing tracking ID" on a JSON POST.
158
+ // mp0st-get reads the owner-scoped email by id and returns the full body.
159
+ ctx.log("debug", "mp0st_view invoking mp0st-get", { message_id: input.message_id });
160
+ return await invokeFunction("mp0st-get", { message_id: input.message_id });
161
+ }
162
+
163
+ async function mp0st_list(
164
+ input: z.infer<typeof mp0st_list_input>,
165
+ ctx: MosaddToolContext,
166
+ ): Promise<{ emails: MailListItem[]; next_cursor: string | null }> {
167
+ readSupabaseEnv();
168
+ ctx.log("debug", "mp0st_list invoking mp0st-list", { direction: input.direction });
169
+ return await invokeFunction<{ emails: MailListItem[]; next_cursor: string | null }>("mp0st-list", {
170
+ direction: input.direction ?? null,
171
+ limit: input.limit ?? 50,
172
+ before: input.before ?? null,
173
+ });
174
+ }
175
+
176
+ async function mp0st_delete(
177
+ input: z.infer<typeof mp0st_delete_input>,
178
+ ctx: MosaddToolContext,
179
+ ): Promise<{ ok: true; message_id: string; deleted: true }> {
180
+ readSupabaseEnv();
181
+ ctx.log("debug", "mp0st_delete invoking mp0st-delete", { message_id: input.message_id });
182
+ return await invokeFunction<{ ok: true; message_id: string; deleted: true }>("mp0st-delete", {
183
+ message_id: input.message_id,
184
+ });
185
+ }
186
+
187
+ interface MailEngagement {
188
+ message_id: string;
189
+ subject: string;
190
+ to: string;
191
+ direction: string;
192
+ status: string;
193
+ sent_at: string;
194
+ open_count: number;
195
+ unique_opens: number;
196
+ click_count: number;
197
+ forwarded: boolean;
198
+ first_opened_at: string | null;
199
+ last_opened_at: string | null;
200
+ events_by_type: Record<string, number>;
201
+ total_events: number;
202
+ }
203
+
204
+ async function mp0st_stats(
205
+ input: z.infer<typeof mp0st_stats_input>,
206
+ ctx: MosaddToolContext,
207
+ ): Promise<{ summary: MailEngagement }> {
208
+ readSupabaseEnv();
209
+ ctx.log("debug", "mp0st_stats invoking mp0st-stats", { message_id: input.message_id });
210
+ return await invokeFunction<{ summary: MailEngagement }>("mp0st-stats", {
211
+ message_id: input.message_id,
212
+ });
213
+ }
214
+
215
+ async function mp0st_events(
216
+ input: z.infer<typeof mp0st_events_input>,
217
+ ctx: MosaddToolContext,
218
+ ): Promise<{
219
+ summary: MailEngagement;
220
+ events: Array<{ event_type: string; at: string; device: string | null; ip_hash: string | null; link_url: string | null }>;
221
+ }> {
222
+ readSupabaseEnv();
223
+ ctx.log("debug", "mp0st_events invoking mp0st-stats", { message_id: input.message_id });
224
+ return await invokeFunction("mp0st-stats", { message_id: input.message_id, events: true });
225
+ }
226
+
227
+ async function mp0st_metrics(
228
+ _input: z.infer<typeof mp0st_metrics_input>,
229
+ ctx: MosaddToolContext,
230
+ ): Promise<{
231
+ mailbox: {
232
+ total_sent: number;
233
+ opened_emails: number;
234
+ open_rate_pct: number;
235
+ total_opens: number;
236
+ total_clicks: number;
237
+ forwarded_emails: number;
238
+ };
239
+ }> {
240
+ readSupabaseEnv();
241
+ ctx.log("debug", "mp0st_metrics invoking mp0st-stats");
242
+ return await invokeFunction("mp0st-stats", {});
243
+ }
244
+
245
+ async function mp0st_revoke(
246
+ input: z.infer<typeof mp0st_revoke_input>,
247
+ ctx: MosaddToolContext,
248
+ ): Promise<{ ok: true; message_id: string; revoked: boolean; expires_at: string | null }> {
249
+ readSupabaseEnv();
250
+ ctx.log("debug", "mp0st_revoke invoking mp0st-revoke", { message_id: input.message_id, restore: !!input.restore });
251
+ return await invokeFunction("mp0st-revoke", {
252
+ message_id: input.message_id,
253
+ restore: input.restore ?? false,
254
+ });
255
+ }
256
+
257
+ async function mp0st_audit_export(
258
+ input: z.infer<typeof mp0st_audit_export_input>,
259
+ ctx: MosaddToolContext,
260
+ ): Promise<{ audit: Record<string, unknown>; signature: string; algo: string; note: string }> {
261
+ readSupabaseEnv();
262
+ ctx.log("debug", "mp0st_audit_export invoking mp0st-audit", { message_id: input.message_id });
263
+ return await invokeFunction("mp0st-audit", { message_id: input.message_id });
264
+ }
265
+
266
+ async function mp0st_consent(
267
+ input: z.infer<typeof mp0st_consent_input>,
268
+ ctx: MosaddToolContext,
269
+ ): Promise<Record<string, unknown>> {
270
+ readSupabaseEnv();
271
+ ctx.log("debug", "mp0st_consent invoking mp0st-consent", { action: input.action });
272
+ return await invokeFunction("mp0st-consent", { action: input.action, recipient: input.recipient ?? null });
273
+ }
274
+
275
+ async function mp0st_notify(
276
+ input: z.infer<typeof mp0st_notify_input>,
277
+ ctx: MosaddToolContext,
278
+ ): Promise<{
279
+ events: Array<{ message_id: string; subject: string | null; to: string | null; event_type: string; device: string | null; link_url: string | null; at: string }>;
280
+ cursor: string | null;
281
+ count: number;
282
+ }> {
283
+ readSupabaseEnv();
284
+ ctx.log("debug", "mp0st_notify invoking mp0st-notify", { since: input.since });
285
+ return await invokeFunction("mp0st-notify", { action: "feed", since: input.since ?? null, limit: input.limit ?? 50 });
286
+ }
287
+
288
+ // ---- Registration ----
289
+
290
+ export const mailTools: MosaddTool[] = [
291
+ {
292
+ name: "mp0st_list",
293
+ requires: "network",
294
+ description:
295
+ "List the user's mailbox (their <userId>@mosadd.com inbox/outbox) newest-first, with sender, subject, status and a short snippet. Filter by direction ('inbound' = received, 'outbound' = sent). Use the returned next_cursor with `before` to page through older mail. Call mp0st_view to read a full message body.",
296
+ inputSchema: mp0st_list_input,
297
+ handler: mp0st_list as MosaddTool["handler"],
298
+ },
299
+ {
300
+ name: "mp0st_send",
301
+ requires: "network",
302
+ description:
303
+ "Send an email from the user's mosadd address (<userId>@mosadd.com). Pass body_text or body_html (or both). Supports cc, bcc, reply_to. Monitoring/legal options: tracking (open+click, default on; set false for no tracking), force_reader (stub email → recipient opens in mosadd's secure reader, unlocking print/copy/time-on-read tracking + revoke), watermark (recipient watermark visible in screenshots/prints), disclose_tracking (GDPR footer), auto_destruct ('1h'|'24h'|'7d').",
304
+ inputSchema: mp0st_send_input,
305
+ handler: mp0st_send as MosaddTool["handler"],
306
+ },
307
+ {
308
+ name: "mp0st_view",
309
+ requires: "network",
310
+ description: "Read the full body and metadata of an email by message_id.",
311
+ inputSchema: mp0st_view_input,
312
+ handler: mp0st_view as MosaddTool["handler"],
313
+ },
314
+ {
315
+ name: "mp0st_delete",
316
+ requires: "network",
317
+ description:
318
+ "Delete one of the user's emails by message_id (from mp0st_list). Soft-delete — it stops showing in mp0st_list. Owner-scoped: only your own mail.",
319
+ inputSchema: mp0st_delete_input,
320
+ handler: mp0st_delete as MosaddTool["handler"],
321
+ },
322
+ {
323
+ name: "mp0st_stats",
324
+ requires: "network",
325
+ description:
326
+ "Engagement summary for one sent email (by message_id): open_count, unique_opens, click_count, whether it was likely forwarded, first/last opened time, and a breakdown of tracked event types. Opens/clicks are real (tracking pixel + link-wrap); forward detection is best-effort (IP-subnet diversity). Owner-scoped.",
327
+ inputSchema: mp0st_stats_input,
328
+ handler: mp0st_stats as MosaddTool["handler"],
329
+ },
330
+ {
331
+ name: "mp0st_events",
332
+ requires: "network",
333
+ description:
334
+ "Raw engagement timeline for one email (by message_id): every tracked event (pixel_open, link_click, forwarded, page_view, copy/print/focus signals) with timestamp, device type and link URL. Use mp0st_stats for the rollup; use this for the per-event detail. Owner-scoped.",
335
+ inputSchema: mp0st_events_input,
336
+ handler: mp0st_events as MosaddTool["handler"],
337
+ },
338
+ {
339
+ name: "mp0st_metrics",
340
+ requires: "network",
341
+ description:
342
+ "Mailbox-wide engagement aggregate across the user's sent mail: total_sent, opened_emails, open_rate_pct, total_opens, total_clicks, forwarded_emails. Owner-scoped.",
343
+ inputSchema: mp0st_metrics_input,
344
+ handler: mp0st_metrics as MosaddTool["handler"],
345
+ },
346
+ {
347
+ name: "mp0st_revoke",
348
+ requires: "network",
349
+ description:
350
+ "Revoke (recall) a sent email's secure-reader access by message_id — the recipient can no longer open the full message via the mosadd reader link (Virtru-style recall, immediate). Pass restore:true to re-enable. HONEST LIMIT: cannot un-send or claw back content the recipient already read, copied, or screenshotted — only disables future reader access. Owner-scoped.",
351
+ inputSchema: mp0st_revoke_input,
352
+ handler: mp0st_revoke as MosaddTool["handler"],
353
+ },
354
+ {
355
+ name: "mp0st_audit_export",
356
+ requires: "network",
357
+ description:
358
+ "Export a tamper-evident engagement audit report for one sent email (RMail-style): full event trail (opens, clicks, reader print/copy/forward signals) + totals, plus an HMAC-SHA256 signature over the canonical JSON so the report can be proven unaltered. For legal/compliance use. HONEST LIMIT: proves what mosadd observed; it is not a qualified delivery receipt (ERDS). Owner-scoped.",
359
+ inputSchema: mp0st_audit_export_input,
360
+ handler: mp0st_audit_export as MosaddTool["handler"],
361
+ },
362
+ {
363
+ name: "mp0st_consent",
364
+ requires: "network",
365
+ description:
366
+ "Manage recipient tracking opt-outs (GDPR/ePrivacy). action 'list' = recipients who opted out of your tracking; 'check' {recipient} = whether one opted out; 'optin' {recipient} = re-enable. Recipients self-opt-out via the footer link in your tracked emails; mp0st_send then automatically sends them with NO pixel/link-wrap. Owner-scoped.",
367
+ inputSchema: mp0st_consent_input,
368
+ handler: mp0st_consent as MosaddTool["handler"],
369
+ },
370
+ {
371
+ name: "mp0st_notify",
372
+ requires: "network",
373
+ description:
374
+ "Recent engagement feed across ALL your sent mail — the 'who just opened/clicked my mail' notifications stream (opens, clicks, forwards, reader print/copy signals), newest first, each with the email subject + recipient. Poll: pass the returned `cursor` back as `since` to get only new activity. Owner-scoped.",
375
+ inputSchema: mp0st_notify_input,
376
+ handler: mp0st_notify as MosaddTool["handler"],
377
+ },
378
+ ];
@@ -0,0 +1,216 @@
1
+ /**
2
+ * mCALL — Outbound PSTN calls.
3
+ *
4
+ * Place a real phone call (E.164) from an agent. Control plane is MCP; audio
5
+ * never flows through the tool call — it is bridged over LiveKit SIP (primary)
6
+ * or a Telnyx fallback to the carrier, with an optional voice vocoder.
7
+ *
8
+ * Wired to the m0ssad-3 `call-start-pstn` / `call-end-pstn` Edge Functions
9
+ * (deployed). A carrier must be wired server-side (LIVEKIT_SIP_TRUNK_ID, or
10
+ * TELNYX_API_KEY + TELNYX_CONNECTION_ID + TELNYX_FROM_NUMBER); until then the
11
+ * call session is created and metered but no audio leg is bridged.
12
+ *
13
+ * NOTE: mCALL is the telephone (PSTN). For 1:1 in-app voice use mDM; for
14
+ * walkie-talkie / floor-controlled voice use mTALK.
15
+ *
16
+ * Burner numbers: mCALL_acquire_number leases an ephemeral DID (~10 min) that
17
+ * becomes your outbound caller-ID and can receive inbound calls. Inbound rings
18
+ * are delivered out-of-band (Supabase Realtime broadcast on
19
+ * `mcall-inbound-<identity_id>`, or an integrator webhook) carrying a room_name;
20
+ * mCALL_answer mints the LiveKit token to join and bridge that call. Pair with
21
+ * the `vocoder` flag / a published vocoder track to mask the caller's voice.
22
+ */
23
+
24
+ import { z } from "zod";
25
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
26
+ import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
27
+
28
+ // ---- Schemas ----
29
+
30
+ const E164 = z
31
+ .string()
32
+ .regex(/^\+\d{7,15}$/)
33
+ .describe("Destination phone number in E.164 format, e.g. +14155550123.");
34
+
35
+ const mCALL_start_pstn_input = z.object({
36
+ to: E164,
37
+ vocoder: z
38
+ .boolean()
39
+ .optional()
40
+ .describe("Disguise the caller's voice with a vocoder (anonymous calling). Default false."),
41
+ });
42
+
43
+ const mCALL_end_pstn_input = z.object({
44
+ session_id: z.string().min(1).describe("Session id returned by mCALL_start_pstn."),
45
+ });
46
+
47
+ // ---- Burner (ephemeral number) schemas ----
48
+
49
+ const mCALL_acquire_number_input = z.object({}).describe(
50
+ "No parameters. Leases the next available number for ~10 minutes (idempotent: returns your live lease if you already hold one).",
51
+ );
52
+
53
+ const mCALL_my_numbers_input = z.object({}).describe("No parameters.");
54
+
55
+ const mCALL_extend_number_input = z.object({
56
+ number_id: z
57
+ .string()
58
+ .optional()
59
+ .describe("Pool id of the number to extend. Omit to extend your current lease."),
60
+ });
61
+
62
+ const mCALL_release_number_input = z.object({
63
+ number_id: z
64
+ .string()
65
+ .optional()
66
+ .describe("Pool id of the number to release. Omit to release all numbers you hold."),
67
+ });
68
+
69
+ const mCALL_answer_input = z.object({
70
+ room_name: z
71
+ .string()
72
+ .min(1)
73
+ .describe("room_name from an inbound_call event (Realtime broadcast / integrator webhook)."),
74
+ });
75
+
76
+ // ---- Handlers ----
77
+
78
+ async function mCALL_start_pstn(
79
+ input: z.infer<typeof mCALL_start_pstn_input>,
80
+ ctx: MosaddToolContext,
81
+ ): Promise<{
82
+ session_id: string;
83
+ room_name: string;
84
+ destination_number: string;
85
+ vocoder_enabled: boolean;
86
+ minutes_remaining: number;
87
+ zone: string;
88
+ zone_label: string;
89
+ }> {
90
+ readSupabaseEnv();
91
+ ctx.log("debug", "mCALL_start_pstn invoking call-start-pstn", { to: input.to });
92
+ return await invokeFunction("call-start-pstn", {
93
+ destination_number: input.to,
94
+ vocoder_enabled: input.vocoder ?? false,
95
+ });
96
+ }
97
+
98
+ async function mCALL_end_pstn(
99
+ input: z.infer<typeof mCALL_end_pstn_input>,
100
+ ctx: MosaddToolContext,
101
+ ): Promise<{ duration_ms: number; cost_credits: number }> {
102
+ readSupabaseEnv();
103
+ ctx.log("debug", "mCALL_end_pstn invoking call-end-pstn", { session_id: input.session_id });
104
+ return await invokeFunction("call-end-pstn", { session_id: input.session_id });
105
+ }
106
+
107
+ // ---- Burner (ephemeral number) handlers ----
108
+
109
+ interface AcquiredNumber {
110
+ did: { id: string; phone_number: string; hold_until: string | null };
111
+ reused: boolean;
112
+ hold_until: string;
113
+ seconds_remaining: number;
114
+ }
115
+
116
+ async function mCALL_acquire_number(
117
+ _input: z.infer<typeof mCALL_acquire_number_input>,
118
+ ctx: MosaddToolContext,
119
+ ): Promise<AcquiredNumber> {
120
+ readSupabaseEnv();
121
+ ctx.log("debug", "mCALL_acquire_number invoking call-did-pool acquire");
122
+ return await invokeFunction("call-did-pool", { action: "acquire" });
123
+ }
124
+
125
+ async function mCALL_my_numbers(
126
+ _input: z.infer<typeof mCALL_my_numbers_input>,
127
+ ctx: MosaddToolContext,
128
+ ): Promise<{ numbers: Array<{ id: string; phone_number: string; seconds_remaining: number | null }> }> {
129
+ readSupabaseEnv();
130
+ ctx.log("debug", "mCALL_my_numbers invoking call-did-pool mine");
131
+ return await invokeFunction("call-did-pool", { action: "mine" });
132
+ }
133
+
134
+ async function mCALL_extend_number(
135
+ input: z.infer<typeof mCALL_extend_number_input>,
136
+ ctx: MosaddToolContext,
137
+ ): Promise<{ did: unknown; hold_until: string; seconds_remaining: number }> {
138
+ readSupabaseEnv();
139
+ ctx.log("debug", "mCALL_extend_number invoking call-did-pool extend", { number_id: input.number_id });
140
+ return await invokeFunction("call-did-pool", { action: "extend", did_id: input.number_id });
141
+ }
142
+
143
+ async function mCALL_release_number(
144
+ input: z.infer<typeof mCALL_release_number_input>,
145
+ ctx: MosaddToolContext,
146
+ ): Promise<{ released: number; dids: unknown[] }> {
147
+ readSupabaseEnv();
148
+ ctx.log("debug", "mCALL_release_number invoking call-did-pool release_mine", { number_id: input.number_id });
149
+ return await invokeFunction("call-did-pool", { action: "release_mine", did_id: input.number_id });
150
+ }
151
+
152
+ async function mCALL_answer(
153
+ input: z.infer<typeof mCALL_answer_input>,
154
+ ctx: MosaddToolContext,
155
+ ): Promise<{ token: string; url: string; roomName: string; identity: string }> {
156
+ readSupabaseEnv();
157
+ ctx.log("debug", "mCALL_answer minting livekit token", { room_name: input.room_name });
158
+ return await invokeFunction("livekit-token", { roomName: input.room_name });
159
+ }
160
+
161
+ // ---- Registration ----
162
+
163
+ export const mcallTools: MosaddTool[] = [
164
+ {
165
+ name: "mCALL_start_pstn",
166
+ requires: "network",
167
+ description:
168
+ "Place an outbound PSTN phone call to an E.164 number. Bridges audio over an encrypted SIP relay (LiveKit SIP / Telnyx); optional voice vocoder for anonymous calling. Returns session_id, room_name, zone + per-minute cost, and minutes_remaining. Requires PSTN minutes in the wallet.",
169
+ inputSchema: mCALL_start_pstn_input,
170
+ handler: mCALL_start_pstn as MosaddTool["handler"],
171
+ },
172
+ {
173
+ name: "mCALL_end_pstn",
174
+ requires: "network",
175
+ description: "End an active PSTN call by session_id. Returns call duration and credits spent.",
176
+ inputSchema: mCALL_end_pstn_input,
177
+ handler: mCALL_end_pstn as MosaddTool["handler"],
178
+ },
179
+ {
180
+ name: "mCALL_acquire_number",
181
+ requires: "network",
182
+ description:
183
+ "Lease an ephemeral 'burner' phone number for ~10 minutes. While held, it is presented as your caller-ID on mCALL_start_pstn and can receive inbound calls; it auto-recycles when the lease lapses (unless on a live call). Idempotent — returns your existing lease if you already hold one. Returns the number, hold_until and seconds_remaining.",
184
+ inputSchema: mCALL_acquire_number_input,
185
+ handler: mCALL_acquire_number as MosaddTool["handler"],
186
+ },
187
+ {
188
+ name: "mCALL_my_numbers",
189
+ requires: "network",
190
+ description: "List the ephemeral numbers currently leased to you, each with its seconds_remaining.",
191
+ inputSchema: mCALL_my_numbers_input,
192
+ handler: mCALL_my_numbers as MosaddTool["handler"],
193
+ },
194
+ {
195
+ name: "mCALL_extend_number",
196
+ requires: "network",
197
+ description: "Extend the lease on a held ephemeral number by another ~10 minutes (by number_id, or your current lease).",
198
+ inputSchema: mCALL_extend_number_input,
199
+ handler: mCALL_extend_number as MosaddTool["handler"],
200
+ },
201
+ {
202
+ name: "mCALL_release_number",
203
+ requires: "network",
204
+ description: "Release an ephemeral number back to the pool before its lease expires (by number_id, or all you hold).",
205
+ inputSchema: mCALL_release_number_input,
206
+ handler: mCALL_release_number as MosaddTool["handler"],
207
+ },
208
+ {
209
+ name: "mCALL_answer",
210
+ requires: "network",
211
+ description:
212
+ "Answer an inbound call to your burner number. Pass the room_name from the inbound_call event; returns a LiveKit token + url so your client joins the room and bridges audio (publish a vocoder track to mask your voice on answer).",
213
+ inputSchema: mCALL_answer_input,
214
+ handler: mCALL_answer as MosaddTool["handler"],
215
+ },
216
+ ];