@lotargo/memory_plugin 1.1.5 → 1.1.7
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/README.md +133 -120
- package/mcp-server/admin/server.js +228 -228
- package/mcp-server/admin/snapshot.js +303 -303
- package/mcp-server/benchmarks/fetch_real_corpus.js +351 -351
- package/mcp-server/benchmarks/gpu_profile_benchmark.js +170 -0
- package/mcp-server/benchmarks/stress_ingestion.js +195 -193
- package/mcp-server/benchmarks/test_dual_layer.js +140 -140
- package/mcp-server/cli.js +293 -7
- package/mcp-server/config/config_manager.js +11 -7
- package/mcp-server/db/database.js +43 -43
- package/mcp-server/graph/graph_extractor.js +72 -72
- package/mcp-server/graph/knowledge_linker.js +102 -102
- package/mcp-server/index.js +454 -454
- package/mcp-server/ingest/chunker.js +337 -337
- package/mcp-server/ingest/exporter.js +80 -80
- package/mcp-server/ingest/normalizer.js +104 -104
- package/mcp-server/ingest/pipeline.js +22 -7
- package/mcp-server/ingest/sentence_segmenter.js +74 -74
- package/mcp-server/memory.js +72 -72
- package/mcp-server/ml/gpu_monitor.js +166 -0
- package/mcp-server/ml/model_manager.js +321 -17
- package/mcp-server/preinstall.js +44 -44
- package/mcp-server/retrieval/retriever.js +10 -5
- package/mcp-server/setup.js +148 -148
- package/mcp-server/storage/blob_store.js +62 -62
- package/opencode-plugin/index.js +244 -244
- package/package.json +58 -54
- package/skills/using-memory/SKILL.md +122 -122
package/mcp-server/index.js
CHANGED
|
@@ -1,454 +1,454 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
-
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
|
-
import * as z from "zod/v4";
|
|
5
|
-
import { ensureDir, readMemory, readMemoryRaw, writeMemory, today, MEMORY_DIR, GLOBAL_KEY, scopeKey, projectName } from "./memory.js";
|
|
6
|
-
|
|
7
|
-
const cliArgs = process.argv.slice(2);
|
|
8
|
-
|
|
9
|
-
if (cliArgs.includes("setup") || cliArgs.includes("install") || cliArgs.includes("--setup") || cliArgs.includes("-s")) {
|
|
10
|
-
const { runSetup } = await import("./setup.js");
|
|
11
|
-
await runSetup();
|
|
12
|
-
process.exit(0);
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
if (cliArgs.includes("admin") || cliArgs.includes("--admin") || cliArgs.includes("-a")) {
|
|
16
|
-
const { startAdminServer } = await import("./admin/server.js");
|
|
17
|
-
await startAdminServer();
|
|
18
|
-
// Keep process running for web server
|
|
19
|
-
await new Promise(() => {});
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
if (cliArgs.includes("cli") || cliArgs.includes("config") || cliArgs.includes("--cli") || cliArgs.includes("-c")) {
|
|
23
|
-
const { runCli } = await import("./cli.js");
|
|
24
|
-
await runCli();
|
|
25
|
-
process.exit(0);
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
await ensureDir();
|
|
29
|
-
|
|
30
|
-
const server = new McpServer({
|
|
31
|
-
name: "memory-agent",
|
|
32
|
-
version: "1.0.0",
|
|
33
|
-
});
|
|
34
|
-
|
|
35
|
-
// --- Legacy Key-Value Memory Tools ---
|
|
36
|
-
|
|
37
|
-
// --- Legacy Key-Value Memory Tools & Agent Graph Linking ---
|
|
38
|
-
|
|
39
|
-
server.registerTool(
|
|
40
|
-
"remember",
|
|
41
|
-
{
|
|
42
|
-
description:
|
|
43
|
-
"Save an important, durable fact to memory. Only use for high-signal information " +
|
|
44
|
-
"(name, goals, constraints, tech preferences, project conventions). " +
|
|
45
|
-
"Optionally link the fact to a Knowledge Base document or exact line range (docId, startLine, endLine). " +
|
|
46
|
-
"Translate the fact into English and keep it concise. " +
|
|
47
|
-
"scope: 'project' (default) or 'global'",
|
|
48
|
-
inputSchema: z.object({
|
|
49
|
-
fact: z.string().describe("The fact to remember, written in English"),
|
|
50
|
-
scope: z.string().default("project").describe("'project' (default) or 'global'"),
|
|
51
|
-
docId: z.string().optional().describe("Optional document ID, title, or path to link this fact to"),
|
|
52
|
-
startLine: z.number().optional().describe("Optional starting line number in target document"),
|
|
53
|
-
endLine: z.number().optional().describe("Optional ending line number in target document"),
|
|
54
|
-
relationType: z.string().default("LINKS_TO").describe("Relation type (e.g. 'RULES_FOR', 'IMPLEMENTS', 'REFERENCES')"),
|
|
55
|
-
}),
|
|
56
|
-
},
|
|
57
|
-
async ({ fact, scope, docId, startLine, endLine, relationType }) => {
|
|
58
|
-
const key = scopeKey(scope, null, null);
|
|
59
|
-
const entries = await readMemory(key);
|
|
60
|
-
const factNormalized = fact.toLowerCase().trim();
|
|
61
|
-
if (!entries.some((e) => {
|
|
62
|
-
const idx = e.indexOf("] ");
|
|
63
|
-
return idx !== -1 && e.slice(idx + 2).toLowerCase().trim() === factNormalized;
|
|
64
|
-
})) {
|
|
65
|
-
entries.push(`- [${today()}] ${fact}`);
|
|
66
|
-
await writeMemory(key, entries);
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
let linkInfo = "";
|
|
70
|
-
if (docId) {
|
|
71
|
-
const { linkFactToDocument } = await import("./graph/knowledge_linker.js");
|
|
72
|
-
try {
|
|
73
|
-
const linkRes = linkFactToDocument({
|
|
74
|
-
factKey: key,
|
|
75
|
-
factText: fact,
|
|
76
|
-
docId,
|
|
77
|
-
startLine,
|
|
78
|
-
endLine,
|
|
79
|
-
relationType,
|
|
80
|
-
});
|
|
81
|
-
const linesStr = startLine ? `:L${startLine}${endLine ? `-${endLine}` : ""}` : "";
|
|
82
|
-
linkInfo = ` [Linked to Doc: "${linkRes.docTitle}"${linesStr}]`;
|
|
83
|
-
} catch (err) {
|
|
84
|
-
linkInfo = ` (Note: Fact saved, but document link failed: ${err.message})`;
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
return { content: [{ type: "text", text: `Memory updated${linkInfo}` }] };
|
|
89
|
-
}
|
|
90
|
-
);
|
|
91
|
-
|
|
92
|
-
server.registerTool(
|
|
93
|
-
"recall",
|
|
94
|
-
{
|
|
95
|
-
description: "Show saved facts with any Agent-linked Knowledge Base documents/lines. scope: 'project', 'global', or 'all' (default)",
|
|
96
|
-
inputSchema: z.object({
|
|
97
|
-
scope: z.string().default("all").describe("'project', 'global', or 'all'"),
|
|
98
|
-
}),
|
|
99
|
-
},
|
|
100
|
-
async ({ scope }) => {
|
|
101
|
-
const project = projectName(null, null);
|
|
102
|
-
const { getLinksForFact } = await import("./graph/knowledge_linker.js");
|
|
103
|
-
const results = [];
|
|
104
|
-
|
|
105
|
-
const formatFactWithLinks = (factText, key) => {
|
|
106
|
-
let line = factText;
|
|
107
|
-
try {
|
|
108
|
-
const links = getLinksForFact(key, factText);
|
|
109
|
-
if (links && links.length > 0) {
|
|
110
|
-
const docStr = links
|
|
111
|
-
.map((l) => {
|
|
112
|
-
const range = l.start_line ? `:L${l.start_line}${l.end_line ? `-${l.end_line}` : ""}` : "";
|
|
113
|
-
return `${l.doc_title || l.doc_path}${range}`;
|
|
114
|
-
})
|
|
115
|
-
.join(", ");
|
|
116
|
-
line += ` 🔗 [Linked Docs: ${docStr}]`;
|
|
117
|
-
}
|
|
118
|
-
} catch (e) {}
|
|
119
|
-
return line;
|
|
120
|
-
};
|
|
121
|
-
|
|
122
|
-
if (scope !== "project") {
|
|
123
|
-
const global = await readMemoryRaw(GLOBAL_KEY);
|
|
124
|
-
if (global.length) {
|
|
125
|
-
results.push("--- Global ---");
|
|
126
|
-
global.forEach((e, i) => results.push(`${i + 1}. ${formatFactWithLinks(e, GLOBAL_KEY)}`));
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
if (scope !== "global") {
|
|
130
|
-
const local = await readMemoryRaw(project);
|
|
131
|
-
if (local.length) {
|
|
132
|
-
if (results.length) results.push("");
|
|
133
|
-
results.push(`--- ${project} ---`);
|
|
134
|
-
local.forEach((e, i) => results.push(`${i + 1}. ${formatFactWithLinks(e, project)}`));
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
const text = results.length ? results.join("\n") : "Memory is empty.";
|
|
138
|
-
return { content: [{ type: "text", text }] };
|
|
139
|
-
}
|
|
140
|
-
);
|
|
141
|
-
|
|
142
|
-
server.registerTool(
|
|
143
|
-
"forget",
|
|
144
|
-
{
|
|
145
|
-
description: "Delete a fact by number (from recall) or text search",
|
|
146
|
-
inputSchema: z.object({
|
|
147
|
-
query: z.string().describe("Number or text to search for"),
|
|
148
|
-
scope: z.string().default("project").describe("'project' (default) or 'global'"),
|
|
149
|
-
}),
|
|
150
|
-
},
|
|
151
|
-
async ({ query, scope }) => {
|
|
152
|
-
const key = scopeKey(scope, null, null);
|
|
153
|
-
const entries = await readMemory(key);
|
|
154
|
-
const num = parseInt(query, 10);
|
|
155
|
-
let removed;
|
|
156
|
-
if (!isNaN(num) && num > 0 && num <= entries.length) {
|
|
157
|
-
removed = entries.splice(num - 1, 1);
|
|
158
|
-
} else {
|
|
159
|
-
const filtered = entries.filter((e) => !e.toLowerCase().includes(query.toLowerCase()));
|
|
160
|
-
removed = entries.filter((e) => e.toLowerCase().includes(query.toLowerCase()));
|
|
161
|
-
entries.length = 0;
|
|
162
|
-
entries.push(...filtered);
|
|
163
|
-
}
|
|
164
|
-
await writeMemory(key, entries);
|
|
165
|
-
const text = removed.length ? "Memory updated" : "Not found.";
|
|
166
|
-
return { content: [{ type: "text", text }] };
|
|
167
|
-
}
|
|
168
|
-
);
|
|
169
|
-
|
|
170
|
-
server.registerTool(
|
|
171
|
-
"link_knowledge",
|
|
172
|
-
{
|
|
173
|
-
description:
|
|
174
|
-
"Explicitly link a Notebook memory fact to a Knowledge Base document, section, or line range. " +
|
|
175
|
-
"Creates Agent-driven Graph Edges connecting memory to RAG documents.",
|
|
176
|
-
inputSchema: z.object({
|
|
177
|
-
action: z.enum(["link", "list_links", "get_doc_links"]).default("link").describe("Action type"),
|
|
178
|
-
factText: z.string().optional().describe("Memory fact text or keyword"),
|
|
179
|
-
docId: z.string().optional().describe("Document ID, title, or file path"),
|
|
180
|
-
scope: z.string().default("project").describe("'project' (default) or 'global'"),
|
|
181
|
-
startLine: z.number().optional().describe("Starting line number in target document"),
|
|
182
|
-
endLine: z.number().optional().describe("Ending line number in target document"),
|
|
183
|
-
relationType: z.string().default("LINKS_TO").describe("Relation type (e.g. 'RULES_FOR', 'IMPLEMENTS', 'EXPLAINS')"),
|
|
184
|
-
}),
|
|
185
|
-
},
|
|
186
|
-
async ({ action, factText, docId, scope, startLine, endLine, relationType }) => {
|
|
187
|
-
const { linkFactToDocument, getLinksForDoc, listAllLinks } = await import("./graph/knowledge_linker.js");
|
|
188
|
-
const key = scopeKey(scope, null, null);
|
|
189
|
-
|
|
190
|
-
if (action === "link") {
|
|
191
|
-
if (!factText || !docId) {
|
|
192
|
-
throw new Error("factText and docId are required parameters for link action");
|
|
193
|
-
}
|
|
194
|
-
const res = linkFactToDocument({
|
|
195
|
-
factKey: key,
|
|
196
|
-
factText,
|
|
197
|
-
docId,
|
|
198
|
-
startLine,
|
|
199
|
-
endLine,
|
|
200
|
-
relationType,
|
|
201
|
-
});
|
|
202
|
-
return {
|
|
203
|
-
content: [{ type: "text", text: JSON.stringify(res, null, 2) }],
|
|
204
|
-
};
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
if (action === "get_doc_links") {
|
|
208
|
-
if (!docId) throw new Error("docId parameter is required for get_doc_links action");
|
|
209
|
-
const links = getLinksForDoc(docId);
|
|
210
|
-
return {
|
|
211
|
-
content: [{ type: "text", text: JSON.stringify(links, null, 2) }],
|
|
212
|
-
};
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
if (action === "list_links") {
|
|
216
|
-
const links = listAllLinks(key);
|
|
217
|
-
return {
|
|
218
|
-
content: [{ type: "text", text: JSON.stringify(links, null, 2) }],
|
|
219
|
-
};
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
throw new Error(`Unknown action: ${action}`);
|
|
223
|
-
}
|
|
224
|
-
);
|
|
225
|
-
|
|
226
|
-
// --- Hybrid RAG Knowledge Engine Tools ---
|
|
227
|
-
|
|
228
|
-
server.registerTool(
|
|
229
|
-
"ingest_document",
|
|
230
|
-
{
|
|
231
|
-
description:
|
|
232
|
-
"Ingest a document into the RAG knowledge base. " +
|
|
233
|
-
"Accepts local file paths, web URLs, or raw Markdown/text content. " +
|
|
234
|
-
"Processes document through 3-tier hierarchy chunking (Big/Medium/Small), " +
|
|
235
|
-
"computes dense vectors, and extracts GraphRAG code symbols.",
|
|
236
|
-
inputSchema: z.object({
|
|
237
|
-
content: z.string().describe("Raw text content, file path, or web URL"),
|
|
238
|
-
type: z.enum(["text", "file", "url"]).default("text").describe("Input content type"),
|
|
239
|
-
title: z.string().optional().describe("Document title"),
|
|
240
|
-
path: z.string().optional().describe("Original document file path"),
|
|
241
|
-
generateEmbeddings: z.boolean().default(true).describe("Compute dense vector embeddings"),
|
|
242
|
-
}),
|
|
243
|
-
},
|
|
244
|
-
async ({ content, type, title, path, generateEmbeddings }) => {
|
|
245
|
-
const { ingestDocument } = await import("./ingest/pipeline.js");
|
|
246
|
-
const result = await ingestDocument({
|
|
247
|
-
content,
|
|
248
|
-
type,
|
|
249
|
-
title: title || null,
|
|
250
|
-
path: path || null,
|
|
251
|
-
generateEmbeddings,
|
|
252
|
-
});
|
|
253
|
-
return {
|
|
254
|
-
content: [
|
|
255
|
-
{
|
|
256
|
-
type: "text",
|
|
257
|
-
text: JSON.stringify(
|
|
258
|
-
{
|
|
259
|
-
status: "success",
|
|
260
|
-
docId: result.docId,
|
|
261
|
-
title: result.title,
|
|
262
|
-
sectionsCount: result.sectionsCount,
|
|
263
|
-
microChunksCount: result.microChunksCount,
|
|
264
|
-
deduplicated: result.deduplicated,
|
|
265
|
-
},
|
|
266
|
-
null,
|
|
267
|
-
2
|
|
268
|
-
),
|
|
269
|
-
},
|
|
270
|
-
],
|
|
271
|
-
};
|
|
272
|
-
}
|
|
273
|
-
);
|
|
274
|
-
|
|
275
|
-
server.registerTool(
|
|
276
|
-
"query_knowledge_base",
|
|
277
|
-
{
|
|
278
|
-
description:
|
|
279
|
-
"Perform hybrid search (RSF/RRF BM25 full-text + dense vector similarity) across the RAG knowledge base. " +
|
|
280
|
-
"Returns top-ranked candidate document sections with breadcrumbs, GraphRAG defined code symbols, and relevance scores.",
|
|
281
|
-
inputSchema: z.object({
|
|
282
|
-
query: z.string().describe("Search query in natural language or symbol name"),
|
|
283
|
-
limit: z.number().default(5).describe("Maximum number of sections to return"),
|
|
284
|
-
instruction: z
|
|
285
|
-
.string()
|
|
286
|
-
.optional()
|
|
287
|
-
.describe(
|
|
288
|
-
"Optional task-specific retrieval instruction shaping embedding focus (e.g. 'Retrieve code snippets', 'Find user preferences'). " +
|
|
289
|
-
"Recommended when using E5/BGE models for domain-specific queries."
|
|
290
|
-
),
|
|
291
|
-
generateEmbeddings: z.boolean().default(true).describe("Use vector search alongside BM25"),
|
|
292
|
-
}),
|
|
293
|
-
},
|
|
294
|
-
async ({ query, limit, instruction, generateEmbeddings }) => {
|
|
295
|
-
const { hybridQuery } = await import("./retrieval/retriever.js");
|
|
296
|
-
const { getConfig } = await import("./config/config_manager.js");
|
|
297
|
-
const activeConfig = getConfig();
|
|
298
|
-
|
|
299
|
-
const results = await hybridQuery({
|
|
300
|
-
query,
|
|
301
|
-
limit,
|
|
302
|
-
generateEmbeddings,
|
|
303
|
-
instruction: instruction || null,
|
|
304
|
-
});
|
|
305
|
-
|
|
306
|
-
if (!results || results.length === 0) {
|
|
307
|
-
return {
|
|
308
|
-
content: [
|
|
309
|
-
{
|
|
310
|
-
type: "text",
|
|
311
|
-
text: `[Active Model: ${activeConfig.embeddingModel}]\nNo matching knowledge found for query.`,
|
|
312
|
-
},
|
|
313
|
-
],
|
|
314
|
-
};
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
const headerNote = `[Active Model: ${activeConfig.embeddingModel} | Fusion: ${activeConfig.fusionAlgorithm.toUpperCase()}]\n\n`;
|
|
318
|
-
|
|
319
|
-
const formatted = results
|
|
320
|
-
.map((r, i) => {
|
|
321
|
-
let header = `### [${i + 1}] ${r.doc_title || "Untitled"}`;
|
|
322
|
-
if (r.heading) header += ` > ${r.heading}`;
|
|
323
|
-
if (r.breadcrumbs) header += ` (${r.breadcrumbs})`;
|
|
324
|
-
let body = `Score: ${(r.score || 0).toFixed(4)}\n`;
|
|
325
|
-
if (r.defined_symbols && r.defined_symbols.length > 0) {
|
|
326
|
-
body += `Defined Symbols: ${r.defined_symbols.join(", ")}\n`;
|
|
327
|
-
}
|
|
328
|
-
body += `\n${r.snippet || r.full_section_content || ""}`;
|
|
329
|
-
return `${header}\n${body}`;
|
|
330
|
-
})
|
|
331
|
-
.join("\n\n---\n\n");
|
|
332
|
-
|
|
333
|
-
return { content: [{ type: "text", text: headerNote + formatted }] };
|
|
334
|
-
}
|
|
335
|
-
);
|
|
336
|
-
|
|
337
|
-
server.registerTool(
|
|
338
|
-
"manage_knowledge_base",
|
|
339
|
-
{
|
|
340
|
-
description:
|
|
341
|
-
"Manage the RAG knowledge base: inspect stats, list documents, read full raw document, delete documents, or export/import snapshots.",
|
|
342
|
-
inputSchema: z.object({
|
|
343
|
-
action: z.enum(["stats", "list", "read_document", "delete", "export_snapshot", "import_snapshot"]).describe("Management action"),
|
|
344
|
-
docId: z.string().optional().describe("Document ID, title, or path (required for read_document and delete)"),
|
|
345
|
-
snapshotPath: z.string().optional().describe("File path for snapshot export/import"),
|
|
346
|
-
}),
|
|
347
|
-
},
|
|
348
|
-
async ({ action, docId, snapshotPath }) => {
|
|
349
|
-
const { getDatabase } = await import("./db/database.js");
|
|
350
|
-
const db = getDatabase();
|
|
351
|
-
|
|
352
|
-
if (action === "stats") {
|
|
353
|
-
const docCount = db.prepare("SELECT COUNT(*) as cnt FROM documents").get().cnt;
|
|
354
|
-
const secCount = db.prepare("SELECT COUNT(*) as cnt FROM sections").get().cnt;
|
|
355
|
-
const chunkCount = db.prepare("SELECT COUNT(*) as cnt FROM micro_chunks").get().cnt;
|
|
356
|
-
const edgeCount = db.prepare("SELECT COUNT(*) as cnt FROM graph_edges").get().cnt;
|
|
357
|
-
return {
|
|
358
|
-
content: [
|
|
359
|
-
{
|
|
360
|
-
type: "text",
|
|
361
|
-
text: JSON.stringify(
|
|
362
|
-
{
|
|
363
|
-
documents: docCount,
|
|
364
|
-
sections: secCount,
|
|
365
|
-
micro_chunks: chunkCount,
|
|
366
|
-
graph_edges: edgeCount,
|
|
367
|
-
},
|
|
368
|
-
null,
|
|
369
|
-
2
|
|
370
|
-
),
|
|
371
|
-
},
|
|
372
|
-
],
|
|
373
|
-
};
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
if (action === "list") {
|
|
377
|
-
const docs = db
|
|
378
|
-
.prepare("SELECT id, title, path, blob_hash, created_at FROM documents ORDER BY created_at DESC")
|
|
379
|
-
.all();
|
|
380
|
-
return {
|
|
381
|
-
content: [{ type: "text", text: JSON.stringify(docs, null, 2) }],
|
|
382
|
-
};
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
if (action === "read_document") {
|
|
386
|
-
if (!docId) throw new Error("docId parameter is required for read_document action");
|
|
387
|
-
const doc = db
|
|
388
|
-
.prepare("SELECT id, title, path, blob_hash, created_at FROM documents WHERE id = ? OR path = ? OR title = ?")
|
|
389
|
-
.get(docId, docId, docId);
|
|
390
|
-
if (!doc) {
|
|
391
|
-
throw new Error(`Document not found in knowledge base for docId: ${docId}`);
|
|
392
|
-
}
|
|
393
|
-
const { readBlob } = await import("./storage/blob_store.js");
|
|
394
|
-
const rawContent = await readBlob(doc.blob_hash);
|
|
395
|
-
return {
|
|
396
|
-
content: [
|
|
397
|
-
{
|
|
398
|
-
type: "text",
|
|
399
|
-
text: JSON.stringify(
|
|
400
|
-
{
|
|
401
|
-
id: doc.id,
|
|
402
|
-
title: doc.title,
|
|
403
|
-
path: doc.path,
|
|
404
|
-
created_at: doc.created_at,
|
|
405
|
-
content: rawContent,
|
|
406
|
-
},
|
|
407
|
-
null,
|
|
408
|
-
2
|
|
409
|
-
),
|
|
410
|
-
},
|
|
411
|
-
],
|
|
412
|
-
};
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
if (action === "delete") {
|
|
416
|
-
if (!docId) throw new Error("docId parameter is required for delete action");
|
|
417
|
-
const { deleteDocument } = await import("./ingest/pipeline.js");
|
|
418
|
-
const result = await deleteDocument(docId, db);
|
|
419
|
-
return {
|
|
420
|
-
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
421
|
-
};
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
if (action === "export_snapshot") {
|
|
425
|
-
const { exportSnapshot } = await import("./admin/snapshot.js");
|
|
426
|
-
const result = await exportSnapshot({ customDb: db, outputPath: snapshotPath || null });
|
|
427
|
-
return {
|
|
428
|
-
content: [
|
|
429
|
-
{
|
|
430
|
-
type: "text",
|
|
431
|
-
text: snapshotPath
|
|
432
|
-
? `Snapshot exported successfully to ${snapshotPath}`
|
|
433
|
-
: JSON.stringify(result, null, 2),
|
|
434
|
-
},
|
|
435
|
-
],
|
|
436
|
-
};
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
if (action === "import_snapshot") {
|
|
440
|
-
if (!snapshotPath) throw new Error("snapshotPath parameter is required for import_snapshot action");
|
|
441
|
-
const { importSnapshot } = await import("./admin/snapshot.js");
|
|
442
|
-
const result = await importSnapshot({ customDb: db, snapshotPathOrData: snapshotPath });
|
|
443
|
-
return {
|
|
444
|
-
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
445
|
-
};
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
throw new Error(`Unknown action: ${action}`);
|
|
449
|
-
}
|
|
450
|
-
);
|
|
451
|
-
|
|
452
|
-
const transport = new StdioServerTransport();
|
|
453
|
-
await server.connect(transport);
|
|
454
|
-
console.error(`memory-agent MCP server running, data dir: ${MEMORY_DIR}`);
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
|
+
import * as z from "zod/v4";
|
|
5
|
+
import { ensureDir, readMemory, readMemoryRaw, writeMemory, today, MEMORY_DIR, GLOBAL_KEY, scopeKey, projectName } from "./memory.js";
|
|
6
|
+
|
|
7
|
+
const cliArgs = process.argv.slice(2);
|
|
8
|
+
|
|
9
|
+
if (cliArgs.includes("setup") || cliArgs.includes("install") || cliArgs.includes("--setup") || cliArgs.includes("-s")) {
|
|
10
|
+
const { runSetup } = await import("./setup.js");
|
|
11
|
+
await runSetup();
|
|
12
|
+
process.exit(0);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
if (cliArgs.includes("admin") || cliArgs.includes("--admin") || cliArgs.includes("-a")) {
|
|
16
|
+
const { startAdminServer } = await import("./admin/server.js");
|
|
17
|
+
await startAdminServer();
|
|
18
|
+
// Keep process running for web server
|
|
19
|
+
await new Promise(() => {});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (cliArgs.includes("cli") || cliArgs.includes("config") || cliArgs.includes("--cli") || cliArgs.includes("-c")) {
|
|
23
|
+
const { runCli } = await import("./cli.js");
|
|
24
|
+
await runCli();
|
|
25
|
+
process.exit(0);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
await ensureDir();
|
|
29
|
+
|
|
30
|
+
const server = new McpServer({
|
|
31
|
+
name: "memory-agent",
|
|
32
|
+
version: "1.0.0",
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
// --- Legacy Key-Value Memory Tools ---
|
|
36
|
+
|
|
37
|
+
// --- Legacy Key-Value Memory Tools & Agent Graph Linking ---
|
|
38
|
+
|
|
39
|
+
server.registerTool(
|
|
40
|
+
"remember",
|
|
41
|
+
{
|
|
42
|
+
description:
|
|
43
|
+
"Save an important, durable fact to memory. Only use for high-signal information " +
|
|
44
|
+
"(name, goals, constraints, tech preferences, project conventions). " +
|
|
45
|
+
"Optionally link the fact to a Knowledge Base document or exact line range (docId, startLine, endLine). " +
|
|
46
|
+
"Translate the fact into English and keep it concise. " +
|
|
47
|
+
"scope: 'project' (default) or 'global'",
|
|
48
|
+
inputSchema: z.object({
|
|
49
|
+
fact: z.string().describe("The fact to remember, written in English"),
|
|
50
|
+
scope: z.string().default("project").describe("'project' (default) or 'global'"),
|
|
51
|
+
docId: z.string().optional().describe("Optional document ID, title, or path to link this fact to"),
|
|
52
|
+
startLine: z.number().optional().describe("Optional starting line number in target document"),
|
|
53
|
+
endLine: z.number().optional().describe("Optional ending line number in target document"),
|
|
54
|
+
relationType: z.string().default("LINKS_TO").describe("Relation type (e.g. 'RULES_FOR', 'IMPLEMENTS', 'REFERENCES')"),
|
|
55
|
+
}),
|
|
56
|
+
},
|
|
57
|
+
async ({ fact, scope, docId, startLine, endLine, relationType }) => {
|
|
58
|
+
const key = scopeKey(scope, null, null);
|
|
59
|
+
const entries = await readMemory(key);
|
|
60
|
+
const factNormalized = fact.toLowerCase().trim();
|
|
61
|
+
if (!entries.some((e) => {
|
|
62
|
+
const idx = e.indexOf("] ");
|
|
63
|
+
return idx !== -1 && e.slice(idx + 2).toLowerCase().trim() === factNormalized;
|
|
64
|
+
})) {
|
|
65
|
+
entries.push(`- [${today()}] ${fact}`);
|
|
66
|
+
await writeMemory(key, entries);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
let linkInfo = "";
|
|
70
|
+
if (docId) {
|
|
71
|
+
const { linkFactToDocument } = await import("./graph/knowledge_linker.js");
|
|
72
|
+
try {
|
|
73
|
+
const linkRes = linkFactToDocument({
|
|
74
|
+
factKey: key,
|
|
75
|
+
factText: fact,
|
|
76
|
+
docId,
|
|
77
|
+
startLine,
|
|
78
|
+
endLine,
|
|
79
|
+
relationType,
|
|
80
|
+
});
|
|
81
|
+
const linesStr = startLine ? `:L${startLine}${endLine ? `-${endLine}` : ""}` : "";
|
|
82
|
+
linkInfo = ` [Linked to Doc: "${linkRes.docTitle}"${linesStr}]`;
|
|
83
|
+
} catch (err) {
|
|
84
|
+
linkInfo = ` (Note: Fact saved, but document link failed: ${err.message})`;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return { content: [{ type: "text", text: `Memory updated${linkInfo}` }] };
|
|
89
|
+
}
|
|
90
|
+
);
|
|
91
|
+
|
|
92
|
+
server.registerTool(
|
|
93
|
+
"recall",
|
|
94
|
+
{
|
|
95
|
+
description: "Show saved facts with any Agent-linked Knowledge Base documents/lines. scope: 'project', 'global', or 'all' (default)",
|
|
96
|
+
inputSchema: z.object({
|
|
97
|
+
scope: z.string().default("all").describe("'project', 'global', or 'all'"),
|
|
98
|
+
}),
|
|
99
|
+
},
|
|
100
|
+
async ({ scope }) => {
|
|
101
|
+
const project = projectName(null, null);
|
|
102
|
+
const { getLinksForFact } = await import("./graph/knowledge_linker.js");
|
|
103
|
+
const results = [];
|
|
104
|
+
|
|
105
|
+
const formatFactWithLinks = (factText, key) => {
|
|
106
|
+
let line = factText;
|
|
107
|
+
try {
|
|
108
|
+
const links = getLinksForFact(key, factText);
|
|
109
|
+
if (links && links.length > 0) {
|
|
110
|
+
const docStr = links
|
|
111
|
+
.map((l) => {
|
|
112
|
+
const range = l.start_line ? `:L${l.start_line}${l.end_line ? `-${l.end_line}` : ""}` : "";
|
|
113
|
+
return `${l.doc_title || l.doc_path}${range}`;
|
|
114
|
+
})
|
|
115
|
+
.join(", ");
|
|
116
|
+
line += ` 🔗 [Linked Docs: ${docStr}]`;
|
|
117
|
+
}
|
|
118
|
+
} catch (e) {}
|
|
119
|
+
return line;
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
if (scope !== "project") {
|
|
123
|
+
const global = await readMemoryRaw(GLOBAL_KEY);
|
|
124
|
+
if (global.length) {
|
|
125
|
+
results.push("--- Global ---");
|
|
126
|
+
global.forEach((e, i) => results.push(`${i + 1}. ${formatFactWithLinks(e, GLOBAL_KEY)}`));
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
if (scope !== "global") {
|
|
130
|
+
const local = await readMemoryRaw(project);
|
|
131
|
+
if (local.length) {
|
|
132
|
+
if (results.length) results.push("");
|
|
133
|
+
results.push(`--- ${project} ---`);
|
|
134
|
+
local.forEach((e, i) => results.push(`${i + 1}. ${formatFactWithLinks(e, project)}`));
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
const text = results.length ? results.join("\n") : "Memory is empty.";
|
|
138
|
+
return { content: [{ type: "text", text }] };
|
|
139
|
+
}
|
|
140
|
+
);
|
|
141
|
+
|
|
142
|
+
server.registerTool(
|
|
143
|
+
"forget",
|
|
144
|
+
{
|
|
145
|
+
description: "Delete a fact by number (from recall) or text search",
|
|
146
|
+
inputSchema: z.object({
|
|
147
|
+
query: z.string().describe("Number or text to search for"),
|
|
148
|
+
scope: z.string().default("project").describe("'project' (default) or 'global'"),
|
|
149
|
+
}),
|
|
150
|
+
},
|
|
151
|
+
async ({ query, scope }) => {
|
|
152
|
+
const key = scopeKey(scope, null, null);
|
|
153
|
+
const entries = await readMemory(key);
|
|
154
|
+
const num = parseInt(query, 10);
|
|
155
|
+
let removed;
|
|
156
|
+
if (!isNaN(num) && num > 0 && num <= entries.length) {
|
|
157
|
+
removed = entries.splice(num - 1, 1);
|
|
158
|
+
} else {
|
|
159
|
+
const filtered = entries.filter((e) => !e.toLowerCase().includes(query.toLowerCase()));
|
|
160
|
+
removed = entries.filter((e) => e.toLowerCase().includes(query.toLowerCase()));
|
|
161
|
+
entries.length = 0;
|
|
162
|
+
entries.push(...filtered);
|
|
163
|
+
}
|
|
164
|
+
await writeMemory(key, entries);
|
|
165
|
+
const text = removed.length ? "Memory updated" : "Not found.";
|
|
166
|
+
return { content: [{ type: "text", text }] };
|
|
167
|
+
}
|
|
168
|
+
);
|
|
169
|
+
|
|
170
|
+
server.registerTool(
|
|
171
|
+
"link_knowledge",
|
|
172
|
+
{
|
|
173
|
+
description:
|
|
174
|
+
"Explicitly link a Notebook memory fact to a Knowledge Base document, section, or line range. " +
|
|
175
|
+
"Creates Agent-driven Graph Edges connecting memory to RAG documents.",
|
|
176
|
+
inputSchema: z.object({
|
|
177
|
+
action: z.enum(["link", "list_links", "get_doc_links"]).default("link").describe("Action type"),
|
|
178
|
+
factText: z.string().optional().describe("Memory fact text or keyword"),
|
|
179
|
+
docId: z.string().optional().describe("Document ID, title, or file path"),
|
|
180
|
+
scope: z.string().default("project").describe("'project' (default) or 'global'"),
|
|
181
|
+
startLine: z.number().optional().describe("Starting line number in target document"),
|
|
182
|
+
endLine: z.number().optional().describe("Ending line number in target document"),
|
|
183
|
+
relationType: z.string().default("LINKS_TO").describe("Relation type (e.g. 'RULES_FOR', 'IMPLEMENTS', 'EXPLAINS')"),
|
|
184
|
+
}),
|
|
185
|
+
},
|
|
186
|
+
async ({ action, factText, docId, scope, startLine, endLine, relationType }) => {
|
|
187
|
+
const { linkFactToDocument, getLinksForDoc, listAllLinks } = await import("./graph/knowledge_linker.js");
|
|
188
|
+
const key = scopeKey(scope, null, null);
|
|
189
|
+
|
|
190
|
+
if (action === "link") {
|
|
191
|
+
if (!factText || !docId) {
|
|
192
|
+
throw new Error("factText and docId are required parameters for link action");
|
|
193
|
+
}
|
|
194
|
+
const res = linkFactToDocument({
|
|
195
|
+
factKey: key,
|
|
196
|
+
factText,
|
|
197
|
+
docId,
|
|
198
|
+
startLine,
|
|
199
|
+
endLine,
|
|
200
|
+
relationType,
|
|
201
|
+
});
|
|
202
|
+
return {
|
|
203
|
+
content: [{ type: "text", text: JSON.stringify(res, null, 2) }],
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
if (action === "get_doc_links") {
|
|
208
|
+
if (!docId) throw new Error("docId parameter is required for get_doc_links action");
|
|
209
|
+
const links = getLinksForDoc(docId);
|
|
210
|
+
return {
|
|
211
|
+
content: [{ type: "text", text: JSON.stringify(links, null, 2) }],
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
if (action === "list_links") {
|
|
216
|
+
const links = listAllLinks(key);
|
|
217
|
+
return {
|
|
218
|
+
content: [{ type: "text", text: JSON.stringify(links, null, 2) }],
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
throw new Error(`Unknown action: ${action}`);
|
|
223
|
+
}
|
|
224
|
+
);
|
|
225
|
+
|
|
226
|
+
// --- Hybrid RAG Knowledge Engine Tools ---
|
|
227
|
+
|
|
228
|
+
server.registerTool(
|
|
229
|
+
"ingest_document",
|
|
230
|
+
{
|
|
231
|
+
description:
|
|
232
|
+
"Ingest a document into the RAG knowledge base. " +
|
|
233
|
+
"Accepts local file paths, web URLs, or raw Markdown/text content. " +
|
|
234
|
+
"Processes document through 3-tier hierarchy chunking (Big/Medium/Small), " +
|
|
235
|
+
"computes dense vectors, and extracts GraphRAG code symbols.",
|
|
236
|
+
inputSchema: z.object({
|
|
237
|
+
content: z.string().describe("Raw text content, file path, or web URL"),
|
|
238
|
+
type: z.enum(["text", "file", "url"]).default("text").describe("Input content type"),
|
|
239
|
+
title: z.string().optional().describe("Document title"),
|
|
240
|
+
path: z.string().optional().describe("Original document file path"),
|
|
241
|
+
generateEmbeddings: z.boolean().default(true).describe("Compute dense vector embeddings"),
|
|
242
|
+
}),
|
|
243
|
+
},
|
|
244
|
+
async ({ content, type, title, path, generateEmbeddings }) => {
|
|
245
|
+
const { ingestDocument } = await import("./ingest/pipeline.js");
|
|
246
|
+
const result = await ingestDocument({
|
|
247
|
+
content,
|
|
248
|
+
type,
|
|
249
|
+
title: title || null,
|
|
250
|
+
path: path || null,
|
|
251
|
+
generateEmbeddings,
|
|
252
|
+
});
|
|
253
|
+
return {
|
|
254
|
+
content: [
|
|
255
|
+
{
|
|
256
|
+
type: "text",
|
|
257
|
+
text: JSON.stringify(
|
|
258
|
+
{
|
|
259
|
+
status: "success",
|
|
260
|
+
docId: result.docId,
|
|
261
|
+
title: result.title,
|
|
262
|
+
sectionsCount: result.sectionsCount,
|
|
263
|
+
microChunksCount: result.microChunksCount,
|
|
264
|
+
deduplicated: result.deduplicated,
|
|
265
|
+
},
|
|
266
|
+
null,
|
|
267
|
+
2
|
|
268
|
+
),
|
|
269
|
+
},
|
|
270
|
+
],
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
);
|
|
274
|
+
|
|
275
|
+
server.registerTool(
|
|
276
|
+
"query_knowledge_base",
|
|
277
|
+
{
|
|
278
|
+
description:
|
|
279
|
+
"Perform hybrid search (RSF/RRF BM25 full-text + dense vector similarity) across the RAG knowledge base. " +
|
|
280
|
+
"Returns top-ranked candidate document sections with breadcrumbs, GraphRAG defined code symbols, and relevance scores.",
|
|
281
|
+
inputSchema: z.object({
|
|
282
|
+
query: z.string().describe("Search query in natural language or symbol name"),
|
|
283
|
+
limit: z.number().default(5).describe("Maximum number of sections to return"),
|
|
284
|
+
instruction: z
|
|
285
|
+
.string()
|
|
286
|
+
.optional()
|
|
287
|
+
.describe(
|
|
288
|
+
"Optional task-specific retrieval instruction shaping embedding focus (e.g. 'Retrieve code snippets', 'Find user preferences'). " +
|
|
289
|
+
"Recommended when using E5/BGE models for domain-specific queries."
|
|
290
|
+
),
|
|
291
|
+
generateEmbeddings: z.boolean().default(true).describe("Use vector search alongside BM25"),
|
|
292
|
+
}),
|
|
293
|
+
},
|
|
294
|
+
async ({ query, limit, instruction, generateEmbeddings }) => {
|
|
295
|
+
const { hybridQuery } = await import("./retrieval/retriever.js");
|
|
296
|
+
const { getConfig } = await import("./config/config_manager.js");
|
|
297
|
+
const activeConfig = getConfig();
|
|
298
|
+
|
|
299
|
+
const results = await hybridQuery({
|
|
300
|
+
query,
|
|
301
|
+
limit,
|
|
302
|
+
generateEmbeddings,
|
|
303
|
+
instruction: instruction || null,
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
if (!results || results.length === 0) {
|
|
307
|
+
return {
|
|
308
|
+
content: [
|
|
309
|
+
{
|
|
310
|
+
type: "text",
|
|
311
|
+
text: `[Active Model: ${activeConfig.embeddingModel}]\nNo matching knowledge found for query.`,
|
|
312
|
+
},
|
|
313
|
+
],
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
const headerNote = `[Active Model: ${activeConfig.embeddingModel} | Fusion: ${activeConfig.fusionAlgorithm.toUpperCase()}]\n\n`;
|
|
318
|
+
|
|
319
|
+
const formatted = results
|
|
320
|
+
.map((r, i) => {
|
|
321
|
+
let header = `### [${i + 1}] ${r.doc_title || "Untitled"}`;
|
|
322
|
+
if (r.heading) header += ` > ${r.heading}`;
|
|
323
|
+
if (r.breadcrumbs) header += ` (${r.breadcrumbs})`;
|
|
324
|
+
let body = `Score: ${(r.score || 0).toFixed(4)}\n`;
|
|
325
|
+
if (r.defined_symbols && r.defined_symbols.length > 0) {
|
|
326
|
+
body += `Defined Symbols: ${r.defined_symbols.join(", ")}\n`;
|
|
327
|
+
}
|
|
328
|
+
body += `\n${r.snippet || r.full_section_content || ""}`;
|
|
329
|
+
return `${header}\n${body}`;
|
|
330
|
+
})
|
|
331
|
+
.join("\n\n---\n\n");
|
|
332
|
+
|
|
333
|
+
return { content: [{ type: "text", text: headerNote + formatted }] };
|
|
334
|
+
}
|
|
335
|
+
);
|
|
336
|
+
|
|
337
|
+
server.registerTool(
|
|
338
|
+
"manage_knowledge_base",
|
|
339
|
+
{
|
|
340
|
+
description:
|
|
341
|
+
"Manage the RAG knowledge base: inspect stats, list documents, read full raw document, delete documents, or export/import snapshots.",
|
|
342
|
+
inputSchema: z.object({
|
|
343
|
+
action: z.enum(["stats", "list", "read_document", "delete", "export_snapshot", "import_snapshot"]).describe("Management action"),
|
|
344
|
+
docId: z.string().optional().describe("Document ID, title, or path (required for read_document and delete)"),
|
|
345
|
+
snapshotPath: z.string().optional().describe("File path for snapshot export/import"),
|
|
346
|
+
}),
|
|
347
|
+
},
|
|
348
|
+
async ({ action, docId, snapshotPath }) => {
|
|
349
|
+
const { getDatabase } = await import("./db/database.js");
|
|
350
|
+
const db = getDatabase();
|
|
351
|
+
|
|
352
|
+
if (action === "stats") {
|
|
353
|
+
const docCount = db.prepare("SELECT COUNT(*) as cnt FROM documents").get().cnt;
|
|
354
|
+
const secCount = db.prepare("SELECT COUNT(*) as cnt FROM sections").get().cnt;
|
|
355
|
+
const chunkCount = db.prepare("SELECT COUNT(*) as cnt FROM micro_chunks").get().cnt;
|
|
356
|
+
const edgeCount = db.prepare("SELECT COUNT(*) as cnt FROM graph_edges").get().cnt;
|
|
357
|
+
return {
|
|
358
|
+
content: [
|
|
359
|
+
{
|
|
360
|
+
type: "text",
|
|
361
|
+
text: JSON.stringify(
|
|
362
|
+
{
|
|
363
|
+
documents: docCount,
|
|
364
|
+
sections: secCount,
|
|
365
|
+
micro_chunks: chunkCount,
|
|
366
|
+
graph_edges: edgeCount,
|
|
367
|
+
},
|
|
368
|
+
null,
|
|
369
|
+
2
|
|
370
|
+
),
|
|
371
|
+
},
|
|
372
|
+
],
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
if (action === "list") {
|
|
377
|
+
const docs = db
|
|
378
|
+
.prepare("SELECT id, title, path, blob_hash, created_at FROM documents ORDER BY created_at DESC")
|
|
379
|
+
.all();
|
|
380
|
+
return {
|
|
381
|
+
content: [{ type: "text", text: JSON.stringify(docs, null, 2) }],
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
if (action === "read_document") {
|
|
386
|
+
if (!docId) throw new Error("docId parameter is required for read_document action");
|
|
387
|
+
const doc = db
|
|
388
|
+
.prepare("SELECT id, title, path, blob_hash, created_at FROM documents WHERE id = ? OR path = ? OR title = ?")
|
|
389
|
+
.get(docId, docId, docId);
|
|
390
|
+
if (!doc) {
|
|
391
|
+
throw new Error(`Document not found in knowledge base for docId: ${docId}`);
|
|
392
|
+
}
|
|
393
|
+
const { readBlob } = await import("./storage/blob_store.js");
|
|
394
|
+
const rawContent = await readBlob(doc.blob_hash);
|
|
395
|
+
return {
|
|
396
|
+
content: [
|
|
397
|
+
{
|
|
398
|
+
type: "text",
|
|
399
|
+
text: JSON.stringify(
|
|
400
|
+
{
|
|
401
|
+
id: doc.id,
|
|
402
|
+
title: doc.title,
|
|
403
|
+
path: doc.path,
|
|
404
|
+
created_at: doc.created_at,
|
|
405
|
+
content: rawContent,
|
|
406
|
+
},
|
|
407
|
+
null,
|
|
408
|
+
2
|
|
409
|
+
),
|
|
410
|
+
},
|
|
411
|
+
],
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
if (action === "delete") {
|
|
416
|
+
if (!docId) throw new Error("docId parameter is required for delete action");
|
|
417
|
+
const { deleteDocument } = await import("./ingest/pipeline.js");
|
|
418
|
+
const result = await deleteDocument(docId, db);
|
|
419
|
+
return {
|
|
420
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
if (action === "export_snapshot") {
|
|
425
|
+
const { exportSnapshot } = await import("./admin/snapshot.js");
|
|
426
|
+
const result = await exportSnapshot({ customDb: db, outputPath: snapshotPath || null });
|
|
427
|
+
return {
|
|
428
|
+
content: [
|
|
429
|
+
{
|
|
430
|
+
type: "text",
|
|
431
|
+
text: snapshotPath
|
|
432
|
+
? `Snapshot exported successfully to ${snapshotPath}`
|
|
433
|
+
: JSON.stringify(result, null, 2),
|
|
434
|
+
},
|
|
435
|
+
],
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
if (action === "import_snapshot") {
|
|
440
|
+
if (!snapshotPath) throw new Error("snapshotPath parameter is required for import_snapshot action");
|
|
441
|
+
const { importSnapshot } = await import("./admin/snapshot.js");
|
|
442
|
+
const result = await importSnapshot({ customDb: db, snapshotPathOrData: snapshotPath });
|
|
443
|
+
return {
|
|
444
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
throw new Error(`Unknown action: ${action}`);
|
|
449
|
+
}
|
|
450
|
+
);
|
|
451
|
+
|
|
452
|
+
const transport = new StdioServerTransport();
|
|
453
|
+
await server.connect(transport);
|
|
454
|
+
console.error(`memory-agent MCP server running, data dir: ${MEMORY_DIR}`);
|