ACP Commerce Protocol
Build commerce-enabled AI agents with product discovery, cart management, checkout flows, and secure payment processing using the Agentic Commerce Protocol (ACP).
Overview
The Agentic Commerce Protocol (ACP) integration enables AI agents to handle complete e-commerce workflows:
- Product Discovery - Search and browse product catalogs
- Cart Management - Add, update, and remove items
- Checkout Processing - Handle checkout flows and validations
- Payment Processing - Secure payments via delegated providers (Stripe, PayPal)
- Order Management - Track orders and view history
- Inventory Tracking - Real-time availability checks
🛒 14 Commerce Tools Included
Product Tools: search, browse, details, recommendations
Cart Tools: add, update, remove, view
Checkout Tools: initiate, validate, complete
Order Tools: track, history, details
Quick Start
Get started with ACP in just a few lines of code:
import { Agent, ACPClient, createACPTools } from '@lov3kaizen/agentsea-core';
// Initialize ACP client
const acpClient = new ACPClient({
baseUrl: 'https://api.yourcommerce.com/v1',
apiKey: process.env.ACP_API_KEY,
merchantId: process.env.MERCHANT_ID,
});
// Create commerce agent with 14 tools
const shoppingAgent = new Agent({
name: 'shopping-assistant',
model: 'claude-sonnet-4-20250514',
systemPrompt: 'You are a helpful shopping assistant. Help customers find products and complete purchases.',
tools: createACPTools(acpClient),
}, provider, toolRegistry);
// Use the agent
const result = await shoppingAgent.execute(
'I need wireless headphones under $100',
context
);Setup and Configuration
Installation
npm install @lov3kaizen/agentsea-core
# Or with yarn
yarn add @lov3kaizen/agentsea-core
# Or with pnpm
pnpm add @lov3kaizen/agentsea-coreEnvironment Variables
Configure your ACP credentials:
# .env
ACP_API_KEY=your_acp_api_key
MERCHANT_ID=your_merchant_id
ACP_BASE_URL=https://api.yourcommerce.com/v1 # OptionalClient Configuration
import { ACPClient } from '@lov3kaizen/agentsea-core';
const acpClient = new ACPClient({
baseUrl: process.env.ACP_BASE_URL,
apiKey: process.env.ACP_API_KEY,
merchantId: process.env.MERCHANT_ID,
// Optional configuration
timeout: 30000, // Request timeout (ms)
retryAttempts: 3, // Retry failed requests
enableCaching: true, // Cache product data
cacheDuration: 300000, // Cache for 5 minutes
});
// Verify connection
const isConnected = await acpClient.healthCheck();
console.log('ACP connected:', isConnected);Available Tools
Product Discovery Tools
searchProducts(query, filters)Search product catalog with advanced filters (category, price range, brand, ratings).
browseCategories()List all available product categories and subcategories.
getProductDetails(productId)Get detailed information about a specific product including specs, reviews, and availability.
getRecommendations(productId, userId)Get personalized product recommendations based on browsing and purchase history.
Cart Management Tools
addToCart(productId, quantity)Add items to the shopping cart with quantity validation.
updateCartItem(itemId, quantity)Update quantity or remove items from cart.
viewCart()View current cart contents with pricing and availability.
clearCart()Remove all items from the shopping cart.
Checkout Tools
initiateCheckout(cartId)Begin checkout process and validate cart items.
validateAddress(address)Validate shipping address and suggest corrections.
calculateShipping(address, items)Calculate shipping costs and delivery estimates.
completeCheckout(paymentDetails)Complete purchase with secure payment processing.
Order Management Tools
trackOrder(orderId)Get real-time order tracking and delivery status.
getOrderHistory(userId)View complete order history with filtering options.
Complete Shopping Flow Example
Here's a complete example showing a customer journey from product search to checkout:
import {
Agent,
AnthropicProvider,
ACPClient,
createACPTools,
ToolRegistry,
BufferMemory,
} from '@lov3kaizen/agentsea-core';
// Initialize ACP client
const acpClient = new ACPClient({
baseUrl: process.env.ACP_BASE_URL,
apiKey: process.env.ACP_API_KEY,
merchantId: process.env.MERCHANT_ID,
enableCaching: true,
});
// Create commerce agent
const shoppingAgent = new Agent(
{
name: 'shopping-assistant',
model: 'claude-sonnet-4-20250514',
systemPrompt: `You are a helpful shopping assistant.
Your capabilities:
- Search products and provide recommendations
- Help customers find what they need
- Manage shopping carts
- Process checkouts securely
- Track orders and provide updates
Always:
- Be helpful and conversational
- Confirm actions before proceeding
- Provide clear product information
- Explain shipping costs and delivery times`,
tools: createACPTools(acpClient),
},
new AnthropicProvider(process.env.ANTHROPIC_API_KEY),
new ToolRegistry(),
new BufferMemory(50),
);
// Customer conversation flow
const context = {
conversationId: 'customer-123',
userId: 'user-456',
sessionData: {},
history: [],
};
// Step 1: Product search
let result = await shoppingAgent.execute(
'I need wireless headphones under $100 with good battery life',
context
);
console.log('Agent:', result.content);
// Step 2: Product details
result = await shoppingAgent.execute(
'Tell me more about the Sony WH-1000XM4',
context
);
console.log('Agent:', result.content);
// Step 3: Add to cart
result = await shoppingAgent.execute(
'Add those Sony headphones to my cart',
context
);
console.log('Agent:', result.content);
// Step 4: View cart and proceed
result = await shoppingAgent.execute(
'What\'s in my cart? How much is shipping to New York?',
context
);
console.log('Agent:', result.content);
// Step 5: Checkout
result = await shoppingAgent.execute(
'Proceed to checkout with my saved payment method',
context
);
console.log('Agent:', result.content);
// Step 6: Order tracking
result = await shoppingAgent.execute(
'Track my order',
context
);
console.log('Agent:', result.content);Payment Processing
ACP uses delegated payment providers for secure transaction processing:
🔒 Stripe Integration
Industry-standard payment processing with PCI compliance, fraud detection, and support for 135+ currencies.
💳 PayPal Integration
Trusted payment platform with buyer protection, one-click checkout, and global coverage.
🔐 Security Best Practices
- ✓ PCI DSS compliant - no card data touches your servers
- ✓ Tokenized payments - secure payment method storage
- ✓ 3D Secure support - additional fraud protection
- ✓ Webhook verification - validate all payment events
- ✓ HTTPS only - all communications encrypted
Use Cases
🛍️ Voice Shopping Assistant
Combine ACP with Voice capabilities to create hands-free shopping experiences. "Alexa, find me running shoes under $80."
💬 Chat Commerce
Integrate shopping into messaging platforms. Let customers browse and buy without leaving the conversation.
🤖 Personal Shopping Agent
Build AI agents that learn customer preferences and proactively suggest products based on history and behavior.
📱 Multi-Channel Commerce
Deploy the same commerce agent across web, mobile, voice assistants, and messaging platforms.
Advanced Features
Custom Tool Configuration
import { createACPTools } from '@lov3kaizen/agentsea-core';
// Select specific tools
const tools = createACPTools(acpClient, {
includeTools: [
'searchProducts',
'getProductDetails',
'addToCart',
'viewCart',
],
// Or exclude specific tools
excludeTools: ['clearCart'],
});
// Configure tool behavior
const tools = createACPTools(acpClient, {
maxResults: 10, // Limit search results
enableRecommendations: true, // Show related products
autoValidate: true, // Validate addresses automatically
currencyCode: 'USD', // Default currency
});Error Handling
try {
const result = await shoppingAgent.execute(input, context);
console.log(result.content);
} catch (error) {
if (error.code === 'INSUFFICIENT_INVENTORY') {
console.log('Product is out of stock');
} else if (error.code === 'PAYMENT_FAILED') {
console.log('Payment was declined');
} else if (error.code === 'INVALID_ADDRESS') {
console.log('Shipping address is invalid');
} else {
console.error('Unexpected error:', error);
}
}Webhooks and Events
// Listen to commerce events
acpClient.on('order.created', (order) => {
console.log('New order:', order.id);
// Send confirmation email
// Update inventory
// Trigger fulfillment
});
acpClient.on('payment.succeeded', (payment) => {
console.log('Payment received:', payment.amount);
});
acpClient.on('order.shipped', (order) => {
console.log('Order shipped:', order.trackingNumber);
// Send tracking notification
});NestJS Integration
Use ACP commerce in your NestJS applications:
import { Module } from '@nestjs/common';
import { AgenticModule } from '@lov3kaizen/agentsea-nestjs';
@Module({
imports: [
AgenticModule.forRoot({
provider: 'anthropic',
apiKey: process.env.ANTHROPIC_API_KEY,
acp: {
baseUrl: process.env.ACP_BASE_URL,
apiKey: process.env.ACP_API_KEY,
merchantId: process.env.MERCHANT_ID,
},
}),
],
})
export class AppModule {}
// Use in a service
import { Injectable } from '@nestjs/common';
import { AgentService } from '@lov3kaizen/agentsea-nestjs';
@Injectable()
export class ShoppingService {
constructor(private agentService: AgentService) {}
async processCustomerRequest(input: string, userId: string) {
const agent = this.agentService.getAgent('shopping-assistant');
return agent.execute(input, { userId });
}
}Best Practices
🎯 Clear System Prompts
Define agent behavior clearly. Specify when to recommend products, how to handle price ranges, and when to ask for clarification.
💰 Price Transparency
Always show total costs including shipping and taxes. Confirm prices before checkout to avoid surprises.
🔒 Secure Payments
Never store payment details directly. Use tokenized payment methods and let delegated providers handle sensitive data.
📱 Mobile-First
Optimize for mobile shopping. Keep interactions concise and make checkout flows seamless on small screens.
⚠️ Inventory Checks
Validate inventory before adding to cart. Show availability status and estimated delivery times upfront.
Performance Optimization
const acpClient = new ACPClient({
baseUrl: process.env.ACP_BASE_URL,
apiKey: process.env.ACP_API_KEY,
merchantId: process.env.MERCHANT_ID,
// Performance optimization
enableCaching: true, // Cache product data
cacheDuration: 300000, // 5 minutes
connectionPoolSize: 10, // HTTP connection pool
timeout: 30000, // 30 second timeout
retryAttempts: 3, // Retry failed requests
// Rate limiting
rateLimitPerSecond: 100, // Max 100 requests/sec
rateLimitBurst: 10, // Allow bursts of 10
});Troubleshooting
Connection Errors
If you see "Failed to connect to ACP API":
- ✓ Verify ACP_BASE_URL is correct
- ✓ Check API key is valid
- ✓ Ensure network allows outbound HTTPS
- ✓ Run healthCheck() to test connection
Payment Failures
Common payment issues and solutions:
- ✓ Verify payment provider credentials
- ✓ Check webhook endpoints are accessible
- ✓ Ensure 3D Secure is properly configured
- ✓ Review error logs for specific decline codes
Tool Execution Issues
If tools aren't being called correctly:
- ✓ Check system prompt includes commerce instructions
- ✓ Verify tools are properly registered
- ✓ Enable debug logging to see tool calls
- ✓ Ensure model supports function calling
Next Steps
- Learn about Agent Configuration - Customize your commerce agents
- Add Voice Capabilities - Build voice shopping experiences
- NestJS Integration - Use ACP in NestJS apps
- View Examples - Complete commerce examples
- MCP Protocol - Combine with MCP tools
💡 Pro Tip
Start with a simple product search agent, then gradually add cart management and checkout capabilities. Test thoroughly in sandbox mode before going to production. Combine with Voice features for truly unique shopping experiences.