Skip to main content
Glama
ContextTree MCP

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: smart-coding-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.

Inputs: symbol_name (required), limit, directory_path. Returns: result

go_to_definitionA

Finds the exact definition/declaration location of a symbol (function, method, class, struct, trait, interface) across workspace files.

Inputs: symbol_name (required), limit, directory_path. Returns: result

index_workspaceA

Walks the project, detects changed files by SHA-256 hash, and incrementally updates the persistent local ChromaDB vector store.

Inputs: directory_path. Returns: result

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelogโ€ฆ

    TDQS

    A3.9/5.0

    Scored across 4 tools

    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

    ActivityStale
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      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
      A
      quality
      D
      maintenance
      Enables AI assistants to perform intelligent semantic code search across codebases using local AI embeddings for meaning-based retrieval.
      6
      24 npm
      MIT
    • A
      license
      Not graded
      quality
      A
      maintenance
      Enables AI coding assistants to search codebases by meaning using local AI embeddings, with tools for indexing, cache management, workspace switching, status checks, and package version lookup. It supports incremental and progressive indexing with configurable embedding dimensions to find relevant code even when terminology differs.
      24 npm
      MIT