ast-mcp-server 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +63 -14
  3. package/SECURITY.md +31 -0
  4. package/dist/cli.js +0 -0
  5. package/dist/index.js +129 -10
  6. package/dist/server.js +25 -2
  7. package/dist/services/agent-setup.js +36 -117
  8. package/dist/services/agent-targets.js +122 -0
  9. package/dist/services/context-builder.js +262 -0
  10. package/dist/services/diagnostics.js +10 -5
  11. package/dist/services/file-fingerprints.js +104 -0
  12. package/dist/services/file-snapshot.js +103 -0
  13. package/dist/services/impact.js +334 -0
  14. package/dist/services/operations.js +343 -254
  15. package/dist/services/outline.js +94 -21
  16. package/dist/services/pagination.js +10 -4
  17. package/dist/services/project-operation-scheduler.js +475 -0
  18. package/dist/services/project-status.js +134 -52
  19. package/dist/services/project-watcher.js +230 -0
  20. package/dist/services/project.js +646 -66
  21. package/dist/services/public-errors.js +255 -0
  22. package/dist/services/references.js +54 -0
  23. package/dist/services/relationships.js +1198 -0
  24. package/dist/services/request-context.js +42 -0
  25. package/dist/services/runtime-activity.js +65 -0
  26. package/dist/services/runtime-logger.js +50 -0
  27. package/dist/services/runtime-policy.js +47 -0
  28. package/dist/services/setup-wizard.js +4 -7
  29. package/dist/services/shutdown.js +93 -0
  30. package/dist/services/symbol-index-limits.js +5 -0
  31. package/dist/services/symbol-index-order.js +13 -0
  32. package/dist/services/symbol-index-policy.js +91 -0
  33. package/dist/services/symbol-index-sqlite.js +850 -0
  34. package/dist/services/symbol-index.js +447 -0
  35. package/dist/services/symbols.js +430 -47
  36. package/dist/services/test-candidates.js +209 -0
  37. package/dist/services/workspace.js +18 -7
  38. package/dist/tools/apply_operation.js +8 -4
  39. package/dist/tools/explore.js +176 -0
  40. package/dist/tools/find_references.js +17 -55
  41. package/dist/tools/get_diagnostics.js +10 -7
  42. package/dist/tools/get_file.js +107 -0
  43. package/dist/tools/get_impact.js +134 -0
  44. package/dist/tools/get_operation_preview.js +7 -4
  45. package/dist/tools/get_outline.js +8 -6
  46. package/dist/tools/get_project_status.js +77 -8
  47. package/dist/tools/get_symbol_source.js +8 -6
  48. package/dist/tools/list_files.js +11 -6
  49. package/dist/tools/rename_symbol.js +6 -4
  50. package/dist/tools/replace_symbol_body.js +6 -4
  51. package/dist/tools/result.js +27 -17
  52. package/dist/tools/scaffold_class.js +6 -4
  53. package/dist/tools/search_symbols.js +15 -63
  54. package/docs/support.md +80 -0
  55. package/package.json +18 -6
  56. package/skills/structural-code-editing/SKILL.md +42 -8
  57. package/benchmark/README.md +0 -129
package/CHANGELOG.md CHANGED
@@ -4,6 +4,40 @@ All notable changes to this project will be documented in this file.
4
4
 
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [0.7.0] — release candidate (unreleased, 2026-08-11)
8
+
9
+ ### Added
10
+
11
+ - Compiler-backed, freshness-aware impact traversal with bounded direct/transitive relationships and fail-closed test-candidate evidence.
12
+ - Opt-in SQLite symbol-index canary with corruption/write-failure fallback, restart reuse, explicit recovery, and bounded project-status observability; default and reserved `enabled` policies remain memory-only.
13
+ - Bounded per-project scheduling, cancellation/deadline semantics, idempotent graceful shutdown, and a closed public-error envelope with correlation IDs.
14
+ - Deterministic Linux x64 production-readiness evidence across Node.js 22.5.0 and Node.js 24 for this repository and `x-scraper`.
15
+ - Exact-SHA staged release workflows for `next` publication, public-registry verification, and separately authorized `latest` promotion.
16
+
17
+ ### Changed
18
+
19
+ - Symbol search and impact discovery now remain compiler-authoritative while applying deterministic limits before globally materializing expensive relationships.
20
+ - The supported release target is explicitly Linux x64 with the required GNU coreutils publication primitive; other platforms and architectures remain unverified.
21
+ - The package now ships its support and security policies alongside the README, changelog, binaries, and bundled structural-editing skill.
22
+
23
+ ### Security
24
+
25
+ - Release preparation, GitHub authorization, OIDC publication, and npm-token promotion use physically separated least-authority phases with lifecycle scripts disabled.
26
+ - Workflow actions, permissions, inputs, conditions, commands, environments, and credential placement are checked against a closed immutable policy.
27
+ - Package publication binds exact tarball bytes and packed `gitHead` to the authorized SHA; consumer verification independently proves preview/apply/replay postimages and no-write failure paths.
28
+ - Public MCP and stderr errors are bounded and sanitized against source, path, stack, environment, and credential disclosure.
29
+
30
+ ## [0.6.0] - 2026-08-05
31
+
32
+ ### Added
33
+
34
+ - Read-only `ast_get_file` with bounded exact source lines, SHA-256 byte hashes, compiler snapshot state, and `symbols_only` body-free output.
35
+ - `ast_get_file` now also returns bounded project freshness metadata, distinguishing fresh, pending, stale, rebuilding, and degraded session state from the file-level snapshot state.
36
+ - Project-scoped file snapshot validation with UTF-8 checks, traversal rejection, symlink containment checks, and ambiguous-path failures.
37
+ - Read-only `ast_explore` with query/file/symbol routing, progressive source and compiler-reference evidence, freshness/completeness metadata, unresolved selectors, and serialized byte budgets.
38
+ - Public trust guidance for compiler, syntax, heuristic and derived-index evidence, including the fail-closed rules for stale/degraded reads and compiler-backed test candidates.
39
+ - A deterministic context workflow benchmark comparing full-file, primitive, and composed exploration workflows.
40
+
7
41
  ## [0.5.1] - 2026-08-05
8
42
 
9
43
  ### Added
@@ -16,6 +50,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
16
50
 
17
51
  - Source synchronization verifies stability across refresh, snapshot, refresh, and verification before reporting fresh state.
18
52
  - Phase 1 keeps the symbol index disabled while exposing explicit stale/degraded recovery state.
53
+ - Documentation now distinguishes file snapshot freshness from project freshness, reports bounded read budgets/truncation, and defines the prepare-review-apply mutation boundary.
19
54
 
20
55
  ### Security
21
56
 
@@ -84,6 +119,7 @@ Initial public release.
84
119
  - Apply rejects stale workspaces, changed configs/sources, mismatched plan hashes, unsafe plan files, conflicting MCP registrations, and conflicting skill content.
85
120
  - Inputs, outputs, operation stores, subprocesses, batch fan-out, plan lifetime, and filesystem access are bounded.
86
121
 
122
+ [0.6.0]: https://github.com/yailPeralta/ast-mcp-server/releases/tag/v0.6.0
87
123
  [0.5.1]: https://github.com/yailPeralta/ast-mcp-server/releases/tag/v0.5.1
88
124
  [0.5.0]: https://github.com/yailPeralta/ast-mcp-server/releases/tag/v0.5.0
89
125
  [0.4.0]: https://github.com/yailPeralta/ast-mcp-server/releases/tag/v0.4.0
package/README.md CHANGED
@@ -1,8 +1,12 @@
1
+ <p align="center">
2
+ <img src="assets/header.jpg" alt="Abstract network of connected code symbols with the text AST MCP Server." width="100%" />
3
+ </p>
4
+
1
5
  # ast-mcp-server
2
6
 
3
7
  [![CI](https://github.com/yailPeralta/ast-mcp-server/actions/workflows/ci.yml/badge.svg)](https://github.com/yailPeralta/ast-mcp-server/actions/workflows/ci.yml)
4
8
  [![npm version](https://img.shields.io/npm/v/ast-mcp-server.svg)](https://www.npmjs.com/package/ast-mcp-server)
5
- [![Node.js 20.19+](https://img.shields.io/badge/Node.js-20.19%2B-339933?logo=node.js&logoColor=white)](https://nodejs.org/)
9
+ [![Node.js 22.5+](https://img.shields.io/badge/Node.js-22.5%2B-339933?logo=node.js&logoColor=white)](https://nodejs.org/)
6
10
  [![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg)](LICENSE)
7
11
 
8
12
  `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.
@@ -21,15 +25,44 @@ Coding agents often fall back to two generic operations: read files as plain tex
21
25
 
22
26
  This MCP server gives the agent structural code tools in addition to generic file reads and writes. Under the hood, `ts-morph` uses the TypeScript compiler project model, so the server can reason about declarations and references as code rather than undifferentiated text.
23
27
 
24
- | Need | Structural operation | Returned scope |
25
- | ------------------------------ | ------------------------- | ----------------------------------------------------- |
26
- | Understand a file | `ast_get_outline` | Signatures without implementation bodies |
27
- | Inspect one declaration | `ast_get_symbol_source` | Exact source for one function, method, class, or type |
28
- | Find usages across the project | `ast_find_references` | Compiler-resolved reference locations |
29
- | Rename a symbol everywhere | `ast_rename_symbol` | A reviewed project-wide rename plan |
30
- | Change one implementation | `ast_replace_symbol_body` | A body-only plan that preserves the declaration |
28
+ | Need | Structural operation | Returned scope |
29
+ | ------------------------------ | ------------------------- | ---------------------------------------------------------- |
30
+ | Read a bounded file | `ast_get_file` | Exact selected source lines, hashes, and bounded freshness |
31
+ | Explore bounded context | `ast_explore` | Ranked selectors plus optional source and references |
32
+ | Understand a file | `ast_get_outline` | Signatures without implementation bodies |
33
+ | Inspect one declaration | `ast_get_symbol_source` | Exact source for one function, method, class, or type |
34
+ | Find usages across the project | `ast_find_references` | Compiler-resolved reference locations |
35
+ | Understand symbol impact | `ast_get_impact` | Bounded direct/transitive compiler-backed relationships |
36
+ | Rename a symbol everywhere | `ast_rename_symbol` | A reviewed project-wide rename plan |
37
+ | Change one implementation | `ast_replace_symbol_body` | A body-only plan that preserves the declaration |
38
+
39
+ 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.
40
+
41
+ ### Choosing a read tool
42
+
43
+ - Use `ast_get_file` when the file path is known and the agent needs exact source lines. It is read-only, uses zero-based `offset` and bounded `limit`, returns one-based line records, a SHA-256 byte hash, file-level `snapshot_state`, and bounded project `freshness` metadata (`fresh`, `pending`, `stale`, `rebuilding`, or `degraded`).
44
+ - Use `ast_get_file` with `symbols_only: true` when only selectors and body-free signatures are needed from one known file.
45
+ - Use `ast_explore` when the question spans discovery and evidence. Its default summary is bounded; use `detail: "context"` for selected source and `detail: "full"` for source plus compiler references.
46
+ - Use `ast_get_outline` for a compact body-free view of a known file without source lines.
47
+ - Use `ast_get_symbol_source` when one declaration or implementation is the required evidence.
48
+ - Use `ast_get_impact` when the exact symbol is known and bounded direct/transitive compiler relationships are needed; it is read-only evidence, not a mutation plan.
49
+
50
+ `snapshot_state: "fresh"` means that the returned file bytes match the synchronized compiler snapshot. The separate `freshness` object 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; use `ast_get_diagnostics` for compiler errors and warnings.
51
+
52
+ ### Trust, freshness and completeness
53
+
54
+ The server exposes evidence labels instead of collapsing every result into an unqualified confidence score:
55
+
56
+ | Label | Meaning | Safe use |
57
+ | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
58
+ | `provenance: "compiler"`, `confidence: "exact"`, `resolution: "resolved"`, `freshness.state: "fresh"` | A relationship resolved by the active TypeScript compiler snapshot. This is the only combination that sets `compiler_authoritative: true`. | May support bounded impact evidence and compiler-backed test candidates. |
59
+ | `provenance: "syntax"` | Syntax or AST structure without semantic symbol resolution. | Navigation and structural context only; not proof that two symbols are related. |
60
+ | `provenance: "heuristic"` | A convention or name-based suggestion. | Discovery hints only; never mutation authority or a compiler-backed test candidate. |
61
+ | index evidence | A derived query accelerator, not compiler authority. The current production status reports the index as disabled; any future ready index still requires compiler selector validation and a compiler fallback. | Faster routing only; stale, missing or mismatched entries must fail closed or fall back to the compiler. |
31
62
 
32
- Reads can start with a compact outline and fetch exact source only when needed. 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.
63
+ Freshness is orthogonal to TypeScript diagnostics. `fresh` means the evidence matches the synchronized snapshot; `pending`, `rebuilding`, `stale`, or `degraded` means the response must not be presented as current compiler evidence. Read tools expose the state, causes (`source_change`, `config_change`, `index_failure`, `watcher_failure`, or `compiler_rebuild`), and bounded `checked_at` timestamp. `ast_get_impact` refuses non-fresh compiler relationships. `ast_explore` returns the state together with `completeness`, `unresolved`, `budget`, and `truncation` metadata rather than silently dropping evidence.
64
+
65
+ All reads are budgeted. Callers control pagination and, where applicable, `max_bytes`, `reference_limit`, `max_depth`, `max_nodes`, and `max_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.
33
66
 
34
67
  ## Why this helps
35
68
 
@@ -39,14 +72,24 @@ Reads can start with a compact outline and fetch exact source only when needed.
39
72
 
40
73
  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.
41
74
 
42
- 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. These are reproducible local `o200k_base` estimates, not universal token, billing, cache, or latency claims.
75
+ 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, and `ast_explore` workflows. These are reproducible local `o200k_base` estimates, not universal token, billing, cache, or latency claims.
43
76
 
44
77
  ## Requirements
45
78
 
46
- - Node.js 20.19 or newer
79
+ - Node.js 22.5.0 or newer
47
80
  - Corepack with Yarn 4.15.0 (pinned by `packageManager`)
48
81
  - A target project with a `tsconfig.json`
49
82
 
83
+ ## Supported environment and trust boundary
84
+
85
+ The supported v0.7.0 target is Linux x64 with GNU coreutils `mv` supporting `--update=none-fail`, under Node.js 22.5.0 and the current Node.js 24 line. The production-readiness matrix covers both runtimes on that target; the Node 22.5 persistence canary requires `--experimental-sqlite`. Other Linux architectures or systems without the required GNU `mv`, macOS, and Windows are unverified until they pass equivalent filesystem, process, MCP/CLI/package, and mutation gates.
86
+
87
+ This is a local stdio server. It runs with the invoking user's filesystem permissions, and clients may request any `project_root` that 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.
88
+
89
+ Symbol-index persistence remains disabled by default. `AST_SYMBOL_INDEX_PERSISTENCE=canary` additionally requires an explicit absolute `AST_SYMBOL_INDEX_CACHE_ROOT`; the reserved `enabled` mode fails closed to memory-only with `enabled_not_released`.
90
+
91
+ See [Support policy](docs/support.md) for the complete platform, runtime, persistence, and operational contract. Report security issues through [SECURITY.md](SECURITY.md).
92
+
50
93
  ## Install
51
94
 
52
95
  Install the published CLI globally while keeping dependency lifecycle scripts disabled:
@@ -217,10 +260,14 @@ Project-scoped tools accept `project_root`, either the project directory or an e
217
260
  | Tool | Purpose | Mutates files |
218
261
  | --------------------------- | -------------------------------------------------------------------- | ------------- |
219
262
  | `ast_list_files` | Paginated, project-relative source file inventory | No |
263
+ | `ast_get_project_status` | Read-only compiler, freshness, index, and operation status | No |
264
+ | `ast_explore` | Bounded composed selectors, source evidence, and references | No |
265
+ | `ast_get_file` | Bounded exact source lines, byte hash, and snapshot state | No |
220
266
  | `ast_get_outline` | Body-free declaration signatures; detailed symbol metadata is opt-in | No |
221
267
  | `ast_get_symbol_source` | Exact source for one declaration | No |
222
268
  | `ast_search_symbols` | Paginated structural symbol discovery | No |
223
269
  | `ast_find_references` | Compiler-resolved references with bounded context | No |
270
+ | `ast_get_impact` | Bounded incoming/outgoing compiler-backed impact evidence | No |
224
271
  | `ast_get_diagnostics` | Project- or file-scoped TypeScript diagnostics | No |
225
272
  | `ast_rename_symbol` | Prepare a project-wide rename | No |
226
273
  | `ast_replace_symbol_body` | Prepare a body-only replacement while preserving the signature | No |
@@ -230,13 +277,15 @@ Project-scoped tools accept `project_root`, either the project directory or an e
230
277
 
231
278
  Read results use project-relative paths, deterministic ordering, structured MCP output, and pagination where result sets can grow with the project.
232
279
 
280
+ `ast_explore` supports query, exact file, and exact symbol routes. Its default `summary` profile returns bounded reusable selectors; `context` adds selected source and `full` adds 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.
281
+
233
282
  Symbol search is relevance-ranked and defaults to at most 20 `summary` records containing `file`, a directly reusable `selector`, `kind`, and body-free `signature`. Request `detail: "selectors"` for routing coordinates only, or `detail: "full", limit: 100` for the v0.4.0 fields/page. References default to `detail: "locations"`; request `detail: "context"` only when the bounded source line is needed.
234
283
 
235
284
  ### Optional TOON results
236
285
 
237
- `ast_search_symbols`, `ast_find_references`, and `ast_get_diagnostics` accept `output_format: "toon"` for collection-heavy results consumed directly by a model. JSON remains the default and preserves the canonical structured object.
286
+ `ast_search_symbols`, `ast_find_references`, `ast_get_impact`, and `ast_get_diagnostics` accept `output_format: "toon"` for collection-heavy results consumed directly by a model. JSON remains the default and preserves the canonical structured object.
238
287
 
239
- MCP TOON is returned once as structured content shaped like `{ "format": "toon", "data": "..." }`; `data` is the lossless TOON document. The complete JSON result is not duplicated. These three tools validate their canonical Zod result and verify an encode/decode deep-equality round trip before presentation, but do not advertise a single MCP `outputSchema` because their successful structured content has two representations.
288
+ MCP TOON is returned once as structured content shaped like `{ "format": "toon", "data": "..." }`; `data` is 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 MCP `outputSchema` because their successful structured content has two representations.
240
289
 
241
290
  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.
242
291
 
@@ -392,7 +441,7 @@ The batch benchmark compares two separate client calls with one batch invocation
392
441
 
393
442
  The format benchmark runs real tools against this repository plus deterministic reference/diagnostic fixtures. It checks JSON→TOON→value equality, UTF-8 bytes, `gpt-tokenizer` `o200k_base` estimates, encode/decode latency, the actual MCP envelope, tool metadata, and negative controls. Its checked result is `benchmark/results/self-formats.json`; local tokenizer estimates do not establish provider-side billing or cache savings. See `benchmark/README.md` for methodology and limitations.
394
443
 
395
- The result-shaping benchmark compares the v0.4.0-compatible `full/100/context` profiles with the new public defaults across exact-name, exact-path, prefix, broad-substring, and multi-file-reference tasks. It fails on missing evidence, extra logical calls, fewer than 11 tools, or less than 35% aggregate TOON token reduction. Its checked result is `benchmark/results/self-result-shapes.json`.
444
+ The result-shaping benchmark compares the v0.4.0-compatible `full/100/context` profiles with the new public defaults across exact-name, exact-path, prefix, broad-substring, and multi-file-reference tasks. It fails on missing evidence, extra required calls, fewer than the benchmark's required minimum tool surface, or less than 35% aggregate TOON token reduction. Its checked result is `benchmark/results/self-result-shapes.json`.
396
445
 
397
446
  ## Scope
398
447
 
package/SECURITY.md ADDED
@@ -0,0 +1,31 @@
1
+ # Security Policy
2
+
3
+ ## Supported versions
4
+
5
+ Security fixes are provided for the latest published minor release and the current `main` development line. During the v0.7.0 release-candidate cycle, the support window is:
6
+
7
+ | Version | Supported |
8
+ | ---------------------------------- | ---------------------------------- |
9
+ | `main` / v0.7.0 release candidates | Yes |
10
+ | 0.6.x | Yes, until v0.7.0 becomes `latest` |
11
+ | 0.5.x and earlier | No |
12
+
13
+ This project supports trusted single-user local stdio use. The current v0.7.0 target supports Linux x64 only when GNU coreutils `mv` provides `--update=none-fail`, with Node.js 22.5.0 or the current Node.js 24 line. Other Linux architectures, systems without that primitive, macOS and Windows are unverified. Remote, untrusted and multi-tenant use is outside the supported security boundary.
14
+
15
+ ## Reporting a vulnerability
16
+
17
+ Do not open a public issue for a suspected vulnerability. Email `yaildeveloper@gmail.com` with the subject `ast-mcp-server security report` and include:
18
+
19
+ - affected version or commit;
20
+ - impact and required attacker access;
21
+ - minimal reproduction steps;
22
+ - whether source mutation, credentials or local paths may have been exposed;
23
+ - a safe way to coordinate follow-up.
24
+
25
+ Do not include live API keys, tokens, credentials, private source bodies or production connection strings. Replace any necessary secret-shaped evidence with `[REDACTED]` and use a disposable fixture where possible.
26
+
27
+ A maintainer will acknowledge the report within five business days and provide an initial triage result within ten business days. Remediation and coordinated disclosure timing depend on severity, exploitability and release impact; no universal fix deadline is promised.
28
+
29
+ ## Disclosure and scope
30
+
31
+ Please allow time for a fix and package readback before public disclosure. Reports are evaluated against the documented local stdio trust boundary: the server runs with the invoking user's filesystem permissions and is not an OS sandbox. Vulnerabilities that cross the compiler-authority, reviewed mutation, path-containment, credential-redaction, package-provenance or release-integrity boundaries remain in scope.
package/dist/cli.js CHANGED
File without changes
package/dist/index.js CHANGED
@@ -1,13 +1,132 @@
1
1
  #!/usr/bin/env node
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
2
5
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
6
  import { createServer } from "./server.js";
4
- async function main() {
5
- const server = createServer();
6
- const transport = new StdioServerTransport();
7
- await server.connect(transport);
8
- console.error("ast-mcp-server running over stdio.");
9
- }
10
- main().catch((error) => {
11
- console.error("Fatal ast-mcp-server error:", error);
12
- process.exit(1);
13
- });
7
+ import { beginProjectShutdown, closeDrainedProjectSessions, getProjectRuntimeShutdownSnapshot, prepareProjectRuntimeForStartup, waitForProjectCompletionCriticalOperationsToDrain, waitForProjectOperationsToDrain, } from "./services/project.js";
8
+ import { RuntimeActivityTracker } from "./services/runtime-activity.js";
9
+ import { readRuntimePolicy } from "./services/runtime-policy.js";
10
+ import { emitIncompleteShutdownEvent, ShutdownCoordinator, } from "./services/shutdown.js";
11
+ function emitShutdownFailureEvent() {
12
+ process.stderr.write(`${JSON.stringify({ event: "shutdown_failed", version: 1 })}\n`);
13
+ }
14
+ export async function runStdioServer(options = {}) {
15
+ if (options.server && !options.runtimeActivity) {
16
+ throw new Error("An injected MCP server requires its runtime activity tracker.");
17
+ }
18
+ prepareProjectRuntimeForStartup();
19
+ const runtimeActivity = options.runtimeActivity ?? new RuntimeActivityTracker();
20
+ runtimeActivity.prepareForStartup();
21
+ const server = options.server ?? createServer({ runtimeActivity });
22
+ const transport = options.transport ?? new StdioServerTransport();
23
+ const send = transport.send.bind(transport);
24
+ transport.send = (message, sendOptions) => runtimeActivity.trackSend(() => send(message, sendOptions));
25
+ const runtimePolicy = options.runtimePolicy ?? readRuntimePolicy();
26
+ const installProcessHandlers = options.installProcessHandlers ?? true;
27
+ const exit = options.exit ?? ((code) => process.exit(code));
28
+ const protocol = server.server;
29
+ const previousTransportClose = protocol.onclose;
30
+ let listenersInstalled = false;
31
+ let terminalHandlerInstalled = false;
32
+ const onSigint = () => requestFromRuntime("sigint");
33
+ const onSigterm = () => requestFromRuntime("sigterm");
34
+ const onStdinEnd = () => requestFromRuntime("stdin_eof");
35
+ const onStdinClose = () => requestFromRuntime("stdin_eof");
36
+ const onTransportClose = () => {
37
+ previousTransportClose?.();
38
+ requestFromRuntime("transport_closed");
39
+ };
40
+ const removeLifecycleListeners = () => {
41
+ if (listenersInstalled) {
42
+ process.off("SIGINT", onSigint);
43
+ process.off("SIGTERM", onSigterm);
44
+ process.stdin.off("end", onStdinEnd);
45
+ process.stdin.off("close", onStdinClose);
46
+ listenersInstalled = false;
47
+ }
48
+ if (protocol.onclose === onTransportClose)
49
+ protocol.onclose = previousTransportClose;
50
+ };
51
+ const coordinator = new ShutdownCoordinator({
52
+ drainTimeoutMs: runtimePolicy.shutdownDrainTimeoutMs,
53
+ stopAdmissionAndCancel: () => {
54
+ runtimeActivity.beginShutdown();
55
+ return beginProjectShutdown();
56
+ },
57
+ getDrainSnapshot: getProjectRuntimeShutdownSnapshot,
58
+ waitForDrain: async () => {
59
+ await Promise.all([waitForProjectOperationsToDrain(), runtimeActivity.waitForIdle()]);
60
+ },
61
+ waitForCompletionCriticalOperationsToDrain: waitForProjectCompletionCriticalOperationsToDrain,
62
+ closeMcp: async () => {
63
+ await server.close();
64
+ },
65
+ closeProjects: closeDrainedProjectSessions,
66
+ emitIncompleteShutdown: emitIncompleteShutdownEvent,
67
+ onCompletionCriticalWait: options.onCompletionCriticalWait,
68
+ });
69
+ let lifecycleCompletion;
70
+ function requestShutdown(trigger) {
71
+ lifecycleCompletion ??= coordinator.shutdown(trigger).finally(removeLifecycleListeners);
72
+ return lifecycleCompletion;
73
+ }
74
+ function requestFromRuntime(trigger) {
75
+ try {
76
+ options.onRuntimeTrigger?.(trigger);
77
+ }
78
+ catch {
79
+ // Runtime observation is non-authoritative and must never interrupt shutdown.
80
+ }
81
+ const completion = requestShutdown(trigger);
82
+ if (terminalHandlerInstalled)
83
+ return;
84
+ terminalHandlerInstalled = true;
85
+ void completion
86
+ .then((result) => {
87
+ if (result.state === "forced_noncritical")
88
+ exit(1);
89
+ })
90
+ .catch(() => {
91
+ emitShutdownFailureEvent();
92
+ exit(1);
93
+ });
94
+ }
95
+ protocol.onclose = onTransportClose;
96
+ if (installProcessHandlers) {
97
+ process.on("SIGINT", onSigint);
98
+ process.on("SIGTERM", onSigterm);
99
+ process.stdin.once("end", onStdinEnd);
100
+ process.stdin.once("close", onStdinClose);
101
+ listenersInstalled = true;
102
+ }
103
+ try {
104
+ await server.connect(transport);
105
+ }
106
+ catch (error) {
107
+ await requestShutdown("requested").catch(() => undefined);
108
+ throw error;
109
+ }
110
+ if (options.logStartup ?? true)
111
+ process.stderr.write("ast-mcp-server running over stdio.\n");
112
+ return Object.freeze({
113
+ shutdown: (trigger = "requested") => requestShutdown(trigger),
114
+ });
115
+ }
116
+ function isMainModule() {
117
+ const entry = process.argv[1];
118
+ if (!entry)
119
+ return false;
120
+ try {
121
+ return fs.realpathSync(entry) === fs.realpathSync(fileURLToPath(import.meta.url));
122
+ }
123
+ catch {
124
+ return path.resolve(entry) === path.resolve(fileURLToPath(import.meta.url));
125
+ }
126
+ }
127
+ if (isMainModule()) {
128
+ runStdioServer().catch(() => {
129
+ process.stderr.write("Fatal ast-mcp-server startup error.\n");
130
+ process.exit(1);
131
+ });
132
+ }
package/dist/server.js CHANGED
@@ -1,8 +1,11 @@
1
1
  import { createRequire } from "node:module";
2
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { McpServer, } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { PublicOperationalError } from "./services/public-errors.js";
3
4
  import { registerApplyOperation } from "./tools/apply_operation.js";
4
5
  import { registerFindReferences } from "./tools/find_references.js";
5
6
  import { registerGetDiagnostics } from "./tools/get_diagnostics.js";
7
+ import { registerGetFile } from "./tools/get_file.js";
8
+ import { registerGetImpact } from "./tools/get_impact.js";
6
9
  import { registerGetOperationPreview } from "./tools/get_operation_preview.js";
7
10
  import { registerGetOutline } from "./tools/get_outline.js";
8
11
  import { registerGetProjectStatus } from "./tools/get_project_status.js";
@@ -12,20 +15,40 @@ import { registerRenameSymbol } from "./tools/rename_symbol.js";
12
15
  import { registerReplaceSymbolBody } from "./tools/replace_symbol_body.js";
13
16
  import { registerScaffoldClass } from "./tools/scaffold_class.js";
14
17
  import { registerSearchSymbols } from "./tools/search_symbols.js";
18
+ import { registerExplore } from "./tools/explore.js";
19
+ import { createToolErrorContext, errorResult } from "./tools/result.js";
15
20
  const packageMetadata = createRequire(import.meta.url)("../package.json");
16
21
  export const PACKAGE_VERSION = packageMetadata.version;
17
- export function createServer() {
22
+ function installRuntimeActivityTracking(server, runtimeActivity) {
23
+ const registerTool = server.registerTool.bind(server);
24
+ function trackedRegisterTool(name, config, callback) {
25
+ const trackedCallback = (async (...args) => runtimeActivity.trackRequest(() => {
26
+ if (runtimeActivity.admission === "closed") {
27
+ return errorResult(new PublicOperationalError("SERVER_SHUTTING_DOWN", "Server is shutting down."), createToolErrorContext(name));
28
+ }
29
+ return Reflect.apply(callback, undefined, args);
30
+ }));
31
+ return registerTool(name, config, trackedCallback);
32
+ }
33
+ server.registerTool = trackedRegisterTool;
34
+ }
35
+ export function createServer(options = {}) {
18
36
  const server = new McpServer({
19
37
  name: "ast-mcp-server",
20
38
  version: PACKAGE_VERSION,
21
39
  });
40
+ if (options.runtimeActivity)
41
+ installRuntimeActivityTracking(server, options.runtimeActivity);
22
42
  registerListFiles(server);
23
43
  registerGetProjectStatus(server);
44
+ registerExplore(server);
24
45
  registerGetOutline(server);
25
46
  registerGetSymbolSource(server);
26
47
  registerSearchSymbols(server);
27
48
  registerFindReferences(server);
49
+ registerGetImpact(server);
28
50
  registerGetDiagnostics(server);
51
+ registerGetFile(server);
29
52
  registerRenameSymbol(server);
30
53
  registerReplaceSymbolBody(server);
31
54
  registerScaffoldClass(server);