# Errors

One error shape, a short list of codes, and which ones to retry.

## The error shape

Every error has the same JSON body, whatever the endpoint:

```json
{
  "error": {
    "code": "INVALID_PARAM",
    "message": "num_results must be between 1 and 50.",
    "retry_after_seconds": null,
    "details": {}
  },
  "request_id": "req_..."
}
```

- `code` is stable and meant for your code to branch on. The list is below.
- `message` is for a person. Its wording can change.
- `retry_after_seconds` is a number when waiting helps, otherwise `null`.
- `request_id` identifies the call. Quote it when you contact us.

A call that ends in an error is never charged.

## Codes

| Code | HTTP | Meaning | Retry? |
|---|---|---|---|
| `INVALID_PARAM` | 400 | A field is missing, wrong or unknown. `message` names it. | No. Fix the request. |
| `UNSUPPORTED_OPTION` | 400 | The request asks for an option this API version does not offer. | No. Remove the option. |
| `AUTH_INVALID_KEY` | 401 | The key is malformed, revoked or expired. | No. Use a valid key. |
| `AUTH_MISSING_KEY` | 401 | No `Authorization` header was sent. | No. Send a key. |
| `QUOTA_EXCEEDED` | 403 | The team has reached a limit set on its account. | No. Raise the limit or wait for the next period. |
| `ACCOUNT_NOT_ELIGIBLE` | 403 | Dashboard sign-up only: this sign-in cannot open a free account (the email is not verified, is a disposable address, or already has an account). Never returned by a `/v1` call. | No. |
| `ACCOUNT_SUSPENDED` | 403 | The account is suspended: its keys are refused until it is lifted. Nothing is charged. | No. Contact support. |
| `NOT_FOUND` | 404 | No such resource for this team. | No. |
| `RATE_LIMITED` | 429 | The plan's requests per minute, heavy-source searches per minute, or searches in flight were exceeded. | Yes, after `Retry-After` seconds. |
| `CAPACITY` | 429 | The service has no free capacity for this call right now. Nothing is charged. | Yes, after `Retry-After` seconds. |
| `INSUFFICIENT_CREDITS` | 429 | The balance does not cover the call. Nothing is charged. | No. Add credits first. |
| `INTERNAL` | 500 | Something failed on our side. Nothing is charged. | Yes, with backoff. Send us the `request_id` if it persists. |
| `SEARCH_UNAVAILABLE` | 502 | Search could not be served right now. Nothing is charged. | Yes, after `Retry-After` seconds. |

A key with a monthly cap answers `403 QUOTA_EXCEEDED` with `error.details.limit` set to `key_monthly_cap` when it has spent its cap, or when a call could cost more than the key has left (`error.details.needed_credits`). Your other keys keep working. See [The dashboard](https://millionshort.com/docs/dashboard#monthly-cap-per-key).

### Codes of Spaces

[Spaces](https://millionshort.com/docs/spaces) add two codes:

| Code | HTTP | Meaning | Retry? |
|---|---|---|---|
| `SPACE_NOT_FOUND` | 404 | No such Space for this caller: it does not exist, or it belongs to another team. The two are not told apart. | No. |
| `SPACE_READ_ONLY` | 403 | A curated Space cannot be changed or deleted. | No. Create your own Space from its fields. |

Creating more Spaces than the plan allows is a `403 QUOTA_EXCEEDED`, with the plan's number in `error.details.limit`.

## What to retry

Retry `RATE_LIMITED`, `CAPACITY` and `SEARCH_UNAVAILABLE` after the number of seconds in the `Retry-After` header, which is also `error.retry_after_seconds` in the body. Retry `INTERNAL` with a growing pause and give up after a few attempts.

Do not retry a `400`, a `401`, a `403` or `INSUFFICIENT_CREDITS`: the same request will fail the same way until something changes.

A retry loop with nothing but what curl and each language come with. curl retries a `429`, a `500` and a `502` by itself and waits as long as `Retry-After` says. It goes by the status alone and cannot read `error.code`, so it also retries `INSUFFICIENT_CREDITS`, which is a `429` too; the two programs do not:

```bash
curl --retry 3 https://api.millionshort.com/v1/search \
  -H "Authorization: Bearer $MILLIONSHORT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"query": "tide tables", "num_results": 5}'
```

```python
import json
import os
import time
import urllib.error
import urllib.request

RETRYABLE = {"RATE_LIMITED", "CAPACITY", "SEARCH_UNAVAILABLE", "INTERNAL"}


def search(body, attempts=4):
    request = urllib.request.Request(
        "https://api.millionshort.com/v1/search",
        data=json.dumps(body).encode(),
        headers={
            "Authorization": "Bearer " + os.environ["MILLIONSHORT_API_KEY"],
            "Content-Type": "application/json",
        },
    )
    for attempt in range(attempts):
        try:
            with urllib.request.urlopen(request, timeout=30) as response:
                return json.load(response)
        except urllib.error.HTTPError as failure:
            problem = json.load(failure)["error"]
            if problem["code"] not in RETRYABLE or attempt == attempts - 1:
                raise
            time.sleep(problem.get("retry_after_seconds") or 2**attempt)


print(search({"query": "tide tables", "num_results": 5})["data"]["summary"])
```

```ts
const RETRYABLE = new Set(['RATE_LIMITED', 'CAPACITY', 'SEARCH_UNAVAILABLE', 'INTERNAL']);

type Answer = { data: { summary: unknown } };
type Problem = { code: string; retry_after_seconds?: number | null };

async function search(body: object, attempts = 4) {
  for (let attempt = 0; ; attempt += 1) {
    const res = await fetch('https://api.millionshort.com/v1/search', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${process.env.MILLIONSHORT_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(body),
    });
    if (res.ok) return (await res.json()) as Answer;
    const problem = ((await res.json()) as { error: Problem }).error;
    if (!RETRYABLE.has(problem.code) || attempt === attempts - 1) {
      throw new Error(`${res.status} ${problem.code}`);
    }
    const seconds = problem.retry_after_seconds || 2 ** attempt;
    await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
  }
}

console.log((await search({ query: 'tide tables', num_results: 5 })).data.summary);
```

## Warnings are not errors

A call can succeed and still have something to tell you. Those notices arrive in `warnings`, with a `200`:

| Warning code | Meaning |
|---|---|
| `option_not_supported` | A field was accepted but does nothing. `option` names it. |
| `source_unavailable` | One source did not answer. `source` names it. It was not charged, and the other sources' results are returned. |
| `short_results` | Fewer results came back than were asked for. `requested` and `returned` give the numbers. |
| `filter_not_applied` | A filter could not be applied to some sources. `filter` names the field and `sources` the sources; with no `sources` it was applied nowhere right now. |
| `language_detected` | `language` was applied to a source that stores no language (`web`), on a language detected from each result's text. `sources` names it. The list can be short. |
| `content_partial` | `include_content`: some results have no stored page text, so their `content` is `null`. `with_content` and `returned` give the numbers. Only results with content are charged for it. |
| `content_unavailable` | `include_content`: page content is away right now. The results came back without it and it was not charged. |

With [Spaces](https://millionshort.com/docs/spaces#warnings), a search with a `space` has two more:

| Warning code | Meaning |
|---|---|
| `space_sites_cut` | The Space searches inside a list and holds more sites than one search uses (50; 20 without a key). `sites_total` and `sites_applied` in the warning give the numbers. |
| `space_setting_not_applied` | Something the Space asks for was left out: a setting that cannot be applied right now (named in `settings`), or a page type, topic or source that no longer exists (named in `values`). The search ran without it. |

## In the SDKs

Both SDKs raise one class per kind of error, all derived from `MillionShortError`. Each error carries the code, the message, the request id and the suggested wait. The [Python](https://millionshort.com/docs/sdks/python#errors) and [TypeScript](https://millionshort.com/docs/sdks/typescript#errors) pages list the classes.

## Over MCP

The [MCP server](https://millionshort.com/docs/mcp) reports a failed search as a tool result marked as an error, with one short sentence the model can act on, such as a bad argument or a limit that was reached. A connection problem is an HTTP status instead: `401` for a key that was refused (a request with no key is served in the no-key mode, where that mode is on), `403` for a browser origin that is not allowed, `405` for `GET`, `413` for a body over 256 KB.
