From 8a66704945ae5e59e4b33355c0643b17602f7f7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florin=20As=C4=83voaie?= Date: Sun, 22 Nov 2026 14:33:03 +0200 Subject: [PATCH] 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. --- .../cli/src/commands/mcp/tools/projects.ts | 137 ++++-------------- .../src/commands/mcp/tools/projects_spec.ts | 77 +++++++++- 2 files changed, 106 insertions(+), 108 deletions(-) diff --git a/packages/angular/cli/src/commands/mcp/tools/projects.ts b/packages/angular/cli/src/commands/mcp/tools/projects.ts index 5b9d15808b44..227a66326165 100644 --- a/packages/angular/cli/src/commands/mcp/tools/projects.ts +++ b/packages/angular/cli/src/commands/mcp/tools/projects.ts @@ -8,6 +8,7 @@ import { realpathSync } from 'node:fs'; import { readFile, readdir, stat } from 'node:fs/promises'; +import { createRequire } from 'node:module'; import { dirname, extname, isAbsolute, join, normalize, posix, relative, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import semver from 'semver'; @@ -252,80 +253,34 @@ async function* findAngularJsonFiles( } /** - * Searches upwards from a starting directory to find the version of '@angular/core'. - * It caches results to avoid redundant lookups. - * @param startDir The directory to start the search from. - * @param cache A map to store cached results. - * @param searchRoot The directory at which to stop the search. - * @returns The major version of '@angular/core' as a string, otherwise undefined. + * Determines the major version of the `@angular/core` package installed for a workspace. + * The package is resolved with Node.js module resolution from the workspace's `angular.json` + * file, so the result is independent of how the dependency is declared in `package.json` + * (e.g., a semver range, a pnpm/yarn `catalog:` reference, a `workspace:` protocol, or an + * `npm:` alias). + * @param configFile The path to the workspace's `angular.json` file. + * @returns The major version of '@angular/core' as a string, or `undefined` if the package is + * not installed or its version cannot be read. */ -async function findAngularCoreVersion( - startDir: string, - cache: Map, - searchRoot: string, -): Promise { - let currentDir = startDir; - const dirsToCache: string[] = []; - - while (currentDir) { - dirsToCache.push(currentDir); - if (cache.has(currentDir)) { - const cachedResult = cache.get(currentDir); - // Populate cache for all intermediate directories. - for (const dir of dirsToCache) { - cache.set(dir, cachedResult); - } - - return cachedResult; - } - - const pkgPath = join(currentDir, 'package.json'); - try { - const pkgContent = await readFile(pkgPath, 'utf-8'); - const pkg = JSON.parse(pkgContent); - const versionSpecifier = - pkg.dependencies?.['@angular/core'] ?? pkg.devDependencies?.['@angular/core']; - - if (versionSpecifier) { - const minVersion = semver.minVersion(versionSpecifier); - const result = minVersion ? String(minVersion.major) : undefined; - for (const dir of dirsToCache) { - cache.set(dir, result); - } - - return result; - } - } catch (error) { - assertIsError(error); - if (error.code !== 'ENOENT') { - // Ignore missing package.json files, but rethrow other errors. - throw error; - } - } - - // Stop if we are at the search root or the filesystem root. - if (currentDir === searchRoot) { - break; - } - const parentDir = dirname(currentDir); - if (parentDir === currentDir) { - break; // Reached the filesystem root. - } - currentDir = parentDir; - } - - // Cache the failure for all traversed directories. - for (const dir of dirsToCache) { - cache.set(dir, undefined); +async function findAngularCoreVersion(configFile: string): Promise { + try { + // `createRequire` resolves from the parent directory of the given path. The path to the + // `angular.json` file is used (instead of the workspace directory) so that the workspace's + // own `node_modules` directory is included in the search. + const pkgJsonPath = createRequire(resolve(configFile)).resolve('@angular/core/package.json'); + const { version } = JSON.parse(await readFile(pkgJsonPath, 'utf-8')); + const major = semver.parse(version)?.major; + + return major === undefined ? undefined : String(major); + } catch { + // The package is not installed or its `package.json` could not be read. + return undefined; } - - return undefined; } // Helper types inferred from the Zod schema for structured data processing. type WorkspaceData = z.infer[number]; type ParsingError = z.infer[number]; -type VersioningError = z.infer[number]; /** * Determines the unit test framework for a project based on its 'test' target configuration. @@ -495,20 +450,15 @@ async function loadAndParseWorkspace( /** * Processes a single `angular.json` file to extract workspace and framework version information. * @param configFile The path to the `angular.json` file. - * @param searchRoot The directory at which to stop the upward search for `package.json`. * @param seenPaths A Set of absolute paths that have already been processed to avoid duplicates. - * @param versionCache A Map to cache framework version lookups for performance. - * @returns A promise resolving to an object containing the processed data and any errors. + * @returns A promise resolving to an object containing the processed data or a parsing error. */ async function processConfigFile( configFile: string, - searchRoot: string, seenPaths: Set, - versionCache: Map, ): Promise<{ workspace?: WorkspaceData; parsingError?: ParsingError; - versioningError?: VersioningError; }> { const { workspace, error } = await loadAndParseWorkspace(configFile, seenPaths); if (error) { @@ -519,24 +469,9 @@ async function processConfigFile( return {}; // Skipped as it was already seen. } - try { - const workspaceDir = dirname(configFile); - workspace.frameworkVersion = await findAngularCoreVersion( - workspaceDir, - versionCache, - searchRoot, - ); - - return { workspace }; - } catch (e) { - return { - workspace, - versioningError: { - filePath: workspace.path, - message: e instanceof Error ? e.message : 'An unknown error occurred.', - }, - }; - } + workspace.frameworkVersion = await findAngularCoreVersion(configFile); + + return { workspace }; } /** @@ -568,9 +503,7 @@ async function createListProjectsHandler({ server, roots: configuredRoots }: Mcp return async () => { const workspaces: WorkspaceData[] = []; const parsingErrors: ParsingError[] = []; - const versioningErrors: z.infer = []; const seenPaths = new Set(); - const versionCache = new Map(); let searchRoots: string[] | undefined; const clientCapabilities = server.server.getClientCapabilities(); @@ -600,12 +533,7 @@ async function createListProjectsHandler({ server, roots: configuredRoots }: Mcp for (const root of searchRoots) { for await (const configFile of findAngularJsonFiles(root, realAllowedRoots)) { - const { workspace, parsingError, versioningError } = await processConfigFile( - configFile, - root, - seenPaths, - versionCache, - ); + const { workspace, parsingError } = await processConfigFile(configFile, seenPaths); if (workspace) { workspaces.push(workspace); @@ -613,9 +541,6 @@ async function createListProjectsHandler({ server, roots: configuredRoots }: Mcp if (parsingError) { parsingErrors.push(parsingError); } - if (versioningError) { - versioningErrors.push(versioningError); - } } } @@ -639,14 +564,12 @@ async function createListProjectsHandler({ server, roots: configuredRoots }: Mcp text += `\n\nWarning: The following ${parsingErrors.length} file(s) could not be parsed and were skipped:\n`; text += parsingErrors.map((e) => `- ${e.filePath}: ${e.message}`).join('\n'); } - if (versioningErrors.length > 0) { - text += `\n\nWarning: The framework version for the following ${versioningErrors.length} workspace(s) could not be determined:\n`; - text += versioningErrors.map((e) => `- ${e.filePath}: ${e.message}`).join('\n'); - } return { content: [{ type: 'text' as const, text }], - structuredContent: { workspaces, parsingErrors, versioningErrors }, + // `versioningErrors` is kept for output schema compatibility. A framework version that + // cannot be determined (e.g., `@angular/core` is not installed) is not reported as an error. + structuredContent: { workspaces, parsingErrors, versioningErrors: [] }, }; }; } diff --git a/packages/angular/cli/src/commands/mcp/tools/projects_spec.ts b/packages/angular/cli/src/commands/mcp/tools/projects_spec.ts index 8ed77e673466..2aef415b3ecf 100644 --- a/packages/angular/cli/src/commands/mcp/tools/projects_spec.ts +++ b/packages/angular/cli/src/commands/mcp/tools/projects_spec.ts @@ -83,7 +83,6 @@ describe('List Projects Tool', () => { expect(result.structuredContent).toBeDefined(); const workspaces = result.structuredContent.workspaces; expect(workspaces.length).toBe(1); - expect(workspaces[0].frameworkVersion).toBe('18'); const projects = workspaces[0].projects; expect(projects.length).toBe(1); @@ -130,4 +129,80 @@ describe('List Projects Tool', () => { expect(result.structuredContent.workspaces.length).toBe(1); expect(result.structuredContent.workspaces[0].projects[0].name).toBe('my-app'); }); + + describe('frameworkVersion', () => { + function installAngularCore(dir: string, version: string): void { + const packageDir = join(dir, 'node_modules', '@angular', 'core'); + mkdirSync(packageDir, { recursive: true }); + writeFileSync( + join(packageDir, 'package.json'), + JSON.stringify({ name: '@angular/core', version }), + ); + } + + async function listProjects() { + const handler = await LIST_PROJECTS_TOOL.factory(mockContext); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return (handler as any)({}); + } + + it('should use the installed version when the dependency is declared with a catalog', async () => { + writeFileSync( + join(workspaceDir, 'package.json'), + JSON.stringify({ dependencies: { '@angular/core': 'catalog:' } }), + ); + installAngularCore(workspaceDir, '22.3.0'); + + const result = await listProjects(); + + expect(result.structuredContent.workspaces.length).toBe(1); + expect(result.structuredContent.workspaces[0].frameworkVersion).toBe('22'); + expect(result.structuredContent.versioningErrors).toEqual([]); + expect(result.content[0].text).not.toContain('could not be determined'); + }); + + it('should not set a version or report an error when @angular/core is not installed', async () => { + writeFileSync( + join(workspaceDir, 'package.json'), + JSON.stringify({ dependencies: { '@angular/core': 'catalog:' } }), + ); + + const result = await listProjects(); + + expect(result.structuredContent.workspaces.length).toBe(1); + expect(result.structuredContent.workspaces[0].frameworkVersion).toBeUndefined(); + expect(result.structuredContent.versioningErrors).toEqual([]); + expect(result.content[0].text).not.toContain('could not be determined'); + }); + + it(`should resolve the version from a nested workspace's own node_modules`, async () => { + const appDir = join(allowedRoot, 'apps', 'web'); + mkdirSync(appDir, { recursive: true }); + writeFileSync(join(appDir, 'angular.json'), '{}'); + writeFileSync( + join(appDir, 'package.json'), + JSON.stringify({ dependencies: { '@angular/core': 'catalog:angular' } }), + ); + installAngularCore(appDir, '21.1.4'); + + const result = await listProjects(); + + const appWorkspace = result.structuredContent.workspaces.find( + (ws: { path: string }) => ws.path === join(appDir, 'angular.json'), + ); + expect(appWorkspace).toBeDefined(); + expect(appWorkspace.frameworkVersion).toBe('21'); + expect(result.structuredContent.versioningErrors).toEqual([]); + }); + + it('should resolve the version from a node_modules directory in a parent directory', async () => { + installAngularCore(allowedRoot, '20.0.2'); + + const result = await listProjects(); + + expect(result.structuredContent.workspaces.length).toBe(1); + expect(result.structuredContent.workspaces[0].frameworkVersion).toBe('20'); + }); + }); });