-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
603 lines (568 loc) · 17.3 KB
/
index.ts
File metadata and controls
603 lines (568 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
#!/usr/bin/env node
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { promises as fs } from "fs";
import path from "path";
const fileURLToPath =
typeof Bun !== "undefined" && process.versions.bun
? Bun.fileURLToPath
: (await import("url")).fileURLToPath;
// Define memory file path using environment variable with fallback
const defaultMemoryPath = path.join(
path.dirname(fileURLToPath(import.meta.url)),
"memory.json"
);
// If MEMORY_FILE_PATH is just a filename, put it in the same directory as the script
const MEMORY_FILE_PATH = process.env.MEMORY_FILE_PATH
? path.isAbsolute(process.env.MEMORY_FILE_PATH)
? process.env.MEMORY_FILE_PATH
: path.join(
path.dirname(fileURLToPath(import.meta.url)),
process.env.MEMORY_FILE_PATH
)
: defaultMemoryPath;
// We are storing our memory using entities, relations, and observations in a graph structure
interface Entity {
name: string;
entityType: string;
observations: string[];
}
interface Relation {
from: string;
to: string;
relationType: string;
}
interface KnowledgeGraph {
entities: Entity[];
relations: Relation[];
}
// The KnowledgeGraphManager class contains all operations to interact with the knowledge graph
class KnowledgeGraphManager {
private async loadGraph(): Promise<KnowledgeGraph> {
try {
const data = await fs.readFile(MEMORY_FILE_PATH, "utf-8");
const lines = data.split("\n").filter((line) => line.trim() !== "");
return lines.reduce(
(graph: KnowledgeGraph, line) => {
const item = JSON.parse(line);
if (item.type === "entity") graph.entities.push(item as Entity);
if (item.type === "relation") graph.relations.push(item as Relation);
return graph;
},
{ entities: [], relations: [] }
);
} catch (error) {
if (
error instanceof Error &&
"code" in error &&
(error as any).code === "ENOENT"
) {
return { entities: [], relations: [] };
}
throw error;
}
}
private async saveGraph(graph: KnowledgeGraph): Promise<void> {
const lines = [
...graph.entities.map((e) => JSON.stringify({ type: "entity", ...e })),
...graph.relations.map((r) => JSON.stringify({ type: "relation", ...r })),
];
await fs.writeFile(MEMORY_FILE_PATH, lines.join("\n"));
}
async createEntities(entities: Entity[]): Promise<Entity[]> {
const graph = await this.loadGraph();
const newEntities = entities.filter(
(e) =>
!graph.entities.some((existingEntity) => existingEntity.name === e.name)
);
graph.entities.push(...newEntities);
await this.saveGraph(graph);
return newEntities;
}
async createRelations(relations: Relation[]): Promise<Relation[]> {
const graph = await this.loadGraph();
const newRelations = relations.filter(
(r) =>
!graph.relations.some(
(existingRelation) =>
existingRelation.from === r.from &&
existingRelation.to === r.to &&
existingRelation.relationType === r.relationType
)
);
graph.relations.push(...newRelations);
await this.saveGraph(graph);
return newRelations;
}
async addObservations(
observations: { entityName: string; contents: string[] }[]
): Promise<{ entityName: string; addedObservations: string[] }[]> {
const graph = await this.loadGraph();
const results = observations.map((o) => {
const entity = graph.entities.find((e) => e.name === o.entityName);
if (!entity) {
throw new Error(`Entity with name ${o.entityName} not found`);
}
const newObservations = o.contents.filter(
(content) => !entity.observations.includes(content)
);
entity.observations.push(...newObservations);
return { entityName: o.entityName, addedObservations: newObservations };
});
await this.saveGraph(graph);
return results;
}
async deleteEntities(entityNames: string[]): Promise<void> {
const graph = await this.loadGraph();
graph.entities = graph.entities.filter(
(e) => !entityNames.includes(e.name)
);
graph.relations = graph.relations.filter(
(r) => !entityNames.includes(r.from) && !entityNames.includes(r.to)
);
await this.saveGraph(graph);
}
async deleteObservations(
deletions: { entityName: string; observations: string[] }[]
): Promise<void> {
const graph = await this.loadGraph();
deletions.forEach((d) => {
const entity = graph.entities.find((e) => e.name === d.entityName);
if (entity) {
entity.observations = entity.observations.filter(
(o) => !d.observations.includes(o)
);
}
});
await this.saveGraph(graph);
}
async deleteRelations(relations: Relation[]): Promise<void> {
const graph = await this.loadGraph();
graph.relations = graph.relations.filter(
(r) =>
!relations.some(
(delRelation) =>
r.from === delRelation.from &&
r.to === delRelation.to &&
r.relationType === delRelation.relationType
)
);
await this.saveGraph(graph);
}
async readGraph(): Promise<KnowledgeGraph> {
return this.loadGraph();
}
// Very basic search function
async searchNodes(query: string): Promise<KnowledgeGraph> {
const graph = await this.loadGraph();
// Filter entities
const filteredEntities = graph.entities.filter(
(e) =>
e.name.toLowerCase().includes(query.toLowerCase()) ||
e.entityType.toLowerCase().includes(query.toLowerCase()) ||
e.observations.some((o) =>
o.toLowerCase().includes(query.toLowerCase())
)
);
// Create a Set of filtered entity names for quick lookup
const filteredEntityNames = new Set(filteredEntities.map((e) => e.name));
// Filter relations to only include those between filtered entities
const filteredRelations = graph.relations.filter(
(r) => filteredEntityNames.has(r.from) && filteredEntityNames.has(r.to)
);
const filteredGraph: KnowledgeGraph = {
entities: filteredEntities,
relations: filteredRelations,
};
return filteredGraph;
}
async openNodes(names: string[]): Promise<KnowledgeGraph> {
const graph = await this.loadGraph();
// Filter entities
const filteredEntities = graph.entities.filter((e) =>
names.includes(e.name)
);
// Create a Set of filtered entity names for quick lookup
const filteredEntityNames = new Set(filteredEntities.map((e) => e.name));
// Filter relations to only include those between filtered entities
const filteredRelations = graph.relations.filter(
(r) => filteredEntityNames.has(r.from) && filteredEntityNames.has(r.to)
);
const filteredGraph: KnowledgeGraph = {
entities: filteredEntities,
relations: filteredRelations,
};
return filteredGraph;
}
}
const knowledgeGraphManager = new KnowledgeGraphManager();
// The server instance and tools exposed to Claude
const server = new Server(
{
name: "memory-server",
version: "1.0.0",
},
{
capabilities: {
tools: {},
},
}
);
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "create_entities",
description: "Create multiple new entities in the knowledge graph",
inputSchema: {
type: "object",
properties: {
entities: {
type: "array",
items: {
type: "object",
properties: {
name: {
type: "string",
description: "The name of the entity",
},
entityType: {
type: "string",
description: "The type of the entity",
},
observations: {
type: "array",
items: { type: "string" },
description:
"An array of observation contents associated with the entity",
},
},
required: ["name", "entityType", "observations"],
},
},
},
required: ["entities"],
},
},
{
name: "create_relations",
description:
"Create multiple new relations between entities in the knowledge graph. Relations should be in active voice",
inputSchema: {
type: "object",
properties: {
relations: {
type: "array",
items: {
type: "object",
properties: {
from: {
type: "string",
description:
"The name of the entity where the relation starts",
},
to: {
type: "string",
description:
"The name of the entity where the relation ends",
},
relationType: {
type: "string",
description: "The type of the relation",
},
},
required: ["from", "to", "relationType"],
},
},
},
required: ["relations"],
},
},
{
name: "add_observations",
description:
"Add new observations to existing entities in the knowledge graph",
inputSchema: {
type: "object",
properties: {
observations: {
type: "array",
items: {
type: "object",
properties: {
entityName: {
type: "string",
description:
"The name of the entity to add the observations to",
},
contents: {
type: "array",
items: { type: "string" },
description: "An array of observation contents to add",
},
},
required: ["entityName", "contents"],
},
},
},
required: ["observations"],
},
},
{
name: "delete_entities",
description:
"Delete multiple entities and their associated relations from the knowledge graph",
inputSchema: {
type: "object",
properties: {
entityNames: {
type: "array",
items: { type: "string" },
description: "An array of entity names to delete",
},
},
required: ["entityNames"],
},
},
{
name: "delete_observations",
description:
"Delete specific observations from entities in the knowledge graph",
inputSchema: {
type: "object",
properties: {
deletions: {
type: "array",
items: {
type: "object",
properties: {
entityName: {
type: "string",
description:
"The name of the entity containing the observations",
},
observations: {
type: "array",
items: { type: "string" },
description: "An array of observations to delete",
},
},
required: ["entityName", "observations"],
},
},
},
required: ["deletions"],
},
},
{
name: "delete_relations",
description: "Delete multiple relations from the knowledge graph",
inputSchema: {
type: "object",
properties: {
relations: {
type: "array",
items: {
type: "object",
properties: {
from: {
type: "string",
description:
"The name of the entity where the relation starts",
},
to: {
type: "string",
description:
"The name of the entity where the relation ends",
},
relationType: {
type: "string",
description: "The type of the relation",
},
},
required: ["from", "to", "relationType"],
},
description: "An array of relations to delete",
},
},
required: ["relations"],
},
},
{
name: "read_graph",
description: "Read the entire knowledge graph",
inputSchema: {
type: "object",
properties: {},
},
},
{
name: "search_nodes",
description: "Search for nodes in the knowledge graph based on a query",
inputSchema: {
type: "object",
properties: {
query: {
type: "string",
description:
"The search query to match against entity names, types, and observation content",
},
},
required: ["query"],
},
},
{
name: "open_nodes",
description:
"Open specific nodes in the knowledge graph by their names",
inputSchema: {
type: "object",
properties: {
names: {
type: "array",
items: { type: "string" },
description: "An array of entity names to retrieve",
},
},
required: ["names"],
},
},
],
};
});
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
if (!args) {
throw new Error(`No arguments provided for tool: ${name}`);
}
switch (name) {
case "create_entities":
return {
content: [
{
type: "text",
text: JSON.stringify(
await knowledgeGraphManager.createEntities(
args.entities as Entity[]
),
null,
2
),
},
],
};
case "create_relations":
return {
content: [
{
type: "text",
text: JSON.stringify(
await knowledgeGraphManager.createRelations(
args.relations as Relation[]
),
null,
2
),
},
],
};
case "add_observations":
return {
content: [
{
type: "text",
text: JSON.stringify(
await knowledgeGraphManager.addObservations(
args.observations as {
entityName: string;
contents: string[];
}[]
),
null,
2
),
},
],
};
case "delete_entities":
await knowledgeGraphManager.deleteEntities(args.entityNames as string[]);
return {
content: [{ type: "text", text: "Entities deleted successfully" }],
};
case "delete_observations":
await knowledgeGraphManager.deleteObservations(
args.deletions as { entityName: string; observations: string[] }[]
);
return {
content: [{ type: "text", text: "Observations deleted successfully" }],
};
case "delete_relations":
await knowledgeGraphManager.deleteRelations(args.relations as Relation[]);
return {
content: [{ type: "text", text: "Relations deleted successfully" }],
};
case "read_graph":
return {
content: [
{
type: "text",
text: JSON.stringify(
await knowledgeGraphManager.readGraph(),
null,
2
),
},
],
};
case "search_nodes":
return {
content: [
{
type: "text",
text: JSON.stringify(
await knowledgeGraphManager.searchNodes(args.query as string),
null,
2
),
},
],
};
case "open_nodes":
return {
content: [
{
type: "text",
text: JSON.stringify(
await knowledgeGraphManager.openNodes(args.names as string[]),
null,
2
),
},
],
};
default:
throw new Error(`Unknown tool: ${name}`);
}
});
async function main() {
try {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Memory MCP Server running on stdio");
await fs.writeFile(
"/Users/quanle96/Documents/mcp-servers/memory/log.txt",
`Memory file path: ${MEMORY_FILE_PATH}`
);
} catch (error) {
console.error("Error starting server:", error);
process.exit(1);
}
}
main().catch((error) => {
console.error("Fatal error in main():", error);
process.exit(1);
});