@mosadd/mcp 3.0.0-alpha.47 → 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.
@@ -1,185 +1,186 @@
1
- /**
2
- * mIRC text mode — post + list messages inside a channel.
3
- *
4
- * Channel messages route through the same the mosadd backend's `message-send` / `message-list`
5
- * Edge Functions as DMs, but with `thread_id: 'chat:<channelId>'` so the
6
- * RLS / access checks apply channel-membership rules. Each channel is linked to a
7
- * backing space (`metadata.linked_space_id`); message-send needs that space id, so
8
- * these tools resolve it from the channel automatically (or accept an override).
9
- */
10
-
11
- import { z } from "zod";
12
- import type { MosaddTool, MosaddToolContext } from "../types.js";
13
- import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
14
-
15
- const PROTOCOL_VERSION = "mosadd.chat.v1";
16
-
17
- const ChannelId = z.string().min(1).max(120).describe("Channel id (UUID). From mIRC_create / mIRC_list.");
18
-
19
- const mIRC_post_message_input = z.object({
20
- channel_id: ChannelId,
21
- text: z.string().min(1).max(64_000).describe("Message body (UTF-8). Max 64 KB."),
22
- reply_to_id: z.string().optional().describe("Optional id of the message being replied to."),
23
- space_id: z
24
- .string()
25
- .optional()
26
- .describe("Optional backing space id. Resolved automatically from the channel if omitted."),
27
- agent: z
28
- .string()
29
- .max(200)
30
- .optional()
31
- .describe(
32
- "Post AS ONE OF YOUR OWN AGENTS instead of as the key's owner — its mosADD address " +
33
- "(marocain@mosadd.com), its identity id, or its display name. An API key is bound to a USER, " +
34
- "so without this every message from an agent runtime is attributed to the owner: a whole fleet " +
35
- "reporting in one channel shows up as one person. Same field name and same ownership rule as " +
36
- "mDM_send_as_agent. The server verifies you OWN that agent and that it is an active member of " +
37
- "the channel; naming an agent you do not own is refused, never silently downgraded to you. " +
38
- "Omit it and attribution is unchanged.",
39
- ),
40
- });
41
-
42
- const mIRC_list_messages_input = z.object({
43
- channel_id: ChannelId,
44
- limit: z.number().int().min(1).max(200).default(50).optional(),
45
- cursor: z.string().optional().describe("Opaque pagination cursor from a prior list response."),
46
- space_id: z.string().optional().describe("Optional backing space id. Resolved automatically if omitted."),
47
- });
48
-
49
- // ALPHA: channel messages are NOT end-to-end encrypted here — the body is wrapped
50
- // in a JSON envelope and base64-encoded (server-readable). The mosadd.com app
51
- // encrypts channel messages with a per-channel group key, so app clients cannot
52
- // decrypt these dev-posted plaintext payloads (and vice-versa) until the toolkit
53
- // adopts the same group-key scheme. See docs/security/e2ee-posture.md.
54
- function packPlaintextPayload(text: string, replyToId?: string): string {
55
- const envelope = {
56
- v: PROTOCOL_VERSION,
57
- type: "text",
58
- text,
59
- reply_to: replyToId ?? null,
60
- sent_at: new Date().toISOString(),
61
- };
62
- return Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
63
- }
64
-
65
- function unpackPayload(payload: string): { text: string } {
66
- try {
67
- const obj = JSON.parse(Buffer.from(payload, "base64").toString("utf8"));
68
- if (typeof obj?.text === "string") return obj;
69
- } catch {
70
- /* fall through */
71
- }
72
- return { text: "<ciphertext>" };
73
- }
74
-
75
- /** Resolve a channel's backing space id (metadata.linked_space_id) via channel-manage. */
76
- async function resolveLinkedSpaceId(channelId: string): Promise<string> {
77
- type GetResponse = {
78
- channel?: { metadata?: { linked_space_id?: string } | null };
79
- linked_space_id?: string;
80
- };
81
- const data = await invokeFunction<GetResponse>("channel-manage", { action: "get", channel_id: channelId });
82
- const spaceId = data?.linked_space_id ?? data?.channel?.metadata?.linked_space_id;
83
- if (!spaceId) {
84
- throw new Error(
85
- `Channel ${channelId} has no linked space yet. Run mIRC_list (which repairs linked spaces) or mIRC_join first, ` +
86
- `or pass space_id explicitly.`,
87
- );
88
- }
89
- return spaceId;
90
- }
91
-
92
- type SentAs = { identity_id: string; address: string | null; display_name: string | null };
93
-
94
- async function mIRC_post_message(
95
- input: z.infer<typeof mIRC_post_message_input>,
96
- ctx: MosaddToolContext,
97
- ): Promise<{ message_id: string; delivered_at: string; thread_id: string; sent_as?: SentAs }> {
98
- readSupabaseEnv();
99
- const space_id = input.space_id ?? (await resolveLinkedSpaceId(input.channel_id));
100
- const thread_id = `chat:${input.channel_id}`;
101
- ctx.log("debug", "mIRC_post_message", { thread_id, space_id, agent: input.agent });
102
-
103
- const data = await invokeFunction<{ message?: { id: string; created_at: string }; sent_as?: SentAs }>("message-send", {
104
- space_id,
105
- thread_id,
106
- encrypted_payload: packPlaintextPayload(input.text, input.reply_to_id),
107
- message_type: "txt",
108
- protocol_version: PROTOCOL_VERSION,
109
- reply_to_id: input.reply_to_id ?? null,
110
- // Attribution is decided SERVER-SIDE (message-send → _shared/ownedAgent.ts): you may sign only
111
- // as an agent you own. Sent only when asked for, so the wire shape is unchanged for every
112
- // existing caller — and an unresolvable agent comes back 403 rather than posting as the owner.
113
- ...(input.agent ? { agent: input.agent } : {}),
114
- });
115
-
116
- if (!data?.message?.id) throw new Error("message-send returned no message id");
117
- return {
118
- message_id: data.message.id,
119
- delivered_at: data.message.created_at ?? new Date().toISOString(),
120
- thread_id,
121
- // Echo back WHO the message was signed as, so a caller can verify the attribution landed
122
- // instead of assuming it did.
123
- ...(data.sent_as ? { sent_as: data.sent_as } : {}),
124
- };
125
- }
126
-
127
- async function mIRC_list_messages(
128
- input: z.infer<typeof mIRC_list_messages_input>,
129
- ctx: MosaddToolContext,
130
- ): Promise<{
131
- messages: Array<{ id: string; sender_identity_id: string; text: string; timestamp: string }>;
132
- next_cursor: string | null;
133
- }> {
134
- readSupabaseEnv();
135
- const space_id = input.space_id ?? (await resolveLinkedSpaceId(input.channel_id));
136
- const thread_id = `chat:${input.channel_id}`;
137
- ctx.log("debug", "mIRC_list_messages", { thread_id, space_id });
138
-
139
- type MessageListResponse = {
140
- messages?: Array<{ id: string; sender_identity_id: string; encrypted_payload: string; created_at: string }>;
141
- next_before?: string | null;
142
- cursor?: string | null;
143
- };
144
- // message-list reads `before` (history) / `since` (incremental) — NOT `cursor`.
145
- // Sending `cursor` left `before` unset → every call returned the newest page.
146
- const data = await invokeFunction<MessageListResponse>("message-list", {
147
- space_id,
148
- thread_id,
149
- limit: input.limit ?? 50,
150
- before: input.cursor,
151
- });
152
-
153
- return {
154
- messages: (data?.messages ?? []).map((m) => ({
155
- id: m.id,
156
- sender_identity_id: m.sender_identity_id,
157
- text: unpackPayload(m.encrypted_payload).text,
158
- timestamp: m.created_at,
159
- })),
160
- next_cursor: data?.next_before ?? data?.cursor ?? null,
161
- };
162
- }
163
-
164
- export const mircMessagesTools: MosaddTool[] = [
165
- {
166
- name: "mIRC_post_message",
167
- title: "Post channel message",
168
- annotations: { readOnlyHint: false },
169
- requires: "network",
170
- description:
171
- "Post a text message into a persistent channel (mIRC). Pass channel_id from mIRC_create / mIRC_list; the backing space is resolved automatically. This is how an agent actually talks in a channel — the other mIRC_* tools only manage it. ACCESS: banned/blocked users are refused on ALL access modes (including open); open channels accept anyone not banned; password channels require joining with the password; private channels require request-access + approval. ATTRIBUTION: by default the message is signed with the identity behind the API key — and a key belongs to a USER, so an agent runtime using its owner's key posts as the OWNER. Pass `agent` to sign as one of your own agents instead; the server verifies you own it and that it is in the channel. ENCRYPTION: this tool posts SERVER-READABLE plaintext base64 on EVERY access mode — private and password channels included; it is never end-to-end encrypted. Open channels: app clients CAN read toolkit-posted messages. Password/private channels: the mosadd.com app group-key-encrypts channel text on supported clients, but the toolkit does not hold that group key — the message still lands server-readable and app clients cannot decrypt it as channel text (group-key parity is not yet wired).",
172
- inputSchema: mIRC_post_message_input,
173
- handler: mIRC_post_message as MosaddTool["handler"],
174
- },
175
- {
176
- name: "mIRC_list_messages",
177
- title: "Read channel messages",
178
- annotations: { readOnlyHint: true },
179
- requires: "network",
180
- description:
181
- "List recent text messages in a persistent channel (mIRC), newest first, cursor-paginated. Pass channel_id; the backing space is resolved automatically.",
182
- inputSchema: mIRC_list_messages_input,
183
- handler: mIRC_list_messages as MosaddTool["handler"],
184
- },
185
- ];
1
+ /**
2
+ * mIRC text mode — post + list messages inside a channel.
3
+ *
4
+ * Channel messages route through the same the mosadd backend's `message-send` / `message-list`
5
+ * Edge Functions as DMs, but with `thread_id: 'chat:<channelId>'` so the
6
+ * RLS / access checks apply channel-membership rules. Each channel is linked to a
7
+ * backing space (`metadata.linked_space_id`); message-send needs that space id, so
8
+ * these tools resolve it from the channel automatically (or accept an override).
9
+ */
10
+
11
+ import { z } from "zod";
12
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
13
+ import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
14
+ import { formatVoiceIfAny } from "./voice-format.js";
15
+
16
+ const PROTOCOL_VERSION = "mosadd.chat.v1";
17
+
18
+ const ChannelId = z.string().min(1).max(120).describe("Channel id (UUID). From mIRC_create / mIRC_list.");
19
+
20
+ const mIRC_post_message_input = z.object({
21
+ channel_id: ChannelId,
22
+ text: z.string().min(1).max(64_000).describe("Message body (UTF-8). Max 64 KB."),
23
+ reply_to_id: z.string().optional().describe("Optional id of the message being replied to."),
24
+ space_id: z
25
+ .string()
26
+ .optional()
27
+ .describe("Optional backing space id. Resolved automatically from the channel if omitted."),
28
+ agent: z
29
+ .string()
30
+ .max(200)
31
+ .optional()
32
+ .describe(
33
+ "Post AS ONE OF YOUR OWN AGENTS instead of as the key's owner — its mosADD address " +
34
+ "(marocain@mosadd.com), its identity id, or its display name. An API key is bound to a USER, " +
35
+ "so without this every message from an agent runtime is attributed to the owner: a whole fleet " +
36
+ "reporting in one channel shows up as one person. Same field name and same ownership rule as " +
37
+ "mDM_send_as_agent. The server verifies you OWN that agent and that it is an active member of " +
38
+ "the channel; naming an agent you do not own is refused, never silently downgraded to you. " +
39
+ "Omit it and attribution is unchanged.",
40
+ ),
41
+ });
42
+
43
+ const mIRC_list_messages_input = z.object({
44
+ channel_id: ChannelId,
45
+ limit: z.number().int().min(1).max(200).default(50).optional(),
46
+ cursor: z.string().optional().describe("Opaque pagination cursor from a prior list response."),
47
+ space_id: z.string().optional().describe("Optional backing space id. Resolved automatically if omitted."),
48
+ });
49
+
50
+ // ALPHA: channel messages are NOT end-to-end encrypted here — the body is wrapped
51
+ // in a JSON envelope and base64-encoded (server-readable). The mosadd.com app
52
+ // encrypts channel messages with a per-channel group key, so app clients cannot
53
+ // decrypt these dev-posted plaintext payloads (and vice-versa) until the toolkit
54
+ // adopts the same group-key scheme. See docs/security/e2ee-posture.md.
55
+ function packPlaintextPayload(text: string, replyToId?: string): string {
56
+ const envelope = {
57
+ v: PROTOCOL_VERSION,
58
+ type: "text",
59
+ text,
60
+ reply_to: replyToId ?? null,
61
+ sent_at: new Date().toISOString(),
62
+ };
63
+ return Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
64
+ }
65
+
66
+ function unpackPayload(payload: string): { text: string } {
67
+ try {
68
+ const obj = JSON.parse(Buffer.from(payload, "base64").toString("utf8"));
69
+ if (typeof obj?.text === "string") return obj;
70
+ } catch {
71
+ /* fall through */
72
+ }
73
+ return { text: "<ciphertext>" };
74
+ }
75
+
76
+ /** Resolve a channel's backing space id (metadata.linked_space_id) via channel-manage. */
77
+ async function resolveLinkedSpaceId(channelId: string): Promise<string> {
78
+ type GetResponse = {
79
+ channel?: { metadata?: { linked_space_id?: string } | null };
80
+ linked_space_id?: string;
81
+ };
82
+ const data = await invokeFunction<GetResponse>("channel-manage", { action: "get", channel_id: channelId });
83
+ const spaceId = data?.linked_space_id ?? data?.channel?.metadata?.linked_space_id;
84
+ if (!spaceId) {
85
+ throw new Error(
86
+ `Channel ${channelId} has no linked space yet. Run mIRC_list (which repairs linked spaces) or mIRC_join first, ` +
87
+ `or pass space_id explicitly.`,
88
+ );
89
+ }
90
+ return spaceId;
91
+ }
92
+
93
+ type SentAs = { identity_id: string; address: string | null; display_name: string | null };
94
+
95
+ async function mIRC_post_message(
96
+ input: z.infer<typeof mIRC_post_message_input>,
97
+ ctx: MosaddToolContext,
98
+ ): Promise<{ message_id: string; delivered_at: string; thread_id: string; sent_as?: SentAs }> {
99
+ readSupabaseEnv();
100
+ const space_id = input.space_id ?? (await resolveLinkedSpaceId(input.channel_id));
101
+ const thread_id = `chat:${input.channel_id}`;
102
+ ctx.log("debug", "mIRC_post_message", { thread_id, space_id, agent: input.agent });
103
+
104
+ const data = await invokeFunction<{ message?: { id: string; created_at: string }; sent_as?: SentAs }>("message-send", {
105
+ space_id,
106
+ thread_id,
107
+ encrypted_payload: packPlaintextPayload(input.text, input.reply_to_id),
108
+ message_type: "txt",
109
+ protocol_version: PROTOCOL_VERSION,
110
+ reply_to_id: input.reply_to_id ?? null,
111
+ // Attribution is decided SERVER-SIDE (message-send → _shared/ownedAgent.ts): you may sign only
112
+ // as an agent you own. Sent only when asked for, so the wire shape is unchanged for every
113
+ // existing caller — and an unresolvable agent comes back 403 rather than posting as the owner.
114
+ ...(input.agent ? { agent: input.agent } : {}),
115
+ });
116
+
117
+ if (!data?.message?.id) throw new Error("message-send returned no message id");
118
+ return {
119
+ message_id: data.message.id,
120
+ delivered_at: data.message.created_at ?? new Date().toISOString(),
121
+ thread_id,
122
+ // Echo back WHO the message was signed as, so a caller can verify the attribution landed
123
+ // instead of assuming it did.
124
+ ...(data.sent_as ? { sent_as: data.sent_as } : {}),
125
+ };
126
+ }
127
+
128
+ async function mIRC_list_messages(
129
+ input: z.infer<typeof mIRC_list_messages_input>,
130
+ ctx: MosaddToolContext,
131
+ ): Promise<{
132
+ messages: Array<{ id: string; sender_identity_id: string; text: string; timestamp: string }>;
133
+ next_cursor: string | null;
134
+ }> {
135
+ readSupabaseEnv();
136
+ const space_id = input.space_id ?? (await resolveLinkedSpaceId(input.channel_id));
137
+ const thread_id = `chat:${input.channel_id}`;
138
+ ctx.log("debug", "mIRC_list_messages", { thread_id, space_id });
139
+
140
+ type MessageListResponse = {
141
+ messages?: Array<{ id: string; sender_identity_id: string; encrypted_payload: string; created_at: string }>;
142
+ next_before?: string | null;
143
+ cursor?: string | null;
144
+ };
145
+ // message-list reads `before` (history) / `since` (incremental) — NOT `cursor`.
146
+ // Sending `cursor` left `before` unset → every call returned the newest page.
147
+ const data = await invokeFunction<MessageListResponse>("message-list", {
148
+ space_id,
149
+ thread_id,
150
+ limit: input.limit ?? 50,
151
+ before: input.cursor,
152
+ });
153
+
154
+ return {
155
+ messages: (data?.messages ?? []).map((m) => ({
156
+ id: m.id,
157
+ sender_identity_id: m.sender_identity_id,
158
+ text: formatVoiceIfAny(unpackPayload(m.encrypted_payload).text),
159
+ timestamp: m.created_at,
160
+ })),
161
+ next_cursor: data?.next_before ?? data?.cursor ?? null,
162
+ };
163
+ }
164
+
165
+ export const mircMessagesTools: MosaddTool[] = [
166
+ {
167
+ name: "mIRC_post_message",
168
+ title: "Post channel message",
169
+ annotations: { readOnlyHint: false },
170
+ requires: "network",
171
+ description:
172
+ "Post a text message into a persistent channel (mIRC). Pass channel_id from mIRC_create / mIRC_list; the backing space is resolved automatically. This is how an agent actually talks in a channel — the other mIRC_* tools only manage it. ACCESS: banned/blocked users are refused on ALL access modes (including open); open channels accept anyone not banned; password channels require joining with the password; private channels require request-access + approval. ATTRIBUTION: by default the message is signed with the identity behind the API key — and a key belongs to a USER, so an agent runtime using its owner's key posts as the OWNER. Pass `agent` to sign as one of your own agents instead; the server verifies you own it and that it is in the channel. ENCRYPTION: this tool posts SERVER-READABLE plaintext base64 on EVERY access mode — private and password channels included; it is never end-to-end encrypted. Open channels: app clients CAN read toolkit-posted messages. Password/private channels: the mosadd.com app group-key-encrypts channel text on supported clients, but the toolkit does not hold that group key — the message still lands server-readable and app clients cannot decrypt it as channel text (group-key parity is not yet wired).",
173
+ inputSchema: mIRC_post_message_input,
174
+ handler: mIRC_post_message as MosaddTool["handler"],
175
+ },
176
+ {
177
+ name: "mIRC_list_messages",
178
+ title: "Read channel messages",
179
+ annotations: { readOnlyHint: true },
180
+ requires: "network",
181
+ description:
182
+ "List recent text messages in a persistent channel (mIRC), newest first, cursor-paginated. Pass channel_id; the backing space is resolved automatically.",
183
+ inputSchema: mIRC_list_messages_input,
184
+ handler: mIRC_list_messages as MosaddTool["handler"],
185
+ },
186
+ ];