Did you know that up to 40% of AI-generated frontend code breaks production because agents lack direct context of modern framework features? After locking down your codebase with strict TypeScript and compiler guardrails in How to Use TypeScript and Angular to Shield Your Code Against AI Errors, it is time to solve the problem at the source: teaching the agent to write modern Angular and giving it real tools to operate your app.
Two very different conversations hide behind "Angular and AI," and almost every team mixes them up:
AI writing your Angular code: language models learned Angular from years of legacy tutorials. Without guidance, they dump
NgModule,*ngIf, constructor injection, andBehaviorSubjecteverywhere. The Angular 22 ecosystem provides context files, Agent Skills, and a native MCP server to fix that at the root.AI using your application: a browser agent does not need to scrape the DOM or click blindly like a lost intern. With experimental support for WebMCP, your app exposes typed, validated functions directly to the agent.
In this practical guide, you will set up the first half today in any production repository and see where the loose ends are in the second before shipping anything experimental.
Part 1: Teaching the Agent to Write Modern Angular 22#
1. Start With the Official Context Files#
The highest-leverage upgrade costs nothing. The Angular team maintains three artifacts published specifically for LLM consumption:
llms.txt (
angular.dev/llms.txt): lightweight index pointing to the framework's core docs and guides.llms-full.txt (
angular.dev/assets/context/llms-full.txt): full compilation covering architecture, APIs, and building applications.best-practices.md (
angular.dev/assets/context/best-practices.md): short, opinionated file ready to serve as system instructions in your editor.
The best-practices.md file locks the model onto current conventions: strict typing with unknown instead of any, standalone components, signals for state, input(), output(), and model(), native control flow (@if, @for), direct class and style bindings instead of ngClass and ngStyle, @Service for singletons, inject(), Signal Forms, and WCAG AA compliance.
Save that content in the rules file matching your team's tool:
Tool / IDE | Rules File |
|---|---|
Antigravity / Gemini CLI |
|
GitHub Copilot |
|
Cursor |
|
JetBrains IDEs |
|
VS Code |
|
Windsurf |
|
Rule of thumb: commit the rules file to the repository. If it lives only on your machine, the next teammate gets legacy Angular in their pull request all over again.
2. Install the Official Agent Skills#
Rules files load on every prompt. That works for a one-page convention sheet, but wastes context window if you dump entire manuals inside. Agent Skills (an open standard created by Anthropic) solve this bottleneck by loading deep instructions on demand, only when the task calls for them.
The official angular/skills repository ships two skills maintained alongside the framework source code:
angular-developer: generates code and guides architectural decisions covering components, signals, forms, dependency injection, routing, SSR, ARIA accessibility, animations, testing, and the CLI.angular-new-app: scaffolds and configures a brand-new project with the Angular CLI following modern defaults.
Install both with a single command:
npx skills add https://github.com/angular/skillsIf you were using the community package analogjs/angular-skills, migrate to the official one. The operational payoff is simple: when an API changes in Angular, the official skill updates in the same release without relying on someone on your team remembering to edit hand-written prompts.
3. Connect the Angular CLI MCP Server#
Context files and skills give the model knowledge. The MCP (Model Context Protocol) server gives it hands.
The Angular CLI ships with a built-in MCP server. Instead of guessing shell commands, the agent calls structured tools exposed by the CLI itself. No extra packages are required; point your editor to npx -y @angular/cli mcp.
In VS Code, create .vscode/mcp.json:
{
"servers": {
"angular-cli": {
"command": "npx",
"args": ["-y", "@angular/cli", "mcp"]
}
}
}In Cursor (.cursor/mcp.json) and Antigravity (.antigravity/mcp.json), the structure is identical—just swap the root key servers for mcpServers.
These are the nine tools the server exposes by default:
MCP Tool | Workspace Function |
|---|---|
| Lists workspace apps and libraries by reading angular.json. |
| Searches up-to-date official documentation on angular.dev. |
| Returns Angular's official best-practices guide. |
| Starts ng serve in the background without blocking the agent. |
| Captures real logs and compiler diagnostics from the latest build. |
| Stops the running development server. |
| Runs configured targets such as build, test, lint, e2e, or deploy. |
| Analyzes components and generates a step-by-step OnPush and zoneless migration plan. |
| Launches an interactive tutor grounded in the current project. |
Pairing search_documentation with get_best_practices eliminates the biggest source of API hallucinations: the agent reads live documentation instead of relying on training weights.
For teams just getting started with agents, pass the --read-only flag (--local-only is also available for air-gapped environments):
"args": ["-y", "@angular/cli", "mcp", "--read-only"]Start with --read-only for a week. Let the agent inspect the workspace and query the docs; unlock run_target and the dev server once your team trusts the workflow.
Three Workflows Worth Copying#
Guided OnPush and zoneless migration: the agent maps the workspace with
list_projects, runs signal schematics viang generate, and triggersonpush_zoneless_migrationdirectory by directory. It applies one change at a time, validates withrun_target, and moves forward only when tests pass.TDD loop with real compiler feedback: the agent checks APIs via
search_documentation, starts the dev server withdevserver_start, reads real diagnostics fromdevserver_wait_for_build, executes tests viarun_target, and shuts down the server when done. No more "this should compile."Codebase onboarding: the agent maps your architecture and opens
ai_tutorto walk new engineers through hands-on exercises verified directly against your team's repository.
One non-negotiable rule: the MCP server makes the agent better informed, not accountable. Whoever signs off on the pull request owns the code. Read the diff.
Part 2: Opening Your App to Agents With WebMCP#
Today, when a browser agent needs to operate a web app, it parses the DOM, guesses what each button does, and simulates clicks. That approach is slow, burns tokens, and breaks the moment someone refactors a CSS selector.
WebMCP flips that contract: instead of scraping screens, your application exposes structured, typed tools directly to browser agents. Chrome offers an origin trial starting in version 149 (or locally via chrome://flags/#enable-webmcp-testing), supporting both an imperative JavaScript API and declarative HTML form annotations.
Angular 22 wraps the imperative registration directly into dependency injection and route/service lifecycles.
App-Level Tools and Defensive Parameter Validation#
To expose tools at the application level, use provideExperimentalWebMcpTools. The execute callback runs inside an injection context, so you can call inject() directly:
import { inject, provideExperimentalWebMcpTools } from '@angular/core';
import { OrdersStore } from './features/orders/data/orders.store';
export const ordersWebMcpProvider = provideExperimentalWebMcpTools([
{
name: 'findOrders',
description: 'Searches orders by customer name. Returns at most maxResults records.',
inputSchema: {
type: 'object',
properties: {
customer: { type: 'string', description: 'Full or partial customer name.' },
maxResults: { type: 'number', description: 'Maximum number of orders to return.' },
},
required: ['customer'],
additionalProperties: false,
},
execute: ({ customer, maxResults }) => {
if (typeof customer !== 'string' || customer.length > 100) {
throw new Error(`Invalid customer: ${customer}`);
}
if (maxResults !== undefined && typeof maxResults !== 'number') {
throw new Error(`Invalid maxResults: ${maxResults}`);
}
const store = inject(OrdersStore);
const found = store.search(customer).slice(0, maxResults ?? 10);
return { content: [{ type: 'text', text: JSON.stringify(found) }] };
},
},
]);Two critical details stand out here:
The description is the routing contract: the agent never reads the body of
execute. It decides whether to invoke your tool based solely onnameanddescription.Validate at runtime like a public HTTP endpoint: Angular infers TypeScript types from
inputSchema, but does not validate incoming agent payloads at runtime. Treat every argument as untrusted input.
Scoping Tools to Routes and Root Services#
A tool for exporting dashboard metrics should not exist while the user is on the login screen. To bind tools to a route's lifecycle, register the provider on the route definition and enable automatic cleanup on the router:
// app.routes.ts
export const routes: Routes = [
{
path: 'dashboard',
loadComponent: () => import('./dashboard').then((m) => m.Dashboard),
providers: [
provideExperimentalWebMcpTools([
{
name: 'exportDashboardReports',
description: 'Exports metrics from the current dashboard.',
execute: () => ({
content: [{ type: 'text', text: 'Dashboard export started.' }],
}),
},
]),
],
},
];
// app.config.ts
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes, withAutoCleanupInjectors())],
};Without withAutoCleanupInjectors() (named withExperimentalAutoCleanupInjectors() in early 22.0 builds), route-scoped tools stay registered even after the user navigates away.
When a tool belongs to global state, declare it inside a root singleton service using declareExperimentalWebMcpTool. Never register tools inside a reusable component: tool names must be unique in the browser, and rendering three instances of the same component throws a runtime error.
Exposing Signal Forms as Tools Automatically#
The highest-leverage WebMCP feature in Angular 22 is Signal Forms integration. Enable provideExperimentalWebMcpForms() at the root and attach the experimentalWebMcpTool option to your form:
import { provideExperimentalWebMcpForms } from '@angular/forms/signals';
bootstrapApplication(AppRoot, {
providers: [provideExperimentalWebMcpForms()],
});
readonly userForm = form(
this.model,
(f) => {
required(f.firstName, { message: 'First name is required.' });
required(f.lastName, { message: 'Last name is required.' });
},
{
experimentalWebMcpTool: {
name: 'registerUser',
description: 'Registers a new user in the system.',
},
submission: {
action: async (formValue) => {
// submit validated data to your API
},
},
},
);Angular generates the JSON Schema from the form model and wires the tool to your validators and submission action. If the agent submits invalid data, it receives the exact validation errors and retries. Three constraints apply:
Concrete initial values: initialize fields with
'',0, orfalse. Withnullorundefined, the schema generator cannot infer field types.Typed arrays need a sample item: include at least one initial element so Angular can infer the item schema.
Async validators do not block submission: remote checks (such as duplicate email validation) are not surfaced back to the agent automatically; re-verify inside
submission.action.
For unit testing without relying on experimental browser flags, use the @mcp-b/webmcp-polyfill package and test hostile paths first: wrong types, missing fields, and oversized strings.
Where Tools Fit in Your Architecture and What Belongs in Production#
Keep WebMCP tools inside the feature folder they belong to, right next to the store, acting as thin adapters that delegate all business rules to the state layer:
features/orders/
├── data/
│ ├── orders.store.ts
│ └── orders.tools.ts # WebMCP adapters for this domain
├── ui/
├── pages/
└── orders.routes.ts # registers providers at route scopeWhen presenting this stack to your engineering team, draw a clear line between production-ready tooling and experimental APIs:
Capability | Maturity | Impact & Recommendation |
|---|---|---|
| Stable (Production) | Zero runtime risk; standardizes AI-generated code across the whole team. |
Official Angular Agent Skills | Stable (Production) | Versioned alongside the framework; prevents stale prompt drift. |
Angular CLI MCP Server | Stable (Production) | Speeds up OnPush/zoneless migrations and TDD; start with --read-only. |
WebMCP (Tools & Forms) | Experimental | Great for prototypes and PoCs; subject to breaking changes in Angular and Chrome. |
Frequently Asked Questions About AI, MCP, and WebMCP in Angular 22#
Does the Angular CLI MCP server modify project files on its own?#
Only if you allow write or execution tools like run_target. Launching the server with the --read-only flag restricts the agent strictly to documentation lookups and read-only workspace inspection.
What is the difference between Agent Skills and GEMINI.md or cursor.md?#
A repository rules file is injected into every conversation and should stay concise. Agent Skills load progressively on demand: the agent pulls in deep architectural or project-scaffolding instructions only when working on an Angular task, saving context tokens while keeping precision high.
Can I ship WebMCP in critical production flows today?#
Not recommended for critical user paths. Both Angular 22's provideExperimentalWebMcpTools APIs and Chrome's browser specification are experimental and may introduce breaking changes outside major releases.
Where to Start Today#
Start with what delivers immediate payoff at zero runtime risk: commit a rules file based on best-practices.md, install the official Agent Skills, and enable the CLI MCP server in --read-only mode. Use the guided migration workflow to move legacy components toward zoneless—and keep WebMCP in prototypes until the browser spec settles.
Which of these workflows are you enabling first in your team's repository? Drop a comment sharing how agents are behaving with Angular on your projects—and subscribe to the Blense newsletter for upcoming hands-on frontend engineering guides.
