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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +309 -0
  2. package/LICENSE +201 -201
  3. package/README.md +150 -126
  4. package/dist/bin/mcp.js +42 -3
  5. package/dist/chunk-BTAIZKYT.js +3800 -0
  6. package/dist/index.d.ts +118 -5
  7. package/dist/index.js +7 -3
  8. package/package.json +10 -7
  9. package/src/__tests__/channel-e2ee.test.ts +62 -0
  10. package/src/__tests__/golden-path.test.ts +139 -137
  11. package/src/__tests__/integration.test.ts +182 -178
  12. package/src/__tests__/knowledge-ingest.test.ts +114 -0
  13. package/src/__tests__/mdm-e2ee.test.ts +212 -178
  14. package/src/__tests__/mirc-invite.test.ts +112 -0
  15. package/src/__tests__/mtalk.test.ts +122 -122
  16. package/src/__tests__/presence.test.ts +199 -0
  17. package/src/__tests__/server.test.ts +71 -67
  18. package/src/__tests__/serverJsonVersion.test.ts +45 -0
  19. package/src/__tests__/tool-count-consistency.test.ts +199 -0
  20. package/src/bin/login.ts +138 -138
  21. package/src/bin/mcp.ts +145 -97
  22. package/src/config.ts +66 -66
  23. package/src/crypto/channel-e2ee.ts +288 -0
  24. package/src/crypto/mdm-session.ts +502 -403
  25. package/src/index.ts +19 -17
  26. package/src/observability/sentry.ts +79 -79
  27. package/src/providers/blob-upload.ts +116 -0
  28. package/src/providers/memory-voice.ts +79 -79
  29. package/src/providers/supabase-dm.ts +122 -117
  30. package/src/providers/supabase-voice.ts +91 -91
  31. package/src/providers/supabase.ts +231 -96
  32. package/src/server.ts +162 -105
  33. package/src/tools/__tests__/ragDeleteFoldsSourceId.test.ts +67 -0
  34. package/src/tools/actions.ts +166 -0
  35. package/src/tools/attachments.ts +276 -0
  36. package/src/tools/capabilities.ts +70 -68
  37. package/src/tools/embed.ts +110 -0
  38. package/src/tools/index.ts +181 -51
  39. package/src/tools/knowledge-graph.ts +186 -0
  40. package/src/tools/knowledge.ts +344 -132
  41. package/src/tools/mail-agentbox.ts +155 -0
  42. package/src/tools/mail-aliases.ts +25 -0
  43. package/src/tools/mail-provenance.ts +137 -0
  44. package/src/tools/mail.ts +403 -157
  45. package/src/tools/mcall.ts +216 -216
  46. package/src/tools/mdm-as-agent.ts +126 -0
  47. package/src/tools/mdm-voice.ts +220 -206
  48. package/src/tools/mdm.ts +73 -26
  49. package/src/tools/mirc-edge.ts +196 -190
  50. package/src/tools/mirc-members.ts +287 -177
  51. package/src/tools/mirc-messages.ts +76 -27
  52. package/src/tools/mirc.ts +308 -170
  53. package/src/tools/mroom-messages.ts +142 -142
  54. package/src/tools/mroom.ts +221 -221
  55. package/src/tools/mtalk.ts +131 -121
  56. package/src/tools/murl.ts +314 -0
  57. package/src/tools/presence.ts +442 -0
  58. package/src/tools/ptt-ingest.ts +99 -0
  59. package/src/tools/threat.ts +123 -0
  60. package/src/tools/voice-format.ts +28 -0
  61. package/src/types.ts +121 -85
  62. package/src/version.ts +8 -0
  63. package/src/voice/floor.ts +132 -132
  64. package/dist/chunk-4C36JDTJ.js +0 -1836
@@ -0,0 +1,110 @@
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
+ title: "Create website embed",
103
+ annotations: { readOnlyHint: false },
104
+ requires: "network",
105
+ description:
106
+ "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 }.",
107
+ inputSchema: embed_create_input,
108
+ handler: embed_create as MosaddTool["handler"],
109
+ },
110
+ ];
@@ -1,51 +1,181 @@
1
- /**
2
- * Tool registry. Each m* module contributes a set of tools.
3
- *
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.
8
- */
9
-
10
- import type { MosaddTool } from "../types.js";
11
- import { mdmTools } from "./mdm.js";
12
- import { mdmVoiceTools } from "./mdm-voice.js";
13
- import { mircTools } from "./mirc.js";
14
- import { mircMembersTools } from "./mirc-members.js";
15
- import { mircMessagesTools } from "./mirc-messages.js";
16
- import { mircEdgeTools } from "./mirc-edge.js";
17
- import { mroomTools } from "./mroom.js";
18
- import { mroomMessagesTools } from "./mroom-messages.js";
19
- import { mailTools } from "./mail.js";
20
- import { mtalkTools } from "./mtalk.js";
21
- // import { mcallTools } from "./mcall.js"; // mCALL: carrier-pending — not registered (see header note)
22
- import { knowledgeTools } from "./knowledge.js";
23
- import { makeCapabilitiesTool } from "./capabilities.js";
24
-
25
- /** The m* channel tools (everything except the meta discovery tool). */
26
- const channelTools: MosaddTool[] = [
27
- ...mdmTools,
28
- ...mdmVoiceTools,
29
- ...mircTools,
30
- ...mircMembersTools,
31
- ...mircMessagesTools,
32
- ...mircEdgeTools,
33
- ...mroomTools,
34
- ...mroomMessagesTools,
35
- ...mailTools,
36
- ...mtalkTools,
37
- ...knowledgeTools,
38
- // ...mcallTools, // mCALL: carrier-pending (no telephony carrier live) — re-register when a carrier is configured
39
- // mirlTools,
40
- // mmatrixTools, mdiscordTools, mtelegramTools, mslackTools, msignalTools,
41
- //
42
- // Each m* module registers its tools here as it ships.
43
- // RFC required to add a new m* module (see docs/rfcs/0001-module-naming.md).
44
- ];
45
-
46
- export const allTools: MosaddTool[] = [
47
- ...channelTools,
48
- // comms_capabilities: one-call discovery of every tool's `requires` flag,
49
- // so carrier-aware hosts (cymru-os) can gate the tool list by transport.
50
- makeCapabilitiesTool(channelTools),
51
- ];
1
+ /**
2
+ * Tool registry. Each m* module contributes a set of tools.
3
+ *
4
+ * User-facing modules (4): mDM, mIRC, mURL, mAYL — the re-arch (LINEAR-3938)
5
+ * mAYL replaces the old mp0st name (mp0st_* still registered as back-compat
6
+ * aliases via mail-aliases.ts; will be removed in a later alpha).
7
+ *
8
+ * Capabilities (not modules — cross-cutting agent tooling): mRAG, comms_.
9
+ * mTALK = voice tier inside mIRC, still its own tools for now; folding into
10
+ * mIRC_voice_* in a follow-up release. threat_* (threat_catalog + threat_classify)
11
+ * are REGISTERED (2026-07-15, founder directive + LINEAR-3498): pure/offline
12
+ * defensive classification over the threat taxonomy — the surveillance-era
13
+ * *marketing* was killed, the classification engine is real and wanted.
14
+ *
15
+ * 85 callable tools registered — the exact live count is exported as TOOL_COUNT
16
+ * (= allTools.length) below; ALWAYS reference that, never re-hard-code a number that drifts.
17
+ * Breakdown (2026-09-03, from allTools in this tree; the live tools/list on mcp.mosadd.com catches up
18
+ * when the alpha carrying mIRC_invite is published and the gateway redeployed):
19
+ * modules mDM 16 · mIRC 25 · mURL 7 · mAYL 16 = 64; capabilities mTALK 6 · mRAG 8 ·
20
+ * comms 5 (action_create/action_frame_get/embed_create/capabilities/session_attach) · Irondome/threat 2
21
+ * = 21. 64 + 21 = 85. (mIRC 25 = 24 + mIRC_invite added 2026-09-03 (LINEAR-5870): mIRC_join adds the KEY's
22
+ * identity while channel posts are signed by the AGENT, so every channel created from the toolkit was mute
23
+ * until its agent was added from the app — mIRC_invite wraps channel-members-manage `invite`: own agent →
24
+ * auto_joined, anyone else → invite code. mDM 16 = 14 + mDM_send_as_agent/mDM_list_my_agents added 2026-08-17: an MCP key
25
+ * is bound to a USER, so an agent runtime wired up with its owner's key spoke AS THE OWNER — these
26
+ * let it speak as an agent it OWNS instead, checked server-side. mRAG 8 = 4 search/ingest + 4 mRAG_graph_* traversal tools added 2026-08-11.
27
+ * comms_session_attach added 2026-08-14: a live agent session claims the account's reply lane so
28
+ * the cloud stand-in defers to it — the front door that used to be a script on one PC.)
29
+ * (History of this line drifting: the 2026-07-17 breakdown ended "= 69"
30
+ * — wrong twice over, its own terms summed to 71; the 07-30 rewrite said 73 and still had
31
+ * mAYL at 12 after mAYL_send_as_agent had been re-registered, so it stayed wrong through the
32
+ * four mAYL_agentbox_* tools landing on 08-06. Arithmetic in comments drifts; TOOL_COUNT
33
+ * doesn't — and since 08-11 the anti-drift gate checks the PER-MODULE numbers too, not just
34
+ * the total, so this comment cannot rot alone any more.)
35
+ * (mDM/mIRC each include their 2 attachment tools from attachments.ts.)
36
+ * Modules (4): mDM, mIRC, mURL, mAYL. Capabilities: mTALK (voice/PTT), mRAG, comms_, Irondome (threat_*).
37
+ * mp0st_* stay as DEPRECATED back-compat aliases for mAYL_* (removed in a later alpha).
38
+ * mAYL_send_as_agent + mTALK_ingest_ptt were RE-REGISTERED 2026-07-29: both had been disabled
39
+ * on 07-14 notes that had since become false, and both were re-verified on authenticated calls.
40
+ * comms_embed_create RE-REGISTERED 2026-07-17 (embed.mosadd.com/v1.js live — P3 of mURL→mIRC).
41
+ * mROOM was KILLED (LINEAR-3414, channel re-cut → ephemeral private mIRC): its tools
42
+ * live in tools/mroom.ts + mroom-messages.ts but are NOT registered here.
43
+ * Plus action links: comms_action_create (agent → user one-link browser action,
44
+ * incl. screen_share) + comms_action_frame_get (see the recipient's shared screen).
45
+ * mURL is a FULL registered dev module (revived, founder 2026-06-27) — IRC-for-URLs,
46
+ * agent-native; backends live (mosadd-edge + murl-channels EF). tools/murl.ts.
47
+ * mURL now has full lifecycle: read/post/presence/list_channels (hub-key) PLUS owner-side
48
+ * create/claim + update(branding/status) + delete (mURL_create/update/delete → murl-manage
49
+ * EF, owner-scoped via user JWT — same auth as mURL_list_channels action='mine').
50
+ * mCALL is carrier-pending (no telephony carrier live yet): its tools live in
51
+ * tools/mcall.ts but are NOT registered here, so an agent only ever discovers
52
+ * tools that actually work. Re-register the one line below when a carrier ships.
53
+ */
54
+
55
+ import type { MosaddTool } from "../types.js";
56
+ import { mdmTools } from "./mdm.js";
57
+ import { mdmAsAgentTools } from "./mdm-as-agent.js"; // mDM_send_as_agent + mDM_list_my_agents — 2026-08-17 (LINEAR-5620): a key is bound to a USER, so an agent runtime connected with its owner's key spoke AS THE OWNER and had no thread with him. These let that session speak as an agent it OWNS (verified server-side in mdm-send-as-agent).
58
+ import { mdmVoiceTools } from "./mdm-voice.js";
59
+ import { mircTools } from "./mirc.js";
60
+ import { mircMembersTools } from "./mirc-members.js";
61
+ import { mircMessagesTools } from "./mirc-messages.js";
62
+ import { mircEdgeTools } from "./mirc-edge.js";
63
+ // import { mroomTools } from "./mroom.js"; // mROOM: killed (LINEAR-3414) — not registered
64
+ // import { mroomMessagesTools } from "./mroom-messages.js"; // mROOM: killed (LINEAR-3414) — not registered
65
+ import { mailTools } from "./mail.js";
66
+ // import { mailAliasTools } from "./mail-aliases.js"; // mp0st_* aliases RETIRED 2026-07-15 (founder: unify on mAYL, drop the mp0st codename from every user-visible surface). Source kept for reference.
67
+ import { mailProvenanceTools } from "./mail-provenance.js"; // mAYL_send_as_agent — RE-REGISTERED 2026-07-29, see the note at the registry below
68
+ import { mailAgentboxTools } from "./mail-agentbox.js"; // mAYL_agentbox_*: agent mints/lists/releases its OWN two-way disposable inbox (backs mayl-agentbox EF). Added 2026-08-06 (LINEAR-5201 Part B)
69
+ import { mtalkTools } from "./mtalk.js";
70
+ import { attachmentTools } from "./attachments.js";
71
+ import { pttIngestTools } from "./ptt-ingest.js"; // mTALK_ingest_ptt — RE-REGISTERED 2026-07-29, see the note at the registry below
72
+ // import { mcallTools } from "./mcall.js"; // mCALL: carrier-pending — not registered (see header note)
73
+ import { knowledgeTools } from "./knowledge.js";
74
+ import { knowledgeGraphTools } from "./knowledge-graph.js"; // mRAG_graph_* — 2026-08-11: MCP door onto the kg_* graph RPCs (traverse people/threads, not just search text)
75
+ import { actionTools } from "./actions.js";
76
+ import { presenceTools } from "./presence.js"; // comms_session_attach — 2026-08-14: a live agent session claims the account's reply lane (agent_bridge_heartbeat), so the cloud stand-in defers to it. Replaces the PC-only bridge script as the ONLY writer of that signal.
77
+ import { embedTools } from "./embed.js"; // comms_embed_create RE-REGISTERED 2026-07-17: embed.mosadd.com/v1.js is LIVE (served by the mosadd Vercel project) — the widget + embed-keys/mirc-embed-token backend were already complete.
78
+ import { threatTools } from "./threat.js"; // threat_*: RE-REGISTERED 2026-07-15 (founder directive + LINEAR-3498). Pure/offline classification of the real Pegasus-class threat taxonomy — the engine DECIDES, the caller acts; no surveillance, no backend.
79
+ import { murlTools } from "./murl.js"; // mURL: REGISTERED — revived as a full dev module (founder 2026-06-27, re-arch). IRC-for-URLs, agent-native; backends live (mosadd-edge + murl-channels EF).
80
+ import { makeCapabilitiesTool } from "./capabilities.js";
81
+
82
+ /** The m* channel tools (everything except the meta discovery tool). */
83
+ const channelTools: MosaddTool[] = [
84
+ ...mdmTools,
85
+ ...mdmAsAgentTools,
86
+ ...mdmVoiceTools,
87
+ ...mircTools,
88
+ ...mircMembersTools,
89
+ ...mircMessagesTools,
90
+ ...mircEdgeTools,
91
+ // ...mroomTools, // mROOM: killed (LINEAR-3414) — channel re-cut into ephemeral private mIRC
92
+ // ...mroomMessagesTools, // mROOM: killed (LINEAR-3414)
93
+ ...mailTools, // mAYL_*: canonical email module (was the mp0st codename; renamed re-arch 2026-06-27)
94
+ // ...mailAliasTools, // mp0st_* aliases RETIRED 2026-07-15 — mAYL is the one name; the mp0st codename is now backend-internal only
95
+ // ⭐ mAYL_send_as_agent: RE-REGISTERED 2026-07-29 — proven end to end, without sending mail.
96
+ // Unregistered since 07-14 on the note "hub-claim EF 404s every call". That note was stale in
97
+ // the same way ptt-ingest's was: unauthenticated it returns 401 (the auth gate), not 404.
98
+ //
99
+ // Settled by running the whole chain rather than the convenient half:
100
+ // 1. hub-keys with a plain user JWT issued a real `mosadd_sk_live_…` — so a user session
101
+ // mints a hub key and no founder credential was ever needed. I had told the founder it
102
+ // required his key; that was wrong and this is the retraction.
103
+ // 2. hub-claim-mint with that key → 200, valid claim token, aud `mp0st-send`, 600s expiry.
104
+ // 3. mp0st-send with the claim token and a DELIBERATELY EMPTY payload → 400 "Missing to or
105
+ // subject". A 400 on payload validation proves the token was ACCEPTED; 401/403 would have
106
+ // proven it was not. Auth verified end to end with zero mail sent — a diagnostic must not
107
+ // put a real message in someone's inbox.
108
+ // The diagnostic key was then REVOKED (revoked_at set, not deleted, so the audit trail lives).
109
+ ...mailProvenanceTools,
110
+ // mAYL_agentbox_provision/list/release/extend — the agent mints/lists/releases/extends its OWN
111
+ // real, two-way, disposable inbox (agent-<hex>@mosadd.com). create_inbox parity with AgentMail,
112
+ // on our own stack + provenance. Backs the live mayl-agentbox EF; receive path landed 2026-08-06
113
+ // in mp0st-inbound-webhook (LINEAR-5201). Same requireUser auth as every other mAYL tool.
114
+ ...mailAgentboxTools,
115
+ ...mtalkTools,
116
+ ...attachmentTools,
117
+ // ⭐ mTALK_ingest_ptt: RE-REGISTERED 2026-07-29 — the backend finally does what the tool promises.
118
+ // Unregistered since 07-14 on the note "ptt-ingest EF 400s every call". Re-measured 07-29: that
119
+ // reason was stale (it returned 401, the auth gate), and an AUTHENTICATED probe then exposed the
120
+ // real fault — 500, `Could not find the table 'public.rag_jobs'`. It authenticated, validated,
121
+ // wrote the transcript row, and died one step later against a table dropped when the rag_events
122
+ // v2 queue landed. Agent push-to-talk had NEVER once reached memory.
123
+ //
124
+ // Fixed by handing the audio to `rag-transcribe` (NOT to the v2 queue — that queue carries TEXT
125
+ // for embedding and cannot transcribe; audio has to become words first). Verified on prod:
126
+ // 200 {"queued":true}, edge log 200 in 2.7s where it used to 500, and the transcript row's
127
+ // updated_at moved 4s after insert, so the backgrounded chain genuinely ran.
128
+ //
129
+ // Registered only AFTER that authenticated 200 — a liveness probe was never enough, because the
130
+ // whole point of this registry is that an agent sees only tools that actually work.
131
+ ...pttIngestTools,
132
+ //
133
+ // ✅ RESOLVED 2026-07-29 — both halves of this note are closed; kept as the record of how.
134
+ // The disable note recorded a diagnosis from 2026-07-14: hub-claim "404s every call".
135
+ // Live-probed today, unauthenticated:
136
+ // hub-claim-mint → 401 · ptt-ingest → 401 · mp0st-send → 401 (the control, a tool that
137
+ // IS registered and works)
138
+ // 401 is the auth gate answering. A dead or missing function returns 404; a function that
139
+ // rejects our payload shape returns 400. Neither happens any more, and both are ACTIVE on
140
+ // the project. So whatever was broken in July was fixed at some point and nobody came back
141
+ // to these lines — we advertised two capabilities as unavailable while their backends
142
+ // answered. One of them (ptt) is now proven and registered; this is the other.
143
+ //
144
+ // NOT re-registering hub-claim on this evidence, deliberately. An unauthenticated 401 proves the
145
+ // function is alive; it proves NOTHING about the authenticated path, which is where both
146
+ // originally failed. Re-registering on a liveness probe would swap "wrongly disabled" for
147
+ // "advertised and broken in a user's hands", which is the worse of the two.
148
+ //
149
+ // TO CLOSE: call each with a real hub key / session token. If they succeed, delete these
150
+ // two comment blocks and uncomment the imports — the count moves 71 → 73 and the anti-drift
151
+ // gate will then force every doc surface to follow. (This session cannot mint a session
152
+ // token, so it stops here rather than guess.)
153
+ ...knowledgeTools,
154
+ ...knowledgeGraphTools, // mRAG_graph_*: traverse the per-user knowledge graph (kg_* RPCs) — search finds text, this walks who/what/when
155
+ ...actionTools, // Action links (Tier 1): agent → user one-link browser action via action-create EF
156
+ ...presenceTools, // comms_session_attach: THIS session owns the account's reply lane while it runs; the 24/7 cloud stand-in defers. Any session, any machine — no bespoke bridge on one PC.
157
+ ...embedTools, // comms_embed_create: RE-REGISTERED 2026-07-17 — embed.mosadd.com/v1.js live; mints an embed key + paste-in snippet (mURL→mIRC rework P3)
158
+ ...threatTools, // threat_catalog + threat_classify: RE-REGISTERED 2026-07-15 (founder directive + LINEAR-3498) — pure/offline, makes the Pegasus-class classification claim a live, callable capability
159
+ ...murlTools, // mURL: revived as a full module (founder 2026-06-27) — read/post/presence/list_channels over live domain channels
160
+ // ...mcallTools, // mCALL: carrier-pending (no telephony carrier live) — re-register when a carrier is configured
161
+ // mirlTools,
162
+ // mmatrixTools, mdiscordTools, mtelegramTools, mslackTools, msignalTools,
163
+ //
164
+ // Each m* module registers its tools here as it ships.
165
+ // RFC required to add a new m* module (see docs/rfcs/0001-module-naming.md).
166
+ ];
167
+
168
+ export const allTools: MosaddTool[] = [
169
+ ...channelTools,
170
+ // comms_capabilities: one-call discovery of every tool's `requires` flag,
171
+ // so carrier-aware hosts (cymru-os) can gate the tool list by transport.
172
+ makeCapabilitiesTool(channelTools),
173
+ ];
174
+
175
+ /**
176
+ * The exact, live number of callable tools this server registers. Reference THIS
177
+ * (import { TOOL_COUNT }) in any code/doc surface that shows a tool count, instead
178
+ * of hard-coding a number that silently drifts (the "70+/65/68" inconsistency that
179
+ * bit us). Mirrors @mosadd/threat-engine's THREAT_EVENT_COUNT pattern.
180
+ */
181
+ export const TOOL_COUNT: number = allTools.length;
@@ -0,0 +1,186 @@
1
+ /**
2
+ * mRAG_graph — the KNOWLEDGE GRAPH over the user's own mosadd data.
3
+ *
4
+ * mRAG_search recalls WHAT was said; this surface walks WHO/WHAT is connected to whom, and WHEN.
5
+ * The engine already runs inside the mosadd backend as a set of Postgres functions built from the
6
+ * SAME per-user embeddings mRAG_search reads (metadata only — sender/recipient/thread — NEVER the
7
+ * message body, so it does not weaken the E2EE posture). Until now those functions had no MCP door,
8
+ * so an agent could search the corpus but not traverse it. These four tools are that door.
9
+ *
10
+ * ⚠ TRANSPORT: unlike the other mRAG tools (which call Edge Functions via invokeFunction), the
11
+ * graph lives in Postgres RPCs (kg_*), so these call `getSupabase().rpc(...)` directly. The RPCs
12
+ * are `grant execute … to authenticated`, and the graph-building one is SECURITY DEFINER keyed on
13
+ * `auth.uid()`, so under the caller's hub-session JWT every result is scoped to the caller's own
14
+ * account — there is no cross-tenant path.
15
+ *
16
+ * Typical flow for an agent: mRAG_graph_refresh (build/update from the latest ingested data) →
17
+ * mRAG_graph_overview (see the top parties + their ids) → mRAG_graph_neighbors / _timeline on a
18
+ * party id from the overview.
19
+ *
20
+ * Plan note: gated by plan at the hub (the knowledge graph is a paid capability — matches the
21
+ * app's `knowledgeGraph` flag). BYOK/self-host runs it against the user's own backend.
22
+ */
23
+
24
+ import { z } from "zod";
25
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
26
+ import { getSupabase, readSupabaseEnv } from "../providers/supabase.js";
27
+
28
+ /** One authenticated RPC round-trip with normalized errors an agent can reason about. */
29
+ async function callRpc<T>(fn: string, args: Record<string, unknown>, ctx: MosaddToolContext): Promise<T> {
30
+ readSupabaseEnv();
31
+ ctx.log("debug", `mRAG_graph via ${fn}`, args);
32
+ const { data, error } = await getSupabase().rpc(fn, args);
33
+ if (error) {
34
+ // PostgREST surfaces RLS denials, auth failures and function errors here; hand the agent the
35
+ // real message + code rather than a generic sentence, so it can self-correct.
36
+ throw new Error(`${fn} failed: ${error.message}${error.code ? ` (${error.code})` : ""}`);
37
+ }
38
+ return data as T;
39
+ }
40
+
41
+ // ── mRAG_graph_refresh ───────────────────────────────────────────────────────
42
+ const mRAG_graph_refresh_input = z.object({
43
+ max_docs: z
44
+ .number()
45
+ .int()
46
+ .min(1)
47
+ .max(20_000)
48
+ .optional()
49
+ .describe("Cap on source documents scanned when (re)building the graph. Default 20000 (the max)."),
50
+ });
51
+
52
+ async function mRAG_graph_refresh(
53
+ input: z.infer<typeof mRAG_graph_refresh_input>,
54
+ ctx: MosaddToolContext,
55
+ ): Promise<unknown> {
56
+ // kg_refresh_me rebuilds parties/mentions/edges from the caller's embeddings METADATA only
57
+ // (sender/recipient/thread), never content_text. Returns counts {parties, mentions, edges, …}.
58
+ return await callRpc("kg_refresh_me", { p_max_docs: input.max_docs ?? 20_000 }, ctx);
59
+ }
60
+
61
+ // ── mRAG_graph_overview ──────────────────────────────────────────────────────
62
+ const mRAG_graph_overview_input = z.object({
63
+ limit: z.number().int().min(1).max(200).optional().describe("Max parties to return (busiest first). Default 40, max 200."),
64
+ });
65
+
66
+ interface GraphParty {
67
+ party_id: string;
68
+ display_name: string;
69
+ kind: string;
70
+ aliases: string[];
71
+ appearances: number;
72
+ connections: number;
73
+ first_seen_at: string | null;
74
+ last_seen_at: string | null;
75
+ }
76
+
77
+ async function mRAG_graph_overview(
78
+ input: z.infer<typeof mRAG_graph_overview_input>,
79
+ ctx: MosaddToolContext,
80
+ ): Promise<{ parties: GraphParty[]; count: number }> {
81
+ const rows = await callRpc<GraphParty[]>("kg_overview", { p_limit: input.limit ?? 40 }, ctx);
82
+ const parties = rows ?? [];
83
+ return { parties, count: parties.length };
84
+ }
85
+
86
+ // ── mRAG_graph_neighbors ─────────────────────────────────────────────────────
87
+ const mRAG_graph_neighbors_input = z.object({
88
+ party_id: z.string().uuid().describe("The party whose connections to walk (a party_id from mRAG_graph_overview)."),
89
+ depth: z.number().int().min(1).max(2).optional().describe("Hops to walk. Hard-clamped to 2 server-side. Default 1."),
90
+ limit: z.number().int().min(1).max(200).optional().describe("Max neighbours to return. Clamped to 200. Default 50."),
91
+ });
92
+
93
+ interface GraphNeighbor {
94
+ party_id: string;
95
+ display_name: string;
96
+ kind: string;
97
+ depth: number;
98
+ edge_type: string;
99
+ observations: number;
100
+ valid_from: string | null;
101
+ last_seen_at: string | null;
102
+ }
103
+
104
+ async function mRAG_graph_neighbors(
105
+ input: z.infer<typeof mRAG_graph_neighbors_input>,
106
+ ctx: MosaddToolContext,
107
+ ): Promise<{ neighbors: GraphNeighbor[]; count: number }> {
108
+ const rows = await callRpc<GraphNeighbor[]>(
109
+ "kg_neighbors",
110
+ { p_party_id: input.party_id, p_depth: input.depth ?? 1, p_limit: input.limit ?? 50 },
111
+ ctx,
112
+ );
113
+ const neighbors = rows ?? [];
114
+ return { neighbors, count: neighbors.length };
115
+ }
116
+
117
+ // ── mRAG_graph_timeline ──────────────────────────────────────────────────────
118
+ const mRAG_graph_timeline_input = z.object({
119
+ party_id: z.string().uuid().describe("The party whose dated appearance timeline to return (a party_id from mRAG_graph_overview)."),
120
+ limit: z.number().int().min(1).max(200).optional().describe("Max timeline entries (newest first). Clamped to 200. Default 50."),
121
+ });
122
+
123
+ interface GraphTimelineEntry {
124
+ source_type: string;
125
+ source_id: string;
126
+ thread_id: string | null;
127
+ role: string | null;
128
+ occurred_at: string | null;
129
+ evidence_chunk_id: string | null;
130
+ }
131
+
132
+ async function mRAG_graph_timeline(
133
+ input: z.infer<typeof mRAG_graph_timeline_input>,
134
+ ctx: MosaddToolContext,
135
+ ): Promise<{ timeline: GraphTimelineEntry[]; count: number }> {
136
+ const rows = await callRpc<GraphTimelineEntry[]>(
137
+ "kg_party_timeline",
138
+ { p_party_id: input.party_id, p_limit: input.limit ?? 50 },
139
+ ctx,
140
+ );
141
+ const timeline = rows ?? [];
142
+ return { timeline, count: timeline.length };
143
+ }
144
+
145
+ export const knowledgeGraphTools: MosaddTool[] = [
146
+ {
147
+ name: "mRAG_graph_refresh",
148
+ title: "Rebuild knowledge graph",
149
+ annotations: { readOnlyHint: false },
150
+ requires: "network",
151
+ description:
152
+ "(Re)build the USER'S OWN knowledge graph from their indexed data, then return what it found (counts of parties/mentions/edges). Run this first, or after new data has been ingested, so mRAG_graph_overview/neighbors/timeline reflect the latest. Built from METADATA only (who-sent-to-whom, thread membership) — never message bodies, so it does not weaken E2EE. Owner-scoped.",
153
+ inputSchema: mRAG_graph_refresh_input,
154
+ handler: mRAG_graph_refresh as MosaddTool["handler"],
155
+ },
156
+ {
157
+ name: "mRAG_graph_overview",
158
+ title: "Knowledge graph overview",
159
+ annotations: { readOnlyHint: true },
160
+ requires: "network",
161
+ description:
162
+ "List the parties (people / companies / services) in the user's knowledge graph, busiest first, each with its party_id, kind, aliases, appearance count, connection count and first/last-seen dates. This is the entry point: use a returned party_id with mRAG_graph_neighbors or mRAG_graph_timeline. Owner-scoped.",
163
+ inputSchema: mRAG_graph_overview_input,
164
+ handler: mRAG_graph_overview as MosaddTool["handler"],
165
+ },
166
+ {
167
+ name: "mRAG_graph_neighbors",
168
+ title: "Explore graph neighbors",
169
+ annotations: { readOnlyHint: true },
170
+ requires: "network",
171
+ description:
172
+ "Walk the connections of one party (from mRAG_graph_overview) — who/what it is linked to, with the edge type, how many times observed, and when. Answers 'who is connected to X, and how'. Depth is hard-clamped to 2 hops and breadth to 200 server-side. Owner-scoped.",
173
+ inputSchema: mRAG_graph_neighbors_input,
174
+ handler: mRAG_graph_neighbors as MosaddTool["handler"],
175
+ },
176
+ {
177
+ name: "mRAG_graph_timeline",
178
+ title: "Knowledge graph timeline",
179
+ annotations: { readOnlyHint: true },
180
+ requires: "network",
181
+ description:
182
+ "Return the dated appearance timeline of one party (from mRAG_graph_overview) — each source (email/message/call/…), its thread, the party's role, and when it occurred, newest first. Answers 'when and where did X show up'. Owner-scoped.",
183
+ inputSchema: mRAG_graph_timeline_input,
184
+ handler: mRAG_graph_timeline as MosaddTool["handler"],
185
+ },
186
+ ];