dondetir/CodeGrok_mcp

GitHub: dondetir/CodeGrok_mcp

一个基于 MCP 的语义代码搜索与理解服务器,让 AI 助手在本地高效查询代码库。

Stars: 13 | Forks: 4

# CodeGrok MCP **语义代码搜索用于AI助手** [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![MCP](https://img.shields.io/badge/MCP-Compatible-green.svg)](https://modelcontextprotocol.io/) *让您的AI助手真正理解您的代码库* [功能](#features) • [快速开始](#quick-start) • [能力](#-what-codegrok-can-do) • [限制](#-what-codegrok-cannot-do) • [集成](#-ai-tool-integrations) • [用例](#-use-cases)
## 什么是 CodeGrok MCP? CodeGrok MCP 是一个 **模型上下文协议(MCP)服务器**,它使AI助手能够使用 **语义嵌入** 和 **Tree-sitter 解析** 智能地搜索和理解代码库。 与简单的文本搜索不同,CodeGrok 理解代码结构——它知道什么是函数、类和方法,并且即使您用自然语言描述也能找到相关代码。 ``` You: "Where is authentication handled?" CodeGrok: Returns auth middleware, login handlers, JWT validation code... ``` ### 为什么要使用 CodeGrok? **问题:** AI 助手的上下文窗口有限。发送整个代码库既昂贵又常常不可能。 **解决方案:** CodeGrok 一次性索引您的代码,然后AI可以语义化查询并仅返回最相关的 5-10 个代码片段——相比“读取所有文件”的朴素方法,**减少 10-100 倍的 token**。 ## 功能 - **语义代码搜索** - 按含义而非关键词查找代码 - **9 种语言支持** - Python、JavaScript、TypeScript、C、C++、Go、Java、Kotlin、Bash - **28 种文件扩展名** - 全面覆盖 `.jsx`、`.tsx`、`.mjs`、`.hpp` 等 - **快速并行索引** - 多线程解析提速 3-5 倍 - **增量更新** - 仅重新索引已更改的文件(自动模式) - **本地且私有** - 所有数据保留在您的机器上的 `.codegrok/` 文件夹中 - **零 LLM 依赖** - 轻量级专注工具(无需 API 密钥) - **GPU 加速** - 自动检测 CUDA 以加快嵌入计算 - **适用于任何 MCP 客户端** - Claude、Cursor、Cline 等 ## ✅ CodeGrok 能做什么 ### 用于实时编码(AI 辅助开发) | 能力 | 描述 | |------------|-------------| | **语义代码搜索** | 自然语言查询 → 向量相似度搜索已索引代码 | | **按目的查找代码** | 查询“认证如何工作?”→ 返回相关认证文件及行号 | | **符号提取** | 提取函数、类、方法及其签名、文档字符串、调用、导入 | | **增量更新** | `learn` 使用自动模式时仅重新索引已修改文件(使用文件修改时间) | | **持久化存储** | 索引在 `.codegrok/` 文件夹中保存,重启后仍存在 | | **加载现有索引** | `learn` 使用 `mode='load_only'` 可立即加载已索引的代码库 | ### 用于学习新代码库 | 能力 | 描述 | |------------|-------------| | **入口点发现** | 查询“主入口点”以查找执行起点 | | **架构理解** | 查询“数据库连接”以查找数据层 | | **领域概念** | 查询“用户认证流程”以查找认证逻辑 | | **索引统计** | 查看已解析文件、提取符号数量及耗时信息 | ## ❌ CodeGrok 不能做什么 ### 不适用于以下场景 | 限制 | 解释 | |------------|-------------| | **代码执行** | 纯索引/搜索——无解释器,无测试运行 | | **代码修改** | 只读搜索——不写入或编辑文件 | | **实时文件监控** | 无守护进程模式——需手动再次调用 `learn` 更新索引 | | **跨仓库搜索** | 每个索引对应单个代码库——无法同时搜索多个项目 | | **查找所有引用** | 查找定义而非引用(不回答“谁调用了这个函数?”) | | **类型推断 / LSP** | 无语言服务器——无跳转到定义、无自动补全 | | **Git 历史分析** | 仅索引当前状态——无提交历史或 blame 信息 | | **正则/精确搜索** | 仅语义搜索——如需精确字符串匹配请使用 `grep` 或 `ripgrep` | | **代码指标** | 无复杂度评分、无 linting、无覆盖率数据 | ### 技术约束 | 约束 | 影响 | |------------|--------| | **首次索引较慢** | 约 50 块/秒(~3-4 分钟完成 10K 符号) | | **内存占用** | 嵌入模型占用 500MB-2GB RAM | | **模型下载** | 首次运行从 HuggingFace 下载约 500MB 模型 | | **查询延迟** | 每次搜索约 50-100ms | ## 快速开始 ### 安装 ``` # 克隆仓库 git clone https://github.com/rdondeti/CodeGrok_mcp.git cd CodeGrok_mcp # 选项 1:使用设置脚本(推荐) ./setup.sh # Linux/macOS # 或 .\setup.ps1 # Windows PowerShell # 选项 2:手动安装 python -m venv .venv source .venv/bin/activate # Linux/macOS pip install -e . # 验证安装 codegrok-mcp --help ``` **设置脚本选项:** | 标志 | 描述 | |------|-------------| | `--clean` | 创建新虚拟环境前移除现有环境 | | `--prod` | 仅安装生产依赖 | | `--no-verify` | 跳过验证步骤 | ### 首次索引 集成到您的 AI 工具后(参见下文),请询问您的助手: ``` "Learn my codebase at /path/to/my/project" ``` 然后搜索: ``` "Find how API endpoints are defined" "Where is error handling implemented?" "Show me the database models" ``` ## 🎯 使用场景 ### 使用场景 1:带 AI 的实时编码 **CodeGrok 如何节省 token:** ``` Without CodeGrok: AI tries to read entire codebase → exceeds context window → fails or costs $$ With CodeGrok: AI: "I need to add a new route" ↓ calls get_sources("Express route definition") CodeGrok: Returns routes/api.js:15, routes/auth.js:8 ↓ AI reads only those 2 files Result: 10-100x fewer tokens, faster responses ``` ### 使用场景 2:学习新代码库 ``` Step 1: "Learn my codebase at ~/projects/big-app" Step 2: "Where is the main entry point?" Step 3: "How is authentication implemented?" Step 4: "Find the database connection logic" Step 5: "Show me how API errors are handled" ``` ### 使用场景 3:代码审查辅助 ``` "Find all functions that handle user input" "Where is validation performed?" "Show me error handling patterns" ``` ## 🔌 AI 工具集成 ### Claude Code (CLI) 将 CodeGrok 添加到 Claude Code 的最简单方式: ``` # 添加 MCP 服务器 claude mcp add codegrok-mcp -- codegrok-mcp ``` 或手动添加到设置文件(`~/.claude/settings.json`): ``` { "mcpServers": { "codegrok": { "command": "codegrok-mcp" } } } ``` **在 Claude Code 中使用:** ``` > learn my codebase at ./my-project > find authentication logic > where is the main entry point? ``` ### Claude Desktop 添加到您的 Claude Desktop 配置: | 平台 | 配置文件位置 | |----------|---------------------| | macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` | | Windows | `%APPDATA%\Claude\claude_desktop_config.json` | | Linux | `~/.config/Claude/claude_desktop_config.json` | ``` { "mcpServers": { "codegrok": { "command": "codegrok-mcp", "args": [] } } } ``` 保存后重启 Claude Desktop。 ### Cursor Cursor 通过其扩展系统支持 MCP 服务器: 1. **打开设置** → 扩展 → MCP 2. **添加服务器配置**: ``` { "codegrok": { "command": "codegrok-mcp", "transport": "stdio" } } ``` 或添加到项目中的 `.cursor/mcp.json`: ``` { "servers": { "codegrok": { "command": "codegrok-mcp" } } } ``` ### Windsurf (Codeium) Windsurf 通过 Cascade 支持 MCP: 1. 打开 **Cascade 设置** 2. 导航至 **MCP 服务器** 3. 添加配置: ``` { "codegrok": { "command": "codegrok-mcp", "transport": "stdio" } } ``` ### Cline (VS Code) 在 VS Code 中添加至 Cline 的 MCP 设置: 1. 打开命令面板(`Ctrl+Shift+P` / `Cmd+Shift+P`) 2. 搜索“Cline: 打开 MCP 设置” 3. 添加: ``` { "mcpServers": { "codegrok": { "command": "codegrok-mcp" } } } ``` ### Zed Editor Zed 通过其助手面板支持 MCP。添加到设置: ``` { "assistant": { "mcp_servers": { "codegrok": { "command": "codegrok-mcp" } } } } ``` ### Continue (VS Code/JetBrains) 添加到您的 Continue 配置(`~/.continue/config.json`): ``` { "mcpServers": [ { "name": "codegrok", "command": "codegrok-mcp" } ] } ``` ### 通用 MCP 客户端 对于任何兼容 MCP 的客户端,使用 stdio传输: ``` # 运行命令 codegrok-mcp # 传输 stdio (stdin/stdout) # 协议 Model Context Protocol (MCP) ``` ## MCP 工具参考 CodeGrok 提供 **4 种工具**供 AI 助手使用: | 工具 | 描述 | 关键参数 | |------|-------------|----------------| | `learn` | 索引代码库(智能模式) | `path`(必需)、`mode`(auto/full/load_only)、`file_extensions`、`embedding_model` | | `get_sources` | 语义代码搜索 | `question`(必需)、`n_results`(1-50,默认 10)、`language`、`symbol_type` | | `get_stats` | 获取索引统计 | 无参数 | | `list_supported_languages` | 列出支持的语言 | 无参数 | **Learn 模式:** - `auto`(默认):智能检测——存在则增量重新索引,否则全量索引 - `full`:强制完全重新索引(销毁现有索引) - `load_only`:仅加载现有索引,不进行任何索引 ### 工具示例 #### 索引代码库 ``` { "tool": "learn", "arguments": { "path": "/home/user/my-project", "mode": "auto" } } ``` **响应:** ``` { "success": true, "message": "Indexed 150 files with 1,247 symbols", "stats": { "total_files": 150, "total_symbols": 1247, "total_chunks": 2834, "indexing_time": 12.5 } } ``` #### 搜索代码 ``` { "tool": "get_sources", "arguments": { "question": "How is user authentication implemented?", "n_results": 5 } } ``` **响应:** ``` { "sources": [ { "file": "src/auth/middleware.py", "symbol": "authenticate_request", "type": "function", "line": 45, "content": "def authenticate_request(request):\n ...", "score": 0.89 } ] } ``` #### 增量更新(使用 learn 的自动模式) ``` { "tool": "learn", "arguments": { "path": "/home/user/my-project", "mode": "auto" } } ``` **响应(当索引存在时):** ``` { "success": true, "mode_used": "incremental", "files_added": 2, "files_modified": 5, "files_deleted": 1 } ``` ## 支持的语言 | 语言 | 扩展名 | 解析器 | |----------|------------|--------| | **Python** | `.py`、`.pyi`、`.pyw` | tree-sitter-python | | **JavaScript** | `.js`、`.jsx`、`.mjs`、`.cjs` | tree-sitter-javascript | | **TypeScript** | `.ts`、`.tsx`、`.mts`、`.cts` | tree-sitter-typescript | | **C** | `.c`、`.h` | tree-sitter-c | | **C++** | `.cpp`、`.cc`、`.cxx`、`.hpp`、`.hh`、`.hxx` | tree-sitter-cpp | | **Go** | `.go` | tree-sitter-go | | **Java** | `.java` | tree-sitter-java | | **Kotlin** | `.kt`、`.kts` | tree-sitter-kotlin | | **Bash** | `.sh`、`.bash`、`.zsh` | tree-sitter-bash | **总计:9 种语言,28 种扩展名** ## 工作原理 ### 架构 ``` ┌─────────────────────────────────────────────────────────────┐ │ MCP Client │ │ (Claude, Cursor, Cline, etc.) │ └─────────────────────────┬───────────────────────────────────┘ │ MCP Protocol (stdio) ▼ ┌─────────────────────────────────────────────────────────────┐ │ CodeGrok MCP Server │ ├─────────────────────────────────────────────────────────────┤ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │ │ │ Parsers │ │ Embeddings │ │ Vector Storage │ │ │ │ (Tree-sitter)│ │ (Sentence │ │ (ChromaDB) │ │ │ │ │ │ Transformers)│ │ │ │ │ └─────────────┘ └─────────────┘ └─────────────────────┘ │ └─────────────────────────────────────────────────────────────┘ ``` ### 索引流水线 ``` Source Files → Tree-sitter Parser → Symbol Extraction → Code Chunks → Embeddings → ChromaDB Storage ``` 1. **解析**:Tree-sitter 提取函数、类、方法及其签名 2. **分块**:代码被拆分为带有上下文(文档字符串、导入、调用)的语义块 3. **嵌入**:Sentence-transformers 创建向量嵌入 4. **存储**:ChromaDB 在本地 `.codegrok/` 文件夹中持久化向量 ### 搜索流水线 ``` Query → Embedding → Vector Similarity → Ranked Results ``` 1. **嵌入查询**:将自然语言转换为向量 2. **搜索**:在 ChromaDB 中查找相似向量 3. **返回**:返回前 k 个结果,包含文件路径、行号和代码片段 ### 存储 所有数据本地存储在您的项目中: ``` your-project/ └── .codegrok/ ├── chroma/ # Vector database └── metadata.json # Index metadata (stats, file mtimes) ``` ## 配置 ### 环境变量 | 变量 | 描述 | 默认值 | |----------|-------------|---------| | `CODEGROK_EMBEDDING_MODEL` | 使用的嵌入模型 | `nomic-embed-code` | | `CODEGROK_DEVICE` | 计算设备(cpu/cuda/mps) | 自动检测 | ### 嵌入模型 | 模型 | 大小 | 适用场景 | |-------|------|----------| | `coderankembed` | 768d / 137M | **代码(默认,推荐)** - 使用 `nomic-ai/CodeRankEmbed` | 默认模型(`nomic-ai/CodeRankEmbed`)针对代码检索进行了优化: - 768 维嵌入 - 最大序列长度 8192 - 在 CodeSearchNet 基准测试上达到最先进性能 ### 安全提示:`trust_remote_code` 默认嵌入模型(`nomic-ai/CodeRankEmbed`)在通过 SentenceTransformers 加载时需要 `trust_remote_code=True`。此标志允许执行与模型捆绑的自定义 Python 代码。 **原因:** - 该模型使用自定义的 Nomic BERT 架构,不属于标准 HuggingFace 模型库 - 自定义文件:`modeling_hf_nomic_bert.py`(模型架构)、`configuration_hf_nomic_bert.py`(配置) **安全审计:** 自定义代码已通过审查,包含: - 标准 PyTorch 神经网络定义 - 无 `exec()`、`eval()` 或动态代码执行 - 无子进程或 Shell 命令 - 无网络请求(除了 HuggingFace 的标准模型下载 API) - 仅导入受信任的库(torch、transformers、einops、safetensors) **最大安全性:** - 自行审查模型代码:[nomic-ai/CodeRankEmbed on HuggingFace](https://huggingface.co/nomic-ai/CodeRankEmbed/tree/main) - 在生产部署中固定到特定模型版本 - 考虑使用 Microsoft CodeBERT(`microsoft/codebert-base`)作为替代方案,它不需要 `trust_remote_code`(但可能存在质量差异) ## 开发 ### 设置 ``` # 克隆 git clone https://github.com/rdondeti/CodeGrok_mcp.git cd CodeGrok_mcp # 运行设置脚本 ./setup.sh # Linux/macOS (includes dev dependencies) .\setup.ps1 # Windows PowerShell # 如需干净重装: ./setup.sh --clean ``` ### 测试 ``` # 运行所有测试 pytest # 带覆盖率运行 pytest --cov=src/codegrok_mcp --cov-report=term-missing # 运行特定测试类别 pytest tests/unit/ -v # Fast unit tests pytest tests/integration/ -v # Integration tests (uses real embeddings) pytest tests/mcp/ -v # MCP protocol simulation tests ``` ### 代码质量 ``` # 格式化代码 black src/ # 类型检查 mypy src/ # Linting flake8 src/ ``` ## 常见问题与故障排除
服务器无法启动 ``` # 检查安装 pip show codegrok-mcp # 检查 Python 版本(需要 3.10+) python --version # 重新安装 pip install -e . ```
索引速度慢 - 大型代码库(>10K 文件)首次索引耗时更长 - 使用 `learn` 再次索引以实现增量更新(自动模式) - 关闭其他占用资源的应用 - 考虑先索引子目录
搜索返回不相关结果 - 查询时更具体(例如“JWT 令牌验证”而非“认证”) - 如果代码库有显著变更,请重新索引 - 检查要搜索的代码类型是否存在
内存不足 - 索引更小的代码库部分 - 默认 `coderankembed` 模型占用约 500MB-2GB RAM - 关闭其他应用程序
“未加载索引”错误 先使用 `learn` 工具: ``` "Learn my codebase at /path/to/project" ```
## 与其他工具的对比 | 功能 | CodeGrok MCP | grep/ripgrep | GitHub 搜索 | Sourcegraph | |---------|--------------|--------------|---------------|-------------| | 语义搜索 | ✅ | ❌ | 部分 | ✅ | | 本地/私有 | ✅ | ✅ | ❌ | ❌ | | MCP 支持 | ✅ | ❌ | ❌ | ❌ | | 无需 API 密钥 | ✅ | ✅ | ❌ | ❌ | | 多语言 | ✅ | ✅ | ✅ | ✅ | | 理解代码结构 | ✅ | ❌ | 部分 | ✅ | | 离线 | ✅ | ✅ | ❌ | ❌ | ## 贡献 欢迎贡献!请: 1. 叉取仓库 2. 创建功能分支(`git checkout -b feature/amazing`) 3. 进行修改 4. 运行测试(`pytest`) 5. 格式化代码(`black src/`) 6. 提交 Pull Request ### 开发指南 - 遵循 Black 格式(长度 100) - 为所有函数添加类型提示 - 为新功能编写测试 - 更新文档 ## 许可证 MIT 许可证 - 详见 [LICENSE](LICENSE) ## 相关项目 - **[模型上下文协议](https://modelcontextprotocol.io/)** - 支持此集成的协议 - **[Tree-sitter](https://tree-sitter.github.io/tree-sitter/)** - 快速、准确的代码解析 - **[ChromaDB](https://www.trychroma.com/)** - 向量数据库用于嵌入 - **[Sentence Transformers](https://www.sbert.net/)** - 先进嵌入模型 ## 支持 - **问题**:[GitHub Issues](https://github.com/rdondeti/CodeGrok_mcp/issues) - **讨论**:[GitHub Discussions](https://github.com/rdondeti/CodeGrok_mcp/discussions)
**为希望 AI 真正理解其代码的开发人员打造** [⬆ 返回顶部](#codegrok-mcp)
标签:AI助手, Bash, C, C++, CMS安全, Go, IPv6支持, JavaScript, Kotlin, MCP, Python, Ruby工具, SEO: AI编码助手, SEO: 代码智能分析, SEO: 语义代码搜索, Token优化, Tree-sitter, TypeScript, 代码搜索, 代码理解, 代码理解与检索, 代码索引, 增量更新, 多语言支持, 安全插件, 安全测试框架, 并行解析, 开源, 数据擦除, 无后门, 模型上下文协议, 语义嵌入, 语义搜索, 逆向工具