@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
@@ -0,0 +1,108 @@
1
+ /**
2
+ * comms_embed — let a builder-agent drop a LIVE mosadd channel into the app/site
3
+ * it is generating.
4
+ *
5
+ * Mints a publishable embed key (`m_pk_live_…`) scoped to a channel + the app's
6
+ * domain(s) via the `embed-keys` Edge Function, and returns a paste-in HTML
7
+ * snippet that loads the mosadd widget from the CDN (embed.mosadd.com/v1.js).
8
+ *
9
+ * Security: the publishable key is safe to ship in HTML — it can ONLY mint
10
+ * channel-scoped JWTs (the widget exchanges it at runtime via `mirc-embed-token`,
11
+ * validated against the key's origin allow-list). Your hub key (`mosadd_sk_live_…`)
12
+ * never enters the browser. The action is owned by the calling user (user-JWT
13
+ * scoped — `mosadd login` / MOSADD_USER_JWT / hub-key exchange).
14
+ *
15
+ * Reuses the shipped embed infra (apps/embed widget + embed-keys + mirc-embed-token).
16
+ * RFC 0001: channel-agnostic capability → `comms_` namespace (not an m<MODULE>_ prefix).
17
+ */
18
+
19
+ import { z } from "zod";
20
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
21
+ import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
22
+
23
+ /** Widget CDN base. Override with MOSADD_EMBED_CDN for self-host / dev. */
24
+ const EMBED_CDN = (process.env.MOSADD_EMBED_CDN ?? "https://embed.mosadd.com").replace(/\/+$/, "");
25
+
26
+ const POSITIONS = ["inline", "sidebar-left", "sidebar-right", "floating-bl", "floating-br", "fullscreen"] as const;
27
+ const SKINS = ["default", "retro-irc-1990", "terminal", "minimal-dark", "minimal-light"] as const;
28
+
29
+ const embed_create_input = z.object({
30
+ channel: z
31
+ .string().min(1).max(128).regex(/^[A-Za-z0-9_-]+$/)
32
+ .describe("The mIRC channel id everyone on the embed shares (e.g. 'acme-support'). Auto-created on first message if new."),
33
+ allowed_origins: z
34
+ .array(z.string().min(1)).min(1).max(10)
35
+ .describe("REQUIRED. Domain(s) where the widget will be served — the key only works from these origins. Use the host(s) of the app you're building, e.g. ['app.acme.com','*.acme.com']. For local testing use mode:'test' and e.g. 'localhost:3000'."),
36
+ name: z.string().max(64).optional().describe("Label for the key in the owner's dashboard. Default 'embed: <channel>'."),
37
+ position: z.enum(POSITIONS).optional().describe("Where the widget renders. Default 'inline'."),
38
+ skin: z.enum(SKINS).optional().describe("Visual skin. Default 'default' (mosadd-branded retro mIRC)."),
39
+ title: z.string().max(60).optional().describe("Header title shown in the widget. Default 'mIRC'."),
40
+ anon: z.boolean().optional().describe("Allow visitors to join with just a nick (no mosadd account). Default true."),
41
+ locale: z.enum(["en", "pl"]).optional().describe("Widget UI language. Default 'en'."),
42
+ mode: z.enum(["live", "test"]).optional().describe("Key mode — 'test' for local/dev origins, 'live' for production. Default 'live'."),
43
+ });
44
+
45
+ interface EmbedKeyResult {
46
+ id?: string;
47
+ key?: string;
48
+ pk_prefix?: string;
49
+ allowed_channels?: string[];
50
+ error?: string;
51
+ }
52
+
53
+ interface EmbedCreateResult {
54
+ embed_key: string;
55
+ channel: string;
56
+ allowed_origins: string[];
57
+ snippet: string;
58
+ }
59
+
60
+ /** HTML-attr-safe: drop quotes/angle brackets (inputs are already length-bounded). */
61
+ const attrSafe = (s: string): string => s.replace(/["'<>]/g, "");
62
+
63
+ function buildSnippet(input: z.infer<typeof embed_create_input>, key: string): string {
64
+ const attrs = [`data-channel="${attrSafe(input.channel)}"`, `data-position="${input.position ?? "inline"}"`];
65
+ if (input.skin) attrs.push(`data-skin="${input.skin}"`);
66
+ if (input.title) attrs.push(`data-title="${attrSafe(input.title)}"`);
67
+ if (input.anon === false) attrs.push(`data-anon="false"`);
68
+ if (input.locale) attrs.push(`data-locale="${input.locale}"`);
69
+ return (
70
+ `<div id="mosadd-mirc" ${attrs.join(" ")}></div>\n` +
71
+ `<script src="${EMBED_CDN}/v1.js" data-key="${key}"></script>`
72
+ );
73
+ }
74
+
75
+ async function embed_create(
76
+ input: z.infer<typeof embed_create_input>,
77
+ ctx: MosaddToolContext,
78
+ ): Promise<EmbedCreateResult> {
79
+ readSupabaseEnv();
80
+ ctx.log("debug", "comms_embed_create minting embed key", { channel: input.channel, origins: input.allowed_origins.length });
81
+
82
+ const res = await invokeFunction<EmbedKeyResult>("embed-keys", {
83
+ name: input.name ?? `embed: ${input.channel}`,
84
+ channels: [input.channel],
85
+ allowed_origins: input.allowed_origins,
86
+ mode: input.mode ?? "live",
87
+ });
88
+ if (res.error) throw new Error(res.error);
89
+ if (!res.key) throw new Error("embed-keys returned no publishable key (missing `key`).");
90
+
91
+ return {
92
+ embed_key: res.key,
93
+ channel: input.channel,
94
+ allowed_origins: input.allowed_origins,
95
+ snippet: buildSnippet(input, res.key),
96
+ };
97
+ }
98
+
99
+ export const embedTools: MosaddTool[] = [
100
+ {
101
+ name: "comms_embed_create",
102
+ requires: "network",
103
+ description:
104
+ "Embed a LIVE mosadd chat channel into an app/site you're building (great for builder-agents on Lovable/Bolt/Cursor/v0). Mints a publishable embed key scoped to a channel + the app's domain(s) and returns a ready-to-paste HTML snippet (a <div> + <script src=embed.mosadd.com/v1.js data-key=…>). Visitors of the host page chat in real time (anonymous nick or mosadd login). REQUIRES `allowed_origins` — the domain(s) the app is served from (the key only works there). The publishable key is browser-safe (mints only channel-scoped JWTs); your hub key never leaves the server. Returns { embed_key, channel, allowed_origins, snippet }.",
105
+ inputSchema: embed_create_input,
106
+ handler: embed_create as MosaddTool["handler"],
107
+ },
108
+ ];
@@ -1,37 +1,76 @@
1
- /**
2
- * Tool registry. Each m* module contributes a set of tools.
3
- *
4
- * Phase 1 MVP (shipped): mDM, mIRC, mROOM, mAIL.
5
- * Phase 1 full: + mTALK, mCALL, mIRL, plus bridges (mMATRIX, mDISCORD, mTELEGRAM, mSLACK, mSIGNAL).
6
- */
7
-
8
- import type { MosaddTool } from "../types.js";
9
- import { mdmTools } from "./mdm.js";
10
- import { mircTools } from "./mirc.js";
11
- import { mircMembersTools } from "./mirc-members.js";
12
- import { mroomTools } from "./mroom.js";
13
- import { mroomMessagesTools } from "./mroom-messages.js";
14
- import { mailTools } from "./mail.js";
15
- import { makeCapabilitiesTool } from "./capabilities.js";
16
-
17
- /** The m* channel tools (everything except the meta discovery tool). */
18
- const channelTools: MosaddTool[] = [
19
- ...mdmTools,
20
- ...mircTools,
21
- ...mircMembersTools,
22
- ...mroomTools,
23
- ...mroomMessagesTools,
24
- ...mailTools,
25
- // mtalkTools, mcallTools, mirlTools,
26
- // mmatrixTools, mdiscordTools, mtelegramTools, mslackTools, msignalTools,
27
- //
28
- // Each m* module registers its tools here as it ships.
29
- // RFC required to add a new m* module (see docs/rfcs/0001-module-naming.md).
30
- ];
31
-
32
- export const allTools: MosaddTool[] = [
33
- ...channelTools,
34
- // comms_capabilities: one-call discovery of every tool's `requires` flag,
35
- // so carrier-aware hosts (cymru-os) can gate the tool list by transport.
36
- makeCapabilitiesTool(channelTools),
37
- ];
1
+ /**
2
+ * Tool registry. Each m* module contributes a set of tools.
3
+ *
4
+ * Live modules (5): mDM, mIRC, mTALK, mp0st, mRAG (58 channel tools) + comms (4)
5
+ * + threat_catalog/threat_classify (pure defensive engine, LINEAR-3498) = 64 callable.
6
+ * mROOM was KILLED (LINEAR-3414, channel re-cut → ephemeral private mIRC): its tools
7
+ * live in tools/mroom.ts + mroom-messages.ts but are NOT registered here.
8
+ * Plus action links: comms_action_create (agent → user one-link browser action,
9
+ * incl. screen_share) + comms_action_frame_get (see the recipient's shared screen).
10
+ * mURL is a consumer/brand surface (murl.mosadd.com), NOT a dev product — its tools
11
+ * live in tools/murl.ts but are NOT registered here (founder decision 2026-06-10).
12
+ * mCALL is carrier-pending (no telephony carrier live yet): its tools live in
13
+ * tools/mcall.ts but are NOT registered here, so an agent only ever discovers
14
+ * tools that actually work. Re-register the one line below when a carrier ships.
15
+ */
16
+
17
+ import type { MosaddTool } from "../types.js";
18
+ import { mdmTools } from "./mdm.js";
19
+ import { mdmVoiceTools } from "./mdm-voice.js";
20
+ import { mircTools } from "./mirc.js";
21
+ import { mircMembersTools } from "./mirc-members.js";
22
+ import { mircMessagesTools } from "./mirc-messages.js";
23
+ import { mircEdgeTools } from "./mirc-edge.js";
24
+ // import { mroomTools } from "./mroom.js"; // mROOM: killed (LINEAR-3414) — not registered
25
+ // import { mroomMessagesTools } from "./mroom-messages.js"; // mROOM: killed (LINEAR-3414) — not registered
26
+ import { mailTools } from "./mail.js";
27
+ // import { mailProvenanceTools } from "./mail-provenance.js"; // scaffold (mp0st_send_as_agent) — not registered, see below
28
+ import { mtalkTools } from "./mtalk.js";
29
+ import { attachmentTools } from "./attachments.js";
30
+ // import { pttIngestTools } from "./ptt-ingest.js"; // scaffold (mTALK_ingest_ptt) — not registered, see below
31
+ // import { mcallTools } from "./mcall.js"; // mCALL: carrier-pending — not registered (see header note)
32
+ import { knowledgeTools } from "./knowledge.js";
33
+ import { actionTools } from "./actions.js";
34
+ import { embedTools } from "./embed.js";
35
+ import { threatTools } from "./threat.js";
36
+ // import { murlTools } from "./murl.js"; // mURL: brand/consumer surface, not a dev product — not registered
37
+ import { makeCapabilitiesTool } from "./capabilities.js";
38
+
39
+ /** The m* channel tools (everything except the meta discovery tool). */
40
+ const channelTools: MosaddTool[] = [
41
+ ...mdmTools,
42
+ ...mdmVoiceTools,
43
+ ...mircTools,
44
+ ...mircMembersTools,
45
+ ...mircMessagesTools,
46
+ ...mircEdgeTools,
47
+ // ...mroomTools, // mROOM: killed (LINEAR-3414) — channel re-cut into ephemeral private mIRC
48
+ // ...mroomMessagesTools, // mROOM: killed (LINEAR-3414)
49
+ ...mailTools,
50
+ // ...mailProvenanceTools, // mp0st_send_as_agent: SCAFFOLD — calls a non-existent hub-claim-mint
51
+ // endpoint (404s every call) + sends provenance body fields the EF never reads. Unregister until
52
+ // rewired onto hub-key-exchange (agent_id/task_id + mosadd_hub JWT claim). See consistency ticket.
53
+ ...mtalkTools,
54
+ ...attachmentTools,
55
+ // ...pttIngestTools, // mTALK_ingest_ptt: SCAFFOLD — request body doesn't match the deployed
56
+ // ptt-ingest EF (needs {direction, audio_base64, mime_type, message_id|thread_id} → 400s every
57
+ // call) and the PTT→RAG path needs rework. Unregister until both are fixed. See consistency ticket.
58
+ ...knowledgeTools,
59
+ ...actionTools, // Action links (Tier 1): agent → user one-link browser action via action-create EF
60
+ ...embedTools, // comms_embed_create: agent embeds a live channel into the app it builds (embed-keys EF + embed.mosadd.com widget)
61
+ ...threatTools, // threat_catalog + threat_classify: pure defensive threat-event engine (@mosadd/threat-engine, LINEAR-3498)
62
+ // ...murlTools, // mURL: brand/consumer surface (murl.mosadd.com), not a dev product
63
+ // ...mcallTools, // mCALL: carrier-pending (no telephony carrier live) — re-register when a carrier is configured
64
+ // mirlTools,
65
+ // mmatrixTools, mdiscordTools, mtelegramTools, mslackTools, msignalTools,
66
+ //
67
+ // Each m* module registers its tools here as it ships.
68
+ // RFC required to add a new m* module (see docs/rfcs/0001-module-naming.md).
69
+ ];
70
+
71
+ export const allTools: MosaddTool[] = [
72
+ ...channelTools,
73
+ // comms_capabilities: one-call discovery of every tool's `requires` flag,
74
+ // so carrier-aware hosts (cymru-os) can gate the tool list by transport.
75
+ makeCapabilitiesTool(channelTools),
76
+ ];
@@ -0,0 +1,191 @@
1
+ /**
2
+ * mRAG — Knowledge Base (RAG): search and reason over the user's own mosadd data.
3
+ *
4
+ * This is the developer-facing surface of the RAG pipeline that already runs
5
+ * inside the mosadd backend: every message/email/call is embedded into a
6
+ * private per-user vector index (rag_embeddings) with hybrid vector + BM25
7
+ * retrieval, Cohere reranking, and a freshness lane for just-sent items. The
8
+ * `mRAG_search` tool lets an AGENT query that index — semantic recall over
9
+ * the user's communications — WITHOUT the mosadd.com app. It is the dev-product
10
+ * form of RAG (decision C): the same engine, exposed as one MCP tool.
11
+ *
12
+ * Wired to the mosadd backend's `rag-query` Edge Function. The answer + cited sources
13
+ * come back grounded strictly in the user's indexed data (no fabrication).
14
+ *
15
+ * Plan note: on the hosted hub this tool is gated by plan (free = off,
16
+ * pro/team = on); BYOK/self-host runs it against the user's own backend. Gating
17
+ * is enforced at the hub, not in this tool.
18
+ */
19
+
20
+ import { z } from "zod";
21
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
22
+ import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
23
+
24
+ const mRAG_search_input = z.object({
25
+ query: z
26
+ .string()
27
+ .min(1)
28
+ .max(2_000)
29
+ .describe("Natural-language question to answer from the user's own indexed messages/emails/calls/notes."),
30
+ top_k: z
31
+ .number()
32
+ .int()
33
+ .min(1)
34
+ .max(25)
35
+ .optional()
36
+ .describe("Max number of source chunks to retrieve and ground the answer in. Default 8."),
37
+ source_types: z
38
+ .array(z.enum(["message", "email", "call", "note", "contact"]))
39
+ .optional()
40
+ .describe("Restrict retrieval to these source types. Omit to search everything."),
41
+ thread_id: z
42
+ .string()
43
+ .optional()
44
+ .describe("Optional: restrict retrieval to a single thread id (e.g. a dm:/chat: thread)."),
45
+ });
46
+
47
+ interface RagSource {
48
+ source_type: string;
49
+ source_id: string;
50
+ thread_id: string | null;
51
+ similarity: number;
52
+ snippet: string;
53
+ created_at: string;
54
+ }
55
+
56
+ async function mRAG_search(
57
+ input: z.infer<typeof mRAG_search_input>,
58
+ ctx: MosaddToolContext,
59
+ ): Promise<{ answer: string; sources: RagSource[]; chunks_found: number }> {
60
+ readSupabaseEnv();
61
+ ctx.log("debug", "mRAG_search via rag-query", { top_k: input.top_k ?? 8 });
62
+
63
+ type RagQueryResponse = {
64
+ answer?: string;
65
+ sources?: RagSource[];
66
+ chunks_found?: number;
67
+ };
68
+ const data = await invokeFunction<RagQueryResponse>("rag-query", {
69
+ query: input.query,
70
+ top_k: input.top_k ?? 8,
71
+ source_types: input.source_types ?? null,
72
+ thread_id: input.thread_id ?? null,
73
+ });
74
+
75
+ return {
76
+ answer: data.answer ?? "",
77
+ sources: data.sources ?? [],
78
+ chunks_found: data.chunks_found ?? (data.sources?.length ?? 0),
79
+ };
80
+ }
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
+
115
+ const mRAG_list_sources_input = z.object({});
116
+
117
+ interface RagSourceEntry {
118
+ source_type: string;
119
+ source_id: string | null;
120
+ thread_id: string | null;
121
+ title: string | null;
122
+ chunks: number;
123
+ first_indexed: string;
124
+ last_indexed: string;
125
+ }
126
+
127
+ async function mRAG_list_sources(
128
+ _input: z.infer<typeof mRAG_list_sources_input>,
129
+ ctx: MosaddToolContext,
130
+ ): Promise<{ sources: RagSourceEntry[]; total_sources: number; total_chunks: number }> {
131
+ readSupabaseEnv();
132
+ ctx.log("debug", "mRAG_list_sources via rag-sources");
133
+ return await invokeFunction("rag-sources", { action: "list" });
134
+ }
135
+
136
+ const mRAG_delete_input = z
137
+ .object({
138
+ source_id: z.string().optional().describe("Delete every indexed chunk with this source_id (from mRAG_list_sources)."),
139
+ thread_id: z.string().optional().describe("Delete every indexed chunk associated with this thread_id."),
140
+ })
141
+ .refine((v) => v.source_id || v.thread_id, {
142
+ message: "Provide source_id or thread_id — mRAG_delete refuses to purge the whole index.",
143
+ });
144
+
145
+ async function mRAG_delete(
146
+ input: z.infer<typeof mRAG_delete_input>,
147
+ ctx: MosaddToolContext,
148
+ ): Promise<{ ok: true; deleted: number; source_id: string | null; thread_id: string | null }> {
149
+ readSupabaseEnv();
150
+ ctx.log("debug", "mRAG_delete via rag-sources", { source_id: input.source_id, thread_id: input.thread_id });
151
+ return await invokeFunction("rag-sources", {
152
+ action: "delete",
153
+ source_id: input.source_id ?? null,
154
+ thread_id: input.thread_id ?? null,
155
+ });
156
+ }
157
+
158
+ export const knowledgeTools: MosaddTool[] = [
159
+ {
160
+ name: "mRAG_ingest",
161
+ requires: "network",
162
+ description:
163
+ "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.",
164
+ inputSchema: mRAG_ingest_input,
165
+ handler: mRAG_ingest as MosaddTool["handler"],
166
+ },
167
+ {
168
+ name: "mRAG_search",
169
+ requires: "network",
170
+ description:
171
+ "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.",
172
+ inputSchema: mRAG_search_input,
173
+ handler: mRAG_search as MosaddTool["handler"],
174
+ },
175
+ {
176
+ name: "mRAG_list_sources",
177
+ requires: "network",
178
+ description:
179
+ "List what is currently indexed in the user's private knowledge base, grouped by source (source_type, source_id, thread_id, title) with per-source chunk counts and first/last indexed timestamps. Use it to see what mRAG_search can recall, and to find a source_id to remove with mRAG_delete. Owner-scoped.",
180
+ inputSchema: mRAG_list_sources_input,
181
+ handler: mRAG_list_sources as MosaddTool["handler"],
182
+ },
183
+ {
184
+ name: "mRAG_delete",
185
+ requires: "network",
186
+ description:
187
+ "Remove indexed content from the user's knowledge base by source_id or thread_id (from mRAG_list_sources). Deletes every embedded chunk for that source so mRAG_search can no longer recall it. Requires source_id or thread_id (will not purge the whole index). Returns the number of chunks deleted. Owner-scoped.",
188
+ inputSchema: mRAG_delete_input,
189
+ handler: mRAG_delete as MosaddTool["handler"],
190
+ },
191
+ ];
@@ -0,0 +1,137 @@
1
+ /**
2
+ * mp0st provenance — agent-attributed email send.
3
+ *
4
+ * The plain `mp0st_send` (mail.ts) sends as the USER. When an AGENT sends mail on
5
+ * the user's behalf, the recipient (and the audit trail) should be able to tell
6
+ * it was agent-originated. Per the Lane A contract, `mp0st-send`, when called
7
+ * with a HUB-CLAIM JWT, stamps the row with:
8
+ * sent_by = 'agent', sent_by_agent_id, sent_by_task_id
9
+ *
10
+ * This tool mints/forwards that hub-claim JWT and sets the provenance fields.
11
+ *
12
+ * AUTH MODEL (differs from the rest of mp0st):
13
+ * - mp0st_send uses the user's Supabase session JWT (via invokeFunction).
14
+ * - mp0st_send_as_agent presents a HUB-CLAIM JWT (hub key → claim exchange) so
15
+ * mp0st-send can attribute the send to the agent/task.
16
+ *
17
+ * STATUS: scaffold. The hub-claim exchange endpoint is assumed (TODO Lane A —
18
+ * confirm the exact route + claim shape). Falls back to the user session JWT if
19
+ * no hub key is configured, with provenance fields passed through for the EF to
20
+ * honor once deployed.
21
+ */
22
+
23
+ import { z } from "zod";
24
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
25
+
26
+ const DEFAULT_SUPABASE_URL = "https://rooffhgbxafyjcwmwpsy.supabase.co";
27
+
28
+ function supabaseUrl(): string {
29
+ return (
30
+ process.env.MOSADD_SUPABASE_URL?.replace(/\/$/, "") ??
31
+ process.env.SUPABASE_URL?.replace(/\/$/, "") ??
32
+ DEFAULT_SUPABASE_URL
33
+ );
34
+ }
35
+
36
+ function hubKey(): string | null {
37
+ return process.env.MOSADD_API_KEY ?? process.env.MOSADD_HUB_KEY ?? null;
38
+ }
39
+
40
+ const EmailAddress = z.string().email().max(254);
41
+
42
+ const mp0st_send_as_agent_input = z.object({
43
+ to: z.union([EmailAddress, z.array(EmailAddress).min(1).max(50)]),
44
+ subject: z.string().min(1).max(998),
45
+ body_text: z.string().max(1_048_576).optional(),
46
+ body_html: z.string().max(1_048_576).optional(),
47
+ cc: z.array(EmailAddress).max(50).optional(),
48
+ bcc: z.array(EmailAddress).max(50).optional(),
49
+ reply_to: EmailAddress.optional(),
50
+ tracking: z.boolean().optional(),
51
+ agent_id: z
52
+ .string()
53
+ .min(1)
54
+ .max(120)
55
+ .describe("Stable id of the agent doing the send. Stamped as sent_by_agent_id for provenance."),
56
+ task_id: z
57
+ .string()
58
+ .min(1)
59
+ .max(120)
60
+ .optional()
61
+ .describe("Optional id of the task/run this send belongs to. Stamped as sent_by_task_id."),
62
+ });
63
+
64
+ /**
65
+ * Exchange the hub key for a hub-claim JWT that authorizes agent-attributed
66
+ * actions. TODO(Lane A): confirm endpoint + response. Mirrors the
67
+ * hub-mint-channel-token pattern in mirc-edge.ts.
68
+ */
69
+ async function mintHubClaim(agentId: string, taskId?: string): Promise<string> {
70
+ const key = hubKey();
71
+ if (!key) {
72
+ throw new Error("mp0st_send_as_agent needs MOSADD_API_KEY (hub key) to mint a provenance claim.");
73
+ }
74
+ const r = await fetch(`${supabaseUrl()}/functions/v1/hub-claim-mint`, {
75
+ method: "POST",
76
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${key}` },
77
+ body: JSON.stringify({ scope: "mail:send", agent_id: agentId, task_id: taskId ?? null }),
78
+ });
79
+ if (!r.ok) {
80
+ const b = await r.text().catch(() => "");
81
+ throw new Error(`hub-claim-mint ${r.status}: ${b.slice(0, 200)}`);
82
+ }
83
+ const data = (await r.json()) as { token?: string };
84
+ if (!data?.token) throw new Error("hub-claim-mint: no token in response");
85
+ return data.token;
86
+ }
87
+
88
+ async function mp0st_send_as_agent(
89
+ input: z.infer<typeof mp0st_send_as_agent_input>,
90
+ ctx: MosaddToolContext,
91
+ ): Promise<{ message_id: string; status: string; is_internal: boolean; sent_by: "agent" }> {
92
+ if (!input.body_text && !input.body_html) {
93
+ throw new Error("mp0st_send_as_agent requires at least one of body_text or body_html.");
94
+ }
95
+
96
+ // Present the hub-claim JWT directly to mp0st-send (NOT the user session client)
97
+ // so the EF attributes the row to the agent. TODO(Lane A): confirm mp0st-send
98
+ // accepts a Bearer hub-claim and reads sent_by_agent_id / sent_by_task_id.
99
+ const claim = await mintHubClaim(input.agent_id, input.task_id);
100
+ ctx.log("debug", "mp0st_send_as_agent invoking mp0st-send with hub-claim", { agent_id: input.agent_id });
101
+
102
+ const { agent_id, task_id, ...mailFields } = input;
103
+ const r = await fetch(`${supabaseUrl()}/functions/v1/mp0st-send`, {
104
+ method: "POST",
105
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${claim}` },
106
+ body: JSON.stringify({
107
+ ...mailFields,
108
+ sent_by: "agent",
109
+ sent_by_agent_id: agent_id,
110
+ sent_by_task_id: task_id ?? null,
111
+ }),
112
+ });
113
+ if (!r.ok) {
114
+ const b = await r.text().catch(() => "");
115
+ throw new Error(`mp0st-send ${r.status}: ${b.slice(0, 200)}`);
116
+ }
117
+ const res = (await r.json()) as { email_id?: string; status?: string; is_internal?: boolean; error?: string };
118
+ if (res.error) throw new Error(res.error);
119
+
120
+ return {
121
+ message_id: res.email_id ?? "",
122
+ status: res.status ?? "sent",
123
+ is_internal: res.is_internal ?? false,
124
+ sent_by: "agent",
125
+ };
126
+ }
127
+
128
+ export const mailProvenanceTools: MosaddTool[] = [
129
+ {
130
+ name: "mp0st_send_as_agent",
131
+ requires: "network",
132
+ description:
133
+ "Send an email ATTRIBUTED TO THE AGENT (provenance-stamped). Unlike mp0st_send (sends as the user), this stamps sent_by='agent' plus your agent_id and optional task_id onto the email record and audit trail — so recipients and compliance can see the mail was agent-originated. Auth: presents a hub-claim JWT (needs MOSADD_API_KEY). SCAFFOLD: depends on mp0st-send honoring the hub-claim + provenance fields (TODO Lane A).",
134
+ inputSchema: mp0st_send_as_agent_input,
135
+ handler: mp0st_send_as_agent as MosaddTool["handler"],
136
+ },
137
+ ];