@mosadd/mcp 3.0.0-alpha.3 → 3.0.0-alpha.30

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 (49) hide show
  1. package/CHANGELOG.md +212 -0
  2. package/README.md +150 -116
  3. package/dist/bin/mcp.js +42 -3
  4. package/dist/chunk-6PGDNIKR.js +2556 -0
  5. package/dist/index.d.ts +99 -7
  6. package/dist/index.js +7 -3
  7. package/package.json +10 -7
  8. package/src/__tests__/golden-path.test.ts +137 -132
  9. package/src/__tests__/integration.test.ts +179 -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 -97
  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 +148 -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 +104 -37
  30. package/src/tools/knowledge.ts +191 -0
  31. package/src/tools/mail-aliases.ts +25 -0
  32. package/src/tools/mail-provenance.ts +135 -0
  33. package/src/tools/mail.ts +381 -89
  34. package/src/tools/mcall.ts +216 -0
  35. package/src/tools/mdm-voice.ts +212 -0
  36. package/src/tools/mdm.ts +479 -379
  37. package/src/tools/mirc-edge.ts +190 -0
  38. package/src/tools/mirc-members.ts +198 -177
  39. package/src/tools/mirc-messages.ts +155 -0
  40. package/src/tools/mirc.ts +190 -170
  41. package/src/tools/mroom-messages.ts +142 -142
  42. package/src/tools/mroom.ts +221 -189
  43. package/src/tools/mtalk.ts +121 -0
  44. package/src/tools/murl.ts +298 -0
  45. package/src/tools/ptt-ingest.ts +97 -0
  46. package/src/tools/threat.ts +119 -0
  47. package/src/types.ts +94 -79
  48. package/src/voice/floor.ts +132 -0
  49. package/dist/chunk-HD5RLE5K.js +0 -1193
@@ -0,0 +1,91 @@
1
+ /**
2
+ * SupabaseVoiceProvider — the default (network) mTALK provider.
3
+ *
4
+ * Audio media: a LiveKit room, credentials minted by the existing
5
+ * `livekit-token` Edge Function. Floor control: the `mtalk-floor` Edge Function
6
+ * holds the AUTHORITATIVE per-room floor state (running the same reference FSM
7
+ * as floor.ts) and broadcasts changes over Supabase Realtime for sub-100ms PTT
8
+ * grant. mosadd-os just asks and relays the answer.
9
+ */
10
+
11
+ import type {
12
+ VoiceProvider,
13
+ FloorSnapshot,
14
+ FloorRequestResult,
15
+ VoiceJoinTicket,
16
+ } from "@mosadd/providers";
17
+ import { getSupabase, invokeFunction, readSupabaseEnv } from "./supabase.js";
18
+
19
+ const ROOM_PREFIX = "mosadd-room-";
20
+
21
+ export class SupabaseVoiceProvider implements VoiceProvider {
22
+ private cachedSelfId: string | null = null;
23
+
24
+ async selfId(): Promise<string> {
25
+ if (this.cachedSelfId) return this.cachedSelfId;
26
+ readSupabaseEnv();
27
+ const sb = getSupabase();
28
+ const { data: u, error: ue } = await sb.auth.getUser();
29
+ if (ue || !u?.user) {
30
+ throw new Error(
31
+ "Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token.",
32
+ );
33
+ }
34
+ const { data: identity, error } = await sb
35
+ .from("identities")
36
+ .select("id")
37
+ .eq("user_id", u.user.id)
38
+ .maybeSingle();
39
+ if (error || !identity) {
40
+ throw new Error("Current user has no mosadd identity row. Sign in to mosadd.com first.");
41
+ }
42
+ this.cachedSelfId = identity.id as string;
43
+ return this.cachedSelfId;
44
+ }
45
+
46
+ async createRoom(label?: string): Promise<{ roomId: string }> {
47
+ const self = await this.selfId();
48
+ const roomId = `${ROOM_PREFIX}${label ? slug(label) : self}`;
49
+ // Floor row is created lazily by mtalk-floor on first request; nothing to do
50
+ // here beyond returning the canonical id.
51
+ return { roomId };
52
+ }
53
+
54
+ async joinTicket(roomId: string): Promise<VoiceJoinTicket> {
55
+ const self = await this.selfId();
56
+ type TokenResp = { token: string; url: string; roomName: string; identity: string };
57
+ const data = await invokeFunction<TokenResp>("livekit-token", {
58
+ roomName: roomId,
59
+ identity: self,
60
+ });
61
+ return { token: data.token, url: data.url, identity: data.identity, roomId: data.roomName };
62
+ }
63
+
64
+ async requestFloor(roomId: string): Promise<FloorRequestResult> {
65
+ return invokeFunction<FloorRequestResult>("mtalk-floor", { action: "request", room_id: roomId });
66
+ }
67
+
68
+ async releaseFloor(roomId: string): Promise<FloorSnapshot> {
69
+ const data = await invokeFunction<{ snapshot: FloorSnapshot }>("mtalk-floor", {
70
+ action: "release",
71
+ room_id: roomId,
72
+ });
73
+ return data.snapshot;
74
+ }
75
+
76
+ async floorState(roomId: string): Promise<FloorSnapshot> {
77
+ const data = await invokeFunction<{ snapshot: FloorSnapshot }>("mtalk-floor", {
78
+ action: "state",
79
+ room_id: roomId,
80
+ });
81
+ return data.snapshot;
82
+ }
83
+ }
84
+
85
+ function slug(s: string): string {
86
+ return s
87
+ .toLowerCase()
88
+ .replace(/[^a-z0-9._-]+/g, "-")
89
+ .replace(/^-+|-+$/g, "")
90
+ .slice(0, 200);
91
+ }
@@ -1,96 +1,148 @@
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 m0ssad-3 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 m0ssad-3 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 { createClient, type SupabaseClient } from "@supabase/supabase-js";
14
+ import { loadSession, isSessionExpired } from "../config.js";
15
+
16
+ export interface SupabaseEnv {
17
+ url: string;
18
+ anonKey: string;
19
+ userJwt?: string;
20
+ }
21
+
22
+ /**
23
+ * Per-request session context for the hosted HTTP gateway (mcp.mosadd.com).
24
+ *
25
+ * stdio runs one user per process, so credentials live in process.env. The
26
+ * hosted gateway serves MANY users from one process — sharing process.env would
27
+ * leak user A's JWT into user B's concurrent request. The gateway instead
28
+ * resolves the caller's session (Bearer api key → hub-key-exchange) and runs the
29
+ * whole request inside `runWithSupabaseEnv(env, …)`; `readSupabaseEnv()` reads
30
+ * this store first and falls back to process.env, so stdio is unaffected.
31
+ */
32
+ const requestEnv = new AsyncLocalStorage<SupabaseEnv>();
33
+
34
+ /** Run `fn` (and every tool call it triggers) with a per-request Supabase session. */
35
+ export function runWithSupabaseEnv<T>(env: SupabaseEnv, fn: () => T): T {
36
+ return requestEnv.run(env, fn);
37
+ }
38
+
39
+ export class MissingSupabaseEnvError extends Error {
40
+ constructor(missing: string[]) {
41
+ super(
42
+ `Missing Supabase credentials: ${missing.join(", ")}. ` +
43
+ `Run \`mosadd login\`, or set MOSADD_SUPABASE_URL, MOSADD_SUPABASE_ANON_KEY and MOSADD_USER_JWT.`,
44
+ );
45
+ this.name = "MissingSupabaseEnvError";
46
+ }
47
+ }
48
+
49
+ export function readSupabaseEnv(): SupabaseEnv {
50
+ // Hosted HTTP gateway: a per-request session set via runWithSupabaseEnv wins
51
+ // over any process-global env (multi-tenant safety). stdio has no store → falls
52
+ // through to the env/login resolution below.
53
+ const perRequest = requestEnv.getStore();
54
+ if (perRequest) return perRequest;
55
+
56
+ // Canonical env vars are MOSADD_*; the legacy M0SSAD_* names are still
57
+ // honored (deprecated) so anyone who set them before the brand sweep keeps
58
+ // working. Env vars take precedence; fall back to the session saved by
59
+ // `mosadd login`.
60
+ const env = (canonical: string, legacy: string): string | undefined =>
61
+ process.env[canonical] ?? process.env[legacy];
62
+ const userJwtEnv = env("MOSADD_USER_JWT", "M0SSAD_USER_JWT");
63
+
64
+ const session = loadSession();
65
+ const url = env("MOSADD_SUPABASE_URL", "M0SSAD_SUPABASE_URL") ?? session?.url;
66
+ const anonKey = env("MOSADD_SUPABASE_ANON_KEY", "M0SSAD_SUPABASE_ANON_KEY") ?? session?.anonKey;
67
+ const userJwt = userJwtEnv ?? session?.accessToken;
68
+
69
+ const missing: string[] = [];
70
+ if (!url) missing.push("MOSADD_SUPABASE_URL");
71
+ if (!anonKey) missing.push("MOSADD_SUPABASE_ANON_KEY");
72
+ if (missing.length) throw new MissingSupabaseEnvError(missing);
73
+
74
+ // Surface an expired `mosadd login` token early with an actionable message.
75
+ if (!userJwtEnv && session && isSessionExpired(session)) {
76
+ throw new Error("Your mosadd session has expired. Run `mosadd login` again to refresh it.");
77
+ }
78
+ return { url: url!, anonKey: anonKey!, userJwt };
79
+ }
80
+
81
+ export function getSupabase(env: SupabaseEnv = readSupabaseEnv()): SupabaseClient {
82
+ return createClient(env.url, env.anonKey, {
83
+ auth: {
84
+ persistSession: false,
85
+ autoRefreshToken: false,
86
+ detectSessionInUrl: false,
87
+ },
88
+ global: env.userJwt
89
+ ? {
90
+ headers: { Authorization: `Bearer ${env.userJwt}` },
91
+ }
92
+ : undefined,
93
+ });
94
+ }
95
+
96
+ /**
97
+ * Invoke a the legacy mosadd consumer-app repo Edge Function. Wraps `supabase.functions.invoke` with
98
+ * normalized error handling so MCP tool handlers can throw clean errors that
99
+ * agents can reason about.
100
+ */
101
+ export async function invokeFunction<T = unknown>(
102
+ fn: string,
103
+ body: Record<string, unknown>,
104
+ ): Promise<T> {
105
+ const client = getSupabase();
106
+ const { data, error } = await client.functions.invoke<T>(fn, { body });
107
+ if (error) {
108
+ // supabase-js throws FunctionsHttpError for any non-2xx, whose `.message`
109
+ // is the FIXED generic string "Edge Function returned a non-2xx status
110
+ // code" — the *real* reason (e.g. {"error":"wrapped_group_key required"},
111
+ // "forbidden", an RLS denial) lives in `error.context`, a Response. Read it
112
+ // so the agent gets an actionable message (and the HTTP status) it can
113
+ // reason about and self-correct on, instead of the same opaque sentence
114
+ // for every failure across mDM/mIRC/mp0st/mRAG/prekey/message-list.
115
+ let msg =
116
+ error instanceof Error && error.message
117
+ ? error.message
118
+ : `Edge function ${fn} failed`;
119
+ const ctx = (error as { context?: unknown }).context;
120
+ if (ctx && typeof (ctx as Response).text === "function") {
121
+ const res = ctx as Response;
122
+ try {
123
+ const raw = await res.text();
124
+ if (raw) {
125
+ let detail = raw;
126
+ try {
127
+ const parsed = JSON.parse(raw) as { error?: unknown; message?: unknown };
128
+ detail =
129
+ (typeof parsed.error === "string" && parsed.error) ||
130
+ (typeof parsed.message === "string" && parsed.message) ||
131
+ raw;
132
+ } catch {
133
+ // non-JSON body — use the raw text as-is
134
+ }
135
+ const status = typeof res.status === "number" ? res.status : undefined;
136
+ msg = status ? `${fn} (${status}): ${detail}` : `${fn}: ${detail}`;
137
+ }
138
+ } catch {
139
+ // body already consumed or unreadable — keep the generic message
140
+ }
141
+ }
142
+ throw new Error(msg);
143
+ }
144
+ if (data == null) {
145
+ throw new Error(`Edge function ${fn} returned no data`);
146
+ }
147
+ return data;
148
+ }
package/src/server.ts CHANGED
@@ -1,103 +1,123 @@
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 { InMemoryMdmKeyStore } from "./crypto/mdm-session.js";
9
- import type { MosaddServerOptions, MosaddToolContext, ProviderRegistry } from "./types.js";
10
-
11
- /**
12
- * Resolve the channel ProviderRegistry: default network adapters merged with
13
- * anything the host injects. A carrier-aware host (cymru-os) passes its own
14
- * radio DmProvider via `injected.dm`. This is the single place the default
15
- * adapters are named — both `createMosaddServer` and the `@mosadd/ai` adapters
16
- * build their context through it so they stay in lockstep.
17
- */
18
- export function defaultProviders(injected?: Partial<ProviderRegistry>): ProviderRegistry {
19
- return {
20
- dm: injected?.dm ?? new SupabaseDmProvider(),
21
- keys: injected?.keys ?? new InMemoryMdmKeyStore(),
22
- };
23
- }
24
-
25
- export function createMosaddServer(options: MosaddServerOptions = {}) {
26
- const mode = options.mode ?? (options.apiKey ? "cloud" : "local");
27
- const hubUrl = options.hubUrl ?? "https://mcp.mosadd.com";
28
- const logLevel = options.logLevel ?? "info";
29
-
30
- // DI seam: default network adapters, overridden by anything the host injects.
31
- const providers = defaultProviders(options.providers);
32
-
33
- const ctx: MosaddToolContext = {
34
- options: { ...options, mode, hubUrl },
35
- providers,
36
- log: (level, msg, extra) => {
37
- if (shouldLog(level, logLevel)) {
38
- // MCP servers must write logs to stderr (stdout is the protocol channel).
39
- process.stderr.write(
40
- JSON.stringify({ level, msg, extra, ts: new Date().toISOString() }) + "\n",
41
- );
42
- }
43
- },
44
- };
45
-
46
- const server = new McpServer(
47
- {
48
- name: "mosadd",
49
- version: "3.0.0-alpha.0",
50
- },
51
- {
52
- capabilities: {
53
- tools: {},
54
- },
55
- },
56
- );
57
-
58
- for (const tool of allTools) {
59
- // MCP SDK v1.x expects the field-level Zod shape (`{ to: z.string(), text: z.string() }`),
60
- // not the wrapping `z.object({...})`. Tool inputs are declared as ZodObject schemas
61
- // so we can `.parse()` them in the handler; surface the inner `.shape` to the SDK here.
62
- const shape =
63
- tool.inputSchema && typeof tool.inputSchema === "object" && "shape" in tool.inputSchema
64
- ? (tool.inputSchema as { shape: Record<string, unknown> }).shape
65
- : (tool.inputSchema as unknown as Record<string, unknown>);
66
-
67
- server.tool(
68
- tool.name,
69
- tool.description,
70
- shape as Parameters<typeof server.tool>[2],
71
- async (input: unknown) => {
72
- const parsed = tool.inputSchema.parse(input);
73
- try {
74
- const result = await tool.handler(parsed as never, ctx);
75
- return {
76
- content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }],
77
- };
78
- } catch (err) {
79
- ctx.log("error", `tool ${tool.name} failed`, { error: String(err) });
80
- return {
81
- isError: true,
82
- content: [
83
- {
84
- type: "text" as const,
85
- text: JSON.stringify({
86
- error: err instanceof Error ? err.message : String(err),
87
- tool: tool.name,
88
- }),
89
- },
90
- ],
91
- };
92
- }
93
- },
94
- );
95
- }
96
-
97
- return server;
98
- }
99
-
100
- function shouldLog(level: string, threshold: string): boolean {
101
- const order = { debug: 0, info: 1, warn: 2, error: 3 } as const;
102
- return (order[level as keyof typeof order] ?? 1) >= (order[threshold as keyof typeof order] ?? 1);
103
- }
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, publishOwnPrekeys } 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
+ // Cold-start fix: make this identity reachable for inbound E2EE DMs the moment
49
+ // the server is up, so mDM_send works without every recipient first running
50
+ // mDM_publish_keys. Best-effort and non-fatal — it needs an authenticated
51
+ // session, so it silently skips when there is none (BYOK without a JWT, offline,
52
+ // etc.) and never blocks startup. Uses the SAME keystore the tools use, so the
53
+ // published identity matches what mDM_send/encryptForPeer will use this process.
54
+ if (options.autoPublishKeys) {
55
+ void publishOwnPrekeys(providers.keys, providers.dm)
56
+ .then((r) => ctx.log("debug", "auto-published mDM prekeys", { one_time_prekeys: r.oneTimePrekeyCount }))
57
+ .catch((err) => ctx.log("debug", "auto-publish mDM prekeys skipped", { error: String(err) }));
58
+ }
59
+
60
+ const server = new McpServer(
61
+ {
62
+ name: "mosadd",
63
+ version: "3.0.0-alpha.28",
64
+ },
65
+ {
66
+ capabilities: {
67
+ tools: {},
68
+ },
69
+ },
70
+ );
71
+
72
+ for (const tool of allTools) {
73
+ // MCP SDK v1.x expects the field-level Zod shape (`{ to: z.string(), text: z.string() }`),
74
+ // not the wrapping `z.object({...})`. Tool inputs are declared as ZodObject schemas
75
+ // so we can `.parse()` them in the handler; surface the inner `.shape` to the SDK here.
76
+ const shape =
77
+ tool.inputSchema && typeof tool.inputSchema === "object" && "shape" in tool.inputSchema
78
+ ? (tool.inputSchema as { shape: Record<string, unknown> }).shape
79
+ : (tool.inputSchema as unknown as Record<string, unknown>);
80
+
81
+ server.tool(
82
+ tool.name,
83
+ tool.description,
84
+ shape as Parameters<typeof server.tool>[2],
85
+ async (input: unknown) => {
86
+ const parsed = tool.inputSchema.parse(input);
87
+ try {
88
+ const result = await tool.handler(parsed as never, ctx);
89
+ // A tool may return rich MCP content (e.g. an image frame from
90
+ // comms_action_frame_get) via `mcpContent`; pass it through verbatim.
91
+ const rich = result as { mcpContent?: unknown[] } | null;
92
+ if (rich && Array.isArray(rich.mcpContent)) {
93
+ return { content: rich.mcpContent as never[] };
94
+ }
95
+ return {
96
+ content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }],
97
+ };
98
+ } catch (err) {
99
+ ctx.log("error", `tool ${tool.name} failed`, { error: String(err) });
100
+ return {
101
+ isError: true,
102
+ content: [
103
+ {
104
+ type: "text" as const,
105
+ text: JSON.stringify({
106
+ error: err instanceof Error ? err.message : String(err),
107
+ tool: tool.name,
108
+ }),
109
+ },
110
+ ],
111
+ };
112
+ }
113
+ },
114
+ );
115
+ }
116
+
117
+ return server;
118
+ }
119
+
120
+ function shouldLog(level: string, threshold: string): boolean {
121
+ const order = { debug: 0, info: 1, warn: 2, error: 3 } as const;
122
+ return (order[level as keyof typeof order] ?? 1) >= (order[threshold as keyof typeof order] ?? 1);
123
+ }