# API conventions

The rules every endpoint shares: requests and responses, request ids, versions, pagination, idempotency, conditional requests, jobs, errors, retries, and rate limits.

## Requests and responses

| Item | Rule |
| --- | --- |
| Address | `https://api.mirabase.dev`, with every endpoint under `/v2` |
| Authentication | `Authorization: Bearer <API key>`, see [Authentication](https://mirabase.io/developers/authentication.md) |
| Request body | JSON in UTF-8 with `Content-Type: application/json`. File content is the exception: raw bytes with the file's own type |
| Field names | Lowercase with underscores, such as `next_cursor` |
| Times | RFC 3339. Responses are always UTC, such as `2026-11-06T08:30:00.000Z`. A time in a request needs an offset |
| id | Opaque strings. Store and send them back as they are. Do not parse them or rely on a prefix |
| Validation | Strict. An unknown field or query parameter returns 422 `validation_error` with `field` naming it |
| Errors | Every error has the same shape, see [Errors](https://mirabase.io/developers/conventions.md#errors) below |

## Request ids

Every response carries `X-Request-Id`, and `request_id` in an error body is the same value. Include it when you contact support. You can also send your own `X-Request-Id` and the service keeps it. If the value is invalid, the service replaces it with a new one.

## Versions

- The major version is in the path: `/v2`.
- Every response carries `Mirabase-Contract-Version`, now `1.0`. A request does not need this header. A value the service does not support returns 400 `unsupported_contract_version`: drop the header.
- New endpoints, optional parameters, and response fields arrive without a new version, so a client should ignore response fields it does not know.
- Endpoints marked Coming soon do not exist yet and may change before launch. Endpoints marked Deployment option are optional. Both are labeled in the [API reference](https://mirabase.io/developers/api.md).
- The machine-readable contract is the OpenAPI document. Its address and the spec version for these docs are in the [API overview](https://mirabase.io/developers/api.md).

## Behavior changes

The latest update changed the existing behavior listed here. New parameters and fields are not listed: see the guides and the [API reference](https://mirabase.io/developers/api.md).

- [`POST /v2/retrieval/answer`](https://mirabase.io/developers/api/retrieval.md#retrieval-answer) no longer uses the `changes` and `skills` sources when you send no `weights`. A question with no related evidence returns `abstained` with `reason` `no_evidence`. To get the earlier behavior, send `weights`. See [Answers with citations](https://mirabase.io/developers/retrieval.md#answer).
- Answers running at once per principal went from 1 to 3.
- The error envelope of a 429 `rate_limited` gained `limit`. A 429 for a concurrency limit no longer carries the `RateLimit-*` headers. See [Rate limits and quotas](https://mirabase.io/developers/conventions.md#rate-limits).
- [`POST /v2/memories`](https://mirabase.io/developers/api/memories.md#memories-create) with a `project` or `agent` memory that matches a current one returns 200 with the existing memory, instead of creating another and returning 201.
- Reading `view=table` before processing finishes now returns 404 `content_not_ready` instead of 404 `not_found`.
- `tools/list` over MCP has 8 more tools, and a key with a metadata scope sees only the tools it can call. See [Connect an Agent (MCP)](https://mirabase.io/developers/agents.md#tools).
- When an MCP tool call succeeds, the service places the result JSON in the `content` text. Only when the negotiated protocol version is `2025-06-18` or later do the nine read-only tools also include the same object in `structuredContent`. See [Protocol versions](https://mirabase.io/developers/agents.md#protocol-versions). When a key lacks the capability required by a tool, it receives a tool result with `isError: true` and the code `forbidden`, rather than the JSON-RPC error `-32003`.
- A failed MCP tool result no longer carries `structuredContent`, at any protocol version: the `content` text describes the error, and `_meta["dev.mirabase/error"]` carries the envelope. See [Tools](https://mirabase.io/developers/agents.md#tools).
- [`GET /v2/openapi.yaml`](https://mirabase.io/developers/api/discovery.md#discovery-openapi) describes only the operations an API key can call, with examples. Console, operator, and not-yet-live operations are no longer in it, and its `ETag` changes accordingly.
- `stated_date` no longer comes from a date mentioned in the middle of a sentence: only from a date marked with words such as "as of", the date in a section heading, a date that starts a line or a clause, and the date at the head of the document. See [Search](https://mirabase.io/developers/retrieval.md#search).
- The service computes a table aggregate only when it understands the whole question, and never on an older version of the table. Some questions that previously returned a computed result now return `table_aggregate:not_computed:<reason>`. See [Context](https://mirabase.io/developers/retrieval.md#context).
- For questions about the current state, newest-first ordering now applies only to evidence about the same subject: the same Entry, the same web page saved more than once, or Entries that share a `metadata.subject_key` value. Similar paths or titles, or being in the same folder, do not count. Evidence on a different subject with a similar score is no longer ranked higher solely because it has a newer date. See [Answers with citations](https://mirabase.io/developers/retrieval.md#answer).
- MCP `initialize` now responds with the protocol version requested by the client (four versions from `2024-11-05` to `2025-11-25` are supported) instead of always returning `2024-11-05`, and the server name is now `mirabase-developer`. See [Protocol versions](https://mirabase.io/developers/agents.md#protocol-versions).
- When the deployment does not distill memories or the Entry has `memory_exclude`, a conversation's `memory.state` is `skipped` from the start, with the reason specified in `reason`, instead of starting as `pending`. See [Why distillation is skipped](https://mirabase.io/developers/memory.md#skip-reasons).
- A version that was already distilled stays `ready` after the deployment turns distillation off or removes the model, instead of turning `skipped`. `distill_disabled`, `model_not_configured`, and `distill_paused` are shown only to an unrestricted key of a `tenant_admin` or one with `knowledge:manage`; other keys see `distill_unavailable` in place of the first two, and no reason in place of `distill_paused`: the state stays `pending`. See [Why distillation is skipped](https://mirabase.io/developers/memory.md#skip-reasons).
- In an account with a team, an Admin can no longer issue keys for Agents or end users created by others, or revoke the keys of the Owner or another Admin. See [Creating a key through the API](https://mirabase.io/developers/authentication.md#api).
- When a write returns 429 `ingest_backlog`, `Retry-After` is 30 to 600 seconds instead of a fixed 30. When `Retry-After` is longer than `maxRetryAfterMs` (`max_retry_after` in Python, 60 seconds by default), the SDKs do not retry and throw `MirabaseRateLimitError`. See [When the processing queue is full](https://mirabase.io/developers/processing.md#backlog).
- The SDKs check the API key when the client is created: white space at its ends is dropped, and a line break, space, control character, or non-ASCII character inside it throws `MirabaseConfigError` with code `invalid_api_key`, instead of failing when a request is sent. See [Handle errors](https://mirabase.io/developers/sdks.md#errors).
- With `redact_secrets` on a conversation, each message is now redacted on its own and the title separately; `secrets_redacted` is the number of replacements actually made in the messages and the title. A credential split across two messages is no longer matched as one. Text ingest is unchanged.
- The `score` and order of retrieval results, and the candidate counts in `explain`, are computed only over content the caller can read. A caller with a limited read range (for example, a member with a `read_root`) may see different `score` values; a caller who could read every candidate gets the same results as before.
- [`GET /v2/retrieval/traces/{trace_id}`](https://mirabase.io/developers/api/request-logs.md#requestlogs-trace) no longer returns `summary.candidates` and `summary.fused_count` for traces recorded before this update.
- While an account is pending approval, a console session can only manage API keys and view the account and the read-only lists. Retrieval, reprocessing, deletion, and creating or changing a Space return 403 `account_pending_approval`; [`POST /v2/spaces`](https://mirabase.io/developers/api/spaces.md#spaces-create) returned 201 before. See [Create a key in the console](https://mirabase.io/developers/authentication.md#console).
- A model call that was never sent (it failed while connecting) no longer counts toward the monthly model quota. When a model call is refused for quota, the `message` of the 429 `quota_exceeded` no longer states how much the call needs or how much of the account's quota remains: read [`GET /v2/usage`](https://mirabase.io/developers/api/usage.md#usage-usage).
- Within one account, memory distillation for different Spaces takes turns, so a backlog in one Space no longer delays distillation in another; ingesting conversations no longer delays the distillation of text.

## Pagination

Lists return `{data, next_cursor}`. Pass `next_cursor` back as `cursor` for the next page. The last page has no `next_cursor`. Cursors are opaque, so do not parse or build them.

| Parameter | Meaning |
| --- | --- |
| `limit` | Items per page: 20 by default, 100 at most |
| `cursor` | The `next_cursor` of the page before. Keep the other parameters the same while paging |

curl:

```bash
# First page
curl "https://api.mirabase.dev/v2/entries?limit=100" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"

# Next page: pass next_cursor back as cursor.
curl "https://api.mirabase.dev/v2/entries?limit=100&cursor=$NEXT_CURSOR" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"
```

TypeScript:

```ts
// Iterating fetches pages as needed.
for await (const entry of mirabase.entries.list({ limit: 100 })) {
  console.log(entry.id);
}
```

Python:

```python
# Iterating fetches pages as needed.
for entry in mb.entries.list(limit=100):
    print(entry["id"])
```

Each list states its order in its own entry of the [API reference](https://mirabase.io/developers/api.md). The change feed is the exception: it returns `{data, cursor, has_more}`, and `cursor` is always present so you can continue from it, see [Sync](https://mirabase.io/developers/sync.md#loop). Search is not paginated: `limit` sets how many hits it returns.

## Idempotency

When the network drops you cannot tell whether a write happened. Sending it again with `Idempotency-Key` is safe: the same key, principal, API key, operation, and input return the first result for 24 hours without running again.

| Item | Rule |
| --- | --- |
| Format | 1 to 512 visible ASCII characters. A UUID is a good choice. Use a new key for each logical request |
| Kept for | 24 hours |
| Same key, different input | Returns 409 `conflict` with `remediation.action` `use_new_idempotency_key` |
| Scope | Per API key: two keys using the same value do not affect each other |

```bash
curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/ingest" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Idempotency-Key: 7d3f4c0e-5b1a-4f6e-9c2d-1a2b3c4d5e6f" \
  -H "Content-Type: application/json" \
  -d '{"kind":"text","text":"The launch moved to March 14."}'
```

- Most `POST`, `PUT`, and `PATCH` endpoints take the header, and merging a branch requires it. Each endpoint's parameter table in the [API reference](https://mirabase.io/developers/api.md) says whether it does.
- Endpoints that do not take it are safe to repeat as they are: `GET` changes nothing, the upload `parts`, `complete`, and `abort` calls are deduplicated by the upload id, and repeating [`PATCH /v2/entries/{entry_id}`](https://mirabase.io/developers/api/entries.md#entries-update) gives the same result.
- A single `DELETE` does not take it: the second call returns 404 `not_found`, so you still know the outcome. To make a delete replayable, send it through `files/batch` with a key.
- The SDKs generate a key for every call that takes one, and a retry reuses it.

## Conditional requests

A file's `ETag` is the id of its latest version. Versions never change, so it is a strong validator. Use it to avoid overwriting someone else's change, and to avoid downloading what you already have.

| Header | Used on | Effect |
| --- | --- | --- |
| `If-Match: "<etag>"` | Writes, edits, deletes, reverts | Runs only if the file is still at this version. Otherwise it returns 412 `precondition_failed`, and `current_version_id` in the error is the version now |
| `If-None-Match: *` | Writes | Writes only if nothing is at the path. An existing file returns 412 `precondition_failed` |
| `If-None-Match: "<etag>"` | Reads | Returns 304 with no body when the content has not changed |
| `Range`, `If-Range` | Reading the original | Returns 206 with the bytes asked for. A range outside the file returns 416 `range_not_satisfiable` |

A successful write returns the new version's `ETag`, so the next `If-Match` can use it without another read. See [Files](https://mirabase.io/developers/files.md#conditional) for a full example.

## Jobs

Work that cannot finish within the request becomes a job: it returns 202 with a `job_id` and a `Location` that points at the job. Poll [`GET /v2/jobs/{job_id}`](https://mirabase.io/developers/api/jobs.md#jobs-read) every second or two until the status is final.

What each status means is in [DevJobStatus](https://mirabase.io/developers/api/schemas.md#DevJobStatus), and the kinds of job in [DevJobKind](https://mirabase.io/developers/api/schemas.md#DevJobKind).

| Request | Notes |
| --- | --- |
| Processing after a write (parsing, indexing, distilling) | The write itself is committed and processing runs in the background. `Prefer: wait=N`, at most 10 seconds, holds the response until processing finishes, see [Files](https://mirabase.io/developers/files.md#processing) |
| Large tree operations and branch merges | Send `Prefer: respond-async` when the request is over the synchronous limit, see [Files](https://mirabase.io/developers/files.md#jobs) and [Branches](https://mirabase.io/developers/branches.md#async-merge) |
| Exports and imports | Always jobs, see [Sync](https://mirabase.io/developers/sync.md#export) |

```bash
curl "https://api.mirabase.dev/v2/jobs/$JOB_ID" \
  -H "Authorization: Bearer $MIRABASE_API_KEY"
```

Only whoever started a tree, merge, export, or import job and the Space owner can read it. The service keeps these jobs for 7 days after they finish. Jobs have no long poll.

## Errors

Every error has the same structure. `type` is the broad class, for handling a whole class of errors the same way. Branch on `code` and `remediation.action` for the specific case: they are stable. `message` is for people and may change.

```json
{
  "error": {
    "code": "precondition_failed",
    "type": "conflict",
    "status": 412,
    "message": "the file has moved on",
    "request_id": "req_a18f",
    "retryable": false,
    "current_version_id": "ver_3c44",
    "remediation": {
      "action": "reread_and_retry",
      "doc_url": "https://api.mirabase.dev/llms.txt"
    }
  }
}
```

For the meaning of each field, see [DevErrorBody](https://mirabase.io/developers/api/schemas.md#DevErrorBody). For how `type` follows the HTTP status, see [DevErrorType](https://mirabase.io/developers/api/schemas.md#DevErrorType). Every error code is listed in [Error codes](https://mirabase.io/developers/errors.md#codes).

### Every invalid field at once

When a request body fails validation, `errors` on the 422 `validation_error` response lists every problem found, so one round of fixes is enough. Paths are dotted, such as `messages.0.role`.

```json
{
  "error": {
    "code": "validation_error",
    "type": "invalid_request",
    "status": 422,
    "message": "query is required",
    "request_id": "req_b27c",
    "retryable": false,
    "field": "query",
    "errors": [
      {
        "field": "query",
        "code": "validation_error",
        "message": "query is required"
      },
      {
        "field": "colour",
        "code": "validation_error",
        "message": "unknown field: colour"
      }
    ],
    "remediation": {
      "action": "fix_request",
      "doc_url": "https://api.mirabase.dev/llms.txt"
    }
  }
}
```

The SDKs throw a subclass of `MirabaseError` chosen by HTTP status, such as `MirabaseNotFoundError` or `MirabaseRateLimitError`, and the error object carries `type` and `errors` too. See [SDK](https://mirabase.io/developers/sdks.md#errors).

## Retries

- Check `retryable`. Wait for `Retry-After` when it is present, otherwise use exponential backoff with jitter.
- Send `Idempotency-Key` when retrying a write, or you may create an extra version.

The seconds `Retry-After` gives for each code are in [Error codes](https://mirabase.io/developers/errors.md#codes).

## Rate limits and quotas

Authenticated responses carry `RateLimit-Limit`, `RateLimit-Remaining`, and `RateLimit-Reset`. Each key has two buckets: one for `GET` and `HEAD`, one for everything else. The bucket holds one minute's allowance, so a burst can use it all at once. An account also has a total across all its keys, and a request refused by the total reports that bucket in these headers. Limits are enforced per server process, so treat the numbers as a guide, not an exact allowance.

```bash
curl https://api.mirabase.dev/v2/limits \
  -H "Authorization: Bearer $MIRABASE_API_KEY"

curl https://api.mirabase.dev/v2/usage \
  -H "Authorization: Bearer $MIRABASE_API_KEY"
```

Every limit's name, default, scope, and what exceeding it returns are in the [API reference](https://mirabase.io/developers/api/schemas.md#DevLimit). The defaults are provisional: [`GET /v2/limits`](https://mirabase.io/developers/api/usage.md#usage-limits) reports what this deployment enforces, and [`GET /v2/usage`](https://mirabase.io/developers/api/usage.md#usage-usage) shows what you have used. When a concurrency limit is full, a request first waits on the server for a slot, so the server slows a short burst of parallel requests rather than refusing it.

The error envelope of a 429 `rate_limited` carries `limit`, which says which limit was hit. `request_rate` is the per-minute request allowance: wait for `Retry-After`, then retry. `concurrency` is a limit on calls in flight: the request already waited on the server for a slot, and the response has no `RateLimit-*` headers. Run fewer calls at once; waiting longer helps less.

The limits of a single endpoint, such as file size, batch size, and value ranges, are in that endpoint's description and parameters in the [API reference](https://mirabase.io/developers/api.md).

### Plans

Every account has a plan, returned in [plan](https://mirabase.io/developers/api/schemas.md#DevPlan) by [`GET /v2/limits`](https://mirabase.io/developers/api/usage.md#usage-limits) and [`GET /v2/usage`](https://mirabase.io/developers/api/usage.md#usage-usage). The plan determines which limits apply; [`GET /v2/limits`](https://mirabase.io/developers/api/usage.md#usage-limits) returns the specific values.

| Plan | Description |
| --- | --- |
| `standard` | Uses this deployment's limits. |
| `free` | The initial plan for self-serve accounts. In addition to this deployment's limits, it caps storage, monthly writes, monthly model tokens, monthly model spend, and the request rate. When a stored quota is used up, the API returns 429 `quota_exceeded`, with `quota` identifying the quota. |
| `legacy` | An account opened before plans existed. Like `standard`, it uses this deployment's limits. |

## Next steps

- [Error codes](https://mirabase.io/developers/errors.md): what each error code means, with its `remediation.action`.
- [SDK](https://mirabase.io/developers/sdks.md): the clients already implement these rules.
- [API reference](https://mirabase.io/developers/api.md): the parameters and responses of every endpoint.
