Skip to content

Commit 6d53062

Browse files
d.weizheclaude
andcommitted
feat(@angular/cli): add devserver_rebuild MCP tool
The `devserver_start` MCP tool now accepts a `manualRebuild` option which starts `ng serve` with `--manual-rebuild`. A new `devserver_rebuild` tool triggers an incremental rebuild of such a dev server once a batch of edits is complete, waits for it to finish, and returns the build status and logs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent b0358d8 commit 6d53062

5 files changed

Lines changed: 257 additions & 2 deletions

File tree

‎packages/angular/cli/src/commands/mcp/devserver.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,16 @@ const BUILD_END_MESSAGES = [
2727

2828
export type BuildStatus = 'success' | 'failure' | 'unknown';
2929

30+
/**
31+
* The outcome of a manually requested rebuild, as reported by the development server.
32+
*/
33+
export type RebuildStatus = 'success' | 'failure' | 'no-changes' | 'cancelled';
34+
35+
/**
36+
* The development server route used to request a rebuild when manual rebuild mode is enabled.
37+
*/
38+
export const REBUILD_ROUTE = '/__ng_rebuild';
39+
3040
/**
3141
* An Angular development server managed by the MCP server.
3242
*/
@@ -58,11 +68,24 @@ export interface Devserver {
5868
*/
5969
isBuilding(): boolean;
6070

71+
/**
72+
* Requests an incremental rebuild of all pending file changes. Only supported when the
73+
* dev server was started in manual rebuild mode.
74+
*
75+
* Resolves once the rebuild has completed.
76+
*/
77+
requestRebuild(): Promise<RebuildStatus>;
78+
6179
/**
6280
* `ng serve` port to use.
6381
*/
6482
port: number;
6583

84+
/**
85+
* Whether the dev server only rebuilds when explicitly requested.
86+
*/
87+
manualRebuild: boolean;
88+
6689
/**
6790
* The workspace path for this server.
6891
*/
@@ -82,6 +105,7 @@ export class LocalDevserver implements Devserver {
82105
readonly port: number;
83106
readonly workspacePath: string;
84107
readonly project: string;
108+
readonly manualRebuild: boolean;
85109

86110
private devserverProcess: ChildProcess | null = null;
87111
private serverLogs: string[] = [];
@@ -94,16 +118,19 @@ export class LocalDevserver implements Devserver {
94118
port,
95119
workspacePath,
96120
project,
121+
manualRebuild = false,
97122
}: {
98123
host: Host;
99124
port: number;
100125
workspacePath: string;
101126
project: string;
127+
manualRebuild?: boolean;
102128
}) {
103129
this.host = host;
104130
this.port = port;
105131
this.workspacePath = workspacePath;
106132
this.project = project;
133+
this.manualRebuild = manualRebuild;
107134
}
108135

109136
start() {
@@ -118,6 +145,10 @@ export class LocalDevserver implements Devserver {
118145

119146
args.push(`--port=${this.port}`);
120147

148+
if (this.manualRebuild) {
149+
args.push('--manual-rebuild');
150+
}
151+
121152
this.devserverProcess = this.host.startNgProcess(args, {
122153
stdio: 'pipe',
123154
cwd: this.workspacePath,
@@ -163,6 +194,33 @@ export class LocalDevserver implements Devserver {
163194
isBuilding() {
164195
return this.buildInProgress;
165196
}
197+
198+
async requestRebuild(): Promise<RebuildStatus> {
199+
if (!this.manualRebuild) {
200+
throw new Error(
201+
`Development server for project '${this.project}' was not started in manual rebuild mode.`,
202+
);
203+
}
204+
if (!this.devserverProcess) {
205+
throw new Error(`Development server for project '${this.project}' is not running.`);
206+
}
207+
208+
const response = await fetch(new URL(REBUILD_ROUTE, `http://localhost:${this.port}`), {
209+
method: 'POST',
210+
});
211+
let body: { status?: RebuildStatus } | undefined;
212+
try {
213+
body = (await response.json()) as { status?: RebuildStatus };
214+
} catch {}
215+
216+
if (!body?.status) {
217+
throw new Error(
218+
`Unexpected rebuild response from the development server (HTTP ${response.status}).`,
219+
);
220+
}
221+
222+
return body.status;
223+
}
166224
}
167225

168226
export function getDevserverKey(workspacePath: string, projectName: string): string {

‎packages/angular/cli/src/commands/mcp/mcp-server.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { LocalWorkspaceHost, createRootRestrictedHost } from './host';
1616
import { registerInstructionsResource } from './resources/instructions';
1717
import { AI_TUTOR_TOOL } from './tools/ai-tutor';
1818
import { BEST_PRACTICES_TOOL } from './tools/best-practices';
19+
import { DEVSERVER_REBUILD_TOOL } from './tools/devserver/devserver-rebuild';
1920
import { DEVSERVER_START_TOOL } from './tools/devserver/devserver-start';
2021
import { DEVSERVER_STOP_TOOL } from './tools/devserver/devserver-stop';
2122
import { DEVSERVER_WAIT_FOR_BUILD_TOOL } from './tools/devserver/devserver-wait-for-build';
@@ -28,7 +29,12 @@ import { type AnyMcpToolDeclaration, registerTools } from './tools/tool-registry
2829
/**
2930
* Tools to manage devservers. Should be bundled together, then added to experimental or stable as a group.
3031
*/
31-
const DEVSERVER_TOOLS = [DEVSERVER_START_TOOL, DEVSERVER_STOP_TOOL, DEVSERVER_WAIT_FOR_BUILD_TOOL];
32+
const DEVSERVER_TOOLS = [
33+
DEVSERVER_START_TOOL,
34+
DEVSERVER_STOP_TOOL,
35+
DEVSERVER_WAIT_FOR_BUILD_TOOL,
36+
DEVSERVER_REBUILD_TOOL,
37+
];
3238

3339
/**
3440
* The set of tools that are enabled by default for the MCP server.
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
import { z } from 'zod';
10+
import { createDevServerNotFoundError, getDevserverKey } from '../../devserver';
11+
import { workspaceAndProjectOptions } from '../../shared-options';
12+
import { createStructuredContentOutput } from '../../utils';
13+
import { resolveWorkspaceAndProject } from '../../workspace-utils';
14+
import { type McpToolContext, type McpToolDeclaration, declareTool } from '../tool-registry';
15+
16+
/**
17+
* Maximum time to wait for the build logs of a completed rebuild to be received from the
18+
* dev server process output.
19+
*/
20+
const LOG_FLUSH_TIMEOUT = 2_000; // In milliseconds
21+
22+
const LOG_FLUSH_INTERVAL = 50; // In milliseconds
23+
24+
const devserverRebuildToolInputSchema = z.object({
25+
...workspaceAndProjectOptions,
26+
});
27+
28+
export type DevserverRebuildToolInput = z.infer<typeof devserverRebuildToolInputSchema>;
29+
30+
const devserverRebuildToolOutputSchema = z.object({
31+
status: z
32+
.enum(['success', 'failure', 'no-changes', 'cancelled'])
33+
.describe(
34+
'The outcome of the rebuild. "no-changes" means no file changes were pending so no rebuild was performed. ' +
35+
'"cancelled" means the dev server stopped before the rebuild could complete.',
36+
),
37+
logs: z
38+
.array(z.string())
39+
.optional()
40+
.describe('The logs from the most recent build, if a rebuild was performed.'),
41+
});
42+
43+
export type DevserverRebuildToolOutput = z.infer<typeof devserverRebuildToolOutputSchema>;
44+
45+
function wait(ms: number): Promise<void> {
46+
return new Promise((resolve) => setTimeout(resolve, ms));
47+
}
48+
49+
export async function rebuildDevserver(input: DevserverRebuildToolInput, context: McpToolContext) {
50+
const { workspacePath, projectName } = await resolveWorkspaceAndProject({
51+
host: context.host,
52+
server: context.server,
53+
workspacePathInput: input.workspace,
54+
projectNameInput: input.project,
55+
mcpWorkspace: context.workspace,
56+
});
57+
const key = getDevserverKey(workspacePath, projectName);
58+
const devserver = context.devservers.get(key);
59+
60+
if (!devserver) {
61+
throw createDevServerNotFoundError(context.devservers);
62+
}
63+
64+
if (!devserver.manualRebuild) {
65+
throw new Error(
66+
`Development server for project '${projectName}' was not started in manual rebuild mode and ` +
67+
'rebuilds automatically on file changes. Use "devserver_wait_for_build" instead, or restart it ' +
68+
'with "devserver_start" and the "manualRebuild" option.',
69+
);
70+
}
71+
72+
const status = await devserver.requestRebuild();
73+
if (status !== 'success' && status !== 'failure') {
74+
return createStructuredContentOutput<DevserverRebuildToolOutput>({ status, logs: undefined });
75+
}
76+
77+
// The rebuild has completed but its log output may still be in transit from the process.
78+
const deadline = Date.now() + LOG_FLUSH_TIMEOUT;
79+
while (devserver.isBuilding() && Date.now() < deadline) {
80+
await wait(LOG_FLUSH_INTERVAL);
81+
}
82+
83+
return createStructuredContentOutput<DevserverRebuildToolOutput>({
84+
status,
85+
logs: devserver.getMostRecentBuild().logs,
86+
});
87+
}
88+
89+
export const DEVSERVER_REBUILD_TOOL: McpToolDeclaration<
90+
typeof devserverRebuildToolInputSchema.shape,
91+
typeof devserverRebuildToolOutputSchema.shape
92+
> = declareTool({
93+
name: 'devserver_rebuild',
94+
title: 'Rebuild Devserver',
95+
description: `
96+
<Purpose>
97+
Triggers an incremental rebuild of a dev server that was started with the "devserver_start" tool in manual rebuild mode
98+
("manualRebuild" option), waits for it to complete, and reports the build status and logs.
99+
</Purpose>
100+
<Use Cases>
101+
* **Applying a batch of changes:** After finishing a set of file edits (possibly across many files), call this tool once to
102+
rebuild all of the changes together. This avoids repeated intermediate rebuilds while files are still being edited.
103+
* **Checking a change compiles:** The returned status and logs indicate whether the rebuild succeeded and contain any
104+
build errors to fix.
105+
</Use Cases>
106+
<Operational Notes>
107+
* This tool only works for dev servers started with "devserver_start" and "manualRebuild" set to true. Dev servers started
108+
without it rebuild automatically; use "devserver_wait_for_build" for those instead.
109+
* The dev server tracks file changes continuously, so only the files changed since the previous rebuild are recompiled.
110+
* If no files changed since the previous rebuild, the tool returns the "no-changes" status without rebuilding.
111+
</Operational Notes>
112+
`,
113+
isReadOnly: false,
114+
isLocalOnly: true,
115+
inputSchema: devserverRebuildToolInputSchema.shape,
116+
outputSchema: devserverRebuildToolOutputSchema.shape,
117+
factory: (context) => (input) => {
118+
return rebuildDevserver(input, context);
119+
},
120+
});

‎packages/angular/cli/src/commands/mcp/tools/devserver/devserver-start.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,13 @@ const devserverStartToolInputSchema = z.object({
2222
'The port number to run the server on. If not provided, a random available port will be chosen. ' +
2323
'It is recommended to reuse port numbers across calls within the same workspace to maintain consistency.',
2424
),
25+
manualRebuild: z
26+
.boolean()
27+
.optional()
28+
.describe(
29+
'When true, the server tracks file changes but only rebuilds when the "devserver_rebuild" tool is called. ' +
30+
'Recommended when making many file edits in a batch, to avoid repeated rebuilds while files are still being edited.',
31+
),
2532
});
2633

2734
export type DevserverStartToolInput = z.infer<typeof devserverStartToolInputSchema>;
@@ -78,13 +85,17 @@ export async function startDevserver(input: DevserverStartToolInput, context: Mc
7885
project: projectName,
7986
port,
8087
workspacePath,
88+
manualRebuild: input.manualRebuild,
8189
});
8290
devserver.start();
8391

8492
context.devservers.set(key, devserver);
8593

8694
return createStructuredContentOutput({
87-
message: `Development server for project '${projectName}' started and watching for workspace changes.`,
95+
message: input.manualRebuild
96+
? `Development server for project '${projectName}' started in manual rebuild mode. ` +
97+
`Call "devserver_rebuild" to rebuild after making changes.`
98+
: `Development server for project '${projectName}' started and watching for workspace changes.`,
8899
address: localhostAddress(port),
89100
});
90101
}
@@ -117,6 +128,8 @@ the first build completes.
117128
changes or run more tests, as it saves time on restarts and maintains the file watcher state. You must still call
118129
'devserver_wait_for_build' after every change to see whether the change was successfully built and be sure that the app was updated.
119130
* **Consistent Ports**: If making multiple calls, it is recommended to reuse the port you got from the first call for subsequent ones.
131+
* **Manual Rebuilds**: Set "manualRebuild" to true to only rebuild when "devserver_rebuild" is called. This is useful when editing
132+
many files in a batch. In this mode, call "devserver_rebuild" (instead of "devserver_wait_for_build") once all edits are done.
120133
</Operational Notes>
121134
`,
122135
isReadOnly: false,

‎packages/angular/cli/src/commands/mcp/tools/devserver/devserver_spec.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
addProjectToWorkspace,
1515
createMockContext,
1616
} from '../../testing/test-utils';
17+
import { rebuildDevserver } from './devserver-rebuild';
1718
import { startDevserver } from './devserver-start';
1819
import { stopDevserver } from './devserver-stop';
1920
import { WATCH_DELAY, waitForDevserverBuild } from './devserver-wait-for-build';
@@ -236,4 +237,61 @@ describe('Serve Tools', () => {
236237
expect((e as Error).message).toContain("- Project 'app-one' in workspace path '/test'");
237238
}
238239
});
240+
241+
describe('manual rebuild', () => {
242+
let fetchSpy: jasmine.Spy<typeof fetch>;
243+
244+
beforeEach(() => {
245+
fetchSpy = spyOn(globalThis, 'fetch');
246+
});
247+
248+
it('should start the dev server in manual rebuild mode', async () => {
249+
const startResult = await startDevserver({ manualRebuild: true }, mockContext);
250+
expect(startResult.structuredContent.message).toContain('started in manual rebuild mode');
251+
expect(mockHost.startNgProcess).toHaveBeenCalledWith(
252+
['serve', 'my-app', '--port=12345', '--manual-rebuild'],
253+
{ stdio: 'pipe', cwd: '/test' },
254+
);
255+
});
256+
257+
it('should request a rebuild and report the build logs', async () => {
258+
await startDevserver({ manualRebuild: true }, mockContext);
259+
fetchSpy.and.callFake(async () => {
260+
mockProcess.stdout.emit('data', '❯ Changes detected. Rebuilding...\n');
261+
mockProcess.stdout.emit('data', 'Application bundle generation complete.\n');
262+
263+
return Response.json({ status: 'success' });
264+
});
265+
266+
const result = await rebuildDevserver({}, mockContext);
267+
268+
expect(fetchSpy).toHaveBeenCalledWith(new URL('http://localhost:12345/__ng_rebuild'), {
269+
method: 'POST',
270+
});
271+
expect(result.structuredContent.status).toBe('success');
272+
expect(result.structuredContent.logs).toEqual([
273+
'❯ Changes detected. Rebuilding...',
274+
'Application bundle generation complete.',
275+
]);
276+
});
277+
278+
it('should report when there are no changes to rebuild', async () => {
279+
await startDevserver({ manualRebuild: true }, mockContext);
280+
fetchSpy.and.resolveTo(Response.json({ status: 'no-changes' }));
281+
282+
const result = await rebuildDevserver({}, mockContext);
283+
284+
expect(result.structuredContent.status).toBe('no-changes');
285+
expect(result.structuredContent.logs).toBeUndefined();
286+
});
287+
288+
it('should fail if the dev server is not in manual rebuild mode', async () => {
289+
await startDevserver({}, mockContext);
290+
291+
await expectAsync(rebuildDevserver({}, mockContext)).toBeRejectedWithError(
292+
/not started in manual rebuild mode/,
293+
);
294+
expect(fetchSpy).not.toHaveBeenCalled();
295+
});
296+
});
239297
});

0 commit comments

Comments
 (0)