woocommerce-mcp-connector

Brijes987/woocommerce-mcp-connector Checked 2 days ago

Read-only WooCommerce MCP connector for an agent: GET-only client, masked PII, retries with backoff, circuit breaker, rate limiting, 144 offline tests.

# WooCommerce read-only MCP connector (Agent Studio assignment 3) A small MCP server that lets an Agent Studio agent read orders, products and stock from a WooCommerce store, safely: read-only, PII masked by default, bounded, and honest about what it can't see. A mid-size D2C merchant's support team spends much of its day on two questions: *"where is my order?"* and *"is this in stock?"*. Both are lookups, not judgement calls. An agent that can read orders and inventory can answer them, if it can't leak customer data, hammer the store, or confidently say something wrong.

Summary extracted from the README.

# WooCommerce read-only MCP connector (Agent Studio assignment 3)

A small MCP server that lets an Agent Studio agent read orders, products and stock from a WooCommerce store, safely: read-only, PII masked by default, bounded, and honest about what it can't see.

Never commit .env. It is git-ignored; .env.example holds placeholders only. Use a WooCommerce API key created with Read permission.

The merchant problem

A mid-size D2C merchant's support team spends much of its day on two questions: "where is my order?" and "is this in stock?". Both are lookups, not judgement calls. An agent that can read orders and inventory can answer them, if it can't leak customer data, hammer the store, or confidently say something wrong.

Metrics (what "moved the metric" means here):

Metric Definition
Deflection rate WISMO / stock tickets resolved with no human touch ÷ all such tickets
Time to first response Ticket created → first useful answer
Escalation rate due to wrong/missing data Handoffs where the agent lacked or misreported data (tracking missing, stale stock, order not found) ÷ agent-handled tickets

Measurement plan (this repo does not claim results; no pilot has been run):

  1. Baseline (2-4 weeks): tag tickets as WISMO / stock; record volume, time to first response, handle time, CSAT and reopen rate. Note how often tracking info is simply absent from orders.
  2. Pilot (2-4 weeks): route a slice of WISMO/stock tickets (one channel or a random 25-50%) to the agent; the rest stay on humans as a concurrent control. Review every escalation reason.
  3. Compare: deflection, time to first response and escalation rate vs control, with CSAT and reopen rate as guardrails (deflection that raises reopen rate is not a win). Stop or fix if wrong-data escalations are high; the top causes will be missing tracking and stale stock.

Tools

Tool Purpose
list_orders Newest first, one page per call (per_page ≤ 50), has_more for paging
get_order One order; optional email must match the billing email or the result is NOT_FOUND
search_orders By email (exact), order number, status, dates or text; examines ≤ 2 pages / 100 orders, flags truncated
list_products One page per call
get_product Plain-text description (HTML stripped, ≤ 500 chars); cached 60 s
check_inventory By sku or product_id; cached 30 s; as_of shows freshness

Full schemas, error codes and real example responses: docs/mcp-tools.json (generated from the registered tools and checked by a contract test). What the agent can and cannot do: CAPABILITIES.md.

Architecture

Architecture

Source: Same flow as the Mermaid version below.

flowchart LR
  A[Agent Studio agent] -- MCP over stdio --> S[FastMCP server]
  S --> R[run_tool: audit log + error mapping]
  R --> T[Tool: validate -> cache -> fetch -> allowlist -> mask]
  T --> C["WooCommerceClient.request() GET-only"]
  C --> B[circuit breaker] --> L[token bucket] --> W[(WooCommerce REST v3)]
  R -. JSON lines .-> E[stderr audit log]

Raw WooCommerce payloads are never passed through: masking.py builds a new dict from an allowlist and then masks it, so a tool cannot skip masking. Everything outbound goes through one request() method that enforces GET-only, the circuit breaker, the rate limiter, retries and one time budget per tool call.

Quick start: no Docker, no store (mock mode)

Requires Python 3.11+.

python -m venv .venv
source .venv/bin/activate            # Windows PowerShell: .venv\Scripts\Activate.ps1
pip install -e ".[dev]"

python -m pytest -q                              # offline unit/resilience/contract tests
python -m scripts.live_smoke_test --mock         # drives the REAL server over MCP stdio
python -m scripts.demo_where_is_my_order         # the "where is my order?" flow, printed

(make test, make smoke-mock, make run-mock, make lint, make spec are shortcuts if you have GNU make.)

To run the server by hand against the fake store:

# terminal 1: fake WooCommerce on :8080 (FAKE data)
python -m uvicorn scripts.mock_woocommerce:app --port 8080

# terminal 2 (bash)
export WC_BASE_URL=http://localhost:8080 WC_CONSUMER_KEY=ck_mockkey000000000000 WC_CONSUMER_SECRET=cs_mocksecret0000000000
python -m server.main

PowerShell: $env:WC_BASE_URL="http://localhost:8080"; $env:WC_CONSUMER_KEY="ck_mockkey000000000000"; $env:WC_CONSUMER_SECRET="cs_mocksecret0000000000". (Those two keys are fake values that only the mock accepts.)

Resilience demo: curl "http://localhost:8080/__mock/fault?mode=429&count=3" makes the next 3 API calls return 429 with Retry-After: 1; the connector retries transparently. mode=500 and mode=none also work.

Live mode against a real or Docker store

docker compose -f docker/docker-compose.yml up -d
bash scripts/setup_woocommerce.sh     # installs WooCommerce, seeds fake data, prints a READ key
python -m scripts.live_smoke_test     # uses WC_* from .env

Status: not verified. The Docker/WP-CLI setup was written from the documented interfaces but was not executed when this repo was produced; the mock-mode path is the verified one. Manual fallback: run WordPress + WooCommerce any way you like, enable Settings → Permalinks → Post name (otherwise /wp-json returns 404), then WooCommerce → Settings → Advanced → REST API → Add key with Read permission, and put the key/secret in .env.

Connecting an MCP client (stdio)

{
  "mcpServers": {
    "woocommerce": {
      "command": "python",
      "args": ["-m", "server.main"],
      "cwd": "/path/to/woocommerce-mcp-connector",
      "env": {
        "WC_BASE_URL": "https://your-store.example.com",
        "WC_CONSUMER_KEY": "ck_replace_me",
        "WC_CONSUMER_SECRET": "cs_replace_me"
      }
    }
  }
}

Startup runs one authenticated read (GET /products?per_page=1). Bad credentials, an unreachable store or plain http:// to a non-localhost host exit non-zero with a message on stderr (stdout is reserved for the MCP protocol).

Configuration

Variable Default Meaning
WC_BASE_URL required Store URL. https only; http only for localhost, 127.0.0.1, ::1
WC_CONSUMER_KEY / WC_CONSUMER_SECRET required WooCommerce REST API key pair (Read)
REVEAL_PII false true unmasks name/email/phone/street address (warning logged at startup)
REQUIRE_EMAIL_FOR_ORDER_LOOKUP false true makes get_order require the billing email
RATE_LIMIT_PER_SEC 5 Client-side token bucket
REQUEST_TIMEOUT_SEC 10 Per-request timeout (also capped by the time left in the budget)
TOTAL_TIME_BUDGET_SEC 30 Per tool call: limiter waits + retry sleeps + requests
MAX_RETRIES 3 For 429, 5xx, timeouts and network errors
PRODUCT_CACHE_TTL_SEC / INVENTORY_CACHE_TTL_SEC 60 / 30 Cache TTLs
CACHE_MAX_ENTRIES 500 Per cache
WC_TRACKING_META_KEYS _tracking_number,_wc_shipment_tracking_items Exact order-meta keys exposed as tracking
LOG_LEVEL INFO Audit/diagnostic logs, JSON lines on stderr

How it behaves

  • Auth: API key pair. HTTPS → HTTP Basic. Local HTTP → query-string credentials (the only way WooCommerce accepts keys without TLS). TLS verification is never disabled; redirects are not followed.
  • Retries: 429 / 5xx / timeout / network error, max 3 retries, exponential backoff with jitter (cap 10 s). Retry-After (integer seconds) is honoured; if it is longer than the time left, the call fails immediately with RATE_LIMITED. After retries are exhausted the error is retryable: false with "hand over to a human" guidance.
  • Circuit breaker: opens after 5 consecutive tool-level failures (5xx, timeout, network; not 4xx), stays open 30 s, then lets exactly one probe through. A 4xx counts as "upstream is alive".
  • Errors: VALIDATION_ERROR, NOT_FOUND, AUTH_ERROR, RATE_LIMITED, TIMEOUT, SERVER_ERROR, UPSTREAM_UNAVAILABLE, each with message, retryable, guidance. Messages never contain URLs, exception text or credentials.
  • Audit log: one JSON line per tool call on stderr: tool, timestamp, latency, status, and an allowlist of parameters. Emails, queries, SKUs and order numbers are logged only as *_provided: true.

Tests

python -m pytest -q runs 144 tests offline in about 10 s: no network beyond localhost, no real sleeping (fake clock/sleep injected). They cover auth, GET-only enforcement, URL rules, every tool, pagination, masking on/off, allowlisting, validation, 404 / 429+Retry-After / 500-then-success / timeout / exhausted retries / malformed JSON / empty results, circuit-breaker transitions, rate-limiter behaviour, cache TTL / bounds / no-error-caching, a credential-leak test (secrets absent from results, logs and error text, in the worst case of localhost query-string auth), a contract test (docs match code), and real-subprocess tests proving stdout contains only MCP protocol messages.

Assumptions and known limitations

  • WooCommerce REST API v3. search behaviour differs between WooCommerce versions and HPOS vs legacy storage; the exact-email check is client-side, so an order the store's own search doesn't surface can't be found.
  • order_number equals the order ID unless the store uses a sequential-number plugin; the tool matches both.
  • WooCommerce has no native tracking field. Tracking appears only if a plugin stores it in order meta under a key listed in WC_TRACKING_META_KEYS. Don't promise customers tracking the store doesn't have.
  • The API doesn't expose an API key's permission level, so "use a Read key" can't be verified; this connector only ever sends GET, regardless.
  • Variation SKUs are not found by check_inventory (variations aren't returned by /products).
  • Caches, rate limiter and breaker are in-memory and per process (one store, one tenant).
  • Verified here: Linux, Python 3.12, the mock store. Not verified: a real WooCommerce store, the Docker setup script, Windows.

Provenance

Spec drafted in Kiro; implementation and tests written with Claude (Anthropic); reviewed and tested by Brijesh Kumar Joshi.