@angular-modernizer/adapter-mcp 1.0.0 → 1.1.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 (129) hide show
  1. package/README.md +78 -64
  2. package/dist/cli.js +8 -0
  3. package/dist/core/project-analyzer.d.ts +3 -12
  4. package/dist/core/project-analyzer.js +3 -12
  5. package/dist/index.d.ts +118 -3
  6. package/dist/index.js +46 -3
  7. package/dist/mcp-watcher.d.ts +28 -8
  8. package/dist/mcp-watcher.js +7 -7
  9. package/dist/scan-host/scan-host.d.ts +119 -0
  10. package/dist/scan-host/scan-host.js +376 -0
  11. package/dist/scan-host/scan-protocol.d.ts +35 -0
  12. package/dist/scan-host/scan-protocol.js +6 -0
  13. package/dist/scan-host/scan-worker.d.ts +14 -0
  14. package/dist/scan-host/scan-worker.js +48 -0
  15. package/dist/server/limited-stdio-transport.d.ts +7 -0
  16. package/dist/server/mcp-server.d.ts +11 -7
  17. package/dist/server/mcp-server.js +4 -7
  18. package/dist/server/sdk-server.d.ts +1 -0
  19. package/dist/server/tool-registry.d.ts +3 -7
  20. package/dist/server/tool-registry.js +1 -7
  21. package/dist/streaming/progress-store.d.ts +22 -5
  22. package/dist/streaming/progress-store.js +9 -5
  23. package/dist/tools/analyze-build-impact.d.ts +56 -34
  24. package/dist/tools/analyze-build-impact.js +30 -25
  25. package/dist/tools/analyze-core-to-shared.d.ts +42 -12
  26. package/dist/tools/analyze-core-to-shared.js +11 -10
  27. package/dist/tools/analyze-parser-performance.d.ts +23 -22
  28. package/dist/tools/analyze-parser-performance.js +20 -18
  29. package/dist/tools/analyze-project.d.ts +82 -12
  30. package/dist/tools/analyze-project.js +98 -101
  31. package/dist/tools/check-incremental-compatibility.d.ts +13 -11
  32. package/dist/tools/check-incremental-compatibility.js +11 -8
  33. package/dist/tools/collect-feedback.d.ts +41 -26
  34. package/dist/tools/collect-feedback.js +32 -23
  35. package/dist/tools/compare-health.d.ts +76 -19
  36. package/dist/tools/compare-health.js +26 -19
  37. package/dist/tools/extract-libraries.d.ts +44 -20
  38. package/dist/tools/extract-libraries.js +16 -17
  39. package/dist/tools/find-angular-symbol.d.ts +25 -23
  40. package/dist/tools/find-angular-symbol.js +17 -14
  41. package/dist/tools/find-component-hosts.d.ts +31 -25
  42. package/dist/tools/find-component-hosts.js +24 -21
  43. package/dist/tools/find-usages.d.ts +23 -21
  44. package/dist/tools/find-usages.js +19 -16
  45. package/dist/tools/get-bootstrap-execution.d.ts +33 -25
  46. package/dist/tools/get-bootstrap-execution.js +25 -22
  47. package/dist/tools/get-call-graph.d.ts +18 -13
  48. package/dist/tools/get-call-graph.js +24 -21
  49. package/dist/tools/get-operation-progress-tool.d.ts +12 -6
  50. package/dist/tools/get-operation-progress-tool.js +11 -6
  51. package/dist/tools/get-operation-progress.d.ts +26 -0
  52. package/dist/tools/helpers/analysis-output.d.ts +5 -0
  53. package/dist/tools/helpers/batch-kernel.d.ts +14 -0
  54. package/dist/tools/helpers/batch-kernel.js +12 -0
  55. package/dist/tools/helpers/compact-output.d.ts +2 -1
  56. package/dist/tools/helpers/compact-output.js +2 -1
  57. package/dist/tools/helpers/health-delta.d.ts +27 -14
  58. package/dist/tools/helpers/health-delta.js +11 -14
  59. package/dist/tools/helpers/project-cache.d.ts +50 -34
  60. package/dist/tools/helpers/project-cache.js +33 -34
  61. package/dist/tools/helpers/rule-runner.d.ts +23 -16
  62. package/dist/tools/helpers/rule-runner.js +24 -17
  63. package/dist/tools/helpers/scan-engine.d.ts +107 -0
  64. package/dist/tools/helpers/scan-engine.js +197 -0
  65. package/dist/tools/helpers/suggestion-generator.d.ts +9 -13
  66. package/dist/tools/helpers/suggestion-generator.js +0 -12
  67. package/dist/tools/helpers/tool-cache.d.ts +11 -0
  68. package/dist/tools/helpers/tool-cache.js +15 -0
  69. package/dist/tools/helpers/tool-context.d.ts +11 -8
  70. package/dist/tools/helpers/tool-context.js +5 -8
  71. package/dist/tools/inspect-form-group.d.ts +32 -25
  72. package/dist/tools/inspect-form-group.js +24 -21
  73. package/dist/tools/inspect-i18n.d.ts +28 -22
  74. package/dist/tools/inspect-i18n.js +20 -17
  75. package/dist/tools/inspect-template.d.ts +31 -24
  76. package/dist/tools/inspect-template.js +23 -20
  77. package/dist/tools/learn-patterns.d.ts +88 -12
  78. package/dist/tools/learn-patterns.js +17 -11
  79. package/dist/tools/list-imports.d.ts +42 -25
  80. package/dist/tools/list-imports.js +23 -20
  81. package/dist/tools/orchestrate-migration.d.ts +31 -9
  82. package/dist/tools/orchestrate-migration.js +12 -7
  83. package/dist/tools/parse-stack-trace.d.ts +23 -21
  84. package/dist/tools/parse-stack-trace.js +10 -7
  85. package/dist/tools/plan-migration.d.ts +65 -25
  86. package/dist/tools/plan-migration.js +19 -19
  87. package/dist/tools/resolve-type.d.ts +19 -9
  88. package/dist/tools/resolve-type.js +19 -11
  89. package/dist/tools/review-feedback.d.ts +27 -24
  90. package/dist/tools/review-feedback.js +24 -20
  91. package/dist/tools/rollback-changes.d.ts +13 -9
  92. package/dist/tools/rollback-changes.js +10 -7
  93. package/dist/tools/run-angular-cli.d.ts +12 -10
  94. package/dist/tools/run-angular-cli.js +11 -8
  95. package/dist/tools/run-build.d.ts +13 -11
  96. package/dist/tools/run-build.js +11 -8
  97. package/dist/tools/run-schematic.d.ts +12 -10
  98. package/dist/tools/run-schematic.js +11 -8
  99. package/dist/tools/scan-all.d.ts +69 -12
  100. package/dist/tools/scan-all.js +55 -122
  101. package/dist/tools/scan-angular.d.ts +41 -9
  102. package/dist/tools/scan-angular.js +66 -135
  103. package/dist/tools/scan-architecture.d.ts +75 -14
  104. package/dist/tools/scan-architecture.js +180 -185
  105. package/dist/tools/scan-solid.d.ts +40 -9
  106. package/dist/tools/scan-solid.js +64 -133
  107. package/dist/tools/search-codebase.d.ts +30 -24
  108. package/dist/tools/search-codebase.js +13 -10
  109. package/dist/tools/server-status.d.ts +116 -24
  110. package/dist/tools/server-status.js +85 -26
  111. package/dist/tools/suggest-improvements.d.ts +22 -19
  112. package/dist/tools/suggest-improvements.js +21 -17
  113. package/dist/tools/trace-output-flow.d.ts +32 -25
  114. package/dist/tools/trace-output-flow.js +24 -21
  115. package/dist/tools/transform-code.d.ts +71 -10
  116. package/dist/tools/transform-code.js +60 -42
  117. package/dist/tools/validate-before-transform.d.ts +24 -9
  118. package/dist/tools/validate-before-transform.js +10 -7
  119. package/dist/tools/validate-project-compatibility.d.ts +18 -13
  120. package/dist/tools/validate-project-compatibility.js +17 -11
  121. package/dist/tools/validate-transformation.d.ts +28 -11
  122. package/dist/tools/validate-transformation.js +14 -8
  123. package/dist/tools/verify-citations.d.ts +37 -16
  124. package/dist/tools/verify-citations.js +19 -16
  125. package/dist/types.d.ts +40 -10
  126. package/dist/types.js +0 -5
  127. package/package.json +12 -18
  128. package/dist/tools/shared/scan-types.d.ts +0 -200
  129. package/dist/tools/shared/scan-types.js +0 -7
@@ -1,28 +1,13 @@
1
- /**
2
- * @angular-modernizer/adapter-mcp - Comprehensive Scan Tool
3
- *
4
- * MCP tool for comprehensive scanning with all plugins:
5
- * - SolidPlugin (7 rules): SOLID principles
6
- * - AngularPlugin (28 rules): Angular best practices
7
- * - ArchitecturePlugin (17 rules): Architectural issues
8
- * Total: 52 rules
9
- */
10
- /* eslint-disable @typescript-eslint/no-unsafe-assignment */
11
1
  import { findTsConfig } from './helpers/find-ts-config.js';
12
- import { Kernel, MultiCacheFallbackManager, RealFileSystemAdapter, createToolCacheConfig, createMultiCacheConfig, loadConfig, } from '@angular-modernizer/core';
13
- import { SolidPlugin } from '@angular-modernizer/plugin-solid';
14
- import { AngularPlugin } from '@angular-modernizer/plugin-angular';
15
- import { ArchitecturePlugin } from '@angular-modernizer/plugin-architecture';
16
- import { ContextFactory } from '@angular-modernizer/plugin-system';
17
- import { createPublicApi } from '@angular-modernizer/api';
2
+ import { MultiCacheFallbackManager, RealFileSystemAdapter, createMultiCacheConfig, loadConfig, } from '@angular-modernizer/core';
18
3
  import { glob } from 'glob';
19
4
  import { relative } from 'node:path';
20
- import { existsSync, statSync } from 'node:fs';
5
+ import { statSync } from 'node:fs';
21
6
  import { FindingWindow } from './helpers/finding-window.js';
22
- import { cancelledExecution, fileProgressMessage, yieldIfCancellable, } from './helpers/tool-context.js';
23
- import { loadSourceFiles } from './helpers/load-source-files.js';
7
+ import { cancelledExecution, fileProgressMessage, } from './helpers/tool-context.js';
8
+ import { runScan } from '../scan-host/scan-host.js';
24
9
  import { describeScan, SCAN_EXECUTION_SCHEMA, scanOutputSchema, } from './helpers/analysis-output.js';
25
- import { dependenciesUnchanged, templateDependencies, } from './helpers/scan-cache.js';
10
+ import { dependenciesUnchanged } from './helpers/scan-cache.js';
26
11
  /**
27
12
  * Version of the cache entries scan-all writes. Entries from before the
28
13
  * per-analyzed-file layout (findings filed under their template, files without
@@ -30,7 +15,13 @@ import { dependenciesUnchanged, templateDependencies, } from './helpers/scan-cac
30
15
  */
31
16
  const SCAN_ALL_CACHE_VERSION = 'scan-all-2';
32
17
  /**
33
- * Comprehensive scan with all available plugins (52 rules total).
18
+ * MCP tool `scan-all`: one scan with all analysis plugins (52 rules total).
19
+ *
20
+ * @remarks
21
+ * Plugins and rules:
22
+ * - SolidPlugin (7 rules): SOLID principles
23
+ * - AngularPlugin (28 rules): Angular best practices
24
+ * - ArchitecturePlugin (17 rules): architectural issues
34
25
  */
35
26
  export class ScanAllTool {
36
27
  name = 'scan-all';
@@ -43,6 +34,10 @@ export class ScanAllTool {
43
34
  };
44
35
  description = 'Comprehensive code quality scan with all plugins (SOLID 7, Angular 28, Architecture 17: 52 rules total). ' +
45
36
  'maxResults (default 1000) and resultOffset page the violations; counts cover all of them, summary is a short text.';
37
+ /**
38
+ * JSON Schema of the tool arguments.
39
+ * @hidden
40
+ */
46
41
  inputSchema = {
47
42
  type: 'object',
48
43
  additionalProperties: false,
@@ -115,6 +110,10 @@ export class ScanAllTool {
115
110
  },
116
111
  required: ['rootPath'],
117
112
  };
113
+ /**
114
+ * JSON Schema of the tool result (`structuredContent`).
115
+ * @hidden
116
+ */
118
117
  outputSchema = scanOutputSchema({
119
118
  cache: { type: 'object' },
120
119
  execution: SCAN_EXECUTION_SCHEMA,
@@ -132,21 +131,6 @@ export class ScanAllTool {
132
131
  if (!tsConfigPath) {
133
132
  throw new Error('Could not find tsconfig.json');
134
133
  }
135
- // Initialize kernel with all plugins and caching
136
- // IMPORTANT: skipAddingFilesFromTsConfig prevents loading dist/, e2e/, etc.
137
- const kernel = new Kernel({
138
- tsConfigPath,
139
- plugins: [
140
- new SolidPlugin(),
141
- new AngularPlugin(),
142
- new ArchitecturePlugin(),
143
- ],
144
- fileSystem: undefined,
145
- projectOptions: {
146
- skipAddingFilesFromTsConfig: true, // We'll add filtered files manually
147
- },
148
- cacheConfig: createToolCacheConfig(mergedParams.rootPath, 'all'),
149
- });
150
134
  // Find files to analyze
151
135
  const includePatterns = mergedParams.includePatterns ?? ['**/*.{ts,tsx}'];
152
136
  const excludePatterns = mergedParams.excludePatterns ?? [
@@ -174,13 +158,6 @@ export class ScanAllTool {
174
158
  const uniqueFiles = Array.from(new Set(allFiles)).sort();
175
159
  const filesToAnalyze = uniqueFiles; // Analyze ALL files found (batch processing prevents memory issues)
176
160
  const maxFiles = mergedParams.maxFiles ?? 100; // Batch size (default 100)
177
- // Initialize kernel
178
- await kernel.initialize();
179
- // Reuse the already-initialized plugin instances from the kernel so that
180
- // ruleConfigs loaded from .angular-modernizer.json are applied correctly.
181
- const allRules = kernel
182
- .getAllPlugins()
183
- .flatMap((p) => p.getAnalysisRules());
184
161
  // ============================================================================
185
162
  // CACHE READ
186
163
  // ============================================================================
@@ -195,9 +172,6 @@ export class ScanAllTool {
195
172
  version: SCAN_ALL_CACHE_VERSION,
196
173
  });
197
174
  await multiCacheManager.initialize();
198
- // Load rules config from .angular-modernizer.json for per-rule overrides (BUG-3)
199
- const fullConfig = loadConfig(mergedParams.rootPath);
200
- const rulesConfig = fullConfig.rules;
201
175
  const cachedResults = []; // eslint-disable-line @typescript-eslint/no-explicit-any
202
176
  const filesToProcess = [];
203
177
  const cacheHitsBySource = {};
@@ -257,84 +231,44 @@ export class ScanAllTool {
257
231
  window.add(cached);
258
232
  }
259
233
  let filesAnalyzed = cachedResults.length;
260
- let cancelled = false;
261
234
  const progressTotal = cachedResults.length + totalFiles;
262
- // Process each batch; cancellation is checked between files
263
- for (let batchNum = 0; batchNum < totalBatches && !cancelled; batchNum++) {
264
- const batchStart = batchNum * batchSize;
265
- const batchEnd = Math.min(batchStart + batchSize, totalFiles);
266
- const batchFiles = filesToProcess.slice(batchStart, batchEnd);
267
- console.info(`\nBatch ${batchNum + 1}/${totalBatches}: Processing files ${batchStart + 1}-${batchEnd} (${batchFiles.length} files)`);
268
- // Clear project and add batch files
269
- const project = kernel.getProject();
270
- // Remove all source files from previous batch
271
- const existingFiles = project.getSourceFiles();
272
- for (const file of existingFiles) {
273
- project.removeSourceFile(file);
274
- }
275
- // Add current batch files, keeping their sorted order: findings must
276
- // come out in the order a warm run reads them from the cache, or pages
277
- // computed cold and warm overlap. A cancel during the load stops the scan.
278
- const loaded = await loadSourceFiles(project, batchFiles, { signal: ctx.signal });
279
- if (loaded.cancelled) {
280
- cancelled = true;
281
- break;
282
- }
283
- const batchSourceFiles = loaded.sourceFiles;
284
- console.info(`Batch ${batchNum + 1}: Project now has ${project.getSourceFiles().length} source files`);
285
- // Create PublicApi for this batch
286
- const api = createPublicApi(project); // eslint-disable-line @typescript-eslint/no-explicit-any
287
- // Analyze files in this batch
288
- let batchViolationCount = 0;
289
- let batchFilesAnalyzed = 0;
290
- for (const sourceFile of batchSourceFiles) {
291
- await yieldIfCancellable(ctx.signal);
292
- if (ctx.signal?.aborted === true) {
293
- cancelled = true;
294
- break;
295
- }
296
- const fileResults = [];
297
- for (const rule of allRules) {
298
- try {
299
- const ruleResults = await rule.analyze(ContextFactory.createAnalysisContext({
300
- sourceFile,
301
- project,
302
- api,
303
- config: rulesConfig,
304
- }));
305
- for (const result of ruleResults) {
306
- const entry = {
307
- ruleId: result.ruleId,
308
- severity: result.severity ?? rule.severity,
309
- message: result.message,
310
- filePath: result.filePath,
311
- line: result.line,
312
- column: result.column,
313
- category: rule.category,
314
- suggestedFix: result.suggestedFix,
315
- metadata: result.metadata,
316
- };
317
- // Always accumulate for cache writes.
318
- fileResults.push(entry);
319
- window.add(entry);
320
- batchViolationCount++;
321
- }
322
- }
323
- catch (error) {
324
- console.warn(`Failed to analyze with rule ${rule.id}:`, error);
325
- }
326
- }
327
- const sourcePath = sourceFile.getFilePath();
328
- entriesForCache.set(sourcePath, {
329
- results: fileResults,
330
- dependencies: templateDependencies(sourcePath, sourceFile.getFullText(), fileResults.map((r) => r.filePath), existsSync),
235
+ // Kernel, batches and rules run in a scan worker (scan-host), so the
236
+ // server keeps reading stdin while the type checker is built. Files that
237
+ // failed to load count as analyzed once their batch is done, as before.
238
+ let batchFilesAnalyzed = 0;
239
+ if (totalFiles > 0) {
240
+ ctx.progress?.(filesAnalyzed, progressTotal, `loading project, ${totalFiles} files to analyze`);
241
+ }
242
+ const engine = await runScan({
243
+ tool: this.name,
244
+ plugins: 'all',
245
+ tsConfigPath,
246
+ rootPath: mergedParams.rootPath,
247
+ files: filesToProcess,
248
+ mode: 'batches',
249
+ batchSize,
250
+ templateDependencies: true,
251
+ }, {
252
+ file: (event) => {
253
+ // Always accumulate for cache writes, also files without findings
254
+ entriesForCache.set(event.filePath, {
255
+ results: event.findings,
256
+ dependencies: event.dependencies ?? [],
331
257
  });
258
+ for (const finding of event.findings) {
259
+ window.add(finding);
260
+ }
332
261
  batchFilesAnalyzed++;
333
262
  ctx.progress?.(filesAnalyzed + batchFilesAnalyzed, progressTotal, fileProgressMessage(filesAnalyzed + batchFilesAnalyzed, progressTotal, window.getTotals().totalViolations));
334
- }
335
- // Files that failed to load count as analyzed, as before
336
- filesAnalyzed += cancelled ? batchFilesAnalyzed : batchFiles.length;
337
- console.info(`Batch ${batchNum + 1}: Found ${batchViolationCount} violations in ${batchFiles.length} files`);
263
+ },
264
+ batchDone: (files) => {
265
+ filesAnalyzed += files;
266
+ batchFilesAnalyzed = 0;
267
+ },
268
+ }, { signal: ctx.signal });
269
+ const cancelled = engine.cancelled;
270
+ if (cancelled) {
271
+ filesAnalyzed += batchFilesAnalyzed;
338
272
  }
339
273
  console.info(`\nBatch processing complete: ${totalBatches} batch(es), ${filesAnalyzed} total files analyzed, ${window.getTotals().totalViolations} total violations`);
340
274
  // ============================================================================
@@ -403,8 +337,7 @@ export class ScanAllTool {
403
337
  hasMore: window.hasMore(),
404
338
  };
405
339
  const duration = Date.now() - startTime;
406
- // Get all rule IDs from the rules we executed
407
- const allRuleIds = allRules.map((r) => r.id);
340
+ const allRuleIds = engine.ruleIds;
408
341
  // Get final cache statistics (Phase 3)
409
342
  const finalStats = multiCacheManager.getStats();
410
343
  return {
@@ -1,23 +1,29 @@
1
- /**
2
- * @angular-modernizer/adapter-mcp - Scan Angular Best Practices Tool
3
- *
4
- * MCP tool for scanning Angular codebases for Angular-specific best practice violations.
5
- * Runs only the AngularPlugin (28 rules: OnPush, TrackBy, Performance, RxJS, etc.).
6
- */
7
1
  import type { MCPTool, ToolAnnotations, ToolContext } from '../types.js';
8
2
  import { type ScanCounts } from './helpers/analysis-output.js';
9
3
  import { type CancelledExecution } from './helpers/tool-context.js';
10
- interface ScanAngularResult {
4
+ /** Result of the scan-angular tool. */
5
+ export interface ScanAngularResult {
6
+ /** The requested page of violations (`maxResults`, `resultOffset`). */
11
7
  violations: {
8
+ /** Index-based id of the violation (`angular-<index>`). */
12
9
  id: string;
10
+ /** Rule that reported the violation. */
13
11
  ruleId: string;
12
+ /** Severity reported by the rule. */
14
13
  severity: 'error' | 'warning' | 'info';
14
+ /** Rule message. */
15
15
  message: string;
16
+ /** File path relative to `rootPath`. */
16
17
  filePath: string;
18
+ /** 1-based line of the finding, when the rule reports one. */
17
19
  line?: number;
20
+ /** Column of the finding, when the rule reports one. */
18
21
  column?: number;
22
+ /** Rule category; `Angular` when the rule sets none. */
19
23
  category: string;
24
+ /** Fix suggested by the rule; only with `includeAutoFixes`. */
20
25
  suggestedFix?: string;
26
+ /** Rule-specific details. */
21
27
  metadata?: Record<string, unknown>;
22
28
  }[];
23
29
  /** Counts over all violations, independent of the page. */
@@ -26,35 +32,58 @@ interface ScanAngularResult {
26
32
  summary: string;
27
33
  /** Set when the client cancelled the scan; counts cover the analyzed files. */
28
34
  execution?: CancelledExecution;
35
+ /** Scan metadata. */
29
36
  metadata: {
37
+ /** Ids of the rules that ran. */
30
38
  rulesExecuted: string[];
39
+ /** Duration of the scan in milliseconds. */
31
40
  duration: number;
41
+ /** Root path of the scanned project. */
32
42
  projectRoot: string;
33
43
  };
44
+ /** Orchestration figures; set only when `orchestration.useWorkerThreads` is set. */
34
45
  orchestration?: {
46
+ /** Whether the scan ran in parallel. */
35
47
  parallel: boolean;
48
+ /** Whether only changed files were analyzed (always `false` here). */
36
49
  incremental: boolean;
50
+ /** Files selected for the scan. */
37
51
  filesAnalyzed: number;
52
+ /** Files skipped (always 0 here). */
38
53
  filesSkipped: number;
54
+ /** Cache hit rate (always 0 here). */
39
55
  cacheHitRate: number;
56
+ /** Duration of the scan in milliseconds. */
40
57
  duration: number;
58
+ /** Files per second. */
41
59
  throughput: number;
42
60
  };
61
+ /** What the page covers of all violations. */
43
62
  pagination?: {
63
+ /** Number of all violations. */
44
64
  totalResults: number;
65
+ /** Number of violations in this page. */
45
66
  returnedResults: number;
67
+ /** Offset of the page (`resultOffset`). */
46
68
  offset: number;
69
+ /** Whether violations follow after this page. */
47
70
  hasMore: boolean;
48
71
  };
49
72
  }
50
73
  /**
51
- * Scan for Angular best practice violations using the AngularPlugin.
74
+ * MCP tool `scan-angular`: scans for Angular-specific best practice
75
+ * violations. Runs only the AngularPlugin (28 rules: OnPush, TrackBy,
76
+ * performance, RxJS and others).
52
77
  */
53
78
  export declare class ScanAngularTool implements MCPTool {
54
79
  readonly name = "scan-angular";
55
80
  readonly title = "Scan Angular Patterns";
56
81
  readonly annotations: ToolAnnotations;
57
82
  readonly description: string;
83
+ /**
84
+ * JSON Schema of the tool arguments.
85
+ * @hidden
86
+ */
58
87
  readonly inputSchema: {
59
88
  type: string;
60
89
  additionalProperties: boolean;
@@ -124,6 +153,10 @@ export declare class ScanAngularTool implements MCPTool {
124
153
  };
125
154
  required: string[];
126
155
  };
156
+ /**
157
+ * JSON Schema of the tool result (`structuredContent`).
158
+ * @hidden
159
+ */
127
160
  readonly outputSchema: {
128
161
  type: "object";
129
162
  properties: Record<string, unknown>;
@@ -137,5 +170,4 @@ export declare class ScanAngularTool implements MCPTool {
137
170
  private loadConfig;
138
171
  private calculateSummary;
139
172
  }
140
- export {};
141
173
  //# sourceMappingURL=scan-angular.d.ts.map
@@ -1,22 +1,15 @@
1
- /**
2
- * @angular-modernizer/adapter-mcp - Scan Angular Best Practices Tool
3
- *
4
- * MCP tool for scanning Angular codebases for Angular-specific best practice violations.
5
- * Runs only the AngularPlugin (28 rules: OnPush, TrackBy, Performance, RxJS, etc.).
6
- */
7
1
  import { findTsConfig } from './helpers/find-ts-config.js';
8
- import { Kernel, createToolCacheConfig, loadConfig, } from '@angular-modernizer/core';
9
- import { AngularPlugin } from '@angular-modernizer/plugin-angular';
10
- import { ContextFactory } from '@angular-modernizer/plugin-system';
11
- import { createPublicApi } from '@angular-modernizer/api';
12
2
  import { glob } from 'glob';
13
3
  import { resolve, relative } from 'node:path';
14
4
  import { readFileSync, existsSync } from 'node:fs';
15
5
  import { describeScan, SCAN_EXECUTION_SCHEMA, scanOutputSchema, } from './helpers/analysis-output.js';
16
- import { cancelledExecution, fileProgressMessage, yieldIfCancellable, } from './helpers/tool-context.js';
17
- import { loadSourceFiles } from './helpers/load-source-files.js';
6
+ import { cancelledExecution, fileProgressMessage, } from './helpers/tool-context.js';
7
+ import { runScan } from '../scan-host/scan-host.js';
8
+ import { openToolCache } from './helpers/tool-cache.js';
18
9
  /**
19
- * Scan for Angular best practice violations using the AngularPlugin.
10
+ * MCP tool `scan-angular`: scans for Angular-specific best practice
11
+ * violations. Runs only the AngularPlugin (28 rules: OnPush, TrackBy,
12
+ * performance, RxJS and others).
20
13
  */
21
14
  export class ScanAngularTool {
22
15
  name = 'scan-angular';
@@ -29,6 +22,10 @@ export class ScanAngularTool {
29
22
  };
30
23
  description = 'Scan for Angular best practice violations (OnPush, TrackBy, Performance, RxJS, etc.). maxResults (default 1000) ' +
31
24
  'and resultOffset page the violations; counts cover all of them, summary is a short text.';
25
+ /**
26
+ * JSON Schema of the tool arguments.
27
+ * @hidden
28
+ */
32
29
  inputSchema = {
33
30
  type: 'object',
34
31
  additionalProperties: false,
@@ -101,6 +98,10 @@ export class ScanAngularTool {
101
98
  },
102
99
  required: ['rootPath'],
103
100
  };
101
+ /**
102
+ * JSON Schema of the tool result (`structuredContent`).
103
+ * @hidden
104
+ */
104
105
  outputSchema = scanOutputSchema({ execution: SCAN_EXECUTION_SCHEMA });
105
106
  async execute(args, ctx = {}) {
106
107
  const params = args;
@@ -115,16 +116,6 @@ export class ScanAngularTool {
115
116
  if (!tsConfigPath) {
116
117
  throw new Error('Could not find tsconfig.json');
117
118
  }
118
- // Initialize kernel with AngularPlugin and caching
119
- const kernel = new Kernel({
120
- tsConfigPath,
121
- plugins: [new AngularPlugin()],
122
- fileSystem: undefined,
123
- projectOptions: {
124
- skipAddingFilesFromTsConfig: true, // We'll add filtered files manually
125
- },
126
- cacheConfig: createToolCacheConfig(mergedParams.rootPath, 'angular'),
127
- });
128
119
  // Find files to analyze
129
120
  const includePatterns = mergedParams.includePatterns ?? ['**/*.{ts,tsx}'];
130
121
  const excludePatterns = mergedParams.excludePatterns ?? [
@@ -150,16 +141,7 @@ export class ScanAngularTool {
150
141
  const uniqueFiles = Array.from(new Set(allFiles)).sort();
151
142
  const filesToAnalyze = uniqueFiles; // Analyze ALL files found (batch processing prevents memory issues)
152
143
  const maxFiles = mergedParams.maxFiles ?? 100; // Batch size (default 100)
153
- // Initialize kernel
154
- await kernel.initialize();
155
- // Load rules config from .angular-modernizer.json for per-rule overrides (BUG-3)
156
- const fullConfig = loadConfig(mergedParams.rootPath);
157
- const rulesConfig = fullConfig.rules;
158
- // Get analysis rules from the already-initialized plugin instances so that
159
- // ruleConfigs from .angular-modernizer.json are applied correctly.
160
- const allRules = kernel
161
- .getAllPlugins()
162
- .flatMap((p) => p.getAnalysisRules());
144
+ const cache = await openToolCache(mergedParams.rootPath, 'angular');
163
145
  // ============================================================================
164
146
  // CACHE READ SYSTEM
165
147
  // ============================================================================
@@ -179,28 +161,20 @@ export class ScanAngularTool {
179
161
  // Cache directory: .angular-modernizer-cache/angular/
180
162
  // Cache invalidation: Automatic via mtime/content hash checking
181
163
  // ============================================================================
182
- const cacheManagerForRead = kernel.getCacheManager();
183
164
  const cachedResults = []; // eslint-disable-line @typescript-eslint/no-explicit-any
184
- let filesToProcess = [];
185
- if (cacheManagerForRead) {
186
- for (const filePath of filesToAnalyze) {
187
- const cached = await cacheManagerForRead.getAnalysisResult(filePath);
188
- if (cached?.results && cached.results.length > 0) {
189
- // File is cached and hasn't changed
190
- cachedResults.push(...cached.results);
191
- }
192
- else {
193
- // File not cached or has changed
194
- filesToProcess.push(filePath);
195
- }
165
+ const filesToProcess = [];
166
+ for (const filePath of filesToAnalyze) {
167
+ const cached = await cache.getAnalysisResult(filePath);
168
+ if (cached?.results && cached.results.length > 0) {
169
+ // File is cached and hasn't changed
170
+ cachedResults.push(...cached.results);
171
+ }
172
+ else {
173
+ // File not cached or has changed
174
+ filesToProcess.push(filePath);
196
175
  }
197
- const stats = cacheManagerForRead.getStats();
198
- console.info(`Cache: ${cachedResults.length} results from cache, ${filesToProcess.length} files to analyze (hit rate: ${stats.hitRate.toFixed(1)}%)`);
199
- }
200
- else {
201
- // No cache manager, analyze all files
202
- filesToProcess = filesToAnalyze;
203
176
  }
177
+ console.info(`Cache: ${cachedResults.length} results from cache, ${filesToProcess.length} files to analyze (hit rate: ${cache.getStats().hitRate.toFixed(1)}%)`);
204
178
  // ============================================================================
205
179
  // BATCH PROCESSING SYSTEM
206
180
  // ============================================================================
@@ -220,73 +194,33 @@ export class ScanAngularTool {
220
194
  // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
221
195
  const results = [...cachedResults];
222
196
  let filesAnalyzed = cachedResults.length;
223
- // Process each batch; cancellation is checked between files
197
+ // Kernel, batches and rules run in a scan worker (scan-host), so the
198
+ // server keeps reading stdin while the type checker is built.
224
199
  const cachedFiles = filesToAnalyze.length - totalFiles;
225
200
  let processedFiles = 0;
226
- let cancelled = false;
227
- for (let batchNum = 0; batchNum < totalBatches && !cancelled; batchNum++) {
228
- const batchStart = batchNum * batchSize;
229
- const batchEnd = Math.min(batchStart + batchSize, totalFiles);
230
- const batchFiles = filesToProcess.slice(batchStart, batchEnd);
231
- console.info(`\nBatch ${batchNum + 1}/${totalBatches}: Processing files ${batchStart + 1}-${batchEnd} (${batchFiles.length} files)`);
232
- // Clear project and add batch files
233
- const project = kernel.getProject();
234
- // Remove all source files from previous batch
235
- const existingFiles = project.getSourceFiles();
236
- for (const file of existingFiles) {
237
- project.removeSourceFile(file);
238
- }
239
- // Add current batch files; a cancel during the load stops the scan
240
- const loaded = await loadSourceFiles(project, batchFiles, { signal: ctx.signal });
241
- if (loaded.cancelled) {
242
- cancelled = true;
243
- break;
244
- }
245
- console.info(`Batch ${batchNum + 1}: Project now has ${project.getSourceFiles().length} source files`);
246
- // Create PublicApi for this batch
247
- const api = createPublicApi(project); // eslint-disable-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
248
- // Analyze files in this batch
249
- let batchViolationCount = 0;
250
- for (const sourceFile of project.getSourceFiles()) {
251
- await yieldIfCancellable(ctx.signal);
252
- if (ctx.signal?.aborted === true) {
253
- cancelled = true;
254
- break;
255
- }
256
- for (const rule of allRules) {
257
- try {
258
- const ruleResults = await rule.analyze(ContextFactory.createAnalysisContext({
259
- sourceFile,
260
- project,
261
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
262
- api,
263
- config: rulesConfig,
264
- }));
265
- for (const result of ruleResults) {
266
- results.push({
267
- ruleId: result.ruleId,
268
- severity: result.severity ?? rule.severity,
269
- message: result.message,
270
- filePath: result.filePath,
271
- line: result.line,
272
- column: result.column,
273
- category: rule.category,
274
- suggestedFix: result.suggestedFix,
275
- metadata: result.metadata,
276
- });
277
- batchViolationCount++;
278
- }
279
- }
280
- catch (error) {
281
- console.warn(`Failed to analyze with rule ${rule.id}:`, error);
282
- }
283
- }
201
+ if (totalFiles > 0) {
202
+ ctx.progress?.(cachedFiles, filesToAnalyze.length, `loading project, ${totalFiles} files to analyze`);
203
+ }
204
+ const engine = await runScan({
205
+ tool: this.name,
206
+ plugins: 'angular',
207
+ tsConfigPath,
208
+ rootPath: mergedParams.rootPath,
209
+ files: filesToProcess,
210
+ mode: 'batches',
211
+ batchSize,
212
+ analyzeProjectFiles: true,
213
+ }, {
214
+ file: (event) => {
215
+ results.push(...event.findings);
284
216
  processedFiles++;
285
217
  ctx.progress?.(cachedFiles + processedFiles, filesToAnalyze.length, fileProgressMessage(cachedFiles + processedFiles, filesToAnalyze.length, results.length));
286
- }
287
- filesAnalyzed += batchFiles.length;
288
- console.info(`Batch ${batchNum + 1}: Found ${batchViolationCount} violations in ${batchFiles.length} files`);
289
- }
218
+ },
219
+ batchDone: (files) => {
220
+ filesAnalyzed += files;
221
+ },
222
+ }, { signal: ctx.signal });
223
+ const cancelled = engine.cancelled;
290
224
  console.info(`\nBatch processing complete: ${totalBatches} batch(es), ${filesAnalyzed} total files analyzed, ${results.length} total violations`);
291
225
  // ============================================================================
292
226
  // CACHE WRITE SYSTEM
@@ -306,26 +240,23 @@ export class ScanAngularTool {
306
240
  // - Parsing Angular templates and metadata takes significant time
307
241
  // - Cache hit eliminates all AST parsing and decorator analysis overhead
308
242
  // ============================================================================
309
- const cacheManager = kernel.getCacheManager();
310
- if (cacheManager) {
311
- // Group results by file path
312
- const resultsByFile = new Map();
313
- for (const result of results) {
314
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
315
- const filePath = result.filePath;
316
- if (!resultsByFile.has(filePath)) {
317
- resultsByFile.set(filePath, []);
318
- }
319
- resultsByFile.get(filePath).push(result);
320
- }
321
- // Write each file's results to cache
322
- for (const [filePath, fileResults] of resultsByFile.entries()) {
323
- await cacheManager.setAnalysisResult(filePath, fileResults);
243
+ // Group results by file path
244
+ const resultsByFile = new Map();
245
+ for (const result of results) {
246
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
247
+ const filePath = result.filePath;
248
+ if (!resultsByFile.has(filePath)) {
249
+ resultsByFile.set(filePath, []);
324
250
  }
325
- // Log cache effectiveness
326
- const stats = cacheManager.getStats();
327
- console.info(`Cached ${resultsByFile.size} files (hit rate: ${stats.hitRate.toFixed(1)}%)`);
251
+ resultsByFile.get(filePath).push(result);
252
+ }
253
+ // Write each file's results to cache
254
+ for (const [filePath, fileResults] of resultsByFile.entries()) {
255
+ await cache.setAnalysisResult(filePath, fileResults);
328
256
  }
257
+ // Log cache effectiveness
258
+ const stats = cache.getStats();
259
+ console.info(`Cached ${resultsByFile.size} files (hit rate: ${stats.hitRate.toFixed(1)}%)`);
329
260
  // Filter by specific rules if requested
330
261
  let violations = results
331
262
  .filter((r) => r.ruleId && r.filePath)
@@ -364,12 +295,12 @@ export class ScanAngularTool {
364
295
  hasMore: offset + maxResults < totalViolations,
365
296
  };
366
297
  const duration = Date.now() - startTime;
367
- const angularRules = allRules.map((r) => r.id);
298
+ const ruleIds = engine.ruleIds;
368
299
  return {
369
300
  violations: paginatedViolations,
370
301
  counts,
371
302
  metadata: {
372
- rulesExecuted: angularRules,
303
+ rulesExecuted: ruleIds,
373
304
  duration,
374
305
  projectRoot: mergedParams.rootPath,
375
306
  },