@levalicious/server-memory 0.0.0

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.
Files changed (3) hide show
  1. package/README.md +281 -0
  2. package/dist/index.js +579 -0
  3. package/package.json +29 -0
package/README.md ADDED
@@ -0,0 +1,281 @@
1
+ # Knowledge Graph Memory Server
2
+
3
+ A basic implementation of persistent memory using a local knowledge graph. This lets Claude remember information about the user across chats.
4
+
5
+ ## Core Concepts
6
+
7
+ ### Entities
8
+ Entities are the primary nodes in the knowledge graph. Each entity has:
9
+ - A unique name (identifier)
10
+ - An entity type (e.g., "person", "organization", "event")
11
+ - A list of observations
12
+
13
+ Example:
14
+ ```json
15
+ {
16
+ "name": "John_Smith",
17
+ "entityType": "person",
18
+ "observations": ["Speaks fluent Spanish"]
19
+ }
20
+ ```
21
+
22
+ ### Relations
23
+ Relations define directed connections between entities. They are always stored in active voice and describe how entities interact or relate to each other.
24
+
25
+ Example:
26
+ ```json
27
+ {
28
+ "from": "John_Smith",
29
+ "to": "Anthropic",
30
+ "relationType": "works_at"
31
+ }
32
+ ```
33
+ ### Observations
34
+ Observations are discrete pieces of information about an entity. They are:
35
+
36
+ - Stored as strings
37
+ - Attached to specific entities
38
+ - Can be added or removed independently
39
+ - Should be atomic (one fact per observation)
40
+
41
+ Example:
42
+ ```json
43
+ {
44
+ "entityName": "John_Smith",
45
+ "observations": [
46
+ "Speaks fluent Spanish",
47
+ "Graduated in 2019",
48
+ "Prefers morning meetings"
49
+ ]
50
+ }
51
+ ```
52
+
53
+ ## API
54
+
55
+ ### Tools
56
+ - **create_entities**
57
+ - Create multiple new entities in the knowledge graph
58
+ - Input: `entities` (array of objects)
59
+ - Each object contains:
60
+ - `name` (string): Entity identifier
61
+ - `entityType` (string): Type classification
62
+ - `observations` (string[]): Associated observations
63
+ - Ignores entities with existing names
64
+
65
+ - **create_relations**
66
+ - Create multiple new relations between entities
67
+ - Input: `relations` (array of objects)
68
+ - Each object contains:
69
+ - `from` (string): Source entity name
70
+ - `to` (string): Target entity name
71
+ - `relationType` (string): Relationship type in active voice
72
+ - Skips duplicate relations
73
+
74
+ - **add_observations**
75
+ - Add new observations to existing entities
76
+ - Input: `observations` (array of objects)
77
+ - Each object contains:
78
+ - `entityName` (string): Target entity
79
+ - `contents` (string[]): New observations to add
80
+ - Returns added observations per entity
81
+ - Fails if entity doesn't exist
82
+
83
+ - **delete_entities**
84
+ - Remove entities and their relations
85
+ - Input: `entityNames` (string[])
86
+ - Cascading deletion of associated relations
87
+ - Silent operation if entity doesn't exist
88
+
89
+ - **delete_observations**
90
+ - Remove specific observations from entities
91
+ - Input: `deletions` (array of objects)
92
+ - Each object contains:
93
+ - `entityName` (string): Target entity
94
+ - `observations` (string[]): Observations to remove
95
+ - Silent operation if observation doesn't exist
96
+
97
+ - **delete_relations**
98
+ - Remove specific relations from the graph
99
+ - Input: `relations` (array of objects)
100
+ - Each object contains:
101
+ - `from` (string): Source entity name
102
+ - `to` (string): Target entity name
103
+ - `relationType` (string): Relationship type
104
+ - Silent operation if relation doesn't exist
105
+
106
+ - **read_graph**
107
+ - Read the entire knowledge graph
108
+ - No input required
109
+ - Returns complete graph structure with all entities and relations
110
+
111
+ - **search_nodes**
112
+ - Search for nodes based on query
113
+ - Input: `query` (string)
114
+ - Searches across:
115
+ - Entity names
116
+ - Entity types
117
+ - Observation content
118
+ - Returns matching entities and their relations
119
+
120
+ - **open_nodes**
121
+ - Retrieve specific nodes by name
122
+ - Input: `names` (string[])
123
+ - Returns:
124
+ - Requested entities
125
+ - Relations between requested entities
126
+ - Silently skips non-existent nodes
127
+
128
+ # Usage with Claude Desktop
129
+
130
+ ### Setup
131
+
132
+ Add this to your claude_desktop_config.json:
133
+
134
+ #### Docker
135
+
136
+ ```json
137
+ {
138
+ "mcpServers": {
139
+ "memory": {
140
+ "command": "docker",
141
+ "args": ["run", "-i", "-v", "claude-memory:/app/dist", "--rm", "mcp/memory"]
142
+ }
143
+ }
144
+ }
145
+ ```
146
+
147
+ #### NPX
148
+ ```json
149
+ {
150
+ "mcpServers": {
151
+ "memory": {
152
+ "command": "npx",
153
+ "args": [
154
+ "-y",
155
+ "@levalicious/server-memory"
156
+ ]
157
+ }
158
+ }
159
+ }
160
+ ```
161
+
162
+ #### NPX with custom setting
163
+
164
+ The server can be configured using the following environment variables:
165
+
166
+ ```json
167
+ {
168
+ "mcpServers": {
169
+ "memory": {
170
+ "command": "npx",
171
+ "args": [
172
+ "-y",
173
+ "@levalicious/server-memory"
174
+ ],
175
+ "env": {
176
+ "MEMORY_FILE_PATH": "/path/to/custom/memory.json"
177
+ }
178
+ }
179
+ }
180
+ }
181
+ ```
182
+
183
+ - `MEMORY_FILE_PATH`: Path to the memory storage JSON file (default: `memory.json` in the server directory)
184
+
185
+ # VS Code Installation Instructions
186
+
187
+ For quick installation, use one of the one-click installation buttons below:
188
+
189
+ [![Install with NPX in VS Code](https://img.shields.io/badge/VS_Code-NPM-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=memory&config=%7B%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40modelcontextprotocol%2Fserver-memory%22%5D%7D) [![Install with NPX in VS Code Insiders](https://img.shields.io/badge/VS_Code_Insiders-NPM-24bfa5?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=memory&config=%7B%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40modelcontextprotocol%2Fserver-memory%22%5D%7D&quality=insiders)
190
+
191
+ [![Install with Docker in VS Code](https://img.shields.io/badge/VS_Code-Docker-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=memory&config=%7B%22command%22%3A%22docker%22%2C%22args%22%3A%5B%22run%22%2C%22-i%22%2C%22-v%22%2C%22claude-memory%3A%2Fapp%2Fdist%22%2C%22--rm%22%2C%22mcp%2Fmemory%22%5D%7D) [![Install with Docker in VS Code Insiders](https://img.shields.io/badge/VS_Code_Insiders-Docker-24bfa5?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=memory&config=%7B%22command%22%3A%22docker%22%2C%22args%22%3A%5B%22run%22%2C%22-i%22%2C%22-v%22%2C%22claude-memory%3A%2Fapp%2Fdist%22%2C%22--rm%22%2C%22mcp%2Fmemory%22%5D%7D&quality=insiders)
192
+
193
+ For manual installation, add the following JSON block to your User Settings (JSON) file in VS Code. You can do this by pressing `Ctrl + Shift + P` and typing `Preferences: Open Settings (JSON)`.
194
+
195
+ Optionally, you can add it to a file called `.vscode/mcp.json` in your workspace. This will allow you to share the configuration with others.
196
+
197
+ > Note that the `mcp` key is not needed in the `.vscode/mcp.json` file.
198
+
199
+ #### NPX
200
+
201
+ ```json
202
+ {
203
+ "mcp": {
204
+ "servers": {
205
+ "memory": {
206
+ "command": "npx",
207
+ "args": [
208
+ "-y",
209
+ "@levalicious/server-memory"
210
+ ]
211
+ }
212
+ }
213
+ }
214
+ }
215
+ ```
216
+
217
+ #### Docker
218
+
219
+ ```json
220
+ {
221
+ "mcp": {
222
+ "servers": {
223
+ "memory": {
224
+ "command": "docker",
225
+ "args": [
226
+ "run",
227
+ "-i",
228
+ "-v",
229
+ "claude-memory:/app/dist",
230
+ "--rm",
231
+ "mcp/memory"
232
+ ]
233
+ }
234
+ }
235
+ }
236
+ }
237
+ ```
238
+
239
+ ### System Prompt
240
+
241
+ The prompt for utilizing memory depends on the use case. Changing the prompt will help the model determine the frequency and types of memories created.
242
+
243
+ Here is an example prompt for chat personalization. You could use this prompt in the "Custom Instructions" field of a [Claude.ai Project](https://www.anthropic.com/news/projects).
244
+
245
+ ```
246
+ Follow these steps for each interaction:
247
+
248
+ 1. User Identification:
249
+ - You should assume that you are interacting with default_user
250
+ - If you have not identified default_user, proactively try to do so.
251
+
252
+ 2. Memory Retrieval:
253
+ - Always begin your chat by saying only "Remembering..." and retrieve all relevant information from your knowledge graph
254
+ - Always refer to your knowledge graph as your "memory"
255
+
256
+ 3. Memory
257
+ - While conversing with the user, be attentive to any new information that falls into these categories:
258
+ a) Basic Identity (age, gender, location, job title, education level, etc.)
259
+ b) Behaviors (interests, habits, etc.)
260
+ c) Preferences (communication style, preferred language, etc.)
261
+ d) Goals (goals, targets, aspirations, etc.)
262
+ e) Relationships (personal and professional relationships up to 3 degrees of separation)
263
+
264
+ 4. Memory Update:
265
+ - If any new information was gathered during the interaction, update your memory as follows:
266
+ a) Create entities for recurring organizations, people, and significant events
267
+ b) Connect them to the current entities using relations
268
+ c) Store facts about them as observations
269
+ ```
270
+
271
+ ## Building
272
+
273
+ Docker:
274
+
275
+ ```sh
276
+ docker build -t mcp/memory -f src/memory/Dockerfile .
277
+ ```
278
+
279
+ ## License
280
+
281
+ This MCP server is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository.
package/dist/index.js ADDED
@@ -0,0 +1,579 @@
1
+ #!/usr/bin/env node
2
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
5
+ import { promises as fs } from 'fs';
6
+ import path from 'path';
7
+ import { fileURLToPath } from 'url';
8
+ // Define memory file path using environment variable with fallback
9
+ const defaultMemoryPath = path.join(path.dirname(fileURLToPath(import.meta.url)), 'memory.json');
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
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
+ class KnowledgeGraphManager {
18
+ async loadGraph() {
19
+ try {
20
+ const data = await fs.readFile(MEMORY_FILE_PATH, "utf-8");
21
+ const lines = data.split("\n").filter(line => line.trim() !== "");
22
+ return lines.reduce((graph, line) => {
23
+ const item = JSON.parse(line);
24
+ if (item.type === "entity")
25
+ graph.entities.push(item);
26
+ if (item.type === "relation")
27
+ graph.relations.push(item);
28
+ return graph;
29
+ }, { entities: [], relations: [] });
30
+ }
31
+ catch (error) {
32
+ if (error instanceof Error && 'code' in error && error.code === "ENOENT") {
33
+ return { entities: [], relations: [] };
34
+ }
35
+ throw error;
36
+ }
37
+ }
38
+ async saveGraph(graph) {
39
+ const lines = [
40
+ ...graph.entities.map(e => JSON.stringify({ type: "entity", ...e })),
41
+ ...graph.relations.map(r => JSON.stringify({ type: "relation", ...r })),
42
+ ];
43
+ await fs.writeFile(MEMORY_FILE_PATH, lines.join("\n"));
44
+ }
45
+ async createEntities(entities) {
46
+ const graph = await this.loadGraph();
47
+ const newEntities = entities.filter(e => !graph.entities.some(existingEntity => existingEntity.name === e.name));
48
+ graph.entities.push(...newEntities);
49
+ await this.saveGraph(graph);
50
+ return newEntities;
51
+ }
52
+ async createRelations(relations) {
53
+ const graph = await this.loadGraph();
54
+ const newRelations = relations.filter(r => !graph.relations.some(existingRelation => existingRelation.from === r.from &&
55
+ existingRelation.to === r.to &&
56
+ existingRelation.relationType === r.relationType));
57
+ graph.relations.push(...newRelations);
58
+ await this.saveGraph(graph);
59
+ return newRelations;
60
+ }
61
+ async addObservations(observations) {
62
+ const graph = await this.loadGraph();
63
+ const results = observations.map(o => {
64
+ const entity = graph.entities.find(e => e.name === o.entityName);
65
+ if (!entity) {
66
+ throw new Error(`Entity with name ${o.entityName} not found`);
67
+ }
68
+ const newObservations = o.contents.filter(content => !entity.observations.includes(content));
69
+ entity.observations.push(...newObservations);
70
+ return { entityName: o.entityName, addedObservations: newObservations };
71
+ });
72
+ await this.saveGraph(graph);
73
+ return results;
74
+ }
75
+ async deleteEntities(entityNames) {
76
+ const graph = await this.loadGraph();
77
+ graph.entities = graph.entities.filter(e => !entityNames.includes(e.name));
78
+ graph.relations = graph.relations.filter(r => !entityNames.includes(r.from) && !entityNames.includes(r.to));
79
+ await this.saveGraph(graph);
80
+ }
81
+ async deleteObservations(deletions) {
82
+ const graph = await this.loadGraph();
83
+ deletions.forEach(d => {
84
+ const entity = graph.entities.find(e => e.name === d.entityName);
85
+ if (entity) {
86
+ entity.observations = entity.observations.filter(o => !d.observations.includes(o));
87
+ }
88
+ });
89
+ await this.saveGraph(graph);
90
+ }
91
+ async deleteRelations(relations) {
92
+ const graph = await this.loadGraph();
93
+ graph.relations = graph.relations.filter(r => !relations.some(delRelation => r.from === delRelation.from &&
94
+ r.to === delRelation.to &&
95
+ r.relationType === delRelation.relationType));
96
+ await this.saveGraph(graph);
97
+ }
98
+ async readGraph() {
99
+ return this.loadGraph();
100
+ }
101
+ // Very basic search function
102
+ async searchNodes(query) {
103
+ const graph = await this.loadGraph();
104
+ // Filter entities
105
+ const filteredEntities = graph.entities.filter(e => e.name.toLowerCase().includes(query.toLowerCase()) ||
106
+ e.entityType.toLowerCase().includes(query.toLowerCase()) ||
107
+ e.observations.some(o => o.toLowerCase().includes(query.toLowerCase())));
108
+ // Create a Set of filtered entity names for quick lookup
109
+ const filteredEntityNames = new Set(filteredEntities.map(e => e.name));
110
+ // Filter relations to only include those between filtered entities
111
+ const filteredRelations = graph.relations.filter(r => filteredEntityNames.has(r.from) && filteredEntityNames.has(r.to));
112
+ const filteredGraph = {
113
+ entities: filteredEntities,
114
+ relations: filteredRelations,
115
+ };
116
+ return filteredGraph;
117
+ }
118
+ async openNodesFiltered(names) {
119
+ const graph = await this.loadGraph();
120
+ // Filter entities
121
+ const filteredEntities = graph.entities.filter(e => names.includes(e.name));
122
+ // Create a Set of filtered entity names for quick lookup
123
+ const filteredEntityNames = new Set(filteredEntities.map(e => e.name));
124
+ // Filter relations to only include those between filtered entities
125
+ const filteredRelations = graph.relations.filter(r => filteredEntityNames.has(r.from) && filteredEntityNames.has(r.to));
126
+ const filteredGraph = {
127
+ entities: filteredEntities,
128
+ relations: filteredRelations,
129
+ };
130
+ return filteredGraph;
131
+ }
132
+ async openNodes(names) {
133
+ const graph = await this.loadGraph();
134
+ // Filter entities
135
+ const filteredEntities = graph.entities.filter(e => names.includes(e.name));
136
+ // Create a Set of filtered entity names for quick lookup
137
+ const filteredEntityNames = new Set(filteredEntities.map(e => e.name));
138
+ // Filter relations to only include those between filtered entities
139
+ const filteredRelations = graph.relations.filter(r => filteredEntityNames.has(r.from));
140
+ const filteredGraph = {
141
+ entities: filteredEntities,
142
+ relations: filteredRelations,
143
+ };
144
+ return filteredGraph;
145
+ }
146
+ async getNeighbors(entityName, depth = 1) {
147
+ const graph = await this.loadGraph();
148
+ const visited = new Set();
149
+ const resultEntities = new Map();
150
+ const resultRelations = [];
151
+ const traverse = (currentName, currentDepth) => {
152
+ if (currentDepth > depth || visited.has(currentName))
153
+ return;
154
+ visited.add(currentName);
155
+ const entity = graph.entities.find(e => e.name === currentName);
156
+ if (entity) {
157
+ resultEntities.set(currentName, entity);
158
+ }
159
+ // Find all relations involving this entity
160
+ const connectedRelations = graph.relations.filter(r => r.from === currentName || r.to === currentName);
161
+ resultRelations.push(...connectedRelations);
162
+ if (currentDepth < depth) {
163
+ // Traverse to connected entities
164
+ connectedRelations.forEach(r => {
165
+ const nextEntity = r.from === currentName ? r.to : r.from;
166
+ traverse(nextEntity, currentDepth + 1);
167
+ });
168
+ }
169
+ };
170
+ traverse(entityName, 0);
171
+ return {
172
+ entities: Array.from(resultEntities.values()),
173
+ relations: resultRelations
174
+ };
175
+ }
176
+ async findPath(fromEntity, toEntity, maxDepth = 5) {
177
+ const graph = await this.loadGraph();
178
+ const visited = new Set();
179
+ const dfs = (current, target, path, depth) => {
180
+ if (depth > maxDepth || visited.has(current))
181
+ return null;
182
+ if (current === target)
183
+ return path;
184
+ visited.add(current);
185
+ const outgoingRelations = graph.relations.filter(r => r.from === current);
186
+ for (const relation of outgoingRelations) {
187
+ const result = dfs(relation.to, target, [...path, relation], depth + 1);
188
+ if (result)
189
+ return result;
190
+ }
191
+ visited.delete(current);
192
+ return null;
193
+ };
194
+ return dfs(fromEntity, toEntity, [], 0) || [];
195
+ }
196
+ async getEntitiesByType(entityType) {
197
+ const graph = await this.loadGraph();
198
+ return graph.entities.filter(e => e.entityType === entityType);
199
+ }
200
+ async getEntityTypes() {
201
+ const graph = await this.loadGraph();
202
+ const types = new Set(graph.entities.map(e => e.entityType));
203
+ return Array.from(types).sort();
204
+ }
205
+ async getRelationTypes() {
206
+ const graph = await this.loadGraph();
207
+ const types = new Set(graph.relations.map(r => r.relationType));
208
+ return Array.from(types).sort();
209
+ }
210
+ async getStats() {
211
+ const graph = await this.loadGraph();
212
+ const entityTypes = new Set(graph.entities.map(e => e.entityType));
213
+ const relationTypes = new Set(graph.relations.map(r => r.relationType));
214
+ return {
215
+ entityCount: graph.entities.length,
216
+ relationCount: graph.relations.length,
217
+ entityTypes: entityTypes.size,
218
+ relationTypes: relationTypes.size
219
+ };
220
+ }
221
+ async getOrphanedEntities() {
222
+ const graph = await this.loadGraph();
223
+ const connectedEntityNames = new Set();
224
+ graph.relations.forEach(r => {
225
+ connectedEntityNames.add(r.from);
226
+ connectedEntityNames.add(r.to);
227
+ });
228
+ return graph.entities.filter(e => !connectedEntityNames.has(e.name));
229
+ }
230
+ async validateGraph() {
231
+ const graph = await this.loadGraph();
232
+ const entityNames = new Set(graph.entities.map(e => e.name));
233
+ const missingEntities = new Set();
234
+ graph.relations.forEach(r => {
235
+ if (!entityNames.has(r.from)) {
236
+ missingEntities.add(r.from);
237
+ }
238
+ if (!entityNames.has(r.to)) {
239
+ missingEntities.add(r.to);
240
+ }
241
+ });
242
+ return Array.from(missingEntities);
243
+ }
244
+ }
245
+ const knowledgeGraphManager = new KnowledgeGraphManager();
246
+ // The server instance and tools exposed to Claude
247
+ const server = new Server({
248
+ name: "memory-server",
249
+ version: "0.0.0",
250
+ }, {
251
+ capabilities: {
252
+ tools: {},
253
+ },
254
+ });
255
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
256
+ return {
257
+ tools: [
258
+ {
259
+ name: "create_entities",
260
+ description: "Create multiple new entities in the knowledge graph",
261
+ inputSchema: {
262
+ type: "object",
263
+ properties: {
264
+ entities: {
265
+ type: "array",
266
+ items: {
267
+ type: "object",
268
+ properties: {
269
+ name: { type: "string", description: "The name of the entity" },
270
+ entityType: { type: "string", description: "The type of the entity" },
271
+ observations: {
272
+ type: "array",
273
+ items: { type: "string" },
274
+ description: "An array of observation contents associated with the entity"
275
+ },
276
+ },
277
+ required: ["name", "entityType", "observations"],
278
+ },
279
+ },
280
+ },
281
+ required: ["entities"],
282
+ },
283
+ },
284
+ {
285
+ name: "create_relations",
286
+ description: "Create multiple new relations between entities in the knowledge graph. Relations should be in active voice",
287
+ inputSchema: {
288
+ type: "object",
289
+ properties: {
290
+ relations: {
291
+ type: "array",
292
+ items: {
293
+ type: "object",
294
+ properties: {
295
+ from: { type: "string", description: "The name of the entity where the relation starts" },
296
+ to: { type: "string", description: "The name of the entity where the relation ends" },
297
+ relationType: { type: "string", description: "The type of the relation" },
298
+ },
299
+ required: ["from", "to", "relationType"],
300
+ },
301
+ },
302
+ },
303
+ required: ["relations"],
304
+ },
305
+ },
306
+ {
307
+ name: "add_observations",
308
+ description: "Add new observations to existing entities in the knowledge graph",
309
+ inputSchema: {
310
+ type: "object",
311
+ properties: {
312
+ observations: {
313
+ type: "array",
314
+ items: {
315
+ type: "object",
316
+ properties: {
317
+ entityName: { type: "string", description: "The name of the entity to add the observations to" },
318
+ contents: {
319
+ type: "array",
320
+ items: { type: "string" },
321
+ description: "An array of observation contents to add"
322
+ },
323
+ },
324
+ required: ["entityName", "contents"],
325
+ },
326
+ },
327
+ },
328
+ required: ["observations"],
329
+ },
330
+ },
331
+ {
332
+ name: "delete_entities",
333
+ description: "Delete multiple entities and their associated relations from the knowledge graph",
334
+ inputSchema: {
335
+ type: "object",
336
+ properties: {
337
+ entityNames: {
338
+ type: "array",
339
+ items: { type: "string" },
340
+ description: "An array of entity names to delete"
341
+ },
342
+ },
343
+ required: ["entityNames"],
344
+ },
345
+ },
346
+ {
347
+ name: "delete_observations",
348
+ description: "Delete specific observations from entities in the knowledge graph",
349
+ inputSchema: {
350
+ type: "object",
351
+ properties: {
352
+ deletions: {
353
+ type: "array",
354
+ items: {
355
+ type: "object",
356
+ properties: {
357
+ entityName: { type: "string", description: "The name of the entity containing the observations" },
358
+ observations: {
359
+ type: "array",
360
+ items: { type: "string" },
361
+ description: "An array of observations to delete"
362
+ },
363
+ },
364
+ required: ["entityName", "observations"],
365
+ },
366
+ },
367
+ },
368
+ required: ["deletions"],
369
+ },
370
+ },
371
+ {
372
+ name: "delete_relations",
373
+ description: "Delete multiple relations from the knowledge graph",
374
+ inputSchema: {
375
+ type: "object",
376
+ properties: {
377
+ relations: {
378
+ type: "array",
379
+ items: {
380
+ type: "object",
381
+ properties: {
382
+ from: { type: "string", description: "The name of the entity where the relation starts" },
383
+ to: { type: "string", description: "The name of the entity where the relation ends" },
384
+ relationType: { type: "string", description: "The type of the relation" },
385
+ },
386
+ required: ["from", "to", "relationType"],
387
+ },
388
+ description: "An array of relations to delete"
389
+ },
390
+ },
391
+ required: ["relations"],
392
+ },
393
+ },
394
+ {
395
+ name: "read_graph",
396
+ description: "Read the entire knowledge graph",
397
+ inputSchema: {
398
+ type: "object",
399
+ properties: {},
400
+ },
401
+ },
402
+ {
403
+ name: "search_nodes",
404
+ description: "Search for nodes in the knowledge graph based on a query",
405
+ inputSchema: {
406
+ type: "object",
407
+ properties: {
408
+ query: { type: "string", description: "The search query to match against entity names, types, and observation content" },
409
+ },
410
+ required: ["query"],
411
+ },
412
+ },
413
+ {
414
+ name: "open_nodes_filtered",
415
+ description: "Open specific nodes in the knowledge graph by their names, filtering relations to only those between the opened nodes",
416
+ inputSchema: {
417
+ type: "object",
418
+ properties: {
419
+ names: {
420
+ type: "array",
421
+ items: { type: "string" },
422
+ description: "An array of entity names to retrieve",
423
+ },
424
+ },
425
+ required: ["names"],
426
+ },
427
+ },
428
+ {
429
+ name: "open_nodes",
430
+ description: "Open specific nodes in the knowledge graph by their names",
431
+ inputSchema: {
432
+ type: "object",
433
+ properties: {
434
+ names: {
435
+ type: "array",
436
+ items: { type: "string" },
437
+ description: "An array of entity names to retrieve",
438
+ },
439
+ },
440
+ required: ["names"],
441
+ },
442
+ },
443
+ {
444
+ name: "get_neighbors",
445
+ description: "Get neighboring entities connected to a specific entity within a given depth",
446
+ inputSchema: {
447
+ type: "object",
448
+ properties: {
449
+ entityName: { type: "string", description: "The name of the entity to find neighbors for" },
450
+ depth: { type: "number", description: "Maximum depth to traverse (default: 1)", default: 1 },
451
+ },
452
+ required: ["entityName"],
453
+ },
454
+ },
455
+ {
456
+ name: "find_path",
457
+ description: "Find a path between two entities in the knowledge graph",
458
+ inputSchema: {
459
+ type: "object",
460
+ properties: {
461
+ fromEntity: { type: "string", description: "The name of the starting entity" },
462
+ toEntity: { type: "string", description: "The name of the target entity" },
463
+ maxDepth: { type: "number", description: "Maximum depth to search (default: 5)", default: 5 },
464
+ },
465
+ required: ["fromEntity", "toEntity"],
466
+ },
467
+ },
468
+ {
469
+ name: "get_entities_by_type",
470
+ description: "Get all entities of a specific type",
471
+ inputSchema: {
472
+ type: "object",
473
+ properties: {
474
+ entityType: { type: "string", description: "The type of entities to retrieve" },
475
+ },
476
+ required: ["entityType"],
477
+ },
478
+ },
479
+ {
480
+ name: "get_entity_types",
481
+ description: "Get all unique entity types in the knowledge graph",
482
+ inputSchema: {
483
+ type: "object",
484
+ properties: {},
485
+ },
486
+ },
487
+ {
488
+ name: "get_relation_types",
489
+ description: "Get all unique relation types in the knowledge graph",
490
+ inputSchema: {
491
+ type: "object",
492
+ properties: {},
493
+ },
494
+ },
495
+ {
496
+ name: "get_stats",
497
+ description: "Get statistics about the knowledge graph",
498
+ inputSchema: {
499
+ type: "object",
500
+ properties: {},
501
+ },
502
+ },
503
+ {
504
+ name: "get_orphaned_entities",
505
+ description: "Get entities that have no relations (orphaned entities)",
506
+ inputSchema: {
507
+ type: "object",
508
+ properties: {},
509
+ },
510
+ },
511
+ {
512
+ name: "validate_graph",
513
+ description: "Validate the knowledge graph and return a list of missing entities referenced in relations",
514
+ inputSchema: {
515
+ type: "object",
516
+ properties: {},
517
+ },
518
+ },
519
+ ],
520
+ };
521
+ });
522
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
523
+ const { name, arguments: args } = request.params;
524
+ if (!args) {
525
+ throw new Error(`No arguments provided for tool: ${name}`);
526
+ }
527
+ switch (name) {
528
+ case "create_entities":
529
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.createEntities(args.entities), null, 2) }] };
530
+ case "create_relations":
531
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.createRelations(args.relations), null, 2) }] };
532
+ case "add_observations":
533
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.addObservations(args.observations), null, 2) }] };
534
+ case "delete_entities":
535
+ await knowledgeGraphManager.deleteEntities(args.entityNames);
536
+ return { content: [{ type: "text", text: "Entities deleted successfully" }] };
537
+ case "delete_observations":
538
+ await knowledgeGraphManager.deleteObservations(args.deletions);
539
+ return { content: [{ type: "text", text: "Observations deleted successfully" }] };
540
+ case "delete_relations":
541
+ await knowledgeGraphManager.deleteRelations(args.relations);
542
+ return { content: [{ type: "text", text: "Relations deleted successfully" }] };
543
+ case "read_graph":
544
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.readGraph(), null, 2) }] };
545
+ case "search_nodes":
546
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.searchNodes(args.query), null, 2) }] };
547
+ case "open_nodes_filtered":
548
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.openNodesFiltered(args.names), null, 2) }] };
549
+ case "open_nodes":
550
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.openNodes(args.names), null, 2) }] };
551
+ case "get_neighbors":
552
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.getNeighbors(args.entityName, args.depth), null, 2) }] };
553
+ case "find_path":
554
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.findPath(args.fromEntity, args.toEntity, args.maxDepth), null, 2) }] };
555
+ case "get_entities_by_type":
556
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.getEntitiesByType(args.entityType), null, 2) }] };
557
+ case "get_entity_types":
558
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.getEntityTypes(), null, 2) }] };
559
+ case "get_relation_types":
560
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.getRelationTypes(), null, 2) }] };
561
+ case "get_stats":
562
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.getStats(), null, 2) }] };
563
+ case "get_orphaned_entities":
564
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.getOrphanedEntities(), null, 2) }] };
565
+ case "validate_graph":
566
+ return { content: [{ type: "text", text: JSON.stringify(await knowledgeGraphManager.validateGraph(), null, 2) }] };
567
+ default:
568
+ throw new Error(`Unknown tool: ${name}`);
569
+ }
570
+ });
571
+ async function main() {
572
+ const transport = new StdioServerTransport();
573
+ await server.connect(transport);
574
+ console.error("Knowledge Graph MCP Server running on stdio");
575
+ }
576
+ main().catch((error) => {
577
+ console.error("Fatal error in main():", error);
578
+ process.exit(1);
579
+ });
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "@levalicious/server-memory",
3
+ "version": "0.0.0",
4
+ "description": "MCP server for enabling memory for Claude through a knowledge graph",
5
+ "license": "MIT",
6
+ "author": "Levalicious",
7
+ "homepage": "https://modelcontextprotocol.io",
8
+ "bugs": "https://github.com/modelcontextprotocol/servers/issues",
9
+ "type": "module",
10
+ "bin": {
11
+ "mcp-server-memory": "dist/index.js"
12
+ },
13
+ "files": [
14
+ "dist"
15
+ ],
16
+ "scripts": {
17
+ "build": "tsc && shx chmod +x dist/*.js",
18
+ "prepare": "npm run build",
19
+ "watch": "tsc --watch"
20
+ },
21
+ "dependencies": {
22
+ "@modelcontextprotocol/sdk": "1.0.1"
23
+ },
24
+ "devDependencies": {
25
+ "@types/node": "^22",
26
+ "shx": "^0.3.4",
27
+ "typescript": "^5.6.2"
28
+ }
29
+ }