Expose WooCommerce Actions to AI via MCP
Luke Anderson WordPress

Expose WooCommerce Actions to AI via MCP

Expose WooCommerce actions to an MCP server by writing a bridge that translates MCP tool calls into HTTP requests against the WooCommerce REST API. You define specific tools like add_to_cart or get_stock in the MCP server configuration, mapping each to a corresponding REST endpoint and passing credentials securely. The AI agent then invokes these tools, and the bridge executes the request on your behalf.

Most guides treat the MCP server as a black box, omitting the critical distinction between read-only data exposure and write-action execution. They also ignore the hosting requirement: you need a Node.js or Python environment to run the bridge, which most WordPress users do not have pre-configured. This guide covers the specific code-level steps to map endpoints, scope permissions for sensitive actions like checkout, and deploy the bridge without exposing your store to unauthorised modifications.

Understanding the MCP-WooCommerce Bridge

WordPress does not natively speak MCP, so you must deploy a middleware server to translate Model Context Protocol tool definitions into WooCommerce REST API calls. The bridge requires a runtime environment like Node.js or Python that listens for MCP requests and maps them to specific HTTP endpoints. When an AI agent requests the add_to_cart tool, the middleware constructs a POST request to /wp-json/wc/v3/cart/items with the necessary product identifiers. Similarly, a get_stock query translates to a GET request against the products endpoint, filtering by SKU or ID. This translation layer handles authentication, payload formatting, and error parsing that the raw REST API expects but the MCP client does not provide.

Defining these tools requires explicit JSON schemas in your MCP server configuration. You specify the input parameters, such as product_id and quantity, and map them to the corresponding WooCommerce REST API fields. For subscription-based products, the middleware must also handle the subscription object within the payload, ensuring that billing intervals and trial periods align with the WooCommerce Subscriptions data structure. Without this precise mapping, the AI agent cannot execute actions or retrieve accurate inventory data.

Setting up this connection involves configuring your Node.js or Python server to point to your WordPress site’s REST API base URL. You must generate application passwords or API keys for secure authentication. The middleware then exposes these capabilities as MCP tools, allowing the AI to interact with your store’s backend directly. This setup enables complex workflows, such as automated stock adjustments or order processing, without manual intervention. For a deeper look at how these automated processes integrate with broader store operations, review our guide on Advanced Inventory Management and Automation for WooCommerce. Additionally, ensuring your site structure supports AI interpretation is critical, so consider the Checklist: Making Your WordPress Site Readable by AI to validate your frontend and schema markup.

Generating Secure API Credentials

Application Passwords and OAuth 2.0 are the two mechanisms for securing WooCommerce API access for your AI agent. Application Passwords are built into WordPress core and require no additional plugins, while OAuth 2.0 requires a dedicated plugin to handle the token exchange. For most WooCommerce setups, Application Passwords are the simplest path because they generate a unique username and password pair specifically for API requests, bypassing the need for session cookies.

To create an Application Password, log in to your WordPress admin as a user with the Administrator or Shop Manager role. Navigate to Users in the left-hand menu, then click your username to open the Edit User screen. Scroll down to the Application Passwords section at the bottom of the page. Type a descriptive name, such as mcp-woo-agent, into the input field and click Add New Application Password. WordPress will display the generated password immediately. Copy it to a secure location, as it will not be shown again. This password works with the standard WooCommerce REST API endpoints, including /wc/v3/products and /wc/v3/cart, when you include it in the HTTP Authorization header using Basic Authentication.

If your MCP server requires OAuth 2.0, install a plugin like OAuth 2.0 for WordPress or WP OAuth2. These plugins add a new menu item under Settings or Tools where you can register a new application. You will specify a redirect URI that matches your MCP server’s callback endpoint. The plugin generates a Client ID and Client Secret. Use these credentials in your MCP configuration to initiate the OAuth 2.0 authorization code flow. The resulting access token grants scoped permissions, allowing you to restrict the AI agent to specific endpoints like /wc/v3/products while blocking access to sensitive data such as /wc/v3/customers.

For both methods, ensure your server enforces HTTPS. WooCommerce REST API requests over HTTP will fail if the site is configured to require secure connections. Test the credentials by making a simple GET request to /wp-json/wc/v3/products?per_page=1 using the generated password or token. If the response returns product data, your credentials are working correctly. If you receive a 401 Unauthorized error, verify that the password or token is correct and that the user role has permission to read products. For detailed setup on other platforms, see Boost Shopify Sales with AI Automation | CloudyWP.

Defining Tools in the MCP Server

Defining tools in the MCP server requires mapping specific JSON-RPC methods to WooCommerce REST API endpoints. Each tool object you register tells the AI agent exactly which HTTP request to make and how to structure the payload. For example, to let an agent check inventory, you define a tool named get_product_stock that targets the /wp-json/wc/v3/products endpoint. The tool schema specifies the required parameters, such as product_id, and the expected response format. Similarly, to enable cart operations, you create an add_to_cart tool that maps to the /wp-json/wc/v3/cart endpoint. This tool accepts parameters like cart_item_key and quantity. The MCP server translates the agent’s natural language intent into these structured JSON-RPC calls, ensuring the AI executes precise WooCommerce actions rather than guessing. This direct mapping is what allows an agent to accurately view stock levels or add items to a cart without human intervention. If you are building broader workflows around these interactions, see 7 Steps to AI Business Automation | CloudyWP for context on how these tools fit into larger automation strategies.

{
  "name": "get_product_stock",
  "description": "Retrieve current stock levels for a specific WooCommerce product",
  "inputSchema": {
    "type": "object",
    "properties": {
      "product_id": {
        "type": "integer",
        "description": "The unique ID of the product"
      }
    },
    "required": ["product_id"]
  },
  "endpoint": "/wp-json/wc/v3/products/{product_id}"
}

For plugins like WooCommerce Bookings, you follow the same pattern. You define a tool such as get_booking_slots that queries the relevant bookings endpoint. The key is precision: the tool name, description, and schema must match the actual API contract. This ensures the AI agent receives valid data and can act on it correctly. Vague definitions lead to failed requests and confused agents. By explicitly coding these mappings, you give the AI a reliable interface to your store’s data.

Handling Write Actions and State

Write actions in WooCommerce, such as adding items to the cart, require state management that standard read-only API calls cannot handle. The Model Context Protocol does not natively manage browser sessions or cookies, so your MCP server must explicitly handle the persistence of cart data. Direct database manipulation via wp db query or WP-CLI commands is dangerous because it bypasses WooCommerce’s hook system, meaning no stock validation, tax calculation, or coupon application occurs. Instead, route all write operations through the WooCommerce REST API endpoints designed for stateful interactions.

To implement this, your MCP server tool definition for add_to_cart must capture the session parameter. When the AI agent initiates a cart action, the server sends a request to the /wc/v3/cart endpoint (or the appropriate custom endpoint if using a specific cart plugin) using the consumer key and secret you generated. The response includes a session_token. Your server must store this token in a secure, short-lived cache keyed by the AI conversation ID. Subsequent requests, such as update_cart or checkout, must include this token in the request headers to maintain context. If you are testing locally, you can verify the flow by using WP-CLI to inspect the session table after a request, ensuring the cart line items are persisted correctly before the AI proceeds to the next step.

Common failure modes include session expiry and concurrent state conflicts. If the AI pauses for user input, the session token may expire. Configure your server to catch 401 or 403 responses and prompt the agent to re-initialise the session. Never allow the AI to guess cart contents; always fetch the current state via GET /cart before modifying it. This pattern ensures that the AI acts on real, validated data rather than assumptions. For a broader look at how this fits into a larger architecture, see WebMCP: How to Expose Site Actions to AI Agents.

Testing the Connection with an AI Client

Testing the connection with an AI client verifies that your MCP server correctly translates natural language prompts into WooCommerce API calls. Start by launching your chosen client, such as Claude Desktop or a custom LangChain agent, and configure it to point at your local MCP server endpoint. For Claude Desktop, edit the claude_desktop_config.json file to include the server command and environment variables. For a LangChain setup, instantiate the MultiServerMCPClient class in your Python script, specifying the server URL and authentication headers.

Once the client connects, issue a simple read-only command to retrieve product data. In Claude Desktop, type a prompt like “Get the stock level for product ID 101.” In a LangChain agent, call the tool function directly with the product ID parameter. The AI client sends this request to your MCP server, which maps it to the WooCommerce REST API endpoint /wp-json/wc/v3/products/101. Your server executes the PHP function defined in your bridge code, retrieves the JSON response from WordPress, and returns the stock quantity to the client.

Check the response for two things. First, confirm the data matches what you see in the WordPress admin dashboard under Products. Second, verify the response time. If the request hangs, check your MCP server logs for PHP errors or CORS issues. If the data is missing, ensure your API credentials have the read permission for the products resource. A successful test returns clean JSON with the expected fields, proving the bridge works end-to-end.

Troubleshooting CORS and Authentication Errors

CORS and authentication errors block most MCP server connections to WordPress. If your FastMCP instance runs locally or on a different domain, the browser or HTTP client enforces the Same-Origin Policy, resulting in 401 or 403 responses before the request reaches the REST API. You need to configure both the server-side headers and the client-side credentials correctly.

First, ensure your WordPress site sends the correct Access-Control-Allow-Origin header. Add the following to your theme’s functions.php file or a custom plugin:

add_action('init', function() { header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Content-Type, Authorization, X-WP-Nonce');
});

If you use a specific domain instead of a wildcard, replace * with that exact origin. For production environments, avoid wildcards to prevent cross-site request forgery. Next, verify your authentication method. If you use Application Passwords, ensure the Authorization header is formatted as Basic base64_encode('username:password'). If you use JWT or OAuth, confirm the token is valid and not expired.

Common pitfalls include missing the OPTIONS preflight request handler. WordPress does not automatically respond to preflight requests with the required CORS headers. The snippet above handles this by adding the necessary headers during the rest_api_init hook. If you still see 403 errors, check your wp-config.php for WP_DEBUG settings that might block certain headers, or review your web server’s security rules in Apache or Nginx. For persistent issues, our WooCommerce Support team can audit your server configuration. Understanding how these headers affect AI visibility for WordPress sites ensures your MCP tools remain accessible to external agents without compromising security.

Frequently asked questions

How to connect WooCommerce to MCP server

Connect them by creating a custom MCP server that acts as a bridge between the AI client and your store’s REST API. You do not connect the plugin directly to the AI. Instead, you write a small server application, often in Node.js or Python, that reads the MCP protocol. This server holds your WooCommerce API keys and translates the AI’s tool calls into standard HTTP requests to your WordPress site.

Can AI agents add to cart in WooCommerce

Yes, AI agents can trigger cart additions if you expose the appropriate endpoints as tools. The agent must send a valid POST request to the /wc/v3/cart or specific product endpoints with the correct item data. This requires the MCP server to handle the session context or use consumer keys with write permissions. You should restrict this capability to trusted AI models to prevent unintended purchases or cart manipulation by malicious prompts.

Which plugin exposes WooCommerce API to AI

No single plugin does this natively. You need a custom MCP server implementation or a specific community-built bridge. Most developers use a standalone Node.js or Python script that implements the Model Context Protocol. This script communicates with the standard WooCommerce REST API. You do not install a WordPress plugin for the MCP layer itself; you install the MCP server on your hosting environment and point it at your WordPress URL.

How to define tools for WooCommerce in MCP

Define tools by creating JSON objects in your MCP server code that describe the function, input schema, and description. Each tool maps to a specific WooCommerce REST endpoint, such as get_products or get_stock. The description field is critical because the AI uses it to decide when to call the tool. Keep descriptions precise and include examples of expected inputs so the AI formats the request correctly.

Does WooCommerce have native MCP support

No, WooCommerce does not have native MCP support. The platform provides a robust REST API, but it does not speak the Model Context Protocol language. You must build or install a middleware layer that translates MCP messages into HTTP requests. This bridge handles the authentication, request formatting, and response parsing that the AI client expects. The core WordPress and WooCommerce codebases remain unchanged during this setup.

How to secure WooCommerce actions for AI access

Secure actions by using consumer keys with the minimum necessary permissions. Create a dedicated API key for the AI agent that only has read access if you only need data retrieval. If the agent must write data, such as updating stock, grant write permissions but restrict the key to specific endpoints if possible. Never use your administrator account credentials for the MCP server. Rotate these keys regularly and monitor the WooCommerce logs for unusual request patterns.

What to do next

The most useful next step is to validate your exposed tools against a real user intent, not just a technical handshake. Open your MCP client and ask the AI agent to perform a specific, low-risk action, such as “Check the current stock level for product SKU-12345.” If the agent returns the correct data without error, your bridge is functioning. If it fails, check the server logs immediately; the error message will point to either a missing permission in WooCommerce or a malformed tool definition in your MCP server configuration. Do not move on to write actions like adding to cart until you have successfully executed at least three different read-only queries. This confirms that your API credentials are valid and that the JSON-RPC messages are being parsed correctly by the client. Once you have this baseline, you can safely test state-changing operations in a staging environment.

Discussion

Be the first to comment

Leave a comment

Get in touch