@mosadd/mcp 3.0.0-alpha.1 → 3.0.0-alpha.11

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 (41) hide show
  1. package/README.md +127 -116
  2. package/dist/bin/login.js +4 -4
  3. package/dist/bin/mcp.js +29 -1
  4. package/dist/chunk-NQ624SIP.js +2121 -0
  5. package/dist/index.d.ts +46 -4
  6. package/dist/index.js +5 -3
  7. package/package.json +8 -5
  8. package/src/__tests__/golden-path.test.ts +137 -132
  9. package/src/__tests__/integration.test.ts +178 -175
  10. package/src/__tests__/mdm-e2ee.test.ts +178 -149
  11. package/src/__tests__/mtalk.test.ts +122 -0
  12. package/src/__tests__/server.test.ts +67 -67
  13. package/src/bin/login.ts +138 -127
  14. package/src/bin/mcp.ts +97 -55
  15. package/src/config.ts +66 -66
  16. package/src/crypto/mdm-session.ts +403 -378
  17. package/src/index.ts +19 -17
  18. package/src/observability/sentry.ts +79 -79
  19. package/src/providers/memory-voice.ts +79 -0
  20. package/src/providers/supabase-dm.ts +117 -117
  21. package/src/providers/supabase-voice.ts +91 -0
  22. package/src/providers/supabase.ts +120 -89
  23. package/src/server.ts +105 -103
  24. package/src/tools/capabilities.ts +68 -68
  25. package/src/tools/index.ts +53 -37
  26. package/src/tools/knowledge.ts +191 -0
  27. package/src/tools/mail.ts +371 -89
  28. package/src/tools/mcall.ts +216 -0
  29. package/src/tools/mdm-voice.ts +206 -0
  30. package/src/tools/mdm.ts +448 -379
  31. package/src/tools/mirc-edge.ts +190 -0
  32. package/src/tools/mirc-members.ts +177 -177
  33. package/src/tools/mirc-messages.ts +156 -0
  34. package/src/tools/mirc.ts +170 -170
  35. package/src/tools/mroom-messages.ts +142 -142
  36. package/src/tools/mroom.ts +221 -189
  37. package/src/tools/mtalk.ts +121 -0
  38. package/src/tools/murl.ts +195 -0
  39. package/src/types.ts +85 -79
  40. package/src/voice/floor.ts +132 -0
  41. package/dist/chunk-6IA4QVAJ.js +0 -1191
@@ -1,89 +1,120 @@
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 M0SSAD_SUPABASE_URL, M0SSAD_SUPABASE_ANON_KEY and M0SSAD_USER_JWT.`,
26
- );
27
- this.name = "MissingSupabaseEnvError";
28
- }
29
- }
30
-
31
- export function readSupabaseEnv(): SupabaseEnv {
32
- // Env vars take precedence; fall back to the session saved by `mosadd login`.
33
- const session = loadSession();
34
- const url = process.env.M0SSAD_SUPABASE_URL ?? session?.url;
35
- const anonKey = process.env.M0SSAD_SUPABASE_ANON_KEY ?? session?.anonKey;
36
- const userJwt = process.env.M0SSAD_USER_JWT ?? session?.accessToken;
37
-
38
- const missing: string[] = [];
39
- if (!url) missing.push("M0SSAD_SUPABASE_URL");
40
- if (!anonKey) missing.push("M0SSAD_SUPABASE_ANON_KEY");
41
- if (missing.length) throw new MissingSupabaseEnvError(missing);
42
-
43
- // Surface an expired `mosadd login` token early with an actionable message.
44
- if (!process.env.M0SSAD_USER_JWT && session && isSessionExpired(session)) {
45
- throw new Error("Your mosadd session has expired. Run `mosadd login` again to refresh it.");
46
- }
47
- return { url: url!, anonKey: anonKey!, userJwt };
48
- }
49
-
50
- export function getSupabase(env: SupabaseEnv = readSupabaseEnv()): SupabaseClient {
51
- return createClient(env.url, env.anonKey, {
52
- auth: {
53
- persistSession: false,
54
- autoRefreshToken: false,
55
- detectSessionInUrl: false,
56
- },
57
- global: env.userJwt
58
- ? {
59
- headers: { Authorization: `Bearer ${env.userJwt}` },
60
- }
61
- : undefined,
62
- });
63
- }
64
-
65
- /**
66
- * Invoke a m0ssad-3 Edge Function. Wraps `supabase.functions.invoke` with
67
- * normalized error handling so MCP tool handlers can throw clean errors that
68
- * agents can reason about.
69
- */
70
- export async function invokeFunction<T = unknown>(
71
- fn: string,
72
- body: Record<string, unknown>,
73
- ): Promise<T> {
74
- const client = getSupabase();
75
- const { data, error } = await client.functions.invoke<T>(fn, { body });
76
- if (error) {
77
- const msg =
78
- error instanceof Error
79
- ? error.message
80
- : typeof (error as { message?: unknown })?.message === "string"
81
- ? (error as { message: string }).message
82
- : `Edge function ${fn} failed`;
83
- throw new Error(msg);
84
- }
85
- if (data == null) {
86
- throw new Error(`Edge function ${fn} returned no data`);
87
- }
88
- return data;
89
- }
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
+ const msg =
109
+ error instanceof Error
110
+ ? error.message
111
+ : typeof (error as { message?: unknown })?.message === "string"
112
+ ? (error as { message: string }).message
113
+ : `Edge function ${fn} failed`;
114
+ throw new Error(msg);
115
+ }
116
+ if (data == null) {
117
+ throw new Error(`Edge function ${fn} returned no data`);
118
+ }
119
+ return data;
120
+ }
package/src/server.ts CHANGED
@@ -1,103 +1,105 @@
1
- /**
2
- * Build a McpServer instance with all mosadd tools registered.
3
- */
4
-
5
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
6
- import { allTools } from "./tools/index.js";
7
- import { 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 } from "./crypto/mdm-session.js";
10
+ import type { MosaddServerOptions, MosaddToolContext, ProviderRegistry } from "./types.js";
11
+
12
+ /**
13
+ * Resolve the channel ProviderRegistry: default network adapters merged with
14
+ * anything the host injects. A carrier-aware host (cymru-os) passes its own
15
+ * radio DmProvider via `injected.dm`. This is the single place the default
16
+ * adapters are named — both `createMosaddServer` and the `@mosadd/ai` adapters
17
+ * build their context through it so they stay in lockstep.
18
+ */
19
+ export function defaultProviders(injected?: Partial<ProviderRegistry>): ProviderRegistry {
20
+ return {
21
+ dm: injected?.dm ?? new SupabaseDmProvider(),
22
+ keys: injected?.keys ?? new InMemoryMdmKeyStore(),
23
+ voice: injected?.voice ?? new SupabaseVoiceProvider(),
24
+ };
25
+ }
26
+
27
+ export function createMosaddServer(options: MosaddServerOptions = {}) {
28
+ const mode = options.mode ?? (options.apiKey ? "cloud" : "local");
29
+ const hubUrl = options.hubUrl ?? "https://mcp.mosadd.com";
30
+ const logLevel = options.logLevel ?? "info";
31
+
32
+ // DI seam: default network adapters, overridden by anything the host injects.
33
+ const providers = defaultProviders(options.providers);
34
+
35
+ const ctx: MosaddToolContext = {
36
+ options: { ...options, mode, hubUrl },
37
+ providers,
38
+ log: (level, msg, extra) => {
39
+ if (shouldLog(level, logLevel)) {
40
+ // MCP servers must write logs to stderr (stdout is the protocol channel).
41
+ process.stderr.write(
42
+ JSON.stringify({ level, msg, extra, ts: new Date().toISOString() }) + "\n",
43
+ );
44
+ }
45
+ },
46
+ };
47
+
48
+ const server = new McpServer(
49
+ {
50
+ name: "mosadd",
51
+ version: "3.0.0-alpha.0",
52
+ },
53
+ {
54
+ capabilities: {
55
+ tools: {},
56
+ },
57
+ },
58
+ );
59
+
60
+ for (const tool of allTools) {
61
+ // MCP SDK v1.x expects the field-level Zod shape (`{ to: z.string(), text: z.string() }`),
62
+ // not the wrapping `z.object({...})`. Tool inputs are declared as ZodObject schemas
63
+ // so we can `.parse()` them in the handler; surface the inner `.shape` to the SDK here.
64
+ const shape =
65
+ tool.inputSchema && typeof tool.inputSchema === "object" && "shape" in tool.inputSchema
66
+ ? (tool.inputSchema as { shape: Record<string, unknown> }).shape
67
+ : (tool.inputSchema as unknown as Record<string, unknown>);
68
+
69
+ server.tool(
70
+ tool.name,
71
+ tool.description,
72
+ shape as Parameters<typeof server.tool>[2],
73
+ async (input: unknown) => {
74
+ const parsed = tool.inputSchema.parse(input);
75
+ try {
76
+ const result = await tool.handler(parsed as never, ctx);
77
+ return {
78
+ content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }],
79
+ };
80
+ } catch (err) {
81
+ ctx.log("error", `tool ${tool.name} failed`, { error: String(err) });
82
+ return {
83
+ isError: true,
84
+ content: [
85
+ {
86
+ type: "text" as const,
87
+ text: JSON.stringify({
88
+ error: err instanceof Error ? err.message : String(err),
89
+ tool: tool.name,
90
+ }),
91
+ },
92
+ ],
93
+ };
94
+ }
95
+ },
96
+ );
97
+ }
98
+
99
+ return server;
100
+ }
101
+
102
+ function shouldLog(level: string, threshold: string): boolean {
103
+ const order = { debug: 0, info: 1, warn: 2, error: 3 } as const;
104
+ return (order[level as keyof typeof order] ?? 1) >= (order[threshold as keyof typeof order] ?? 1);
105
+ }
@@ -1,68 +1,68 @@
1
- /**
2
- * comms_capabilities — capability discovery for consuming hosts.
3
- *
4
- * THE contract surface between mosadd-os and carrier-aware hosts (e.g.
5
- * cymru-os, which filters tools by available transports — see cymru-os RFC
6
- * 0002 D-Bus "Capability-flag bridge"). A host spawns `@mosadd/mcp` over stdio
7
- * and calls `comms_capabilities` once to learn which tools are usable on which
8
- * carrier, then gates the tool list accordingly (e.g. off-grid radio →
9
- * only `requires: "any" | "radio"` tools are offered).
10
- *
11
- * `requires: "any"` here too — discovery must work on any transport, including
12
- * off-grid radio, otherwise a host couldn't learn what it's allowed to call.
13
- */
14
-
15
- import { z } from "zod";
16
- import type { CapabilityRequirement, MosaddTool } from "../types.js";
17
-
18
- export interface CapabilityEntry {
19
- name: string;
20
- requires: CapabilityRequirement;
21
- }
22
-
23
- export interface CapabilityManifest {
24
- /** Stable contract version. Bump on any enum/shape change (requires:cymru-input). */
25
- contract_version: string;
26
- /** The finalized capability enum, echoed so hosts can validate against it. */
27
- requirements: CapabilityRequirement[];
28
- /** Flat list of every tool and its transport requirement. */
29
- tools: CapabilityEntry[];
30
- /** Pre-grouped by requirement for cheap host-side filtering. */
31
- by_requirement: Record<CapabilityRequirement, string[]>;
32
- }
33
-
34
- const CONTRACT_VERSION = "1.0.0";
35
- const ALL_REQUIREMENTS: CapabilityRequirement[] = ["any", "radio", "network"];
36
-
37
- /** Build the capability manifest from a tool list. Pure, host-agnostic. */
38
- export function buildCapabilityManifest(tools: MosaddTool[]): CapabilityManifest {
39
- const entries: CapabilityEntry[] = tools.map((t) => ({ name: t.name, requires: t.requires }));
40
- const by_requirement: Record<CapabilityRequirement, string[]> = {
41
- any: [],
42
- radio: [],
43
- network: [],
44
- };
45
- for (const e of entries) by_requirement[e.requires].push(e.name);
46
- return {
47
- contract_version: CONTRACT_VERSION,
48
- requirements: ALL_REQUIREMENTS,
49
- tools: entries,
50
- by_requirement,
51
- };
52
- }
53
-
54
- /**
55
- * Factory: build the comms_capabilities tool over a given tool set. The tool
56
- * itself is appended to that set, so it self-reports too (requires: "any").
57
- */
58
- export function makeCapabilitiesTool(channelTools: MosaddTool[]): MosaddTool {
59
- const tool: MosaddTool = {
60
- name: "comms_capabilities",
61
- requires: "any",
62
- description:
63
- "Discover which mosadd tools are available and what transport each requires (any | radio | network). Carrier-aware hosts (e.g. off-grid radio devices) call this once to gate the tool list to what the current carrier supports. Returns a manifest with per-tool requirements grouped by transport.",
64
- inputSchema: z.object({}),
65
- handler: async () => buildCapabilityManifest([...channelTools, tool]),
66
- };
67
- return tool;
68
- }
1
+ /**
2
+ * comms_capabilities — capability discovery for consuming hosts.
3
+ *
4
+ * THE contract surface between mosadd-os and carrier-aware hosts (e.g.
5
+ * cymru-os, which filters tools by available transports — see cymru-os RFC
6
+ * 0002 D-Bus "Capability-flag bridge"). A host spawns `@mosadd/mcp` over stdio
7
+ * and calls `comms_capabilities` once to learn which tools are usable on which
8
+ * carrier, then gates the tool list accordingly (e.g. off-grid radio →
9
+ * only `requires: "any" | "radio"` tools are offered).
10
+ *
11
+ * `requires: "any"` here too — discovery must work on any transport, including
12
+ * off-grid radio, otherwise a host couldn't learn what it's allowed to call.
13
+ */
14
+
15
+ import { z } from "zod";
16
+ import type { CapabilityRequirement, MosaddTool } from "../types.js";
17
+
18
+ export interface CapabilityEntry {
19
+ name: string;
20
+ requires: CapabilityRequirement;
21
+ }
22
+
23
+ export interface CapabilityManifest {
24
+ /** Stable contract version. Bump on any enum/shape change (requires:cymru-input). */
25
+ contract_version: string;
26
+ /** The finalized capability enum, echoed so hosts can validate against it. */
27
+ requirements: CapabilityRequirement[];
28
+ /** Flat list of every tool and its transport requirement. */
29
+ tools: CapabilityEntry[];
30
+ /** Pre-grouped by requirement for cheap host-side filtering. */
31
+ by_requirement: Record<CapabilityRequirement, string[]>;
32
+ }
33
+
34
+ const CONTRACT_VERSION = "1.0.0";
35
+ const ALL_REQUIREMENTS: CapabilityRequirement[] = ["any", "radio", "network"];
36
+
37
+ /** Build the capability manifest from a tool list. Pure, host-agnostic. */
38
+ export function buildCapabilityManifest(tools: MosaddTool[]): CapabilityManifest {
39
+ const entries: CapabilityEntry[] = tools.map((t) => ({ name: t.name, requires: t.requires }));
40
+ const by_requirement: Record<CapabilityRequirement, string[]> = {
41
+ any: [],
42
+ radio: [],
43
+ network: [],
44
+ };
45
+ for (const e of entries) by_requirement[e.requires].push(e.name);
46
+ return {
47
+ contract_version: CONTRACT_VERSION,
48
+ requirements: ALL_REQUIREMENTS,
49
+ tools: entries,
50
+ by_requirement,
51
+ };
52
+ }
53
+
54
+ /**
55
+ * Factory: build the comms_capabilities tool over a given tool set. The tool
56
+ * itself is appended to that set, so it self-reports too (requires: "any").
57
+ */
58
+ export function makeCapabilitiesTool(channelTools: MosaddTool[]): MosaddTool {
59
+ const tool: MosaddTool = {
60
+ name: "comms_capabilities",
61
+ requires: "any",
62
+ description:
63
+ "Discover which mosadd tools are available and what transport each requires (any | radio | network). Carrier-aware hosts (e.g. off-grid radio devices) call this once to gate the tool list to what the current carrier supports. Returns a manifest with per-tool requirements grouped by transport.",
64
+ inputSchema: z.object({}),
65
+ handler: async () => buildCapabilityManifest([...channelTools, tool]),
66
+ };
67
+ return tool;
68
+ }