Skip to content

Commit 8a66704

Browse files
fix(@angular/cli): resolve installed @angular/core version in list_projects MCP tool
The `list_projects` MCP tool determined `frameworkVersion` by walking up from the workspace directory to the first `package.json` that declared `@angular/core` and passing the declared value to `semver.minVersion`. Declared values that are not semver ranges, such as pnpm/yarn catalogs (`catalog:`, `catalog:angular`), `workspace:*` or `npm:` aliases, made `semver.minVersion` throw. The tool then reported a versioning error for the workspace (e.g. `Invalid comparator: catalog:`) and left `frameworkVersion` unset. The version is now read from the installed `@angular/core/package.json`, resolved with `createRequire` in the same way as the `get_best_practices` tool, so the way the dependency is declared no longer matters. The resolution starts from the workspace's `angular.json` file rather than its directory, because `createRequire` searches from the parent directory of the given path and would otherwise skip the `node_modules` of nested workspaces such as `apps/web`. When `@angular/core` is not installed or its version cannot be read, `frameworkVersion` is left unset and no error is reported. The upward `package.json` search and its cache are removed; the output schema is unchanged.
1 parent 090bc99 commit 8a66704

2 files changed

Lines changed: 106 additions & 108 deletions

File tree

‎packages/angular/cli/src/commands/mcp/tools/projects.ts‎

Lines changed: 30 additions & 107 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
import { realpathSync } from 'node:fs';
1010
import { readFile, readdir, stat } from 'node:fs/promises';
11+
import { createRequire } from 'node:module';
1112
import { dirname, extname, isAbsolute, join, normalize, posix, relative, resolve } from 'node:path';
1213
import { fileURLToPath } from 'node:url';
1314
import semver from 'semver';
@@ -252,80 +253,34 @@ async function* findAngularJsonFiles(
252253
}
253254

254255
/**
255-
* Searches upwards from a starting directory to find the version of '@angular/core'.
256-
* It caches results to avoid redundant lookups.
257-
* @param startDir The directory to start the search from.
258-
* @param cache A map to store cached results.
259-
* @param searchRoot The directory at which to stop the search.
260-
* @returns The major version of '@angular/core' as a string, otherwise undefined.
256+
* Determines the major version of the `@angular/core` package installed for a workspace.
257+
* The package is resolved with Node.js module resolution from the workspace's `angular.json`
258+
* file, so the result is independent of how the dependency is declared in `package.json`
259+
* (e.g., a semver range, a pnpm/yarn `catalog:` reference, a `workspace:` protocol, or an
260+
* `npm:` alias).
261+
* @param configFile The path to the workspace's `angular.json` file.
262+
* @returns The major version of '@angular/core' as a string, or `undefined` if the package is
263+
* not installed or its version cannot be read.
261264
*/
262-
async function findAngularCoreVersion(
263-
startDir: string,
264-
cache: Map<string, string | undefined>,
265-
searchRoot: string,
266-
): Promise<string | undefined> {
267-
let currentDir = startDir;
268-
const dirsToCache: string[] = [];
269-
270-
while (currentDir) {
271-
dirsToCache.push(currentDir);
272-
if (cache.has(currentDir)) {
273-
const cachedResult = cache.get(currentDir);
274-
// Populate cache for all intermediate directories.
275-
for (const dir of dirsToCache) {
276-
cache.set(dir, cachedResult);
277-
}
278-
279-
return cachedResult;
280-
}
281-
282-
const pkgPath = join(currentDir, 'package.json');
283-
try {
284-
const pkgContent = await readFile(pkgPath, 'utf-8');
285-
const pkg = JSON.parse(pkgContent);
286-
const versionSpecifier =
287-
pkg.dependencies?.['@angular/core'] ?? pkg.devDependencies?.['@angular/core'];
288-
289-
if (versionSpecifier) {
290-
const minVersion = semver.minVersion(versionSpecifier);
291-
const result = minVersion ? String(minVersion.major) : undefined;
292-
for (const dir of dirsToCache) {
293-
cache.set(dir, result);
294-
}
295-
296-
return result;
297-
}
298-
} catch (error) {
299-
assertIsError(error);
300-
if (error.code !== 'ENOENT') {
301-
// Ignore missing package.json files, but rethrow other errors.
302-
throw error;
303-
}
304-
}
305-
306-
// Stop if we are at the search root or the filesystem root.
307-
if (currentDir === searchRoot) {
308-
break;
309-
}
310-
const parentDir = dirname(currentDir);
311-
if (parentDir === currentDir) {
312-
break; // Reached the filesystem root.
313-
}
314-
currentDir = parentDir;
315-
}
316-
317-
// Cache the failure for all traversed directories.
318-
for (const dir of dirsToCache) {
319-
cache.set(dir, undefined);
265+
async function findAngularCoreVersion(configFile: string): Promise<string | undefined> {
266+
try {
267+
// `createRequire` resolves from the parent directory of the given path. The path to the
268+
// `angular.json` file is used (instead of the workspace directory) so that the workspace's
269+
// own `node_modules` directory is included in the search.
270+
const pkgJsonPath = createRequire(resolve(configFile)).resolve('@angular/core/package.json');
271+
const { version } = JSON.parse(await readFile(pkgJsonPath, 'utf-8'));
272+
const major = semver.parse(version)?.major;
273+
274+
return major === undefined ? undefined : String(major);
275+
} catch {
276+
// The package is not installed or its `package.json` could not be read.
277+
return undefined;
320278
}
321-
322-
return undefined;
323279
}
324280

325281
// Helper types inferred from the Zod schema for structured data processing.
326282
type WorkspaceData = z.infer<typeof listProjectsOutputSchema.workspaces>[number];
327283
type ParsingError = z.infer<typeof listProjectsOutputSchema.parsingErrors>[number];
328-
type VersioningError = z.infer<typeof listProjectsOutputSchema.versioningErrors>[number];
329284

330285
/**
331286
* Determines the unit test framework for a project based on its 'test' target configuration.
@@ -495,20 +450,15 @@ async function loadAndParseWorkspace(
495450
/**
496451
* Processes a single `angular.json` file to extract workspace and framework version information.
497452
* @param configFile The path to the `angular.json` file.
498-
* @param searchRoot The directory at which to stop the upward search for `package.json`.
499453
* @param seenPaths A Set of absolute paths that have already been processed to avoid duplicates.
500-
* @param versionCache A Map to cache framework version lookups for performance.
501-
* @returns A promise resolving to an object containing the processed data and any errors.
454+
* @returns A promise resolving to an object containing the processed data or a parsing error.
502455
*/
503456
async function processConfigFile(
504457
configFile: string,
505-
searchRoot: string,
506458
seenPaths: Set<string>,
507-
versionCache: Map<string, string | undefined>,
508459
): Promise<{
509460
workspace?: WorkspaceData;
510461
parsingError?: ParsingError;
511-
versioningError?: VersioningError;
512462
}> {
513463
const { workspace, error } = await loadAndParseWorkspace(configFile, seenPaths);
514464
if (error) {
@@ -519,24 +469,9 @@ async function processConfigFile(
519469
return {}; // Skipped as it was already seen.
520470
}
521471

522-
try {
523-
const workspaceDir = dirname(configFile);
524-
workspace.frameworkVersion = await findAngularCoreVersion(
525-
workspaceDir,
526-
versionCache,
527-
searchRoot,
528-
);
529-
530-
return { workspace };
531-
} catch (e) {
532-
return {
533-
workspace,
534-
versioningError: {
535-
filePath: workspace.path,
536-
message: e instanceof Error ? e.message : 'An unknown error occurred.',
537-
},
538-
};
539-
}
472+
workspace.frameworkVersion = await findAngularCoreVersion(configFile);
473+
474+
return { workspace };
540475
}
541476

542477
/**
@@ -568,9 +503,7 @@ async function createListProjectsHandler({ server, roots: configuredRoots }: Mcp
568503
return async () => {
569504
const workspaces: WorkspaceData[] = [];
570505
const parsingErrors: ParsingError[] = [];
571-
const versioningErrors: z.infer<typeof listProjectsOutputSchema.versioningErrors> = [];
572506
const seenPaths = new Set<string>();
573-
const versionCache = new Map<string, string | undefined>();
574507

575508
let searchRoots: string[] | undefined;
576509
const clientCapabilities = server.server.getClientCapabilities();
@@ -600,22 +533,14 @@ async function createListProjectsHandler({ server, roots: configuredRoots }: Mcp
600533

601534
for (const root of searchRoots) {
602535
for await (const configFile of findAngularJsonFiles(root, realAllowedRoots)) {
603-
const { workspace, parsingError, versioningError } = await processConfigFile(
604-
configFile,
605-
root,
606-
seenPaths,
607-
versionCache,
608-
);
536+
const { workspace, parsingError } = await processConfigFile(configFile, seenPaths);
609537

610538
if (workspace) {
611539
workspaces.push(workspace);
612540
}
613541
if (parsingError) {
614542
parsingErrors.push(parsingError);
615543
}
616-
if (versioningError) {
617-
versioningErrors.push(versioningError);
618-
}
619544
}
620545
}
621546

@@ -639,14 +564,12 @@ async function createListProjectsHandler({ server, roots: configuredRoots }: Mcp
639564
text += `\n\nWarning: The following ${parsingErrors.length} file(s) could not be parsed and were skipped:\n`;
640565
text += parsingErrors.map((e) => `- ${e.filePath}: ${e.message}`).join('\n');
641566
}
642-
if (versioningErrors.length > 0) {
643-
text += `\n\nWarning: The framework version for the following ${versioningErrors.length} workspace(s) could not be determined:\n`;
644-
text += versioningErrors.map((e) => `- ${e.filePath}: ${e.message}`).join('\n');
645-
}
646567

647568
return {
648569
content: [{ type: 'text' as const, text }],
649-
structuredContent: { workspaces, parsingErrors, versioningErrors },
570+
// `versioningErrors` is kept for output schema compatibility. A framework version that
571+
// cannot be determined (e.g., `@angular/core` is not installed) is not reported as an error.
572+
structuredContent: { workspaces, parsingErrors, versioningErrors: [] },
650573
};
651574
};
652575
}

‎packages/angular/cli/src/commands/mcp/tools/projects_spec.ts‎

Lines changed: 76 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,6 @@ describe('List Projects Tool', () => {
8383
expect(result.structuredContent).toBeDefined();
8484
const workspaces = result.structuredContent.workspaces;
8585
expect(workspaces.length).toBe(1);
86-
expect(workspaces[0].frameworkVersion).toBe('18');
8786

8887
const projects = workspaces[0].projects;
8988
expect(projects.length).toBe(1);
@@ -130,4 +129,80 @@ describe('List Projects Tool', () => {
130129
expect(result.structuredContent.workspaces.length).toBe(1);
131130
expect(result.structuredContent.workspaces[0].projects[0].name).toBe('my-app');
132131
});
132+
133+
describe('frameworkVersion', () => {
134+
function installAngularCore(dir: string, version: string): void {
135+
const packageDir = join(dir, 'node_modules', '@angular', 'core');
136+
mkdirSync(packageDir, { recursive: true });
137+
writeFileSync(
138+
join(packageDir, 'package.json'),
139+
JSON.stringify({ name: '@angular/core', version }),
140+
);
141+
}
142+
143+
async function listProjects() {
144+
const handler = await LIST_PROJECTS_TOOL.factory(mockContext);
145+
146+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
147+
return (handler as any)({});
148+
}
149+
150+
it('should use the installed version when the dependency is declared with a catalog', async () => {
151+
writeFileSync(
152+
join(workspaceDir, 'package.json'),
153+
JSON.stringify({ dependencies: { '@angular/core': 'catalog:' } }),
154+
);
155+
installAngularCore(workspaceDir, '22.3.0');
156+
157+
const result = await listProjects();
158+
159+
expect(result.structuredContent.workspaces.length).toBe(1);
160+
expect(result.structuredContent.workspaces[0].frameworkVersion).toBe('22');
161+
expect(result.structuredContent.versioningErrors).toEqual([]);
162+
expect(result.content[0].text).not.toContain('could not be determined');
163+
});
164+
165+
it('should not set a version or report an error when @angular/core is not installed', async () => {
166+
writeFileSync(
167+
join(workspaceDir, 'package.json'),
168+
JSON.stringify({ dependencies: { '@angular/core': 'catalog:' } }),
169+
);
170+
171+
const result = await listProjects();
172+
173+
expect(result.structuredContent.workspaces.length).toBe(1);
174+
expect(result.structuredContent.workspaces[0].frameworkVersion).toBeUndefined();
175+
expect(result.structuredContent.versioningErrors).toEqual([]);
176+
expect(result.content[0].text).not.toContain('could not be determined');
177+
});
178+
179+
it(`should resolve the version from a nested workspace's own node_modules`, async () => {
180+
const appDir = join(allowedRoot, 'apps', 'web');
181+
mkdirSync(appDir, { recursive: true });
182+
writeFileSync(join(appDir, 'angular.json'), '{}');
183+
writeFileSync(
184+
join(appDir, 'package.json'),
185+
JSON.stringify({ dependencies: { '@angular/core': 'catalog:angular' } }),
186+
);
187+
installAngularCore(appDir, '21.1.4');
188+
189+
const result = await listProjects();
190+
191+
const appWorkspace = result.structuredContent.workspaces.find(
192+
(ws: { path: string }) => ws.path === join(appDir, 'angular.json'),
193+
);
194+
expect(appWorkspace).toBeDefined();
195+
expect(appWorkspace.frameworkVersion).toBe('21');
196+
expect(result.structuredContent.versioningErrors).toEqual([]);
197+
});
198+
199+
it('should resolve the version from a node_modules directory in a parent directory', async () => {
200+
installAngularCore(allowedRoot, '20.0.2');
201+
202+
const result = await listProjects();
203+
204+
expect(result.structuredContent.workspaces.length).toBe(1);
205+
expect(result.structuredContent.workspaces[0].frameworkVersion).toBe('20');
206+
});
207+
});
133208
});

0 commit comments

Comments
 (0)