内容
# 代码索引
源代码(.cs / .h / .cpp)索引并为自然语言查询返回相关代码块的**本地MCP服务器**。
与支持MCP的AI客户端(如VS Code,Visual Studio 2022,Claude Desktop等)联动。
## 特点
- **项目过滤** — 同时索引多个项目,并在搜索时限制特定项目的范围
- **Qdrant向量DB(https://qdrant.tech/)自动安装和管理** — 首次运行时自动下载Qdrant二进制文件并作为子进程管理
- **GPU自动检测和CUDA轮自动安装** — 检测到NVIDIA GPU时自动安装合适的PyTorch CUDA版本
- **基于SHA-256的增量索引** — 仅重新处理更改的文件,即使在大规模代码库中也能快速更新
- **content_hash嵌入缓存** — 将相同代码块的嵌入向量缓存到SQLite中,以加速重新索引
- **Tree-sitter AST解析** — 将C++/C/C#源代码分析为AST,按函数、类、方法、命名空间级别进行精细化
- **稠密(HNSW)+ BM25混合搜索 + RRF分数结合** — 结合语义向量搜索和基于关键字的BM25,以提高准确性
- **排名重新排序** — 使用交叉编码器模型重新排序搜索结果,以提高准确性(`use_reranker: true`)
- **MCP服务器支持** - 支持stdio / HTTP(streamable-http)两种传输方式
---
## 要求
- Python 3.11+
- 推荐使用NVIDIA GPU(可以运行在CPU上,但速度较慢)
- 使用NVIDIA GPU时,需要安装CUDA 11.8+或12.x驱动程序(https://developer.nvidia.com/cuda-downloads)
---
## 安装和MCP服务器编辑器联动
1. **克隆和安装** — 克隆仓库并进行Python打包
```powershell
git clone https://github.com/ChoiIngon/CodeIndex.git
cd CodeIndex
pip install -e .
```
- `pip install -e .`将`code_index`命令注册到系统中。之后,可以在任何目录中使用`python -m code_index`或`code_index`运行。
- **具有依赖关系的模块将在首次运行时自动安装。** 如果检测到GPU,将自动选择合适的PyTorch版本。
- **注意**:在GPU环境中,将自动安装与CUDA 11.8+或12.x匹配的PyTorch稳定版本。如果找不到GPU,则会以CPU版本运行。
2. **个性化设置** — 在`config/settings.json`中添加每个项目的索引设置(详见[设置](#设置))
复制`config/settings.json.template`并修改为`config/settings.json`使用
**2-1. 索引目标项目路径设置**
```json
{
"indexer": {
"GameClient": {
"source_paths": ["C:/MyProject/Client/Assets"], // 推荐使用绝对路径
"extensions": [".cs"]
},
"GameServer": {
"source_paths": ["C:/MyProject/Server/src1"],
"extensions": [".cpp", ".h", ".c"]
}
}
}
```
**2-2. 索引数据存储位置设置**
```json
{
"vector_store": {
"data_dir": "C:/MyProject/CodeIndex/data"
}
}
```
3. **MCP服务器运行和编辑器联动**
**3-1. HTTP模式** (推荐)
首先运行MCP服务器,然后在每个编辑器中注册URL。
```powershell
python -m code_index --http-port 6380
```
**VS Code / Visual Studio 2022** — mcp.json
```json
{
"servers": {
"CodeIndex": {
"type": "http",
"url": "http://127.0.0.1:6380/mcp"
}
}
}
```
**Claude Desktop** — claude_desktop_config.json
```json
{
"mcpServers": {
"CodeIndex": {
"type": "http",
"url": "http://127.0.0.1:6380/mcp"
}
}
}
```
**3-2. stdio模式** (不推荐)
在stdio模式下,不需要单独运行MCP服务器进程,编辑器将直接启动进程。
> 大型项目可能加载时间较长,编辑器可能创建子进程超时。
**VS Code / Visual Studio 2022** — mcp.json
```json
{
"servers": {
"CodeIndex": {
"type": "stdio",
"command": "python",
"args": [ "-m", "code_index" ],
"env": {
"PYTHONPATH": "E:\\work\\CodeIndex"
}
}
}
}
```
**Claude Desktop** — claude_desktop_config.json
```json
{
"mcpServers": {
"CodeIndex": {
"command": "python",
"args": ["-m", "code_index"],
"cwd": "E:/work/CodeIndex"
}
}
}
```
**3-3. mcp设置文件路径**
| 编辑器 | 优先级 | 路径 | 范围 |
|----------|----------|------|------|
| VSCode| 1 | <工作区文件夹>/.vscode/mcp.json | 工作区级别 |
| | 2 | %USERPROFILE%/.vscode/mcp.json | 全局用户 |
| Visual Studio 2022| 1 | <解决方案文件夹>/.vs/mcp.json | 解决方案级别(仅限VS) |
| | 2 | <解决方案文件夹>/.vscode/mcp.json | 解决方案级别(可与VS Code共享) |
| | 3 | %USERPROFILE%/.mcp.json | 全局用户 |
| Claude Desktop | 1 | %APPDATA%\Claude\claude_desktop_config.json | 全局用户 |
> 注意:Claude Desktop仅支持单个全局设置文件,不支持工作区/项目级别的单独路径。
---
## 设置
在`config/settings.json`文件中管理每个项目的索引设置。
```json
{
"indexer": {
"chunk_min_lines": 5,
"chunk_max_lines": 80,
"chunk_overlap_lines": 10,
"chunk_workers": 0,
"GameServer": {
"source_paths": ["C:/MyProject/Server"],
"extensions": [".cpp", ".h", ".c"],
"exclude_patterns": ["*/build/*", "*/.git/*", "*/Utility/*"]
},
"GameClient": {
"source_paths": ["C:/MyProject/Client/Assets"],
"extensions": [".cs"],
"exclude_patterns": ["*/Library/*", "*/Packages/*"]
}
},
"models": {
"cache_dir": "",
"embed": "BAAI/bge-m3",
"rerank": "cross-encoder/ms-marco-MiniLM-L-12-v2"
},
"embedding": {
"vector_size": 1024,
"batch_size": 64,
"n_gpu_layers": -1
},
"vector_store": {
"mode": "server",
"host": "localhost",
"port": 6333,
"data_dir": "./data"
},
"search": {
"top_k": 20,
"rerank_top_k": 8,
"min_score": 0.0,
"alpha": 0.5,
"use_reranker": false
},
"debug": false
}
```
### indexer
**结构**: `"indexer": { "chunk_设置...", "ProjectName": { ... }, "AnotherProject": { ... } }`
#### 共享分块设置(适用于所有项目)
| 项目 | 描述 | 默认值 |
|---|---|---|
| `chunk_min_lines` | 小于此值的行数的符号将从块中排除 | `5` |
| `chunk_max_lines` | 块的最大行数。超过时,将保持重叠并分割 | `80` |
| `chunk_overlap_lines` | 分割块之间的重叠行数。维护上下文连续性 | `10` |
| `chunk_workers` | 块处理并行进程数。`0` = 自动使用一半CPU核心数 | `0` |
#### 项目单独设置
每个项目可以具有独立的设置:
| 项目 | 描述 | 默认值 |
|---|---|---|
| `source_paths` | 该项目的索引源路径列表。绝对/相对路径 | `[]` |
| `extensions` | 该项目的索引目标扩展名列表 | `[".cpp", ".h", ".c", ".cs"]` |
| `exclude_patterns` | 该项目的排除路径模式(glob) | `["*/build/*", "*/.git/*", "*/generated/*"]` |
**示例**:
- `GameServer`: 仅C++文件,排除Utility文件夹
- `Middleware`: 仅C#文件,排除Unity相关文件夹
**项目过滤使用案例**:
- 数据包兼容性验证: GameServer的序列化与Middleware的反序列化比较
- 语言编码模式分析: C++ vs C# 实现方式比较
- 项目间API一致性检查: 共同模块的接口实现验证
### models
| 项目 | 描述 | 默认值 |
|---|---|---|
| `cache_dir` | 模型下载缓存路径。留空则使用项目根目录的`.cache/` | `""` |
| `embed` | 嵌入模型HuggingFace ID。更改时需要同时更改`vector_size`并重新索引 | `"BAAI/bge-m3"` |
| `rerank` | 重新排序模型HuggingFace ID。仅在`search.use_reranker: true`时加载 | `"cross-encoder/ms-marco-MiniLM-L-12-v2"` |
### embedding
| 项目 | 描述 | 默认值 |
|---|---|---|
| `vector_size` | 嵌入向量维度。必须与使用的`models.embed`模型输出维度一致 | `1024` |
| `batch_size` | 嵌入批次大小。根据GPU VRAM调整(RTX 3060: 64, RTX 4090: 128+) | `64` |
| `n_gpu_layers` | (预留)GPU层数。目前未使用 | `-1` |
### vector_store
| 项目 | 描述 | 默认值 |
|---|---|---|
| `mode` | `"server"`: 使用单独的Qdrant进程(推荐),`"embedded"`: 在Python进程内嵌入模式 | `"server"` |
| `host` | Qdrant服务器主机。在`mode: "server"`时使用 | `"localhost"` |
| `port` | Qdrant HTTP端口。gRPC自动使用`port + 1` | `6333` |
| `data_dir` | 数据存储根路径。在此路径下创建`qdrant/`目录,并存储`metadata.db`和`embed_cache.db` | `"./data"` 或 `"C:\data` |
> **服务器模式**: 首次运行时,`.cache/qdrant/qdrant.exe`将从GitHub Releases自动下载并作为后台进程启动。 code_index退出时也会终止。
### search
| 项目 | 描述 | 默认值 |
|---|---|---|
| `top_k` | 搜索结果返回数量。在使用重新排序时,将选择此数量的候选项,然后压缩为`rerank_top_k` | `20` |
| `rerank_top_k` | 重新排序的最终返回数量。仅在`use_reranker: true`时应用 | `8` |
| `min_score` | 最低分数过滤器。低于此值的结果将被排除(`0.0` = 无过滤) | `0.0` |
| `alpha` | Dense/BM25权重。`1.0` = 仅Dense,`0.0` = 仅BM25,`0.5` = 均衡混合 | `0.5` |
| `use_reranker` | 为`true`时,使用`models.rerank`模型重新排序结果,以提高准确性。速度略有下降 | `false` |
### 调试
| 项目 | 描述 | 默认值 |
|---|---|---|
| `debug` | 为`true`时,将MCP请求/响应记录到`log.txt` | `false` |
---
## 运行
* 仅执行索引
```powershell
python -m code_index --index-only
```
* 以stdio模式运行MCP服务器(单个编辑器)
```powershell
python -m code_index
```
* 以HTTP模式运行MCP服务器(多个编辑器同时使用)
```powershell
python -m code_index --http-port 6380
```
* 查看索引状态
```powershell
python -m code_index --status
```
* CLI搜索(无需MCP直接查询)
```powershell
# 自然语言搜索
python -m code_index --search-code "伤害计算逻辑"
# 过滤选项
python -m code_index --search-code "CalculateDamage" --top-k 10 --language cpp --symbol-type function
# 项目搜索(仅在GameServer项目中搜索)
python -m code_index --search-code "QA_Login serialize" --project "GameServer" --top-k 5
# 项目间比较分析示例
python -m code_index --search-code "QA_Login serialize" --project "GameServer" --top-k 3
python -m code_index --search-code "QA_Login deserialize" --project "Middleware" --top-k 3
# 文件符号列表
python -m code_index --get-file-outline "combat.cpp"
# 通过块ID查询代码
python -m code_index --get-chunk "fc617902-35bc-5155-b9d1-b94837fd181d"
```
---
## MCP工具列表
AI客户端可以调用的工具。
| 工具 | 描述 | 主要参数 |
|---|---|---|
| `search_code` | 通过自然语言/符号名称搜索代码块 | `query`, `top_k`, `language`, `symbol_type`, `project` |
| `get_file_outline` | 返回文件的符号列表(类/函数/方法) | `file_path` |
| `get_chunk` | 通过块ID查询完整代码 | `chunk_id` |
---
## 数据存储位置
| 文件/目录 | 内容 |
|---|---|
| `./data/metadata.db` | 文件/块元数据 + FTS5 BM25索引(SQLite) |
| `./data/embed_cache.db` | content_hash → 嵌入向量缓存(SQLite) |
| `./data/qdrant/` | HNSW向量索引(Qdrant数据) |
| `./.cache/qdrant/qdrant.exe` | 自动下载的Qdrant可执行文件 |
| `./.cache/` | HuggingFace模型缓存(`models.cache_dir`未设置时) |
| `./log.txt` | MCP请求/响应日志(`debug: true`时) |
要完全初始化索引:
```powershell
python -m code_index --remove
python -m code_index --index-only
```
---
## 架构
```
索引管道
源代码 → 文件扫描器(变更检测)→ Tree-sitter解析
→ 分块 → 嵌入(GPU)→ Qdrant + SQLite FTS5
搜索管道
查询 → 查询嵌入
├─ 稠密搜索(HNSW)
└─ BM25搜索(FTS5)
└─ RRF分数结合 → [重新排序(可选)] → 结果返回
```
## 项目结构
```
CodeIndex/
├── code_index/
│ ├── __main__.py # 入口点,CLI选项处理
│ ├── config.py # 加载设置和默认值
│ ├── constants.py # 全局常量和设置值
│ ├── indexer/
│ │ ├── scanner.py # 文件扫描和变更检测
│ │ ├── parser.py # Tree-sitter AST解析
│ │ ├── chunker.py # 符号级别分块
│ │ ├── embedder.py # 嵌入生成
│ │ └── pipeline.py # 索引管道编排
│ ├── options/ # CLI选项处理模块
│ ├── store/
│ │ ├── vector_store.py # Qdrant HNSW向量存储
│ │ ├── metadata_store.py # SQLite元数据 + FTS5
│ │ ├── qdrant_server.py # Qdrant二进制自动下载和服务器管理
│ │ └── cache.py # 嵌入缓存
│ ├── retriever/
│ │ ├── hybrid_search.py # Dense + BM25 + RRF
│ │ └── reranker.py # 重新排序(可选)
│ ├── mcp/
│ │ ├── server.py # FastMCP服务器(工具定义)
│ │ └── debug_logger.py # 请求/响应记录器
│ └── models/
│ └── model_manager.py # HuggingFace模型路径管理
├── config/
│ └── settings.json.template # 设置模板
├── test/
│ ├── run_test.py # 精确度测试运行
│ ├── code_index.py # CodeIndex子进程管理
│ ├── utility.py # 测试工具
│ ├── project1/ # C++和C#测试用例代码
│ ├── project2_1/ # C++和C#测试用例代码
│ ├── project2_2/ # C++和TypeScript测试用例代码
│ └── test_suite/ # 自动化测试集
└── data/ # 索引数据(gitignore)
```
MCP 配置
以下是此 MCP Server 的配置信息,可直接复制到 Cursor 或其他 MCP 客户端中使用。
mcp.json
连接信息
猜你喜欢
暂无推荐服务器