@angular-modernizer/adapter-mcp 1.1.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 (38) hide show
  1. package/README.md +4 -2
  2. package/dist/index.d.ts +1 -1
  3. package/dist/tools/analyze-build-impact.d.ts +2 -2
  4. package/dist/tools/analyze-build-impact.js +6 -4
  5. package/dist/tools/analyze-project.d.ts +5 -2
  6. package/dist/tools/analyze-project.js +42 -21
  7. package/dist/tools/find-angular-symbol.d.ts +2 -2
  8. package/dist/tools/find-angular-symbol.js +3 -3
  9. package/dist/tools/find-component-hosts.d.ts +2 -2
  10. package/dist/tools/find-component-hosts.js +3 -3
  11. package/dist/tools/find-usages.d.ts +2 -2
  12. package/dist/tools/find-usages.js +3 -3
  13. package/dist/tools/get-bootstrap-execution.d.ts +2 -2
  14. package/dist/tools/get-bootstrap-execution.js +3 -3
  15. package/dist/tools/get-call-graph.d.ts +2 -2
  16. package/dist/tools/get-call-graph.js +3 -3
  17. package/dist/tools/helpers/project-cache.d.ts +73 -2
  18. package/dist/tools/helpers/project-cache.js +194 -9
  19. package/dist/tools/helpers/scan-plan.d.ts +1 -1
  20. package/dist/tools/helpers/scan-plan.js +1 -1
  21. package/dist/tools/inspect-form-group.d.ts +2 -2
  22. package/dist/tools/inspect-form-group.js +3 -3
  23. package/dist/tools/inspect-i18n.d.ts +3 -3
  24. package/dist/tools/inspect-i18n.js +3 -3
  25. package/dist/tools/inspect-template.d.ts +2 -2
  26. package/dist/tools/inspect-template.js +3 -3
  27. package/dist/tools/list-imports.d.ts +3 -3
  28. package/dist/tools/list-imports.js +3 -3
  29. package/dist/tools/plan-migration.d.ts +2 -2
  30. package/dist/tools/plan-migration.js +3 -2
  31. package/dist/tools/resolve-type.d.ts +2 -2
  32. package/dist/tools/resolve-type.js +3 -3
  33. package/dist/tools/search-codebase.d.ts +2 -2
  34. package/dist/tools/search-codebase.js +3 -3
  35. package/dist/tools/trace-output-flow.d.ts +2 -2
  36. package/dist/tools/trace-output-flow.js +3 -3
  37. package/dist/tools/transform-code.js +89 -13
  38. package/package.json +11 -11
@@ -1,6 +1,18 @@
1
1
  import { statSync } from 'node:fs';
2
- import { Project } from 'ts-morph';
2
+ import { Project, ts } from 'ts-morph';
3
3
  import { findUnresolvedLibraryImports, libraryImportWarning, } from './library-imports.js';
4
+ /** Thrown by `acquire()` when its signal aborts. */
5
+ export class ProjectLoadCancelledError extends Error {
6
+ constructor(tsConfigPath) {
7
+ super(`Loading ${tsConfigPath} was cancelled`);
8
+ this.name = 'ProjectLoadCancelledError';
9
+ }
10
+ }
11
+ /**
12
+ * Default files per batch. On a large app (3869 files) a batch of 50 takes 50
13
+ * to 75 ms to read and parse, 160 ms under heavy load.
14
+ */
15
+ export const DEFAULT_LOAD_BATCH_SIZE = 50;
4
16
  /** Default number of workspaces kept in memory at once. */
5
17
  export const DEFAULT_MAX_ENTRIES = 3;
6
18
  /**
@@ -23,6 +35,35 @@ function fileMtime(filePath) {
23
35
  return undefined;
24
36
  }
25
37
  }
38
+ /** Runs a generator to its end and returns its result. */
39
+ function runToEnd(steps) {
40
+ let step = steps.next();
41
+ while (step.done !== true) {
42
+ step = steps.next();
43
+ }
44
+ return step.value;
45
+ }
46
+ /** One turn of the event loop (stdin data, timers, other requests). */
47
+ function nextTurn() {
48
+ return new Promise((resolve) => setImmediate(resolve));
49
+ }
50
+ /**
51
+ * Opens the project of a tsconfig with its compiler options and the file list
52
+ * `new Project({ tsConfigFilePath })` would add, without adding the files.
53
+ */
54
+ export function openTsConfigProject(tsConfigFilePath) {
55
+ const project = new Project({
56
+ tsConfigFilePath,
57
+ skipAddingFilesFromTsConfig: true,
58
+ });
59
+ const parsed = ts.getParsedCommandLineOfConfigFile(tsConfigFilePath, {}, {
60
+ ...ts.sys,
61
+ onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
62
+ throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'));
63
+ },
64
+ });
65
+ return { project, files: parsed?.fileNames ?? [] };
66
+ }
26
67
  const processMemory = {
27
68
  usage: () => process.memoryUsage(),
28
69
  ...(typeof globalThis.gc === 'function'
@@ -67,6 +108,9 @@ export class ProjectCache {
67
108
  maxEntries;
68
109
  maxHeapMb;
69
110
  createProject;
111
+ openProject;
112
+ batchSize;
113
+ loading = new Map();
70
114
  memory;
71
115
  statFile;
72
116
  evictionCount = 0;
@@ -78,13 +122,16 @@ export class ProjectCache {
78
122
  constructor(options = {}) {
79
123
  this.maxEntries = Math.max(1, options.maxEntries ?? DEFAULT_MAX_ENTRIES);
80
124
  this.maxHeapMb = Math.max(0, options.maxHeapMb ?? DEFAULT_MAX_HEAP_MB);
81
- this.createProject =
82
- options.createProject ??
83
- ((tsConfigFilePath) => new Project({ tsConfigFilePath }));
125
+ this.createProject = options.createProject;
126
+ this.openProject = options.openProject ?? openTsConfigProject;
127
+ this.batchSize = Math.max(1, Math.floor(options.batchSize ?? DEFAULT_LOAD_BATCH_SIZE));
84
128
  this.memory = options.memory ?? processMemory;
85
129
  this.statFile = options.statFile ?? fileMtime;
86
130
  }
87
- /** Returns the cached Project for `tsConfigPath`, building it on a miss. */
131
+ /**
132
+ * Returns the cached Project for `tsConfigPath`, building it on a miss in
133
+ * one synchronous piece. Tools use `acquire()`.
134
+ */
88
135
  get(tsConfigPath) {
89
136
  const mtimeMs = statSync(tsConfigPath).mtimeMs;
90
137
  let project = this.touch(tsConfigPath, mtimeMs);
@@ -92,12 +139,43 @@ export class ProjectCache {
92
139
  // Make room first: a load on top of a heap already over the limit
93
140
  // would stack two large programs before the check below evicts one.
94
141
  this.evictOverHeap(tsConfigPath);
95
- project = this.load(tsConfigPath, mtimeMs);
142
+ const heapBefore = this.memory.usage().heapUsed;
143
+ project = this.store(tsConfigPath, mtimeMs, heapBefore, runToEnd(this.loadSteps(tsConfigPath)));
96
144
  }
97
145
  this.evictOverCount();
98
146
  this.evictOverHeap(tsConfigPath);
99
147
  return project;
100
148
  }
149
+ /**
150
+ * Returns the cached Project for `tsConfigPath`; on a miss loads it in
151
+ * batches of files with one event-loop turn after each, then builds the
152
+ * program and, after another turn, the type checker. The server keeps
153
+ * reading requests in between, and an aborted signal leaves the load at
154
+ * the next turn.
155
+ *
156
+ * Calls for the same tsconfig while it loads share the load. It stops only
157
+ * when every caller has left; a stopped load is not cached. A hit behaves
158
+ * like `get()`.
159
+ *
160
+ * @throws ProjectLoadCancelledError when `control.signal` aborts.
161
+ */
162
+ async acquire(tsConfigPath, control = {}) {
163
+ if (control.signal?.aborted === true) {
164
+ throw new ProjectLoadCancelledError(tsConfigPath);
165
+ }
166
+ const mtimeMs = statSync(tsConfigPath).mtimeMs;
167
+ let job = this.loading.get(tsConfigPath);
168
+ if (job === undefined) {
169
+ const project = this.touch(tsConfigPath, mtimeMs);
170
+ if (project !== undefined) {
171
+ this.evictOverCount();
172
+ this.evictOverHeap(tsConfigPath);
173
+ return project;
174
+ }
175
+ job = this.startLoad(tsConfigPath, mtimeMs);
176
+ }
177
+ return this.waitFor(tsConfigPath, job, control);
178
+ }
101
179
  /** Number of cached projects. */
102
180
  get size() {
103
181
  return this.entries.size;
@@ -199,9 +277,101 @@ export class ProjectCache {
199
277
  }
200
278
  return mtimes;
201
279
  }
202
- load(tsConfigPath, mtimeMs) {
203
- const heapBefore = this.memory.usage().heapUsed;
204
- const project = this.createProject(tsConfigPath);
280
+ /**
281
+ * The load as steps: one per batch of added files (files added, total),
282
+ * the program built after the last one. An injected `createProject` loads
283
+ * in one step.
284
+ */
285
+ *loadSteps(tsConfigPath) {
286
+ if (this.createProject !== undefined) {
287
+ return this.createProject(tsConfigPath);
288
+ }
289
+ const { project, files } = this.openProject(tsConfigPath);
290
+ for (let start = 0; start < files.length; start += this.batchSize) {
291
+ for (const filePath of files.slice(start, start + this.batchSize)) {
292
+ project.addSourceFileAtPath(filePath);
293
+ }
294
+ yield [Math.min(start + this.batchSize, files.length), files.length];
295
+ }
296
+ project.resolveSourceFileDependencies();
297
+ return project;
298
+ }
299
+ startLoad(tsConfigPath, mtimeMs) {
300
+ const state = { waiters: new Set(), cancelled: false };
301
+ const job = Object.assign(state, {
302
+ promise: this.loadInBatches(tsConfigPath, mtimeMs, state),
303
+ });
304
+ // Every waiter handles the outcome; a load nobody waits for any more
305
+ // must not end as an unhandled rejection.
306
+ job.promise.catch(() => undefined);
307
+ this.loading.set(tsConfigPath, job);
308
+ return job;
309
+ }
310
+ async loadInBatches(tsConfigPath, mtimeMs, job) {
311
+ try {
312
+ // The first turn lets the caller register as a waiter.
313
+ await nextTurn();
314
+ this.stopIfCancelled(tsConfigPath, job);
315
+ this.evictOverHeap(tsConfigPath);
316
+ const heapBefore = this.memory.usage().heapUsed;
317
+ const steps = this.loadSteps(tsConfigPath);
318
+ let step = steps.next();
319
+ while (step.done !== true) {
320
+ const [loaded, total] = step.value;
321
+ for (const waiter of job.waiters) {
322
+ waiter.onProgress?.(loaded, total);
323
+ }
324
+ await nextTurn();
325
+ this.stopIfCancelled(tsConfigPath, job);
326
+ step = steps.next();
327
+ }
328
+ const project = step.value;
329
+ await nextTurn();
330
+ this.stopIfCancelled(tsConfigPath, job);
331
+ project.getProgram().compilerObject.getTypeChecker();
332
+ const cached = this.entries.get(tsConfigPath);
333
+ const result = cached?.mtimeMs === mtimeMs
334
+ ? cached.project
335
+ : this.store(tsConfigPath, mtimeMs, heapBefore, project);
336
+ this.evictOverCount();
337
+ this.evictOverHeap(tsConfigPath);
338
+ return result;
339
+ }
340
+ finally {
341
+ // Synchronously, so a call after a stopped load starts a new one.
342
+ if (this.loading.get(tsConfigPath) === job) {
343
+ this.loading.delete(tsConfigPath);
344
+ }
345
+ }
346
+ }
347
+ stopIfCancelled(tsConfigPath, job) {
348
+ if (job.cancelled) {
349
+ throw new ProjectLoadCancelledError(tsConfigPath);
350
+ }
351
+ }
352
+ /** Joins `job` until it settles or `control.signal` aborts. */
353
+ waitFor(tsConfigPath, job, control) {
354
+ const waiter = { onProgress: control.onProgress };
355
+ job.waiters.add(waiter);
356
+ // A caller joining a load whose last caller just left keeps it going.
357
+ job.cancelled = false;
358
+ const { signal } = control;
359
+ if (signal === undefined) {
360
+ return job.promise;
361
+ }
362
+ return new Promise((resolve, reject) => {
363
+ const onAbort = () => {
364
+ job.waiters.delete(waiter);
365
+ job.cancelled = job.waiters.size === 0;
366
+ reject(new ProjectLoadCancelledError(tsConfigPath));
367
+ };
368
+ signal.addEventListener('abort', onAbort, { once: true });
369
+ void job.promise
370
+ .then(resolve, reject)
371
+ .finally(() => signal.removeEventListener('abort', onAbort));
372
+ });
373
+ }
374
+ store(tsConfigPath, mtimeMs, heapBefore, project) {
205
375
  const now = new Date();
206
376
  this.entries.set(tsConfigPath, {
207
377
  project,
@@ -327,4 +497,19 @@ export function parseProjectCacheLimits(argv, env) {
327
497
  }
328
498
  return { options, warnings };
329
499
  }
500
+ /**
501
+ * Project of a tool call from the shared cache: the call's signal leaves the
502
+ * load, and with a progress token the files loaded are reported per batch.
503
+ */
504
+ export function acquireProject(projects, tsConfigPath, ctx = {}) {
505
+ const { progress } = ctx;
506
+ return projects.acquire(tsConfigPath, {
507
+ signal: ctx.signal,
508
+ onProgress: progress === undefined
509
+ ? undefined
510
+ : (loaded, total) => {
511
+ progress(loaded, total, `${loaded}/${total} files loaded`);
512
+ },
513
+ });
514
+ }
330
515
  //# sourceMappingURL=project-cache.js.map
@@ -43,6 +43,6 @@ export declare function buildScanPlan(options: {
43
43
  violations: readonly ScanViolationInput[];
44
44
  maxPhases?: number;
45
45
  /** Project for a tsconfig, e.g. from the shared ProjectCache; a fresh Project otherwise. */
46
- loadProject?: (tsConfigPath: string) => Project;
46
+ loadProject?: (tsConfigPath: string) => Promise<Project>;
47
47
  }): Promise<ScanPlanResult>;
48
48
  //# sourceMappingURL=scan-plan.d.ts.map
@@ -81,7 +81,7 @@ export async function buildScanPlan(options) {
81
81
  if (!tsConfigPath) {
82
82
  throw new Error(`tsconfig.json not found in project: ${projectRoot}`);
83
83
  }
84
- const project = options.loadProject?.(tsConfigPath) ?? new Project({ tsConfigFilePath: tsConfigPath });
84
+ const project = (await options.loadProject?.(tsConfigPath)) ?? new Project({ tsConfigFilePath: tsConfigPath });
85
85
  const graph = new DependencyGraphBuilder(project, { templateEdges: true });
86
86
  await graph.buildGraph();
87
87
  const { layers, source } = await loadLayers(projectRoot, warnings);
@@ -1,4 +1,4 @@
1
- import { type MCPTool, type ToolAnnotations } from '../types.js';
1
+ import { type MCPTool, type ToolAnnotations, type ToolContext } from '../types.js';
2
2
  import { type InspectedForm, type InspectedFormControl } from '@angular-modernizer/api';
3
3
  import { ProjectCache } from './helpers/project-cache.js';
4
4
  /** A control with the cascade optionally dropped. */
@@ -324,7 +324,7 @@ export declare class InspectFormGroupTool implements MCPTool {
324
324
  };
325
325
  required: string[];
326
326
  };
327
- execute(args: Record<string, unknown>): Promise<InspectFormGroupOutput>;
327
+ execute(args: Record<string, unknown>, ctx?: ToolContext): Promise<InspectFormGroupOutput>;
328
328
  private shape;
329
329
  private buildSummary;
330
330
  }
@@ -2,7 +2,7 @@ import { FormGroupInspector, } from '@angular-modernizer/api';
2
2
  import { existsSync } from 'node:fs';
3
3
  import { isAbsolute, resolve } from 'node:path';
4
4
  import { findTsConfig } from './helpers/find-ts-config.js';
5
- import { ProjectCache } from './helpers/project-cache.js';
5
+ import { ProjectCache, acquireProject } from './helpers/project-cache.js';
6
6
  import { COMPACT_OUTPUT_SCHEMA, limitList, parseCompactOptions, } from './helpers/compact-output.js';
7
7
  import { WARNINGS_OUTPUT_SCHEMA, withWarnings, } from './helpers/output-contract.js';
8
8
  import { STRING_ARRAY } from './helpers/investigation-schemas.js';
@@ -197,7 +197,7 @@ export class InspectFormGroupTool {
197
197
  },
198
198
  required: ['forms', 'summary', 'tsConfigPath'],
199
199
  };
200
- async execute(args) {
200
+ async execute(args, ctx = {}) {
201
201
  const params = args;
202
202
  if (!params.file || typeof params.file !== 'string') {
203
203
  throw new Error('file is required');
@@ -217,7 +217,7 @@ export class InspectFormGroupTool {
217
217
  if (!tsConfigPath) {
218
218
  throw new Error(`tsconfig.json not found in projectRoot: ${params.projectRoot}`);
219
219
  }
220
- const project = this.projects.get(tsConfigPath);
220
+ const project = await acquireProject(this.projects, tsConfigPath, ctx);
221
221
  if (!project.getSourceFile(filePath)) {
222
222
  throw new Error(`file is not part of the tsconfig program: ${filePath}`);
223
223
  }
@@ -1,4 +1,4 @@
1
- import { type MCPTool, type ToolAnnotations } from '../types.js';
1
+ import { type MCPTool, type ToolAnnotations, type ToolContext } from '../types.js';
2
2
  import { type I18nReport, type I18nSourceSummary } from '@angular-modernizer/api';
3
3
  import { ProjectCache } from './helpers/project-cache.js';
4
4
  /** List fields of the report that `summaryOnly` drops and `maxResults` caps. */
@@ -448,7 +448,7 @@ export declare class InspectI18nTool implements MCPTool {
448
448
  type: string;
449
449
  };
450
450
  };
451
- required: ("usages" | "templatesScanned" | "undefinedKeys" | "missingTranslations" | "dynamicPrefixes" | "unresolvedUsages" | "sources" | "definedKeys" | "usedKeys" | "noStaticUsage" | "coveredByDynamic" | "referencedAsLiteral" | "dynamicUsages")[];
451
+ required: ("usages" | "templatesScanned" | "definedKeys" | "sources" | "usedKeys" | "undefinedKeys" | "missingTranslations" | "noStaticUsage" | "coveredByDynamic" | "referencedAsLiteral" | "dynamicPrefixes" | "dynamicUsages" | "unresolvedUsages")[];
452
452
  };
453
453
  truncated: {
454
454
  type: string;
@@ -462,7 +462,7 @@ export declare class InspectI18nTool implements MCPTool {
462
462
  };
463
463
  required: string[];
464
464
  };
465
- execute(args: Record<string, unknown>): Promise<InspectI18nOutput>;
465
+ execute(args: Record<string, unknown>, ctx?: ToolContext): Promise<InspectI18nOutput>;
466
466
  private parseText;
467
467
  private parseI18nNames;
468
468
  private shape;
@@ -2,7 +2,7 @@ import { I18nInspector, } from '@angular-modernizer/api';
2
2
  import { existsSync } from 'node:fs';
3
3
  import { relative } from 'node:path';
4
4
  import { findTsConfig } from './helpers/find-ts-config.js';
5
- import { ProjectCache } from './helpers/project-cache.js';
5
+ import { ProjectCache, acquireProject } from './helpers/project-cache.js';
6
6
  import { COMPACT_OUTPUT_SCHEMA, limitList, parseCompactOptions, } from './helpers/compact-output.js';
7
7
  import { WARNINGS_OUTPUT_SCHEMA, withWarnings, } from './helpers/output-contract.js';
8
8
  import { STRING_ARRAY } from './helpers/investigation-schemas.js';
@@ -271,7 +271,7 @@ export class InspectI18nTool {
271
271
  'tsConfigPath',
272
272
  ],
273
273
  };
274
- async execute(args) {
274
+ async execute(args, ctx = {}) {
275
275
  const params = args;
276
276
  if (!params.projectRoot || typeof params.projectRoot !== 'string') {
277
277
  throw new Error('projectRoot is required');
@@ -290,7 +290,7 @@ export class InspectI18nTool {
290
290
  if (!tsConfigPath) {
291
291
  throw new Error(`tsconfig.json not found in projectRoot: ${params.projectRoot}`);
292
292
  }
293
- const project = this.projects.get(tsConfigPath);
293
+ const project = await acquireProject(this.projects, tsConfigPath, ctx);
294
294
  const report = new I18nInspector(project, {
295
295
  rootDir: params.projectRoot,
296
296
  ...(key === undefined ? {} : { key }),
@@ -1,4 +1,4 @@
1
- import { type MCPTool, type ToolAnnotations } from '../types.js';
1
+ import { type MCPTool, type ToolAnnotations, type ToolContext } from '../types.js';
2
2
  import { type ComponentTemplateReport } from '@angular-modernizer/api';
3
3
  import { ProjectCache } from './helpers/project-cache.js';
4
4
  /** List fields of a template report that `summaryOnly` drops and `maxResults` caps. */
@@ -319,7 +319,7 @@ export declare class InspectTemplateTool implements MCPTool {
319
319
  };
320
320
  required: string[];
321
321
  };
322
- execute(args: Record<string, unknown>): Promise<InspectTemplateOutput>;
322
+ execute(args: Record<string, unknown>, ctx?: ToolContext): Promise<InspectTemplateOutput>;
323
323
  private parseI18nNames;
324
324
  private shape;
325
325
  private buildSummary;
@@ -2,7 +2,7 @@ import { TemplateInspector, } from '@angular-modernizer/api';
2
2
  import { existsSync } from 'node:fs';
3
3
  import { isAbsolute, resolve } from 'node:path';
4
4
  import { findTsConfig } from './helpers/find-ts-config.js';
5
- import { ProjectCache } from './helpers/project-cache.js';
5
+ import { ProjectCache, acquireProject } from './helpers/project-cache.js';
6
6
  import { COMPACT_OUTPUT_SCHEMA, limitList, parseCompactOptions, } from './helpers/compact-output.js';
7
7
  import { configuredComponentDecorators } from './helpers/project-decorators.js';
8
8
  import { WARNINGS_OUTPUT_SCHEMA, withWarnings, } from './helpers/output-contract.js';
@@ -232,7 +232,7 @@ export class InspectTemplateTool {
232
232
  },
233
233
  required: ['templates', 'summary', 'tsConfigPath'],
234
234
  };
235
- async execute(args) {
235
+ async execute(args, ctx = {}) {
236
236
  const params = args;
237
237
  if (!params.file || typeof params.file !== 'string') {
238
238
  throw new Error('file is required');
@@ -255,7 +255,7 @@ export class InspectTemplateTool {
255
255
  if (!tsConfigPath) {
256
256
  throw new Error(`tsconfig.json not found in projectRoot: ${params.projectRoot}`);
257
257
  }
258
- const project = this.projects.get(tsConfigPath);
258
+ const project = await acquireProject(this.projects, tsConfigPath, ctx);
259
259
  if (!filePath.endsWith('.html') && !project.getSourceFile(filePath)) {
260
260
  throw new Error(`file is not part of the tsconfig program: ${filePath}`);
261
261
  }
@@ -1,4 +1,4 @@
1
- import { type MCPTool, type ToolAnnotations } from '../types.js';
1
+ import { type MCPTool, type ToolAnnotations, type ToolContext } from '../types.js';
2
2
  import { type ModuleSpecifierKind } from '@angular-modernizer/core';
3
3
  import { ProjectCache } from './helpers/project-cache.js';
4
4
  /**
@@ -219,7 +219,7 @@ export declare class ListImportsTool implements MCPTool {
219
219
  type: string;
220
220
  };
221
221
  };
222
- required: ("total" | "external" | "unresolved" | "aliased" | "relative" | "reExports" | "typeOnly")[];
222
+ required: ("total" | "unresolved" | "typeOnly" | "aliased" | "relative" | "external" | "reExports")[];
223
223
  };
224
224
  summary: {
225
225
  type: string;
@@ -227,7 +227,7 @@ export declare class ListImportsTool implements MCPTool {
227
227
  };
228
228
  required: string[];
229
229
  };
230
- execute(args: Record<string, unknown>): Promise<ListImportsOutput>;
230
+ execute(args: Record<string, unknown>, ctx?: ToolContext): Promise<ListImportsOutput>;
231
231
  private resolveFilePath;
232
232
  private findProjectRoot;
233
233
  private toEntry;
@@ -3,7 +3,7 @@ import { classifyModuleSpecifier, collectModuleEdges, } from '@angular-modernize
3
3
  import { existsSync } from 'node:fs';
4
4
  import { dirname, isAbsolute, relative, resolve } from 'node:path';
5
5
  import { findTsConfig } from './helpers/find-ts-config.js';
6
- import { ProjectCache } from './helpers/project-cache.js';
6
+ import { ProjectCache, acquireProject } from './helpers/project-cache.js';
7
7
  import { COMPACT_OUTPUT_SCHEMA, limitList, parseCompactOptions, truncationNote, } from './helpers/compact-output.js';
8
8
  import { WARNINGS_OUTPUT_SCHEMA, withWarnings, } from './helpers/output-contract.js';
9
9
  /** Unresolved specifiers named in the summary. */
@@ -139,7 +139,7 @@ export class ListImportsTool {
139
139
  },
140
140
  required: ['file', 'projectRoot', 'tsConfigPath', 'truncated', 'counts', 'summary'],
141
141
  };
142
- async execute(args) {
142
+ async execute(args, ctx = {}) {
143
143
  const params = args;
144
144
  if (!params.file || typeof params.file !== 'string') {
145
145
  throw new Error('file is required');
@@ -161,7 +161,7 @@ export class ListImportsTool {
161
161
  }
162
162
  // A file outside the program (a spec excluded by the tsconfig, say) gets
163
163
  // its own Project: the cached one must not grow.
164
- const sourceFile = this.projects.get(tsConfigPath).getSourceFile(filePath) ??
164
+ const sourceFile = (await acquireProject(this.projects, tsConfigPath, ctx)).getSourceFile(filePath) ??
165
165
  new Project({ tsConfigFilePath: tsConfigPath }).addSourceFileAtPath(filePath);
166
166
  const includeReExports = params.includeReExports !== false;
167
167
  const imports = collectModuleEdges(sourceFile, includeReExports).map((edge) => this.toEntry(sourceFile, edge, projectRoot));
@@ -1,4 +1,4 @@
1
- import { type MCPTool, type ToolAnnotations } from '../types.js';
1
+ import { type MCPTool, type ToolAnnotations, type ToolContext } from '../types.js';
2
2
  import { type ProjectCache } from './helpers/project-cache.js';
3
3
  import type { PlannedFile, PlannedPhase, ViolationPlan } from '@angular-modernizer/core';
4
4
  /**
@@ -790,7 +790,7 @@ export declare class PlanMigrationTool implements MCPTool {
790
790
  };
791
791
  required: string[];
792
792
  };
793
- execute(args: Record<string, unknown>): Promise<PlanMigrationResult>;
793
+ execute(args: Record<string, unknown>, ctx?: ToolContext): Promise<PlanMigrationResult>;
794
794
  /**
795
795
  * Inline violations plus the ones from scanResultFile.
796
796
  */
@@ -1,4 +1,5 @@
1
1
  import { isAbsolute, resolve } from 'node:path';
2
+ import { acquireProject } from './helpers/project-cache.js';
2
3
  import { nameList } from './helpers/analysis-output.js';
3
4
  import { STRING_ARRAY } from './helpers/investigation-schemas.js';
4
5
  import { WARNINGS_OUTPUT_SCHEMA, withWarnings } from './helpers/output-contract.js';
@@ -350,7 +351,7 @@ export class PlanMigrationTool {
350
351
  'summary',
351
352
  ],
352
353
  };
353
- async execute(args) {
354
+ async execute(args, ctx = {}) {
354
355
  const params = args;
355
356
  const compact = parseCompactOptions(args);
356
357
  const projectRoot = typeof params.projectRoot === 'string' ? params.projectRoot : undefined;
@@ -422,7 +423,7 @@ export class PlanMigrationTool {
422
423
  ? {
423
424
  loadProject: (path) => {
424
425
  cachedTsConfig = path;
425
- return projects.get(path);
426
+ return acquireProject(projects, path, ctx);
426
427
  },
427
428
  }
428
429
  : {}),
@@ -1,4 +1,4 @@
1
- import { type MCPTool, type ToolAnnotations } from '../types.js';
1
+ import { type MCPTool, type ToolAnnotations, type ToolContext } from '../types.js';
2
2
  import { type ResolvedTypeInfo } from '@angular-modernizer/api';
3
3
  import { ProjectCache } from './helpers/project-cache.js';
4
4
  /**
@@ -94,7 +94,7 @@ export declare class ResolveTypeTool implements MCPTool {
94
94
  * @param args - Tool arguments validated against the input schema
95
95
  * @returns The resolved type with a text summary
96
96
  */
97
- execute(args: Record<string, unknown>): Promise<ResolvedTypeInfo & {
97
+ execute(args: Record<string, unknown>, ctx?: ToolContext): Promise<ResolvedTypeInfo & {
98
98
  /** Short text summary of the resolved type. */
99
99
  summary: string;
100
100
  /** Conditions that can make the result incomplete (unresolved library imports). */
@@ -1,7 +1,7 @@
1
1
  import { TypeResolver } from '@angular-modernizer/api';
2
2
  import { existsSync } from 'node:fs';
3
3
  import { findTsConfig } from './helpers/find-ts-config.js';
4
- import { ProjectCache } from './helpers/project-cache.js';
4
+ import { ProjectCache, acquireProject } from './helpers/project-cache.js';
5
5
  import { WARNINGS_OUTPUT_SCHEMA, withWarnings, } from './helpers/output-contract.js';
6
6
  /**
7
7
  * MCP tool for resolving the TypeScript type at a given source position.
@@ -92,7 +92,7 @@ export class ResolveTypeTool {
92
92
  * @param args - Tool arguments validated against the input schema
93
93
  * @returns The resolved type with a text summary
94
94
  */
95
- async execute(args) {
95
+ async execute(args, ctx = {}) {
96
96
  const params = args;
97
97
  if (!params.file) {
98
98
  throw new Error('file is required');
@@ -113,7 +113,7 @@ export class ResolveTypeTool {
113
113
  if (!tsConfigPath) {
114
114
  throw new Error(`tsconfig.json not found in projectRoot: ${params.projectRoot}`);
115
115
  }
116
- const project = this.projects.get(tsConfigPath);
116
+ const project = await acquireProject(this.projects, tsConfigPath, ctx);
117
117
  const typeResolver = new TypeResolver(project);
118
118
  const info = typeResolver.resolveType(params.file, params.line, params.column);
119
119
  return withWarnings({
@@ -1,4 +1,4 @@
1
- import { type MCPTool, type ToolAnnotations } from '../types.js';
1
+ import { type MCPTool, type ToolAnnotations, type ToolContext } from '../types.js';
2
2
  import { type SearchCoverage, type SearchResult } from '@angular-modernizer/api';
3
3
  import { ProjectCache } from './helpers/project-cache.js';
4
4
  /**
@@ -167,7 +167,7 @@ export declare class SearchCodebaseTool implements MCPTool {
167
167
  };
168
168
  required: string[];
169
169
  };
170
- execute(args: Record<string, unknown>): Promise<SearchCodebaseOutput>;
170
+ execute(args: Record<string, unknown>, ctx?: ToolContext): Promise<SearchCodebaseOutput>;
171
171
  /**
172
172
  * Explains why 0 hits is not proof of absence, naming what was excluded.
173
173
  */
@@ -1,7 +1,7 @@
1
1
  import { CodebaseSearcher, } from '@angular-modernizer/api';
2
2
  import { existsSync } from 'node:fs';
3
3
  import { findTsConfig } from './helpers/find-ts-config.js';
4
- import { ProjectCache } from './helpers/project-cache.js';
4
+ import { ProjectCache, acquireProject } from './helpers/project-cache.js';
5
5
  import { WARNINGS_OUTPUT_SCHEMA, withWarnings, } from './helpers/output-contract.js';
6
6
  /**
7
7
  * MCP tool for searching across all TypeScript source files in a project.
@@ -136,7 +136,7 @@ export class SearchCodebaseTool {
136
136
  },
137
137
  required: ['results', 'totalCount', 'summary', 'coverage'],
138
138
  };
139
- async execute(args) {
139
+ async execute(args, ctx = {}) {
140
140
  const params = args;
141
141
  if (!params.query) {
142
142
  throw new Error('query is required');
@@ -154,7 +154,7 @@ export class SearchCodebaseTool {
154
154
  if (!tsConfigPath) {
155
155
  throw new Error(`tsconfig.json not found in projectRoot: ${params.projectRoot}`);
156
156
  }
157
- const project = this.projects.get(tsConfigPath);
157
+ const project = await acquireProject(this.projects, tsConfigPath, ctx);
158
158
  const searcher = new CodebaseSearcher(project);
159
159
  const { results, coverage } = searcher.searchWithCoverage(params.query, {
160
160
  mode: params.mode,
@@ -1,4 +1,4 @@
1
- import { type MCPTool, type ToolAnnotations } from '../types.js';
1
+ import { type MCPTool, type ToolAnnotations, type ToolContext } from '../types.js';
2
2
  import { type DynamicResultFlow, type OutputFlow, type OutputFlowResult } from '@angular-modernizer/api';
3
3
  import { ProjectCache } from './helpers/project-cache.js';
4
4
  /** An output with its lists dropped (summaryOnly) or capped (maxResults). */
@@ -787,7 +787,7 @@ export declare class TraceOutputFlowTool implements MCPTool {
787
787
  };
788
788
  required: string[];
789
789
  };
790
- execute(args: Record<string, unknown>): Promise<TraceOutputFlowOutput>;
790
+ execute(args: Record<string, unknown>, ctx?: ToolContext): Promise<TraceOutputFlowOutput>;
791
791
  private shapeDynamic;
792
792
  private buildSummary;
793
793
  private outputLines;
@@ -2,7 +2,7 @@ import { OutputFlowTracer, } from '@angular-modernizer/api';
2
2
  import { existsSync } from 'node:fs';
3
3
  import { isAbsolute, resolve } from 'node:path';
4
4
  import { findTsConfig } from './helpers/find-ts-config.js';
5
- import { ProjectCache } from './helpers/project-cache.js';
5
+ import { ProjectCache, acquireProject } from './helpers/project-cache.js';
6
6
  import { COMPACT_OUTPUT_SCHEMA, limitList, parseCompactOptions, } from './helpers/compact-output.js';
7
7
  import { configuredComponentDecorators } from './helpers/project-decorators.js';
8
8
  import { WARNINGS_OUTPUT_SCHEMA, withWarnings, } from './helpers/output-contract.js';
@@ -437,7 +437,7 @@ export class TraceOutputFlowTool {
437
437
  },
438
438
  required: ['alternatives', 'availableOutputs', 'outputs', 'counts', 'truncated', 'summary', 'tsConfigPath'],
439
439
  };
440
- async execute(args) {
440
+ async execute(args, ctx = {}) {
441
441
  const params = args;
442
442
  if (!params.className && !params.selector) {
443
443
  throw new Error('className or selector is required');
@@ -460,7 +460,7 @@ export class TraceOutputFlowTool {
460
460
  const file = params.file === undefined || isAbsolute(params.file)
461
461
  ? params.file
462
462
  : resolve(params.projectRoot, params.file);
463
- const tracer = new OutputFlowTracer(this.projects.get(tsConfigPath), {
463
+ const tracer = new OutputFlowTracer((await acquireProject(this.projects, tsConfigPath, ctx)), {
464
464
  componentDecorators: configuredComponentDecorators(params.projectRoot),
465
465
  includeTestHosts: params.includeTestHosts === true,
466
466
  includeDynamic: params.includeDynamic !== false,