@levalicious/server-memory 0.0.4 → 0.0.5

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/dist/index.js CHANGED
@@ -8,18 +8,22 @@ import { fileURLToPath } from 'url';
8
8
  // Define memory file path using environment variable with fallback
9
9
  const defaultMemoryPath = path.join(path.dirname(fileURLToPath(import.meta.url)), 'memory.json');
10
10
  // If MEMORY_FILE_PATH is just a filename, put it in the same directory as the script
11
- const MEMORY_FILE_PATH = process.env.MEMORY_FILE_PATH
11
+ const DEFAULT_MEMORY_FILE_PATH = process.env.MEMORY_FILE_PATH
12
12
  ? path.isAbsolute(process.env.MEMORY_FILE_PATH)
13
13
  ? process.env.MEMORY_FILE_PATH
14
14
  : path.join(path.dirname(fileURLToPath(import.meta.url)), process.env.MEMORY_FILE_PATH)
15
15
  : defaultMemoryPath;
16
16
  // The KnowledgeGraphManager class contains all operations to interact with the knowledge graph
17
- class KnowledgeGraphManager {
17
+ export class KnowledgeGraphManager {
18
18
  bclCtr = 0;
19
19
  bclTerm = "";
20
+ memoryFilePath;
21
+ constructor(memoryFilePath = DEFAULT_MEMORY_FILE_PATH) {
22
+ this.memoryFilePath = memoryFilePath;
23
+ }
20
24
  async loadGraph() {
21
25
  try {
22
- const data = await fs.readFile(MEMORY_FILE_PATH, "utf-8");
26
+ const data = await fs.readFile(this.memoryFilePath, "utf-8");
23
27
  const lines = data.split("\n").filter(line => line.trim() !== "");
24
28
  return lines.reduce((graph, line) => {
25
29
  const item = JSON.parse(line);
@@ -31,7 +35,7 @@ class KnowledgeGraphManager {
31
35
  }, { entities: [], relations: [] });
32
36
  }
33
37
  catch (error) {
34
- if (error instanceof Error && 'code' in error && error.code === "ENOENT") {
38
+ if (error?.code === "ENOENT") {
35
39
  return { entities: [], relations: [] };
36
40
  }
37
41
  throw error;
@@ -42,10 +46,21 @@ class KnowledgeGraphManager {
42
46
  ...graph.entities.map(e => JSON.stringify({ type: "entity", ...e })),
43
47
  ...graph.relations.map(r => JSON.stringify({ type: "relation", ...r })),
44
48
  ];
45
- await fs.writeFile(MEMORY_FILE_PATH, lines.join("\n"));
49
+ await fs.writeFile(this.memoryFilePath, lines.join("\n"));
46
50
  }
47
51
  async createEntities(entities) {
48
52
  const graph = await this.loadGraph();
53
+ // Validate observation limits
54
+ for (const entity of entities) {
55
+ if (entity.observations.length > 2) {
56
+ throw new Error(`Entity "${entity.name}" has ${entity.observations.length} observations. Maximum allowed is 2.`);
57
+ }
58
+ for (const obs of entity.observations) {
59
+ if (obs.length > 140) {
60
+ throw new Error(`Observation in entity "${entity.name}" exceeds 140 characters (${obs.length} chars): "${obs.substring(0, 50)}..."`);
61
+ }
62
+ }
63
+ }
49
64
  const newEntities = entities.filter(e => !graph.entities.some(existingEntity => existingEntity.name === e.name));
50
65
  graph.entities.push(...newEntities);
51
66
  await this.saveGraph(graph);
@@ -67,7 +82,17 @@ class KnowledgeGraphManager {
67
82
  if (!entity) {
68
83
  throw new Error(`Entity with name ${o.entityName} not found`);
69
84
  }
85
+ // Validate observation character limits
86
+ for (const obs of o.contents) {
87
+ if (obs.length > 140) {
88
+ throw new Error(`Observation for "${o.entityName}" exceeds 140 characters (${obs.length} chars): "${obs.substring(0, 50)}..."`);
89
+ }
90
+ }
70
91
  const newObservations = o.contents.filter(content => !entity.observations.includes(content));
92
+ // Validate total observation count
93
+ if (entity.observations.length + newObservations.length > 2) {
94
+ throw new Error(`Adding ${newObservations.length} observations to "${o.entityName}" would exceed limit of 2 (currently has ${entity.observations.length}).`);
95
+ }
71
96
  entity.observations.push(...newObservations);
72
97
  return { entityName: o.entityName, addedObservations: newObservations };
73
98
  });
@@ -97,16 +122,20 @@ class KnowledgeGraphManager {
97
122
  r.relationType === delRelation.relationType));
98
123
  await this.saveGraph(graph);
99
124
  }
100
- async readGraph() {
101
- return this.loadGraph();
102
- }
103
- // Very basic search function
125
+ // Regex-based search function
104
126
  async searchNodes(query) {
105
127
  const graph = await this.loadGraph();
128
+ let regex;
129
+ try {
130
+ regex = new RegExp(query, 'i'); // case-insensitive
131
+ }
132
+ catch (e) {
133
+ throw new Error(`Invalid regex pattern: ${query}`);
134
+ }
106
135
  // Filter entities
107
- const filteredEntities = graph.entities.filter(e => e.name.toLowerCase().includes(query.toLowerCase()) ||
108
- e.entityType.toLowerCase().includes(query.toLowerCase()) ||
109
- e.observations.some(o => o.toLowerCase().includes(query.toLowerCase())));
136
+ const filteredEntities = graph.entities.filter(e => regex.test(e.name) ||
137
+ regex.test(e.entityType) ||
138
+ e.observations.some(o => regex.test(o)));
110
139
  // Create a Set of filtered entity names for quick lookup
111
140
  const filteredEntityNames = new Set(filteredEntities.map(e => e.name));
112
141
  // Filter relations to only include those between filtered entities
@@ -145,22 +174,25 @@ class KnowledgeGraphManager {
145
174
  };
146
175
  return filteredGraph;
147
176
  }
148
- async getNeighbors(entityName, depth = 1) {
177
+ async getNeighbors(entityName, depth = 1, withEntities = false) {
149
178
  const graph = await this.loadGraph();
150
179
  const visited = new Set();
151
180
  const resultEntities = new Map();
152
- const resultRelations = [];
181
+ const resultRelations = new Map(); // Deduplicate relations
182
+ const relationKey = (r) => `${r.from}|${r.relationType}|${r.to}`;
153
183
  const traverse = (currentName, currentDepth) => {
154
184
  if (currentDepth > depth || visited.has(currentName))
155
185
  return;
156
186
  visited.add(currentName);
157
- const entity = graph.entities.find(e => e.name === currentName);
158
- if (entity) {
159
- resultEntities.set(currentName, entity);
187
+ if (withEntities) {
188
+ const entity = graph.entities.find(e => e.name === currentName);
189
+ if (entity) {
190
+ resultEntities.set(currentName, entity);
191
+ }
160
192
  }
161
193
  // Find all relations involving this entity
162
194
  const connectedRelations = graph.relations.filter(r => r.from === currentName || r.to === currentName);
163
- resultRelations.push(...connectedRelations);
195
+ connectedRelations.forEach(r => resultRelations.set(relationKey(r), r));
164
196
  if (currentDepth < depth) {
165
197
  // Traverse to connected entities
166
198
  connectedRelations.forEach(r => {
@@ -172,7 +204,7 @@ class KnowledgeGraphManager {
172
204
  traverse(entityName, 0);
173
205
  return {
174
206
  entities: Array.from(resultEntities.values()),
175
- relations: resultRelations
207
+ relations: Array.from(resultRelations.values())
176
208
  };
177
209
  }
178
210
  async findPath(fromEntity, toEntity, maxDepth = 5) {
@@ -233,6 +265,8 @@ class KnowledgeGraphManager {
233
265
  const graph = await this.loadGraph();
234
266
  const entityNames = new Set(graph.entities.map(e => e.name));
235
267
  const missingEntities = new Set();
268
+ const observationViolations = [];
269
+ // Check for missing entities in relations
236
270
  graph.relations.forEach(r => {
237
271
  if (!entityNames.has(r.from)) {
238
272
  missingEntities.add(r.from);
@@ -241,7 +275,26 @@ class KnowledgeGraphManager {
241
275
  missingEntities.add(r.to);
242
276
  }
243
277
  });
244
- return Array.from(missingEntities);
278
+ // Check for observation limit violations
279
+ graph.entities.forEach(e => {
280
+ const oversizedObservations = [];
281
+ e.observations.forEach((obs, idx) => {
282
+ if (obs.length > 140) {
283
+ oversizedObservations.push(idx);
284
+ }
285
+ });
286
+ if (e.observations.length > 2 || oversizedObservations.length > 0) {
287
+ observationViolations.push({
288
+ entity: e.name,
289
+ count: e.observations.length,
290
+ oversizedObservations
291
+ });
292
+ }
293
+ });
294
+ return {
295
+ missingEntities: Array.from(missingEntities),
296
+ observationViolations
297
+ };
245
298
  }
246
299
  // BCL (Binary Combinatory Logic) evaluator
247
300
  async evaluateBCL(program, maxSteps) {
@@ -402,385 +455,387 @@ class KnowledgeGraphManager {
402
455
  this.bclTerm = "";
403
456
  }
404
457
  }
405
- const knowledgeGraphManager = new KnowledgeGraphManager();
406
- // The server instance and tools exposed to Claude
407
- const server = new Server({
408
- name: "memory-server",
409
- icons: [
410
- { src: "data:image/svg+xml;base64,PHN2ZyBmaWxsPSJjdXJyZW50Q29sb3IiIGZpbGwtcnVsZT0iZXZlbm9kZCIgaGVpZ2h0PSIxZW0iIHN0eWxlPSJmbGV4Om5vbmU7bGluZS1oZWlnaHQ6MSIgdmlld0JveD0iMCAwIDI0IDI0IiB3aWR0aD0iMWVtIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjx0aXRsZT5Nb2RlbENvbnRleHRQcm90b2NvbDwvdGl0bGU+PHBhdGggZD0iTTIwLjEgNS41MlYxLjVoLS4xOGMtMy4zNi4xNS02LjE1IDIuMzEtNy44MyA0LjAybC0uMDkuMDktLjA5LS4wOUMxMC4yIDMuODEgNy40NCAxLjY1IDQuMDggMS41SDMuOXY0LjAySDB2Ni45M2MwIDEuNjguMDYgMy4zNi4xOCA0Ljc0YTUuNTcgNS41NyAwIDAgMCA1LjE5IDUuMWMyLjEzLjEyIDQuMzguMjEgNi42My4yMXM0LjUtLjA5IDYuNjMtLjI0YTUuNTcgNS41NyAwIDAgMCA1LjE5LTUuMWMuMTItMS4zOC4xOC0zLjA2LjE4LTQuNzR2LTYuOXptMCA2LjkzYzAgMS41OS0uMDYgMy4xNS0uMTggNC40MS0uMDkuODEtLjc1IDEuNDctMS41NiAxLjVhOTAgOTAgMCAwIDEtMTIuNzIgMGMtLjgxLS4wMy0xLjUtLjY5LTEuNTYtMS41LS4xMi0xLjI2LS4xOC0yLjg1LS4xOC00LjQxVjUuNTJjMi44Mi4xMiA1LjY0IDMuMTUgNi40OCA0LjMyTDEyIDEyLjA5bDEuNjItMi4yNWMuODQtMS4yIDMuNjYtNC4yIDYuNDgtNC4zMnoiLz48L3N2Zz4=",
411
- mimeType: "image/svg+xml",
412
- sizes: ["any"]
413
- }
414
- ],
415
- version: "0.0.4",
416
- }, {
417
- capabilities: {
418
- tools: {},
419
- },
420
- });
421
- server.setRequestHandler(ListToolsRequestSchema, async () => {
422
- return {
423
- tools: [
424
- {
425
- name: "create_entities",
426
- description: "Create multiple new entities in the knowledge graph",
427
- inputSchema: {
428
- type: "object",
429
- properties: {
430
- entities: {
431
- type: "array",
432
- items: {
433
- type: "object",
434
- properties: {
435
- name: { type: "string", description: "The name of the entity" },
436
- entityType: { type: "string", description: "The type of the entity" },
437
- observations: {
438
- type: "array",
439
- items: { type: "string" },
440
- description: "An array of observation contents associated with the entity"
458
+ /**
459
+ * Creates a configured MCP server instance with all tools registered.
460
+ * @param memoryFilePath Optional path to the memory file (defaults to MEMORY_FILE_PATH env var or memory.json)
461
+ */
462
+ export function createServer(memoryFilePath) {
463
+ const knowledgeGraphManager = new KnowledgeGraphManager(memoryFilePath);
464
+ const server = new Server({
465
+ name: "memory-server",
466
+ icons: [
467
+ { src: "data:image/svg+xml;base64,PHN2ZyBmaWxsPSJjdXJyZW50Q29sb3IiIGZpbGwtcnVsZT0iZXZlbm9kZCIgaGVpZ2h0PSIxZW0iIHN0eWxlPSJmbGV4Om5vbmU7bGluZS1oZWlnaHQ6MSIgdmlld0JveD0iMCAwIDI0IDI0IiB3aWR0aD0iMWVtIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjx0aXRsZT5Nb2RlbENvbnRleHRQcm90b2NvbDwvdGl0bGU+PHBhdGggZD0iTTIwLjEgNS41MlYxLjVoLS4xOGMtMy4zNi4xNS02LjE1IDIuMzEtNy44MyA0LjAybC0uMDkuMDktLjA5LS4wOUMxMC4yIDMuODEgNy40NCAxLjY1IDQuMDggMS41SDMuOXY0LjAySDB2Ni45M2MwIDEuNjguMDYgMy4zNi4xOCA0Ljc0YTUuNTcgNS41NyAwIDAgMCA1LjE5IDUuMWMyLjEzLjEyIDQuMzguMjEgNi42My4yMXM0LjUtLjA5IDYuNjMtLjI0YTUuNTcgNS41NyAwIDAgMCA1LjE5LTUuMWMuMTItMS4zOC4xOC0zLjA2LjE4LTQuNzR2LTYuOXptMCA2LjkzYzAgMS41OS0uMDYgMy4xNS0uMTggNC40MS0uMDkuODEtLjc1IDEuNDctMS41NiAxLjVhOTAgOTAgMCAwIDEtMTIuNzIgMGMtLjgxLS4wMy0xLjUtLjY5LTEuNTYtMS41LS4xMi0xLjI2LS4xOC0yLjg1LS4xOC00LjQxVjUuNTJjMi44Mi4xMiA1LjY0IDMuMTUgNi40OCA0LjMyTDEyIDEyLjA5bDEuNjItMi4yNWMuODQtMS4yIDMuNjYtNC4yIDYuNDgtNC4zMnoiLz48L3N2Zz4=",
468
+ mimeType: "image/svg+xml",
469
+ sizes: ["any"]
470
+ }
471
+ ],
472
+ version: "0.0.4",
473
+ }, {
474
+ capabilities: {
475
+ tools: {},
476
+ },
477
+ });
478
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
479
+ return {
480
+ tools: [
481
+ {
482
+ name: "create_entities",
483
+ description: "Create multiple new entities in the knowledge graph",
484
+ inputSchema: {
485
+ type: "object",
486
+ properties: {
487
+ entities: {
488
+ type: "array",
489
+ items: {
490
+ type: "object",
491
+ properties: {
492
+ name: { type: "string", description: "The name of the entity" },
493
+ entityType: { type: "string", description: "The type of the entity" },
494
+ observations: {
495
+ type: "array",
496
+ items: { type: "string", maxLength: 140 },
497
+ maxItems: 2,
498
+ description: "Observations associated with the entity. MAX 2 observations, each MAX 140 characters."
499
+ },
441
500
  },
501
+ required: ["name", "entityType", "observations"],
442
502
  },
443
- required: ["name", "entityType", "observations"],
444
503
  },
445
504
  },
505
+ required: ["entities"],
446
506
  },
447
- required: ["entities"],
448
507
  },
449
- },
450
- {
451
- name: "create_relations",
452
- description: "Create multiple new relations between entities in the knowledge graph. Relations should be in active voice",
453
- inputSchema: {
454
- type: "object",
455
- properties: {
456
- relations: {
457
- type: "array",
458
- items: {
459
- type: "object",
460
- properties: {
461
- from: { type: "string", description: "The name of the entity where the relation starts" },
462
- to: { type: "string", description: "The name of the entity where the relation ends" },
463
- relationType: { type: "string", description: "The type of the relation" },
508
+ {
509
+ name: "create_relations",
510
+ description: "Create multiple new relations between entities in the knowledge graph. Relations should be in active voice",
511
+ inputSchema: {
512
+ type: "object",
513
+ properties: {
514
+ relations: {
515
+ type: "array",
516
+ items: {
517
+ type: "object",
518
+ properties: {
519
+ from: { type: "string", description: "The name of the entity where the relation starts" },
520
+ to: { type: "string", description: "The name of the entity where the relation ends" },
521
+ relationType: { type: "string", description: "The type of the relation" },
522
+ },
523
+ required: ["from", "to", "relationType"],
464
524
  },
465
- required: ["from", "to", "relationType"],
466
525
  },
467
526
  },
527
+ required: ["relations"],
468
528
  },
469
- required: ["relations"],
470
529
  },
471
- },
472
- {
473
- name: "add_observations",
474
- description: "Add new observations to existing entities in the knowledge graph",
475
- inputSchema: {
476
- type: "object",
477
- properties: {
478
- observations: {
479
- type: "array",
480
- items: {
481
- type: "object",
482
- properties: {
483
- entityName: { type: "string", description: "The name of the entity to add the observations to" },
484
- contents: {
485
- type: "array",
486
- items: { type: "string" },
487
- description: "An array of observation contents to add"
530
+ {
531
+ name: "add_observations",
532
+ description: "Add new observations to existing entities in the knowledge graph. Entities are limited to 2 total observations.",
533
+ inputSchema: {
534
+ type: "object",
535
+ properties: {
536
+ observations: {
537
+ type: "array",
538
+ items: {
539
+ type: "object",
540
+ properties: {
541
+ entityName: { type: "string", description: "The name of the entity to add the observations to" },
542
+ contents: {
543
+ type: "array",
544
+ items: { type: "string", maxLength: 140 },
545
+ description: "Observations to add. Each MAX 140 characters. Entity total MAX 2 observations."
546
+ },
488
547
  },
548
+ required: ["entityName", "contents"],
489
549
  },
490
- required: ["entityName", "contents"],
491
550
  },
492
551
  },
552
+ required: ["observations"],
493
553
  },
494
- required: ["observations"],
495
554
  },
496
- },
497
- {
498
- name: "delete_entities",
499
- description: "Delete multiple entities and their associated relations from the knowledge graph",
500
- inputSchema: {
501
- type: "object",
502
- properties: {
503
- entityNames: {
504
- type: "array",
505
- items: { type: "string" },
506
- description: "An array of entity names to delete"
555
+ {
556
+ name: "delete_entities",
557
+ description: "Delete multiple entities and their associated relations from the knowledge graph",
558
+ inputSchema: {
559
+ type: "object",
560
+ properties: {
561
+ entityNames: {
562
+ type: "array",
563
+ items: { type: "string" },
564
+ description: "An array of entity names to delete"
565
+ },
507
566
  },
567
+ required: ["entityNames"],
508
568
  },
509
- required: ["entityNames"],
510
569
  },
511
- },
512
- {
513
- name: "delete_observations",
514
- description: "Delete specific observations from entities in the knowledge graph",
515
- inputSchema: {
516
- type: "object",
517
- properties: {
518
- deletions: {
519
- type: "array",
520
- items: {
521
- type: "object",
522
- properties: {
523
- entityName: { type: "string", description: "The name of the entity containing the observations" },
524
- observations: {
525
- type: "array",
526
- items: { type: "string" },
527
- description: "An array of observations to delete"
570
+ {
571
+ name: "delete_observations",
572
+ description: "Delete specific observations from entities in the knowledge graph",
573
+ inputSchema: {
574
+ type: "object",
575
+ properties: {
576
+ deletions: {
577
+ type: "array",
578
+ items: {
579
+ type: "object",
580
+ properties: {
581
+ entityName: { type: "string", description: "The name of the entity containing the observations" },
582
+ observations: {
583
+ type: "array",
584
+ items: { type: "string" },
585
+ description: "An array of observations to delete"
586
+ },
528
587
  },
588
+ required: ["entityName", "observations"],
529
589
  },
530
- required: ["entityName", "observations"],
531
590
  },
532
591
  },
592
+ required: ["deletions"],
533
593
  },
534
- required: ["deletions"],
535
594
  },
536
- },
537
- {
538
- name: "delete_relations",
539
- description: "Delete multiple relations from the knowledge graph",
540
- inputSchema: {
541
- type: "object",
542
- properties: {
543
- relations: {
544
- type: "array",
545
- items: {
546
- type: "object",
547
- properties: {
548
- from: { type: "string", description: "The name of the entity where the relation starts" },
549
- to: { type: "string", description: "The name of the entity where the relation ends" },
550
- relationType: { type: "string", description: "The type of the relation" },
595
+ {
596
+ name: "delete_relations",
597
+ description: "Delete multiple relations from the knowledge graph",
598
+ inputSchema: {
599
+ type: "object",
600
+ properties: {
601
+ relations: {
602
+ type: "array",
603
+ items: {
604
+ type: "object",
605
+ properties: {
606
+ from: { type: "string", description: "The name of the entity where the relation starts" },
607
+ to: { type: "string", description: "The name of the entity where the relation ends" },
608
+ relationType: { type: "string", description: "The type of the relation" },
609
+ },
610
+ required: ["from", "to", "relationType"],
551
611
  },
552
- required: ["from", "to", "relationType"],
612
+ description: "An array of relations to delete"
553
613
  },
554
- description: "An array of relations to delete"
555
614
  },
615
+ required: ["relations"],
556
616
  },
557
- required: ["relations"],
558
- },
559
- },
560
- {
561
- name: "read_graph",
562
- description: "Read the entire knowledge graph",
563
- inputSchema: {
564
- type: "object",
565
- properties: {},
566
617
  },
567
- },
568
- {
569
- name: "search_nodes",
570
- description: "Search for nodes in the knowledge graph based on a query",
571
- inputSchema: {
572
- type: "object",
573
- properties: {
574
- query: { type: "string", description: "The search query to match against entity names, types, and observation content" },
618
+ {
619
+ name: "search_nodes",
620
+ description: "Search for nodes in the knowledge graph using a regex pattern",
621
+ inputSchema: {
622
+ type: "object",
623
+ properties: {
624
+ query: { type: "string", description: "Regex pattern to match against entity names, types, and observations. Use | for alternatives (e.g., 'Taranis|wheel'). Special regex characters must be escaped for literal matching." },
625
+ },
626
+ required: ["query"],
575
627
  },
576
- required: ["query"],
577
628
  },
578
- },
579
- {
580
- name: "open_nodes_filtered",
581
- description: "Open specific nodes in the knowledge graph by their names, filtering relations to only those between the opened nodes",
582
- inputSchema: {
583
- type: "object",
584
- properties: {
585
- names: {
586
- type: "array",
587
- items: { type: "string" },
588
- description: "An array of entity names to retrieve",
629
+ {
630
+ name: "open_nodes_filtered",
631
+ description: "Open specific nodes in the knowledge graph by their names, filtering relations to only those between the opened nodes",
632
+ inputSchema: {
633
+ type: "object",
634
+ properties: {
635
+ names: {
636
+ type: "array",
637
+ items: { type: "string" },
638
+ description: "An array of entity names to retrieve",
639
+ },
589
640
  },
641
+ required: ["names"],
590
642
  },
591
- required: ["names"],
592
643
  },
593
- },
594
- {
595
- name: "open_nodes",
596
- description: "Open specific nodes in the knowledge graph by their names",
597
- inputSchema: {
598
- type: "object",
599
- properties: {
600
- names: {
601
- type: "array",
602
- items: { type: "string" },
603
- description: "An array of entity names to retrieve",
644
+ {
645
+ name: "open_nodes",
646
+ description: "Open specific nodes in the knowledge graph by their names",
647
+ inputSchema: {
648
+ type: "object",
649
+ properties: {
650
+ names: {
651
+ type: "array",
652
+ items: { type: "string" },
653
+ description: "An array of entity names to retrieve",
654
+ },
604
655
  },
656
+ required: ["names"],
605
657
  },
606
- required: ["names"],
607
658
  },
608
- },
609
- {
610
- name: "get_neighbors",
611
- description: "Get neighboring entities connected to a specific entity within a given depth",
612
- inputSchema: {
613
- type: "object",
614
- properties: {
615
- entityName: { type: "string", description: "The name of the entity to find neighbors for" },
616
- depth: { type: "number", description: "Maximum depth to traverse (default: 1)", default: 1 },
659
+ {
660
+ name: "get_neighbors",
661
+ description: "Get neighboring entities connected to a specific entity within a given depth",
662
+ inputSchema: {
663
+ type: "object",
664
+ properties: {
665
+ entityName: { type: "string", description: "The name of the entity to find neighbors for" },
666
+ depth: { type: "number", description: "Maximum depth to traverse (default: 0)", default: 0 },
667
+ withEntities: { type: "boolean", description: "If true, include full entity data. Default returns only relations for lightweight structure exploration.", default: false },
668
+ },
669
+ required: ["entityName"],
617
670
  },
618
- required: ["entityName"],
619
671
  },
620
- },
621
- {
622
- name: "find_path",
623
- description: "Find a path between two entities in the knowledge graph",
624
- inputSchema: {
625
- type: "object",
626
- properties: {
627
- fromEntity: { type: "string", description: "The name of the starting entity" },
628
- toEntity: { type: "string", description: "The name of the target entity" },
629
- maxDepth: { type: "number", description: "Maximum depth to search (default: 5)", default: 5 },
672
+ {
673
+ name: "find_path",
674
+ description: "Find a path between two entities in the knowledge graph",
675
+ inputSchema: {
676
+ type: "object",
677
+ properties: {
678
+ fromEntity: { type: "string", description: "The name of the starting entity" },
679
+ toEntity: { type: "string", description: "The name of the target entity" },
680
+ maxDepth: { type: "number", description: "Maximum depth to search (default: 5)", default: 5 },
681
+ },
682
+ required: ["fromEntity", "toEntity"],
630
683
  },
631
- required: ["fromEntity", "toEntity"],
632
684
  },
633
- },
634
- {
635
- name: "get_entities_by_type",
636
- description: "Get all entities of a specific type",
637
- inputSchema: {
638
- type: "object",
639
- properties: {
640
- entityType: { type: "string", description: "The type of entities to retrieve" },
685
+ {
686
+ name: "get_entities_by_type",
687
+ description: "Get all entities of a specific type",
688
+ inputSchema: {
689
+ type: "object",
690
+ properties: {
691
+ entityType: { type: "string", description: "The type of entities to retrieve" },
692
+ },
693
+ required: ["entityType"],
641
694
  },
642
- required: ["entityType"],
643
695
  },
644
- },
645
- {
646
- name: "get_entity_types",
647
- description: "Get all unique entity types in the knowledge graph",
648
- inputSchema: {
649
- type: "object",
650
- properties: {},
696
+ {
697
+ name: "get_entity_types",
698
+ description: "Get all unique entity types in the knowledge graph",
699
+ inputSchema: {
700
+ type: "object",
701
+ properties: {},
702
+ },
651
703
  },
652
- },
653
- {
654
- name: "get_relation_types",
655
- description: "Get all unique relation types in the knowledge graph",
656
- inputSchema: {
657
- type: "object",
658
- properties: {},
704
+ {
705
+ name: "get_relation_types",
706
+ description: "Get all unique relation types in the knowledge graph",
707
+ inputSchema: {
708
+ type: "object",
709
+ properties: {},
710
+ },
659
711
  },
660
- },
661
- {
662
- name: "get_stats",
663
- description: "Get statistics about the knowledge graph",
664
- inputSchema: {
665
- type: "object",
666
- properties: {},
712
+ {
713
+ name: "get_stats",
714
+ description: "Get statistics about the knowledge graph",
715
+ inputSchema: {
716
+ type: "object",
717
+ properties: {},
718
+ },
667
719
  },
668
- },
669
- {
670
- name: "get_orphaned_entities",
671
- description: "Get entities that have no relations (orphaned entities)",
672
- inputSchema: {
673
- type: "object",
674
- properties: {},
720
+ {
721
+ name: "get_orphaned_entities",
722
+ description: "Get entities that have no relations (orphaned entities)",
723
+ inputSchema: {
724
+ type: "object",
725
+ properties: {},
726
+ },
675
727
  },
676
- },
677
- {
678
- name: "validate_graph",
679
- description: "Validate the knowledge graph and return a list of missing entities referenced in relations",
680
- inputSchema: {
681
- type: "object",
682
- properties: {},
728
+ {
729
+ name: "validate_graph",
730
+ description: "Validate the knowledge graph. Returns missing entities referenced in relations and observation limit violations (>2 observations or >140 chars).",
731
+ inputSchema: {
732
+ type: "object",
733
+ properties: {},
734
+ },
683
735
  },
684
- },
685
- {
686
- name: "evaluate_bcl",
687
- description: "Evaluate a Binary Combinatory Logic (BCL) program",
688
- inputSchema: {
689
- type: "object",
690
- properties: {
691
- program: { type: "string", description: "The BCL program as a binary string (syntax: T:=00|01|1TT) 00=K, 01=S, 1=application." },
692
- maxSteps: { type: "number", description: "Maximum number of reduction steps to perform (default: 1000000)", default: 1000000 },
736
+ {
737
+ name: "evaluate_bcl",
738
+ description: "Evaluate a Binary Combinatory Logic (BCL) program",
739
+ inputSchema: {
740
+ type: "object",
741
+ properties: {
742
+ program: { type: "string", description: "The BCL program as a binary string (syntax: T:=00|01|1TT) 00=K, 01=S, 1=application." },
743
+ maxSteps: { type: "number", description: "Maximum number of reduction steps to perform (default: 1000000)", default: 1000000 },
744
+ },
745
+ required: ["program"],
693
746
  },
694
- required: ["program"],
695
747
  },
696
- },
697
- {
698
- name: "add_bcl_term",
699
- description: "Add a BCL term to the constructor, maintaining valid syntax. Returns completion status.",
700
- inputSchema: {
701
- type: "object",
702
- properties: {
703
- term: {
704
- type: "string",
705
- description: "BCL term to add. Valid values: '1' or 'App' (application), '00' or 'K' (K combinator), '01' or 'S' (S combinator)"
748
+ {
749
+ name: "add_bcl_term",
750
+ description: "Add a BCL term to the constructor, maintaining valid syntax. Returns completion status.",
751
+ inputSchema: {
752
+ type: "object",
753
+ properties: {
754
+ term: {
755
+ type: "string",
756
+ description: "BCL term to add. Valid values: '1' or 'App' (application), '00' or 'K' (K combinator), '01' or 'S' (S combinator)"
757
+ },
706
758
  },
759
+ required: ["term"],
707
760
  },
708
- required: ["term"],
709
761
  },
710
- },
711
- {
712
- name: "clear_bcl_term",
713
- description: "Clear the current BCL term being constructed and reset the constructor state",
714
- inputSchema: {
715
- type: "object",
716
- properties: {},
762
+ {
763
+ name: "clear_bcl_term",
764
+ description: "Clear the current BCL term being constructed and reset the constructor state",
765
+ inputSchema: {
766
+ type: "object",
767
+ properties: {},
768
+ },
717
769
  },
718
- },
719
- ],
720
- };
721
- });
722
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
723
- const { name, arguments: args } = request.params;
724
- if (!args) {
725
- throw new Error(`No arguments provided for tool: ${name}`);
726
- }
727
- switch (name) {
728
- case "create_entities":
729
- return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.createEntities(args.entities), null, 2) }] };
730
- case "create_relations":
731
- return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.createRelations(args.relations), null, 2) }] };
732
- case "add_observations":
733
- return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.addObservations(args.observations), null, 2) }] };
734
- case "delete_entities":
735
- await knowledgeGraphManager.deleteEntities(args.entityNames);
736
- return { content: [{ type: "text", text: "Entities deleted successfully" }] };
737
- case "delete_observations":
738
- await knowledgeGraphManager.deleteObservations(args.deletions);
739
- return { content: [{ type: "text", text: "Observations deleted successfully" }] };
740
- case "delete_relations":
741
- await knowledgeGraphManager.deleteRelations(args.relations);
742
- return { content: [{ type: "text", text: "Relations deleted successfully" }] };
743
- case "read_graph":
744
- return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.readGraph(), null, 2) }] };
745
- case "search_nodes":
746
- return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.searchNodes(args.query), null, 2) }] };
747
- case "open_nodes_filtered":
748
- return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.openNodesFiltered(args.names), null, 2) }] };
749
- case "open_nodes":
750
- return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.openNodes(args.names), null, 2) }] };
751
- case "get_neighbors":
752
- return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.getNeighbors(args.entityName, args.depth), null, 2) }] };
753
- case "find_path":
754
- return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.findPath(args.fromEntity, args.toEntity, args.maxDepth), null, 2) }] };
755
- case "get_entities_by_type":
756
- return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.getEntitiesByType(args.entityType), null, 2) }] };
757
- case "get_entity_types":
758
- return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.getEntityTypes(), null, 2) }] };
759
- case "get_relation_types":
760
- return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.getRelationTypes(), null, 2) }] };
761
- case "get_stats":
762
- return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.getStats(), null, 2) }] };
763
- case "get_orphaned_entities":
764
- return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.getOrphanedEntities(), null, 2) }] };
765
- case "validate_graph":
766
- return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.validateGraph(), null, 2) }] };
767
- case "evaluate_bcl":
768
- return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.evaluateBCL(args.program, args.maxSteps), null, 2) }] };
769
- case "add_bcl_term":
770
- return { content: [{ type: "text", text: await knowledgeGraphManager.addBCLTerm(args.term) }] };
771
- case "clear_bcl_term":
772
- await knowledgeGraphManager.clearBCLTerm();
773
- return { content: [{ type: "text", text: "BCL term constructor cleared successfully" }] };
774
- default:
775
- throw new Error(`Unknown tool: ${name}`);
776
- }
777
- });
778
- async function main() {
770
+ ],
771
+ };
772
+ });
773
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
774
+ const { name, arguments: args } = request.params;
775
+ if (!args) {
776
+ throw new Error(`No arguments provided for tool: ${name}`);
777
+ }
778
+ switch (name) {
779
+ case "create_entities":
780
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.createEntities(args.entities), null, 2) }] };
781
+ case "create_relations":
782
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.createRelations(args.relations), null, 2) }] };
783
+ case "add_observations":
784
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.addObservations(args.observations), null, 2) }] };
785
+ case "delete_entities":
786
+ await knowledgeGraphManager.deleteEntities(args.entityNames);
787
+ return { content: [{ type: "text", text: "Entities deleted successfully" }] };
788
+ case "delete_observations":
789
+ await knowledgeGraphManager.deleteObservations(args.deletions);
790
+ return { content: [{ type: "text", text: "Observations deleted successfully" }] };
791
+ case "delete_relations":
792
+ await knowledgeGraphManager.deleteRelations(args.relations);
793
+ return { content: [{ type: "text", text: "Relations deleted successfully" }] };
794
+ case "search_nodes":
795
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.searchNodes(args.query), null, 2) }] };
796
+ case "open_nodes_filtered":
797
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.openNodesFiltered(args.names), null, 2) }] };
798
+ case "open_nodes":
799
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.openNodes(args.names), null, 2) }] };
800
+ case "get_neighbors":
801
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.getNeighbors(args.entityName, args.depth, args.withEntities), null, 2) }] };
802
+ case "find_path":
803
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.findPath(args.fromEntity, args.toEntity, args.maxDepth), null, 2) }] };
804
+ case "get_entities_by_type":
805
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.getEntitiesByType(args.entityType), null, 2) }] };
806
+ case "get_entity_types":
807
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.getEntityTypes(), null, 2) }] };
808
+ case "get_relation_types":
809
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.getRelationTypes(), null, 2) }] };
810
+ case "get_stats":
811
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.getStats(), null, 2) }] };
812
+ case "get_orphaned_entities":
813
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.getOrphanedEntities(), null, 2) }] };
814
+ case "validate_graph":
815
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.validateGraph(), null, 2) }] };
816
+ case "evaluate_bcl":
817
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.evaluateBCL(args.program, args.maxSteps), null, 2) }] };
818
+ case "add_bcl_term":
819
+ return { content: [{ type: "text", text: await knowledgeGraphManager.addBCLTerm(args.term) }] };
820
+ case "clear_bcl_term":
821
+ await knowledgeGraphManager.clearBCLTerm();
822
+ return { content: [{ type: "text", text: "BCL term constructor cleared successfully" }] };
823
+ default:
824
+ throw new Error(`Unknown tool: ${name}`);
825
+ }
826
+ });
827
+ return server;
828
+ }
829
+ // Main entry point - only runs when executed directly, not when imported
830
+ const isMainModule = process.argv[1] && (process.argv[1].endsWith('index.js') ||
831
+ process.argv[1].endsWith('index.ts'));
832
+ if (isMainModule) {
833
+ const server = createServer();
779
834
  const transport = new StdioServerTransport();
780
- await server.connect(transport);
781
- console.error("Knowledge Graph MCP Server running on stdio");
835
+ server.connect(transport).then(() => {
836
+ console.error("Knowledge Graph MCP Server running on stdio");
837
+ }).catch((error) => {
838
+ console.error("Fatal error:", error);
839
+ process.exit(1);
840
+ });
782
841
  }
783
- main().catch((error) => {
784
- console.error("Fatal error in main():", error);
785
- process.exit(1);
786
- });