@mosadd/mcp 3.0.0-alpha.55 → 3.0.0-alpha.57

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 (54) hide show
  1. package/CHANGELOG.md +15 -11
  2. package/README.md +152 -150
  3. package/dist/bin/mcp.js +1 -1
  4. package/dist/{chunk-IWUGKLDX.js → chunk-WEGSITAH.js} +30 -14
  5. package/dist/index.js +1 -1
  6. package/package.json +2 -2
  7. package/src/__tests__/blob-upload.test.ts +93 -93
  8. package/src/__tests__/channel-e2ee.test.ts +62 -62
  9. package/src/__tests__/flota-jawnie.test.ts +2 -2
  10. package/src/__tests__/golden-path.test.ts +139 -139
  11. package/src/__tests__/integration.test.ts +217 -182
  12. package/src/__tests__/label-room-owner.test.ts +22 -0
  13. package/src/__tests__/mdm-e2ee.test.ts +212 -212
  14. package/src/__tests__/mdm-mcp-readable.test.ts +390 -390
  15. package/src/__tests__/mirc-invite.test.ts +112 -112
  16. package/src/__tests__/mtalk.test.ts +122 -122
  17. package/src/__tests__/presence.test.ts +199 -199
  18. package/src/__tests__/server.test.ts +71 -71
  19. package/src/__tests__/tool-count-consistency.test.ts +259 -199
  20. package/src/__tests__/voice-fields.test.ts +24 -0
  21. package/src/bin/login.ts +138 -138
  22. package/src/bin/mcp.ts +145 -145
  23. package/src/config.ts +66 -66
  24. package/src/crypto/channel-e2ee.ts +288 -288
  25. package/src/crypto/mdm-session.ts +842 -842
  26. package/src/index.ts +19 -19
  27. package/src/observability/sentry.ts +79 -79
  28. package/src/providers/blob-upload.ts +162 -162
  29. package/src/providers/memory-voice.ts +79 -79
  30. package/src/providers/supabase-dm.ts +212 -202
  31. package/src/providers/supabase-voice.ts +103 -91
  32. package/src/server.ts +195 -195
  33. package/src/tools/actions.ts +166 -166
  34. package/src/tools/attachments.ts +276 -276
  35. package/src/tools/capabilities.ts +70 -70
  36. package/src/tools/channel-payload.ts +2 -2
  37. package/src/tools/embed.ts +110 -110
  38. package/src/tools/index.ts +181 -181
  39. package/src/tools/knowledge.ts +344 -344
  40. package/src/tools/mail-aliases.ts +25 -25
  41. package/src/tools/mail-provenance.ts +137 -137
  42. package/src/tools/mail.ts +403 -403
  43. package/src/tools/mdm-as-agent.ts +138 -126
  44. package/src/tools/mdm.ts +6 -4
  45. package/src/tools/mirc-edge.ts +196 -196
  46. package/src/tools/mirc-members.ts +287 -287
  47. package/src/tools/mirc-messages.ts +1 -1
  48. package/src/tools/mirc.ts +308 -308
  49. package/src/tools/mroom.ts +221 -221
  50. package/src/tools/mtalk.ts +131 -131
  51. package/src/tools/presence.ts +442 -442
  52. package/src/tools/voice-format.ts +43 -28
  53. package/src/types.ts +121 -121
  54. package/src/voice/floor.ts +132 -132
@@ -1,91 +1,103 @@
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
+ /**
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 = labelRoomId(self, label);
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
+ /**
86
+ * 15.11.2026 — nazwa pokoju PTT. Bez etykiety: pokój osobisty `mosadd-room-<id>`. Z etykietą:
87
+ * `mosadd-room-<id otwierającego>-<etykieta>` — właściciel jest w nazwie, więc bramka
88
+ * (mosADD `livekit-token/labelRoom.ts`) wpuszcza właściciela i jego kontakty, a obcy nie przejmie
89
+ * pokoju wejściem jako pierwszy. Dawne `mosadd-room-<etykieta>` było jedną nazwą dla wszystkich
90
+ * kont bez właściciela → 403 dla każdego.
91
+ */
92
+ export function labelRoomId(selfIdentityId: string, label?: string): string {
93
+ if (!label) return `${ROOM_PREFIX}${selfIdentityId}`;
94
+ return `${ROOM_PREFIX}${selfIdentityId}-${slug(label) || "room"}`;
95
+ }
96
+
97
+ function slug(s: string): string {
98
+ return s
99
+ .toLowerCase()
100
+ .replace(/[^a-z0-9._-]+/g, "-")
101
+ .replace(/^-+|-+$/g, "")
102
+ .slice(0, 200);
103
+ }
package/src/server.ts CHANGED
@@ -1,195 +1,195 @@
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 {
12
- InMemoryMdmKeyStore,
13
- SecretMdmKeyStore,
14
- bundlePolicyForKind,
15
- ensureOwnBundlePublished,
16
- } from "./crypto/mdm-session.js";
17
- import type { MosaddServerOptions, MosaddToolContext, ProviderRegistry } from "./types.js";
18
-
19
- /**
20
- * Resolve the channel ProviderRegistry: default network adapters merged with
21
- * anything the host injects. A carrier-aware host (cymru-os) passes its own
22
- * radio DmProvider via `injected.dm`. This is the single place the default
23
- * adapters are named — both `createMosaddServer` and the `@mosadd/ai` adapters
24
- * build their context through it so they stay in lockstep.
25
- */
26
- export function defaultProviders(
27
- injected?: Partial<ProviderRegistry>,
28
- opts: { mdmSecret?: string } = {},
29
- ): ProviderRegistry {
30
- return {
31
- dm: injected?.dm ?? new SupabaseDmProvider(),
32
- keys: injected?.keys ?? defaultKeyStore(opts.mdmSecret),
33
- voice: injected?.voice ?? new SupabaseVoiceProvider(),
34
- };
35
- }
36
-
37
- /**
38
- * ⛔ ONE IDENTITY PER LOGIN SECRET, NOT ONE PER CALL (27.09.2026). With an API key the mDM
39
- * identity is derived from it (SecretMdmKeyStore → SeededMdmKeyStore): the hosted gateway builds
40
- * a new server per HTTP request, and with a random in-memory keystore every mDM_send was sealed
41
- * by an identity that lived for one request. Without any secret (BYOK JWT only) there is nothing
42
- * stable to derive from, so the old per-process random keystore remains.
43
- *
44
- * ⛔ STABLE PER KEY, NOT PER IDENTITY. One identity holds many keys (each OAuth connector mints
45
- * its own), so this seed never publishes on its own authority: agent lines send in the clear and
46
- * people keep the app's bundle (bundlePolicyForKind in crypto/mdm-session.ts).
47
- */
48
- function defaultKeyStore(secret?: string) {
49
- const s = (secret ?? "").trim();
50
- return s ? new SecretMdmKeyStore(s) : new InMemoryMdmKeyStore();
51
- }
52
-
53
- export function createMosaddServer(options: MosaddServerOptions = {}) {
54
- const mode = options.mode ?? (options.apiKey ? "cloud" : "local");
55
- const hubUrl = options.hubUrl ?? "https://mcp.mosadd.com";
56
- const logLevel = options.logLevel ?? "info";
57
-
58
- // DI seam: default network adapters, overridden by anything the host injects.
59
- const providers = defaultProviders(options.providers, { mdmSecret: options.apiKey });
60
-
61
- const ctx: MosaddToolContext = {
62
- options: { ...options, mode, hubUrl },
63
- providers,
64
- log: (level, msg, extra) => {
65
- if (shouldLog(level, logLevel)) {
66
- // MCP servers must write logs to stderr (stdout is the protocol channel).
67
- process.stderr.write(
68
- JSON.stringify({ level, msg, extra, ts: new Date().toISOString() }) + "\n",
69
- );
70
- }
71
- },
72
- };
73
-
74
- // Cold-start fix: make this identity reachable for inbound E2EE DMs the moment
75
- // the server is up, so mDM_send works without every recipient first running
76
- // mDM_publish_keys. Best-effort and non-fatal — it needs an authenticated
77
- // session, so it silently skips when there is none (BYOK without a JWT, offline,
78
- // etc.) and never blocks startup. Uses the SAME keystore the tools use, so the
79
- // published identity matches what mDM_send/encryptForPeer will use this process.
80
- //
81
- // ⛔ ENSURE, NOT BLIND PUBLISH (27.09.2026, poprawka po weryfikacji): the policy is
82
- // bundlePolicyForKind — the SAME one mDM_send uses. Agent line: writes NOTHING (it sends in the
83
- // clear, rozkaz Krola 20.09; a per-key bundle from each of its keys only made the directory flap).
84
- // Human: writes NOTHING (the app owns that bundle). Unknown kind (e.g. radio): empty -> publish.
85
- if (options.autoPublishKeys) {
86
- void (async () => {
87
- const selfId = await providers.dm.selfId();
88
- const kind = await (providers.dm as { selfKind?: () => Promise<string | null> }).selfKind?.();
89
- return ensureOwnBundlePublished(providers.keys, providers.dm, selfId, bundlePolicyForKind(kind, { explicit: false }));
90
- })()
91
- .then((state) => ctx.log("debug", "auto-ensure mDM prekeys", { state }))
92
- .catch((err) => ctx.log("debug", "auto-publish mDM prekeys skipped", { error: String(err) }));
93
- }
94
-
95
- const server = new McpServer(
96
- {
97
- name: "mosadd",
98
- // Human-facing identity of the server itself (initialize result). The icon URLs
99
- // point at the LIVE gateway origin on purpose: clients that honour serverInfo.icons
100
- // get the brand mark without scraping the favicon, and the files ship with
101
- // apps/mcp-http/public (canon 08-26 — generated by m0ssad-3 scripts/
102
- // generate-brand-icons.py, never hand-edited).
103
- title: "mosADD — omnichannel messenger for agents",
104
- websiteUrl: "https://mosadd.com",
105
- icons: [
106
- { src: "https://mcp.mosadd.com/favicon.svg", mimeType: "image/svg+xml", sizes: ["any"] },
107
- { src: "https://mcp.mosadd.com/pwa-192.png", mimeType: "image/png", sizes: ["192x192"] },
108
- ],
109
- version: PKG_VERSION,
110
- },
111
- {
112
- capabilities: {
113
- tools: {},
114
- },
115
- },
116
- );
117
-
118
- for (const tool of allTools) {
119
- // MCP SDK v1.x expects the field-level Zod shape (`{ to: z.string(), text: z.string() }`),
120
- // not the wrapping `z.object({...})`. Tool inputs are declared as ZodObject schemas
121
- // so we can `.parse()` them in the handler; surface the inner `.shape` to the SDK here.
122
- const shape =
123
- tool.inputSchema && typeof tool.inputSchema === "object" && "shape" in tool.inputSchema
124
- ? (tool.inputSchema as { shape: Record<string, unknown> }).shape
125
- : (tool.inputSchema as unknown as Record<string, unknown>);
126
-
127
- // Tool annotations ride the 5-arg overload (SDK ≥1.12 serialises them into
128
- // tools/list verbatim). Without them EVERY tool lands in the connector UI's flat
129
- // "Other tools" bucket — the exact founder complaint this fixes. `title` is spec'd
130
- // inside ToolAnnotations, so it travels in the same object.
131
- const annotations =
132
- tool.title || tool.annotations
133
- ? { ...(tool.title ? { title: tool.title } : {}), ...(tool.annotations ?? {}) }
134
- : undefined;
135
-
136
- const toolCallback = async (input: unknown) => {
137
- const parsed = tool.inputSchema.parse(input);
138
- try {
139
- const result = await tool.handler(parsed as never, ctx);
140
- // AUTO-PAROWANIE (08-26): a LIVE session that is actually WORKING holds its line —
141
- // the founder spent a week talking to cloud stand-ins because models never
142
- // remembered the attach handshake. Fire-and-forget, throttled inside, never blocks
143
- // the tool's own response; see autoBeatFromActivity for which line gets the beat.
144
- void autoBeatFromActivity(ctx);
145
- // A tool may return rich MCP content (e.g. an image frame from
146
- // comms_action_frame_get) via `mcpContent`; pass it through verbatim.
147
- const rich = result as { mcpContent?: unknown[] } | null;
148
- if (rich && Array.isArray(rich.mcpContent)) {
149
- return { content: rich.mcpContent as never[] };
150
- }
151
- return {
152
- content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }],
153
- };
154
- } catch (err) {
155
- ctx.log("error", `tool ${tool.name} failed`, { error: String(err) });
156
- return {
157
- isError: true,
158
- content: [
159
- {
160
- type: "text" as const,
161
- text: JSON.stringify({
162
- error: err instanceof Error ? err.message : String(err),
163
- tool: tool.name,
164
- }),
165
- },
166
- ],
167
- };
168
- }
169
- };
170
-
171
- if (annotations) {
172
- server.tool(
173
- tool.name,
174
- tool.description,
175
- shape as Parameters<typeof server.tool>[2],
176
- annotations,
177
- toolCallback,
178
- );
179
- } else {
180
- server.tool(
181
- tool.name,
182
- tool.description,
183
- shape as Parameters<typeof server.tool>[2],
184
- toolCallback,
185
- );
186
- }
187
- }
188
-
189
- return server;
190
- }
191
-
192
- function shouldLog(level: string, threshold: string): boolean {
193
- const order = { debug: 0, info: 1, warn: 2, error: 3 } as const;
194
- return (order[level as keyof typeof order] ?? 1) >= (order[threshold as keyof typeof order] ?? 1);
195
- }
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 {
12
+ InMemoryMdmKeyStore,
13
+ SecretMdmKeyStore,
14
+ bundlePolicyForKind,
15
+ ensureOwnBundlePublished,
16
+ } from "./crypto/mdm-session.js";
17
+ import type { MosaddServerOptions, MosaddToolContext, ProviderRegistry } from "./types.js";
18
+
19
+ /**
20
+ * Resolve the channel ProviderRegistry: default network adapters merged with
21
+ * anything the host injects. A carrier-aware host (cymru-os) passes its own
22
+ * radio DmProvider via `injected.dm`. This is the single place the default
23
+ * adapters are named — both `createMosaddServer` and the `@mosadd/ai` adapters
24
+ * build their context through it so they stay in lockstep.
25
+ */
26
+ export function defaultProviders(
27
+ injected?: Partial<ProviderRegistry>,
28
+ opts: { mdmSecret?: string } = {},
29
+ ): ProviderRegistry {
30
+ return {
31
+ dm: injected?.dm ?? new SupabaseDmProvider(),
32
+ keys: injected?.keys ?? defaultKeyStore(opts.mdmSecret),
33
+ voice: injected?.voice ?? new SupabaseVoiceProvider(),
34
+ };
35
+ }
36
+
37
+ /**
38
+ * ⛔ ONE IDENTITY PER LOGIN SECRET, NOT ONE PER CALL (27.09.2026). With an API key the mDM
39
+ * identity is derived from it (SecretMdmKeyStore → SeededMdmKeyStore): the hosted gateway builds
40
+ * a new server per HTTP request, and with a random in-memory keystore every mDM_send was sealed
41
+ * by an identity that lived for one request. Without any secret (BYOK JWT only) there is nothing
42
+ * stable to derive from, so the old per-process random keystore remains.
43
+ *
44
+ * ⛔ STABLE PER KEY, NOT PER IDENTITY. One identity holds many keys (each OAuth connector mints
45
+ * its own), so this seed never publishes on its own authority: agent lines send in the clear and
46
+ * people keep the app's bundle (bundlePolicyForKind in crypto/mdm-session.ts).
47
+ */
48
+ function defaultKeyStore(secret?: string) {
49
+ const s = (secret ?? "").trim();
50
+ return s ? new SecretMdmKeyStore(s) : new InMemoryMdmKeyStore();
51
+ }
52
+
53
+ export function createMosaddServer(options: MosaddServerOptions = {}) {
54
+ const mode = options.mode ?? (options.apiKey ? "cloud" : "local");
55
+ const hubUrl = options.hubUrl ?? "https://mcp.mosadd.com";
56
+ const logLevel = options.logLevel ?? "info";
57
+
58
+ // DI seam: default network adapters, overridden by anything the host injects.
59
+ const providers = defaultProviders(options.providers, { mdmSecret: options.apiKey });
60
+
61
+ const ctx: MosaddToolContext = {
62
+ options: { ...options, mode, hubUrl },
63
+ providers,
64
+ log: (level, msg, extra) => {
65
+ if (shouldLog(level, logLevel)) {
66
+ // MCP servers must write logs to stderr (stdout is the protocol channel).
67
+ process.stderr.write(
68
+ JSON.stringify({ level, msg, extra, ts: new Date().toISOString() }) + "\n",
69
+ );
70
+ }
71
+ },
72
+ };
73
+
74
+ // Cold-start fix: make this identity reachable for inbound E2EE DMs the moment
75
+ // the server is up, so mDM_send works without every recipient first running
76
+ // mDM_publish_keys. Best-effort and non-fatal — it needs an authenticated
77
+ // session, so it silently skips when there is none (BYOK without a JWT, offline,
78
+ // etc.) and never blocks startup. Uses the SAME keystore the tools use, so the
79
+ // published identity matches what mDM_send/encryptForPeer will use this process.
80
+ //
81
+ // ⛔ ENSURE, NOT BLIND PUBLISH (27.09.2026, poprawka po weryfikacji): the policy is
82
+ // bundlePolicyForKind — the SAME one mDM_send uses. Agent line: writes NOTHING (it sends in the
83
+ // clear, rozkaz Krola 20.09; a per-key bundle from each of its keys only made the directory flap).
84
+ // Human: writes NOTHING (the app owns that bundle). Unknown kind (e.g. radio): empty -> publish.
85
+ if (options.autoPublishKeys) {
86
+ void (async () => {
87
+ const selfId = await providers.dm.selfId();
88
+ const kind = await (providers.dm as { selfKind?: () => Promise<string | null> }).selfKind?.();
89
+ return ensureOwnBundlePublished(providers.keys, providers.dm, selfId, bundlePolicyForKind(kind, { explicit: false }));
90
+ })()
91
+ .then((state) => ctx.log("debug", "auto-ensure mDM prekeys", { state }))
92
+ .catch((err) => ctx.log("debug", "auto-publish mDM prekeys skipped", { error: String(err) }));
93
+ }
94
+
95
+ const server = new McpServer(
96
+ {
97
+ name: "mosadd",
98
+ // Human-facing identity of the server itself (initialize result). The icon URLs
99
+ // point at the LIVE gateway origin on purpose: clients that honour serverInfo.icons
100
+ // get the brand mark without scraping the favicon, and the files ship with
101
+ // the gateway's public/ folder (canon 08-26 — generated by m0ssad-3 scripts/
102
+ // generate-brand-icons.py, never hand-edited).
103
+ title: "mosADD — omnichannel messenger for agents",
104
+ websiteUrl: "https://mosadd.com",
105
+ icons: [
106
+ { src: "https://mcp.mosadd.com/favicon.svg", mimeType: "image/svg+xml", sizes: ["any"] },
107
+ { src: "https://mcp.mosadd.com/pwa-192.png", mimeType: "image/png", sizes: ["192x192"] },
108
+ ],
109
+ version: PKG_VERSION,
110
+ },
111
+ {
112
+ capabilities: {
113
+ tools: {},
114
+ },
115
+ },
116
+ );
117
+
118
+ for (const tool of allTools) {
119
+ // MCP SDK v1.x expects the field-level Zod shape (`{ to: z.string(), text: z.string() }`),
120
+ // not the wrapping `z.object({...})`. Tool inputs are declared as ZodObject schemas
121
+ // so we can `.parse()` them in the handler; surface the inner `.shape` to the SDK here.
122
+ const shape =
123
+ tool.inputSchema && typeof tool.inputSchema === "object" && "shape" in tool.inputSchema
124
+ ? (tool.inputSchema as { shape: Record<string, unknown> }).shape
125
+ : (tool.inputSchema as unknown as Record<string, unknown>);
126
+
127
+ // Tool annotations ride the 5-arg overload (SDK ≥1.12 serialises them into
128
+ // tools/list verbatim). Without them EVERY tool lands in the connector UI's flat
129
+ // "Other tools" bucket — the exact founder complaint this fixes. `title` is spec'd
130
+ // inside ToolAnnotations, so it travels in the same object.
131
+ const annotations =
132
+ tool.title || tool.annotations
133
+ ? { ...(tool.title ? { title: tool.title } : {}), ...(tool.annotations ?? {}) }
134
+ : undefined;
135
+
136
+ const toolCallback = async (input: unknown) => {
137
+ const parsed = tool.inputSchema.parse(input);
138
+ try {
139
+ const result = await tool.handler(parsed as never, ctx);
140
+ // AUTO-PAROWANIE (08-26): a LIVE session that is actually WORKING holds its line —
141
+ // the founder spent a week talking to cloud stand-ins because models never
142
+ // remembered the attach handshake. Fire-and-forget, throttled inside, never blocks
143
+ // the tool's own response; see autoBeatFromActivity for which line gets the beat.
144
+ void autoBeatFromActivity(ctx);
145
+ // A tool may return rich MCP content (e.g. an image frame from
146
+ // comms_action_frame_get) via `mcpContent`; pass it through verbatim.
147
+ const rich = result as { mcpContent?: unknown[] } | null;
148
+ if (rich && Array.isArray(rich.mcpContent)) {
149
+ return { content: rich.mcpContent as never[] };
150
+ }
151
+ return {
152
+ content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }],
153
+ };
154
+ } catch (err) {
155
+ ctx.log("error", `tool ${tool.name} failed`, { error: String(err) });
156
+ return {
157
+ isError: true,
158
+ content: [
159
+ {
160
+ type: "text" as const,
161
+ text: JSON.stringify({
162
+ error: err instanceof Error ? err.message : String(err),
163
+ tool: tool.name,
164
+ }),
165
+ },
166
+ ],
167
+ };
168
+ }
169
+ };
170
+
171
+ if (annotations) {
172
+ server.tool(
173
+ tool.name,
174
+ tool.description,
175
+ shape as Parameters<typeof server.tool>[2],
176
+ annotations,
177
+ toolCallback,
178
+ );
179
+ } else {
180
+ server.tool(
181
+ tool.name,
182
+ tool.description,
183
+ shape as Parameters<typeof server.tool>[2],
184
+ toolCallback,
185
+ );
186
+ }
187
+ }
188
+
189
+ return server;
190
+ }
191
+
192
+ function shouldLog(level: string, threshold: string): boolean {
193
+ const order = { debug: 0, info: 1, warn: 2, error: 3 } as const;
194
+ return (order[level as keyof typeof order] ?? 1) >= (order[threshold as keyof typeof order] ?? 1);
195
+ }