ast-mcp-server 0.4.0 → 0.5.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ast-mcp-server",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Structural code MCP server and batch CLI for compact TypeScript/JavaScript reads and hash-bound AST edits.",
5
5
  "keywords": [
6
6
  "mcp",
@@ -55,6 +55,7 @@
55
55
  "benchmark:corpus": "yarn build && node scripts/benchmark-corpus.mjs",
56
56
  "benchmark:batch": "yarn build && node scripts/benchmark-batch.mjs",
57
57
  "benchmark:formats": "yarn build && node scripts/benchmark-formats.mjs",
58
+ "benchmark:shapes": "yarn build && node scripts/benchmark-result-shapes.mjs",
58
59
  "lint": "eslint src test scripts vitest.config.ts eslint.config.js",
59
60
  "format": "prettier --write .",
60
61
  "format:check": "prettier --check .",
@@ -81,4 +82,4 @@
81
82
  "typescript-eslint": "^8.65.0",
82
83
  "vitest": "^4.1.10"
83
84
  }
84
- }
85
+ }
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: structural-code-editing
3
3
  description: Leer, navegar y editar proyectos TypeScript/JavaScript mediante el resolver real del compilador y operaciones AST preparadas, revisadas y vinculadas por hash.
4
- version: "3.4.0"
4
+ version: "4.0.0"
5
5
  author: "yail"
6
6
  license: "ISC"
7
7
  metadata:
@@ -21,6 +21,7 @@ Usar las tools del servidor MCP `ast` en proyectos TypeScript/JavaScript con `ts
21
21
  - medir el radio de impacto de un rename;
22
22
  - renombrar un símbolo en varios archivos;
23
23
  - reemplazar solo el cuerpo de una función, método, accessor o callable property;
24
+ - crear un archivo de clase nuevo mediante un scaffold estructurado y revisado;
24
25
  - obtener diagnostics sin cargar el proyecto como texto en el contexto.
25
26
 
26
27
  Para configs, Markdown, comentarios o una edición textual trivial en un archivo ya conocido, usar las tools normales de archivos. El AST no cobra alquiler, pero cada roundtrip sí.
@@ -45,6 +46,8 @@ El setup falla cerrado ante un registro `ast` conflictivo. No eliminar ni reempl
45
46
  5. `ast_find_references` antes de renames o cambios con impacto cross-file.
46
47
  6. `ast_get_diagnostics` para establecer y verificar el estado del proyecto.
47
48
 
49
+ `ast_search_symbols` devuelve por default hasta 20 records `summary` rankeados. Su campo `selector` es el valor que se pasa como `symbol_path` a la siguiente tool; pedir `detail: "selectors"` para routing puro o `detail: "full", limit: 100` para el perfil v0.4.0. `ast_find_references` devuelve `detail: "locations"` por default; expandir a `detail: "context"` únicamente cuando la línea fuente aporte evidencia necesaria.
50
+
48
51
  `file_path` debe ser preferentemente relativo al proyecto. Si un suffix coincide con varios archivos, la tool falla y devuelve candidatos en vez de elegir uno silenciosamente.
49
52
 
50
53
  Los clientes pueden prefijar los nombres publicados (`ast_*`) según su convención MCP; elegir por el nombre base y el schema, no adivinar el prefijo.
@@ -77,9 +80,9 @@ Cuando un pipeline conocido requiere varias llamadas MCP dependientes y el clien
77
80
 
78
81
  ## Flujo obligatorio de mutación
79
82
 
80
- Las tools de rename y reemplazo **solo preparan**. `dry_run: false` directo está deshabilitado.
83
+ Las tools de rename, reemplazo y scaffold **solo preparan**. `dry_run: false` directo está deshabilitado.
81
84
 
82
- 1. Llamar `ast_rename_symbol` o `ast_replace_symbol_body` con `dry_run: true`.
85
+ 1. Llamar `ast_rename_symbol`, `ast_replace_symbol_body` o `ast_scaffold_class` con `dry_run: true`.
83
86
  2. Revisar:
84
87
  - `affected_files`;
85
88
  - summaries y previews;
@@ -93,6 +96,12 @@ Las tools de rename y reemplazo **solo preparan**. `dry_run: false` directo est
93
96
 
94
97
  Nunca reconstruir el contenido a aplicar a partir del diff. Apply escribe los postimages exactos retenidos en el plan.
95
98
 
99
+ ### Scaffold de clase
100
+
101
+ Usar `ast_scaffold_class` solo para crear un `.ts`/`.tsx` ausente con una clase estructurada. Pasar imports, heritage, decorators, constructor params, properties inicializadas y métodos mediante el schema; no inyectar un archivo completo como string. Debe haber al menos un método.
102
+
103
+ Cada método generado contiene exclusivamente `throw new Error("Not implemented: Class.method")`. Preparar el scaffold, revisar el diff desde `/dev/null`, diagnostics, `pending_methods`, `blocked` y `plan_hash`, aplicar y luego reemplazar cada selector pendiente con `ast_replace_symbol_body`. Un target existente, path fuera del proyecto o parent simbólico debe fallar; no buscar un fallback textual.
104
+
96
105
  ### Mutaciones desde el CLI
97
106
 
98
107
  Un batch puede terminar en una sola preparación, pero nunca puede incluir `ast_apply_operation`. El resultado expone `operation_id`, `plan_hash` y `plan_file` en el nivel superior aunque `emit` los omita; revisar preview, diagnostics y affected files, y aplicar en otra llamada:
@@ -110,7 +119,8 @@ Los planes CLI sobreviven al proceso bajo `${XDG_STATE_HOME:-~/.local/state}/ast
110
119
  - plan vinculado por hash al workspace completo, configs extendidos/referenciados y postimages;
111
120
  - rechazo si cambió cualquier source/config antes de apply;
112
121
  - lock filesystem cooperativo por config/workspace canónico compartido por MCP y CLI;
113
- - staging, flush, rename, verificación de hash y rollback conservador;
122
+ - staging, flush, rename para reemplazos y creación no-clobber para targets nuevos, con verificación de hash y rollback conservador;
123
+ - scaffold create-only con target ausente, parent real, postimage incluida en el fingerprint y diff contra `/dev/null`;
114
124
  - retry idempotente de un operation ya aplicado;
115
125
  - preservación de modo y UTF-8 BOM.
116
126
 
@@ -125,7 +135,7 @@ La edición AST no demuestra que un cambio sea semánticamente correcto ni vuelv
125
135
  - El receipt se persiste dentro de la sección crítica. Si esa persistencia falla después de reemplazar sources, apply sale no-cero y el retry recupera sólo si el workspace completo coincide exactamente con el fingerprint post-apply revisado.
126
136
  - Un crash duro puede dejar un lock stale: retirarlo requiere inspeccionar metadata y confirmar que no hay apply activo. Un estado parcial o divergente sigue fallando cerrado.
127
137
  - Solo admite sources UTF-8 con o sin BOM.
128
- - No implementa migración arbitraria de firmas, creación/eliminación de archivos ni lenguajes fuera de TS/JS.
138
+ - No implementa migración arbitraria de firmas, creación/eliminación general de archivos ni lenguajes fuera de TS/JS; la única creación admitida es el scaffold de una clase.
129
139
  - `allow_new_errors: true` evita el bloqueo del plan; no convierte código roto en código sano.
130
140
 
131
141
  ## Verificación
@@ -1,118 +0,0 @@
1
- # Benchmark methodology
2
-
3
- The benchmark suite measures structural payload reduction, batch orchestration, and model-facing result formats. The first two benchmarks deliberately avoid converting characters into tokens. The format benchmark pins and names one tokenizer so its estimates are reproducible rather than universal.
4
-
5
- ## Project payload and latency
6
-
7
- `scripts/benchmark.mjs`:
8
-
9
- 1. Loads a real TypeScript project from disk.
10
- 2. Selects the lexicographically first non-declaration source files after an optional filter.
11
- 3. Serializes the default compact outline payload (`file` plus `outline`).
12
- 4. Also records the larger opt-in payload containing detailed symbol metadata.
13
- 5. Reports fresh project load, cold cached-session, warm cached-session, and per-file outline latency.
14
-
15
- Run:
16
-
17
- ```bash
18
- yarn benchmark /absolute/project/path --sample 20 --output benchmark/results/project.json
19
- ```
20
-
21
- The selection rule is deterministic but not statistically representative of every repository. Use `--filter` and multiple samples when comparing particular modules.
22
-
23
- ## Compact-first task corpus
24
-
25
- `task-corpus.json` defines twelve questions over this repository. Each task declares:
26
-
27
- - files a full-file workflow would load;
28
- - declarations a compact-first workflow would request after inspecting outlines;
29
- - evidence strings necessary to answer that task.
30
-
31
- `scripts/benchmark-corpus.mjs` compares:
32
-
33
- - baseline: complete text of every declared file;
34
- - compact: default outline payloads plus only the selected declaration sources.
35
-
36
- It fails unless every predefined evidence string is present in the compact payload. This makes the check reproducible, but it does not prove that every possible reviewer would reach an equivalent conclusion.
37
-
38
- Run:
39
-
40
- ```bash
41
- yarn benchmark:corpus benchmark/task-corpus.json --output benchmark/results/self-corpus.json
42
- ```
43
-
44
- ## Interpreting results
45
-
46
- - Character reduction measures serialized payload size, not billed model tokens.
47
- - Negative reduction on a tiny file is valid: protocol structure can cost more than reading that file directly.
48
- - Project-load latency and warm-session latency should be considered separately.
49
- - Detailed symbol metadata is opt-in because it repeats signature text and can dominate small files.
50
- - Benchmark scripts record absolute local paths and timestamps. Checked reports replace local paths with descriptive placeholders; regenerate them when comparing another machine or revision.
51
-
52
- ## Batch orchestration
53
-
54
- `scripts/benchmark-batch.mjs` compares a two-operation search-to-source workflow in fresh Node processes:
55
-
56
- - separate: the client receives the broad symbol-search payload, selects the first match, then requests its source;
57
- - batch: `ast-tool` performs the same two MCP tool invocations in process and emits only the final source result.
58
-
59
- Run:
60
-
61
- ```bash
62
- yarn benchmark:batch --iterations 5 --output benchmark/results/self-batch.json
63
- ```
64
-
65
- The report records logical model round-trips, actual tool invocations, median wall time, process maximum RSS, final-result characters, and total characters exposed to the model. It does not include model inference latency, so the practical wall-time benefit of removing a model round-trip will be larger than this local process-only comparison. Maximum RSS includes the Node runtime and TypeScript project in each fresh worker.
66
-
67
- ## Model-facing JSON and TOON
68
-
69
- `scripts/benchmark-formats.mjs` compares compact JSON with TOON for actual MCP logical results. It uses this repository for broad symbol search and deterministic temporary TypeScript fixtures for repeated references and non-empty diagnostics. File lists, outlines, exact source, and a prepared rename are retained as negative controls.
70
-
71
- For each payload it records:
72
-
73
- - exact JSON→TOON→value round-trip equality;
74
- - UTF-8 bytes;
75
- - `gpt-tokenizer@3.4.0` `o200k_base` token estimates;
76
- - plain TOON for CLI output and the real MCP `{format,data}` envelope;
77
- - median encode/decode time over 50 local iterations;
78
- - serialized `tools/list` metadata against the checked v0.3.0 baseline.
79
-
80
- Run:
81
-
82
- ```bash
83
- yarn benchmark:formats
84
- ```
85
-
86
- The script fails unless every round trip is exact, the broad-search MCP envelope reduces estimated tokens by at least 20%, and the aggregate eligible corpus reduces them by at least 15%. Tokenizer estimates are not provider usage records and do not establish billed-token or prompt-cache savings.
87
-
88
- ## Checked results
89
-
90
- Results generated on 2026-08-03 with Node.js v24.16.0:
91
-
92
- | Workload | Sample | Full source chars | Compact chars | Reduction | Fresh load | Warm session |
93
- | --------------- | -------: | ----------------: | ------------: | --------: | ---------: | -----------: |
94
- | This repository | 20 files | 77,982 | 12,512 | 83.96% | 543 ms | 1.86 ms |
95
- | `x-scraper` | 20 files | 178,110 | 17,036 | 90.44% | 3,951 ms | 180.16 ms |
96
- | Task corpus | 12 tasks | 83,289 | 28,372 | 65.94% | n/a | n/a |
97
-
98
- The task corpus passed all 12 predefined evidence checks. Its compact count includes the selected declaration bodies, not just outlines. Exact raw reports are under `benchmark/results/`.
99
-
100
- The checked broad search-to-source batch result used five fresh-process samples:
101
-
102
- | Mode | Model round-trips | Tool invocations | Context chars | Median wall time | Median max RSS |
103
- | -------- | ----------------: | ---------------: | ------------: | ---------------: | -------------: |
104
- | Separate | 2 | 2 | 11,514 | 536.19 ms | 377.54 MB |
105
- | Batch | 1 | 2 | 552 | 535.24 ms | 378.35 MB |
106
-
107
- That run reduced model round-trips by 50% and serialized context by 95.21%. Local execution latency decreased by 0.18% and RSS increased by 0.21%, both small enough to treat as noise rather than a performance claim. The batch value is orchestration/context reduction; it does not make TypeScript analysis free.
108
-
109
- The checked model-facing format corpus used the complete MCP envelope for TOON:
110
-
111
- | Payload | Records | JSON tokens | MCP TOON tokens | Reduction |
112
- | ------------------- | ------: | ----------: | --------------: | --------: |
113
- | Broad symbol search | 100 | 5,225 | 3,881 | 25.72% |
114
- | References | 71 | 3,086 | 2,150 | 30.33% |
115
- | Diagnostics | 30 | 1,309 | 1,034 | 21.01% |
116
- | Eligible aggregate | 201 | 9,620 | 7,065 | 26.56% |
117
-
118
- All seven positive and negative payloads round-tripped exactly. File list, outline, source, and prepare envelopes ranged from 5.50% to 23.40% worse in estimated tokens, which is why they remain JSON-only. Current serialized tool metadata is 2,451 characters smaller than the v0.3.0 baseline despite the three new input fields, because multi-shape tools no longer advertise a single incompatible output schema.