← Back to blog

Agent Shop API: How Your AI Agent Buys Credits

September 18, 2026 · Eric · 6 min read

Sooner or later an autonomous agent runs out of quota in the middle of a job. Speech-to-text, background removal, screenshots, HTML→PDF, image generation, and over-limit API calls all consume credits after a free daily allowance. When that happens, the API answers with a 402 and a billing object that literally tells the agent which endpoint to call to fix it.

This post walks the agent-initiated purchase path end to end: discovering what can be bought, why the agent key must be linked to a human account, how a checkout can complete without a human redirect, and how the spend policy stops a runaway loop before it touches a card. Everything below is a real route on agentmediatools.com — no SDK, no wrapper library, no client package to install.

Step 1 — Read the public catalog

The catalog endpoint needs no authentication, which means an agent can inspect prices and item IDs before it holds a key at all:

curl -s "https://agentmediatools.com/api/shop/items" | python3 -m json.tool

It returns four things you care about: scripts[] and bundles[] (the downloadable Python Blueprints, all currently priced 0.00), credit_packs[] (the only purchasable items), and credit_costs, which maps a tool name to the credits it burns once the free quota is gone. Trimmed live response:

{
  "description": "Free downloadable Python Blueprints plus optional credit packs for hosted usage.",
  "scripts": [ { "id": "gen.py", "price_usd": "0.00", "tier": "free",
                 "download_url": "/api/shop/download/gen.py" } ],
  "bundles": [ { "id": "toolkit-bundle", "price_usd": "0.00", "tier": "free" } ],
  "credit_packs": [
    { "id": "credits-100",  "name": "100 Usage Credits",  "price_usd": "5.00",  "price_cents": 500,  "credits": 100,  "popular": true },
    { "id": "credits-500",  "name": "500 Usage Credits",  "price_usd": "20.00", "price_cents": 2000, "credits": 500 },
    { "id": "credits-2000", "name": "2000 Usage Credits", "price_usd": "60.00", "price_cents": 6000, "credits": 2000 }
  ],
  "credit_costs": { "transcribe": 2, "remove-bg": 2, "screenshot": 1, "html-to-pdf": 1, "generate-image": 3 },
  "how_agents_buy": "Download Blueprints from /api/shop/download/{item}. Buy optional credits with POST /api/agent/shop/checkout { \"item\": \"credits-100\" } and Authorization: Bearer ***"
}

Two things worth internalizing. First, Blueprints are not purchasable — they are free files, so there is nothing to buy and nothing for a spend policy to approve. Second, the only items that move money are the three credit packs, and their IDs are stable: credits-100, credits-500, credits-2000. Aliases such as usage-credit resolve to credits-100 server-side, and your allowlist should use the canonical ID.

Step 2 — Link the agent key to a human account

An agent key is a string starting with mt_, sent as Authorization: Bearer mt_.... Purchases additionally require that the key belongs to a user account — create the key while logged in and the row stores a user_id. If it does not, checkout fails cleanly:

{"error":"Agent key not linked to a user account. Generate the key while logged into a user account to enable purchases."}

That is the consent boundary by design: an orphan key can consume free quota, but it can never spend money. Note also that policy checks run before the linkage check, so an unlinked key still gets an honest NO_CONSENT or KILL_SWITCH answer rather than a billing surprise later.

Step 3 — Buy credits with an agent-initiated checkout

One endpoint does the purchase. It is a plain JSON POST:

curl -s -X POST "https://agentmediatools.com/api/agent/shop/checkout" \
  -H "Authorization: Bearer $MEDIA_TOOL_AGENT_KEY" \
  -H "Content-Type: application/json" \
  -d '{"item":"credits-100"}' | python3 -m json.tool

There are three possible outcomes, and a well-behaved agent handles all of them.

Outcome A — autonomous purchase

If the linked Stripe customer has a default payment method on file, the key has purchase consent, and the amount is inside the per-purchase ceiling, the charge happens off-session and the credits land immediately:

{
  "success": true,
  "payment_intent_id": "pi_...",
  "status": "succeeded",
  "credits_added": 100,
  "receipt_id": "rcpt_...",
  "message": "Added 100 usage credits to linked keys."
}

A signed receipt of kind purchase (action purchase.autonomous) is written at the same time, so the spend shows up in GET /api/agent/receipts?kind=purchase.

Outcome B — human completes the checkout

With no saved payment method (or no usable one), the API falls back to a Stripe Checkout session and returns a URL instead of charging. Your agent should surface it, not retry in a loop:

{ "url": "https://checkout.stripe.com/c/pay/...",
  "item": "credits-100", "credits": 100,
  "message": "Agent-initiated checkout URL created (human completion required for this purchase)." }

Payment is credited to the linked account, so the agent only needs to re-check its balance afterwards.

Outcome C — further action required

If Stripe returns requires_action, the response carries a client_secret and requires_action: true. Treat this as "hand to the human" as well.

You can also pass an explicit payment_method in the body when you want the agent to use a specific saved payment method rather than the customer default. And calling checkout with a Blueprint ID is safe: the response is {"free": true, "download_url": "/api/shop/download/gen.py"} with the message "Blueprints are free. No payment or agent spend approval is required."

Step 4 — Confirm the balance actually moved

Never assume a purchase succeeded because the HTTP status was 200. Verify from the agent side:

# credits, plan, daily usage, and a suggested_action hint
curl -s "https://agentmediatools.com/api/agent/usage" \
  -H "Authorization: Bearer $MEDIA_TOOL_AGENT_KEY" | python3 -m json.tool

# purchase history for the linked user
curl -s "https://agentmediatools.com/api/agent/shop/purchases" \
  -H "Authorization: Bearer $MEDIA_TOOL_AGENT_KEY" | python3 -m json.tool

# access check for a specific catalog item
curl -s "https://agentmediatools.com/api/agent/shop/check-access?item=toolkit-bundle" \
  -H "Authorization: Bearer $MEDIA_TOOL_AGENT_KEY" | python3 -m json.tool

GET /api/agent/usage returns a credits summary (subscription balance plus purchased credits) and a suggested_action that flips to buy_credits when the agent is out of runway. GET /api/agent/shop/purchases returns one row per purchase — {"purchases": [{"item": "credits-100", "created_at": "..."}]} — and an empty array with an explanatory message for unlinked keys.

check-access is about catalog items, not about your credit balance: for a Blueprint it answers {"has_access": true, "via": "free_library"}, and otherwise it reports whether the linked user has a purchase row. Use /api/agent/usage when you want to know how many credits are left.

Step 5 — Keep the agent inside its policy

Every checkout passes through checkPurchasePolicy before any charge attempt. New keys start with purchase consent on, a $50.00 per-purchase ceiling, an empty item allowlist, no daily dollar cap, and no approval threshold — sane defaults, but defaults you should tighten for a production worker. The human writes those fields with a session (never with the agent key):

# full policy surface (session auth, human)
curl -s -X POST "https://agentmediatools.com/api/agent/keys/KEY_ID/spend-policy" \
  -H "Content-Type: application/json" -b cookies.txt \
  -d '{"purchase_consent": true, "max_purchase_cents": 2000,
       "allowed_items": ["credits-100"], "daily_spend_cents": 2000,
       "require_approval_over_cents": 500}'

POST /api/agent/keys/:id/purchase-settings covers the purchasing subset (purchase_consent, max_purchase_cents, allowed_items) if you prefer a narrow endpoint. The agent-side read is GET /api/agent/policy, which also returns today's spend and remaining budget. The full policy model — credit budgets, kill switch, rotation — is covered in the spend policy post.

What a denied purchase looks like

Policy denials are specific strings with machine-readable codes, so an agent can branch on them instead of parsing prose:

StatusCodeMeaning
403KILL_SWITCHHuman-level stop is on; all purchases blocked until cleared.
403NO_CONSENTPurchase consent is off for this key.
403OVER_MAX_PURCHASEAmount exceeds max_purchase_cents.
403ITEM_NOT_ALLOWEDItem is missing from a non-empty allowed_items allowlist.
403DAILY_SPEND_CAPToday's spend plus this purchase would exceed the daily dollar cap.
402APPROVAL_REQUIREDAbove the approval threshold — request an approval and retry with approval_id.
403APPROVAL_NOT_APPROVEDThe referenced approval is still pending, denied, or expired.
403APPROVAL_AMOUNT_MISMATCHApproved amount differs from the purchase amount.
400BAD_APPROVALapproval_id does not belong to this key.

The 402 is the interesting one, because it tells the agent exactly how to escalate — including that the approval amount must match the pack price within a cent:

{
  "status": 402,
  "error": "Human approval required for purchases over $5.00. Request one via POST /api/agent/approvals.",
  "code": "APPROVAL_REQUIRED",
  "require_approval_over_cents": 500,
  "amount_cents": 500,
  "how": {
    "request": "POST /api/agent/approvals",
    "body": { "action": "purchase", "summary": "Buy credits-100", "amount_cents": 500, "details": { "item": "credits-100" } },
    "poll": "GET /api/agent/approvals/:id",
    "retry": "POST /api/agent/shop/checkout with approval_id"
  }
}

Requesting the approval returns approve_url (a human opens it, sees the amount and summary, and clicks approve or deny) plus poll_url for the agent. Once approved, resend the same checkout with {"item": "credits-100", "approval_id": "..."} and the purchase proceeds normally. Notifications to email, Discord, and Telegram fire automatically if the human configured them. The request/decide/poll loop is documented in Human-in-the-Loop Approvals for AI Agents.

The loop that pays off: 402 → buy → retry

Put the two halves together and the failure mode that used to end a job becomes a recovery step. A paid tool runs out of credits, returns 402 with a billing object that includes buy_credits (the pricing page) and agent_checkout ("POST /api/agent/shop/checkout {"item":"credits-100"} with Bearer key"), the agent buys the smallest pack inside its ceiling, reads credits_added and receipt_id, verifies with /api/agent/usage, and retries the original call. No human in the loop unless the policy says so.

Python: the whole flow, without an SDK

import os, requests

BASE = "https://agentmediatools.com"
KEY  = os.environ["MEDIA_TOOL_AGENT_KEY"]          # mt_...
H    = {"Authorization": f"Bearer {KEY}"}

catalog = requests.get(f"{BASE}/api/shop/items", timeout=20).json()
packs   = {p["id"]: p for p in catalog["credit_packs"]}
pack    = "credits-100"

usage = requests.get(f"{BASE}/api/agent/usage", headers=H, timeout=20).json()
if usage.get("suggested_action") != "buy_credits":
    raise SystemExit(f"no purchase needed ({usage.get('remaining')} calls left today)")

r = requests.post(f"{BASE}/api/agent/shop/checkout", headers=H,
                 json={"item": pack}, timeout=30)
body = r.json()

if r.status_code == 402 and body.get("code") == "APPROVAL_REQUIRED":
    ap = requests.post(f"{BASE}/api/agent/approvals", headers=H, json={
        "action": "purchase",
        "summary": f"Buy {packs[pack]['name']}",
        "amount_cents": packs[pack]["price_cents"],
        "details": {"item": pack},
    }, timeout=20).json()
    print("Waiting on a human:", ap["approval"]["approve_url"])
    raise SystemExit(1)          # poll ap["approval"]["poll_url"], then retry with approval_id

r.raise_for_status()
if "url" in body:
    print("Human must complete payment:", body["url"])
else:
    print("Paid", body.get("payment_intent_id"),
          "→ +", body.get("credits_added"), "credits (receipt", body.get("receipt_id"), ")")

MCP: two tools, one caveat

If your agent speaks MCP instead of REST, the same flow is exposed as list_shop_items (no arguments, returns the catalog) and initiate_purchase (takes item). The MCP handler posts to the same checkout endpoint with the key from MEDIA_TOOL_AGENT_KEY, and the returned payload is annotated with a note to present the url to the human. One caveat worth knowing: the published description of initiate_purchase still mentions scripts and bundles, but the live behavior is that scripts are free and the Stripe path is for credit packs — so do not hardcode an assumption about which items cost money. Read list_shop_items output first; price_usd and tier tell you the truth.

Honest boundaries

Current pack prices and free daily allowances are on the pricing page, the free Python downloads live on Blueprints, and the full endpoint list is in the docs.

Try it in the Toolbox

Run the same tools in the browser, or let your agent buy credits and call them with an API key.

Open toolbox