ContextTree MCP
ContextTree MCP 🌳
面向 AI 编码助手的深度语义代码搜索——基于 AST 解析与本地嵌入实现,100% 离线运行。
ContextTree MCP 是一个本地 Model Context Protocol 服务器,它让你的 AI 编码助手获得对代码库的结构化理解能力。它融合了两个世界:
tree-sitter 将源文件解析为 AST,并提取逻辑块——函数、方法、带有文档字符串的类签名。
sentence-transformers(
all-MiniLM-L6-v2)把每个逻辑块(连同文件路径、类名、方法名和文档字符串一起)嵌入到本地的 ChromaDB 向量存储中。
最终效果是:你的助手能够按语义而非关键词来查找代码,而且每一次搜索命中都会返回精确的文件路径和行号。
🔒 隐私优先。 一切都在你的机器本地运行:解析、嵌入模型、向量索引。不调用云端、无遥测数据,代码永远不会离开它所在的磁盘。
为什么不用纯文本搜索?
grep 和全文搜索只能做字符串匹配。它们恰恰在开发者最需要帮助的地方失灵:
任务 | 文本搜索 | ContextTree MCP |
“我们在哪里验证 JWT 令牌?” | ❌ 需要猜测精确的关键词 | ✅ 即使代码中完全没有 “validate”,也能匹配 |
查找被改名的函数 | ❌ 重命名后就会失效 | ✅ 文档字符串和上下文仍然保留语义 |
分辨定义 vs. 使用 | ❌ 不做正则表达式技巧就无法实现 | ✅ 在 AST 层面区分声明与调用位置 |
返回精确位置 | ⚠️ 只返回命中行 | ✅ 返回 |
忽略注释/字符串/import 等干扰噪音 | ❌ | ✅ 只对真正的逻辑单元建立索引 |
Related MCP server: Paparats MCP
功能特点
🌲 AST 感知分块 —— 通过 tree-Sitter 对函数、方法和类签名建立索引,而不是任意文本窗口。
🧩 上下文增强逻辑块 —— 每个索引文档都嵌入了它的文件路径、所属类、方法名、文档字符串和函数体,因此像 “支付重试逻辑” 这样的查询会命中正确的方法。
⚡ 增量索引 —— 通过 SHA-256 内容哈希跟踪每个文件;只重新处理变更/新增/删除的文件。
🔍 语义搜索 —— 自然语言查询 → 返回按相关度排序的代码片段及准确的行号范围。
📞 AST 调用关系查询 —— 查找任意符号(函数或类)的真实调用位置,并过滤掉字符串字面量、注释等误报。
🗄️ 持久性本地索引 —— ChromaDB 用于
.chroma/目录,重启后仍然存在,永远不会提交到 Git。🔌 stdio MCP 传输 —— 可以接入 Claude Desktop、OpenCode、Cursor、Cline 或其他与 MCP 兼容的客户端。
技术栈
技术层 | 技术 |
语言 | Python 3.12+ |
协议 | 官方 |
AST 解析 |
|
向量数据库 |
|
嵌入模型 |
|
安装说明
需要 Python 3.12+ 版本。uv 被推荐为快捷、现代的包管理器:
git clone https://github.com/<your-org>/mcp-context-tree.git
cd mcp-context-tree
# Option A — uv (recommended): resolves dependencies from pyproject.toml, locks uv.lock
uv sync
# Option B — classic pip + venv
python -m venv venv && source venv/bin/activate # Windows: venv\Scripts\activate
pip install -r requirements.txt💡 首次运行会下载嵌入模型(约 90 MB)。PyTorch 作为
sentence-transformers的依赖项会被安装进来;CPU 版本就足够了——不需要 GPU。
注册到 MCP 客户端
配置示例(Claude Desktop / 任何支持 stdio 服务器的客户端):
{
"mcpServers": {
"context-tree": {
"command": "<path-to-venv>/bin/python",
"args": ["-m", "context_tree"],
"env": {}
}
}
}(在 Windows 上请使用 <path-to-venv>\Scripts\python.exe。)
暴露给助手的工具
工具 | 签名 | 功能描述 |
|
| 遍历整个项目,根据文件哈希检测发生变更的文件,增量更新 ChromaDB 集合。 |
|
| 对已索引的代码进行自然语言检索,返回带 |
|
| 基于 AST 以查找某个函数或类的真实调用位置 / 实例化位置。 |
典型工作流:
1. index_workspace("D:/projects/my-app")
2. semantic_search("where do we handle payment retries", limit=8)
3. find_ast_usages("PaymentGateway.retry")已支持的语言
语言 | 状态 |
Python | ✅ 发布时已支持 |
TypeScript / TSX | ✅ 发布时已支持 |
JavaScript / JSX | ✅ 发布时已支持 |
Go、Java、Rust… | 🗺️ 路线规划——解析器的注册设计为支持扩展 |
文档
🏛 ARCHITECTURE.md —— 项目布局、ChromaDB 数据 Schema、AST 提取逻辑、增量索引设计。
🇷 🇺 README.ru.md —— 俄语文档。
路线规划
监听模式 —— 文件变更时自动重新建立索引(file watcher)。
通过 tree-sitter 绑定扩展到更多语言。
混合检索(BM25 + 向量的重排序)。
基于调用图的排序算法(“谁在调用它?”)。
发布到 PyPI(
context-tree-mcp)。
贡献力量
欢迎 issue 和 PR。请保持与 ARCHITECTURE.md 的一致性。
License
MIT — 详见 LICENSE。
Available Tools
4 toolsfind_ast_usagesA
AST-based lookup of real call sites / instantiations of a function or class. Filters out string literals, comments, and non-call occurrences.
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No | ||
| symbol_name | Yes | ||
| directory_path | No | . |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations supplied, the description carries the full behavioral burden. It does disclose a valuable filtering behavior: "Filters out string literals, comments, and non-call occurrences." However, it does not mention whether indexing is required, how missing symbols are handled, or any result behavior beyond being AST-based.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single focused sentence that communicates the mechanism, target resource, and exclusion behavior without redundancy. Every clause adds useful information.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The tool is simple enough that the core lookup behavior is adequately described, and an output schema exists. The main gaps are the lack of usage guidance around semantic_search/index_workspace and the absence of practical details about scoping and limit behavior, which leaves the description merely adequate rather than complete.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The schema has 0% description coverage, so the description should compensate. It adds meaning for symbol_name by stating it refers to "a function or class," but it gives no guidance on directory_path or limit, such as how the directory is searched or what the limit controls. This leaves non-obvious semantics undocumented.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description uses a specific verb plus precise resource: "AST-based lookup of real call sites / instantiations of a function or class." It also clarifies what is excluded, which distinguishes it from string or semantic search. This is far more informative than the bare tool name.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The AST-based wording implicitly indicates this is for exact code-structure matching rather than fuzzy search, and the sibling tools suggest a semantic-search alternative. However, the description does not explicitly state when to use this tool versus semantic_search or index_workspace, nor does it mention any exclusions or preconditions.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
go_to_definitionA
Finds the exact definition/declaration location of a symbol (function, method, class, struct, trait, interface) across workspace files.
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No | ||
| symbol_name | Yes | ||
| directory_path | No | . |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden of behavioral disclosure. It adds meaningful context by stating the search is workspace-wide and targets exact definition/declaration locations. Still, it leaves important behavioral details undisclosed, such as whether an index must exist first, how missing or ambiguous symbols are handled, and whether the operation is purely read-only.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single, front-loaded sentence with no filler or redundant restatement of the tool name. It conveys the core action, target, and scope efficiently while listing relevant symbol categories without over-elaborating.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Although an output schema exists and the basic action is clear, the description lacks usage guidance relative to its three sibling tools and fails to explain two of three parameters. With no annotations, this is too thin to fully support an agent in choosing and invoking the tool correctly across realistic scenarios.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, so the description must compensate for bare parameter schemas. It partially clarifies symbol_name by listing supported symbol types, but it says nothing about the format of symbol_name (e.g., fully qualified vs simple name, case sensitivity). The limit and directory_path parameters are completely unaddressed in the description, leaving their semantics to inference from the schema titles and defaults.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description uses a specific verb ('Finds') with a precise resource: the exact definition/declaration location of symbols, listing supported symbol categories and clarifying the search scope ('across workspace files'). This clearly distinguishes it from sibling tools like find_ast_usages or semantic_search, which target usages or semantically similar matches rather than exact definitions.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The phrasing 'exact definition/declaration location' implies the tool is appropriate when precise definitions are needed, rather than usages or semantic matches. However, it does not explicitly state when to prefer this tool over semantic_search or find_ast_usages, nor does it mention any exclusions or prerequisites such as requiring an indexed workspace.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
index_workspaceA
Walks the project, detects changed files by SHA-256 hash, and incrementally updates the persistent local ChromaDB vector store.
| Name | Required | Description | Default |
|---|---|---|---|
| directory_path | No | . |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full burden of behavioral disclosure. It covers that the operation walks the project, uses SHA-256 hashing for change detection, and mutates a persistent local ChromaDB store. This is meaningful behavioral context beyond 'index workspace' though it does not mention potential costs, permissions, or failure modes.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
A single sentence with no filler. It front-loads the core action and packs in the hashing, incrementality, and storage target without becoming verbose.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a tool with one optional parameter and an output schema, the description covers the essential behavior: what is walked, how changes are detected, and what is updated. It is reasonably complete, though it could add an explicit note about running after source changes or before semantic_search.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
There is only one parameter and schema description coverage is 0%, so the description needs to clarify the parameter's meaning. It never mentions directory_path or the default of '.', forcing the agent to rely on the schema's 'Directory Path' title and default value. The description does not compensate for the low schema coverage.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description names a specific action sequence ('Walks the project', 'detects changed files', 'updates the vector store') and a concrete resource ('persistent local ChromaDB vector store'). It is clearly distinct from the sibling tools semantic_search and find_ast_usages, which do search and AST lookup rather than indexing.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The phrase 'incrementally updates' and 'detects changed files' implies the tool is meant to keep the index fresh after edits, but the description never explicitly says when to run it relative to semantic_search or find_ast_usages. It also does not mention exclusions or alternatives.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
semantic_searchA
Search code by meaning and keywords (hybrid BM25+vectors, semantic, or keyword). Returns ranked code fragments with exact file, class, method, start_line, end_line, and code snippets. Supports optional Cross-Encoder re-ranking (rerank=True).
| Name | Required | Description | Default |
|---|---|---|---|
| mode | No | hybrid | |
| limit | No | ||
| query | Yes | ||
| rerank | No | ||
| directory_path | No | . |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden and does well by disclosing the hybrid retrieval approach, the exact return fields, and optional Cross-Encoder re-ranking. It lacks explicit statements about read-only behavior, performance, or side effects, but for a search tool the disclosed behavior is substantial and useful.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is two sentences with no filler. Key behavior ('ranked code fragments') and return fields are front-loaded, and the optional re-ranking detail is placed at the end without bloating the text.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The output schema exists and covers the return format, so the description does not need to repeat that. However, important invocation context is missing: what 'directory_path' refers to, whether indexing from index_workspace is required first, and how the repository scope is determined. These gaps make the definition adequate but not fully complete for correct invocation.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, so the description must compensate, but it only enriches two parameters: 'mode' (hybrid BM25+vectors, semantic, keyword) and 'rerank' (Cross-Encoder re-ranking). The parameters 'query', 'limit', and 'directory_path' are not meaningfully explained beyond their schema titles and defaults, leaving significant gaps.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly identifies a specific verb ('Search') and resource ('code') while explaining that results are ranked by meaning and keywords. It also distinguishes the tool from siblings like find_ast_usages and go_to_definition by emphasizing semantic/keyword search with ranked code fragments rather than AST or definition lookups.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies when to use the tool: when the user wants to search code semantically or by keyword. However, it does not explicitly state when not to use it or contrast it with alternatives, leaving the agent to infer selection from the tool name and sibling context.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
2 tool updates
v0.4.0- Added
go_to_definition - Changed
semantic_search2 fields changed- added
Input schema / properties / modeAdded value: +{ + "default": "hybrid", + "enum": [ + "hybrid", + "semantic", + "keyword" + ], + "title": "Mode", + "type": "string" +} - added
Input schema / properties / rerankAdded value: +{ + "default": false, + "title": "Rerank", + "type": "boolean" +}
3 tool updates
v0.1.0- First observed
find_ast_usages - First observed
index_workspace - First observed
semantic_search
TDQS
Scored across 4 tools
Each tool targets a distinct part of code navigation: semantic search vs. exact definitions vs. AST usages vs. index maintenance. There is no realistic confusion between their purposes.
Three of four tools use imperative verb-first names (find_ast_usages, index_workspace, go_to_definition), and all are snake_case. semantic_search breaks the pattern slightly by starting with an adjective instead of a verb, but the naming remains readable and predictable.
With 4 tools, the server is well-scoped and each tool earns its place in the code indexing/search/navigation workflow. There is no redundancy or bloat.
The core lifecycle is covered: index the workspace, search semantically, go to definitions, and find AST usages. Minor gaps such as no explicit index status or reset operation prevent a perfect score, but agents can work around them.
Maintenance
Related MCP Connectors
Code intelligence for coding agents: semantic, AST, graph, and full-text search. 279+ languages.
Search indexed code, trace dependencies, assess change impact, and recall repository memory.
Project memory, semantic code search, and grounded agent context.
Codebase graphs, caller impact analysis, and recorded project context for AI coding agents.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables semantic code search for AI assistants by indexing codebases with embeddings and Tree-sitter, returning relevant snippets via natural language queries.15MIT
- AlicenseNot gradedqualityBmaintenanceProvides AI coding assistants with deep, semantic understanding of local codebases via AST-aware chunking, cross-repo symbol graphs, and architectural memory, enabling context-aware code search and dependency tracing.11MIT
- AlicenseAqualityDmaintenanceEnables AI assistants to perform intelligent semantic code search across codebases using local AI embeddings for meaning-based retrieval.635 npmMIT
- AlicenseNot gradedqualityDmaintenanceEnables AI coding agents to perform semantic code search locally, finding code by meaning rather than exact keywords.3MIT