代码搜索分析服务器

MCP服务器通过向量嵌入技术为AI代理提供高效的代码搜索和分析功能,显著减少token使用并提升响应速度。

  • by zeropep
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 zeropep/code-agent-mcp

使用说明

代码嵌入AI-MCP服务器

MCP(模型上下文协议)服务器,用于使用向量嵌入进行AI驱动的代码搜索和分析。

概述

此MCP服务器通过基于向量的语义搜索为AI代理提供了对大型代码库的高效访问,将令牌使用率降低了约99%,响应时间缩短了10倍。

价值主张

Traditional approach: Read entire codebase → 500K tokens → 5 minutes
MCP approach:        Vector search        → 5K tokens   → 0.5 seconds

结果: 99%的代币减少+10倍的速度提升

特性

工具

  • 搜索代码:使用自然语言进行语义代码搜索
  • 查找_类似代码:查找代码重复和重构机会
  • get_function_实现:按名称快速查找函数
  • list_项目:列出所有已注册的项目
  • get_project_stats:获取项目统计信息(文件、块、语言)

资源

  • 项目://{id}:访问项目信息
  • 项目://{id}/stats:访问项目统计信息

提示

  • 代码审查:带上下文的自动代码审查
  • 重构代码:用类似的代码模式重构建议
  • 修复bug:调试相关代码上下文的帮助
  • 编写测试:使用实现上下文生成测试
  • 解释代码:完整上下文的代码解释

平台支持

  • 克劳德桌面版:本地MCP集成
  • 克劳德代码:MCP SDK集成
  • LangGraph:LangChain工具适配器
  • REST API:直接HTTP访问回退

快速开始

1.先决条件

  • Python 3.10+
  • 运行在上的代码嵌入ai FastAPI服务器 localhost:8000

2.安装

cd code-agent-mcp
pip install -r requirements.txt

3.启动FastAPI服务器

cd ../code-embedding-ai
python -m src.cli server start --host localhost --port 8000

4.注册项目

python -m src.cli project add /path/to/your/project --name "MyProject"
python -m src.cli process project <project_id>

5.运行MCP服务器

cd ../code-agent-mcp
python -m src.server

服务器将在stdio模式下运行,为MCP客户端连接做好准备。

配置

mcpconfig.json

{
  "server": {
    "name": "code-embedding-ai",
    "version": "1.0.0",
    "description": "MCP server for AI-powered code search"
  },
  "api": {
    "base_url": "http://localhost:8000",
    "timeout": 30
  },
  "logging": {
    "level": "INFO",
    "format": "json"
  }
}

配置选项:

  • api.base_url:FastAPI服务器URL(默认值: http://localhost:8000)
  • api.timeout:请求超时(秒)(默认值:30)
  • logging.level:日志级别(调试、信息、警告、错误)
  • logging.format:日志格式(json、文本)

重要提示:Claude代码集成

Claude代码中的MCP工具暴露

电流限幅:MCP工具(搜索代码、查找相似代码等)有 未直接暴露 作为Claude Code中的可调用函数。只有资源可以通过以下方式访问 ListMcpResourcesTool 和 ReadMcpResourceTool.

解决方案

1.使用MCP资源(基础)

# List available projects
ListMcpResourcesTool(server='code-search')

# Get project information
ReadMcpResourceTool(
    server='code-search',
    uri='project://proj_212e9b33ec8e'
)

# Get project statistics
ReadMcpResourceTool(
    server='code-search',
    uri='project://proj_212e9b33ec8e/stats'
)

2.直接FastAPI调用(高级)

使用中提供的辅助脚本 .claude/helpers/code_search.py:

# Search code
python .claude/helpers/code_search.py search "authentication logic" proj_id 5

# Find similar code
python .claude/helpers/code_search.py similar "def connect():" python

# Get function implementation
python .claude/helpers/code_search.py function connect GitMonitor

# List projects
python .claude/helpers/code_search.py projects

# Get stats
python .claude/helpers/code_search.py stats proj_212e9b33ec8e

3.项目配置

要在Claude code项目中启用代码搜索优先级,请执行以下操作:

  1. 复制配置文件 对于您的项目:

    # Windows
    .\setup-code-search.ps1 C:\path\to\your\project
    
    # Linux/Mac
    ./setup-code-search.sh /path/to/your/project
    
  2. 或手动创建 .claude/settings.local.json:

    {
      "systemInstructions": "When finding or modifying code, FIRST check code-search MCP using ListMcpResourcesTool...",
      "enableAllProjectMcpServers": true,
      "enabledMcpjsonServers": ["code-search"],
      "permissions": {
        "allow": [
          "Bash(curl http://localhost:8000/*)",
          "Bash(python .claude/helpers/code_search.py:*)"
        ]
      }
    }
    

看 QUICK_START_GUIDE.md 有关详细的设置说明。


使用示例

克劳德桌面版

在中配置 claude_desktop_config.json:

使用虚拟环境(推荐):

{
  "mcpServers": {
    "code-embedding-ai": {
      "command": "/path/to/code-agent-mcp/.venv/Scripts/python.exe",
      "args": ["-m", "src.server"],
      "cwd": "/path/to/code-agent-mcp",
      "env": {
        "PYTHONPATH": "/path/to/code-agent-mcp"
      }
    }
  }
}

使用Python系统:

{
  "mcpServers": {
    "code-embedding-ai": {
      "command": "python",
      "args": ["-m", "src.server"],
      "cwd": "/absolute/path/to/code-agent-mcp",
      "env": {
        "PYTHONPATH": "/absolute/path/to/code-agent-mcp"
      }
    }
  }
}

然后在Claude Desktop中:

Find all authentication-related code in my project

克劳德代码

新项目的设置:

# Quick setup (automated)
cd /path/to/your/project
/path/to/vector/setup-code-search.sh .

# Or copy configuration manually
mkdir -p .claude/helpers
cp /path/to/vector/.claude/settings.local.json .claude/
cp /path/to/vector/.claude/helpers/code_search.py .claude/helpers/

在Claude Code会话中使用:

由于MCP工具不直接暴露,请使用以下方法之一:

# Method 1: MCP Resources (basic queries)
# In Claude session, say:
"List projects in code-search"
# Claude will use: ListMcpResourcesTool(server='code-search')

# Method 2: Helper script (advanced search)
# In Claude session, say:
"Search for 'authentication logic' in code using the helper script"
# Claude will run: python .claude/helpers/code_search.py search "..." proj_id

# Method 3: Direct API call
curl -X POST http://localhost:8000/search/semantic \
  -H "Content-Type: application/json" \
  -d '{"query": "authentication", "project_id": "proj_id", "top_k": 5}'

程序化使用(MCP SDK):

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

server_params = StdioServerParameters(
    command="python",
    args=["-m", "src.server"],
    cwd="/path/to/code-agent-mcp"
)

async with stdio_client(server_params) as (read, write):
    async with ClientSession(read, write) as session:
        await session.initialize()

        # Search for code
        result = await session.call_tool(
            "search_code",
            {"query": "user authentication", "top_k": 5}
        )
        print(result.content[0].text)

LangGraph

from examples.langgraph_integration import SearchCodeTool
from langchain_anthropic import ChatAnthropic
from langgraph.prebuilt import create_react_agent

tools = [SearchCodeTool(), FindSimilarCodeTool()]
llm = ChatAnthropic(model="claude-3-5-sonnet-20241022")
agent = create_react_agent(llm, tools)

result = await agent.ainvoke({
    "messages": [("human", "Find authentication code and review it")]
})

建筑

┌─────────────────────────────────────────────────────────┐
│                     AI Clients                          │
│  Claude Desktop │ Claude Code │ LangGraph │ Custom App  │
└────────┬────────────────┬─────────────┬────────────┬────┘
         │                │             │            │
         │ MCP Protocol   │ MCP SDK     │ Adapter    │ REST API
         │                │             │            │
         ▼                ▼             ▼            ▼
┌─────────────────────────────────────────────────────────┐
│              MCP Server (stdio/SSE)                     │
│  ┌──────────────┬──────────────┬──────────────┐        │
│  │   Tools      │  Resources   │   Prompts    │        │
│  └──────────────┴──────────────┴──────────────┘        │
└────────────────────────┬────────────────────────────────┘
                         │ HTTP (httpx)
                         ▼
┌─────────────────────────────────────────────────────────┐
│           FastAPI Server (localhost:8000)               │
│  /search/semantic │ /search/similar-code │ /projects   │
└────────────────────────┬────────────────────────────────┘
                         │
                         ▼
┌─────────────────────────────────────────────────────────┐
│              ChromaDB + Embeddings                      │
│         (Local or API-based embeddings)                 │
└─────────────────────────────────────────────────────────┘

文档

提供全面的指南:

项目特定文件(in .claude/ 设置后):

例子

看 examples/ 目录:

测试

使用pytest运行测试:

# Install test dependencies
pip install pytest pytest-asyncio

# Run all tests
pytest tests/ -v

# Run specific test
pytest tests/test_mcp_server.py::TestAPIClient::test_search_semantic -v

故障排除

服务器无法启动

  1. 检查Python版本: python --version (要求3.10+)
  2. 检查依赖关系: pip install -r requirements.txt
  3. 手动测试服务器: python -m src.server

工具不工作

  1. 验证FastAPI服务器是否正在运行:

    curl http://localhost:8000/health
    
  2. 检查项目注册:

    cd ../code-embedding-ai
    python -m src.cli project list
    
  3. 如果需要,处理项目:

    python -m src.cli process project <project_id>
    

连接超时

  • 增加超时时间 mcp_config.json:

    {"api": {"timeout": 60}}
    
  • 检查FastAPI服务器日志是否有错误

演出

响应时间

典型响应时间(因代码库大小而异):

  • search_code:100-500ms
  • find_similar_code:150-600毫秒
  • get_function_implementation:50-200ms
  • list_projects:10-50ms
  • get_project_stats:20-100ms

优化提示

  1. 按项目_id筛选:将搜索范围缩小到特定项目
  2. 调整top_k:请求更少的结果以获得更快的响应
  3. 使用最小相似性:筛选低质量匹配项
  4. 本地嵌入:使用本地模型避免API延迟

安全

  • 仅限本地:服务器仅连接到本地主机
  • 无外部请求:所有操作都是本地操作
  • 无数据共享:代码永远不会离开你的机器
  • stdio传输:确保本地通信安全

发展

项目结构

code-agent-mcp/
├── src/
│   ├── server.py           # MCP server main
│   ├── api_client.py       # FastAPI client
│   ├── config.py           # Configuration
│   └── __init__.py
├── tests/
│   └── test_mcp_server.py  # Unit tests
├── examples/
│   ├── claude_code_integration.py
│   └── langgraph_integration.py
├── docs/
│   ├── MCP_SERVER_GUIDE.md
│   └── CLAUDE_DESKTOP_SETUP.md
├── mcp_config.json         # Configuration
├── requirements.txt        # Dependencies
└── README.md

贡献

  1. 复刻仓库
  2. 创建要素分支
  3. 进行更改
  4. 添加新功能的测试
  5. 运行测试: pytest tests/ -v
  6. 提交拉取请求

路线图

未来改进:

  • []请求缓存重复查询
  • []并行API性能调用
  • []大结果的流式响应
  • []多后端支持
  • []身份验证/授权
  • []指标和监控仪表板
  • []用于实时更新的Git webhook集成

许可证

麻省理工学院

支持

  • 问题: GitHub问题
  • 文档:参见 docs/ 目录
  • 例子:参见 examples/ 目录

相关项目