MCP代码分析服务器
    
一种智能MCP(模型上下文协议)服务器,为大型代码库提供高级代码分析和搜索功能。它使用纯FastMCP实现构建,使用TreeSitter进行解析,使用PostgreSQL和pgvector进行向量存储,使用OpenAI嵌入进行语义搜索。
特性
- 🔍 语义代码搜索:查找相关代码的自然语言查询
- 🏛️ 领域驱动分析:使用LLM提取业务实体和有界上下文
- 📊 代码结构分析:对模块、类和函数的分层理解
- 🔄 增量更新:基于Git的更改跟踪,实现高效的重新索引
- 🎯 智能代码解释:具有上下文聚合的AI驱动解释
- 🔗 相关性分析:了解代码关系和依赖关系
- 🌐 知识图谱:使用社区检测(Leiden算法)构建语义图
- 💡 DDD重构:领域驱动设计建议和改进
- 🚀 高性能:处理包含数百万行代码的代码库
- 🐍 Python支持:全面支持Python,更多语言即将推出
MCP工具可用
核心搜索工具
search_code-使用具有语义理解的自然语言查询搜索代码find_definition-查找定义符号(函数、类、模块)的位置find_similar_code-使用向量相似度查找与给定代码段相似的代码模式get_code_structure-获取代码文件的层次结构
代码分析工具
explain_code-获取代码元素(模块、类、函数)的层次化解释suggest_refactoring-获取AI支持的代码重构建议以进行代码改进analyze_dependencies-分析代码实体之间的依赖关系和关系
存储库管理工具
sync_repository-手动触发特定存储库的同步
领域驱动设计分析工具
extract_domain_model-使用LLM分析提取域实体和关系find_aggregate_roots-使用域分析在代码库中查找聚合根analyze_bounded_context-分析有界上下文及其关系suggest_ddd_refactoring-建议领域驱动设计重构改进find_bounded_contexts-查找代码库中的所有有界上下文generate_context_map-生成上下文映射(JSON、Mermaid、PlantUML)
高级分析工具
analyze_coupling-使用度量分析有界上下文之间的耦合suggest_context_splits-建议如何拆分大型有界上下文detect_anti_patterns-检测DDD反模式(贫血模型、上帝对象等)analyze_domain_evolution-跟踪域模型随时间的变化get_domain_metrics-获取全面的领域健康指标和见解
快速开始
先决条件
- Docker和Docker Compose
- OpenAI API密钥(用于语义搜索功能)
- 带薄片的镍(建议用于开发)
Docker部署(推荐)
最简单的入门方法是使用Docker Compose,它提供了一个包含PostgreSQL和pgvector的完整隔离环境。
- 克隆存储库:
git clone https://github.com/johannhartmann/mcp-code-analysis-server.git
cd mcp-code-analysis-server- 设置环境变量:
export OPENAI_API_KEY="your-api-key-here"
# Or add to .env file- 配置存储库:
创建一个 config.yaml 文件以指定要跟踪的存储库:
repositories:
- url: https://github.com/owner/repo1
branch: main
- url: https://github.com/owner/repo2
branch: develop
- url: https://github.com/owner/private-repo
access_token: "github_pat_..." # For private repos
# Scanner configuration
scanner:
storage_path: ./repositories
exclude_patterns:
- "__pycache__"
- "*.pyc"
- ".git"
- "venv"
- "node_modules"- 使用Docker Compose启动服务:
docker-compose up -d这将:
- 使用pgvector扩展名启动PostgreSQL
- 构建并启动MCP代码分析服务器
- 使用所需的架构初始化数据库
- 开始自动扫描已配置的存储库
服务器作为纯MCP实现运行,可以通过任何兼容MCP的客户端访问。
发展环境(当地)
对于开发工作,请使用提供所有必要工具和依赖关系的Nix开发环境:
# Enter the Nix development environment
nix develop
# Install Python dependencies
uv sync
# Start PostgreSQL (if not using Docker Compose)
docker-compose up -d postgres
# Run the scanner to populate the database
python -m src.scanner
# Start the MCP server
python -m src.mcp_server
# Or run tests
pytest
# Check code quality
ruff check .
black --check .
mypy .
vulture src vulture_whitelist.pyNix环境包括:
- Python 3.11及其所有依赖项
- 代码格式化工具(黑色,isort)
- 棉绒(头皮屑、皮绒、土匪)
- 类型检查器(mypy)
- 死码检测(秃鹫)
- 测试运行器(pytest)
- 预提交挂钩
配置
编辑 config.yaml 自定义:
# OpenAI API key (can also use OPENAI_API_KEY env var)
openai_api_key: "sk-..."
# Repositories to track
repositories:
- url: https://github.com/owner/repo
branch: main # Optional, uses default branch if not specified
- url: https://github.com/owner/private-repo
access_token: "github_pat_..." # For private repos
# Scanner configuration
scanner:
storage_path: ./repositories
exclude_patterns:
- "__pycache__"
- "*.pyc"
- ".git"
- "venv"
- "node_modules"
# Embeddings configuration
embeddings:
model: "text-embedding-ada-002"
batch_size: 100
max_tokens: 8000
# MCP server configuration
mcp:
host: "0.0.0.0"
port: 8080
# Database configuration
database:
host: localhost
port: 5432
database: code_analysis
user: codeanalyzer
password: your-secure-password使用示例
使用MCP工具
服务器运行后,您可以通过任何MCP客户端使用这些工具:
# Search for code using natural language
await mcp.call_tool("search_code", {
"query": "functions that handle user authentication",
"limit": 10
})
# Find where a symbol is defined
await mcp.call_tool("find_definition", {
"name": "UserService",
"entity_type": "class"
})
# Get hierarchical code explanation
await mcp.call_tool("explain_code", {
"path": "src.auth.user_service.UserService"
})
# Find similar code patterns
await mcp.call_tool("find_similar_code", {
"code_snippet": "def authenticate_user(username, password):",
"limit": 5,
"threshold": 0.7
})
# Get code structure
await mcp.call_tool("get_code_structure", {
"file_path": "src/auth/user_service.py"
})
# Get refactoring suggestions
await mcp.call_tool("suggest_refactoring", {
"file_path": "src/auth/user_service.py",
"focus_area": "performance"
})
# Extract domain model from code
await mcp.call_tool("extract_domain_model", {
"code_path": "src/domain/user.py",
"include_relationships": True
})
# Find aggregate roots
await mcp.call_tool("find_aggregate_roots", {
"context_name": "user_management" # optional
})
# Analyze bounded context
await mcp.call_tool("analyze_bounded_context", {
"context_name": "authentication"
})
# Generate context map
await mcp.call_tool("generate_context_map", {
"output_format": "mermaid" # json, mermaid, or plantuml
})使用克劳德桌面
在Claude Desktop设置中配置MCP服务器:
对于stdio模式(在本地运行时):
{
"mcpServers": {
"code-analysis": {
"command": "python",
"args": ["-m", "src.mcp_server"],
"cwd": "/path/to/mcp-code-analysis-server",
"env": {
"OPENAI_API_KEY": "your-api-key"
}
}
}
}对于HTTP模式(使用Docker时):
{
"mcpServers": {
"code-analysis": {
"url": "http://localhost:8000"
}
}
}然后在Claude Desktop中:
- “搜索处理身份验证的函数”
- “显示UserService类的实现”
- “查找数据库连接池的所有用法”
- “哪些文件导入utils模块?”
发展
运行测试
# Run all tests
pytest
# Run with coverage
pytest --cov=src --cov-report=html
# Run specific test types
pytest tests/unit/
pytest tests/integration/代码质量
该项目使用集成到Nix开发环境中的全面代码质量工具:
# Run all linters
ruff check .
# Format code
black .
isort .
# Type checking
mypy .
# Find dead code
vulture src vulture_whitelist.py
# Run pre-commit hooks
nix-pre-commit预提交钩子
安装预提交挂钩以进行自动代码质量检查:
echo '#!/bin/sh' > .git/hooks/pre-commit
echo 'nix-pre-commit' >> .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit建筑
服务器由几个关键组件组成:
- 扫描仪模块:通过增量更新监视和同步Git存储库
- 解析器模块:使用TreeSitter提取代码结构以进行精确的AST解析
- 嵌入模块:通过OpenAI生成用于向量搜索的语义嵌入
- 数据库模块:PostgreSQL具有pgvector扩展,可实现高效的向量存储
- 查询模块:处理自然语言查询和符号查找
- MCP服务器:纯FastMCP实现,公开代码分析工具
- 域模块:提取用于DDD分析的域实体和关系
演出
- 初始索引:并行处理时约1000个文件/分钟
- 增量更新:使用Git跟踪100个更改的文件,时间\<10秒
- 查询响应:使用pgvector进行语义搜索\<2秒
- 可扩展性:支持多达1000万行以上的代码库
- 存储器效率:优化了数据库会话和批处理
贡献
我们欢迎捐款!请看 贡献.md 作为指导方针。
许可证
此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。
作者
约翰·彼得·哈特曼 电子邮件:johann-peter.hartmann@mayflower.de github: @约翰哈特曼
关键技术
- FastMCP:纯MCP协议实现
- TreeSitter:强大的代码解析和AST生成
- pg载体:高性能矢量相似性搜索
- OpenAI嵌入:代码的语义理解
- PostgreSQL:可靠的数据持久性和复杂的查询
- 无:可复制的开发环境
- 码头工人:容器化部署和隔离
