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

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-L4PB6A6Z.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
@@ -1,96 +1,231 @@
1
- /**
2
- * Supabase provider for the alpha MCP server.
3
- *
4
- * Local BYOK mode: user supplies their own Supabase URL + anon key + user JWT
5
- * via env vars. The MCP server creates a per-request Supabase client and
6
- * invokes the mosadd Edge Functions on the user's behalf.
7
- *
8
- * In Phase 2 this is replaced by the hosted gateway (mcp.mosadd.com) which
9
- * holds keys server-side via the BYOK broker.
10
- */
11
-
12
- import { createClient, type SupabaseClient } from "@supabase/supabase-js";
13
- import { loadSession, isSessionExpired } from "../config.js";
14
-
15
- export interface SupabaseEnv {
16
- url: string;
17
- anonKey: string;
18
- userJwt?: string;
19
- }
20
-
21
- export class MissingSupabaseEnvError extends Error {
22
- constructor(missing: string[]) {
23
- super(
24
- `Missing Supabase credentials: ${missing.join(", ")}. ` +
25
- `Run \`mosadd login\`, or set MOSADD_SUPABASE_URL, MOSADD_SUPABASE_ANON_KEY and MOSADD_USER_JWT.`,
26
- );
27
- this.name = "MissingSupabaseEnvError";
28
- }
29
- }
30
-
31
- export function readSupabaseEnv(): SupabaseEnv {
32
- // Canonical env vars are MOSADD_*; the legacy M0SSAD_* names are still
33
- // honored (deprecated) so anyone who set them before the brand sweep keeps
34
- // working. Env vars take precedence; fall back to the session saved by
35
- // `mosadd login`.
36
- const env = (canonical: string, legacy: string): string | undefined =>
37
- process.env[canonical] ?? process.env[legacy];
38
- const userJwtEnv = env("MOSADD_USER_JWT", "M0SSAD_USER_JWT");
39
-
40
- const session = loadSession();
41
- const url = env("MOSADD_SUPABASE_URL", "M0SSAD_SUPABASE_URL") ?? session?.url;
42
- const anonKey = env("MOSADD_SUPABASE_ANON_KEY", "M0SSAD_SUPABASE_ANON_KEY") ?? session?.anonKey;
43
- const userJwt = userJwtEnv ?? session?.accessToken;
44
-
45
- const missing: string[] = [];
46
- if (!url) missing.push("MOSADD_SUPABASE_URL");
47
- if (!anonKey) missing.push("MOSADD_SUPABASE_ANON_KEY");
48
- if (missing.length) throw new MissingSupabaseEnvError(missing);
49
-
50
- // Surface an expired `mosadd login` token early with an actionable message.
51
- if (!userJwtEnv && session && isSessionExpired(session)) {
52
- throw new Error("Your mosadd session has expired. Run `mosadd login` again to refresh it.");
53
- }
54
- return { url: url!, anonKey: anonKey!, userJwt };
55
- }
56
-
57
- export function getSupabase(env: SupabaseEnv = readSupabaseEnv()): SupabaseClient {
58
- return createClient(env.url, env.anonKey, {
59
- auth: {
60
- persistSession: false,
61
- autoRefreshToken: false,
62
- detectSessionInUrl: false,
63
- },
64
- global: env.userJwt
65
- ? {
66
- headers: { Authorization: `Bearer ${env.userJwt}` },
67
- }
68
- : undefined,
69
- });
70
- }
71
-
72
- /**
73
- * Invoke a the legacy mosadd consumer-app repo Edge Function. Wraps `supabase.functions.invoke` with
74
- * normalized error handling so MCP tool handlers can throw clean errors that
75
- * agents can reason about.
76
- */
77
- export async function invokeFunction<T = unknown>(
78
- fn: string,
79
- body: Record<string, unknown>,
80
- ): Promise<T> {
81
- const client = getSupabase();
82
- const { data, error } = await client.functions.invoke<T>(fn, { body });
83
- if (error) {
84
- const msg =
85
- error instanceof Error
86
- ? error.message
87
- : typeof (error as { message?: unknown })?.message === "string"
88
- ? (error as { message: string }).message
89
- : `Edge function ${fn} failed`;
90
- throw new Error(msg);
91
- }
92
- if (data == null) {
93
- throw new Error(`Edge function ${fn} returned no data`);
94
- }
95
- return data;
96
- }
1
+ /**
2
+ * Supabase provider for the alpha MCP server.
3
+ *
4
+ * Local BYOK mode: user supplies their own Supabase URL + anon key + user JWT
5
+ * via env vars. The MCP server creates a per-request Supabase client and
6
+ * invokes the mosadd Edge Functions on the user's behalf.
7
+ *
8
+ * In Phase 2 this is replaced by the hosted gateway (mcp.mosadd.com) which
9
+ * holds keys server-side via the BYOK broker.
10
+ */
11
+
12
+ import { AsyncLocalStorage } from "node:async_hooks";
13
+ import { randomUUID } from "node:crypto";
14
+ import { hostname } from "node:os";
15
+ import { createClient, type SupabaseClient } from "@supabase/supabase-js";
16
+ import { loadSession, isSessionExpired } from "../config.js";
17
+
18
+ /**
19
+ * Tożsamość TEGO procesu — stała przez całe życie sesji, nowa przy każdym starcie.
20
+ *
21
+ * ⛔ NIE MOŻE być pochodną konta ani hosta. Dwie sesje generałów potrafią stać na tej samej
22
+ * maszynie i pod tym samym kontem (box floty), więc identyfikator z hosta zlepiłby je z powrotem
23
+ * w jedną — czyli odtworzył dokładnie ten błąd, który to naprawia. Nazwa hosta zostaje tylko jako
24
+ * czytelny przedrostek do diagnostyki; o rozróżnieniu decyduje losowy ogon.
25
+ */
26
+ let cachedSessionId: string | null = null;
27
+ export function sessionId(): string {
28
+ // ⛔ BRAMA HOSTOWANA ≠ PROCES (audyt 2026-08-27). Na mcp.mosadd.com jeden proces lambdy obsługuje
29
+ // WIELU najemców, a kolejne wywołania tej samej rozmowy potrafią trafić w RÓŻNE procesy — więc
30
+ // tożsamość per-proces byłaby tam jednocześnie wspólna (wyciek między najemcami) i niestała
31
+ // (fałszywe 409 przy każdym przełączeniu instancji). W kontekście bramy prawda żyje w ALS:
32
+ // brama wyznacza stabilny `sessionKey` per klucz API; brak klucza = puste "" (semantyka legacy,
33
+ // zero roszczeń per-sesja). Losowy identyfikator per-proces zostaje TYLKO dla stdio.
34
+ const perRequest = requestEnv.getStore();
35
+ if (perRequest) return perRequest.sessionKey ?? "";
36
+ if (cachedSessionId) return cachedSessionId;
37
+ let host = "mcp";
38
+ try { host = (hostname() || "mcp").slice(0, 24); } catch { /* bez nazwy hosta też działa */ }
39
+ cachedSessionId = `${host}:${randomUUID()}`;
40
+ return cachedSessionId;
41
+ }
42
+
43
+ export interface SupabaseEnv {
44
+ url: string;
45
+ anonKey: string;
46
+ userJwt?: string;
47
+ /** Stabilna tożsamość sesji dla bramy hostowanej (per klucz API) — patrz sessionId(). */
48
+ sessionKey?: string;
49
+ }
50
+
51
+ /**
52
+ * Per-request session context for the hosted HTTP gateway (mcp.mosadd.com).
53
+ *
54
+ * stdio runs one user per process, so credentials live in process.env. The
55
+ * hosted gateway serves MANY users from one process — sharing process.env would
56
+ * leak user A's JWT into user B's concurrent request. The gateway instead
57
+ * resolves the caller's session (Bearer api key → hub-key-exchange) and runs the
58
+ * whole request inside `runWithSupabaseEnv(env, …)`; `readSupabaseEnv()` reads
59
+ * this store first and falls back to process.env, so stdio is unaffected.
60
+ */
61
+ const requestEnv = new AsyncLocalStorage<SupabaseEnv>();
62
+
63
+ /** Run `fn` (and every tool call it triggers) with a per-request Supabase session. */
64
+ export function runWithSupabaseEnv<T>(env: SupabaseEnv, fn: () => T): T {
65
+ return requestEnv.run(env, fn);
66
+ }
67
+
68
+ export class MissingSupabaseEnvError extends Error {
69
+ constructor(missing: string[]) {
70
+ super(
71
+ `Missing Supabase credentials: ${missing.join(", ")}. ` +
72
+ `Run \`mosadd login\`, or set MOSADD_SUPABASE_URL, MOSADD_SUPABASE_ANON_KEY and MOSADD_USER_JWT.`,
73
+ );
74
+ this.name = "MissingSupabaseEnvError";
75
+ }
76
+ }
77
+
78
+ export function readSupabaseEnv(): SupabaseEnv {
79
+ // Hosted HTTP gateway: a per-request session set via runWithSupabaseEnv wins
80
+ // over any process-global env (multi-tenant safety). stdio has no store → falls
81
+ // through to the env/login resolution below.
82
+ const perRequest = requestEnv.getStore();
83
+ if (perRequest) return perRequest;
84
+
85
+ // Canonical env vars are MOSADD_*; the legacy M0SSAD_* names are still
86
+ // honored (deprecated) so anyone who set them before the brand sweep keeps
87
+ // working. Env vars take precedence; fall back to the session saved by
88
+ // `mosadd login`.
89
+ const env = (canonical: string, legacy: string): string | undefined =>
90
+ process.env[canonical] ?? process.env[legacy];
91
+ const userJwtEnv = env("MOSADD_USER_JWT", "M0SSAD_USER_JWT");
92
+
93
+ const session = loadSession();
94
+ const url = env("MOSADD_SUPABASE_URL", "M0SSAD_SUPABASE_URL") ?? session?.url;
95
+ const anonKey = env("MOSADD_SUPABASE_ANON_KEY", "M0SSAD_SUPABASE_ANON_KEY") ?? session?.anonKey;
96
+ const userJwt = userJwtEnv ?? session?.accessToken;
97
+
98
+ const missing: string[] = [];
99
+ if (!url) missing.push("MOSADD_SUPABASE_URL");
100
+ if (!anonKey) missing.push("MOSADD_SUPABASE_ANON_KEY");
101
+ if (missing.length) throw new MissingSupabaseEnvError(missing);
102
+
103
+ // Surface an expired `mosadd login` token early with an actionable message.
104
+ if (!userJwtEnv && session && isSessionExpired(session)) {
105
+ throw new Error("Your mosadd session has expired. Run `mosadd login` again to refresh it.");
106
+ }
107
+ return { url: url!, anonKey: anonKey!, userJwt };
108
+ }
109
+
110
+ export function getSupabase(env: SupabaseEnv = readSupabaseEnv()): SupabaseClient {
111
+ return createClient(env.url, env.anonKey, {
112
+ auth: {
113
+ persistSession: false,
114
+ autoRefreshToken: false,
115
+ detectSessionInUrl: false,
116
+ },
117
+ // ⛔ x-mosadd-origin: KAŻDE wywołanie z toolkitu/bramy MCP niesie ten znacznik (2026-08-25,
118
+ // rozkaz Króla „kradną tożsamości"). Sesje agentów wpinały klucz WŁAŚCICIELA i postowały na
119
+ // kanałach z jego dymka (SOVEREIGN) — serwer nie miał JAK odróżnić bramy od aplikacji, bo
120
+ // hub-key-exchange zwraca zwykły JWT usera. Ten nagłówek to rozróżnia: message-send odrzuca
121
+ // post na kanał z tożsamości CZŁOWIEKA, gdy przyszedł przez bramę — z komunikatem każącym
122
+ // wpiąć klucz SWOJEJ linii. Aplikacja mosadd.com nigdy nie wysyła tego nagłówka.
123
+ global: {
124
+ headers: {
125
+ ...(env.userJwt ? { Authorization: `Bearer ${env.userJwt}` } : {}),
126
+ "x-mosadd-origin": "hub-gateway",
127
+ // Nagłówek tylko, gdy sesja MA tożsamość — puste "" (brama bez sessionKey) nie wysyła nic,
128
+ // więc serwerowy strażnik 409 nie widzi fałszywych roszczeń.
129
+ ...(sessionId() ? { "x-mosadd-session": sessionId() } : {}),
130
+ // ⛔ KTÓRA TO SESJA (2026-08-27, „każdy generał co chwilę gubi mózg"). Wszyscy generałowie
131
+ // wpinają się kluczem hub TEGO SAMEGO właściciela, więc dla serwera ich wywołania były
132
+ // nieodróżnialne — a deklaracja linii (`comms_session_attach as_agent`) trzymała JEDEN
133
+ // wiersz na konto. Skutek: kto wpiął się ostatni, odbierał linię wszystkim pozostałym, a
134
+ // ich posty na kanałach zaczynały wracać z 403. Tożsamość sesji (stdio: per proces,
135
+ // brama: per klucz API) pozwala dziewięciu liniom na jednym koncie nie deptać sobie po piętach.
136
+ },
137
+ },
138
+ });
139
+ }
140
+
141
+ /**
142
+ * Invoke a the legacy mosadd consumer-app repo Edge Function. Wraps `supabase.functions.invoke` with
143
+ * normalized error handling so MCP tool handlers can throw clean errors that
144
+ * agents can reason about.
145
+ */
146
+ export async function invokeFunction<T = unknown>(
147
+ fn: string,
148
+ body: Record<string, unknown>,
149
+ ): Promise<T> {
150
+ const client = getSupabase();
151
+ const { data, error } = await client.functions.invoke<T>(fn, { body });
152
+ if (error) {
153
+ // supabase-js throws FunctionsHttpError for any non-2xx, whose `.message`
154
+ // is the FIXED generic string "Edge Function returned a non-2xx status
155
+ // code" — the *real* reason (e.g. {"error":"wrapped_group_key required"},
156
+ // "forbidden", an RLS denial) lives in `error.context`, a Response. Read it
157
+ // so the agent gets an actionable message (and the HTTP status) it can
158
+ // reason about and self-correct on, instead of the same opaque sentence
159
+ // for every failure across mDM/mIRC/mp0st/mRAG/prekey/message-list.
160
+ let msg =
161
+ error instanceof Error && error.message
162
+ ? error.message
163
+ : `Edge function ${fn} failed`;
164
+ const ctx = (error as { context?: unknown }).context;
165
+ if (ctx && typeof (ctx as Response).text === "function") {
166
+ const res = ctx as Response;
167
+ try {
168
+ const raw = await res.text();
169
+ if (raw) {
170
+ let detail = raw;
171
+ let recipe = "";
172
+ try {
173
+ const parsed = JSON.parse(raw) as {
174
+ error?: unknown;
175
+ message?: unknown;
176
+ code?: unknown;
177
+ message_en?: unknown;
178
+ next_steps?: unknown;
179
+ };
180
+ detail =
181
+ (typeof parsed.error === "string" && parsed.error) ||
182
+ (typeof parsed.message === "string" && parsed.message) ||
183
+ raw;
184
+ // ⛔ The refusal CONTRACT (supabase/functions/_shared/errors.ts) travels as
185
+ // { code, message_en, message_pl, next_steps[] }. Until 2026-09-04 this block read
186
+ // `error` alone and threw the rest away — so the server said "here is exactly what to
187
+ // do next" and the agent received one flat sentence. The recipe is the whole point of
188
+ // the contract: it is written FOR a machine to act on. Measured on production the same
189
+ // day: mIRC_post_message with someone else's agent returned only
190
+ // "message-send (403): agent_not_owned" — code, both messages and 2 next_steps dropped.
191
+ // Rendered below as plain text because that is what an MCP tool error carries.
192
+ const steps = Array.isArray(parsed.next_steps) ? parsed.next_steps : [];
193
+ const lines: string[] = [];
194
+ if (typeof parsed.code === "string" && parsed.code) lines.push(`code: ${parsed.code}`);
195
+ if (typeof parsed.message_en === "string" && parsed.message_en && parsed.message_en !== detail) {
196
+ lines.push(parsed.message_en);
197
+ }
198
+ for (const raw_step of steps) {
199
+ const step = raw_step as { actor?: unknown; tool?: unknown; ui?: unknown; args?: unknown; why?: unknown };
200
+ const who = typeof step.actor === "string" ? step.actor : "?";
201
+ const what =
202
+ (typeof step.tool === "string" && step.tool) ||
203
+ (typeof step.ui === "string" && step.ui) ||
204
+ "";
205
+ if (!what) continue;
206
+ const why = typeof step.why === "string" ? ` — ${step.why}` : "";
207
+ const args =
208
+ step.args && typeof step.args === "object"
209
+ ? ` ${JSON.stringify(step.args)}`
210
+ : "";
211
+ lines.push(`next (${who}): ${what}${args}${why}`);
212
+ }
213
+ if (lines.length) recipe = "\n" + lines.join("\n");
214
+ } catch {
215
+ // non-JSON body — use the raw text as-is
216
+ }
217
+ const status = typeof res.status === "number" ? res.status : undefined;
218
+ // First line stays byte-for-byte what callers have always matched on; the recipe follows.
219
+ msg = (status ? `${fn} (${status}): ${detail}` : `${fn}: ${detail}`) + recipe;
220
+ }
221
+ } catch {
222
+ // body already consumed or unreadable — keep the generic message
223
+ }
224
+ }
225
+ throw new Error(msg);
226
+ }
227
+ if (data == null) {
228
+ throw new Error(`Edge function ${fn} returned no data`);
229
+ }
230
+ return data;
231
+ }
package/src/server.ts CHANGED
@@ -1,105 +1,162 @@
1
- /**
2
- * Build a McpServer instance with all mosadd tools registered.
3
- */
4
-
5
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
6
- import { allTools } from "./tools/index.js";
7
- import { SupabaseDmProvider } from "./providers/supabase-dm.js";
8
- import { SupabaseVoiceProvider } from "./providers/supabase-voice.js";
9
- import { InMemoryMdmKeyStore } from "./crypto/mdm-session.js";
10
- import type { MosaddServerOptions, MosaddToolContext, ProviderRegistry } from "./types.js";
11
-
12
- /**
13
- * Resolve the channel ProviderRegistry: default network adapters merged with
14
- * anything the host injects. A carrier-aware host (cymru-os) passes its own
15
- * radio DmProvider via `injected.dm`. This is the single place the default
16
- * adapters are named — both `createMosaddServer` and the `@mosadd/ai` adapters
17
- * build their context through it so they stay in lockstep.
18
- */
19
- export function defaultProviders(injected?: Partial<ProviderRegistry>): ProviderRegistry {
20
- return {
21
- dm: injected?.dm ?? new SupabaseDmProvider(),
22
- keys: injected?.keys ?? new InMemoryMdmKeyStore(),
23
- voice: injected?.voice ?? new SupabaseVoiceProvider(),
24
- };
25
- }
26
-
27
- export function createMosaddServer(options: MosaddServerOptions = {}) {
28
- const mode = options.mode ?? (options.apiKey ? "cloud" : "local");
29
- const hubUrl = options.hubUrl ?? "https://mcp.mosadd.com";
30
- const logLevel = options.logLevel ?? "info";
31
-
32
- // DI seam: default network adapters, overridden by anything the host injects.
33
- const providers = defaultProviders(options.providers);
34
-
35
- const ctx: MosaddToolContext = {
36
- options: { ...options, mode, hubUrl },
37
- providers,
38
- log: (level, msg, extra) => {
39
- if (shouldLog(level, logLevel)) {
40
- // MCP servers must write logs to stderr (stdout is the protocol channel).
41
- process.stderr.write(
42
- JSON.stringify({ level, msg, extra, ts: new Date().toISOString() }) + "\n",
43
- );
44
- }
45
- },
46
- };
47
-
48
- const server = new McpServer(
49
- {
50
- name: "mosadd",
51
- version: "3.0.0-alpha.0",
52
- },
53
- {
54
- capabilities: {
55
- tools: {},
56
- },
57
- },
58
- );
59
-
60
- for (const tool of allTools) {
61
- // MCP SDK v1.x expects the field-level Zod shape (`{ to: z.string(), text: z.string() }`),
62
- // not the wrapping `z.object({...})`. Tool inputs are declared as ZodObject schemas
63
- // so we can `.parse()` them in the handler; surface the inner `.shape` to the SDK here.
64
- const shape =
65
- tool.inputSchema && typeof tool.inputSchema === "object" && "shape" in tool.inputSchema
66
- ? (tool.inputSchema as { shape: Record<string, unknown> }).shape
67
- : (tool.inputSchema as unknown as Record<string, unknown>);
68
-
69
- server.tool(
70
- tool.name,
71
- tool.description,
72
- shape as Parameters<typeof server.tool>[2],
73
- async (input: unknown) => {
74
- const parsed = tool.inputSchema.parse(input);
75
- try {
76
- const result = await tool.handler(parsed as never, ctx);
77
- return {
78
- content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }],
79
- };
80
- } catch (err) {
81
- ctx.log("error", `tool ${tool.name} failed`, { error: String(err) });
82
- return {
83
- isError: true,
84
- content: [
85
- {
86
- type: "text" as const,
87
- text: JSON.stringify({
88
- error: err instanceof Error ? err.message : String(err),
89
- tool: tool.name,
90
- }),
91
- },
92
- ],
93
- };
94
- }
95
- },
96
- );
97
- }
98
-
99
- return server;
100
- }
101
-
102
- function shouldLog(level: string, threshold: string): boolean {
103
- const order = { debug: 0, info: 1, warn: 2, error: 3 } as const;
104
- return (order[level as keyof typeof order] ?? 1) >= (order[threshold as keyof typeof order] ?? 1);
105
- }
1
+ /**
2
+ * Build a McpServer instance with all mosadd tools registered.
3
+ */
4
+
5
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
6
+ import { allTools } from "./tools/index.js";
7
+ import { autoBeatFromActivity } from "./tools/presence.js";
8
+ import { PKG_VERSION } from "./version.js";
9
+ import { SupabaseDmProvider } from "./providers/supabase-dm.js";
10
+ import { SupabaseVoiceProvider } from "./providers/supabase-voice.js";
11
+ import { InMemoryMdmKeyStore, publishOwnPrekeys } from "./crypto/mdm-session.js";
12
+ import type { MosaddServerOptions, MosaddToolContext, ProviderRegistry } from "./types.js";
13
+
14
+ /**
15
+ * Resolve the channel ProviderRegistry: default network adapters merged with
16
+ * anything the host injects. A carrier-aware host (cymru-os) passes its own
17
+ * radio DmProvider via `injected.dm`. This is the single place the default
18
+ * adapters are named — both `createMosaddServer` and the `@mosadd/ai` adapters
19
+ * build their context through it so they stay in lockstep.
20
+ */
21
+ export function defaultProviders(injected?: Partial<ProviderRegistry>): ProviderRegistry {
22
+ return {
23
+ dm: injected?.dm ?? new SupabaseDmProvider(),
24
+ keys: injected?.keys ?? new InMemoryMdmKeyStore(),
25
+ voice: injected?.voice ?? new SupabaseVoiceProvider(),
26
+ };
27
+ }
28
+
29
+ export function createMosaddServer(options: MosaddServerOptions = {}) {
30
+ const mode = options.mode ?? (options.apiKey ? "cloud" : "local");
31
+ const hubUrl = options.hubUrl ?? "https://mcp.mosadd.com";
32
+ const logLevel = options.logLevel ?? "info";
33
+
34
+ // DI seam: default network adapters, overridden by anything the host injects.
35
+ const providers = defaultProviders(options.providers);
36
+
37
+ const ctx: MosaddToolContext = {
38
+ options: { ...options, mode, hubUrl },
39
+ providers,
40
+ log: (level, msg, extra) => {
41
+ if (shouldLog(level, logLevel)) {
42
+ // MCP servers must write logs to stderr (stdout is the protocol channel).
43
+ process.stderr.write(
44
+ JSON.stringify({ level, msg, extra, ts: new Date().toISOString() }) + "\n",
45
+ );
46
+ }
47
+ },
48
+ };
49
+
50
+ // Cold-start fix: make this identity reachable for inbound E2EE DMs the moment
51
+ // the server is up, so mDM_send works without every recipient first running
52
+ // mDM_publish_keys. Best-effort and non-fatal — it needs an authenticated
53
+ // session, so it silently skips when there is none (BYOK without a JWT, offline,
54
+ // etc.) and never blocks startup. Uses the SAME keystore the tools use, so the
55
+ // published identity matches what mDM_send/encryptForPeer will use this process.
56
+ if (options.autoPublishKeys) {
57
+ void publishOwnPrekeys(providers.keys, providers.dm)
58
+ .then((r) => ctx.log("debug", "auto-published mDM prekeys", { one_time_prekeys: r.oneTimePrekeyCount }))
59
+ .catch((err) => ctx.log("debug", "auto-publish mDM prekeys skipped", { error: String(err) }));
60
+ }
61
+
62
+ const server = new McpServer(
63
+ {
64
+ name: "mosadd",
65
+ // Human-facing identity of the server itself (initialize result). The icon URLs
66
+ // point at the LIVE gateway origin on purpose: clients that honour serverInfo.icons
67
+ // get the brand mark without scraping the favicon, and the files ship with
68
+ // apps/mcp-http/public (canon 08-26 — generated by m0ssad-3 scripts/
69
+ // generate-brand-icons.py, never hand-edited).
70
+ title: "mosADD — omnichannel messenger for agents",
71
+ websiteUrl: "https://mosadd.com",
72
+ icons: [
73
+ { src: "https://mcp.mosadd.com/favicon.svg", mimeType: "image/svg+xml", sizes: ["any"] },
74
+ { src: "https://mcp.mosadd.com/pwa-192.png", mimeType: "image/png", sizes: ["192x192"] },
75
+ ],
76
+ version: PKG_VERSION,
77
+ },
78
+ {
79
+ capabilities: {
80
+ tools: {},
81
+ },
82
+ },
83
+ );
84
+
85
+ for (const tool of allTools) {
86
+ // MCP SDK v1.x expects the field-level Zod shape (`{ to: z.string(), text: z.string() }`),
87
+ // not the wrapping `z.object({...})`. Tool inputs are declared as ZodObject schemas
88
+ // so we can `.parse()` them in the handler; surface the inner `.shape` to the SDK here.
89
+ const shape =
90
+ tool.inputSchema && typeof tool.inputSchema === "object" && "shape" in tool.inputSchema
91
+ ? (tool.inputSchema as { shape: Record<string, unknown> }).shape
92
+ : (tool.inputSchema as unknown as Record<string, unknown>);
93
+
94
+ // Tool annotations ride the 5-arg overload (SDK ≥1.12 serialises them into
95
+ // tools/list verbatim). Without them EVERY tool lands in the connector UI's flat
96
+ // "Other tools" bucket — the exact founder complaint this fixes. `title` is spec'd
97
+ // inside ToolAnnotations, so it travels in the same object.
98
+ const annotations =
99
+ tool.title || tool.annotations
100
+ ? { ...(tool.title ? { title: tool.title } : {}), ...(tool.annotations ?? {}) }
101
+ : undefined;
102
+
103
+ const toolCallback = async (input: unknown) => {
104
+ const parsed = tool.inputSchema.parse(input);
105
+ try {
106
+ const result = await tool.handler(parsed as never, ctx);
107
+ // AUTO-PAROWANIE (08-26): a LIVE session that is actually WORKING holds its line —
108
+ // the founder spent a week talking to cloud stand-ins because models never
109
+ // remembered the attach handshake. Fire-and-forget, throttled inside, never blocks
110
+ // the tool's own response; see autoBeatFromActivity for which line gets the beat.
111
+ void autoBeatFromActivity(ctx);
112
+ // A tool may return rich MCP content (e.g. an image frame from
113
+ // comms_action_frame_get) via `mcpContent`; pass it through verbatim.
114
+ const rich = result as { mcpContent?: unknown[] } | null;
115
+ if (rich && Array.isArray(rich.mcpContent)) {
116
+ return { content: rich.mcpContent as never[] };
117
+ }
118
+ return {
119
+ content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }],
120
+ };
121
+ } catch (err) {
122
+ ctx.log("error", `tool ${tool.name} failed`, { error: String(err) });
123
+ return {
124
+ isError: true,
125
+ content: [
126
+ {
127
+ type: "text" as const,
128
+ text: JSON.stringify({
129
+ error: err instanceof Error ? err.message : String(err),
130
+ tool: tool.name,
131
+ }),
132
+ },
133
+ ],
134
+ };
135
+ }
136
+ };
137
+
138
+ if (annotations) {
139
+ server.tool(
140
+ tool.name,
141
+ tool.description,
142
+ shape as Parameters<typeof server.tool>[2],
143
+ annotations,
144
+ toolCallback,
145
+ );
146
+ } else {
147
+ server.tool(
148
+ tool.name,
149
+ tool.description,
150
+ shape as Parameters<typeof server.tool>[2],
151
+ toolCallback,
152
+ );
153
+ }
154
+ }
155
+
156
+ return server;
157
+ }
158
+
159
+ function shouldLog(level: string, threshold: string): boolean {
160
+ const order = { debug: 0, info: 1, warn: 2, error: 3 } as const;
161
+ return (order[level as keyof typeof order] ?? 1) >= (order[threshold as keyof typeof order] ?? 1);
162
+ }