WebMCP: How to Expose Site Actions to AI Agents
On this page
WebMCP exposes site actions to AI agents by embedding executable JSON schemas directly in the DOM, allowing agents to trigger state-changing events like form submissions or API calls without parsing visual interfaces. It is not a new HTML standard, but a client-side protocol specification that bridges browser events and backend logic, distinct from static data exposure methods like JSON-LD.
Most implementations fail because they treat agent actions as simple data retrieval. The critical distinction lies in defining executable actions versus passive resources. You must structure the JSON to specify validation rules, authentication handshakes, and specific DOM event bindings. This prevents untrusted agents from triggering destructive state changes while ensuring the agent can verify success. We detail the exact schema differences and the security patterns required to safely expose internal site logic to external LLMs.
What WebMCP Is and Why It Exists
How to Connect AI Tools to WordPress Using MCP covers the foundational transport mechanisms, while WebMCP focuses specifically on the execution layer within the browser. This separation of concerns allows developers to maintain strict security boundaries. The agent does not need raw DOM access; it only needs permission to call defined, validated actions. This model shifts the responsibility from the LLM to the application. The developer defines the safe actions, and the agent selects the appropriate one based on user intent. For teams looking to implement this without rebuilding their frontend, the process involves wrapping existing event handlers in a standardised interface. You can see a practical implementation of this logic in our walkthrough on Automate Your Website with AI in 3 Easy Steps | CloudyWP, which demonstrates how to map simple UI interactions to agent-callable functions. The core benefit is reliability. By constraining agent behaviour to pre-defined actions, you eliminate the risk of unpredictable DOM mutations. The agent acts as a user with developer-level precision. This is the fundamental shift from descriptive metadata to prescriptive execution.
The Architecture: From Agent to Action
WebMCP architecture positions the browser as the execution layer between the LLM and your backend. The LLM does not call your database directly. Instead, it generates a structured intent based on the schema you provide. A client-side interpreter in the browser validates this intent against your defined rules. Only then does it construct a standard HTTP request to your API Gateway. This flow ensures that the AI never sees raw credentials or direct database access. It only sees the permitted actions you have explicitly exposed.
This design answers a common concern: does WebMCP replace REST APIs? No. Your existing REST endpoints remain the source of truth for data retrieval and state changes. WebMCP acts as a semantic wrapper. It translates the LLM’s natural language reasoning into specific API calls. The API Gateway still enforces rate limits, authentication, and CORS policies. The browser’s role is critical here because it acts as a secure sandbox. JavaScript execution is isolated from the core application logic. The interpreter rejects actions outside the schema before network requests leave the client, preventing prompt injection from reaching the backend.
The distinction from standard JSON-LD or OpenAPI specs is functional. OpenAPI documents how to call an endpoint. WebMCP defines what an action means in the context of a user’s goal. For example, an OpenAPI spec might list a /cart/add endpoint. A WebMCP action might be defined as “add item to purchase list,” with specific parameters for quantity and variant. The LLM reasons about the goal, not the URL. This semantic layer allows the agent to chain actions intelligently without hardcoding logic for every possible user request.
We have seen this pattern work well when integrating with visual builders. The browser handles the complexity of state management and DOM updates. The backend remains stateless and secure. For a practical look at how this connects to front-end frameworks, see Connect Elementor to AI via MCP: Setup Guide | CloudyWP. The key takeaway is that you are not exposing your entire API surface to the LLM. You are exposing a curated set of capabilities. The API Gateway remains the final gatekeeper, validating every request that passes through the browser’s interpreter. This layered approach keeps your security model intact while enabling agentic behaviour.
Defining Actions: The Schema
The Action Schema defines the exact JSON structure an agent uses to invoke a site function, specifying parameters, expected outputs, and error handling. Unlike OpenAPI, which documents REST endpoints for server-to-server communication, the WebMCP Action Schema describes executable capabilities within a browser context. This distinction matters because agents must understand not just what data to send, but what UI state changes result from the call.
Each action object contains a unique identifier, a human-readable description, and a parameters array. Every parameter object includes a name, type, description, and a required boolean. The schema also defines the output structure, detailing the JSON shape returned upon success. Crucially, it includes an errors object that maps specific error codes to human-readable messages and recovery suggestions. This allows the agent to interpret failures logically rather than treating them as opaque crashes.
Consider a “Search Products” action. The schema would define a query string parameter and an optional category string. The output would specify an array of product objects, each with an id, name, and price. If the search returns no results, the error object might return a NO_RESULTS code with a message suggesting broader search terms. This structure enables the agent to adjust its strategy autonomously.
When an agent executes an action, it validates the input against the schema before dispatching the request. If a required parameter is missing, the agent receives a validation error immediately, preventing unnecessary network calls. If the server returns an unexpected status code, the error mapping guides the agent’s next step. For instance, a 403 Forbidden response might trigger a re-authentication flow, while a 500 Internal Server Error prompts a retry with exponential backoff. This deterministic error handling ensures that agent behaviour remains predictable and debuggable.
We recommend keeping action schemas granular. A single “Update Profile” action is harder to secure and test than separate “Update Name” and “Update Email” actions. Granularity allows you to apply specific permissions and logging to each capability. It also simplifies the agent’s decision-making process, as each action has a single, clear purpose. This approach aligns with how you would design 7 Steps to AI Business Automation | CloudyWP workflows, where discrete, well-defined steps are easier to monitor and optimise than monolithic operations.
Finally, version your schemas. As your site evolves, action parameters may change. By including a version field in the schema, you can deprecate old actions gracefully while introducing new ones. Agents can then select the appropriate version based on their capabilities, ensuring backward compatibility without breaking existing integrations. This structured approach to schema design provides the clarity both developers and AI agents need to interact reliably with your platform.
Security and Authentication
WebMCP security relies on standard web protocols, but the execution context changes how you apply them. An agent is not a human user. It does not see a login form, and it cannot complete a CAPTCHA. Your endpoints must treat automated traffic as the default, not the exception.
Authentication is the first layer. You cannot rely on session cookies if the agent runs in a headless environment or a server-side process. Use OAuth 2.0 with the client credentials grant type for server-to-server communication. This allows the agent to obtain a short-lived access token without exchanging user credentials. For actions that require user-specific data, such as viewing a private order history, you need a delegated flow. The agent requests a token on behalf of a user, and the endpoint validates that token against the user’s permissions. This mirrors how standard REST APIs handle scoped access, but the token lifetime should be shorter.
Cross-Origin Resource Sharing (CORS) policies are often misconfigured for agent traffic. If your frontend calls the API from a different origin, you must explicitly allow the agent’s origin. More critically, you must restrict the Access-Control-Allow-Methods and Access-Control-Allow-Headers to only what the agent needs. Do not use * for credentials. If you use Access-Control-Allow-Credentials: true, you must specify exact origins. An open CORS policy with credentials is a direct path to session hijacking by a malicious agent.
Rate limiting is a key defence against abuse. An LLM can generate hundreds of requests per second if it is not constrained. Implement token bucket or leaky bucket algorithms at the API gateway level. Set limits per API key, not per IP address, because agents often rotate IPs. If an agent exceeds its limit, return a standard 429 Too Many Requests response with a Retry-After header. This tells the agent to back off. Without this, a single buggy agent can exhaust your server resources and take down the site for human users. See our analysis of WordPress AI Infrastructure: What Actually Breaks for how these failures manifest in production.
Finally, audit your logs. Standard access logs are not enough. You need to log the agent’s identifier, the action taken, and the parameters used. This allows you to analyse behaviour patterns and detect anomalies. If an agent starts requesting sensitive endpoints it has not accessed before, you need an alert. Security for agents is not a one-time setup. It is an ongoing process of monitoring and adjustment.
Implementation: A Practical Example
Implementation begins with registering a specific action handler in JavaScript, binding a semantic intent to a secure backend endpoint rather than manipulating the DOM. The handler must validate inputs, execute the server-side operation, and return a structured result that the agent can parse. This approach ensures that the action respects the authentication boundaries established in the security layer, preventing unauthorised state changes.
Consider an “add to cart” action. The registration process defines the input schema and the execution logic. The code below demonstrates a compliant implementation. It uses a fetch call to a protected endpoint, handling both success and failure states explicitly. The error handling structure returns a standardised object, allowing the agent to retry or inform the user without breaking the conversation flow.
WebMCP.registerAction({
name: "add_to_cart",
description: "Adds an item to the user's shopping cart",
inputSchema: {
type: "object",
properties: {
itemId: { type: "string" },
quantity: { type: "integer", minimum: 1 }
},
required: ["itemId", "quantity"]
},
handler: async (input) => {
const response = await fetch("/api/cart/add", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(input)
});
if (!response.ok) {
return {
status: "error",
code: response.status,
message: "Failed to add item to cart"
};
}
const data = await response.json();
return {
status: "success",
data: data
};
}
});
This pattern separates the agent’s intent from the browser’s interface. The agent never touches the DOM directly; it communicates with the server through a defined contract. This distinction is critical for maintaining consistent behaviour across different client environments. If you are building broader automation workflows, the principles here align with the strategies outlined in our AI Agents for Business Automation: A Practical Guide. Always ensure your server-side endpoints enforce the same validation rules as the client-side schema. This redundancy protects against malformed requests from any source. Review your Terms of service to confirm that automated actions comply with your platform’s usage policies. The handler returns a simple JSON object. The agent reads this object and decides its next step. The DOM remains untouched, preserving the user’s current view and interaction state. This separation of concerns allows developers to optimise the backend for performance while keeping the frontend responsive. The code is straightforward JavaScript, requiring no special libraries. It relies on standard browser APIs and the WebMCP registration interface. This makes it easy to integrate into existing projects without adding heavy dependencies.
Frequently asked questions
What is the difference between WebMCP and OpenAPI
WebMCP targets browser-side execution, while OpenAPI describes server-side REST endpoints. OpenAPI defines how to call a function; WebMCP defines how to trigger a user action within a live DOM. An agent using OpenAPI sends a request to a server. An agent using WebMCP executes a script in the user’s browser context, allowing it to interact with UI elements directly without requiring a backend API change.
How do I let an AI agent click buttons on my site
You expose the button’s action through a WebMCP action definition. The agent does not physically click the element. Instead, it calls the defined action, which triggers the same JavaScript event handler a human click would. This ensures state management, validation, and side effects remain consistent with normal user behaviour, preventing the agent from bypassing your application logic.
Is WebMCP a new HTML standard
WebMCP is not a new HTML standard. It is a protocol layer that sits on top of existing web technologies. It uses standard JSON schemas to describe actions and relies on the browser’s JavaScript engine for execution. You do not need to add new HTML tags or change your markup. The integration happens through script injection or API calls that map agent intents to your existing front-end functions.
How does WebMCP handle authentication for agents
WebMCP inherits the browser’s existing authentication state. The agent operates within the user’s session, so cookies, tokens, and headers are automatically included in any subsequent requests triggered by the action. You do not need to issue separate agent credentials. This means the agent acts on behalf of the logged-in user, subject to the same permissions and restrictions that apply to a human visitor.
Can I use WebMCP with Claude or GPT
Yes, you can use WebMCP with both Claude and GPT. These models can interpret WebMCP action schemas and generate the necessary calls to trigger site actions. The model does not execute the code itself. It sends the intent to your front-end logic, which then performs the action in the browser. This allows you to connect major LLMs to your site’s interactive features without building a custom integration for each model.
How to secure WebMCP endpoints
Secure WebMCP by treating actions as sensitive operations, just like any other API call. Validate all inputs on the server side, even if the action runs in the browser. Implement rate limiting and monitor for unusual patterns of agent requests. Because the agent acts within the user’s session, your existing security controls, such as CSRF tokens and session validation, remain effective and do not need to be bypassed.
What to do next
Start by mapping your highest-value user actions to WebMCP schemas. Pick one workflow that drives significant traffic or revenue, such as updating a profile or filtering product listings, and define its inputs, outputs, and error states. Do not attempt to expose your entire backend at once. Write the JSON schema for that single action, including strict type definitions and validation rules. Then, build a minimal endpoint that accepts the agent’s request, executes the logic, and returns a structured response. Test this loop with a simple LLM prompt before integrating complex authentication. This approach isolates security risks and lets you verify that the agent interprets your data correctly. Once that single action works reliably, you can replicate the pattern for other features.
Be the first to comment