# Madely agent guide (v0 sandbox, price list pv_c4d476df4744)
> Print-on-demand fulfillment built for AI agents: find a product, get an exact whole-dollar quote, place an order, and track it.
## What is real in v0
- Catalog and prices: real. They come from our price list (324 products, whole-dollar prices).
- Quotes: real math. Shipping is a flat MOCK estimate of $5.00 per order (real carrier rates replace it before launch). Ship date assumes 2 business days of production (not yet measured).
- Orders: TEST ONLY. In-memory, lost on restart. Nothing is printed or shipped.
- Payments: run against a MOCK of Stripe's API (same objects and field names). No real charges. Real Stripe test mode is switched on by the server owner with STRIPE_SECRET_KEY; agents change nothing.
- Volume tiers: DRAFT, not approved.
- Not built yet: outbound order webhooks, reprints, partial refunds, sales tax, saved-card removal, file download and upscale, color/size variants, non-US shipping, payment, live orders.
## Agent-first rules
- Structured data everywhere: JSON responses, schema.org Product/Offer JSON-LD (/catalog.jsonld, /v1/products/{id}.jsonld), NDJSON and CSV feeds, /pricing.json, OpenAPI 3.1, MCP.
- Deterministic whole-dollar quotes: the same input returns the same quote_id and price (price_version pv_c4d476df4744).
- Errors always have code, message, param, fix, docs, retryable and request_id.
- No human step: mint a sandbox key with one call; quotes and catalog need no key.
- Fast: in-memory; every response has X-Response-Time-Ms. Feeds have ETag and Cache-Control.
- Safe by default: draft orders, max_cost_usd, idempotency keys, test-only ids.
## Payments (Stripe; mock in the sandbox)
You are charged when the order is submitted, before production. The amount is the quote total (whole-dollar items plus carrier-cost shipping). max_cost_usd is a hard ceiling: above it, no order and no charge.
1. agent_token: Stripe Shared Payment Token. Your agent (with the customer's saved card in its wallet) grants an spt_ token to Madely's Stripe profile profile_test_61VrkB0XwlLf0T0sIA6VrkB079SQUMsvBMOZN85NAT2u with usage_limits.max_amount at least the total in cents, currency usd, and a future expires_at. You send it as payment.shared_payment_token. Madely creates and confirms a Stripe PaymentIntent with payment_method_data[shared_payment_granted_token]. The token is single-use here and is never echoed back. Docs: https://docs.stripe.com/agentic-commerce/sellers/one-time-payments
2. card_on_file: POST /v1/payment-methods {"payment_method_id":"pm_..."} saves a Stripe PaymentMethod on a Stripe Customer. Orders are charged off-session. A card that needs 3-D Secure fails with payment_requires_authentication: use agent_token or balance instead.
3. balance: POST /v1/balance/top-ups {"amount_usd":200,"payment":{"method":"card_on_file"}} (whole dollars, 10 to 5000, Idempotency-Key required). Orders debit it. If it is too low you get insufficient_balance with the shortfall and the exact top-up call to make.
Failed charge: HTTP 402, no order is created, nothing is charged. Retry with the same Idempotency-Key and a different payment.
Cancel: POST /v1/orders/{order_id}/cancel refunds in full (Stripe refund, or back to the balance) while the order is draft or in_production. Repeating it never refunds twice.
Sandbox helpers: POST /v1/sandbox/shared-payment-tokens (mint a test token), card pm_card_visa (succeeds), pm_card_chargeCustomerFail (saves, then declines), pm_card_chargeDeclinedInsufficientFunds, pm_card_authenticationRequired.
Webhooks: Stripe calls POST /v1/webhooks/stripe; the Stripe-Signature header is verified. You do not need it.
## Sample agent flow
```
GET https://api.madely.ai/v1/products?q=mug&limit=3
POST https://api.madely.ai/v1/quotes
{"items":[{"product_id":"A29","quantity":120}],"ship_to":{"country":"US","zip":"80202"}}
-> {"quote_id":"q_...","items_usd":1320,"shipping":{"amount_usd":5},"total_usd":1325,"estimated_ship_date":"YYYY-MM-DD","tier_applied":{"tier_id":"standard"}}
POST https://api.madely.ai/v1/sandbox/keys
-> {"api_key":"madely_sandbox_..."}
POST https://api.madely.ai/v1/orders (Authorization: Bearer , Idempotency-Key: madely-smoketest-001)
{"quote_id":"q_...","external_id":"madely-smoketest-001","submit":true,"max_cost_usd":1400,
"payment":{"method":"agent_token","shared_payment_token":"spt_..."},
"ship_to":{"name":"Test Buyer","address1":"1 Test St","city":"Denver","state":"CO","zip":"80202","country":"US"},
"items":[{"product_id":"A29","quantity":120,"artwork":[{"placement":"front","url":"https://example.com/art.png","width_px":3600,"height_px":4800}]}]}
-> 201 {"order_id":"ord_test_...","status":"in_production","payment":{"method":"agent_token","status":"succeeded","payment_intent_id":"pi_..."},...}
GET https://api.madely.ai/v1/orders/ord_test_...
```
## Print specs (code first)
The machine-readable print spec is the source of truth for file sizes. Templates and product pages are generated from it.
- GET /v1/products/{product_id}/print-spec: one product (product_id or sku).
- GET /print-specs.json: all products (filter ?category= or ?source=measured). GET /schemas/print-spec.schema.json: JSON Schema.
- Fields: canvas_px {width,height} (includes bleed), inches, dpi, orientation, aspect_ratio, bleed {inches,px}, trim_box_px, safe_zone {margin_inches,margin_px,box_px}, print_zones[] (name = the placement to send; kind flat or wrap; wrap has a cylinder note with front_center_x_px), color_mode (sRGB, no CMYK), accepted_formats (PNG, JPG, PDF, SVG), max_file_mb, background {transparent: required|preferred|avoid, fill_canvas}, generation_hint {prompt_suffix, size, aspect_ratio}, source, field_sources, assumed_fields, conflicts, template_urls.
- Boxes are {x,y,width,height} in canvas pixels, origin top-left.
- Make a file: pass generation_hint.prompt_suffix to your image model, generate at generation_hint.aspect_ratio, upscale to canvas_px if needed. Keep text and key art inside safe_zone.box_px.
- Check a file before ordering: POST /v1/print-spec/validate {"product_id":"K04","width_px":2550,"height_px":1155,"format":"png","has_transparency":false,"preview":true}. Optional: url, file_size_mb, color_mode, content_bbox_px, placement, fit. Returns valid, checks[] (name, status pass|warn|fail, detail, expected, actual, fix), fixes[], fit, preview_url. v0 does not download the file; it checks what you declare. MCP: validate_print_file (alias check_print_file).
- Trust: each spec has "source". "measured" means read from a template file or equal to our production size. "Madely product specs" and "industry standard, to verify" are good but unconfirmed. Do not treat the unconfirmed ones as final for a large run: check source in the response. max_file_mb (50), bleed defaults and the wrap-curvature notes are assumptions.
- A product with no print area in any source returns 404 print_spec_not_available from /print-spec; its files get a warning, not a pass.
Counts in this build: 178 Madely product specs, 14 measured, 1 industry standard, to verify, 131 no spec.
## MCP
POST https://api.madely.ai/mcp takes JSON-RPC 2.0 (initialize, tools/list, tools/call, ping). GET /mcp returns 405 with Allow: POST. Send your API key as "Authorization: Bearer "; the old api_key tool argument still works but is deprecated and no longer advertised. Every tool has a title and annotations (readOnlyHint, destructiveHint, idempotentHint, openWorldHint). CORS is open for reads and for the read-only POST tools (mcp, quotes, print-spec validation); order and payment writes are not opened to other origins.
## Client setup
MCP URL: https://api.madely.ai/mcp (streamable HTTP, POST). ChatGPT: Plugins, Add custom MCP server, no auth. Claude and Claude Desktop: Customize, Connectors, custom connector (public HTTPS only). Claude Code: claude mcp add --transport http madely https://api.madely.ai/mcp. Cursor: ~/.cursor/mcp.json {"mcpServers":{"madely":{"url":"https://api.madely.ai/mcp"}}}. VS Code: .mcp.json with mcpServers and type http. Grok: xAI Responses API tools [{"type":"mcp","server_url":"https://api.madely.ai/mcp","server_label":"madely"}]. Sources and exact snippets: https://api.madely.ai/connect/clients.md
## Quickstart
Seven calls, no human step: GET /llms.txt, POST /v1/sandbox/keys, GET /v1/products/K04/print-spec, POST /v1/print-spec/validate, POST /v1/quotes, POST /v1/orders (Idempotency-Key, external_id madely-smoketest-...), GET /v1/orders/{id}. Runnable scripts: https://api.madely.ai/quickstart.md and https://api.madely.ai/examples/quickstart.sh|py|ts
## Markdown
Send the header Accept: text/markdown to GET / (returns this guide's short form) or to any error (returns a Markdown error with the hint). Content-Type is text/markdown and Vary: Accept is set.
## Discovery files
/.well-known/api-catalog (RFC 9727 linkset), /.well-known/mcp.json, /.well-known/ai-plugin.json, /.well-known/security.txt, /openapi.json, /llms.txt, /sitemap.xml. Every response carries Link headers for service-desc, describedby and api-catalog.
## Rate limits
Sandbox write calls (orders, submit, top-ups, payment methods, sandbox keys, sandbox tokens) are limited per address per hour. Those responses carry RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset. Over the limit you get 429 rate_limited with Retry-After (seconds) and retryable true. Reads are not limited.
## Sandbox endpoints
Everything tagged "Sandbox" in the OpenAPI spec (/v1/sandbox/* and /v1/webhooks/stripe) exists only in the test version. It is not part of the production contract. Do not build on it.
## Volume tiers (draft)
Same for everyone. A tier lowers a price only where there is room above the tier's minimum margin. Read /v1/pricing/tiers. Pass committed_monthly_items to POST /v1/quotes to price at a tier; the response says which tier applied.
## Error codes and fixes
- api_key_required (401): Send "Authorization: Bearer ". Mint a key with POST /v1/sandbox/keys.
- api_key_invalid (401): Mint a new sandbox key.
- idempotency_key_required (400): Add the Idempotency-Key header.
- idempotency_key_reused (409): Same key, different body. Use a new key, or resend the identical body to get the original order.
- invalid_json (400): Send valid JSON.
- unknown_product (422 (404 on GET)): Search with GET /v1/products?q=.
- print_spec_not_available (404): No source has a print area for this product yet. Send artwork at 300 dpi at the finished size, or choose another product.
- nothing_to_check (422): POST /v1/print-spec/validate needs a url and/or width_px and height_px (or format, file_size_mb, has_transparency, content_bbox_px).
- items_required / too_many_lines / invalid_quantity (422): Send 1-100 items, each with an integer quantity 1-10000.
- ship_to_required / ship_to_zip_invalid / ship_to_country_unsupported (422): v0 ships to US only; send country "US" and a 5-digit zip.
- invalid_committed_monthly_items / invalid_max_price (422): Send a non-negative number or omit it.
- rate_limited (429): Public test link only: more than the hourly cap of sandbox write calls from one address. Wait and retry; reads are not limited.
- quote_id_required / quote_not_found (422 / 404): Create a quote first with POST /v1/quotes.
- quote_expired (410): Re-request the quote. The same input returns the same quote_id with a fresh expiry. Retryable.
- max_cost_exceeded (422): Raise max_cost_usd or reduce items.
- items_do_not_match_quote (422): Order items must equal the quote lines, in order.
- artwork_required (422): Send at least one artwork file per item.
- print_file_check_failed (422): See details[].checks[].fix. No order was created.
- external_id_required (422): Send your own order id.
- payment_required (402): No payment and no balance or card covers it. Send payment as agent_token, card_on_file or balance (see the fix text).
- insufficient_balance (402): details has shortfall_usd and suggested_top_up_usd. POST /v1/balance/top-ups, then retry with the same Idempotency-Key.
- payment_failed (402): The card was declined (details has the Stripe decline_code). Use another card, an agent_token, or a balance top-up. No order was created.
- payment_requires_authentication (402): The card needs customer authentication an agent cannot do off-session. Use agent_token or balance.
- payment_token_amount_too_low / payment_token_expired / payment_token_deactivated (402): Grant a new Shared Payment Token with usage_limits.max_amount of at least the total in cents, a later expires_at, and use it once.
- payment_token_invalid / payment_token_not_found / payment_method_invalid / payment_method_id_required / payment_method_not_found (422): Send an spt_ token, a pm_ id, or method agent_token, card_on_file or balance.
- no_card_on_file (402): POST /v1/payment-methods first.
- invalid_top_up_amount (422): Whole dollars from 10 to 5000.
- payment_provider_error / refund_failed (502): Temporary. Retry with the same Idempotency-Key (never double charges or refunds). Retryable.
- payment_not_completed (402): Retry with the same Idempotency-Key, or use another payment method.
- request_in_progress (409): An identical request is still running. Wait a second and resend; same result. Retryable.
- order_not_cancelable / order_canceled / order_not_submitted (409): Only draft or in_production orders can be canceled; a draft must be submitted (paid) before it moves on.
- webhook_signature_invalid / webhook_not_configured / mock_only (400 / 503 / 409): Webhook endpoint for Stripe only; see the Payments section.
- live_orders_disabled (403): Sandbox only: external_id must start with "madely-smoketest-".
- ship_to_incomplete / items_required / item_invalid / external_order_id_required / source_unsupported (422): Etsy orders need source "etsy", store_id, external_order_id (the Etsy receipt id), items with quantity and sku or listing_id, and a full ship_to. Fix the field named in the error and resend.
- store_not_found (404): POST /v1/stores with platform "etsy" and sync your listings first.
- not_shipped_yet / not_ready / sandbox_only (409 / 409 / 403): Tracking can be acknowledged only after the order ships. The sandbox ship button is for madely-smoketest orders only.
- csv_required / csv_not_recognized / csv_too_large / since_invalid / webhook_url_invalid (422 / 422 / 413 / 422 / 422): Download "Order Items" from Etsy (Shop Manager > Settings > Options > Download Data) and send {"csv": "..."}; since is an ISO date-time; webhook url is https.
- order_not_found (404): Use the order_id from POST /v1/orders with the same API key.
- order_not_draft / order_already_delivered (409): GET the order to see its status.
- not_found / method_not_allowed (404 / 405): Start at GET / or /llms.txt.
## Terms (sandbox)
Test orders only. No warranty. Prices can change; price_version tells you which list you saw.