AST MCP SERVER

by yailperalta

Not rated
GitHub

About

ast-mcp-server gives coding agents compact, type-aware access to TypeScript and JavaScript projects. It uses the real compiler project model through ts-morph, so declarations, references, rename locations, and diagnostics come from the AST instead of text-search guesses.

Details

Author
yailperalta
Categories
Productivity, Developer Tools, AI

Supported environment and trust boundary

The local0.9.2release candidate requires Node.js>=22.13.0; its evidence matrix targets exact Node.js 22.13.0 and the current Node.js 24 line. Published v0.8.1 retains its immutable historical Node.js 22.5.0/24 evidence. Managed setup-file publication additionally requires GNU coreutils 9.7mvsupporting--update=none-fail,--exchange,--no-copy, and--no-target-directory, GNU coreutilsln -L -T, procfs descriptor paths at/proc/self/fd, andO_DIRECTORY/O_NOFOLLOW. Other Linux architectures or systems without those filesystem primitives, macOS, and Windows remain unverified.

This is a local stdio server. It runs with the invoking user's filesystem permissions, and clients may request anyproject_rootthat user can access. It does not provide HTTP authentication, sandboxing, tenant isolation, or a remote-service security boundary. Remote, untrusted, and multi-tenant operation is unsupported.

In the local0.9.2release candidate, an absentAST_SYMBOL_INDEX_PERSISTENCEor explicitenabledselects the private SQLite symbol-index cache.disabledis the immediate memory-only rollback.canaryrequires an explicit absolute normalizedAST_SYMBOL_INDEX_CACHE_ROOT. Invalid policy or storage fails closed to compiler-authoritative memory reads with bounded path-free status.

The default cache root is selected fromAST_SYMBOL_INDEX_CACHE_ROOT, thenXDG_CACHE_HOME, thenHOME. Inspect or clear only derived cache artifacts through the bounded CLI:

ast-tool cache inspect ast-tool cache clear --yes

Clear requires exact confirmation, refuses unsafe or active SQLite artifacts, and preserves unknown regular files. No automatic cache GC is enabled.

SeeSupport policyfor the complete platform, runtime, persistence, and operational contract. Report security issues throughSECURITY.md.

Install the published CLI globally while keeping dependency lifecycle scripts disabled:

npm install --global ast-mcp-server --ignore-scripts ast-tool setup

--ignore-scriptsprevents dependencies from runningpreinstall,install, orpostinstallhooks. The package and its current runtime dependencies do not require those hooks.

git clone https://github.com/yailPeralta/ast-mcp-server.git cd ast-mcp-server corepack enable yarn install --immutable yarn build

The repository pins Yarn 4 and commitsenableScripts: falsein.yarnrc.yml. Dependency lifecycle scripts are therefore disabled during installation; switching from npm without this setting would merely change logos while preserving the risk.

The package exposes two executables when installed:

- ast-mcp-server: MCP stdio server.
- ast-tool: batch, skill-installation, and agent-setup CLI.

The installed package opens the interactive wizard with:

From a source checkout, use the Yarn script; it builds first and then opens the same wizard:

The wizard supports exactly six CLI clients in this order: Claude Code, Hermes, OpenCode, Codex CLI, Gemini CLI, and GitHub Copilot CLI. Cursor, Windsurf, Cline, and other editor-integrated clients are intentionally excluded. Compatible detected clients start checked; unavailable or incompatible clients are disabled with a reason. Use Up/Down to move, Space to toggle, Enter to submit, or Escape/Ctrl-C to cancel.
- preflights every selected client's existingastMCP registration, skill destination, and effective managed-guidance destination;
- installs or safely upgrades the bundledstructural-code-editingskill;
- adds one marker-owned activation block to each verified global instruction surface while preserving all user-owned bytes;
- registers this package's MCP server through the agent's official CLI;
- reconnects and verifies the expected tools.

Existing matching registrations, skill files, and managed blocks are unchanged. Conflicting MCP registrations or malformed/unknown managed guidance fail before any write; resolve them explicitly instead of letting a setup script guess. Skill upgrades are automatic only when the installed bytes match an exact SHA-256 admitted from a published npm tarball. Unknown or customized skill bytes fail closed unless--force-skillis explicit. That flag applies only to the skill and cannot override guidance conflicts, unsafe routes, or filesystem races.

Guidance uses each client's verified global instruction contract rather than one universal filename:

The managed range is delimited byast-tool:structural-code-editing guidance v1begin/end markers. Setup updates only that range, preserves the file's UTF-8 BOM, newline style, mode, and all content outside the range, and rejects duplicate, partial, reordered, unknown, symlinked, or non-regular destinations. Writes pin the parent chain, preimage, held temporary inode, and destination. New files use descriptor-bound no-clobber publication; replacements use an atomic same-directory exchange, validate both exchanged identities plus the pinned preimage bytes and mode, and roll the exact pair back when an in-call substitution or same-inode edit is detected. Every completed postimage is reauthenticated before later asset or MCP mutation. Cross-client setup is convergent rather than globally transactional.

Successful setup output uses schemaversion: 2. Each agent reportsmcp,skill, andguidance; physical writes include anassetofskill,guidance, ormcp_config. A complete replay returns every applicable item asunchanged/skill_onlyand an emptyphysical_writesarray. A failed managed publication separatescompleted_writes,possibly_committed,rolled_back,rollback_failed, andpending; an uncertain commit or failed rollback is never reported as untouched and requires inspection plus a fresh replan.

For automation, make the target set and confirmation explicit:

ast-tool setup --agents all --yes ast-tool setup --agents claude,codex --yes

From a source checkout, replaceast-toolwithyarn setupin those commands.

--agents allis resolved only after detection and means every detected compatible client. If any detected client has unknown or incompatible output, setup fails before writes. Explicit IDs are strict and reject unavailable clients. Non-interactive setup requires both--agentsand--yes.

OpenCode 1.18.18 or newer is required. Becauseopencode mcp addignores custom config routing, setup updates onlymcp.astinOPENCODE_CONFIG, thenOPENCODE_CONFIG_DIR/opencode.json, then~/.config/opencode/opencode.json. JSONC comments, unrelated keys, and file mode are preserved. OpenCode's nominally diagnostic config command normalizes both routed config files, so setup runs discovery and verification against disposable copies while retaining the selected config bytes and fails closed if the planned real destination changes. Gemini setup may require trusting the current folder before registration. Diagnostics use a correlation ID and omit command arguments, environment, credentials, and raw provider output; setup failures may include a bounded destination path so the operator can inspect an uncertain or pending write.

The package bundles astructural-code-editingskill that teaches an agent when to use the AST tools, how to minimize context, and how to review mutations safely. Install it for both Claude Code and Hermes with one command:

ast-tool install-skill claude ast-tool install-skill hermes

The default is user scope. It writes to Claude Code's personal skill directory and to the activeHERMES_HOME:

To commit the skill into one project for Claude Code, use project scope:

ast-tool install-skill claude --scope project --project-root /absolute/project

This writes.claude/skills/structural-code-editing/SKILL.mdbelow that project. Project scope is intentionally rejected for Hermes because Hermes skills belong to a profile, not a source repository.

Installation is idempotent. Existing current bytes are left untouched; exact predecessor bytes admitted by the bundled npm-provenance manifest are upgraded safely. Unknown or customized bytes fail closed unless--forceis explicit.install-skillnever writes global guidance or configures MCP. From an unlinked source checkout, replaceast-toolwithyarn node /absolute/path/to/ast-mcp-server/dist/cli.js.

Claude Code detects changes in an existing skill directory live; restart it if the top-level skills directory did not exist when the session started. In Hermes, run/reload-skillsor start a new session, then verify withhermes skills list.

install-skillonly installs the skill; it does not configure the MCP transport. Use the guidedsetupcommand to do both, or complete the client-specific MCP setup below—the instructions are useful, but they have not yet learned to open a stdio socket through positive thinking.

Claude Code supports local stdio MCP servers. After building this repository, register the server with an absolute entrypoint:

AST_MCP_DIR="$(pwd)" claude mcp add --scope user --transport stdio ast -- \ node "$AST_MCP_DIR/dist/index.js" claude mcp get ast

claude mcp get astshould reportStatus: ✔ Connected. The--separator is required: everything after it is the server command, not a Claude Code option.

The example uses--scope user, which makes the server available in all your projects. Use--scope localinstead to register it only for the project from which you run the command. Avoid committing a project-scoped.mcp.jsonthat contains another developer's absolute checkout path.

Start Claude Code inside any TypeScript project with atsconfig.json:

cd /absolute/path/to/your-typescript-project claude

Then ask Claude to use theasttools. For example:

Use the ast MCP server to inspect this project. First search for UserService, then fetch only the exact source of its create method.
Use ast_rename_symbol to prepare renaming UserService.create to createUser. Do not apply it yet. Show me the affected files, diagnostic delta, plan hash, and the complete operation preview.
Apply that operation with ast_apply_operation using the exact operation_id and plan_hash returned by the prepare step.

Project-scoped read and prepare tools requireproject_root. Claude should pass the current project directory or its explicittsconfig.jsonpath. Preview and apply calls instead use the prepared operation coordinates; the MCP server itself contains no repository-specific paths.

Use/mcpinside Claude Code to inspect server status and tools. Outside the session, useclaude mcp list,claude mcp get ast, orclaude mcp remove ast -s user.

hermes mcp add ast --command node --args /absolute/path/to/ast-mcp-server/dist/index.js hermes mcp test ast

Project-scoped tools acceptproject_root, either the project directory or an explicittsconfig.jsonpath. The server contains no repository-specific paths.

Read results use project-relative paths, deterministic ordering, structured MCP output, and pagination where result sets can grow with the project.

ast_exploresupports query, exact file, and exact symbol routes. Its defaultsummaryprofile returns bounded reusable selectors;contextadds selected source andfulladds compiler references. Every response reports freshness, completeness, truncation, unresolved selectors, record limits, and a serialized byte budget. Use the primitive tools when a single exact operation is clearer or when preparing a mutation.

Symbol search is relevance-ranked and defaults to at most 20summaryrecords containingfile, a directly reusableselector,kind, and body-freesignature. Requestdetail: "selectors"for routing coordinates only, ordetail: "full", limit: 100for the v0.4.0 fields/page. References default todetail: "locations"; requestdetail: "context"only when the bounded source line is needed.

ast_search_symbols,ast_find_references,ast_get_impact, andast_get_diagnosticsacceptoutput_format: "toon"for collection-heavy results consumed directly by a model. JSON remains the default and preserves the canonical structured object.

MCP TOON is returned once as structured content shaped like{ "format": "toon", "data": "..." };datais the lossless TOON document. The complete JSON result is not duplicated. These four tools validate their canonical Zod result and verify an encode/decode deep-equality round trip before presentation, but do not advertise a single MCPoutputSchemabecause their successful structured content has two representations.

Do not request TOON for source, outlines, file lists, previews, or mutation results. Checked negative controls show that the MCP envelope makes those shapes larger. TOON is an explicit shape-specific optimization, not a new dialect for every object in sight.

ast-toollets Claude Code and other Bash-capable clients collapse a known structural pipeline into one shell call:

ast-tool validate pipeline.json ast-tool run pipeline.json ast-tool run pipeline.json --output-format toon cat pipeline.json | ast-tool run -
{ "version": 1, "project_root": "/absolute/project", "steps": [ { "id": "search", "tool": "ast_search_symbols", "input": { "query": "UserService", "limit": 20 } }, { "id": "source", "tool": "ast_get_symbol_source", "input": { "file_path": { "$ref": "#/steps/search/symbols/0/file" }, "symbol_path": { "$ref": "#/steps/search/symbols/0/selector" } } } ], "emit": { "$ref": "#/steps/source" } }

A$refis an RFC 6901 JSON Pointer rooted at prior step results. References cannot point forward. Ifemitis omitted, only the final step result is returned; intermediate results remain inside the process.

{ "version": 1, "project_root": "/absolute/project", "limits": { "concurrency": 4 }, "steps": [ { "id": "files", "tool": "ast_list_files", "input": { "limit": 20 } }, { "id": "outlines", "tool": "ast_get_outline", "foreach": { "$ref": "#/steps/files/files" }, "input": { "file_path": { "$item": "" } } } ] }

$itemaccepts an empty pointer for the complete item or/fieldfor one field. Foreach is read-only, order-preserving, fail-fast, and concurrency-bounded.

- Input document: 1 MiB.
- Steps: 50.
- Total tool invocations: 500.
- Foreach items per step: 200.
- Read concurrency: default 4, maximum 16.
- Each retained step result and final serialized output: 10 MiB.
- Total retained intermediate context: 50 MiB.
- One project root per pipeline.
- No branches, eval, embedded JavaScript, while loops, or arbitrary transformations.

ast-mcp-servergives coding agents compact, type-aware access to TypeScript and JavaScript projects. It uses the real compiler project model throughts-morph, so declarations, references, rename locations, and diagnostics come from the AST instead of text-search guesses.

Reads are bounded and structured. Writes follow an explicitprepare → review → applyprotocol with immutable hashes, workspace freshness checks, diagnostic guards, and idempotent receipts.

Coding agents often fall back to two generic operations: read files as plain text and write text patches. That works, but it has three predictable costs:
- Too much context.The agent may load hundreds of lines when it only needs one signature or method body. That consumes model context and tokens without improving the answer.
- Fragile edits.Text patches do not inherently understand declarations, scopes, overloads, or TypeScript diagnostics. A plausible-looking edit can target the wrong construct or introduce a new compiler error.
- Weak cross-file reasoning.Text search can find matching words, but it cannot reliably distinguish two unrelated symbols with the same name. Project-wide references and renames need the compiler's understanding of the program.

This MCP server gives the agent structural code tools in addition to generic file reads and writes. Under the hood,ts-morphuses the TypeScript compiler project model, so the server can reason about declarations and references as code rather than undifferentiated text.

Reads can start with a bounded file slice, a compact outline, or exact source only for the declaration that needs inspection. Mutations are prepared in memory first, compared against baseline diagnostics, and returned as immutable, hash-bound plans. Nothing is written until the caller reviews and explicitly applies the plan.

- Useast_get_filewhen the file path is known and the agent needs exact source lines. It is read-only, uses zero-basedoffsetand boundedlimit, returns one-based line records, a SHA-256 byte hash, file-levelsnapshot_state, and bounded projectfreshnessmetadata (fresh,pending,stale,rebuilding, ordegraded).
- Useast_get_filewithsymbols_only: truewhen only selectors and body-free signatures are needed from one known file.
- Useast_explorewhen the question spans discovery and evidence. Its default summary is bounded; usedetail: "context"for selected source anddetail: "full"for source plus compiler references.
- Useast_get_outlinefor a compact body-free view of a known file without source lines.
- Useast_get_symbol_sourcewhen one declaration or implementation is the required evidence.
- Useast_get_impactwhen the exact symbol is known and bounded direct/transitive compiler relationships are needed; it is read-only evidence, not a mutation plan.

snapshot_state: "fresh"means that the returned file bytes match the synchronized compiler snapshot. The separatefreshnessobject describes the project/session state and preserves causes such as source changes or watcher failure. Neither field means that the project has zero TypeScript diagnostics; useast_get_diagnosticsfor compiler errors and warnings.

The server exposes evidence labels instead of collapsing every result into an unqualified confidence score:

Freshness is orthogonal to TypeScript diagnostics.freshmeans the evidence matches the synchronized snapshot;pending,rebuilding,stale, ordegradedmeans the response must not be presented as current compiler evidence. Read tools expose the state, causes (source_change,config_change,index_failure,watcher_failure, orcompiler_rebuild), and boundedchecked_attimestamp.ast_get_impactrefuses non-fresh compiler relationships.ast_explorereturns the state together withcompleteness,unresolved,budget, andtruncationmetadata rather than silently dropping evidence.

All reads are budgeted. Callers control pagination and, where applicable,max_bytes,reference_limit,max_depth,max_nodes, andmax_edges; responses report the effective limits and whether a record, byte, depth, edge, invocation, or serialization limit truncated the result. A truncated or unresolved result is incomplete evidence, not an empty negative result. The internal test-candidate resolver follows the same rule: it accepts only fresh, exact compiler-backed impact, emits direct/transitive evidence and bounded relationship IDs, and never executes tests or guesses from filenames alone.

- Less context:the agent retrieves the smallest structural unit that answers the question instead of loading the complete file by default.
- Safer changes:exact symbol selection, diagnostic deltas, workspace freshness checks, andprepare → review → applyreduce the failure modes of ad hoc text editing.
- Accurate project-wide operations:references and renames use compiler resolution rather than matching identifier text with grep.

AST-aware editing is not a proof that a change is semantically correct. The safety comes from combining structural selection with diagnostics, exact previews, reviewed hashes, freshness checks, and fail-closed apply semantics.

The included batch benchmark records a 50% reduction in model round-trips and a 94.67% reduction in serialized context for its search-to-source scenario. The result-shaping corpus records a 68.80% reduction in aggregate model-facing TOON tokens while preserving declared selectors/reference coordinates with the same six logical calls. The separate format benchmark records 25.87% across its eligible collection corpus. The context workflow benchmark verifies evidence preservation and call bounds for full-file, primitive, andast_exploreworkflows. These are reproducible localo200k_baseestimates, not universal token, billing, cache, or latency claims.

- Node.js 22.13.0 or newer
- Corepack with Yarn 4.15.0 (pinned bypackageManager)
- A target project with atsconfig.json

Supported environment and trust boundary

The local0.9.2release candidate requires Node.js>=22.13.0; its evidence matrix targets exact Node.js 22.13.0 and the current Node.js 24 line. Published v0.8.1 retains its immutable historical Node.js 22.5.0/24 evidence. Managed setup-file publication additionally requires GNU coreutils 9.7mvsupporting--update=none-fail,--exchange,--no-copy, and--no-target-directory, GNU coreutilsln -L -T, procfs descriptor paths at/proc/self/fd, andO_DIRECTORY/O_NOFOLLOW. Other Linux architectures or systems without those filesystem primitives, macOS, and Windows remain unverified.

This is a local stdio server. It runs with the invoking user's filesystem permissions, and clients may request anyproject_rootthat user can access. It does not provide HTTP authentication, sandboxing, tenant isolation, or a remote-service security boundary. Remote, untrusted, and multi-tenant operation is unsupported.

In the local0.9.2release candidate, an absentAST_SYMBOL_INDEX_PERSISTENCEor explicitenabledselects the private SQLite symbol-index cache.disabledis the immediate memory-only rollback.canaryrequires an explicit absolute normalizedAST_SYMBOL_INDEX_CACHE_ROOT. Invalid policy or storage fails closed to compiler-authoritative memory reads with bounded path-free status.

The default cache root is selected fromAST_SYMBOL_INDEX_CACHE_ROOT, thenXDG_CACHE_HOME, thenHOME. Inspect or clear only derived cache artifacts through the bounded CLI:

ast-tool cache inspect ast-tool cache clear --yes

Clear requires exact confirmation, refuses unsafe or active SQLite artifacts, and preserves unknown regular files. No automatic cache GC is enabled.

SeeSupport policyfor the complete platform, runtime, persistence, and operational contract. Report security issues throughSECURITY.md.

Install the published CLI globally while keeping dependency lifecycle scripts disabled:

npm install --global ast-mcp-server --ignore-scripts ast-tool setup

--ignore-scriptsprevents dependencies from runningpreinstall,install, orpostinstallhooks. The package and its current runtime dependencies do not require those hooks.

git clone https://github.com/yailPeralta/ast-mcp-server.git cd ast-mcp-server corepack enable yarn install --immutable yarn build

The repository pins Yarn 4 and commitsenableScripts: falsein.yarnrc.yml. Dependency lifecycle scripts are therefore disabled during installation; switching from npm without this setting would merely change logos while preserving the risk.

The package exposes two executables when installed:

- ast-mcp-server: MCP stdio server.
- ast-tool: batch, skill-installation, and agent-setup CLI.

The installed package opens the interactive wizard with:

From a source checkout, use the Yarn script; it builds first and then opens the same wizard:

The wizard supports exactly six CLI clients in this order: Claude Code, Hermes, OpenCode, Codex CLI, Gemini CLI, and GitHub Copilot CLI. Cursor, Windsurf, Cline, and other editor-integrated clients are intentionally excluded. Compatible detected clients start checked; unavailable or incompatible clients are disabled with a reason. Use Up/Down to move, Space to toggle, Enter to submit, or Escape/Ctrl-C to cancel.
- preflights every selected client's existingastMCP registration, skill destination, and effective managed-guidance destination;
- installs or safely upgrades the bundledstructural-code-editingskill;
- adds one marker-owned activation block to each verified global instruction surface while preserving all user-owned bytes;
- registers this package's MCP server through the agent's official CLI;
- reconnects and verifies the expected tools.

Existing matching registrations, skill files, and managed blocks are unchanged. Conflicting MCP registrations or malformed/unknown managed guidance fail before any write; resolve them explicitly instead of letting a setup script guess. Skill upgrades are automatic only when the installed bytes match an exact SHA-256 admitted from a published npm tarball. Unknown or customized skill bytes fail closed unless--force-skillis explicit. That flag applies only to the skill and cannot override guidance conflicts, unsafe routes, or filesystem races.

Guidance uses each client's verified global instruction contract rather than one universal filename:

The managed range is delimited byast-tool:structural-code-editing guidance v1begin/end markers. Setup updates only that range, preserves the file's UTF-8 BOM, newline style, mode, and all content outside the range, and rejects duplicate, partial, reordered, unknown, symlinked, or non-regular destinations. Writes pin the parent chain, preimage, held temporary inode, and destination. New files use descriptor-bound no-clobber publication; replacements use an atomic same-directory exchange, validate both exchanged identities plus the pinned preimage bytes and mode, and roll the exact pair back when an in-call substitution or same-inode edit is detected. Every completed postimage is reauthenticated before later asset or MCP mutation. Cross-client setup is convergent rather than globally transactional.

Successful setup output uses schemaversion: 2. Each agent reportsmcp,skill, andguidance; physical writes include anassetofskill,guidance, ormcp_config. A complete replay returns every applicable item asunchanged/skill_onlyand an emptyphysical_writesarray. A failed managed publication separatescompleted_writes,possibly_committed,rolled_back,rollback_failed, andpending; an uncertain commit or failed rollback is never reported as untouched and requires inspection plus a fresh replan.

For automation, make the target set and confirmation explicit:

ast-tool setup --agents all --yes ast-tool setup --agents claude,codex --yes

From a source checkout, replaceast-toolwithyarn setupin those commands.

--agents allis resolved only after detection and means every detected compatible client. If any detected client has unknown or incompatible output, setup fails before writes. Explicit IDs are strict and reject unavailable clients. Non-interactive setup requires both--agentsand--yes.

OpenCode 1.18.18 or newer is required. Becauseopencode mcp addignores custom config routing, setup updates onlymcp.astinOPENCODE_CONFIG, thenOPENCODE_CONFIG_DIR/opencode.json, then~/.config/opencode/opencode.json. JSONC comments, unrelated keys, and file mode are preserved. OpenCode's nominally diagnostic config command normalizes both routed config files, so setup runs discovery and verification against disposable copies while retaining the selected config bytes and fails closed if the planned real destination changes. Gemini setup may require trusting the current folder before registration. Diagnostics use a correlation ID and omit command arguments, environment, credentials, and raw provider output; setup failures may include a bounded destination path so the operator can inspect an uncertain or pending write.

The package bundles astructural-code-editingskill that teaches an agent when to use the AST tools, how to minimize context, and how to review mutations safely. Install it for both Claude Code and Hermes with one command:

ast-tool install-skill claude ast-tool install-skill hermes

The default is user scope. It writes to Claude Code's personal skill directory and to the activeHERMES_HOME:

To commit the skill into one project for Claude Code, use project scope:

ast-tool install-skill claude --scope project --project-root /absolute/project

This writes.claude/skills/structural-code-editing/SKILL.mdbelow that project. Project scope is intentionally rejected for Hermes because Hermes skills belong to a profile, not a source repository.

Installation is idempotent. Existing current bytes are left untouched; exact predecessor bytes admitted by the bundled npm-provenance manifest are upgraded safely. Unknown or customized bytes fail closed unless--forceis explicit.install-skillnever writes global guidance or configures MCP. From an unlinked source checkout, replaceast-toolwithyarn node /absolute/path/to/ast-mcp-server/dist/cli.js.

Claude Code detects changes in an existing skill directory live; restart it if the top-level skills directory did not exist when the session started. In Hermes, run/reload-skillsor start a new session, then verify withhermes skills list.

install-skillonly installs the skill; it does not configure the MCP transport. Use the guidedsetupcommand to do both, or complete the client-specific MCP setup below—the instructions are useful, but they have not yet learned to open a stdio socket through positive thinking.

Claude Code supports local stdio MCP servers. After building this repository, register the server with an absolute entrypoint:

AST_MCP_DIR="$(pwd)" claude mcp add --scope user --transport stdio ast -- \ node "$AST_MCP_DIR/dist/index.js" claude mcp get ast

claude mcp get astshould reportStatus: ✔ Connected. The--separator is required: everything after it is the server command, not a Claude Code option.

The example uses--scope user, which makes the server available in all your projects. Use--scope localinstead to register it only for the project from which you run the command. Avoid committing a project-scoped.mcp.jsonthat contains another developer's absolute checkout path.

Start Claude Code inside any TypeScript project with atsconfig.json:

cd /absolute/path/to/your-typescript-project claude

Then ask Claude to use theasttools. For example:

Use the ast MCP server to inspect this project. First search for UserService, then fetch only the exact source of its create method.
Use ast_rename_symbol to prepare renaming UserService.create to createUser. Do not apply it yet. Show me the affected files, diagnostic delta, plan hash, and the complete operation preview.
Apply that operation with ast_apply_operation using the exact operation_id and plan_hash returned by the prepare step.

Project-scoped read and prepare tools requireproject_root. Claude should pass the current project directory or its explicittsconfig.jsonpath. Preview and apply calls instead use the prepared operation coordinates; the MCP server itself contains no repository-specific paths.

Use/mcpinside Claude Code to inspect server status and tools. Outside the session, useclaude mcp list,claude mcp get ast, orclaude mcp remove ast -s user.

hermes mcp add ast --command node --args /absolute/path/to/ast-mcp-server/dist/index.js hermes mcp test ast

Project-scoped tools acceptproject_root, either the project directory or an explicittsconfig.jsonpath. The server contains no repository-specific paths.

Read results use project-relative paths, deterministic ordering, structured MCP output, and pagination where result sets can grow with the project.

ast_exploresupports query, exact file, and exact symbol routes. Its defaultsummaryprofile returns bounded reusable selectors;contextadds selected source andfulladds compiler references. Every response reports freshness, completeness, truncation, unresolved selectors, record limits, and a serialized byte budget. Use the primitive tools when a single exact operation is clearer or when preparing a mutation.

Symbol search is relevance-ranked and defaults to at most 20summaryrecords containingfile, a directly reusableselector,kind, and body-freesignature. Requestdetail: "selectors"for routing coordinates only, ordetail: "full", limit: 100for the v0.4.0 fields/page. References default todetail: "locations"; requestdetail: "context"only when the bounded source line is needed.

ast_search_symbols,ast_find_references,ast_get_impact, andast_get_diagnosticsacceptoutput_format: "toon"for collection-heavy results consumed directly by a model. JSON remains the default and preserves the canonical structured object.

MCP TOON is returned once as structured content shaped like{ "format": "toon", "data": "..." };datais the lossless TOON document. The complete JSON result is not duplicated. These four tools validate their canonical Zod result and verify an encode/decode deep-equality round trip before presentation, but do not advertise a single MCPoutputSchemabecause their successful structured content has two representations.

Do not request TOON for source, outlines, file lists, previews, or mutation results. Checked negative controls show that the MCP envelope makes those shapes larger. TOON is an explicit shape-specific optimization, not a new dialect for every object in sight.

ast-toollets Claude Code and other Bash-capable clients collapse a known structural pipeline into one shell call:

ast-tool validate pipeline.json ast-tool run pipeline.json ast-tool run pipeline.json --output-format toon cat pipeline.json | ast-tool run -
{ "version": 1, "project_root": "/absolute/project", "steps": [ { "id": "search", "tool": "ast_search_symbols", "input": { "query": "UserService", "limit": 20 } }, { "id": "source", "tool": "ast_get_symbol_source", "input": { "file_path": { "$ref": "#/steps/search/symbols/0/file" }, "symbol_path": { "$ref": "#/steps/search/symbols/0/selector" } } } ], "emit": { "$ref": "#/steps/source" } }

A$refis an RFC 6901 JSON Pointer rooted at prior step results. References cannot point forward. Ifemitis omitted, only the final step result is returned; intermediate results remain inside the process.

{ "version": 1, "project_root": "/absolute/project", "limits": { "concurrency": 4 }, "steps": [ { "id": "files", "tool": "ast_list_files", "input": { "limit": 20 } }, { "id": "outlines", "tool": "ast_get_outline", "foreach": { "$ref": "#/steps/files/files" }, "input": { "file_path": { "$item": "" } } } ] }

$itemaccepts an empty pointer for the complete item or/fieldfor one field. Foreach is read-only, order-preserving, fail-fast, and concurrency-bounded.

- Input document: 1 MiB.
- Steps: 50.
- Total tool invocations: 500.
- Foreach items per step: 200.
- Read concurrency: default 4, maximum 16.
- Each retained step result and final serialized output: 10 MiB.
- Total retained intermediate context: 50 MiB.
- One project root per pipeline.
- No branches, eval, embedded JavaScript, while loops, or arbitrary transformations.

No reviews yet — be the first

Sign in to leave a review

Use Google, GitHub, or an email account so ratings stay tied to real people.

Email sign in

No reviews posted yet.