UCP Skill — Universal Commerce Protocol Implementation
Core Principles
- Edge runtime is NOT USED — Only Node.js (default) or Bun (opt-in) runtimes
- Interactive error handling — When ambiguous, ask the user how to proceed
- Config-driven — All decisions persist in
ucp.config.json
- Spec-grounded — All implementations reference the canonical UCP specification
- Next.js conventions — Follow App Router patterns for code organization
- Deep analysis — Use AST parsing and data flow tracing for gap detection
Spec Repository Handling
Location Priority
Check in this order:
./ucp/ — User's local copy (use as-is)
./.ucp-spec/ — Previously cloned spec (update it)
- Neither exists — Clone fresh
Clone Procedure
When cloning is needed:
git clone --depth 1 https://github.com/Universal-Commerce-Protocol/ucp.git .ucp-spec
If HTTPS fails, try SSH:
git clone --depth 1 git@github.com:Universal-Commerce-Protocol/ucp.git .ucp-spec
Update Procedure
When ./.ucp-spec/ exists:
cd .ucp-spec && git pull && cd ..
Gitignore Management
After cloning, ensure .ucp-spec/ is in .gitignore:
- Read
.gitignore if it exists
- Check if
.ucp-spec/ or .ucp-spec is already listed
- If not, append
.ucp-spec/ on a new line
Spec File Locations (read on demand)
docs/specification/overview.md
docs/specification/checkout.md
docs/specification/checkout-rest.md
docs/specification/checkout-mcp.md
docs/specification/checkout-a2a.md
docs/specification/embedded-checkout.md
docs/specification/order.md
docs/specification/fulfillment.md
docs/specification/discount.md
docs/specification/buyer-consent.md
docs/specification/identity-linking.md
docs/specification/ap2-mandates.md
docs/specification/payment-handler-guide.md
docs/specification/tokenization-guide.md
spec/services/shopping/rest.openapi.json
spec/services/shopping/mcp.openrpc.json
spec/services/shopping/embedded.openrpc.json
spec/handlers/tokenization/openapi.json
spec/schemas/shopping/*
spec/discovery/profile_schema.json
Configuration File
Location
./ucp.config.json at project root
Schema
{
"$schema": "./ucp.config.schema.json",
"ucp_version": "2026-01-11",
"roles": ["business"],
"runtime": "nodejs",
"capabilities": {
"core": ["dev.ucp.shopping.checkout"],
"extensions": []
},
"transports": ["rest"],
"transport_priority": ["rest", "mcp", "a2a", "embedded"],
"payment_handlers": [],
"features": {
"ap2_mandates": false,
"identity_linking": false,
"multi_destination_fulfillment": false
},
"domain": "",
"existing_apis": {},
"policy_urls": {
"privacy": "",
"terms": "",
"refunds": "",
"shipping": ""
},
"scaffold_depth": "full",
"generated_files": [],
"answers": {},
"deployment": {
"platform": "vercel",
"region": "iad1",
"mcp": {
"enabled": false,
"max_duration": 60
}
}
}
Field Descriptions
| Field |
Type |
Description |
ucp_version |
string |
UCP spec version (date-based) |
roles |
string[] |
One or more of: business, platform, payment_provider, host_embedded |
runtime |
string |
nodejs (default) or bun |
capabilities.core |
string[] |
Required capabilities to implement |
capabilities.extensions |
string[] |
Optional extensions to implement |
transports |
string[] |
Enabled transports: rest, mcp, a2a, embedded |
transport_priority |
string[] |
Order to implement transports |
payment_handlers |
string[] |
Payment handler IDs to support |
features.ap2_mandates |
boolean |
Enable AP2 mandate signing |
features.identity_linking |
boolean |
Enable OAuth identity linking |
features.multi_destination_fulfillment |
boolean |
Enable multi-destination shipping |
domain |
string |
Business domain for /.well-known/ucp |
existing_apis |
object |
Map of existing API endpoints to analyze |
policy_urls |
object |
URLs for privacy, terms, refunds, shipping policies |
scaffold_depth |
string |
types | scaffolding | full |
generated_files |
string[] |
Files created by scaffold (for tracking) |
answers |
object |
Raw answers to qualifying questions |
Sub-command: (no argument)
Trigger
User runs /ucp with no sub-command
Behavior
Display help listing all available sub-commands:
UCP Skill — Universal Commerce Protocol Implementation
Available commands:
/ucp init — Initialize UCP in this project (clone spec, create config)
/ucp consult — Full consultation: answer qualifying questions, build roadmap
/ucp plan — Generate detailed implementation plan
/ucp gaps — Analyze existing code against UCP requirements
/ucp scaffold — Generate full working UCP implementation
/ucp validate — Validate implementation against UCP schemas
/ucp profile — Generate /.well-known/ucp discovery profile
/ucp test — Generate unit tests for UCP handlers
/ucp docs — Generate internal documentation
Typical workflow:
/ucp init → /ucp consult → /ucp plan → /ucp scaffold → /ucp profile → /ucp test → /ucp validate
Configuration: ./ucp.config.json
Spec location: ./ucp/ or ./.ucp-spec/
Sub-command: init
Trigger
User runs /ucp init
Purpose
Bootstrap UCP in a project: clone spec, create config, ask essential questions.
Procedure
Step 1: Check/Clone Spec Repository
- Check if
./ucp/ exists
- If yes: "Found local UCP spec at ./ucp/"
- If not, check if
./.ucp-spec/ exists
- If yes: Run
git pull to update
- If no: Clone the repo (see Spec Repository Handling)
- After cloning, add
.ucp-spec/ to .gitignore
Step 2: Check for Existing Config
- Check if
./ucp.config.json exists
- If yes, ask: "Config file exists. Overwrite, merge, or abort?"
- Overwrite: Delete and create fresh
- Merge: Keep existing values as defaults
- Abort: Stop init
Step 3: Ask Essential Questions (4 questions)
Q1: What role(s) are you implementing?
- Business (merchant of record)
- Platform (consumer app or agent)
- Payment credential provider
- Host embedding checkout
- Multiple (specify)
If user selects multiple roles, WARN:
"Implementing multiple roles is unusual. This is typically for marketplace/aggregator scenarios. Are you sure?"
Q2: What runtime will you use?
- Node.js (recommended, stable)
- Bun (opt-in, experimental)
NOTE: If user mentions Edge, respond:
"Edge runtime is not supported for UCP implementations. Please choose Node.js or Bun."
Q3: What is your business domain?
- The domain that will host
/.well-known/ucp
- Example:
shop.example.com
Q4: Which transports do you need at launch?
- REST (recommended baseline)
- MCP (Model Context Protocol)
- A2A (Agent-to-Agent)
- Embedded (iframe checkout)
Step 4: Create Config File
Create ./ucp.config.json with:
- Answers from essential questions
- Sensible defaults for other fields
ucp_version set to latest from spec
Step 5: Output Ready Message
UCP initialized successfully!
Config: ./ucp.config.json
Spec: ./.ucp-spec/ (or ./ucp/)
Role: {role}
Domain: {domain}
Next steps:
/ucp consult — Complete full consultation (recommended)
/ucp plan — Skip to implementation planning
/ucp gaps — Analyze existing code first
Sub-command: consult
Trigger
User runs /ucp consult
Purpose
Walk through all 12 qualifying questions, update config, produce implementation roadmap.
Prerequisites
- Config file must exist (run
/ucp init first)
- Spec must be available
Procedure
Step 1: Load Existing Config
Read ./ucp.config.json and use existing answers as defaults.
Step 2: Walk Through 12 Qualifying Questions
Ask each question. If already answered in config, show current value and ask to confirm or change.
Q1: Are we implementing the business side, the platform side, or both?
- Map to
roles in config
- If both/multiple, warn about unusual scenario
Q2: Which UCP version and which capabilities/extensions are in scope?
- Read available versions from spec
- Present capability options:
- Core:
dev.ucp.shopping.checkout (required)
- Extensions:
dev.ucp.shopping.fulfillment
dev.ucp.shopping.discount
dev.ucp.shopping.buyer_consent
dev.ucp.shopping.ap2_mandate
dev.ucp.shopping.order
dev.ucp.common.identity_linking
Q3: Which payment handlers do we need?
- Wallets (Apple Pay, Google Pay)
- PSP tokenization (Stripe, Adyen, etc.)
- Custom handler
- None yet (decide later)
Q4: Do we need AP2 mandates and signing key infrastructure?
- Yes → set
features.ap2_mandates: true
- No → set
features.ap2_mandates: false
- If yes, explain: "You'll need to provide JWS signing keys (ES256 recommended)"
Q5: Do we need fulfillment options and multi-group/multi-destination support?
- No fulfillment needed
- Single destination only
- Multi-destination support → set
features.multi_destination_fulfillment: true
Q6: Do we need discounts, buyer consent capture, or identity linking?
- Discounts → add
dev.ucp.shopping.discount to extensions
- Buyer consent → add
dev.ucp.shopping.buyer_consent to extensions
- Identity linking → add
dev.ucp.common.identity_linking, set features.identity_linking: true
Q7: What are the existing checkout and order APIs we should map to UCP?
- Ask for existing endpoint paths
- Store in
existing_apis object
- Examples:
/api/checkout, /api/cart, /api/orders
Q8: What are the required policy URLs?
- Privacy policy URL
- Terms of service URL
- Refund policy URL
- Shipping policy URL
- Store in
policy_urls object
Q9: What authentication model is required for checkout endpoints?
- None (anonymous checkout)
- API key
- OAuth 2.0
- Session-based
- Store in
answers.authentication_model
Q10: Who will receive order webhooks and what event cadence is required?
- Webhook URL for order events
- Event types needed:
order.created, order.updated, order.fulfilled, order.canceled
- Store in
answers.webhook_config
Q11: Do we need to support MCP, A2A, or embedded checkout at launch?
- Confirm/update
transports array
- Set
transport_priority order
Q12: What is the business domain that will host /.well-known/ucp?
- Confirm/update
domain field
Step 3: Update Config
Write all answers to ./ucp.config.json
Step 4: Generate Implementation Roadmap
Based on answers, produce a roadmap:
UCP Implementation Roadmap
==========================
Role: Business (merchant)
Version: 2026-01-11
Domain: shop.example.com
Capabilities to implement:
✓ dev.ucp.shopping.checkout (core)
✓ dev.ucp.shopping.fulfillment
✓ dev.ucp.shopping.discount
○ dev.ucp.shopping.order
Transports (in order):
1. REST
2. MCP
Payment handlers:
- Stripe tokenization
Key implementation tasks:
1. Create /.well-known/ucp discovery profile
2. Implement checkout session endpoints (create, get, update, complete)
3. Implement fulfillment options logic
4. Implement discount code application
5. Set up payment handler integration
6. Implement order webhooks
7. Add MCP transport layer
Estimated files to create/modify: ~15-20
Run /ucp plan for detailed file-by-file plan.
Sub-command: plan
Trigger
User runs /ucp plan
Purpose
Generate detailed implementation plan with specific files and order of operations.
Prerequisites
- Config file must exist with completed consultation
- Spec must be available
Procedure
Step 1: Load Config and Spec
- Read
./ucp.config.json
- Read relevant spec files based on capabilities/transports
Step 2: Analyze Existing Codebase Structure
- Detect Next.js version (App Router vs Pages Router)
- Find existing API routes
- Find existing lib/utils structure
- Find existing types/schemas
- Identify package manager (npm, yarn, pnpm, bun)
Step 3: Generate File Plan
For each capability/transport, list files to create/modify.
Example output:
UCP Implementation Plan
=======================
Phase 1: Core Types and Schemas
-------------------------------
CREATE lib/ucp/types/checkout.ts
- CheckoutSession interface
- LineItem, Totals, Payment types
- Status enum
CREATE lib/ucp/types/index.ts
- Re-export all types
CREATE lib/ucp/schemas/checkout.ts
- Zod schemas for validation
Phase 2: Discovery Profile
--------------------------
CREATE app/.well-known/ucp/route.ts
- GET handler returning profile JSON
- Read capabilities from config
CREATE lib/ucp/profile.ts
- Profile generation logic
Phase 3: Checkout Endpoints (REST)
----------------------------------
CREATE app/api/ucp/checkout/route.ts
- POST: Create checkout session
- Capability negotiation logic
CREATE app/api/ucp/checkout/[id]/route.ts
- GET: Retrieve checkout
- PATCH: Update checkout
- POST: Complete checkout (action=complete)
CREATE lib/ucp/handlers/checkout.ts
- Business logic for checkout operations
- State machine implementation
Phase 4: Fulfillment Extension
------------------------------
CREATE lib/ucp/handlers/fulfillment.ts
- Fulfillment options calculation
- Destination validation
MODIFY lib/ucp/handlers/checkout.ts
- Integrate fulfillment into checkout response
Phase 5: Discount Extension
---------------------------
CREATE lib/ucp/handlers/discount.ts
- Discount code validation
- Applied discount calculation
MODIFY lib/ucp/handlers/checkout.ts
- Integrate discounts into checkout
Phase 6: Payment Integration
----------------------------
CREATE lib/ucp/handlers/payment.ts
- Payment handler registry
- payment_data processing
CREATE lib/ucp/handlers/stripe.ts
- Stripe-specific tokenization
Phase 7: Order Webhooks
-----------------------
CREATE lib/ucp/handlers/order.ts
- Order event emission
- Webhook signing (JWS)
CREATE lib/ucp/webhooks/sender.ts
- Webhook delivery with retries
Phase 8: MCP Transport (if enabled)
-----------------------------------
CREATE lib/ucp/transports/mcp.ts
- MCP tool definitions
- JSON-RPC handlers
Dependencies to install:
------------------------
zod — Schema validation
jose — JWS signing (if AP2/webhooks enabled)
Run /ucp scaffold to generate these files.
Step 4: Save Plan to Config
Store the plan in answers.implementation_plan for scaffold reference.
Sub-command: gaps
Trigger
User runs /ucp gaps
Purpose
Deep analysis of existing codebase against UCP requirements. Uses AST parsing and data flow tracing.
Prerequisites
- Config file should exist (for role/capability context)
- Spec must be available
Procedure
Step 1: Load Context
- Read config for declared capabilities
- Read relevant spec files
Step 2: Discover Existing Code
Scan for:
- API routes (
app/api/**, pages/api/**)
- Checkout-related files (search for "checkout", "cart", "order")
- Payment handling code
- Webhook implementations
Step 3: Deep Analysis (AST-based)
For each relevant file:
- Parse AST
- Trace data flow for checkout objects
- Identify existing patterns
Analyze against UCP requirements:
| Requirement |
Status |
Finding |
| Discovery profile at /.well-known/ucp |
MISSING |
No route found |
| Checkout session creation |
PARTIAL |
Found /api/checkout but missing UCP fields |
| Status lifecycle |
MISSING |
No status state machine |
| Capability negotiation |
MISSING |
No UCP-Agent header handling |
| Payment handler support |
PARTIAL |
Stripe exists but not UCP-compliant |
| Response metadata (ucp object) |
MISSING |
Responses don't include ucp field |
Step 4: Generate Gap Report
UCP Gap Analysis Report
=======================
Existing codebase: Next.js 14 (App Router)
Target role: Business
Target capabilities: checkout, fulfillment, discount
CRITICAL GAPS (must fix)
------------------------
[GAP-001] Missing discovery profile
- Required: /.well-known/ucp endpoint
- Status: NOT FOUND
- Fix: Create app/.well-known/ucp/route.ts
[GAP-002] Missing UCP response envelope
- Required: All responses must include `ucp` object with version/capabilities
- Found: app/api/checkout/route.ts returns raw checkout data
- Fix: Wrap responses with UCP metadata
[GAP-003] Missing capability negotiation
- Required: Read UCP-Agent header, compute intersection
- Found: No header processing in checkout routes
- Fix: Add middleware or handler logic
PARTIAL IMPLEMENTATIONS
-----------------------
[PARTIAL-001] Checkout session exists but non-compliant
- File: app/api/checkout/route.ts
- Missing: id, status, currency, totals.grand_total, links, payment fields
- Has: line_items (needs schema adjustment)
[PARTIAL-002] Payment integration exists
- File: lib/stripe.ts
- Issue: Direct Stripe API, not UCP payment_data flow
- Fix: Wrap with UCP payment handler abstraction
COMPLIANT AREAS
---------------
[OK] Policy URLs configured in existing checkout
[OK] HTTPS enforced
[OK] Idempotency key support in POST handlers
RECOMMENDATIONS
---------------
1. Start with /ucp scaffold to generate compliant structure
2. Migrate existing checkout logic into new handlers
3. Run /ucp validate after migration
Total: 3 critical gaps, 2 partial, 3 compliant
Sub-command: scaffold
Trigger
User runs /ucp scaffold
Purpose
Generate full working UCP implementation based on config and plan.
Prerequisites
- Config file must exist
- Plan should exist (run
/ucp plan first, or scaffold will generate one)
Procedure
Step 1: Confirm Scaffold Depth
Ask user:
"What level of code generation do you want?"
- types: TypeScript interfaces and Zod schemas only
- scaffolding: Structure with TODO markers for business logic
- full: Complete working implementation (recommended)
Store choice in config.scaffold_depth
Step 2: Check Dependencies
Identify required packages based on config:
zod — Always needed
jose — If AP2 mandates or webhook signing enabled
uuid — For session ID generation
Ask before installing:
"The following packages are required: zod, jose, uuid"
"Install now? (npm install / bun add)"
If yes, run appropriate install command.
Step 3: Generate Code
Generate files according to plan. For each file:
- Create parent directories if needed
- Write file content
- Track in
config.generated_files
Code Generation Templates
lib/ucp/types/checkout.ts
/**
* UCP Checkout Types
* Generated by /ucp scaffold
* Spec: {spec_version}
*/
export type CheckoutStatus =
| 'incomplete'
| 'requires_escalation'
| 'ready_for_complete'
| 'complete_in_progress'
| 'completed'
| 'canceled';
export type MessageSeverity =
| 'recoverable'
| 'requires_buyer_input'
| 'requires_buyer_review';
export interface UCPMetadata {
version: string;
capabilities: string[];
}
export interface LineItem {
id: string;
name: string;
quantity: number;
unit_price: number;
total_price: number;
currency: string;
// Extension fields added based on config
}
export interface Totals {
subtotal: number;
tax: number;
shipping: number;
discount: number;
grand_total: number;
currency: string;
}
export interface PaymentInfo {
status: 'pending' | 'authorized' | 'captured' | 'failed';
handlers: PaymentHandler[];
amount_due: number;
currency: string;
}
export interface PaymentHandler {
id: string;
type: string;
config?: Record<string, unknown>;
}
export interface CheckoutMessage {
code: string;
severity: MessageSeverity;
message: string;
field?: string;
}
export interface CheckoutLinks {
self: string;
continue_url?: string;
privacy_policy: string;
terms_of_service: string;
refund_policy?: string;
shipping_policy?: string;
}
export interface CheckoutSession {
ucp: UCPMetadata;
id: string;
status: CheckoutStatus;
currency: string;
line_items: LineItem[];
totals: Totals;
payment: PaymentInfo;
links: CheckoutLinks;
messages: CheckoutMessage[];
expires_at: string;
created_at: string;
updated_at: string;
// Extension fields populated based on negotiated capabilities
buyer?: BuyerInfo;
fulfillment?: FulfillmentInfo;
discounts?: DiscountInfo;
}
export interface BuyerInfo {
email?: string;
phone?: string;
name?: string;
// consent fields if buyer_consent extension enabled
}
// Conditional types based on extensions...
lib/ucp/schemas/checkout.ts
/**
* UCP Checkout Zod Schemas
* Generated by /ucp scaffold
*/
import { z } from 'zod';
export const LineItemSchema = z.object({
id: z.string(),
name: z.string(),
quantity: z.number().int().positive(),
unit_price: z.number().int(), // minor units (cents)
total_price: z.number().int(),
currency: z.string().length(3),
});
export const TotalsSchema = z.object({
subtotal: z.number().int(),
tax: z.number().int(),
shipping: z.number().int(),
discount: z.number().int(),
grand_total: z.number().int(),
currency: z.string().length(3),
});
export const CreateCheckoutRequestSchema = z.object({
line_items: z.array(LineItemSchema).min(1),
currency: z.string().length(3),
buyer: z.object({
email: z.string().email().optional(),
phone: z.string().optional(),
}).optional(),
// Extension fields...
});
export const UpdateCheckoutRequestSchema = z.object({
line_items: z.array(LineItemSchema).optional(),
buyer: z.object({
email: z.string().email().optional(),
phone: z.string().optional(),
}).optional(),
// Extension fields...
});
export const CompleteCheckoutRequestSchema = z.object({
action: z.literal('complete'),
payment_data: z.record(z.unknown()),
});
export type CreateCheckoutRequest = z.infer<typeof CreateCheckoutRequestSchema>;
export type UpdateCheckoutRequest = z.infer<typeof UpdateCheckoutRequestSchema>;
export type CompleteCheckoutRequest = z.infer<typeof CompleteCheckoutRequestSchema>;
app/.well-known/ucp/route.ts
/**
* UCP Discovery Profile Endpoint
* GET /.well-known/ucp
* Generated by /ucp scaffold
*/
import { NextResponse } from 'next/server';
import { generateProfile } from '@/lib/ucp/profile';
export const runtime = 'nodejs'; // Edge runtime is not supported
export async function GET() {
const profile = generateProfile();
return NextResponse.json(profile, {
headers: {
'Cache-Control': 'public, max-age=3600',
'Content-Type': 'application/json',
},
});
}
lib/ucp/profile.ts
/**
* UCP Discovery Profile Generator
* Generated by /ucp scaffold
*/
import config from '@/../ucp.config.json';
export interface UCPProfile {
ucp: {
version: string;
services: Record<string, ServiceDefinition>;
capabilities: CapabilityDefinition[];
};
payment?: {
handlers: PaymentHandlerDefinition[];
};
signing_keys?: JsonWebKey[];
}
interface ServiceDefinition {
version: string;
spec: string;
rest?: { schema: string; endpoint: string };
mcp?: { schema: string; endpoint: string };
a2a?: { endpoint: string };
embedded?: { schema: string };
}
interface CapabilityDefinition {
name: string;
version: string;
spec: string;
schema: string;
extends?: string;
config?: Record<string, unknown>;
}
interface PaymentHandlerDefinition {
id: string;
type: string;
spec: string;
config_schema: string;
}
export function generateProfile(): UCPProfile {
const baseUrl = `https://${config.domain}`;
const profile: UCPProfile = {
ucp: {
version: config.ucp_version,
services: {
'dev.ucp.shopping': {
version: config.ucp_version,
spec: 'https://ucp.dev/spec/services/shopping',
...(config.transports.includes('rest') && {
rest: {
schema: 'https://ucp.dev/spec/services/shopping/rest.openapi.json',
endpoint: `${baseUrl}/api/ucp`,
},
}),
...(config.transports.includes('mcp') && {
mcp: {
schema: 'https://ucp.dev/spec/services/shopping/mcp.openrpc.json',
endpoint: `${baseUrl}/api/ucp/mcp`,
},
}),
...(config.transports.includes('a2a') && {
a2a: {
endpoint: `${baseUrl}/api/ucp/a2a`,
},
}),
...(config.transports.includes('embedded') && {
embedded: {
schema: 'https://ucp.dev/spec/services/shopping/embedded.openrpc.json',
},
}),
},
},
capabilities: buildCapabilities(config),
},
};
if (config.payment_handlers.length > 0) {
profile.payment = {
handlers: config.payment_handlers.map(buildHandlerDefinition),
};
}
return profile;
}
function buildCapabilities(config: typeof import('@/../ucp.config.json')): CapabilityDefinition[] {
const capabilities: CapabilityDefinition[] = [];
// Core checkout capability (always present)
capabilities.push({
name: 'dev.ucp.shopping.checkout',
version: config.ucp_version,
spec: 'https://ucp.dev/spec/capabilities/checkout',
schema: 'https://ucp.dev/spec/schemas/shopping/checkout.json',
});
// Add extensions based on config
for (const ext of config.capabilities.extensions) {
capabilities.push(buildExtensionCapability(ext, config));
}
return capabilities;
}
function buildExtensionCapability(
extension: string,
config: typeof import('@/../ucp.config.json')
): CapabilityDefinition {
// Map extension names to spec URLs
const extMap: Record<string, { spec: string; schema: string; extends?: string }> = {
'dev.ucp.shopping.fulfillment': {
spec: 'https://ucp.dev/spec/capabilities/fulfillment',
schema: 'https://ucp.dev/spec/schemas/shopping/fulfillment.json',
extends: 'dev.ucp.shopping.checkout',
},
'dev.ucp.shopping.discount': {
spec: 'https://ucp.dev/spec/capabilities/discount',
schema: 'https://ucp.dev/spec/schemas/shopping/discount.json',
extends: 'dev.ucp.shopping.checkout',
},
'dev.ucp.shopping.buyer_consent': {
spec: 'https://ucp.dev/spec/capabilities/buyer-consent',
schema: 'https://ucp.dev/spec/schemas/shopping/buyer-consent.json',
extends: 'dev.ucp.shopping.checkout',
},
'dev.ucp.shopping.order': {
spec: 'https://ucp.dev/spec/capabilities/order',
schema: 'https://ucp.dev/spec/schemas/shopping/order.json',
config: {
webhook_url: config.answers?.webhook_config?.url,
},
},
'dev.ucp.common.identity_linking': {
spec: 'https://ucp.dev/spec/capabilities/identity-linking',
schema: 'https://ucp.dev/spec/schemas/common/identity-linking.json',
},
};
const def = extMap[extension];
return {
name: extension,
version: config.ucp_version,
spec: def?.spec || '',
schema: def?.schema || '',
...(def?.extends && { extends: def.extends }),
...(def?.config && { config: def.config }),
};
}
function buildHandlerDefinition(handlerId: string): PaymentHandlerDefinition {
// Map known handlers
const handlerMap: Record<string, Omit<PaymentHandlerDefinition, 'id'>> = {
stripe: {
type: 'tokenization',
spec: 'https://ucp.dev/spec/handlers/stripe',
config_schema: 'https://ucp.dev/spec/handlers/stripe/config.json',
},
// Add more handlers as needed
};
const def = handlerMap[handlerId] || {
type: 'custom',
spec: '',
config_schema: '',
};
return { id: handlerId, ...def };
}
app/api/ucp/checkout/route.ts
/**
* UCP Checkout Session Endpoint
* POST /api/ucp/checkout - Create checkout session
* Generated by /ucp scaffold
*/
import { NextRequest, NextResponse } from 'next/server';
import { createCheckout } from '@/lib/ucp/handlers/checkout';
import { CreateCheckoutRequestSchema } from '@/lib/ucp/schemas/checkout';
import { negotiateCapabilities, parseUCPAgent } from '@/lib/ucp/negotiation';
import { wrapResponse, errorResponse } from '@/lib/ucp/response';
export const runtime = 'nodejs'; // Edge runtime is not supported
export async function POST(request: NextRequest) {
try {
// Parse UCP-Agent header for capability negotiation
const ucpAgent = parseUCPAgent(request.headers.get('UCP-Agent'));
// Negotiate capabilities
const negotiation = await negotiateCapabilities(ucpAgent?.profile);
// Parse and validate request body
const body = await request.json();
const parsed = CreateCheckoutRequestSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(400, 'invalid_request', parsed.error.message);
}
// Get idempotency key
const idempotencyKey = request.headers.get('Idempotency-Key');
// Create checkout session
const checkout = await createCheckout(parsed.data, {
capabilities: negotiation.capabilities,
idempotencyKey,
});
return wrapResponse(checkout, negotiation, 201);
} catch (error) {
console.error('Checkout creation failed:', error);
return errorResponse(500, 'internal_error', 'Failed to create checkout session');
}
}
lib/ucp/handlers/checkout.ts
/**
* UCP Checkout Handler
* Core business logic for checkout operations
* Generated by /ucp scaffold
*/
import { randomUUID } from 'crypto';
import type {
CheckoutSession,
CheckoutStatus,
CreateCheckoutRequest,
UpdateCheckoutRequest,
} from '@/lib/ucp/types/checkout';
import config from '@/../ucp.config.json';
// In-memory store for demo - replace with your database
const checkoutStore = new Map<string, CheckoutSession>();
interface CreateCheckoutOptions {
capabilities: string[];
idempotencyKey?: string | null;
}
export async function createCheckout(
request: CreateCheckoutRequest,
options: CreateCheckoutOptions
): Promise<CheckoutSession> {
const id = randomUUID();
const now = new Date().toISOString();
const expiresAt = new Date(Date.now() + 30 * 60 * 1000).toISOString(); // 30 min
// Calculate totals
const subtotal = request.line_items.reduce((sum, item) => sum + item.total_price, 0);
const tax = calculateTax(subtotal); // Implement your tax logic
const shipping = 0; // Set by fulfillment extension
const discount = 0; // Set by discount extension
const checkout: CheckoutSession = {
ucp: {
version: config.ucp_version,
capabilities: options.capabilities,
},
id,
status: 'incomplete',
currency: request.currency,
line_items: request.line_items.map((item, index) => ({
...item,
id: item.id || `line_${index}`,
})),
totals: {
subtotal,
tax,
shipping,
discount,
grand_total: subtotal + tax + shipping - discount,
currency: request.currency,
},
payment: {
status: 'pending',
handlers: getPaymentHandlers(options.capabilities),
amount_due: subtotal + tax + shipping - discount,
currency: request.currency,
},
links: {
self: `https://${config.domain}/api/ucp/checkout/${id}`,
continue_url: `https://${config.domain}/checkout/${id}`,
privacy_policy: config.policy_urls.privacy,
terms_of_service: config.policy_urls.terms,
...(config.policy_urls.refunds && { refund_policy: config.policy_urls.refunds }),
...(config.policy_urls.shipping && { shipping_policy: config.policy_urls.shipping }),
},
messages: [],
expires_at: expiresAt,
created_at: now,
updated_at: now,
};
// Add buyer info if provided
if (request.buyer) {
checkout.buyer = request.buyer;
}
// Validate checkout state and set appropriate status
checkout.status = determineStatus(checkout);
checkout.messages = generateMessages(checkout);
// Store checkout
checkoutStore.set(id, checkout);
return checkout;
}
export async function getCheckout(id: string): Promise<CheckoutSession | null> {
return checkoutStore.get(id) || null;
}
export async function updateCheckout(
id: string,
request: UpdateCheckoutRequest,
capabilities: string[]
): Promise<CheckoutSession | null> {
const checkout = checkoutStore.get(id);
if (!checkout) return null;
// Check if checkout can be modified
if (['completed', 'canceled'].includes(checkout.status)) {
throw new Error('Checkout cannot be modified in current state');
}
// Apply updates
if (request.line_items) {
checkout.line_items = request.line_items;
recalculateTotals(checkout);
}
if (request.buyer) {
checkout.buyer = { ...checkout.buyer, ...request.buyer };
}
// Update metadata
checkout.updated_at = new Date().toISOString();
checkout.ucp.capabilities = capabilities;
checkout.status = determineStatus(checkout);
checkout.messages = generateMessages(checkout);
checkoutStore.set(id, checkout);
return checkout;
}
export async function completeCheckout(
id: string,
paymentData: Record<string, unknown>,
capabilities: string[]
): Promise<CheckoutSession | null> {
const checkout = checkoutStore.get(id);
if (!checkout) return null;
if (checkout.status !== 'ready_for_complete') {
throw new Error('Checkout is not ready for completion');
}
checkout.status = 'complete_in_progress';
checkout.updated_at = new Date().toISOString();
checkoutStore.set(id, checkout);
try {
// Process payment
await processPayment(checkout, paymentData);
checkout.status = 'completed';
checkout.payment.status = 'captured';
checkout.updated_at = new Date().toISOString();
checkoutStore.set(id, checkout);
// Emit order event if order capability enabled
if (capabilities.includes('dev.ucp.shopping.order')) {
await emitOrderCreated(checkout);
}
return checkout;
} catch (error) {
checkout.status = 'incomplete';
checkout.payment.status = 'failed';
checkout.messages.push({
code: 'payment_failed',
severity: 'recoverable',
message: error instanceof Error ? error.message : 'Payment processing failed',
});
checkout.updated_at = new Date().toISOString();
checkoutStore.set(id, checkout);
return checkout;
}
}
function determineStatus(checkout: CheckoutSession): CheckoutStatus {
// Check for missing required fields
const missingFields: string[] = [];
if (!checkout.buyer?.email) {
missingFields.push('buyer.email');
}
// Check fulfillment if extension enabled
if (checkout.fulfillment && !checkout.fulfillment.selected_option) {
missingFields.push('fulfillment.selected_option');
}
if (missingFields.length > 0) {
return 'incomplete';
}
// Check if buyer input needed
if (checkout.messages.some(m => m.severity === 'requires_buyer_input')) {
return 'requires_escalation';
}
return 'ready_for_complete';
}
function generateMessages(checkout: CheckoutSession): CheckoutSession['messages'] {
const messages: CheckoutSession['messages'] = [];
if (!checkout.buyer?.email) {
messages.push({
code: 'missing_email',
severity: 'recoverable',
message: 'Buyer email is required',
field: 'buyer.email',
});
}
return messages;
}
function recalculateTotals(checkout: CheckoutSession): void {
const subtotal = checkout.line_items.reduce((sum, item) => sum + item.total_price, 0);
checkout.totals.subtotal = subtotal;
checkout.totals.tax = calculateTax(subtotal);
checkout.totals.grand_total =
subtotal + checkout.totals.tax + checkout.totals.shipping - checkout.totals.discount;
checkout.payment.amount_due = checkout.totals.grand_total;
}
function calculateTax(subtotal: number): number {
// Implement your tax calculation logic
return Math.round(subtotal * 0.08); // Example: 8% tax
}
function getPaymentHandlers(capabilities: string[]): CheckoutSession['payment']['handlers'] {
// Return configured payment handlers
return config.payment_handlers.map(id => ({
id,
type: 'tokenization',
}));
}
async function processPayment(
checkout: CheckoutSession,
paymentData: Record<string, unknown>
): Promise<void> {
// Validate handler_id against advertised handlers
const handlerId = paymentData.handler_id as string;
if (!config.payment_handlers.includes(handlerId)) {
throw new Error(`Unknown payment handler: ${handlerId}`);
}
// Implement payment processing based on handler
// This is where you integrate with Stripe, etc.
}
async function emitOrderCreated(checkout: CheckoutSession): Promise<void> {
// Implement order webhook emission
// See lib/ucp/webhooks/sender.ts
}
lib/ucp/negotiation.ts
/**
* UCP Capability Negotiation
* Generated by /ucp scaffold
*/
import config from '@/../ucp.config.json';
interface UCPAgentInfo {
profile: string;
}
interface NegotiationResult {
capabilities: string[];
version: string;
}
/**
* Parse UCP-Agent header (RFC 8941 dictionary syntax)
* Example: profile="https://platform.example.com/.well-known/ucp"
*/
export function parseUCPAgent(header: string | null): UCPAgentInfo | null {
if (!header) return null;
const profileMatch = header.match(/profile="([^"]+)"/);
if (!profileMatch) return null;
return { profile: profileMatch[1] };
}
/**
* Negotiate capabilities between business and platform
*/
export async function negotiateCapabilities(
platformProfileUrl?: string
): Promise<NegotiationResult> {
// Business capabilities
const businessCapabilities = new Set([
...config.capabilities.core,
...config.capabilities.extensions,
]);
if (!platformProfileUrl) {
// No platform profile - return all business capabilities
return {
capabilities: Array.from(businessCapabilities),
version: config.ucp_version,
};
}
try {
// Fetch platform profile
const response = await fetch(platformProfileUrl, {
headers: { Accept: 'application/json' },
});
if (!response.ok) {
console.warn(`Failed to fetch platform profile: ${response.status}`);
return {
capabilities: Array.from(businessCapabilities),
version: config.ucp_version,
};
}
const platformProfile = await response.json();
// Validate namespace authority
const profileUrl = new URL(platformProfileUrl);
// Platform controls its own domain - trust it
// Compute intersection
const platformCapabilities = new Set(
platformProfile.ucp?.capabilities?.map((c: { name: string }) => c.name) || []
);
const intersection = [...businessCapabilities].filter(c =>
platformCapabilities.has(c)
);
// Version negotiation - accept platform version <= business version
const platformVersion = platformProfile.ucp?.version;
if (platformVersion && platformVersion > config.ucp_version) {
throw new Error('version_unsupported');
}
return {
capabilities: intersection,
version: config.ucp_version,
};
} catch (error) {
console.error('Capability negotiation failed:', error);
// Fall back to business capabilities
return {
capabilities: Array.from(businessCapabilities),
version: config.ucp_version,
};
}
}
lib/ucp/response.ts
/**
* UCP Response Helpers
* Generated by /ucp scaffold
*/
import { NextResponse } from 'next/server';
import type { NegotiationResult } from './negotiation';
/**
* Wrap a response with UCP metadata
*/
export function wrapResponse<T extends { ucp?: unknown }>(
data: T,
negotiation: NegotiationResult,
status: number = 200
): NextResponse {
// Ensure ucp metadata is present
const response = {
.
…(truncated)
1---
2name: ucp
3description: >-
4 Expert-level implementation assistant for the Universal Commerce Protocol
5 (UCP). Provides comprehensive tooling for adding UCP support to Next.js
6 ecommerce codebases — from initial consultation through full implementation,
7 testing, and validation.
8arguments:
9 Optional sub-command: init | consult | plan | gaps | scaffold | validate | profile | test | docs
10user_invocable: true
11metadata:
12 source: https://skillmd.com/skills/vercel-labs/ucp
13---
14
15# UCP Skill — Universal Commerce Protocol Implementation
16
17## Core Principles
18
191. **Edge runtime is NOT USED** — Only Node.js (default) or Bun (opt-in) runtimes
202. **Interactive error handling** — When ambiguous, ask the user how to proceed
213. **Config-driven** — All decisions persist in `ucp.config.json`
224. **Spec-grounded** — All implementations reference the canonical UCP specification
235. **Next.js conventions** — Follow App Router patterns for code organization
246. **Deep analysis** — Use AST parsing and data flow tracing for gap detection
25
26---
27
28## Spec Repository Handling
29
30### Location Priority
31Check in this order:
321. `./ucp/` — User's local copy (use as-is)
332. `./.ucp-spec/` — Previously cloned spec (update it)
343. Neither exists — Clone fresh
35
36### Clone Procedure
37When cloning is needed:
38```bash
39git clone --depth 1 https://github.com/Universal-Commerce-Protocol/ucp.git .ucp-spec
40```
41
42If HTTPS fails, try SSH:
43```bash
44git clone --depth 1 git@github.com:Universal-Commerce-Protocol/ucp.git .ucp-spec
45```
46
47### Update Procedure
48When `./.ucp-spec/` exists:
49```bash
50cd .ucp-spec && git pull && cd ..
51```
52
53### Gitignore Management
54After cloning, ensure `.ucp-spec/` is in `.gitignore`:
55- Read `.gitignore` if it exists
56- Check if `.ucp-spec/` or `.ucp-spec` is already listed
57- If not, append `.ucp-spec/` on a new line
58
59### Spec File Locations (read on demand)
60```
61docs/specification/overview.md
62docs/specification/checkout.md
63docs/specification/checkout-rest.md
64docs/specification/checkout-mcp.md
65docs/specification/checkout-a2a.md
66docs/specification/embedded-checkout.md
67docs/specification/order.md
68docs/specification/fulfillment.md
69docs/specification/discount.md
70docs/specification/buyer-consent.md
71docs/specification/identity-linking.md
72docs/specification/ap2-mandates.md
73docs/specification/payment-handler-guide.md
74docs/specification/tokenization-guide.md
75spec/services/shopping/rest.openapi.json
76spec/services/shopping/mcp.openrpc.json
77spec/services/shopping/embedded.openrpc.json
78spec/handlers/tokenization/openapi.json
79spec/schemas/shopping/*
80spec/discovery/profile_schema.json
81```
82
83---
84
85## Configuration File
86
87### Location
88`./ucp.config.json` at project root
89
90### Schema
91```json
92{
93 "$schema": "./ucp.config.schema.json",
94 "ucp_version": "2026-01-11",
95 "roles": ["business"],
96 "runtime": "nodejs",
97 "capabilities": {
98 "core": ["dev.ucp.shopping.checkout"],
99 "extensions": []
100 },
101 "transports": ["rest"],
102 "transport_priority": ["rest", "mcp", "a2a", "embedded"],
103 "payment_handlers": [],
104 "features": {
105 "ap2_mandates": false,
106 "identity_linking": false,
107 "multi_destination_fulfillment": false
108 },
109 "domain": "",
110 "existing_apis": {},
111 "policy_urls": {
112 "privacy": "",
113 "terms": "",
114 "refunds": "",
115 "shipping": ""
116 },
117 "scaffold_depth": "full",
118 "generated_files": [],
119 "answers": {},
120 "deployment": {
121 "platform": "vercel",
122 "region": "iad1",
123 "mcp": {
124 "enabled": false,
125 "max_duration": 60
126 }
127 }
128}
129```
130
131### Field Descriptions
132| Field | Type | Description |
133|-------|------|-------------|
134| `ucp_version` | string | UCP spec version (date-based) |
135| `roles` | string[] | One or more of: `business`, `platform`, `payment_provider`, `host_embedded` |
136| `runtime` | string | `nodejs` (default) or `bun` |
137| `capabilities.core` | string[] | Required capabilities to implement |
138| `capabilities.extensions` | string[] | Optional extensions to implement |
139| `transports` | string[] | Enabled transports: `rest`, `mcp`, `a2a`, `embedded` |
140| `transport_priority` | string[] | Order to implement transports |
141| `payment_handlers` | string[] | Payment handler IDs to support |
142| `features.ap2_mandates` | boolean | Enable AP2 mandate signing |
143| `features.identity_linking` | boolean | Enable OAuth identity linking |
144| `features.multi_destination_fulfillment` | boolean | Enable multi-destination shipping |
145| `domain` | string | Business domain for `/.well-known/ucp` |
146| `existing_apis` | object | Map of existing API endpoints to analyze |
147| `policy_urls` | object | URLs for privacy, terms, refunds, shipping policies |
148| `scaffold_depth` | string | `types` \| `scaffolding` \| `full` |
149| `generated_files` | string[] | Files created by scaffold (for tracking) |
150| `answers` | object | Raw answers to qualifying questions |
151
152---
153
154## Sub-command: (no argument)
155
156### Trigger
157User runs `/ucp` with no sub-command
158
159### Behavior
160Display help listing all available sub-commands:
161
162```
163UCP Skill — Universal Commerce Protocol Implementation
164
165Available commands:
166 /ucp init — Initialize UCP in this project (clone spec, create config)
167 /ucp consult — Full consultation: answer qualifying questions, build roadmap
168 /ucp plan — Generate detailed implementation plan
169 /ucp gaps — Analyze existing code against UCP requirements
170 /ucp scaffold — Generate full working UCP implementation
171 /ucp validate — Validate implementation against UCP schemas
172 /ucp profile — Generate /.well-known/ucp discovery profile
173 /ucp test — Generate unit tests for UCP handlers
174 /ucp docs — Generate internal documentation
175
176Typical workflow:
177 /ucp init → /ucp consult → /ucp plan → /ucp scaffold → /ucp profile → /ucp test → /ucp validate
178
179Configuration: ./ucp.config.json
180Spec location: ./ucp/ or ./.ucp-spec/
181```
182
183---
184
185## Sub-command: init
186
187### Trigger
188User runs `/ucp init`
189
190### Purpose
191Bootstrap UCP in a project: clone spec, create config, ask essential questions.
192
193### Procedure
194
195#### Step 1: Check/Clone Spec Repository
1961. Check if `./ucp/` exists
197 - If yes: "Found local UCP spec at ./ucp/"
1982. If not, check if `./.ucp-spec/` exists
199 - If yes: Run `git pull` to update
200 - If no: Clone the repo (see Spec Repository Handling)
2013. After cloning, add `.ucp-spec/` to `.gitignore`
202
203#### Step 2: Check for Existing Config
2041. Check if `./ucp.config.json` exists
2052. If yes, ask: "Config file exists. Overwrite, merge, or abort?"
206 - Overwrite: Delete and create fresh
207 - Merge: Keep existing values as defaults
208 - Abort: Stop init
209
210#### Step 3: Ask Essential Questions (4 questions)
211
212**Q1: What role(s) are you implementing?**
213- Business (merchant of record)
214- Platform (consumer app or agent)
215- Payment credential provider
216- Host embedding checkout
217- Multiple (specify)
218
219If user selects multiple roles, WARN:
220> "Implementing multiple roles is unusual. This is typically for marketplace/aggregator scenarios. Are you sure?"
221
222**Q2: What runtime will you use?**
223- Node.js (recommended, stable)
224- Bun (opt-in, experimental)
225
226NOTE: If user mentions Edge, respond:
227> "Edge runtime is not supported for UCP implementations. Please choose Node.js or Bun."
228
229**Q3: What is your business domain?**
230- The domain that will host `/.well-known/ucp`
231- Example: `shop.example.com`
232
233**Q4: Which transports do you need at launch?**
234- REST (recommended baseline)
235- MCP (Model Context Protocol)
236- A2A (Agent-to-Agent)
237- Embedded (iframe checkout)
238
239#### Step 4: Create Config File
240Create `./ucp.config.json` with:
241- Answers from essential questions
242- Sensible defaults for other fields
243- `ucp_version` set to latest from spec
244
245#### Step 5: Output Ready Message
246```
247UCP initialized successfully!
248
249Config: ./ucp.config.json
250Spec: ./.ucp-spec/ (or ./ucp/)
251Role: {role}
252Domain: {domain}
253
254Next steps:
255 /ucp consult — Complete full consultation (recommended)
256 /ucp plan — Skip to implementation planning
257 /ucp gaps — Analyze existing code first
258```
259
260---
261
262## Sub-command: consult
263
264### Trigger
265User runs `/ucp consult`
266
267### Purpose
268Walk through all 12 qualifying questions, update config, produce implementation roadmap.
269
270### Prerequisites
271- Config file must exist (run `/ucp init` first)
272- Spec must be available
273
274### Procedure
275
276#### Step 1: Load Existing Config
277Read `./ucp.config.json` and use existing answers as defaults.
278
279#### Step 2: Walk Through 12 Qualifying Questions
280
281Ask each question. If already answered in config, show current value and ask to confirm or change.
282
283**Q1: Are we implementing the business side, the platform side, or both?**
284- Map to `roles` in config
285- If both/multiple, warn about unusual scenario
286
287**Q2: Which UCP version and which capabilities/extensions are in scope?**
288- Read available versions from spec
289- Present capability options:
290 - Core: `dev.ucp.shopping.checkout` (required)
291 - Extensions:
292 - `dev.ucp.shopping.fulfillment`
293 - `dev.ucp.shopping.discount`
294 - `dev.ucp.shopping.buyer_consent`
295 - `dev.ucp.shopping.ap2_mandate`
296 - `dev.ucp.shopping.order`
297 - `dev.ucp.common.identity_linking`
298
299**Q3: Which payment handlers do we need?**
300- Wallets (Apple Pay, Google Pay)
301- PSP tokenization (Stripe, Adyen, etc.)
302- Custom handler
303- None yet (decide later)
304
305**Q4: Do we need AP2 mandates and signing key infrastructure?**
306- Yes → set `features.ap2_mandates: true`
307- No → set `features.ap2_mandates: false`
308- If yes, explain: "You'll need to provide JWS signing keys (ES256 recommended)"
309
310**Q5: Do we need fulfillment options and multi-group/multi-destination support?**
311- No fulfillment needed
312- Single destination only
313- Multi-destination support → set `features.multi_destination_fulfillment: true`
314
315**Q6: Do we need discounts, buyer consent capture, or identity linking?**
316- Discounts → add `dev.ucp.shopping.discount` to extensions
317- Buyer consent → add `dev.ucp.shopping.buyer_consent` to extensions
318- Identity linking → add `dev.ucp.common.identity_linking`, set `features.identity_linking: true`
319
320**Q7: What are the existing checkout and order APIs we should map to UCP?**
321- Ask for existing endpoint paths
322- Store in `existing_apis` object
323- Examples: `/api/checkout`, `/api/cart`, `/api/orders`
324
325**Q8: What are the required policy URLs?**
326- Privacy policy URL
327- Terms of service URL
328- Refund policy URL
329- Shipping policy URL
330- Store in `policy_urls` object
331
332**Q9: What authentication model is required for checkout endpoints?**
333- None (anonymous checkout)
334- API key
335- OAuth 2.0
336- Session-based
337- Store in `answers.authentication_model`
338
339**Q10: Who will receive order webhooks and what event cadence is required?**
340- Webhook URL for order events
341- Event types needed: `order.created`, `order.updated`, `order.fulfilled`, `order.canceled`
342- Store in `answers.webhook_config`
343
344**Q11: Do we need to support MCP, A2A, or embedded checkout at launch?**
345- Confirm/update `transports` array
346- Set `transport_priority` order
347
348**Q12: What is the business domain that will host /.well-known/ucp?**
349- Confirm/update `domain` field
350
351#### Step 3: Update Config
352Write all answers to `./ucp.config.json`
353
354#### Step 4: Generate Implementation Roadmap
355Based on answers, produce a roadmap:
356
357```
358UCP Implementation Roadmap
359==========================
360
361Role: Business (merchant)
362Version: 2026-01-11
363Domain: shop.example.com
364
365Capabilities to implement:
366 ✓ dev.ucp.shopping.checkout (core)
367 ✓ dev.ucp.shopping.fulfillment
368 ✓ dev.ucp.shopping.discount
369 ○ dev.ucp.shopping.order
370
371Transports (in order):
372 1. REST
373 2. MCP
374
375Payment handlers:
376 - Stripe tokenization
377
378Key implementation tasks:
379 1. Create /.well-known/ucp discovery profile
380 2. Implement checkout session endpoints (create, get, update, complete)
381 3. Implement fulfillment options logic
382 4. Implement discount code application
383 5. Set up payment handler integration
384 6. Implement order webhooks
385 7. Add MCP transport layer
386
387Estimated files to create/modify: ~15-20
388
389Run /ucp plan for detailed file-by-file plan.
390```
391
392---
393
394## Sub-command: plan
395
396### Trigger
397User runs `/ucp plan`
398
399### Purpose
400Generate detailed implementation plan with specific files and order of operations.
401
402### Prerequisites
403- Config file must exist with completed consultation
404- Spec must be available
405
406### Procedure
407
408#### Step 1: Load Config and Spec
409- Read `./ucp.config.json`
410- Read relevant spec files based on capabilities/transports
411
412#### Step 2: Analyze Existing Codebase Structure
413- Detect Next.js version (App Router vs Pages Router)
414- Find existing API routes
415- Find existing lib/utils structure
416- Find existing types/schemas
417- Identify package manager (npm, yarn, pnpm, bun)
418
419#### Step 3: Generate File Plan
420For each capability/transport, list files to create/modify.
421
422**Example output:**
423
424```
425UCP Implementation Plan
426=======================
427
428Phase 1: Core Types and Schemas
429-------------------------------
430CREATE lib/ucp/types/checkout.ts
431 - CheckoutSession interface
432 - LineItem, Totals, Payment types
433 - Status enum
434
435CREATE lib/ucp/types/index.ts
436 - Re-export all types
437
438CREATE lib/ucp/schemas/checkout.ts
439 - Zod schemas for validation
440
441Phase 2: Discovery Profile
442--------------------------
443CREATE app/.well-known/ucp/route.ts
444 - GET handler returning profile JSON
445 - Read capabilities from config
446
447CREATE lib/ucp/profile.ts
448 - Profile generation logic
449
450Phase 3: Checkout Endpoints (REST)
451----------------------------------
452CREATE app/api/ucp/checkout/route.ts
453 - POST: Create checkout session
454 - Capability negotiation logic
455
456CREATE app/api/ucp/checkout/[id]/route.ts
457 - GET: Retrieve checkout
458 - PATCH: Update checkout
459 - POST: Complete checkout (action=complete)
460
461CREATE lib/ucp/handlers/checkout.ts
462 - Business logic for checkout operations
463 - State machine implementation
464
465Phase 4: Fulfillment Extension
466------------------------------
467CREATE lib/ucp/handlers/fulfillment.ts
468 - Fulfillment options calculation
469 - Destination validation
470
471MODIFY lib/ucp/handlers/checkout.ts
472 - Integrate fulfillment into checkout response
473
474Phase 5: Discount Extension
475---------------------------
476CREATE lib/ucp/handlers/discount.ts
477 - Discount code validation
478 - Applied discount calculation
479
480MODIFY lib/ucp/handlers/checkout.ts
481 - Integrate discounts into checkout
482
483Phase 6: Payment Integration
484----------------------------
485CREATE lib/ucp/handlers/payment.ts
486 - Payment handler registry
487 - payment_data processing
488
489CREATE lib/ucp/handlers/stripe.ts
490 - Stripe-specific tokenization
491
492Phase 7: Order Webhooks
493-----------------------
494CREATE lib/ucp/handlers/order.ts
495 - Order event emission
496 - Webhook signing (JWS)
497
498CREATE lib/ucp/webhooks/sender.ts
499 - Webhook delivery with retries
500
501Phase 8: MCP Transport (if enabled)
502-----------------------------------
503CREATE lib/ucp/transports/mcp.ts
504 - MCP tool definitions
505 - JSON-RPC handlers
506
507Dependencies to install:
508------------------------
509 zod — Schema validation
510 jose — JWS signing (if AP2/webhooks enabled)
511
512Run /ucp scaffold to generate these files.
513```
514
515#### Step 4: Save Plan to Config
516Store the plan in `answers.implementation_plan` for scaffold reference.
517
518---
519
520## Sub-command: gaps
521
522### Trigger
523User runs `/ucp gaps`
524
525### Purpose
526Deep analysis of existing codebase against UCP requirements. Uses AST parsing and data flow tracing.
527
528### Prerequisites
529- Config file should exist (for role/capability context)
530- Spec must be available
531
532### Procedure
533
534#### Step 1: Load Context
535- Read config for declared capabilities
536- Read relevant spec files
537
538#### Step 2: Discover Existing Code
539Scan for:
540- API routes (`app/api/**`, `pages/api/**`)
541- Checkout-related files (search for "checkout", "cart", "order")
542- Payment handling code
543- Webhook implementations
544
545#### Step 3: Deep Analysis (AST-based)
546For each relevant file:
547- Parse AST
548- Trace data flow for checkout objects
549- Identify existing patterns
550
551**Analyze against UCP requirements:**
552
553| Requirement | Status | Finding |
554|-------------|--------|---------|
555| Discovery profile at /.well-known/ucp | MISSING | No route found |
556| Checkout session creation | PARTIAL | Found /api/checkout but missing UCP fields |
557| Status lifecycle | MISSING | No status state machine |
558| Capability negotiation | MISSING | No UCP-Agent header handling |
559| Payment handler support | PARTIAL | Stripe exists but not UCP-compliant |
560| Response metadata (ucp object) | MISSING | Responses don't include ucp field |
561
562#### Step 4: Generate Gap Report
563
564```
565UCP Gap Analysis Report
566=======================
567
568Existing codebase: Next.js 14 (App Router)
569Target role: Business
570Target capabilities: checkout, fulfillment, discount
571
572CRITICAL GAPS (must fix)
573------------------------
574[GAP-001] Missing discovery profile
575 - Required: /.well-known/ucp endpoint
576 - Status: NOT FOUND
577 - Fix: Create app/.well-known/ucp/route.ts
578
579[GAP-002] Missing UCP response envelope
580 - Required: All responses must include `ucp` object with version/capabilities
581 - Found: app/api/checkout/route.ts returns raw checkout data
582 - Fix: Wrap responses with UCP metadata
583
584[GAP-003] Missing capability negotiation
585 - Required: Read UCP-Agent header, compute intersection
586 - Found: No header processing in checkout routes
587 - Fix: Add middleware or handler logic
588
589PARTIAL IMPLEMENTATIONS
590-----------------------
591[PARTIAL-001] Checkout session exists but non-compliant
592 - File: app/api/checkout/route.ts
593 - Missing: id, status, currency, totals.grand_total, links, payment fields
594 - Has: line_items (needs schema adjustment)
595
596[PARTIAL-002] Payment integration exists
597 - File: lib/stripe.ts
598 - Issue: Direct Stripe API, not UCP payment_data flow
599 - Fix: Wrap with UCP payment handler abstraction
600
601COMPLIANT AREAS
602---------------
603[OK] Policy URLs configured in existing checkout
604[OK] HTTPS enforced
605[OK] Idempotency key support in POST handlers
606
607RECOMMENDATIONS
608---------------
6091. Start with /ucp scaffold to generate compliant structure
6102. Migrate existing checkout logic into new handlers
6113. Run /ucp validate after migration
612
613Total: 3 critical gaps, 2 partial, 3 compliant
614```
615
616---
617
618## Sub-command: scaffold
619
620### Trigger
621User runs `/ucp scaffold`
622
623### Purpose
624Generate full working UCP implementation based on config and plan.
625
626### Prerequisites
627- Config file must exist
628- Plan should exist (run `/ucp plan` first, or scaffold will generate one)
629
630### Procedure
631
632#### Step 1: Confirm Scaffold Depth
633Ask user:
634> "What level of code generation do you want?"
635> - **types**: TypeScript interfaces and Zod schemas only
636> - **scaffolding**: Structure with TODO markers for business logic
637> - **full**: Complete working implementation (recommended)
638
639Store choice in `config.scaffold_depth`
640
641#### Step 2: Check Dependencies
642Identify required packages based on config:
643- `zod` — Always needed
644- `jose` — If AP2 mandates or webhook signing enabled
645- `uuid` — For session ID generation
646
647Ask before installing:
648> "The following packages are required: zod, jose, uuid"
649> "Install now? (npm install / bun add)"
650
651If yes, run appropriate install command.
652
653#### Step 3: Generate Code
654Generate files according to plan. For each file:
6551. Create parent directories if needed
6562. Write file content
6573. Track in `config.generated_files`
658
659### Code Generation Templates
660
661#### lib/ucp/types/checkout.ts
662```typescript
663/**
664 * UCP Checkout Types
665 * Generated by /ucp scaffold
666 * Spec: {spec_version}
667 */
668
669export type CheckoutStatus =
670 | 'incomplete'
671 | 'requires_escalation'
672 | 'ready_for_complete'
673 | 'complete_in_progress'
674 | 'completed'
675 | 'canceled';
676
677export type MessageSeverity =
678 | 'recoverable'
679 | 'requires_buyer_input'
680 | 'requires_buyer_review';
681
682export interface UCPMetadata {
683 version: string;
684 capabilities: string[];
685}
686
687export interface LineItem {
688 id: string;
689 name: string;
690 quantity: number;
691 unit_price: number;
692 total_price: number;
693 currency: string;
694 // Extension fields added based on config
695}
696
697export interface Totals {
698 subtotal: number;
699 tax: number;
700 shipping: number;
701 discount: number;
702 grand_total: number;
703 currency: string;
704}
705
706export interface PaymentInfo {
707 status: 'pending' | 'authorized' | 'captured' | 'failed';
708 handlers: PaymentHandler[];
709 amount_due: number;
710 currency: string;
711}
712
713export interface PaymentHandler {
714 id: string;
715 type: string;
716 config?: Record<string, unknown>;
717}
718
719export interface CheckoutMessage {
720 code: string;
721 severity: MessageSeverity;
722 message: string;
723 field?: string;
724}
725
726export interface CheckoutLinks {
727 self: string;
728 continue_url?: string;
729 privacy_policy: string;
730 terms_of_service: string;
731 refund_policy?: string;
732 shipping_policy?: string;
733}
734
735export interface CheckoutSession {
736 ucp: UCPMetadata;
737 id: string;
738 status: CheckoutStatus;
739 currency: string;
740 line_items: LineItem[];
741 totals: Totals;
742 payment: PaymentInfo;
743 links: CheckoutLinks;
744 messages: CheckoutMessage[];
745 expires_at: string;
746 created_at: string;
747 updated_at: string;
748 // Extension fields populated based on negotiated capabilities
749 buyer?: BuyerInfo;
750 fulfillment?: FulfillmentInfo;
751 discounts?: DiscountInfo;
752}
753
754export interface BuyerInfo {
755 email?: string;
756 phone?: string;
757 name?: string;
758 // consent fields if buyer_consent extension enabled
759}
760
761// Conditional types based on extensions...
762```
763
764#### lib/ucp/schemas/checkout.ts
765```typescript
766/**
767 * UCP Checkout Zod Schemas
768 * Generated by /ucp scaffold
769 */
770
771import { z } from 'zod';
772
773export const LineItemSchema = z.object({
774 id: z.string(),
775 name: z.string(),
776 quantity: z.number().int().positive(),
777 unit_price: z.number().int(), // minor units (cents)
778 total_price: z.number().int(),
779 currency: z.string().length(3),
780});
781
782export const TotalsSchema = z.object({
783 subtotal: z.number().int(),
784 tax: z.number().int(),
785 shipping: z.number().int(),
786 discount: z.number().int(),
787 grand_total: z.number().int(),
788 currency: z.string().length(3),
789});
790
791export const CreateCheckoutRequestSchema = z.object({
792 line_items: z.array(LineItemSchema).min(1),
793 currency: z.string().length(3),
794 buyer: z.object({
795 email: z.string().email().optional(),
796 phone: z.string().optional(),
797 }).optional(),
798 // Extension fields...
799});
800
801export const UpdateCheckoutRequestSchema = z.object({
802 line_items: z.array(LineItemSchema).optional(),
803 buyer: z.object({
804 email: z.string().email().optional(),
805 phone: z.string().optional(),
806 }).optional(),
807 // Extension fields...
808});
809
810export const CompleteCheckoutRequestSchema = z.object({
811 action: z.literal('complete'),
812 payment_data: z.record(z.unknown()),
813});
814
815export type CreateCheckoutRequest = z.infer<typeof CreateCheckoutRequestSchema>;
816export type UpdateCheckoutRequest = z.infer<typeof UpdateCheckoutRequestSchema>;
817export type CompleteCheckoutRequest = z.infer<typeof CompleteCheckoutRequestSchema>;
818```
819
820#### app/.well-known/ucp/route.ts
821```typescript
822/**
823 * UCP Discovery Profile Endpoint
824 * GET /.well-known/ucp
825 * Generated by /ucp scaffold
826 */
827
828import { NextResponse } from 'next/server';
829import { generateProfile } from '@/lib/ucp/profile';
830
831export const runtime = 'nodejs'; // Edge runtime is not supported
832
833export async function GET() {
834 const profile = generateProfile();
835
836 return NextResponse.json(profile, {
837 headers: {
838 'Cache-Control': 'public, max-age=3600',
839 'Content-Type': 'application/json',
840 },
841 });
842}
843```
844
845#### lib/ucp/profile.ts
846```typescript
847/**
848 * UCP Discovery Profile Generator
849 * Generated by /ucp scaffold
850 */
851
852import config from '@/../ucp.config.json';
853
854export interface UCPProfile {
855 ucp: {
856 version: string;
857 services: Record<string, ServiceDefinition>;
858 capabilities: CapabilityDefinition[];
859 };
860 payment?: {
861 handlers: PaymentHandlerDefinition[];
862 };
863 signing_keys?: JsonWebKey[];
864}
865
866interface ServiceDefinition {
867 version: string;
868 spec: string;
869 rest?: { schema: string; endpoint: string };
870 mcp?: { schema: string; endpoint: string };
871 a2a?: { endpoint: string };
872 embedded?: { schema: string };
873}
874
875interface CapabilityDefinition {
876 name: string;
877 version: string;
878 spec: string;
879 schema: string;
880 extends?: string;
881 config?: Record<string, unknown>;
882}
883
884interface PaymentHandlerDefinition {
885 id: string;
886 type: string;
887 spec: string;
888 config_schema: string;
889}
890
891export function generateProfile(): UCPProfile {
892 const baseUrl = `https://${config.domain}`;
893
894 const profile: UCPProfile = {
895 ucp: {
896 version: config.ucp_version,
897 services: {
898 'dev.ucp.shopping': {
899 version: config.ucp_version,
900 spec: 'https://ucp.dev/spec/services/shopping',
901 ...(config.transports.includes('rest') && {
902 rest: {
903 schema: 'https://ucp.dev/spec/services/shopping/rest.openapi.json',
904 endpoint: `${baseUrl}/api/ucp`,
905 },
906 }),
907 ...(config.transports.includes('mcp') && {
908 mcp: {
909 schema: 'https://ucp.dev/spec/services/shopping/mcp.openrpc.json',
910 endpoint: `${baseUrl}/api/ucp/mcp`,
911 },
912 }),
913 ...(config.transports.includes('a2a') && {
914 a2a: {
915 endpoint: `${baseUrl}/api/ucp/a2a`,
916 },
917 }),
918 ...(config.transports.includes('embedded') && {
919 embedded: {
920 schema: 'https://ucp.dev/spec/services/shopping/embedded.openrpc.json',
921 },
922 }),
923 },
924 },
925 capabilities: buildCapabilities(config),
926 },
927 };
928
929 if (config.payment_handlers.length > 0) {
930 profile.payment = {
931 handlers: config.payment_handlers.map(buildHandlerDefinition),
932 };
933 }
934
935 return profile;
936}
937
938function buildCapabilities(config: typeof import('@/../ucp.config.json')): CapabilityDefinition[] {
939 const capabilities: CapabilityDefinition[] = [];
940
941 // Core checkout capability (always present)
942 capabilities.push({
943 name: 'dev.ucp.shopping.checkout',
944 version: config.ucp_version,
945 spec: 'https://ucp.dev/spec/capabilities/checkout',
946 schema: 'https://ucp.dev/spec/schemas/shopping/checkout.json',
947 });
948
949 // Add extensions based on config
950 for (const ext of config.capabilities.extensions) {
951 capabilities.push(buildExtensionCapability(ext, config));
952 }
953
954 return capabilities;
955}
956
957function buildExtensionCapability(
958 extension: string,
959 config: typeof import('@/../ucp.config.json')
960): CapabilityDefinition {
961 // Map extension names to spec URLs
962 const extMap: Record<string, { spec: string; schema: string; extends?: string }> = {
963 'dev.ucp.shopping.fulfillment': {
964 spec: 'https://ucp.dev/spec/capabilities/fulfillment',
965 schema: 'https://ucp.dev/spec/schemas/shopping/fulfillment.json',
966 extends: 'dev.ucp.shopping.checkout',
967 },
968 'dev.ucp.shopping.discount': {
969 spec: 'https://ucp.dev/spec/capabilities/discount',
970 schema: 'https://ucp.dev/spec/schemas/shopping/discount.json',
971 extends: 'dev.ucp.shopping.checkout',
972 },
973 'dev.ucp.shopping.buyer_consent': {
974 spec: 'https://ucp.dev/spec/capabilities/buyer-consent',
975 schema: 'https://ucp.dev/spec/schemas/shopping/buyer-consent.json',
976 extends: 'dev.ucp.shopping.checkout',
977 },
978 'dev.ucp.shopping.order': {
979 spec: 'https://ucp.dev/spec/capabilities/order',
980 schema: 'https://ucp.dev/spec/schemas/shopping/order.json',
981 config: {
982 webhook_url: config.answers?.webhook_config?.url,
983 },
984 },
985 'dev.ucp.common.identity_linking': {
986 spec: 'https://ucp.dev/spec/capabilities/identity-linking',
987 schema: 'https://ucp.dev/spec/schemas/common/identity-linking.json',
988 },
989 };
990
991 const def = extMap[extension];
992 return {
993 name: extension,
994 version: config.ucp_version,
995 spec: def?.spec || '',
996 schema: def?.schema || '',
997 ...(def?.extends && { extends: def.extends }),
998 ...(def?.config && { config: def.config }),
999 };
1000}
1001
1002function buildHandlerDefinition(handlerId: string): PaymentHandlerDefinition {
1003 // Map known handlers
1004 const handlerMap: Record<string, Omit<PaymentHandlerDefinition, 'id'>> = {
1005 stripe: {
1006 type: 'tokenization',
1007 spec: 'https://ucp.dev/spec/handlers/stripe',
1008 config_schema: 'https://ucp.dev/spec/handlers/stripe/config.json',
1009 },
1010 // Add more handlers as needed
1011 };
1012
1013 const def = handlerMap[handlerId] || {
1014 type: 'custom',
1015 spec: '',
1016 config_schema: '',
1017 };
1018
1019 return { id: handlerId, ...def };
1020}
1021```
1022
1023#### app/api/ucp/checkout/route.ts
1024```typescript
1025/**
1026 * UCP Checkout Session Endpoint
1027 * POST /api/ucp/checkout - Create checkout session
1028 * Generated by /ucp scaffold
1029 */
1030
1031import { NextRequest, NextResponse } from 'next/server';
1032import { createCheckout } from '@/lib/ucp/handlers/checkout';
1033import { CreateCheckoutRequestSchema } from '@/lib/ucp/schemas/checkout';
1034import { negotiateCapabilities, parseUCPAgent } from '@/lib/ucp/negotiation';
1035import { wrapResponse, errorResponse } from '@/lib/ucp/response';
1036
1037export const runtime = 'nodejs'; // Edge runtime is not supported
1038
1039export async function POST(request: NextRequest) {
1040 try {
1041 // Parse UCP-Agent header for capability negotiation
1042 const ucpAgent = parseUCPAgent(request.headers.get('UCP-Agent'));
1043
1044 // Negotiate capabilities
1045 const negotiation = await negotiateCapabilities(ucpAgent?.profile);
1046
1047 // Parse and validate request body
1048 const body = await request.json();
1049 const parsed = CreateCheckoutRequestSchema.safeParse(body);
1050
1051 if (!parsed.success) {
1052 return errorResponse(400, 'invalid_request', parsed.error.message);
1053 }
1054
1055 // Get idempotency key
1056 const idempotencyKey = request.headers.get('Idempotency-Key');
1057
1058 // Create checkout session
1059 const checkout = await createCheckout(parsed.data, {
1060 capabilities: negotiation.capabilities,
1061 idempotencyKey,
1062 });
1063
1064 return wrapResponse(checkout, negotiation, 201);
1065 } catch (error) {
1066 console.error('Checkout creation failed:', error);
1067 return errorResponse(500, 'internal_error', 'Failed to create checkout session');
1068 }
1069}
1070```
1071
1072#### lib/ucp/handlers/checkout.ts
1073```typescript
1074/**
1075 * UCP Checkout Handler
1076 * Core business logic for checkout operations
1077 * Generated by /ucp scaffold
1078 */
1079
1080import { randomUUID } from 'crypto';
1081import type {
1082 CheckoutSession,
1083 CheckoutStatus,
1084 CreateCheckoutRequest,
1085 UpdateCheckoutRequest,
1086} from '@/lib/ucp/types/checkout';
1087import config from '@/../ucp.config.json';
1088
1089// In-memory store for demo - replace with your database
1090const checkoutStore = new Map<string, CheckoutSession>();
1091
1092interface CreateCheckoutOptions {
1093 capabilities: string[];
1094 idempotencyKey?: string | null;
1095}
1096
1097export async function createCheckout(
1098 request: CreateCheckoutRequest,
1099 options: CreateCheckoutOptions
1100): Promise<CheckoutSession> {
1101 const id = randomUUID();
1102 const now = new Date().toISOString();
1103 const expiresAt = new Date(Date.now() + 30 * 60 * 1000).toISOString(); // 30 min
1104
1105 // Calculate totals
1106 const subtotal = request.line_items.reduce((sum, item) => sum + item.total_price, 0);
1107 const tax = calculateTax(subtotal); // Implement your tax logic
1108 const shipping = 0; // Set by fulfillment extension
1109 const discount = 0; // Set by discount extension
1110
1111 const checkout: CheckoutSession = {
1112 ucp: {
1113 version: config.ucp_version,
1114 capabilities: options.capabilities,
1115 },
1116 id,
1117 status: 'incomplete',
1118 currency: request.currency,
1119 line_items: request.line_items.map((item, index) => ({
1120 ...item,
1121 id: item.id || `line_${index}`,
1122 })),
1123 totals: {
1124 subtotal,
1125 tax,
1126 shipping,
1127 discount,
1128 grand_total: subtotal + tax + shipping - discount,
1129 currency: request.currency,
1130 },
1131 payment: {
1132 status: 'pending',
1133 handlers: getPaymentHandlers(options.capabilities),
1134 amount_due: subtotal + tax + shipping - discount,
1135 currency: request.currency,
1136 },
1137 links: {
1138 self: `https://${config.domain}/api/ucp/checkout/${id}`,
1139 continue_url: `https://${config.domain}/checkout/${id}`,
1140 privacy_policy: config.policy_urls.privacy,
1141 terms_of_service: config.policy_urls.terms,
1142 ...(config.policy_urls.refunds && { refund_policy: config.policy_urls.refunds }),
1143 ...(config.policy_urls.shipping && { shipping_policy: config.policy_urls.shipping }),
1144 },
1145 messages: [],
1146 expires_at: expiresAt,
1147 created_at: now,
1148 updated_at: now,
1149 };
1150
1151 // Add buyer info if provided
1152 if (request.buyer) {
1153 checkout.buyer = request.buyer;
1154 }
1155
1156 // Validate checkout state and set appropriate status
1157 checkout.status = determineStatus(checkout);
1158 checkout.messages = generateMessages(checkout);
1159
1160 // Store checkout
1161 checkoutStore.set(id, checkout);
1162
1163 return checkout;
1164}
1165
1166export async function getCheckout(id: string): Promise<CheckoutSession | null> {
1167 return checkoutStore.get(id) || null;
1168}
1169
1170export async function updateCheckout(
1171 id: string,
1172 request: UpdateCheckoutRequest,
1173 capabilities: string[]
1174): Promise<CheckoutSession | null> {
1175 const checkout = checkoutStore.get(id);
1176 if (!checkout) return null;
1177
1178 // Check if checkout can be modified
1179 if (['completed', 'canceled'].includes(checkout.status)) {
1180 throw new Error('Checkout cannot be modified in current state');
1181 }
1182
1183 // Apply updates
1184 if (request.line_items) {
1185 checkout.line_items = request.line_items;
1186 recalculateTotals(checkout);
1187 }
1188
1189 if (request.buyer) {
1190 checkout.buyer = { ...checkout.buyer, ...request.buyer };
1191 }
1192
1193 // Update metadata
1194 checkout.updated_at = new Date().toISOString();
1195 checkout.ucp.capabilities = capabilities;
1196 checkout.status = determineStatus(checkout);
1197 checkout.messages = generateMessages(checkout);
1198
1199 checkoutStore.set(id, checkout);
1200 return checkout;
1201}
1202
1203export async function completeCheckout(
1204 id: string,
1205 paymentData: Record<string, unknown>,
1206 capabilities: string[]
1207): Promise<CheckoutSession | null> {
1208 const checkout = checkoutStore.get(id);
1209 if (!checkout) return null;
1210
1211 if (checkout.status !== 'ready_for_complete') {
1212 throw new Error('Checkout is not ready for completion');
1213 }
1214
1215 checkout.status = 'complete_in_progress';
1216 checkout.updated_at = new Date().toISOString();
1217 checkoutStore.set(id, checkout);
1218
1219 try {
1220 // Process payment
1221 await processPayment(checkout, paymentData);
1222
1223 checkout.status = 'completed';
1224 checkout.payment.status = 'captured';
1225 checkout.updated_at = new Date().toISOString();
1226 checkoutStore.set(id, checkout);
1227
1228 // Emit order event if order capability enabled
1229 if (capabilities.includes('dev.ucp.shopping.order')) {
1230 await emitOrderCreated(checkout);
1231 }
1232
1233 return checkout;
1234 } catch (error) {
1235 checkout.status = 'incomplete';
1236 checkout.payment.status = 'failed';
1237 checkout.messages.push({
1238 code: 'payment_failed',
1239 severity: 'recoverable',
1240 message: error instanceof Error ? error.message : 'Payment processing failed',
1241 });
1242 checkout.updated_at = new Date().toISOString();
1243 checkoutStore.set(id, checkout);
1244 return checkout;
1245 }
1246}
1247
1248function determineStatus(checkout: CheckoutSession): CheckoutStatus {
1249 // Check for missing required fields
1250 const missingFields: string[] = [];
1251
1252 if (!checkout.buyer?.email) {
1253 missingFields.push('buyer.email');
1254 }
1255
1256 // Check fulfillment if extension enabled
1257 if (checkout.fulfillment && !checkout.fulfillment.selected_option) {
1258 missingFields.push('fulfillment.selected_option');
1259 }
1260
1261 if (missingFields.length > 0) {
1262 return 'incomplete';
1263 }
1264
1265 // Check if buyer input needed
1266 if (checkout.messages.some(m => m.severity === 'requires_buyer_input')) {
1267 return 'requires_escalation';
1268 }
1269
1270 return 'ready_for_complete';
1271}
1272
1273function generateMessages(checkout: CheckoutSession): CheckoutSession['messages'] {
1274 const messages: CheckoutSession['messages'] = [];
1275
1276 if (!checkout.buyer?.email) {
1277 messages.push({
1278 code: 'missing_email',
1279 severity: 'recoverable',
1280 message: 'Buyer email is required',
1281 field: 'buyer.email',
1282 });
1283 }
1284
1285 return messages;
1286}
1287
1288function recalculateTotals(checkout: CheckoutSession): void {
1289 const subtotal = checkout.line_items.reduce((sum, item) => sum + item.total_price, 0);
1290 checkout.totals.subtotal = subtotal;
1291 checkout.totals.tax = calculateTax(subtotal);
1292 checkout.totals.grand_total =
1293 subtotal + checkout.totals.tax + checkout.totals.shipping - checkout.totals.discount;
1294 checkout.payment.amount_due = checkout.totals.grand_total;
1295}
1296
1297function calculateTax(subtotal: number): number {
1298 // Implement your tax calculation logic
1299 return Math.round(subtotal * 0.08); // Example: 8% tax
1300}
1301
1302function getPaymentHandlers(capabilities: string[]): CheckoutSession['payment']['handlers'] {
1303 // Return configured payment handlers
1304 return config.payment_handlers.map(id => ({
1305 id,
1306 type: 'tokenization',
1307 }));
1308}
1309
1310async function processPayment(
1311 checkout: CheckoutSession,
1312 paymentData: Record<string, unknown>
1313): Promise<void> {
1314 // Validate handler_id against advertised handlers
1315 const handlerId = paymentData.handler_id as string;
1316 if (!config.payment_handlers.includes(handlerId)) {
1317 throw new Error(`Unknown payment handler: ${handlerId}`);
1318 }
1319
1320 // Implement payment processing based on handler
1321 // This is where you integrate with Stripe, etc.
1322}
1323
1324async function emitOrderCreated(checkout: CheckoutSession): Promise<void> {
1325 // Implement order webhook emission
1326 // See lib/ucp/webhooks/sender.ts
1327}
1328```
1329
1330#### lib/ucp/negotiation.ts
1331```typescript
1332/**
1333 * UCP Capability Negotiation
1334 * Generated by /ucp scaffold
1335 */
1336
1337import config from '@/../ucp.config.json';
1338
1339interface UCPAgentInfo {
1340 profile: string;
1341}
1342
1343interface NegotiationResult {
1344 capabilities: string[];
1345 version: string;
1346}
1347
1348/**
1349 * Parse UCP-Agent header (RFC 8941 dictionary syntax)
1350 * Example: profile="https://platform.example.com/.well-known/ucp"
1351 */
1352export function parseUCPAgent(header: string | null): UCPAgentInfo | null {
1353 if (!header) return null;
1354
1355 const profileMatch = header.match(/profile="([^"]+)"/);
1356 if (!profileMatch) return null;
1357
1358 return { profile: profileMatch[1] };
1359}
1360
1361/**
1362 * Negotiate capabilities between business and platform
1363 */
1364export async function negotiateCapabilities(
1365 platformProfileUrl?: string
1366): Promise<NegotiationResult> {
1367 // Business capabilities
1368 const businessCapabilities = new Set([
1369 ...config.capabilities.core,
1370 ...config.capabilities.extensions,
1371 ]);
1372
1373 if (!platformProfileUrl) {
1374 // No platform profile - return all business capabilities
1375 return {
1376 capabilities: Array.from(businessCapabilities),
1377 version: config.ucp_version,
1378 };
1379 }
1380
1381 try {
1382 // Fetch platform profile
1383 const response = await fetch(platformProfileUrl, {
1384 headers: { Accept: 'application/json' },
1385 });
1386
1387 if (!response.ok) {
1388 console.warn(`Failed to fetch platform profile: ${response.status}`);
1389 return {
1390 capabilities: Array.from(businessCapabilities),
1391 version: config.ucp_version,
1392 };
1393 }
1394
1395 const platformProfile = await response.json();
1396
1397 // Validate namespace authority
1398 const profileUrl = new URL(platformProfileUrl);
1399 // Platform controls its own domain - trust it
1400
1401 // Compute intersection
1402 const platformCapabilities = new Set(
1403 platformProfile.ucp?.capabilities?.map((c: { name: string }) => c.name) || []
1404 );
1405
1406 const intersection = [...businessCapabilities].filter(c =>
1407 platformCapabilities.has(c)
1408 );
1409
1410 // Version negotiation - accept platform version <= business version
1411 const platformVersion = platformProfile.ucp?.version;
1412 if (platformVersion && platformVersion > config.ucp_version) {
1413 throw new Error('version_unsupported');
1414 }
1415
1416 return {
1417 capabilities: intersection,
1418 version: config.ucp_version,
1419 };
1420 } catch (error) {
1421 console.error('Capability negotiation failed:', error);
1422 // Fall back to business capabilities
1423 return {
1424 capabilities: Array.from(businessCapabilities),
1425 version: config.ucp_version,
1426 };
1427 }
1428}
1429```
1430
1431#### lib/ucp/response.ts
1432```typescript
1433/**
1434 * UCP Response Helpers
1435 * Generated by /ucp scaffold
1436 */
1437
1438import { NextResponse } from 'next/server';
1439import type { NegotiationResult } from './negotiation';
1440
1441/**
1442 * Wrap a response with UCP metadata
1443 */
1444export function wrapResponse<T extends { ucp?: unknown }>(
1445 data: T,
1446 negotiation: NegotiationResult,
1447 status: number = 200
1448): NextResponse {
1449 // Ensure ucp metadata is present
1450 const response = {
1451 ...data,
1452 ucp: {
1453 version: negotiation.version,
1454 capabilities: negotiation.capabilities,
1455 },
1456 };
1457
1458 return NextResponse.json(response, { status });
1459}
1460
1461/**
1462 * Create an error response
1463 */
1464export function errorResponse(
1465 status: number,
1466 code: string,
1467 message: string,
1468 details?: Record<string, unknown>
1469): NextResponse {
1470 return NextResponse.json(
1471 {
1472 error: {
1473 code,
1474 message,
1475 ...(details && { details }),
1476 },
1477 },
1478 { status }
1479 );
1480}
1481```
1482
1483### MCP Transport Code Templates (using mcp-handler)
1484
1485When MCP transport is enabled in config, generate these additional files.
1486
1487#### Dependencies for MCP Transport
1488```bash
1489npm install mcp-handler @modelcontextprotocol/sdk@1.25.2 zod
1490```
1491
1492**IMPORTANT:** Use `@modelcontextprotocol/sdk@1.25.2` or later — earlier versions have security vulnerabilities.
1493
1494#### app/api/mcp/[transport]/route.ts
1495```typescript
1496/**
1497 * UCP MCP Transport Endpoint
1498 * Model Context Protocol server for UCP checkout operations
1499 * Generated by /ucp scaffold
1500 *
1501 * Supports:
1502 * - Streamable HTTP transport (direct client connection)
1503 * - SSE transport (via mcp-remote bridge)
1504 *
1505 * @see https://github.com/vercel/mcp-handler
1506 */
1507
1508import { createMcpHandler } from 'mcp-handler';
1509import { z } from 'zod';
1510import {
1511 createCheckout,
1512 getCheckout,
1513 updateCheckout,
1514 completeCheckout,
1515} from '@/lib/ucp/handlers/checkout';
1516import { negotiateCapabilities } from '@/lib/ucp/negotiation';
1517import { generateProfile } from '@/lib/ucp/profile';
1518import config from '@/../ucp.config.json';
1519
1520export const runtime = 'nodejs'; // Edge runtime is not supported
1521
1522const handler = createMcpHandler(
1523 (server) => {
1524 // =========================================================================
1525 // UCP Discovery
1526 // =========================================================================
1527
1528 server.registerTool(
1529 'ucp_get_profile',
1530 {
1531 title: 'Get UCP Profile',
1532 description: 'Retrieve the UCP discovery profile for this business. Returns supported capabilities, transports, and payment handlers.',
1533 inputSchema: {},
1534 },
1535 async () => {
1536 const profile = generateProfile();
1537 return {
1538 content: [
1539 {
1540 type: 'text',
1541 text: JSON.stringify(profile, null, 2),
1542 },
1543 ],
1544 };
1545 }
1546 );
1547
1548 // =========================================================================
1549 // Checkout Session Management
1550 // =========================================================================
1551
1552 server.registerTool(
1553 'ucp_create_checkout',
1554 {
1555 title: 'Create Checkout Session',
1556 description: 'Create a new UCP checkout session with line items. Returns a checkout session with id, status, totals, and available payment handlers.',
1557 inputSchema: {
1558 line_items: z.array(
1559 z.object({
1560 id: z.string().optional().describe('Unique identifier for the line item'),
1561 name: z.string().describe('Product name'),
1562 quantity: z.number().int().positive().describe('Quantity ordered'),
1563 unit_price: z.number().int().describe('Price per unit in minor units (cents)'),
1564 total_price: z.number().int().describe('Total price for this line (quantity * unit_price)'),
1565 currency: z.string().length(3).describe('ISO 4217 currency code'),
1566 })
1567 ).min(1).describe('Array of items in the checkout'),
1568 currency: z.string().length(3).describe('ISO 4217 currency code for the checkout'),
1569 buyer: z.object({
1570 email: z.string().email().optional().describe('Buyer email address'),
1571 phone: z.string().optional().describe('Buyer phone number'),
1572 name: z.string().optional().describe('Buyer full name'),
1573 }).optional().describe('Buyer information'),
1574 platform_profile_url: z.string().url().optional().describe('URL to the platform UCP profile for capability negotiation'),
1575 },
1576 },
1577 async ({ line_items, currency, buyer, platform_profile_url }) => {
1578 try {
1579 // Negotiate capabilities
1580 const negotiation = await negotiateCapabilities(platform_profile_url);
1581
1582 const checkout = await createCheckout(
1583 { line_items, currency, buyer },
1584 { capabilities: negotiation.capabilities }
1585 );
1586
1587 return {
1588 content: [
1589 {
1590 type: 'text',
1591 text: JSON.stringify(checkout, null, 2),
1592 },
1593 ],
1594 };
1595 } catch (error) {
1596 return {
1597 content: [
1598 {
1599 type: 'text',
1600 text: JSON.stringify({
1601 error: {
1602 code: 'checkout_creation_failed',
1603 message: error instanceof Error ? error.message : 'Unknown error',
1604 },
1605 }),
1606 },
1607 ],
1608 isError: true,
1609 };
1610 }
1611 }
1612 );
1613
1614 server.registerTool(
1615 'ucp_get_checkout',
1616 {
1617 title: 'Get Checkout Session',
1618 description: 'Retrieve an existing checkout session by ID. Returns the current state including status, line items, totals, and messages.',
1619 inputSchema: {
1620 checkout_id: z.string().describe('The checkout session ID'),
1621 },
1622 },
1623 async ({ checkout_id }) => {
1624 const checkout = await getCheckout(checkout_id);
1625
1626 if (!checkout) {
1627 return {
1628 content: [
1629 {
1630 type: 'text',
1631 text: JSON.stringify({
1632 error: {
1633 code: 'checkout_not_found',
1634 message: `Checkout session ${checkout_id} not found`,
1635 },
1636 }),
1637 },
1638 ],
1639 isError: true,
1640 };
1641 }
1642
1643 return {
1644 content: [
1645 {
1646 type: 'text',
1647 text: JSON.stringify(checkout, null, 2),
1648 },
1649 ],
1650 };
1651 }
1652 );
1653
1654 server.registerTool(
1655 'ucp_update_checkout',
1656 {
1657 title: 'Update Checkout Session',
1658 description: 'Update an existing checkout session. Can modify line items, buyer info, fulfillment selection, or discount codes.',
1659 inputSchema: {
1660 checkout_id: z.string().describe('The checkout session ID'),
1661 line_items: z.array(
1662 z.object({
1663 id: z.string(),
1664 name: z.string(),
1665 quantity: z.number().int().positive(),
1666 unit_price: z.number().int(),
1667 total_price: z.number().int(),
1668 currency: z.string().length(3),
1669 })
1670 ).optional().describe('Updated line items (replaces existing)'),
1671 buyer: z.object({
1672 email: z.string().email().optional(),
1673 phone: z.string().optional(),
1674 name: z.string().optional(),
1675 }).optional().describe('Updated buyer information (merged with existing)'),
1676 fulfillment: z.object({
1677 selected_option_id: z.string().optional().describe('ID of selected fulfillment option'),
1678 destination: z.object({
1679 address_line1: z.string(),
1680 address_line2: z.string().optional(),
1681 city: z.string(),
1682 state: z.string().optional(),
1683 postal_code: z.string(),
1684 country: z.string().length(2),
1685 }).optional().describe('Shipping destination address'),
1686 }).optional().describe('Fulfillment selection (if fulfillment extension enabled)'),
1687 discount_codes: z.array(z.string()).optional().describe('Discount codes to apply (if discount extension enabled)'),
1688 platform_profile_url: z.string().url().optional().describe('Platform profile URL for capability negotiation'),
1689 },
1690 },
1691 async ({ checkout_id, line_items, buyer, fulfillment, discount_codes, platform_profile_url }) => {
1692 try {
1693 const negotiation = await negotiateCapabilities(platform_profile_url);
1694
1695 const checkout = await updateCheckout(
1696 checkout_id,
1697 { line_items, buyer },
1698 negotiation.capabilities
1699 );
1700
1701 if (!checkout) {
1702 return {
1703 content: [
1704 {
1705 type: 'text',
1706 text: JSON.stringify({
1707 error: {
1708 code: 'checkout_not_found',
1709 message: `Checkout session ${checkout_id} not found`,
1710 },
1711 }),
1712 },
1713 ],
1714 isError: true,
1715 };
1716 }
1717
1718 return {
1719 content: [
1720 {
1721 type: 'text',
1722 text: JSON.stringify(checkout, null, 2),
1723 },
1724 ],
1725 };
1726 } catch (error) {
1727 return {
1728 content: [
1729 {
1730 type: 'text',
1731 text: JSON.stringify({
1732 error: {
1733 code: 'checkout_update_failed',
1734 message: error instanceof Error ? error.message : 'Unknown error',
1735 },
1736 }),
1737 },
1738 ],
1739 isError: true,
1740 };
1741 }
1742 }
1743 );
1744
1745 server.registerTool(
1746 'ucp_complete_checkout',
1747 {
1748 title: 'Complete Checkout',
1749 description: 'Complete a checkout session with payment. Checkout must be in ready_for_complete status. Returns the completed checkout or error messages.',
1750 inputSchema: {
1751 checkout_id: z.string().describe('The checkout session ID'),
1752 payment_data: z.object({
1753 handler_id: z.string().describe('Payment handler ID (must match one from checkout.payment.handlers)'),
1754 token: z.string().optional().describe('Payment token from tokenization handler'),
1755 instrument: z.record(z.unknown()).optional().describe('Payment instrument data'),
1756 }).describe('Payment data from the selected payment handler'),
1757 platform_profile_url: z.string().url().optional().describe('Platform profile URL'),
1758 },
1759 },
1760 async ({ checkout_id, payment_data, platform_profile_url }) => {
1761 try {
1762 const negotiation = await negotiateCapabilities(platform_profile_url);
1763
1764 const checkout = await completeCheckout(
1765 checkout_id,
1766 payment_data,
1767 negotiation.capabilities
1768 );
1769
1770 if (!checkout) {
1771 return {
1772 content: [
1773 {
1774 type: 'text',
1775 text: JSON.stringify({
1776 error: {
1777 code: 'checkout_not_found',
1778 message: `Checkout session ${checkout_id} not found`,
1779 },
1780 }),
1781 },
1782 ],
1783 isError: true,
1784 };
1785 }
1786
1787 return {
1788 content: [
1789 {
1790 type: 'text',
1791 text: JSON.stringify(checkout, null, 2),
1792 },
1793 ],
1794 };
1795 } catch (error) {
1796 return {
1797 content: [
1798 {
1799 type: 'text',
1800 text: JSON.stringify({
1801 error: {
1802 code: 'checkout_completion_failed',
1803 message: error instanceof Error ? error.message : 'Unknown error',
1804 },
1805 }),
1806 },
1807 ],
1808 isError: true,
1809 };
1810 }
1811 }
1812 );
1813
1814 // =========================================================================
1815 // Fulfillment Extension Tools (if enabled)
1816 // =========================================================================
1817
1818 if (config.capabilities.extensions.includes('dev.ucp.shopping.fulfillment')) {
1819 server.registerTool(
1820 'ucp_get_fulfillment_options',
1821 {
1822 title: 'Get Fulfillment Options',
1823 description: 'Get available fulfillment/shipping options for a checkout. Requires a destination address.',
1824 inputSchema: {
1825 checkout_id: z.string().describe('The checkout session ID'),
1826 destination: z.object({
1827 address_line1: z.string(),
1828 address_line2: z.string().optional(),
1829 city: z.string(),
1830 state: z.string().optional(),
1831 postal_code: z.string(),
1832 country: z.string().length(2).describe('ISO 3166-1 alpha-2 country code'),
1833 }).describe('Shipping destination'),
1834 },
1835 },
1836 async ({ checkout_id, destination }) => {
1837 // Implementation would call fulfillment handler
1838 return {
1839 content: [
1840 {
1841 type: 'text',
1842 text: JSON.stringify({
1843 checkout_id,
1844 destination,
1845 options: [
1846 {
1847 id: 'standard',
1848 name: 'Standard Shipping',
1849 description: '5-7 business days',
1850 price: 599,
1851 currency: 'USD',
1852 },
1853 {
1854 id: 'express',
1855 name: 'Express Shipping',
1856 description: '2-3 business days',
1857 price: 1299,
1858 currency: 'USD',
1859 },
1860 ],
1861 }, null, 2),
1862 },
1863 ],
1864 };
1865 }
1866 );
1867 }
1868
1869 // =========================================================================
1870 // Discount Extension Tools (if enabled)
1871 // =========================================================================
1872
1873 if (config.capabilities.extensions.includes('dev.ucp.shopping.discount')) {
1874 server.registerTool(
1875 'ucp_validate_discount',
1876 {
1877 title: 'Validate Discount Code',
1878 description: 'Validate a discount code before applying to checkout. Returns discount details or rejection reason.',
1879 inputSchema: {
1880 checkout_id: z.string().describe('The checkout session ID'),
1881 code: z.string().describe('The discount code to validate'),
1882 },
1883 },
1884 async ({ checkout_id, code }) => {
1885 // Implementation would call discount handler
1886 return {
1887 content: [
1888 {
1889 type: 'text',
1890 text: JSON.stringify({
1891 valid: true,
1892 code,
1893 discount: {
1894 type: 'percentage',
1895 value: 10,
1896 description: '10% off your order',
1897 },
1898 }, null, 2),
1899 },
1900 ],
1901 };
1902 }
1903 );
1904 }
1905
1906 // =========================================================================
1907 // Payment Handler Tools
1908 // =========================================================================
1909
1910 server.registerTool(
1911 'ucp_get_payment_handlers',
1912 {
1913 title: 'Get Payment Handlers',
1914 description: 'Get available payment handlers for a checkout session. Use this to determine how to collect payment information.',
1915 inputSchema: {
1916 checkout_id: z.string().describe('The checkout session ID'),
1917 },
1918 },
1919 async ({ checkout_id }) => {
1920 const checkout = await getCheckout(checkout_id);
1921
1922 if (!checkout) {
1923 return {
1924 content: [
1925 {
1926 type: 'text',
1927 text: JSON.stringify({
1928 error: {
1929 code: 'checkout_not_found',
1930 message: `Checkout session ${checkout_id} not found`,
1931 },
1932 }),
1933 },
1934 ],
1935 isError: true,
1936 };
1937 }
1938
1939 return {
1940 content: [
1941 {
1942 type: 'text',
1943 text: JSON.stringify({
1944 checkout_id,
1945 amount_due: checkout.payment.amount_due,
1946 currency: checkout.payment.currency,
1947 handlers: checkout.payment.handlers,
1948 }, null, 2),
1949 },
1950 ],
1951 };
1952 }
1953 );
1954 },
1955 {
1956 // Server metadata
1957 name: 'ucp-shopping',
1958 version: config.ucp_version,
1959 },
1960 {
1961 // Handler options
1962 basePath: '/api/mcp',
1963 maxDuration: 60,
1964 verboseLogs: process.env.NODE_ENV === 'development',
1965 }
1966);
1967
1968export { handler as GET, handler as POST };
1969```
1970
1971#### lib/ucp/transports/mcp-tools.ts
1972```typescript
1973/**
1974 * UCP MCP Tool Definitions
1975 * Reusable tool schemas for MCP transport
1976 * Generated by /ucp scaffold
1977 */
1978
1979import { z } from 'zod';
1980
1981// Common schemas
1982export const LineItemSchema = z.object({
1983 id: z.string().optional(),
1984 name: z.string(),
1985 quantity: z.number().int().positive(),
1986 unit_price: z.number().int(),
1987 total_price: z.number().int(),
1988 currency: z.string().length(3),
1989});
1990
1991export const BuyerSchema = z.object({
1992 email: z.string().email().optional(),
1993 phone: z.string().optional(),
1994 name: z.string().optional(),
1995});
1996
1997export const AddressSchema = z.object({
1998 address_line1: z.string(),
1999 address_line2: z.string().optional(),
2000 city: z.string(),
2001 state: z.string().optional(),
2002 postal_code: z.string(),
2003 country: z.string().length(2),
2004});
2005
2006export const PaymentDataSchema = z.object({
2007 handler_id: z.string(),
2008 token: z.string().optional(),
2009 instrument: z.record(z.unknown()).optional(),
2010});
2011
2012// Tool definitions for documentation
2013export const UCP_MCP_TOOLS = {
2014 ucp_get_profile: {
2015 description: 'Get UCP discovery profile',
2016 input: {},
2017 },
2018 ucp_create_checkout: {
2019 description: 'Create a new checkout session',
2020 input: {
2021 line_items: 'Array of line items (required)',
2022 currency: 'ISO 4217 currency code (required)',
2023 buyer: 'Buyer information (optional)',
2024 platform_profile_url: 'Platform UCP profile URL (optional)',
2025 },
2026 },
2027 ucp_get_checkout: {
2028 description: 'Get checkout session by ID',
2029 input: {
2030 checkout_id: 'Checkout session ID (required)',
2031 },
2032 },
2033 ucp_update_checkout: {
2034 description: 'Update checkout session',
2035 input: {
2036 checkout_id: 'Checkout session ID (required)',
2037 line_items: 'Updated line items (optional)',
2038 buyer: 'Updated buyer info (optional)',
2039 fulfillment: 'Fulfillment selection (optional)',
2040 discount_codes: 'Discount codes to apply (optional)',
2041 },
2042 },
2043 ucp_complete_checkout: {
2044 description: 'Complete checkout with payment',
2045 input: {
2046 checkout_id: 'Checkout session ID (required)',
2047 payment_data: 'Payment handler data (required)',
2048 },
2049 },
2050 ucp_get_fulfillment_options: {
2051 description: 'Get shipping options (fulfillment extension)',
2052 input: {
2053 checkout_id: 'Checkout session ID (required)',
2054 destination: 'Shipping address (required)',
2055 },
2056 },
2057 ucp_validate_discount: {
2058 description: 'Validate discount code (discount extension)',
2059 input: {
2060 checkout_id: 'Checkout session ID (required)',
2061 code: 'Discount code (required)',
2062 },
2063 },
2064 ucp_get_payment_handlers: {
2065 description: 'Get available payment handlers',
2066 input: {
2067 checkout_id: 'Checkout session ID (required)',
2068 },
2069 },
2070} as const;
2071```
2072
2073---
2074
2075## Vercel Deployment
2076
2077### Deployment Configuration
2078
2079#### vercel.json
2080```json
2081{
2082 "framework": "nextjs",
2083 "regions": ["iad1"],
2084 "functions": {
2085 "app/api/mcp/[transport]/route.ts": {
2086 "maxDuration": 60
2087 },
2088 "app/api/ucp/**/*.ts": {
2089 "maxDuration": 30
2090 }
2091 },
2092 "headers": [
2093 {
2094 "source": "/.well-known/ucp",
2095 "headers": [
2096 {
2097 "key": "Cache-Control",
2098 "value": "public, max-age=3600"
2099 },
2100 {
2101 "key": "Content-Type",
2102 "value": "application/json"
2103 }
2104 ]
2105 }
2106 ]
2107}
2108```
2109
2110#### Environment Variables
2111Set these in Vercel Dashboard → Settings → Environment Variables:
2112
2113| Variable | Required | Description |
2114|----------|----------|-------------|
2115| `UCP_DOMAIN` | Yes | Production domain (e.g., `shop.example.com`) |
2116| `UCP_SIGNING_KEY` | If AP2 | JWS signing key (PEM or JWK) |
2117| `STRIPE_SECRET_KEY` | If Stripe | Stripe API secret key |
2118
2119#### next.config.js (MCP-optimized)
2120```javascript
2121/** @type {import('next').NextConfig} */
2122const nextConfig = {
2123 // Required for mcp-handler streaming
2124 experimental: {
2125 serverActions: {
2126 bodySizeLimit: '2mb',
2127 },
2128 },
2129
2130 // Ensure proper headers for MCP
2131 async headers() {
2132 return [
2133 {
2134 source: '/api/mcp/:path*',
2135 headers: [
2136 { key: 'Access-Control-Allow-Origin', value: '*' },
2137 { key: 'Access-Control-Allow-Methods', value: 'GET, POST, OPTIONS' },
2138 { key: 'Access-Control-Allow-Headers', value: 'Content-Type, Authorization' },
2139 ],
2140 },
2141 ];
2142 },
2143
2144 // Required for MCP streaming responses
2145 async rewrites() {
2146 return [];
2147 },
2148};
2149
2150module.exports = nextConfig;
2151```
2152
2153### MCP Client Configuration
2154
2155#### For Claude Desktop / Cursor / Windsurf
2156
2157**Option 1: Direct HTTP (if client supports streamable HTTP)**
2158Add to MCP client config:
2159```json
2160{
2161 "mcpServers": {
2162 "ucp-shopping": {
2163 "url": "https://your-domain.vercel.app/api/mcp"
2164 }
2165 }
2166}
2167```
2168
2169**Option 2: Via mcp-remote bridge (for stdio-only clients)**
2170```json
2171{
2172 "mcpServers": {
2173 "ucp-shopping": {
2174 "command": "npx",
2175 "args": ["-y", "mcp-remote", "https://your-domain.vercel.app/api/mcp"]
2176 }
2177 }
2178}
2179```
2180
2181### Testing MCP Deployment
2182
2183#### scripts/test-mcp.mjs
2184```javascript
2185#!/usr/bin/env node
2186/**
2187 * MCP Server Test Script
2188 * Usage: node scripts/test-mcp.mjs [deployment-url]
2189 */
2190
2191const deploymentUrl = process.argv[2] || 'http://localhost:3000';
2192
2193async function testMcpServer() {
2194 console.log(`Testing MCP server at ${deploymentUrl}/api/mcp\n`);
2195
2196 // Test 1: Get Profile
2197 console.log('1. Testing ucp_get_profile...');
2198 const profileResponse = await fetch(`${deploymentUrl}/api/mcp`, {
2199 method: 'POST',
2200 headers: { 'Content-Type': 'application/json' },
2201 body: JSON.stringify({
2202 jsonrpc: '2.0',
2203 id: 1,
2204 method: 'tools/call',
2205 params: {
2206 name: 'ucp_get_profile',
2207 arguments: {},
2208 },
2209 }),
2210 });
2211 const profileResult = await profileResponse.json();
2212 console.log(' Profile:', profileResult.result ? 'OK' : 'FAILED');
2213
2214 // Test 2: Create Checkout
2215 console.log('2. Testing ucp_create_checkout...');
2216 const createResponse = await fetch(`${deploymentUrl}/api/mcp`, {
2217 method: 'POST',
2218 headers: { 'Content-Type': 'application/json' },
2219 body: JSON.stringify({
2220 jsonrpc: '2.0',
2221 id: 2,
2222 method: 'tools/call',
2223 params: {
2224 name: 'ucp_create_checkout',
2225 arguments: {
2226 line_items: [
2227 {
2228 name: 'Test Product',
2229 quantity: 1,
2230 unit_price: 1000,
2231 total_price: 1000,
2232 currency: 'USD',
2233 },
2234 ],
2235 currency: 'USD',
2236 },
2237 },
2238 }),
2239 });
2240 const createResult = await createResponse.json();
2241 console.log(' Create:', createResult.result ? 'OK' : 'FAILED');
2242
2243 // Parse checkout ID for subsequent tests
2244 if (createResult.result?.content?.[0]?.text) {
2245 const checkout = JSON.parse(createResult.result.content[0].text);
2246 console.log(` Checkout ID: ${checkout.id}`);
2247 console.log(` Status: ${checkout.status}`);
2248
2249 // Test 3: Get Checkout
2250 console.log('3. Testing ucp_get_checkout...');
2251 const getResponse = await fetch(`${deploymentUrl}/api/mcp`, {
2252 method: 'POST',
2253 headers: { 'Content-Type': 'application/json' },
2254 body: JSON.stringify({
2255 jsonrpc: '2.0',
2256 id: 3,
2257 method: 'tools/call',
2258 params: {
2259 name: 'ucp_get_checkout',
2260 arguments: { checkout_id: checkout.id },
2261 },
2262 }),
2263 });
2264 const getResult = await getResponse.json();
2265 console.log(' Get:', getResult.result ? 'OK' : 'FAILED');
2266 }
2267
2268 console.log('\nMCP server tests completed.');
2269}
2270
2271testMcpServer().catch(console.error);
2272```
2273
2274### Vercel Deployment Checklist
2275
2276When running `/ucp scaffold` with Vercel deployment, verify:
2277
2278- [ ] `vercel.json` created with function timeouts
2279- [ ] Environment variables documented
2280- [ ] `next.config.js` updated for MCP streaming
2281- [ ] MCP route at `app/api/mcp/[transport]/route.ts`
2282- [ ] Test script at `scripts/test-mcp.mjs`
2283- [ ] `.env.example` updated with required variables
2284
2285### Post-Deployment Verification
2286
2287After deploying to Vercel:
2288
22891. **Check discovery profile:**
2290 ```bash
2291 curl https://your-domain.vercel.app/.well-known/ucp | jq .
2292 ```
2293
22942. **Test MCP endpoint:**
2295 ```bash
2296 node scripts/test-mcp.mjs https://your-domain.vercel.app
2297 ```
2298
22993. **Configure MCP client:**
2300 Add the server to Claude Desktop, Cursor, or your preferred MCP client.
2301
23024. **Verify in client:**
2303 Ask the AI to "list available UCP tools" — it should show the checkout tools.
2304
2305---
2306
2307### Post-Generation Steps
2308
2309#### Step 4: Update Config
2310After generation, update `ucp.config.json`:
2311- Add all created files to `generated_files` array
2312- Update `scaffold_depth` to reflect what was generated
2313
2314#### Step 5: Output Summary
2315```
2316UCP Scaffold Complete
2317=====================
2318
2319Generated files:
2320 CREATE lib/ucp/types/checkout.ts
2321 CREATE lib/ucp/types/index.ts
2322 CREATE lib/ucp/schemas/checkout.ts
2323 CREATE lib/ucp/profile.ts
2324 CREATE lib/ucp/negotiation.ts
2325 CREATE lib/ucp/response.ts
2326 CREATE lib/ucp/handlers/checkout.ts
2327 CREATE app/.well-known/ucp/route.ts
2328 CREATE app/api/ucp/checkout/route.ts
2329 CREATE app/api/ucp/checkout/[id]/route.ts
2330
2331MCP Transport (if enabled):
2332 CREATE app/api/mcp/[transport]/route.ts
2333 CREATE lib/ucp/transports/mcp-tools.ts
2334
2335Vercel Deployment:
2336 CREATE vercel.json
2337 CREATE scripts/test-mcp.mjs
2338 MODIFY next.config.js
2339
2340Dependencies installed:
2341 zod, jose, uuid
2342 mcp-handler, @modelcontextprotocol/sdk (if MCP enabled)
2343
2344Next steps:
2345 1. Review generated code and customize business logic
2346 2. Set environment variables in Vercel dashboard
2347 3. Deploy: vercel --prod
2348 4. Run /ucp profile to verify discovery profile
2349 5. Run /ucp test to generate unit tests
2350 6. Run /ucp validate to check compliance
2351 7. Configure MCP client with deployment URL
2352```
2353
2354---
2355
2356## Sub-command: validate
2357
2358### Trigger
2359User runs `/ucp validate`
2360
2361### Purpose
2362Validate the implementation against UCP JSON schemas.
2363
2364### Prerequisites
2365- Implementation must exist (run `/ucp scaffold` first)
2366- Spec must be available
2367
2368### Procedure
2369
2370#### Step 1: Load Schemas
2371Read JSON schemas from spec:
2372- `spec/schemas/shopping/checkout.json`
2373- `spec/schemas/shopping/fulfillment.json`
2374- `spec/schemas/shopping/discount.json`
2375- `spec/discovery/profile_schema.json`
2376
2377#### Step 2: Validate Discovery Profile
2378- Make request to `/.well-known/ucp` route (or read file directly)
2379- Validate against `profile_schema.json`
2380
2381#### Step 3: Validate Response Shapes
2382For each implemented endpoint:
2383- Generate sample request
2384- Execute handler (mock mode)
2385- Validate response against schema
2386
2387#### Step 4: Check Protocol Requirements
2388Verify:
2389- [ ] All responses include `ucp` object
2390- [ ] Status values are valid enum values
2391- [ ] Amounts are integers (minor units)
2392- [ ] Dates are RFC 3339 format
2393- [ ] Links are absolute HTTPS URLs
2394- [ ] Capability names follow reverse-DNS format
2395
2396#### Step 5: Output Report
2397```
2398UCP Validation Report
2399=====================
2400
2401Discovery Profile: PASS
2402 ✓ Schema valid
2403 ✓ Required fields present
2404 ✓ Service definitions valid
2405 ✓ Capability specs accessible
2406
2407Checkout Endpoints:
2408 POST /api/ucp/checkout
2409 ✓ Response schema valid
2410 ✓ UCP metadata present
2411 ✓ Status enum valid
2412
2413 GET /api/ucp/checkout/[id]
2414 ✓ Response schema valid
2415 ✓ Idempotent
2416
2417 PATCH /api/ucp/checkout/[id]
2418 ✓ Response schema valid
2419 ✓ Partial update works
2420
2421 POST /api/ucp/checkout/[id] (complete)
2422 ✓ Response schema valid
2423 ✓ State transition correct
2424
2425Protocol Requirements:
2426 ✓ Amounts in minor units
2427 ✓ Dates in RFC 3339
2428 ✓ HTTPS links
2429 ✓ Reverse-DNS capability names
2430
2431Overall: PASS (24/24 checks)
2432```
2433
2434---
2435
2436## Sub-command: profile
2437
2438### Trigger
2439User runs `/ucp profile`
2440
2441### Purpose
2442Generate and display the `/.well-known/ucp` discovery profile JSON.
2443
2444### Prerequisites
2445- Config must exist
2446
2447### Procedure
2448
2449#### Step 1: Generate Profile
2450Use the `generateProfile()` function from `lib/ucp/profile.ts` (or generate inline if not scaffolded yet).
2451
2452#### Step 2: Display Profile
2453Output the formatted JSON:
2454
2455```json
2456{
2457 "ucp": {
2458 "version": "2026-01-11",
2459 "services": {
2460 "dev.ucp.shopping": {
2461 "version": "2026-01-11",
2462 "spec": "https://ucp.dev/spec/services/shopping",
2463 "rest": {
2464 "schema": "https://ucp.dev/spec/services/shopping/rest.openapi.json",
2465 "endpoint": "https://shop.example.com/api/ucp"
2466 }
2467 }
2468 },
2469 "capabilities": [
2470 {
2471 "name": "dev.ucp.shopping.checkout",
2472 "version": "2026-01-11",
2473 "spec": "https://ucp.dev/spec/capabilities/checkout",
2474 "schema": "https://ucp.dev/spec/schemas/shopping/checkout.json"
2475 }
2476 ]
2477 }
2478}
2479```
2480
2481#### Step 3: Offer to Write File
2482Ask: "Write this to `public/.well-known/ucp` for static serving, or keep as dynamic route?"
2483
2484If static:
2485- Create `public/.well-known/ucp` (no extension, JSON content)
2486- Note: May need Next.js config for extensionless files
2487
2488---
2489
2490## Sub-command: test
2491
2492### Trigger
2493User runs `/ucp test`
2494
2495### Purpose
2496Generate unit tests for UCP handlers.
2497
2498### Prerequisites
2499- Implementation must exist
2500- Test framework detected (Jest, Vitest, etc.)
2501
2502### Procedure
2503
2504#### Step 1: Detect Test Framework
2505Look for:
2506- `jest.config.js` / `jest.config.ts` → Jest
2507- `vitest.config.js` / `vitest.config.ts` → Vitest
2508- `package.json` test script hints
2509
2510#### Step 2: Generate Test Files
2511For each handler, generate corresponding test file.
2512
2513#### Example: lib/ucp/handlers/__tests__/checkout.test.ts
2514```typescript
2515/**
2516 * UCP Checkout Handler Tests
2517 * Generated by /ucp test
2518 */
2519
2520import { describe, it, expect, beforeEach } from 'vitest'; // or jest
2521import {
2522 createCheckout,
2523 getCheckout,
2524 updateCheckout,
2525 completeCheckout,
2526} from '../checkout';
2527
2528describe('UCP Checkout Handler', () => {
2529 const validRequest = {
2530 line_items: [
2531 {
2532 id: 'item_1',
2533 name: 'Test Product',
2534 quantity: 1,
2535 unit_price: 1000,
2536 total_price: 1000,
2537 currency: 'USD',
2538 },
2539 ],
2540 currency: 'USD',
2541 };
2542
2543 describe('createCheckout', () => {
2544 it('creates a checkout with valid request', async () => {
2545 const checkout = await createCheckout(validRequest, {
2546 capabilities: ['dev.ucp.shopping.checkout'],
2547 });
2548
2549 expect(checkout.id).toBeDefined();
2550 expect(checkout.status).toBe('incomplete');
2551 expect(checkout.currency).toBe('USD');
2552 expect(checkout.line_items).toHaveLength(1);
2553 expect(checkout.ucp.version).toBeDefined();
2554 expect(checkout.ucp.capabilities).toContain('dev.ucp.shopping.checkout');
2555 });
2556
2557 it('calculates totals correctly', async () => {
2558 const checkout = await createCheckout(validRequest, {
2559 capabilities: ['dev.ucp.shopping.checkout'],
2560 });
2561
2562 expect(checkout.totals.subtotal).toBe(1000);
2563 expect(checkout.totals.grand_total).toBeGreaterThanOrEqual(checkout.totals.subtotal);
2564 });
2565
2566 it('sets expiration time', async () => {
2567 const checkout = await createCheckout(validRequest, {
2568 capabilities: ['dev.ucp.shopping.checkout'],
2569 });
2570
2571 expect(checkout.expires_at).toBeDefined();
2572 const expiresAt = new Date(checkout.expires_at);
2573 expect(expiresAt.getTime()).toBeGreaterThan(Date.now());
2574 });
2575
2576 it('includes required links', async () => {
2577 const checkout = await createCheckout(validRequest, {
2578 capabilities: ['dev.ucp.shopping.checkout'],
2579 });
2580
2581 expect(checkout.links.self).toContain(checkout.id);
2582 expect(checkout.links.privacy_policy).toBeDefined();
2583 expect(checkout.links.terms_of_service).toBeDefined();
2584 });
2585 });
2586
2587 describe('getCheckout', () => {
2588 it('retrieves existing checkout', async () => {
2589 const created = await createCheckout(validRequest, {
2590 capabilities: ['dev.ucp.shopping.checkout'],
2591 });
2592
2593 const retrieved = await getCheckout(created.id);
2594 expect(retrieved).toEqual(created);
2595 });
2596
2597 it('returns null for non-existent checkout', async () => {
2598 const retrieved = await getCheckout('non-existent-id');
2599 expect(retrieved).toBeNull();
2600 });
2601 });
2602
2603 describe('updateCheckout', () => {
2604 it('updates line items', async () => {
2605 const created = await createCheckout(validRequest, {
2606 capabilities: ['dev.ucp.shopping.checkout'],
2607 });
2608
2609 const updated = await updateCheckout(
2610 created.id,
2611 {
2612 line_items: [
2613 { ...validRequest.line_items[0], quantity: 2, total_price: 2000 },
2614 ],
2615 },
2616 ['dev.ucp.shopping.checkout']
2617 );
2618
2619 expect(updated?.totals.subtotal).toBe(2000);
2620 });
2621
2622 it('updates buyer info', async () => {
2623 const created = await createCheckout(validRequest, {
2624 capabilities: ['dev.ucp.shopping.checkout'],
2625 });
2626
2627 const updated = await updateCheckout(
2628 created.id,
2629 { buyer: { email: 'test@example.com' } },
2630 ['dev.ucp.shopping.checkout']
2631 );
2632
2633 expect(updated?.buyer?.email).toBe('test@example.com');
2634 });
2635
2636 it('transitions to ready_for_complete when requirements met', async () => {
2637 const created = await createCheckout(validRequest, {
2638 capabilities: ['dev.ucp.shopping.checkout'],
2639 });
2640
2641 const updated = await updateCheckout(
2642 created.id,
2643 { buyer: { email: 'test@example.com' } },
2644 ['dev.ucp.shopping.checkout']
2645 );
2646
2647 expect(updated?.status).toBe('ready_for_complete');
2648 });
2649 });
2650
2651 describe('status lifecycle', () => {
2652 it('follows correct state transitions', async () => {
2653 // incomplete -> ready_for_complete -> complete_in_progress -> completed
2654 const checkout = await createCheckout(validRequest, {
2655 capabilities: ['dev.ucp.shopping.checkout'],
2656 });
2657 expect(checkout.status).toBe('incomplete');
2658
2659 const updated = await updateCheckout(
2660 checkout.id,
2661 { buyer: { email: 'test@example.com' } },
2662 ['dev.ucp.shopping.checkout']
2663 );
2664 expect(updated?.status).toBe('ready_for_complete');
2665 });
2666 });
2667});
2668```
2669
2670#### Step 3: Output Summary
2671```
2672Generated test files:
2673 CREATE lib/ucp/handlers/__tests__/checkout.test.ts
2674 CREATE lib/ucp/handlers/__tests__/fulfillment.test.ts
2675 CREATE lib/ucp/__tests__/negotiation.test.ts
2676 CREATE lib/ucp/__tests__/profile.test.ts
2677 CREATE app/api/ucp/__tests__/checkout.route.test.ts
2678
2679Run tests with: npm test (or bun test)
2680```
2681
2682---
2683
2684## Sub-command: docs
2685
2686### Trigger
2687User runs `/ucp docs`
2688
2689### Purpose
2690Generate internal documentation for the UCP integration.
2691
2692### Prerequisites
2693- Config must exist
2694- Implementation ideally exists
2695
2696### Procedure
2697
2698#### Step 1: Gather Information
2699- Read config for capabilities, transports, handlers
2700- Scan generated files
2701- Read spec files for accurate descriptions
2702
2703#### Step 2: Generate Documentation
2704
2705Create `docs/ucp-integration.md`:
2706
2707```markdown
2708# UCP Integration Documentation
2709
2710## Overview
2711
2712This codebase implements the Universal Commerce Protocol (UCP) version {version}.
2713
2714**Role:** {role}
2715**Domain:** {domain}
2716**Transports:** {transports}
2717
2718## Capabilities
2719
2720### Core
2721- `dev.ucp.shopping.checkout` - Checkout session management
2722
2723### Extensions
2724{list extensions with descriptions}
2725
2726## API Endpoints
2727
2728### Discovery
2729- `GET /.well-known/ucp` - UCP discovery profile
2730
2731### Checkout (REST)
2732- `POST /api/ucp/checkout` - Create checkout session
2733- `GET /api/ucp/checkout/:id` - Get checkout session
2734- `PATCH /api/ucp/checkout/:id` - Update checkout session
2735- `POST /api/ucp/checkout/:id` (action=complete) - Complete checkout
2736
2737## Checkout Status Lifecycle
2738
2739```
2740incomplete → requires_escalation → ready_for_complete → complete_in_progress → completed
2741 ↘ canceled
2742```
2743
2744## Payment Handlers
2745
2746{list configured handlers with integration notes}
2747
2748## Capability Negotiation
2749
2750The platform sends their profile URL via `UCP-Agent` header:
2751```
2752UCP-Agent: profile="https://platform.example.com/.well-known/ucp"
2753```
2754
2755The business fetches the platform profile, computes the capability intersection,
2756and includes the negotiated capabilities in every response.
2757
2758## Configuration
2759
2760Configuration is stored in `ucp.config.json` at the project root.
2761
2762## Files
2763
2764{list generated files with descriptions}
2765
2766## Testing
2767
2768Run unit tests:
2769```bash
2770npm test
2771```
2772
2773## Validation
2774
2775Validate implementation against UCP schemas:
2776```bash
2777# Using the skill
2778/ucp validate
2779```
2780```
2781
2782#### Step 3: Output
2783```
2784Generated documentation:
2785 CREATE docs/ucp-integration.md
2786
2787Documentation includes:
2788 - Capability overview
2789 - API endpoint reference
2790 - Status lifecycle diagram
2791 - Configuration guide
2792 - File manifest
2793```
2794
2795---
2796
2797## Error Handling
2798
2799### Interactive Error Resolution
2800When encountering ambiguous situations, always ask the user:
2801
28021. **Missing config:** "Config file not found. Run /ucp init first, or create manually?"
28032. **Spec fetch failed:** "Could not clone UCP spec. Check network/auth. Retry, use local path, or abort?"
28043. **Conflicting files:** "File {path} already exists. Overwrite, merge, skip, or abort?"
28054. **Unknown role:** "Role '{role}' not recognized. Did you mean: business, platform, payment_provider, or host_embedded?"
28065. **Validation failure:** "Schema validation failed for {file}. Show details, attempt fix, or skip?"
2807
2808### Error Codes
2809| Code | Meaning | Resolution |
2810|------|---------|------------|
2811| `CONFIG_NOT_FOUND` | ucp.config.json missing | Run /ucp init |
2812| `SPEC_NOT_FOUND` | Spec repo not available | Check network, clone manually |
2813| `INVALID_ROLE` | Unknown role in config | Fix config |
2814| `SCHEMA_INVALID` | Response doesn't match schema | Review generated code |
2815| `EDGE_RUNTIME_DETECTED` | Edge runtime used | Change to nodejs/bun |
2816
2817---
2818
2819## Next.js Conventions
2820
2821### File Structure
2822```
2823project/
2824├── app/
2825│ ├── .well-known/
2826│ │ └── ucp/
2827│ │ └── route.ts # Discovery profile
2828│ └── api/
2829│ └── ucp/
2830│ ├── checkout/
2831│ │ ├── route.ts # POST create
2832│ │ └── [id]/
2833│ │ └── route.ts # GET, PATCH, POST complete
2834│ ├── mcp/
2835│ │ └── route.ts # MCP transport (if enabled)
2836│ └── a2a/
2837│ └── route.ts # A2A transport (if enabled)
2838├── lib/
2839│ └── ucp/
2840│ ├── types/
2841│ │ ├── checkout.ts
2842│ │ └── index.ts
2843│ ├── schemas/
2844│ │ └── checkout.ts
2845│ ├── handlers/
2846│ │ ├── checkout.ts
2847│ │ ├── fulfillment.ts
2848│ │ ├── discount.ts
2849│ │ └── payment.ts
2850│ ├── transports/
2851│ │ └── mcp.ts
2852│ ├── profile.ts
2853│ ├── negotiation.ts
2854│ └── response.ts
2855├── docs/
2856│ └── ucp-integration.md
2857├── ucp.config.json
2858└── .ucp-spec/ # Cloned spec (gitignored)
2859```
2860
2861### Runtime Declaration
2862Every route file must include:
2863```typescript
2864export const runtime = 'nodejs'; // Edge runtime is not supported
2865```
2866
2867Or for Bun:
2868```typescript
2869export const runtime = 'nodejs'; // Bun-compatible Node.js runtime
2870```
2871
2872### App Router Patterns
2873- Use Route Handlers (`route.ts`) not API Routes (`pages/api`)
2874- Use `NextRequest` and `NextResponse` from `next/server`
2875- Await `request.json()` for body parsing
2876- Use `request.headers.get()` for header access
2877
2878---
2879
2880## Credential Handling
2881
2882### Keys Required For
2883- **AP2 Mandates:** JWS signing key (ES256)
2884- **Webhook Signing:** JWS signing key (ES256)
2885- **Identity Linking:** OAuth client credentials
2886
2887### Prompting for Credentials
2888When a feature requires credentials, ask:
2889
2890> "AP2 mandates require a JWS signing key (ES256 recommended).
2891> Do you have an existing key pair, or should I explain how to generate one?"
2892
2893If user needs generation instructions:
2894```bash
2895# Generate ES256 key pair
2896openssl ecparam -genkey -name prime256v1 -noout -out private.pem
2897openssl ec -in private.pem -pubout -out public.pem
2898
2899# Convert to JWK format (use jose library or online tool)
2900```
2901
2902### Storage
2903Credentials should be stored in environment variables, not in config:
2904- `UCP_SIGNING_KEY` - Private key (PEM or JWK)
2905- `UCP_OAUTH_CLIENT_ID` - OAuth client ID
2906- `UCP_OAUTH_CLIENT_SECRET` - OAuth client secret
2907
2908---
2909
2910## Version History
2911
2912- **2026-01-11**: Initial UCP spec version
2913- **Skill v1.0**: Initial skill release
2914
2915---
2916
2917## References
2918
2919- UCP Spec Repository: https://github.com/Universal-Commerce-Protocol/ucp.git
2920- UCP Documentation: See `./ucp/docs/` or `./.ucp-spec/docs/`
2921- JSON Schema Draft 2020-12
2922- RFC 8941 (Structured Field Values)
2923- RFC 3339 (Date/Time Format)
2924- RFC 8785 (JSON Canonicalization Scheme)