Memory MCP

Memory MCP

A Model Context Protocol server that provides AI assistants with persistent semantic memory and knowledge graph capabilities using PostgreSQL and vector embeddings. It enables cross-session storage, hybrid search, and complex relationship tracking for enhanced contextual awareness.

Category
Visit Server

README

Memory MCP

<div align="center">

为 AI 助手提供持久化语义记忆与知识图谱能力的 MCP 服务器

A Model Context Protocol server providing persistent semantic memory and knowledge graph capabilities for AI assistants

License: MIT Node.js Version PostgreSQL MCP Protocol

</div>


🎯 Why This Project?

AI 助手(如 Claude、ChatGPT)在对话结束后会"失忆"。本项目通过 MCP (Model Context Protocol) 为 AI 提供:

  • 跨会话记忆:用户偏好、历史对话、学习到的事实都能持久保存
  • 语义检索:不是简单的关键词匹配,而是理解"意思相近"的内容
  • 知识图谱:构建实体之间的关系网络,支持复杂推理
用户: "我之前说过喜欢什么编程语言?"
AI:   [调用 memory_search] → 找到 3 个月前的对话记录
      "您提到过喜欢 Rust 的内存安全特性,以及 Python 的简洁语法。"

✨ 核心特性

🧠 语义记忆系统

特性 说明
向量嵌入 使用阿里云 DashScope text-embedding-v3 模型,1024 维向量
HNSW 索引 pgvector 的高性能近似最近邻搜索,毫秒级响应
混合检索 向量相似度 (70%) + 关键词匹配 (30%) 加权融合
记忆衰减 基于访问频率和时间的自动权重调整,防止信息过载
LRU 缓存 嵌入向量缓存(最大 1000 条),减少 80%+ API 调用
版本历史 完整的变更审计日志,支持回溯

记忆衰减算法

权重 = 置信度 × 时间衰减 × 访问加成
     = confidence × 0.9^(天数/30) × (1 + min(访问次数×0.05, 0.5))

🕸️ 知识图谱引擎

特性 说明
实体管理 创建带类型和观察记录的实体节点
关系追踪 定义实体间的有向关系(如 uses, depends_on
双向关系 自动创建反向关系(A uses BB is_used_by A
传递推理 递归查询多跳关系路径(A→B→C→D)
语义搜索 基于向量相似度搜索实体
Mermaid 导出 生成可视化图谱代码

支持的反向关系映射

uses ↔ is_used_by
depends_on ↔ is_dependency_of
contains ↔ is_contained_in
calls ↔ is_called_by
owns ↔ is_owned_by
creates ↔ is_created_by
manages ↔ is_managed_by

🏗️ 系统架构

┌────────────────────────────────────────────────────────────────┐
│                MCP Client (Claude Desktop / Windsurf)          │
└───────────────────────────┬────────────────────────────────────┘
                            │ JSON-RPC 2.0 over stdio
┌───────────────────────────▼────────────────────────────────────┐
│                      Memory MCP                         │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │                    Tool Dispatcher                       │  │
│  │   memory_*  →  memoryService    graph_*  →  graphService │  │
│  └──────────────────────────────────────────────────────────┘  │
│                              │                                 │
│  ┌─────────────┐  ┌─────────▼─────────┐  ┌─────────────────┐   │
│  │   Memory    │  │    Embedding      │  │     Graph       │   │
│  │   Service   │  │    Service        │  │     Service     │   │
│  │             │  │  ┌─────────────┐  │  │                 │   │
│  │ • create    │  │  │ LRU Cache   │  │  │ • entities      │   │
│  │ • search    │  │  │ (1000 max)  │  │  │ • relations     │   │
│  │ • update    │  │  └──────┬──────┘  │  │ • transitive    │   │
│  │ • delete    │  │         │         │  │ • mermaid       │   │
│  │ • hybrid    │  │         ▼         │  │                 │   │
│  └──────┬──────┘  │  Aliyun DashScope │  └────────┬────────┘   │
│         │         │  text-embedding-v3│           │            │
│         │         └─────────┬─────────┘           │            │
│         └───────────────────┼─────────────────────┘            │
│                             │                                  │
└─────────────────────────────┼──────────────────────────────────┘
                              │
┌─────────────────────────────▼───────────────────────────────────┐
│                   PostgreSQL 14+ with pgvector                  │
│  ┌────────────┐  ┌────────────┐  ┌───────────┐  ┌────────────┐  │
│  │  memories  │  │  entities  │  │ relations │  │  history   │  │
│  │            │  │            │  │           │  │            │  │
│  │ • HNSW idx │  │ • HNSW idx │  │ • FK refs │  │ • triggers │  │
│  │ • GIN tags │  │ • UNIQUE   │  │ • UNIQUE  │  │ • audit    │  │
│  └────────────┘  └────────────┘  └───────────┘  └────────────┘  │
└─────────────────────────────────────────────────────────────────┘

🚀 快速开始

环境要求

  • Node.js >= 18.0.0
  • PostgreSQL >= 14 + pgvector 扩展
  • 阿里云 DashScope API Key(用于生成嵌入向量)

安装步骤

# 1. 克隆仓库
git clone https://github.com/YOUR_USERNAME/mcp-memory.git
cd mcp-memory

# 2. 安装依赖
npm install

# 3. 配置环境变量
cp .env.sample .env
# 编辑 .env 填入数据库连接和 API Key

# 4. 初始化数据库
psql -c "CREATE DATABASE mcp_memory;"
psql -d mcp_memory -f migrations/init.sql

# 5. 启动服务
npm start

MCP 客户端配置

Claude Desktop (claude_desktop_config.json):

{
  "mcpServers": {
    "memory": {
      "command": "node",
      "args": ["C:/path/to/mcp-memory/src/server.js"],
      "env": {
        "DATABASE_URL": "postgresql://user:pass@localhost:5432/mcp_memory",
        "DASHSCOPE_API_KEY": "sk-your-api-key"
      }
    }
  }
}

Windsurf (mcp_config.json):

{
  "mcpServers": {
    "memory": {
      "command": "node",
      "args": ["src/server.js"],
      "cwd": "C:/path/to/mcp-memory",
      "env": {
        "DATABASE_URL": "postgresql://user:pass@localhost:5432/mcp_memory",
        "DASHSCOPE_API_KEY": "sk-your-api-key"
      }
    }
  }
}

🛠️ 工具详解

记忆操作 (Memory Tools)

memory_create - 创建记忆

{
  "type": "preference",
  "content": { "topic": "编程语言", "preference": "喜欢 Rust 和 Python" },
  "source": "user_message",
  "tags": ["programming", "preferences"],
  "confidence": 0.95
}
参数 类型 必填 说明
type string 记忆类型:fact, preference, conversation, task
content object 记忆内容(JSONB 存储,支持任意结构)
source string 来源:user_message, system_inference, external_api
tags string[] 标签数组,用于过滤
confidence number 置信度 0.0-1.0,影响检索权重

memory_search - 语义搜索

{
  "query": "用户喜欢什么编程语言",
  "type": "preference",
  "tags": ["programming"],
  "limit": 5
}

工作原理

  1. 将查询文本转换为 1024 维向量
  2. 使用 HNSW 索引计算余弦相似度
  3. 按相似度排序返回结果
  4. 异步更新访问统计(access_count, last_accessed_at

memory_update - 更新记忆

{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "content": { "updated": true },
  "confidence": 0.8
}

特性:内容变更时自动重新生成嵌入向量

memory_list - 列出记忆

{
  "type": "fact",
  "tags": ["important"],
  "limit": 20
}

memory_delete - 删除记忆

{
  "id": "550e8400-e29b-41d4-a716-446655440000"
}

注意:删除操作会记录到 memory_history


知识图谱操作 (Graph Tools)

graph_create_entities - 创建实体

{
  "entities": [
    {
      "name": "Memory MCP",
      "entityType": "Project",
      "observations": [
        "使用 PostgreSQL + pgvector",
        "支持语义搜索",
        "MIT 开源协议"
      ]
    },
    {
      "name": "pgvector",
      "entityType": "Technology",
      "observations": ["PostgreSQL 向量扩展", "支持 HNSW 索引"]
    }
  ]
}

特性

  • 自动为实体生成嵌入向量(批量处理)
  • 同名实体会合并观察记录(UPSERT)

graph_create_relations - 创建关系

{
  "relations": [
    {
      "from": "Memory MCP",
      "to": "pgvector",
      "relationType": "uses"
    }
  ]
}

自动双向关系:创建 A uses B 时自动创建 B is_used_by A

graph_add_observations - 添加观察

{
  "observations": [
    {
      "entityName": "Memory MCP",
      "contents": ["新增混合检索功能", "支持 Mermaid 导出"]
    }
  ]
}

graph_search_nodes - 搜索实体

{
  "query": "向量数据库",
  "semantic": true,
  "limit": 10
}
参数 说明
semantic: false 关键词匹配(名称、类型、观察记录)
semantic: true 向量相似度搜索

graph_open_nodes - 打开指定实体

{
  "names": ["Memory MCP", "pgvector"]
}

返回实体详情及其所有关联关系

graph_read - 读取完整图谱

返回所有实体和关系,适合小规模图谱

graph_delete_* - 删除操作

  • graph_delete_entities: 删除实体(级联删除关系)
  • graph_delete_relations: 删除指定关系
  • graph_delete_observations: 删除实体的特定观察记录

📊 数据库设计

表结构

memories - 语义记忆表

列名 类型 说明
id UUID 主键,自动生成
type TEXT 记忆类型
content JSONB 结构化内容
source TEXT 来源标识
embedding vector(1024) 嵌入向量
tags TEXT[] 标签数组
confidence FLOAT 置信度
access_count INT 访问次数
last_accessed_at TIMESTAMPTZ 最后访问时间
created_at TIMESTAMPTZ 创建时间
updated_at TIMESTAMPTZ 更新时间

entities - 实体表

列名 类型 说明
id UUID 主键
name TEXT 实体名称(唯一)
entity_type TEXT 实体类型
observations TEXT[] 观察记录数组
embedding vector(1024) 可选,用于语义搜索

relations - 关系表

列名 类型 说明
id UUID 主键
from_entity TEXT 源实体(外键)
to_entity TEXT 目标实体(外键)
relation_type TEXT 关系类型

memory_history - 历史记录表

列名 类型 说明
memory_id UUID 关联的记忆 ID
content JSONB 变更时的内容快照
change_type TEXT create / update / delete
previous_confidence FLOAT 变更前置信度
new_confidence FLOAT 变更后置信度

索引策略

索引 类型 用途
idx_memories_embedding HNSW 向量相似度搜索
idx_memories_tags GIN 标签数组包含查询
idx_memories_type B-tree 类型过滤
idx_entities_embedding HNSW (条件) 实体语义搜索
idx_relations_from/to B-tree 关系查询

触发器与函数

名称 类型 说明
update_memories_updated_at Trigger 自动更新 updated_at
memory_history_trigger Trigger 自动记录变更历史
calculate_memory_weight() Function 计算记忆衰减权重
update_memory_access() Function 更新访问统计
log_memory_change() Function 记录变更历史

⚙️ 配置参考

环境变量

变量 必填 默认值 说明
DATABASE_URL - PostgreSQL 连接字符串
DASHSCOPE_API_KEY - 阿里云 DashScope API Key
DASHSCOPE_API_URL https://dashscope.aliyuncs.com/... 嵌入 API 端点
EMBEDDINGS_MODEL text-embedding-v3 嵌入模型
EMBEDDINGS_DIMENSIONS 1024 向量维度
DB_MAX_POOL_SIZE 20 数据库连接池大小
DB_IDLE_TIMEOUT 30000 空闲连接超时 (ms)
SEARCH_DEFAULT_LIMIT 10 默认搜索结果数
MCP_DEBUG_LOG_PATH memory-debug.log 调试日志路径

示例 .env

# 数据库
DATABASE_URL=postgresql://postgres:password@localhost:5432/mcp_memory

# 阿里云 DashScope
DASHSCOPE_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxx

# 可选配置
DB_MAX_POOL_SIZE=10
SEARCH_DEFAULT_LIMIT=20

🔧 开发指南

# 开发模式(自动重载)
npm run dev

# 查看调试日志
Get-Content memory-debug.log -Wait  # PowerShell
tail -f memory-debug.log            # Linux/Mac

# 初始化数据库
npm run db:init

项目结构

mcp-memory/
├── src/
│   ├── server.js          # MCP 服务入口,JSON-RPC 处理
│   ├── config.js          # 配置加载
│   ├── db/
│   │   ├── index.js       # 数据库导出
│   │   └── pool.js        # 连接池管理
│   ├── services/
│   │   ├── memory.js      # 记忆服务(CRUD + 搜索)
│   │   ├── graph.js       # 知识图谱服务
│   │   └── embedding.js   # 嵌入生成 + LRU 缓存
│   ├── tools/
│   │   └── definitions.js # MCP 工具定义
│   └── utils/
│       ├── logger.js      # 日志工具
│       └── response.js    # JSON-RPC 响应格式化
├── migrations/
│   └── init.sql           # 数据库初始化脚本(幂等)
├── docs/
│   └── ROADMAP.md         # 开发路线图
├── .env.sample            # 环境变量模板
└── package.json

📈 性能优化

本项目已实现以下优化(详见 ROADMAP.md):

优化项 效果
嵌入缓存 相同文本重复查询时,API 调用减少 80%+
HNSW 索引 向量搜索从 O(n) 降至 O(log n)
混合检索 召回率提升,避免纯语义搜索的遗漏
批量嵌入 创建多个实体时,单次 API 调用
异步访问统计 不阻塞搜索响应

📜 许可证

本项目采用 MIT License 开源。


🙏 致谢


🤝 贡献

欢迎提交 Issue 和 Pull Request!

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
E2B

E2B

Using MCP to run code via e2b.

Official
Featured
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured