@mosadd/mcp 3.0.0 → 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.
- package/CHANGELOG.md +415 -410
- package/LICENSE +21 -0
- package/dist/bin/mcp.js +1 -1
- package/dist/{chunk-VMMJJYXF.js → chunk-J2S44U5R.js} +52 -27
- package/dist/index.d.ts +6 -6
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/src/__tests__/blob-upload.test.ts +1 -1
- package/src/__tests__/{flota-jawnie.test.ts → fleet-plaintext.test.ts} +59 -60
- package/src/__tests__/integration.test.ts +1 -1
- package/src/__tests__/mdm-e2ee.test.ts +3 -3
- package/src/__tests__/mdm-mcp-readable.test.ts +95 -95
- package/src/__tests__/mirc-invite.test.ts +1 -1
- package/src/__tests__/mirc-voice.test.ts +82 -0
- package/src/__tests__/mrag-search-diagnostics.test.ts +78 -0
- package/src/__tests__/presence.test.ts +2 -2
- package/src/__tests__/server.test.ts +3 -3
- package/src/__tests__/tool-count-consistency.test.ts +4 -4
- package/src/crypto/channel-e2ee.ts +1 -1
- package/src/crypto/mdm-session.ts +14 -14
- package/src/providers/supabase-dm.ts +1 -1
- package/src/providers/supabase.ts +8 -8
- package/src/server.ts +4 -4
- package/src/tools/channel-payload.ts +3 -3
- package/src/tools/index.ts +13 -13
- package/src/tools/knowledge.ts +384 -351
- package/src/tools/mail-aliases.ts +1 -1
- package/src/tools/mail-provenance.ts +1 -1
- package/src/tools/mdm-as-agent.ts +3 -4
- package/src/tools/mdm.ts +15 -13
- package/src/tools/mirc-edge.ts +4 -4
- package/src/tools/mirc-members.ts +1 -1
- package/src/tools/mirc-messages.ts +36 -12
- package/src/tools/mirc.ts +1 -1
- package/src/tools/mroom-messages.ts +1 -1
- package/src/tools/presence.ts +10 -10
- package/src/tools/ptt-ingest.ts +1 -1
- package/src/tools/threat.ts +1 -1
- package/src/tools/voice-format.ts +30 -7
package/src/tools/knowledge.ts
CHANGED
|
@@ -1,351 +1,384 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* mRAG — Knowledge Base (RAG): search and reason over the user's own mosadd data.
|
|
3
|
-
*
|
|
4
|
-
* This is the developer-facing surface of the RAG pipeline that already runs
|
|
5
|
-
* inside the mosadd backend: every message/email/call is embedded into a
|
|
6
|
-
* private per-user vector index (rag_embeddings) with hybrid vector + BM25
|
|
7
|
-
* retrieval, Cohere reranking, and a freshness lane for just-sent items. The
|
|
8
|
-
* `mRAG_search` tool lets an AGENT query that index — semantic recall over
|
|
9
|
-
* the user's communications — WITHOUT the mosadd.com app. It is the dev-product
|
|
10
|
-
* form of RAG (decision C): the same engine, exposed as one MCP tool.
|
|
11
|
-
*
|
|
12
|
-
* Wired to the mosadd backend's `rag-query` Edge Function. The answer + cited sources
|
|
13
|
-
* come back grounded strictly in the user's indexed data (no fabrication).
|
|
14
|
-
*
|
|
15
|
-
* Plan note: on the hosted hub this tool is gated by plan (free = off,
|
|
16
|
-
* pro/team = on); BYOK/self-host runs it against the user's own backend. Gating
|
|
17
|
-
* is enforced at the hub, not in this tool.
|
|
18
|
-
*/
|
|
19
|
-
|
|
20
|
-
import { createHash } from "node:crypto";
|
|
21
|
-
import { z } from "zod";
|
|
22
|
-
import type { MosaddTool, MosaddToolContext } from "../types.js";
|
|
23
|
-
import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
|
|
24
|
-
|
|
25
|
-
// ── source_id: free-form for the caller, a UUID on the wire ──────────────────
|
|
26
|
-
// `user_embeddings.source_id` is a **uuid** column (measured on prod 2026-08-14). This tool has
|
|
27
|
-
// always advertised source_id as "an optional stable id so re-ingests can be grouped" and typed it
|
|
28
|
-
// as a plain string — so the natural thing to pass (a file path, a case number, a docket id) made
|
|
29
|
-
// the INSERT blow up and the whole call came back as an opaque `rag-index (500): Internal error`.
|
|
30
|
-
// Bisected that day: every other field succeeded, `source_id: "bisect-1"` alone failed. It would
|
|
31
|
-
// have hit the legal-corpus ingest on document #1, with an error message pointing nowhere.
|
|
32
|
-
//
|
|
33
|
-
// Rather than push the problem onto every caller ("bring your own UUID"), a non-UUID id is folded
|
|
34
|
-
// into a DETERMINISTIC UUIDv5. Same input → same uuid, for ever, so grouping and mRAG_delete keep
|
|
35
|
-
// working on natural keys; a caller that already passes a real UUID is untouched. The original
|
|
36
|
-
// string is preserved as `metadata.source_ref` so it comes back with search hits and nothing is
|
|
37
|
-
// silently renamed behind the user's back.
|
|
38
|
-
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
39
|
-
|
|
40
|
-
/** Fixed namespace for mosadd mRAG source ids. Changing it would orphan every previously grouped source. */
|
|
41
|
-
const SOURCE_ID_NAMESPACE = "1f0b6c2e-6a4d-4f7a-9c1e-0b2d3a4f5e6b";
|
|
42
|
-
|
|
43
|
-
/** RFC 4122 v5 (SHA-1, namespaced). Small enough to keep here rather than add a dependency. */
|
|
44
|
-
function uuidV5(name: string, namespace: string): string {
|
|
45
|
-
const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
|
|
46
|
-
const digest = createHash("sha1").update(Buffer.concat([ns, Buffer.from(name, "utf8")])).digest();
|
|
47
|
-
const b = Buffer.from(digest.subarray(0, 16));
|
|
48
|
-
b[6] = (b[6] & 0x0f) | 0x50; // version 5
|
|
49
|
-
b[8] = (b[8] & 0x3f) | 0x80; // RFC 4122 variant
|
|
50
|
-
const h = b.toString("hex");
|
|
51
|
-
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
const mRAG_search_input = z.object({
|
|
55
|
-
query: z
|
|
56
|
-
.string()
|
|
57
|
-
.min(1)
|
|
58
|
-
.max(2_000)
|
|
59
|
-
.describe("Natural-language question to answer from the user's own indexed messages/emails/calls/notes."),
|
|
60
|
-
top_k: z
|
|
61
|
-
.number()
|
|
62
|
-
.int()
|
|
63
|
-
.min(1)
|
|
64
|
-
.max(25)
|
|
65
|
-
.optional()
|
|
66
|
-
.describe("Max number of source chunks to retrieve and ground the answer in. Default 8."),
|
|
67
|
-
source_types: z
|
|
68
|
-
// ⚠ MUST stay a superset of everything that can REACH the index, or a filter
|
|
69
|
-
// silently hides data the user owns. Until 2026-08-11 this enum was missing
|
|
70
|
-
// "file" and "ptt" while the index held both — `file` is what mRAG_ingest itself
|
|
71
|
-
// writes (it is the DEFAULT source_type, and "note" is mapped onto it), and `ptt`
|
|
72
|
-
// is what mTALK_ingest_ptt writes once a push-to-talk transcript lands. Measured
|
|
73
|
-
// on prod that day: email 4098 · call 233 · note 187 · message 86 · file 49 · ptt 14
|
|
74
|
-
// — i.e. 63 rows were unreachable by any source_types filter. Add a value HERE
|
|
75
|
-
// whenever a new writer starts stamping a new source_type.
|
|
76
|
-
.array(z.enum(["message", "email", "call", "note", "contact", "file", "ptt"]))
|
|
77
|
-
.optional()
|
|
78
|
-
.describe(
|
|
79
|
-
"Restrict retrieval to these source types. Omit to search everything. 'file' covers anything added with mRAG_ingest (its default, and where 'note' ingests land); 'ptt' covers push-to-talk transcripts ingested by mTALK_ingest_ptt.",
|
|
80
|
-
),
|
|
81
|
-
thread_id: z
|
|
82
|
-
.string()
|
|
83
|
-
.optional()
|
|
84
|
-
.describe("Optional: restrict retrieval to a single thread id (e.g. a dm:/chat: thread)."),
|
|
85
|
-
answer: z
|
|
86
|
-
.boolean()
|
|
87
|
-
.optional()
|
|
88
|
-
.describe(
|
|
89
|
-
"Set true to also get a generated answer (answer field) grounded in the returned sources. Default false: ranked sources only, answer is empty.",
|
|
90
|
-
),
|
|
91
|
-
});
|
|
92
|
-
|
|
93
|
-
interface RagSource {
|
|
94
|
-
source_type: string;
|
|
95
|
-
source_id: string;
|
|
96
|
-
thread_id: string | null;
|
|
97
|
-
similarity: number;
|
|
98
|
-
snippet: string;
|
|
99
|
-
created_at: string;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
};
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
.
|
|
151
|
-
.
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
.
|
|
156
|
-
.
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
"
|
|
178
|
-
),
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
.
|
|
185
|
-
.
|
|
186
|
-
.describe("
|
|
187
|
-
|
|
188
|
-
.
|
|
189
|
-
.
|
|
190
|
-
.
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
.
|
|
194
|
-
.
|
|
195
|
-
.
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
)
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
1
|
+
/**
|
|
2
|
+
* mRAG — Knowledge Base (RAG): search and reason over the user's own mosadd data.
|
|
3
|
+
*
|
|
4
|
+
* This is the developer-facing surface of the RAG pipeline that already runs
|
|
5
|
+
* inside the mosadd backend: every message/email/call is embedded into a
|
|
6
|
+
* private per-user vector index (rag_embeddings) with hybrid vector + BM25
|
|
7
|
+
* retrieval, Cohere reranking, and a freshness lane for just-sent items. The
|
|
8
|
+
* `mRAG_search` tool lets an AGENT query that index — semantic recall over
|
|
9
|
+
* the user's communications — WITHOUT the mosadd.com app. It is the dev-product
|
|
10
|
+
* form of RAG (decision C): the same engine, exposed as one MCP tool.
|
|
11
|
+
*
|
|
12
|
+
* Wired to the mosadd backend's `rag-query` Edge Function. The answer + cited sources
|
|
13
|
+
* come back grounded strictly in the user's indexed data (no fabrication).
|
|
14
|
+
*
|
|
15
|
+
* Plan note: on the hosted hub this tool is gated by plan (free = off,
|
|
16
|
+
* pro/team = on); BYOK/self-host runs it against the user's own backend. Gating
|
|
17
|
+
* is enforced at the hub, not in this tool.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { createHash } from "node:crypto";
|
|
21
|
+
import { z } from "zod";
|
|
22
|
+
import type { MosaddTool, MosaddToolContext } from "../types.js";
|
|
23
|
+
import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
|
|
24
|
+
|
|
25
|
+
// ── source_id: free-form for the caller, a UUID on the wire ──────────────────
|
|
26
|
+
// `user_embeddings.source_id` is a **uuid** column (measured on prod 2026-08-14). This tool has
|
|
27
|
+
// always advertised source_id as "an optional stable id so re-ingests can be grouped" and typed it
|
|
28
|
+
// as a plain string — so the natural thing to pass (a file path, a case number, a docket id) made
|
|
29
|
+
// the INSERT blow up and the whole call came back as an opaque `rag-index (500): Internal error`.
|
|
30
|
+
// Bisected that day: every other field succeeded, `source_id: "bisect-1"` alone failed. It would
|
|
31
|
+
// have hit the legal-corpus ingest on document #1, with an error message pointing nowhere.
|
|
32
|
+
//
|
|
33
|
+
// Rather than push the problem onto every caller ("bring your own UUID"), a non-UUID id is folded
|
|
34
|
+
// into a DETERMINISTIC UUIDv5. Same input → same uuid, for ever, so grouping and mRAG_delete keep
|
|
35
|
+
// working on natural keys; a caller that already passes a real UUID is untouched. The original
|
|
36
|
+
// string is preserved as `metadata.source_ref` so it comes back with search hits and nothing is
|
|
37
|
+
// silently renamed behind the user's back.
|
|
38
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
39
|
+
|
|
40
|
+
/** Fixed namespace for mosadd mRAG source ids. Changing it would orphan every previously grouped source. */
|
|
41
|
+
const SOURCE_ID_NAMESPACE = "1f0b6c2e-6a4d-4f7a-9c1e-0b2d3a4f5e6b";
|
|
42
|
+
|
|
43
|
+
/** RFC 4122 v5 (SHA-1, namespaced). Small enough to keep here rather than add a dependency. */
|
|
44
|
+
function uuidV5(name: string, namespace: string): string {
|
|
45
|
+
const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
|
|
46
|
+
const digest = createHash("sha1").update(Buffer.concat([ns, Buffer.from(name, "utf8")])).digest();
|
|
47
|
+
const b = Buffer.from(digest.subarray(0, 16));
|
|
48
|
+
b[6] = (b[6] & 0x0f) | 0x50; // version 5
|
|
49
|
+
b[8] = (b[8] & 0x3f) | 0x80; // RFC 4122 variant
|
|
50
|
+
const h = b.toString("hex");
|
|
51
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const mRAG_search_input = z.object({
|
|
55
|
+
query: z
|
|
56
|
+
.string()
|
|
57
|
+
.min(1)
|
|
58
|
+
.max(2_000)
|
|
59
|
+
.describe("Natural-language question to answer from the user's own indexed messages/emails/calls/notes."),
|
|
60
|
+
top_k: z
|
|
61
|
+
.number()
|
|
62
|
+
.int()
|
|
63
|
+
.min(1)
|
|
64
|
+
.max(25)
|
|
65
|
+
.optional()
|
|
66
|
+
.describe("Max number of source chunks to retrieve and ground the answer in. Default 8."),
|
|
67
|
+
source_types: z
|
|
68
|
+
// ⚠ MUST stay a superset of everything that can REACH the index, or a filter
|
|
69
|
+
// silently hides data the user owns. Until 2026-08-11 this enum was missing
|
|
70
|
+
// "file" and "ptt" while the index held both — `file` is what mRAG_ingest itself
|
|
71
|
+
// writes (it is the DEFAULT source_type, and "note" is mapped onto it), and `ptt`
|
|
72
|
+
// is what mTALK_ingest_ptt writes once a push-to-talk transcript lands. Measured
|
|
73
|
+
// on prod that day: email 4098 · call 233 · note 187 · message 86 · file 49 · ptt 14
|
|
74
|
+
// — i.e. 63 rows were unreachable by any source_types filter. Add a value HERE
|
|
75
|
+
// whenever a new writer starts stamping a new source_type.
|
|
76
|
+
.array(z.enum(["message", "email", "call", "note", "contact", "file", "ptt"]))
|
|
77
|
+
.optional()
|
|
78
|
+
.describe(
|
|
79
|
+
"Restrict retrieval to these source types. Omit to search everything. 'file' covers anything added with mRAG_ingest (its default, and where 'note' ingests land); 'ptt' covers push-to-talk transcripts ingested by mTALK_ingest_ptt.",
|
|
80
|
+
),
|
|
81
|
+
thread_id: z
|
|
82
|
+
.string()
|
|
83
|
+
.optional()
|
|
84
|
+
.describe("Optional: restrict retrieval to a single thread id (e.g. a dm:/chat: thread)."),
|
|
85
|
+
answer: z
|
|
86
|
+
.boolean()
|
|
87
|
+
.optional()
|
|
88
|
+
.describe(
|
|
89
|
+
"Set true to also get a generated answer (answer field) grounded in the returned sources. Default false: ranked sources only, answer is empty.",
|
|
90
|
+
),
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
interface RagSource {
|
|
94
|
+
source_type: string;
|
|
95
|
+
source_id: string;
|
|
96
|
+
thread_id: string | null;
|
|
97
|
+
similarity: number;
|
|
98
|
+
snippet: string;
|
|
99
|
+
created_at: string;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* What rag-query says about HOW it found the sources. Until now the handler kept only answer/sources/chunks_found, so an agent
|
|
104
|
+
* could not tell a complete hybrid result from a keyword-only fallback after the vector stage ran out of time (rag-query ≥ 2026-11-22),
|
|
105
|
+
* nor see which stage was slow. All fields are optional and copied only when the backend sent them — an older backend yields the same
|
|
106
|
+
* three-field result as before.
|
|
107
|
+
*/
|
|
108
|
+
export interface RagSearchDiagnostics {
|
|
109
|
+
/** true when the vector stage did not deliver and the sources come from the keyword fallback (or are empty because both stages failed). */
|
|
110
|
+
partial?: boolean;
|
|
111
|
+
/** search_timeout | embed_failed | search_error */
|
|
112
|
+
partial_reason?: string;
|
|
113
|
+
/** "hybrid" (vector + keyword) or "keyword" (fallback). */
|
|
114
|
+
search_mode?: string;
|
|
115
|
+
/** Set when a model answer was requested but not produced (e.g. "ai_unavailable", "budget"); sources are still returned. */
|
|
116
|
+
degraded?: string;
|
|
117
|
+
/** Per-stage milliseconds measured by rag-query (auth, embed, vector, keyword, rerank, model, total). */
|
|
118
|
+
timing?: Record<string, number | string>;
|
|
119
|
+
/** Normalised stage summary: embed_ms, wektor_ms, slowa_ms, rerank_ms, synteza_ms, total_ms and per-stage status (ok | limit | blad | pominiety | niedostepny). */
|
|
120
|
+
stages?: Record<string, unknown>;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const DIAGNOSTIC_KEYS = ["partial", "partial_reason", "search_mode", "degraded", "timing", "stages"] as const;
|
|
124
|
+
|
|
125
|
+
function ragDiagnostics(data: RagSearchDiagnostics): RagSearchDiagnostics {
|
|
126
|
+
const out: Record<string, unknown> = {};
|
|
127
|
+
for (const key of DIAGNOSTIC_KEYS) {
|
|
128
|
+
const value = data[key];
|
|
129
|
+
if (value !== undefined && value !== null) out[key] = value;
|
|
130
|
+
}
|
|
131
|
+
return out as RagSearchDiagnostics;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function mRAG_search(
|
|
135
|
+
input: z.infer<typeof mRAG_search_input>,
|
|
136
|
+
ctx: MosaddToolContext,
|
|
137
|
+
): Promise<{ answer: string; sources: RagSource[]; chunks_found: number } & RagSearchDiagnostics> {
|
|
138
|
+
readSupabaseEnv();
|
|
139
|
+
ctx.log("debug", "mRAG_search via rag-query", { top_k: input.top_k ?? 8 });
|
|
140
|
+
|
|
141
|
+
type RagQueryResponse = {
|
|
142
|
+
answer?: string;
|
|
143
|
+
sources?: RagSource[];
|
|
144
|
+
chunks_found?: number;
|
|
145
|
+
} & RagSearchDiagnostics;
|
|
146
|
+
const data = await invokeFunction<RagQueryResponse>("rag-query", {
|
|
147
|
+
query: input.query,
|
|
148
|
+
top_k: input.top_k ?? 8,
|
|
149
|
+
source_types: input.source_types ?? null,
|
|
150
|
+
thread_id: input.thread_id ?? null,
|
|
151
|
+
answer: input.answer ?? false,
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
return {
|
|
155
|
+
answer: data.answer ?? "",
|
|
156
|
+
sources: data.sources ?? [],
|
|
157
|
+
chunks_found: data.chunks_found ?? (data.sources?.length ?? 0),
|
|
158
|
+
...ragDiagnostics(data),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* A person / company / address a document involves.
|
|
164
|
+
*
|
|
165
|
+
* Polymorphic on purpose: mail carries an address, mDM carries an identity UUID, a court filing
|
|
166
|
+
* carries a party name — all three flow through the SAME `{ kind, ref, label }` shape so one
|
|
167
|
+
* filter matches any of them. Mirrors `Party` in the backend's _shared/enrichRagMetadata.ts.
|
|
168
|
+
*/
|
|
169
|
+
const PartyArg = z.object({
|
|
170
|
+
kind: z
|
|
171
|
+
.enum(["identity", "account", "email", "phone", "url", "unknown"])
|
|
172
|
+
.describe("How to read `ref`: a mosadd identity UUID, an account id, an email address, a phone number, a URL, or a plain name ('unknown')."),
|
|
173
|
+
ref: z
|
|
174
|
+
.string()
|
|
175
|
+
.min(1)
|
|
176
|
+
.max(400)
|
|
177
|
+
.describe("The stable key this party is recognised by — identity UUID, email address, phone number, or the party's canonical name. Use the SAME ref for the same party across documents; that is what merges them into one node in the knowledge graph."),
|
|
178
|
+
label: z.string().max(300).nullish().describe("Human name to display for this party."),
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
const mRAG_ingest_input = z.object({
|
|
182
|
+
content_text: z
|
|
183
|
+
.string()
|
|
184
|
+
.min(1)
|
|
185
|
+
.max(200_000)
|
|
186
|
+
.describe("Text to index into the user's private knowledge base (a note, document, transcript, pasted page…). Chunked + embedded server-side."),
|
|
187
|
+
source_type: z
|
|
188
|
+
.enum(["file", "note", "message", "email", "contact", "call"])
|
|
189
|
+
.optional()
|
|
190
|
+
.describe("What kind of source this is. Default 'file' (a document/note). Use 'note' for ad-hoc text."),
|
|
191
|
+
source_id: z
|
|
192
|
+
.string()
|
|
193
|
+
.max(500)
|
|
194
|
+
.optional()
|
|
195
|
+
.describe(
|
|
196
|
+
"Optional stable id for the source so re-ingests of the SAME document group together (and can be removed later with mRAG_delete). Any string works — a file path, a case number, a checksum: a non-UUID is folded into a stable id derived from it, deterministically, and the original is kept as metadata.source_ref.",
|
|
197
|
+
),
|
|
198
|
+
thread_id: z.string().optional().describe("Optional thread id to associate this knowledge with (e.g. a dm:/chat: thread)."),
|
|
199
|
+
title: z.string().max(300).optional().describe("Optional human title, stored in metadata."),
|
|
200
|
+
// ── Graph + file-manager fields ────────────────────────────────────────────
|
|
201
|
+
// Added 2026-08-14. The backend (rag-index → enrichRagMetadata) has accepted all of these
|
|
202
|
+
// since 2026-07-19; THIS tool was the only ingest path that dropped them, so everything
|
|
203
|
+
// pushed through MCP landed with no parties and no event date — and therefore contributed
|
|
204
|
+
// NOTHING to mRAG_graph_*, which builds its nodes from exactly these fields. A corpus could
|
|
205
|
+
// be fully indexed and its graph still come back empty. See the note on the tool below.
|
|
206
|
+
sender: PartyArg.optional().describe(
|
|
207
|
+
"Who the document is FROM (author, filing party, sender). Becomes a node in the knowledge graph — without it this document adds no party to mRAG_graph_overview.",
|
|
208
|
+
),
|
|
209
|
+
recipient: PartyArg.optional().describe(
|
|
210
|
+
"Who the document is TO (addressee, court, counterparty). Becomes a node in the knowledge graph, connected to `sender`.",
|
|
211
|
+
),
|
|
212
|
+
occurred_at: z
|
|
213
|
+
.string()
|
|
214
|
+
.optional()
|
|
215
|
+
.describe("ISO-8601 timestamp of WHEN the document happened (letter date, filing date, email Date header) — not when you indexed it. Drives mRAG_graph_timeline; defaults to now if omitted, which makes a 2019 filing look like it happened today."),
|
|
216
|
+
direction: z
|
|
217
|
+
.enum(["in", "out", "self"])
|
|
218
|
+
.optional()
|
|
219
|
+
.describe("Direction relative to the account owner: received, sent, or the owner's own note."),
|
|
220
|
+
labels: z
|
|
221
|
+
.array(z.string().max(120))
|
|
222
|
+
.max(50)
|
|
223
|
+
.optional()
|
|
224
|
+
.describe("Free-text tags to attach (e.g. a case id, a jurisdiction) for later filtering."),
|
|
225
|
+
name: z
|
|
226
|
+
.string()
|
|
227
|
+
.max(400)
|
|
228
|
+
.optional()
|
|
229
|
+
.describe("Original filename, if this came from a file (e.g. 'pozew-2019-03-11.pdf'). Its extension is what classifies the row as a document/image/audio in the file view. Distinct from `title`, which is free prose."),
|
|
230
|
+
mime: z.string().max(200).optional().describe("MIME type of the original file, if known."),
|
|
231
|
+
size: z.number().int().nonnegative().optional().describe("Size of the original file in bytes, if known."),
|
|
232
|
+
metadata: z
|
|
233
|
+
.record(z.string(), z.unknown())
|
|
234
|
+
.optional()
|
|
235
|
+
.describe("Any extra fields to store alongside the row (case id, docket number, jurisdiction, file path, checksum, sensitivity flag…). Stored verbatim and returned with search hits. NOTE: this is stored server-side in plaintext like the content itself."),
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
async function mRAG_ingest(
|
|
239
|
+
input: z.infer<typeof mRAG_ingest_input>,
|
|
240
|
+
ctx: MosaddToolContext,
|
|
241
|
+
): Promise<{ indexed: number; chunk_count: number }> {
|
|
242
|
+
readSupabaseEnv();
|
|
243
|
+
// rag-index accepts a fixed source_type set; map "note" → "file".
|
|
244
|
+
const backendType = input.source_type === "note" ? "file" : (input.source_type ?? "file");
|
|
245
|
+
ctx.log("debug", "mRAG_ingest via rag-index", {
|
|
246
|
+
source_type: backendType,
|
|
247
|
+
has_parties: Boolean(input.sender || input.recipient),
|
|
248
|
+
has_occurred_at: Boolean(input.occurred_at),
|
|
249
|
+
});
|
|
250
|
+
// The enrichment fields are TOP-LEVEL on the rag-index request, not inside `metadata` — the
|
|
251
|
+
// function destructures them by name and hands them to enrichRagMetadata, which is what stamps
|
|
252
|
+
// metadata.sender / .recipient / .occurred_at in the canonical shape kg_refresh_me reads.
|
|
253
|
+
// Passing them inside `metadata` would land them via `passthrough` and happen to work today,
|
|
254
|
+
// but it would bypass the canonical stamping (and its `sender.ref` validation) — so send them
|
|
255
|
+
// where the contract says they go. Undefined keys are omitted rather than sent as null, so a
|
|
256
|
+
// caller that passes none produces byte-identical requests to before this change.
|
|
257
|
+
const rawSourceId = input.source_id?.trim() || null;
|
|
258
|
+
const sourceId = rawSourceId && !UUID_RE.test(rawSourceId) ? uuidV5(rawSourceId, SOURCE_ID_NAMESPACE) : rawSourceId;
|
|
259
|
+
const data = await invokeFunction<{ indexed?: number; chunk_count?: number }>("rag-index", {
|
|
260
|
+
source_type: backendType,
|
|
261
|
+
source_id: sourceId,
|
|
262
|
+
thread_id: input.thread_id ?? null,
|
|
263
|
+
content_text: input.content_text,
|
|
264
|
+
...(input.sender ? { sender: input.sender } : {}),
|
|
265
|
+
...(input.recipient ? { recipient: input.recipient } : {}),
|
|
266
|
+
...(input.occurred_at ? { occurred_at: input.occurred_at } : {}),
|
|
267
|
+
...(input.direction ? { direction: input.direction } : {}),
|
|
268
|
+
...(input.labels?.length ? { labels: input.labels } : {}),
|
|
269
|
+
...(input.name ? { name: input.name } : {}),
|
|
270
|
+
...(input.mime ? { mime: input.mime } : {}),
|
|
271
|
+
...(typeof input.size === "number" ? { size: input.size } : {}),
|
|
272
|
+
metadata: {
|
|
273
|
+
...(input.metadata ?? {}),
|
|
274
|
+
...(input.title ? { title: input.title } : {}),
|
|
275
|
+
// Only when we actually rewrote it — a caller that passed a real UUID sees no extra key.
|
|
276
|
+
...(rawSourceId && rawSourceId !== sourceId ? { source_ref: rawSourceId } : {}),
|
|
277
|
+
ingested_via: "mRAG_ingest",
|
|
278
|
+
},
|
|
279
|
+
});
|
|
280
|
+
return { indexed: data.indexed ?? 0, chunk_count: data.chunk_count ?? 0 };
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const mRAG_list_sources_input = z.object({});
|
|
284
|
+
|
|
285
|
+
interface RagSourceEntry {
|
|
286
|
+
source_type: string;
|
|
287
|
+
source_id: string | null;
|
|
288
|
+
thread_id: string | null;
|
|
289
|
+
title: string | null;
|
|
290
|
+
chunks: number;
|
|
291
|
+
first_indexed: string;
|
|
292
|
+
last_indexed: string;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async function mRAG_list_sources(
|
|
296
|
+
_input: z.infer<typeof mRAG_list_sources_input>,
|
|
297
|
+
ctx: MosaddToolContext,
|
|
298
|
+
): Promise<{ sources: RagSourceEntry[]; total_sources: number; total_chunks: number }> {
|
|
299
|
+
readSupabaseEnv();
|
|
300
|
+
ctx.log("debug", "mRAG_list_sources via rag-sources");
|
|
301
|
+
return await invokeFunction("rag-sources", { action: "list" });
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const mRAG_delete_input = z
|
|
305
|
+
.object({
|
|
306
|
+
source_id: z.string().optional().describe("Delete every indexed chunk with this source_id (from mRAG_list_sources)."),
|
|
307
|
+
thread_id: z.string().optional().describe("Delete every indexed chunk associated with this thread_id."),
|
|
308
|
+
})
|
|
309
|
+
.refine((v) => v.source_id || v.thread_id, {
|
|
310
|
+
message: "Provide source_id or thread_id — mRAG_delete refuses to purge the whole index.",
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
async function mRAG_delete(
|
|
314
|
+
input: z.infer<typeof mRAG_delete_input>,
|
|
315
|
+
ctx: MosaddToolContext,
|
|
316
|
+
): Promise<{ ok: true; deleted: number; source_id: string | null; thread_id: string | null }> {
|
|
317
|
+
readSupabaseEnv();
|
|
318
|
+
// ⛔ TĘ SAMĄ FUNKCJĘ MUSI PRZEJŚĆ KASOWANIE, CO INDEKSOWANIE (2026-08-28).
|
|
319
|
+
//
|
|
320
|
+
// `mRAG_ingest` foldował nie-UUID przez `uuidV5`, a `mRAG_delete` wysyłał SUROWY napis prosto do
|
|
321
|
+
// kolumny UUID — więc `rag-sources` odpowiadał `500: invalid input syntax for type uuid`.
|
|
322
|
+
// Skutek: dokument zaindeksowany pod naturalnym kluczem (numer sprawy, ścieżka pliku, threadId
|
|
323
|
+
// Gmaila) dawało się dodać, ale **NIGDY nie dawało się go usunąć tym samym identyfikatorem**.
|
|
324
|
+
// Dwie połowy tej samej rury nie zgadzały się ze sobą.
|
|
325
|
+
//
|
|
326
|
+
// I nie jest to niedopatrzenie w cieniu: komentarz przy foldowaniu (linie 30-37) obiecuje wprost
|
|
327
|
+
// „so grouping and mRAG_delete keep working on natural keys", a opis narzędzia mówi userowi
|
|
328
|
+
// „can later be removed with mRAG_delete". Obietnica była w dwóch miejscach, implementacja
|
|
329
|
+
// w jednym. Zmierzone na żywo: ingest `DIAG-…-a1b2c3` → indexed 1; delete tego samego id → 500.
|
|
330
|
+
//
|
|
331
|
+
// Boli to najbardziej przy korpusie, bo tam naturalne klucze są jedynym sposobem na dedup przy
|
|
332
|
+
// ponownym wczytaniu — a Dyspozytor mieli akta właśnie tak.
|
|
333
|
+
const rawId = input.source_id?.trim() || null;
|
|
334
|
+
const sourceId = rawId && !UUID_RE.test(rawId) ? uuidV5(rawId, SOURCE_ID_NAMESPACE) : rawId;
|
|
335
|
+
ctx.log("debug", "mRAG_delete via rag-sources", { source_id: sourceId, source_ref: rawId, thread_id: input.thread_id });
|
|
336
|
+
return await invokeFunction("rag-sources", {
|
|
337
|
+
action: "delete",
|
|
338
|
+
source_id: sourceId,
|
|
339
|
+
thread_id: input.thread_id ?? null,
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
export const knowledgeTools: MosaddTool[] = [
|
|
344
|
+
{
|
|
345
|
+
name: "mRAG_ingest",
|
|
346
|
+
title: "Ingest into memory",
|
|
347
|
+
annotations: { readOnlyHint: false },
|
|
348
|
+
requires: "network",
|
|
349
|
+
description:
|
|
350
|
+
"Add text to the USER'S OWN private knowledge base so mRAG_search can recall it later. Pass content_text (a note, document, transcript, pasted page); it is semantically chunked, embedded (1536-d) and stored in the per-user vector index mRAG_search reads. Returns how many chunks were indexed. ⚠ IF YOU ARE INDEXING A CORPUS you want to TRAVERSE (who is connected to whom, when), also pass sender / recipient / occurred_at: the knowledge graph builds its nodes from those fields alone, so documents ingested without them are searchable but contribute NOTHING to mRAG_graph_overview / _neighbors / _timeline — the graph comes back empty however many documents you loaded. Reuse the same party `ref` across documents to merge them into one node. NOTE: indexed content and metadata are stored server-side in plaintext — NOT covered by the zero-knowledge / E2EE guarantee. Only ingest what the user opted to make searchable.",
|
|
351
|
+
inputSchema: mRAG_ingest_input,
|
|
352
|
+
handler: mRAG_ingest as MosaddTool["handler"],
|
|
353
|
+
},
|
|
354
|
+
{
|
|
355
|
+
name: "mRAG_search",
|
|
356
|
+
title: "Search memory",
|
|
357
|
+
annotations: { readOnlyHint: true },
|
|
358
|
+
requires: "network",
|
|
359
|
+
description:
|
|
360
|
+
"Search and answer questions over the USER'S OWN mosadd data (messages, emails, calls, notes) with a private per-user RAG index — hybrid vector + keyword retrieval, reranked, grounded in cited sources (no fabrication). Use it to recall 'what did X say about Y', summarize a thread, or pull facts the user has received. By DEFAULT (via MCP) it returns the ranked source snippets only (answer_mode retrieve_only): fast, no model call; `answer` is empty or a short status note starting with '[mRAG' that names the stages and their times. Pass answer:true to also get a generated answer grounded in those sources (slower, uses the model budget). If the vector stage runs out of time the call still succeeds: the sources come from a keyword fallback and the result carries partial:true, partial_reason and search_mode:'keyword' (never a silent empty list); `timing` and `stages` give the milliseconds of every stage. This is agent memory (mRAG = RAG over your own data) over the user's communications, available outside the mosadd app. NOTE: RAG requires content to be indexed server-side in plaintext, so anything searchable here is NOT covered b",
|
|
361
|
+
inputSchema: mRAG_search_input,
|
|
362
|
+
handler: mRAG_search as MosaddTool["handler"],
|
|
363
|
+
},
|
|
364
|
+
{
|
|
365
|
+
name: "mRAG_list_sources",
|
|
366
|
+
title: "List memory sources",
|
|
367
|
+
annotations: { readOnlyHint: true },
|
|
368
|
+
requires: "network",
|
|
369
|
+
description:
|
|
370
|
+
"List what is currently indexed in the user's private knowledge base, grouped by source (source_type, source_id, thread_id, title) with per-source chunk counts and first/last indexed timestamps. Use it to see what mRAG_search can recall, and to find a source_id to remove with mRAG_delete. Owner-scoped.",
|
|
371
|
+
inputSchema: mRAG_list_sources_input,
|
|
372
|
+
handler: mRAG_list_sources as MosaddTool["handler"],
|
|
373
|
+
},
|
|
374
|
+
{
|
|
375
|
+
name: "mRAG_delete",
|
|
376
|
+
title: "Delete memory source",
|
|
377
|
+
annotations: { destructiveHint: true },
|
|
378
|
+
requires: "network",
|
|
379
|
+
description:
|
|
380
|
+
"Remove indexed content from the user's knowledge base by source_id or thread_id (from mRAG_list_sources). Deletes every embedded chunk for that source so mRAG_search can no longer recall it. Requires source_id or thread_id (will not purge the whole index). Returns the number of chunks deleted. Owner-scoped.",
|
|
381
|
+
inputSchema: mRAG_delete_input,
|
|
382
|
+
handler: mRAG_delete as MosaddTool["handler"],
|
|
383
|
+
},
|
|
384
|
+
];
|