@angular-modernizer/adapter-mcp 0.2.0 → 1.0.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 (255) hide show
  1. package/README.md +188 -235
  2. package/dist/cli.js +77 -27
  3. package/dist/index.d.ts +11 -3
  4. package/dist/index.js +10 -2
  5. package/dist/mcp-watcher.d.ts +6 -1
  6. package/dist/mcp-watcher.js +14 -10
  7. package/dist/server/limited-stdio-transport.d.ts +68 -0
  8. package/dist/server/limited-stdio-transport.js +115 -0
  9. package/dist/server/mcp-server.d.ts +41 -12
  10. package/dist/server/mcp-server.js +113 -94
  11. package/dist/server/package-version.d.ts +16 -0
  12. package/dist/server/package-version.js +37 -0
  13. package/dist/server/sdk-server.d.ts +70 -0
  14. package/dist/server/sdk-server.js +113 -0
  15. package/dist/server/stdio-guard.d.ts +20 -0
  16. package/dist/server/stdio-guard.js +48 -0
  17. package/dist/server/tool-registry.d.ts +3 -2
  18. package/dist/server/tool-registry.js +5 -5
  19. package/dist/tools/analyze-build-impact.d.ts +346 -14
  20. package/dist/tools/analyze-build-impact.js +315 -31
  21. package/dist/tools/analyze-core-to-shared.d.ts +134 -4
  22. package/dist/tools/analyze-core-to-shared.js +113 -9
  23. package/dist/tools/analyze-parser-performance.d.ts +200 -7
  24. package/dist/tools/analyze-parser-performance.js +108 -47
  25. package/dist/tools/analyze-project.d.ts +267 -5
  26. package/dist/tools/analyze-project.js +196 -8
  27. package/dist/tools/check-incremental-compatibility.d.ts +61 -1
  28. package/dist/tools/check-incremental-compatibility.js +58 -2
  29. package/dist/tools/collect-feedback.d.ts +199 -10
  30. package/dist/tools/collect-feedback.js +171 -99
  31. package/dist/tools/compare-health.d.ts +356 -0
  32. package/dist/tools/compare-health.js +472 -0
  33. package/dist/tools/extract-libraries.d.ts +156 -4
  34. package/dist/tools/extract-libraries.js +115 -10
  35. package/dist/tools/find-angular-symbol.d.ts +98 -9
  36. package/dist/tools/find-angular-symbol.js +104 -12
  37. package/dist/tools/find-component-hosts.d.ts +684 -0
  38. package/dist/tools/find-component-hosts.js +441 -0
  39. package/dist/tools/find-usages.d.ts +99 -4
  40. package/dist/tools/find-usages.js +131 -11
  41. package/dist/tools/get-bootstrap-execution.d.ts +258 -0
  42. package/dist/tools/get-bootstrap-execution.js +324 -0
  43. package/dist/tools/get-call-graph.d.ts +139 -4
  44. package/dist/tools/get-call-graph.js +123 -13
  45. package/dist/tools/get-operation-progress-tool.d.ts +114 -2
  46. package/dist/tools/get-operation-progress-tool.js +114 -7
  47. package/dist/tools/get-operation-progress.d.ts +1 -1
  48. package/dist/tools/get-operation-progress.js +5 -5
  49. package/dist/tools/helpers/analysis-output.d.ts +177 -0
  50. package/dist/tools/helpers/analysis-output.js +165 -0
  51. package/dist/tools/helpers/build-schemas.d.ts +36 -0
  52. package/dist/tools/helpers/build-schemas.js +23 -0
  53. package/dist/tools/helpers/citation-file-source.d.ts +10 -0
  54. package/dist/tools/helpers/citation-file-source.js +82 -0
  55. package/dist/tools/helpers/compact-output.d.ts +61 -0
  56. package/dist/tools/helpers/compact-output.js +83 -0
  57. package/dist/tools/helpers/finding-window.d.ts +43 -0
  58. package/dist/tools/helpers/finding-window.js +64 -0
  59. package/dist/tools/helpers/health-delta.d.ts +86 -0
  60. package/dist/tools/helpers/health-delta.js +239 -0
  61. package/dist/tools/helpers/investigation-schemas.d.ts +93 -0
  62. package/dist/tools/helpers/investigation-schemas.js +48 -0
  63. package/dist/tools/helpers/library-imports.d.ts +57 -0
  64. package/dist/tools/helpers/library-imports.js +151 -0
  65. package/dist/tools/helpers/load-source-files.d.ts +30 -0
  66. package/dist/tools/helpers/load-source-files.js +34 -0
  67. package/dist/tools/helpers/output-contract.d.ts +32 -0
  68. package/dist/tools/helpers/output-contract.js +32 -0
  69. package/dist/tools/helpers/platform-root-resolver.d.ts +55 -25
  70. package/dist/tools/helpers/platform-root-resolver.js +75 -48
  71. package/dist/tools/helpers/process-output.d.ts +19 -0
  72. package/dist/tools/helpers/process-output.js +31 -0
  73. package/dist/tools/helpers/project-cache.d.ts +184 -0
  74. package/dist/tools/helpers/project-cache.js +331 -0
  75. package/dist/tools/helpers/project-decorators.d.ts +14 -0
  76. package/dist/tools/helpers/project-decorators.js +22 -0
  77. package/dist/tools/helpers/rule-matcher.js +5 -0
  78. package/dist/tools/helpers/rule-runner.d.ts +72 -0
  79. package/dist/tools/helpers/rule-runner.js +131 -0
  80. package/dist/tools/helpers/scan-cache.d.ts +22 -0
  81. package/dist/tools/helpers/scan-cache.js +34 -0
  82. package/dist/tools/helpers/scan-plan.d.ts +48 -0
  83. package/dist/tools/helpers/scan-plan.js +166 -0
  84. package/dist/tools/helpers/scope-paths.d.ts +17 -0
  85. package/dist/tools/helpers/scope-paths.js +32 -0
  86. package/dist/tools/helpers/stack-frame-file-index.d.ts +10 -0
  87. package/dist/tools/helpers/stack-frame-file-index.js +71 -0
  88. package/dist/tools/helpers/tool-context.d.ts +60 -0
  89. package/dist/tools/helpers/tool-context.js +82 -0
  90. package/dist/tools/helpers/transform-safety.d.ts +40 -0
  91. package/dist/tools/helpers/transform-safety.js +87 -0
  92. package/dist/tools/helpers/validation-output.d.ts +53 -0
  93. package/dist/tools/helpers/validation-output.js +48 -0
  94. package/dist/tools/inspect-form-group.d.ts +324 -0
  95. package/dist/tools/inspect-form-group.js +279 -0
  96. package/dist/tools/inspect-i18n.d.ts +466 -0
  97. package/dist/tools/inspect-i18n.js +400 -0
  98. package/dist/tools/inspect-template.d.ts +320 -0
  99. package/dist/tools/inspect-template.js +324 -0
  100. package/dist/tools/learn-patterns.d.ts +122 -1
  101. package/dist/tools/learn-patterns.js +97 -2
  102. package/dist/tools/list-imports.d.ts +128 -11
  103. package/dist/tools/list-imports.js +128 -8
  104. package/dist/tools/orchestrate-migration.d.ts +129 -5
  105. package/dist/tools/orchestrate-migration.js +166 -12
  106. package/dist/tools/parse-stack-trace.d.ts +59 -2
  107. package/dist/tools/parse-stack-trace.js +52 -4
  108. package/dist/tools/plan-migration.d.ts +418 -1
  109. package/dist/tools/plan-migration.js +355 -8
  110. package/dist/tools/resolve-type.d.ts +42 -1
  111. package/dist/tools/resolve-type.js +37 -4
  112. package/dist/tools/review-feedback.d.ts +206 -11
  113. package/dist/tools/review-feedback.js +132 -51
  114. package/dist/tools/rollback-changes.d.ts +79 -2
  115. package/dist/tools/rollback-changes.js +66 -14
  116. package/dist/tools/run-angular-cli.d.ts +45 -2
  117. package/dist/tools/run-angular-cli.js +67 -7
  118. package/dist/tools/run-build.d.ts +114 -2
  119. package/dist/tools/run-build.js +117 -8
  120. package/dist/tools/run-schematic.d.ts +70 -2
  121. package/dist/tools/run-schematic.js +104 -10
  122. package/dist/tools/scan-all.d.ts +24 -16
  123. package/dist/tools/scan-all.js +145 -137
  124. package/dist/tools/scan-angular.d.ts +20 -11
  125. package/dist/tools/scan-angular.js +52 -24
  126. package/dist/tools/scan-architecture.d.ts +42 -14
  127. package/dist/tools/scan-architecture.js +206 -163
  128. package/dist/tools/scan-solid.d.ts +20 -11
  129. package/dist/tools/scan-solid.js +52 -24
  130. package/dist/tools/search-codebase.d.ts +85 -1
  131. package/dist/tools/search-codebase.js +61 -4
  132. package/dist/tools/server-status.d.ts +370 -0
  133. package/dist/tools/server-status.js +369 -0
  134. package/dist/tools/suggest-improvements.d.ts +97 -5
  135. package/dist/tools/suggest-improvements.js +80 -44
  136. package/dist/tools/trace-output-flow.d.ts +791 -0
  137. package/dist/tools/trace-output-flow.js +668 -0
  138. package/dist/tools/transform-code-batch.d.ts +3 -0
  139. package/dist/tools/transform-code-batch.js +10 -5
  140. package/dist/tools/transform-code.d.ts +335 -12
  141. package/dist/tools/transform-code.js +649 -608
  142. package/dist/tools/validate-before-transform.d.ts +116 -2
  143. package/dist/tools/validate-before-transform.js +55 -2
  144. package/dist/tools/validate-project-compatibility.d.ts +64 -2
  145. package/dist/tools/validate-project-compatibility.js +67 -4
  146. package/dist/tools/validate-transformation.d.ts +220 -2
  147. package/dist/tools/validate-transformation.js +113 -15
  148. package/dist/tools/verify-citations.d.ts +181 -0
  149. package/dist/tools/verify-citations.js +218 -0
  150. package/dist/types.d.ts +45 -1
  151. package/dist/utils/format-tool-response.d.ts +22 -59
  152. package/dist/utils/format-tool-response.js +25 -134
  153. package/package.json +30 -13
  154. package/dist/cli.d.ts.map +0 -1
  155. package/dist/cli.js.map +0 -1
  156. package/dist/core/project-analyzer.d.ts.map +0 -1
  157. package/dist/core/project-analyzer.js.map +0 -1
  158. package/dist/index.d.ts.map +0 -1
  159. package/dist/index.js.map +0 -1
  160. package/dist/mcp-watcher.d.ts.map +0 -1
  161. package/dist/mcp-watcher.js.map +0 -1
  162. package/dist/server/json-rpc-handler.d.ts +0 -57
  163. package/dist/server/json-rpc-handler.d.ts.map +0 -1
  164. package/dist/server/json-rpc-handler.js +0 -222
  165. package/dist/server/json-rpc-handler.js.map +0 -1
  166. package/dist/server/mcp-server.d.ts.map +0 -1
  167. package/dist/server/mcp-server.js.map +0 -1
  168. package/dist/server/tool-registry.d.ts.map +0 -1
  169. package/dist/server/tool-registry.js.map +0 -1
  170. package/dist/streaming/progress-store.d.ts.map +0 -1
  171. package/dist/streaming/progress-store.js.map +0 -1
  172. package/dist/tools/analyze-build-impact.d.ts.map +0 -1
  173. package/dist/tools/analyze-build-impact.js.map +0 -1
  174. package/dist/tools/analyze-core-to-shared.d.ts.map +0 -1
  175. package/dist/tools/analyze-core-to-shared.js.map +0 -1
  176. package/dist/tools/analyze-parser-performance.d.ts.map +0 -1
  177. package/dist/tools/analyze-parser-performance.js.map +0 -1
  178. package/dist/tools/analyze-project.d.ts.map +0 -1
  179. package/dist/tools/analyze-project.js.map +0 -1
  180. package/dist/tools/check-incremental-compatibility.d.ts.map +0 -1
  181. package/dist/tools/check-incremental-compatibility.js.map +0 -1
  182. package/dist/tools/collect-feedback.d.ts.map +0 -1
  183. package/dist/tools/collect-feedback.js.map +0 -1
  184. package/dist/tools/extract-libraries.d.ts.map +0 -1
  185. package/dist/tools/extract-libraries.js.map +0 -1
  186. package/dist/tools/find-angular-symbol.d.ts.map +0 -1
  187. package/dist/tools/find-angular-symbol.js.map +0 -1
  188. package/dist/tools/find-usages.d.ts.map +0 -1
  189. package/dist/tools/find-usages.js.map +0 -1
  190. package/dist/tools/get-call-graph.d.ts.map +0 -1
  191. package/dist/tools/get-call-graph.js.map +0 -1
  192. package/dist/tools/get-operation-progress-tool.d.ts.map +0 -1
  193. package/dist/tools/get-operation-progress-tool.js.map +0 -1
  194. package/dist/tools/get-operation-progress.d.ts.map +0 -1
  195. package/dist/tools/get-operation-progress.js.map +0 -1
  196. package/dist/tools/helpers/feedback-analyzer.d.ts.map +0 -1
  197. package/dist/tools/helpers/feedback-analyzer.js.map +0 -1
  198. package/dist/tools/helpers/find-ts-config.d.ts.map +0 -1
  199. package/dist/tools/helpers/find-ts-config.js.map +0 -1
  200. package/dist/tools/helpers/platform-root-resolver.d.ts.map +0 -1
  201. package/dist/tools/helpers/platform-root-resolver.js.map +0 -1
  202. package/dist/tools/helpers/rule-matcher.d.ts.map +0 -1
  203. package/dist/tools/helpers/rule-matcher.js.map +0 -1
  204. package/dist/tools/helpers/suggestion-generator.d.ts.map +0 -1
  205. package/dist/tools/helpers/suggestion-generator.js.map +0 -1
  206. package/dist/tools/learn-patterns.d.ts.map +0 -1
  207. package/dist/tools/learn-patterns.js.map +0 -1
  208. package/dist/tools/list-imports.d.ts.map +0 -1
  209. package/dist/tools/list-imports.js.map +0 -1
  210. package/dist/tools/orchestrate-migration.d.ts.map +0 -1
  211. package/dist/tools/orchestrate-migration.js.map +0 -1
  212. package/dist/tools/parse-stack-trace.d.ts.map +0 -1
  213. package/dist/tools/parse-stack-trace.js.map +0 -1
  214. package/dist/tools/plan-migration.d.ts.map +0 -1
  215. package/dist/tools/plan-migration.js.map +0 -1
  216. package/dist/tools/resolve-type.d.ts.map +0 -1
  217. package/dist/tools/resolve-type.js.map +0 -1
  218. package/dist/tools/review-feedback.d.ts.map +0 -1
  219. package/dist/tools/review-feedback.js.map +0 -1
  220. package/dist/tools/rollback-changes.d.ts.map +0 -1
  221. package/dist/tools/rollback-changes.js.map +0 -1
  222. package/dist/tools/run-angular-cli.d.ts.map +0 -1
  223. package/dist/tools/run-angular-cli.js.map +0 -1
  224. package/dist/tools/run-build.d.ts.map +0 -1
  225. package/dist/tools/run-build.js.map +0 -1
  226. package/dist/tools/run-schematic.d.ts.map +0 -1
  227. package/dist/tools/run-schematic.js.map +0 -1
  228. package/dist/tools/scan-all.d.ts.map +0 -1
  229. package/dist/tools/scan-all.js.map +0 -1
  230. package/dist/tools/scan-angular.d.ts.map +0 -1
  231. package/dist/tools/scan-angular.js.map +0 -1
  232. package/dist/tools/scan-architecture.d.ts.map +0 -1
  233. package/dist/tools/scan-architecture.js.map +0 -1
  234. package/dist/tools/scan-solid.d.ts.map +0 -1
  235. package/dist/tools/scan-solid.js.map +0 -1
  236. package/dist/tools/search-codebase.d.ts.map +0 -1
  237. package/dist/tools/search-codebase.js.map +0 -1
  238. package/dist/tools/shared/scan-types.d.ts.map +0 -1
  239. package/dist/tools/shared/scan-types.js.map +0 -1
  240. package/dist/tools/suggest-improvements.d.ts.map +0 -1
  241. package/dist/tools/suggest-improvements.js.map +0 -1
  242. package/dist/tools/transform-code-batch.d.ts.map +0 -1
  243. package/dist/tools/transform-code-batch.js.map +0 -1
  244. package/dist/tools/transform-code.d.ts.map +0 -1
  245. package/dist/tools/transform-code.js.map +0 -1
  246. package/dist/tools/validate-before-transform.d.ts.map +0 -1
  247. package/dist/tools/validate-before-transform.js.map +0 -1
  248. package/dist/tools/validate-project-compatibility.d.ts.map +0 -1
  249. package/dist/tools/validate-project-compatibility.js.map +0 -1
  250. package/dist/tools/validate-transformation.d.ts.map +0 -1
  251. package/dist/tools/validate-transformation.js.map +0 -1
  252. package/dist/types.d.ts.map +0 -1
  253. package/dist/types.js.map +0 -1
  254. package/dist/utils/format-tool-response.d.ts.map +0 -1
  255. package/dist/utils/format-tool-response.js.map +0 -1
@@ -2,13 +2,15 @@
2
2
  * @angular-modernizer/adapter-mcp - Scan Architecture Tool
3
3
  *
4
4
  * MCP tool for scanning Angular codebases for architectural issues.
5
- * Runs only the ArchitecturePlugin (13 rules: circular deps, layer violations, god objects, etc.).
5
+ * Runs only the ArchitecturePlugin (17 rules: import cycles, layer violations, god objects, etc.).
6
6
  */
7
7
  import { findTsConfig } from './helpers/find-ts-config.js';
8
+ import { cancelledExecution, fileProgress, yieldIfCancellable, } from './helpers/tool-context.js';
9
+ import { loadSourceFiles } from './helpers/load-source-files.js';
10
+ import { filterFilesByScopePaths } from './helpers/scope-paths.js';
8
11
  import { toParallelOptions } from '../types.js';
9
12
  import { Kernel, createToolCacheConfig, loadConfig, } from '@angular-modernizer/core';
10
13
  import { ArchitecturePlugin } from '@angular-modernizer/plugin-architecture';
11
- import { ContextFactory, } from '@angular-modernizer/plugin-system';
12
14
  import { createPublicApi } from '@angular-modernizer/api';
13
15
  import { getWorkerScriptPath } from '@angular-modernizer/worker';
14
16
  import { glob } from 'glob';
@@ -17,17 +19,60 @@ import { readFileSync, existsSync, statSync } from 'node:fs';
17
19
  import { randomUUID } from 'node:crypto';
18
20
  import { cpus } from 'node:os';
19
21
  import { ProgressStore } from '../streaming/progress-store.js';
22
+ import { describeScan, scanOutputSchema, } from './helpers/analysis-output.js';
23
+ import { incompleteNote, parseMaxDurationMs, runRulesOverFiles, } from './helpers/rule-runner.js';
24
+ /** Violations per response unless `maxResults` says otherwise. */
25
+ const DEFAULT_MAX_RESULTS = 1000;
26
+ /**
27
+ * Page of violations per `maxResults` (default 1000) and `resultOffset`.
28
+ * The summary is computed from all violations; `pagination` says what was cut.
29
+ */
30
+ function paginateViolations(violations, params) {
31
+ const maxResults = params.maxResults ?? DEFAULT_MAX_RESULTS;
32
+ const offset = params.resultOffset ?? 0;
33
+ const page = violations.slice(offset, offset + maxResults);
34
+ return {
35
+ violations: page,
36
+ pagination: {
37
+ totalResults: violations.length,
38
+ returnedResults: page.length,
39
+ offset,
40
+ hasMore: offset + maxResults < violations.length,
41
+ },
42
+ };
43
+ }
44
+ /**
45
+ * Adds the text summary to a scan result; an incomplete run adds its note.
46
+ */
47
+ function withScanSummary(result) {
48
+ const notes = result.execution?.note === undefined ? [] : [result.execution.note];
49
+ return {
50
+ ...result,
51
+ summary: describeScan(result.counts, result.violations, result.pagination, notes),
52
+ };
53
+ }
20
54
  /**
21
55
  * Scan Architecture Tool
22
56
  *
23
- * Provides architectural analysis capabilities through MCP.
24
- * Uses the SOLID plugin to detect violations of SOLID principles.
57
+ * Provides architectural analysis capabilities through MCP with the rules of
58
+ * the ArchitecturePlugin.
25
59
  */
26
60
  export class ScanArchitectureTool {
27
61
  name = 'scan-architecture';
28
- description = 'Scan Angular codebases for SOLID principle violations and architectural issues';
62
+ title = 'Scan Architecture';
63
+ annotations = {
64
+ readOnlyHint: true,
65
+ destructiveHint: false,
66
+ idempotentHint: true,
67
+ openWorldHint: false,
68
+ };
69
+ description = 'Scan Angular codebases for architectural issues with the 17 architecture rules: import cycles ' +
70
+ '(solid:circular-dependency, NG0919 risk), import direction, god objects, layer boundaries, content ' +
71
+ 'placement, service bags and more. Returns the violations directly; streaming: true (deprecated) runs in the background instead (poll get-operation-progress); ' +
72
+ 'maxResults (default 1000) and resultOffset page the violations; counts cover all of them, summary is a short text.';
29
73
  inputSchema = {
30
74
  type: 'object',
75
+ additionalProperties: false,
31
76
  properties: {
32
77
  rootPath: {
33
78
  type: 'string',
@@ -185,8 +230,8 @@ export class ScanArchitectureTool {
185
230
  },
186
231
  streaming: {
187
232
  type: 'boolean',
188
- description: 'Enable streaming mode - returns operationId immediately for polling progress. When true, analysis runs in background and progress can be queried via get-operation-progress tool.',
189
- default: true,
233
+ description: 'Deprecated, kept in 1.x (default: false): returns operationId immediately, the analysis runs in the background and get-operation-progress returns the result. Synchronous calls report progress through MCP progress notifications and stop on cancellation.',
234
+ default: false,
190
235
  },
191
236
  apiStyle: {
192
237
  type: 'string',
@@ -194,13 +239,38 @@ export class ScanArchitectureTool {
194
239
  description: 'API style to use for analysis execution. "fluent" (default) uses the chainable FluentKernel API with pipeline stages. "imperative" uses traditional Kernel API.',
195
240
  default: 'fluent',
196
241
  },
242
+ maxDurationMs: {
243
+ type: 'number',
244
+ description: 'Time budget in ms, checked between files. When it is reached the scan stops and returns what it has with ' +
245
+ 'execution.incomplete = true, the number of skipped files and the slowest rules. 0 disables it. Default 300000 (5 min).',
246
+ default: 300000,
247
+ },
197
248
  },
198
249
  required: ['rootPath'],
199
250
  };
200
- async execute(args) {
251
+ outputSchema = scanOutputSchema({
252
+ operationId: { type: 'string' },
253
+ execution: {
254
+ type: 'object',
255
+ properties: {
256
+ maxDurationMs: { type: 'number' },
257
+ incomplete: { type: 'boolean' },
258
+ stopReason: { type: 'string' },
259
+ skippedFiles: { type: 'integer' },
260
+ ruleTimings: { type: 'array', items: { type: 'object' } },
261
+ note: { type: 'string' },
262
+ },
263
+ required: ['maxDurationMs', 'incomplete', 'skippedFiles', 'ruleTimings'],
264
+ },
265
+ scope: { type: 'object' },
266
+ progress: { type: 'object' },
267
+ pipeline: { type: 'array', items: { type: 'string' } },
268
+ intermediateResults: { type: 'object' },
269
+ });
270
+ async execute(args, ctx = {}) {
201
271
  const params = args;
202
272
  // Check if streaming mode is enabled
203
- const streaming = params.streaming ?? true;
273
+ const streaming = params.streaming ?? false;
204
274
  if (streaming) {
205
275
  // Streaming mode - start operation in background and return operationId
206
276
  return this.executeStreaming(params);
@@ -208,7 +278,7 @@ export class ScanArchitectureTool {
208
278
  // Check if fluent API should be used
209
279
  const apiStyle = params.apiStyle ?? 'fluent';
210
280
  if (apiStyle === 'fluent') {
211
- return this.executeWithFluentApi(params);
281
+ return this.executeWithFluentApi(params, ctx);
212
282
  }
213
283
  // Load configuration from .angular-modernizer.json if it exists
214
284
  const config = this.loadConfig(typeof params.rootPath === 'string' ? params.rootPath : undefined);
@@ -249,6 +319,7 @@ export class ScanArchitectureTool {
249
319
  // CRITICAL: Default to 100 files to prevent memory exhaustion
250
320
  // Production scans should explicitly set maxFiles if they need more
251
321
  const maxFiles = params.maxFiles ?? 100;
322
+ const maxDurationMs = parseMaxDurationMs(params.maxDurationMs);
252
323
  // Auto-detect required paths
253
324
  const tsConfigPath = orchestration.tsConfigPath ?? findTsConfig(params.rootPath);
254
325
  const workerScriptPath = orchestration.workerScriptPath ?? getWorkerScriptPath();
@@ -337,6 +408,7 @@ export class ScanArchitectureTool {
337
408
  }
338
409
  const violations = [];
339
410
  let filesAnalyzed = 0;
411
+ let execution;
340
412
  // Pre-discover files to enable auto-selection of parallel mode
341
413
  const preDiscoveryFiles = await this.findFilesToAnalyze(params.rootPath, includePatterns, excludePatterns, Number.MAX_SAFE_INTEGER);
342
414
  // Apply scope filtering for file count
@@ -374,8 +446,17 @@ export class ScanArchitectureTool {
374
446
  rules: params.rules,
375
447
  timeout: orchestration.timeout ?? 120000, // 2 minutes for complex architecture rules
376
448
  };
377
- // Process each batch
449
+ // Process each batch; cancellation is checked between batches
378
450
  for (let batchNum = 0; batchNum < totalBatches; batchNum++) {
451
+ await yieldIfCancellable(ctx.signal);
452
+ if (ctx.signal?.aborted === true) {
453
+ execution = {
454
+ ...cancelledExecution(batchNum * batchSize, totalFiles - batchNum * batchSize),
455
+ maxDurationMs: parseMaxDurationMs(params.maxDurationMs),
456
+ };
457
+ break;
458
+ }
459
+ ctx.progress?.(batchNum * batchSize, totalFiles, `batch ${batchNum + 1}/${totalBatches}, ${violations.length} violations`);
379
460
  const batchStart = batchNum * batchSize;
380
461
  const batchEnd = Math.min(batchStart + batchSize, totalFiles);
381
462
  const batchFiles = filesToAnalyze.slice(batchStart, batchEnd);
@@ -388,9 +469,17 @@ export class ScanArchitectureTool {
388
469
  for (const file of existingFiles) {
389
470
  project.removeSourceFile(file);
390
471
  }
391
- // Add current batch files
392
- for (const filePath of batchFiles) {
393
- project.addSourceFileAtPath(filePath);
472
+ // Add current batch files; a cancel during the load stops the scan
473
+ const loaded = await loadSourceFiles(project, batchFiles, {
474
+ signal: ctx.signal,
475
+ failOnError: true,
476
+ });
477
+ if (loaded.cancelled) {
478
+ execution = {
479
+ ...cancelledExecution(batchStart, totalFiles - batchStart),
480
+ maxDurationMs: parseMaxDurationMs(params.maxDurationMs),
481
+ };
482
+ break;
394
483
  }
395
484
  console.info(`Batch ${batchNum + 1}: Project now has ${project.getSourceFiles().length} source files`);
396
485
  // Log cache stats to show cache effectiveness
@@ -421,7 +510,7 @@ export class ScanArchitectureTool {
421
510
  violations.push({
422
511
  id: `${analysisResult.ruleId}-${analysisResult.filePath}-${analysisResult.line ?? 0}-${analysisResult.column ?? 0}`,
423
512
  ruleId: analysisResult.ruleId,
424
- severity: rule.severity,
513
+ severity: analysisResult.severity ?? rule.severity,
425
514
  message: analysisResult.message,
426
515
  filePath: analysisResult.filePath,
427
516
  line: analysisResult.line,
@@ -449,7 +538,7 @@ export class ScanArchitectureTool {
449
538
  violations.push({
450
539
  id: `${analysisResult.ruleId}-${analysisResult.filePath}-${analysisResult.line ?? 0}-${analysisResult.column ?? 0}`,
451
540
  ruleId: analysisResult.ruleId,
452
- severity: rule.severity,
541
+ severity: analysisResult.severity ?? rule.severity,
453
542
  message: analysisResult.message,
454
543
  filePath: analysisResult.filePath,
455
544
  line: analysisResult.line,
@@ -528,43 +617,20 @@ export class ScanArchitectureTool {
528
617
  // Add cached violations to results
529
618
  // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
530
619
  violations.push(...cachedViolations);
531
- for (const filePath of filesToProcess) {
532
- // Check resource limits periodically
533
- if (resourceManager?.shouldThrottle()) {
534
- console.warn('Resource throttling activated, pausing...');
535
- await new Promise((resolve) => setTimeout(resolve, 1000));
536
- }
537
- try {
538
- const sourceFile = project.addSourceFileAtPath(filePath);
539
- for (const rule of rulesToRun) {
540
- const results = await rule.analyze(ContextFactory.createAnalysisContext({
541
- sourceFile,
542
- project,
543
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
544
- api,
545
- config: rulesConfig,
546
- }));
547
- for (const result of results) {
548
- violations.push({
549
- id: `${result.ruleId}-${result.filePath}-${result.line ?? 0}-${result.column ?? 0}`,
550
- ruleId: result.ruleId,
551
- severity: rule.severity,
552
- message: result.message,
553
- filePath: result.filePath,
554
- line: result.line,
555
- column: result.column,
556
- category: rule.category,
557
- suggestedFix: result.suggestedFix,
558
- metadata: result.metadata,
559
- });
560
- }
561
- }
562
- }
563
- catch (error) {
564
- console.warn(`Error analyzing ${filePath}:`, error);
565
- }
566
- }
567
- filesAnalyzed = filesToAnalyze.length;
620
+ const run = await runRulesOverFiles({
621
+ project,
622
+ files: filesToProcess,
623
+ rules: rulesToRun,
624
+ api,
625
+ config: rulesConfig,
626
+ maxDurationMs,
627
+ startTime,
628
+ signal: ctx.signal,
629
+ onFileAnalyzed: fileProgress(ctx.progress),
630
+ });
631
+ violations.push(...run.violations);
632
+ execution = toExecution(run, maxDurationMs);
633
+ filesAnalyzed = filesToAnalyze.length - run.skippedFiles;
568
634
  // ============================================================================
569
635
  // CACHE WRITE SYSTEM (Sequential Mode Only)
570
636
  // ============================================================================
@@ -613,17 +679,7 @@ export class ScanArchitectureTool {
613
679
  // Calculate summary (before pagination)
614
680
  const summary = this.calculateSummary(violations);
615
681
  const duration = Date.now() - startTime;
616
- // Apply pagination to violations
617
- const totalViolations = violations.length;
618
- const maxResults = params.maxResults ?? 1000;
619
- const resultOffset = params.resultOffset ?? 0;
620
- const paginatedViolations = violations.slice(resultOffset, resultOffset + maxResults);
621
- const paginationMetadata = {
622
- totalResults: totalViolations,
623
- returnedResults: paginatedViolations.length,
624
- offset: resultOffset,
625
- hasMore: resultOffset + maxResults < totalViolations,
626
- };
682
+ const page = paginateViolations(violations, params);
627
683
  // Gather orchestration stats using full Phase 6d/7b options
628
684
  let orchestrationMetrics;
629
685
  if (orchestration.parallel || orchestration.incremental) {
@@ -653,9 +709,9 @@ export class ScanArchitectureTool {
653
709
  : undefined,
654
710
  };
655
711
  }
656
- const result = {
657
- violations: paginatedViolations,
658
- summary: {
712
+ return withScanSummary({
713
+ violations: page.violations,
714
+ counts: {
659
715
  ...summary,
660
716
  analyzedFiles: filesAnalyzed,
661
717
  },
@@ -664,12 +720,12 @@ export class ScanArchitectureTool {
664
720
  duration,
665
721
  projectRoot: params.rootPath,
666
722
  },
723
+ ...(execution ? { execution } : {}),
667
724
  scope: resolvedScope.type !== 'all' ? resolvedScope : undefined,
668
- pagination: paginationMetadata,
725
+ pagination: page.pagination,
669
726
  orchestration: orchestrationMetrics,
670
727
  progress: lastProgress,
671
- };
672
- return result;
728
+ });
673
729
  }
674
730
  catch (error) {
675
731
  throw new Error(`Architecture scan failed: ${error instanceof Error ? error.message : String(error)}`);
@@ -678,7 +734,7 @@ export class ScanArchitectureTool {
678
734
  /**
679
735
  * Execute analysis using fluent API.
680
736
  */
681
- async executeWithFluentApi(params) {
737
+ async executeWithFluentApi(params, ctx) {
682
738
  // Validate input
683
739
  if (!params.rootPath || typeof params.rootPath !== 'string') {
684
740
  throw new Error('rootPath is required and must be a string');
@@ -750,44 +806,26 @@ export class ScanArchitectureTool {
750
806
  // causing config-driven rules to return 0 violations (Bug 1/3).
751
807
  const project = kernel.getProject();
752
808
  const api = createPublicApi(project);
753
- const violations = [];
754
- let filesAnalyzed = 0;
755
- for (const filePath of filesToAnalyze) {
756
- try {
757
- const sourceFile = project.addSourceFileAtPath(filePath);
758
- for (const rule of rulesToRun) {
759
- const results = await rule.analyze(ContextFactory.createAnalysisContext({
760
- sourceFile,
761
- project,
762
- api: api,
763
- config: rulesConfig,
764
- }));
765
- for (const result of results) {
766
- violations.push({
767
- id: `${result.ruleId}-${result.filePath}-${result.line ?? 0}-${result.column ?? 0}`,
768
- ruleId: result.ruleId,
769
- severity: rule.severity,
770
- message: result.message,
771
- filePath: result.filePath,
772
- line: result.line,
773
- column: result.column,
774
- category: rule.category,
775
- suggestedFix: result.suggestedFix,
776
- metadata: result.metadata,
777
- });
778
- }
779
- }
780
- filesAnalyzed++;
781
- }
782
- catch (error) {
783
- console.warn(`Error analyzing ${filePath}:`, error);
784
- }
785
- }
809
+ const run = await runRulesOverFiles({
810
+ project,
811
+ files: filesToAnalyze,
812
+ rules: rulesToRun,
813
+ api,
814
+ config: rulesConfig,
815
+ maxDurationMs: parseMaxDurationMs(params.maxDurationMs),
816
+ startTime,
817
+ signal: ctx.signal,
818
+ onFileAnalyzed: fileProgress(ctx.progress),
819
+ });
820
+ const violations = run.violations;
821
+ const filesAnalyzed = run.filesAnalyzed;
822
+ const execution = toExecution(run, parseMaxDurationMs(params.maxDurationMs));
786
823
  const duration = Date.now() - startTime;
787
824
  const summary = this.calculateSummary(violations);
788
- return {
789
- violations,
790
- summary: {
825
+ const page = paginateViolations(violations, params);
826
+ return withScanSummary({
827
+ violations: page.violations,
828
+ counts: {
791
829
  ...summary,
792
830
  analyzedFiles: filesAnalyzed,
793
831
  },
@@ -796,6 +834,8 @@ export class ScanArchitectureTool {
796
834
  duration,
797
835
  projectRoot: params.rootPath,
798
836
  },
837
+ execution,
838
+ pagination: page.pagination,
799
839
  pipeline: ['analyze'],
800
840
  intermediateResults: {
801
841
  analyze: {
@@ -804,7 +844,7 @@ export class ScanArchitectureTool {
804
844
  message: `Analysis completed with ${violations.length} violations`,
805
845
  },
806
846
  },
807
- };
847
+ });
808
848
  }
809
849
  catch (error) {
810
850
  throw new Error(`Architecture analysis failed: ${error instanceof Error ? error.message : String(error)}`);
@@ -836,7 +876,7 @@ export class ScanArchitectureTool {
836
876
  return {
837
877
  operationId,
838
878
  violations: [],
839
- summary: {
879
+ counts: {
840
880
  totalViolations: 0,
841
881
  analyzedFiles: 0,
842
882
  bySeverity: {},
@@ -848,6 +888,8 @@ export class ScanArchitectureTool {
848
888
  duration: 0,
849
889
  projectRoot: params.rootPath,
850
890
  },
891
+ summary: `Scan started in the background as operation ${operationId}; ` +
892
+ 'get-operation-progress returns the violations when it is complete.',
851
893
  };
852
894
  }
853
895
  /**
@@ -941,51 +983,39 @@ export class ScanArchitectureTool {
941
983
  const project = kernel.getProject();
942
984
  const api = createPublicApi(project);
943
985
  const violations = [];
944
- let filesProcessed = 0;
945
- for (const filePath of filesToAnalyze) {
946
- if (store.isCancelled(operationId)) {
947
- break;
948
- }
949
- try {
950
- const sourceFile = project.addSourceFileAtPath(filePath);
951
- for (const rule of rulesToRun) {
952
- const results = await rule.analyze(ContextFactory.createAnalysisContext({
953
- sourceFile,
954
- project,
955
- api: api,
956
- config: streamingRulesConfig,
957
- }));
958
- for (const result of results) {
959
- violations.push({
960
- id: `${result.ruleId}-${result.filePath}-${result.line ?? 0}-${result.column ?? 0}`,
961
- ruleId: result.ruleId,
962
- severity: rule.severity,
963
- message: result.message,
964
- filePath: result.filePath,
965
- line: result.line,
966
- column: result.column,
967
- category: rule.category,
968
- suggestedFix: result.suggestedFix,
969
- metadata: result.metadata,
970
- });
971
- }
972
- }
973
- filesProcessed++;
974
- const percentage = 30 + Math.round((filesProcessed / filesToAnalyze.length) * 60);
975
- // Add progress event every 10 files
976
- if (filesProcessed % 10 === 0 ||
977
- filesProcessed === filesToAnalyze.length) {
978
- store.addEvent(operationId, {
979
- phase: 'analyzing',
980
- message: `Analyzed ${filesProcessed}/${filesToAnalyze.length} files, found ${violations.length} violations`,
981
- percentage,
982
- timestamp: Date.now(),
983
- });
986
+ const maxDurationMs = parseMaxDurationMs(params.maxDurationMs);
987
+ const run = await runRulesOverFiles({
988
+ project,
989
+ files: filesToAnalyze,
990
+ rules: rulesToRun,
991
+ api,
992
+ config: streamingRulesConfig,
993
+ maxDurationMs,
994
+ startTime: store.getMetadata(operationId).startTime,
995
+ isCancelled: () => store.isCancelled(operationId),
996
+ onFileAnalyzed: (analyzed, total, found) => {
997
+ // Progress event every 10 files
998
+ if (analyzed % 10 !== 0 && analyzed !== total) {
999
+ return;
984
1000
  }
985
- }
986
- catch (error) {
987
- console.warn(`Error analyzing ${filePath}:`, error);
988
- }
1001
+ store.addEvent(operationId, {
1002
+ phase: 'analyzing',
1003
+ message: `Analyzed ${analyzed}/${total} files, found ${found} violations`,
1004
+ percentage: 30 + Math.round((analyzed / total) * 60),
1005
+ timestamp: Date.now(),
1006
+ });
1007
+ },
1008
+ });
1009
+ violations.push(...run.violations);
1010
+ const filesProcessed = run.filesAnalyzed;
1011
+ const execution = toExecution(run, maxDurationMs);
1012
+ if (execution.note) {
1013
+ store.addEvent(operationId, {
1014
+ phase: 'analyzing',
1015
+ message: execution.note,
1016
+ percentage: 90,
1017
+ timestamp: Date.now(),
1018
+ });
989
1019
  }
990
1020
  // Add completion event
991
1021
  store.addEvent(operationId, {
@@ -996,9 +1026,11 @@ export class ScanArchitectureTool {
996
1026
  });
997
1027
  // Store full result so get-operation-progress can return violations
998
1028
  const summary = this.calculateSummary(violations);
999
- store.setResult(operationId, {
1000
- violations,
1001
- summary: {
1029
+ const page = paginateViolations(violations, params);
1030
+ store.setResult(operationId, withScanSummary({
1031
+ violations: page.violations,
1032
+ pagination: page.pagination,
1033
+ counts: {
1002
1034
  ...summary,
1003
1035
  analyzedFiles: filesProcessed,
1004
1036
  },
@@ -1007,7 +1039,8 @@ export class ScanArchitectureTool {
1007
1039
  duration: Date.now() - store.getMetadata(operationId).startTime,
1008
1040
  projectRoot: params.rootPath,
1009
1041
  },
1010
- });
1042
+ execution,
1043
+ }));
1011
1044
  // Mark complete
1012
1045
  store.markComplete(operationId);
1013
1046
  }
@@ -1024,8 +1057,9 @@ export class ScanArchitectureTool {
1024
1057
  });
1025
1058
  allFiles.push(...files);
1026
1059
  }
1027
- // Remove duplicates and limit
1028
- const uniqueFiles = [...new Set(allFiles)].slice(0, maxFiles);
1060
+ // Sorted before the limit: glob returns files in no fixed order, and both
1061
+ // the chosen files and the result pages depend on it
1062
+ const uniqueFiles = [...new Set(allFiles)].sort().slice(0, maxFiles);
1029
1063
  // Filter to only TypeScript files and ensure they are actual files (not directories)
1030
1064
  return uniqueFiles.filter((file) => {
1031
1065
  const isTsFile = ['.ts', '.tsx'].includes(extname(file));
@@ -1281,10 +1315,19 @@ export class ScanArchitectureTool {
1281
1315
  resolvedScope.resolvedPaths.length === 0) {
1282
1316
  return files;
1283
1317
  }
1284
- return files.filter((file) => {
1285
- return resolvedScope.resolvedPaths.some((scopePath) => file.startsWith(scopePath) ||
1286
- file.startsWith(scopePath.replaceAll('\\', '/')));
1287
- });
1318
+ // Inside the folder, not a sibling sharing its prefix
1319
+ return filterFilesByScopePaths(files, resolvedScope.resolvedPaths);
1288
1320
  }
1289
1321
  }
1322
+ function toExecution(run, maxDurationMs) {
1323
+ const note = incompleteNote(run, maxDurationMs);
1324
+ return {
1325
+ maxDurationMs,
1326
+ incomplete: run.incomplete,
1327
+ ...(run.stopReason ? { stopReason: run.stopReason } : {}),
1328
+ skippedFiles: run.skippedFiles,
1329
+ ruleTimings: run.ruleTimings,
1330
+ ...(note ? { note } : {}),
1331
+ };
1332
+ }
1290
1333
  //# sourceMappingURL=scan-architecture.js.map
@@ -2,9 +2,11 @@
2
2
  * @angular-modernizer/adapter-mcp - Scan SOLID Principles Tool
3
3
  *
4
4
  * MCP tool for scanning Angular codebases for SOLID principle violations.
5
- * Runs only the SolidPlugin (5 rules: DIP, SRP, LSP, OCP, ISP).
5
+ * Runs only the SolidPlugin (7 rules: DIP, SRP, LSP, OCP, ISP).
6
6
  */
7
- import type { MCPTool } from '../types.js';
7
+ import type { MCPTool, ToolAnnotations, ToolContext } from '../types.js';
8
+ import { type ScanCounts } from './helpers/analysis-output.js';
9
+ import { type CancelledExecution } from './helpers/tool-context.js';
8
10
  interface ScanSolidResult {
9
11
  violations: {
10
12
  id: string;
@@ -18,13 +20,12 @@ interface ScanSolidResult {
18
20
  suggestedFix?: string;
19
21
  metadata?: Record<string, unknown>;
20
22
  }[];
21
- summary: {
22
- totalViolations: number;
23
- analyzedFiles: number;
24
- bySeverity: Record<string, number>;
25
- byCategory: Record<string, number>;
26
- byRule: Record<string, number>;
27
- };
23
+ /** Counts over all violations, independent of the page. */
24
+ counts: ScanCounts;
25
+ /** Human-readable summary for LLM consumption. */
26
+ summary: string;
27
+ /** Set when the client cancelled the scan; counts cover the analyzed files. */
28
+ execution?: CancelledExecution;
28
29
  metadata: {
29
30
  rulesExecuted: string[];
30
31
  duration: number;
@@ -51,9 +52,12 @@ interface ScanSolidResult {
51
52
  */
52
53
  export declare class ScanSolidTool implements MCPTool {
53
54
  readonly name = "scan-solid";
54
- readonly description = "Scan for SOLID principle violations (DIP, SRP, LSP, OCP, ISP)";
55
+ readonly title = "Scan SOLID Principles";
56
+ readonly annotations: ToolAnnotations;
57
+ readonly description: string;
55
58
  readonly inputSchema: {
56
59
  type: string;
60
+ additionalProperties: boolean;
57
61
  properties: {
58
62
  rootPath: {
59
63
  type: string;
@@ -120,7 +124,12 @@ export declare class ScanSolidTool implements MCPTool {
120
124
  };
121
125
  required: string[];
122
126
  };
123
- execute(args: Record<string, unknown>): Promise<ScanSolidResult>;
127
+ readonly outputSchema: {
128
+ type: "object";
129
+ properties: Record<string, unknown>;
130
+ required: string[];
131
+ };
132
+ execute(args: Record<string, unknown>, ctx?: ToolContext): Promise<ScanSolidResult>;
124
133
  /**
125
134
  * Load configuration from .angular-modernizer.json file.
126
135
  * Only loads from the provided root path to avoid cache directory issues.