代码语义记忆服务器

一个为Claude提供代码语义理解和长期记忆的服务器,支持代码搜索、偏好记忆和项目上下文维护。

  • by emmilco
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 emmilco/claude-memory-server

使用说明

克劳德内存+RAG服务器

Claude的语义记忆和代码理解层

这是一个MCP服务器,位于Claude和您的开发环境之间,保持对代码库、偏好和上下文的持久理解。把它看作是给克劳德一个长期记忆和语义搜索代码的能力。

系统

┌─────────────────────────────────────────────────────────┐
│  Claude Code                                             │
│  "Find the authentication logic"                         │
│  "Remember I prefer Python"                              │
└────────────────┬────────────────────────────────────────┘
                 │ MCP Protocol
┌────────────────▼────────────────────────────────────────┐
│  Memory RAG Server                                       │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │
│  │   Memories   │  │     Code     │  │   Git Hist   │  │
│  │ (preferences,│  │   (indexed   │  │  (commits &  │  │
│  │  workflows)  │  │  functions)  │  │   changes)   │  │
│  └──────────────┘  └──────────────┘  └──────────────┘  │
│         Semantic Vector Search (7ms)                     │
└─────────────────────────────────────────────────────────┘
                 │
┌────────────────▼────────────────────────────────────────┐
│  Your Development Environment                            │
│  • Code files (Python, JS, TS, Java, Go, Rust, PHP)     │
│  • Documentation (Markdown)                              │
│  • Git repository                                        │
└─────────────────────────────────────────────────────────┘

运作原理

1.索引: 服务器解析您的代码(使用Rust提高速度),提取语义单元(函数、类),并将其存储在带有嵌入的向量数据库中。

2.内存存储: 当您使用Claude时,服务器会自动存储首选项、项目上下文和决策。这些被分类和嵌入以进行语义检索。

3.语义搜索: 当Claude需要信息时,它会使用自然语言查询服务器。服务器根据以下内容返回相关代码、内存或git历史记录 意义,而不是关键字。

4.上下文维护: 在整个会话中,Claude保留了对代码库结构、偏好和项目特定知识的理解。

这能带来什么

  • 代码理解: 询问“身份验证逻辑在哪里?”而不是查找函数名
  • 持久首选项: Claude记得你更喜欢Python,使用async/await等。
  • 项目记忆: Claude知道这个项目使用FastAPI、PostgreSQL,并遵循特定的模式
  • Git意识: 从语义上搜索提交历史,跟踪代码是如何演变的
  • 混合搜索: 将语义理解与关键字精度相结合

状态: v4.0 RC1•✅ 2723次测试(BUG-023已修复)•覆盖率67%•搜索延迟7-13ms

版本: 4.0(生产就绪型企业功能)

特性

🔍 语义代码搜索(新增!)

按含义而不是关键字搜索代码库。用自然语言提问,并根据语义找到相关代码,而不仅仅是文本匹配。

搜索示例:

📌 Find authentication logic:
You: "Find the authentication logic"
→ auth/handlers.py:45-67 - login() async function
→ auth/middleware.py:23-45 - authenticate_request()
→ auth/token.py:12-34 - verify_jwt_token()

📌 Find error handling:
You: "Where do we handle database errors?"
→ db/connection.py:89-105 - handle_db_exception()
→ models/base.py:34-56 - retry_on_connection_error() decorator
→ api/error_handlers.py:12-28 - database_error_handler()

📌 Find API endpoints:
You: "Show me all the user-related API routes"
→ api/routes/users.py:23-45 - GET /api/users endpoint
→ api/routes/users.py:67-89 - POST /api/users/create endpoint
→ api/routes/users.py:102-124 - PUT /api/users/{id} endpoint

📌 Find initialization code:
You: "How does the application start up?"
→ main.py:12-34 - initialize_app() function
→ config/startup.py:45-78 - load_configuration()
→ db/init.py:23-45 - setup_database_connection()

为什么有效:

  • 语义理解:根据代码内容查找代码 做,而不仅仅是变量名
  • 混合模式:将语义搜索与关键字匹配相结合以提高精度
  • 上下文感知:了解函数、类和模块之间的关系
  • 快速:即使在大型代码库上,搜索延迟也为7-13ms

支持的语言:

  • 编程: Python、JavaScript、TypeScript、Java、Go、Rust、Ruby、Swift、Kotlin、PHP、C、C++、C#、SQL(14种语言)
  • 配置: JSON、YAML、TOML(3种格式)
  • 总计: 支持17种文件格式

演出

  • 7-13ms搜索延迟(混合搜索:10-18ms)
  • 10-20个文件/秒索引(采用并行嵌入,速度快4-8倍)
  • 重新索引的缓存命中率为98%(快5-10倍)
  • 7-13ms搜索延迟
  • 2.45个文件/秒索引
  • 7-13ms搜索延迟
  • 10-20个文件/秒索引(并行处理)
  • 通过自动重新索引实时查看文件

⚡ 自动索引(新增!)

零配置项目索引 -开始工作时,您的项目会自动索引:

$ python -m src.mcp_server
INFO: Starting auto-indexing for project: my-app at /path/to/my-app
INFO: Found 450 indexable files
INFO: Foreground indexing complete: 450 files, 2,340 units
INFO: File watcher started for my-app
INFO: Server initialized successfully

特征:

  • 自动检测:在服务器启动时为当前项目建立索引
  • 智能模式选择:
    • 小项目(<500个文件):前台模式,在~30-60s内完成
    • 大型项目(>500个文件):后台模式,非阻塞
  • 稳定性检测:仅当文件自上次索引后发生更改时才重新索引
  • 排除图案:自动跳过node_modules、.git、, ____pycache____等等。
  • 文件监视器集成:初始索引后,观察变化并逐步重新索引
  • 进度跟踪:使用查询索引状态 get_indexing_status() MCP工具

配置 (in ~/.claude-rag/.env 或环境变量):

# Enable/disable auto-indexing (default: true)
CLAUDE_RAG_AUTO_INDEX_ENABLED=true

# Index on server startup (default: true)
CLAUDE_RAG_AUTO_INDEX_ON_STARTUP=true

# File count threshold for background mode (default: 500)
CLAUDE_RAG_AUTO_INDEX_SIZE_THRESHOLD=500

# Recursive directory indexing (default: true)
CLAUDE_RAG_AUTO_INDEX_RECURSIVE=true

排除模式 可配置为 src/config.py:

  • node_modules/**, .git/**, venv/**, __pycache__/**
  • *.pyc, dist/**, build/**, .next/**, target/**
  • *.min.js, *.map

🧠 自动存储器

克劳德会自动记住:

  • 偏好设置:“我更喜欢Python”,“我总是使用async/await”
  • 工作流:“我通常在提交之前运行测试”
  • 项目事实:“此API使用FastAPI”,“数据库为PostgreSQL”
  • 事件:“修复了11月15日的身份验证错误”,“已部署到生产环境”

📚 文档搜索

  • 摄取markdown文档(README,docs/文件夹)
  • 跨所有文档的语义搜索
  • 项目特定背景
  • 智能组块保留结构

快速开始

先决条件

  • 必修的:
    • Python 3.8+(建议使用Python 3.13+以获得最佳性能)
    • Docker(用于Qdrant矢量数据库- 语义代码搜索所需)
  • 锈 -代码解析所需(mcp_performance_core模块)
  • ~1GB磁盘空间(大型代码库建议使用10GB)

安装(一个命令!)

# Clone and setup
git clone https://github.com/yourusername/claude-memory-server.git
cd claude-memory-server
python setup.py

# That's it! The setup wizard handles everything.

交互式向导将:

  • ✅ 检查您的系统
  • ✅ 安装依赖项
  • ✅ 配置存储(Qdrant矢量数据库用于语义搜索)
  • ✅ 通过Docker启动Qdrant(代码搜索需要)
  • ✅ 设置解析器(如果Rust不可用,Python回退)
  • ✅ 验证一切正常

结果: 2-5分钟即可完成安装!

注: 语义代码搜索需要在Docker上运行Qdrant。使用 claude-rag validate-setup 检查您的设置。

添加到克劳德代码

# Step 1: Get absolute Python path (important for pyenv users!)
PYTHON_PATH=$(which python)
echo "Python path: $PYTHON_PATH"  # Verify the path

# Step 2: Get project directory (make sure you're in claude-memory-server directory!)
PROJECT_DIR=$(pwd)
echo "Project directory: $PROJECT_DIR"  # Verify the path

# Step 3: Add MCP server with absolute paths
claude mcp add --transport stdio --scope user \
  claude-memory-rag -- \
  $PYTHON_PATH "$PROJECT_DIR/src/mcp_server.py"

这些变量意味着什么:

  • $PYTHON_PATH:Python解释器的完整路径(例如。, /usr/local/bin/python3)
  • $PROJECT_DIR:此项目目录的完整路径(例如。, /Users/you/claude-memory-server)
  • 这些是bashshell变量,当您运行上述命令时,它们会自动替换为实际路径

重要配置说明:

  • 对于pyenv用户: 使用绝对Python路径($PYTHON_PATH)确保MCP服务器使用安装了依赖项的正确Python环境,即使您在具有不同pyenv环境的不同项目目录之间切换。
  • 使用绝对脚本路径: 该配置使用完整路径 mcp_server.py 而不是 -m src.mcp_server 以确保它在任何目录下都能正常工作。这 cwd 并非所有Claude Code版本都可靠地遵守该参数。

验证安装

# Quick health check
python -m src.cli health

# Comprehensive validation (checks Python, dependencies, Qdrant, parsers)
python -m src.cli validate-install

# If validation fails, follow the actionable error messages provided

可选:升级以获得更好的性能

# Add Rust parser (10-20x faster indexing)
python setup.py --build-rust

# Upgrade to Qdrant (better for large datasets)
python setup.py --upgrade-to-qdrant
Advanced: Manual Installation

如果您更喜欢手动控制:

# 1. Install dependencies
pip install -r requirements.txt

# 2. Build Rust module (required for code indexing)
cd rust_core && maturin develop && cd ..

# 3. (Optional) Start Qdrant
docker-compose up -d

# 4. Configure (edit .env or set environment variables)
export CLAUDE_RAG_STORAGE_BACKEND=qdrant

用法

代码搜索

索引代码库:

# Via CLI
python -m src.cli index ./src --project-name my-project

# Via Claude (MCP)
You: Please index the src directory
Claude: ✅ Indexed 175 semantic units from 4 files in 2.99s

搜索代码:

# Via Claude (MCP)
You: Find code related to database connections
Claude: [Shows relevant functions with file paths and line numbers]

注意变化:

python -m src.cli watch ./src
# Auto-reindexes when files change

内存和文档

存储首选项:

You: I prefer TypeScript for all new projects
Claude: ✅ Stored preference memory (global scope)

摄入文件:

You: Please analyze this directory and ingest all documentation
Claude: ✅ Documentation Ingestion Complete
        Files processed: 15
        Total chunks created: 87

查询文档:

You: How does authentication work in this project?
Claude: Based on the documentation:
        [Shows relevant sections from docs]

交互式浏览记忆:

# Launch the interactive memory browser (TUI)
python -m src.cli browse

# Features:
# - Full-text search across all memories
# - Filter by category, context level, or project
# - View detailed memory metadata (provenance, trust score, usage stats)
# - Navigate with keyboard shortcuts
# - Real-time search as you type

项目档案

归档非活动项目:

# View project status
python -m src.cli archival status
# Shows active, paused, archived projects with inactivity metrics

# Archive a project to save storage
python -m src.cli archival archive old-project
# ✅ Compressed and archived (77% storage reduction)

# Reactivate when needed
python -m src.cli archival reactivate old-project
# ✅ Restored in ~10 seconds

导出以进行备份或迁移:

# Export archived project to portable file
python -m src.cli archival export my-project
# Creates: my-project_archive_20251118_103000.tar.gz (28.3 MB)
# Includes: compressed index, manifest, README

# Import on another machine
python -m src.cli archival import my-project_archive_20251118_103000.tar.gz
# ✅ Imported project 'my-project' (28.3 MB)

# List available exports
python -m src.cli archival list-exportable
# Shows all archived projects ready for export

存储优化:

  • 压缩:归档项目的存储空间减少60-80%
  • 便携的:导出到.tar.gz进行备份或共享
  • 自动:配置基于非活动状态的自动存档
  • 快速:在5-30秒内恢复存档的项目

节省示例:

Before: 623.7 MB (5000 files, active project)
After:  142.8 MB (archived with compression)
Saved:  77% storage reduction

可用的MCP工具

Claude可以使用这些工具:

代码搜索工具(新增!)

  • search_code -跨索引文件的语义代码搜索
  • index_codebase -为目录建立索引以进行代码搜索

内存工具

  • store_memory -存储内存(通常是自动的)
  • retrieve_memories -搜索记忆和/或文档
  • delete_memory -按ID删除特定内存

文档工具

  • ingest_docs -摄入降价文件
  • search_all -无路由的显式搜索

实用工具

  • get_status -查看内存和索引统计信息
  • show_context -调试工具查看当前上下文

建筑

┌─────────────────────────────────────┐
│          Claude via MCP              │
└──────────────┬──────────────────────┘
               │
               ▼
┌─────────────────────────────────────┐
│      MCP Server (mcp_server.py)      │
│  ┌───────────────────────────────┐  │
│  │   search_code                 │  │
│  │   index_codebase              │  │
│  │   store_memory                │  │
│  │   retrieve_memories           │  │
│  └───────────────────────────────┘  │
└───────┬──────────────────┬──────────┘
        │                  │
        ▼                  ▼
┌──────────────┐    ┌──────────────┐
│  Incremental │    │   Qdrant     │
│   Indexer    │───▶│  Vector DB   │
│              │    │ (localhost   │
│ Rust Parser  │    │  :6333)      │
│ 1-6ms/file   │    │ 7-13ms search│
└──────────────┘    └──────────────┘

技术栈

核心

  • Python 3.8+ -主要应用(推荐3.13+)
  • 锈蚀1.91 -代码解析(树型,索引所需)
  • Qdrant -矢量数据库(可选,SQLite回退可用)
  • PyO3 -Python Rust桥(代码解析所需)

AI/ML

  • 句子变换器 -嵌入生成
  • 全mpnet-base-v2 -嵌入模型(384调光)

存储

  • Qdrant -初级矢量存储
  • SQLite -回退+嵌入缓存

演出

度量 性能
代码搜索 7-13ms延迟
索引 2.45个文件/秒
解析 每个文件1-6ms(Rust)
嵌入 每条文本约30ms
嵌入(缓存) <1ms
测试 2723通过✅
代码覆盖率 67%(核心80-85%)

项目结构

claude-memory-server/
├── src/
│   ├── core/              # Main server logic
│   │   ├── server.py      # MemoryRAGServer with all tools
│   │   ├── models.py      # Pydantic data models
│   │   └── exceptions.py  # Custom exceptions
│   ├── store/             # Vector storage
│   │   ├── qdrant_store.py    # Qdrant (primary)
│   │   └── sqlite_store.py    # SQLite (fallback)
│   ├── embeddings/        # Embedding generation & cache
│   ├── memory/            # Code indexing
│   │   ├── incremental_indexer.py  # Main indexer
│   │   └── file_watcher.py         # Auto-reindexing
│   ├── cli/               # CLI commands (index, watch)
│   ├── mcp_server.py      # MCP entry point
│   └── config.py          # Configuration
├── rust_core/             # Rust parsing module
│   └── src/parsing.rs     # Tree-sitter parsing
├── tests/                 # 2723 tests
├── docker-compose.yml     # Qdrant setup
└── README.md              # This file

文档

📖 基本文件:

  1. TUTORIAL.md - 🚀 从这里开始! 完整的初学者友好教程(macOS+Qdrant)
  2. README.md -此文件(用户指南和快速参考)
  3. CLAUDE.md -参与此项目的AI代理指南
  4. 更改日志.md -版本历史和更改
  5. TODO.md -当前任务和未来工作

综合指南(docs/)

技术文档

存档文档

  • 会议摘要 docs/archive/

配置

可以使用以下任一方式配置服务器 JSON配置文件 (推荐)或 环境变量.

配置优先级(从高到低):

  1. 环境变量(CLAUDE_RAG_*)
  2. JSON配置文件(~/.claude-rag/config.json)
  3. 内置默认值

选项1:JSON配置(推荐)

创建 ~/.claude-rag/config.json:

{
  "storage_backend": "qdrant",
  "embedding_model": "all-mpnet-base-v2",
  "enable_parallel_embeddings": true,
  "enable_file_watcher": true,
  "watch_debounce_ms": 1000
}

优点:

  • 更易于阅读和编辑
  • 在所有项目中持续
  • 无环境变量冲突
  • 看 config.json.example 对于所有带有注释的选项

常见预设:

// Standard
{
  "storage_backend": "qdrant",
  "qdrant_url": "http://localhost:6333",
  "enable_parallel_embeddings": true
}

// High Performance
{
  "storage_backend": "qdrant",
  "enable_parallel_embeddings": true,
  "embedding_parallel_workers": 8,
  "embedding_batch_size": 64,
  "enable_hybrid_search": true
}

选项2:环境变量

创建 .env 文件(项目特定配置):

# Storage Backend
CLAUDE_RAG_STORAGE_BACKEND=qdrant
CLAUDE_RAG_QDRANT_URL=http://localhost:6333

# Embeddings
CLAUDE_RAG_EMBEDDING_MODEL=all-mpnet-base-v2
CLAUDE_RAG_ENABLE_PARALLEL_EMBEDDINGS=true

# File Watching
CLAUDE_RAG_ENABLE_FILE_WATCHER=true
CLAUDE_RAG_WATCH_DEBOUNCE_MS=1000

何时使用:

  • 覆盖特定项目的全局设置
  • 临时配置更改
  • CI/CD环境
  • 看 .env.example 对于所有可用变量

快速配置指南

# View current configuration
python -m src.cli status

# Configure storage backend
export CLAUDE_RAG_STORAGE_BACKEND=qdrant

测试

# Run all tests (68/68 should pass)
pytest tests/ -v

# With coverage
pytest tests/ --cov=src --cov-report=term-missing

# Specific test suite
pytest tests/unit/ -v           # Unit tests
pytest tests/integration/ -v    # Integration tests

# Code search end-to-end
python test_code_search.py

故障排除

Qdrant未连接

# Check Qdrant status
docker-compose ps
curl http://localhost:6333/health

# Restart if needed
docker-compose restart

Rust模块错误

# Rebuild Rust module
cd rust_core
maturin develop
cd ..

导入错误

# Reinstall dependencies
pip install -r requirements.txt

代码搜索不起作用

# 1. Check Qdrant is running
curl http://localhost:6333/health

# 2. Re-index codebase
python -m src.cli index ./src

# 3. Run tests
python test_code_search.py

发展

运行测试

pytest tests/ -v              # All tests
pytest tests/unit/ -v         # Unit only
pytest tests/integration/ -v  # Integration only

构建Rust模块

cd rust_core
maturin develop --release    # For development
maturin build --release      # For distribution
cd ..

代码风格

  • Python:PEP 8,类型提示,文档字符串
  • 锈迹:货物形状,易碎
  • 合并前必须通过所有测试
  • 预提交挂钩: 强制执行CHANGELOG.md更新(绕过 --no-verify 如果需要)

隐私和安全

  • ✅ 100%本地处理(无云同步)
  • ✅ 本地生成的嵌入(无外部API)
  • ✅ 只有Claude API调用进入Anthropic
  • ✅ Vector DB在Docker中本地运行
  • ⚠️ 数据库未加密(如果需要,请添加SQLCipher)

性能基准

编码索引

  • 索引文件: 29
  • 语义单位: 981
  • 时间: 11.82秒
  • 成功率: 100%
  • 搜索延迟: 平均6.3毫秒
  • 吞吐量: 2.45个文件/秒

项目档案

  • 压缩比: 0.20-0.30(减少70-80%)
  • 存档时间: 5-30秒(因项目规模而异)
  • 恢复时间: 5-20秒
  • 进出口往返: 100%完整性
  • 节省存储空间: 60-80%用于存档项目

存档性能示例:

项目大小 文件 单位 存档时间 压缩大小 节省
小 100 500 ~5s 2.1 MB 75%
中等 1000 5000 ~15s 28.4MB 77%
大 5000 25000 ~30秒 142.8 MB 77%

看 性能_手册_报告.md 了解详情。

需求

  • python 3.8+(3.13测试)
  • 锈蚀: 1.70+(用于建筑,不需要运行)
  • Docker: 对于Qdrant
  • 磁盘: ~500MB(型号+数据)
  • 猛撞: ~1GB(已加载型号)

支持的语言

代码搜索支持 17种文件格式 (14种编程语言+3种配置格式):

编程语言:

  • Python(.py)
  • JavaScript(.js、.jsx)
  • TypeScript(.ts、.tsx)
  • Java(.Java)
  • 去(.去)
  • 锈蚀(.rs)
  • Ruby(.rb)
  • Swift(.Swift)
  • Kotlin(.kt,.kts)
  • PHP(.PHP)
  • C(.C,.h)
  • C++(.cpp、.cc、.cxx、.hpp、.hxx、.hh)
  • C#(.cs)
  • SQL(.SQL)

配置文件:

  • JSON(.JSON)
  • YAML(.YAML,.yml)
  • 汤姆(.TOML)

可以通过树型语法添加更多语言。

贡献

看 Developpent.md 获取开发指南和贡献说明。

当前状态

  • ✅ 第一阶段:基础(100%完成)
  • ✅ 第2阶段:安全和上下文(100%完成)
  • ✅ 第三阶段:代码智能(85%完成)
  • ⚠️ 第4阶段:测试和文档(完成70%-编写8份综合指南,覆盖率为61%)

许可证

麻省理工学院

致谢

内置:


🚀 准备好开始了吗?遵循完整 TUTORIAL.md 用于逐步设置!