convez.ai
MCP ServerDevOps & InfraestruturaAvançado
beruang

AST-MCP — Servidor de Inteligência Estrutural de Código

beruang/ast-mcp

Inteligência estrutural de código para LLMs via 54 ferramentas AST

Ver no GitHub
InicialPluginScore · de 0 a 100

Servidor MCP em Rust que expõe análise profunda de código via Tree-sitter, oferecendo 54 ferramentas para parsing de AST, extração de estrutura, detecção de frameworks, reescritas seguras e análise de complexidade. Suporta TypeScript, JavaScript, Python, Go e Rust com limites de segurança e cache inteligente.

Instalação

$npx convez-ai beruang/ast-mcp

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
2
Forks
0
Acompanhando
0
Saúde
28%
Último commit
há 5 meses
Versão
—
Issues abertas
0
Contribuidores
3

Casos de uso

  • Análise e refatoração automática de código com preview seguro
  • Extração de contexto estrutural (funções, imports, dependências) para prompts LLM
  • Detecção de padrões e complexidade em bases de código grandes
  • Integração em pipelines de DevTools e linters inteligentes

Veredito

Ferramenta production-grade robusta para análise estrutural de código em escala. Ideal para quem precisa extrair contexto técnico preciso ou automatizar refatorações, mas exige compreensão profunda de AST e MCP.

README

A tradução para o português deste README ainda está na fila.

MCP AST — Code Intelligence Server

Rust License Tests

Production-grade structural code intelligence over MCP. 54 tools across parsing, extraction, context selection, framework detection, structural rewrites, complexity analysis, and operational observability. Backed by Tree-sitter parsers for TypeScript, TSX, JavaScript, JSX, Python, Go, and Rust.


Architecture

                            ┌─────────────────────────────────────┐
                            │           MCP Client (LLM)          │
                            └──────────────┬──────────────────────┘
                                           │  JSON-RPC 2.0
                                           │  stdin / stdout
                                           ▼
┌─────────────────────────────────────────────────────────────────────────────────┐
│                              ast-mcp Server                                     │
│                                                                                 │
│   ┌───────────┐    ┌─────────────────┐    ┌──────────────┐    ┌──────────────┐  │
│   │ Transport │───▶│  ServerContext  │───▶│  Dispatch    │───▶│ Safety Layer │  │
│   │ tower-lsp │    │  · workspace    │    │  54 tools    │    │ · path bound │  │
│   │   stdio   │    │  · config       │    │  registered  │    │ · size caps  │  │
│   │           │    │  · caches       │    │              │    │ · truncation │  │
│   └───────────┘    │  · req tracker  │    └──────────────┘    └──────┬───────┘  │
│                    │  · scan registry│                               │          │
│                    └─────────────────┘                               ▼          │
│                                                           ┌───────────────┐     │
│                                                           │  Tree-sitter  │     │
│                                                           │   0.22 × 7    │     │
│                                                           │ TS/JS/Py/Go/Rs│     │
│                                                           └───────────────┘     │
└─────────────────────────────────────────────────────────────────────────────────┘
LayerRole
TransportJSON-RPC 2.0 over stdin/stdout via tower-lsp. Notifications are dropped.
ServerContextShared state: workspace resolver, layered runtime config, TTL caches, request log ring buffer, scan registry with cancellation.
Dispatch54 registered tools. Each handler validates input, enforces limits, and delegates to the appropriate engine.
SafetyWorkspace-bounded paths — .., absolute paths, and symlink escapes rejected. File size, node count, and text bytes capped. Truncation flagged in responses.
Tree-sitter7 language grammars at 0.22. Byte offsets → LSP positions via O(log n) binary search on pre-built line index.

Positions are LSP-compatible: zero-based line + UTF-16 character offset.


Supported Languages

LanguageExtensionsParser Crate
TypeScript.tstree-sitter-typescript
TSX.tsxtree-sitter-typescript (tsx)
JavaScript.js, .mjs, .cjstree-sitter-javascript
JSX.jsxtree-sitter-javascript
Python.pytree-sitter-python
Go.gotree-sitter-go
Rust.rstree-sitter-rust

Tools

Diagnostics & Health

ToolDescription
ast_health_checkWorkspace path, available parsers, configured limits
ast_list_supported_languagesLanguage registry — extensions, parser name, availability
ast_readinessReadiness probe — workspace, parser registry, cache initialization, config validity
ast_livenessLiveness probe — uptime, memory usage. No parsing or scanning.
ast_parser_statusParser registry health — language, version, query count, last error
ast_rebuild_parser_cacheClear and reinitialize parser/query caches per language

Parsing

ToolDescription
ast_parse_fileParse a file — root kind, node count, parse time, optional depth-limited tree
ast_queryRun a Tree-sitter query pattern — captures with kind, name, range, text
ast_file_outlineStructured outline — classes, functions, methods, imports, exports
ast_file_metricsStructural metrics — lines, nodes, functions, nesting depth

Navigation

ToolDescription
ast_top_level_nodesDirect children of the root node with kinds and ranges
ast_enclosing_nodeSmallest node at a position, filterable ancestor chain (outermost first)
ast_enclosing_scopeSyntactic scope chain at a position — module, class, function, block
ast_node_at_rangeSmallest node that exactly matches or contains a source range
ast_node_textExact source text for a range — byte-budgeted, no whole-file read

Context Selection

ToolDescription
ast_context_for_rangeSyntax context around a range — target node, parent chain, optional siblings
ast_context_packCompact agent-ready context pack — imports, exports, scope, outline, nearby symbols

Extraction

ToolDescription
ast_find_importsAll imports — ES modules, require(), Python import/from
ast_find_exportsAll exports — TS/JS declarations, re-exports, Python __all__, public defs
ast_find_functionsFunctions, methods, constructors, arrows, lambdas — params, return types
ast_find_classesClass definitions — extends, implements, decorators, methods
ast_find_callsCall expressions — filter by callee name or substring
ast_find_member_accessMember/property access expressions — filter by property or object
ast_find_literalsString, number, boolean, null, regex literals — filter by kind or value
ast_find_template_literalsTemplate literals — filter by tag name (e.g. sql, gql) or content
ast_dependency_edgesSyntax-level dependency edges — imports, exports, requires across files

Structural Chunking

ToolDescription
ast_chunk_fileSplit a file into chunks — 4 strategies: top_level, function_class, semantic_blocks, max_lines

Framework-Aware Detection

ToolDescription
ast_find_schema_definitionsZod schemas, TypeScript interfaces, Pydantic models, dataclasses, SQLAlchemy, Go/Rust structs
ast_find_react_componentsFunction, arrow, and class components — props, hooks used, JSX root
ast_find_hooksBuilt-in and custom React hooks — usages and definitions
ast_find_routesExpress, Fastify, Hono, Next.js, NestJS, FastAPI, Flask, Django, Go net/http, Rust Axum
ast_find_decoratorsTypeScript decorators, Python decorators, Rust #[attributes] — with target attachment
ast_find_testsJest, Vitest, Mocha, Pytest, unittest, Go tests, Rust #[test] — suite/test/fixture/hook
ast_query_workspaceBounded Tree-sitter query across workspace files — glob, limits, parallelism

Structural Rewrites (Preview-Only)

ToolDescription
ast_rewrite_previewPreview structural rewrites — replace, insert before/after, delete. Returns diff + validation.
ast_validate_rewriteValidate rewrite operations — safety, overlap, limits. No diff generated.
ast_parse_after_rewriteApply edits in memory, re-parse, report syntax errors.
ast_insert_import_previewPreview adding an import — TS/JS/Python. Merges with existing imports.
ast_remove_unused_import_previewPreview removing syntactically unused imports. Side-effect imports preserved.
ast_rename_local_previewPreview renaming a local variable within its scope. Exported/top-level rejected.
ast_wrap_node_previewPreview wrapping a node — prefix/suffix, try/catch, or call expression.
ast_add_decorator_previewPreview adding a decorator/attribute — TS/JS/Python/Rust.
ast_modify_function_signature_previewPreview modifying function signature — add/remove/rename params or replace.

Structural Analysis

ToolDescription
ast_complexity_summaryPer-file and workspace-wide complexity — branch/loop count, nesting depth, hotspot ranking with risk heuristics
ast_detect_large_nodesFind oversized functions, classes, modules, tests — configurable min_lines threshold
ast_detect_duplicate_shapesHeuristic clone detection — structural fingerprinting with identifier/literal normalization

Operations & Observability

ToolDescription
ast_get_configReturn effective runtime config — optional source breakdown (defaults, env, overrides)
ast_update_runtime_configUpdate limits, timeouts, cache TTLs, scan parallelism at runtime. Immutable fields rejected.
ast_request_logRecent request history — filter by tool name, status, file path. Ring buffer.
ast_clear_request_logClear request log entries — optionally filtered by tool.
ast_cache_statusCache sizes, TTLs, estimated memory per cache — parse trees, queries, framework results, request log
ast_clear_cachesClear caches selectively. Clearing parse trees cascades to dependent query/framework caches.
ast_workspace_scan_statusActive and recent workspace scan progress — files discovered, processed, results found
ast_cancel_workspace_scanCooperatively cancel a running workspace scan by ID.

Runtime Configuration

Layered, in-memory configuration. Precedence:

defaults  →  AST_* environment variables  →  ast_update_runtime_config overrides

Environment Variables

VariableDefaultDescription
WORKSPACE_PATHCWDWorkspace root directory
AST_MAX_FILE_BYTES1048576Max file size (1 MiB)
AST_MAX_WORKSPACE_FILES500Max files per workspace scan
AST_MAX_WORKSPACE_RESULTS5000Max results per workspace scan
AST_MAX_CONTEXT_CHARACTERS20000Max context characters in responses
AST_MAX_PARALLELISM8Parallel workers for workspace scans
AST_RESPECT_GITIGNOREtrueRespect .gitignore during file discovery
AST_INCLUDE_HIDDENfalseInclude hidden files in scans
AST_PARSE_TREE_TTL_MS300000Parse tree cache TTL (5 min)
AST_REQUEST_LOG_MAX_ENTRIES500Request log ring buffer capacity
AST_MAX_CACHED_FILES1000Max cached parse trees
AST_VERBOSE_LOGGINGfalseEnable verbose tracing output

Runtime updates via ast_update_runtime_config are in-memory only. workspace_path, parser registry, and language grammar paths are immutable at runtime.


Limits

LimitDefaultConfigurable Via
maxFileBytes1 MiBAST_MAX_FILE_BYTES / runtime update
maxParseTreeNodes200,000Runtime update
maxQueryResults1,000Runtime update
maxWorkspaceFiles500AST_MAX_WORKSPACE_FILES / runtime update
maxWorkspaceResults5,000AST_MAX_WORKSPACE_RESULTS / runtime update
maxContextCharacters20,000AST_MAX_CONTEXT_CHARACTERS / runtime update
maxChunkLines160Runtime update
maxChangedFiles100Runtime update
maxEdits1,000Runtime update
maxDuplicateCandidates200Runtime update
maxParallelism8AST_MAX_PARALLELISM / runtime update

Results exceeding limits are truncated. Responses include "truncated": true.


Usage

Build

cargo build --release
# Binary: target/release/ast-mcp

MCP Client Configuration

{
  "mcpServers": {
    "ast": {
      "command": "/path/to/target/release/ast-mcp",
      "env": {
        "WORKSPACE_PATH": "/absolute/path/to/your/project"
      }
    }
  }
}

If WORKSPACE_PATH is not set, the server uses the current working directory. All file_path arguments are workspace-relative — absolute paths and .. are rejected.

Example Tool Calls

Complexity analysis before a refactor:

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "ast_complexity_summary",
    "arguments": { "glob": "src/**/*.ts", "max_files": 200, "max_results": 100 }
  }
}

Adjust scan parallelism at runtime:

{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "ast_update_runtime_config",
    "arguments": {
      "limits": { "max_workspace_files": 1000 },
      "scans": { "max_parallelism": 12 }
    }
  }
}

Inspect cache health:

{
  "jsonrpc": "2.0",
  "id": 3,
  "method": "tools/call",
  "params": {
    "name": "ast_cache_status",
    "arguments": {}
  }
}

Check readiness before a workspace scan:

{
  "jsonrpc": "2.0",
  "id": 4,
  "method": "tools/call",
  "params": {
    "name": "ast_readiness",
    "arguments": { "require_languages": ["typescript", "python"] }
  }
}

Development

cargo build --release                          # Release build
cargo test                                     # All tests across 19 binaries
cargo clippy --all-targets -- -D warnings       # Strict lint
cargo fmt --check                              # Format check

Test Suite

SuiteTestsCoverage
Unit (lib)29Parser, positions, fingerprints, request log, rewrite engine
Integration sweep14All V1 tools end-to-end against fixture files
V3 framework45Route, schema, React, decorator, test, dependency extractors
V4 rewrites12Rewrite preview, import insert, rename, wrap, decorator, signature
Per-tool~50Enclosing nodes, functions/classes, imports/exports, outline, parse, query, positions
Safety & rejection8Path traversal, missing files, unsupported languages, oversize truncation
Architecture lints3No unwrap/expect in library code, no file writes, no LSP dependency
Fuzz2500 random byte sequences across 5 parsers with reproducible seeds
Total~162

Project Structure

src/
├── main.rs                  # Entry point — workspace + transport loop
├── lib.rs                   # Crate root
├── config/                  # Workspace resolver, runtime config, env parsing, validation
├── mcp/                     # JSON-RPC transport, tool registry, ServerContext
├── parser/                  # Tree-sitter wrappers (0.22), line index, query engine
├── languages/               # Per-language node kinds — TS, JS, Python, Go, Rust
├── shared/                  # Position, Range, AST node, errors, V2–V5 type schemas
├── safety/                  # Path resolution, range validation, size limits, truncation
├── text/                    # Position encoding, UTF-16 conversion, indentation, byte budget
├── workspace/               # File scanner, glob matching, .gitignore rules
│
├── extractors/              # V1 — AST extractors (outline, imports, exports, functions, classes)
├── context/                 # V2 — Scope chain, node-at-range, context pack
├── extraction/              # V2 — Calls, literals, member access, template literals
├── metrics/                 # V2 — File/function metrics, nesting depth
├── frameworks/              # V3 — Routes, React, schemas, decorators, tests, dependencies
├── rewrite/                 # V4 — Diff engine, edit overlap, parse-after-rewrite
├── rewrite_tools/           # V4 — Import merge, rename, wrap, decorator, signature
├── analysis/                # V5 — Complexity summary, large node detection, duplicate shapes
├── cache/                   # V5 — TTL caches (parse tree, query, framework results)
├── observability/           # V5 — Request log ring buffer, request tracker
├── ops/                     # V5 — Readiness, liveness, parser status, cache rebuild
├── scan/                    # V5 — Scan registry, cooperative cancellation
│
└── tools/                   # 54 tool handlers — one module per tool

Architectural Boundaries

MCP AST is structural only. It does not own semantic compiler truth.

May DoMust Not Do
Parse files and walk syntax treesCall LSP MCP
Run Tree-sitter queriesResolve semantic references
Extract imports, exports, functions, classes, routes, tests, decoratorsInfer full type information
Chunk files structurallyPerform semantic rename
Preview structural rewrites (read-only, in-memory)Apply patches to disk
Compute structural metrics and complexityExecute shell commands
Cache parse trees, query results, framework extractionsRun tests or typecheck
Scan workspaces with bounded parallelism and cancellation

For semantic analysis, use LSP MCP. For cross-service orchestration, use Agent Skills.


Error Handling

All tools return structured errors:

{
  "error": {
    "code": "path_outside_workspace",
    "message": "path outside workspace: ../outside.ts"
  }
}

V5 adds 16 error codes for cache operations (cache_unavailable, cache_clear_failed), config validation (invalid_runtime_config, config_update_rejected), scan lifecycle (workspace_scan_not_found, scan_timeout), analysis failures (complexity_analysis_failed, duplicate_shape_detection_failed), and health checks (readiness_check_failed, parser_rebuild_failed).


Known Limitations

  • Timeout enforcement: Declared in metadata and enforced at request level; Tree-sitter parse operations are synchronous (no hard interrupt mid-parse).
  • Position encoding: Exact for ASCII, Latin-1, BMP, and surrogate pairs. Complex grapheme clusters may diverge from user-perceived positions.
  • Duplicate detection: Heuristic structural fingerprinting — not a full clone-detection engine. Normalization may produce false positives.
  • Complexity metrics: Node-kind counting heuristics — not compiler-grade cyclomatic complexity. Risk classifications (low/medium/high) are advisory.
Ver o original no GitHub

Bom para

Relacionados