acp-handler
CLAUDE.md29 starsChanged 14 months agoMITView on GitHub
This is acp-handler, a TypeScript SDK for implementing the Agentic Commerce Protocol (ACP). It enables web applications to handle checkout requests from AI agents like ChatGPT with built-in idempotency, signature verification, and OpenTelemetry tracing support. Package Manager: pnpm (v10.16.1) src/checkout/handlers.ts - Core business logic - Implements 5 ACP endpoints: create, update, complete, cancel, get - Orchestrates Products, Payments, and Webhooks handlers (user-provided) - All POST operations wrapped with withIdempotency() to prevent double-charging - Optional signature verification via checkSignature() - OpenTelemetry…
The file
We split this CLAUDE.md into the rules it gives an agent
3 rules. About 0 are common, 0 are distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 59
All POST operations wrapped with withIdempotency() to prevent double-charging
- Very specific: line 148
All operations are idempotent via the Idempotency-Key header.
- Very specific: line 151
Before any status change, canTransition(from, to) validates the FSM rules.
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Project Overview
This is acp-handler, a TypeScript SDK for implementing the Agentic Commerce Protocol (ACP). It enables web applications to handle checkout requests from AI agents like ChatGPT with built-in idempotency, signature verification, and OpenTelemetry tracing support.
Package Manager: pnpm (v10.16.1)
Commands
Development
pnpm dev- Start development server (runs all workspaces via turbo)pnpm build- Build all packages via turbopnpm test- Run vitest testspnpm test:watch- Run tests in watch mode (usecd packages/sdkfirst)
Code Quality
pnpm lint- Run biome linter across workspacespnpm lint:fix- Auto-fix linting issuespnpm format- Check formatting with biomepnpm format:fix- Auto-format code with biometurbo check-types- Type check all workspaces
Testing Individual Package
cd packages/sdk
pnpm test # Run all tests
pnpm test checkout.test.ts # Run specific test fileExample App
cd examples/basic
pnpm dev # Start Next.js example appArchitecture
Monorepo Structure
packages/sdk/- Coreacp-handlerpackage (published to npm)examples/basic/- Next.js reference implementation- Managed with Turborepo for build orchestration
Core Package: packages/sdk/
Module Exports
The SDK has dedicated export paths:
acp-handler- Main entry (all checkout functionality)acp-handler/next- Next.js catch-all route helperacp-handler/test- Test utilities and mocks
Key Components
src/checkout/handlers.ts - Core business logic
- Implements 5 ACP endpoints: create, update, complete, cancel, get
- Orchestrates Products, Payments, and Webhooks handlers (user-provided)
- All POST operations wrapped with
withIdempotency()to prevent double-charging - Optional signature verification via
checkSignature() - OpenTelemetry tracing spans for observability
src/checkout/fsm.ts - State machine
- Enforces valid checkout status transitions:
not_ready_for_payment→ready_for_payment|canceledready_for_payment→completed|canceledcompletedandcanceledare terminal states
- Used by handlers to validate state changes before mutations
src/checkout/idempotency.ts - Idempotency layer
- Implements distributed locking with
setnx(set-if-not-exists) - Caches computation results by idempotency key (1h TTL default)
- Returns cached result on retry instead of re-executing
- Critical for payment operations to prevent double-charging
src/checkout/storage.ts - Storage abstraction
KVinterface:get(),set(),setnx()(atomic operations)SessionStoreinterface:get(),put()for session persistencecreateRedisSessionStore()helper: default Redis-backed session storage- Session TTL: 24 hours default
- Redis adapter in
src/checkout/storage/redis.ts - Sessions are optional - users can provide custom
SessionStoreimplementation
src/checkout/signature.ts - Request verification
- HMAC-SHA256 signature validation
- Timestamp freshness check (5 min tolerance default)
- Constant-time comparison to prevent timing attacks
- Optional (disabled by default for easier development)
src/checkout/types.ts - ACP spec types
CheckoutSession,LineItem,Money,Totals,Address- Request/response types for all endpoints
- Status types:
CheckoutSessionStatus
User-Provided Handlers
Users must implement three handler interfaces (and optionally a fourth):
Products- Pricing engineprice()method calculates items, totals, fulfillment options- Returns
ready: booleanto indicate if checkout can proceed - Called on every create/update operation
Payments- Two-phase payment commitauthorize()- Reserve funds (returns intent_id)capture()- Charge customer (uses intent_id)- Follows payment provider patterns (Stripe, etc.)
Webhooks- Outbound notificationsorderUpdated()- Notify AI agent about status changes- Called after complete/cancel operations
- Helper in
src/checkout/webhooks/outbound.tsfor signing
Sessions(optional) - Custom session storage- Defaults to Redis-backed storage using the provided
store - Can be overridden for platform integrations (Shopify, commercetools, etc.)
- Allows single source of truth in existing cart systems
- See
docs/session-storage.mdfor detailed examples
- Defaults to Redis-backed storage using the provided
Framework Adapters
src/checkout/next/index.ts - Next.js App Router
createNextCatchAll()exports GET/POST route handlers- Works with
[[...segments]]/route.tscatch-all routes - Handles path parsing and body extraction
Testing Infrastructure
src/test/index.ts - Test utilities
createMemoryStore()- In-memory KV for testing (no Redis needed)createMockProducts(),createMockPayments(),createMockWebhooks()- Mock implementationscreateRequest()- Helper to construct Request objects with proper headers
Tests use Vitest and are located in packages/sdk/test/.
Build System
- tsdown for package bundling (generates dist/ with .js and .d.ts files)
- Biome for linting and formatting (replaces ESLint/Prettier)
- TypeScript 5 with strict mode enabled
- Turborepo for parallel task execution across workspaces
Key Patterns
Payment Flow
- User creates session →
products.price()called → session saved - User updates cart →
products.price()re-run → session updated - User completes →
payments.authorize()→payments.capture()→webhooks.orderUpdated()→ session marked completed
All operations are idempotent via the Idempotency-Key header.
State Transitions
Before any status change, canTransition(from, to) validates the FSM rules. Invalid transitions return 400 errors with detailed messages.
Storage Keys
- Sessions:
acp:session:{id}(24h TTL) - when using default Redis storage - Idempotency:
{idempotency_key}(1h TTL) - Note: Custom session stores can use any storage mechanism (Shopify, DB, etc.)
Error Handling
Structured errors with:
code- Machine-readable error codemessage- Human-readable descriptionparam- Field that caused the errortype- Error category (e.g., "invalid_request_error")
HTTP status codes: 400 (client error), 401 (auth), 404 (not found), 500 (server error)
Dependencies
Core
- zod ^4.1.11 - Schema validation
Peer (Optional)
- next >=15.5 - Next.js catch-all route helper
- redis >=5.8 - Redis storage backend
- @opentelemetry/api >=1.0.0 - Tracing support
Resources
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

