# Architecture
## Overview
The Shopify Agentic MCP Gateway is a tri-protocol commerce gateway that enables autonomous AI agents to perform end-to-end shopping transactions on Shopify stores. It implements three complementary protocols -- UCP, AP2, and MCP -- in a layered architecture designed for security, extensibility, and serverless deployment.
## System Architecture
```
+================================================================+
| AI Agent Layer |
| Claude Desktop | GPT | Custom Agent | Any MCP-compatible LLM |
+================================+===============================+
|
MCP Transport (stdio / HTTP)
|
+================================v===============================+
| MCP Server Layer |
| |
| +------------------+ +-------------------+ +---------------+ |
| | scout_inventory | | negotiate_terms | | track_order | |
| +------------------+ +-------------------+ +---------------+ |
| +------------------+ +-------------------+ |
| | manage_cart | | execute_checkout | |
| +------------------+ +-------------------+ |
| |
+====+===================+==================+===================+
| | |
+====v======+ +========v========+ +====v================+
| UCP Layer | | AP2 Layer | | Middleware Layer |
| | | | | |
| Profile | | MandateSigner | | Guardrail |
| Publisher | | (ES256 JWS) | | - Price validation |
| | | | | - Inventory check |
| Capability| | MandateVerifier | | - Mandate limits |
| Negotiator| | (Chain verify) | | - State transitions |
| | | | | |
| Checkout | | MandateStore | | FeeCollector |
| Session | | (In-mem / | | - Fee calculation |
| Manager | | DynamoDB) | | - Ledger tracking |
| | | | | |
| Discovery | | | | RateLimiter |
| Facade | | | | Auth |
+-----------+ +-----------------+ +----------------------+
|
+====v==================+
| Shopify API Layer |
| |
| StorefrontAPI (GraphQL)|
| - Product search |
| - Cart operations |
| - Checkout creation |
| |
| AdminAPI (REST) |
| - Order retrieval |
| - Fulfillment status |
+------------------------+
```
## Protocol Layers
### UCP (Universal Commerce Protocol)
UCP provides the **discovery and capability** layer. When an agent encounters a merchant, it fetches `/.well-known/ucp` to learn what the merchant supports.
**Responsibilities:**
- **Profile Publishing** (`src/ucp/profile.ts`) -- Generates the `/.well-known/ucp` JSON document advertising the merchant's services, transports, capabilities, payment handlers, and signing keys.
- **Capability Negotiation** (`src/ucp/negotiate.ts`) -- Implements the intersection algorithm that determines which capabilities both the agent and merchant support. Extensions are pruned if their parent capability is absent.
- **Checkout Session Management** (`src/ucp/checkout-session.ts`) -- Manages the three-state checkout machine (`incomplete` -> `requires_escalation` -> `ready_for_complete`), auto-detects status transitions, recalculates totals, and tracks missing fields.
- **Catalog Discovery** (`src/ucp/discovery.ts`) -- Facade for product search and retrieval, delegating to Shopify Storefront API.
**UCP Profile Structure:**
```json
{
"version": "2026-01-11",
"services": [{
"type": "dev.ucp.shopping",
"transports": [
{ "type": "rest", "endpoint": "https://gw.example.com/api/v1" },
{ "type": "mcp", "endpoint": "https://gw.example.com/mcp" },
{ "type": "a2a", "endpoint": "https://gw.example.com/a2a" }
],
"capabilities": [
{ "name": "dev.ucp.shopping.checkout", "version": "2026-01-11" },
{ "name": "dev.ucp.shopping.catalog", "version": "2026-01-11" },
{ "name": "dev.ucp.shopping.order", "version": "2026-01-11" },
{ "name": "dev.ucp.shopping.fulfillment", "version": "2026-01-11" }
],
"payment_handlers": [
{ "id": "shopify_payments", "type": "processor_tokenizer" },
{ "id": "ap2_mandate", "type": "mandate" }
],
"signing_keys": { "jwk": "https://gw.example.com/.well-known/jwks.json" }
}]
}
```
### AP2 (Agent Payment Protocol)
AP2 provides the **authorization and security** layer. It ensures that an AI agent can only spend exactly what the user authorized, through a cryptographic mandate chain.
**Responsibilities:**
- **Mandate Signing** (`src/ap2/signer.ts`) -- Merchant-side ES256 JWS signing of cart mandates. Generates key pairs and signs checkout sessions into compact JWS tokens with `mandate+jwt` type headers.
- **Mandate Verification** (`src/ap2/verifier.ts`) -- Verifies individual mandates (Intent, Cart, Payment) and the full three-mandate chain. Supports both local JWK verification and remote JWKS endpoint resolution.
- **Mandate Storage** (`src/ap2/mandate-store.ts`) -- In-memory mandate persistence with a DynamoDB-ready interface. Maintains a primary store and a secondary index on checkout ID.
**Mandate Chain:**
```
User Agent Gateway Merchant
| | |
|-- Intent Mandate (max $100) -| |
| |-- Cart Mandate (total $79) |
| |<- Signed cart mandate ------|
|-- Payment Mandate ($79) ---->| |
| |-- Verify chain ----------->|
| |<- Order confirmed ---------|
|<- Order confirmation --------| |
```
### MCP (Model Context Protocol)
MCP provides the **agent interface** layer. It exposes five tools that any MCP-compatible AI agent (Claude, GPT, etc.) can call.
**Responsibilities:**
- **Tool Registration** (`src/server.ts`) -- Registers all five tools with the MCP SDK, including Zod schemas for parameter validation.
- **Dual Transport** (`src/index.ts`) -- Supports stdio transport for local development (Claude Desktop) and HTTP transport for Lambda deployment.
## Middleware Layer
### Guardrail (`src/middleware/guardrail.ts`)
The Guardrail is an AI hallucination defense system. It validates that agent-claimed data matches actual Shopify data before any destructive operation proceeds.
**Checks performed:**
| Check | What It Validates |
|-------|-------------------|
| Price Validation | Agent-claimed price matches actual Shopify price within tolerance (default 1%) |
| Inventory Validation | Requested quantity does not exceed available stock |
| Mandate Amount Validation | Checkout total does not exceed the intent mandate's `max_amount` |
| Checkout Transition Validation | State transitions follow the legal state machine graph |
### Fee Collector (`src/middleware/fee-collector.ts`)
Automatic platform fee deduction from checkout transactions. Configurable rate (default 0.5%) with an in-memory ledger that supports date-range queries and currency-filtered totals.
## Data Flow: Complete Purchase
```
1. Agent calls scout_inventory("wireless headphones", price_max: 5000)
|
+-> Shopify Storefront API: product search
+-> Price filter applied client-side
+-> Returns: CatalogProduct[]
2. Agent calls manage_cart(action: "create")
|
+-> Creates in-memory cart entry
+-> Returns: cart_id, empty line_items
3. Agent calls manage_cart(action: "add", cart_id, variant_id, quantity: 1)
|
+-> Adds LineItem to cart store
+-> Recalculates totals
+-> Returns: updated cart with totals
4. Agent calls negotiate_terms(cart_id, agent_profile_url)
|
+-> Fetches agent UCP profile from URL
+-> Generates server UCP profile
+-> Runs capability intersection algorithm
+-> Creates/retrieves checkout session
+-> Returns: NegotiationResult + CheckoutSession
5. Agent calls execute_checkout(checkout_id, intent_mandate, cart_mandate, payment_mandate)
|
+-> Retrieves checkout session
+-> Verifies session is ready_for_complete
+-> Verifies full mandate chain (intent -> cart -> payment)
+-> Guardrail: validates intent max_amount covers total
+-> Stores all 3 mandates
+-> Calculates and collects platform fee
+-> Creates confirmed Order
+-> Returns: Order + checkout_url + FeeRecord
6. Agent calls track_order(order_id)
|
+-> Shopify Admin API: order + fulfillment lookup
+-> Returns: Order status, tracking number, carrier, ETA
```
## Component Map
```
src/
index.ts Entry point (Lambda handler + stdio server)
server.ts MCP tool registrations (5 tools)
types.ts Shared type definitions + config loader
tools/
scout-inventory.ts Product search tool
manage-cart.ts Cart CRUD tool
negotiate-terms.ts Capability negotiation tool
execute-checkout.ts Checkout execution tool (most critical)
track-order.ts Order tracking tool
ucp/
profile.ts UCP profile generation (/.well-known/ucp)
negotiate.ts Capability intersection algorithm
checkout-session.ts Checkout state machine manager
discovery.ts Catalog search facade
shopping-service.ts Line item and totals helpers
ap2/
types.ts AP2-specific type definitions
signer.ts ES256 JWS mandate signer
verifier.ts Mandate chain verifier
mandate-store.ts Mandate persistence (in-memory + DynamoDB-ready)
middleware/
guardrail.ts AI hallucination guard
fee-collector.ts Platform fee calculator and ledger
rate-limiter.ts Request rate limiting
auth.ts Authentication middleware
shopify/
client.ts Shopify API client wrapper
storefront.ts Storefront API (GraphQL) operations
admin.ts Admin API (REST) operations
types.ts Shopify-specific type mappings
utils/
logger.ts Structured logger
errors.ts UCP-compliant error types and factories
crypto.ts Cryptographic utilities
```
## Deployment Targets
| Target | Transport | Storage | Use Case |
|--------|-----------|---------|----------|
| Local (stdio) | MCP stdio | In-memory | Development with Claude Desktop |
| AWS Lambda | HTTP API Gateway | DynamoDB | Production serverless deployment |
| Docker (future) | HTTP / SSE | DynamoDB / PostgreSQL | Self-hosted deployment |
## Security Model
1. **Transport Security** -- HTTPS enforced for all production endpoints. Lambda API Gateway provides TLS termination.
2. **Mandate Signatures** -- ES256 (ECDSA with P-256 curve) JWS compact serialization. Keys rotatable via JWKS endpoint.
3. **Chain Verification** -- Intent, Cart, and Payment mandates form an unbreakable chain: cart total cannot exceed intent max_amount, payment amount must match cart total exactly.
4. **Guardrails** -- Multi-layer validation prevents AI agents from hallucinating prices, inventing inventory, or exceeding spending limits.
5. **Fee Integrity** -- Platform fees are calculated and collected atomically during checkout execution.