Make Your Angular App Agent-Ready with WebMCP

Originally published on my blog.
Version note: I wrote this against Angular 22.3 and the WebMCP draft as of November 2026. Every API shown here is experimental, and I will update the post after Angular 22.4 if anything changes.
Browser AI agents can already book a table or fill in a form for someone, but they do it the hard way. They take screenshots, read the DOM, guess which button is the right one, click, and hope. That is slow and expensive in tokens, and it breaks the moment you rename a CSS class or move a button.
WebMCP turns this around. Your page publishes a small contract of tools: named functions with a description and a JSON Schema for their input. The agent reads the contract and calls the function directly.
Angular 22 ships experimental support for it. In this article we build a small todo app that exposes seven tools to agents. One of them is a Signal Form that turns into a tool with no extra code. We also build a small "agent console" so you can test everything in a normal browser today.
The full demo is on GitHub: angular-webmcp-todo. You can also try the live demo.
What WebMCP is, in one minute
WebMCP is a W3C Community Group draft that adds a modelContext object to the document. A page registers tools on it:
await document.modelContext.registerTool({ name: 'add_todo', description: 'Creates a new todo with the given title.', inputSchema: { type: 'object', properties: { title: { type: 'string' } }, required: ['title'] }, execute: ({ title }) => ({ content: [{ type: 'text', text: `Added ${title}` }] }), }); An agent in the browser calls getTools() to discover what the page offers and executeTool() to run one. Think of it as MCP, but the server is your web page and the tools run in the user's own session, with the user's own auth.
Here is the difference for a simple request like "add 'buy milk' to my todos":
| Without WebMCP | With WebMCP |
|---|---|
| Screenshot the page, find the input, click it, type, find the Add button, click, screenshot again to check | add_todo({ title: 'buy milk' }) |
As of today, Chrome ships WebMCP as an early preview, and Angular marks its support as experimental. The Angular docs say the APIs may change even outside major versions. I would use it for learning and prototypes for now, and keep it out of production architecture.
Setup
Create an Angular 22 app and add the W3C polyfill so the API exists in any browser:
npx @angular/cli@22 new angular-webmcp-todo cd angular-webmcp-todo npm install @w3c/webmcp-polyfill Install the polyfill before bootstrapping, because Angular registers tools while the application initialises:
// src/main.ts import { bootstrapApplication } from '@angular/platform-browser'; import { installWebMCP } from '@w3c/webmcp-polyfill'; import { appConfig } from './app/app.config'; import { App } from './app/app'; // Never replaces a native implementation, so it is safe to leave in. installWebMCP(); bootstrapApplication(App, appConfig).catch((err) => console.error(err)); WebMCP only exists in a secure context, so serve the app from localhost or HTTPS.
One store for the UI and the agent
Before writing any tools, decide where the logic lives. My rule is that tools call the same store the UI calls. That way an agent can never do something the UI cannot, and you never maintain two versions of "add a todo".
// src/app/todos/todo-store.ts @Injectable({ providedIn: 'root' }) export class TodoStore { private readonly _todos = signal<Todo[]>(load()); readonly filter = signal<TodoFilter>('all'); readonly todos = this._todos.asReadonly(); readonly remaining = computed(() => this._todos().filter((t) => !t.done).length); constructor() { effect(() => localStorage.setItem(STORAGE_KEY, JSON.stringify(this._todos()))); } add(title: string): Todo { /* ... */ } setDone(id: string, done: boolean): Todo | undefined { /* ... */ } remove(id: string): boolean { /* ... */ } clearCompleted(): number { /* ... */ } } Because the state lives in signals, anything an agent changes shows up in the UI straight away. With OnPush now the default in Angular 22, signals are also what keeps rendering cheap. I wrote more about that in Optimizing Angular Change Detection with OnPush.
App-wide tools with provideExperimentalWebMcpTools
provideExperimentalWebMcpTools takes an array of tool descriptors and returns environment providers. The tools are registered when the injector initialises and unregistered when it is destroyed.
// src/app/todos/todo-tools.ts import { inject, provideExperimentalWebMcpTools } from '@angular/core'; import { TodoStore } from './todo-store'; export const provideTodoTools = () => provideExperimentalWebMcpTools([ { name: 'list_todos', title: 'List todos', description: 'Returns every todo with its id, title and done state. Call this first to find the id of a todo.', annotations: { readOnlyHint: true }, execute: () => { const store = inject(TodoStore); return json({ remaining: store.remaining(), todos: store.todos() }); }, }, { name: 'add_todo', title: 'Add a todo', description: 'Creates a new todo with the given title. Returns the created todo.', inputSchema: { type: 'object', properties: { title: { type: 'string', description: 'What needs to be done, 1 to 200 characters.' }, }, required: ['title'], }, execute: ({ title }) => { if (typeof title !== 'string' || !title.trim() || title.length > 200) { return error('title must be a non-empty string of at most 200 characters.'); } return json(inject(TodoStore).add(title)); }, }, // complete_todo, delete_todo, clear_completed ... ]); const json = (value: unknown) => ({ content: [{ type: 'text', text: JSON.stringify(value) }] }); const error = (message: string) => ({ isError: true, content: [{ type: 'text', text: message }] }); Register it like any other provider:
// src/app/app.config.ts export const appConfig: ApplicationConfig = { providers: [provideBrowserGlobalErrorListeners(), provideTodoTools()], }; Some details in that code:
-
inject()works insideexecute. Angular runs the callback in the injection context of the injector that registered the tool, so you use your services exactly as you would anywhere else. - Angular infers the argument type
{ title: string }frominputSchema. This only affects TypeScript, which matters later in the security section. - Annotations tell the agent how careful to be.
readOnlyHint: truesays the tool only reads.consequentialHint: true, which I put ondelete_todoandclear_completed, says the effect is significant or hard to undo, so a well-behaved agent should confirm with the user first. - The description is read by a model, so write it like a prompt. "Call this first to find the id of a todo" saves the agent a wrong guess.
Tools that live and die with a component
Some tools only make sense on one screen. A "filter the list" tool is useless when the list is hidden. declareExperimentalWebMcpTool registers a single tool from the current injection context and removes it automatically when that context is destroyed:
// src/app/todos/todo-list.ts export class TodoList { protected readonly store = inject(TodoStore); constructor() { declareExperimentalWebMcpTool({ name: 'set_filter', title: 'Filter the visible todos', description: 'Changes which todos the list shows to the user: all, active or completed.', inputSchema: { type: 'object', properties: { filter: { type: 'string', enum: ['all', 'active', 'completed'] } }, required: ['filter'], }, execute: ({ filter }) => { if (!FILTERS.includes(filter as TodoFilter)) { return { isError: true, content: [{ type: 'text', text: `filter must be one of ${FILTERS.join(', ')}.` }] }; } this.store.filter.set(filter as TodoFilter); return { content: [{ type: 'text', text: `Showing ${filter} todos.` }] }; }, }); } } Under the hood, Angular passes an AbortSignal to registerTool and aborts it from the component's DestroyRef. The demo has a checkbox that hides the list. Untick it and set_filter disappears from getTools(); tick it and it comes back.
That suggests declaring tools per route or per feature, so the agent sees what the user sees and the tool list stays short. It is the same modular approach I described in Building Scalable and Maintainable Front-End Applications, with an agent as one more consumer.
Signal Forms as tools, with no tool code
This is my favourite part. Signal Forms are stable in Angular 22, and a form can register itself as a WebMCP tool.
First, enable it once in the app config:
// src/app/app.config.ts import { provideExperimentalWebMcpForms } from '@angular/forms/signals'; providers: [provideBrowserGlobalErrorListeners(), provideTodoTools(), provideExperimentalWebMcpForms()], Then add experimentalWebMcpTool to the options of any form:
// src/app/todos/todo-list.ts private readonly newTodo = signal({ title: '' }); protected readonly todoForm = form( this.newTodo, (p) => { required(p.title, { message: 'Title is required.' }); pattern(p.title, /\S/, { message: 'Title cannot be only spaces.' }); maxLength(p.title, 200, { message: 'Title must be at most 200 characters.' }); }, { experimentalWebMcpTool: { name: 'new_todo_form', description: 'Fills in and submits the "new todo" form shown on the page.', }, submission: { action: async (f) => { this.store.add(f.title().value()); this.newTodo.set({ title: '' }); return undefined; }, }, }, ); <!-- src/app/todos/todo-list.html --> <form [formRoot]="todoForm"> <input [formField]="todoForm.title" placeholder="What needs to be done?" /> <button type="submit">Add</button> </form> That is the whole tool. Angular does the rest:
- It infers the input schema from the model.
{ title: '' }becomes{ type: 'object', properties: { title: { type: 'string' } }, required: ['title'], additionalProperties: false }. Therequiredlist comes from yourrequired()rule. - It writes the agent's arguments into the form and calls
submit(), so your normalsubmission.actionruns. - It returns validation errors to the agent. Calling it with
{ title: ' ' }returns:
Form submission failed: title: Title cannot be only spaces. The agent can read that and retry, and you only wrote the rules once.
There are limits. The schema is inferred from the current value, so a model with null, undefined or an empty array cannot be inferred and Angular throws. Fields get no per-field descriptions, so put the guidance in the tool description. A failed submission comes back as plain text without isError, so check the text if you build your own agent tooling.
So when do you pick a form tool over a hand-written one? Use a form tool when the action already exists as a form and you want the agent to go through exactly the same rules as the user. Write a tool by hand when you need rich descriptions per argument, structured results (like returning the created todo's id), or an action that has no form at all.
Treat the agent as an untrusted user
Angular does not validate agent input against inputSchema. The schema produces TypeScript types and tells the agent what to send, but nothing at runtime stops an agent from sending { title: 42 }.
So every hand-written tool validates its own arguments and returns an error the agent can act on:
execute: ({ id, done }) => { const store = inject(TodoStore); if (typeof id !== 'string' || !store.find(id)) { return error(`No todo with id "${String(id)}". Call list_todos to get valid ids.`); } if (done !== undefined && typeof done !== 'boolean') { return error('done must be a boolean.'); } return json(store.setDone(id, done ?? true)); }, The error message tells the agent what to do next. If you like making invalid states impossible at compile time, exhaustive checks pair nicely with this runtime layer.
My checklist for every tool:
- Validate every argument's type and range at runtime, even when the schema seems to guarantee it.
- Return errors with
isError: trueand a next step. - Mark destructive tools with
consequentialHint. - Expose only what the current user may do. Tools run in the user's session, so never register admin-only actions for normal users.
- Keep authorization on the server. A tool is one more client of your API, and the backend still checks every request.
Testing your tools
The polyfill works in unit tests too. jsdom is not a secure context, so mark it as one before installing:
// src/app/app.spec.ts Object.defineProperty(window, 'isSecureContext', { value: true }); installWebMCP(); const call = async (name: string, input: object = {}) => { const tool = (await document.modelContext!.getTools()).find((t) => t.name === name); if (!tool) throw new Error(`tool ${name} is not registered`); return JSON.parse(await document.modelContext!.executeTool(tool, input)); }; it('rejects invalid input instead of trusting the schema', async () => { const res = await call('add_todo', { title: 42 }); expect(res.isError).toBe(true); expect(TestBed.inject(TodoStore).todos().length).toBe(0); }); The demo has four Vitest tests: all seven tools register, an agent call reaches the store, bad input is rejected, and the Signal Form tool submits through its validators.
For manual testing, the demo includes an agent console: a component that knows nothing about TodoStore and only uses getTools() and executeTool(), exactly like a real agent. Pick a tool, edit the JSON arguments, call it, and watch the list update.
Once that works, try it with a real browser agent that supports WebMCP.
Should you ship this?
Not to production yet. WebMCP is a draft, browser support is an early preview, and Angular's APIs are explicitly experimental. Still, the design fits Angular well: tools can use DI, registration follows component lifecycles, and a Signal Form becomes a tool with one option.
For internal tools and prototypes I would start now. Put your features in store methods the UI and an agent can share, keep tools next to the components they belong to, and validate every call.
The complete demo is on GitHub: angular-webmcp-todo. Try it live at atheodosiou.github.io/angular-webmcp-todo.
What tools would your app expose? Tell me in the comments.
Sources
- Angular: Build with AI, WebMCP
- Angular API: provideExperimentalWebMcpTools
- WebMCP draft, W3C Web Machine Learning Community Group
- @w3c/webmcp-polyfill
- Angular 22: the most important new features (Angular Architects)
This article was originally published on anastasios.theodosiou.me. Read it there for the latest updates.
原文:https://www.a8q9.cn/en/article/make-your-angular-app-agent-ready-with-webmcp-f1c0b2.html