DEV Community

Cover image for Build an AI Shopping Agent in 50 Lines of TypeScript
Peter
Peter

Posted on

Build an AI Shopping Agent in 50 Lines of TypeScript

TL;DR

Two new open protocols - UCP (Google/Shopify) and ACP OpenAI/Stripe) - are turning AI agents into shoppers. Google AI Mode already has 75M+ daily active users making purchase decisions. ChatGPT just launched Instant Checkout for 800M+ weekly users. But there's no developer toolkit for building on these protocols.

Agorio is an open-source TypeScript SDK that gives you a UCP client, 12 shopping tools, a plan-act-observe agent loop, and a mock merchant test server. In this tutorial, you'll build a working shopping agent - discovery through checkout - in under 50 lines of code.


Why This Matters Right Now

This isn't a "someday" opportunity. The infrastructure is live and scaling fast:

The Protocols

UCP (Universal Commerce Protocol) was announced by Google at NRF on January 11, 2026. Co-developed with Shopify, and endorsed by 25+ companies including Walmart, Target, Etsy, Wayfair, Best Buy, Macy's, The Home Depot, Visa, Mastercard, Stripe, PayPal, and American Express. It works by having merchants publish a JSON manifest at /.well-known/ucp that tells AI agents what the store supports - think robots.txt for commerce. Agents can then discover capabilities, browse products, manage carts, and complete checkout through standardized REST, MCP, or A2A transports.

ACP (Agentic Commerce Protocol) is an open standard (Apache 2.0) by OpenAI and Stripe. It powers ChatGPT's Instant Checkout, launched February 16, 2026. ACP uses a delegated payment model - users store payment methods with Stripe, AI agents act as operators, and merchants receive tokenized credentials. Five REST endpoints handle the entire checkout lifecycle. Etsy is live today, and over 1 million Shopify merchants (including Glossier, SKIMS, Spanx) are coming online.

The Numbers

Metric Source
$190B–$385B in US e-commerce spending by AI agents by 2030 Morgan Stanley, Dec 2025
$3T–$5T global agentic commerce opportunity by 2030 McKinsey, Oct 2025
75M+ daily active users on Google AI Mode Google, Feb 2026
800M+ weekly active ChatGPT users OpenAI, Feb 2026
9x higher conversion from AI search vs. social media Salesforce Holiday 2025
59% higher sales growth for brands using shopper agents Salesforce, 2025
45% of consumers already use AI in their buying journey IBM IBV, Jan 2026

The Merchant Infrastructure

This is the part that makes it real. The supply side is already enormous:

  • 4.8M Shopify merchants are discoverable via Shopify Catalog MCP - any AI agent can search billions of products across the entire Shopify network
  • 1M+ Shopify merchants are being onboarded to ChatGPT Instant Checkout via ACP
  • 1.5M Stripe merchants can enable ACP with minimal integration
  • 35M PayPal merchants coming online via Agent Ready

And the payment rails are locking in:

The Developer Gap

Here's the problem: there's no commerce-specific developer toolkit.

Generic agent frameworks like LangChain, CrewAI, and Mastra give you agent loops and tool calling - but nothing for UCP discovery, checkout state machines, or merchant testing. Google's ADK and OpenAI's Agents SDK handle orchestration but know nothing about commerce protocols.

The only commerce-specific SDK is Lucid Agents by Daydream ($50M seed, Forerunner/Index) - but it's focused on crypto payment rails (x402, ERC-8004), not UCP/ACP.

Agorio fills the gap: a TypeScript SDK built specifically for UCP and ACP, with commerce-native tools, a protocol client, and a mock merchant for testing.


What We're Building

By the end of this tutorial, you'll have a working AI agent that:

  1. Discovers a merchant via UCP (/.well-known/ucp)
  2. Parses its capabilities (checkout, orders, fulfillment, discounts)
  3. Searches the product catalog
  4. Adds items to a cart
  5. Completes checkout with shipping and payment
  6. Returns an order confirmation

All orchestrated by an LLM through a plan-act-observe reasoning loop. Under 50 lines of TypeScript.


Prerequisites

That's it. No merchant account, no Stripe keys, no Docker. Agorio ships with a MockMerchant - a full UCP-compliant Express server with product catalog, checkout flow, and order tracking that runs locally.


Step 1: Set Up the Project

mkdir my-shopping-agent && cd my-shopping-agent
npm init -y
npm install @agorio/sdk
Enter fullscreen mode Exit fullscreen mode

Create an agent.ts file:

Step 2: Write the Agent (47 Lines)

// agent.ts
import { ShoppingAgent, GeminiAdapter, MockMerchant } from '@agorio/sdk';

// Start a UCP-compliant mock merchant for testing.
// This serves a /.well-known/ucp profile, product catalog,
// checkout flow, and order tracking — all locally.
const merchant = new MockMerchant({ name: 'TechShop' });
await merchant.start();
console.log(`Mock merchant running at ${merchant.domain}`);

// Create an agent powered by Gemini.
// The LlmAdapter interface is provider-agnostic —
// swap GeminiAdapter for ClaudeAdapter or OpenAIAdapter
// when they ship in v0.2.
const agent = new ShoppingAgent({
  llm: new GeminiAdapter({
    apiKey: process.env.GEMINI_API_KEY!,
    model: 'gemini-2.0-flash',
  }),
  verbose: true,    // Logs every think → tool_call → result step
  maxIterations: 20,
  onStep: (step) => {
    if (step.type === 'tool_call') {
      console.log(`  → ${step.toolName}(${JSON.stringify(step.args).slice(0, 80)})`);
    }
  },
});

// Give the agent a natural language shopping task.
const result = await agent.run(
  `Go to ${merchant.domain} and buy me wireless headphones.
   Ship to: Jane Doe, 123 Main St, San Francisco, CA 94102, US`
);

// Inspect the result.
if (result.success) {
  console.log('\n✅ Purchase complete!');
  console.log(`Answer: ${result.answer}`);
  console.log(`Order ID: ${result.checkout?.orderId}`);
  console.log(`Total: $${result.checkout?.total?.amount}`);
  console.log(`Steps: ${result.iterations} iterations, ${result.steps.length} steps`);
} else {
  console.log('\n❌ Agent failed:', result.answer);
}

await merchant.stop();
Enter fullscreen mode Exit fullscreen mode

Step 3: Run It

GEMINI_API_KEY=your_key npx tsx agent.ts
Enter fullscreen mode Exit fullscreen mode

You'll see the agent reason through each step in real time:

Mock merchant running at http://localhost:3456
  → discover_merchant({"domain":"localhost:3456"})
  → search_products({"query":"wireless headphones"})
  → get_product({"productId":"prod_003"})
  → add_to_cart({"productId":"prod_003","quantity":1})
  → initiate_checkout({})
  → submit_shipping({"name":"Jane Doe","address":"123 Main St"...})
  → submit_payment({"method":"card"})

✅ Purchase complete!
Answer: I found ProSound Wireless Headphones for $79.99 and completed your order.
Order ID: ord_1708300000_abc123
Total: $79.99
Steps: 8 iterations, 15 steps
Enter fullscreen mode Exit fullscreen mode

That's a full purchase flow - discovery, search, cart, checkout, payment - driven entirely by an LLM.


What Just Happened: UCP Discovery + Agent Loop

Let's break down what the agent actually did, because each step maps to a real protocol operation.

Step 1: UCP Discovery

When the agent calls discover_merchant, Agorio's UcpClient fetches /.well-known/ucp from the merchant. This returns a JSON manifest defined by the UCP specification (version 2026-01-11):

{
  "ucp": {
    "version": "2026-01-11",
    "services": {
      "dev.ucp.shopping": {
        "version": "2026-01-11",
        "rest": {
          "schema": "https://shop.example.com/openapi.json",
          "endpoint": "https://shop.example.com/api/ucp"
        }
      }
    },
    "capabilities": [
      { "name": "dev.ucp.shopping.checkout", "version": "2026-01-11" },
      { "name": "dev.ucp.shopping.order", "version": "2026-01-11" },
      { "name": "dev.ucp.shopping.fulfillment", "version": "2026-01-11",
        "extends": "dev.ucp.shopping.checkout" }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

UCP uses reverse-domain naming (dev.ucp.shopping.checkout) for capabilities and supports four transport bindings: REST (OpenAPI 3.x), MCP (for LLM tool integration), A2A (agent-to-agent), and EP (embedded checkout). Agorio's UcpClient normalizes both array and object capability formats, resolves transport endpoints, and handles the capability intersection algorithm that prunes orphaned extensions.

Step 2: The Plan-Act-Observe Loop

The ShoppingAgent runs a reasoning loop:

  1. Plan: The LLM reads the user's request and decides what to do next
  2. Act: It calls one of 12 built-in shopping tools via function calling
  3. Observe: It reads the tool result and updates its plan

The 12 tools cover the full UCP shopping lifecycle:

Tool UCP Operation
discover_merchant Fetch and parse /.well-known/ucp
list_capabilities Enumerate dev.ucp.shopping.* capabilities
browse_products Paginated catalog with category filtering
search_products Keyword search across names and descriptions
get_product Full product details including variants and pricing
add_to_cart Cart management with quantity and variant selection
view_cart Current cart contents and subtotal
remove_from_cart Remove items from cart
initiate_checkout Create checkout session (UCP state: incomplete)
submit_shipping Submit address (transitions to ready_for_complete)
submit_payment Complete payment (transitions to completed)
get_order_status Track order via dev.ucp.shopping.order

The agent decides which tools to call, in what order, based on the task. You don't write the orchestration logic - the LLM does.

How This Relates to ACP

UCP and ACP solve the same problem from different angles. UCP is decentralized - merchants host their own discovery profiles and agents connect directly. ACP is centralized - merchants apply to OpenAI, provide product feeds, and implement 5 REST endpoints that ChatGPT calls during Instant Checkout.

Agorio v0.1 implements UCP. The ACP client is coming in v0.2 - the goal is a single SDK that lets your agent work with both Google AI Mode merchants (UCP) and ChatGPT merchants (ACP).


Go Deeper: Use the UCP Client Directly

If you want lower-level control without the agent loop, UcpClient gives you direct access to UCP discovery and merchant APIs:

import { UcpClient } from '@agorio/sdk';

const client = new UcpClient({ timeoutMs: 10000 });

// Discover a merchant's capabilities
const discovery = await client.discover('shop.example.com');
console.log(discovery.version);        // "2026-01-11"
console.log(discovery.capabilities);   // checkout, orders, fulfillment...
console.log(discovery.services);       // REST, MCP, A2A transports

// Check specific capabilities
client.hasCapability('dev.ucp.shopping.checkout');    // true
client.hasCapability('dev.ucp.shopping.fulfillment'); // true

// Call merchant APIs directly
const products = await client.callApi('/products/search?q=headphones');
const cart = await client.callApi('/cart', {
  method: 'POST',
  body: { items: [{ productId: 'prod_123', quantity: 1 }] },
});
Enter fullscreen mode Exit fullscreen mode

This is useful when you want to build custom agent logic, integrate with your own orchestration framework, or create specialized tools beyond the 12 built-in ones.


Test Against a Realistic Merchant

The MockMerchant is a full UCP-compliant Express server - not a stub. It serves a /.well-known/ucp profile, an OpenAPI schema, a 10-product catalog with search and filtering, a complete checkout flow with session management, and order tracking. It's what we use to run Agorio's 37 tests.

Chaos Testing

Build resilient agents by simulating real-world conditions:

const merchant = new MockMerchant({
  latencyMs: 500,     // Simulate 500ms network latency
  errorRate: 0.1,     // 10% of requests fail with 500
});
Enter fullscreen mode Exit fullscreen mode

This tests whether your agent retries correctly, handles timeouts, and degrades gracefully - critical when you're hitting real merchants where Shopify's Catalog MCP searches across billions of products.


Bring Your Own LLM

Agorio is LLM-agnostic by design. The LlmAdapter interface has two methods:

interface LlmAdapter {
  chat(messages: ChatMessage[], tools?: ToolDefinition[]): Promise<LlmResponse>;
  readonly modelName: string;
}
Enter fullscreen mode Exit fullscreen mode

Any LLM with function calling can implement this. GeminiAdapter ships today with full function calling support. Claude and OpenAI adapters are coming in v0.2. Or build your own - the Gemini adapter source is a clean reference implementation (~100 lines).


The Competitive Landscape

Agorio isn't the only project in this space, but it occupies a unique position:

Project Focus Protocol Support Open Source
Agorio Commerce-specific agent SDK UCP (now), ACP (v0.2) MIT
Lucid Agents Crypto payment rails for agents x402, ERC-8004, A2A Yes
Shopify UCP Proxy UCP translation layer for non-native platforms UCP Yes
LangChain / CrewAI Generic agent frameworks None (commerce-agnostic) Yes
Google ADK / OpenAI Agents SDK Provider-specific orchestration None (commerce-agnostic) Yes
Daydream AI fashion shopping (consumer product) Proprietary No

Generic frameworks give you agent loops. Agorio gives you agent loops plus UCP discovery, checkout state machines, commerce-native tools, and merchant test infrastructure.


What's Next

Agorio v0.1 is the foundation. Here's the roadmap:

The multi-protocol angle in v0.3 is what we're most excited about. No other SDK lets you build agents that work with both Google AI Mode merchants (via UCP) and ChatGPT merchants (via ACP) - reaching the combined 75M+ daily Google AI Mode users and 800M+ weekly ChatGPT users through a single agent.


Get Started

npm install @agorio/sdk
Enter fullscreen mode Exit fullscreen mode

We're building the picks and shovels for the agentic commerce gold rush. The protocols are live, the merchants are onboarding, the payment rails are locking in. Come build with us.


Agorio is open source (MIT) and not affiliated with Google, Shopify, OpenAI, or Stripe. UCP and ACP are open standards maintained by their respective organizations.

Top comments (0)