Codii-混合搜索的本地代码库索引
具有混合BM25和矢量搜索功能的本地代码库索引工具。既可作为CLI工具,也可作为MCP(模型上下文协议)服务器。
架构概述
graph TB
subgraph Clients
CLI[Terminal / Shell]
C[Claude Desktop]
end
subgraph Codii
subgraph Entry
CLIM[CLI Module]
SVR[MCP Server]
end
subgraph Tools
T1[index_codebase]
T2[search_code]
T3[clear_index]
T4[get_indexing_status]
end
subgraph Core
CH[AST Chunker]
EM[Embedder]
CE[Cross-Encoder]
MK[Merkle Tree]
end
subgraph Indexers
BM25[BM25 Indexer]
VEC[Vector Indexer]
HYB[Hybrid Search]
end
subgraph Storage
DB[(SQLite DB)]
IDX[(HNSW Index)]
SNAP[(Snapshot)]
MKC[(Merkle Cache)]
end
end
FS[Code Repository]
CLI --> CLIM
C --> SVR
CLIM --> T1
CLIM --> T2
CLIM --> T3
CLIM --> T4
SVR --> T1
SVR --> T2
SVR --> T3
SVR --> T4
T1 --> CH
CH --> EM
EM --> BM25
EM --> VEC
T1 --> MK
T1 --> FS
T2 --> HYB
HYB --> BM25
HYB --> VEC
HYB --> CE
BM25 --> DB
VEC --> IDX
T4 --> SNAP
MK --> MKC
T3 --> DB
T3 --> IDX
T3 --> MKC
T3 --> SNAP数据流
sequenceDiagram
participant C as MCP Client
participant S as Codii Server
participant MK as Merkle Tree
participant CH as AST Chunker
participant EM as Embedder
participant BM25 as BM25 Index
participant VEC as Vector Index
participant FS as File System
Note over C,FS: Indexing Flow
C->>S: index_codebase(path)
S->>FS: Scan directory
S->>MK: Build new Merkle tree
S->>MK: Compare with old tree (if exists)
alt No changes detected
S-->>C: Already indexed, no changes
else Changes detected (incremental)
S-->>C: Indexing started (async)
Note over S,VEC: DELETE phase - removed/modified files
loop For each removed/modified file
S->>BM25: Delete chunks by path
S->>VEC: Remove vectors by chunk IDs
end
Note over S,VEC: ADD phase - added/modified files
loop For each added/modified file
FS->>CH: File content
CH->>CH: Parse AST
CH->>CH: Extract chunks
CH->>BM25: Store chunks
CH->>EM: Get embeddings
EM->>VEC: Store vectors
end
S->>S: Save snapshot
S->>MK: Save Merkle tree
else New codebase (full index)
S-->>C: Indexing started (async)
loop For each file
FS->>CH: File content
CH->>CH: Parse AST
CH->>CH: Extract chunks
CH->>BM25: Store chunks
CH->>EM: Get embeddings
EM->>VEC: Store vectors
end
S->>S: Save snapshot
S->>MK: Save Merkle tree
end
Note over C,FS: Search Flow
C->>S: search_code(query)
S->>BM25: BM25 search (50 candidates)
S->>VEC: Vector search (50 candidates)
S->>S: Reciprocal Rank Fusion
S->>S: RRF reduction (top 20)
S->>S: Cross-Encoder Re-ranking
S-->>C: Search results特性
- 混合搜索:结合BM25(SQLite FTS5)和向量搜索(HNSW)以实现最佳代码检索
- 交叉编码器重新排序:使用交叉编码器对结果进行重新评分,以提高相关性(默认情况下禁用以加快搜索速度;启用
rerank=true) - 智能查询处理:多词查询通过OR匹配、通配符、代码标记化和缩写扩展进行了优化,以提高召回率
- AST感知分块:使用树形图进行语义代码拆分(函数、类等)
- 并行索引:CPU绑定操作使用并行处理-通过ProcessPoolExecutor和多线程HNSW索引构造进行AST分块
- 增量更新:基于Merkle树的更改检测,用于高效的重新索引——只处理添加、修改或删除的文件,而不是重新索引所有内容
- 本地嵌入:用于向量嵌入的CPU可运行的全MiniLM-L6-v2模型
- 多语言支持:Python、JavaScript、TypeScript、Go、Rust、Java、C/C++
- Gitignore支持:自动尊重
.gitignore索引时的模式
先决条件
此套餐取决于 hnswlib 这需要C++编译。您需要安装Python开发头文件:
Ubuntu/Debian:
sudo apt install python3-dev build-essentialFedora/RHEL:
sudo dnf install python3-devel gcc-c++macOS:
xcode-select --installAlpine Linux:
apk add python3-dev gcc g++ musl-dev安装
选项1:pipx或uv工具(推荐)
pipx和uv工具都为CLI工具提供了隔离的环境。用你喜欢的任何一种。
使用pipx:
# Install directly from GitHub
pipx install git+https://github.com/oOSomnus/Codii.git
# Or install from local clone
git clone https://github.com/oOSomnus/Codii.git
cd codii
pipx install .使用uv工具:
# Install directly from GitHub
uv tool install git+https://github.com/oOSomnus/Codii.git
# Or install from local clone
git clone https://github.com/oOSomnus/Codii.git
cd codii
uv tool install .选项2:使用venv的pip
适用于喜欢手动环境管理的用户。
git clone https://github.com/oOSomnus/Codii.git
cd codii
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
pip install -e .选项3:uv pip(开发)
适用于开发人员或已经使用uv并希望进行可编辑安装的用户。
git clone https://github.com/oOSomnus/Codii.git
cd codii
uv pip install -e .卸载
# If installed with pipx
pipx uninstall codii
# If installed with uv tool
uv tool uninstall codii
# If installed with pip/uv pip
pip uninstall codii
# Remove Claude Code integration (if added)
claude mcp remove codii
# Optional: Remove all index data
rm -rf ~/.codii/注: 该软件包提供了两个入口点:
codii-用于直接终端访问的CLI工具codii-server-用于AI助手集成的MCP服务器
卸载软件包时,两者都会被删除。
用法
Codii提供两个接口:
- CLI工具 -直接访问终端进行索引管理和调试
- MCP服务器 -与Claude Code等MCP客户端集成
命令行命令
安装后 codii CLI工具可用:
codii --help # Show all commands
codii status [PATH] # Show indexing status (defaults to cwd)
codii list # List all indexed codebases
codii inspect QUERY [PATH] # Search chunks for debugging
codii build [PATH] [--force] [--daemon] # Build/rebuild index
codii stats [PATH] # Show detailed statistics
codii clear [PATH] [--all] # Clear index for path or allcodii status
使用颜色编码输出显示代码库的索引状态:
codii status # Status of current directory
codii status /path/to/repo # Status of specific pathcodii list
以表格形式列出所有索引代码库:
codii list输出显示每个代码库的路径、状态、文件、块和索引大小。
codii build
使用可选的进度条构建或重建索引:
codii build . # Build index with progress bar (foreground)
codii build . --force # Force full re-index
codii build . --daemon # Build in background (like MCP behavior)前台模式显示一个实时进度条,分为几个阶段:准备、删除、分块、嵌入、索引。
codii inspect
搜索并检查块以进行调试:
codii inspect "function" # Search current directory
codii inspect "database" /path/to/repo # Search specific path
codii inspect "query" --limit 20 # More results
codii inspect "query" --raw # Show full content (no truncation)codii stats
显示详细的统计数据,包括按语言和块类型细分:
codii stats # Stats for current directory
codii stats /path/to/repo # Stats for specific pathcodii clear
清除带有确认提示的索引:
codii clear . # Clear current directory (prompts for confirmation)
codii clear . --force # Skip confirmation prompt
codii clear --all # Clear all indexed codebases运行MCP服务器
MCP服务器为AI助手提供工具:
codii-server # Start MCP server (after installation)如果从源目录运行而不安装:
# Using uv
uv run python -m codii.server
# Using standard Python
python -m codii.serverMCP工具
index_codebase
为语义搜索的代码库建立索引。自动检测文件更改并执行增量更新(仅处理添加/修改/删除的文件)。
{
"path": "/path/to/repo", # Required: Absolute path
"force": false, # Optional: Force full re-index (clears existing index)
"splitter": "ast", # Optional: "ast" or "langchain"
"customExtensions": [".md"], # Optional: Additional extensions
"ignorePatterns": ["tests/"], # Optional: Additional ignore patterns
"workers": 0, # Optional: Parallel chunking workers (0 = auto-detect)
"hnswThreads": 0 # Optional: HNSW index threads (0 = auto-detect)
}行为:
- 新代码库→ 全文索引
- 已编入索引+无文件更改→ 返回“未检测到更改”
- 已索引+检测到文件更改→ 增量更新(仅处理更改的文件)
force=true→ 清除现有索引并执行完全重新索引
平行度:
workers:AST分块的并行进程数。默认值0根据CPU计数自动检测。hnswThreads:HNSW向量索引构造的线程数。默认值0自动检测。
使用 force=true 仅用于从损坏的索引中恢复,或者当您想完全重置索引时。
search_code
搜索索引代码。
{
"path": "/path/to/repo", # Required: Absolute path
"query": "function to sort", # Required: Search query
"limit": 10, # Optional: Max results (default 10, max 50)
"extensionFilter": [".py"], # Optional: Filter by extension
"rerank": false # Optional: Enable cross-encoder re-ranking (default: false)
}get_indexing_status
检查索引进度。
{
"path": "/path/to/repo" # Required: Absolute path
}clear_index
清除索引代码库。
{
"path": "/path/to/repo" # Required: Absolute path
}MCP客户端集成
克劳德代码
安装软件包(通过pipx或pip)后,将MCP服务器添加到Claude Code中:
# Simple method - works after pipx install or pip install
claude mcp add --transport stdio codii -- codii-server对于手动配置,请编辑 ~/.claude/settings.json:
{
"mcpServers": {
"codii": {
"command": "codii-server"
}
}
}注: 使用 codii-server (不是 codii)用于MCP集成。这 codii command是CLI工具。
开发环境 (从源代码运行而不安装):
# Add using uv to run from source directory
claude mcp add --transport stdio codii -- uv run --directory /path/to/codii python -m codii.server或手动:
{
"mcpServers": {
"codii": {
"command": "uv",
"args": ["run", "--directory", "/path/to/codii", "python", "-m", "codii.server"]
}
}
}自定义存储位置
要使用自定义存储位置,请设置 CODII_BASE_DIR 环境变量:
{
"mcpServers": {
"codii": {
"command": "codii",
"env": {
"CODII_BASE_DIR": "/custom/storage/path"
}
}
}
}首次运行说明
首次运行时,嵌入模型(all-MiniLM-L6-v2)将被下载,这可能需要几分钟的时间。
存储
所有索引数据都存储在 ~/.codii/:
~/.codii/
├── indexes/ # SQLite databases per codebase
│ └── /
│ ├── chunks.db # SQLite with FTS5
│ └── vectors.bin # HNSW index
├── snapshots/
│ └── snapshot.json # Index state tracking
└── merkle/
└── .json # Merkle tree cache per codebase有关数据库模式、数据类和文件格式的详细信息,请参见 docs/schemas.md.
配置
创建一个 .codii.yaml 项目根目录中的文件:
# Custom ignore patterns
ignore_patterns:
- "dist/"
- "*.generated.*"
# Custom file extensions
extensions:
- ".kt"
- ".scala"
# Embedding settings
embedding_model: "all-MiniLM-L6-v2"
embedding_batch_size: 32
# Chunk settings
max_chunk_size: 1500
min_chunk_size: 100环境变量
CODII_BASE_DIR:覆盖默认存储目录
支持的语言
| 语言 | AST分块 |
|---|---|
| python✅ | |
| JavaScript | ✅ |
| TypeScript | ✅ |
| 去吧✅ | |
| 锈蚀 | ✅ |
| Java✅ | |
| C✅ | |
| C✅ | |
| 其他 | 基于文本的回退 |
项目结构
codii/
├── src/codii/
│ ├── cli.py # CLI entry point
│ ├── server.py # MCP server entry point
│ ├── tools/ # MCP tool implementations
│ │ ├── index_codebase.py
│ │ ├── search_code.py
│ │ ├── clear_index.py
│ │ └── status.py
│ ├── indexers/ # Search indexers
│ │ ├── bm25_indexer.py # SQLite FTS5
│ │ ├── vector_indexer.py # HNSW
│ │ ├── hybrid_search.py # RRF combination
│ │ └── query_processor.py # Query preprocessing
│ ├── chunkers/ # Code chunking
│ │ ├── ast_chunker.py # tree-sitter based
│ │ └── text_chunker.py # Fallback
│ ├── embedding/ # Embedding utilities
│ │ ├── embedder.py
│ │ └── cross_encoder.py # Re-ranking model
│ ├── evaluation/ # Benchmark evaluation
│ │ └── coir_adapter.py # CoIR benchmark adapter
│ ├── merkle/ # Change detection
│ │ └── tree.py
│ ├── storage/ # Persistence
│ │ ├── database.py
│ │ └── snapshot.py
│ └── utils/ # Utilities
│ ├── config.py
│ └── file_utils.py
├── scripts/
│ └── run_coir_benchmark.py # Benchmark evaluation script
└── pyproject.toml基准评价
Codii包括一个CoIR(代码信息检索)基准适配器,用于评估标准代码检索任务的搜索质量。
安装
# Install with benchmark dependencies
uv pip install -e ".[benchmark]"
# Or with pip
pip install -e ".[benchmark]"运行基准
# Run all CoIR tasks
python scripts/run_coir_benchmark.py --output results/
# Run specific tasks
python scripts/run_coir_benchmark.py --tasks codetrans-dl,stackoverflow-qa
# Quick test with limited samples
python scripts/run_coir_benchmark.py --tasks codetrans-dl --limit 100
# Enable re-ranking for evaluation
python scripts/run_coir_benchmark.py --tasks codetrans-dl
# Clean up datasets after run
python scripts/run_coir_benchmark.py --tasks codetrans-dl --cleanup-datasets可用任务
codetrans-dl-代码翻译(深度学习)codetrans-contest-代码翻译(竞赛)cosqa-代码搜索QAstackoverflow-qa-StackOverflow质量保证apps-APPS数据集codefeedback-mt-代码反馈(多圈)codefeedback-st-代码反馈(单圈)codetranspool-代码翻译池codesearchnet-CodeSearchNetstackoverflow-qa-mr-StackOverflow QA(多轮)
报告的指标
- NDCG@10 -标准化贴现累计收益为10
- MRR@10 -平均倒数排名为10
- Recall@10 -10时召回
- Recall@100 -100时召回
- 地图 -平均精度
发展
# Install dev dependencies (using uv)
uv pip install -e ".[dev]"
# Or using pip
pip install -e ".[dev]"
# Run tests
pytest许可证
麻省理工学院
