mcp-server-tree-sitter
The MCP Tree-sitter Server provides code analysis capabilities using tree-sitter, enabling AI assistants to intelligently explore and analyze codebases. Key capabilities include:
Project Management: Register and manage multiple code projects
Code Exploration: Examine files, extract content, and retrieve metadata
Syntax Analysis: Get Abstract Syntax Trees (AST) with customizable depth and identify specific nodes
Pattern Search: Search for text patterns or run tree-sitter queries to find code patterns
Symbol Extraction: Identify and analyze functions, classes, imports and other code symbols
Complexity Analysis: Calculate code metrics for files
Dependency Tracking: Find and analyze code dependencies and imports
Query Building: Create, adapt, and use predefined tree-sitter queries across languages
Similar Code Detection: Find similar code snippets and symbol usage locations
Cache Management: Optimize performance through parse tree caching
Configuration: Customize server behavior through YAML configs and environment variables
AI Assistance: Generate predefined prompts for code review and explanation
State Persistence: Maintain registered projects and cached data
Integrates with Git repositories by recognizing and excluding .git directories from analysis
Provides language-specific code parsing and analysis for JavaScript files, with symbol extraction and AST-based understanding
Enables analysis of Julia code with tree-sitter parsing, symbol extraction, and dependency analysis
Supports parsing and analysis of Kotlin code with tree-sitter for symbol extraction and AST generation
Offers language-specific code parsing and analysis for Python files, including symbol extraction, AST generation, and complexity analysis
Enables analysis of Rust codebases with capabilities for symbol extraction, dependency analysis, and AST generation
Provides code analysis for Swift files with tree-sitter parsing and structure-aware code exploration
Supports TypeScript code analysis with tree-sitter, including syntax tree generation and structure-aware code exploration
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@mcp-server-tree-sitter analyze the main function in my Python project"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
MCP Tree-sitter Server
A Model Context Protocol (MCP) server that provides code analysis capabilities using tree-sitter, designed to give AI assistants intelligent access to codebases with appropriate context management. Claude Desktop is the reference implementation target.
Features
🔍 Flexible Exploration: Examine code at multiple levels of granularity
🧠 Context Management: Provides just enough information without overwhelming the context window
🌐 Language Agnostic: Supports many programming languages including Python, JavaScript, TypeScript, Go, Rust, C, C++, C#, Swift, Java, Kotlin, Dart, Julia, and APL via tree-sitter-language-pack
🌳 Structure-Aware: Uses AST-based understanding with efficient cursor-based traversal
🔎 Searchable: Find specific patterns using text search and tree-sitter queries
🔄 Caching: Optimized performance through parse tree caching
🔑 Symbol Extraction: Extract and analyze functions, classes, and other code symbols
📊 Dependency Analysis: Identify and analyze code dependencies and relationships
🧩 State Persistence: Maintains project registrations and cached data between invocations
🔒 Secure: Built-in security boundaries and input validation
For a comprehensive list of all available commands, their current implementation status, and detailed feature matrix, please refer to the FEATURES.md document.
Related MCP server: @lex-tools/codebase-context-dumper
Installation
Prerequisites
Python 3.10+
Tree-sitter language parsers for your preferred languages
Basic Installation
pip install mcp-server-tree-sitterDevelopment Installation
git clone https://github.com/wrale/mcp-server-tree-sitter.git
cd mcp-server-tree-sitter
pip install -e ".[dev]"Quick Start
Running with Claude Desktop
You can make the server available in Claude Desktop either through the MCP CLI or by manually configuring Claude Desktop.
Using MCP CLI
Register the server with Claude Desktop:
mcp install mcp_server_tree_sitter.server:mcp --name "tree_sitter"Manual Configuration
Alternatively, you can manually configure Claude Desktop:
Open your Claude Desktop configuration file:
macOS/Linux:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.json
Create the file if it doesn't exist.
Add the server to the
mcpServerssection:{ "mcpServers": { "tree_sitter": { "command": "python", "args": [ "-m", "mcp_server_tree_sitter.server" ] } } }Alternatively, if using uv or another package manager:
{ "mcpServers": { "tree_sitter": { "command": "uv", "args": [ "--directory", "/ABSOLUTE/PATH/TO/YOUR/PROJECT", "run", "-m", "mcp_server_tree_sitter.server" ] } } }Note: Make sure to replace
/ABSOLUTE/PATH/TO/YOUR/PROJECTwith the actual absolute path to your project directory.Save the file and restart Claude Desktop.
The MCP tools icon (hammer) will appear in Claude Desktop's interface once you have properly configured at least one MCP server. You can then access the tree_sitter server's functionality by clicking on this icon.
Configuring with Released Version
If you prefer not to manually install the package from PyPI (released version) or clone the repository, simply use the following configuration for Claude Desktop:
Open your Claude Desktop configuration file (same location as above).
Add the tree-sitter server to the
mcpServerssection:{ "mcpServers": { "tree_sitter": { "command": "uvx", "args": [ "--directory", "/ABSOLUTE/PATH/TO/YOUR/PROJECT", "mcp-server-tree-sitter" ] } } }Save the file and restart Claude Desktop.
This method uses uvx to run the installed PyPI package directly, which is the recommended approach for the released version. The server doesn't require any additional parameters to run in its basic configuration.
State Persistence
The MCP Tree-sitter Server maintains state between invocations. This means:
Projects stay registered until explicitly removed or the server is restarted
Parse trees are cached according to configuration settings
Language information is retained throughout the server's lifetime
This persistence is maintained in-memory during the server's lifetime using singleton patterns for key components.
Running as a standalone server
There are several ways to run the server:
Using the MCP CLI directly:
python -m mcp run mcp_server_tree_sitter.serverUsing Makefile targets:
# Show available targets
make
# Run the server with default settings
make mcp-run
# Show help information
make mcp-run ARGS="--help"
# Show version information
make mcp-run ARGS="--version"
# Run with custom configuration file
make mcp-run ARGS="--config /path/to/config.yaml"
# Enable debug logging
make mcp-run ARGS="--debug"
# Disable parse tree caching
make mcp-run ARGS="--disable-cache"Using the installed script:
# Run the server with default settings
mcp-server-tree-sitter
# Show help information
mcp-server-tree-sitter --help
# Show version information
mcp-server-tree-sitter --version
# Run with custom configuration file
mcp-server-tree-sitter --config /path/to/config.yaml
# Enable debug logging
mcp-server-tree-sitter --debug
# Disable parse tree caching
mcp-server-tree-sitter --disable-cacheUsing with the MCP Inspector
Using the MCP CLI directly:
python -m mcp dev mcp_server_tree_sitter.serverOr using the Makefile target:
make mcp-devYou can also pass arguments:
make mcp-dev ARGS="--debug"Usage
Register a Project
First, register a project to analyze:
register_project_tool(path="/path/to/your/project", name="my-project")Explore Files
List files in the project:
list_files(project="my-project", pattern="**/*.py")View file content:
get_file(project="my-project", path="src/main.py")Analyze Code Structure
Get the syntax tree:
get_ast(project="my-project", path="src/main.py", max_depth=3)Extract symbols:
get_symbols(project="my-project", path="src/main.py")Search Code
Search for text:
find_text(project="my-project", pattern="function", file_pattern="**/*.py")Run tree-sitter queries:
run_query(
project="my-project",
query='(function_definition name: (identifier) @function.name)',
language="python"
)Analyze Complexity
analyze_complexity(project="my-project", path="src/main.py")Direct Python Usage
While the primary intended use is through the MCP server, you can also use the library directly in Python code:
# Import from the API module
from mcp_server_tree_sitter.api import (
register_project, list_projects, get_config, get_language_registry
)
# Register a project
project_info = register_project(
path="/path/to/project",
name="my-project",
description="Description"
)
# List projects
projects = list_projects()
# Get configuration
config = get_config()
# Access components through dependency injection
from mcp_server_tree_sitter.di import get_container
container = get_container()
project_registry = container.project_registry
language_registry = container.language_registryConfiguration
Create a YAML configuration file:
cache:
enabled: true # Enable/disable caching (default: true)
max_size_mb: 100 # Maximum cache size in MB (default: 100)
ttl_seconds: 300 # Cache entry time-to-live in seconds (default: 300)
security:
max_file_size_mb: 5 # Maximum file size to process in MB (default: 5)
excluded_dirs: # Directories to exclude from processing
- .git
- node_modules
- __pycache__
allowed_extensions: # Optional list of allowed file extensions
# - py
# - js
# Leave empty or omit for all extensions
language:
default_max_depth: 5 # Default max depth for AST traversal (default: 5)
preferred_languages: # List of languages to pre-load at startup for faster performance
- python # Pre-loading reduces latency for first operations
- javascript
log_level: INFO # Logging level (DEBUG, INFO, WARNING, ERROR)
max_results_default: 100 # Default maximum results for search operationsLoad it with:
configure(config_path="/path/to/config.yaml")Logging Configuration
The server's logging verbosity can be controlled using environment variables:
# Enable detailed debug logging
export MCP_TS_LOG_LEVEL=DEBUG
# Use normal informational logging (default)
export MCP_TS_LOG_LEVEL=INFO
# Only show warning and error messages
export MCP_TS_LOG_LEVEL=WARNINGFor comprehensive information about logging configuration, please refer to the logging documentation. For details on the command-line interface, see the CLI documentation.
About preferred_languages
The preferred_languages setting controls which language parsers are pre-loaded at server startup rather than on-demand. This provides several benefits:
Faster initial analysis: No delay when first analyzing a file of a pre-loaded language
Early error detection: Issues with parsers are discovered at startup, not during use
Predictable memory allocation: Memory for frequently used parsers is allocated upfront
By default, all parsers are loaded on-demand when first needed. For optimal performance, specify the languages you use most frequently in your projects.
You can also configure specific settings:
configure(cache_enabled=True, max_file_size_mb=10, log_level="DEBUG")Or use environment variables:
export MCP_TS_CACHE_MAX_SIZE_MB=256
export MCP_TS_LOG_LEVEL=DEBUG
export MCP_TS_CONFIG_PATH=/path/to/config.yamlEnvironment variables use the format MCP_TS_SECTION_SETTING (e.g., MCP_TS_CACHE_MAX_SIZE_MB) for section settings, or MCP_TS_SETTING (e.g., MCP_TS_LOG_LEVEL) for top-level settings.
Configuration values are applied in this order of precedence:
Environment variables (highest)
Values set via
configure()callsYAML configuration file
Default values (lowest)
The server will look for configuration in:
Path specified in
configure()callPath specified by
MCP_TS_CONFIG_PATHenvironment variableDefault location:
~/.config/tree-sitter/config.yaml
For Developers
Diagnostic Capabilities
The MCP Tree-sitter Server includes a diagnostic framework to help identify and fix issues:
# Run diagnostic tests
make test-diagnostics
# CI-friendly version (won't fail the build on diagnostic issues)
make test-diagnostics-ciDiagnostic tests provide detailed information about the server's behavior and can help isolate specific issues. For more information about the diagnostic framework, please see the diagnostics documentation.
Type Safety Considerations
The MCP Tree-sitter Server maintains type safety when interfacing with tree-sitter libraries through careful design patterns and protocols. If you're extending the codebase, please review the type safety guide for important information about handling tree-sitter API variations.
Available Resources
The server provides the following MCP resources:
project://{project}/files- List all files in a projectproject://{project}/files/{pattern}- List files matching a patternproject://{project}/file/{path}- Get file contentproject://{project}/file/{path}/lines/{start}-{end}- Get specific lines from a fileproject://{project}/ast/{path}- Get the AST for a fileproject://{project}/ast/{path}/depth/{depth}- Get the AST with custom depth
Available Tools
The server provides tools for:
Project management:
register_project_tool,list_projects_tool,remove_project_toolLanguage management:
list_languages,check_language_availableFile operations:
list_files,get_file,get_file_metadataAST analysis:
get_ast,get_node_at_positionCode search:
find_text,run_querySymbol extraction:
get_symbols,find_usageProject analysis:
analyze_project,get_dependencies,analyze_complexityQuery building:
get_query_template_tool,list_query_templates_tool,build_query,adapt_query,get_node_typesSimilar code detection:
find_similar_codeCache management:
clear_cacheConfiguration diagnostics:
diagnose_config
See FEATURES.md for detailed information about each tool's implementation status, dependencies, and usage examples.
Available Prompts
The server provides the following MCP prompts:
code_review- Create a prompt for reviewing codeexplain_code- Create a prompt for explaining codeexplain_tree_sitter_query- Explain tree-sitter query syntaxsuggest_improvements- Create a prompt for suggesting code improvementsproject_overview- Create a prompt for a project overview analysis
Feedback & Community
We'd love to hear how you're using mcp-server-tree-sitter and what would make it more useful for your workflow.
Questions & Feature Requests: GitHub Discussions
Bug Reports: GitHub Issues
License
MIT
Available Tools
26 toolsadapt_queryC
Adapt a query from one language to another.
Args:
query: Original query string
from_language: Source language
to_language: Target language
Returns:
Adapted query
Inputs: from_language (required), query (required), to_language (required).
analyze_complexityC
Analyze code complexity.
Args:
project: Project name
file_path: Path to the file
Returns:
Complexity metrics
Inputs: file_path (required), project (required).
analyze_projectC
Analyze overall project structure.
Args:
project: Project name
scan_depth: Depth of detailed analysis (higher is slower)
ctx: Optional MCP context for progress reporting
Returns:
Project analysis
Inputs: project (required), ctx, scan_depth.
build_queryC
Build a tree-sitter query from templates or patterns.
Args:
language: Language name
patterns: List of template names or custom patterns
combine: How to combine patterns ("or" or "and")
Returns:
Combined query
Inputs: language (required), patterns (required), combine.
check_language_availableC
Check if a tree-sitter language parser is available.
Args:
language: Language to check
Returns:
Success message
Inputs: language (required).
clear_cacheC
Clear the parse tree cache.
Args:
project: Optional project to clear cache for
file_path: Optional specific file to clear cache for
Returns:
Status message
Inputs: file_path, project.
configureC
Configure the server.
Args:
config_path: Path to YAML config file
cache_enabled: Whether to enable parse tree caching
max_file_size_mb: Maximum file size in MB
log_level: Logging level (DEBUG, INFO, WARNING, ERROR)
Returns:
Current configuration
Inputs: cache_enabled, config_path, log_level, max_file_size_mb.
diagnose_configC
Diagnose issues with YAML configuration loading.
Args:
config_path: Path to YAML config file
Returns:
Diagnostic information
Inputs: config_path (required).
find_similar_codeC
Find similar code to a snippet.
Args:
project: Project name
snippet: Code snippet to find
language: Language of the snippet
threshold: Similarity threshold (0.0-1.0)
max_results: Maximum number of results
Returns:
List of similar code locations
Inputs: project (required), snippet (required), language, max_results, +1 more.
find_textB
Search for text pattern in project files.
Args:
project: Project name
pattern: Text pattern to search for
file_pattern: Optional glob pattern (e.g., "**/*.py")
max_results: Maximum number of results
case_sensitive: Whether to do case-sensitive matching
whole_word: Whether to match whole words only
use_regex: Whether to treat pattern as a regular expression
context_lines: Number of context lines to include
Returns:
List of matches with file, line number, and text
Inputs: pattern (required), project (required), case_sensitive, context_lines, +4 more.
find_usageC
Find usage of a symbol.
Args:
project: Project name
symbol: Symbol name to find
file_path: Optional file to look in (for local symbols)
language: Language to search in
Returns:
List of usage locations
Inputs: project (required), symbol (required), file_path, language.
get_astA
Get abstract syntax tree for a file.
Args:
project: Project name
path: File path relative to project root
max_depth: Maximum depth of the tree (default: 5)
include_text: Whether to include node text
Returns:
AST as a nested dictionary
Inputs: path (required), project (required), include_text, max_depth.
get_dependenciesB
Find dependencies of a file.
Args:
project: Project name
file_path: Path to the file
Returns:
Dictionary of imports/includes
Inputs: file_path (required), project (required).
get_fileB
Get content of a file.
Args:
project: Project name
path: File path relative to project root
max_lines: Maximum number of lines to return
start_line: First line to include (0-based)
Returns:
File content
Inputs: path (required), project (required), max_lines, start_line.
get_file_metadataC
Get metadata for a file.
Args:
project: Project name
path: File path relative to project root
Returns:
File metadata
Inputs: path (required), project (required).
get_node_at_positionA
Find the AST node at a specific position.
Args:
project: Project name
path: File path relative to project root
row: Line number (0-based)
column: Column number (0-based)
Returns:
Node information or None if not found
Inputs: column (required), path (required), project (required), row (required).
get_node_typesB
Get descriptions of common node types for a language.
Args:
language: Language name
Returns:
Dictionary of node types and descriptions
Inputs: language (required).
get_query_template_toolC
Get a predefined tree-sitter query template.
Args:
language: Language name
template_name: Template name (e.g., "functions", "classes")
Returns:
Query template information
Inputs: language (required), template_name (required).
get_symbolsC
Extract symbols from a file.
Args:
project: Project name
file_path: Path to the file
symbol_types: Types of symbols to extract (functions, classes, imports, etc.)
Returns:
Dictionary of symbols by type
Inputs: file_path (required), project (required), symbol_types.
list_filesB
List files in a project.
Args:
project: Project name
pattern: Optional glob pattern (e.g., "**/*.py")
max_depth: Maximum directory depth
extensions: List of file extensions to include (without dot)
Returns:
List of file paths
Inputs: project (required), extensions, max_depth, pattern.
list_languagesC
List available languages.
Returns:
Information about available languages
Inputs: no named parameters.
list_projects_toolC
List all registered projects.
Returns:
List of project information
Inputs: no named parameters.
list_query_templates_toolC
List available query templates.
Args:
language: Optional language to filter by
Returns:
Available templates
Inputs: language.
register_project_toolC
Register a project directory for code exploration.
Args:
path: Path to the project directory
name: Optional name for the project (defaults to directory name)
description: Optional description of the project
Returns:
Project information
Inputs: path (required), description, name.
remove_project_toolC
Remove a registered project.
Args:
name: Project name
Returns:
Success message
Inputs: name (required).
run_queryA
Run a tree-sitter query on project files.
Args:
project: Project name
query: Tree-sitter query string
file_path: Optional specific file to query
language: Language to use (required if file_path not provided)
max_results: Maximum number of results
Returns:
List of query matches
Inputs: project (required), query (required), file_path, language, +1 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 26 tools
Most tools have distinct purposes, but some overlap exists. For example, 'find_text' and 'run_query' both search for patterns, though one uses text matching and the other uses tree-sitter queries. Similarly, 'analyze_complexity' and 'analyze_project' both analyze code but at different scopes. Descriptions help clarify boundaries, but an agent might occasionally hesitate between these pairs.
Naming is mixed with no clear pattern. Some tools use verb_noun (e.g., 'clear_cache', 'build_query'), others use noun_verb (e.g., 'list_files', 'list_projects_tool'), and some are ambiguous (e.g., 'configure', 'diagnose_config'). There's inconsistency in suffix usage, like 'list_projects_tool' vs. 'register_project_tool', which disrupts predictability. However, names are generally readable despite the lack of a uniform convention.
With 26 tools, the count feels heavy for a tree-sitter server, bordering on excessive. While the domain of code analysis and querying is broad, many tools could be consolidated (e.g., 'get_file' and 'get_file_metadata'). It's not extreme, but the number may overwhelm agents and suggests over-specialization rather than a well-scoped set.
The tool set comprehensively covers the tree-sitter and code analysis domain. It includes project management (register, list, remove), file operations (get, list, metadata), AST and query tools (get_ast, run_query, build_query), analysis (complexity, dependencies, symbols), and utilities (cache, configuration). There are no obvious gaps; agents can perform full workflows from setup to detailed code exploration.
Maintenance
Related MCP Connectors
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
Shared memory MCP server for Claude Code, Codex, Gemini CLI and Cursor. Cited, editable.
Augments MCP Server - A comprehensive framework documentation provider for Claude Code
The Cortex MCP server provides read-only access to real-time engineering context from the Cortex developer portal, allowing AI coding assistants to answer natural language questions about your organization's catalog (microservices, libraries, domains, teams, infrastructure), scorecards (engineering standards and best practices), initiatives (goals and deadlines), and Engineering Intelligence metrics. It includes tools for querying documentation, tracking personal entities, and accessing AI-assisted insights across the entire Cortex ecosystem.
Related MCP Servers
- AlicenseAqualityCmaintenanceA Model Context Protocol (MCP) server that helps large language models index, search, and analyze code repositories with minimal setup22142,325 PyPI1,004MIT
- AlicenseAqualityDmaintenanceA Model Context Protocol (MCP) server designed to easily dump your codebase context into Large Language Models (LLMs).18 npm3Apache 2.0
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server that analyzes application codebases with real-time file watching, providing AI assistants like Claude with deep insights into project structure, code patterns, and architecture.MIT
- AlicenseAqualityBmaintenanceA robust, language-agnostic Model Context Protocol (MCP) server that provides AI coding agents with the ability to edit files surgically via Abstract Syntax Trees (AST) instead of relying on token-heavy, brittle search-and-replace or diff operations.2811MIT