@levalicious/server-memory 0.0.5 → 0.0.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/dist/index.js +7 -839
- package/dist/server.js +857 -0
- package/dist/tests/memory-server.test.js +1 -1
- package/package.json +4 -2
package/dist/index.js
CHANGED
|
@@ -1,841 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
3
2
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
const DEFAULT_MEMORY_FILE_PATH = process.env.MEMORY_FILE_PATH
|
|
12
|
-
? path.isAbsolute(process.env.MEMORY_FILE_PATH)
|
|
13
|
-
? process.env.MEMORY_FILE_PATH
|
|
14
|
-
: path.join(path.dirname(fileURLToPath(import.meta.url)), process.env.MEMORY_FILE_PATH)
|
|
15
|
-
: defaultMemoryPath;
|
|
16
|
-
// The KnowledgeGraphManager class contains all operations to interact with the knowledge graph
|
|
17
|
-
export class KnowledgeGraphManager {
|
|
18
|
-
bclCtr = 0;
|
|
19
|
-
bclTerm = "";
|
|
20
|
-
memoryFilePath;
|
|
21
|
-
constructor(memoryFilePath = DEFAULT_MEMORY_FILE_PATH) {
|
|
22
|
-
this.memoryFilePath = memoryFilePath;
|
|
23
|
-
}
|
|
24
|
-
async loadGraph() {
|
|
25
|
-
try {
|
|
26
|
-
const data = await fs.readFile(this.memoryFilePath, "utf-8");
|
|
27
|
-
const lines = data.split("\n").filter(line => line.trim() !== "");
|
|
28
|
-
return lines.reduce((graph, line) => {
|
|
29
|
-
const item = JSON.parse(line);
|
|
30
|
-
if (item.type === "entity")
|
|
31
|
-
graph.entities.push(item);
|
|
32
|
-
if (item.type === "relation")
|
|
33
|
-
graph.relations.push(item);
|
|
34
|
-
return graph;
|
|
35
|
-
}, { entities: [], relations: [] });
|
|
36
|
-
}
|
|
37
|
-
catch (error) {
|
|
38
|
-
if (error?.code === "ENOENT") {
|
|
39
|
-
return { entities: [], relations: [] };
|
|
40
|
-
}
|
|
41
|
-
throw error;
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
async saveGraph(graph) {
|
|
45
|
-
const lines = [
|
|
46
|
-
...graph.entities.map(e => JSON.stringify({ type: "entity", ...e })),
|
|
47
|
-
...graph.relations.map(r => JSON.stringify({ type: "relation", ...r })),
|
|
48
|
-
];
|
|
49
|
-
await fs.writeFile(this.memoryFilePath, lines.join("\n"));
|
|
50
|
-
}
|
|
51
|
-
async createEntities(entities) {
|
|
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
|
-
}
|
|
64
|
-
const newEntities = entities.filter(e => !graph.entities.some(existingEntity => existingEntity.name === e.name));
|
|
65
|
-
graph.entities.push(...newEntities);
|
|
66
|
-
await this.saveGraph(graph);
|
|
67
|
-
return newEntities;
|
|
68
|
-
}
|
|
69
|
-
async createRelations(relations) {
|
|
70
|
-
const graph = await this.loadGraph();
|
|
71
|
-
const newRelations = relations.filter(r => !graph.relations.some(existingRelation => existingRelation.from === r.from &&
|
|
72
|
-
existingRelation.to === r.to &&
|
|
73
|
-
existingRelation.relationType === r.relationType));
|
|
74
|
-
graph.relations.push(...newRelations);
|
|
75
|
-
await this.saveGraph(graph);
|
|
76
|
-
return newRelations;
|
|
77
|
-
}
|
|
78
|
-
async addObservations(observations) {
|
|
79
|
-
const graph = await this.loadGraph();
|
|
80
|
-
const results = observations.map(o => {
|
|
81
|
-
const entity = graph.entities.find(e => e.name === o.entityName);
|
|
82
|
-
if (!entity) {
|
|
83
|
-
throw new Error(`Entity with name ${o.entityName} not found`);
|
|
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
|
-
}
|
|
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
|
-
}
|
|
96
|
-
entity.observations.push(...newObservations);
|
|
97
|
-
return { entityName: o.entityName, addedObservations: newObservations };
|
|
98
|
-
});
|
|
99
|
-
await this.saveGraph(graph);
|
|
100
|
-
return results;
|
|
101
|
-
}
|
|
102
|
-
async deleteEntities(entityNames) {
|
|
103
|
-
const graph = await this.loadGraph();
|
|
104
|
-
graph.entities = graph.entities.filter(e => !entityNames.includes(e.name));
|
|
105
|
-
graph.relations = graph.relations.filter(r => !entityNames.includes(r.from) && !entityNames.includes(r.to));
|
|
106
|
-
await this.saveGraph(graph);
|
|
107
|
-
}
|
|
108
|
-
async deleteObservations(deletions) {
|
|
109
|
-
const graph = await this.loadGraph();
|
|
110
|
-
deletions.forEach(d => {
|
|
111
|
-
const entity = graph.entities.find(e => e.name === d.entityName);
|
|
112
|
-
if (entity) {
|
|
113
|
-
entity.observations = entity.observations.filter(o => !d.observations.includes(o));
|
|
114
|
-
}
|
|
115
|
-
});
|
|
116
|
-
await this.saveGraph(graph);
|
|
117
|
-
}
|
|
118
|
-
async deleteRelations(relations) {
|
|
119
|
-
const graph = await this.loadGraph();
|
|
120
|
-
graph.relations = graph.relations.filter(r => !relations.some(delRelation => r.from === delRelation.from &&
|
|
121
|
-
r.to === delRelation.to &&
|
|
122
|
-
r.relationType === delRelation.relationType));
|
|
123
|
-
await this.saveGraph(graph);
|
|
124
|
-
}
|
|
125
|
-
// Regex-based search function
|
|
126
|
-
async searchNodes(query) {
|
|
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
|
-
}
|
|
135
|
-
// Filter entities
|
|
136
|
-
const filteredEntities = graph.entities.filter(e => regex.test(e.name) ||
|
|
137
|
-
regex.test(e.entityType) ||
|
|
138
|
-
e.observations.some(o => regex.test(o)));
|
|
139
|
-
// Create a Set of filtered entity names for quick lookup
|
|
140
|
-
const filteredEntityNames = new Set(filteredEntities.map(e => e.name));
|
|
141
|
-
// Filter relations to only include those between filtered entities
|
|
142
|
-
const filteredRelations = graph.relations.filter(r => filteredEntityNames.has(r.from) && filteredEntityNames.has(r.to));
|
|
143
|
-
const filteredGraph = {
|
|
144
|
-
entities: filteredEntities,
|
|
145
|
-
relations: filteredRelations,
|
|
146
|
-
};
|
|
147
|
-
return filteredGraph;
|
|
148
|
-
}
|
|
149
|
-
async openNodesFiltered(names) {
|
|
150
|
-
const graph = await this.loadGraph();
|
|
151
|
-
// Filter entities
|
|
152
|
-
const filteredEntities = graph.entities.filter(e => names.includes(e.name));
|
|
153
|
-
// Create a Set of filtered entity names for quick lookup
|
|
154
|
-
const filteredEntityNames = new Set(filteredEntities.map(e => e.name));
|
|
155
|
-
// Filter relations to only include those between filtered entities
|
|
156
|
-
const filteredRelations = graph.relations.filter(r => filteredEntityNames.has(r.from) && filteredEntityNames.has(r.to));
|
|
157
|
-
const filteredGraph = {
|
|
158
|
-
entities: filteredEntities,
|
|
159
|
-
relations: filteredRelations,
|
|
160
|
-
};
|
|
161
|
-
return filteredGraph;
|
|
162
|
-
}
|
|
163
|
-
async openNodes(names) {
|
|
164
|
-
const graph = await this.loadGraph();
|
|
165
|
-
// Filter entities
|
|
166
|
-
const filteredEntities = graph.entities.filter(e => names.includes(e.name));
|
|
167
|
-
// Create a Set of filtered entity names for quick lookup
|
|
168
|
-
const filteredEntityNames = new Set(filteredEntities.map(e => e.name));
|
|
169
|
-
// Filter relations to only include those between filtered entities
|
|
170
|
-
const filteredRelations = graph.relations.filter(r => filteredEntityNames.has(r.from));
|
|
171
|
-
const filteredGraph = {
|
|
172
|
-
entities: filteredEntities,
|
|
173
|
-
relations: filteredRelations,
|
|
174
|
-
};
|
|
175
|
-
return filteredGraph;
|
|
176
|
-
}
|
|
177
|
-
async getNeighbors(entityName, depth = 1, withEntities = false) {
|
|
178
|
-
const graph = await this.loadGraph();
|
|
179
|
-
const visited = new Set();
|
|
180
|
-
const resultEntities = new Map();
|
|
181
|
-
const resultRelations = new Map(); // Deduplicate relations
|
|
182
|
-
const relationKey = (r) => `${r.from}|${r.relationType}|${r.to}`;
|
|
183
|
-
const traverse = (currentName, currentDepth) => {
|
|
184
|
-
if (currentDepth > depth || visited.has(currentName))
|
|
185
|
-
return;
|
|
186
|
-
visited.add(currentName);
|
|
187
|
-
if (withEntities) {
|
|
188
|
-
const entity = graph.entities.find(e => e.name === currentName);
|
|
189
|
-
if (entity) {
|
|
190
|
-
resultEntities.set(currentName, entity);
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
// Find all relations involving this entity
|
|
194
|
-
const connectedRelations = graph.relations.filter(r => r.from === currentName || r.to === currentName);
|
|
195
|
-
connectedRelations.forEach(r => resultRelations.set(relationKey(r), r));
|
|
196
|
-
if (currentDepth < depth) {
|
|
197
|
-
// Traverse to connected entities
|
|
198
|
-
connectedRelations.forEach(r => {
|
|
199
|
-
const nextEntity = r.from === currentName ? r.to : r.from;
|
|
200
|
-
traverse(nextEntity, currentDepth + 1);
|
|
201
|
-
});
|
|
202
|
-
}
|
|
203
|
-
};
|
|
204
|
-
traverse(entityName, 0);
|
|
205
|
-
return {
|
|
206
|
-
entities: Array.from(resultEntities.values()),
|
|
207
|
-
relations: Array.from(resultRelations.values())
|
|
208
|
-
};
|
|
209
|
-
}
|
|
210
|
-
async findPath(fromEntity, toEntity, maxDepth = 5) {
|
|
211
|
-
const graph = await this.loadGraph();
|
|
212
|
-
const visited = new Set();
|
|
213
|
-
const dfs = (current, target, path, depth) => {
|
|
214
|
-
if (depth > maxDepth || visited.has(current))
|
|
215
|
-
return null;
|
|
216
|
-
if (current === target)
|
|
217
|
-
return path;
|
|
218
|
-
visited.add(current);
|
|
219
|
-
const outgoingRelations = graph.relations.filter(r => r.from === current);
|
|
220
|
-
for (const relation of outgoingRelations) {
|
|
221
|
-
const result = dfs(relation.to, target, [...path, relation], depth + 1);
|
|
222
|
-
if (result)
|
|
223
|
-
return result;
|
|
224
|
-
}
|
|
225
|
-
visited.delete(current);
|
|
226
|
-
return null;
|
|
227
|
-
};
|
|
228
|
-
return dfs(fromEntity, toEntity, [], 0) || [];
|
|
229
|
-
}
|
|
230
|
-
async getEntitiesByType(entityType) {
|
|
231
|
-
const graph = await this.loadGraph();
|
|
232
|
-
return graph.entities.filter(e => e.entityType === entityType);
|
|
233
|
-
}
|
|
234
|
-
async getEntityTypes() {
|
|
235
|
-
const graph = await this.loadGraph();
|
|
236
|
-
const types = new Set(graph.entities.map(e => e.entityType));
|
|
237
|
-
return Array.from(types).sort();
|
|
238
|
-
}
|
|
239
|
-
async getRelationTypes() {
|
|
240
|
-
const graph = await this.loadGraph();
|
|
241
|
-
const types = new Set(graph.relations.map(r => r.relationType));
|
|
242
|
-
return Array.from(types).sort();
|
|
243
|
-
}
|
|
244
|
-
async getStats() {
|
|
245
|
-
const graph = await this.loadGraph();
|
|
246
|
-
const entityTypes = new Set(graph.entities.map(e => e.entityType));
|
|
247
|
-
const relationTypes = new Set(graph.relations.map(r => r.relationType));
|
|
248
|
-
return {
|
|
249
|
-
entityCount: graph.entities.length,
|
|
250
|
-
relationCount: graph.relations.length,
|
|
251
|
-
entityTypes: entityTypes.size,
|
|
252
|
-
relationTypes: relationTypes.size
|
|
253
|
-
};
|
|
254
|
-
}
|
|
255
|
-
async getOrphanedEntities() {
|
|
256
|
-
const graph = await this.loadGraph();
|
|
257
|
-
const connectedEntityNames = new Set();
|
|
258
|
-
graph.relations.forEach(r => {
|
|
259
|
-
connectedEntityNames.add(r.from);
|
|
260
|
-
connectedEntityNames.add(r.to);
|
|
261
|
-
});
|
|
262
|
-
return graph.entities.filter(e => !connectedEntityNames.has(e.name));
|
|
263
|
-
}
|
|
264
|
-
async validateGraph() {
|
|
265
|
-
const graph = await this.loadGraph();
|
|
266
|
-
const entityNames = new Set(graph.entities.map(e => e.name));
|
|
267
|
-
const missingEntities = new Set();
|
|
268
|
-
const observationViolations = [];
|
|
269
|
-
// Check for missing entities in relations
|
|
270
|
-
graph.relations.forEach(r => {
|
|
271
|
-
if (!entityNames.has(r.from)) {
|
|
272
|
-
missingEntities.add(r.from);
|
|
273
|
-
}
|
|
274
|
-
if (!entityNames.has(r.to)) {
|
|
275
|
-
missingEntities.add(r.to);
|
|
276
|
-
}
|
|
277
|
-
});
|
|
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
|
-
};
|
|
298
|
-
}
|
|
299
|
-
// BCL (Binary Combinatory Logic) evaluator
|
|
300
|
-
async evaluateBCL(program, maxSteps) {
|
|
301
|
-
let stepCount = 0;
|
|
302
|
-
let max_size = program.length;
|
|
303
|
-
let mode = 0;
|
|
304
|
-
let ctr = 1;
|
|
305
|
-
let t0 = program;
|
|
306
|
-
let t1 = '';
|
|
307
|
-
let t2 = '';
|
|
308
|
-
let t3 = '';
|
|
309
|
-
let t4 = '';
|
|
310
|
-
while (stepCount < maxSteps) {
|
|
311
|
-
if (t0.length == 0)
|
|
312
|
-
break;
|
|
313
|
-
let b = t0[0];
|
|
314
|
-
t0 = t0.slice(1);
|
|
315
|
-
if (mode === 0) {
|
|
316
|
-
t1 += b;
|
|
317
|
-
let size = t1.length + t0.length;
|
|
318
|
-
if (size > max_size)
|
|
319
|
-
max_size = size;
|
|
320
|
-
if (t1.slice(-4) === '1100') {
|
|
321
|
-
mode = 1;
|
|
322
|
-
t1 = t1.slice(0, -4);
|
|
323
|
-
}
|
|
324
|
-
else if (t1.slice(-5) === '11101') {
|
|
325
|
-
mode = 3;
|
|
326
|
-
t1 = t1.slice(0, -5);
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
else if (mode === 1) {
|
|
330
|
-
t2 += b;
|
|
331
|
-
if (b == '1') {
|
|
332
|
-
ctr += 1;
|
|
333
|
-
}
|
|
334
|
-
else if (b == '0') {
|
|
335
|
-
ctr -= 1;
|
|
336
|
-
t2 += t0[0];
|
|
337
|
-
t0 = t0.slice(1);
|
|
338
|
-
}
|
|
339
|
-
if (ctr === 0) {
|
|
340
|
-
mode = 2;
|
|
341
|
-
ctr = 1;
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
else if (mode === 2) {
|
|
345
|
-
if (b == '1') {
|
|
346
|
-
ctr += 1;
|
|
347
|
-
}
|
|
348
|
-
else if (b == '0') {
|
|
349
|
-
ctr -= 1;
|
|
350
|
-
t0 = t0.slice(1);
|
|
351
|
-
}
|
|
352
|
-
if (ctr === 0) {
|
|
353
|
-
t0 = t2 + t0;
|
|
354
|
-
t2 = '';
|
|
355
|
-
mode = 0;
|
|
356
|
-
ctr = 1;
|
|
357
|
-
stepCount += 1;
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
else if (mode === 3) {
|
|
361
|
-
t2 += b;
|
|
362
|
-
if (b == '1') {
|
|
363
|
-
ctr += 1;
|
|
364
|
-
}
|
|
365
|
-
else if (b == '0') {
|
|
366
|
-
ctr -= 1;
|
|
367
|
-
t2 += t0[0];
|
|
368
|
-
t0 = t0.slice(1);
|
|
369
|
-
}
|
|
370
|
-
if (ctr === 0) {
|
|
371
|
-
mode = 4;
|
|
372
|
-
ctr = 1;
|
|
373
|
-
}
|
|
374
|
-
}
|
|
375
|
-
else if (mode === 4) {
|
|
376
|
-
t3 += b;
|
|
377
|
-
if (b == '1') {
|
|
378
|
-
ctr += 1;
|
|
379
|
-
}
|
|
380
|
-
else if (b == '0') {
|
|
381
|
-
ctr -= 1;
|
|
382
|
-
t3 += t0[0];
|
|
383
|
-
t0 = t0.slice(1);
|
|
384
|
-
}
|
|
385
|
-
if (ctr === 0) {
|
|
386
|
-
mode = 5;
|
|
387
|
-
ctr = 1;
|
|
388
|
-
}
|
|
389
|
-
}
|
|
390
|
-
else if (mode === 5) {
|
|
391
|
-
t4 += b;
|
|
392
|
-
if (b == '1') {
|
|
393
|
-
ctr += 1;
|
|
394
|
-
}
|
|
395
|
-
else if (b == '0') {
|
|
396
|
-
ctr -= 1;
|
|
397
|
-
t4 += t0[0];
|
|
398
|
-
t0 = t0.slice(1);
|
|
399
|
-
}
|
|
400
|
-
if (ctr === 0) {
|
|
401
|
-
t0 = '11' + t2 + t4 + '1' + t3 + t4 + t0;
|
|
402
|
-
t2 = '';
|
|
403
|
-
t3 = '';
|
|
404
|
-
t4 = '';
|
|
405
|
-
mode = 0;
|
|
406
|
-
ctr = 1;
|
|
407
|
-
stepCount += 1;
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
}
|
|
411
|
-
const halted = stepCount < maxSteps;
|
|
412
|
-
return {
|
|
413
|
-
result: t1,
|
|
414
|
-
info: `${stepCount} steps, max size ${max_size}`,
|
|
415
|
-
halted,
|
|
416
|
-
errored: halted && mode != 0,
|
|
417
|
-
};
|
|
418
|
-
}
|
|
419
|
-
async addBCLTerm(term) {
|
|
420
|
-
const termset = ["1", "00", "01"];
|
|
421
|
-
if (!term || term.trim() === "") {
|
|
422
|
-
throw new Error("BCL term cannot be empty");
|
|
423
|
-
}
|
|
424
|
-
// Term can be 1, 00, 01, or K, S, App (application)
|
|
425
|
-
const validTerms = ["1", "App", "00", "K", "01", "S"];
|
|
426
|
-
if (!validTerms.includes(term)) {
|
|
427
|
-
throw new Error(`Invalid BCL term: ${term}\nExpected one of: ${validTerms.join(", ")}`);
|
|
428
|
-
}
|
|
429
|
-
let processedTerm = 0;
|
|
430
|
-
if (term === "00" || term === "K")
|
|
431
|
-
processedTerm = 1;
|
|
432
|
-
else if (term === "01" || term === "S")
|
|
433
|
-
processedTerm = 2;
|
|
434
|
-
this.bclTerm += termset[processedTerm];
|
|
435
|
-
if (processedTerm === 0) {
|
|
436
|
-
if (this.bclCtr === 0)
|
|
437
|
-
this.bclCtr += 1;
|
|
438
|
-
this.bclCtr += 1;
|
|
439
|
-
}
|
|
440
|
-
else {
|
|
441
|
-
this.bclCtr -= 1;
|
|
442
|
-
}
|
|
443
|
-
if (this.bclCtr <= 0) {
|
|
444
|
-
const constructedProgram = this.bclTerm;
|
|
445
|
-
this.bclCtr = 0;
|
|
446
|
-
this.bclTerm = "";
|
|
447
|
-
return `Constructed Program: ${constructedProgram}`;
|
|
448
|
-
}
|
|
449
|
-
else {
|
|
450
|
-
return `Need ${this.bclCtr} more term(s) to complete the program.`;
|
|
451
|
-
}
|
|
452
|
-
}
|
|
453
|
-
async clearBCLTerm() {
|
|
454
|
-
this.bclCtr = 0;
|
|
455
|
-
this.bclTerm = "";
|
|
456
|
-
}
|
|
457
|
-
}
|
|
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
|
-
},
|
|
500
|
-
},
|
|
501
|
-
required: ["name", "entityType", "observations"],
|
|
502
|
-
},
|
|
503
|
-
},
|
|
504
|
-
},
|
|
505
|
-
required: ["entities"],
|
|
506
|
-
},
|
|
507
|
-
},
|
|
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"],
|
|
524
|
-
},
|
|
525
|
-
},
|
|
526
|
-
},
|
|
527
|
-
required: ["relations"],
|
|
528
|
-
},
|
|
529
|
-
},
|
|
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
|
-
},
|
|
547
|
-
},
|
|
548
|
-
required: ["entityName", "contents"],
|
|
549
|
-
},
|
|
550
|
-
},
|
|
551
|
-
},
|
|
552
|
-
required: ["observations"],
|
|
553
|
-
},
|
|
554
|
-
},
|
|
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
|
-
},
|
|
566
|
-
},
|
|
567
|
-
required: ["entityNames"],
|
|
568
|
-
},
|
|
569
|
-
},
|
|
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
|
-
},
|
|
587
|
-
},
|
|
588
|
-
required: ["entityName", "observations"],
|
|
589
|
-
},
|
|
590
|
-
},
|
|
591
|
-
},
|
|
592
|
-
required: ["deletions"],
|
|
593
|
-
},
|
|
594
|
-
},
|
|
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"],
|
|
611
|
-
},
|
|
612
|
-
description: "An array of relations to delete"
|
|
613
|
-
},
|
|
614
|
-
},
|
|
615
|
-
required: ["relations"],
|
|
616
|
-
},
|
|
617
|
-
},
|
|
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"],
|
|
627
|
-
},
|
|
628
|
-
},
|
|
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
|
-
},
|
|
640
|
-
},
|
|
641
|
-
required: ["names"],
|
|
642
|
-
},
|
|
643
|
-
},
|
|
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
|
-
},
|
|
655
|
-
},
|
|
656
|
-
required: ["names"],
|
|
657
|
-
},
|
|
658
|
-
},
|
|
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"],
|
|
670
|
-
},
|
|
671
|
-
},
|
|
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"],
|
|
683
|
-
},
|
|
684
|
-
},
|
|
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"],
|
|
694
|
-
},
|
|
695
|
-
},
|
|
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
|
-
},
|
|
703
|
-
},
|
|
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
|
-
},
|
|
711
|
-
},
|
|
712
|
-
{
|
|
713
|
-
name: "get_stats",
|
|
714
|
-
description: "Get statistics about the knowledge graph",
|
|
715
|
-
inputSchema: {
|
|
716
|
-
type: "object",
|
|
717
|
-
properties: {},
|
|
718
|
-
},
|
|
719
|
-
},
|
|
720
|
-
{
|
|
721
|
-
name: "get_orphaned_entities",
|
|
722
|
-
description: "Get entities that have no relations (orphaned entities)",
|
|
723
|
-
inputSchema: {
|
|
724
|
-
type: "object",
|
|
725
|
-
properties: {},
|
|
726
|
-
},
|
|
727
|
-
},
|
|
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
|
-
},
|
|
735
|
-
},
|
|
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"],
|
|
746
|
-
},
|
|
747
|
-
},
|
|
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
|
-
},
|
|
758
|
-
},
|
|
759
|
-
required: ["term"],
|
|
760
|
-
},
|
|
761
|
-
},
|
|
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
|
-
},
|
|
769
|
-
},
|
|
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();
|
|
834
|
-
const transport = new StdioServerTransport();
|
|
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
|
-
});
|
|
841
|
-
}
|
|
3
|
+
import { createServer } from "./server.js";
|
|
4
|
+
const server = createServer();
|
|
5
|
+
const transport = new StdioServerTransport();
|
|
6
|
+
server.connect(transport).catch((error) => {
|
|
7
|
+
console.error("Fatal error:", error);
|
|
8
|
+
process.exit(1);
|
|
9
|
+
});
|