@mosadd/mcp 3.0.0-alpha.46 → 3.0.0-alpha.48

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.
package/src/server.ts CHANGED
@@ -1,162 +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 { 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
- }
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
+ }
@@ -1,67 +1,67 @@
1
- /**
2
- * mRAG_delete MUSI foldować source_id dokładnie tak, jak robi to mRAG_ingest.
3
- *
4
- * ⛔ ZMIERZONA AWARIA (2026-08-28). `mRAG_ingest` przepuszczał nie-UUID przez `uuidV5`, a
5
- * `mRAG_delete` wysyłał SUROWY napis prosto do kolumny UUID. Efekt na żywo:
6
- *
7
- * mRAG_ingest { source_id: "DIAG-GENERAL-2026-08-28-a1b2c3" } → { indexed: 1 } ✅
8
- * mRAG_delete { source_id: "DIAG-GENERAL-2026-08-28-a1b2c3" } → 500
9
- * "invalid input syntax for type uuid" ❌
10
- *
11
- * Czyli: dokument zaindeksowany pod NATURALNYM kluczem (numer sprawy, ścieżka pliku, threadId
12
- * Gmaila) dawało się dodać, ale **nigdy nie dawało się go usunąć tym samym identyfikatorem**.
13
- * Dwie połowy tej samej rury nie zgadzały się ze sobą.
14
- *
15
- * I to nie było niedopatrzenie w cieniu — obietnica stała w DWÓCH miejscach, a implementacja
16
- * w jednym: komentarz przy foldowaniu mówi „so grouping and mRAG_delete keep working on natural
17
- * keys", a opis narzędzia obiecuje userowi „can later be removed with mRAG_delete".
18
- *
19
- * Boli najbardziej przy korpusie, bo tam naturalne klucze są jedynym sposobem na dedup przy
20
- * ponownym wczytaniu — a właśnie tak mielone są akta.
21
- *
22
- * Ten test pilnuje INWARIANTU, nie implementacji: cokolwiek robi ingest ze swoim `source_id`,
23
- * delete ma zrobić to samo. Gdyby ktoś kiedyś zmienił namespace albo wersję UUID, obie strony
24
- * muszą pojechać razem — i to złapie każdy rozjazd.
25
- */
26
- import { describe, it, expect } from "vitest";
27
- import { readFileSync } from "node:fs";
28
- import { dirname, join } from "node:path";
29
- import { fileURLToPath } from "node:url";
30
-
31
- const HERE = dirname(fileURLToPath(import.meta.url));
32
- const SRC = readFileSync(join(HERE, "..", "knowledge.ts"), "utf8");
33
-
34
- /** Ciało funkcji o danej nazwie — od jej deklaracji do następnej deklaracji `async function`. */
35
- function bodyOf(name: string): string {
36
- const start = SRC.indexOf(`async function ${name}(`);
37
- expect(start, `nie znaleziono funkcji ${name} w knowledge.ts`).toBeGreaterThan(-1);
38
- const next = SRC.indexOf("\nasync function ", start + 1);
39
- return SRC.slice(start, next === -1 ? SRC.length : next);
40
- }
41
-
42
- describe("mRAG_delete — zgodność foldowania z mRAG_ingest", () => {
43
- it("delete folduje source_id przez uuidV5, tak samo jak ingest", () => {
44
- const del = bodyOf("mRAG_delete");
45
- expect(del, "mRAG_delete musi wołać uuidV5 — inaczej naturalny klucz da 500 na kolumnie uuid")
46
- .toContain("uuidV5(");
47
- expect(del, "mRAG_delete musi używać TEGO SAMEGO namespace co ingest")
48
- .toContain("SOURCE_ID_NAMESPACE");
49
- expect(del, "mRAG_delete musi rozpoznawać gotowy UUID i go NIE przerabiać")
50
- .toContain("UUID_RE");
51
- });
52
-
53
- it("delete NIE wysyła surowego input.source_id do rag-sources", () => {
54
- const del = bodyOf("mRAG_delete");
55
- expect(
56
- /source_id:\s*input\.source_id\s*\?\?\s*null/.test(del),
57
- "regresja: surowy input.source_id znowu leci do rag-sources — to jest dokładnie ten błąd 500",
58
- ).toBe(false);
59
- });
60
-
61
- it("obie strony dzielą jedną definicję namespace i jedną funkcję uuidV5", () => {
62
- // Po jednej definicji każdej — dwie kopie to dwie prawdy, a na tym już się przejechaliśmy
63
- // przy trasach modeli (FALLBACK_ROUTES vs ai_routes).
64
- expect(SRC.match(/const SOURCE_ID_NAMESPACE\s*=/g)?.length ?? 0).toBe(1);
65
- expect(SRC.match(/function uuidV5\(/g)?.length ?? 0).toBe(1);
66
- });
67
- });
1
+ /**
2
+ * mRAG_delete MUSI foldować source_id dokładnie tak, jak robi to mRAG_ingest.
3
+ *
4
+ * ⛔ ZMIERZONA AWARIA (2026-08-28). `mRAG_ingest` przepuszczał nie-UUID przez `uuidV5`, a
5
+ * `mRAG_delete` wysyłał SUROWY napis prosto do kolumny UUID. Efekt na żywo:
6
+ *
7
+ * mRAG_ingest { source_id: "DIAG-GENERAL-2026-08-28-a1b2c3" } → { indexed: 1 } ✅
8
+ * mRAG_delete { source_id: "DIAG-GENERAL-2026-08-28-a1b2c3" } → 500
9
+ * "invalid input syntax for type uuid" ❌
10
+ *
11
+ * Czyli: dokument zaindeksowany pod NATURALNYM kluczem (numer sprawy, ścieżka pliku, threadId
12
+ * Gmaila) dawało się dodać, ale **nigdy nie dawało się go usunąć tym samym identyfikatorem**.
13
+ * Dwie połowy tej samej rury nie zgadzały się ze sobą.
14
+ *
15
+ * I to nie było niedopatrzenie w cieniu — obietnica stała w DWÓCH miejscach, a implementacja
16
+ * w jednym: komentarz przy foldowaniu mówi „so grouping and mRAG_delete keep working on natural
17
+ * keys", a opis narzędzia obiecuje userowi „can later be removed with mRAG_delete".
18
+ *
19
+ * Boli najbardziej przy korpusie, bo tam naturalne klucze są jedynym sposobem na dedup przy
20
+ * ponownym wczytaniu — a właśnie tak mielone są akta.
21
+ *
22
+ * Ten test pilnuje INWARIANTU, nie implementacji: cokolwiek robi ingest ze swoim `source_id`,
23
+ * delete ma zrobić to samo. Gdyby ktoś kiedyś zmienił namespace albo wersję UUID, obie strony
24
+ * muszą pojechać razem — i to złapie każdy rozjazd.
25
+ */
26
+ import { describe, it, expect } from "vitest";
27
+ import { readFileSync } from "node:fs";
28
+ import { dirname, join } from "node:path";
29
+ import { fileURLToPath } from "node:url";
30
+
31
+ const HERE = dirname(fileURLToPath(import.meta.url));
32
+ const SRC = readFileSync(join(HERE, "..", "knowledge.ts"), "utf8");
33
+
34
+ /** Ciało funkcji o danej nazwie — od jej deklaracji do następnej deklaracji `async function`. */
35
+ function bodyOf(name: string): string {
36
+ const start = SRC.indexOf(`async function ${name}(`);
37
+ expect(start, `nie znaleziono funkcji ${name} w knowledge.ts`).toBeGreaterThan(-1);
38
+ const next = SRC.indexOf("\nasync function ", start + 1);
39
+ return SRC.slice(start, next === -1 ? SRC.length : next);
40
+ }
41
+
42
+ describe("mRAG_delete — zgodność foldowania z mRAG_ingest", () => {
43
+ it("delete folduje source_id przez uuidV5, tak samo jak ingest", () => {
44
+ const del = bodyOf("mRAG_delete");
45
+ expect(del, "mRAG_delete musi wołać uuidV5 — inaczej naturalny klucz da 500 na kolumnie uuid")
46
+ .toContain("uuidV5(");
47
+ expect(del, "mRAG_delete musi używać TEGO SAMEGO namespace co ingest")
48
+ .toContain("SOURCE_ID_NAMESPACE");
49
+ expect(del, "mRAG_delete musi rozpoznawać gotowy UUID i go NIE przerabiać")
50
+ .toContain("UUID_RE");
51
+ });
52
+
53
+ it("delete NIE wysyła surowego input.source_id do rag-sources", () => {
54
+ const del = bodyOf("mRAG_delete");
55
+ expect(
56
+ /source_id:\s*input\.source_id\s*\?\?\s*null/.test(del),
57
+ "regresja: surowy input.source_id znowu leci do rag-sources — to jest dokładnie ten błąd 500",
58
+ ).toBe(false);
59
+ });
60
+
61
+ it("obie strony dzielą jedną definicję namespace i jedną funkcję uuidV5", () => {
62
+ // Po jednej definicji każdej — dwie kopie to dwie prawdy, a na tym już się przejechaliśmy
63
+ // przy trasach modeli (FALLBACK_ROUTES vs ai_routes).
64
+ expect(SRC.match(/const SOURCE_ID_NAMESPACE\s*=/g)?.length ?? 0).toBe(1);
65
+ expect(SRC.match(/function uuidV5\(/g)?.length ?? 0).toBe(1);
66
+ });
67
+ });