Skip to main content
Glama
chelslava

ContextTree MCP

by chelslava

๐ŸŒณ ContextTree MCP

Local Deep Semantic & Hybrid Code Search Engine for AI Assistants
Powered by tree-sitter AST logical parsing, local embeddings, 3-layer RRF ranking & Cross-Encoder re-ranking.

GitHub Release Python Version MCP Protocol Tests Code Style License: MIT Privacy: 100% Offline README in Russian


๐Ÿ’ก Why ContextTree MCP?

Standard semantic search tools split code into arbitrary line or token windows, breaking function contexts and hallucinating definitions. ContextTree MCP provides LLMs with true structural intelligence of your codebase:

  • ๐Ÿงฉ AST Logical Block Extraction: Indexes complete, meaningful units (functions, methods, classes, structs, traits) preserving docstrings and signatures.

  • ๐Ÿข Multi-Repository Unified Indexing: Seamlessly index and search across multiple repositories or multi-root workspaces in a single session.

  • ๐Ÿ—œ๏ธ Embedding Quantization (INT8 & Binary): 4x to 32x RAM and storage compression with scalar/binary quantized vector representations.

  • ๐Ÿ”Œ Language Server Protocol (LSP) Bridge: Compiler-grade symbol definitions, hover documentation, and references across local language servers.

  • โšก 3-Layer Hybrid Search (RRF): Blends dense vectors (sentence-transformers/all-MiniLM-L6-v2), BM25 lexical token matching (camelCase/snake_case), and Call-Graph In-Degree Ranking.

  • ๐ŸŽฏ Cross-Encoder 2nd-Stage Re-ranking: Joint cross-attention re-scoring (rerank=True) for maximum precision on nuanced queries.

  • ๐Ÿ” Zero-Hallucination Code Navigation: Real AST call-site tracking (find_ast_usages) and cross-file definition jump (go_to_definition).

  • ๐Ÿ”„ Incremental Indexing & Watch Mode: SHA-256 state tracking with 500ms debounced filesystem watcher across multiple workspaces.

  • ๐ŸŒ Flexible Transports: Standard stdio, SSE over HTTP, and Streamable HTTP.

  • ๐Ÿ”’ 100% Offline & Private: Zero cloud dependencies, zero external API calls, zero telemetry.


Related MCP server: CodeGrok MCP

๐ŸŒ Supported Languages (12 Languages)

Language

Extensions

Extracted AST Constructs

Python

.py

Functions, decorated definitions, classes, methods, docstrings (PEP-257)

TypeScript / TSX

.ts, .tsx, .mts, .cts

Functions, arrow functions, methods, class/interface signatures, JSDoc

JavaScript / JSX

.js, .jsx, .mjs, .cjs

Functions, arrow functions, methods, class signatures, JSDoc

Go

.go

Functions, receiver methods, struct/interface types, package comments

Rust

.rs

Functions, impl methods, structs, traits, /// documentation

C#

.cs

Methods, constructors, classes, interfaces, structs, /// <summary> XML-docs

Java

.java

Methods, constructors, classes, interfaces, records, Javadoc

C

.c, .h

Functions, structs, unions, enums, declarator unpacking, comments

C++

.cpp, .hpp, .cc, .cxx, .hh, .hxx

Methods, classes, structs, namespaces, destructors, doc comments

Kotlin

.kt, .kts

Functions, classes, objects, member methods, KDoc comments

Swift

.swift

Functions, methods, classes, structs, protocols, enums, Swift-doc


๐Ÿ—๏ธ Architecture

flowchart TB
    subgraph Client["๐Ÿค– AI Assistant Client"]
        Claude["Claude Desktop / Cursor / Antigravity / OpenCode"]
    end

    subgraph Server["๐ŸŒณ ContextTree MCP Server"]
        Transport["Transport Layer (Stdio / SSE / HTTP)"]
        Tools["MCP Tools (search, usages, definition, index)"]
        
        subgraph Pipeline["Indexing & Search Pipeline"]
            TreeSitter["Tree-sitter AST Parser (12 Grammars)"]
            Chunker["Logical Block Chunker (Signatures + Docs)"]
            BM25["In-Memory BM25 Index (Cached)"]
            VectorStore["ChromaDB Vector Store (384d Embeddings)"]
            CallGraph["Call-Graph In-Degree Frequency"]
            RRF["3-Layer Reciprocal Rank Fusion"]
            CrossEncoder["Cross-Encoder Re-ranker (ms-marco-MiniLM)"]
        end
    end

    subgraph Workspace["๐Ÿ’ป Local Workspace Files"]
        SourceFiles["Source Code (.py, .ts, .go, .rs, .cpp, .kt, ...)"]
        State[".chroma/index_state.json (SHA-256 Fast Path)"]
    end

    Claude <--> Transport
    Transport <--> Tools
    Tools <--> Pipeline
    Pipeline <--> Workspace

๐Ÿš€ Quick Start

Prerequisites

  • Python 3.12+

  • uv (strongly recommended) or standard pip

1. Installation

# Clone the repository
git clone https://github.com/chelslava/mcp-context-tree.git
cd mcp-context-tree

# Install dependencies and local package via uv
uv sync

2. Running ContextTree MCP

# Standard MCP stdio mode (default for AI desktop clients)
uv run context-tree

# Server-Sent Events (SSE) HTTP transport on port 8000
uv run context-tree --transport sse --host 127.0.0.1 --port 8000

# Streamable HTTP transport
uv run context-tree --transport streamable-http --port 8000

# Standalone Watch Mode (continuously indexes workspace on save)
uv run context-tree --watch /path/to/project

โš™๏ธ Client Configuration

Claude Desktop

Add to your claude_desktop_config.json:

{
  "mcpServers": {
    "context-tree": {
      "command": "uv",
      "args": [
        "run",
        "--directory",
        "D:/Repo/mcp-context-tree",
        "context-tree"
      ]
    }
  }
}

Cursor IDE / Windsurf

Add to .cursor/mcp.json or Cursor MCP Settings:

{
  "mcpServers": {
    "context-tree": {
      "command": "uv",
      "args": ["run", "--directory", "/absolute/path/to/mcp-context-tree", "context-tree"]
    }
  }
}

Google Antigravity / Remote SSE Setup

If using network transport (--transport sse):

{
  "mcpServers": {
    "context-tree": {
      "url": "http://127.0.0.1:8000/sse"
    }
  }
}

๐Ÿ› ๏ธ MCP Tools Reference

1. index_workspace

Scans the project directory, computes SHA-256 hashes, applies .gitignore rules, and incrementally updates the local ChromaDB vector store.

// Parameters
{
  "directory_path": "."
}

// Response
{
  "status": "ok",
  "workspace": "/path/to/project",
  "added": 12,
  "modified": 2,
  "deleted": 0,
  "unchanged": 85,
  "indexed_chunks": 340,
  "total_in_store": 340
}

2. semantic_search

Executes deep code search across the workspace with live snippet resolution from disk.

// Parameters
{
  "query": "how to verify and refresh JWT authentication tokens",
  "directory_path": ".",
  "limit": 5,
  "mode": "hybrid",   // "hybrid" | "semantic" | "keyword"
  "rerank": true      // Optional 2nd-stage Cross-Encoder re-ranking
}

// Response
{
  "results": [
    {
      "file": "src/auth/service.py",
      "type": "method",
      "class": "AuthService",
      "name": "verify_jwt_token",
      "start_line": 45,
      "end_line": 68,
      "score": 0.9624,
      "code": "def verify_jwt_token(self, token: str) -> Claims:\n    ..."
    }
  ]
}

3. find_ast_usages

Performs true AST-level call-site resolution for functions, methods, and classes, ignoring string literals and comments.

// Parameters
{
  "symbol_name": "AuthService.verify_jwt_token",
  "directory_path": ".",
  "limit": 50
}

// Response
{
  "usages": [
    {
      "file": "src/api/routes.py",
      "line": 104,
      "preview": "claims = auth_service.verify_jwt_token(token)"
    }
  ]
}

4. go_to_definition

Instantly resolves the exact AST declaration/definition location of a symbol across all 12 supported languages.

// Parameters
{
  "symbol_name": "UserRepo.getUser",
  "directory_path": ".",
  "limit": 20
}

// Response
{
  "definitions": [
    {
      "file": "src/models/User.kt",
      "language": "kotlin",
      "type": "method",
      "name": "getUser",
      "class": "UserRepo",
      "start_line": 14,
      "end_line": 22,
      "code": "fun getUser(id: String): User? {\n    ...",
      "docstring": "/** Retrieve user by identifier */"
    }
  ]
}

๐Ÿ”ฌ Search & Ranking Algorithm

ContextTree MCP uses a 3-Layer Reciprocal Rank Fusion (RRF) formula to merge dense semantic embeddings, exact lexical matches, and architectural importance:

$$RRF(d) = \frac{w_{vec}}{k + rank_{vec}(d)} + \frac{w_{bm25}}{k + rank_{bm25}(d)} + \frac{w_{graph}}{k + rank_{graph}(d)}$$

Where:

  • $k = 60$ (smoothing constant)

  • $w_{vec} = 1.0$ (dense semantic similarity via all-MiniLM-L6-v2)

  • $w_{bm25} = 1.0$ (Robertson-Spรคrck Jones BM25 with camelCase/snake_case tokenization)

  • $w_{graph} = 0.5$ (in-degree call frequency boost: heavily referenced core symbols float to the top)

  • Cross-Encoder Layer: When rerank=True, candidate chunks pass through joint self-attention (cross-encoder/ms-marco-MiniLM-L-6-v2) for fine-grained semantic scoring.


๐Ÿ”’ Privacy & Security

  • 100% Local Execution: All parsing, embedding generation, and vector indexing happen entirely on your machine.

  • Zero Cloud Network Calls: Never transmits source code or embeddings to external APIs.

  • Respects Ignore Rules: Honors root and nested .gitignore rules alongside built-in filters for target/, node_modules/, bin/, obj/, .git/, .venv/.


๐Ÿงช Testing & Quality

ContextTree MCP maintains 100% pass rate across its test suite and strict linting:

# Run test suite (60 unit & integration tests)
uv run pytest

# Run linter and formatting check
uv run ruff check .
uv run ruff format --check .

๐Ÿ“„ License

Distributed under the MIT License. See LICENSE for details.

Available Tools

4 tools
find_ast_usagesA

AST-based lookup of real call sites / instantiations of a function or class. Filters out string literals, comments, and non-call occurrences.

ParametersJSON Schema
NameRequiredDescriptionDefault
limitNo
symbol_nameYes
directory_pathNo.

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A3.6/5.0
Behavior3/5

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.

Conciseness5/5

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.

Completeness3/5

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.

Parameters2/5

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.

Purpose5/5

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.

Usage Guidelines3/5

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.

ParametersJSON Schema
NameRequiredDescriptionDefault
limitNo
symbol_nameYes
directory_pathNo.

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A3.5/5.0
Behavior3/5

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.

Conciseness5/5

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.

Completeness2/5

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.

Parameters2/5

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.

Purpose5/5

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.

Usage Guidelines3/5

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.

ParametersJSON Schema
NameRequiredDescriptionDefault
directory_pathNo.

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A3.9/5.0
Behavior4/5

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.

Conciseness5/5

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.

Completeness4/5

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.

Parameters2/5

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.

Purpose5/5

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.

Usage Guidelines3/5

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.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.

  1. 2 tool updatesv0.4.0
    • Addedgo_to_definition
    • Changedsemantic_search2 fields changed
      • addedInput schema / properties / mode
        Added value: +{
        +  "default": "hybrid",
        +  "enum": [
        +    "hybrid",
        +    "semantic",
        +    "keyword"
        +  ],
        +  "title": "Mode",
        +  "type": "string"
        +}
      • addedInput schema / properties / rerank
        Added value: +{
        +  "default": false,
        +  "title": "Rerank",
        +  "type": "boolean"
        +}
  2. 3 tool updatesv0.1.0
    • First observedfind_ast_usages
    • First observedindex_workspace
    • First observedsemantic_search

TDQS

A3.9/5.0
Disambiguation5/5

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.

Naming Consistency4/5

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.

Tool Count5/5

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.

Completeness4/5

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

ActivityMaintained
ResponsivenessResponsive

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • A
    license
    A
    quality
    F
    maintenance
    Provides intelligent semantic code search using local AI embeddings, enabling natural language queries to find relevant code by meaning rather than exact keywords. Indexes codebases in the background with smart project detection and privacy-first local processing.
    6
    39
    199
    MIT
  • A
    license
    Not graded
    quality
    F
    maintenance
    Enables semantic code search for AI assistants by indexing codebases with embeddings and Tree-sitter, returning relevant snippets via natural language queries.
    15
    MIT
  • A
    license
    Not graded
    quality
    B
    maintenance
    Provides 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.
    10
    MIT
  • A
    license
    A
    quality
    D
    maintenance
    Enables AI assistants to perform intelligent semantic code search across codebases using local AI embeddings for meaning-based retrieval.
    6
    39
    MIT

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/chelslava/mcp-context-tree'

If you have feedback or need assistance with the MCP directory API, please join our Discord server