# Spend Control for AI Agents: See the Price Before Anything Runs

> Stop agents and automations from running up surprise bills: price every generation first, approve the USD amount, then generate, with limits the agent cannot raise.

Canonical: https://raywake.si/blog/ai-agent-spend-control-api-mcp
Last updated: 2026-12-01

Published: 2026-12-01 · Raywake

Raywake shows the price first. Every generation, from the API or through the MCP server, is priced for its exact input before anything runs, and nothing is spent until something approves that price. This guide shows how to put that approval into your own code, how the MCP server applies the same flow in Claude, ChatGPT and Cursor, and how to see afterwards which agent spent what. The same rules cover all 500+ models on Raywake, from image and video to audio.

## The rule: quote, approve, generate

One Raywake generation is three steps:

1. **Quote.** `POST /v1/quotes` with a model ID and the complete input. The response carries `quote_id`, `price_usd` and `expires_at` (at most 10 minutes away). Requesting a quote does not start a job or spend funds.
2. **Approve.** Your code, your budget rule or a person looks at `price_usd` and says yes or no.
3. **Generate.** `POST /v1/generate` with the same model, the same input, the `quote_id` and an `Idempotency-Key` header. Change one field of the input or wait past `expires_at`, and the API answers `409` instead of running something you never priced.

For models billed by what they produce, such as seconds of video, the quote is an upper bound: you are charged the measured amount and a generation never costs more than its quote. Details are in [Quotes and funds](https://raywake.si/docs/credits) and the [quotes reference](https://raywake.si/docs/reference/quotes).

## Put the approval gate in code

Quoting and generating both need the key's `generate` permission, so the approval step has to live in your code (or in your MCP client, covered below). The pattern is short: quote, compare against a hard ceiling, ask, then generate with the quoted input.

```raywake-component
{"type": "code-tabs", "snippets": {"curl": "MODEL=\"nano-banana-pro\"\nINPUT='{\"prompt\":\"A red ceramic cup on a wooden table, soft morning light\",\"aspect_ratio\":\"1:1\"}'\nMAX_USD=\"0.50\"\n\n# 1. Quote: prices this exact input. No job starts, nothing is spent.\nQUOTE=$(curl -s https://api.raywake.com/v1/quotes \\\n  -H \"Authorization: Bearer $RAYWAKE_API_KEY\" \\\n  -H \"Content-Type: application/json\" \\\n  -d \"$(jq -n --arg m \"$MODEL\" --argjson i \"$INPUT\" '{model: $m, input: $i}')\")\nPRICE=$(echo \"$QUOTE\" | jq -r .price_usd)\nQUOTE_ID=$(echo \"$QUOTE\" | jq -r .quote_id)\necho \"$MODEL: $PRICE USD, valid until $(echo \"$QUOTE\" | jq -r .expires_at)\"\n\n# 2. Budget rule, then a human yes. Anything else stops here.\nawk -v p=\"$PRICE\" -v m=\"$MAX_USD\" 'BEGIN { exit !(p <= m) }' || { echo \"Over budget\"; exit 1; }\nread -r -p \"Generate for $PRICE USD? [y/N] \" OK\n[ \"$OK\" = \"y\" ] || exit 0\n\n# 3. Generate with the SAME model, input and quote_id.\n#    Keep KEY: retrying with it returns the same job instead of starting a second one.\nKEY=$(uuidgen)\ncurl -s \"https://api.raywake.com/v1/generate?wait=true\" \\\n  -H \"Authorization: Bearer $RAYWAKE_API_KEY\" \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Idempotency-Key: $KEY\" \\\n  -d \"$(jq -n --arg m \"$MODEL\" --argjson i \"$INPUT\" --arg q \"$QUOTE_ID\" '{model: $m, input: $i, quote_id: $q}')\"\n# If the job is not terminal yet: GET https://api.raywake.com/v1/jobs/JOB_ID every 2-5 seconds.", "python": "import os, sys, time, uuid\nfrom decimal import Decimal\nimport requests\n\nAPI = \"https://api.raywake.com/v1\"\nH = {\"Authorization\": f\"Bearer {os.environ['RAYWAKE_API_KEY']}\"}\nMAX_USD = Decimal(\"0.50\")  # hard ceiling for one generation\nTERMINAL = {\"succeeded\", \"failed\", \"needs_review\", \"submission_unknown\", \"needs_reconciliation\"}\n\nmodel = \"nano-banana-pro\"\ninp = {\"prompt\": \"A red ceramic cup on a wooden table, soft morning light\", \"aspect_ratio\": \"1:1\"}\n\ndef call(method, path, headers=None, **kw):\n    r = requests.request(method, f\"{API}{path}\", headers={**H, **(headers or {})}, **kw)\n    r.raise_for_status()\n    return r.json()\n\n# 1. Quote: prices this exact input. No job starts, nothing is spent.\nquote = call(\"POST\", \"/quotes\", json={\"model\": model, \"input\": inp})\nprice = Decimal(quote[\"price_usd\"])\nprint(f\"{model}: {price} USD, valid until {quote['expires_at']}\")\n\n# 2. Budget rule, then a human yes. Anything else stops here.\nif price > MAX_USD:\n    sys.exit(f\"Over the {MAX_USD} USD ceiling, not generating.\")\nif input(\"Generate for this price? [y/N] \").strip().lower() != \"y\":\n    sys.exit(\"Not approved. Nothing was spent.\")\n\n# 3. Generate with the SAME model, input and quote_id.\n#    Keep the key: retrying with it returns the same job instead of starting a second one.\nkey = str(uuid.uuid4())\njob = call(\"POST\", \"/generate\", params={\"wait\": \"true\"},\n           headers={\"Idempotency-Key\": key},\n           json={\"model\": model, \"input\": inp, \"quote_id\": quote[\"quote_id\"]})\n\nwhile job[\"status\"] not in TERMINAL:\n    time.sleep(3)\n    job = call(\"GET\", f\"/jobs/{job['job_id']}\")\n\nprint(job[\"status\"], job[\"charged_usd\"], [o[\"url\"] for o in job[\"outputs\"]])", "javascript": "import readline from \"node:readline/promises\";\nimport { stdin, stdout } from \"node:process\";\n\nconst API = \"https://api.raywake.com/v1\";\nconst auth = { Authorization: `Bearer ${process.env.RAYWAKE_API_KEY}`, \"Content-Type\": \"application/json\" };\nconst MAX_USD = 0.5; // hard ceiling for one generation\nconst TERMINAL = [\"succeeded\", \"failed\", \"needs_review\", \"submission_unknown\", \"needs_reconciliation\"];\n\nconst model = \"nano-banana-pro\";\nconst input = { prompt: \"A red ceramic cup on a wooden table, soft morning light\", aspect_ratio: \"1:1\" };\n\nasync function call(path, init = {}) {\n  const res = await fetch(`${API}${path}`, { ...init, headers: { ...auth, ...init.headers } });\n  if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);\n  return res.json();\n}\n\n// 1. Quote: prices this exact input. No job starts, nothing is spent.\nconst quote = await call(\"/quotes\", { method: \"POST\", body: JSON.stringify({ model, input }) });\nconsole.log(`${model}: ${quote.price_usd} USD, valid until ${quote.expires_at}`);\n\n// 2. Budget rule, then a human yes. Anything else stops here.\nif (Number(quote.price_usd) > MAX_USD) throw new Error(\"Over budget, not generating.\");\nconst rl = readline.createInterface({ input: stdin, output: stdout });\nconst answer = await rl.question(\"Generate for this price? [y/N] \");\nrl.close();\nif (answer.trim().toLowerCase() !== \"y\") process.exit(0);\n\n// 3. Generate with the SAME model, input and quote_id.\n//    Keep the key: retrying with it returns the same job instead of starting a second one.\nconst key = crypto.randomUUID();\nlet job = await call(\"/generate?wait=true\", {\n  method: \"POST\",\n  headers: { \"Idempotency-Key\": key },\n  body: JSON.stringify({ model, input, quote_id: quote.quote_id }),\n});\nwhile (!TERMINAL.includes(job.status)) {\n  await new Promise((resolve) => setTimeout(resolve, 3000));\n  job = await call(`/jobs/${job.job_id}`);\n}\nconsole.log(job.status, job.charged_usd, job.outputs.map((o) => o.url));"}, "label": "Quote, budget check, human approval, then generate"}
```

Three details make this safe in production:

- **The ceiling is a number.** `price_usd` is a decimal string; compare it with `Decimal` (Python) or a parsed number before anyone is asked.
- **One idempotency key per intended generation.** If the generate call times out, retry with the *same* key and body: you get the original job back, not a second paid one. The same key with a different body returns `409`.
- **A timeout is not a failure.** `submission_unknown`, `needs_review` and `needs_reconciliation` are held states: the funds stay reserved and the job can still turn `succeeded` or `failed`. The loops above stop on them so a person can look; check the job again later and never submit a replacement automatically. The statuses are listed in [Generations](https://raywake.si/docs/generations).

## Limits the agent cannot raise

Code-level gates are only as good as the code. Raywake adds account-level limits that sit outside the agent:

- **Spending limits per hour or per 24 hours.** Set them on the Alerts page in the studio. A generation that would cross one returns `429` with `X-Limit-Reason: spend_limit` and a `Retry-After` header. The limits cover the studio and every API key, and they can only be changed from the studio, so an agent holding an API key cannot lift its own ceiling. See [Errors and limits](https://raywake.si/docs/errors).
- **Key permissions and expiry.** Each key carries only the permissions you pick: `models:read`, `generate`, `jobs:read`, `wallet:read`. A reporting job only needs `jobs:read` and `wallet:read`. A key can expire after 30 days, 90 days or 1 year, and you can revoke it at any time. See [Authentication](https://raywake.si/docs/authentication).
- **Not enough funds is a hard stop.** If the available balance does not cover the quote, generate returns `402`.

## The same flow through MCP

The [Raywake MCP server](https://raywake.si/docs/mcp) gives Claude, ChatGPT, Claude Code, Cursor and other MCP clients the full catalog with the same quote-first rule. **`generate` is the only tool that spends balance**, and it needs a quote for the exact model and input. The others, such as `search_models`, `get_model`, `quote`, `get_job`, `list_jobs` and `get_account`, only read or price. For a comparison with other MCP servers for media generation, see [MCP servers for image and video generation](https://raywake.si/compare/mcp-servers-image-video-generation).

Hosted connector, nothing to install:

```bash
claude mcp add --transport http raywake https://mcp.raywake.com/v1
```

When you connect with your Raywake account, you choose a **spending limit per generation**, so even an approved generation cannot go past that cap. The connection expires after 30 days, and you can disconnect it in settings at any time.

Local package over stdio (Node.js 20+), with the key in the environment, not in your prompt:

```bash
claude mcp add raywake -e RAYWAKE_API_KEY=$RAYWAKE_API_KEY -- npx -y @raywake/mcp
```

The assistant is instructed to quote, show you the USD price and expiry, and wait for your approval before calling `generate`. Know the limit of that: the server cannot verify that a person actually said yes in the chat. So also set your MCP client to ask for confirmation before the paid `generate` tool. Then a model that skips the rule still hits a confirmation prompt, and the spending limits above still apply.

A prompt that works well:

```text
Quote a 5-second Kling 4.0 video of a burger assembling itself. Show me the price in USD and ask me before generating.
```

## Which agent is spending the budget?

Give every agent or scheduled workflow its own API key. Each job records `source` (`api` or `studio`) and the `api_key_id` that started it, so attribution is a filter, not a guess:

```raywake-component
{"type": "code-tabs", "snippets": {"curl": "# Available and reserved balance (needs wallet:read)\ncurl -s https://api.raywake.com/v1/wallet \\\n  -H \"Authorization: Bearer $RAYWAKE_API_KEY\"\n\n# Last 7 days: totals, per day, per model, failure reasons (needs jobs:read)\ncurl -s \"https://api.raywake.com/v1/usage?days=7\" \\\n  -H \"Authorization: Bearer $RAYWAKE_API_KEY\"\n\n# Every job one agent's key started since Monday, with charged_usd on each\ncurl -s \"https://api.raywake.com/v1/jobs?api_key_id=AGENT_KEY_ID&since=2026-11-30T00:00:00Z&limit=500\" \\\n  -H \"Authorization: Bearer $RAYWAKE_API_KEY\"", "python": "import os, requests\n\nAPI = \"https://api.raywake.com/v1\"\nH = {\"Authorization\": f\"Bearer {os.environ['RAYWAKE_API_KEY']}\"}\n\nwallet = requests.get(f\"{API}/wallet\", headers=H).json()\nprint(\"available:\", wallet[\"available_usd\"], \"reserved:\", wallet[\"reserved_usd\"])\n\nusage = requests.get(f\"{API}/usage\", params={\"days\": 7}, headers=H).json()\nprint(\"totals:\", usage[\"totals\"])\nfor row in usage[\"models\"]:      # most spend first\n    print(row)\n\njobs = requests.get(f\"{API}/jobs\", headers=H, params={\n    \"api_key_id\": \"AGENT_KEY_ID\", \"since\": \"2026-11-30T00:00:00Z\", \"limit\": 500,\n}).json()\nprint(jobs)", "javascript": "const API = \"https://api.raywake.com/v1\";\nconst headers = { Authorization: `Bearer ${process.env.RAYWAKE_API_KEY}` };\nconst get = (path) => fetch(`${API}${path}`, { headers }).then((r) => r.json());\n\nconst wallet = await get(\"/wallet\");\nconsole.log(\"available:\", wallet.available_usd, \"reserved:\", wallet.reserved_usd);\n\nconst usage = await get(\"/usage?days=7\");\nconsole.log(\"totals:\", usage.totals);\nconsole.table(usage.models); // most spend first\n\nconst jobs = await get(\"/jobs?api_key_id=AGENT_KEY_ID&since=2026-11-30T00:00:00Z&limit=500\");\nconsole.log(jobs);"}, "label": "Balance, 7-day usage and one key's jobs"}
```

- `GET /v1/wallet` returns `available_usd`, `reserved_usd` (held by running jobs) and `debt_usd`. See [Wallet](https://raywake.si/docs/reference/wallet).
- `GET /v1/usage?days=7` (also `30` or `90`) returns totals, a per-day series, a per-model breakdown sorted by spend and failure reasons with counts. See [Usage](https://raywake.si/docs/reference/usage).
- `GET /v1/jobs` filters by `api_key_id`, `source`, `model`, `status`, `since` and `until`, and every job carries `charged_usd`. See [Jobs](https://raywake.si/docs/reference/jobs).

## Checklist

- One API key per agent or workflow, with only the permissions it needs and an expiry.
- Hourly and daily spending limits set on the Alerts page.
- Every generate call preceded by a quote and a check against a ceiling.
- One saved `Idempotency-Key` per intended generation, reused on retries.
- Held statuses checked later, never resubmitted automatically.
- For MCP: a per-generation limit chosen at connect, plus client confirmation on `generate`.

The same flow as an importable [n8n workflow](https://raywake.si/blog/n8n-quote-approve-generate-workflow) waits for a human approval link before it generates. For a worked example with real models, see [product photos with an API, without breaking the label](https://raywake.si/blog/product-photo-api-keep-label-text).

```raywake-component
{"type": "cta", "id": "api", "label": "Read the API quickstart"}
```

## Related

- [Türkçe sürüm](https://raywake.si/tr/blog/yapay-zeka-ajani-harcama-kontrolu)
- [Raywake Blog](https://raywake.si/blog)
