How-to Add WebMCP Tools to WooCommerce (Free JavaScript Template)

illustration of shoping cart web page layout and neon digital lines

To add WebMCP tools to WooCommerce simply add client-side JavaScript file that checks for document.modelContext.registerTool and binds three core functions search_products, add_to_cart, and get_cart_summary directly to the native WooCommerce Store API (/wp-json/wc/store/v1/) using active session nonces.

What is WebMCP for WooCommerce?

WebMCP for WooCommerce is a browser-native Model Context Protocol integration that exposes structured e-commerce actions directly to AI agents inside a user’s active browser session. By connecting document.modelContext to the WooCommerce Store API, online stores allow AI assistants to search catalogs, inspect live inventory, and add items to carts without brittle DOM scraping.

How Does the Free WebMCP WooCommerce JavaScript Template Work?

The free JavaScript starter template detects WebMCP browser support on page load and registers three deterministic JSON-schema tools against the WooCommerce Store API. Because all requests execute with credentials: "same-origin", the browser automatically preserves the shopper’s active cart cookies and session state.

  • search_products: Queries /wp-json/wc/store/v1/products by keyword and converts major currency units into minor units (such as cents) for accurate max_price filtering.
  • add_to_cart: Fetches a fresh cryptographic Store API nonce from the cart endpoint before posting product or variation IDs to /wp-json/wc/store/v1/cart/add-item, then triggers wc_fragment_refresh to update theme mini-carts.
  • get_cart_summary: Reads current line items, formatted subtotals, item counts, and the live checkout URL so agents can hand off completed carts to human buyers.

What Are the Technical Requirements to Run WebMCP on WooCommerce?

Your WordPress environment must serve pages over HTTPS and run a modern version of WooCommerce with the public Store API enabled. Visitors also require a WebMCP-compatible browser or AI agent runtime that exposes the document.modelContext API.

  • HTTPS Protocol: Browsers restrict document.modelContext registration to secure origins.
  • WooCommerce Store API: Active by default in WooCommerce 7.2+ at /wp-json/wc/store/v1/ without requiring REST API consumer keys.
  • Currency Configuration: Set minorUnitMultiplier to 100 for two-decimal currencies (USD, AUD, EUR) or 1 for zero-decimal currencies (JPY).

How Do You Install the Free WebMCP Ecommerce Starter Template on WordPress?

You can deploy the template by uploading the Free_WebMCP_Ecommerce_Starter_Template_for_WooCommerce.zip package as a lightweight WordPress plugin or enqueuing the script inside your child theme’s functions.php file.

  1. Download the Free_WebMCP_Ecommerce_Starter_Template_for_WooCommerce.zip starter package or save the JavaScript code as webmcp-woocommerce.js inside your child theme’s /js/ directory.
  2. Adjust the WC_CONFIG object at the top of the file if your store uses a custom checkout slug or a zero-decimal currency.
  3. Enqueue the script on front-end store pages using WordPress’s wp_enqueue_script() hook with defer loading enabled.
  4. Purge your page cache and Cloudflare edge cache so visitors receive the updated JavaScript asset.
  5. Verify tool registration by opening your storefront in a WebMCP-enabled browser and inspecting available tools in the agent console.

Alternative Installation Method

You can instead copy/paste this code and place it in your WordPress WooCommerce Theme (usually in footer.php) before closing of </body>

/**
 * Free WebMCP Ecommerce Starter Template for WooCommerce
 * Uses native WooCommerce Store API (/wp-json/wc/store/v1/)
 * Exposes Product Search, Add to Cart, and Cart Summary tools to AI agents.
 */
document.addEventListener("DOMContentLoaded", () => {
  // 1. Feature-detect WebMCP support (requires HTTPS & WebMCP-enabled browser)
  if (!("modelContext" in document) || typeof document.modelContext.registerTool !== "function") {
    return;
  }

  // Configuration: Customize currency minor unit multiplier (100 for USD/AUD/EUR, 1 for JPY)
  const WC_CONFIG = {
    storeApiBase: "/wp-json/wc/store/v1",
    minorUnitMultiplier: 100,
    checkoutPath: "/checkout/"
  };

  // Helper: Fetch cart & capture the required WooCommerce Store API Nonce
  async function getStoreApiNonce() {
    const res = await fetch(`${WC_CONFIG.storeApiBase}/cart`, {
      credentials: "same-origin"
    });
    const nonce = res.headers.get("Nonce") || res.headers.get("X-WC-Store-API-Nonce");
    const cartData = await res.json();
    return { nonce, cartData };
  }

  // =========================================================================
  // TOOL 1: Search WooCommerce Products
  // =========================================================================
  document.modelContext.registerTool({
    name: "search_products",
    description: "Search the WooCommerce store catalog by keyword or maximum price.",
    inputSchema: {
      type: "object",
      properties: {
        query: {
          type: "string",
          description: "Search keywords (e.g., 'Courses', 'plugins', 'hoodie')."
        },
        maxPrice: {
          type: "number",
          description: "Optional maximum price filter in major currency units (e.g., 50 for $50.00)."
        }
      },
      required: ["query"]
    },
    async execute({ query, maxPrice }) {
      try {
        const url = new URL(`${WC_CONFIG.storeApiBase}/products`, window.location.origin);
        url.searchParams.set("search", query);
        url.searchParams.set("per_page", "10");

        // WooCommerce Store API expects max_price in minor units (cents)
        if (maxPrice && !isNaN(maxPrice)) {
          url.searchParams.set("max_price", Math.round(maxPrice * WC_CONFIG.minorUnitMultiplier));
        }

        const response = await fetch(url, { credentials: "same-origin" });
        if (!response.ok) throw new Error(`HTTP ${response.status}`);
        const products = await response.json();

        return {
          status: "success",
          count: products.length,
          results: products.map(item => {
            const minorUnit = item.prices?.currency_minor_unit ?? 2;
            const rawPrice = Number(item.prices?.price || 0);
            const formattedPrice = (rawPrice / Math.pow(10, minorUnit)).toFixed(minorUnit);

            return {
              id: String(item.id),
              title: item.name,
              price: `${item.prices?.currency_symbol || "$"}${formattedPrice}`,
              inStock: item.is_in_stock,
              type: item.type, // 'simple', 'variable', etc. (variable items require variation ID)
              url: item.permalink
            };
          })
        };
      } catch (error) {
        return { status: "error", message: `WooCommerce search failed: ${error.message}` };
      }
    }
  });

  // =========================================================================
  // TOOL 2: Add Item to WooCommerce Cart
  // =========================================================================
  document.modelContext.registerTool({
    name: "add_to_cart",
    description: "Add a specific product or variation to the WooCommerce shopping cart using its numeric ID.",
    inputSchema: {
      type: "object",
      properties: {
        productId: {
          type: "string",
          description: "The numeric WooCommerce product ID (or variation ID) from search_products."
        },
        quantity: {
          type: "integer",
          description: "Number of units to add (defaults to 1).",
          default: 1
        }
      },
      required: ["productId"]
    },
    async execute({ productId, quantity = 1 }) {
      try {
        // Step 1: Retrieve active Store API Nonce
        const { nonce } = await getStoreApiNonce();
        if (!nonce) throw new Error("Could not retrieve WooCommerce Store API Nonce.");

        // Step 2: Add item via Store API
        const response = await fetch(`${WC_CONFIG.storeApiBase}/cart/add-item`, {
          method: "POST",
          credentials: "same-origin",
          headers: {
            "Content-Type": "application/json",
            "Nonce": nonce
          },
          body: JSON.stringify({
            id: parseInt(productId, 10),
            quantity: parseInt(quantity, 10)
          })
        });

        const updatedCart = await response.json();
        if (!response.ok) {
          throw new Error(updatedCart.message || "Could not add item to WooCommerce cart.");
        }

        // Trigger standard WooCommerce jQuery fragment refresh if jQuery is present
        if (window.jQuery) {
          window.jQuery(document.body).trigger("wc_fragment_refresh");
        }

        const minorUnit = updatedCart.totals?.currency_minor_unit ?? 2;
        const totalFormatted = (Number(updatedCart.totals?.total_price || 0) / Math.pow(10, minorUnit)).toFixed(minorUnit);

        return {
          status: "success",
          message: `Added ${quantity}x item (${productId}) to cart.`,
          cartTotal: `${updatedCart.totals?.currency_symbol || "$"}${totalFormatted}`,
          itemCount: updatedCart.items_count
        };
      } catch (error) {
        return { status: "error", message: error.message };
      }
    }
  });

  // =========================================================================
  // TOOL 3: Get Current WooCommerce Cart Contents
  // =========================================================================
  document.modelContext.registerTool({
    name: "get_cart_summary",
    description: "Retrieve the items, quantities, and subtotal currently in the WooCommerce cart.",
    inputSchema: {
      type: "object",
      properties: {}
    },
    async execute() {
      try {
        const { cartData } = await getStoreApiNonce();
        const minorUnit = cartData.totals?.currency_minor_unit ?? 2;
        const symbol = cartData.totals?.currency_symbol || "$";

        return {
          status: "success",
          itemCount: cartData.items_count,
          items: (cartData.items || []).map(item => ({
            id: String(item.id),
            name: item.name,
            quantity: item.quantity,
            lineTotal: `${symbol}${(Number(item.totals?.line_total || 0) / Math.pow(10, minorUnit)).toFixed(minorUnit)}`
          })),
          subtotal: `${symbol}${(Number(cartData.totals?.total_items || 0) / Math.pow(10, minorUnit)).toFixed(minorUnit)}`,
          checkoutUrl: `${window.location.origin}${WC_CONFIG.checkoutPath}`
        };
      } catch (error) {
        return { status: "error", message: "Unable to retrieve WooCommerce cart details." };
      }
    }
  });
});

How Should You Customize the Template for Variable Products and Custom Stores?

For stores selling variable products with size or color attributes, extend the search_products response or add a dedicated variation lookup tool that returns valid variation IDs. You can also append custom metadata filters to the Store API query string to let AI agents filter by category, tag, or stock status before executing cart actions.

Frequently Asked Questions

Does the WebMCP WooCommerce template require REST API consumer keys?

No. The template uses the public WooCommerce Store API (/wp-json/wc/store/v1/), which operates directly within the shopper’s browser session using cryptographic Store API nonces rather than secret API keys.

Why does the add_to_cart tool fetch a nonce before adding products?

WooCommerce protects state-changing Store API endpoints like /cart/add-item against cross-site request forgery by requiring a valid Nonce header tied to the user’s active session cookie.

Will adding items via WebMCP update my theme's mini-cart automatically?

Yes. When jQuery is loaded on the page, the template triggers wc_fragment_refresh immediately after a successful cart addition so standard WooCommerce mini-cart widgets update without a full page reload.

By Tolga Savas

Tolga Savas is an Australian web developer, technical SEO consultant, and digital content creator. As the founder of RankYa, Tolga brings over 10 years of hands-on expertise in WordPress and Shopify code-level optimization, technical search engine optimization, Agentic AI discovery, and Google Search Console remediation.

Questions? Leave a Comment!

Your email address will not be published. Required fields are marked *