知识图谱存储服务

一个轻量级的模型上下文协议(MCP)服务器,为AI助手提供持久化的知识图谱存储,支持实体关系管理和跨会话记忆保持。

  • by AojdevStudio
  • Python
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 AojdevStudio/simple-memory-mcp

使用说明

简单内存MCP服务器

一个轻量级的模型上下文协议(MCP)服务器,为AI助手提供持久的知识图存储。使AI代理能够通过具有JSON文件持久性的实体关系存储在会话之间维护内存。

🚀 特性

  • 持久存储器:知识图存储,自动持久化为JSON文件
  • 实体管理:使用键入的观察值创建、读取、更新和删除实体
  • 关系跟踪:管理具有类型注释的实体之间的关系
  • 搜索功能:在实体名称、类型和观察值之间进行全文搜索
  • 符合MCP标准:完全模型上下文协议v2025-06-18兼容性
  • 简单架构:轻量级、单文件实现,依赖性最小

📋 目录

🛠 安装

交互式安装(推荐)

# Bash installer with interactive configuration
curl -fsSL https://raw.githubusercontent.com/your-username/simple-memory-mcp/main/install.sh | bash

它的作用:

  • 🔍 自动检测您的黑曜石保险库
  • 📁 配置自定义内存存储位置
  • ⚙️ 自动设置Claude桌面/光标
  • 🗂️ 可选的黑曜石自动导出配置

交互式设置流程:

📁 Memory Storage Configuration
Where should memory be stored? [~/.cursor/memory.json]: 

🗂️ Obsidian Integration  
Do you use Obsidian? (y/n) [n]: y

📚 Found Obsidian vaults:
  1. My Knowledge Base (/Users/you/Documents/MyVault)
  2. Work Notes (/Users/you/Desktop/WorkVault)
Choose vault (1-2) or enter custom path [1]: 1

Enable auto-export after entity creation? (y/n) [n]: y
Export format (markdown/dataview/canvas/all) [markdown]: all

手动安装

先决条件

  • Node.js v18.x或更高版本
  • npm或pnpm包管理器

再进行

npm install

环境设置

服务器会自动将内存保存到:

  • ~/.cursor/memory.json (默认)
  • 通过自定义路径 MEMORY_PATH 环境变量
# Optional: Set custom memory file location
export MEMORY_PATH="/path/to/your/memory/directory"

🚀 快速开始

1.启动服务器

npm start
# or
node index.js

2.使用MCP检查员进行测试

# Install and run MCP Inspector
npx @modelcontextprotocol/inspector

# Configure server in Inspector:
# Command: node
# Args: /path/to/your/simple-memory-mcp/index.js

3.基本使用示例

// Create entities
await client.callTool({
  name: "create_entities",
  arguments: {
    entities: [{
      name: "john-doe",
      entityType: "person",
      observations: ["Software engineer", "Works remotely", "Enjoys hiking"]
    }]
  }
});

// Create relationships
await client.callTool({
  name: "create_relations",
  arguments: {
    relations: [{
      from: "john-doe",
      to: "acme-corp",
      relationType: "works_for"
    }]
  }
});

// Search entities
await client.callTool({
  name: "search_nodes",
  arguments: {
    query: "engineer"
  }
});

📚 api参考

工具概述

工具 描述 输入 输出
create_entities 创建多个实体 {entities: Entity[]} 已创建实体
create_relations 建立关系 {relations: Relation[]} 建立关系
add_observations 向实体添加观察结果 {observations: Observation[]} 最新观察结果
delete_entities 删除实体和关系 {entityNames: string[]} 已删除实体
delete_observations 删除具体观察结果 {deletions: Deletion[]} 删除的观察结果
delete_relations 删除关系 {relations: Relation[]} 已删除关系
read_graph 获取完整的知识图谱 {} 完整图形数据
search_nodes 按查询搜索实体 {query: string} 匹配实体
open_nodes 获取特定实体 {names: string[]} 被请求的实体
export_to_obsidian 将图形导出到黑曜石保险库 {vaultPath: string, format?: string} 导出结果

数据类型

实体

interface Entity {
  name: string;           // Unique identifier
  entityType: string;     // Type classification
  observations: string[]; // Array of observation texts
}

关系

interface Relation {
  from: string;          // Source entity name
  to: string;            // Target entity name
  relationType: string;  // Relationship type
}

观察

interface Observation {
  entityName: string;    // Target entity name
  contents: string[];    // New observations to add
}

删除

interface Deletion {
  entityName: string;      // Target entity name
  observations: string[];  // Observations to remove
}

详细的工具文档

create_entities

在知识图中创建多个新实体。

输入架构:

{
  "entities": [
    {
      "name": "entity-name",
      "entityType": "person|organization|concept|etc",
      "observations": ["observation1", "observation2"]
    }
  ]
}

例子:

{
  "entities": [
    {
      "name": "alice-johnson",
      "entityType": "person",
      "observations": ["Data scientist", "PhD in Computer Science", "Lives in San Francisco"]
    },
    {
      "name": "tech-startup-xyz",
      "entityType": "organization", 
      "observations": ["AI/ML company", "Founded in 2023", "Series A funding"]
    }
  ]
}

答复:

[
  {
    "name": "alice-johnson",
    "entityType": "person",
    "observations": ["Data scientist", "PhD in Computer Science", "Lives in San Francisco"]
  }
]

create_relations

在现有实体之间创建关系。

输入架构:

{
  "relations": [
    {
      "from": "source-entity",
      "to": "target-entity", 
      "relationType": "relationship-type"
    }
  ]
}

例子:

{
  "relations": [
    {
      "from": "alice-johnson",
      "to": "tech-startup-xyz",
      "relationType": "works_for"
    }
  ]
}

search_nodes

在名称、类型和观察值之间使用全文搜索来搜索实体。

输入架构:

{
  "query": "search-term"
}

例子:

{
  "query": "data scientist"
}

答复: 具有完整数据的匹配实体数组。

read_graph

返回包含所有实体和关系的完整知识图。

输入架构:

{}

答复:

{
  "entities": [
    {
      "name": "alice-johnson",
      "entityType": "person",
      "observations": ["Data scientist", "PhD in Computer Science"]
    }
  ],
  "relations": [
    {
      "from": "alice-johnson",
      "to": "tech-startup-xyz", 
      "relationType": "works_for"
    }
  ]
}

export_to_obsidian

将知识图以各种格式导出到黑曜石库。

输入架构:

{
  "vaultPath": "/path/to/obsidian/vault",
  "format": "markdown",
  "autoIndex": true
}

参数:

  • vaultPath (必填):黑曜石保险库目录的路径
  • format (可选):导出格式-“markdown”、“dataview”、“canvas”或“all”(默认:“markdown)
  • autoIndex (可选):是否创建索引文件(默认值:true)

例子:

{
  "vaultPath": "/Users/username/Documents/MyVault",
  "format": "all",
  "autoIndex": true
}

答复:

{
  "success": true,
  "vaultPath": "/Users/username/Documents/MyVault",
  "format": "all",
  "entityCount": 42,
  "relationCount": 18,
  "timestamp": "2024-01-15T10:30:00.000Z"
}

⚙️ 配置

环境变量

变量 默认值 描述
MEMORY_PATH ~/.cursor/memory.json 自定义内存文件位置
NODE_ENV development 运行时环境
OBSIDIAN_AUTO_EXPORT false 在实体创建后启用自动黑曜石导出
OBSIDIAN_VAULT_PATH - 用于自动导出的黑曜石保险库路径
OBSIDIAN_EXPORT_FORMAT markdown 自动导出的导出格式

内存文件结构

服务器以JSON格式保存数据:

{
  "entities": [
    {
      "name": "entity-name",
      "entityType": "type",
      "observations": ["obs1", "obs2"]
    }
  ],
  "relations": [
    {
      "from": "entity1",
      "to": "entity2",
      "relationType": "relationship"
    }
  ]
}

MCP客户端配置

对于Claude Desktop,请在MCP设置中添加:

{
  "mcpServers": {
    "simple-memory": {
      "command": "node",
      "args": ["/path/to/simple-memory-mcp/index.js"],
      "env": {
        "MEMORY_PATH": "/custom/path/to/memory/directory"
      }
    }
  }
}

🧪 测试

运行测试

# Run comprehensive server test
node test-server.js

预期测试输出

🧪 Testing Simple Memory MCP Server...
✅ Connected successfully!
✅ Found 9 tools: create_entities, create_relations, ...
✅ All tests passed! Server is working correctly.

检验员手动测试

  1. 启动MCP检查器: npx @modelcontextprotocol/inspector
  2. 配置服务器连接
  3. 用样本数据测试每个工具
  4. 通过重新启动服务器验证持久性

集成测试

使用实际的MCP客户端进行测试:

import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

const transport = new StdioClientTransport({
  command: "node",
  args: ["index.js"]
});

const client = new Client({
  name: "test-client",
  version: "1.0.0"
}, {
  capabilities: {}
});

await client.connect(transport);

🔧 故障排除

常见问题

服务器无法启动

错误: Cannot read properties of undefined (reading 'method')

解决方案: 确保您使用的是正确的MCP SDK版本和架构导入:

import {
  ListToolsRequestSchema,
  CallToolRequestSchema,
  ListPromptsRequestSchema,
  ListResourcesRequestSchema
} from '@modelcontextprotocol/sdk/types.js';

缺少功能错误

错误: Server does not support prompts (required for prompts/list)

解决方案: 声明服务器配置中的所有功能:

const server = new Server(
  { name: 'simple-memory-mcp', version: '1.1.0' },
  {
    capabilities: {
      tools: {},
      prompts: {},
      resources: {}
    }
  }
);

内存文件权限

错误: EACCES: permission denied

解决方案: 确保对内存目录的写入权限:

mkdir -p ~/.cursor
chmod 755 ~/.cursor

未找到工具

错误: Unknown tool: create_entities

解决方案: 验证工具注册是否与架构名称完全匹配。

调试模式

启用详细日志记录:

console.error("Debug info:", JSON.stringify(data, null, 2));

性能问题

对于大型知识图(>10000个实体):

  1. 考虑为实现分页 read_graph
  2. 为搜索操作添加索引
  3. 实现实体详细信息的延迟加载

🛠 发展

项目结构

simple-memory-mcp/
├── index.js              # Main server implementation
├── package.json          # Dependencies and scripts
├── test-server.js        # Comprehensive test suite
├── inspector-config.json # MCP Inspector configuration
├── CLAUDE.md             # AI development protocols
└── README.md             # This documentation

建筑

graph TD
    A[MCP Client] --> B[StdioServerTransport]
    B --> C[Simple Memory Server]
    C --> D[Entity Manager]
    C --> E[Relation Manager]
    C --> F[Search Engine]
    D --> G[JSON File Storage]
    E --> G
    F --> G

核心类

SimpleMemoryServer

主服务器类处理:

  • 内存持久性(loadMemory(), saveMemory())
  • 实体操作(CRUD)
  • 关系管理
  • 搜索功能

关键方法:

  • createEntities(entities) -批量实体创建
  • createRelations(relations) -关系创建
  • searchNodes(query) -全文搜索
  • readGraph() -完成图形导出

扩展服务器

添加新工具

  1. 在中定义工具架构 tools/list 处理器
  2. 实现逻辑 tools/call 处理器
  3. 添加方法 SimpleMemoryServer 类
  4. 更新文档

自定义存储后端

替换JSON文件存储:

class DatabaseMemoryServer extends SimpleMemoryServer {
  async saveMemory() {
    // Custom database implementation
  }
  
  async loadMemory() {
    // Custom database loading
  }
}

贡献

  1. 分叉存储库
  2. 创建要素分支: git checkout -b feature-name
  3. 运行测试: node test-server.js
  4. 提交更改: git commit -m "Description"
  5. 推送分支: git push origin feature-name
  6. 创建拉取请求

📄 许可证

MIT许可证-有关详细信息,请参阅许可证文件。

📚 其他文件

🤝 支持


内置于❤️ 使用 模型上下文协议