# Retrieval

Search, context packs, and cited answers over what the key can read.

API reference. Base URL: `https://api.mirabase.dev`

## Answer with citations

`POST /v2/retrieval/answer`

Answer a question from the evidence `context` would pick, citing it as `[cN]`. Needs `knowledge:read` and `knowledge:answer`. The model is told when each passage was written and, when known, the date its content is from (`occurred_at`, else `stated_date`); for a question about the present state ("now", "currently", "现在"), passages on the same topic are ordered newest first. With `stream: true`, the 200 response is `text/event-stream`: `x-mirabase-sse-events` on this operation names the model of each event's `data`, and `stream` on the request describes the order. A generated client keeps the JSON type for the call without `stream`. Up to `answer_concurrency` answers (at [`GET /v2/limits`](https://mirabase.io/developers/api/usage.md#usage-limits), 3 by default) run at a time per principal, across all of its keys; another waits up to 10 seconds, then returns 429 `rate_limited` with `limit: "concurrency"`. 502 `model_failed` and 503 `answer_unavailable` are worth retrying later. 503 `answer_not_configured` means this deployment has no answer model, so a retry does not help: build the context and run your own model.

**Capability** `knowledge:read` `knowledge:answer`

Guide: [Retrieval and context](https://mirabase.io/developers/retrieval.md)

### Request body

`application/json` `DevAnswerRequest`

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `question` | `string` | Required | The question to answer, 1 to 4000 characters. length 1..4000 |
| `space_ids` | `DevSpaceRef[]` | Optional | Space ids; `default` names your default Space, as it does in a path. Omit to use every Space you can read; a key that can read more than 200 Spaces must name them (returns 422 otherwise). items 1..64 |
| `purpose` | `DevContextPurpose` | Optional | What the answer is for, as on `context`: `task`, `coding`, `research`, or `audit`. |
| `weights` | `DevContextWeights` | Optional | As on `context`. When you send none, an answer leaves out the `changes` and `skills` sources: they name recent files and skills whatever the question is. `route.rules_fired` then lists `source:off:changes:answer_default` and `source:off:skills:answer_default`. Send `weights` to include them. |
| `tier` | `DevContextTier` | Optional | How much retrieval work goes into finding the evidence, as on `context`: `fast`, `standard`, or `deep`. default: "standard" |
| `budget_tokens` | `integer` | Optional | Budget for the evidence the model reads. 500..16000, default: 4000 |
| `history` | `DevAnswerTurn[]` | Optional | Earlier turns, oldest first. A follow-up question is searched together with the question it follows. When the turns add up to more than 12,000 characters, the oldest are left out. max items 10 |
| `output_language` | `string` | Optional | A BCP 47 tag such as `en` or `zh-CN`. Only changes the language of `answer`. max length 35 |
| `filter` | `DevRetrievalFilter` | Optional | Narrow the evidence the answer may draw on, as on `context`. |
| `include` | `evidence[]` | Optional | `["evidence"]` adds `evidence` to the response: every item the model read, without its text. Use it to see what an answer was based on beyond the passages it cited. items 1..1 |
| `stream` | `boolean` | Optional | True streams the answer as `text/event-stream` instead of returning one JSON body. Each event has an `id` (1, 2, 3, ... in order), an `event` name, and one line of JSON in `data`: - `start` (`DevAnswerStreamStart`): sent once, after retrieval and before any text. It carries the `request_id`, the `pack_id`, and how much evidence the model was given. A stream that fails during retrieval has no `start`. - `delta` (`DevAnswerStreamDelta`): the next piece of the answer. Append the pieces in order. - `replace` (`DevAnswerStreamReplace`): sent at most once, directly before `final`, when the text streamed so far is not the final answer (the service repaired a draft that cited nothing, or the answer became an abstention). Discard the streamed text and show `final.answer`. - `final` (`DevAnswer`): the same JSON this operation returns without `stream`. It is authoritative. - `error` (`DevErrorResponse`): the error envelope an HTTP error would carry; its `status` is the status the request would have had. Discard the streamed text: no answer was produced. `retryable` says whether asking again can help. Exactly one of `final` and `error` is sent, it is the last event, and the stream closes after it. A stream that ends without either was cut off: treat it as a failed request and ask again. Lines that start with `:` are comments, sent when the stream opens and whenever it has been idle for 15 seconds; they keep the connection open and carry nothing. A stream cannot be resumed: `id` shows the order only and `Last-Event-ID` is ignored. Ignore event names you do not know; more can be added. Closing the connection cancels the answer. Authentication, validation, and the wait for a free slot happen before the stream opens, so those errors are ordinary HTTP responses. |
| `profile` | `string` | Optional | A retrieval profile declared on this deployment: a named set of these settings (and of the candidate and rerank widths). Fields sent in the request override the profile's. An unknown name is 422. When you send none, a profile the deployment set as the default for the Spaces searched, or for your account, applies. |
| `rerank` | `boolean` | Optional | `false` skips the reranker: results keep the order of the fused candidates, scores are not relevance, and `partial` is true when there are results. Cannot be combined with `min_score`; `true` cannot be combined with tier `fast`. |
| `min_score` | `number` | Optional | The lowest rerank score kept, from 0 to 1. It replaces the service's default relevance floor and also removes lexical matches below it. Hits from the freshness buffer (`freshness: pending_index`) have no rerank score and are kept. Not applied when reranking failed (`partial` says so). Needs reranking. 0..1 |
| `max_per_entry` | `integer` | Optional | At most this many passages from one Entry. A hard cap: the places it frees go to other Entries, not to more passages of the same one. On `context` and `answer` it applies to search results, not to the files a task names or to recent changes. 1..50 |
| `reference_time` | `string (date-time)` | Optional | The moment that relative time in the query ("yesterday", "last week") is counted from. Defaults to now. Send the time of the message when you retrieve on behalf of an older one. On `answer` it is also the day the model is told is today. |
| `timezone` | `string` | Optional | IANA time zone of the person asking, such as `Asia/Shanghai`: it decides which day "yesterday" is. Defaults to the deployment's time zone. An unknown name returns 422. |
| `explain` | `boolean` | Optional | True adds `explain` to every hit, item or citation and to the response: which branches found it, its position before and after reranking, the query terms it matched, what let it past the relevance floor and which rules moved it. Results and their order are the same with or without it. Costs nothing when left out. Counts, positions and scores cover only candidates you can read: nothing outside your read root, metadata scope or permissions is counted. |

### Responses

- `200` `application/json` `DevAnswer`, `text/event-stream` `string`

### Stream events

The events sent when the response is `text/event-stream`, and the schema of each event's `data`:

- `start` `DevAnswerStreamStart`
- `delta` `DevAnswerStreamDelta`
- `replace` `DevAnswerStreamReplace`
- `final` `DevAnswer`
- `error` `DevErrorResponse`

### Error statuses

`400` `401` `403` `404` `409` `422` `429` `500` `502` `503` `504` See [Errors](https://mirabase.io/developers/conventions.md#errors) for the error shape and [Error codes](https://mirabase.io/developers/errors.md) for what each code means.

### Example request

```bash
curl -X POST "https://api.mirabase.dev/v2/retrieval/answer" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"question":"When does version 2.4 launch?","space_ids":["default"]}'
```

### Example response

```json
{
  "status": "answered",
  "answer": "Version 2.4 launches on Friday 21 November [c1].",
  "citations": [
    {
      "citation_id": "c1",
      "entry_id": "ent_01JD2M8Z4K",
      "version_id": "ver_01JD2M8Z4M",
      "space_id": "col_01JD2M7QK3",
      "path": "/notes/plan.md",
      "modified_at": "2026-11-17T08:02:00Z",
      "title": "plan.md",
      "source": "knowledge",
      "text": "The launch of version 2.4 moved to Friday 21 November."
    }
  ],
  "evidence_count": 1,
  "pack_id": "trc_01JD2M7R",
  "partial": false,
  "route": {
    "purpose": "task",
    "tier": "standard",
    "rules_fired": [],
    "sources": [
      {
        "source": "knowledge",
        "budget": 4000,
        "used": 38,
        "picked": 1,
        "omitted": 0,
        "why": "matched the question"
      }
    ],
    "unused_tokens": 3962
  }
}
```

## Build context

`POST /v2/retrieval/context`

The service picks and budgets sources for a task. The result explains its choices in `route`. Shares the per-principal concurrency limit described on `search`. When the task asks for a sum, a count, an average, or the largest or smallest value over a table you can read, the service computes it over the whole table by fixed rules, without a model, for up to 3 tables. The result is an item of its own, placed first in its source and citing the table's Entry and version, and `route.rules_fired` includes `table_aggregate:computed`. The service computes only when it understands every word of the task and the table suits the calculation; otherwise it records `table_aggregate:not_computed:<reason>` and still returns the rows as evidence. Rows, cells, and time per request are capped, and past a cap nothing is computed. `answer` uses the same item. Needs `knowledge:read`.

**Capability** `knowledge:read`

Guide: [Retrieval and context](https://mirabase.io/developers/retrieval.md)

### Request body

`application/json` `DevContextRequest`

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `task` | `string` | Required | What the context is for, in natural language. A task that states several things is searched for each of them. length 1..1000 |
| `space_ids` | `DevSpaceRef[]` | Optional | Space ids; `default` names your default Space, as it does in a path. Omit to use every Space you can read; a key that can read more than 200 Spaces must name them (returns 422 otherwise). items 1..64 |
| `purpose` | `DevContextPurpose` | Optional | What the context is for (`task`, `coding`, `research`, or `audit`). Set this to skip intent inference. |
| `weights` | `DevContextWeights` | Optional | Shift the budget between sources. Omit to use the shares that go with the purpose. |
| `tier` | `DevContextTier` | Optional | `fast` uses no model and matches words only; `standard` adds semantic search and reranking; `deep` looks at twice as many candidates. default: "standard" |
| `budget_tokens` | `integer` | Optional | Covers the whole response, not only `items`. With `render: "compact"` it covers `rendered.text` instead: the text you put in the prompt. 500..16000, default: 4000 |
| `have_memory_etag` | `string` | Optional | Omits `memory_view` when it still matches `memory_view_etag`. length 1..128 |
| `filter` | `DevRetrievalFilter` | Optional | Narrow what is searched before ranking. Applies to every source that reads Entries; `memory_view` is not filtered. |
| `render` | `text \| compact` | Optional | `text` adds `rendered` to the response: the same pack laid out as text you can put in a prompt as it is, with each source under its citation id. Leave it out when you build the prompt from `items` yourself. `compact` adds `rendered` in a shorter layout (one line per source with its origin and one time; a repeated message timestamp inside a conversation passage is written once) and counts `budget_tokens` and `tokens_used` on that text instead of on the JSON response, so the same budget holds more evidence. Use it when the text is what your model reads. `items` still carries every id, time and locator. |
| `profile` | `string` | Optional | A retrieval profile declared on this deployment: a named set of these settings (and of the candidate and rerank widths). Fields sent in the request override the profile's. An unknown name is 422. When you send none, a profile the deployment set as the default for the Spaces searched, or for your account, applies. |
| `rerank` | `boolean` | Optional | `false` skips the reranker: results keep the order of the fused candidates, scores are not relevance, and `partial` is true when there are results. Cannot be combined with `min_score`; `true` cannot be combined with tier `fast`. |
| `min_score` | `number` | Optional | The lowest rerank score kept, from 0 to 1. It replaces the service's default relevance floor and also removes lexical matches below it. Hits from the freshness buffer (`freshness: pending_index`) have no rerank score and are kept. Not applied when reranking failed (`partial` says so). Needs reranking. 0..1 |
| `max_per_entry` | `integer` | Optional | At most this many passages from one Entry. A hard cap: the places it frees go to other Entries, not to more passages of the same one. On `context` and `answer` it applies to search results, not to the files a task names or to recent changes. 1..50 |
| `reference_time` | `string (date-time)` | Optional | The moment that relative time in the query ("yesterday", "last week") is counted from. Defaults to now. Send the time of the message when you retrieve on behalf of an older one. On `answer` it is also the day the model is told is today. |
| `timezone` | `string` | Optional | IANA time zone of the person asking, such as `Asia/Shanghai`: it decides which day "yesterday" is. Defaults to the deployment's time zone. An unknown name returns 422. |
| `explain` | `boolean` | Optional | True adds `explain` to every hit, item or citation and to the response: which branches found it, its position before and after reranking, the query terms it matched, what let it past the relevance floor and which rules moved it. Results and their order are the same with or without it. Costs nothing when left out. Counts, positions and scores cover only candidates you can read: nothing outside your read root, metadata scope or permissions is counted. |

### Responses

- `200` `application/json` `DevContextResponse`

### Error statuses

`400` `401` `403` `404` `409` `422` `429` `500` `503` `504` See [Errors](https://mirabase.io/developers/conventions.md#errors) for the error shape and [Error codes](https://mirabase.io/developers/errors.md) for what each code means.

### Example request

```bash
curl -X POST "https://api.mirabase.dev/v2/retrieval/context" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"task":"Draft the release notes for version 2.4","space_ids":["default"],"budget_tokens":4000}'
```

### Example response

```json
{
  "pack_id": "<pack_id>",
  "items": [
    {
      "entry_id": "<entry_id>",
      "version_id": "<version_id>",
      "title": "Launch notes",
      "text": "The launch moved to March 14.",
      "citation_id": "<citation_id>",
      "source": "memory"
    }
  ],
  "route": {
    "purpose": "task",
    "tier": "fast",
    "rules_fired": [
      "<rules_fired>"
    ],
    "sources": [
      {
        "source": "memory",
        "budget": 1,
        "used": 1,
        "picked": 1,
        "omitted": 1,
        "why": "<why>"
      }
    ],
    "unused_tokens": 1
  },
  "tokens_used": 1,
  "budget_tokens": 1,
  "tokenizer": "cl100k_base",
  "omitted": {
    "count": 1,
    "max_score": 1
  },
  "scope_used": {
    "space_ids": [
      "<space_ids>"
    ]
  },
  "partial": false
}
```

## Send context feedback

`POST /v2/retrieval/context/{pack_id}/feedback`

Report which items of a pack were used. A citation that is not in the pack returns 422 `unknown_citation`. Needs `knowledge:read`.

**Capability** `knowledge:read`

Guide: [Retrieval and context](https://mirabase.io/developers/retrieval.md#feedback)

### Parameters

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `pack_id` | Path | `DevId` | Required | Opaque server-issued identifier. Clients compare it byte for byte. length 1..256 |

### Request body

`application/json` `DevContextFeedbackRequest`

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `used_citation_ids` | `string[]` | Required | `citation_id`s from the pack that you actually used. References only, no content. Reports add up: repeating one, or reporting in several calls, is safe. items 1..256 |

### Responses

- `204` No response body

### Error statuses

`400` `401` `403` `404` `409` `422` `429` `500` `503` See [Errors](https://mirabase.io/developers/conventions.md#errors) for the error shape and [Error codes](https://mirabase.io/developers/errors.md) for what each code means.

### Example request

```bash
curl -X POST "https://api.mirabase.dev/v2/retrieval/context/$PACK_ID/feedback" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"used_citation_ids":["<used_citation_ids>"]}'
```

## Search

`POST /v2/retrieval/search`

Search for `query` in the sources you choose. A write is searchable lexically on the next request. Besides the request rate, each principal has a limit on how many searches and context calls run at once (`retrieval_concurrency`, or `agent_retrieval_concurrency` for an Agent, at [`GET /v2/limits`](https://mirabase.io/developers/api/usage.md#usage-limits)). A call over the limit waits on the server for a free slot, about one second by default, and returns 429 `rate_limited` with `limit: "concurrency"` only when none frees up in that time; then retry after `Retry-After`. The account-wide total (`tenant_retrieval_concurrency`) does not queue: a call over it returns 429 at once. Needs `knowledge:read`.

**Capability** `knowledge:read`

Guide: [Retrieval and context](https://mirabase.io/developers/retrieval.md)

### Request body

`application/json` `DevSearchRequest`

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `query` | `string` | Required | What to look for, in natural language or keywords. length 1..1000 |
| `space_ids` | `DevSpaceRef[]` | Optional | Space ids; `default` names your default Space, as it does in a path. Omit to search every Space you can read; a key that can read more than 200 Spaces must name them (returns 422 otherwise). items 1..64 |
| `path` | `DevPath` | Optional | Restrict results to this subtree, or to this one file. Resolved in each Space searched. Empty when it exists in none of them. |
| `include` | `memory[]` | Optional | `["memory"]` adds memory facets to the results and switches ranking to the memory profile: no relevance floor, and at most one passage per Entry. The only accepted value, given once. items 1..1 |
| `limit` | `integer` | Optional | How many hits to return at most. This is a total, unlike a list's page size. 1..50, default: 20 |
| `filter` | `DevRetrievalFilter` | Optional | Narrow what is searched before ranking. Combines with `path` and `space_ids`: all of them must hold. |
| `tier` | `DevContextTier` | Optional | As on `context`: `fast` uses no model and matches words only (scores are not relevance, `partial` is true when there are hits); `standard` adds semantic search and reranking; `deep` looks at twice as many candidates and reranks twice as many. default: "standard" |
| `fields` | `DevSearchHitField[]` | Optional | Keep only these optional fields on each hit. `entry_id`, `version_id`, `title`, `text`, `score`, `citation_id` and `source_type` are always there. Each field once. Leave it out for every field. max items 9 |
| `profile` | `string` | Optional | A retrieval profile declared on this deployment: a named set of these settings (and of the candidate and rerank widths). Fields sent in the request override the profile's. An unknown name is 422. When you send none, a profile the deployment set as the default for the Spaces searched, or for your account, applies. |
| `rerank` | `boolean` | Optional | `false` skips the reranker: results keep the order of the fused candidates, scores are not relevance, and `partial` is true when there are results. Cannot be combined with `min_score`; `true` cannot be combined with tier `fast`. |
| `min_score` | `number` | Optional | The lowest rerank score kept, from 0 to 1. It replaces the service's default relevance floor and also removes lexical matches below it. Hits from the freshness buffer (`freshness: pending_index`) have no rerank score and are kept. Not applied when reranking failed (`partial` says so). Needs reranking. 0..1 |
| `max_per_entry` | `integer` | Optional | At most this many passages from one Entry. A hard cap: the places it frees go to other Entries, not to more passages of the same one. On `context` and `answer` it applies to search results, not to the files a task names or to recent changes. 1..50 |
| `reference_time` | `string (date-time)` | Optional | The moment that relative time in the query ("yesterday", "last week") is counted from. Defaults to now. Send the time of the message when you retrieve on behalf of an older one. On `answer` it is also the day the model is told is today. |
| `timezone` | `string` | Optional | IANA time zone of the person asking, such as `Asia/Shanghai`: it decides which day "yesterday" is. Defaults to the deployment's time zone. An unknown name returns 422. |
| `explain` | `boolean` | Optional | True adds `explain` to every hit, item or citation and to the response: which branches found it, its position before and after reranking, the query terms it matched, what let it past the relevance floor and which rules moved it. Results and their order are the same with or without it. Costs nothing when left out. Counts, positions and scores cover only candidates you can read: nothing outside your read root, metadata scope or permissions is counted. |

### Responses

- `200` `application/json` `DevSearchResponse`

### Error statuses

`400` `401` `403` `404` `409` `422` `429` `500` `503` `504` See [Errors](https://mirabase.io/developers/conventions.md#errors) for the error shape and [Error codes](https://mirabase.io/developers/errors.md) for what each code means.

### Example request

```bash
curl -X POST "https://api.mirabase.dev/v2/retrieval/search" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"query":"launch date for version 2.4","space_ids":["ext:user-42"],"include":["memory"],"limit":5}'
```

### Example response

```json
{
  "data": [
    {
      "entry_id": "ent_01JD2M8Z4K",
      "version_id": "ver_01JD2M8Z4M",
      "space_id": "col_01JD2M7QK3",
      "title": "plan.md",
      "text": "The launch of version 2.4 moved to Friday 21 November.",
      "score": 0.82,
      "citation_id": "c1",
      "source_type": "file",
      "path": "/notes/plan.md",
      "modified_at": "2026-11-17T08:02:00Z"
    }
  ],
  "trace_id": "trc_01JD2M7R",
  "partial": false
}
```
