增强内存MCP服务器
基于 模型上下文协议。提供200多种工具,涵盖压缩SQLite存储、4层内存架构、类似Git的版本控制、多策略RAG、AGI认知阶段以及基于配置文件的扩展的模块化工具加载。
特性
- 4层内存架构:具有自动升级/降级功能的核心层、工作层、参考层和归档层
- 200+MCP工具:基于配置文件加载的模块化注册系统(全模式与编排模式)
- 先进的RAG管道:4层检索策略——混合搜索、重新排序、查询扩展、代理RAG、GraphRAG
- 神经记忆结构(NMF):具有打开/编辑/关闭语义的Letta风格内存块
- 类似Git的版本控制:跨会话分支、区分和恢复内存状态
- 真实压缩:使用zlib级别9、SHA256校验和进行2.4倍数据缩减
- AGI认知阶段:身份、时间推理、情感标记、元认知(4个阶段)
- 智能路由器:具有不确定性评分的多提供商LLM路由
- 防幻觉引擎:因果推理、奇怪循环检测、持续学习
- 代码执行沙盒:基于Python的受限安全执行,带有PII标记
- 语义缓存:LLM推理结果缓存(生产中的命中率为30-40%)
- 歧管工作记忆:具有轨迹压缩的高维工作记忆
- 三重信号搜索:结合BM25、向量相似度和图接近度的三向排名
- 熵评分:记忆优先级的信息论重要性评分
- 工具使用分析:跟踪调用哪些工具来优化配置文件加载
- 集群智能:通过集群大脑和SAFLA远程集成进行多节点协调
演出
基于生产测试:
- 写入速度:每个实体约0.04ms
- 读取速度:每次查询约0.01毫秒
- 压缩:平均减少2.4倍
- 语义缓存命中率: 30-40%
- 存储:SQLite数据库位于
~/.claude/enhanced_memories/memory.db
安装
先决条件
- Python 3.11+
- 紫外线 (推荐)或pip
快速开始```bash
git clone https://github.com/marc-shade/enhanced-memory-mcp.git
cd enhanced-memory-mcp
uv venv --python 3.11 .venv
source .venv/bin/activate
uv pip install -r requirements.txt
### 在Claude代码中配置
添加到您的 `~/.claude.json`:```json
{
"mcpServers": {
"enhanced-memory": {
"command": "python3",
"args": ["/path/to/enhanced-memory-mcp/server.py"]
}
}
}
在Claude桌面中配置
添加到您的Claude Desktop MCP配置中:```json
{
"mcpServers": {
"enhanced-memory": {
"command": "/path/to/enhanced-memory-mcp/.venv/bin/python3",
"args": ["/path/to/enhanced-memory-mcp/server.py"]
}
}
}
## 建筑
### 内存层
|层次|目的|访问模式|
|------|---------|----------------|
| **核心** |系统角色、AI代理库、执行模式|启动时预装,子ms访问|
| **工作** |活动项目、当前上下文、代理分配|会话范围、频繁读/写|
| **参考** |文档、代码模式、错误解决方案|全文搜索,延迟加载|
| **档案** |历史数据、指标、决策日志|最大压缩,日期分区|
### 模块体系结构```
server.py # Main FastMCP entry point
├── server/ # Core server modules
│ ├── config.py # Configuration and logging
│ ├── database.py # SQLite connection management
│ ├── compression.py # zlib compression engine
│ ├── compaction.py # Entity compaction and cleanup
│ ├── integrity.py # SHA256 integrity verification
│ ├── versioning.py # Git-like memory versioning
│ └── modules.py # Profile-based module loader
├── router/ # Intelligent LLM routing
│ ├── router.py # Multi-provider router
│ ├── intelligent_router.py # Uncertainty-aware routing
│ ├── uncertainty.py # Uncertainty scoring
│ └── providers/ # Provider implementations
├── sandbox/ # Code execution sandbox
│ ├── executor.py # RestrictedPython execution
│ ├── security.py # Safety checks
│ ├── pii_tokenizer.py # PII detection and tokenization
│ ├── lazy_loader.py # Deferred module loading
│ └── tool_discovery.py # Dynamic tool discovery
├── agi/ # AGI cognitive modules (22 files)
│ ├── consolidation.py # Sleep-like memory consolidation
│ ├── metacognition.py # Self-awareness tracking
│ ├── belief_tracking.py # Probabilistic belief states
│ ├── temporal_reasoning.py # Causal chains
│ ├── emotional_memory.py # Emotional tagging
│ └── ...
├── *_tools.py (31 files) # MCP tool modules
└── test_*.py (67 files) # Test suite
RAG战略管道
| 层级 | 策略 | 工具 | 文件 |
|---|---|---|---|
| 1 | 混合搜索(BM25+矢量) | search_hybrid |
hybrid_search_tools_nmf.py |
| 1 | 重新排序(交叉编码器) | search_with_reranking |
reranking_tools_nmf.py |
| 2 | 查询扩展 | search_with_query_expansion |
query_expansion_tools.py |
| 2 | 多查询RAG | search_with_multi_query |
multi_query_rag_tools.py |
| 3.1 | 上下文检索 | generate_context_for_chunk |
contextual_retrieval_tools.py |
| 3.2 | 上下文感知分块 | chunk_document_semantic |
context_aware_chunking.py |
| 3.3 | 分层RAG | search_hierarchical |
hierarchical_rag_tools.py |
| 4.1 | 代理+自我反思的RAG | agentic_retrieve |
agentic_rag_tools.py |
| 4.2 | GraphRAG | graph_enhanced_search |
graphrag_tools.py |
| 4.3 | 视觉记忆 | store_visual_episode |
visual_memory_tools.py |
| -- | 三重信号搜索 | triple_signal_search |
triple_signal_tools.py |
| -- | 语义缓存 | semantic_cache_get, agi_cached_reasoning |
semantic_cache_tools.py |
| -- | FACT缓存 | fact_search |
fact_integration.py |
| -- | 统一搜索 | unified_search |
unified_search_api.py |
内存配置文件
通过控制工具加载 MEMORY_PROFILE 环境变量:```bash
Full mode (default): All 200+ tools loaded
MEMORY_PROFILE=full python3 server.py
Orchestrator mode: ~15 essential tools for coordination
MEMORY_PROFILE=orchestrator python3 server.py
仅加载编排器模式: `nmf_tools`, `safla_remote_integration`, `fact_integration`, `unified_search_api`, `semantic_cache_tools`, `reasoning_bank`.
### 数据库模式
中的主表 `~/.claude/enhanced_memories/memory.db`:```sql
-- Core memory storage with compression and versioning
CREATE TABLE entities (
id INTEGER PRIMARY KEY,
name TEXT UNIQUE NOT NULL,
entity_type TEXT NOT NULL,
tier TEXT DEFAULT 'working',
compressed_data BLOB,
original_size INTEGER,
compressed_size INTEGER,
compression_ratio REAL,
checksum TEXT,
created_at TIMESTAMP,
accessed_at TIMESTAMP,
access_count INTEGER DEFAULT 0
);
-- Entity relationships with causal tracking
CREATE TABLE relations (
id INTEGER PRIMARY KEY,
from_entity TEXT NOT NULL,
to_entity TEXT NOT NULL,
relation_type TEXT NOT NULL,
weight REAL DEFAULT 1.0,
causal INTEGER DEFAULT 0,
created_at TIMESTAMP,
UNIQUE(from_entity, to_entity, relation_type)
);
-- Git-like version history
CREATE TABLE entity_versions (
id INTEGER PRIMARY KEY,
entity_name TEXT NOT NULL,
version INTEGER NOT NULL,
branch TEXT DEFAULT 'main',
compressed_data BLOB,
checksum TEXT,
created_at TIMESTAMP
);
附加表格: observations, entity_branches, working_memory, episodic_memory, semantic_memory, procedural_memory, visual_episodes.
API示例
创建实体```python
await create_entities({
"entities": [
{
"name": "project_alpha",
"entityType": "project",
"observations": ["Architecture uses microservices", "Deployed on Kubernetes"]
}
]
})
### 搜索节点```python
await search_nodes({
"query": "microservices architecture",
"entity_types": ["project"],
"limit": 10
})
统一搜索(智能路由)```python
await unified_search({
"query": "How does authentication work?",
"strategy": "auto" # Automatically selects best RAG strategy
})
### 代理RAG(自反射检索)```python
await agentic_retrieve({
"query": "memory consolidation patterns",
"max_iterations": 3,
"quality_threshold": 0.7
})
神经记忆结构```python
Open a memory block for editing
await nmf_open_block({"block_id": "working_context"})
Edit the block
await nmf_edit_block({
"block_id": "working_context",
"content": "Current focus: implementing authentication module"
})
Recall related memories
await nmf_recall({"query": "authentication patterns"})
Close the block
await nmf_close_block({"block_id": "working_context"})
### 语义缓存```python
# Cache an LLM reasoning result
await semantic_cache_store({
"query": "Explain transformer attention mechanisms",
"result": "Transformers use self-attention to...",
"ttl_hours": 24
})
# Retrieve cached result (fuzzy match)
await semantic_cache_get({
"query": "How do transformer attention heads work?"
})
内存版本控制```python
Create a branch
await memory_branch({"branch_name": "experiment-v2"})
Make changes, then diff
await memory_diff({"branch": "experiment-v2", "base": "main"})
Revert if needed
await memory_revert({"entity_name": "project_alpha", "version": 3})
## 工具模块
### 核心工具(始终加载)
|模块|工具|说明|
|--------|-------|-------------|
| `server/` | `create_entities`, `search_nodes`, `get_memory_status` |核心CRUD+版本控制|
### AGI认知工具
|模块|阶段|描述|
|--------|-------|-------------|
| `agi_tools.py` |第1阶段|身份、动作跟踪、代理注册|
| `agi_tools_phase2.py` |第二阶段|时间推理,类似睡眠的巩固|
| `agi_tools_phase3.py` |第3阶段|情感标记,联想网络|
| `agi_tools_phase4.py` |阶段4 |元认知,自我提升周期|
### RAG和搜索工具
|模块|说明|
|--------|-------------|
| `hybrid_search_tools_nmf.py` |BM25+矢量混合搜索|
| `reranking_tools_nmf.py` |交叉编码器重新排序(ms marco MiniLM)|
| `query_expansion_tools.py` |LLM驱动的查询扩展|
| `multi_query_rag_tools.py` |多视角查询生成|
| `contextual_retrieval_tools.py` |上下文增强的块检索|
| `hierarchical_rag_tools.py` |多级文档索引|
| `agentic_rag_tools.py` |自主自反射检索|
| `graphrag_tools.py` |图形增强搜索|
| `triple_signal_tools.py` |三向排名(BM25+矢量+图形)|
| `visual_memory_tools.py` |可视化剧集存储和相似性搜索|
### 内存管理工具
|模块|说明|
|--------|-------------|
| `nmf_tools.py` |神经记忆织物(Letta风格块)|
| `reasoning_tools.py` |75/15规则优先级|
| `semantic_cache_tools.py` |LLM推理结果缓存|
| `fact_integration.py` |快速缓存优先事实检索|
| `unified_search_api.py` |智能搜索策略路由|
| `reasoning_bank.py` |从推理结果中持续学习|
| `manifold_working_memory_tools.py` |高维工作记忆|
| `trajectory_compression.py` |内存轨迹压缩|
| `entropy_scoring.py` |信息论重要性评分|
| `lru_cache_layer.py` |热实体的LRU缓存|
### 情报工具
|模块|说明|
|--------|-------------|
| `anti_hallucination.py` |幻觉检测和预防|
| `causal_inference.py` |因果关系发现|
| `strange_loops.py` |自参考循环检测|
| `continuous_learning.py` |在线互动学习|
| `model_router.py` |多提供商LLM路由|
| `activation_field_tools.py` |记忆激活场动力学|
| `procedural_evolution_tools.py` |程序性记忆进化|
| `routing_learning_tools.py` |学习查询路由优化|
| `surprise_consolidation_tools.py` |基于惊喜的内存整合|
| `provenance.py` |来源跟踪和L-Score验证|
### 集成工具
|模块|说明|
|--------|-------------|
| `safla_tools.py` |SAFLA 4层内存集成|
| `safla_remote_integration.py` |远程SAFLA集群网桥|
| `cluster_brain_tools.py` |多节点集群智能|
| `sleeptime_tools.py` |Letta睡眠时间计算集成|
| `tool_usage_logger.py` |工具调用分析|
## 测试```bash
# Run comprehensive test suite
python3 comprehensive_test.py
# RAG integration tests (22 tests)
python3 test_rag_integration_comprehensive.py
# Test specific subsystems
python3 test_graphrag_integration.py
python3 test_manifold_working_memory.py
python3 test_triple_signal_search.py
python3 test_surprise_consolidation.py
python3 test_trajectory_compression.py
python3 test_anti_hallucination.py
python3 test_causal_inference.py
# AGI phase tests
python3 test_agi_phase1.py
python3 test_agi_phase2.py
python3 test_agi_phase3.py
python3 test_agi_phase4.py
# Code execution sandbox
python3 test_advanced_tool_use.py
添加新工具
- 创建
{feature}_tools.py使用注册模式:```python
def register_{feature}_tools(app, *args):
@app.tool()
async def my_new_tool(param: str) -> str:
"""Tool description shown in MCP."""
return result
2. 注册于 `server/modules.py`:```python
if should_load_module("{feature}_tools"):
try:
from {feature}_tools import register_{feature}_tools
register_{feature}_tools(app)
except Exception as e:
logger.warning(f"{feature} integration skipped: {e}")
- 添加
tool_catalog.py用于渐进式工具发现。 - 在中编写测试
test_{feature}.py.
环境变量
| 变量 | 默认值 | 描述 |
|---|---|---|
MEMORY_PROFILE |
full |
刀具加载曲线(full 或 orchestrator) |
TOOL_USAGE_LOGGING |
true |
启用工具调用分析 |
AGENTIC_SYSTEM_PATH |
~/agentic-system |
代理系统的根路径 |
OLLAMA_HOST |
localhost:11434 |
用于LLM操作的Ollama服务器 |
QDRANT_HOST |
localhost |
Qdrant矢量数据库主机 |
QDRANT_PORT |
6333 |
Qdrant矢量数据库端口 |
ANTHROPIC_API_KEY |
-- | 用于生成上下文前缀 |
OPENAI_API_KEY |
-- | 用于查询扩展(可选) |
依赖项
关键依赖关系(参见 requirements.txt 完整列表):
fastmcp--MCP协议实现sentence-transformers--交叉编码器重新排序(ms-marco-MiniLM-L-6-v2)qdrant-client--BM25+矢量混合搜索RestrictedPython--安全执行沙盒代码anthropic-用于上下文检索的Claude APInumpy--矢量运算和熵评分
许可证
麻省理工学院
