# API reference (v1)

The CapVM REST API: every route, field and error code for machines, exec, usage, balance, signup and (Coming soon) card top-ups. An OpenAPI 3.1 document is at https://capvm.com/openapi.json.

- **Base URL:** `https://api.capvm.com/v1`
- **Auth:** `Authorization: Bearer ak_test_…` or `ak_live_…`. Every `/v1` route needs it except `POST /v1/signup`.
- **JSON:** request and response fields and enum values are `snake_case`.
- **Money:** integer micro-USD (`1 USD = 1_000_000`). Never send floats.
- **Scope:** machines, exec and usage only see the calling key's own machines. Balance is shared across the organization.
- *Coming soon:* `/v1/account` and `/v1/org/*` also accept a dashboard session; `/mcp` also accepts OAuth tokens. See [Organization](#organization-coming-soon) and [OAuth](#oauth-coming-soon).
- **Rate limit:** 120 requests per 60 seconds per key. Over the limit you get `429 rate_limited` with a `Retry-After` header: the seconds until the oldest counted request leaves the window.

## Machines

### `POST /v1/machines`: create

| Header | Required | Notes |
|---|---|---|
| `Idempotency-Key` | yes | 1 to 255 visible characters after trimming (no control characters), sent once, scoped to the key. Same key + same body → the same machine. Different `sku`/`ttl_seconds` → `409 idempotency_conflict`. |

| Body field | Type | Required | Notes |
|---|---|---|---|
| `sku` | string | yes | `arm-small` or `gpu-l4`, and it must be in the key's allow-list |
| `ttl_seconds` | integer | yes | 60 to 7200 |

What happens, all in one transaction: the request is validated, the hold (`ceil(price_per_hour_micro × ttl_seconds / 3600)`) is checked against the org's available credits and then against the key's spend cap (charged + held + this hold), then the key's concurrency limit and the new-account limits are checked. Only after that does the machine launch. Response: `201` with a [Machine](#machine-object).

Errors: `400` sku_required, unknown_sku, ttl_seconds_required, ttl_out_of_range, idempotency_key_required, idempotency_key_invalid (see below), invalid_json · `402` insufficient_credits, spend_cap_exceeded · `403` sku_not_allowed, account_limit_reached, terms_not_accepted (see [Signup](signup.md#403-terms_not_accepted)), account_suspended (`New machines are suspended while a payment dispute is open.`, see [Billing → Refunds and disputes](billing-and-caps.md#refunds-and-disputes)) · `409` idempotency_conflict, concurrency_limit_exceeded · `502` provider_error · `503` capacity_unavailable, launches_disabled. If a launch fails with `502` or `503`, the hold is released. `account_suspended` is checked right after an idempotent replay is returned and before the Terms gate, the TTL range, the SKU and credits, so a replay of a machine you already created still returns it during a dispute. Your balance can be negative after a refund or dispute; any new hold is then more than what's available, so create returns `402 insufficient_credits` (`Need {hold} micro-USD for this lease but only {balance} micro-USD is available.`, with the negative number).

Idempotency-Key errors (exact text):

| Case | Error |
|---|---|
| Header missing or sent more than once | `400 idempotency_key_required` `Idempotency-Key header is required.` |
| Empty or whitespace-only value (HTTP strips surrounding spaces, so a whitespace-only header arrives empty) | `400 idempotency_key_required` `Idempotency-Key header is required.` |
| Over 255 characters after trimming, or a control character | `400 idempotency_key_invalid` `Idempotency-Key must be 1 to 255 visible characters.` |

A rejected key takes no hold and launches nothing. Checkout follows the same codes over REST today, but its messages name `idempotency_key`, not the header; see [Card top-ups](#post-v1checkoutsessions-start-a-card-top-up).

> **Coming soon:** one shared key check for machine create and checkout over REST and MCP (keys trimmed and stored trimmed, emoji allowed, only control characters rejected), with slightly different error messages.

### `GET /v1/machines`: list
`200 {"machines":[Machine…]}`, the key's 100 most recent machines, newest first.

### `GET /v1/machines/{id}`: get
`200` Machine, or `404 not_found` if the ID doesn't exist or belongs to another key.

### `DELETE /v1/machines/{id}`: stop
Stops the machine, charges the billed seconds and releases the rest of the hold. `200` returns the Machine with `charge_micro`. Calling it on a machine that's already settled returns that machine unchanged.

### `POST /v1/machines/{id}/exec`: run a command

> **Available.**

Runs one shell command on a `ready` machine owned by the calling key.

| Body field | Type | Required | Notes |
|---|---|---|---|
| `command` | string | yes | 1 to 8192 characters, no NUL. Only whitespace counts as missing. |
| `timeout_seconds` | integer | no | 1 to 300, default 30 |
| `working_directory` | string | no | Absolute path, 1 to 256 characters, starting with `/`. Each segment uses only ASCII letters, digits, `.`, `_` and `-`; no `.` or `..` segments, no `//`, no trailing `/` (except `/` itself). Surrounding whitespace is trimmed. Leave it out (or send only whitespace) for the machine's default directory. |

`200`:

```json
{"stdout":"…","stderr":"","exit_code":0,"truncated":false}
```

- A non-zero `exit_code` is still a `200` result (for example `exit 7` returns `exit_code` 7).
- `stdout` and `stderr` are each capped at 256 KiB (262,144 bytes), cut on a UTF-8 character boundary. `truncated` is `true` if either stream was cut. In rare cases CapVM can return only a shorter copy of the output (at most 24,000 characters of `stdout` and 8,000 of `stderr`); `truncated` is then `true` if that copy was cut.
- **Before sending**, CapVM checks that the machine's command agent is online. If it doesn't, the call returns `409 machine_not_ready` (`Machine is running but is not accepting commands yet.`) without storing or sending anything.
- **Pickup window:** if the machine hasn't started the command **30 seconds** after it was sent, CapVM cancels it.
- **Cancelled commands:** if the command was cancelled before it started you get the same `409 machine_not_ready`; it never ran, so it's safe to retry. If it had started, you get `408 command_timeout`.
- **Timeout:** `timeout_seconds` is how long the command may run on the machine. CapVM waits at most `timeout_seconds` + 75 seconds; if there's still no result, it cancels the command and returns `408 command_timeout`. A `408` means the command hit a timeout and may or may not have started: **it may have run partly or fully, so don't blindly retry.**
- **No exit code:** if the command finished (success or failure) but without an exit code, you get `502 provider_error` `The machine did not report an exit code.` and no output.
- `exec` isn't billed per call: it writes nothing to the credit ledger, including on errors. You pay only for the machine's lease time.
- Your command runs with `bash` on the machine (after `cd -- '<working_directory>'` if you set one). If the machine can't download the command script, `exit_code` is the download tool's exit code (`curl`, or `wget` if `curl` is missing), not your command's.
- **Output isn't kept.** Command output is stored only temporarily in Zurich so it can be returned to you, and deleted once returned (at the latest after 1 day). There's no route to fetch it again, and a later call can't see it.
- **Command text isn't kept.** CapVM records each call that reaches the machine with a hash and the length of the command, never the command text, the working directory or the output.
- The command agent on a new machine can lag behind `ready` by about a minute. Retry on `409 machine_not_ready`.

Errors, in the order they're checked (exact messages):

| Status | Code | Message | When |
|---|---|---|---|
| 400 | `command_required` | `command is required.` | `command` missing, empty or only whitespace |
| 400 | `command_too_long` | `command must be 1 to 8192 characters.` | Longer than 8192 characters, **or** contains a NUL |
| 400 | `timeout_out_of_range` | `timeout_seconds must be between 1 and 300.` | |
| 400 | `working_directory_invalid` | `working_directory must be an absolute path of letters, digits, dots, underscores, and hyphens.` | Fails any rule above |
| 404 | `not_found` | `Machine was not found.` | Unknown ID or another key's machine |
| 409 | `machine_not_running` | `Machine is not running. The lease has expired.` | Past `expires_at` |
| 409 | `machine_not_running` | `Machine is not running.` | `stopping`, `terminated` or already settled, or the instance stopped running during the call |
| 409 | `machine_not_ready` | `Machine is not ready yet.` | Not `ready` yet |
| 409 | `machine_not_ready` | `Machine is running but is not accepting commands yet.` | The machine's command agent isn't online yet, or the command was cancelled before it started; it didn't run, so retry |
| 408 | `command_timeout` | `Command timed out.` | The command ran past `timeout_seconds`, gave no result within `timeout_seconds` + 75 s, or was cancelled after it started; it may have had effects, so don't blindly retry |
| 502 | `provider_error` | `The machine did not report an exit code.` | The command finished (success or failure) with no exit code; no output is returned |
| 502 | `provider_error` | `The compute provider failed to run the command.` | Any other failure of the compute provider |
| 500 | `internal_error` | `The command finished but the audit record could not be stored.` | The command ran, but CapVM couldn't record the call; the output isn't returned |

### Machine object

| Field | Type | Notes |
|---|---|---|
| `id` | string | `m_` + 32 hex characters |
| `sku` | string | |
| `state` | enum | `requested`, `provisioning`, `ready`, `stopping`, `terminated` |
| `instance_id` | string\|null | provider instance ID |
| `public_ip` | string\|null | |
| `region` | string | `eu-central-2` |
| `ttl_seconds` | int | |
| `price_per_hour_micro` | int64 | price locked when the machine was created |
| `hold_micro` | int64 | amount reserved at create |
| `charge_micro` | int64\|null | set once the machine is settled |
| `created_at`, `expires_at` | date-time | `expires_at = created_at + ttl_seconds` |
| `ready_at`, `stop_requested_at`, `terminated_at` | date-time\|null | |

## Account

### `GET /v1/usage`
The calling key's numbers:
`{"spend_micro","held_micro","spend_cap_micro","events":[{"id","machine_id","sku","seconds","amount_micro","created_at"}]}`. `events` holds the 100 most recent.

### `GET /v1/balance`
The organization's numbers:
`{"available_micro","held_micro","currency":"USD","unit":"micro_usd"}`. `available_micro` already excludes holds. It can be negative after a Stripe refund or dispute.

## Top-ups

> **Coming soon.** Card top-ups aren't available yet; for now, CapVM adds credits to your account. The routes below describe how they will work. Also Coming soon as the MCP tool [`create_checkout_session`](mcp.md#create_checkout_session).
>
> **The `amount_usd` wire format may change**, possibly to integer cents (`1000` = $10). Don't hard-code it yet.

### `POST /v1/checkout/sessions`: start a card top-up (Coming soon)

Creates a Stripe Checkout Session for prepaid credits and returns its URL. **A human pays on that page.** The agent only creates the session and passes the link on. Credits arrive when Stripe reports the payment.

| Header | Required | Notes |
|---|---|---|
| `Authorization` | yes | `Bearer ak_…`, as for every `/v1` route |
| `Idempotency-Key` | **yes** | 1 to 255 characters after trimming, no control characters, sent once. Scoped to the **API key**, like machine create: two keys of the same organization sending the same value get two separate sessions. |

| Body field | Type | Required | Notes |
|---|---|---|---|
| `amount_usd` | string or integer | yes | USD. A JSON integer is whole dollars (`10`). A string can have cents, with at most two decimals (`"10"`, `"10.5"`, `"10.50"`). A JSON number with a decimal point (`10.5`, also `10.0`) is rejected, and so are signs, exponents and more than two decimals. **Minimum $10, maximum $1000.** |
| `success_url` | string | no | Absolute `http`/`https` URL, 8 to 2048 characters, no spaces or `user:pass@`. Where Stripe sends the payer afterwards. If left out, CapVM's configured URL is used, by default `https://capvm.com/checkout/success` (no query string added). |
| `cancel_url` | string | no | Same rules. Default `https://capvm.com/checkout/cancel` (also not built yet). |

A value that's only whitespace counts as left out. The maximum top-up is $1000.

```bash
curl -X POST https://api.capvm.com/v1/checkout/sessions \
  -H "Authorization: Bearer ak_test_..." \
  -H "Idempotency-Key: topup-2026-10-25" \
  -H "Content-Type: application/json" \
  -d '{"amount_usd":"25.00"}'
```

`201`:

```json
{"id":"cs_test_…","url":"https://checkout.stripe.com/…"}
```

The Checkout page Stripe shows:

- One line item, "CapVM credits", for the amount, in **USD**, payment mode (a one-off payment).
- Prices **exclude VAT**. By default Stripe Tax adds VAT where it applies (`automatic_tax`), so the payer can be charged more than `amount_usd`. 
- A **Company name** field the payer must fill in, an optional VAT ID field, and a **billing address** the payer must enter.
- Above the pay button, CapVM's checkout notice (`checkout-notice-0.2`): "No refunds during the beta: credits are non-refundable and never expire. You are buying USD {amount, e.g. 25.00} in CapVM credits (plus VAT where applicable) for {organization name}. Usage by you and your agents is deducted per second. By paying, you agree to the Terms of Service and the Billing and Refund Policy."

**What gets credited:** the price **before tax**, converted to micro-USD (`$25.00` → `25000000`). VAT is never credited. Only USD sessions are credited. A paid top-up also lifts the new-account limits for your organization (it marks it trusted).

**Retrying:** the same `Idempotency-Key` from the same API key, with the same amount and URLs, returns the same session (Stripe's own idempotency, keyed on your API key and the key). The same key with a different amount or URL gets `409 idempotency_conflict`. CapVM records one "checkout notice shown" entry per session, written only after Stripe has returned the session; a retry that gets the same session back doesn't add another.

**Invoices:** CapVM turns on Stripe's invoice creation for every Checkout Session (`invoice_creation`), so Stripe creates an invoice for each paid top-up, with the description "CapVM prepaid compute credits".

Checked in this order (exact messages):

| Status | Code | Message | When |
|---|---|---|---|
| 400 | `validation_error` | `amount_usd is required.` | No body, or `amount_usd` missing, `null`, empty or not a string/number |
| 400 | `validation_error` | `amount_usd must be an integer number of cents. Send a whole number of dollars, or a string with at most two decimal places.` | Bad format (above) |
| 400 | `validation_error` | `amount_usd must be positive.` | A negative JSON integer |
| 400 | `validation_error` | `amount_usd is too large.` | A JSON integer so large that it overflows when converted to cents |
| 400 | `idempotency_key_required` | `idempotency_key is required.` | Header missing, sent more than once, empty or only whitespace (the message names the MCP param, not the header). Machine create treats whitespace-only as `idempotency_key_invalid`; Coming soon: the same for a whitespace-only MCP key (a whitespace-only REST header reaches the server empty and stays `idempotency_key_required`), names the header in REST messages, and makes a header sent twice `idempotency_key_invalid` (see [create](#post-v1machines-create)) |
| 400 | `idempotency_key_invalid` | `idempotency_key must be 1 to 255 visible characters.` | Over 255 characters after trimming, or containing a control character |
| 400 | `min_topup_not_met` | `Minimum top-up is 10000000 micro-USD ($10).` | Under $10 (for example `"9.99"` or `9`) |
| 400 | `max_topup_exceeded` | `Maximum top-up is 1000000000 micro-USD ($1000.00).` (with the server's maximum) | Over the maximum (for example `"1000.01"`) |
| 400 | `validation_error` | `success_url must be an absolute http(s) URL.` (or `cancel_url …`) | Bad URL |
| 403 | `terms_not_accepted` | as in [Signup](signup.md#403-terms_not_accepted), with `required_versions` and `accept_url` | No current Terms acceptance. Checked before Stripe is called: no session is created and nothing is recorded. |
| 400 | `terms_acceptance_required` | `No Terms of Service version is effective yet.` (`required_versions: null`) | A non-production server before any Terms version is in effect |
| 503 | `stripe_not_configured` | | Card payments are unavailable |
| 409 | `idempotency_conflict` | `This Idempotency-Key was already used with a different checkout request.` | See Retrying |
| 502 | `stripe_error` | `Stripe could not create the Checkout Session.` or `Stripe did not return a Checkout Session URL.` | Stripe failed |

None of these errors records a checkout notice: it's written only once Stripe returns a session. An open dispute does **not** block starting a top-up (`account_suspended` is only on machine create).

There is **no refunds route**: credits are non-refundable (Terms §7). Refunds and disputes change your balance: see below.

### When credits arrive, refunds and disputes

- Credits arrive once Stripe confirms the payment, once per Checkout Session. A payment method that settles later is credited when it settles.
- A refund is taken back only once it **succeeds**: the pre-tax share of what the payment credited (refund amount × credited amount ÷ the gross charge including VAT). If a refund that was taken back later fails or is canceled, it's credited back once. The balance can go negative.
- A card issuer's inquiry changes nothing.
- A dispute (chargeback) takes back the pre-tax share of the disputed amount and suspends new machines (`403 account_suspended` on `POST /v1/machines`). A won dispute gives the credits back; a lost one keeps them taken. New machines are allowed again once no dispute is open.
- When a dispute opens, or a refund leaves the balance negative, CapVM stops and destroys every running machine of the organization within seconds (billed up to the stop, rest of each hold released) and emails the account once (subject `CapVM stopped your machines`). Stopped machines aren't restarted after a won dispute. Details: [Billing → Refunds and disputes](billing-and-caps.md#refunds-and-disputes).

## Signup (public)

### `POST /v1/signup`
> Available. Starts a signup for a business; a human must confirm by email before anything works. No API key needed. Limited to 5 requests per hour per client IP and 5 per hour per `accepted_by_email`; over that, `429 rate_limited` `Signup rate limit exceeded.` with `Retry-After` (seconds left in the window). Repeating it for the same email while that organization is still pending sends a new link, voids the old one, and replaces the company name, country and VAT ID with the newest values. If the email can't be sent: `503 email_send_failed` with `Retry-After: 30`; retry the call. Full contract: [Signup and Terms acceptance](signup.md).

## Account details (Coming soon)

> **Coming soon.**

### `GET /v1/account`
Works with an `ak_` key or with a signed-in [dashboard](dashboard.md) session cookie (no bearer). Returns `200 {"org_id","company_name","status","balance_micro","frozen"}`. Without either: `401 unauthorized` `Authorization is required.` With an `ak_` key of a frozen organization it returns `403 org_frozen`, like other key routes (see [Frozen organizations](dashboard.md#frozen-organizations)).

## Organization (Coming soon)

> **Coming soon.** For people signed in to the [dashboard](dashboard.md), not agents.

- **Auth:** the dashboard session cookie (`__Host-capvm_session`). `ak_` keys and OAuth tokens aren't accepted. No session: `401 unauthorized` `Authorization is required.`
- **Writes** (`POST`, `PATCH`, `DELETE`) also need the antiforgery token from a dashboard page in a `RequestVerificationToken` header; without it: `400 validation_error` `Antiforgery token is required.`
- **Scope:** the whole organization, not one key.

### `GET /v1/org/keys`
`200 {"keys":[…]}`, newest first, revoked keys included. Each key: `id`, `label` (or `null`), `prefix`, `created_at`, `created_ip` (or `null`), `last_used_at` (its latest machine create or usage record, or `null`), `revoked_at` (or `null`), `spend_cap_micro`.

### `POST /v1/org/keys`
Body `{"spend_cap_micro": 5000000, "label": "Codex laptop"}`. `label` is optional. Returns `201 {"id","secret","label","prefix","spend_cap_micro","created_at"}`. **`secret` is the full `ak_live_…` key and is shown only here.** The key may use every SKU and run 10 machines at once. Sends the `CapVM API key created` alert email.

| Status | Code | Message / when |
|---|---|---|
| 403 | `reauth_required` | `Sign in again to continue.` No sign-in or confirmation in the last 5 minutes |
| 400 | `validation_error` | `spend_cap_micro is required.` / `spend_cap_micro must be positive.` / `label must be 1 to 80 characters.` (after trimming; control characters count as invalid; an empty label is stored as `null`) |
| 403 | `org_frozen` | `This organization is frozen.` |
| 403 | `terms_not_accepted` | No current Terms acceptance |

### `PATCH /v1/org/keys/{id}`
Body with `label`, `spend_cap_micro` or both. Returns `200` with the key (same fields as in the list).

| Status | Code | Message / when |
|---|---|---|
| 400 | `validation_error` | `label or spend_cap_micro is required.` / `spend_cap_micro must be positive.` / `label must be 1 to 80 characters.` |
| 404 | `not_found` | `API key was not found.` |
| 400 | `key_revoked` | `API key has been revoked.` |
| 403 | `org_frozen` | Renaming or raising the cap while frozen (lowering still works) |
| 403 | `reauth_required` | `Sign in again to continue.` Raising the cap without a sign-in in the last 5 minutes |

### `DELETE /v1/org/keys/{id}`
Revokes the key. Returns `200 {"id","revoked_at"}`; revoking an already revoked key returns its original `revoked_at`. Works while frozen. `404 not_found` `API key was not found.`

### `GET /v1/org/machines`
`200 {"machines":[…]}`: every machine in the organization, same fields as [`GET /v1/machines`](#machines).

### `DELETE /v1/org/machines/{id}`
Stops any machine in the organization. Returns `200` with the machine. Works while frozen. `404 not_found` `Machine was not found.`

### `GET /v1/org/usage`
The organization's usage, same response shape as [`GET /v1/usage`](#account).

### Sign-in routes (browser pages)
`/signin`, `/signin/confirm/{token}`, `POST /signin/code`, `/signin/reauth`, `POST /signin/reauth/code`, `/signin/lockdown/{token}`, `POST /signout`, `POST /signout/all`, `/dashboard`. They're pages for people, not an API; their behavior and errors are in [Dashboard](dashboard.md). Sign-in requests: `429 rate_limited` `Sign-in rate limit exceeded.` (5 per hour per IP and per email), `400 invalid_email` `email must be a valid address.`

## OAuth (Coming soon)

> **Coming soon.** How to connect a client: [MCP → Connect with OAuth](mcp.md#connect-with-oauth-coming-soon).

OAuth access tokens work **only on `/mcp`**. On `/v1` routes they get `401 invalid_api_key`. OAuth endpoint errors use the OAuth shape `{"error":"…","error_description":"…"}`, not CapVM's `{"error":{"code","message"}}`, except where noted.

### Discovery
- `GET /.well-known/oauth-protected-resource` and `GET /.well-known/oauth-protected-resource/mcp` (RFC 9728): `{"resource":"https://api.capvm.com/mcp","authorization_servers":["https://api.capvm.com"],"scopes_supported":["mcp","offline_access"]}`.
- `GET /.well-known/oauth-authorization-server` (RFC 8414): issuer `https://api.capvm.com`, `authorization_endpoint` `https://api.capvm.com/oauth/authorize`, `token_endpoint` `https://api.capvm.com/oauth/token`, `revocation_endpoint` `https://api.capvm.com/oauth/revoke`, `registration_endpoint` `https://api.capvm.com/oauth/register` (absolute URLs on the issuer), `code_challenge_methods_supported` `["S256"]`, `token_endpoint_auth_methods_supported` `["none"]`, `grant_types_supported` `["authorization_code","refresh_token"]`, `scopes_supported` `["mcp","offline_access"]`.

### `POST /oauth/register`
Dynamic client registration (RFC 7591), public clients only. Body:

| Field | Required | |
|---|---|---|
| `redirect_uris` | yes | Non-empty array of strings. Each must be `https`, or `http` on `127.0.0.1` or `localhost`; no fragment, no user info. For `127.0.0.1`/`localhost` the port can differ at authorize time; other hosts must match exactly (scheme, host, path, query, port) |
| `client_name` | no | Trimmed, at most 120 characters. Missing, blank or not a string: `Unverified app` |
| `grant_types` | no | `authorization_code`, `refresh_token` or both. Default both |
| `response_types` | no | `code`. Default `["code"]` |
| `token_endpoint_auth_method` | no | Must be `none` |
| `client_secret` | must be absent | |

Returns `201 {"client_id","client_name","redirect_uris","token_endpoint_auth_method":"none","grant_types","response_types"}`. Rate limit: 10 registrations per hour per IP, `429 rate_limited` `Registration rate limit exceeded.` (CapVM error shape) with `Retry-After`.

Errors are `400 {"error":"invalid_client_metadata","error_description":…}` with:

| `error_description` |
|---|
| `Request body must be valid JSON.` / `Request body must be a JSON object.` |
| `Public clients must not send client_secret.` / `token_endpoint_auth_method must be none.` |
| `redirect_uris is required.` / `redirect_uris must be a non-empty array of strings.` / `redirect_uris must be https, or http on 127.0.0.1 or localhost.` |
| `grant_types must be a non-empty array of strings.` / `grant_types must be authorization_code, refresh_token, or both.` |
| `response_types must be a non-empty array of strings.` / `response_types must be code.` |
| `client_name must be at most 120 characters.` |

### `GET /oauth/authorize`
Authorization code flow with PKCE (`code_challenge_method=S256` required; `plain` isn't offered). Required: `resource=https://api.capvm.com/mcp` and a scope that includes `mcp` (only `mcp` and `offline_access` are allowed). The browser signs in and confirms within 5 minutes if needed, then sees the approval page, which posts back to the same URL with `decision=approve` and `spend_cap_usd` (whole dollars, 1 to 1000). The code lasts 60 seconds.

| Result | When |
|---|---|
| `400 {"error":"invalid_target","error_description":"resource must be https://api.capvm.com/mcp."}` | `resource` missing or different (several identical values count as one) |
| `invalid_client` `The client is unknown.` / `invalid_request` `redirect_uri does not match a registered URI.` / `redirect_uri is not an absolute URI.` | Bad client or redirect |
| Redirect with `error=invalid_scope` (`scope must include mcp.`) | Other scopes, or no `mcp` |
| Redirect with `error=access_denied`, `error_description=org_pending` | Organization still `pending_acceptance` |
| Redirect with `error=access_denied` (`The resource owner denied the request.`) | **Deny** clicked |
| Redirect with `error=access_denied`, `error_description=org_frozen` | Organization frozen |
| `400 validation_error` `spend_cap_usd must be a whole number of dollars from 1 to 1000.` / `Antiforgery token is missing or invalid.` (CapVM shape) | Bad approve form |

### `POST /oauth/token`
`grant_type=authorization_code` (with `code`, `redirect_uri`, `code_verifier`, `client_id`) or `grant_type=refresh_token` (with `refresh_token`, `client_id`). Both need `resource=https://api.capvm.com/mcp` (otherwise `400 invalid_target` as above). Returns an opaque `access_token`, `"token_type":"Bearer"`, `"expires_in":900`, and a new `refresh_token` if `offline_access` was granted.

| `error` / `error_description` (400) | When |
|---|---|
| `invalid_grant` `The refresh token was reused.` | A refresh token sent again more than 60 seconds after its first use: the whole grant is revoked and an alert is emailed. Within 60 seconds the first response is returned again |
| `invalid_grant` `The grant has expired.` | 30 days after approval |
| `invalid_grant` `The refresh token is no longer valid.` | Grant revoked or unknown |

Other errors follow the OAuth 2.0 standard.

### `POST /oauth/revoke`
Token revocation (RFC 7009), form-encoded: `token` (an access or refresh token), `client_id`, optional `token_type_hint`. Returns `200`. Revoking either token revokes the whole connection (grant) and all its tokens, the same as [`DELETE /v1/org/oauth/grants/{id}`](#oauth-grants-coming-soon): the grant leaves `GET /v1/org/oauth/grants`, the next `/mcp` call gets `401`, and a refresh gets `invalid_grant`. It writes the security event `oauth_revoked` and sends no email.

### `/mcp` with an OAuth token
`401` with `WWW-Authenticate: Bearer resource_metadata="https://api.capvm.com/.well-known/oauth-protected-resource/mcp"` when there's no bearer; an expired or revoked token adds `, error="invalid_token"` and the body `{"error":{"code":"unauthorized","message":"Access token is expired or revoked."}}`. Rate limit: 120 per 60 s per grant. While the organization is frozen (same as for `ak_` keys): `initialize`, `ping` and `tools/list` work; `get_balance`, `get_usage` and `stop_machine` work; the other tools return the tool error `org_frozen`.

## OAuth grants (Coming soon)

> **Coming soon.** Same auth as [Organization](#organization-coming-soon): session cookie; antiforgery header on writes (message here: `Antiforgery token is missing or invalid.`). No session: `401 unauthorized` `Authorization is required.`

### `GET /v1/org/oauth/grants`
`200 {"grants":[{"id","client_name","verified","redirect_host","spend_cap_micro","spent_micro","created_at","last_used_at"}]}`. `verified` is always `false`.

### `PATCH /v1/org/oauth/grants/{id}`
Body `{"spend_cap_micro": 10000000}`. Returns `200 {"id","spend_cap_micro"}`.

| Status | Code | Message / when |
|---|---|---|
| 400 | `validation_error` | `spend_cap_micro is required.` / `spend_cap_micro must be between 1000000 and 1000000000.` |
| 404 | `not_found` | `Grant was not found.` (unknown or revoked) |
| 403 | `org_frozen` | Raising the cap while frozen |
| 403 | `reauth_required` | `Sign in again to raise this spend cap.` Raising without a sign-in in the last 5 minutes |

Lowering works while frozen and without a fresh sign-in. Changing the cap doesn't change `last_used_at`.

### `DELETE /v1/org/oauth/grants/{id}`
Revokes the grant and all its tokens. Returns `200 {"id","revoked_at"}`. No email is sent. `404 not_found` `Grant was not found.`

## Errors

Every error has the same shape: `{"error":{"code":"…","message":"…"}}`. Two errors add fields: `terms_not_accepted` adds `required_versions` and `accept_url`, and `terms_acceptance_required` adds `required_versions`. See [Signup](signup.md).

| Status | Codes |
|---|---|
| 400 | `sku_required` `unknown_sku` `ttl_seconds_required` `ttl_out_of_range` `idempotency_key_required` `idempotency_key_invalid` `command_required` `command_too_long` `timeout_out_of_range` `working_directory_invalid` `terms_acceptance_required` `link_used` (only from the human confirmation page and form `/signup/confirm/{token}`) `min_topup_not_met` `max_topup_exceeded` `invalid_json` `validation_error` `invalid_email` `invalid_source` |
| 401 | `unauthorized` (missing bearer) `invalid_api_key` `key_revoked` |
| Coming soon | `400 code_invalid` (with `tries_left`) · `410 code_burned` · `403 org_frozen` · `403 reauth_required` · `400 key_revoked` (`PATCH /v1/org/keys/{id}`) · `400`/`410` `link_used`/`link_expired` on sign-in and lockdown pages. See [Dashboard](dashboard.md) |
| Coming soon | OAuth shape `{"error","error_description"}`: `invalid_client_metadata`, `invalid_target`, `invalid_grant`, `invalid_scope`, `access_denied`. See [OAuth](#oauth-coming-soon) |
| 402 | `insufficient_credits` `spend_cap_exceeded` |
| 403 | `sku_not_allowed` `account_limit_reached` `terms_not_accepted` `account_suspended` (machine create during an open payment dispute) |
| 404 | `not_found` |
| 408 | `command_timeout` |
| 409 | `idempotency_conflict` `concurrency_limit_exceeded` `machine_not_ready` `machine_not_running` `details_changed` (only from the human acceptance form `POST /signup/confirm/{token}`; the acceptance page again unless `Accept` prefers JSON, see [Signup](signup.md#submitting-the-form)) |
| 410 | `link_superseded` `link_expired` (only from the human confirmation page and form `/signup/confirm/{token}`. These, `400 link_used`, `404 not_found` for an unknown link, and the form-token `400 validation_error` errors are an HTML status page unless the `Accept` header prefers `application/json` over `text/html`: no `Accept`, `*/*` alone, or a tie gets HTML. See [Signup → HTML or JSON](signup.md#html-or-json)) |
| 429 | `rate_limited` (also on `POST /v1/signup`) |
| 500 | `internal_error` (on exec: the command finished but CapVM couldn't record the call) |
| 502 | `provider_error` `stripe_error` |
| 503 | `capacity_unavailable` `launches_disabled` `email_send_failed` (with `Retry-After: 30`) `stripe_not_configured` |

## Not in the API for agents

CapVM creates organizations, issues and revokes keys, adds credits by hand and lifts new-account limits. Agents can't add credits or set a balance. (An agent can start a card top-up with [`POST /v1/checkout/sessions`](#post-v1checkoutsessions-start-a-card-top-up), but a human pays.) Issuing a key and adding credits need a current Terms acceptance, and issued keys record the Terms and AUP versions in force. If your account needs an acceptance link, ask CapVM (see [Signup](signup.md#how-to-resolve-it)).
