# threefold Error Contract

Every threefold API error and MCP tool error returns a uniform, agent-friendly error body:

```json
{
  "error": "Human-readable description of the problem",
  "code": "machine_readable_code",
  "whose_error": "caller" | "upstream" | "threefold",
  "retryable": true | false,
  "hint": "Actionable suggestion to resolve or work around the error",
  "request_id": "A short unique error reference"
}
```

Payment-related errors (`402`) include additional quantitative fields from phase 2 metering to explain balance and budget limits. Rate limit responses (`429`) always include the `Retry-After` HTTP header.

Every error gets a fresh `request_id`; MCP tool errors also carry it in `_meta.request_id` and `_meta.error.request_id`. Check [service status](https://threefold.eco/status) and [how to get help](https://threefold.eco/help/) first. For persistent internal or upstream errors, email [info@threefold.eco](mailto:info@threefold.eco) with the request ID, error code and time. Never send a full API key or other secret. The error-reference log records the ID and code, not the key.

**How a hint is built** (`publicError`, `modules/platform/errors.mjs`). An error with a hint of its own gets that hint, then the default hint for its code, which ends with a documentation link. An error with no hint of its own gets the default. One case differs: an invalid request (`invalid_request`) at a known endpoint. Its default is that endpoint's own inputs page (`GET /api/discover/<endpoint id>`), and when the error has its own hint, that hint is the whole correction (for example "Call again with market=es: GET /api/paid?market=es") and nothing is added.

For hosted MCP, `X-Threefold-Request-Id` matches the error reference when the server sends an error body. Some JSON-RPC errors are emitted directly by the MCP HTTP transport before the server can add `error.data`; for those, quote the header instead. The transport preserves non-object JSON-RPC `error.data` unchanged, so such errors also use the header. HTTP transport references and error codes are logged without API keys. For stdio, a protocol error with non-object `error.data` is passed through unchanged and has no header.

---

## Closed Set of Error Codes

| Code | HTTP Status | Whose Error | Retryable | Description & Hint |
|---|---|---|---|---|
| `invalid_request` | 400 | `caller` | `false` | Malformed parameters, missing required arguments, or invalid JSON. The hint names the endpoint's own inputs page, `GET /api/discover/<endpoint id>` (inputs and one example). It does not name `/openapi.json`: that file is 1.8 MB, for code generators. |
| `unauthorized` | 401 | `caller` | `false` | Missing, invalid, expired or revoked API key or session. Provide `Authorization: Bearer tf_live_...`. |
| `sign_in_required` | 401 | `caller` | `false` | Unauthenticated (keyless) caller attempted a `fresh_pull` or `ai_brief` endpoint. Sign in or provide an API key to access live ingest and AI analyses. |
| `forbidden` | 403 | `caller` | `false` | API key lacks required scope, CSRF validation failed, or route is operator-only. Check scopes or permissions. |
| `not_found` | 404 | `caller` | `false` | Route, app, job, analysis, or report not found in the library, or a chart (market × store × genre × chart type) that has not been collected: chart endpoints never answer an uncollected chart with empty lists, and the hint lists the charts that market has. Label endpoints (`label_profile`, `label_compare`, `language_fit`) answer the same way when nothing in scope has been labelled yet (a compare's message names the from or to market), and `market_take` when no take has been written. Verify the ID or discover available endpoints via `GET /api/discover`. |
| `insufficient_balance` | 402 | `caller` | `false` | Workspace wallet balance is lower than the endpoint price. The `error` text states both amounts. The person tops up on the account page (`#/account`): spending is the person's choice, so the hint names no checkout call. |
| `spend_cap_exceeded` | 402 | `caller` | `false` | Per-key monthly spend cap reached. Raise the cap or wait for the monthly allowance refresh. |
| `fresh_pull_unpriced` | 402 | `caller` | `false` | Endpoint cost class `fresh_pull` is operator-only until pricing calibration completes. Use cached library reads. |
| `plan_limit` | 402 | `caller` | `false` | Workspace plan quota exceeded (e.g. tracked apps limit, target markets limit, or analysis allowance). The person changes the plan on the account page (`#/account`). |
| `conflict` | 409 | `caller` | `true` | A request with the same `Idempotency-Key` is currently in flight. Wait for the in-progress operation to settle. When the key was already used for another endpoint, `retryable` is `false`: send a new key. |
| `rate_limited` | 429 | `caller` | `true` | Request rate limit exceeded. Respect the `Retry-After` header before retrying. |
| `not_implemented` | 501 | `threefold` | `false` | Feature unavailable on this server in its current mode (e.g. priced endpoints or Play Store scraping in JSON mode without Postgres; PDF rendering without Playwright; billing not set up). It is the server's state, not a fault in the request: the same call fails until the server changes. |
| `upstream_error` | 502 / 504 | `upstream` | `true` | Upstream data provider failed or timed out. Retry with exponential backoff, check [status](https://threefold.eco/status), and contact info@threefold.eco with the request ID, code and time if it persists. |
| `internal_error` | 500 | `threefold` | `false` | Unexpected threefold internal server error. Check [status](https://threefold.eco/status) and email info@threefold.eco with the request ID, code and time. |

---

## Warnings on a successful answer

A `GET` that answers 200 can carry a `warnings` array of plain sentences (`api/query-input.mjs`). It names each query parameter that the route did not use, with the nearest valid name. The status and the rest of the answer are the same as without it.

```json
{ "items": [], "warnings": ["Unknown parameter \"country\" was ignored. Did you mean \"market\"? Inputs: GET /api/discover/paid_ads."] }
```

Other names that are accepted: `genre` and `category` for `niche`, on every route whose input is `niche`; `market` for `to` on `GET /api/apps/<id>/brief`.

---

## A country value that is not a country code

A country input takes a market code: `es`, `mx`, `jp` (the 32 codes are in `GET /api/meta` and in each tool's schema). Any other value is a 400 `invalid_request` that carries its own correction: the value sent, the code it most likely meant, and the corrected call. The rule is one function (`modules/core/market-code.mjs`) for every REST input that the registry types as a country, in a query or a JSON body, and for the four agent tools.

```json
{
  "error": "market: \"Spain\" is not a country code. Did you mean \"es\" (Spain)?",
  "code": "invalid_request",
  "whose_error": "caller",
  "retryable": false,
  "hint": "Call again with market=es: GET /api/paid?market=es&niche=health-fitness"
}
```

- It reads a country's name in English and in its own language (`Spain`, `España`), a three-letter code (`ESP`) and a locale tag (`es-MX` means `mx`, `fr-CA` means `ca-fr`), in any case.
- With no close match, the error lists the valid codes.
- A code in another case (`ES`) is accepted as the code on REST. The tools' schemas list the codes in lower case.
- A valid code that the library holds no data for (`it`) is not this error. The answer says that 10 of the 32 countries have data.
- Over MCP the same sentence arrives as the tool's input validation error: `Input validation error: Invalid arguments for tool market: "Spain" is not a country code. Did you mean "es" (Spain)? at market`.

---

## Payment Error Fields

When `code` is one of `insufficient_balance`, `spend_cap_exceeded`, `fresh_pull_unpriced`, or `plan_limit`, the response body also includes:

- `endpoint_id` (string): The identifier of the endpoint called.
- `balance_micro_usd` (integer, optional): Current workspace balance in micro-USD ($1.00 = 1,000,000 micro-USD).
- `required_micro_usd` (integer, optional): Price required to execute the call.
- `cap_micro_usd` (integer, optional): The key's monthly spend cap in micro-USD.
- `spent_micro_usd` (integer, optional): The key's settled + reserved spend this month in micro-USD.

---

## Example Error Responses

### Missing Parameter (400)
```json
{
  "error": "compare_markets needs --to, --niche",
  "code": "invalid_request",
  "whose_error": "caller",
  "retryable": false,
  "hint": "Inputs and an example for this endpoint: GET /api/discover/compare_markets.",
  "request_id": "f2e195a638eb0f97e61c"
}
```

### Keyless Fresh Pull Refusal (401)
```json
{
  "error": "Sign in required for fresh_pull endpoints.",
  "code": "sign_in_required",
  "whose_error": "caller",
  "retryable": false,
  "hint": "Sign in or provide an API key for live pulls and AI analyses; see https://threefold.eco/docs/accounts/.",
  "request_id": "7ac042b42f5693df1d34"
}
```

### Insufficient Balance (402)
```json
{
  "error": "Insufficient balance: the balance is $0.0001 and this call needs $0.0002.",
  "code": "insufficient_balance",
  "whose_error": "caller",
  "retryable": false,
  "hint": "This needs more wallet balance. Tell the user: top-ups are on the account page (#/account); an agent can call POST /api/billing/checkout; see https://threefold.eco/docs/accounts/.",
  "request_id": "5e0102399509ff78dbce",
  "balance_micro_usd": 100,
  "required_micro_usd": 200,
  "endpoint_id": "compare_markets"
}
```

### Rate Limited (429)
HTTP Headers:
```http
HTTP/1.1 429 Too Many Requests
Retry-After: 30
```
Body:
```json
{
  "error": "Rate limit exceeded. Retry in 30s.",
  "code": "rate_limited",
  "whose_error": "caller",
  "retryable": true,
  "hint": "Wait for the Retry-After duration; see https://threefold.eco/docs/errors/.",
  "request_id": "cc5d826ee905a15fe95f"
}
```
