Skip to main content

MCP server for structural code analysis and editing

Project description

rw-ast-tools

Structural Code Analysis & Editing MCP Server โ€” 77 tools for AST-based code intelligence, semantic search, and surgical Python/TypeScript editing.

Tests License Python


๐ŸŽฏ What It Does

rw-ast-tools is an MCP (Model Context Protocol) server that gives LLMs structural code intelligence โ€” not just text search, but understanding of code as Abstract Syntax Trees:

Capability Tools
Structural Search ast_grep โ€” pattern-match on AST nodes across 8 languages
Code Reading ast_read โ€” extract API surface (classes, functions, imports, line numbers)
Surgical Editing ast_edit โ€” libcst-powered edits (rename, add params, replace nodes)
Semantic Search semantic_search โ€” hybrid vector + FTS5, finds code by meaning
Impact Analysis impact_analysis, blast_radius_v2 โ€” what breaks if you change X?
Code Intelligence find_references, module_imports, circular_dependencies, class_hierarchy
LSP Integration 11 LSP tools: definition, references, hover, completion, rename, diagnostics, code actions
Knowledge Graph kg_query, kg_shortest_path, kg_neighborhood โ€” natural language graph traversal
Dead Code dead_code_enhanced โ€” 6 FP reduction strategies (>40% โ†’ <20%)
Syntax Validation code_validate_syntax โ€” 10 languages via compilers + tree-sitter
Auto-Fix fix_code, fix_check โ€” multi-language convergent fix pipeline
Tool Discovery search_tools, call_tool, tool_info, tool_usage_stats โ€” dynamic tool lookup

๐Ÿš€ Quick Start

Install

git clone https://github.com/rapidwebs/rw-ast-tools
cd rw-ast-tools
uv venv && source .venv/bin/activate
uv pip install -e .

Run MCP Server

# Daemon mode (persistent, systemd-managed) โ€” RECOMMENDED
ast-tools --mode daemon

# Or timeout mode (default, stdio with idle timeout)
ast-tools

Hermes Integration

Add to ~/.hermes/config.yaml:

mcp_servers:
  ast-tools:
    command: socat
    args:
      - "-"
      - "UNIX-CONNECT:/home/user/.cache/rw-ast-tools/server.sock"
    connect_timeout: 10
    timeout: 120

Daemon setup:

# Install systemd user service
cp deploy/rw-ast-tools.service ~/.config/systemd/user/
systemctl --user daemon-reload
systemctl --user enable --now rw-ast-tools

The daemon auto-starts via systemd and Hermes connects via socat bridge. No per-session cold start โ€” the daemon is always ready.


๐Ÿงฐ All 77 Tools

Core AST (8)

Tool Description
ast_grep Structural search with AST patterns (Python, JS, TS, Rust, Go, Java, C++, C#)
ast_read Extract API surface โ€” classes, functions, imports, line numbers
ast_edit Surgical edits via libcst โ€” always dry_run=true first!
ast_generate_stub Generate .pyi stub files or interface summaries
ast_refactor_extract_interface Extract ABC/Protocol from a class
ast_capsule Export code as self-contained capsule with dependencies
ast_query Smart router โ€” describe intent, auto-selects best tool
ts_edit TypeScript/TSX structural editing (tree-sitter)

Analysis & Impact (14)

Tool Description
structural_analysis Call graphs, type hierarchies, references, dependencies
impact_analysis Before refactoring โ€” affected files + risk assessment
blast_radius_v2 Unified blast radius (imports + hierarchy + call graph)
module_imports Fan-in/fan-out import graph, circular dependency detection
find_references All usages of a symbol across the codebase
transitive_dependents Full transitive dependency chain
class_hierarchy MRO, bases, subclasses, method categories
circular_dependencies Detect circular imports
dependency_chain Trace dependency paths end-to-end
external_dependencies Find third-party imports
api_surface_diff Compare API surfaces between versions
co_change_predict Files that tend to change with a given file
co_change_hotspots Top-N riskiest files by churn ร— coupling
co_change_diff Symbols at risk when changing a symbol

Knowledge Graph (3)

Tool Description
kg_query Natural language graph traversal
kg_shortest_path Shortest path between two symbols
kg_neighborhood All symbols within N hops

Semantic Search & Index (8)

Tool Description
semantic_search Vector + FTS5 hybrid โ€” search by meaning
search_symbols FTS5 keyword search
find_symbol_definition Lookup by qualified name
list_symbols All symbols in a file
refresh_index Incremental indexing (SHA256 content hashing)
index_status Symbols, files, embeddings count
reindex_path Per-file reindex
watch_add / watch_status Auto-index watcher daemon

Dead Code & Quality (4)

Tool Description
dead_code_detection Basic unused code detection
dead_code_enhanced 6 FP reductions โ€” confidence scoring, framework decorators, entry points, SCC, __all__, polymorphism
code_validate_syntax 10 languages: Python, SQL, Shell, JS, TS, Rust, Go (compilers) + C, C++, C# (tree-sitter)
fix_code / fix_check Multi-language auto-fix pipeline (SAFE/UNSAFE/DISPLAY)

LSP Code Intelligence (11)

Tool Description
lsp_definition Go to definition
lsp_references Find all references
lsp_hover Type signature + docs
lsp_symbols All symbols in file
lsp_diagnostics Errors/warnings from LSP
lsp_format Format code
lsp_code_actions Quick fixes & refactorings
lsp_rename Workspace-wide rename
lsp_signature_help Function signature at call site
lsp_completion / lsp_completion_detail Code completion
lsp_available_languages / lsp_check_server Server management

Meta & Discovery (5)

Tool Description
search_tools Semantic search across all 77 tool descriptions
call_tool Execute tool by name with validated params
tool_info Full schema, category, usage stats for any tool
tool_usage_stats Call counts, error rates, latency, ranking boosts
context_inject / context_status / token_status / validate_usage Context injection system

Embedding Models (4)

Tool Description
switch_embedding_model Hot-swap embedding model
list_embedding_models Available models
get_embedding_model_info Model details
rerank_results Cross-encoder reranking

Curator (3)

Tool Description
curator_audit Automated code review
curator_summary Review summary
curator_status Curator system status

๐Ÿ”ง Common Workflows

Before Making Changes (MANDATORY)

# 1. Orient to project
ast-tools codebase_summary

# 2. Read target file structure
ast-tools ast_read --file src/auth/middleware.py

# 3. Check what calls it (impact)
ast-tools impact_analysis --target src/auth/middleware.py

# 4. Check imports (if splitting module)
ast-tools module_imports --module src.auth.middleware

Find Code by Meaning

# "Where is the websocket handler?"
ast-tools semantic_search --query "websocket handler" --k 5

# "How does error retry work?"
ast-tools semantic_search --query "exponential backoff retry" --k 10

Refactor Large Module โ†’ Subpackage

# 1. Map all imports
ast-tools structural_analysis --analysis-type dependencies --file src/large_module.py

# 2. Check circular deps
ast-tools module_imports --module large_module

# 3. Extract to subpackage (create __init__.py with __all__)
# 4. Run tests AFTER EACH extraction

Dead Code Cleanup

# High-confidence dead code only
ast-tools dead_code_enhanced --format json | jq '.dead_functions[] | select(.confidence=="high")'

๐Ÿ“ฆ Server Modes

Mode Transport Use Case
daemon (default) Unix domain socket (systemd) Persistent, production โ€” recommended for Hermes
timeout stdio + idle timeout Interactive, short sessions
remote Streamable HTTP + bearer auth Remote container access

Daemon mode (used by Hermes):

# systemd-managed (production)
systemctl --user enable --now rw-ast-tools

# Or manually:
ast-tools --mode daemon

# Via socat from Hermes:
socat - UNIX-CONNECT:/home/user/.cache/rw-ast-tools/server.sock

The daemon listens on a Unix domain socket using NDJSON line protocol. Multiple clients (Hermes, subagents, CLI) share the same daemon โ€” no per-session cold start overhead (~10-16s saved per Hermes session).

Multi-Project Watching in Daemon Mode

Daemon mode can monitor multiple projects simultaneously (saves resources vs running multiple instances). Configure via:

  1. Config file (~/.config/rw-ast-tools/config.yaml):
daemon:
  watchdogs: true
  watch_paths:
    - "/home/user/Workspaces/project-a"
    - "/home/user/Workspaces/project-b"
    - "/home/user/Workspaces/project-c"
  1. Environment variable (comma-separated):
AST_TOOLS_DAEMON_WATCH_PATHS="/home/user/Workspaces/project-a,/home/user/Workspaces/project-b" ast-tools --mode daemon
  1. CLI (coming soon): ast-tools --mode daemon --watch-paths /path/a,/path/b

If no paths configured, defaults to CWD.



๐Ÿ”Œ Hermes Plugin: rw-ast-tools

Unified plugin replacing 3 old plugins. 4 hooks:

Hook Purpose
pre_llm_call Injects project-specific context via semantic_search + quick reference + typo corrections
on_session_start Compact 200-token tool index
post_tool_call Token tracking + error correction for common mistakes
on_session_end Session intelligence (modified files + codebase summary)

Key improvement: pre_llm_call now calls semantic_search(query, inject_context=True) โ€” returns actual project symbols (signatures, docstrings, file paths) instead of generic tool docs.


๐Ÿ—๏ธ Architecture

rw-ast-tools/
โ”œโ”€โ”€ src/ast_tools/
โ”‚   โ”œโ”€โ”€ _server.py              # MCP server entry (3 modes)
โ”‚   โ”œโ”€โ”€ server_config.py        # Unified config: CLI > env > file > defaults
โ”‚   โ”œโ”€โ”€ config/unified.py       # Pydantic config with validation
โ”‚   โ”œโ”€โ”€ tools/                  # 77 MCP tools (auto-registered)
โ”‚   โ”‚   โ”œโ”€โ”€ semantic_search.py  # Hybrid vector + FTS5 (6-factor RRF)
โ”‚   โ”‚   โ”œโ”€โ”€ ast_edit.py         # libcst surgical editing
โ”‚   โ”‚   โ”œโ”€โ”€ ast_grep.py         # Tree-sitter structural search
โ”‚   โ”‚   โ”œโ”€โ”€ lsp_tools.py        # 11 LSP tools
โ”‚   โ”‚   โ”œโ”€โ”€ dynamic_schemas.py  # generate_quick_reference(), find_similar_tool()
โ”‚   โ”‚   โ””โ”€โ”€ ... (70 more)
โ”‚   โ”œโ”€โ”€ database/               # SQLite + sqlite-vec (384-dim)
โ”‚   โ”‚   โ”œโ”€โ”€ connection.py       # Persistent pool + thread-pool fallback
โ”‚   โ”‚   โ”œโ”€โ”€ schema.py           # Schema v5, migrations
โ”‚   โ”‚   โ””โ”€โ”€ queries.py          # Symbol CRUD, vector KNN
โ”‚   โ”œโ”€โ”€ indexer/                # Incremental indexing
โ”‚   โ”‚   โ”œโ”€โ”€ extractor.py        # Tree-sitter + libcst extraction
โ”‚   โ”‚   โ”œโ”€โ”€ diff.py             # Symbol-level diff (added/removed/modified)
โ”‚   โ”‚   โ””โ”€โ”€ daemon.py           # Watchdog watcher (100ms debounce)
โ”‚   โ”œโ”€โ”€ embeddings/             # SentenceTransformers + provider abstraction
โ”‚   โ”œโ”€โ”€ reranker/               # Cross-encoder (ms-marco-MiniLM-L-6-v2)
โ”‚   โ”œโ”€โ”€ lsp_client.py           # Persistent LSP cache, ref counting
โ”‚   โ”œโ”€โ”€ agent_integration/      # Zero-Hermes-dependency modules
โ”‚   โ”‚   โ”œโ”€โ”€ context_builder.py  # build_ast_tools_context, detect_ast_query
โ”‚   โ”‚   โ”œโ”€โ”€ token_tracker.py    # TokenTracker, ContextPressureMonitor
โ”‚   โ”‚   โ”œโ”€โ”€ error_correction.py # Common tool error detection
โ”‚   โ”‚   โ””โ”€โ”€ session_intel.py    # Mutation tracking, codebase_summary
โ”‚   โ”œโ”€โ”€ fix/                    # Auto-fix pipeline (C1)
โ”‚   โ”‚   โ”œโ”€โ”€ engine.py           # Convergent fix runner
โ”‚   โ”‚   โ””โ”€โ”€ fixers.py           # Per-language fixers
โ”‚   โ”œโ”€โ”€ curator/                # Code review automation
โ”‚   โ”œโ”€โ”€ ts_backend.py           # TypeScript tree-sitter backend
โ”‚   โ””โ”€โ”€ spectral.py             # Spectral clustering (Nystrรถm, TF-IDF naming)
โ”œโ”€โ”€ tests/                      # 71 test files, 943 tests
โ”œโ”€โ”€ docs/
โ”‚   โ”œโ”€โ”€ portal/                 # Interactive HTML docs (React)
โ”‚   โ”œโ”€โ”€ AST_TOOLS_QUICKSTART.md
โ”‚   โ”œโ”€โ”€ CLI_REFERENCE.md
โ”‚   โ””โ”€โ”€ DOCUMENTATION_INDEX.md
โ””โ”€โ”€ plugins/
    โ””โ”€โ”€ rw-ast-tools/           # Hermes plugin

๐Ÿ“Š Specs

Metric Value
MCP Tools 77
Source Files 134
Test Files 71
Test Lines 8,946
Tests Passing 943 (2 skipped)
Languages (AST) Python, JS, TS, TSX, Rust, Go, Java, C++, C, C#
Languages (Syntax Validation) 10 (7 compilers + 3 tree-sitter)
Embedding Dim 384 (all-MiniLM-L6-v2)
Schema Version v5
License MIT

๐Ÿงช Testing

# Full suite (2 min)
pytest tests/ -v

# Fast: unit tests only
pytest tests/ -m "not integration" -x

# Specific area
pytest tests/tools/test_semantic_search.py -v
pytest tests/tools/test_lsp_tools.py -v
pytest tests/test_cli.py -v

๐Ÿ“š Documentation

File Description
docs/AST_TOOLS_QUICKSTART.md 13KB intro + workflows
docs/CLI_REFERENCE.md 15KB complete CLI guide (11 commands)
docs/DOCUMENTATION_INDEX.md Full index of all docs
docs/portal/ Interactive HTML docs (React + live search)

๐Ÿ“„ License

MIT โ€” see LICENSE


Built by RapidWebs Enterprise โ€” ast-tools is the structural code intelligence layer for the NexusAgent platform.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

rw_ast_tools-0.2.2.tar.gz (1.8 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

rw_ast_tools-0.2.2-py3-none-any.whl (371.2 kB view details)

Uploaded Python 3

File details

Details for the file rw_ast_tools-0.2.2.tar.gz.

File metadata

  • Download URL: rw_ast_tools-0.2.2.tar.gz
  • Upload date:
  • Size: 1.8 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.29 {"installer":{"name":"uv","version":"0.11.29","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for rw_ast_tools-0.2.2.tar.gz
Algorithm Hash digest
SHA256 2b6b6c5087cf281fafb4ea3cf09570e78c9705c5816943af7c02c16f20574706
MD5 5bde9b6ddbda2d859ede1706da29843c
BLAKE2b-256 23f37c50b4b1b2b6a6ed07e1d5d97c9cf2db2e5747987e6b3bead0703470eae1

See more details on using hashes here.

File details

Details for the file rw_ast_tools-0.2.2-py3-none-any.whl.

File metadata

  • Download URL: rw_ast_tools-0.2.2-py3-none-any.whl
  • Upload date:
  • Size: 371.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.29 {"installer":{"name":"uv","version":"0.11.29","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for rw_ast_tools-0.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 160c7bcd8822b0226c84a1f156d2ab10fe8f15948c830303c1dacdffd0f0f976
MD5 eabff99df4dadd96d57f40191b3409dd
BLAKE2b-256 a19e686dd0446b078337d7141c91585e73c5ed72373b744c07185e66a8c12b67

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page