AP2 Protocol (Agent Payments Protocol) implementation with microservices architecture. Built with FastAPI, Docker Compose, Next.js, LangGraph, MCP, Meilisearch, Redis, WebAuthn, A2UI, and OpenTelemetry.
AP2_demo_app is an early-stage Python project in the AI payments / x402 ecosystem, focused on a2ui, ap2, langgraph, mcp. It currently has 1 GitHub stars and 1 forks, and sits alongside related tools like agentanycast, agentic-commerce-skills-plugins, sardis, .github, nexus, trust-gated-agent-example.
AP2 Protocol (Agent Payments Protocol) implementation with microservices architecture. Built with FastAPI, Docker Compose, Next.js, LangGraph, MCP, Meilisearch, Redis, WebAuthn, and OpenTelemetry.

This application is a implementation of the AP2 (Agent Payments Protocol) specification using a microservices architecture. It features 15 services (7 Backend + 2 MCP + 1 Frontend + 1 Redis + 1 Meilisearch + 1 Jaeger + 1 Payment Network + 1 Init Services) that work together to provide:
graph TB
subgraph "Frontend (Next.js)"
UI[Chat UI<br/>Merchant Dashboard<br/>Port 3000]
end
subgraph "Backend Services"
SA[Shopping Agent<br/>Port 8000<br/>LangGraph Integration]
SA_MCP[Shopping Agent MCP<br/>Port 8010<br/>6 MCP Tools]
MA[Merchant Agent<br/>Port 8001<br/>LangGraph Integration]
MA_MCP[Merchant Agent MCP<br/>Port 8011<br/>3 MCP Tools]
M[Merchant<br/>Port 8002<br/>CartMandate Signing]
CP[Credential Provider<br/>Port 8003<br/>WebAuthn Verification]
CP2[Credential Provider 2<br/>Port 8006<br/>Multi-CP Support]
PP[Payment Processor<br/>Port 8004<br/>Payment Processing]
PN[Payment Network<br/>Port 8005<br/>Agent Token Issuance]
end
subgraph "Infrastructure Services"
REDIS[(Redis<br/>Port 6379<br/>KV Store & Sessions)]
MEILI[(Meilisearch<br/>Port 7700<br/>Full-text Search)]
JAEGER[Jaeger<br/>Port 16686<br/>Distributed Tracing]
end
subgraph "External Services"
DMR[DMR/OpenAI<br/>LLM Endpoint]
LF[Langfuse<br/>LLM Observability]
end
subgraph "Data Layer"
DB[(SQLite Databases<br/>Per-Service Storage)]
Keys[Encrypted Keys<br/>Ed25519 + ECDSA]
end
UI -->|SSE Chat| SA
UI -->|WebAuthn| CP
UI -->|Product CRUD| M
SA -->|LangGraph Tools| SA_MCP
SA_MCP -->|build_intent<br/>request_carts<br/>select_cart<br/>assess_risk<br/>build_payment<br/>execute_payment| SA
MA -->|LangGraph Tools| MA_MCP
MA_MCP -->|search_products<br/>check_inventory<br/>build_cart_mandates| MA
MA_MCP -->|Full-text Search| MEILI
SA -->|A2A Message| MA
MA -->|A2A Message| M
M -->|A2A Message| SA
SA -->|A2A Message| PP
SA -->|A2A Message| CP
CP -->|POST /network/tokenize| PN
PP -->|POST /credentials/verify| CP
PP -->|POST /network/charge| PN
CP -->|Token/Session<br/>TTL: 15min/10min| REDIS
PN -->|Agent Token<br/>TTL: 1hour| REDIS
SA & MA & M & CP & PP -->|Read/Write| DB
SA & MA & M & CP & PP -->|Load Keys| Keys
SA & MA & M & CP & PP -.->|Trace| JAEGER
SA -.->|LLM Query| DMR
MA -.->|LLM Query| DMR
SA -.->|Langfuse Trace| LF
MA -.->|Langfuse Trace| LF
style UI fill:#e1f5ff
style SA fill:#fff4e6
style SA_MCP fill:#e1bee7
style MA fill:#fff4e6
style MA_MCP fill:#e1bee7
style M fill:#fff4e6
style CP fill:#e8f5e9
style CP2 fill:#e8f5e9
style PP fill:#e8f5e9
style PN fill:#b2dfdb
style REDIS fill:#fce4ec
style MEILI fill:#ffccbc
style JAEGER fill:#c8e6c9
| Service | Port | Type | Role | Technology Stack |
|---|---|---|---|---|
| Frontend | 3000 | UI | User Interface | Next.js 15, TypeScript, shadcn/ui |
| Shopping Agent | 8000 | Backend | User's AI Agent | FastAPI, LangGraph, A2A Protocol |
| Shopping Agent MCP | 8010 | MCP | MCP Tool Server (×6) | FastAPI, MCP Server |
| Merchant Agent | 8001 | Backend | Product Search & Cart Creation | FastAPI, LangGraph, A2A Protocol |
| Merchant Agent MCP | 8011 | MCP | MCP Tool Server (×3) | FastAPI, MCP Server, Meilisearch |
| Merchant | 8002 | Backend | Cart Signing & Inventory | FastAPI, CartMandate Signing |
| Credential Provider | 8003 | Backend | WebAuthn & Token Issuance | FastAPI, WebAuthn, Redis |
| Credential Provider 2 | 8006 | Backend | Multi-CP Support | FastAPI, WebAuthn, Redis |
| Payment Processor | 8004 | Backend | Payment Processing | FastAPI, Receipt Generation |
| Payment Network | 8005 | Backend | Agent Token Lifecycle | FastAPI, Token Issuance & Verification |
| Redis | 6379 | Infra | KV Store & Sessions | Redis 7-alpine, TTL Management |
| Meilisearch | 7700 | Infra | Full-text Search Engine | Meilisearch v1.11 |
| Jaeger | 16686 | Infra | Distributed Tracing | Jaeger All-in-One, OpenTelemetry |
| Entity | Service | Port | Role | AP2 Compliance |
|---|---|---|---|---|
| User | Frontend | 3000 | End User | ✅ WebAuthn Signing (SD-JWT+KB) |
| Shopping Agent | Shopping Agent | 8000 | User's Agent | ✅ IntentMandate/PaymentMandate |
| Merchant Agent | Merchant Agent | 8001 | Product Search | ✅ A2A Protocol |
| Merchant | Merchant | 8002 | Seller | ✅ CartMandate Signing |
| Credential Provider | Credential Provider | 8003 | Authentication | ✅ WebAuthn Verification |
| Payment Processor | Payment Processor | 8004 | Payment Processing | ✅ Mandate Verification |
| Payment Network | Payment Network | 8005 | Token Issuance | ✅ Agent Token Lifecycle |
extract_info → check_completeness → generate_questionintent, max_amountStep 17-19: Tokenization
Step 20-22: PaymentMandate Creation
Step 23: Agent Token Issuance
Step 26-27: Credential Verification
Step 28: Payment Execution
Step 29: Receipt Generation
cd /path/to/ap2/
# Create .env file
cat > .env << 'EOF'
# OpenAI API (Required for LangGraph)
OPENAI_API_KEY=sk-proj-your-api-key-here
# DMR Endpoint (alternative to OpenAI)
DMR_API_URL=http://host.docker.internal:12434/engines/llama.cpp/v1
DMR_MODEL=ai/qwen3
DMR_API_KEY=none
# Logging
LOG_LEVEL=INFO
LOG_FORMAT=text
# Langfuse (Optional)
LANGFUSE_ENABLED=false
LANGFUSE_PUBLIC_KEY=
LANGFUSE_SECRET_KEY=
LANGFUSE_HOST=https://cloud.langfuse.com
# OpenTelemetry
OTEL_ENABLED=true
EOF
Note: If you're using DMR (alternative to OpenAI), you need to set up DMR before starting the services. See DMR Setup below.
If you want to use DMR instead of OpenAI for LangGraph's LLM inference, follow these steps:
What is DMR?
Installation:
# 1. Install DMR (example using Homebrew on macOS)
brew install dmr
# Or download from DMR releases
# https://github.com/your-dmr-repo/releases
# 2. Download and configure a model (e.g., Qwen3)
dmr pull ai/qwen3
# 3. Start DMR server
dmr serve --port 12434
# 4. Verify DMR is running
curl http://localhost:12434/v1/models
Configuration:
In your .env file, set:
DMR_API_URL=http://host.docker.internal:12434/engines/llama.cpp/v1
DMR_MODEL=ai/qwen3
DMR_API_KEY=none
Note: host.docker.internal allows Docker containers to access the host machine's localhost.
Alternative: Use OpenAI
If you don't want to set up DMR, simply provide your OpenAI API key:
OPENAI_API_KEY=sk-proj-your-api-key-here
The Shopping Agent will automatically use OpenAI if OPENAI_API_KEY is set.
# Build and start all services
docker compose up --build
# Or run in background
docker compose up --build -d
This will start all 15 services:
# Check service health
curl http://localhost:8000/health # Shopping Agent
curl http://localhost:8001/health # Merchant Agent
curl http://localhost:8002/health # Merchant
curl http://localhost:8003/health # Credential Provider
curl http://localhost:8004/health # Payment Processor
curl http://localhost:8005/health # Payment Network
# Access web interfaces
open http://localhost:3000 # Frontend
open http://localhost:3000/chat # Chat UI (main demo)
open http://localhost:3000/merchant # Merchant Dashboard
open http://localhost:16686 # Jaeger UI (tracing)
open http://localhost:7700 # Meilisearch UI
/chat on first visit# All services
docker compose logs -f
# Specific service
docker compose logs -f shopping_agent
docker compose logs -f payment_processor
docker compose logs -f payment_network
# Filter for Payment Network integration
docker compose logs -f payment_processor payment_network credential_provider | grep -E "(agent_token|charge|tokenize)"
# Stop (keep containers)
docker compose stop
# Stop and remove containers
docker compose down
# Remove everything including volumes
docker compose down -v
For local development without Docker:
# Install Python dependencies
cd /path/to/ap2/
pip install -e .
# Frontend dependencies
cd frontend/
npm install
# Set environment variables
export OPENAI_API_KEY=sk-proj-your-api-key-here
export LOG_LEVEL=INFO
# Start services in separate terminals
# Terminal 1: Shopping Agent
cd services/shopping_agent && python main.py
# Terminal 2: Merchant Agent
cd services/merchant_agent && python main.py
# Terminal 3: Merchant
cd services/merchant && python main.py
# Terminal 4: Credential Provider
cd services/credential_provider && python main.py
# Terminal 5: Payment Processor
cd services/payment_processor && python main.py
# Terminal 6: Payment Network
cd services/payment_network && python main.py
# Terminal 7: Frontend
cd frontend && npm run dev
This project includes comprehensive test coverage for core functionality.
# Install test dependencies
uv pip install --system pytest pytest-asyncio
# Run all tests
pytest tests/ -v
# Run specific test file
pytest tests/test_crypto.py -v
# Run specific test class
pytest tests/test_database.py::TestProductCRUD -v
# Run with coverage (requires pytest-cov)
pytest tests/ --cov=common --cov=services --cov-report=html
tests/
├── __init__.py
├── conftest.py # Pytest fixtures and configuration
├── test_crypto.py # Cryptography tests (21 tests)
├── test_database.py # Database CRUD tests (28 tests)
├── test_shopping_agent_api.py # Shopping Agent API tests (14 tests)
└── test_payment_processor_api.py # Payment Processor API tests (13 tests)
Cryptography Module (common/crypto.py):
Database Module (common/database.py):
API Modules:
Tests are automatically run on every push and pull request via GitHub Actions:
# .github/workflows/test.yml
# Tests run on Python 3.10 and 3.11
View test results in the Actions tab of the GitHub repository.
ap2/
├── common/ # Shared modules
│ ├── models.py # Pydantic models (A2A messages, API types)
│ ├── a2a_handler.py # A2A message handling
│ ├── base_agent.py # Base class for all agents
│ ├── database.py # SQLAlchemy models + CRUD
│ ├── redis_client.py # Redis KV client (TokenStore, SessionStore)
│ ├── crypto.py # Ed25519/ECDSA signing, AES-256 encryption
│ ├── logger.py # Unified logging (JSON/text)
│ ├── user_authorization.py # SD-JWT+KB verification
│ ├── risk_assessment.py # Risk assessment engine
│ └── receipt_generator.py # PDF receipt generation
│
├── services/ # Microservices
│ ├── shopping_agent/ # Shopping Agent (Port 8000)
│ ├── shopping_agent_mcp/ # Shopping Agent MCP (Port 8010)
│ ├── merchant_agent/ # Merchant Agent (Port 8001)
│ ├── merchant_agent_mcp/ # Merchant Agent MCP (Port 8011)
│ ├── merchant/ # Merchant (Port 8002)
│ ├── credential_provider/ # Credential Provider (Port 8003)
│ ├── payment_processor/ # Payment Processor (Port 8004)
│ └── payment_network/ # Payment Network (Port 8005)
│
├── frontend/ # Next.js frontend (Port 3000)
│ ├── app/ # App Router
│ │ ├── page.tsx # Home page
│ │ ├── chat/page.tsx # Chat UI (SSE/Streaming)
│ │ └── merchant/page.tsx # Merchant Dashboard
│ ├── components/ # React components
│ └── lib/ # Utilities & types
│
├── scripts/ # Utility scripts
│ ├── init_keys.py # Key pair initialization
│ └── init_seeds.py # Seed data injection
│
├── data/ # Persistent data (Docker Volume)
│ ├── *.db # SQLite databases (per service)
│ ├── receipts/ # PDF receipts
│ └── did_documents/ # DID Documents
│
├── keys/ # Encrypted keys (Docker Volume)
│ └── *_private.pem # Ed25519/ECDSA private keys (AES-256)
│
├── docker-compose.yml # Service orchestration
├── pyproject.toml # Python dependencies (uv)
└── README.md # This file
All services expose these endpoints:
GET / - Health check (returns agent_id, agent_name, status, version)GET /health - Health check (for Docker)POST /a2a/message - A2A message reception (auto-implemented by BaseAgent)User Interaction:
POST /chat/stream - Chat dialogue (SSE Streaming)POST /create-intent - Create IntentMandatePOST /create-payment - Create PaymentMandateGET /transactions/{transaction_id} - Get transactionProduct Search & Cart Creation:
GET /products?query=...&limit=10 - Product searchPOST /create-cart - Create CartMandate (unsigned)Cart Signing & Inventory:
POST /sign/cart - Sign CartMandateGET /inventory/{sku} - Check inventoryGET /products - List productsPOST /products - Add productWebAuthn & Token Issuance:
POST /attestations/verify - Verify WebAuthn attestationGET /payment-methods?user_id=... - List payment methodsPOST /payment-methods - Add payment methodPOST /payment-methods/tokenize - Tokenize payment methodPOST /credentials/verify - Verify credential token (returns agent_token)GET /webauthn/options - Get WebAuthn challengePayment Processing:
POST /process - Execute paymentGET /transactions/{transaction_id} - Get transactionPOST /refund - Process refundGET /receipts/{transaction_id}.pdf - Download PDF receipt (JWT-authenticated)Agent Token Lifecycle:
POST /network/tokenize - Issue Agent Token (AP2 Step 23)POST /network/verify-token - Verify Agent TokenPOST /network/charge - Execute payment charge (AP2 Step 28)GET /network/info - Get network informationThis application fully implements the AP2 (Agent Payments Protocol) v0.2 specification:
This application implements the A2UI (Agent-to-User Interface) protocol v0.9 for dynamic UI rendering during the shopping flow.
A2UI is a protocol that allows AI agents to dynamically render UI components in the user's interface. Instead of hardcoding UI for each interaction type, the agent sends structured messages describing what UI to display, and the frontend renders it accordingly.
Reference: A2UI Specification v0.9
| Message Type | Description |
|---|---|
createSurface |
Initialize a new UI surface with a unique ID |
updateComponents |
Provide component definitions (layout, fields, buttons) |
updateDataModel |
Send/update data for two-way binding |
deleteSurface |
Remove a surface when no longer needed |
| Component | Description | Usage |
|---|---|---|
Text |
Text display with style hints | Labels, headings, descriptions |
TextField |
Text input with validation | Form fields (name, address, email) |
Button |
Clickable button with action | Submit, cancel, navigation |
ChoicePicker |
Radio/checkbox selection | Country selection, payment method |
Card |
Container with optional click action | Credential provider cards |
Column |
Vertical layout | Form layout |
Row |
Horizontal layout | Button groups |
Divider |
Visual separator | Section breaks |
Image |
Image display | Product images, logos |
A2UI is used in the following steps:
Shipping Form (shipping_form)
Credential Provider Selection (cp_selection)
Payment Method Selection (payment_method_selection)
A2UI v0.9 uses a simplified envelope format without a type field:
// createSurface
{"createSurface": {"surfaceId": "shipping-form-abc123", "catalogId": "..."}}
// updateComponents
{"updateComponents": {"surfaceId": "shipping-form-abc123", "components": [...]}}
// updateDataModel
{"updateDataModel": {"surfaceId": "shipping-form-abc123", "path": "/", "op": "replace", "value": {...}}}
| File | Description |
|---|---|
services/shopping_agent/utils/a2ui_builders.py |
Backend A2UI message generators |
frontend/hooks/useSSEChat.ts |
SSE parsing for A2UI events |
frontend/components/a2ui/A2UISurfaceRenderer.tsx |
React component renderer |
frontend/lib/types/a2ui.ts |
TypeScript type definitions |
frontend/lib/a2ui/jsonPointer.ts |
JSON Pointer (RFC 6901) utilities |
frontend/lib/a2ui/userAction.ts |
User action message builder |
# Reset databases
rm -rf data/*.db
# Reinitialize
docker compose up init-seeds
# Reset keys
rm -rf keys/*
# Services will auto-generate keys on restart
docker compose restart
# Check port usage
lsof -ti:8000 | xargs kill -9 # Kill process on port 8000
# Restart Redis
docker compose restart redis
# Check Redis health
docker compose exec redis redis-cli ping
Connect AI agents across any network — zero config, encrypted, skill-based routing
Skills & plugins for agentic commerce : UCP, ACP, AP2, A2A, WebMCP, Magento 2, BigCommerce, WooCommerce
The open authority layer + SDKs for AI-agent payments. Thin Python/TS clients, an MCP server, framework adapters (LangChain/CrewAI/Hermes/OpenClaw/…), and @sardis/reference — a pure policy simulator + AP2/TAP/x402 verifiers showing exactly how Sardis decides if an agent may spend. The hosted engine that moves money is private.
Plausible is a proof of anything protocol for Algorand
The AI-to-AI Protocol Layer that catches unreliable agent outputs before they cost you money. Claim-level verification, escrow, and slashing. 224 tests, 12/12 adversarial patterns caught.
Trust-gated AI agent examples. Check CraftedTrust before connecting to any MCP server. Python (LangGraph) + TypeScript.
Lucid Agents Commerce SDK. Bootstrap AI agents in 60 seconds that can pay, sell, and participate in agentic commerce supply chains. Our protocol agnostic SDK provides CLI-generated templates and drop-in adapters for Hono, Express, Next.js, and TanStack, giving you instant access to crypto/fiat payment rails (AP2, A2A, x402, ERC8004).
Building blocks for Agentic payments (x402, MPP, AP2) for TypeScript, Rust, Go, Python, Ruby, PHP, Lua, Kotlin and Swift.
Building blocks for Agentic payments (x402, MPP, AP2) for TypeScript, Rust, Go, Python, Ruby, PHP, Lua, Kotlin and Swift.
Trust infrastructure for million-agent economies on Solana - identity, reputation, and validation designed for continuous feedback at scale.
A chain-agnostic AI-native payment infrastructure, authz layer for x402
🚀 Curated resources for Google's Agent Payments Protocol (AP2), A2A & x402 — blogs, videos, repos & specs. Contributions welcome!