drupal-mods/commerce-agent-detector

Detects AI procurement/shopping agents and switches the commerce experience to machine-optimized mode.

Maintainers

Package info

gitlab.com/drupal-mods/commerce-agent-detector

Issues

Type:drupal-module

pkg:composer/drupal-mods/commerce-agent-detector

Statistics

Installs: 17

Dependents: 1

Suggesters: 0

Stars: 1

1.0.0-beta4 2026-04-02 10:00 UTC

README

pipeline status PHPCS PHPStan PHPUnit

A Drupal module that automatically detects AI procurement/shopping agents and serves machine-optimized JSON commerce endpoints — while keeping the human experience 100% unchanged.

Features

Core

  • Automatic agent detection — identifies ChatGPT, Claude, Gemini, Perplexity, Copilot, and custom agents via tokens, headers, user-agent strings, and optional heuristics
  • JSON commerce API — search, product detail, cart, and checkout endpoints with Schema.org structured data
  • Token management — SHA-256 hashed, customer-bound API tokens with scopes, expiration, and usage tracking
  • Customer self-service — "Connected Agents" tab on user profiles for generating and revoking personal tokens
  • Order ownership — orders placed via managed tokens are automatically assigned to the customer's account
  • Rate limiting — configurable per-window limits via Drupal flood control
  • Audit logging — every agent interaction logged with dashboard analytics
  • Extensible — event-driven architecture for custom agent personas
  • Zero impact on humans — normal site routing is completely unaffected

API Features

  • Order tracking — order history and detail endpoints for agents to check status, items, and totals on behalf of customers
  • Webhook subscriptions — agents can subscribe to store events (order placed, shipped, refunded, etc.) with HMAC-signed payloads and secret rotation
  • Bulk cart operations — add, update, remove, or replace multiple cart items in a single request
  • Shipping estimates — get shipping rates and available methods for a given address and order before checkout
  • MCP server — Model Context Protocol endpoint for LLM tool-use integration (browsing, search, cart, checkout as MCP tools)
  • Product comparison — compare multiple products side-by-side with attribute diffs, price comparison, and recommendations
  • Budget-aware search — search products within a budget constraint with price-range facets and smart allocation
  • Reorder — one-call reorder from a previous order, automatically recreating the cart with the same items
  • Natural language query — POST natural language questions ("find me a red laptop under $1000") and get structured product results
  • Inventory checks — real-time stock availability for single items or bulk variation lookups
  • Agent sessions — persistent session context (preferences, conversation history) across multiple agent requests
  • Returns & refunds — check return eligibility, create RMA requests, and track return status via API
  • .well-known/agent-commerce.json — standardized discovery endpoint for agents to auto-detect store capabilities, endpoints, and protocols

Discovery & Interoperability

  • Agent discovery — OpenAPI 3.1 spec, JSON product sitemap, and enhanced llms.txt for automatic API and catalog discovery
  • ACP/UCP protocol support — compatible with OpenAI/Stripe Agentic Commerce Protocol and Google Universal Commerce Protocol
  • A2A protocol — Google Agent-to-Agent protocol support with /.well-known/agent.json agent card and JSON-RPC handler

Architecture

Incoming Request
      │
      ▼
AgentDetectionSubscriber (priority 200)
      │
      ├─ 1. Managed tokens (cad_..., SHA-256, customer-bound)
      ├─ 2. Legacy tokens (config whitelist)
      ├─ 3. Agent headers (X-Agent-ID, X-ACP-Version, etc.)
      ├─ 4. User-Agent patterns (ChatGPT, ClaudeBot, etc.)
      └─ 5. Heuristics (opt-in behavioral scoring)
      │
      ├── Agent detected → AgentDetectedEvent → Agent API endpoints
      └── Not an agent  → Normal Drupal routing (unchanged)

Requirements

DependencyVersion
Drupal10.3+ or 11
PHP8.2+
Drupal Commerce2.38+ or 3.x
JSON:API modulecore (auto-enabled)
REST modulecore (auto-enabled)

Optional: Search API, Commerce API, JSON:API Extras

Installation

Via Composer (Packagist)

composer require drupal-mods/commerce-agent-detector
drush en commerce_agent_detector -y
drush cr

From GitLab (alternative)

composer config repositories.commerce_agent_detector vcs https://gitlab.com/drupal-mods/commerce-agent-detector
composer require drupal-mods/commerce-agent-detector:dev-main
drush en commerce_agent_detector -y
drush cr

The commerce_agent_log and commerce_agent_token database tables are created automatically. Drupal Commerce and its dependencies (Address, Entity, Profile, etc.) will be pulled in by Composer if not already installed.

Quick Start

  1. Enable the module (detection is on by default)
  2. Go to Commerce → Configuration → Agent Detector to review settings
  3. Create managed tokens at Agent Detector → Tokens for enterprise agents
  4. Grant customers the manage own agent tokens permission for self-service
  5. Agents access your store via /api/commerce/agent/* endpoints

Documentation

GuideDescription
Token ManagementManaged tokens, customer binding, admin/customer UI, migration from legacy tokens
API ReferenceAll endpoints, parameters, request/response examples, error codes
DetectionHow detection works, priority order, AgentResult, AgentDetectedEvent
ConfigurationAll settings explained, permissions, admin tabs
SecurityRate limiting, token auth, audit logging, input validation, fallbacks
ExtendingCustom agent personas, programmatic API, adding agent-only routes
TestingPHPUnit test suite, simulation script, cURL examples

API Endpoints

Search & Products

MethodPathDescription
GET/api/commerce/agent/searchSearch products
GET/api/commerce/agent/product/{id}View product detail
GET,POST/api/commerce/agent/products/compareCompare multiple products
POST/api/commerce/agent/budget/searchBudget-constrained search
GET/api/commerce/agent/budget/price-rangesGet price range facets
POST/api/commerce/agent/queryNatural language product query

Cart & Checkout

MethodPathDescription
GET/api/commerce/agent/cartView cart
POST/api/commerce/agent/cart/addAdd item to cart
POST/api/commerce/agent/cart/bulk-addAdd multiple items
PATCH/api/commerce/agent/cart/bulk-updateUpdate multiple items
POST/api/commerce/agent/cart/bulk-removeRemove multiple items
POST/api/commerce/agent/cart/replaceReplace entire cart
POST/api/commerce/agent/checkoutComplete checkout
POST/api/commerce/agent/reorderReorder from previous order

Orders & Returns

MethodPathDescription
GET/api/commerce/agent/ordersOrder history
GET/api/commerce/agent/order/{id}Order detail
GET/api/commerce/agent/return/eligibility/{order_id}Check return eligibility
POST/api/commerce/agent/returnCreate return/RMA
GET/api/commerce/agent/return/{return_id}Get return status

Shipping & Inventory

MethodPathDescription
GET,POST/api/commerce/agent/shipping/estimateGet shipping rates
GET/api/commerce/agent/shipping/methodsList shipping methods
GET/api/commerce/agent/inventory/{variation_id}Check stock
POST/api/commerce/agent/inventory/bulkBulk stock check

Webhooks

MethodPathDescription
GET/api/commerce/agent/webhooksList subscriptions
POST/api/commerce/agent/webhooksSubscribe to events
PATCH/api/commerce/agent/webhooks/{id}Update subscription
DELETE/api/commerce/agent/webhooks/{id}Unsubscribe
POST/api/commerce/agent/webhooks/{id}/rotate-secretRotate webhook secret
GET/api/commerce/agent/webhooks/eventsList available event types

Sessions

MethodPathDescription
POST/api/commerce/agent/sessionCreate session
GET/api/commerce/agent/session/{id}Get session
PATCH/api/commerce/agent/session/{id}Update session
DELETE/api/commerce/agent/session/{id}Delete session
GET/api/commerce/agent/sessionsList sessions

Discovery & Protocols

MethodPathDescription
GET/api/commerce/agent/openapi.jsonOpenAPI 3.1 specification
GET/api/commerce/agent/sitemap.jsonJSON product sitemap
GET/llms.txtMachine-readable store description
GET/.well-known/agent-commerce.jsonAgent commerce discovery
GET/.well-known/agent.jsonA2A agent card
POST/api/commerce/agent/a2aA2A JSON-RPC handler
POST/api/commerce/agent/mcpMCP tool-use endpoint

See API Reference for full details.

Agent Dashboard

View traffic analytics at Commerce → Agent Dashboard: requests, unique agents, orders, revenue, conversion rate, and per-agent breakdown. Requires the view commerce agent dashboard permission.

How It Works (for Site Owners)

This module watches every request to your Drupal Commerce site. When it detects an AI agent, it serves clean JSON data instead of HTML pages. Human visitors see no change whatsoever — your themes, checkout flow, CAPTCHA, and every other module work exactly as before.

Agents get structured product data, direct cart/checkout APIs, and machine-readable error responses. Orders placed by agents with managed tokens are automatically assigned to the customer's account and appear in their normal order history.

Rate limiting, audit logging, and token authentication ensure your store stays secure. If anything fails, agents get a structured error with a fallback URL to the human version.

License

GPL-2.0-or-later