@mosadd/mcp 3.0.0-alpha.7 → 3.0.1

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 (68) hide show
  1. package/CHANGELOG.md +415 -0
  2. package/LICENSE +21 -201
  3. package/README.md +79 -40
  4. package/dist/bin/mcp.js +132 -8
  5. package/dist/chunk-J2S44U5R.js +4258 -0
  6. package/dist/index.d.ts +112 -8
  7. package/dist/index.js +3 -1
  8. package/package.json +19 -16
  9. package/src/__tests__/blob-upload.test.ts +93 -0
  10. package/src/__tests__/channel-e2ee.test.ts +62 -0
  11. package/src/__tests__/cli.test.ts +47 -0
  12. package/src/__tests__/fleet-plaintext.test.ts +243 -0
  13. package/src/__tests__/golden-path.test.ts +4 -2
  14. package/src/__tests__/integration.test.ts +50 -11
  15. package/src/__tests__/knowledge-ingest.test.ts +114 -0
  16. package/src/__tests__/label-room-owner.test.ts +22 -0
  17. package/src/__tests__/mdm-e2ee.test.ts +36 -2
  18. package/src/__tests__/mdm-mcp-readable.test.ts +390 -0
  19. package/src/__tests__/mirc-invite.test.ts +112 -0
  20. package/src/__tests__/mirc-voice.test.ts +82 -0
  21. package/src/__tests__/mrag-search-answer.test.ts +42 -0
  22. package/src/__tests__/mrag-search-diagnostics.test.ts +78 -0
  23. package/src/__tests__/no-dead-host.test.ts +37 -0
  24. package/src/__tests__/presence.test.ts +199 -0
  25. package/src/__tests__/server.test.ts +11 -7
  26. package/src/__tests__/serverJsonVersion.test.ts +45 -0
  27. package/src/__tests__/tool-count-consistency.test.ts +259 -0
  28. package/src/__tests__/voice-fields.test.ts +24 -0
  29. package/src/bin/mcp.ts +71 -6
  30. package/src/cli.ts +100 -0
  31. package/src/crypto/channel-e2ee.ts +288 -0
  32. package/src/crypto/mdm-session.ts +479 -40
  33. package/src/index.ts +2 -2
  34. package/src/providers/blob-upload.ts +162 -0
  35. package/src/providers/supabase-dm.ts +102 -7
  36. package/src/providers/supabase-voice.ts +13 -1
  37. package/src/providers/supabase.ts +121 -10
  38. package/src/server.ts +102 -12
  39. package/src/tools/__tests__/ragDeleteFoldsSourceId.test.ts +67 -0
  40. package/src/tools/actions.ts +166 -0
  41. package/src/tools/attachments.ts +276 -0
  42. package/src/tools/capabilities.ts +2 -0
  43. package/src/tools/channel-payload.ts +69 -0
  44. package/src/tools/embed.ts +110 -0
  45. package/src/tools/index.ts +136 -6
  46. package/src/tools/knowledge-graph.ts +186 -0
  47. package/src/tools/knowledge.ts +205 -12
  48. package/src/tools/mail-agentbox.ts +155 -0
  49. package/src/tools/mail-aliases.ts +25 -0
  50. package/src/tools/mail-provenance.ts +137 -0
  51. package/src/tools/mail.ts +214 -60
  52. package/src/tools/mdm-as-agent.ts +137 -0
  53. package/src/tools/mdm-voice.ts +17 -3
  54. package/src/tools/mdm.ts +306 -58
  55. package/src/tools/mirc-edge.ts +12 -6
  56. package/src/tools/mirc-members.ts +130 -20
  57. package/src/tools/mirc-messages.ts +109 -40
  58. package/src/tools/mirc.ts +149 -11
  59. package/src/tools/mroom-messages.ts +5 -13
  60. package/src/tools/mtalk.ts +11 -1
  61. package/src/tools/murl.ts +314 -0
  62. package/src/tools/presence.ts +442 -0
  63. package/src/tools/ptt-ingest.ts +99 -0
  64. package/src/tools/threat.ts +123 -0
  65. package/src/tools/voice-format.ts +66 -0
  66. package/src/types.ts +36 -0
  67. package/src/version.ts +8 -0
  68. package/dist/chunk-EFTB743G.js +0 -1924
package/src/tools/mirc.ts CHANGED
@@ -2,7 +2,9 @@
2
2
  * mIRC — Persistent Channels.
3
3
  *
4
4
  * IRC-style persistent channels (Discord/Slack semantics). Channels live forever
5
- * until deleted, members come and go. Distinct from mROOM (ephemeral, no-account).
5
+ * until deleted, members come and go. Ephemeral / no-account / single-action
6
+ * channels are PRESETS of mIRC (planned: TTL `expires_at` +
7
+ * guest-link + voice), not a separate module. The killed mROOM is absorbed here.
6
8
  *
7
9
  * Phase 1 alpha: wired to the mosadd backend's `channel-manage` Edge Function (strangler-fig).
8
10
  * The single edge fn dispatches on `action` — we expose each action as its own
@@ -12,6 +14,7 @@
12
14
  import { z } from "zod";
13
15
  import type { MosaddTool, MosaddToolContext } from "../types.js";
14
16
  import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
17
+ import { inviteToChannel, type MircInviteResult } from "./mirc-members.js";
15
18
 
16
19
  // ---- Schemas ----
17
20
 
@@ -28,10 +31,12 @@ const AccessMode = z
28
31
  const Capabilities = z
29
32
  .object({
30
33
  txt: z.boolean().default(true),
34
+ voice: z.boolean().default(false),
35
+ files: z.boolean().default(false),
31
36
  ptt: z.boolean().default(false),
32
37
  live: z.boolean().default(false),
33
38
  })
34
- .describe("Which modes are enabled in this channel: txt (text), ptt (push-to-talk voice), live (live stream).")
39
+ .describe("Which modes are enabled: txt (text), voice (group voice), files (file attach), ptt (push-to-talk), live (live stream). Voice/PTT/live are server-relayed via LiveKit — NOT end-to-end encrypted.")
35
40
  .optional();
36
41
 
37
42
  const mIRC_create_input = z.object({
@@ -40,12 +45,31 @@ const mIRC_create_input = z.object({
40
45
  access_mode: AccessMode.default("open"),
41
46
  password: z.string().min(6).max(120).optional().describe("Password (only for access_mode=password)."),
42
47
  capabilities: Capabilities,
48
+ discoverable: z
49
+ .boolean()
50
+ .optional()
51
+ .describe("List this channel in the PUBLIC directory (mIRC_discover). Honoured ONLY for access_mode=open; ignored for password/private."),
52
+ wrapped_group_key: z
53
+ .string()
54
+ .optional()
55
+ .describe(
56
+ "Required for access_mode=password|private (these channels are provisioned for group-key text encryption on supported clients): the channel's group key wrapped to the creator's identity key. Open channels ignore it. If omitted on a non-open channel the backend rejects the call with a 'wrapped_group_key required' error.",
57
+ ),
58
+ invite_agents: z
59
+ .array(z.string().min(1))
60
+ .max(20)
61
+ .optional()
62
+ .describe(
63
+ "Identity ids (UUID) of YOUR agents/robots to add right after the channel is created (agents: mDM_list_my_agents → agents[].identity_id; robots are not in that list — use the identity id from the app's Robots page). Each is fanned out to mIRC_invite: your own agents auto-join (auto_joined:true); anything else gets an invite code. Per-agent failures are reported in invites[] — the channel itself is still created. Max 20 per call (the invite mint is rate-limited to 20/min). On password/private channels the fan-out cannot carry a per-agent wrapped_group_key — use mIRC_invite per agent there.",
64
+ ),
43
65
  });
44
66
 
45
67
  const mIRC_list_input = z.object({
46
68
  limit: z.number().int().min(1).max(500).default(100).optional(),
47
69
  offset: z.number().int().min(0).default(0).optional(),
48
- access_mode: AccessMode.optional().describe("Filter to a single access mode."),
70
+ // NOTE: an access_mode filter was removed — channel-manage's list branch doesn't
71
+ // filter by it (it was a silent no-op). Filter client-side on the returned
72
+ // access_mode field. Server-side filtering is tracked in the consistency ticket.
49
73
  });
50
74
 
51
75
  const mIRC_get_input = z.object({
@@ -56,8 +80,23 @@ const mIRC_update_input = z.object({
56
80
  channel_id: ChannelId,
57
81
  name: z.string().min(1).max(80).optional(),
58
82
  topic: z.string().max(500).optional(),
59
- access_mode: AccessMode.optional(),
83
+ // NOTE: access_mode was removed — channel-manage's update branch ignores it, and
84
+ // switching an existing channel to/from an E2EE (password/private) mode needs
85
+ // group-key handling that isn't wired yet. Recreate the channel to change mode.
60
86
  capabilities: Capabilities,
87
+ discoverable: z.boolean().optional().describe("Toggle public-directory listing (open channels only)."),
88
+ });
89
+
90
+ const mIRC_discover_input = z.object({
91
+ q: z.string().max(100).optional().describe("Optional channel-name filter."),
92
+ limit: z.number().int().min(1).max(500).default(50).optional(),
93
+ offset: z.number().int().min(0).default(0).optional(),
94
+ });
95
+
96
+ const mIRC_report_input = z.object({
97
+ channel_id: ChannelId,
98
+ reason: z.enum(["spam", "abuse", "harassment", "illegal", "other"]).describe("Report reason."),
99
+ detail: z.string().max(1000).optional().describe("Optional free-text context."),
61
100
  });
62
101
 
63
102
  const mIRC_delete_input = z.object({
@@ -66,16 +105,56 @@ const mIRC_delete_input = z.object({
66
105
 
67
106
  // ---- Handlers ----
68
107
 
108
+ /** One row per agent in mIRC_create's `invite_agents` — a refusal is DATA, never a thrown create. */
109
+ export type InviteFanout =
110
+ | { identity_id: string; ok: true; auto_joined: boolean; result: MircInviteResult }
111
+ | { identity_id: string; ok: false; error: string };
112
+
69
113
  async function mIRC_create(
70
114
  input: z.infer<typeof mIRC_create_input>,
71
115
  ctx: MosaddToolContext,
72
- ): Promise<{ channel: unknown }> {
116
+ ): Promise<{ channel: unknown; invites?: InviteFanout[] }> {
73
117
  readSupabaseEnv();
74
118
  ctx.log("debug", "mIRC_create invoking channel-manage", { name: input.name });
75
- return await invokeFunction<{ channel: unknown }>("channel-manage", {
119
+ // channel-manage reads `description`, not `topic` — map it so the channel
120
+ // topic isn't silently dropped on create (the update handler does the same).
121
+ // `invite_agents` is TOOLKIT-side composition (the fan-out below) — it must not
122
+ // reach channel-manage, which knows nothing about it.
123
+ const { topic, invite_agents, ...rest } = input as typeof input & { topic?: string };
124
+ const payload = topic !== undefined ? { ...rest, description: topic } : { ...rest };
125
+ const created = await invokeFunction<{ channel: unknown }>("channel-manage", {
76
126
  action: "create",
77
- ...input,
127
+ ...payload,
78
128
  });
129
+ if (!invite_agents?.length) return created;
130
+
131
+ const channelId = (created.channel as { id?: unknown } | null)?.id;
132
+ if (typeof channelId !== "string" || !channelId) {
133
+ // The channel exists; only the fan-out is impossible. Report, don't throw — a throw here
134
+ // would tell the model the CREATE failed while the row is already there.
135
+ return {
136
+ ...created,
137
+ invites: invite_agents.map((identity_id) => ({
138
+ identity_id,
139
+ ok: false as const,
140
+ error: "channel created but its id was missing from the reply — call mIRC_invite with the id from mIRC_list",
141
+ })),
142
+ };
143
+ }
144
+ // Sequential on purpose: channel-members-manage rate-limits the invite mint per caller
145
+ // (20/min, fail-closed); a parallel burst would trip it for the tail of the list.
146
+ const invites: InviteFanout[] = [];
147
+ for (const identity_id of invite_agents) {
148
+ try {
149
+ const result = await inviteToChannel({ channel_id: channelId, identity_id }, ctx);
150
+ invites.push({ identity_id, ok: true, auto_joined: "auto_joined" in result && result.auto_joined === true, result });
151
+ } catch (e) {
152
+ // One agent's refusal (banned, already a member, not yours, encrypted channel without a
153
+ // wrapped key) must not undo the others or mask the channel that was just created.
154
+ invites.push({ identity_id, ok: false, error: e instanceof Error ? e.message : String(e) });
155
+ }
156
+ }
157
+ return { ...created, invites };
79
158
  }
80
159
 
81
160
  async function mIRC_list(
@@ -108,9 +187,13 @@ async function mIRC_update(
108
187
  ): Promise<{ channel: unknown }> {
109
188
  readSupabaseEnv();
110
189
  ctx.log("debug", "mIRC_update invoking channel-manage", { channel_id: input.channel_id });
190
+ // channel-manage reads `description`, not `topic` — map it so topic edits aren't
191
+ // silently dropped.
192
+ const { topic, ...rest } = input as typeof input & { topic?: string };
193
+ const payload = topic !== undefined ? { ...rest, description: topic } : { ...rest };
111
194
  return await invokeFunction<{ channel: unknown }>("channel-manage", {
112
195
  action: "update",
113
- ...input,
196
+ ...payload,
114
197
  });
115
198
  }
116
199
 
@@ -127,27 +210,58 @@ async function mIRC_delete(
127
210
  return { deleted: true };
128
211
  }
129
212
 
213
+ async function mIRC_discover(
214
+ input: z.infer<typeof mIRC_discover_input>,
215
+ ctx: MosaddToolContext,
216
+ ): Promise<{ channels: unknown[] }> {
217
+ readSupabaseEnv();
218
+ ctx.log("debug", "mIRC_discover invoking channel-manage");
219
+ return await invokeFunction<{ channels: unknown[] }>("channel-manage", {
220
+ action: "discover",
221
+ ...input,
222
+ });
223
+ }
224
+
225
+ async function mIRC_report(
226
+ input: z.infer<typeof mIRC_report_input>,
227
+ ctx: MosaddToolContext,
228
+ ): Promise<{ ok: boolean }> {
229
+ readSupabaseEnv();
230
+ ctx.log("debug", "mIRC_report invoking report-content", { channel_id: input.channel_id });
231
+ return await invokeFunction<{ ok: boolean }>("report-content", {
232
+ thread_id: `channel:${input.channel_id}`,
233
+ reason: input.reason,
234
+ detail: input.detail,
235
+ });
236
+ }
237
+
130
238
  // ---- Registration ----
131
239
 
132
240
  export const mircTools: MosaddTool[] = [
133
241
  {
134
242
  name: "mIRC_create",
243
+ title: "Create channel",
244
+ annotations: { readOnlyHint: false },
135
245
  requires: "network",
136
246
  description:
137
- "Create a new persistent channel (Discord/Slack-style). Set access_mode to open (anyone joins), password (shared-password gated), or private (invite-only). capabilities controls modes (txt/ptt/live).",
247
+ "Create a new persistent channel (Discord/Slack-style). Set access_mode to open (anyone joins), password (shared-password gated), or private (invite-only). capabilities controls modes (txt/voice/files/ptt/live; voice/ptt/live are server-relayed via LiveKit, NOT E2EE). Set discoverable:true (open channels only) to list it in the public directory. NOTE: password/private channels are provisioned for group-key TEXT encryption — supply wrapped_group_key (the group key wrapped to your identity key); open channels do not need it. The mosadd.com app encrypts/decrypts channel text with that key on supported clients; the toolkit's own mIRC_post_message posts server-readable text today (group-key parity is the next milestone). Channel voice is never E2EE. A channel WITHOUT its agent is a silent room — pass invite_agents (identity ids of your own agents, from mDM_list_my_agents) to add them in the same call, or call mIRC_invite afterwards.",
138
248
  inputSchema: mIRC_create_input,
139
249
  handler: mIRC_create as MosaddTool["handler"],
140
250
  },
141
251
  {
142
252
  name: "mIRC_list",
253
+ title: "List your channels",
254
+ annotations: { readOnlyHint: true },
143
255
  requires: "network",
144
256
  description:
145
- "List channels available to the current user. Optionally filter by access_mode.",
257
+ "List channels available to the current user.",
146
258
  inputSchema: mIRC_list_input,
147
259
  handler: mIRC_list as MosaddTool["handler"],
148
260
  },
149
261
  {
150
262
  name: "mIRC_get",
263
+ title: "Get channel details",
264
+ annotations: { readOnlyHint: true },
151
265
  requires: "network",
152
266
  description: "Get full details of a single channel by id.",
153
267
  inputSchema: mIRC_get_input,
@@ -155,16 +269,40 @@ export const mircTools: MosaddTool[] = [
155
269
  },
156
270
  {
157
271
  name: "mIRC_update",
272
+ title: "Update channel settings",
273
+ annotations: { readOnlyHint: false },
158
274
  requires: "network",
159
- description: "Update channel metadata (name, topic, access_mode, capabilities). Owner only.",
275
+ description: "Update channel metadata (name, topic, capabilities). Owner only. Access mode is fixed at creation — recreate the channel to change it.",
160
276
  inputSchema: mIRC_update_input,
161
277
  handler: mIRC_update as MosaddTool["handler"],
162
278
  },
163
279
  {
164
280
  name: "mIRC_delete",
281
+ title: "Delete channel",
282
+ annotations: { destructiveHint: true },
165
283
  requires: "network",
166
284
  description: "Delete a channel and cascade-remove its members. Owner only.",
167
285
  inputSchema: mIRC_delete_input,
168
286
  handler: mIRC_delete as MosaddTool["handler"],
169
287
  },
288
+ {
289
+ name: "mIRC_discover",
290
+ title: "Discover public channels",
291
+ annotations: { readOnlyHint: true },
292
+ requires: "network",
293
+ description:
294
+ "Browse the PUBLIC channel DIRECTORY — open channels whose owners opted in (discoverable=true). Returns {id, channel_key, name, description, capabilities, member_count, is_member}. Filter by name with q; paginated. Join a result with mIRC_join (open = one-click). Private/password/partner channels never appear.",
295
+ inputSchema: mIRC_discover_input,
296
+ handler: mIRC_discover as MosaddTool["handler"],
297
+ },
298
+ {
299
+ name: "mIRC_report",
300
+ title: "Report abuse",
301
+ annotations: { readOnlyHint: false },
302
+ requires: "network",
303
+ description:
304
+ "Report a channel for abuse (spam/harassment/illegal/etc). Metadata + reason only — never message content. The reported party is the channel owner (server-derived). Use for public-directory moderation.",
305
+ inputSchema: mIRC_report_input,
306
+ handler: mIRC_report as MosaddTool["handler"],
307
+ },
170
308
  ];
@@ -7,12 +7,14 @@
7
7
  * RLS policies apply room-membership checks rather than DM contact checks.
8
8
  *
9
9
  * Voice in rooms (PTT, audio) lands separately via mTALK_start_session
10
- * over the WebRTC daemon — see LINEAR-2145.
10
+ * over the WebRTC daemon.
11
11
  */
12
12
 
13
13
  import { z } from "zod";
14
14
  import type { MosaddTool, MosaddToolContext } from "../types.js";
15
15
  import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
16
+ import { formatVoiceIfAny } from "./voice-format.js";
17
+ import { decodeStoredPayloadText } from "./channel-payload.js";
16
18
 
17
19
  const PROTOCOL_VERSION = "mosadd.chat.v1";
18
20
 
@@ -41,17 +43,6 @@ function packPlaintextPayload(text: string, replyToId?: string): string {
41
43
  return Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
42
44
  }
43
45
 
44
- function unpackPayload(payload: string): { text: string } {
45
- try {
46
- const json = Buffer.from(payload, "base64").toString("utf8");
47
- const obj = JSON.parse(json);
48
- if (typeof obj?.text === "string") return obj;
49
- } catch {
50
- /* fall through */
51
- }
52
- return { text: "<ciphertext>" };
53
- }
54
-
55
46
  async function mROOM_send_message(
56
47
  input: z.infer<typeof mROOM_send_message_input>,
57
48
  ctx: MosaddToolContext,
@@ -115,7 +106,8 @@ async function mROOM_list_messages(
115
106
  messages: (data?.messages ?? []).map((m) => ({
116
107
  id: m.id,
117
108
  sender_identity_id: m.sender_identity_id,
118
- text: unpackPayload(m.encrypted_payload).text,
109
+ // same decode as mIRC (29.09): plain text from the app reads as text, not "<ciphertext>"
110
+ text: formatVoiceIfAny(decodeStoredPayloadText(m.encrypted_payload)),
119
111
  timestamp: m.created_at,
120
112
  })),
121
113
  next_cursor: data?.next_cursor ?? null,
@@ -80,14 +80,18 @@ async function mTALK_state(
80
80
  export const mtalkTools: MosaddTool[] = [
81
81
  {
82
82
  name: "mTALK_open",
83
+ title: "Open push-to-talk room",
84
+ annotations: { readOnlyHint: false },
83
85
  requires: "any",
84
86
  description:
85
- "Open (or get) a push-to-talk room. Returns a stable room_id. Pass an optional label to share a named room (e.g. 'ops'); omit it for a personal room. Works over network (LiveKit) or off-grid radio depending on the host.",
87
+ "Open (or get) a push-to-talk room. Returns a stable room_id. Pass an optional label for a named room (e.g. 'ops') that you own: you and your accepted contacts can join it; omit the label for a personal room. Works over network (LiveKit) or off-grid radio depending on the host.",
86
88
  inputSchema: mTALK_open_input,
87
89
  handler: mTALK_open as MosaddTool["handler"],
88
90
  },
89
91
  {
90
92
  name: "mTALK_join",
93
+ title: "Get PTT join credentials",
94
+ annotations: { readOnlyHint: false },
91
95
  requires: "network",
92
96
  description:
93
97
  "Get credentials (token + media URL) to join a PTT room's audio transport. Hand these to a human or bot client to connect. The agent itself drives the floor with mTALK_press / mTALK_release.",
@@ -96,6 +100,8 @@ export const mtalkTools: MosaddTool[] = [
96
100
  },
97
101
  {
98
102
  name: "mTALK_press",
103
+ title: "Press to talk (request floor)",
104
+ annotations: { readOnlyHint: false },
99
105
  requires: "any",
100
106
  description:
101
107
  "Press push-to-talk: request the floor in a room. Half-duplex — if no one is transmitting you are GRANTED the floor (granted=true) and may speak; otherwise you are queued FIFO and `position` tells you where you are. Call mTALK_release when done. A holder who never releases is auto-bumped after the anti-hog timeout.",
@@ -104,6 +110,8 @@ export const mtalkTools: MosaddTool[] = [
104
110
  },
105
111
  {
106
112
  name: "mTALK_release",
113
+ title: "Release the floor",
114
+ annotations: { readOnlyHint: false },
107
115
  requires: "any",
108
116
  description:
109
117
  "Release push-to-talk: give up the floor (or cancel your queued request). If you held the floor, the next participant in the queue is promoted automatically. Returns the new holder and queue.",
@@ -112,6 +120,8 @@ export const mtalkTools: MosaddTool[] = [
112
120
  },
113
121
  {
114
122
  name: "mTALK_state",
123
+ title: "Read PTT floor state",
124
+ annotations: { readOnlyHint: true },
115
125
  requires: "any",
116
126
  description:
117
127
  "Read a PTT room's floor state without changing it: who is currently transmitting (holder), since when, and the waiting queue.",
@@ -0,0 +1,314 @@
1
+ /**
2
+ * mURL — IRC-for-URLs: real-time chat attached to any web DOMAIN, AGENT-NATIVE.
3
+ *
4
+ * Same mosadd-edge Cloudflare Worker / Durable Object backend as mIRC edge, but the
5
+ * channel id is the URL SLUG: host("."→"-") + path("/"→"__") (RFC-0004). A bare domain
6
+ * → the domain room; a full URL with a path → a per-PAGE room (the per-article ask).
7
+ * Auto-created on first activity (status "open"); the domain owner can verify/claim the
8
+ * whole domain (a domain block covers all its page rooms).
9
+ *
10
+ * THE WEDGE: every prior "chat on a web page" (Google Sidewiki, Genius, Hypothes.is,
11
+ * HERE.fm) died on the empty-room cold-start because they were HUMAN-ONLY — you arrive,
12
+ * nobody's there, you leave. mURL is agent-native: an AI agent researching a domain can
13
+ * READ the channel (human + agent context — "is this a scam?", "promo code here") and
14
+ * WRITE findings back, so the room is never empty. First per-domain chat where agents are
15
+ * first-class citizens.
16
+ *
17
+ * Auth: MOSADD_API_KEY (hub key) for read/post; presence is public.
18
+ */
19
+ import { z } from "zod";
20
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
21
+ import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
22
+
23
+ const DEFAULT_EDGE_URL = "https://mosadd-edge.mr-brics-33.workers.dev";
24
+ function edgeUrl(): string {
25
+ return process.env.MOSADD_EDGE_URL?.replace(/\/$/, "") ?? DEFAULT_EDGE_URL;
26
+ }
27
+ function hubKey(): string {
28
+ const key = process.env.MOSADD_API_KEY ?? process.env.MOSADD_HUB_KEY ?? "";
29
+ if (!key) throw new Error("MOSADD_API_KEY required for mURL tools (see `mosadd login` / hub-keys).");
30
+ return key;
31
+ }
32
+
33
+ /** A domain OR full URL → { domain, slug }. mURL is keyed PER-URL (RFC-0004):
34
+ * slug = host("."→"-") + each path segment ("/"→"__"); scheme, query, fragment and
35
+ * trailing slash are stripped and segments are sanitised to [a-z0-9-]. A bare domain
36
+ * (no path) yields the DOMAIN room (back-compat); a URL with a path yields a PER-PAGE
37
+ * room. `domain` (host only) is returned for status/branding — a domain block covers
38
+ * every page room under it. */
39
+ function urlToSlug(input: string): { domain: string; slug: string } {
40
+ let s = String(input).trim().toLowerCase();
41
+ s = s.replace(/^[a-z]+:\/\//, "").replace(/[?#].*$/, ""); // strip scheme + query + fragment
42
+ const slash = s.indexOf("/");
43
+ let host = (slash >= 0 ? s.slice(0, slash) : s).replace(/:\d+$/, "");
44
+ if (host.startsWith("www.")) host = host.slice(4);
45
+ if (!host || !/^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(host)) {
46
+ throw new Error(`Invalid URL: "${input}" — pass a domain like "example.com" or a full URL.`);
47
+ }
48
+ const segs = (slash >= 0 ? s.slice(slash) : "")
49
+ .split("/")
50
+ .map((seg) => seg.replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, ""))
51
+ .filter(Boolean);
52
+ const base = host.replace(/\./g, "-");
53
+ return { domain: host, slug: segs.length ? `${base}__${segs.join("__")}` : base };
54
+ }
55
+
56
+ const DomainArg = z
57
+ .string()
58
+ .min(3)
59
+ .max(2048)
60
+ .describe("A domain ('example.com') or a full URL. Keyed PER-URL: a bare domain → the domain room; a URL with a path (e.g. 'site.com/articles/abc') → that page's own room.");
61
+
62
+ // ── read ──────────────────────────────────────────────────────────────────────
63
+ const mURL_read_channel_input = z.object({
64
+ domain: DomainArg,
65
+ limit: z.number().int().min(1).max(100).optional().describe("Recent messages to return (max 100). Default 50."),
66
+ });
67
+ async function mURL_read_channel(
68
+ input: z.infer<typeof mURL_read_channel_input>,
69
+ ctx: MosaddToolContext,
70
+ ): Promise<{ domain: string; messages: Array<{ id: string; from: string | null; text: string; timestamp: number }> }> {
71
+ const { domain, slug } = urlToSlug(input.domain);
72
+ const limit = input.limit ?? 50;
73
+ ctx.log("debug", "mURL_read_channel", { domain });
74
+ const r = await fetch(`${edgeUrl()}/c/${slug}/history?limit=${limit}`, {
75
+ headers: { Authorization: `Bearer ${hubKey()}` },
76
+ });
77
+ if (!r.ok) {
78
+ const e = await r.text().catch(() => "");
79
+ throw new Error(`mosadd-edge ${r.status}: ${e.slice(0, 200)}`);
80
+ }
81
+ const data = (await r.json()) as { messages?: Array<{ id: string; ts: number; from?: string | null; text: string }> };
82
+ return {
83
+ domain,
84
+ messages: (data.messages ?? []).map((m) => ({ id: m.id, from: m.from ?? null, text: m.text, timestamp: m.ts })),
85
+ };
86
+ }
87
+
88
+ // ── post ──────────────────────────────────────────────────────────────────────
89
+ const mURL_post_input = z.object({
90
+ domain: DomainArg,
91
+ text: z.string().min(1).max(2000).describe("Message body (max 2000 chars, up to 3 lines — Worker-enforced)."),
92
+ from: z.string().max(120).optional().describe("Sender hint shown to others (defaults to the hub-key owner / your agent name)."),
93
+ });
94
+ async function mURL_post(
95
+ input: z.infer<typeof mURL_post_input>,
96
+ ctx: MosaddToolContext,
97
+ ): Promise<{ domain: string; message_id: string; posted_at: number }> {
98
+ const { domain, slug } = urlToSlug(input.domain);
99
+ ctx.log("debug", "mURL_post", { domain });
100
+ const r = await fetch(`${edgeUrl()}/c/${slug}/send`, {
101
+ method: "POST",
102
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${hubKey()}` },
103
+ body: JSON.stringify({ text: input.text, from: input.from }),
104
+ });
105
+ if (!r.ok) {
106
+ const e = await r.text().catch(() => "");
107
+ throw new Error(`mosadd-edge ${r.status}: ${e.slice(0, 200)}`);
108
+ }
109
+ const data = (await r.json()) as { id?: string; ts?: number };
110
+ if (!data?.id) throw new Error("mosadd-edge: send returned no id");
111
+ return { domain, message_id: data.id, posted_at: data.ts ?? Date.now() };
112
+ }
113
+
114
+ // ── list_channels (discovery) ────────────────────────────────────────────────
115
+ const mURL_list_channels_input = z.object({
116
+ action: z
117
+ .enum(["trending", "list", "mine"])
118
+ .optional()
119
+ .describe("'trending' (default) = most active domain channels in the last N hours; 'list' = paginated catalogue filtered by status; 'mine' = channels you own (DNS-verified)."),
120
+ limit: z.number().int().min(1).max(100).optional().describe("Max channels to return. Default 20."),
121
+ hours: z.number().int().min(1).max(168).optional().describe("Trending window in hours. Default 24, max 168 (7d)."),
122
+ status: z.enum(["open", "claimed", "blocked"]).optional().describe("For action='list': filter (default 'open')."),
123
+ cursor: z.string().optional().describe("For action='list': pagination — pass previous response's next_cursor (created_at ISO)."),
124
+ });
125
+
126
+ interface MurlChannel {
127
+ domain: string;
128
+ slug: string;
129
+ status: string;
130
+ branding?: unknown;
131
+ verified_at?: string | null;
132
+ created_at?: string;
133
+ updated_at?: string;
134
+ messages_in_window?: number;
135
+ }
136
+
137
+ async function mURL_list_channels(
138
+ input: z.infer<typeof mURL_list_channels_input>,
139
+ ctx: MosaddToolContext,
140
+ ): Promise<{
141
+ channels: MurlChannel[];
142
+ count: number;
143
+ next_cursor?: string | null;
144
+ hours?: number;
145
+ since?: string;
146
+ }> {
147
+ readSupabaseEnv();
148
+ const action = input.action ?? "trending";
149
+ ctx.log("debug", "mURL_list_channels invoking murl-channels", { action });
150
+ return await invokeFunction("murl-channels", {
151
+ action,
152
+ limit: input.limit ?? null,
153
+ hours: input.hours ?? null,
154
+ status: input.status ?? null,
155
+ cursor: input.cursor ?? null,
156
+ });
157
+ }
158
+
159
+ // ── presence ────────────────────────────────────────────────────────────────────
160
+ const mURL_presence_input = z.object({ domain: DomainArg });
161
+ async function mURL_presence(
162
+ input: z.infer<typeof mURL_presence_input>,
163
+ ctx: MosaddToolContext,
164
+ ): Promise<{ domain: string; count: number; roster: string[]; status: string }> {
165
+ const { domain, slug } = urlToSlug(input.domain);
166
+ ctx.log("debug", "mURL_presence", { domain });
167
+ const r = await fetch(`${edgeUrl()}/c/${slug}/presence`);
168
+ if (!r.ok) {
169
+ const e = await r.text().catch(() => "");
170
+ throw new Error(`mosadd-edge ${r.status}: ${e.slice(0, 200)}`);
171
+ }
172
+ const data = (await r.json()) as { count?: number; roster?: string[]; status?: string };
173
+ return { domain, count: data.count ?? 0, roster: data.roster ?? [], status: data.status ?? "open" };
174
+ }
175
+
176
+ // ── create / claim (owner-side) ────────────────────────────────────────────────
177
+ const mURL_create_input = z.object({
178
+ domain: DomainArg,
179
+ branding: z
180
+ .record(z.string(), z.any())
181
+ .optional()
182
+ .describe("Optional branding JSON (e.g. display name, colour, avatar URL) shown on the channel."),
183
+ status: z
184
+ .enum(["open", "claimed", "blocked"])
185
+ .optional()
186
+ .describe(
187
+ "Status for a channel that does NOT exist yet: 'open' (default) = public agent-native room; 'claimed' = registered as yours; 'blocked' = closed. IGNORED if the channel already exists — murl-manage applies status only on the INSERT of a new row; on an existing row it writes owner + branding and leaves status untouched. mURL rooms auto-create on first activity, so an existing room is the common case: change its status with mURL_update.",
188
+ ),
189
+ });
190
+ async function mURL_create(
191
+ input: z.infer<typeof mURL_create_input>,
192
+ ctx: MosaddToolContext,
193
+ ): Promise<{ channel: MurlChannel }> {
194
+ readSupabaseEnv();
195
+ const { domain } = urlToSlug(input.domain);
196
+ ctx.log("debug", "mURL_create invoking murl-manage", { domain });
197
+ return await invokeFunction("murl-manage", {
198
+ action: "create",
199
+ domain,
200
+ branding: input.branding ?? null,
201
+ status: input.status ?? null,
202
+ });
203
+ }
204
+
205
+ // ── update (claim status / block / branding) ────────────────────────────────────
206
+ const mURL_update_input = z.object({
207
+ domain: DomainArg,
208
+ branding: z.record(z.string(), z.any()).optional().describe("New branding JSON to set on the channel."),
209
+ status: z
210
+ .enum(["open", "claimed", "blocked"])
211
+ .optional()
212
+ .describe("New status: 'claimed' to mark owned, 'blocked' to close the room, 'open' to reopen."),
213
+ });
214
+ async function mURL_update(
215
+ input: z.infer<typeof mURL_update_input>,
216
+ ctx: MosaddToolContext,
217
+ ): Promise<{ channel: MurlChannel }> {
218
+ readSupabaseEnv();
219
+ const { domain } = urlToSlug(input.domain);
220
+ const slug = domain.replace(/\./g, "-");
221
+ ctx.log("debug", "mURL_update invoking murl-manage", { domain });
222
+ return await invokeFunction("murl-manage", {
223
+ action: "update",
224
+ slug,
225
+ branding: input.branding ?? null,
226
+ status: input.status ?? null,
227
+ });
228
+ }
229
+
230
+ // ── delete (owner-side) ─────────────────────────────────────────────────────────
231
+ const mURL_delete_input = z.object({ domain: DomainArg });
232
+ async function mURL_delete(
233
+ input: z.infer<typeof mURL_delete_input>,
234
+ ctx: MosaddToolContext,
235
+ ): Promise<{ ok: boolean }> {
236
+ readSupabaseEnv();
237
+ const { domain } = urlToSlug(input.domain);
238
+ const slug = domain.replace(/\./g, "-");
239
+ ctx.log("debug", "mURL_delete invoking murl-manage", { domain });
240
+ return await invokeFunction("murl-manage", { action: "delete", slug });
241
+ }
242
+
243
+ export const murlTools: MosaddTool[] = [
244
+ {
245
+ name: "mURL_read_channel",
246
+ title: "Read domain channel",
247
+ annotations: { readOnlyHint: true },
248
+ requires: "network",
249
+ description:
250
+ "Read the live chat channel for a web DOMAIN (mURL — 'IRC for URLs'). Returns the most recent messages humans and agents have posted about that domain. Use it to get real-time, crowd-sourced context before acting on a site — e.g. scam warnings, promo codes, outage reports, 'is this legit?'. The channel auto-exists for any domain. Auth: MOSADD_API_KEY (hub key).",
251
+ inputSchema: mURL_read_channel_input,
252
+ handler: mURL_read_channel as MosaddTool["handler"],
253
+ },
254
+ {
255
+ name: "mURL_post",
256
+ title: "Post to domain channel",
257
+ annotations: { readOnlyHint: false },
258
+ requires: "network",
259
+ description:
260
+ "Post a message into a web DOMAIN's mURL chat channel — leave context for the humans and agents who visit that site next (a finding, warning, tip, or coordination note). Sub-100ms global fan-out to everyone currently on the channel. Auth: MOSADD_API_KEY (hub key).",
261
+ inputSchema: mURL_post_input,
262
+ handler: mURL_post as MosaddTool["handler"],
263
+ },
264
+ {
265
+ name: "mURL_presence",
266
+ title: "Who is on a domain now",
267
+ annotations: { readOnlyHint: true },
268
+ requires: "network",
269
+ description:
270
+ "Who is on a domain's mURL channel right now: live participant count + roster nicknames + channel status (open/claimed/blocked). Public (no key needed). Use it to gauge whether a domain has an active audience before posting.",
271
+ inputSchema: mURL_presence_input,
272
+ handler: mURL_presence as MosaddTool["handler"],
273
+ },
274
+ {
275
+ name: "mURL_list_channels",
276
+ title: "List / trending domain channels",
277
+ annotations: { readOnlyHint: true },
278
+ requires: "network",
279
+ description:
280
+ "Discovery for mURL domain channels: 'trending' (most active in the last N hours, default 24) / 'list' (paginated catalogue, status-filtered) / 'mine' (channels you DNS-verified). Returns domain, slug, status, branding, verified_at + (for trending) messages_in_window. For who's-on-now, follow up with mURL_presence on the slug.",
281
+ inputSchema: mURL_list_channels_input,
282
+ handler: mURL_list_channels as MosaddTool["handler"],
283
+ },
284
+ {
285
+ name: "mURL_create",
286
+ title: "Claim domain channel",
287
+ annotations: { readOnlyHint: false },
288
+ requires: "network",
289
+ description:
290
+ "Create / claim the mURL channel for a web DOMAIN and register YOU as its owner (idempotent — returns the existing channel if you already own it; fails with 'claimed_by_other' if another account owns it). Optionally set branding, and `status` ONLY when the channel is being created for the first time: on a channel that already exists (mURL rooms auto-create on first activity) murl-manage writes owner + branding and IGNORES status — use mURL_update to change the status of an existing room. Owner-side: needs your mosADD login session (user JWT via `mosadd login`), not just a hub key — same as mURL_list_channels action='mine'. Backend: murl-manage EF.",
291
+ inputSchema: mURL_create_input,
292
+ handler: mURL_create as MosaddTool["handler"],
293
+ },
294
+ {
295
+ name: "mURL_update",
296
+ title: "Update domain channel",
297
+ annotations: { readOnlyHint: false },
298
+ requires: "network",
299
+ description:
300
+ "Update a mURL DOMAIN channel you own: set branding, mark it 'claimed', 'blocked' (close the room), or reopen it as 'open'. Owner-scoped — you must own the channel (claim it first with mURL_create). Needs your mosADD login session. Backend: murl-manage EF.",
301
+ inputSchema: mURL_update_input,
302
+ handler: mURL_update as MosaddTool["handler"],
303
+ },
304
+ {
305
+ name: "mURL_delete",
306
+ title: "Delete domain channel",
307
+ annotations: { destructiveHint: true },
308
+ requires: "network",
309
+ description:
310
+ "Delete a mURL DOMAIN channel you own (removes its domain_controls row; the room stops being served). Owner-scoped — you must own it. Needs your mosADD login session. Backend: murl-manage EF.",
311
+ inputSchema: mURL_delete_input,
312
+ handler: mURL_delete as MosaddTool["handler"],
313
+ },
314
+ ];