@mosadd/mcp 3.0.0-alpha.4 → 3.0.0-alpha.6

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.
package/dist/index.d.ts CHANGED
@@ -186,10 +186,31 @@ declare function createMosaddServer(options?: MosaddServerOptions): McpServer;
186
186
  /**
187
187
  * Tool registry. Each m* module contributes a set of tools.
188
188
  *
189
- * Phase 1 MVP (shipped): mDM, mIRC, mROOM, mAIL.
190
- * Phase 1 full: + mTALK, mCALL, mIRL, plus bridges (mMATRIX, mDISCORD, mTELEGRAM, mSLACK, mSIGNAL).
189
+ * Live modules (6): mDM, mIRC, mROOM, mTALK, mAIL, mRAG — 52 tools + comms_capabilities.
190
+ * mCALL is carrier-pending (no telephony carrier live yet): its tools live in
191
+ * tools/mcall.ts but are NOT registered here, so an agent only ever discovers
192
+ * tools that actually work. Re-register the one line below when a carrier ships.
191
193
  */
192
194
 
193
195
  declare const allTools: MosaddTool[];
194
196
 
195
- export { type MosaddServerOptions, type MosaddTool, type MosaddToolContext, type ProviderRegistry, allTools, createMosaddServer, defaultProviders };
197
+ /**
198
+ * Supabase provider for the alpha MCP server.
199
+ *
200
+ * Local BYOK mode: user supplies their own Supabase URL + anon key + user JWT
201
+ * via env vars. The MCP server creates a per-request Supabase client and
202
+ * invokes the mosadd Edge Functions on the user's behalf.
203
+ *
204
+ * In Phase 2 this is replaced by the hosted gateway (mcp.mosadd.com) which
205
+ * holds keys server-side via the BYOK broker.
206
+ */
207
+
208
+ interface SupabaseEnv {
209
+ url: string;
210
+ anonKey: string;
211
+ userJwt?: string;
212
+ }
213
+ /** Run `fn` (and every tool call it triggers) with a per-request Supabase session. */
214
+ declare function runWithSupabaseEnv<T>(env: SupabaseEnv, fn: () => T): T;
215
+
216
+ export { type MosaddServerOptions, type MosaddTool, type MosaddToolContext, type ProviderRegistry, type SupabaseEnv, allTools, createMosaddServer, defaultProviders, runWithSupabaseEnv };
package/dist/index.js CHANGED
@@ -1,11 +1,13 @@
1
1
  import {
2
2
  allTools,
3
3
  createMosaddServer,
4
- defaultProviders
5
- } from "./chunk-YDFU6S5E.js";
4
+ defaultProviders,
5
+ runWithSupabaseEnv
6
+ } from "./chunk-KAPG5FBN.js";
6
7
  import "./chunk-Z7WR52GE.js";
7
8
  export {
8
9
  allTools,
9
10
  createMosaddServer,
10
- defaultProviders
11
+ defaultProviders,
12
+ runWithSupabaseEnv
11
13
  };
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@mosadd/mcp",
3
- "version": "3.0.0-alpha.4",
4
- "description": "Model Context Protocol server for mosadd. Exposes m* OS modules (mDM, mTALK, mAIL, mCALL, mIRC, mIRL, mROOM, and bridges) as MCP tools to any agent runtime (Claude Code, Cursor, Windsurf, Cline, ChatGPT Apps, Lovable, Bolt, Goose, Manus, custom).",
5
- "homepage": "https://github.com/Hei33enberg/mosADD-OS/tree/main/packages/mcp",
3
+ "version": "3.0.0-alpha.6",
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",
6
6
  "repository": {
7
7
  "type": "git",
8
- "url": "https://github.com/Hei33enberg/mosADD-OS.git",
8
+ "url": "https://github.com/Hei33enberg/mosadd-os.git",
9
9
  "directory": "packages/mcp"
10
10
  },
11
11
  "license": "Apache-2.0",
@@ -140,7 +140,7 @@ describe("@mosadd/mcp — integration (real stdio)", () => {
140
140
  expect(names).toContain("mROOM_create_guest_link");
141
141
  expect(names).toContain("mAIL_send");
142
142
  expect(names).toContain("mTALK_press"); // mTALK PTT now shipped
143
- expect(names).toContain("mKB_search"); // mKB RAG-for-devs now shipped
143
+ expect(names).toContain("mRAG_search"); // mRAG RAG-for-devs now shipped
144
144
  expect(names).toContain("mIRC_post_message"); // channel messaging now shipped
145
145
 
146
146
  // Total tool count today (grows as modules ship)
package/src/index.ts CHANGED
@@ -15,3 +15,5 @@ export type {
15
15
  ProviderRegistry,
16
16
  } from "./types.js";
17
17
  export { allTools } from "./tools/index.js";
18
+ // Per-request session context for the hosted HTTP gateway (mcp.mosadd.com).
19
+ export { runWithSupabaseEnv, type SupabaseEnv } from "./providers/supabase.js";
@@ -2,7 +2,7 @@
2
2
  * SupabaseDmProvider — the default (network) DmProvider.
3
3
  *
4
4
  * Implements the transport-agnostic `DmProvider` contract from
5
- * `@mosadd/providers` over the m0ssad-3 Supabase Edge Functions
5
+ * `@mosadd/providers` over the mosadd Supabase Edge Functions
6
6
  * (`message-send` / `message-list`). This is the strangler-fig network path;
7
7
  * a carrier-aware host injects a different DmProvider for radio.
8
8
  *
@@ -70,7 +70,7 @@ export class SupabaseDmProvider implements DmProvider {
70
70
 
71
71
  async publishPrekeyBundle(bundle: Uint8Array): Promise<void> {
72
72
  // Network key directory. Server-side fn (`prekey-bundle-publish`) is the
73
- // m0ssad-3 hub's responsibility — it stores the opaque bundle keyed by the
73
+ // the mosadd hub's responsibility — it stores the opaque bundle keyed by the
74
74
  // caller's identity (resolved from the JWT). mosadd-os just ships bytes.
75
75
  await invokeFunction<{ ok: boolean }>("prekey-bundle-publish", {
76
76
  bundle: Buffer.from(bundle).toString("base64"),
@@ -3,12 +3,13 @@
3
3
  *
4
4
  * Local BYOK mode: user supplies their own Supabase URL + anon key + user JWT
5
5
  * via env vars. The MCP server creates a per-request Supabase client and
6
- * invokes the m0ssad-3 Edge Functions on the user's behalf.
6
+ * invokes the mosadd Edge Functions on the user's behalf.
7
7
  *
8
8
  * In Phase 2 this is replaced by the hosted gateway (mcp.mosadd.com) which
9
9
  * holds keys server-side via the BYOK broker.
10
10
  */
11
11
 
12
+ import { AsyncLocalStorage } from "node:async_hooks";
12
13
  import { createClient, type SupabaseClient } from "@supabase/supabase-js";
13
14
  import { loadSession, isSessionExpired } from "../config.js";
14
15
 
@@ -18,6 +19,23 @@ export interface SupabaseEnv {
18
19
  userJwt?: string;
19
20
  }
20
21
 
22
+ /**
23
+ * Per-request session context for the hosted HTTP gateway (mcp.mosadd.com).
24
+ *
25
+ * stdio runs one user per process, so credentials live in process.env. The
26
+ * hosted gateway serves MANY users from one process — sharing process.env would
27
+ * leak user A's JWT into user B's concurrent request. The gateway instead
28
+ * resolves the caller's session (Bearer api key → hub-key-exchange) and runs the
29
+ * whole request inside `runWithSupabaseEnv(env, …)`; `readSupabaseEnv()` reads
30
+ * this store first and falls back to process.env, so stdio is unaffected.
31
+ */
32
+ const requestEnv = new AsyncLocalStorage<SupabaseEnv>();
33
+
34
+ /** Run `fn` (and every tool call it triggers) with a per-request Supabase session. */
35
+ export function runWithSupabaseEnv<T>(env: SupabaseEnv, fn: () => T): T {
36
+ return requestEnv.run(env, fn);
37
+ }
38
+
21
39
  export class MissingSupabaseEnvError extends Error {
22
40
  constructor(missing: string[]) {
23
41
  super(
@@ -29,6 +47,12 @@ export class MissingSupabaseEnvError extends Error {
29
47
  }
30
48
 
31
49
  export function readSupabaseEnv(): SupabaseEnv {
50
+ // Hosted HTTP gateway: a per-request session set via runWithSupabaseEnv wins
51
+ // over any process-global env (multi-tenant safety). stdio has no store → falls
52
+ // through to the env/login resolution below.
53
+ const perRequest = requestEnv.getStore();
54
+ if (perRequest) return perRequest;
55
+
32
56
  // Canonical env vars are MOSADD_*; the legacy M0SSAD_* names are still
33
57
  // honored (deprecated) so anyone who set them before the brand sweep keeps
34
58
  // working. Env vars take precedence; fall back to the session saved by
@@ -70,7 +94,7 @@ export function getSupabase(env: SupabaseEnv = readSupabaseEnv()): SupabaseClien
70
94
  }
71
95
 
72
96
  /**
73
- * Invoke a m0ssad-3 Edge Function. Wraps `supabase.functions.invoke` with
97
+ * Invoke a the legacy mosadd consumer-app repo Edge Function. Wraps `supabase.functions.invoke` with
74
98
  * normalized error handling so MCP tool handlers can throw clean errors that
75
99
  * agents can reason about.
76
100
  */
@@ -1,34 +1,42 @@
1
1
  /**
2
2
  * Tool registry. Each m* module contributes a set of tools.
3
3
  *
4
- * Phase 1 MVP (shipped): mDM, mIRC, mROOM, mAIL.
5
- * Phase 1 full: + mTALK, mCALL, mIRL, plus bridges (mMATRIX, mDISCORD, mTELEGRAM, mSLACK, mSIGNAL).
4
+ * Live modules (6): mDM, mIRC, mROOM, mTALK, mAIL, mRAG — 52 tools + comms_capabilities.
5
+ * mCALL is carrier-pending (no telephony carrier live yet): its tools live in
6
+ * tools/mcall.ts but are NOT registered here, so an agent only ever discovers
7
+ * tools that actually work. Re-register the one line below when a carrier ships.
6
8
  */
7
9
 
8
10
  import type { MosaddTool } from "../types.js";
9
11
  import { mdmTools } from "./mdm.js";
12
+ import { mdmVoiceTools } from "./mdm-voice.js";
10
13
  import { mircTools } from "./mirc.js";
11
14
  import { mircMembersTools } from "./mirc-members.js";
12
15
  import { mircMessagesTools } from "./mirc-messages.js";
16
+ import { mircEdgeTools } from "./mirc-edge.js";
13
17
  import { mroomTools } from "./mroom.js";
14
18
  import { mroomMessagesTools } from "./mroom-messages.js";
15
19
  import { mailTools } from "./mail.js";
16
20
  import { mtalkTools } from "./mtalk.js";
21
+ // import { mcallTools } from "./mcall.js"; // mCALL: carrier-pending — not registered (see header note)
17
22
  import { knowledgeTools } from "./knowledge.js";
18
23
  import { makeCapabilitiesTool } from "./capabilities.js";
19
24
 
20
25
  /** The m* channel tools (everything except the meta discovery tool). */
21
26
  const channelTools: MosaddTool[] = [
22
27
  ...mdmTools,
28
+ ...mdmVoiceTools,
23
29
  ...mircTools,
24
30
  ...mircMembersTools,
25
31
  ...mircMessagesTools,
32
+ ...mircEdgeTools,
26
33
  ...mroomTools,
27
34
  ...mroomMessagesTools,
28
35
  ...mailTools,
29
36
  ...mtalkTools,
30
37
  ...knowledgeTools,
31
- // mcallTools, mirlTools,
38
+ // ...mcallTools, // mCALL: carrier-pending (no telephony carrier live) — re-register when a carrier is configured
39
+ // mirlTools,
32
40
  // mmatrixTools, mdiscordTools, mtelegramTools, mslackTools, msignalTools,
33
41
  //
34
42
  // Each m* module registers its tools here as it ships.
@@ -1,15 +1,15 @@
1
1
  /**
2
- * mKB — Knowledge Base (RAG): search and reason over the user's own mosadd data.
2
+ * mRAG — Knowledge Base (RAG): search and reason over the user's own mosadd data.
3
3
  *
4
4
  * This is the developer-facing surface of the RAG pipeline that already runs
5
5
  * inside the mosadd backend: every message/email/call is embedded into a
6
6
  * private per-user vector index (rag_embeddings) with hybrid vector + BM25
7
7
  * retrieval, Cohere reranking, and a freshness lane for just-sent items. The
8
- * `mKB_search` tool lets an AGENT query that index — semantic recall over
8
+ * `mRAG_search` tool lets an AGENT query that index — semantic recall over
9
9
  * the user's communications — WITHOUT the mosadd.com app. It is the dev-product
10
10
  * form of RAG (decision C): the same engine, exposed as one MCP tool.
11
11
  *
12
- * Wired to the m0ssad-3 `rag-query` Edge Function. The answer + cited sources
12
+ * Wired to the mosadd backend's `rag-query` Edge Function. The answer + cited sources
13
13
  * come back grounded strictly in the user's indexed data (no fabrication).
14
14
  *
15
15
  * Plan note: on the hosted hub this tool is gated by plan (free = off,
@@ -21,7 +21,7 @@ import { z } from "zod";
21
21
  import type { MosaddTool, MosaddToolContext } from "../types.js";
22
22
  import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
23
23
 
24
- const mKB_search_input = z.object({
24
+ const mRAG_search_input = z.object({
25
25
  query: z
26
26
  .string()
27
27
  .min(1)
@@ -53,12 +53,12 @@ interface RagSource {
53
53
  created_at: string;
54
54
  }
55
55
 
56
- async function mKB_search(
57
- input: z.infer<typeof mKB_search_input>,
56
+ async function mRAG_search(
57
+ input: z.infer<typeof mRAG_search_input>,
58
58
  ctx: MosaddToolContext,
59
59
  ): Promise<{ answer: string; sources: RagSource[]; chunks_found: number }> {
60
60
  readSupabaseEnv();
61
- ctx.log("debug", "mKB_search via rag-query", { top_k: input.top_k ?? 8 });
61
+ ctx.log("debug", "mRAG_search via rag-query", { top_k: input.top_k ?? 8 });
62
62
 
63
63
  type RagQueryResponse = {
64
64
  answer?: string;
@@ -79,13 +79,54 @@ async function mKB_search(
79
79
  };
80
80
  }
81
81
 
82
+ const mRAG_ingest_input = z.object({
83
+ content_text: z
84
+ .string()
85
+ .min(1)
86
+ .max(200_000)
87
+ .describe("Text to index into the user's private knowledge base (a note, document, transcript, pasted page…). Chunked + embedded server-side."),
88
+ source_type: z
89
+ .enum(["file", "note", "message", "email", "contact", "call"])
90
+ .optional()
91
+ .describe("What kind of source this is. Default 'file' (a document/note). Use 'note' for ad-hoc text."),
92
+ source_id: z.string().optional().describe("Optional stable id for the source so re-ingests can be grouped."),
93
+ thread_id: z.string().optional().describe("Optional thread id to associate this knowledge with (e.g. a dm:/chat: thread)."),
94
+ title: z.string().max(300).optional().describe("Optional human title, stored in metadata."),
95
+ });
96
+
97
+ async function mRAG_ingest(
98
+ input: z.infer<typeof mRAG_ingest_input>,
99
+ ctx: MosaddToolContext,
100
+ ): Promise<{ indexed: number; chunk_count: number }> {
101
+ readSupabaseEnv();
102
+ // rag-index accepts a fixed source_type set; map "note" → "file".
103
+ const backendType = input.source_type === "note" ? "file" : (input.source_type ?? "file");
104
+ ctx.log("debug", "mRAG_ingest via rag-index", { source_type: backendType });
105
+ const data = await invokeFunction<{ indexed?: number; chunk_count?: number }>("rag-index", {
106
+ source_type: backendType,
107
+ source_id: input.source_id ?? null,
108
+ thread_id: input.thread_id ?? null,
109
+ content_text: input.content_text,
110
+ metadata: { ...(input.title ? { title: input.title } : {}), ingested_via: "mRAG_ingest" },
111
+ });
112
+ return { indexed: data.indexed ?? 0, chunk_count: data.chunk_count ?? 0 };
113
+ }
114
+
82
115
  export const knowledgeTools: MosaddTool[] = [
83
116
  {
84
- name: "mKB_search",
117
+ name: "mRAG_ingest",
118
+ requires: "network",
119
+ description:
120
+ "Add text to the USER'S OWN private knowledge base so mRAG_search can recall it later. Pass content_text (a note, document, transcript, pasted page); it is semantically chunked, embedded (1536-d) and stored in the per-user vector index mRAG_search reads. Returns how many chunks were indexed. NOTE: indexed content is stored server-side in plaintext — NOT covered by the zero-knowledge / E2EE guarantee. Only ingest what the user opted to make searchable.",
121
+ inputSchema: mRAG_ingest_input,
122
+ handler: mRAG_ingest as MosaddTool["handler"],
123
+ },
124
+ {
125
+ name: "mRAG_search",
85
126
  requires: "network",
86
127
  description:
87
- "Search and answer questions over the USER'S OWN mosadd data (messages, emails, calls, notes) with a private RAG index — hybrid vector + keyword retrieval, reranked, grounded in cited sources (no fabrication). Use it to recall 'what did X say about Y', summarize a thread, or pull facts the user has received. Returns an answer plus the source snippets it used. This is agent memory (mKB = knowledge base) over the user's communications, available outside the mosadd app.",
88
- inputSchema: mKB_search_input,
89
- handler: mKB_search as MosaddTool["handler"],
128
+ "Search and answer questions over the USER'S OWN mosadd data (messages, emails, calls, notes) with a private per-user RAG index — hybrid vector + keyword retrieval, reranked, grounded in cited sources (no fabrication). Use it to recall 'what did X say about Y', summarize a thread, or pull facts the user has received. Returns an answer plus the source snippets it used. This is agent memory (mRAG = RAG over your own data) over the user's communications, available outside the mosadd app. NOTE: RAG requires content to be indexed server-side in plaintext, so anything searchable here is NOT covered by the zero-knowledge / E2EE guarantee — only data the user has explicitly opted into indexing is searchable. See docs/security/e2ee-posture.md.",
129
+ inputSchema: mRAG_search_input,
130
+ handler: mRAG_search as MosaddTool["handler"],
90
131
  },
91
132
  ];
package/src/tools/mail.ts CHANGED
@@ -2,9 +2,9 @@
2
2
  * mAIL — Email.
3
3
  *
4
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.
5
+ * in their app, outgoing mail flows through the mosadd mp0st pipeline.
6
6
  *
7
- * Phase 1 alpha: wired to m0ssad-3 `mp0st-send` + `mp0st-view` Edge Functions.
7
+ * Phase 1 alpha: wired to the mosadd backend's `mp0st-send` + `mp0st-view` Edge Functions.
8
8
  */
9
9
 
10
10
  import { z } from "zod";
@@ -37,6 +37,34 @@ const mAIL_view_input = z.object({
37
37
  message_id: MessageId,
38
38
  });
39
39
 
40
+ const mAIL_delete_input = z.object({
41
+ message_id: MessageId,
42
+ });
43
+
44
+ const mAIL_list_input = z.object({
45
+ direction: z
46
+ .enum(["inbound", "outbound"])
47
+ .optional()
48
+ .describe("Filter to received (inbound) or sent (outbound) mail. Omit for both."),
49
+ limit: z.number().int().min(1).max(200).optional().describe("Max emails to return. Default 50."),
50
+ before: z
51
+ .string()
52
+ .optional()
53
+ .describe("Pagination cursor: pass the previous response's next_cursor to get the next (older) page."),
54
+ });
55
+
56
+ interface MailListItem {
57
+ message_id: string;
58
+ direction: "inbound" | "outbound";
59
+ from: string;
60
+ to: string;
61
+ subject: string;
62
+ priority: string;
63
+ status: string;
64
+ sent_at: string;
65
+ snippet: string;
66
+ }
67
+
40
68
  // ---- Handlers ----
41
69
 
42
70
  async function mAIL_send(
@@ -68,9 +96,41 @@ async function mAIL_view(
68
96
  return await invokeFunction("mp0st-view", { message_id: input.message_id });
69
97
  }
70
98
 
99
+ async function mAIL_list(
100
+ input: z.infer<typeof mAIL_list_input>,
101
+ ctx: MosaddToolContext,
102
+ ): Promise<{ emails: MailListItem[]; next_cursor: string | null }> {
103
+ readSupabaseEnv();
104
+ ctx.log("debug", "mAIL_list invoking mp0st-list", { direction: input.direction });
105
+ return await invokeFunction<{ emails: MailListItem[]; next_cursor: string | null }>("mp0st-list", {
106
+ direction: input.direction ?? null,
107
+ limit: input.limit ?? 50,
108
+ before: input.before ?? null,
109
+ });
110
+ }
111
+
112
+ async function mAIL_delete(
113
+ input: z.infer<typeof mAIL_delete_input>,
114
+ ctx: MosaddToolContext,
115
+ ): Promise<{ ok: true; message_id: string; deleted: true }> {
116
+ readSupabaseEnv();
117
+ ctx.log("debug", "mAIL_delete invoking mp0st-delete", { message_id: input.message_id });
118
+ return await invokeFunction<{ ok: true; message_id: string; deleted: true }>("mp0st-delete", {
119
+ message_id: input.message_id,
120
+ });
121
+ }
122
+
71
123
  // ---- Registration ----
72
124
 
73
125
  export const mailTools: MosaddTool[] = [
126
+ {
127
+ name: "mAIL_list",
128
+ requires: "network",
129
+ description:
130
+ "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 mAIL_view to read a full message body.",
131
+ inputSchema: mAIL_list_input,
132
+ handler: mAIL_list as MosaddTool["handler"],
133
+ },
74
134
  {
75
135
  name: "mAIL_send",
76
136
  requires: "network",
@@ -86,4 +146,12 @@ export const mailTools: MosaddTool[] = [
86
146
  inputSchema: mAIL_view_input,
87
147
  handler: mAIL_view as MosaddTool["handler"],
88
148
  },
149
+ {
150
+ name: "mAIL_delete",
151
+ requires: "network",
152
+ description:
153
+ "Delete one of the user's emails by message_id (from mAIL_list). Soft-delete — it stops showing in mAIL_list. Owner-scoped: only your own mail.",
154
+ inputSchema: mAIL_delete_input,
155
+ handler: mAIL_delete as MosaddTool["handler"],
156
+ },
89
157
  ];
@@ -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
+ ];