内容
<p align="center">
<img src="https://img.shields.io/badge/MCP-1.0+-blue.svg" alt="MCP 1.0+">
<img src="https://img.shields.io/badge/python-3.10+-blue.svg" alt="Python 3.10+">
<img src="https://img.shields.io/badge/license-MIT-green.svg" alt="MIT License">
<img src="https://img.shields.io/badge/version-0.3.1-orange.svg" alt="Version 0.3.1">
<img src="https://img.shields.io/badge/tools-20-purple.svg" alt="20 MCP Tools">
</p>
<h1 align="center">代码导航</h1>
<p align="center">
<strong>图智能、高效的 AI 助手代码导航</strong>
</p>
<p align="center">
<em>精确阅读、执行流程、影响范围评估、风险评分 — 减少 97% 的 tokens</em>
</p>
---
## 什么是代码导航?
代码导航是一个 **MCP 服务器**,帮助 AI 助手高效地探索代码库。除了基本的搜索和阅读外,它还增加了 **图智能**:影响范围分析、执行流程追踪、风险评分差异和社区检测。
```
┌─────────────────────────────────────────────────────────────┐
│ 没有代码导航 │
├─────────────────────────────────────────────────────────────┤
│ 用户:“修复支付漏洞” │
│ │
│ Claude 阅读: │
│ • payments.py (500 行) → 7,500 tokens │
│ • billing.py (300 行) → 4,500 tokens │
│ • models/order.py (200 行) → 3,000 tokens │
│ ───────────────────────────────────────────── │
│ 总计: 15,000 tokens │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ 使用代码导航 │
├─────────────────────────────────────────────────────────────┤
│ 用户:“修复支付漏洞” │
│ │
│ 1. codegraph_get_minimal_context → 100 tokens │
│ 2. codegraph_search("payment") → 100 tokens │
│ 3. codegraph_read(payments.py, 45, 89) → 400 tokens │
│ 4. codegraph_blast_radius → 100 tokens │
│ ───────────────────────────────────────────── │
│ 总计: 700 tokens │
│ │
│ 节省:95% 的 tokens + 影响分析! │
└─────────────────────────────────────────────────────────────┘
```
---
## 快速开始
### 1. 安装
```bash
pip install codegraph-nav[mcp] # MCP 服务器 + 核心
pip install codegraph-nav[all] # 所有功能(tree-sitter, networkx, ast-grep)
```
### 2. 配置 Claude 代码(命令行)
将以下内容添加到 `~/.claude/mcp.json`:
```json
{
"mcpServers": {
"codegraph-nav": {
"command": "codegraph-nav-mcp"
}
}
}
```
### 3. 配置 Claude 桌面版
将以下内容添加到 `~/Library/Application Support/Claude/claude_desktop_config.json`(macOS)或 `%APPDATA%\Claude\claude_desktop_config.json`(Windows):
```json
{
"mcpServers": {
"codegraph-nav": {
"command": "codegraph-nav-mcp"
}
}
}
```
### 4. 使用它
在 Claude 中,直接要求探索您的代码库:
```
"扫描该项目并找到支付功能"
"如果我更改 auth.py,影响范围是什么?"
"给我展示该代码库的架构"
```
Claude 将自动使用代码导航的 20 个工具来高效探索。
---
## 可用工具
### 核心导航
| 工具 | 目的 | 何时使用 |
|------|---------|-------------|
| `codegraph_get_minimal_context` | ~100 token 项目定位 | **始终首先使用** |
| `codegraph_scan` | 索引代码库到 `.codegraph.json` | 首次使用某个项目 |
| `codegraph_search` | 按名称/模式查找符号 | 查找函数/类 |
| `codegraph_read` | 读取特定行范围 | 找到符号位置后 |
| `codegraph_stats` | 代码库大小概览 | 了解项目规模 |
| `codegraph_get_hubs` | 中央文件,或 `scope="symbol"` 用于 PageRank 符号中心 | 架构分析 |
| `codegraph_get_context` | PageRank 排名、预算限制的查询上下文 | "我应该阅读什么来理解 X?" |
| `codegraph_get_structure` | 文件符号大纲 | 在阅读文件之前 |
| `codegraph_get_dependencies` | 导入/导出图 | 了解耦合 |
| `codegraph_test_gaps` | 查找未测试的符号 | 更改前/后 |
### 图智能
| 工具 | 目的 | 何时使用 |
|------|---------|-------------|
| `codegraph_graph_build` | 构建图数据库(`.codegraph.db`) | 进行大量图分析之前 |
| `codegraph_blast_radius` | 影响分析(递归 CTE) | "如果我更改此内容,会发生什么?" |
| `codegraph_list_flows` | 执行流程 + 关键性 | 了解调用链 |
| `codegraph_detect_changes` | 风险评分的 git 差异 | 代码审查/PR 分析 |
| `codegraph_search_graph` | FTS5 + 模糊 + RRF 搜索 | 按概念搜索,而不仅仅是名称 |
### 架构与领域
| 工具 | 目的 | 何时使用 |
|------|---------|-------------|
| `codegraph_list_communities` | 代码社区 + 内聚性 | 架构分组 |
| `codegraph_get_community` | 社区详情 + 成员 | 探索社区 |
| `codegraph_get_architecture_overview` | 架构总结 | 高级结构 |
| `codegraph_list_routes` | HTTP 路由(15+ 框架) | API/路由探索 |
| `codegraph_list_schemas` | ORM 模式(8+ ORMs) | 数据模型探索 |
---
## 工作原理
```mermaid
flowchart TB
subgraph SCAN["步骤 1: 扫描"]
A[(代码库)] --> B[codegraph_scan]
B --> C[.codegraph.json]
end
subgraph NAVIGATE["步骤 2: 导航"]
D[codegraph_search] --> E[file:line locations]
E --> F[codegraph_read]
F --> G[仅需的代码]
end
subgraph GRAPH["步骤 3: 分析"]
C --> H[codegraph_graph_build]
H --> I[.codegraph.db]
I --> J[影响范围 / 流程 / 风险]
end
C --> D
```
1. **扫描一次** - 创建包含所有索引符号的 `.codegraph.json`
2. **外科手术式搜索和阅读** - 查找符号并仅加载所需行
3. **图分析** - 构建 `.codegraph.db` 进行影响范围、流程和风险评分
---
## 示例会话
```
1. codegraph_get_minimal_context(path="/project", task="fix auth bug")
→ 项目:142 个文件 · 1847 个符号 · py,js
→ 中心:config.py(8←), models.py(5←)
→ 建议:codegraph_search → codegraph_read → codegraph_get_dependencies
2. codegraph_search(query="authenticate")
→ src/auth.py:L10-30 [fn] authenticate
3. codegraph_read(file_path="src/auth.py", start_line=10, end_line=30)
→ 仅 20 行(~200 tokens)
4. codegraph_blast_radius(path="/project", changed_files=["src/auth.py"])
→ 影响范围(auth.py):12 个节点 · 5 个文件受影响
5. codegraph_detect_changes(path="/project")
→ 风险:0.78 高 | 3 个文件 · 8 个符号更改
```
---
## 详细级别
所有工具都接受 `detail_level` 参数:
- **`minimal`** (默认)- 紧凑、高效的输出
- **`standard`** - 添加签名、语言分解、双向计数
- **`verbose`** - 添加文档字符串、依赖链、每个文件的详细信息
---
## 工作流提示
5 个内置提示,强制执行 token 纪律:
| 提示 | 用例 |
|--------|----------|
| `investigate_bug` | 漏洞调查:定位、搜索、阅读、依赖关系 |
| `add_feature` | 功能实现:定位、搜索类似、结构、阅读 |
| `review_changes` | 代码审查:定位、测试差距、搜索更改、阅读 |
| `understand_architecture` | 架构分析:定位、中心、依赖关系、结构 |
| `onboard_project` | 项目上线:定位、统计、中心、结构 |
每个提示都以 `codegraph_get_minimal_context` 开头,默认为 `detail_level="minimal"`。
---
## 支持的语言
| 语言 | 分析类型 | 符号 | 父节点 | 文档注释 | 调用(依赖) | 导入 | 质量 |
|----------|---------------|:------:|:-------:|:------------:|:------------:|:-------:|---------|
| Python | 完整 AST(标准库) | ✅ (+枚举、常量、嵌套函数) | ✅ | ✅ 文档字符串 | ✅ | ✅ 解析 | ⭐⭐⭐⭐⭐ |
| JavaScript | AST(tree-sitter)* | ✅ | ✅ | — | ✅ | ✅ 解析 | ⭐⭐⭐⭐⭐ |
| TypeScript | AST(tree-sitter)* | ✅ (+接口、枚举、类型) | ✅ | — | ✅ | ✅ 解析 | ⭐⭐⭐⭐⭐ |
| Ruby | AST(tree-sitter)* | ✅ | ✅ | ✅ `#` | ✅ | ✅ `require` | ⭐⭐⭐⭐⭐ |
| Go | AST(tree-sitter)* | ✅ (+结构体、接口) | ✅ | ✅ `//` | ✅ | ✅ 解析 | ⭐⭐⭐⭐⭐ |
| Rust | AST(tree-sitter)* | ✅ (+结构体、特征、枚举) | ✅ | ✅ `///` | ✅ (+宏) | ✅ `use` | ⭐⭐⭐⭐⭐ |
| Dart / Flutter | AST(tree-sitter)** | ✅ (+混入、扩展) | ✅ | ✅ `///` | ✅ | ✅ 解析 | ⭐⭐⭐⭐⭐ |
| Java | AST(ast-grep)† / 正则表达式 | ✅ | — | — | — | — | ⭐⭐⭐⭐ `[fast]` / ⭐⭐⭐ 正则表达式 |
| C/C++ | AST(ast-grep)† / 正则表达式 | ✅ | — | — | — | — | ⭐⭐⭐⭐ `[fast]` / ⭐⭐⭐ 正则表达式 |
| PHP | AST(ast-grep)† / 正则表达式 | ✅ | — | — | — | — | ⭐⭐⭐⭐ `[fast]` / ⭐⭐⭐ 正则表达式 |
*安装 tree-sitter 支持:`pip install codegraph-nav[ast]`
所有 tree-sitter 分析器在未安装 tree-sitter 时都降级为正则表达式。
†Java/C/C++/PHP 使用 [ast-grep](https://ast-grep.github.io/) 进行真正的 AST 解析
(比正则表达式有更干净的符号边界和签名),当安装 `[fast]` 额外功能时
(`pip install codegraph-nav[fast]`);如果不安装,则降级为正则表达式分析器。两个层级目前都只提取符号,
而不包括父节点链接、调用依赖、文档注释和导入。
tree-sitter 层(Python/JS/TS/Ruby/Go/Rust/Dart)提取具有
父节点上下文的符号、跨文件调用依赖(deps)和导入说明符
解析为内部存储库文件 - 图构建器将其转换为 `CALLS` 和
`IMPORTS_FROM` 边。Go/Rust/Ruby/Dart 还捕获前导文档注释。
**Dart/Flutter 作为其自己的额外功能发布:`pip install codegraph-nav[dart]`。该
语法(`tree-sitter-dart`)为 Linux/macOS/Windows 提供预编译的轮子,
— 不需要 C 编译器。 如果没有它,Dart 降级为正则表达式分析器
(类、混入、枚举、扩展、顶级函数)。Flutter 不需要
单独的语法;小部件是普通的 Dart 类。
---
## 微元数据格式
扫描输出使用紧凑的 ASCII 树和内联元数据:
```
my-project/
├── src/
│ ├── api/
│ │ ├── client.py [C:APIClient M:get,post] (5←)
│ │ └── routes.py [F:handle,validate] (3←)
│ └── core/
│ └── config.py [C:Config M:load] (Hub:8←)
└── tests/
└── test_api.py [F:test_client]
═══ 总结 ═══
28 个文件 · 142 个符号 · 12 个中心
```
每个文件显示:类(C:)、函数(F:)、方法(M:)和导入者计数(N←)。
---
## 命令行用法
```bash
# 生成代码地图
codegraph-nav scan /path/to/project
cgn scan . # 短别名
# 搜索符号
cgn search "process_payment"
cgn search -t class -o table
# 读取特定行
cgn read src/payments.py 45-89
cgn read src/payments.py 45-89 -c 3 # 带上下文
# 获取代码库统计信息
cgn stats
# 增量更新(仅更改的文件)
cgn scan --incremental .
# 从代码地图构建图数据库(.codegraph.db)
cgn graph build . # 增量(跳过未更改的文件)
cgn graph build . --full # 完整重建
cgn graph stats . # 节点/边计数(添加 -o json)
# 监视更改;还会在每次更新后重建图
cgn watch . --graph
# 导出为 Markdown
cgn export -f markdown -o docs/codebase.md
```
图构建还计算符号级 **PageRank** (使用 `[graph]`
额外功能:`pip install codegraph-nav[graph]`),通过 `codegraph_get_hubs`
(`scope="symbol"`)和 `codegraph_get_context` MCP 工具显示。
---
## Python API
```python
from codegraph_nav import CodeNavigator, CodeSearcher, LineReader
# 扫描
navigator = CodeNavigator("/path/to/project")
code_map = navigator.scan()
# 搜索
searcher = CodeSearcher(".codegraph.json")
results = searcher.search_symbol("payment", symbol_type="function")
# 外科手术式阅读
reader = LineReader(root_path="/path/to/project")
content = reader.read_lines("src/pay.py", 45, 89)
```
### 图 API
```python
from codegraph_nav.graph import GraphStore, GraphBuilder, get_blast_radius, trace_flows
# 从代码地图构建图
store = GraphStore(".codegraph.db")
builder = GraphBuilder(store)
stats = builder.build_from_code_map(code_map)
# 影响范围
impact = get_blast_radius(store, changed_files=["src/auth.py"])
print(f"{impact['impacted_nodes']} nodes, {len(impact['impacted_files'])} files affected")
# 执行流程
flows = trace_flows(store)
for f in flows[:5]:
print(f"{f['name']} crit:{f['criticality']:.2f} depth:{f['depth']}")
store.close()
```
### 领域智能 API
```python
from codegraph_nav.domain import detect_routes, detect_schemas, infer_project_tags
# 检测路由(FastAPI、Express、Django、Gin 等)
routes = detect_routes(code_map, root_path="/path/to/project")
# 检测 ORM 模式(SQLAlchemy、Django、Prisma 等)
schemas = detect_schemas(code_map, root_path="/path/to/project")
# 推断领域标签(auth、db、cache、api 等)
tags = infer_project_tags(code_map)
```
---
## 可选依赖
| 额外功能 | 添加内容 |
|-------|-------------|
| `[mcp]` | MCP 服务器(FastMCP) |
| `[ast]` | Tree-sitter 分析器(JS/TS/Ruby/Go/Rust) |
| `[graph]` | PageRank 中心检测(networkx) |
| `[fast]` | ast-grep 高性能解析 |
| `[all]` | 以上所有 |
| `[dev]` | pytest、mypy、black、ruff、build、twine |
---
## 性能
在现实世界开源项目上测试:
| 项目 | 文件 | 符号 | 地图大小 | 地图时间 |
|---------|-------|---------|----------|----------|
| Flask | 142 | 1,847 | 89 KB | 0.8s |
| Django | 2,156 | 28,493 | 1.2 MB | 8.2s |
| requests | 47 | 412 | 23 KB | 0.3s |
**Token 节省:
- 小型项目(50-100 个文件):85-90% 减少
- 中型项目(100-500 个文件):92-96% 减少
- 大型项目(500+ 文件):97-99% 减少
---
## 开发
```bash
git clone https://github.com/efrenbl/codegraph-nav.git
cd codegraph-nav
python3 -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
python3 -m pytest tests/ -v
```
---
## 要求
- Python 3.10+
- MCP SDK 1.0+(仅限 MCP 服务器)
---
## 许可证
MIT 许可证 - 参见 [LICENSE](LICENSE) 了解详情。
---
<p align="center">
<strong>停止烧 Token 读取整个文件。</strong><br>
<em>扫描一次、搜索即时、外科手术式阅读、影响分析。</em>
</p>
MCP 配置
以下是此 MCP Server 的配置信息,可直接复制到 Cursor 或其他 MCP 客户端中使用。
mcp.json
连接信息
猜你喜欢
暂无推荐服务器