@angular-modernizer/adapter-mcp 1.0.0 → 1.2.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 (131) hide show
  1. package/README.md +81 -65
  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 +58 -36
  24. package/dist/tools/analyze-build-impact.js +36 -29
  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 +87 -14
  30. package/dist/tools/analyze-project.js +140 -122
  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 +27 -25
  40. package/dist/tools/find-angular-symbol.js +19 -16
  41. package/dist/tools/find-component-hosts.d.ts +33 -27
  42. package/dist/tools/find-component-hosts.js +27 -24
  43. package/dist/tools/find-usages.d.ts +25 -23
  44. package/dist/tools/find-usages.js +21 -18
  45. package/dist/tools/get-bootstrap-execution.d.ts +35 -27
  46. package/dist/tools/get-bootstrap-execution.js +28 -25
  47. package/dist/tools/get-call-graph.d.ts +19 -14
  48. package/dist/tools/get-call-graph.js +26 -23
  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 +123 -36
  60. package/dist/tools/helpers/project-cache.js +227 -43
  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/scan-plan.d.ts +1 -1
  66. package/dist/tools/helpers/scan-plan.js +1 -1
  67. package/dist/tools/helpers/suggestion-generator.d.ts +9 -13
  68. package/dist/tools/helpers/suggestion-generator.js +0 -12
  69. package/dist/tools/helpers/tool-cache.d.ts +11 -0
  70. package/dist/tools/helpers/tool-cache.js +15 -0
  71. package/dist/tools/helpers/tool-context.d.ts +11 -8
  72. package/dist/tools/helpers/tool-context.js +5 -8
  73. package/dist/tools/inspect-form-group.d.ts +34 -27
  74. package/dist/tools/inspect-form-group.js +27 -24
  75. package/dist/tools/inspect-i18n.d.ts +31 -25
  76. package/dist/tools/inspect-i18n.js +23 -20
  77. package/dist/tools/inspect-template.d.ts +32 -25
  78. package/dist/tools/inspect-template.js +26 -23
  79. package/dist/tools/learn-patterns.d.ts +88 -12
  80. package/dist/tools/learn-patterns.js +17 -11
  81. package/dist/tools/list-imports.d.ts +45 -28
  82. package/dist/tools/list-imports.js +26 -23
  83. package/dist/tools/orchestrate-migration.d.ts +31 -9
  84. package/dist/tools/orchestrate-migration.js +12 -7
  85. package/dist/tools/parse-stack-trace.d.ts +23 -21
  86. package/dist/tools/parse-stack-trace.js +10 -7
  87. package/dist/tools/plan-migration.d.ts +67 -27
  88. package/dist/tools/plan-migration.js +22 -21
  89. package/dist/tools/resolve-type.d.ts +20 -10
  90. package/dist/tools/resolve-type.js +21 -13
  91. package/dist/tools/review-feedback.d.ts +27 -24
  92. package/dist/tools/review-feedback.js +24 -20
  93. package/dist/tools/rollback-changes.d.ts +13 -9
  94. package/dist/tools/rollback-changes.js +10 -7
  95. package/dist/tools/run-angular-cli.d.ts +12 -10
  96. package/dist/tools/run-angular-cli.js +11 -8
  97. package/dist/tools/run-build.d.ts +13 -11
  98. package/dist/tools/run-build.js +11 -8
  99. package/dist/tools/run-schematic.d.ts +12 -10
  100. package/dist/tools/run-schematic.js +11 -8
  101. package/dist/tools/scan-all.d.ts +69 -12
  102. package/dist/tools/scan-all.js +55 -122
  103. package/dist/tools/scan-angular.d.ts +41 -9
  104. package/dist/tools/scan-angular.js +66 -135
  105. package/dist/tools/scan-architecture.d.ts +75 -14
  106. package/dist/tools/scan-architecture.js +180 -185
  107. package/dist/tools/scan-solid.d.ts +40 -9
  108. package/dist/tools/scan-solid.js +64 -133
  109. package/dist/tools/search-codebase.d.ts +32 -26
  110. package/dist/tools/search-codebase.js +15 -12
  111. package/dist/tools/server-status.d.ts +116 -24
  112. package/dist/tools/server-status.js +85 -26
  113. package/dist/tools/suggest-improvements.d.ts +22 -19
  114. package/dist/tools/suggest-improvements.js +21 -17
  115. package/dist/tools/trace-output-flow.d.ts +34 -27
  116. package/dist/tools/trace-output-flow.js +27 -24
  117. package/dist/tools/transform-code.d.ts +71 -10
  118. package/dist/tools/transform-code.js +148 -54
  119. package/dist/tools/validate-before-transform.d.ts +24 -9
  120. package/dist/tools/validate-before-transform.js +10 -7
  121. package/dist/tools/validate-project-compatibility.d.ts +18 -13
  122. package/dist/tools/validate-project-compatibility.js +17 -11
  123. package/dist/tools/validate-transformation.d.ts +28 -11
  124. package/dist/tools/validate-transformation.js +14 -8
  125. package/dist/tools/verify-citations.d.ts +37 -16
  126. package/dist/tools/verify-citations.js +19 -16
  127. package/dist/types.d.ts +40 -10
  128. package/dist/types.js +0 -5
  129. package/package.json +12 -18
  130. package/dist/tools/shared/scan-types.d.ts +0 -200
  131. package/dist/tools/shared/scan-types.js +0 -7
@@ -1,11 +1,7 @@
1
- /**
2
- * @angular-modernizer/adapter-mcp - Scan Architecture Tool
3
- *
4
- * MCP tool for scanning Angular codebases for architectural issues.
5
- * Runs only the ArchitecturePlugin (17 rules: import cycles, layer violations, god objects, etc.).
6
- */
7
1
  import { findTsConfig } from './helpers/find-ts-config.js';
8
- import { cancelledExecution, fileProgress, yieldIfCancellable, } from './helpers/tool-context.js';
2
+ import { cancelledExecution, fileProgressMessage, yieldIfCancellable, } from './helpers/tool-context.js';
3
+ import { runScan } from '../scan-host/scan-host.js';
4
+ import { openToolCache } from './helpers/tool-cache.js';
9
5
  import { loadSourceFiles } from './helpers/load-source-files.js';
10
6
  import { filterFilesByScopePaths } from './helpers/scope-paths.js';
11
7
  import { toParallelOptions } from '../types.js';
@@ -17,7 +13,6 @@ import { glob } from 'glob';
17
13
  import { resolve, extname } from 'node:path';
18
14
  import { readFileSync, existsSync, statSync } from 'node:fs';
19
15
  import { randomUUID } from 'node:crypto';
20
- import { cpus } from 'node:os';
21
16
  import { ProgressStore } from '../streaming/progress-store.js';
22
17
  import { describeScan, scanOutputSchema, } from './helpers/analysis-output.js';
23
18
  import { incompleteNote, parseMaxDurationMs, runRulesOverFiles, } from './helpers/rule-runner.js';
@@ -52,10 +47,9 @@ function withScanSummary(result) {
52
47
  };
53
48
  }
54
49
  /**
55
- * Scan Architecture Tool
56
- *
57
- * Provides architectural analysis capabilities through MCP with the rules of
58
- * the ArchitecturePlugin.
50
+ * MCP tool `scan-architecture`: scans for architectural issues. Runs only the
51
+ * ArchitecturePlugin (17 rules: import cycles, layer violations, god objects
52
+ * and others).
59
53
  */
60
54
  export class ScanArchitectureTool {
61
55
  name = 'scan-architecture';
@@ -70,6 +64,10 @@ export class ScanArchitectureTool {
70
64
  '(solid:circular-dependency, NG0919 risk), import direction, god objects, layer boundaries, content ' +
71
65
  'placement, service bags and more. Returns the violations directly; streaming: true (deprecated) runs in the background instead (poll get-operation-progress); ' +
72
66
  'maxResults (default 1000) and resultOffset page the violations; counts cover all of them, summary is a short text.';
67
+ /**
68
+ * JSON Schema of the tool arguments.
69
+ * @hidden
70
+ */
73
71
  inputSchema = {
74
72
  type: 'object',
75
73
  additionalProperties: false,
@@ -162,16 +160,16 @@ export class ScanArchitectureTool {
162
160
  },
163
161
  orchestration: {
164
162
  type: 'object',
165
- description: 'Advanced orchestration options for analysis',
163
+ description: 'Deprecated, kept in 1.x: parallel and incremental run the old WorkerPool path on the main thread. On a large app it was no faster than the default path, blocked the server for seconds and took about four times the memory. Leave unset; the default path runs in the scan worker and answers cancellation at once.',
166
164
  properties: {
167
165
  parallel: {
168
166
  type: 'boolean',
169
- description: 'Enable parallel rule execution for faster scanning',
167
+ description: 'Deprecated: runs the old WorkerPool path (only with apiStyle imperative). Leave unset.',
170
168
  default: false,
171
169
  },
172
170
  incremental: {
173
171
  type: 'boolean',
174
- description: 'Only analyze changed files (requires git)',
172
+ description: 'Deprecated: analyzes files changed against baseBranch (requires git, else every file) on the main thread. Leave unset.',
175
173
  default: false,
176
174
  },
177
175
  baseBranch: {
@@ -248,6 +246,10 @@ export class ScanArchitectureTool {
248
246
  },
249
247
  required: ['rootPath'],
250
248
  };
249
+ /**
250
+ * JSON Schema of the tool result (`structuredContent`).
251
+ * @hidden
252
+ */
251
253
  outputSchema = scanOutputSchema({
252
254
  operationId: { type: 'string' },
253
255
  execution: {
@@ -326,78 +328,6 @@ export class ScanArchitectureTool {
326
328
  if (!tsConfigPath) {
327
329
  throw new Error('Could not find tsconfig.json in the project root');
328
330
  }
329
- // Initialize kernel with ArchitecturePlugin only + caching
330
- const kernel = new Kernel({
331
- tsConfigPath,
332
- plugins: [new ArchitecturePlugin()],
333
- projectOptions: {
334
- skipAddingFilesFromTsConfig: true, // CRITICAL: We manually add filtered files
335
- },
336
- cacheConfig: createToolCacheConfig(mergedParams.rootPath, 'architecture'),
337
- });
338
- await kernel.initialize();
339
- // Load rules config from .angular-modernizer.json for per-rule overrides (BUG-3)
340
- const fullConfig = loadConfig(mergedParams.rootPath);
341
- const rulesConfig = fullConfig.rules;
342
- // Detect offline mode by testing worker availability
343
- let isOfflineMode = false;
344
- try {
345
- const testWorkerPath = getWorkerScriptPath();
346
- if (existsSync(testWorkerPath)) {
347
- console.info('Worker threads available');
348
- }
349
- else {
350
- console.warn('Worker threads not available (offline mode)');
351
- isOfflineMode = true;
352
- }
353
- }
354
- catch (error) {
355
- console.warn('Worker threads not available (offline mode):', error instanceof Error ? error.message : String(error));
356
- isOfflineMode = true;
357
- }
358
- // In offline mode, disable worker threads but keep auto-selection enabled
359
- // This allows large codebases to still use Promise mode efficiently
360
- if (isOfflineMode) {
361
- console.info('Worker threads disabled in offline mode, keeping auto-selection for optimal performance');
362
- orchestration.useWorkerThreads = false;
363
- // Keep autoSelectMode enabled so large projects still get Promise parallelism
364
- }
365
- // Setup progress tracking if requested
366
- let lastProgress;
367
- if (orchestration.enableProgress) {
368
- const progressReporter = kernel.getProgressReporter();
369
- if (progressReporter) {
370
- progressReporter.on('progress', (progress) => {
371
- lastProgress = {
372
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access -- Progress event typing is dynamic
373
- current: progress.current,
374
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
375
- total: progress.total,
376
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
377
- percentage: progress.percentage,
378
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
379
- eta: progress.eta ?? 0,
380
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
381
- phase: progress.type,
382
- };
383
- });
384
- }
385
- }
386
- // Check resource limits before proceeding
387
- const resourceManager = kernel.getResourceManager();
388
- if (resourceManager && !resourceManager.canProceed()) {
389
- throw new Error('Insufficient resources to proceed with analysis');
390
- }
391
- // Get analysis rules from ArchitecturePlugin
392
- const archPlugin = kernel.getPlugin('@angular-modernizer/plugin-architecture');
393
- const allRules = archPlugin.getAnalysisRules();
394
- const rulesToRun = params.rules
395
- ? allRules.filter((rule) => params.rules.includes(rule.id))
396
- : allRules;
397
- console.info(`ScanArchitecture: Found ${allRules.length} total rules, running ${rulesToRun.length} rules:`, rulesToRun.map((r) => r.id));
398
- if (rulesToRun.length === 0) {
399
- throw new Error('No matching rules found');
400
- }
401
331
  // Run analysis using full orchestration
402
332
  // Resolve scope for targeted scanning
403
333
  const resolvedScope = this.resolveScope(params.rootPath, mergedParams.scope);
@@ -415,16 +345,86 @@ export class ScanArchitectureTool {
415
345
  const scopeFilteredFiles = resolvedScope.type !== 'all'
416
346
  ? this.filterFilesByScope(preDiscoveryFiles, resolvedScope)
417
347
  : preDiscoveryFiles;
418
- // Auto-enable parallel processing for >100 files (unless explicitly disabled)
419
- if (scopeFilteredFiles.length > 100 &&
420
- orchestration.parallel === undefined) {
421
- orchestration.parallel = true;
422
- orchestration.autoSelectMode = orchestration.autoSelectMode ?? true;
423
- orchestration.maxWorkers =
424
- orchestration.maxWorkers ?? Math.min(4, cpus().length);
425
- console.info(`Auto-enabled parallel processing for ${scopeFilteredFiles.length} files (>100 threshold)`);
426
- }
348
+ // No automatic switch to the parallel path above 100 files: on a large
349
+ // app it was no faster than the scan worker (371 files 10.8-12.1 vs
350
+ // 10.3-13.1 s), blocked the server for up to 10.7 s and took about four
351
+ // times the memory.
352
+ // The parallel and incremental paths run the kernel here (it starts its
353
+ // own analysis workers); the sequential path runs in a scan worker.
354
+ let parallelKernel;
355
+ let rulesExecuted = [];
356
+ let lastProgress;
427
357
  if (orchestration.parallel || orchestration.incremental) {
358
+ // Initialize kernel with ArchitecturePlugin only + caching
359
+ const kernel = new Kernel({
360
+ tsConfigPath,
361
+ plugins: [new ArchitecturePlugin()],
362
+ projectOptions: {
363
+ skipAddingFilesFromTsConfig: true, // CRITICAL: We manually add filtered files
364
+ },
365
+ cacheConfig: createToolCacheConfig(mergedParams.rootPath, 'architecture'),
366
+ });
367
+ await kernel.initialize();
368
+ // Detect offline mode by testing worker availability
369
+ let isOfflineMode = false;
370
+ try {
371
+ const testWorkerPath = getWorkerScriptPath();
372
+ if (existsSync(testWorkerPath)) {
373
+ console.info('Worker threads available');
374
+ }
375
+ else {
376
+ console.warn('Worker threads not available (offline mode)');
377
+ isOfflineMode = true;
378
+ }
379
+ }
380
+ catch (error) {
381
+ console.warn('Worker threads not available (offline mode):', error instanceof Error ? error.message : String(error));
382
+ isOfflineMode = true;
383
+ }
384
+ // In offline mode, disable worker threads but keep auto-selection enabled
385
+ // This allows large codebases to still use Promise mode efficiently
386
+ if (isOfflineMode) {
387
+ console.info('Worker threads disabled in offline mode, keeping auto-selection for optimal performance');
388
+ orchestration.useWorkerThreads = false;
389
+ // Keep autoSelectMode enabled so large projects still get Promise parallelism
390
+ }
391
+ // Setup progress tracking if requested
392
+ if (orchestration.enableProgress) {
393
+ const progressReporter = kernel.getProgressReporter();
394
+ if (progressReporter) {
395
+ progressReporter.on('progress', (progress) => {
396
+ lastProgress = {
397
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access -- Progress event typing is dynamic
398
+ current: progress.current,
399
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
400
+ total: progress.total,
401
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
402
+ percentage: progress.percentage,
403
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
404
+ eta: progress.eta ?? 0,
405
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
406
+ phase: progress.type,
407
+ };
408
+ });
409
+ }
410
+ }
411
+ // Check resource limits before proceeding
412
+ const resourceManager = kernel.getResourceManager();
413
+ if (resourceManager && !resourceManager.canProceed()) {
414
+ throw new Error('Insufficient resources to proceed with analysis');
415
+ }
416
+ // Get analysis rules from ArchitecturePlugin
417
+ const archPlugin = kernel.getPlugin('@angular-modernizer/plugin-architecture');
418
+ const allRules = archPlugin.getAnalysisRules();
419
+ const rulesToRun = params.rules
420
+ ? allRules.filter((rule) => params.rules.includes(rule.id))
421
+ : allRules;
422
+ console.info(`ScanArchitecture: Found ${allRules.length} total rules, running ${rulesToRun.length} rules:`, rulesToRun.map((r) => r.id));
423
+ if (rulesToRun.length === 0) {
424
+ throw new Error('No matching rules found');
425
+ }
426
+ parallelKernel = kernel;
427
+ rulesExecuted = rulesToRun.map((r) => r.id);
428
428
  // Use pre-discovered and filtered files
429
429
  const filesToAnalyze = scopeFilteredFiles;
430
430
  // Update resolved scope with matched files count
@@ -559,8 +559,6 @@ export class ScanArchitectureTool {
559
559
  else {
560
560
  // Sequential analysis mode (existing logic)
561
561
  console.info('Using sequential analysis mode...');
562
- const project = kernel.getProject();
563
- const api = createPublicApi(project); // eslint-disable-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
564
562
  let filesToAnalyze = await this.findFilesToAnalyze(params.rootPath, includePatterns, excludePatterns, maxFiles);
565
563
  // Apply scope filtering for sequential mode
566
564
  if (resolvedScope.type !== 'all') {
@@ -592,43 +590,36 @@ export class ScanArchitectureTool {
592
590
  // NOTE: Parallel mode uses kernel.analyzeParallel() which has caching built-in.
593
591
  // This cache read logic is for sequential mode only.
594
592
  // ============================================================================
595
- const cacheManagerForRead = kernel.getCacheManager();
593
+ const cache = await openToolCache(mergedParams.rootPath, 'architecture');
596
594
  const cachedViolations = []; // eslint-disable-line @typescript-eslint/no-explicit-any
597
- let filesToProcess = [];
598
- if (cacheManagerForRead) {
599
- for (const filePath of filesToAnalyze) {
600
- const cached = await cacheManagerForRead.getAnalysisResult(filePath);
601
- if (cached?.results && cached.results.length > 0) {
602
- // File is cached and hasn't changed
603
- cachedViolations.push(...cached.results);
604
- }
605
- else {
606
- // File not cached or has changed
607
- filesToProcess.push(filePath);
608
- }
595
+ const filesToProcess = [];
596
+ for (const filePath of filesToAnalyze) {
597
+ const cached = await cache.getAnalysisResult(filePath);
598
+ if (cached?.results && cached.results.length > 0) {
599
+ // File is cached and hasn't changed
600
+ cachedViolations.push(...cached.results);
601
+ }
602
+ else {
603
+ // File not cached or has changed
604
+ filesToProcess.push(filePath);
609
605
  }
610
- const stats = cacheManagerForRead.getStats();
611
- console.info(`Cache: ${cachedViolations.length} results from cache, ${filesToProcess.length} files to analyze (hit rate: ${stats.hitRate.toFixed(1)}%)`);
612
- }
613
- else {
614
- // No cache manager, analyze all files
615
- filesToProcess = filesToAnalyze;
616
606
  }
607
+ console.info(`Cache: ${cachedViolations.length} results from cache, ${filesToProcess.length} files to analyze (hit rate: ${cache.getStats().hitRate.toFixed(1)}%)`);
617
608
  // Add cached violations to results
618
609
  // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
619
610
  violations.push(...cachedViolations);
620
- const run = await runRulesOverFiles({
621
- project,
611
+ const { run, ruleIds } = await this.runRules({
612
+ tool: this.name,
613
+ plugins: 'architecture',
614
+ tsConfigPath,
615
+ rootPath: mergedParams.rootPath,
622
616
  files: filesToProcess,
623
- rules: rulesToRun,
624
- api,
625
- config: rulesConfig,
617
+ mode: 'runner',
618
+ ...(params.rules === undefined ? {} : { ruleIds: params.rules }),
626
619
  maxDurationMs,
627
620
  startTime,
628
- signal: ctx.signal,
629
- onFileAnalyzed: fileProgress(ctx.progress),
630
- });
631
- violations.push(...run.violations);
621
+ }, violations, ctx);
622
+ rulesExecuted = ruleIds;
632
623
  execution = toExecution(run, maxDurationMs);
633
624
  filesAnalyzed = filesToAnalyze.length - run.skippedFiles;
634
625
  // ============================================================================
@@ -655,26 +646,23 @@ export class ScanArchitectureTool {
655
646
  // NOTE: Parallel mode uses kernel.analyzeParallel() which has caching built-in.
656
647
  // This cache write logic is for sequential mode only.
657
648
  // ============================================================================
658
- const cacheManager = kernel.getCacheManager();
659
- if (cacheManager) {
660
- // Group violations by file path
661
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
662
- const resultsByFile = new Map();
663
- for (const violation of violations) {
664
- const filePath = violation.filePath;
665
- if (!resultsByFile.has(filePath)) {
666
- resultsByFile.set(filePath, []);
667
- }
668
- resultsByFile.get(filePath).push(violation);
669
- }
670
- // Write each file's results to cache
671
- for (const [filePath, fileResults] of resultsByFile.entries()) {
672
- await cacheManager.setAnalysisResult(filePath, fileResults);
649
+ // Group violations by file path
650
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
651
+ const resultsByFile = new Map();
652
+ for (const violation of violations) {
653
+ const filePath = violation.filePath;
654
+ if (!resultsByFile.has(filePath)) {
655
+ resultsByFile.set(filePath, []);
673
656
  }
674
- // Log cache effectiveness
675
- const stats = cacheManager.getStats();
676
- console.info(`Cache: Cached ${resultsByFile.size} files (hit rate: ${stats.hitRate.toFixed(1)}%)`);
657
+ resultsByFile.get(filePath).push(violation);
658
+ }
659
+ // Write each file's results to cache
660
+ for (const [filePath, fileResults] of resultsByFile.entries()) {
661
+ await cache.setAnalysisResult(filePath, fileResults);
677
662
  }
663
+ // Log cache effectiveness
664
+ const stats = cache.getStats();
665
+ console.info(`Cache: Cached ${resultsByFile.size} files (hit rate: ${stats.hitRate.toFixed(1)}%)`);
678
666
  }
679
667
  // Calculate summary (before pagination)
680
668
  const summary = this.calculateSummary(violations);
@@ -682,8 +670,8 @@ export class ScanArchitectureTool {
682
670
  const page = paginateViolations(violations, params);
683
671
  // Gather orchestration stats using full Phase 6d/7b options
684
672
  let orchestrationMetrics;
685
- if (orchestration.parallel || orchestration.incremental) {
686
- const stats = kernel.getOrchestrationStats();
673
+ if (parallelKernel !== undefined) {
674
+ const stats = parallelKernel.getOrchestrationStats();
687
675
  orchestrationMetrics = {
688
676
  parallel: orchestration.parallel ?? false,
689
677
  incremental: orchestration.incremental ?? false,
@@ -716,7 +704,7 @@ export class ScanArchitectureTool {
716
704
  analyzedFiles: filesAnalyzed,
717
705
  },
718
706
  metadata: {
719
- rulesExecuted: rulesToRun.map((r) => r.id),
707
+ rulesExecuted,
720
708
  duration,
721
709
  projectRoot: params.rootPath,
722
710
  },
@@ -731,6 +719,37 @@ export class ScanArchitectureTool {
731
719
  throw new Error(`Architecture scan failed: ${error instanceof Error ? error.message : String(error)}`);
732
720
  }
733
721
  }
722
+ /**
723
+ * Runs the rules through the scan engine (in a scan worker when enabled)
724
+ * and appends each file's findings to `violations`. A worker terminated by
725
+ * a cancel leaves no run summary; it is rebuilt from the files received.
726
+ */
727
+ async runRules(spec, violations, ctx) {
728
+ const total = spec.files.length;
729
+ let analyzed = 0;
730
+ let found = 0;
731
+ if (total > 0) {
732
+ ctx.progress?.(0, total, `loading project, ${total} files to analyze`);
733
+ }
734
+ const engine = await runScan(spec, {
735
+ file: (event) => {
736
+ // The runner mode sets the violation id
737
+ violations.push(...event.findings);
738
+ analyzed++;
739
+ found += event.findings.length;
740
+ ctx.progress?.(analyzed, total, fileProgressMessage(analyzed, total, found));
741
+ },
742
+ }, { signal: ctx.signal });
743
+ const run = engine.run ?? {
744
+ filesAnalyzed: analyzed,
745
+ incomplete: true,
746
+ stopReason: 'cancelled',
747
+ skippedFiles: total - analyzed,
748
+ ruleTimings: [],
749
+ durationMs: Date.now() - (spec.startTime ?? Date.now()),
750
+ };
751
+ return { run, ruleIds: engine.ruleIds };
752
+ }
734
753
  /**
735
754
  * Execute analysis using fluent API.
736
755
  */
@@ -762,26 +781,6 @@ export class ScanArchitectureTool {
762
781
  if (!tsConfigPath) {
763
782
  throw new Error('Could not find tsconfig.json in the project root');
764
783
  }
765
- // Initialize kernel with ArchitecturePlugin
766
- const kernel = new Kernel({
767
- tsConfigPath,
768
- plugins: [new ArchitecturePlugin()],
769
- projectOptions: {
770
- skipAddingFilesFromTsConfig: true,
771
- },
772
- cacheConfig: createToolCacheConfig(params.rootPath, 'architecture'),
773
- });
774
- await kernel.initialize();
775
- // Get analysis rules from ArchitecturePlugin
776
- const archPlugin = kernel.getPlugin('@angular-modernizer/plugin-architecture');
777
- const allRules = archPlugin.getAnalysisRules();
778
- const rulesToRun = params.rules
779
- ? allRules.filter((rule) => params.rules.includes(rule.id))
780
- : allRules;
781
- console.info(`ScanArchitecture (Fluent): Found ${allRules.length} total rules, running ${rulesToRun.length} rules:`, rulesToRun.map((r) => r.id));
782
- if (rulesToRun.length === 0) {
783
- throw new Error('No matching rules found');
784
- }
785
784
  // Find files to analyze — resolve scope BEFORE applying maxFiles cap so
786
785
  // that scope filtering happens on the full set, not on an arbitrary prefix.
787
786
  const maxFiles = params.maxFiles ?? 100;
@@ -798,26 +797,22 @@ export class ScanArchitectureTool {
798
797
  if (filesToAnalyze.length === 0) {
799
798
  throw new Error('No files found to analyze');
800
799
  }
801
- // Load config from .angular-modernizer.json so config-driven rules (e.g.
802
- // architecture:layer-boundary-violation) receive their layers/rule overrides.
803
- const fullConfig = loadConfig(params.rootPath);
804
- const rulesConfig = fullConfig.rules ?? {};
805
- // Run rules directly — FluentKernel creates contexts without user config,
806
- // causing config-driven rules to return 0 violations (Bug 1/3).
807
- const project = kernel.getProject();
808
- const api = createPublicApi(project);
809
- const run = await runRulesOverFiles({
810
- project,
800
+ // Rules run directly with the config of .angular-modernizer.json
801
+ // (FluentKernel creates contexts without user config, so config-driven
802
+ // rules such as layer-boundary-violation returned 0 violations, Bug 1/3),
803
+ // in a scan worker when enabled.
804
+ const violations = [];
805
+ const { run, ruleIds } = await this.runRules({
806
+ tool: this.name,
807
+ plugins: 'architecture',
808
+ tsConfigPath,
809
+ rootPath: params.rootPath,
811
810
  files: filesToAnalyze,
812
- rules: rulesToRun,
813
- api,
814
- config: rulesConfig,
811
+ mode: 'runner',
812
+ ...(params.rules === undefined ? {} : { ruleIds: params.rules }),
815
813
  maxDurationMs: parseMaxDurationMs(params.maxDurationMs),
816
814
  startTime,
817
- signal: ctx.signal,
818
- onFileAnalyzed: fileProgress(ctx.progress),
819
- });
820
- const violations = run.violations;
815
+ }, violations, ctx);
821
816
  const filesAnalyzed = run.filesAnalyzed;
822
817
  const execution = toExecution(run, parseMaxDurationMs(params.maxDurationMs));
823
818
  const duration = Date.now() - startTime;
@@ -830,7 +825,7 @@ export class ScanArchitectureTool {
830
825
  analyzedFiles: filesAnalyzed,
831
826
  },
832
827
  metadata: {
833
- rulesExecuted: rulesToRun.map((r) => r.id),
828
+ rulesExecuted: ruleIds,
834
829
  duration,
835
830
  projectRoot: params.rootPath,
836
831
  },
@@ -1,23 +1,29 @@
1
- /**
2
- * @angular-modernizer/adapter-mcp - Scan SOLID Principles Tool
3
- *
4
- * MCP tool for scanning Angular codebases for SOLID principle violations.
5
- * Runs only the SolidPlugin (7 rules: DIP, SRP, LSP, OCP, ISP).
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 ScanSolidResult {
4
+ /** Result of the scan-solid tool. */
5
+ export interface ScanSolidResult {
6
+ /** The requested page of violations (`maxResults`, `resultOffset`). */
11
7
  violations: {
8
+ /** Index-based id of the violation (`solid-<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; `SOLID` 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,57 @@ interface ScanSolidResult {
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 SOLID principle violations using the SolidPlugin.
74
+ * MCP tool `scan-solid`: scans for SOLID principle violations. Runs only the
75
+ * SolidPlugin (7 rules: DIP, SRP, LSP, OCP, ISP).
52
76
  */
53
77
  export declare class ScanSolidTool implements MCPTool {
54
78
  readonly name = "scan-solid";
55
79
  readonly title = "Scan SOLID Principles";
56
80
  readonly annotations: ToolAnnotations;
57
81
  readonly description: string;
82
+ /**
83
+ * JSON Schema of the tool arguments.
84
+ * @hidden
85
+ */
58
86
  readonly inputSchema: {
59
87
  type: string;
60
88
  additionalProperties: boolean;
@@ -124,6 +152,10 @@ export declare class ScanSolidTool implements MCPTool {
124
152
  };
125
153
  required: string[];
126
154
  };
155
+ /**
156
+ * JSON Schema of the tool result (`structuredContent`).
157
+ * @hidden
158
+ */
127
159
  readonly outputSchema: {
128
160
  type: "object";
129
161
  properties: Record<string, unknown>;
@@ -137,5 +169,4 @@ export declare class ScanSolidTool implements MCPTool {
137
169
  private loadConfig;
138
170
  private calculateSummary;
139
171
  }
140
- export {};
141
172
  //# sourceMappingURL=scan-solid.d.ts.map