@mosadd/mcp 3.0.0-alpha.0

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.
@@ -0,0 +1,174 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { z } from 'zod';
3
+ import { DmProvider } from '@mosadd/providers';
4
+ import { RatchetState, SessionRole } from '@mosadd/crypto';
5
+
6
+ /**
7
+ * mDM end-to-end encryption — session layer (LINEAR-2357).
8
+ *
9
+ * Sits ABOVE the DmProvider. The provider moves opaque bytes; THIS module
10
+ * decides what those bytes are: an X3DH handshake + Double Ratchet ciphertext
11
+ * envelope, produced from `@mosadd/crypto` primitives.
12
+ *
13
+ * Flow (decision "1a" — prekey distribution rides the DmProvider):
14
+ * - Each peer publishes a prekey bundle via `dm.publishPrekeyBundle(bytes)`.
15
+ * - First contact: sender `dm.fetchPrekeyBundle(peer)` → X3DH (initiator) →
16
+ * Double Ratchet. The first ciphertext carries a handshake header
17
+ * (initiator IK + EK + consumed one-time-prekey id) so the recipient can
18
+ * run X3DH (responder) and derive the SAME root key.
19
+ * - Subsequent messages reuse the stored ratchet session (no header).
20
+ *
21
+ * SCOPE / known follow-ups (tracked on LINEAR-2357, NOT silently hidden):
22
+ * - Ratchet is strict in-order (no skipped-message keys) — fine for a single
23
+ * ordered thread; out-of-order/lossy transports need skipped-key handling.
24
+ * - Signed-prekey signature is carried but NOT yet verified (auth follow-up).
25
+ * - Initiator "glare" (both sides open simultaneously) not resolved.
26
+ * - Default keystore is in-memory (per-process); file/OS-keychain backing is
27
+ * a follow-up. The MdmKeyStore seam makes that a drop-in.
28
+ */
29
+
30
+ interface X25519Pair {
31
+ publicKey: Uint8Array;
32
+ privateKey: Uint8Array;
33
+ }
34
+ /** The local peer's long-term identity + prekeys (private halves included). */
35
+ interface OwnPrekeyMaterial {
36
+ /** X25519 DH identity — used in X3DH. */
37
+ identity: X25519Pair;
38
+ /**
39
+ * Ed25519 SIGNING identity — the long-term key a peer pins out-of-band
40
+ * (the "safety number"). Signs the bundle so a network/radio MITM can't swap
41
+ * the signed prekey or DH identity in transit.
42
+ */
43
+ signingIdentity: {
44
+ publicKey: Uint8Array;
45
+ privateKey: Uint8Array;
46
+ };
47
+ signedPrekey: {
48
+ id: number;
49
+ pair: X25519Pair;
50
+ };
51
+ oneTimePrekeys: Array<{
52
+ id: number;
53
+ pair: X25519Pair;
54
+ }>;
55
+ }
56
+ /** Persisted per-peer ratchet session. Plain data → trivially serializable. */
57
+ interface MdmSessionRecord {
58
+ ratchet: RatchetState;
59
+ role: SessionRole;
60
+ /** Handshake header still owed to the peer (initiator only, until first send). */
61
+ pendingHandshake?: {
62
+ ik: Uint8Array;
63
+ ek: Uint8Array;
64
+ opkId?: number;
65
+ };
66
+ }
67
+ /**
68
+ * Local custody of private key material + ratchet sessions. The default impl
69
+ * is in-memory; a host may inject a file- or keychain-backed implementation.
70
+ */
71
+ interface MdmKeyStore {
72
+ /** Own identity + prekeys. Generated lazily on first access, then stable. */
73
+ getOwnMaterial(): Promise<OwnPrekeyMaterial>;
74
+ /** Consume (one-time) a prekey private by id. Returns undefined if unknown. */
75
+ takeOneTimePrekey(id: number): Promise<Uint8Array | undefined>;
76
+ getSession(peerId: string): Promise<MdmSessionRecord | undefined>;
77
+ putSession(peerId: string, record: MdmSessionRecord): Promise<void>;
78
+ }
79
+
80
+ /**
81
+ * Internal types for the mosadd MCP server.
82
+ */
83
+
84
+ type Mode = "cloud" | "local" | "self-host";
85
+ /**
86
+ * Transport backends per channel. The server fills any missing entry with its
87
+ * default network adapter; a host (e.g. cymru-os) injects alternatives —
88
+ * notably a radio DmProvider — via `MosaddServerOptions.providers`. This is
89
+ * the DI seam that keeps mosadd-os transport-agnostic.
90
+ *
91
+ * `keys` is LOCAL crypto custody (identity + prekeys + ratchet sessions) for
92
+ * mDM E2EE — distinct from transport. Defaults to an in-process keystore; a
93
+ * host may inject a file/keychain-backed one.
94
+ */
95
+ interface ProviderRegistry {
96
+ dm: DmProvider;
97
+ keys: MdmKeyStore;
98
+ }
99
+ interface MosaddServerOptions {
100
+ /** API key for hosted mode. Required if mode === "cloud". */
101
+ apiKey?: string;
102
+ /** Override the default hub URL (https://mcp.mosadd.com). */
103
+ hubUrl?: string;
104
+ /** Operating mode. Defaults to "cloud" if apiKey is present, else "local". */
105
+ mode?: Mode;
106
+ /** Log level. */
107
+ logLevel?: "debug" | "info" | "warn" | "error";
108
+ /**
109
+ * Host-injected channel providers. Any omitted channel uses the default
110
+ * network adapter. A carrier-aware host supplies e.g. a radio DmProvider here.
111
+ */
112
+ providers?: Partial<ProviderRegistry>;
113
+ }
114
+ interface MosaddToolContext {
115
+ options: Required<Pick<MosaddServerOptions, "mode" | "hubUrl">> & MosaddServerOptions;
116
+ /** Resolved channel providers (defaults merged with host-injected ones). */
117
+ providers: ProviderRegistry;
118
+ /** Per-request logger. */
119
+ log: (level: "debug" | "info" | "warn" | "error", msg: string, extra?: unknown) => void;
120
+ }
121
+ /**
122
+ * Transport capability a tool requires to function. This is the ONE contract
123
+ * string shared with consuming hosts. e.g. cymru-os gates tools by carrier
124
+ * availability via this flag (cymru-os RFC 0002 D-Bus "Capability-flag bridge").
125
+ * The enum is FINAL and normalized with the cymru-os host; changing these
126
+ * values must be coordinated (Linear label `requires:cymru-input`).
127
+ *
128
+ * - "any" works over any transport, incl. off-grid radio (small,
129
+ * packet-friendly payloads). e.g. text DM.
130
+ * - "radio" radio-specific path (e.g. Codec2 audio frames). Off-grid OK.
131
+ * - "network" needs IP connectivity (server-hosted channels, email, public
132
+ * join links, bridges). NOT available off-grid.
133
+ */
134
+ type CapabilityRequirement = "any" | "radio" | "network";
135
+ interface MosaddTool<TInput = unknown, TOutput = unknown> {
136
+ /** Tool name. MUST follow the m{MODULE}_{operation} convention. */
137
+ name: string;
138
+ /** Short human-readable description. Shown to the model. */
139
+ description: string;
140
+ /**
141
+ * Transport this tool requires. Consuming hosts read this to gate tools by
142
+ * available carriers. Every tool MUST declare it explicitly.
143
+ */
144
+ requires: CapabilityRequirement;
145
+ /** Zod schema for input. */
146
+ inputSchema: z.ZodType<TInput>;
147
+ /** Tool handler. */
148
+ handler: (input: TInput, ctx: MosaddToolContext) => Promise<TOutput>;
149
+ }
150
+
151
+ /**
152
+ * Build a McpServer instance with all mosadd tools registered.
153
+ */
154
+
155
+ /**
156
+ * Resolve the channel ProviderRegistry: default network adapters merged with
157
+ * anything the host injects. A carrier-aware host (cymru-os) passes its own
158
+ * radio DmProvider via `injected.dm`. This is the single place the default
159
+ * adapters are named — both `createMosaddServer` and the `@mosadd/ai` adapters
160
+ * build their context through it so they stay in lockstep.
161
+ */
162
+ declare function defaultProviders(injected?: Partial<ProviderRegistry>): ProviderRegistry;
163
+ declare function createMosaddServer(options?: MosaddServerOptions): McpServer;
164
+
165
+ /**
166
+ * Tool registry. Each m* module contributes a set of tools.
167
+ *
168
+ * Phase 1 MVP (shipped): mDM, mIRC, mROOM, mAIL.
169
+ * Phase 1 full: + mTALK, mCALL, mIRL, plus bridges (mMATRIX, mDISCORD, mTELEGRAM, mSLACK, mSIGNAL).
170
+ */
171
+
172
+ declare const allTools: MosaddTool[];
173
+
174
+ export { type MosaddServerOptions, type MosaddTool, type MosaddToolContext, type ProviderRegistry, allTools, createMosaddServer, defaultProviders };
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ import {
2
+ allTools,
3
+ createMosaddServer,
4
+ defaultProviders
5
+ } from "./chunk-25L536JZ.js";
6
+ export {
7
+ allTools,
8
+ createMosaddServer,
9
+ defaultProviders
10
+ };
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "@mosadd/mcp",
3
+ "version": "3.0.0-alpha.0",
4
+ "description": "Model Context Protocol server for mosadd. Exposes m* OS modules (mDM, mTALK, mAIL, mCALL, mIRC, mIRL, mROOM, and bridges) as MCP tools to any agent runtime (Claude Code, Cursor, Windsurf, Cline, ChatGPT Apps, Lovable, Bolt, Goose, Manus, custom).",
5
+ "homepage": "https://github.com/Hei33enberg/mosadd-os/tree/main/packages/mcp",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/Hei33enberg/mosadd-os.git",
9
+ "directory": "packages/mcp"
10
+ },
11
+ "license": "Apache-2.0",
12
+ "type": "module",
13
+ "main": "./dist/index.js",
14
+ "module": "./dist/index.js",
15
+ "types": "./dist/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js"
20
+ }
21
+ },
22
+ "bin": {
23
+ "mosadd-mcp": "./dist/bin/mcp.js"
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "src",
28
+ "README.md",
29
+ "LICENSE"
30
+ ],
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "dependencies": {
35
+ "@modelcontextprotocol/sdk": "^1.0.4",
36
+ "@supabase/supabase-js": "^2.48.0",
37
+ "zod": "^4.3.6",
38
+ "@mosadd/crypto": "3.0.0-alpha.0",
39
+ "@mosadd/providers": "3.0.0-alpha.0",
40
+ "@mosadd/protocol": "3.0.0-alpha.0"
41
+ },
42
+ "devDependencies": {
43
+ "tsup": "^8.3.5",
44
+ "tsx": "^4.19.2",
45
+ "typescript": "^5.7.2",
46
+ "vitest": "^2.1.8"
47
+ },
48
+ "keywords": [
49
+ "mosadd",
50
+ "mcp",
51
+ "model-context-protocol",
52
+ "agent",
53
+ "claude",
54
+ "cursor",
55
+ "anthropic",
56
+ "communication",
57
+ "messaging"
58
+ ],
59
+ "scripts": {
60
+ "build": "tsup src/index.ts src/bin/mcp.ts --format esm --dts --clean --shims",
61
+ "dev": "tsx src/bin/mcp.ts",
62
+ "test": "vitest run",
63
+ "typecheck": "tsc -p tsconfig.json --noEmit",
64
+ "clean": "rm -rf dist .turbo"
65
+ }
66
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Golden-path E2E: the day-1 "done" bar for the provider-abstraction seam.
3
+ *
4
+ * Proves a carrier-aware HOST (e.g. cymru-os) can inject its own transport
5
+ * under mDM without mosadd-os knowing anything about that transport:
6
+ * 1. host learns capabilities (comms_capabilities) and sees mDM_send = "any"
7
+ * (usable off-grid over radio),
8
+ * 2. host injects a fake RadioProvider,
9
+ * 3. agent calls mDM_send,
10
+ * 4. the opaque payload bytes actually arrive at the injected provider,
11
+ * 5. they round-trip back out via mDM_list.
12
+ *
13
+ * This is the "is it sp, not just written" check the whole 2144 task hinges on.
14
+ */
15
+
16
+ import { describe, expect, it } from "vitest";
17
+ import type {
18
+ DmProvider,
19
+ DmSendArgs,
20
+ DmListArgs,
21
+ DmSendResult,
22
+ DmListResult,
23
+ } from "@mosadd/providers";
24
+ import { mdmTools } from "../tools/mdm.js";
25
+ import { makeCapabilitiesTool } from "../tools/capabilities.js";
26
+ import { allTools } from "../tools/index.js";
27
+ import { createMosaddServer } from "../server.js";
28
+ import { InMemoryMdmKeyStore } from "../crypto/mdm-session.js";
29
+ import type { MosaddToolContext, ProviderRegistry } from "../types.js";
30
+
31
+ /** Stand-in for a host-supplied radio transport: captures the bytes it's asked
32
+ * to send, and replays them on list — i.e. "the message reached the link". */
33
+ class FakeRadioDmProvider implements DmProvider {
34
+ public readonly sent: DmSendArgs[] = [];
35
+ private bundle: Uint8Array | null = null;
36
+ async selfId(): Promise<string> {
37
+ return "radio:self-callsign";
38
+ }
39
+ async send(args: DmSendArgs): Promise<DmSendResult> {
40
+ this.sent.push(args);
41
+ return { id: `radio-${this.sent.length}`, deliveredAt: new Date(0).toISOString() };
42
+ }
43
+ async list(args: DmListArgs): Promise<DmListResult> {
44
+ return {
45
+ messages: this.sent
46
+ .filter((s) => s.threadId === args.threadId)
47
+ .map((s, i) => ({
48
+ id: `radio-${i + 1}`,
49
+ senderId: "radio:self-callsign",
50
+ payload: s.payload,
51
+ timestamp: new Date(0).toISOString(),
52
+ threadId: s.threadId,
53
+ })),
54
+ nextCursor: null,
55
+ };
56
+ }
57
+ async publishPrekeyBundle(bundle: Uint8Array): Promise<void> {
58
+ this.bundle = bundle;
59
+ }
60
+ async fetchPrekeyBundle(): Promise<Uint8Array | null> {
61
+ return this.bundle;
62
+ }
63
+ }
64
+
65
+ function makeCtx(providers: { dm: DmProvider; keys?: ProviderRegistry["keys"] }): MosaddToolContext {
66
+ return {
67
+ options: { mode: "local", hubUrl: "https://mcp.mosadd.com" },
68
+ providers: { dm: providers.dm, keys: providers.keys ?? new InMemoryMdmKeyStore() },
69
+ log: () => {},
70
+ };
71
+ }
72
+
73
+ const getTool = (name: string) => {
74
+ const t = mdmTools.find((x) => x.name === name);
75
+ if (!t) throw new Error(`tool ${name} not found`);
76
+ return t;
77
+ };
78
+
79
+ describe("golden path — host injects transport under mDM", () => {
80
+ it("step 1: comms_capabilities reports mDM_send usable over any carrier", async () => {
81
+ const capTool = makeCapabilitiesTool(allTools);
82
+ const manifest = (await capTool.handler({}, makeCtx({ dm: new FakeRadioDmProvider() }))) as {
83
+ by_requirement: Record<string, string[]>;
84
+ };
85
+ expect(manifest.by_requirement.any).toContain("mDM_send");
86
+ });
87
+
88
+ it("steps 2-4: the deprecated plaintext path delivers opaque bytes to the injected provider", async () => {
89
+ // This proves the TRANSPORT seam (2144): mDM_send_unencrypted packs a
90
+ // plaintext envelope and the bytes reach the injected provider verbatim.
91
+ // (mDM_send is now E2EE — its own round-trip is covered in mdm-e2ee.test.ts.)
92
+ const radio = new FakeRadioDmProvider();
93
+ const ctx = makeCtx({ dm: radio });
94
+
95
+ const send = getTool("mDM_send_unencrypted");
96
+ const result = (await send.handler(
97
+ { to: "bob-callsign", text: "rendezvous at grid 4471, 0600" },
98
+ ctx,
99
+ )) as { message_id: string; thread_id: string };
100
+
101
+ // The bytes actually reached the transport.
102
+ expect(radio.sent).toHaveLength(1);
103
+ expect(radio.sent[0]!.to).toBe("bob-callsign");
104
+ expect(radio.sent[0]!.payload).toBeInstanceOf(Uint8Array);
105
+ expect(radio.sent[0]!.payload.byteLength).toBeGreaterThan(0);
106
+ expect(result.message_id).toBe("radio-1");
107
+
108
+ // The payload is opaque to the provider but carries our text under the hood.
109
+ const decoded = JSON.parse(Buffer.from(radio.sent[0]!.payload).toString("utf8"));
110
+ expect(decoded.text).toBe("rendezvous at grid 4471, 0600");
111
+ });
112
+
113
+ it("step 5: mDM_list round-trips the message back through the same provider", async () => {
114
+ const radio = new FakeRadioDmProvider();
115
+ const ctx = makeCtx({ dm: radio });
116
+
117
+ await getTool("mDM_send_unencrypted").handler({ to: "bob-callsign", text: "ack" }, ctx);
118
+ const listed = (await getTool("mDM_list").handler({ contact_id: "bob-callsign" }, ctx)) as {
119
+ messages: Array<{ text: string }>;
120
+ };
121
+
122
+ expect(listed.messages).toHaveLength(1);
123
+ expect(listed.messages[0]!.text).toBe("ack");
124
+ });
125
+
126
+ it("default server wires a DmProvider without a host override (no throw)", () => {
127
+ // Network default path: constructing the server must not require a host to
128
+ // inject anything (it falls back to the Supabase adapter).
129
+ expect(() => createMosaddServer()).not.toThrow();
130
+ expect(() => createMosaddServer({ providers: { dm: new FakeRadioDmProvider() } })).not.toThrow();
131
+ });
132
+ });
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Integration test — spawns the actual mcp binary as a child process,
3
+ * sends JSON-RPC over stdin, validates JSON-RPC responses on stdout.
4
+ *
5
+ * Catches regressions like the ZodObject.shape vs ._def.shape() incident
6
+ * (commit c237e86) that unit tests against allTools wouldn't have caught —
7
+ * the bug only surfaces when the MCP SDK's `McpServer.tool(...)` rejects
8
+ * the schema we pass.
9
+ */
10
+
11
+ import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
12
+ import { join } from "node:path";
13
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
14
+
15
+ const MCP_BIN = join(__dirname, "..", "..", "dist", "bin", "mcp.js");
16
+
17
+ interface JsonRpcMessage {
18
+ jsonrpc: "2.0";
19
+ id?: number | string;
20
+ method?: string;
21
+ params?: unknown;
22
+ result?: unknown;
23
+ error?: { code: number; message: string };
24
+ }
25
+
26
+ class McpClient {
27
+ private proc!: ChildProcessWithoutNullStreams;
28
+ private buffer = "";
29
+ private resolvers = new Map<number | string, (msg: JsonRpcMessage) => void>();
30
+ private nextId = 1;
31
+
32
+ async start(): Promise<void> {
33
+ this.proc = spawn("node", [MCP_BIN], { stdio: ["pipe", "pipe", "pipe"] });
34
+
35
+ this.proc.stdout.on("data", (chunk: Buffer) => {
36
+ this.buffer += chunk.toString("utf8");
37
+ let nl = this.buffer.indexOf("\n");
38
+ while (nl !== -1) {
39
+ const line = this.buffer.slice(0, nl).trim();
40
+ this.buffer = this.buffer.slice(nl + 1);
41
+ if (line) {
42
+ try {
43
+ const msg = JSON.parse(line) as JsonRpcMessage;
44
+ if (msg.id !== undefined) {
45
+ const resolve = this.resolvers.get(msg.id);
46
+ if (resolve) {
47
+ this.resolvers.delete(msg.id);
48
+ resolve(msg);
49
+ }
50
+ }
51
+ } catch {
52
+ // server log lines on stderr only; stdout is always JSON-RPC
53
+ }
54
+ }
55
+ nl = this.buffer.indexOf("\n");
56
+ }
57
+ });
58
+
59
+ // Wait briefly for the server to be ready (writes a single info log to stderr).
60
+ await new Promise<void>((resolve) => {
61
+ const onData = (chunk: Buffer) => {
62
+ if (chunk.toString("utf8").includes("ready")) {
63
+ this.proc.stderr.off("data", onData);
64
+ resolve();
65
+ }
66
+ };
67
+ this.proc.stderr.on("data", onData);
68
+ setTimeout(resolve, 2000); // hard cap
69
+ });
70
+ }
71
+
72
+ async stop(): Promise<void> {
73
+ this.proc.kill();
74
+ await new Promise<void>((resolve) => this.proc.on("close", () => resolve()));
75
+ }
76
+
77
+ async send(method: string, params?: unknown, timeoutMs = 5000): Promise<JsonRpcMessage> {
78
+ const id = this.nextId++;
79
+ const req: JsonRpcMessage = { jsonrpc: "2.0", id, method, params };
80
+ return new Promise((resolve, reject) => {
81
+ const timer = setTimeout(() => {
82
+ this.resolvers.delete(id);
83
+ reject(new Error(`MCP request ${method} (id=${id}) timed out after ${timeoutMs}ms`));
84
+ }, timeoutMs);
85
+ this.resolvers.set(id, (msg) => {
86
+ clearTimeout(timer);
87
+ resolve(msg);
88
+ });
89
+ this.proc.stdin.write(JSON.stringify(req) + "\n");
90
+ });
91
+ }
92
+ }
93
+
94
+ describe("@mosadd/mcp — integration (real stdio)", () => {
95
+ let client: McpClient;
96
+
97
+ beforeEach(async () => {
98
+ client = new McpClient();
99
+ await client.start();
100
+ });
101
+
102
+ afterEach(async () => {
103
+ await client.stop();
104
+ });
105
+
106
+ it("responds to initialize handshake", async () => {
107
+ const resp = await client.send("initialize", {
108
+ protocolVersion: "2024-11-05",
109
+ capabilities: {},
110
+ clientInfo: { name: "vitest", version: "1.0" },
111
+ });
112
+
113
+ expect(resp.error).toBeUndefined();
114
+ const result = resp.result as {
115
+ protocolVersion?: string;
116
+ capabilities?: { tools?: unknown };
117
+ serverInfo?: { name?: string };
118
+ };
119
+ expect(result.protocolVersion).toBe("2024-11-05");
120
+ expect(result.capabilities?.tools).toBeDefined();
121
+ expect(result.serverInfo?.name).toBe("mosadd");
122
+ });
123
+
124
+ it("lists all 19 tools on tools/list", async () => {
125
+ await client.send("initialize", {
126
+ protocolVersion: "2024-11-05",
127
+ capabilities: {},
128
+ clientInfo: { name: "vitest", version: "1.0" },
129
+ });
130
+
131
+ const resp = await client.send("tools/list");
132
+
133
+ expect(resp.error).toBeUndefined();
134
+ const result = resp.result as { tools?: Array<{ name: string }> };
135
+ const names = result.tools?.map((t) => t.name) ?? [];
136
+
137
+ // All 4 channels surface their tools
138
+ expect(names).toContain("mDM_send");
139
+ expect(names).toContain("mIRC_create");
140
+ expect(names).toContain("mROOM_create_guest_link");
141
+ expect(names).toContain("mAIL_send");
142
+
143
+ // Total tool count today
144
+ expect(names.length).toBeGreaterThanOrEqual(19);
145
+
146
+ // Every tool has a valid JSON Schema
147
+ for (const tool of result.tools ?? []) {
148
+ const t = tool as { name: string; description: string; inputSchema: { type?: string } };
149
+ expect(t.description).toBeTruthy();
150
+ expect(t.inputSchema?.type).toBe("object");
151
+ }
152
+ });
153
+
154
+ it("returns an error envelope (not crash) when a tool handler throws", async () => {
155
+ await client.send("initialize", {
156
+ protocolVersion: "2024-11-05",
157
+ capabilities: {},
158
+ clientInfo: { name: "vitest", version: "1.0" },
159
+ });
160
+
161
+ // mDM_send needs M0SSAD_SUPABASE_URL etc. — in test env we don't have them,
162
+ // so the handler will throw MissingSupabaseEnvError. The MCP layer must wrap
163
+ // that in a normal `isError: true` content block, not a JSON-RPC error
164
+ // (that would crash the agent loop).
165
+ const resp = await client.send("tools/call", {
166
+ name: "mDM_send",
167
+ arguments: { to: "11111111-1111-1111-1111-111111111111", text: "hi" },
168
+ });
169
+
170
+ expect(resp.error).toBeUndefined(); // JSON-RPC level OK
171
+ const result = resp.result as { isError?: boolean; content?: Array<{ text?: string }> };
172
+ expect(result.isError).toBe(true);
173
+ expect(result.content?.[0]?.text).toContain("Missing");
174
+ });
175
+ });