# Retrieval and context

Use `search` when you choose the sources, `context` when the service chooses and budgets them, and `answer` when you want a cited answer.

All three endpoints need `knowledge:read`, and `answer` also needs `knowledge:answer`. Without `space_ids` they use every Space the caller can read, not only the default Space. When a request is about one end user or one project, name its Space in `space_ids`.

| Endpoint | Who chooses | Good for |
| --- | --- | --- |
| [`POST /v2/retrieval/search`](https://mirabase.io/developers/api/retrieval.md#retrieval-search) | The caller | You know what you want and rank or display results yourself |
| [`POST /v2/retrieval/context`](https://mirabase.io/developers/api/retrieval.md#retrieval-buildcontext) | The service | You want context assembled for an Agent task within a token budget |
| [`POST /v2/retrieval/answer`](https://mirabase.io/developers/api/retrieval.md#retrieval-answer) | The service, and a model writes the answer | You have no model of your own and want an answer with citations |

## Search

Lexical search finds a write on the next request. Vector search and reranking apply once processing finishes.

curl:

```bash
curl -X POST https://api.mirabase.dev/v2/retrieval/search \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"query": "where do files and memory live"}'
```

TypeScript:

```ts
const hits = await mirabase.search("where do files and memory live");
```

Python:

```python
hits = mb.search("where do files and memory live")
```

When you read the results, look at these fields:

- `score` is comparable inside one response only.
- `freshness: pending_index` means the match came from the freshness buffer: lexical only, on a version that has not finished processing.
- `partial` is `true` when one retrieval method degraded or the scores are not calibrated relevance.
- `modified_at` is when that version was written; `occurred_at` is the source's own time, such as when a line of a conversation was said. Send `occurred_at` with a write when you know when the content happened.
- When the passage states the date it is as of, a hit carries `stated_date` and `stated_date_from`. Use it to tell an older record from a newer one when files were uploaded together and share a `modified_at`. For how the date is chosen, see [stated_date](https://mirabase.io/developers/api/schemas.md#DevSearchHit.stated_date).
- When you retrieve on behalf of an earlier message, send `reference_time` and `timezone`, so that "yesterday" and "last week" in the query are counted from that message. `context` and `answer` take the same two parameters.
- Content on a branch cannot be found until the branch is merged.

## Build context

`context` takes a task, picks and budgets the sources, packs the result, and explains its choices in `route`. Routing uses deterministic rules rather than a model, so you can replay and explain the same input.

curl:

```bash
curl -X POST https://api.mirabase.dev/v2/retrieval/context \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"task": "Fix the failing upload test", "purpose": "coding", "tier": "standard", "budget_tokens": 4000}'
```

TypeScript:

```ts
const pack = await mirabase.context("Fix the failing upload test", {
  purpose: "coding",
  tier: "standard",
  budget_tokens: 4000,
});
```

Python:

```python
pack = mb.context(
    "Fix the failing upload test",
    purpose="coding",
    tier="standard",
    budget_tokens=4000,
)
```

The sources are `memory`, `agent_profile`, `skills`, `files`, `changes`, and `knowledge`. For each enabled source, `route.sources` reports its budget, usage, picked, and omitted counts, with a stable code in `why`. Disabled sources appear in [rules_fired](https://mirabase.io/developers/api/schemas.md#DevContextRoute.rules_fired). Unused budget stays empty and is reported in `route.unused_tokens` rather than filled with unrelated content.

- `budget_tokens` covers the whole response, not only `items`, and `tokens_used` never exceeds it.
- `memory_view` is the deterministic memory view: the same memories give the same bytes, whatever the task. Send `memory_view_etag` back as `have_memory_etag` and the view is left out while it has not changed, which suits a prompt cache prefix.
- Skills come from `/.mirabase/skills/<name>/SKILL.md`. The `text` of a `skills` item is its one-line description: read the body at `path`.
- Items may carry `flags`: `stale`, `superseded`, `conflict`, or `agent_written`.
- If the evidence changes while the service builds the pack, it rebuilds the pack once on its own. Only if the evidence changes again does it return 409 `evidence_changed`: send the same request again.

### Table aggregates

When a task asks for a sum, a count, an average, or the largest or smallest value over a table, the service computes it over the whole table without a model; when it computes, why it does not, and the caps are in the [API reference](https://mirabase.io/developers/api/retrieval.md#retrieval-buildcontext). The result is an item of its own, whose text states the operation, the column, the filters, the number of rows counted, and the result.

### Get the context as text

When you would rather not build the prompt yourself, send `render: "text"` and the response gains `rendered`: `rendered.text` is the same pack laid out as text you can put in a prompt as it is. Its first line says this is reference material, not instructions; then comes the memory view; then every source under its `[cN]` id. The same pack always renders to the same text.

## Get an answer with citations

[`POST /v2/retrieval/answer`](https://mirabase.io/developers/api/retrieval.md#retrieval-answer) answers a `question` from the evidence `context` would pick, marking citations as `[cN]` in the text. It takes the same selection parameters as `context`, plus `history`, `output_language`, `include`, and `stream`. If you run your own model, `context` is usually what you want.

curl:

```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 do releases go out?", "output_language": "en"}'
```

TypeScript:

```ts
const reply = await mirabase.answer("When do releases go out?", { output_language: "en" });
if (reply.status === "answered") console.log(reply.answer, reply.citations);
else console.log("abstained:", reply.reason);

// Report what you used, the same as for a context pack.
await mirabase.context.feedback(reply.pack_id, reply.citations.map((citation) => citation.citation_id));
```

Python:

```python
reply = mb.answer("When do releases go out?", output_language="en")
if reply["status"] == "answered":
    print(reply["answer"], reply["citations"])
else:
    print("abstained:", reply.get("reason"))

# Report what you used, the same as for a context pack.
mb.context.feedback(reply["pack_id"], [citation["citation_id"] for citation in reply["citations"]])
```

- Check `status` first: `answered` or `abstained`. When it abstains, `answer` is empty and `reason` says why; for the values, see [DevAnswerAbstainReason](https://mirabase.io/developers/api/schemas.md#DevAnswerAbstainReason). With no related evidence the service does not call the model and returns `no_evidence`.
- `citations` lists only the evidence the answer cites, in order of first citation, and `evidence_count` is how many items the model was given. `pack_id` takes feedback like a context pack.
- The service tells the model when each item was written and the date its content is from. For a question about the present state ("now", "currently"), the service orders items about the same subject newest first. The same subject means the same Entry, the same web page saved more than once, or Entries that share a `metadata.subject_key` value; similar paths or titles do not count. To have a set of files, such as weekly status reports, ordered this way, give them the same `subject_key`.
- By default an answer leaves out the `changes` and `skills` sources; to include them, send [weights](https://mirabase.io/developers/api/retrieval.md#retrieval-answer.body.weights).
- The number of answers running at once is limited; past it the service returns 429 `rate_limited`, see [Rate limits and quotas](https://mirabase.io/developers/conventions.md#rate-limits). 502 `model_failed` and 503 `answer_unavailable` are worth retrying later. The SDK retries an answer on its own only after a 429; it does not retry a 502 or 503, because each attempt is a model call.

### See what the model read

With `include: ["evidence"]`, the response gains `evidence`: every item the model read, in the order it read them, without the text. When an answer gives an outdated value, use it to check which items the model read and the date of each.

### Stream an answer

With `stream: true` the response is `text/event-stream` instead of one JSON body. Authentication, validation, and the wait for a free slot happen before the stream opens, so those errors are still ordinary HTTP responses. Once the stream is open the status is 200, and a later error arrives as an `error` event. Both SDKs have `answer.stream`, which parses the events for you. For the `data` of each event, see [Answer with citations](https://mirabase.io/developers/api/retrieval.md#retrieval-answer).

curl:

```bash
# -N turns off curl's output buffering, so each event prints as it arrives.
curl -N -X POST https://api.mirabase.dev/v2/retrieval/answer \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"question": "When do releases go out?", "stream": true}'
```

TypeScript:

```ts
const stream = mirabase.answer.stream("When do releases go out?");
for await (const event of stream) {
  if (event.type === "start") console.log("evidence items:", event.evidence_count);
  if (event.type === "delta") process.stdout.write(event.text);
  if (event.type === "replace") console.log("\n(the text so far is replaced by the final answer)");
}

// final is authoritative: the same object mirabase.answer returns.
const reply = await stream.finalAnswer();
console.log(reply.status, reply.answer, reply.citations);
```

Python:

```python
with mb.answer.stream("When do releases go out?") as stream:
    for event in stream:
        if event["type"] == "start":
            print("evidence items:", event["evidence_count"])
        elif event["type"] == "delta":
            print(event["text"], end="", flush=True)
        elif event["type"] == "replace":
            print("\n(the text so far is replaced by the final answer)")
    # final is authoritative: the same object mb.answer returns.
    reply = stream.final_answer()

print(reply["status"], reply["answer"], reply["citations"])
```

```text
: stream open

id: 1
event: start
data: {"request_id":"req_5d1e","pack_id":"pck_7c19","evidence_count":6,"partial":false}

id: 2
event: delta
data: {"text":"Releases go out "}

: ping

id: 3
event: delta
data: {"text":"on Thursdays [c1]."}

id: 4
event: final
data: {"status":"answered","answer":"Releases go out on Thursdays [c1].","citations":[{"citation_id":"c1","entry_id":"ent_9a41","version_id":"ver_4d02","title":"release-notes.md","source":"files","path":"/notes/release-notes.md","text":"From November on, releases go out on Thursdays."}],"evidence_count":6,"pack_id":"pck_7c19","partial":false,"route":{"purpose":"task","tier":"standard","rules_fired":["source:off:changes:answer_default","source:off:skills:answer_default"],"sources":[],"unused_tokens":1200}}
```

- Append the text of each `delta` in order. On `replace`, discard what you have shown and show the `answer` of `final` instead. Some answers have only `final`, with no `delta`.
- Lines that start with `:` are comments that keep the connection open. Ignore them, and ignore event names you do not know.
- The service sends only one of `final` or `error`, and the stream ends after it. On `error`, discard the text you have shown. If a stream ends without either event, the connection dropped: treat it as a failed request and send the request again. You cannot resume a stream.
- A streamed answer holds one answer slot until the stream ends. Closing the connection cancels the answer and frees the slot; in the SDKs, leaving the loop early, calling `close()`, or aborting the `signal` closes it.
- The SDKs' `answer.stream` throws `MirabaseError` for an `error` event, a stream cut off midway, and data it cannot parse, and does not retry a stream that has started. `mirabase.answer(question, { stream: true })` does not stream: it throws `MirabaseConfigError` with code `stream_not_supported`. Use `answer.stream` instead.

## Send feedback

[`POST /v2/retrieval/context/{pack_id}/feedback`](https://mirabase.io/developers/api/retrieval.md#retrieval-contextfeedback) sends the `used_citation_ids` you actually used: references only, no content. Reports add up, so repeating one or reporting in several calls is safe.

curl:

```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": ["c1"]}'
```

TypeScript:

```ts
await mirabase.context.feedback(pack.pack_id, ["c1"]);
```

Python:

```python
mb.context.feedback(pack["pack_id"], ["c1"])
```

## Authorization

- The service resolves allowed Spaces before planning, and returns 404 `not_found` for both invisible and missing Spaces.
- Every result passes the same final check, and the service generates `route` and omitted counts after authorization.
- `scope_used.space_ids` lists the Spaces this call actually used.
- `agent_profile` is on only for an Agent's key.

> **Note:** MCP clients can connect to `/mcp` with the same API key. The tools `mira.search`, `mira.context`, `mira.answer`, and `mira.context.feedback` each make one of the requests above. See [Connect an Agent (MCP)](https://mirabase.io/developers/agents.md).

## Inspect a retrieval

When [explain](https://mirabase.io/developers/api/retrieval.md#retrieval-search.body.explain) is set to `true`, both the response and each result in `search`, `context`, and `answer` include `explain`, showing which retrieval methods found the result, its rank before and after reranking, the matched query terms, and the rules that adjusted its position. The results and their order remain unchanged.

- The console's Playground runs search, context, and answer under your signed-in account or with an API key you provide, and shows why each result was returned.
- The console's Request logs list the account's recent API requests (metadata only), filterable by status, route, API key, client, and error code. For retrieval requests, you can view the trace or reopen the request in the Playground. Only team owners and admins can view these logs.
- The same data is available through the API: [`GET /v2/request-logs`](https://mirabase.io/developers/api/request-logs.md#requestlogs-list) and [`GET /v2/retrieval/traces/{trace_id}`](https://mirabase.io/developers/api/request-logs.md#requestlogs-trace). For required permissions and retention periods, see the [API reference](https://mirabase.io/developers/api/request-logs.md).

## Next steps

- [Memory](https://mirabase.io/developers/memory.md): bring distilled facts into the context.
- [Connect an Agent](https://mirabase.io/developers/agents.md): let an Agent use the same retrieval over MCP.
- [API conventions](https://mirabase.io/developers/conventions.md#rate-limits): concurrency and rate limits for retrieval.
