# Mirabase Developer docs > One API for a file system, a knowledge base, and memory. The same Entry can be reached by path, by id, or by meaning, with one set of permissions and one version chain. API reference: https://mirabase.io/developers/api.md. OpenAPI: https://api.mirabase.dev/v2/openapi.yaml --- # 5-minute quickstart Write and read a file by path, edit it and see its versions, compare and revert; let an Agent change files on a branch and merge; get an answer that cites the file version; connect an Agent over MCP. ## Before you begin > **Note:** The TypeScript SDK package is `@mirabase/sdk`. The examples import it from `@mirabase/sdk/developer`; it requires Node.js 20.3 or newer and ships as ES modules only, so add each step's example to `quickstart.mjs` in order and run it with `node quickstart.mjs`. The Python SDK package is `mirabase` and requires Python 3.11 or newer. Both are 0.x releases, so method names may still change before 1.0. The versions currently served are release candidates; see [SDK](https://mirabase.io/developers/sdks.md#install). Each step's example continues the one before it and reuses its variables. `mirabase` (TypeScript) and `mb` (Python) are the clients created in step 1, and the examples on the other pages use them too. TypeScript: ```bash npm install https://mirabase.io/sdk/mirabase-sdk-0.3.0-rc.1.tgz ``` Python: ```bash pip install https://mirabase.io/sdk/mirabase-0.3.0rc1-py3-none-any.whl ``` curl: ```bash # The curl examples read fields with jq, for example: # macOS: brew install jq # Debian or Ubuntu: sudo apt-get install jq # The curl examples use $SPACE_ID; default stands for your default Space. export SPACE_ID=default ``` Anywhere a Space id goes you can write `default`: it means your own default Space, or the only Space the key can see. The SDKs use the default Space when you name none. The curl examples require bash or zsh, where `$'…'` converts `\n` into a newline. ## Step 1: Sign up and create an API key Open the [console](https://console.mirabase.dev), sign in, and accept the terms. The sign-in methods are whichever the sign-in page actually offers, and the same verified email reaches the same account through any of them. Your first sign-in automatically creates your tenant and a default Space. Then create a key on the API keys page. The console shows the secret only once, so store it now. Put it in an environment variable and check that it works: curl: ```bash export MIRABASE_API_KEY="mb_live_..." curl https://api.mirabase.dev/v2/whoami \ -H "Authorization: Bearer $MIRABASE_API_KEY" ``` TypeScript: ```ts import { Mirabase } from "@mirabase/sdk/developer"; // Reads MIRABASE_API_KEY when apiKey is omitted. const mirabase = new Mirabase({ apiKey: process.env.MIRABASE_API_KEY }); const me = await mirabase.whoami(); ``` Python: ```python from mirabase import Mirabase # Reads MIRABASE_API_KEY when api_key is omitted. mb = Mirabase() me = mb.whoami() ``` `effective_capabilities` in the response is what this key can do right now. See [Authentication and API keys](https://mirabase.io/developers/authentication.md). > **Note:** Sign-up is limited by capacity. When the day's new accounts are used up or sign-up is closed for a while, new accounts cannot be created and the console says why, so try again later. New accounts need approval: until then you can sign in and create keys, but calling the API with a key returns 403 `account_pending_approval`. After approval every key works at once, with no need to create new ones. ## Step 2: Write a file by path The body of [`PUT /v2/spaces/{space_id}/files`](https://mirabase.io/developers/api/files.md#files-write) is the file. You do not need to create parent directories first. When the response returns, the write is committed and readable: curl: ```bash curl -s -X PUT "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files?path=/notes/launch.md" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: text/markdown" \ --data-binary $'The launch is on March 14.\nTina owns the checklist.\n' \ | tee v1.json | jq '{version_id, entry_id: .entry.id, state: .entry.knowledge.state}' # Save the id of this first version for steps 4 and 5. export V1=$(jq -r .version_id v1.json) ``` TypeScript: ```ts const path = "/notes/launch.md"; const v1 = await mirabase.files.write(path, "The launch is on March 14.\nTina owns the checklist.\n", { contentType: "text/markdown", }); console.log(v1.version_id, v1.entry.id, v1.entry.knowledge.state); ``` Python: ```python path = "/notes/launch.md" v1 = mb.files.write(path, "The launch is on March 14.\nTina owns the checklist.\n", content_type="text/markdown") print(v1["version_id"], v1["entry"]["id"], v1["entry"]["knowledge"]["state"]) ``` - `entry.id`: the file's stable identity, which does not change across renames and moves. - `version_id`: the immutable version this write created. Later steps use it to compare and revert. - `entry.knowledge.state`: `searchable` means lexical search can already find the text; it becomes `indexed` once processing finishes. ## Step 3: Read the file Read the same path to get back the raw bytes you wrote. The `ETag` is the version you read; the next step uses it for a conditional write. curl: ```bash # -i prints the headers too: ETag and Mirabase-Version-Id identify the version you read. curl -i "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files?path=/notes/launch.md" \ -H "Authorization: Bearer $MIRABASE_API_KEY" ``` TypeScript: ```ts const file = await mirabase.files.read(path); console.log(file.text()); console.log(file.etag); // the version you read ``` Python: ```python file = mb.files.read(path) print(file.text()) print(file.etag) # the version you read ``` ## Step 4: Edit the file and see its versions `PATCH` replaces exact text and creates a new version. With `If-Match`, the request fails with 412 if another caller or Agent wrote to the file in the meantime, so their change is not overwritten. The version list is ordered from newest to oldest, and `updated_from` points to the previous version. curl: ```bash # If-Match: the edit fails with 412 if the file changed after version 1. curl -s -X PATCH "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files?path=/notes/launch.md" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "If-Match: \"$V1\"" \ -H "Content-Type: application/json" \ -d '{"edits": [{"old_text": "March 14", "new_text": "March 21"}]}' \ | jq '{version_id, previous_version_id}' # List the file's versions, newest first. curl -s "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files/versions?path=/notes/launch.md" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ | jq '.data[] | {id, updated_from, created_at}' ``` TypeScript: ```ts // Fails with 412 if the file changed after you read it. const v2 = await mirabase.files.edit(path, { old_text: "March 14", new_text: "March 21" }, { ifMatch: file.etag }); console.log(v2.version_id, v2.previous_version_id); // List the file's versions, newest first. for await (const version of mirabase.files.versions(path)) { console.log(version.id, version.updated_from ?? null, version.created_at); } ``` Python: ```python # Fails with 412 if the file changed after you read it. v2 = mb.files.edit(path, {"old_text": "March 14", "new_text": "March 21"}, if_match=file.etag) print(v2["version_id"], v2.get("previous_version_id")) # List the file's versions, newest first. for version in mb.files.versions(path): print(version["id"], version.get("updated_from"), version["created_at"]) ``` ## Step 5: Compare and revert Compare version 1 with the latest version to get a unified diff. A revert writes the old version's content as a new version; all earlier versions are kept, so a revert can be reverted too. curl: ```bash # Compare version 1 with the latest version. curl -s "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files/diff?path=/notes/launch.md&from=$V1" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ | jq -r .unified_diff # Write version 1's content back as a new version. curl -s -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files/revert?path=/notes/launch.md" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"version_id": "'$V1'"}' \ | jq '{latest_version_id}' ``` TypeScript: ```ts // Compare version 1 with the latest version. const diff = await mirabase.versions.diff({ path }, v1.version_id); console.log(diff.unified_diff); // Write version 1's content back as a new version. const reverted = await mirabase.files.revert(path, v1.version_id); console.log(reverted.latest_version_id); ``` Python: ```python # Compare version 1 with the latest version. diff = mb.versions.diff({"path": path}, v1["version_id"]) print(diff.get("unified_diff")) # Write version 1's content back as a new version. reverted = mb.files.revert(path, v1["version_id"]) print(reverted["latest_version_id"]) ``` ```diff --- /notes/launch.md@ver_eba2c457e8456f97 +++ /notes/launch.md@ver_5e7d2e469ac6c42a @@ -1,2 +1,2 @@ -The launch is on March 14. +The launch is on March 21. Tina owns the checklist. ``` ## Step 6: Let an Agent work on a branch An Agent's changes are written to a branch first, while main remains unchanged. A checkpoint records the current state of the branch, and the branch can roll back to it. Review the branch's diff against main before you merge; with `on_conflict: "abort"`, the merge does not take effect if the same path was modified on main. In practice, issue the Agent [its own narrowly scoped API key](https://mirabase.io/developers/permissions.md#agents). curl: ```bash # 1. Create a branch for the Agent. Main does not change until the merge. export BRANCH_ID=$(curl -s -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/branches" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name": "agent/checklist"}' | jq -r .id) # 2. The Agent writes to the branch. curl -s -X PUT "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files?path=/notes/checklist.md&branch=$BRANCH_ID" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: text/markdown" \ --data-binary $'- [ ] Freeze the API\n- [ ] Publish the SDK\n' \ | jq '{path, changed}' # 3. Create a checkpoint that the branch can roll back to. curl -s -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/branches/$BRANCH_ID/checkpoints" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name": "draft-1"}' | jq '{id, name}' # 4. Compare the branch with main. curl -s "https://api.mirabase.dev/v2/spaces/$SPACE_ID/branches/$BRANCH_ID/diff" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ | jq -r '.data[] | "\(.change) \(.path)\n\(.unified_diff)"' # 5. Merge into main. Idempotency-Key is required so a retry cannot merge twice. curl -s -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/branches/$BRANCH_ID/merge" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Idempotency-Key: merge-$BRANCH_ID" \ -H "Content-Type: application/json" \ -d '{"message": "Add the launch checklist", "on_conflict": "abort"}' \ | jq '{state, merged}' ``` TypeScript: ```ts // 1. Create a branch for the Agent. Main does not change until the merge. const branch = await mirabase.branches.create({ name: "agent/checklist" }); // 2. The Agent writes to the branch. await mirabase.files.write("/notes/checklist.md", "- [ ] Freeze the API\n- [ ] Publish the SDK\n", { branch: branch.id, contentType: "text/markdown", }); // 3. Create a checkpoint that the branch can roll back to. const checkpoint = await mirabase.branches.checkpoints.create(branch.id, "draft-1"); console.log(checkpoint.id); // 4. Compare the branch with main. for await (const change of mirabase.branches.diff(branch.id)) { console.log(change.change, change.path); console.log(change.unified_diff); } // 5. Merge into main. The SDK sends the Idempotency-Key automatically. const merged = await mirabase.branches.merge(branch.id, { message: "Add the launch checklist", on_conflict: "abort" }); console.log(merged.state, merged.merged); ``` Python: ```python # 1. Create a branch for the Agent. Main does not change until the merge. branch = mb.branches.create({"name": "agent/checklist"}) # 2. The Agent writes to the branch. mb.files.write( "/notes/checklist.md", "- [ ] Freeze the API\n- [ ] Publish the SDK\n", branch=branch["id"], content_type="text/markdown", ) # 3. Create a checkpoint that the branch can roll back to. checkpoint = mb.branches.checkpoints.create(branch["id"], "draft-1") print(checkpoint["id"]) # 4. Compare the branch with main. for change in mb.branches.diff(branch["id"]): print(change["change"], change["path"]) print(change.get("unified_diff")) # 5. Merge into main. The SDK sends the Idempotency-Key automatically. merged = mb.branches.merge(branch["id"], {"message": "Add the launch checklist", "on_conflict": "abort"}) print(merged["state"], merged["merged"]) ``` For branch expiry, rollback, and large merges, see [Branches and checkpoints](https://mirabase.io/developers/branches.md). ## Step 7: Ask about the files and get citations [`POST /v2/retrieval/answer`](https://mirabase.io/developers/api/retrieval.md#retrieval-answer) selects evidence from files, knowledge, and memory, uses a model to generate an answer, and marks citations in the body text as `[cN]`. Each citation points to a specific version of an Entry: here `version_id` is the version created by the revert in step 5. When evidence is insufficient, it returns `abstained` instead of fabricating an answer. curl: ```bash curl -s -X POST https://api.mirabase.dev/v2/retrieval/answer \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"question": "When is the launch, and who owns the checklist?"}' \ | jq '{status, answer, reason, citations: [.citations[] | {citation_id, path, version_id}]}' ``` TypeScript: ```ts const reply = await mirabase.answer("When is the launch, and who owns the checklist?"); if (reply.status === "answered") console.log(reply.answer, reply.citations); else console.log("abstained:", reply.reason); ``` Python: ```python reply = mb.answer("When is the launch, and who owns the checklist?") if reply["status"] == "answered": print(reply["answer"], reply["citations"]) else: print("abstained:", reply.get("reason")) ``` ```json { "status": "answered", "answer": "The launch is on March 14, and Tina owns the checklist [c1].", "citations": [ { "citation_id": "c1", "entry_id": "ent_cecf61d9d54a1dbb", "version_id": "ver_0b611ffa8bd0b060", "space_id": "col_91f8c425c93c2f99", "path": "/notes/launch.md", "modified_at": "2026-11-17T05:19:34.078Z", "title": "launch.md", "source": "knowledge", "text": "The launch is on March 14.\nTina owns the checklist.\n" } ], "evidence_count": 2, "pack_id": "trc_b67b4d4494102309", "partial": false } ``` ## Step 8: Connect an Agent over MCP Over MCP, an Agent reads and writes the same files and sees the same versions returned by the API and the SDKs. Add Mirabase to Claude Code or Codex, or add the JSON configuration to any client that supports remote MCP: Claude Code: ```bash claude mcp add --transport http mirabase https://api.mirabase.dev/mcp \ --header "Authorization: Bearer $MIRABASE_API_KEY" ``` Codex: ```bash codex mcp add mirabase --url https://api.mirabase.dev/mcp \ --bearer-token-env-var MIRABASE_API_KEY ``` JSON: ```json { "mcpServers": { "mirabase": { "type": "http", "url": "https://api.mirabase.dev/mcp", "headers": { "Authorization": "Bearer mb_live_..." } } } } ``` After connecting, ask the Agent: “Read /notes/launch.md and /notes/checklist.md in Mirabase and list what is left before the launch.” The MCP tools list, read, write, edit, and delete files, and cover search, answers, and memory; versions and branches are currently available through the API and the SDKs. For the tool list, see [Connect an Agent (MCP)](https://mirabase.io/developers/agents.md#tools). ## Next steps 1. Learn how [Entries, versions, files, knowledge, and memory](https://mirabase.io/developers/concepts.md) fit together. 2. [Search](https://mirabase.io/developers/retrieval.md#search) the files, or get evidence for your own model with [context](https://mirabase.io/developers/retrieval.md#context). 3. [Write a memory](https://mirabase.io/developers/memory.md#create), or [ingest a conversation](https://mirabase.io/developers/memory.md#conversation) for the service to distill memories from. 4. Give each end user [a Space of their own](https://mirabase.io/developers/concepts.md#space-per-user), found by your own user id. 5. Have an Agent's writes [go through proposals and review](https://mirabase.io/developers/files.md#proposals), or [limit the directories it can write to](https://mirabase.io/developers/permissions.md#roots). 6. Keep a Space in sync with the [change feed and snapshots](https://mirabase.io/developers/sync.md). --- # Authentication and API keys Send, create, limit, rotate, and revoke API keys. ## Send an API key Send `Authorization: Bearer mb_live_...` on every request. The token is 256 random bits, not a JWT, so it contains no readable data. The service stores only a hash and looks it up on every request. ```bash curl https://api.mirabase.dev/v2/whoami \ -H "Authorization: Bearer $MIRABASE_API_KEY" ``` > **Warning:** Keep keys on a server. Never put one in frontend code, a mobile app, or a public repository. Revoke a key as soon as you suspect it leaked. Only [`GET /llms.txt`](https://mirabase.io/developers/api/discovery.md#discovery-llms) and [`GET /v2/openapi.yaml`](https://mirabase.io/developers/api/discovery.md#discovery-openapi) work without credentials. ## Create a key in the console The [console](https://console.mirabase.dev) creates, narrows, rotates, and revokes API keys. Your first key comes from there: signing up does not issue one. The console shows the secret only once. A console session manages the account and serves the console's own features: listing and deleting files, processing progress, the retrieval playground, and request logs. Reading file content and writing files accept API keys alone. While the account is pending approval, a session can only manage API keys and view the account and the read-only lists; other requests return 403 `account_pending_approval`. ## Create a key through the API [`POST /v2/api-keys`](https://mirabase.io/developers/api/api-keys.md#apikeys-create) issues a key. Only a `tenant_admin` can issue one, and an Agent cannot issue its own; a new key cannot be wider than its issuer in capabilities, Spaces, or expiry. `token` appears in this response only, so store it now. curl: ```bash curl -X POST https://api.mirabase.dev/v2/api-keys \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"actor_id": "'$PRINCIPAL_ID'", "name": "ci-reader", "grant_capabilities": ["knowledge:read"], "allowed_space_ids": ["'$SPACE_ID'"], "expires_at": "2027-01-01T00:00:00Z"}' ``` TypeScript: ```ts const key = await mirabase.keys.create({ actor_id: principalId, name: "ci-reader", grant_capabilities: ["knowledge:read"], allowed_space_ids: [spaceId], expires_at: "2027-01-01T00:00:00Z", }); ``` Python: ```python key = mb.keys.create({ # The principal the key acts as: here, yourself. "actor_id": me["principal"]["id"], "name": "ci-reader", "grant_capabilities": ["knowledge:read"], "allowed_space_ids": [space_id], "expires_at": "2027-01-01T00:00:00Z", }) ``` In an account with a team, which principals and keys an Admin can manage is in the description of [issuing a key](https://mirabase.io/developers/api/api-keys.md#apikeys-create); the Owner is not subject to these rules. ## Limit a key by metadata Send `metadata_scope` when issuing a key, and the key only sees Entries that carry the matching metadata labels. Different metadata keys combine with AND, and multiple values of one metadata key combine with OR. For the operations such a key can call, see [the metadata_scope parameter](https://mirabase.io/developers/api/api-keys.md#apikeys-create.body.metadata_scope); for how its writes are labeled, see [DevMetadataScope](https://mirabase.io/developers/api/schemas.md#DevMetadataScope). ```bash curl -X POST https://api.mirabase.dev/v2/api-keys \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"actor_id": "'$PRINCIPAL_ID'", "name": "acme-agent", "grant_capabilities": ["knowledge:read", "knowledge:answer", "knowledge:write"], "metadata_scope": {"customer": ["acme", "shared"]}}' ``` - The service checks the scope on every request, and the caller cannot bypass it. - Near-duplicate replacement and memory revision only relate Entries with the same values under the scope keys, so one customer's writes never affect another's content. - Account memories carry no labels and are not visible to a key with a scope. - Over MCP, `tools/list` shows a key with a scope only the tools it can call. You can also issue a key with a scope on the API keys page of the [console](https://console.mirabase.dev). - A scope does not hide the names and `external_id` of Spaces. For a hard boundary between end users, give each user a Space. See [One Space per end user](https://mirabase.io/developers/concepts.md#space-per-user). ## Check what a key can do [`GET /v2/whoami`](https://mirabase.io/developers/api/identity.md#identity-whoami) returns the principal, the key, and the effective capabilities. Check it after a 403: when `effective_capabilities` is narrower than `principal.capabilities`, or `key.allowed_space_ids` is set, the key is the limit, not the principal. For how the service computes effective capabilities, see [Capabilities](https://mirabase.io/developers/permissions.md#capabilities). ## Rotate or replace a key [`POST /v2/api-keys/{key_id}/rotate`](https://mirabase.io/developers/api/api-keys.md#apikeys-rotate) issues a new key and revokes the old one in a single transaction, with no overlap. A key cannot rotate itself: if the response were lost, the caller would have no credentials left. To replace the key you are using: 1. Issue a new key with [`POST /v2/api-keys`](https://mirabase.io/developers/api/api-keys.md#apikeys-create). 2. Switch your callers to the new key. 3. Revoke the old key with [`DELETE /v2/api-keys/{key_id}`](https://mirabase.io/developers/api/api-keys.md#apikeys-revoke). > **Note:** If the response to the issue is lost, the old key still works: issue again under a new `Idempotency-Key`. The unused key stays in [`GET /v2/api-keys`](https://mirabase.io/developers/api/api-keys.md#apikeys-list) until an admin revokes it. ## Find unused keys Every key carries `last_used_at`: when it last called the API (see [DevApiKey](https://mirabase.io/developers/api/schemas.md#DevApiKey.last_used_at)). Use it to clean up idle keys and to see whether the recipient has started using a key you handed out; the key list in the [console](https://console.mirabase.dev) shows it too. ## Revoke a key Once [`DELETE /v2/api-keys/{key_id}`](https://mirabase.io/developers/api/api-keys.md#apikeys-revoke) returns, the next request with that key returns 401, and no write it started can still commit. Revocation does not cascade: after a leak, use each key's `issued_by_key_id` to find the keys it issued and revoke them one by one. ## Delete your account To delete your account and all of its data, [contact us](https://mirabase.app/en/contact) with the account's email and its `tenant_id`, which [`GET /v2/whoami`](https://mirabase.io/developers/api/identity.md#identity-whoami) returns. - Deleted data cannot be recovered. Take the files you want to keep with an [export](https://mirabase.io/developers/sync.md#export) first; exports hold files only, without memories or version history. - To remove only some of your content you do not need to contact us: [erase](https://mirabase.io/developers/files.md#delete) files and [forget](https://mirabase.io/developers/memory.md#govern) memories yourself. ## Next steps - [SDK](https://mirabase.io/developers/sdks.md): install a client instead of building requests by hand. - [Permissions](https://mirabase.io/developers/permissions.md): how capabilities combine, and how to limit a key to certain Spaces and directories. - [Connect an Agent](https://mirabase.io/developers/agents.md): give an Agent its own principal and key. --- # SDK Install and configure the TypeScript and Python clients, and learn what they handle for you: Space selection, streaming answers, errors, retries, and pagination. ## Install the SDK | Language | Package | Version | Requires | | --- | --- | --- | --- | | TypeScript | `@mirabase/sdk` | 0.3.0-rc.1 | Node.js 20.3 or newer, ES modules only, no dependencies | | Python | `mirabase` | 0.3.0rc1 | Python 3.11 or newer, no dependencies | TypeScript: ```bash npm install https://mirabase.io/sdk/mirabase-sdk-0.3.0-rc.1.tgz ``` Python: ```bash pip install https://mirabase.io/sdk/mirabase-0.3.0rc1-py3-none-any.whl ``` > **Note:** 0.3.0-rc.1 (0.3.0rc1 in Python) is a release candidate for 0.3.0. Methods and response fields may still change before the final release. > **Note:** This site serves the packages at versioned URLs. To upgrade, install from the new version's URL. Older URLs keep working, and their content never changes. `https://mirabase.io/sdk/SHA256SUMS` lists the SHA-256 checksum of every file. > **Warning:** In 0.2.0, a client pinned to a Space (via the `space` option or `space(id)`) did not restrict `search`, `context`, and `answer` to that Space, reading every Space the key can read instead. Upgrade to 0.3.0-rc.1 (0.3.0rc1 in Python). ## Create a client TypeScript: ```ts import { Mirabase } from "@mirabase/sdk/developer"; // Reads MIRABASE_API_KEY when apiKey is omitted. const mirabase = new Mirabase(); await mirabase.files.write("/notes/plan.md", "We ship on Friday.\n"); const hits = await mirabase.search("when do we ship?"); ``` Python: ```python from mirabase import Mirabase # Reads MIRABASE_API_KEY when api_key is omitted. mb = Mirabase() mb.files.write("/notes/plan.md", "We ship on Friday.\n") hits = mb.search("when do we ship?") ``` | TypeScript | Python | Default | Meaning | | --- | --- | --- | --- | | `apiKey` | `api_key` | The `MIRABASE_API_KEY` environment variable | The API key | | `baseUrl` | `base_url` | `https://api.mirabase.dev` | The service address | | `space` | `space` | Not pinned | Pins the client to one Space, as described below | | `timeoutMs` | `timeout` | 60 seconds | Timeout of each attempt | | `maxRetries` | `max_retries` | 3 | How many times to retry | | `maxRetryAfterMs` | `max_retry_after` | 60 seconds | When the service asks for a longer wait than this, the client returns the error to you without waiting | Python also has `AsyncMirabase` with the same methods for `asyncio`, with `async with` and `aclose()`. Every request carries `User-Agent: mirabase-node/` (`mirabase-python/` in Python); the version is also in `SDK_VERSION` (TypeScript) and `mirabase.__version__` (Python). ## Choose the Space a call uses | Client | Files, ingest, conversations, and the like | `search`, `context`, `answer` | | --- | --- | --- | | Not pinned | The default Space | Every Space the key can read | | Pinned with the `space` option or `space(id)` | The pinned Space | The pinned Space only | - Any call can name one Space with `space`. `search`, `context`, and `answer` also take `spaces`: a list of Space ids, or `"all"` for every Space the key can read. `spaces` takes precedence over `space`, and both take precedence over the pinned Space. - Wherever a call takes a Space id, you can also pass `default` or `ext:`. - The client looks up the default Space once with [`GET /v2/spaces/default`](https://mirabase.io/developers/api/spaces.md#spaces-read) and caches it. With one Space per end user, `spaceFor` (`space_for` in Python) takes your own user id and returns a client pinned to that user's Space, creating the Space when there is none. `spaces.ensure` returns the Space itself. Both send one [`PUT /v2/spaces/ext:`](https://mirabase.io/developers/api/spaces.md#spaces-ensure) and are safe to call again. See [One Space per end user](https://mirabase.io/developers/concepts.md#space-per-user). TypeScript: ```ts const user = await mirabase.spaceFor("user-42", { name: "User 42" }); await user.conversations.add(messages, { sessionId: "chat-1" }); const reply = await user.answer("What does this user prefer?"); // reads this Space only const space = await mirabase.spaces.ensure("user-42"); // the Space itself ``` Python: ```python user = mb.space_for("user-42", name="User 42") user.conversations.add(messages, session_id="chat-1") reply = user.answer("What does this user prefer?") # reads this Space only space = mb.spaces.ensure("user-42") # the Space itself ``` ## Stream an answer `answer.stream` takes the same arguments as `answer` and yields `start`, `delta`, `replace`, and `final` events as the answer is written; see [Stream an answer](https://mirabase.io/developers/retrieval.md#answer-stream) for what each event means. `stream.text` is the text so far, and the `answer` of `final` is what `answer()` returns. 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"]) ``` - The SDK throws `MirabaseError` for an `error` event, a stream cut off midway, or unparseable data, never a raw parse error. It does not retry a stream after it starts. - Leaving the loop early, calling `close()`, or aborting the `signal` closes the connection, and the service cancels the answer. In Python use `with` and `for`, and `async with` and `async for` with `AsyncMirabase`. - `answer` itself does not stream: passing `stream: true` (`stream=True` in Python) throws `MirabaseConfigError` with code `stream_not_supported` and sends no request. ## Handle errors A failed request throws `MirabaseError` or one of its subclasses. The subclass follows the HTTP status, so `instanceof` (`except` in Python) can handle one class of error. Branch on `code` and `action` for the specific case: they are stable. `message` is for human readers. | Class | HTTP status | | --- | --- | | `MirabaseValidationError` | 400, 422 | | `MirabaseAuthenticationError` | 401 | | `MirabasePermissionError` | 403 | | `MirabaseNotFoundError` | 404, 410 | | `MirabaseConflictError` | 409, 412 | | `MirabaseRateLimitError` | 429 | | `MirabaseServerError` | 500 and above | | `MirabaseConnectionError` | No response arrived: a network failure or a timeout. The message names the address, the request, and the cause | | `MirabaseConfigError` | A mistake in the call, caught before sending the request. The API key is checked 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 gives the code `invalid_api_key`, with a message that never contains the key | All of them extend `MirabaseError`; any other status throws `MirabaseError` itself. | TypeScript | Python | Meaning | | --- | --- | --- | | `status` | `status` | HTTP status | | `code` | `code` | The error code; see [Error codes](https://mirabase.io/developers/errors.md#codes) | | `type` | `type` | The broad class of the error, such as `not_found` or `rate_limit` | | `action` | `action` | The next step, when the service names one | | `retryable` | `retryable` | Whether a retry can help | | `requestId` | `request_id` | The request id. Include it when contacting support | | `field` | `field` | First offending field on a 422 | | `errors` | `errors` | On a 422, every problem in the request body, each as `{field, code, message}` | | `limit` | `limit` | On a 429, the limit that was hit: `request_rate` or `concurrency` | | `retryAfterSeconds` | `retry_after_seconds` | Seconds the service asked you to wait | | `currentVersionId` | `current_version_id` | The file's current version on a 412 | | `body` | `body` | The response body | TypeScript: ```ts import { MirabaseConflictError, MirabaseRateLimitError } from "@mirabase/sdk/developer"; const { etag } = await mirabase.files.stat("/notes/plan.md"); try { await mirabase.files.write("/notes/plan.md", "v2\n", { ifMatch: etag }); } catch (error) { if (error instanceof MirabaseConflictError && error.code === "precondition_failed") { // Someone else wrote first: read again, then retry on error.currentVersionId. } else if (error instanceof MirabaseRateLimitError) { console.log(error.limit, error.retryAfterSeconds); } else { throw error; } } ``` Python: ```python from mirabase import MirabaseConflictError, MirabaseRateLimitError etag = mb.files.stat("/notes/plan.md").etag try: mb.files.write("/notes/plan.md", "v2\n", if_match=etag) except MirabaseConflictError as error: if error.code != "precondition_failed": raise ... # Someone else wrote first: read again, then retry on error.current_version_id. except MirabaseRateLimitError as error: print(error.limit, error.retry_after_seconds) ``` ## Retries and idempotency - The SDK retries a 429 automatically after the `Retry-After` wait. When `Retry-After` is longer than `maxRetryAfterMs` (`max_retry_after` in Python), it does not wait and throws `MirabaseRateLimitError`. - The SDK retries network errors and 5xx responses only when repeating is safe: reads, and writes that carry an idempotency key. - For every call that takes `Idempotency-Key`, the SDK generates a key and reuses it on a retry, so a retry never writes twice. See [API conventions](https://mirabase.io/developers/conventions.md#idempotency) for the rules. - The SDK does not retry an error with `retryable` set to `false`. ## Iterate a list A list method returns an object you can iterate, and it fetches pages as needed. `limit` is the page size, not a total. Use `take` when you want only the first few. TypeScript: ```ts for await (const entry of mirabase.entries.list()) { console.log(entry.id); } const firstTen = await mirabase.entries.list().take(10); ``` Python: ```python for entry in mb.entries.list(): print(entry["id"]) first_ten = mb.entries.list().take(10) ``` `search` returns the array of hits, which also carries `traceId` and `partial` (`trace_id` and `partial` in Python). When `partial` is `true`, the results may be incomplete. ## Upload a large file `files.write` picks the route itself: one `PUT` up to 16 MiB, and a multipart upload above that. The call is the same either way. ## Call an endpoint directly Every endpoint in the [API reference](https://mirabase.io/developers/api.md) has a method of its own on `raw` (`mirabase.raw` in TypeScript, `mb.raw` in Python). Reach for it when a resource method does not fit. Authentication, retries, and errors work the same. ## Next steps - [Core concepts](https://mirabase.io/developers/concepts.md): learn what Spaces, Entries, versions, and memory are. - [Files and versions](https://mirabase.io/developers/files.md): write, read, and edit files. - [Memory](https://mirabase.io/developers/memory.md#conversation): store a conversation with `conversations.add` and wait for the service to distill memories. - [API conventions](https://mirabase.io/developers/conventions.md): see the rules behind the pagination, idempotency, and retries the SDK handles for you. --- # Core concepts The data model behind the API: Spaces, Entries and versions, files, knowledge, memory, branches, and access control. The source layer in Mirabase has one kind of data: an **Entry with immutable versions**. A file is how you locate an Entry, knowledge is what processing produces from it, and part of memory comes from it. ```text Entry ├─ id, space_id, title, metadata ├─ latest_version_id newest committed version ├─ current_version_id version serving search ├─ file { path, size, media_type, etag } or null ├─ knowledge { state, indexed_version_id } ├─ memory { scope, kind, pinned, exclude } or null ├─ memory_exclude kept out of memory distillation └─ access { role, capabilities } ``` ## Space A Space is the boundary for permissions and paths. Every account has a default Space, and [`POST /v2/spaces`](https://mirabase.io/developers/api/spaces.md#spaces-create) creates more. Members, roles, and the file tree are all per Space. An account can hold many Spaces (up to `tenant_spaces`, see [Rate limits and quotas](https://mirabase.io/developers/conventions.md#rate-limits)), so you can give each end user or each project its own. Deleting a Space deletes everything in it and cannot be undone, and the default Space cannot be deleted: see [`DELETE /v2/spaces/{space_id}`](https://mirabase.io/developers/api/spaces.md#spaces-delete). ### One Space per end user When end users must be kept strictly apart, give each one a Space: files, knowledge, and memory are all kept per Space, which metadata cannot do. Set your own user id as the Space's `external_id`, then write `ext:`, such as `ext:user-42`, wherever a Space id goes: in a path, in `?space_id=`, and in `space_ids` in a request body. There is no mapping table to keep. [`PUT /v2/spaces/ext:`](https://mirabase.io/developers/api/spaces.md#spaces-ensure) returns the Space or creates it. Two requests that arrive together create one Space, and calling it again is safe, so one call before the first write for a new user is enough. In the SDKs this is `spaces.ensure`, and `spaceFor` (`space_for` in Python) also returns a client pinned to that Space. curl: ```bash # Returns the Space whose external_id is user-42 (200), or creates it (201). curl -X PUT "https://api.mirabase.dev/v2/spaces/ext:user-42" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name": "User 42"}' # ext:user-42 works wherever a Space id does. curl -X PUT "https://api.mirabase.dev/v2/spaces/ext:user-42/files?path=/notes/plan.md" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: text/markdown" \ --data-binary "We ship on Friday." ``` TypeScript: ```ts // A client pinned to the user's Space. The Space is created on the first call. const user = await mirabase.spaceFor("user-42", { name: "User 42" }); await user.files.write("/notes/plan.md", "We ship on Friday.\n"); const hits = await user.search("when do we ship?"); // reads this Space only ``` Python: ```python # A client pinned to the user's Space. The Space is created on the first call. user = mb.space_for("user-42", name="User 42") user.files.write("/notes/plan.md", "We ship on Friday.\n") hits = user.search("when do we ship?") # reads this Space only ``` - `search`, `context`, and `answer` without `space_ids` read every Space the key can read, not only the default Space. When a request is about one user, name that user's Space. In the SDKs, a client pinned to a Space reads that Space only. - [`GET /v2/spaces?external_id=`](https://mirabase.io/developers/api/spaces.md#spaces-list) looks a Space up by `external_id`, returns at most one, and never creates one (`spaces.findByExternalId` and `spaces.find_by_external_id` in the SDKs). - Deleting a Space frees its `external_id` for reuse. ## Entries and versions An Entry is the stable identity of a source: a file, a URL, or a piece of text. Each change of content makes a version. Versions are immutable, and the service keeps the chain. - `latest_version_id` is the newest committed version. Reads use it by default, so you can read what you just wrote. - `current_version_id` is the version `search` and `context` read from. It equals `latest_version_id` once that version is indexed, and stays on the earlier version while a newer one is still processing. It is absent until the first version finishes processing. - A new title is also a new version, because the title is indexed. The only thing you can change on a version is its `message`. You can reach an Entry by path, by id, or by meaning through search. All these access methods share the same identity, permissions, and version chain. ## Files An Entry with a path is a file. The path is the identity: the same bytes at two paths are two files. Renames and moves keep the Entry id. An Entry can also have no path, such as a URL or text added through `ingest`: its `file` is `null`. **Use `files` when you have a path and `entries` when you have an id**. Both take the same read parameters. See [Files and versions](https://mirabase.io/developers/files.md). ## Knowledge Knowledge is not a separate resource. It is the processing state of an Entry. After a write commits, the service parses, chunks, and indexes it, and `knowledge.state` reports progress: | State | Meaning | What works | | --- | --- | --- | | `readable` | Committed | Read the original by path or id | | `searchable` | Text up to 64 KiB from the request body is in the freshness buffer | Lexical search | | `indexed` | Processing finished | Full-text, vector, and reranked search | | `failed` | Processing failed; the bytes remain readable | Read the original, or call `reprocess` | A write is committed before processing finishes. To wait for processing, send `Prefer: wait=N` on the write; see [`PUT /v2/spaces/{space_id}/files`](https://mirabase.io/developers/api/files.md#files-write). ## Memory A memory is a statement with a scope, a status, and a source: an account memory, a memory written as an Entry, or a fact distilled from an Entry. A distilled fact is not an Entry, and its id is not an Entry id. For scopes, statuses, and validity, see [The memory model](https://mirabase.io/developers/memory.md#model). ## Branches A branch is a copy-on-write layer over a Space's main line, used as an Agent's workspace. Content on it creates no versions and is not processed. Each path becomes a new version only when merged into main. See [Branches and mounts](https://mirabase.io/developers/branches.md). ## Access control Every request acts as a principal, a person or an Agent, carried by an API key. What a request may do depends on the capabilities the principal and the key both hold, the principal's role in the Space, and the read and write roots the Space owner set for the member. See [Permissions](https://mirabase.io/developers/permissions.md). ## Next steps - [Files and versions](https://mirabase.io/developers/files.md): start by writing a file. - [Retrieval and context](https://mirabase.io/developers/retrieval.md): search, context, and answers with citations. - [Memory](https://mirabase.io/developers/memory.md): distill facts from conversations, then review, correct, and forget them. --- # Glossary The terms these docs use, each defined in one sentence and linked to the page that explains it. | Term | Definition | Explained in | | --- | --- | --- | | Space | The boundary for permissions and paths, within which members, roles, and the file tree are kept, with one default Space per account. | [Core concepts](https://mirabase.io/developers/concepts.md#space) | | Entry | The stable identity of a source, such as a file, a URL, or a piece of text. | [Core concepts](https://mirabase.io/developers/concepts.md#entry-version) | | Version | An immutable record of an Entry's content, made each time the content changes. | [Core concepts](https://mirabase.io/developers/concepts.md#entry-version) | | Knowledge state | The processing progress of an Entry, reported in `knowledge.state`. | [Core concepts](https://mirabase.io/developers/concepts.md#knowledge) | | Memory | A statement with a scope, a status, and a source, which is an account memory, a memory written as an Entry, or a fact distilled from an Entry. | [Memory](https://mirabase.io/developers/memory.md#model) | | Memory scope | What a memory belongs to: `project` is one Space, `agent` is one Agent, and `account` is the account. | [Memory](https://mirabase.io/developers/memory.md#model) | | Memory status | Where a memory stands in review: `candidate`, `confirmed`, `rejected`, or `superseded`. | [Memory](https://mirabase.io/developers/memory.md#model) | | Principal | The person (`kind: human`) or Agent (`kind: agent`) a request acts as; an API key belongs to a principal and is not one itself. | [Permissions](https://mirabase.io/developers/permissions.md#principals) | | Capability | Permission for one kind of operation, such as `knowledge:read` or `knowledge:write`. | [Permissions](https://mirabase.io/developers/permissions.md#capabilities) | | API key | The credential sent on every request as `Authorization: Bearer mb_live_...`, which can only narrow its principal. | [Authentication and API keys](https://mirabase.io/developers/authentication.md#bearer) | | Agent | A principal of `kind: agent`, with its own permissions, memory, and audit identity. | [Permissions](https://mirabase.io/developers/permissions.md#principals) | | Context pack | What `context` returns for a task: sources the service picked and packed within a token budget, with its choices explained in `route`. | [Retrieval and context](https://mirabase.io/developers/retrieval.md#context) | | Citation | The `[cN]` id of one source in a context pack, which an answer uses to mark where a statement comes from. | [Retrieval and context](https://mirabase.io/developers/retrieval.md#answer) | | Branch | A copy-on-write layer over a Space's main line, used as an Agent's workspace, whose paths become versions on main only when merged. | [Branches and mounts](https://mirabase.io/developers/branches.md#branches) | | Checkpoint | A record of a branch's own changes at one moment, which the branch can roll back to. | [Branches and mounts](https://mirabase.io/developers/branches.md#checkpoints) | | Snapshot | A record of every file's path and version in a Space at one moment, which copies no bytes. | [Sync, snapshots, and export](https://mirabase.io/developers/sync.md#snapshots) | | Proposal | A write an Agent submits for a file owned by someone else, which becomes a new version only when a reviewer approves it. | [Files and versions](https://mirabase.io/developers/files.md#proposals) | | Job | Work that cannot finish within the request, which returns 202 with a `job_id` that you poll until the status is final. | [API conventions](https://mirabase.io/developers/conventions.md#jobs) | | Read root | The `read_root` the Space owner sets on a member, which limits reads to that directory and returns 404 for paths outside it. | [Permissions](https://mirabase.io/developers/permissions.md#roots) | | Write root | The `write_root` the Space owner sets on a member, which limits writes to that directory. | [Permissions](https://mirabase.io/developers/permissions.md#roots) | | Idempotency key | The `Idempotency-Key` header on a write, which lets you send the write again without running it twice. | [API conventions](https://mirabase.io/developers/conventions.md#idempotency) | | Cursor | An opaque string a list or the change feed returns, used to read the next page or continue. | [API conventions](https://mirabase.io/developers/conventions.md#pagination) | | ETag | The id of a file's latest version, used for conditional writes and reads. | [API conventions](https://mirabase.io/developers/conventions.md#conditional) | | Offline consolidation | An optional deployment feature that tidies existing memories while no Agent is working, without generating new content; each run is called a dream in the API. | [Memory](https://mirabase.io/developers/memory.md#dreams) | ## Next steps - [Files and versions](https://mirabase.io/developers/files.md): start by writing a file. - [Permissions](https://mirabase.io/developers/permissions.md): how principals, capabilities, roles, and roots decide a request. - [API reference](https://mirabase.io/developers/api.md): the parameters and responses of every endpoint. --- # Files and versions Write, read, edit, and organize files, compare and revert versions, and handle Agent proposals. ## Write a file [`PUT /v2/spaces/{space_id}/files`](https://mirabase.io/developers/api/files.md#files-write) creates or replaces a file. The request body is the file. When it returns, the write is committed and readable. Size limits, status codes, and headers are in the reference. curl: ```bash curl -X PUT "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files?path=/notes/hello.md" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: text/markdown" \ --data-binary "Mirabase keeps files, knowledge and memory in one place." ``` TypeScript: ```ts const written = await mirabase.files.write( "/notes/hello.md", "Mirabase keeps files, knowledge and memory in one place.", { contentType: "text/markdown" }, ); ``` Python: ```python written = mb.files.write( "/notes/hello.md", "Mirabase keeps files, knowledge and memory in one place.", content_type="text/markdown", ) ``` - Check `version_created` in the response: it is `false` when the bytes and media type are unchanged, and then no version is created and no quota is used. - Without `Content-Type`, the file is stored as `application/octet-stream`. - To return only once this version can be searched, send [Prefer: wait=N](https://mirabase.io/developers/api/files.md#files-write.Prefer). When the key already holds 4 waiting requests, the call does not wait and the response has no `Preference-Applied`. - With a `branch` parameter the write goes to a branch instead of main. See [Branches and mounts](https://mirabase.io/developers/branches.md#reads). ## Record the time, metadata, and memory switch A write can also record three things: when the content happened ([occurred_at](https://mirabase.io/developers/api/files.md#files-write.occurred_at)), your own metadata ([metadata](https://mirabase.io/developers/api/files.md#files-write.metadata)), and whether memory is distilled from it ([memory_exclude](https://mirabase.io/developers/api/files.md#files-write.memory_exclude)). They are kept on the file's Entry and do not change from version to version. The body of a `PUT` is the file's bytes, so the three travel as query parameters, and `metadata` is URL-encoded JSON. ```bash # The body is the file, so the three values ride in the query. --url-query (curl 7.87 or newer) # URL-encodes each one; metadata is a JSON object. curl -X PUT "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files" \ --url-query "path=/recordings/2026-11-06-standup.m4a" \ --url-query "occurred_at=2026-11-06T09:30:00+08:00" \ --url-query 'metadata={"device":"recorder-01","room":"3f"}' \ --url-query "memory_exclude=true" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: audio/mp4" \ --data-binary @standup.m4a ``` - Only what you send changes: replacing a file leaves the items you did not send as they were. They apply even when the content is unchanged: writing the same bytes again with a new `occurred_at` returns `version_created: false`, and the time is updated. - In each item of a [batch](https://mirabase.io/developers/files.md#batch) and in the completion request of a [large file](https://mirabase.io/developers/files.md#uploads), they are body fields of the same names. - To change them later, use [`PATCH /v2/entries/{entry_id}`](https://mirabase.io/developers/api/entries.md#entries-update). ## Avoid overwriting changes Without a condition the last write wins, and the version chain stays intact. To avoid overwriting, send the `ETag` you read in `If-Match`; to create only, send `If-None-Match: *`. The full rules for conditional requests are in [API conventions](https://mirabase.io/developers/conventions.md#conditional). curl: ```bash # Fails with 412 if someone wrote a newer version since you read this one. curl -X PUT "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files?path=/notes/hello.md" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H 'If-Match: "ver_2b10"' \ -H "Content-Type: text/markdown" \ --data-binary @hello.md # Fails with 412 if the file already exists. curl -X PUT "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files?path=/notes/new.md" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "If-None-Match: *" \ -H "Content-Type: text/markdown" \ --data-binary @new.md ``` TypeScript: ```ts // Fails with 412 if someone wrote a newer version since you read this one. await mirabase.files.write("/notes/hello.md", nextText, { contentType: "text/markdown", ifMatch: written.entry.file!.etag, }); // Fails with 412 if the file already exists. await mirabase.files.write("/notes/new.md", newText, { contentType: "text/markdown", createOnly: true }); ``` Python: ```python # Fails with 412 if someone wrote a newer version since you read this one. mb.files.write( "/notes/hello.md", "Mirabase keeps files, knowledge and memory in one place, with every version kept.", content_type="text/markdown", if_match=written["entry"]["file"]["etag"], ) # Fails with 412 if the file already exists. mb.files.write("/notes/new.md", "A new note.", content_type="text/markdown", create_only=True) ``` On 412 `precondition_failed`, `current_version_id` in the error is the version now: read the file again, reapply your change, and write with the new `ETag`. ## Edit text [`PATCH /v2/spaces/{space_id}/files`](https://mirabase.io/developers/api/files.md#files-patch) replaces strings, so you do not send the whole file. It works on UTF-8 text, and each `old_text` must appear exactly once unless `replace_all` is set. ```bash curl -X PATCH "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files?path=/notes/hello.md" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"edits": [{"old_text": "one place", "new_text": "a single place"}]}' ``` A failed edit creates no version. On `edit_no_match`, read the file again and edit; on `edit_ambiguous`, add context or set `replace_all`; when the file is too large or not text, replace it with `PUT`. Error codes and size limits are in the reference. ## Read a file [`GET /v2/spaces/{space_id}/files`](https://mirabase.io/developers/api/files.md#files-read) reads by path and [`GET /v2/entries/{entry_id}/content`](https://mirabase.io/developers/api/entries.md#entries-content) reads by id. Both take the same parameters and read the latest version by default. [view](https://mirabase.io/developers/api/schemas.md#DevFileView) selects which form to return; the default is raw bytes. You can read the `text` view of a text file right after the write; the other views are available after processing finishes. Send `version` to read an older version, `snapshot` to read through a snapshot (see [Snapshots](https://mirabase.io/developers/sync.md#snapshots)), and `Range` to read part of the bytes. The rules for each parameter are in the reference. ### Download URLs To hand a large file to a browser or another service, sign a short-lived URL for the original bytes with [`GET /v2/spaces/{space_id}/files/content-url`](https://mirabase.io/developers/api/files.md#files-contenturl) or [`GET /v2/entries/{entry_id}/content-url`](https://mirabase.io/developers/api/entries.md#entries-contenturl). You can fetch the URL without the key. curl: ```bash # A signed URL for the original bytes, valid 60 to 300 seconds. Fetch it without the key. curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files/content-url?path=/videos/talk.mp4&expires_in=120" \ -H "Authorization: Bearer $MIRABASE_API_KEY" ``` TypeScript: ```ts const link = await mirabase.files.contentUrl("/videos/talk.mp4", { expiresIn: 120 }); // link.url works until link.expires_at for anyone who holds it: treat it like the key. const bytes = await fetch(link.url); ``` Python: ```python from urllib.request import urlopen link = mb.files.content_url("/videos/talk.mp4", expires_in=120) # link["url"] works until link["expires_at"] for anyone who holds it: treat it like the key. data = urlopen(link["url"]).read() ``` > **Warning:** Until it expires, anyone holding the URL can fetch the bytes, and revoking the key does not stop that, so treat the URL like the key. ## Organize directories [`GET /v2/spaces/{space_id}/tree`](https://mirabase.io/developers/api/tree.md#tree-list) lists a directory. [`POST /v2/spaces/{space_id}/tree/operations`](https://mirabase.io/developers/api/tree.md#tree-operations) runs `mkdir`, `move`, `copy`, `delete`, and `restore` in order, and all of them apply or none do. curl: ```bash curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/tree/operations" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"operations": [ {"op": "mkdir", "path": "/archive/2026"}, {"op": "move", "from": "/notes/old.md", "to": "/archive/2026/old.md"}, {"op": "copy", "from": "/templates/report.md", "to": "/reports/2026-11.md"}, {"op": "delete", "path": "/drafts", "recursive": true} ]}' ``` TypeScript: ```ts // All or none, in order. copy returns the new Entries in copies. const done = await mirabase.tree.apply([ { op: "mkdir", path: "/archive/2026" }, { op: "move", from: "/notes/old.md", to: "/archive/2026/old.md" }, { op: "copy", from: "/templates/report.md", to: "/reports/2026-11.md" }, { op: "delete", path: "/drafts", recursive: true }, ]); // The shortcuts send one operation each. await mirabase.tree.move("/notes/draft.md", "/notes/final.md"); ``` Python: ```python # All or none, in order. copy returns the new Entries in copies. done = mb.tree.apply([ {"op": "mkdir", "path": "/archive/2026"}, {"op": "move", "from": "/notes/old.md", "to": "/archive/2026/old.md"}, {"op": "copy", "from": "/templates/report.md", "to": "/reports/2026-11.md"}, {"op": "delete", "path": "/drafts", "recursive": True}, ]) # The shortcuts send one operation each. mb.tree.move("/notes/draft.md", "/notes/final.md") ``` - `to` in a `move` or `copy` is the complete new path. When the target is occupied, the call returns 409 `path_conflict` and nothing is overwritten or merged. - Keep the response's `delete_batch_id`: it restores everything that request deleted. - Each copied file is a new Entry, listed in the response's `copies`. Its history is not copied, and it is processed like a new file. - A subtree over the synchronous limit returns 409 `subtree_too_large`: run it as a job; see [Run large tree operations as jobs](https://mirabase.io/developers/files.md#jobs). ### Path rules Paths are absolute: they start with `/` and have no trailing `/`. Names compare by NFKC and case folding, so `/Docs` and `/docs` are one directory. The full rules for length and characters are in [DevPath](https://mirabase.io/developers/api/schemas.md#DevPath). `/.mirabase/` is reserved: writing there returns 403 `reserved_path`. The exception is `/.mirabase/skills//...`, which holds your skill files, and `context` reads their `SKILL.md`. `/.mirabase/memory/MEMORY.md` is a generated read-only view; see [Memory](https://mirabase.io/developers/memory.md#memory-md). On deployments with offline consolidation, so is `/.mirabase/memory/RECENT.md`; see [the index layout](https://mirabase.io/developers/memory.md#memory-index). ## Run large tree operations as jobs A single `move`, `copy`, recursive `delete`, or `restore` by `delete_batch_id` over the synchronous limit runs as a job when you send `Prefer: respond-async`, and returns 202 with `job_id` and `Location: /v2/jobs/{job_id}`. Follow the job as described in [API conventions](https://mirabase.io/developers/conventions.md#jobs). curl: ```bash # One operation over the synchronous limit runs as a job: 202 with job_id. curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/tree/operations" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Prefer: respond-async" \ -H "Content-Type: application/json" \ -d '{"operations": [{"op": "delete", "path": "/old-exports", "recursive": true}]}' # Poll until status is succeeded or failed. curl "https://api.mirabase.dev/v2/jobs/$JOB_ID" \ -H "Authorization: Bearer $MIRABASE_API_KEY" ``` TypeScript: ```ts // Under the limit it runs right away; over it, the result is a JobReceipt. const started = await mirabase.tree.start({ op: "delete", path: "/old-exports", recursive: true }); if ("job_id" in started) { let job = await mirabase.jobs.get(started.job_id); while (job.status === "queued" || job.status === "running") { await new Promise((resolve) => setTimeout(resolve, 2000)); job = await mirabase.jobs.get(started.job_id); } // A failed delete keeps what it did: restore it with job.result?.delete_batch_id. } ``` Python: ```python # Under the limit it runs right away; over it, the result is a JobReceipt. started = mb.tree.start({"op": "delete", "path": "/old-exports", "recursive": True}) if "job_id" in started: # Polls until status is succeeded, failed, or cancelled. job = mb.jobs.wait(started["job_id"]) # A failed delete keeps what it did: restore it with job["result"]["delete_batch_id"]. ``` > **Warning:** A job `move` is one transaction, but `delete`, `restore`, and `copy` run in chunks and are not atomic: a failed delete job leaves a partly deleted tree, and `result.delete_batch_id` restores it. ## Write in a batch [`POST /v2/spaces/{space_id}/files/batch`](https://mirabase.io/developers/api/files.md#files-batch) writes and deletes several small text files in one request. Each item commits on its own, and one failing does not stop the rest; each result has its own `status` and matches its item by position. ```bash curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files/batch" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Idempotency-Key: import-2026-11-06" \ -H "Content-Type: application/json" \ -d '{"items": [ {"op": "put", "path": "/notes/a.md", "content": "First note", "media_type": "text/markdown"}, {"op": "delete", "path": "/notes/old.md"} ]}' ``` Sending the same `Idempotency-Key` again finishes a batch that was cut short: committed items replay and the rest run. A single `DELETE` returns 404 the second time, so use this endpoint when a retry must tell "done" from "never existed". ## Upload a large file Files over 16 MiB go through a multipart upload: start it, get part URLs, `PUT` each part, then complete it. The path is resolved on completion, and from there it behaves like `PUT`, including `If-Match` and `If-None-Match: *`. ```bash # 1. Start the upload. checksum_sha256 is the Base64 SHA-256 of the whole file. curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/uploads" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"path": "/videos/talk.mp4", "size": 734003200, "media_type": "video/mp4", "checksum_sha256": "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="}' # 2. Ask for part URLs, at most 128 at a time. Each one lasts five minutes. curl -X POST "https://api.mirabase.dev/v2/uploads/$UPLOAD_ID/parts" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"part_numbers": [1, 2, 3]}' # 3. PUT each part to its URL with the returned required_headers, and keep each ETag. # 4. Finish. The file appears at its path now. curl -X POST "https://api.mirabase.dev/v2/uploads/$UPLOAD_ID/complete" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"parts": [{"part_number": 1, "etag": "\"9b2c\""}, {"part_number": 2, "etag": "\"71fd\""}]}' ``` - After an interruption, call [`POST /v2/uploads/{upload_id}/parts`](https://mirabase.io/developers/api/uploads.md#uploads-parts) again: it leaves out the parts already received, so the upload resumes. - Part URLs and the upload session both expire, and after that you must start a new upload. The time limits are in the reference. ## Add a source without a path [`POST /v2/spaces/{space_id}/ingest`](https://mirabase.io/developers/api/ingest.md#ingest-ingest) adds a URL, text, or a conversation (see [Memory](https://mirabase.io/developers/memory.md#conversation)) and returns 202 with `entry_id`, `version_id`, and `job_id`. One call makes one Entry, and the same content twice makes two, so send `Idempotency-Key` when retrying. A URL is fetched after the response, so a bad one shows up as a failed job. ```bash curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/ingest" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Idempotency-Key: article-2026-11-06" \ -H "Content-Type: application/json" \ -d '{"kind": "url", "url": "https://example.com/article"}' ``` Text and conversations take [redact_secrets](https://mirabase.io/developers/api/schemas.md#DevIngestText.redact_secrets), which replaces whatever looks like a credential before anything is stored. It only recognizes credentials with a clear shape, so it is no substitute for your own scrubbing. Conversations also take [memory_instructions](https://mirabase.io/developers/api/schemas.md#DevIngestConversation.memory_instructions), which tells distillation what matters in your app. ## Compare and revert versions [`GET /v2/entries/{entry_id}/versions`](https://mirabase.io/developers/api/entries.md#entries-listversions) lists the chain, newest first. [`POST /v2/entries/{entry_id}/revert`](https://mirabase.io/developers/api/entries.md#entries-revert) writes an older version's content as a new version, without rewriting history. ```bash curl "https://api.mirabase.dev/v2/entries/$ENTRY_ID/versions" \ -H "Authorization: Bearer $MIRABASE_API_KEY" curl -X POST "https://api.mirabase.dev/v2/entries/$ENTRY_ID/revert" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"version_id": "ver_1a07"}' ``` [`GET /v2/entries/{entry_id}/diff?from=&to=`](https://mirabase.io/developers/api/entries.md#entries-diff) compares two versions, and [`GET /v2/entries/{entry_id}/lineage`](https://mirabase.io/developers/api/entries.md#entries-lineage) tells where the Entry came from and how each version came about. By path, use [`GET /v2/spaces/{space_id}/files/diff`](https://mirabase.io/developers/api/files.md#files-diff) and [`GET /v2/spaces/{space_id}/files/lineage`](https://mirabase.io/developers/api/files.md#files-lineage). curl: ```bash # Compare an older version with the latest. curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files/diff?path=/notes/hello.md&from=ver_1a07" \ -H "Authorization: Bearer $MIRABASE_API_KEY" # Where the file came from, and how each version came about. curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files/lineage?path=/notes/hello.md" \ -H "Authorization: Bearer $MIRABASE_API_KEY" ``` TypeScript: ```ts // An Entry by id, or by the path of its file. const diff = await mirabase.versions.diff({ path: "/notes/hello.md" }, "ver_1a07"); if (!diff.identical) console.log(diff.unified_diff ?? diff.diff_omitted); const lineage = await mirabase.versions.lineage({ path: "/notes/hello.md" }); console.log(lineage.origin.kind, lineage.data.map((version) => version.kind)); ``` Python: ```python # An Entry by id, or by the path of its file. The older version here is the quickstart's write. diff = mb.versions.diff({"path": "/notes/hello.md"}, written["version_id"]) if not diff["identical"]: print(diff.get("unified_diff") or diff.get("diff_omitted")) lineage = mb.versions.lineage({"path": "/notes/hello.md"}) print(lineage["origin"]["kind"], [version["kind"] for version in lineage["data"]]) ``` An Agent editing a file can record which conversation the change came from: send [session_id](https://mirabase.io/developers/api/files.md#files-write.session_id) on `PUT` and `PATCH` writes on main, with the same value the conversation was ingested with. `lineage` shows it on that version, and [`GET /v2/entries?metadata={"session_id":"…"}`](https://mirabase.io/developers/api/entries.md#entries-list) finds the conversation later. > **Warning:** If processing a replaced file's new version fails for good, the path falls back to the last version that worked, and `changes` reports it, so a `200` does not promise the path keeps those bytes. The failed version stays in `versions` as `discarded`: read its bytes with `version` or bring it back with `revert`. Check `knowledge.state` when you need to know the new version took. ## Check processing status [`GET /v2/entries/{entry_id}/processing`](https://mirabase.io/developers/api/entries.md#entries-processing) and [`GET /v2/jobs/{job_id}`](https://mirabase.io/developers/api/jobs.md#jobs-read) report processing progress. [`POST /v2/entries/{entry_id}/reprocess`](https://mirabase.io/developers/api/entries.md#entries-reprocess) retries a failed version or processes the latest one again. To wait until a file is searchable or follow a bulk import, see [Processing status](https://mirabase.io/developers/processing.md). ## Delete and erase | Operation | Effect | Requires | Undo | | --- | --- | --- | --- | | `DELETE` a file or Entry | Moves to the trash and leaves search at once | `knowledge:write` and editor | Yes, with `restore` | | [`POST /v2/entries/{entry_id}/purge`](https://mirabase.io/developers/api/entries.md#entries-purge) | Erases the Entry, every version, and its path | `knowledge:manage` and the Space owner | No | > **Note:** Erasure is not charged against quota, so it still works when the quota is used up. ## Handle Agent proposals When an Agent changes a file it does not own, the call returns 403 `proposal_required` by default, and nothing is created. It can write directly once the Space owner sets its `write_mode` to `direct`; see [Permissions](https://mirabase.io/developers/permissions.md#write-mode). Otherwise, the Agent can send `Prefer: handling=proposal` to turn the write into a proposal: the file stays as it is, the call returns 202 with `proposal_id`, and a reviewer decides. File `PUT` and `PATCH`, `files/batch`, the completion of a multipart upload, and branch merges all take this header. curl: ```bash # As the Agent: propose instead of failing with 403 proposal_required. curl -X PUT "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files?path=/notes/plan.md" \ -H "Authorization: Bearer $AGENT_KEY" \ -H "Prefer: handling=proposal" \ -H "Content-Type: text/markdown" \ --data-binary @plan.md # As a reviewer: open proposals, what each one changes, then decide. curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/proposals" \ -H "Authorization: Bearer $MIRABASE_API_KEY" curl "https://api.mirabase.dev/v2/proposals/$PROPOSAL_ID/diff" \ -H "Authorization: Bearer $MIRABASE_API_KEY" curl -X POST "https://api.mirabase.dev/v2/proposals/$PROPOSAL_ID/approve" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"message": "Agreed plan"}' ``` TypeScript: ```ts // As the Agent. On its own files and new files this is an ordinary write. const agent = new Mirabase({ apiKey: process.env.AGENT_KEY }); const submitted = await agent.proposals.submit("/notes/plan.md", nextPlan, { contentType: "text/markdown" }); if ("proposal_id" in submitted) { // Poll until a reviewer acts: status leaves "open". const proposal = await agent.proposals.get(submitted.proposal_id); } // As a reviewer. for await (const proposal of mirabase.proposals.list()) { const change = await mirabase.proposals.diff(proposal.id); if (change.unified_diff?.includes("Thursday")) { await mirabase.proposals.approve(proposal.id, { message: "Agreed plan" }); } else { await mirabase.proposals.reject(proposal.id); } } ``` Python: ```python import os # As the Agent. On its own files and new files this is an ordinary write. agent = Mirabase(api_key=os.environ["AGENT_KEY"]) submitted = agent.proposals.submit( "/notes/plan.md", "Releases move to Thursday.", content_type="text/markdown", ) if "proposal_id" in submitted: # Poll until a reviewer acts: status leaves "open". proposal = agent.proposals.get(submitted["proposal_id"]) # As a reviewer. for proposal in mb.proposals.list(): change = mb.proposals.diff(proposal["id"]) if "Thursday" in change.get("unified_diff", ""): mb.proposals.approve(proposal["id"], message="Agreed plan") else: mb.proposals.reject(proposal["id"]) ``` - It only acts when the write would otherwise return 403: your own files and new files are written directly. - Moving, deleting, and restoring other people's files, `revert`, and memory writes cannot be proposed and still return 403. - Reviewers are the Space owner and editors who can change the file directly: people, and Agents in `direct` mode with the file inside their `write_root`. - A proposal is not a version: only its author and the Space owner see the proposed content in `versions`, and search never returns it. ## Next steps - [Sync, snapshots, and export](https://mirabase.io/developers/sync.md): keep up with changes to files. - [Retrieval and context](https://mirabase.io/developers/retrieval.md): search what you wrote. - [API conventions](https://mirabase.io/developers/conventions.md#conditional): the general rules for conditional requests and idempotency. --- # Processing status A file becomes searchable first, and memories are built afterwards: wait for a single file, track a bulk import, and check whether content is still being processed. After a write, the service extracts the text, indexes it, and publishes it to search, in that order. Once these three steps are done, the file can be found by meaning; relations, classification, summaries, and memories are produced afterwards and do not hold up search. Text of up to 64 KiB sent in the request body can be found by its words right after the write; see [Retrieval](https://mirabase.io/developers/retrieval.md#search). The stage of the latest version is in [stage](https://mirabase.io/developers/api/schemas.md#DevEntryProcessing.stage): once it is `enriching` or `ready`, search finds that version. ## Wait until a file is searchable [`GET /v2/entries/{entry_id}/processing`](https://mirabase.io/developers/api/entries.md#entries-processing) returns the `stage` and `progress` of the latest version, and, while it is queued, `queue` with the number of jobs ahead of it and the reason it is waiting. The SDKs' `entries.waitUntil` (`entries.wait_until` in Python) polls this endpoint for you. By default, it waits until the file is searchable; with `until: "ready"`, it waits until all processing steps complete. curl: ```bash curl "https://api.mirabase.dev/v2/entries/$ENTRY_ID/processing" \ -H "Authorization: Bearer $MIRABASE_API_KEY" ``` TypeScript: ```ts // Returns once search finds the file ("enriching" or "ready"), or when it failed. const status = await mirabase.entries.waitUntil({ path: "/notes/launch.md" }, { onProgress: (s) => console.log(s.stage, `${s.progress.done}/${s.progress.total}`), }); if (status.stage === "failed") console.log(status.error?.code); ``` Python: ```python # Returns once search finds the file ("enriching" or "ready"), or when it failed. status = mb.entries.wait_until( {"path": "/notes/launch.md"}, on_progress=lambda s: print(s["stage"], f"{s['progress']['done']}/{s['progress']['total']}"), ) if status["stage"] == "failed": print(status["error"]["code"]) ``` - When processing fails, `waitUntil` returns the last status instead of throwing: check `error`. Retry a failed version with [`POST /v2/entries/{entry_id}/reprocess`](https://mirabase.io/developers/api/entries.md#entries-reprocess). - When the wait times out (10 minutes by default), the SDK throws an error with code `wait_timeout`; processing continues on the server. - For a single write, you can send `Prefer: wait` with the request instead; see [Write a file](https://mirabase.io/developers/files.md#write). ## Follow a bulk import For a bulk import, you do not need to poll every Entry individually. [`GET /v2/spaces/{space_id}/processing`](https://mirabase.io/developers/api/spaces.md#spaces-processing) counts the Entries in a Space by stage and returns the rate at which they become searchable and the estimated time remaining. The SDKs' `spaces.waitUntil` (`spaces.wait_until` in Python) polls this endpoint until every Entry in the Space is searchable; `onProgress` receives each status summary to update a progress display. curl: ```bash curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/processing" \ -H "Authorization: Bearer $MIRABASE_API_KEY" ``` TypeScript: ```ts // Waits until every Entry in the Space is searchable; failed Entries count as finished. const summary = await mirabase.spaces.waitUntil({ onProgress: ({ counts, eta_seconds }) => console.log(counts, eta_seconds), }); console.log(`${summary.counts.failed} failed`); ``` Python: ```python # Waits until every Entry in the Space is searchable; failed Entries count as finished. summary = mb.spaces.wait_until( on_progress=lambda s: print(s["counts"], s.get("eta_seconds")), ) print(summary["counts"]["failed"], "failed") ``` - Failed Entries are counted in `counts.failed`; check the cause with [`GET /v2/entries/{entry_id}/processing`](https://mirabase.io/developers/api/entries.md#entries-processing). - Memories are distilled separately after a file is searchable, and `memory` reports the distillations still queued or running. An Entry that waits only for distillation counts as searchable. To wait for memories as well, pass `until: "ready"`. - Work from different Spaces and accounts takes turns, so a large import in one Space does not hold up new files in another. ## Check for content still being processed When Entries in the searched Spaces are still being processed, the responses of `search`, `context`, and `answer` include `pending_processing`, where `entries` is the number of Entries that are not yet searchable. Their content may be missing from the results: if the content you need might be among them, query again shortly or wait for processing to finish first. ```json { "pack_id": "pck_...", "items": [ "..." ], "pending_processing": { "entries": 12 } } ``` The SDKs' `context` and `answer` return this field as is; `search` returns the array of hits and carries the field as the array's `pendingProcessing` property (`pending_processing` in Python). The results of the MCP tool `mira.search` also include `pending_processing`. ## When the processing queue is full When the number of queued jobs for an account exceeds its limit, writes return 429 `ingest_backlog`: `queue` gives the number of queued jobs and the estimated wait time, and `Retry-After` is 30 to 600 seconds. Wait for `Retry-After` before retrying. The SDKs wait and retry automatically only when `Retry-After` is no longer than `maxRetryAfterMs` (`max_retry_after` in Python, 60 seconds by default); above that they throw `MirabaseRateLimitError`, so read `retryAfterSeconds` (`retry_after_seconds` in Python) and wait yourself, or raise the option (see [Retries and idempotency](https://mirabase.io/developers/sdks.md#retries)). An account admin can inspect the queue at any time with [`GET /v2/queue`](https://mirabase.io/developers/api/usage.md#usage-queue). ## Next steps - [Files and versions](https://mirabase.io/developers/files.md): write, read, and edit files. - [Retrieval and context](https://mirabase.io/developers/retrieval.md): retrieve from what has been processed. - [API reference](https://mirabase.io/developers/api/spaces.md#spaces-processing): all fields of the processing status response. --- # Sync, snapshots, and export Mirror a Space with the tree, the change feed, and webhooks, pin a moment with snapshots, and move a whole Space with export and import. Sync uses two endpoints: [`GET /v2/spaces/{space_id}/tree`](https://mirabase.io/developers/api/tree.md#tree-list) for the state at one moment, and [`GET /v2/spaces/{space_id}/changes`](https://mirabase.io/developers/api/changes.md#changes-list) for what happened after it. ## Run the sync loop 1. Read `tree` and keep the `changes_cursor` from the **first page**. Paging is not one snapshot, and the first page's cursor covers writes made while you page. 2. Pass the cursor to `changes` and apply the events. 3. Continue with the response's `cursor`. When `has_more` is `true`, call again right away; otherwise, long-poll with `wait`. curl: ```bash # First page of the tree. Keep its changes_cursor. curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/tree?recursive=true" \ -H "Authorization: Bearer $MIRABASE_API_KEY" # Then follow the feed, waiting up to 30 seconds when nothing has changed. curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/changes?cursor=$CURSOR&wait=30" \ -H "Authorization: Bearer $MIRABASE_API_KEY" ``` TypeScript: ```ts // Every page of the tree, plus the first page's changes_cursor. const { nodes, changesCursor } = await mirabase.tree.snapshot("/", { recursive: true }); for (const node of nodes) mirror(node); // Long-polls, follows has_more, and reconnects after failures it can retry. for await (const change of mirabase.changes.watch({ cursor: changesCursor })) apply(change); ``` Python: ```python # Every page of the tree, plus the first page's changes_cursor. nodes, cursor = mb.tree.snapshot(recursive=True) for node in nodes: print(node["path"]) # Long-polls, follows has_more, and reconnects after failures it can retry. for change in mb.changes.watch(cursor=cursor): print(change["op"], change.get("path")) ``` - Without `cursor` the feed starts from now, so read `tree` first for a full sync. - An expired cursor returns 410 `cursor_expired`: read `tree` again and continue from the new `changes_cursor`. How long events are kept and the limits on long polling are in the reference. ## Events Each event's `op` is `create`, `update`, `move`, `delete`, or `restore`; what each means is in [DevChangeOp](https://mirabase.io/developers/api/schemas.md#DevChangeOp). ## Apply events - Events can repeat, including what `tree` already showed, so apply them idempotently by `entry_id`. - `move` carries only the new path, so keep your own map from `entry_id` to path, starting from `tree`. - Directories produce no events of their own, so use `tree` to see empty directories appear or go. - An Agent's private memory is not in the feed. - With `branch` you get the branch's own feed, with a different shape and rules. See [Branches and mounts](https://mirabase.io/developers/branches.md#reads). ## See recent changes When several people or Agents share a Space, call [`GET /v2/spaces/{space_id}/activity`](https://mirabase.io/developers/api/changes.md#changes-activity) before starting work: it is the change feed of the last few days already summed up per principal and per Entry, so you do not have to read `changes` from the start and fold it yourself. ## Receive webhooks Instead of polling `changes`, subscribe to main's changes with [`POST /v2/spaces/{space_id}/webhooks`](https://mirabase.io/developers/api/webhooks.md#webhooks-create). Mirabase delivers batches of events in order, one batch in flight at a time, at least once; the request body is described in [DevWebhookPayload](https://mirabase.io/developers/api/schemas.md#DevWebhookPayload). curl: ```bash curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/webhooks" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"url": "https://hooks.example.com/mirabase", "ops": ["create", "update", "delete"]}' ``` TypeScript: ```ts const webhook = await mirabase.webhooks.create({ url: "https://hooks.example.com/mirabase", ops: ["create", "update", "delete"], }); // Store webhook.secret now: it is in this response only. for await (const delivery of mirabase.webhooks.deliveries(webhook.id)) console.log(delivery.attempt, delivery.outcome); ``` Python: ```python webhook = mb.webhooks.create({ "url": "https://hooks.example.com/mirabase", "ops": ["create", "update", "delete"], }) # Store webhook["secret"] now: it is in this response only. for delivery in mb.webhooks.deliveries(webhook["id"]): print(delivery["attempt"], delivery["outcome"]) ``` TypeScript: ```ts import { parseWebhook } from "@mirabase/sdk/developer"; // Verify against the raw body, before parsing JSON. Throws on a bad or stale signature. const payload = await parseWebhook({ secret: process.env.MIRABASE_WEBHOOK_SECRET!, header: request.headers.get("Mirabase-Signature"), body: await request.text(), }); // Dedupe on payload.delivery_id: a retry resends the same batch. for (const change of payload.events) apply(change); ``` Python: ```python import os from mirabase import parse_webhook def receive(header: str | None, body: bytes) -> None: """header is the Mirabase-Signature header, body the raw request body.""" # Verify against the raw body, before parsing JSON. Raises ValueError on a bad or stale signature. payload = parse_webhook(secret=os.environ["MIRABASE_WEBHOOK_SECRET"], header=header, body=body) # Dedupe on payload["delivery_id"]: a retry resends the same batch. for change in payload["events"]: print(change["op"], change.get("path")) ``` - Verify the signature of every request as in the example above; the signature format and the timestamp tolerance are in [DevWebhook](https://mirabase.io/developers/api/schemas.md#DevWebhook). - Dedupe on `Mirabase-Delivery-Id`, the same as `delivery_id`: a retry resends the same batch. Apply events by `entry_id`. - Return 2xx quickly and do slow work after you respond. What counts as a failure, and how retries are spaced, are in [DevWebhook](https://mirabase.io/developers/api/schemas.md#DevWebhook). - The secret is in the create response only. If you lose it, call [`POST /v2/webhooks/{webhook_id}/rotate-secret`](https://mirabase.io/developers/api/webhooks.md#webhooks-rotatesecret). When deliveries stop, `status` becomes `disabled` and [disabled_reason](https://mirabase.io/developers/api/schemas.md#DevWebhook.disabled_reason) says why. [`PATCH /v2/webhooks/{webhook_id}`](https://mirabase.io/developers/api/webhooks.md#webhooks-update) with `{status: "active"}` reopens the webhook, and [`GET /v2/webhooks/{webhook_id}/deliveries`](https://mirabase.io/developers/api/webhooks.md#webhooks-deliveries) lists the delivery attempts. ## Take a snapshot [`POST /v2/spaces/{space_id}/snapshots`](https://mirabase.io/developers/api/snapshots.md#snapshots-create) records every file's path and version at this moment. Versions are immutable, so a snapshot copies no bytes. curl: ```bash curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/snapshots" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name": "before-import"}' # Read a file as the snapshot pinned it, by name or id. curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files?path=/notes/hello.md&snapshot=before-import" \ -H "Authorization: Bearer $MIRABASE_API_KEY" ``` TypeScript: ```ts const snapshot = await mirabase.snapshots.create("before-import"); const then = await mirabase.files.readText("/notes/hello.md", { snapshot: "before-import" }); for await (const node of mirabase.tree("/", { recursive: true, snapshot: snapshot.id })) console.log(node.path); // Everything written after the snapshot, with no gap and no overlap. for await (const change of mirabase.changes.watch({ cursor: snapshot.changes_cursor })) apply(change); ``` Python: ```python snapshot = mb.snapshots.create("before-import") # Read a file as the snapshot pinned it, by name or id. then = mb.files.read("/notes/hello.md", snapshot="before-import").text() for node in mb.tree("/", recursive=True, snapshot=snapshot["id"]): print(node["path"]) # Everything written after the snapshot, with no gap and no overlap. for change in mb.changes.watch(cursor=snapshot["changes_cursor"]): print(change["op"], change.get("path")) ``` - Pass `snapshot=` to `tree`, `files`, and `files/content-url` to read the version the snapshot pinned, even after the file changed, moved, or went to the trash. - The snapshot's `changes_cursor` continues `changes` from the same moment, so a snapshot plus the feed is a full sync with no gap and no overlap. - A snapshot holds files with a path only: empty directories, memories, and ingested URLs and text are not in it. ## Export and import [`POST /v2/spaces/{space_id}/exports`](https://mirabase.io/developers/api/transfers.md#transfers-createexport) exports files as a tar archive, and [`POST /v2/spaces/{space_id}/imports`](https://mirabase.io/developers/api/transfers.md#transfers-createimport) imports a tar or gzip-compressed tar into a Space. Both run as jobs and return 202 with `job_id`; follow them as described in [API conventions](https://mirabase.io/developers/conventions.md#jobs). curl: ```bash # Export as a job, then follow it with GET /v2/jobs/$JOB_ID curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/exports" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"snapshot": "before-import"}' # Once it succeeded: a signed download, valid up to five minutes. curl "https://api.mirabase.dev/v2/jobs/$JOB_ID/content-url" \ -H "Authorization: Bearer $MIRABASE_API_KEY" # Import a tar that is already a file you can read, into another Space. curl -X POST "https://api.mirabase.dev/v2/spaces/$OTHER_SPACE_ID/imports" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"source_entry_id": "'$ARCHIVE_ENTRY_ID'", "path": "/", "on_conflict": "skip"}' ``` TypeScript: ```ts const exported = await mirabase.transfers.startExport({ snapshot: "before-import" }); // ...poll mirabase.jobs.get(exported.job_id) until it succeeded, then: const archive = await mirabase.transfers.archiveUrl(exported.job_id); // Put the archive somewhere as a file, then import it into another Space. const written = await mirabase.files.write("/imports/space.tar", await (await fetch(archive.url)).blob(), { space: otherSpaceId, contentType: "application/x-tar", }); const imported = await mirabase.transfers.startImport( { source_entry_id: written.entry.id, path: "/", on_conflict: "skip" }, { space: otherSpaceId }, ); ``` Python: ```python from urllib.request import urlopen exported = mb.transfers.start_export({"snapshot": "before-import"}) # Polls until status is succeeded, failed, or cancelled. mb.jobs.wait(exported["job_id"]) archive = mb.transfers.archive_url(exported["job_id"]) # Put the archive in another Space as a file, then import it there. other_space_id is that Space's id. uploaded = mb.files.write( "/imports/space.tar", urlopen(archive["url"]).read(), space=other_space_id, content_type="application/x-tar", ) imported = mb.transfers.start_import( {"source_entry_id": uploaded["entry"]["id"], "path": "/", "on_conflict": "skip"}, space=other_space_id, ) ``` ### Export - The file list is fixed when the job starts, so the archive is one moment of the Space, or the snapshot's with `snapshot`. - Only files are included: content without a path, memories, and version history are not in it. The archive format is in the reference. - When the job succeeds, get a download URL for the archive with [`GET /v2/jobs/{job_id}/content-url`](https://mirabase.io/developers/api/transfers.md#transfers-archiveurl). > **Warning:** An archive is kept for 7 days. Purging any file in the Space, or setting or changing the `read_root` of the member who started the export, makes the archive unavailable at once: export again. ### Import - Put the archive in any Space first with `PUT .../files` or `uploads`; `source_entry_id` is its Entry id. - An archive this API exported comes back at the same paths with the same media types, so export and import round-trip. Any other archive lands under `path`. - Each file is written like `PUT`, under the same path rules, write roots, `write_mode`, and quotas, and an import never becomes a proposal. - An import is not atomic: a member that cannot be written does not stop the job and counts in `result.failed`, and when a quota runs out the job stops and keeps what it has imported. > **Coming soon** > > Forking a Space ([`POST /v2/spaces/{space_id}/forks`](https://mirabase.io/developers/api/transfers.md#transfers-createfork)) is coming soon. Until then, take a snapshot, export it with `snapshot`, create a Space, and import the archive there. ## Next steps - [Branches and mounts](https://mirabase.io/developers/branches.md): give an Agent a workspace it can throw away. - [API conventions](https://mirabase.io/developers/conventions.md#jobs): follow jobs such as exports and imports. - [Error codes](https://mirabase.io/developers/errors.md#codes): what to do about codes such as `cursor_expired`. --- # 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//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. --- # Memory Write, distill, review, correct, and forget memories, and consolidate them offline. ## The memory model `/v2/memories` returns three sources in one shape: account memories, memories written as Entries, and facts distilled from Entries. Only a memory written as an Entry has an Entry id as its `id`. A distilled fact leads back to its Entry and version through `provenance`. Every memory has a scope and a status: the scope says whose memory it is ([DevMemoryScope](https://mirabase.io/developers/api/schemas.md#DevMemoryScope)), and the status says whether retrieval uses it ([DevMemoryStatus](https://mirabase.io/developers/api/schemas.md#DevMemoryStatus)). Forgetting deletes for good and leaves no text to return, so there is no `forgotten` status. ## Write a memory Write a statement that stays true, such as a preference or a decision, with [`POST /v2/memories`](https://mirabase.io/developers/api/memories.md#memories-create). It is `confirmed` at once, and context and answers use it from then on. Submitting the same text again does not create a duplicate; see the reference for required permissions by scope. curl: ```bash curl -X POST https://api.mirabase.dev/v2/memories \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"scope": "project", "space_id": "'$SPACE_ID'", "kind": "decision", "text": "Releases go out on Thursdays."}' ``` TypeScript: ```ts const memory = await mirabase.memories.create({ scope: "project", space_id: spaceId, kind: "decision", text: "Releases go out on Thursdays.", }); ``` Python: ```python memory = mb.memories.create({ "scope": "project", "space_id": space_id, "kind": "decision", "text": "Releases go out on Thursdays.", }) ``` ## Distill memories from a conversation To propose rather than state, ingest a conversation: [`POST /v2/spaces/{space_id}/ingest`](https://mirabase.io/developers/api/ingest.md#ingest-ingest) with `kind: conversation`, `session_id`, and `messages` returns 202. One batch is one Entry, however many turns it has. Facts distilled from it are `confirmed` if you hold `memory:confirm` when you send it, otherwise `candidate`; the receipt's `memory_status` says which. curl: ```bash curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/ingest" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Idempotency-Key: chat-42-batch-1" \ -H "Content-Type: application/json" \ -d '{"kind": "conversation", "session_id": "chat-42", "messages": [ {"role": "user", "content": "Let us ship on Thursdays from now on.", "timestamp": 1762416000000}, {"role": "assistant", "content": "Noted: releases on Thursdays."} ]}' ``` TypeScript: ```ts const receipt = await mirabase.conversations.add( [ { role: "user", content: "Let us ship on Thursdays from now on.", timestamp: 1762416000000 }, { role: "assistant", content: "Noted: releases on Thursdays." }, ], { sessionId: "chat-42", idempotencyKey: "chat-42-batch-1" }, ); ``` Python: ```python receipt = mb.conversations.add( [ {"role": "user", "content": "Let us ship on Thursdays from now on.", "timestamp": 1762416000000}, {"role": "assistant", "content": "Noted: releases on Thursdays."}, ], session_id="chat-42", idempotency_key="chat-42-batch-1", ) ``` Distillation runs after indexing, so the processing job can be `succeeded` before any memory exists. Poll [`GET /v2/entries/{entry_id}/processing`](https://mirabase.io/developers/api/entries.md#entries-processing) until `memory.state` is no longer `pending`: at `ready`, [`GET /v2/memories?entry_id=`](https://mirabase.io/developers/api/memories.md#memories-list) lists what the batch wrote; `skipped` means this version is not distilled, for the reasons below; `failed` means distillation failed. curl: ```bash # Repeat until memory.state is no longer "pending". # "skipped" means the batch is not distilled: memory.reason says why. curl "https://api.mirabase.dev/v2/entries/$ENTRY_ID/processing" \ -H "Authorization: Bearer $MIRABASE_API_KEY" # Then list what the batch wrote. curl "https://api.mirabase.dev/v2/memories?entry_id=$ENTRY_ID" \ -H "Authorization: Bearer $MIRABASE_API_KEY" ``` TypeScript: ```ts let processing = await mirabase.entries.processing(receipt.entry_id); for (let attempt = 0; attempt < 30 && processing.memory?.state === "pending"; attempt += 1) { await new Promise((resolve) => setTimeout(resolve, 2000)); processing = await mirabase.entries.processing(receipt.entry_id); } if (processing.memory?.state === "skipped") { // Not distilled. reason says why, for example "model_not_configured"; // remediation.action, when present, says what to do. console.log(processing.memory.reason, processing.memory.remediation?.action); } else { for await (const memory of mirabase.memories.list({ entry: receipt.entry_id })) { console.log(memory.status, memory.text); } } ``` Python: ```python import time processing = mb.entries.processing(receipt["entry_id"]) for _ in range(30): if processing.get("memory", {}).get("state") != "pending": break time.sleep(2) processing = mb.entries.processing(receipt["entry_id"]) memory_state = processing.get("memory", {}) if memory_state.get("state") == "skipped": # Not distilled. reason says why, for example "model_not_configured"; # remediation["action"], when present, says what to do. print(memory_state.get("reason"), memory_state.get("remediation", {}).get("action")) else: for memory in mb.memories.list(entry=receipt["entry_id"]): print(memory["status"], memory["text"]) ``` - Ingesting the same batch twice makes two Entries, so send `Idempotency-Key` when retrying; see [Idempotency](https://mirabase.io/developers/conventions.md#idempotency). - To record a conversation as it goes, send each batch with the same `session_id`. The `session_id` is also stored as the metadata key `session_id`, so [`GET /v2/entries?metadata={"session_id":"…"}`](https://mirabase.io/developers/api/entries.md#entries-list) lists them together and `filter.metadata` in search narrows to that conversation. - When an Agent in `proposal` mode ingests a conversation, distilled facts are always `candidate`. ### Why distillation is skipped The `memory` object is the same in the ingest receipt, in the processing status, and in the job. When `state` is `skipped`, `reason` says why; when the reason is actionable, `remediation` comes with it, so act on its `remediation.action`: for example, when the deployment has no model for distillation, [write the memories directly](https://mirabase.io/developers/memory.md#create). When the deployment does not distill memories or the Entry has `memory_exclude`, the receipt is already `skipped` at write time, so there is nothing to poll. `distill_disabled`, `model_not_configured`, and `distill_paused` describe the deployment's setup and the account's usage, so only a key that belongs to a `tenant_admin` or holds `knowledge:manage`, and is not limited to Spaces or a metadata scope, sees them; other keys see `distill_unavailable` in place of the first two, and no reason in place of `distill_paused`: the state stays `pending`. A version distilled before the deployment stopped distilling stays `ready`. Every reason and its remediation are in [DevMemoryProcessingReason](https://mirabase.io/developers/api/schemas.md#DevMemoryProcessingReason) and [remediation](https://mirabase.io/developers/api/schemas.md#DevMemoryProcessing.remediation). ## Review, correct, and forget memories ```bash # Candidates waiting for review in one Space. curl "https://api.mirabase.dev/v2/memories?space_id=$SPACE_ID&status=candidate" \ -H "Authorization: Bearer $MIRABASE_API_KEY" # Confirm one, or send "reject". curl -X POST "https://api.mirabase.dev/v2/memories/$MEMORY_ID/review" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"decision": "confirm"}' # Replace it with what is true now. The response is a new memory whose supersedes names the old one. curl -X POST "https://api.mirabase.dev/v2/memories/$MEMORY_ID/correct" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"text": "Releases go out on Wednesdays."}' # Where it came from. curl "https://api.mirabase.dev/v2/memories/$MEMORY_ID/provenance" \ -H "Authorization: Bearer $MIRABASE_API_KEY" # Forget it for good. curl -X DELETE "https://api.mirabase.dev/v2/memories/$MEMORY_ID" \ -H "Authorization: Bearer $MIRABASE_API_KEY" ``` - A candidate waits for a person: confirm or reject it with [`POST /v2/memories/{memory_id}/review`](https://mirabase.io/developers/api/memories.md#memories-review). - When a memory is wrong, write the right statement with [`POST /v2/memories/{memory_id}/correct`](https://mirabase.io/developers/api/memories.md#memories-correct): the old memory is closed and kept as history. You can undo a new memory or correction within 30 minutes with [`POST /v2/memories/{memory_id}/undo`](https://mirabase.io/developers/api/memories.md#memories-undo). - [`DELETE /v2/memories/{memory_id}`](https://mirabase.io/developers/api/memories.md#memories-forget) forgets for good and cannot be undone. After a distilled fact is rejected or forgotten, the same sentence is not distilled again in that Space. - [`GET /v2/memories/{memory_id}/provenance`](https://mirabase.io/developers/api/memories.md#memories-provenance) lists the Entry versions a memory rests on, with the quoted words. - To keep a source from producing memories, set `memory_exclude: true` with [`PATCH /v2/entries/{entry_id}`](https://mirabase.io/developers/api/entries.md#entries-update): the facts distilled from it are retired, and search and reading are unaffected. Setting it back to `false` distills again, without what you forgot or corrected. ## MEMORY.md `/.mirabase/memory/MEMORY.md` is a generated, read-only view of this Space's memory for an Agent starting work. The same memories give the same bytes and the `ETag` is a content hash, which suits a prompt cache prefix. Read it with [`GET /v2/spaces/{space_id}/files`](https://mirabase.io/developers/api/files.md#files-read); it has raw bytes only, and a write returns 405 `virtual_file`. In the default layout, facts distilled from conversations are not in it: use [`GET /v2/memories`](https://mirabase.io/developers/api/memories.md#memories-list) or retrieval for those. Deployments with offline consolidation switch to an index layout and add `RECENT.md`; see [the index layout](https://mirabase.io/developers/memory.md#memory-index). ```bash # Send back the ETag you have. 304 means nothing changed. curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files?path=/.mirabase/memory/MEMORY.md" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H 'If-None-Match: ""' ``` ## Offline consolidation (dreams) While no Agent is working, the service tidies the memories that already exist. The API calls one such run a dream. A dream **only reorganizes and never generates**: it writes no new memory and changes no memory's text, and every action carries its evidence and can be undone. Merges and supersessions are only proposed: a model never changes a memory on its own, and nothing takes effect until a person approves it. > **Note:** Offline consolidation is optional per deployment. Where it is not enabled, the endpoints in this section and the next two return 404, `MEMORY.md` keeps the default layout above, and there is no `RECENT.md`. ### What it does - Checks quotes: it compares each distilled memory's verbatim quotes with the current version of its source Entry. When none of them are found anymore, the dream marks the memory dormant (`quote_missing`). - Finds unused memories: distilled memories that have not been served for a long time and that no person confirmed are only reported by default. With `apply`, the dream marks them dormant (`unused`), and serving them wakes them up. - Counts duplicates: it finds groups of memories that say the same thing and records the number and tokens of active memories before and after in the report (`view`). - Compares memories: once the Space owner turns `d4` on, it asks a model whether pairs of distilled memories repeat, supersede, or contradict each other. The conclusions only ever become [memory proposals](https://mirabase.io/developers/memory.md#memory-proposals). By default no model is called. - Runs automatically: it starts when a scope has new memories, or you can start one on demand. ### What it does not do - It generates nothing: no new memories, no changed text, no Entries, files, or versions, and nothing written outside `MEMORY.md` and `RECENT.md`. - The model changes nothing: it only says how two memories relate and quotes the sources verbatim. It writes no text that lands in memory and applies no change. There is no `auto` mode yet. - It leaves alone what a person decided: approved candidates and memories distilled from a conversation ingested with `memory:confirm` are never marked for missing quotes or for being unused, and memories written as Entries and account memories are never touched. Only distilled memories that took effect without review can go dormant; they too have `status: "confirmed"`. - It never brings back a forgotten memory, and undoing a dream does not either. - It stays in one scope, either a Space's project memory or one Agent's private memory: it never crosses scopes or Spaces, and never runs on branches. - It deletes nothing: the strongest thing a dream does on its own is mark a memory dormant, and a memory is closed only after a person approves a proposal, which can be undone too. Only your own forget and erase calls delete for good. ### Memory layers Different memories follow different rules: a rule that is rarely needed but important should not be set aside for being quiet, and events have an order and should not be merged as duplicates. The layer comes from a memory's `kind` and validity date and is worked out during a dream. A memory has no such field; proposals and judgments carry `layer`. Which memories each of the four layers holds, and which layers are compared and proposed on, are in [DevMemoryLayer](https://mirabase.io/developers/api/schemas.md#DevMemoryLayer); how long a memory stays unused before it goes dormant is in [DevMemoryDormancyReason](https://mirabase.io/developers/api/schemas.md#DevMemoryDormancyReason). A supersession stands only when the model's order agrees with the dates of the sources. Otherwise it becomes a `conflict`, shown to a person only. ### Dormancy and waking up A dormant memory carries `dormant: {reason, dream_id}`. It leaves `RECENT.md` and is not compared by the model, but it is still listed and searchable. `MEMORY.md` holds only what people wrote or confirmed, and none of that ever goes dormant. The conditions of the two reasons and what clears each are in [DevMemoryDormancyReason](https://mirabase.io/developers/api/schemas.md#DevMemoryDormancyReason). - Waking up takes no call of its own: reading it with [`GET /v2/memories/{memory_id}`](https://mirabase.io/developers/api/memories.md#memories-read), or having a search, context pack, or answer hand it back, wakes it up. Reading `MEMORY.md`, `RECENT.md`, or the list does not count. - Switching from `apply` back to `report` leaves existing marks; undo the dream to clear them. ### Settings: proposals by default Each Space has three settings: `memory_dreaming` (default `propose`, dreams run; `off` stops them), `dormancy` (default `report`, unused memories are only reported; `apply` marks them dormant), and `d4` (default `off`, no model is asked; `shadow` only records judgments; `propose` writes the judgments that pass validation as proposals). Under `propose`, dreams on their own only make undoable marks that change no text. Merging duplicates, letting a newer memory supersede an older one, flagging memories that contradict each other, or promoting an Agent's private memory to the project only ever become [memory proposals](https://mirabase.io/developers/memory.md#memory-proposals) for a person to decide. Only the Space owner can change the settings. curl: ```bash curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/memory/settings" \ -H "Authorization: Bearer $MIRABASE_API_KEY" # Stop dreams for this Space. What they already did stays; undo a dream to take it back. curl -X PATCH "https://api.mirabase.dev/v2/spaces/$SPACE_ID/memory/settings" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"memory_dreaming": "off"}' # Mark unused memories dormant, and let a model propose merges and supersessions. curl -X PATCH "https://api.mirabase.dev/v2/spaces/$SPACE_ID/memory/settings" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"dormancy": "apply", "d4": "propose"}' ``` TypeScript: ```ts const settings = await mirabase.memory.settings.get(); // settings.memory_dreaming is "propose" unless someone changed it. await mirabase.memory.settings.update("off"); // A field left out keeps its value. settings.d4_available says whether this deployment can ask a model. await mirabase.memory.settings.update({ dormancy: "apply", d4: "propose" }); ``` Python: ```python settings = mb.memory.settings.get() # settings["memory_dreaming"] is "propose" unless someone changed it. mb.memory.settings.update("off") # A field left out keeps its value. settings["d4_available"] says whether this deployment can ask a model. mb.memory.settings.update(dormancy="apply", d4="propose") ``` - Read a report before switching `dormancy` to `apply`. - Run `shadow` for a while and read the judgments before switching to `propose`: recorded judgments become proposals without asking the model again. - When `d4_available` in the response is false, this deployment asks no model, whatever `d4` says. ### Start, inspect, and undo a dream [`POST /v2/spaces/{space_id}/memory/dreams`](https://mirabase.io/developers/api/memory-dreaming.md#memorydreams-start) starts a dream now and returns 202; `job_id` is the dream id, followed with [`GET /v2/jobs/{job_id}`](https://mirabase.io/developers/api/jobs.md#jobs-read). [`GET /v2/memory/dreams/{dream_id}`](https://mirabase.io/developers/api/memory-dreaming.md#memorydreams-read) is its report, [`GET /v2/memory/dreams/{dream_id}/actions`](https://mirabase.io/developers/api/memory-dreaming.md#memorydreams-actions) lists each change and its reason, and [`GET /v2/memory/dreams/{dream_id}/judgments`](https://mirabase.io/developers/api/memory-dreaming.md#memorydreams-judgments) lists every pair a model compared. [`POST /v2/memory/dreams/{dream_id}/undo`](https://mirabase.io/developers/api/memory-dreaming.md#memorydreams-undo) undoes the whole dream. A scope runs one dream at a time. curl: ```bash # Start one now. job_id is the dream id (drm_...). curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/memory/dreams" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"scope": "project"}' # Poll until status is succeeded or failed. curl "https://api.mirabase.dev/v2/jobs/$DREAM_ID" \ -H "Authorization: Bearer $MIRABASE_API_KEY" # The report, then every change with its reason. curl "https://api.mirabase.dev/v2/memory/dreams/$DREAM_ID" \ -H "Authorization: Bearer $MIRABASE_API_KEY" curl "https://api.mirabase.dev/v2/memory/dreams/$DREAM_ID/actions" \ -H "Authorization: Bearer $MIRABASE_API_KEY" # Every pair a model was asked about, proposed or not. curl "https://api.mirabase.dev/v2/memory/dreams/$DREAM_ID/judgments" \ -H "Authorization: Bearer $MIRABASE_API_KEY" # Take it back. curl -X POST "https://api.mirabase.dev/v2/memory/dreams/$DREAM_ID/undo" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{}' ``` TypeScript: ```ts const started = await mirabase.memory.dreams.start({ scope: "project" }); let job = await mirabase.jobs.get(started.job_id); while (job.status === "queued" || job.status === "running") { await new Promise((resolve) => setTimeout(resolve, 2000)); job = await mirabase.jobs.get(started.job_id); } const dream = await mirabase.memory.dreams.get(started.job_id); console.log(dream.counts.checked, dream.counts.dormant_marked, dream.view?.live_before, dream.view?.live_after); for await (const action of mirabase.memory.dreams.actions(dream.id)) { console.log(action.seq, action.memory_id, action.action, action.reason, action.state); } for await (const judgment of mirabase.memory.dreams.judgments(dream.id)) { console.log(judgment.outcome, judgment.kind, judgment.member_ids, judgment.evidence); } if (dream.undoable) await mirabase.memory.dreams.undo(dream.id); ``` Python: ```python started = mb.memory.dreams.start(scope="project") # Polls until status is succeeded, failed, or cancelled. mb.jobs.wait(started["job_id"]) dream = mb.memory.dreams.get(started["job_id"]) print(dream["counts"]["dormant_marked"], dream.get("view")) for action in mb.memory.dreams.actions(dream["id"]): print(action["seq"], action["memory_id"], action["action"], action["reason"], action["state"]) for judgment in mb.memory.dreams.judgments(dream["id"]): print(judgment["outcome"], judgment.get("kind"), judgment["member_ids"], judgment.get("evidence")) if dream["undoable"]: mb.memory.dreams.undo(dream["id"]) ``` - Undo covers the whole dream, action by action: dormant marks clear, its open proposals become `withdrawn`, and approved merges and supersessions are reversed. A memory that changed since is left alone and counts in `conflict_skipped`. - Reports and actions count only memories whose source you can see, and an `agent` dream is visible only to that Agent and the Space owner. ## Memory proposals A change a dream suggests but does not make is a memory proposal, which is not the same thing as a [file proposal](https://mirabase.io/developers/files.md#proposals). Its kinds are in [DevMemoryProposalKind](https://mirabase.io/developers/api/schemas.md#DevMemoryProposalKind) and its statuses in [DevMemoryProposalStatus](https://mirabase.io/developers/api/schemas.md#DevMemoryProposalStatus). You see it only when you can see the source of every member. > **Note:** A dream writes proposals only when the Space's `d4` setting is `propose` and this deployment has a model (`d4_available` is true). Otherwise the list is empty. ### Verbatim quotes Because a model writes no conclusion of its own, `proposed_text` is always absent for now. Everything to judge by is the sources' own words: each `evidence` item has `memory_id`, `entry_id`, `version_id`, and a verbatim `quote`, `times` holds the dates that decided which memory is newer, and `plan` says which memory stays (`keep`) and which memories close (`close`) if you approve. A quote must be found word for word in its memory's source, otherwise the whole judgment is discarded and never becomes a proposal. curl: ```bash # Open proposals of one dream, oldest first. curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/memory/proposals?dream_id=$DREAM_ID" \ -H "Authorization: Bearer $MIRABASE_API_KEY" # Read the exact version a quote came from. curl "https://api.mirabase.dev/v2/entries/$ENTRY_ID/content?view=text&version=$VERSION_ID" \ -H "Authorization: Bearer $MIRABASE_API_KEY" # Carry it out. It takes effect only now. curl -X POST "https://api.mirabase.dev/v2/memory/proposals/$PROPOSAL_ID/approve" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{}' # Or close it without changing any memory. curl -X POST "https://api.mirabase.dev/v2/memory/proposals/$OTHER_PROPOSAL_ID/reject" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{}' ``` TypeScript: ```ts for await (const proposal of mirabase.memory.proposals.list({ dreamId: dream.id })) { console.log(proposal.kind, proposal.layer, proposal.plan, proposal.times); for (const { entry_id, version_id, quote } of proposal.evidence ?? []) { // Read the exact version the quote came from, and show both to the person deciding. const source = await mirabase.entries.content(entry_id, { view: "text", version: version_id }); console.log(quote, source.text?.includes(quote)); } } // Once a person has decided. await mirabase.memory.proposals.approve(proposalId); await mirabase.memory.proposals.reject(otherProposalId); ``` Python: ```python proposals = mb.memory.proposals.list(dream_id=dream["id"]).to_list() for proposal in proposals: print(proposal["kind"], proposal.get("layer"), proposal.get("plan"), proposal.get("times")) for evidence in proposal.get("evidence", []): # Read the exact version the quote came from, and show both to the person deciding. source = mb.entries.content(evidence["entry_id"], view="text", version=evidence["version_id"]) print(evidence["quote"], evidence["quote"] in source.get("text", "")) # Once a person has decided: proposal_id is the one approved, other_proposal_id the one rejected. mb.memory.proposals.approve(proposal_id) mb.memory.proposals.reject(other_proposal_id) ``` ### Approve and reject [`POST /v2/memory/proposals/{proposal_id}/approve`](https://mirabase.io/developers/api/memory-dreaming.md#memoryproposals-approve) carries out a `merge` or `supersede`: the memories in `plan.close` are closed and `plan.keep` stays, its text unchanged. [`POST /v2/memory/proposals/{proposal_id}/reject`](https://mirabase.io/developers/api/memory-dreaming.md#memoryproposals-reject) closes the proposal without changing any memory. - A `conflict` or `promote` cannot be approved. Settle a conflict by [correcting or forgetting](https://mirabase.io/developers/memory.md#govern) one side, or reject it. - To undo an approval, [undo the dream](https://mirabase.io/developers/memory.md#dreams). Undo covers the whole dream, not one proposal. ### Find proposals from a memory On deployments with offline consolidation, [`GET /v2/memories`](https://mirabase.io/developers/api/memories.md#memories-list) and [`GET /v2/memories/{memory_id}`](https://mirabase.io/developers/api/memories.md#memories-read) carry `pending_proposals` when there are open proposals: the ids of those about this memory (or a member of its group), oldest first, limited to proposals you can see, and absent when there are none. It is all you need to flag a memory as awaiting a decision in your interface. curl: ```bash # pending_proposals is present only when there are open proposals you can see. curl "https://api.mirabase.dev/v2/memories/$MEMORY_ID" \ -H "Authorization: Bearer $MIRABASE_API_KEY" curl "https://api.mirabase.dev/v2/memory/proposals/$PROPOSAL_ID" \ -H "Authorization: Bearer $MIRABASE_API_KEY" ``` TypeScript: ```ts const memory = await mirabase.memories.get("distill:ent_7f20:fact_31"); for (const id of memory.pending_proposals ?? []) { const proposal = await mirabase.memory.proposals.get(id); console.log(proposal.kind, proposal.plan, proposal.evidence); } ``` Python: ```python memory = mb.memories.get("distill:ent_7f20:fact_31") for pending_id in memory.get("pending_proposals", []): proposal = mb.memory.proposals.get(pending_id) print(proposal["kind"], proposal.get("plan"), proposal.get("evidence")) ``` ## The MEMORY.md index and RECENT.md On deployments with offline consolidation, `MEMORY.md` is an index: sections for rules and preferences, decisions and progress, and facts, one memory per line ending in a reference such as `[m1]`, and a `References` table at the end that maps each reference to a memory id. It holds what people wrote (account memories and memories written as Entries) and distilled memories a person confirmed, none of which ever goes dormant, and memories that say the same sentence appear once. ```markdown # Memory ## Rules and preferences - Keep answers short and in English. [m1] ## Decisions and progress - Releases go out on Thursdays. [m2] ## Facts - The staging database runs PostgreSQL 16. [m3] ## References [m1]: mem_5d02 [m2]: ent_9a41 [m3]: distill:ent_7f20:fact_31 ``` - The whole file is at most 2,000 tokens, of which distilled memories take at most 800. Nothing is cut mid-sentence: what does not fit is left out whole and counted on a last line, `… N more: GET /v2/memories?space_id=...`. - There are no dates or times, and the order changes only with the content: what people wrote first, then distilled memories a person confirmed, ordered by how recent they are and id, never by how often they were served. So a search hit does not change the `ETag`, which starts with `mf2.`, and the file still suits a prompt cache prefix. `/.mirabase/memory/RECENT.md` is the second generated file: project and Agent memories written in this Space in the last 7 days, candidates included, newest first, at most 50 of them and 1,000 tokens. Each line names its kind and status, references look like `[r1]`, and the `ETag` starts with `rf1.`. Account memories and dormant ones are not in it. It is read and protected like `MEMORY.md`. ```markdown # Recent memory - (decision, confirmed) Releases go out on Thursdays. [r1] - (preference, candidate) Use metric units in reports. [r2] ## References [r1]: ent_9a41 [r2]: distill:ent_7f20:fact_44 ``` curl: ```bash # The stable part: send back the ETag you have, 304 means nothing changed. curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files?path=/.mirabase/memory/MEMORY.md" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H 'If-None-Match: "mf2."' # The part that moves: what was written in the last 7 days. curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files?path=/.mirabase/memory/RECENT.md" \ -H "Authorization: Bearer $MIRABASE_API_KEY" ``` TypeScript: ```ts const index = await mirabase.files.read("/.mirabase/memory/MEMORY.md"); const recent = await mirabase.files.read("/.mirabase/memory/RECENT.md"); // MEMORY.md first, as the cached prefix; RECENT.md later, where the prompt changes anyway. const prompt = [index.text(), recent.text()].join("\n"); ``` Python: ```python index = mb.files.read("/.mirabase/memory/MEMORY.md") recent = mb.files.read("/.mirabase/memory/RECENT.md") # MEMORY.md first, as the cached prefix; RECENT.md later, where the prompt changes anyway. prompt = index.text() + "\n" + recent.text() # Later, send back the ETag you have: None means nothing changed. newer = mb.files.read_if_changed("/.mirabase/memory/MEMORY.md", index.etag) ``` - Put `MEMORY.md` early in the prompt as the stable prefix, and `RECENT.md` later, where the prompt changes anyway. - Both files show only memories you can see, so two callers can get different bytes and `ETag`s. ## Read a memory by id The index holds one sentence and an id. For the details, call [`GET /v2/memories/{memory_id}`](https://mirabase.io/developers/api/memories.md#memories-read) with an id from `References`; for its source versions and quotes, call [`GET /v2/memories/{memory_id}/provenance`](https://mirabase.io/developers/api/memories.md#memories-provenance). curl: ```bash # An id from the References table. export MEMORY_ID="distill:ent_7f20:fact_31" curl "https://api.mirabase.dev/v2/memories/$MEMORY_ID" \ -H "Authorization: Bearer $MIRABASE_API_KEY" # The versions and quotes it rests on. curl "https://api.mirabase.dev/v2/memories/$MEMORY_ID/provenance" \ -H "Authorization: Bearer $MIRABASE_API_KEY" ``` TypeScript: ```ts const memory = await mirabase.memories.get("distill:ent_7f20:fact_31"); // memory.group_id and memory.sources when other memories say the same; memory.dormant when a dream set it aside. const provenance = await mirabase.memories.provenance(memory.id); ``` Python: ```python # An id from the References table. memory = mb.memories.get("distill:ent_7f20:fact_31") # memory["group_id"] and memory["sources"] when other memories say the same; memory["dormant"] when a dream set it aside. # The versions and quotes it rests on. provenance = mb.memories.provenance(memory["id"]) ``` An Agent working over MCP uses the tool `mira.memory.get`: give it `memory_id` and by default it returns `{memory, provenance}`; with `include_provenance: false` it returns the memory alone. It is in the tool list only on deployments with offline consolidation. ```json { "jsonrpc": "2.0", "id": 7, "method": "tools/call", "params": { "name": "mira.memory.get", "arguments": { "memory_id": "distill:ent_7f20:fact_31" } } } ``` On deployments with offline consolidation, distilled memories that say the same sentence are listed as one group, with `group_id` and `sources`; forget, correct, and review still take a single id. ## Next steps - [Retrieval and context](https://mirabase.io/developers/retrieval.md): how memory reaches context and answers. - [Connect an Agent](https://mirabase.io/developers/agents.md): an Agent reads and writes memory with MCP tools. - [Permissions](https://mirabase.io/developers/permissions.md): who may confirm, correct, and forget memories. --- # Connect an Agent (MCP) Connect Agents such as Claude Code and Codex to Mirabase over MCP: how to connect, protocol versions, the tools and their parameters, and the recommended call order. ## Connect an Agent The MCP endpoint is `https://api.mirabase.dev/mcp`, over Streamable HTTP, and the credential is an API key: `Authorization: Bearer mb_live_...`. Give the Agent a key of its own, on an `agent` principal, so it has its own permissions, memory, and audit identity. See [Permissions](https://mirabase.io/developers/permissions.md#principals). Claude Code: ```bash claude mcp add --transport http mirabase https://api.mirabase.dev/mcp \ --header "Authorization: Bearer $MIRABASE_API_KEY" ``` Codex: ```bash codex mcp add mirabase --url https://api.mirabase.dev/mcp \ --bearer-token-env-var MIRABASE_API_KEY ``` JSON: ```json { "mcpServers": { "mirabase": { "type": "http", "url": "https://api.mirabase.dev/mcp", "headers": { "Authorization": "Bearer mb_live_..." } } } } ``` - Any MCP client that speaks Streamable HTTP and can send a header can connect; follow the JSON form above. - `tools/list` shows only what this key can call: a read-only key does not see the write tools, and a key with a metadata scope sees only the tools a scope allows. See [Permission by metadata](https://mirabase.io/developers/authentication.md#metadata-scope). - The `instructions` of the handshake response say what each tool is for and when to call it. A client that supports the field passes it to the model. - Every tool has a `title` and `annotations` (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`). A client that supports these hints can allow the read-only tools without asking, and ask the user for confirmation before tools such as `mira.memory.forget` and `mira.files.delete`. ## Protocol versions The supported protocol versions, how `initialize` picks one, the `MCP-Protocol-Version` header, and what each version returns for arguments that do not match `inputSchema` are in the [API reference](https://mirabase.io/developers/api/mcp.md#mcp-rpc). The server name in the handshake response (`serverInfo.name`) is `mirabase-developer`. - `structuredContent` is the same object as the JSON in the `content` text. `outputSchema` lists only the fields that are always present; a result may contain additional fields. Which tools have an `outputSchema` is in [Tools](https://mirabase.io/developers/api/mcp.md#tools). - In the service information returned by [`GET /mcp`](https://mirabase.io/developers/api/mcp.md#mcp-handshake), `protocol_versions` lists the supported versions from newest to oldest. ## Tools Each tool makes `/v2` requests, so permissions, limits, and errors are the same as in the `/v2` API. Most tools make one request. `mira.memory.get` reads the sources as well by default, which makes two. | Tool | What it does | The request it makes | | --- | --- | --- | | `mira.whoami` | Who this key is and what it may do. Read it first when a call is refused | [`GET /v2/whoami`](https://mirabase.io/developers/api/identity.md#identity-whoami) | | `mira.context` | A token-budgeted pack for a task, with the reasons for each source | [`POST /v2/retrieval/context`](https://mirabase.io/developers/api/retrieval.md#retrieval-buildcontext) | | `mira.search` | Search the scope you choose and get ranked passages with citations | [`POST /v2/retrieval/search`](https://mirabase.io/developers/api/retrieval.md#retrieval-search) | | `mira.answer` | Answer a question from what is stored, with citations | [`POST /v2/retrieval/answer`](https://mirabase.io/developers/api/retrieval.md#retrieval-answer) | | `mira.context.feedback` | Report which items of a pack were used | [`POST /v2/retrieval/context/{pack_id}/feedback`](https://mirabase.io/developers/api/retrieval.md#retrieval-contextfeedback) | | `mira.files.list` | List a directory | [`GET /v2/spaces/{space_id}/tree`](https://mirabase.io/developers/api/tree.md#tree-list) | | `mira.files.read` | Read a file by path; text comes in windows | [`GET /v2/spaces/{space_id}/files`](https://mirabase.io/developers/api/files.md#files-read) | | `mira.entries.read` | Read an Entry's content by id, including content that has no path | [`GET /v2/entries/{entry_id}/content`](https://mirabase.io/developers/api/entries.md#entries-content) | | `mira.files.write` | Create or replace a file | [`PUT /v2/spaces/{space_id}/files`](https://mirabase.io/developers/api/files.md#files-write) | | `mira.files.edit` | Replace exact text in a file | [`PATCH /v2/spaces/{space_id}/files`](https://mirabase.io/developers/api/files.md#files-patch) | | `mira.files.delete` | Move a file to the trash | [`DELETE /v2/spaces/{space_id}/files`](https://mirabase.io/developers/api/files.md#files-delete) | | `mira.trash.list` | List the Entries in a Space's trash | [`GET /v2/entries`](https://mirabase.io/developers/api/entries.md#entries-list) | | `mira.trash.restore` | Restore one trashed Entry to the path it had | [`POST /v2/entries/{entry_id}/restore`](https://mirabase.io/developers/api/entries.md#entries-restore) | | `mira.activity` | Who changed what lately, per principal and per file | [`GET /v2/spaces/{space_id}/activity`](https://mirabase.io/developers/api/changes.md#changes-activity) | | `mira.conversation.ingest` | Save a stretch of conversation for the service to distill memories from | [`POST /v2/spaces/{space_id}/ingest`](https://mirabase.io/developers/api/ingest.md#ingest-ingest) | | `mira.text.ingest` | Store a text as one Entry without a path | [`POST /v2/spaces/{space_id}/ingest`](https://mirabase.io/developers/api/ingest.md#ingest-ingest) | | `mira.url.ingest` | Fetch a public web page and store its readable text as one Entry | [`POST /v2/spaces/{space_id}/ingest`](https://mirabase.io/developers/api/ingest.md#ingest-ingest) | | `mira.memory.remember` | Write one memory as a statement | [`POST /v2/memories`](https://mirabase.io/developers/api/memories.md#memories-create) | | `mira.memory.list` | List memories, filtered by scope, status, kind, or literal text | [`GET /v2/memories`](https://mirabase.io/developers/api/memories.md#memories-list) | | `mira.memory.forget` | Forget a memory by id | [`DELETE /v2/memories/{memory_id}`](https://mirabase.io/developers/api/memories.md#memories-forget) | | `mira.memory.correct` | Replace a memory with a corrected statement | [`POST /v2/memories/{memory_id}/correct`](https://mirabase.io/developers/api/memories.md#memories-correct) | | `mira.memory.review` | Confirm or reject a memory waiting for review | [`POST /v2/memories/{memory_id}/review`](https://mirabase.io/developers/api/memories.md#memories-review) | | `mira.memory.get` | Read one memory by id, with its sources. Only on deployments with offline consolidation enabled | [`GET /v2/memories/{memory_id}`](https://mirabase.io/developers/api/memories.md#memories-read) | - When the `/v2` request fails, the tool call returns a result with `isError: true`: its `content` text gives the code, whether to retry, and the next step, and `_meta["dev.mirabase/error"]` carries the whole error envelope, including `code` and `remediation.action`; see [Errors](https://mirabase.io/developers/conventions.md#errors). A failed result has no `structuredContent`. The same applies when a key lacks the capability a tool needs: the code is `forbidden`. What a call with arguments that do not match the tool's definition returns depends on the protocol version; see the [API reference](https://mirabase.io/developers/api/mcp.md#mcp-rpc). - A tool call counts against your rate limit as the `/mcp` call plus the `/v2` requests it makes, so usually two. - With `mira.memory.remember`, scope `agent` is the Agent's own private memory and needs an Agent key. ## Tool parameters A tool's parameters are the fields of `arguments` in `tools/call`. Every tool's parameters, with their types, ranges, and whether they are required, are in the [API reference](https://mirabase.io/developers/api/mcp.md#tools); the `inputSchema` that `tools/list` returns is the same definition. ## Recommended call order - Call `mira.context` at the start of a task: the service picks and budgets sources by fixed rules, and `route` explains each choice. Use `mira.search` when you already know what to look for. Afterwards, report what you used with `mira.context.feedback`. - Use `mira.answer` when the user wants the answer itself, and `mira.context` to gather material for your own reasoning. - In a Space you share with others, call `mira.activity` before you start, to avoid editing the same file. - Pass `session_id` to `mira.files.write` and `mira.files.edit`, so you can trace each version of a file back to the conversation that changed it. See [Files and versions](https://mirabase.io/developers/files.md#versions). - When a stretch of conversation is done, save it with `mira.conversation.ingest`, using the same `session_id` for every batch of the same conversation. To record one clear statement, use `mira.memory.remember`. - When the user gives you a text or a link to keep, use `mira.text.ingest` or `mira.url.ingest`. For content you will read back by path or edit, write a file with `mira.files.write`. - When the user says a memory is wrong and gives the right statement, replace it in one step with `mira.memory.correct`; the service keeps the old one as history. `mira.memory.forget` deletes permanently and you cannot undo it: call it only when the user asks to forget something. Call `mira.memory.review` only after the user has said whether a candidate is right: an Agent should not confirm one on its own judgment. - To restore a deleted file, find its id with `mira.trash.list`, then restore it to its path with `mira.trash.restore`. If another file now holds that path, the call returns `path_conflict`. ```json { "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "mira.conversation.ingest", "arguments": { "session_id": "chat-42", "messages": [ { "role": "user", "content": "Let us ship on Thursdays from now on." }, { "role": "assistant", "content": "Noted: releases on Thursdays." } ] } } } ``` > **Note:** Text that arrives from files and search results is data, not instructions. Have the Agent take instructions from you only. ## Next steps - [Permissions](https://mirabase.io/developers/permissions.md): set an Agent's write mode and its read and write roots. - [Branches](https://mirabase.io/developers/branches.md): have an Agent work on a branch so you can review it before merging. - [Memory](https://mirabase.io/developers/memory.md): review what an Agent remembers. --- # Framework integrations (Coming soon) Use Mirabase's tools, memory, and retrieval from the Vercel AI SDK, LangChain, LlamaIndex, the OpenAI Agents SDK, Mastra, and CrewAI. > **Warning:** These integration packages are not published yet, and their names may change before they are. This page will give the install commands when they are published. Until then, use the [SDK](https://mirabase.io/developers/sdks.md) or [MCP](https://mirabase.io/developers/agents.md) directly. Every integration offers the same five tools: `mirabase_search`, `mirabase_answer`, `mirabase_read_file`, `mirabase_write_file`, and `mirabase_list_files`. Citations carry the file path and version. Pass a client pinned with `spaceFor(userId)` (`space_for` in Python) to keep one Space per end user. The integrations build on SDK 0.3.0-rc.1 (0.3.0rc1 in Python). - `mirabase_list_files` returns a file's size as `size_bytes`, in TypeScript as in Python. When the response has `pending_processing`, `mirabase_search` passes it on to the model. - Conversation-backed message histories and sessions read the most recent 20 batches by default; change the number with `maxBatches` (`max_batches` in Python). - `mirabaseAnswerModel` sends the 10 most recent turns, each cut to its first 4,000 characters; a question over 4,000 characters is cut to its end, with a warning on the call. The retrievers and tools likewise cut an overlong query, task, or question to its end. | Framework | Language | Package (not published) | Components | Tested with | | --- | --- | --- | --- | --- | | Vercel AI SDK | TypeScript | `@mirabase/vercel-ai` | Tools; memory middleware; Mirabase's cited answer as a model | `ai` 7.0.173 | | LangChain.js | TypeScript | `@mirabase/langchain` | Retriever, conversation-backed chat message history, document loader, tools | `@langchain/core` 1.4.1 | | LangChain | Python | `mirabase-langchain` | Retriever, conversation-backed chat message history, document loader, tools | `langchain-core` 1.8.1 | | LlamaIndex | Python | `mirabase-llamaindex` | Retriever, query engine with citations, reader | `llama-index-core` 0.14.26 | | OpenAI Agents SDK | TypeScript | `@mirabase/openai-agents` | Tools, conversation-backed `Session` | `@openai/agents` 0.22.0 | | OpenAI Agents SDK | Python | `mirabase-openai-agents` | Tools, conversation-backed session | `openai-agents` 0.24.0 | | Mastra | TypeScript | `@mirabase/mastra` | Tools, memory processor | `@mastra/core` 1.83.0 | | CrewAI | Python | `mirabase-crewai` | Tools, Mirabase-backed `Knowledge` | `crewai` 1.15.41 | > **Note:** `model` in the examples stands for the model you use with that framework. ## Vercel AI SDK `mirabaseTools` provides the five tools. `mirabaseMemory` is model middleware: before a call, it builds context from the last user message; after the call, it stores the turn as a conversation from which the service distills memories. If you do not use your own model, `mirabaseAnswerModel` wraps Mirabase's cited answer as a model. ```ts import { Mirabase } from "@mirabase/sdk/developer"; import { mirabaseMemory, mirabaseTools } from "@mirabase/vercel-ai"; import { generateText, stepCountIs, wrapLanguageModel } from "ai"; const mb = await new Mirabase().spaceFor("user-42"); // one Space per end user const { text } = await generateText({ model: wrapLanguageModel({ model, middleware: mirabaseMemory({ client: mb, sessionId: "chat-1" }) }), tools: mirabaseTools({ client: mb }), stopWhen: stepCountIs(5), prompt: "What did we decide about the launch?", }); ``` ## LangChain `MirabaseRetriever` returns cited documents whose `metadata` contains the file path, version, and citation id. `MirabaseChatMessageHistory` stores message history as a Mirabase conversation. A document loader and the five tools are also included. TypeScript: ```ts import { Mirabase } from "@mirabase/sdk/developer"; import { MirabaseChatMessageHistory, MirabaseRetriever } from "@mirabase/langchain"; const mb = new Mirabase(); const docs = await new MirabaseRetriever({ client: mb, k: 5 }).invoke("When do we ship?"); console.log(docs[0]?.metadata.path, docs[0]?.metadata.citation_id); const history = new MirabaseChatMessageHistory({ client: await mb.spaceFor("user-42"), sessionId: "chat-1" }); ``` Python: ```python from mirabase import Mirabase from mirabase_langchain import MirabaseChatMessageHistory, MirabaseRetriever mb = Mirabase() docs = MirabaseRetriever(client=mb, k=5).invoke("When do we ship?") print(docs[0].metadata["path"], docs[0].metadata["citation_id"]) history = MirabaseChatMessageHistory(mb.space_for("user-42"), "chat-1") ``` ## LlamaIndex `MirabaseQueryEngine` answers through Mirabase's answer endpoint, with the cited passages as `source_nodes`, and needs no model of your own. `MirabaseRetriever` plugs into a LlamaIndex query engine when your own model writes the answer. ```python from mirabase import Mirabase from mirabase_llamaindex import MirabaseQueryEngine, MirabaseRetriever mb = Mirabase() response = MirabaseQueryEngine(client=mb).query("When do we ship?") print(response, [n.node.metadata["path"] for n in response.source_nodes]) nodes = MirabaseRetriever(mb, similarity_top_k=5).retrieve("launch owner") ``` ## OpenAI Agents SDK `mirabaseTools` (`mirabase_tools` in Python) gives the five tools with strict schemas. `MirabaseSession` stores each turn as a Mirabase conversation. TypeScript: ```ts import { Agent, run } from "@openai/agents"; import { Mirabase } from "@mirabase/sdk/developer"; import { MirabaseSession, mirabaseTools } from "@mirabase/openai-agents"; const mb = await new Mirabase().spaceFor("user-42"); const assistant = new Agent({ name: "Assistant", instructions: "Answer from the user's files.", tools: mirabaseTools({ client: mb }) }); const session = new MirabaseSession({ client: mb, sessionId: "chat-1" }); const result = await run(assistant, "What did we decide about the launch?", { session }); ``` Python: ```python from agents import Agent, Runner from mirabase import Mirabase from mirabase_openai_agents import MirabaseSession, mirabase_tools mb = Mirabase().space_for("user-42") assistant = Agent(name="Assistant", instructions="Answer from the user's files.", tools=mirabase_tools(mb)) result = Runner.run_sync(assistant, "What did we decide?", session=MirabaseSession(mb, "chat-1")) ``` ## Mastra `mirabaseMemory` is a processor: on input it adds the context Mirabase builds, and on output it stores the turn as a conversation. It works alongside Mastra's own thread memory. ```ts import { Agent } from "@mastra/core/agent"; import { Mirabase } from "@mirabase/sdk/developer"; import { mirabaseMemory, mirabaseTools } from "@mirabase/mastra"; const mb = await new Mirabase().spaceFor("user-42"); const memory = mirabaseMemory({ client: mb, sessionId: "chat-1" }); const assistant = new Agent({ id: "assistant", name: "Assistant", instructions: "Be brief.", model, tools: mirabaseTools({ client: mb }), inputProcessors: [memory], outputProcessors: [memory] }); const { text } = await assistant.generate("What should I cook tonight?"); ``` ## CrewAI `mirabase_knowledge` is a CrewAI `Knowledge` source backed by Mirabase search, requiring no local vector store or embedding model API key. `mirabase_tools` provides the five tools. ```python from crewai import Agent, Crew, Task from mirabase import Mirabase from mirabase_crewai import mirabase_knowledge, mirabase_tools mb = Mirabase() planner = Agent( role="Planner", goal="Answer from the team's notes", backstory="Knows the release plan.", tools=mirabase_tools(mb, read_only=True), knowledge=mirabase_knowledge(mb, path="/notes"), ) task = Task(description="When do we ship, and who owns it?", expected_output="A day and a name", agent=planner) print(Crew(agents=[planner], tasks=[task]).kickoff()) ``` ## Next steps - [SDK](https://mirabase.io/developers/sdks.md): the client the integrations build on. - [Connect an Agent (MCP)](https://mirabase.io/developers/agents.md): reach the same tools over MCP without a framework. - [Retrieval and context](https://mirabase.io/developers/retrieval.md): the retrieval endpoints the integrations call. --- # Branches and mounts Copy-on-write workspaces for Agents, FUSE mounts, a sync command, and Git workspaces. ## Use a branch A branch is a copy-on-write layer over a Space's main line, and serves as an Agent's workspace. Content on a branch is **not parsed, indexed, or distilled**. It goes through normal processing only when merged, so a failed experiment leaves knowledge and memory untouched. ```bash # Open a branch. Keep its id (brn_...). curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/branches" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name": "try-new-outline"}' # Write to it. Main does not change. curl -X PUT "https://api.mirabase.dev/v2/spaces/$SPACE_ID/files?path=/notes/hello.md&branch=$BRANCH_ID" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: text/markdown" \ --data-binary @hello.md # See what changed. curl "https://api.mirabase.dev/v2/spaces/$SPACE_ID/branches/$BRANCH_ID/diff" \ -H "Authorization: Bearer $MIRABASE_API_KEY" # Merge into main. Idempotency-Key is required here. curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/branches/$BRANCH_ID/merge" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Idempotency-Key: merge-try-new-outline" \ -H "Content-Type: application/json" \ -d '{"message": "New outline", "on_conflict": "abort"}' ``` [`POST /v2/spaces/{space_id}/branches`](https://mirabase.io/developers/api/branches.md#branches-create) opens a branch, [`GET /v2/spaces/{space_id}/branches/{branch_id}/diff`](https://mirabase.io/developers/api/branches.md#branches-diff) shows its path-level changes, [`POST /v2/spaces/{space_id}/branches/{branch_id}/merge`](https://mirabase.io/developers/api/branches.md#branches-merge) merges it into main, and [`DELETE /v2/spaces/{space_id}/branches/{branch_id}`](https://mirabase.io/developers/api/branches.md#branches-abandon) abandons it. - Use the branch id, which starts with `brn_`, rather than its name in anything that retries: once a branch closes, its name can move to another one. - Opening a branch needs only write access to the Space. `write_mode` is checked at merge, so an Agent in `proposal` mode can experiment freely. - A member with a `read_root` in the Space cannot use branches. See [Permissions](https://mirabase.io/developers/permissions.md#roots). ## Read and write on a branch `files`, `files/batch`, `tree`, `tree/operations`, `uploads`, and `changes` take an optional `branch` parameter. Without it, they act on main. - A branch read checks the overlay, then falls through to the latest on main. A path the branch has not touched shows main as it is now, not as it was when the branch opened. - A write to a branch makes no version and counts no `writes` until a merge. The `etag` in its response is a content hash and goes back in `If-Match`. - `DELETE` on a branch hides the file on that branch only, and main is untouched. To undo changes on a branch, roll back to a checkpoint. - Symlinks and file modes (`symlink`, `chmod`, `mode`) work on a branch only: main has no symlinks. - `changes?branch=` is the branch's own feed, with cursors from `tree?branch=` that do not work on main. `source: branch` events keep only the latest write per path, so treat them as paths to re-read. - `search` and `context` do not take `branch`: branch content cannot be found until merged. ## Create checkpoints and roll back A checkpoint records the branch's own changes at one moment. Paths read through to main are not pinned. After a rollback, later checkpoints stay, so a rollback can be undone, and older `changes` cursors return 410: read `tree?branch=` again. ```bash curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/branches/$BRANCH_ID/checkpoints" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name": "before-refactor"}' curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/branches/$BRANCH_ID/rollback" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"checkpoint_id": "'$CHECKPOINT_ID'"}' ``` ## Merge a branch A merge requires `Idempotency-Key`. All paths apply or none do, and each becomes a new version on main with `message`. - Each path is compared with the version main had when the branch first touched it; if main changed it since, that is a conflict. By default, the whole merge fails with 409 `merge_conflict`, and `error.conflicts` lists each conflict; `on_conflict` can keep main or overwrite it instead. There is no content merge. - With `paths` only those paths merge, and the branch stays `active`. Without it the branch ends `merged` and takes no more writes. - An Agent merging a file it does not own needs `write_mode: direct`. With `Prefer: handling=proposal` its changes to such files become proposals instead. See [Proposals](https://mirabase.io/developers/files.md#proposals). ## Merge as a job A merge over the synchronous limit runs as a job when it carries `Prefer: respond-async`, returning 202 with `job_id`. Follow it with [`GET /v2/jobs/{job_id}`](https://mirabase.io/developers/api/jobs.md#jobs-read); see [Jobs](https://mirabase.io/developers/conventions.md#jobs). curl: ```bash # Over 1000 paths: run the merge as a job instead of 409 merge_too_large. curl -X POST "https://api.mirabase.dev/v2/spaces/$SPACE_ID/branches/$BRANCH_ID/merge" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Idempotency-Key: merge-big-refactor" \ -H "Prefer: respond-async" \ -H "Content-Type: application/json" \ -d '{"message": "Big refactor", "on_conflict": "abort"}' ``` TypeScript: ```ts const merged = await mirabase.branches.startMerge(branchId, { message: "Big refactor", on_conflict: "abort" }); if ("job_id" in merged) { const job = await mirabase.jobs.get(merged.job_id); // job.result?.merged counts paths; a failed plan lists job.result?.conflicts. } ``` Python: ```python # branch_id is the branch to merge: the id mb.branches.create returned. merged = mb.branches.start_merge(branch_id, {"message": "Big refactor", "on_conflict": "abort"}) if "job_id" in merged: job = mb.jobs.get(merged["job_id"]) # job["result"]["merged"] counts paths; a failed plan lists job["result"]["conflicts"]. ``` - The job plans every path first: a conflict fails it before anything is written. - It then merges in batches and is not atomic. A conflict that appears midway stops it with the merged paths already gone from the branch: merge again for the rest. - While the job is queued or running, the branch takes no other merge and no file writes. Renaming, checkpoints, and abandoning still work, and abandoning stops the job. ## Expiry and reclaim Every write moves `expires_at` out by `ttl_days`, which you set on creation or with [`PATCH /v2/spaces/{space_id}/branches/{branch_id}`](https://mirabase.io/developers/api/branches.md#branches-update). A branch with no writes expires and becomes `abandoned`. After a branch is abandoned, expires, or merges, it is kept for `branch_reclaim_days` days and then reclaimed. Branch storage counts toward `storage_bytes`. For the defaults, see [Rate limits and quotas](https://mirabase.io/developers/conventions.md#rate-limits). ## Store branch objects [`PUT /v2/spaces/{space_id}/branches/{branch_id}/objects/{sha256}`](https://mirabase.io/developers/api/branches.md#branches-putobject) stores an opaque object under its hash, to hold Git bundles and overlays. Objects are not paths, do not appear in `tree` or `changes`, are not merged, parsed, or indexed, and count toward `storage_bytes`. On a merged or abandoned branch they stay readable until the branch is reclaimed. > **Warning:** What is in a branch's objects, Git bundles included, cannot be erased until the branch is reclaimed. `purge` acts on Entries on main only. To get rid of it sooner, abandon the branch and wait `branch_reclaim_days` days for reclaim. > **Coming soon** ## CLI and mounts (Coming soon) The `mirabase` CLI is a single binary with no runtime dependencies, which suits sandboxes, and it uses only the public API. It reads `MIRABASE_API_KEY` (required), `MIRABASE_API_URL`, and `MIRABASE_SPACE`. A mount writes to a branch rather than to main, because one editor save produces several writes and renames. > **Note:** The CLI is not released yet, so you cannot install the commands below today. Branches themselves are live, and you can call every endpoint in the sections above now. ```bash export MIRABASE_API_KEY="mb_live_..." # Stays in the foreground and prints the branch it opened. mirabase mount ./workspace --space "$SPACE_ID" # In another shell: grep -rn "TODO" ./workspace sed -i 's/one place/a single place/' ./workspace/notes/hello.md mirabase drain ./workspace mirabase branch diff "$BRANCH_ID" --space "$SPACE_ID" mirabase branch merge "$BRANCH_ID" --message "Wording" --space "$SPACE_ID" ``` | Command | Purpose | | --- | --- | | `mirabase mount --space s [--branch b] [--read-only]` | FUSE mount. Opens a branch unless `--branch` is given | | `mirabase sync --space s [--branch b] [--once]` | For sandboxes without FUSE: pulls, watches local changes, and pushes | | `mirabase drain [dir] [--timeout 5m] [--ack]` | Blocks until local writes are uploaded. Exit code 0 means all uploaded, 1 a write was given up or authentication failed, 2 a timeout, 3 another machine overwrote your write | | `mirabase branch ` | `create`, `list`, `get`, `rename`, `extend`, `diff`, `checkpoint`, `checkpoints`, `rollback`, `merge`, and `abandon` | | `mirabase git save\|restore\|worktree` | Git workspaces, see the next section | - Consistency is close-to-open: another machine sees new content on its next open. `fsync` only guarantees a local write, and `drain` is what makes it visible elsewhere. - When two machines write one path, the last write wins. - Rename, mkdir, unlink, truncate, the executable bit, and symlinks work. Hard links, device files, and file locks do not. - `.mirabase/memory/MEMORY.md` is read-only in a mount, and writing it returns `EROFS`. - `.git/`, `node_modules/`, `.venv/`, `__pycache__/`, and `.DS_Store` are not uploaded by default and stay local. Adjust this with `.mirabaseignore`, which uses gitignore syntax. - On Linux, a mount needs `/dev/fuse` (and `SYS_ADMIN` in a container); without them, use `mirabase sync`. On macOS, install macFUSE or FUSE-T first. ## Git workspaces (Coming soon) `mirabase git save` bundles commits, incrementally after the first save, stores uncommitted and untracked changes as an overlay, and creates a checkpoint whose `git` field records `HEAD`, the ref, and the remote URL without credentials. `mirabase git restore ` brings it back in a fresh environment and verifies `HEAD` and the working tree. `mirabase git worktree --ref r` restores it and opens another ref with `git worktree`. ```bash # In a Git repository: bundle commits, store uncommitted changes, create a checkpoint. # Without --branch it opens one and remembers it in .git/mirabase-branch. mirabase git save --space "$SPACE_ID" --name "before-upgrade" # Somewhere else: restore and verify HEAD and the working tree. mirabase git restore "$CHECKPOINT_ID" ./repo --space "$SPACE_ID" ``` - Bundles and overlays are stored as branch objects and are never sent to a model provider. - The staging area is not saved, so restored changes are all unstaged. - Files ignored by `.gitignore`, and `.env`, are not saved by default. Pass `--include-ignored` to include them. - Saved content cannot be erased until the branch is reclaimed. See [Branch objects](https://mirabase.io/developers/branches.md#objects). ## Next steps - [Sync, snapshots, and export](https://mirabase.io/developers/sync.md#snapshots): use a snapshot when all you need is a fixed point to read from. - [Permissions](https://mirabase.io/developers/permissions.md): who may merge, and when an Agent's change becomes a proposal. - [API conventions](https://mirabase.io/developers/conventions.md#idempotency): a merge requires an idempotency key. --- # Permissions How principals, capabilities, Space roles, read and write roots, and API key limits together decide a request. ## How a request is decided A request must satisfy all of these. Failing any one is a refusal: ```text allowed = capability in (principal.capabilities ∩ key.capabilities) and space in key.allowed_space_ids (when set) and the Space role is sufficient and the path is under the member's read_root / write_root (when set) ``` ## Principals | Type | Notes | | --- | --- | | Human | `kind: human`, and may carry the `tenant_admin` role | | Agent | `kind: agent`, with its own permissions, memory, and audit identity | | API key | A credential, not a principal; it can only narrow its principal | Principals have no display name, so keep your own label against `id`. [`POST /v2/principals`](https://mirabase.io/developers/api/principals.md#principals-create) creates `human` and `agent` principals, and the `tenant_admin` role cannot be granted through the API. ## Capabilities A capability is permission for one kind of operation, such as `knowledge:read`, `knowledge:write`, `knowledge:manage`, `knowledge:answer`, or `memory:confirm`. A key's effective capabilities are its principal's intersected with the key's own. `effective_capabilities` on [`GET /v2/whoami`](https://mirabase.io/developers/api/identity.md#identity-whoami) reports that intersection. For what each capability allows, see [DevCapability](https://mirabase.io/developers/api/schemas.md#DevCapability) in the reference; each operation in the reference names the capability it needs. ## Space roles A member has one role in each Space: `owner`, `editor`, or `viewer`. An operation needs both a capability and a minimum role. What each role can do is in [DevSpaceRole](https://mirabase.io/developers/api/schemas.md#DevSpaceRole); the capability each operation needs, and any stricter rule, are in that operation's description in the [API reference](https://mirabase.io/developers/api.md). The Space owner sets a member's role, `write_mode`, `write_root`, and `read_root` with [`PUT /v2/spaces/{space_id}/members/{principal_id}`](https://mirabase.io/developers/api/spaces.md#spaces-setmember). ## Agent write mode `write_mode` applies only to Agents, and only to files they do not own. A new member defaults to `proposal`: changing someone else's file returns 403 `proposal_required`, moves and deletes included, and creates nothing. Set it to `direct` to allow the write. The Space owner is always `direct`. An Agent in `proposal` mode can send `Prefer: handling=proposal` to turn such a write into a proposal for a reviewer to approve. See [Proposals](https://mirabase.io/developers/files.md#proposals). ## Write roots and read roots The Space owner can limit a member to one subtree when setting the membership. Both roots only narrow: role, capabilities, and API key limits still apply, and there are no deny rules. For the accepted values, see [write_root](https://mirabase.io/developers/api/spaces.md#spaces-setmember.body.write_root) and [read_root](https://mirabase.io/developers/api/spaces.md#spaces-setmember.body.read_root). curl: ```bash # The Agent reads /projects/acme and writes only under /projects/acme/drafts. curl -X PUT "https://api.mirabase.dev/v2/spaces/$SPACE_ID/members/$AGENT_ID" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"role": "editor", "write_mode": "direct", "read_root": "/projects/acme", "write_root": "/projects/acme/drafts"}' ``` TypeScript: ```ts await mirabase.spaces.members.set(agentId, { role: "editor", write_mode: "direct", read_root: "/projects/acme", write_root: "/projects/acme/drafts", }); ``` Python: ```python # agent_id is the Agent's principal id. It reads /projects/acme and writes only under /projects/acme/drafts. mb.spaces.members.set(agent_id, { "role": "editor", "write_mode": "direct", "read_root": "/projects/acme", "write_root": "/projects/acme/drafts", }) ``` | Root | Inside | Outside | | --- | --- | --- | | `write_root` | Writes below the directory, but not renaming, moving, or deleting the directory itself | 403 `outside_write_root`; reads are unaffected | | `read_root` | Reads the directory and everything under it, and writes there when there is no `write_root` | 404, the same as missing; search, context, memories, and the change feed leave it out | - Entries without a path, such as `ingest`, project memories, and distilled facts, are outside both roots, except the member's own Agent memories. - A root follows its directory through renames and moves. Deleting a directory that is, or contains, a member's root returns 409 `directory_is_write_root` or `directory_is_read_root`, for the Space owner too. - A `write_root` does not limit branches; a merge into main is checked path by path, all or nothing. - [`GET /v2/spaces`](https://mirabase.io/developers/api/spaces.md#spaces-list) and [`GET /v2/spaces/{space_id}`](https://mirabase.io/developers/api/spaces.md#spaces-read) show your own `read_root` and `write_root`; start the tree there. ## Set up an Agent Give an Agent its own principal rather than sharing a person's API key. Its writes, memory, and audit trail then have their own identity, and revoking it affects no one else. ```bash # 1. Create the Agent. Without grant_capabilities it gets knowledge:read. curl -X POST https://api.mirabase.dev/v2/principals \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"kind": "agent", "grant_capabilities": ["knowledge:read", "knowledge:write"]}' # 2. Make it a member of one Space. write_mode direct lets it change files it does not own. curl -X PUT "https://api.mirabase.dev/v2/spaces/$SPACE_ID/members/$AGENT_ID" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"role": "editor", "write_mode": "direct"}' # 3. Issue its key, narrowed to that Space. curl -X POST https://api.mirabase.dev/v2/api-keys \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"actor_id": "'$AGENT_ID'", "name": "docs-agent", "grant_capabilities": ["knowledge:read", "knowledge:write"], "allowed_space_ids": ["'$SPACE_ID'"]}' ``` ## Limit a key to Spaces - Reaching a Space outside the list returns 404, the same as for a Space that does not exist. - A restricted API key cannot reach account-level or tenant-level surfaces: account memory, [`GET /v2/principals`](https://mirabase.io/developers/api/principals.md#principals-list), [`GET /v2/api-keys`](https://mirabase.io/developers/api/api-keys.md#apikeys-list), and [`GET /v2/audit/events`](https://mirabase.io/developers/api/audit.md#audit-events). - A key narrower than its principal can issue keys only for that principal, so changing identity does not bypass a limit. ## Invisible means not found A resource you cannot see and one that does not exist both return 404. After a 403, read [`GET /v2/whoami`](https://mirabase.io/developers/api/identity.md#identity-whoami). After a 404, check the id, the API key's Spaces, and your membership. ## Audit [`GET /v2/audit/events`](https://mirabase.io/developers/api/audit.md#audit-events) returns governance and access events. Events hold identifiers only, never user content. The service records a governance action in the same transaction as the change it makes, and rolls them back together. > **Note:** Permission changes take effect on the next statement and so does revocation. There is no cache window. ## Next steps - [Authentication and API keys](https://mirabase.io/developers/authentication.md): create, rotate, and revoke keys. - [Files and versions](https://mirabase.io/developers/files.md#proposals): submit and review proposals. - [Error codes](https://mirabase.io/developers/errors.md#codes): what each 403 code means. --- # 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 `, 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:`. 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: ""` | 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: ""` | 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. --- # Error codes Every error code an API key can receive, with its HTTP status, remediation.action, meaning, and Retry-After. This table is generated from the OpenAPI document. The structure of the error envelope, how to retry, and the rate limits are in [API conventions](https://mirabase.io/developers/conventions.md#errors). Branch on `code` and `remediation.action`. A code without a `remediation.action` has no fixed next step: handle it by its HTTP status. Future updates may add new codes; handle an unknown code by its HTTP status as well. ## Error codes | Code | Status | `remediation.action` | Meaning | | --- | --- | --- | --- | | `validation_error` | 400 / 422 | `fix_request` | The request is invalid. | | `invalid_request` | 400 / 422 | `fix_request` | The request is invalid. | | `unsupported_contract_version` | 400 | `drop_contract_version` | The service does not support this `Mirabase-Contract-Version` value: drop the header. | | `unauthorized` | 401 | `check_api_key` | The key is missing, invalid, expired, or revoked. | | `account_pending_approval` | 403 | `wait_for_approval` | The account has not been approved yet. Retry after approval, with the same key. | | `account_rejected` | 403 | `contact_support` | The account was not approved. Reach out through the contact page. | | `account_suspended` | 403 | `contact_support` | The account is suspended. Reach out through the contact page. | | `forbidden` | 403 | `check_permissions` | Capability or role is insufficient. | | `identity_override` | 403 | `remove_identity_fields` | The request sent a server-controlled field such as `principal_id`. | | `proposal_required` | 403 | `request_direct_write_mode` | An Agent changed someone else's file and needs `write_mode: direct`. | | `reserved_path` | 403 | `choose_another_path` | The path is under `/.mirabase/`. | | `outside_write_root` | 403 | `ask_owner_to_change_write_root` | The write lands outside the member's write root. | | `outside_read_root` | 403 | `ask_owner_to_change_read_root` | A member with a read root used a branch. | | `outside_metadata_scope` | 403 | `omit_scope_metadata_keys` | A key with a metadata scope wrote another value under a scope key: leave the key out, or send the scope's first value. | | `scoped_key_route_unavailable` | 403 | `use_unscoped_key` | A key with a metadata scope can only read, search, answer, and ingest: this operation needs a key without a scope. | | `console_session_required` | 403 | `use_console` | This operation accepts a console session only, not an API key: do it in the console. | | `not_found` | 404 | `check_identifier` | Missing or not visible to you. | | `content_not_ready` | 404 | `wait_and_retry` | This view waits for processing. | | `branch_not_found` | 404 | `check_identifier` | The branch does not exist. | | `checkpoint_not_found` | 404 | `check_identifier` | The checkpoint does not exist. | | `object_not_found` | 404 | `check_identifier` | The branch object does not exist. | | `snapshot_not_found` | 404 | `check_identifier` | The snapshot does not exist. | | `webhook_not_found` | 404 | `check_identifier` | The webhook does not exist. | | `upload_not_found` | 404 | `check_identifier` | The upload does not exist. | | `virtual_file` | 405 | `use_memories_api` | `/.mirabase/memory/MEMORY.md` and `RECENT.md` are read-only views. | | `request_timeout` | 408 | `retry_later` | Reading the request body timed out. | | `conflict` | 409 | - | The request conflicts with the current state. `remediation.action` is `use_new_idempotency_key` only when an `Idempotency-Key` was reused with different input; other conflicts have no action. | | `path_conflict` | 409 | `choose_another_path` | The target path is occupied. | | `not_a_directory` | 409 | `choose_another_path` | A segment of the path is a file. | | `move_into_descendant` | 409 | `choose_another_path` | A directory cannot move into itself. | | `copy_into_descendant` | 409 | `choose_another_path` | A directory cannot be copied into itself. | | `directory_not_empty` | 409 | `set_recursive` | Deleting a non-empty directory needs `recursive: true`. | | `subtree_too_large` | 409 | `split_request` | Over the synchronous node limit: split the request, or send `Prefer: respond-async`. | | `directory_is_write_root` | 409 | `change_member_write_root` | The directory is, or contains, a member's write root. | | `directory_is_read_root` | 409 | `change_member_read_root` | The directory is, or contains, a member's read root. | | `content_url_unavailable` | 409 | `use_content_endpoint` | A small text file kept on the server has no URL: read it with `view=raw`. | | `too_many_open_proposals` | 409 | `review_or_withdraw_proposals` | The Agent already has 100 open proposals in the Space. | | `proposal_conflict` | 409 | `resubmit_proposal` | The file changed or went to the trash since the proposal: submit a new one. | | `proposal_closed` | 409 | `stop_retrying` | The proposal or memory proposal is no longer open. | | `memory_pending_review` | 409 | `review_memory_first` | The memory is waiting for review: review it before changing it. | | `memory_already_reviewed` | 409 | `stop_retrying` | The memory is no longer pending review. | | `memory_superseded` | 409 | `read_current_memory` | The memory was replaced by a later revision: read the current one. | | `undo_window_expired` | 409 | `stop_retrying` | Undo is available for 30 minutes only. | | `undo_not_applicable` | 409 | `undo_the_correction` | A distilled fact has no write to undo: undo the correction that replaced it. | | `upload_not_open` | 409 | `start_new_upload` | The upload is completed or aborted: start a new one. | | `upload_conflict` | 409 | `start_new_upload` | The upload is in a conflicting state: start a new one. | | `snapshot_name_taken` | 409 | `choose_another_name` | The Space already has a snapshot with this name. | | `too_many_snapshots` | 409 | `delete_unused_snapshots` | The Space has its maximum of snapshots. | | `snapshot_too_large` | 409 | `review_usage` | Over the snapshot's file limit. | | `too_many_webhooks` | 409 | `delete_unused_webhooks` | The Space has its maximum of webhooks. | | `export_too_large` | 409 | `split_request` | The export is over the file or byte limit: export a `path` at a time. | | `artifact_not_ready` | 409 | `wait_for_job` | The export has not finished. | | `space_busy` | 409 | `wait_and_retry` | The Space stayed busy for 2 seconds. `Retry-After`: 1 second. | | `space_external_id_taken` | 409 | `find_space_by_external_id` | Another Space in the account already has this `external_id`. If you can see it, get it with [`GET /v2/spaces?external_id=`](https://mirabase.io/developers/api/spaces.md#spaces-list) or [`PUT /v2/spaces/ext:`](https://mirabase.io/developers/api/spaces.md#spaces-ensure); if you cannot, choose another id. | | `job_in_flight` | 409 | `wait_and_retry` | Work is in flight: wait for `job_id`. | | `evidence_changed` | 409 | `retry_request` | The evidence changed while the result was built: send it again. | | `branch_not_active` | 409 | `open_new_branch` | The branch is merged or abandoned. | | `branch_name_taken` | 409 | `choose_another_name` | An active branch already has this name. | | `branch_limit_reached` | 409 | `abandon_or_merge_branches` | The Space has its maximum of active branches. | | `branch_too_large` | 409 | `merge_or_split_branch` | The branch has its maximum of paths. | | `checkpoint_limit_reached` | 409 | `open_new_branch` | The branch has its maximum of checkpoints. | | `merge_conflict` | 409 | `resolve_conflicts` | Main changed paths the branch also changed: see `conflicts`. | | `merge_too_large` | 409 | `split_request` | Over 1000 paths in one merge: split it with `paths`, or send `Prefer: respond-async`. | | `merge_in_progress` | 409 | `wait_for_job` | A merge job of this branch is queued or running. | | `dream_run_in_flight` | 409 | `wait_for_job` | A dream of this scope is queued or running. | | `dreaming_disabled` | 409 | `enable_memory_dreaming` | The Space's consolidation setting is `off`. | | `api_key_not_live` | 409 | `issue_new_key` | The key is revoked or expired. | | `self_rotation_not_allowed` | 409 | `issue_new_key_then_revoke` | A key cannot rotate itself. | | `owner_membership_immutable` | 409 | `keep_owner_membership` | The owner's membership cannot change. | | `default_space_protected` | 409 | `keep_default_space` | The default Space cannot be deleted. | | `tenant_deleted` | 409 | `stop_requests` | The account was deleted. | | `tenant_limit_reached` | 409 | `delete_unused_resources` | The account has its maximum of live keys, principals, or Spaces. | | `gone` | 410 | `stop_retrying` | The Entry behind this receipt was erased. | | `cursor_expired` | 410 | `resync_from_tree` | The cursor is over 90 days old: resync from `tree`. | | `artifact_expired` | 410 | `start_new_export` | The export failed, is over 7 days old, or was invalidated by a purge or a read-root change. | | `export_invalidated` | 410 | `start_new_export` | Content was erased or the read scope changed during the export: start a new one. | | `precondition_failed` | 412 | `reread_and_retry` | `If-Match` or `If-None-Match` failed. | | `payload_too_large` | 413 | `reduce_payload` | The request body is too large. | | `patch_base_too_large` | 413 | `use_put` | The file is over 1 MiB, too large for `PATCH`. | | `archive_too_large` | 413 | `split_archive` | The import archive is too large or has over 10,000 members. | | `upload_invalid` | 413 / 422 | `fix_request` | The upload request is invalid, or the file is over the limit. | | `upload_media_type_mismatch` | 415 | `fix_request` | The uploaded content type differs from the one declared at the start. | | `unsupported_media_type` | 415 | `use_put` | Not UTF-8 text. | | `range_not_satisfiable` | 416 | `fix_request` | The `Range` lies outside the file. | | `invalid_path` | 422 | `fix_path` | The path breaks the rules. | | `path_too_long` | 422 | `shorten_path` | The path is over the limit. | | `edit_no_match` | 422 | `reread_and_retry` | `old_text` was not found. | | `edit_ambiguous` | 422 | `add_context_or_replace_all` | `old_text` appears more than once. | | `view_not_available` | 422 | `choose_another_view` | This source has no such view. | | `upload_expired` | 422 | `start_new_upload` | The upload session has ended. | | `upload_size_mismatch` | 422 | `fix_request` | The uploaded bytes differ from the `size` declared at the start. | | `upload_integrity_mismatch` | 422 | `start_new_upload` | The uploaded content does not match `checksum_sha256`: upload again. | | `checksum_mismatch` | 422 | `fix_request` | A branch object does not hash to its `sha256`. | | `unknown_citation` | 422 | `use_citations_from_pack` | A citation in the feedback is not in the pack. | | `write_root_outside_read_root` | 422 | `set_write_root_inside_read_root` | The write root is not inside the read root. | | `invalid_webhook_url` | 422 | `fix_webhook_url` | The webhook URL is not public `https` on port 443. | | `unsupported_archive` | 422 | `use_tar_archive` | The import is not a tar or gzip-compressed tar. | | `rate_limited` | 429 | `wait_and_retry` | Request rate or concurrency limit reached. `Retry-After`: Seconds until the request bucket has room when `limit` is `request_rate`; 1 when `limit` is `concurrency`. | | `too_many_waiters` | 429 | `wait_and_retry` | A key already holds 4 long polls. `Retry-After`: 1 second. | | `ingest_backlog` | 429 | `wait_and_retry` | Too many jobs are queued for the account: jobs that make content searchable past `tenant_queued_jobs`, or summaries, classification, relations and memories past five times that. `queue` says how many of that kind, the limit, whether processing is paused, and an estimate of how long the queue needs. A key limited to some Spaces or to metadata is told only that the limit is reached. `Retry-After`: 30 to 600: the estimated time until the account's queue is below its limit; 600 while processing is paused. 60 for a key limited to some Spaces or to metadata. | | `too_many_jobs` | 429 | `wait_and_retry` | The Space already runs 4 jobs that change the tree, or 4 exports. `Retry-After`: 30 seconds. | | `login_code_throttled` | 429 | `wait_and_retry` | Console email codes: requested too often, or too many wrong codes from one address. `Retry-After`: 60 when codes are requested too often; 3600 after too many requests or wrong codes in an hour. | | `quota_exceeded` | 429 | `review_usage` | A stored quota is used up, or the call would take more of it than is left, and retrying does not help. `quota` names it: `writes`, `storage_bytes`, `model_tokens`, or `model_spend_micro_usd`. | | `internal_error` | 500 | `retry_later` | An internal error. | | `model_failed` | 502 | `retry_later` | The model call failed while answering. | | `original_unavailable` | 503 | `retry_later` | The original is temporarily unavailable. | | `answer_unavailable` | 503 | `retry_later` | The answer model is temporarily unavailable. | | `object_store_unavailable` | 503 | `retry_later` | Object storage is temporarily unavailable. | | `object_store_request_failed` | 503 | `retry_later` | Object storage is temporarily unavailable. | | `object_stream_integrity_mismatch` | 503 | `retry_later` | Object storage is temporarily unavailable. | | `spec_unavailable` | 503 | `feature_not_enabled` | This deployment does not have the feature enabled, and retrying does not help. | | `webhooks_unavailable` | 503 | `feature_not_enabled` | This deployment does not have the feature enabled, and retrying does not help. | | `answer_not_configured` | 503 | `use_context_with_your_model` | This deployment has no answer model: build a context pack with [`POST /v2/retrieval/context`](https://mirabase.io/developers/api/retrieval.md#retrieval-buildcontext) and run your own model. | | `deadline_exceeded` | 504 | `retry_later` | Retrieval ran past the `deadline_ms` in the request. | ## Next steps - [API conventions](https://mirabase.io/developers/conventions.md#errors): the error envelope, retries, and rate limits. - [SDK](https://mirabase.io/developers/sdks.md#errors): the error classes the SDKs throw. - [API reference](https://mirabase.io/developers/api.md): the statuses each endpoint can return. --- # Skills Mirabase's official skills tell an Agent when to call which MCP tool, in what order, and what to ask the user first. Nine skills cover the API task by task, and two cover complete scenarios: project memory and a knowledge base with cited answers. A skill is a folder with a `SKILL.md`: its `name` and `description` say what it does and when to use it, and its body holds the steps. An Agent keeps only the descriptions in context and loads a body when a task matches, so skills cost little until they are used. The official skills use the Agent Skills format and do not depend on any one Agent host; the tools they call come from Mirabase's [MCP server](https://mirabase.io/developers/agents.md). ## Official skills | Skill | What it does | | --- | --- | | `mirabase` | The entry point: decides whether something belongs in a file, a memory, or the conversation record, stores emails, transcripts, and web pages, picks the skill to load, and handles the start and end of a task. | | `mirabase-setup` | Connects an Agent, checks a key with `mira.whoami`, and explains a 401, 403, 404, or 429. | | `mirabase-files` | Reads, writes, edits, moves, copies, and uploads files by path, using ETags so Agents do not overwrite each other. | | `mirabase-recover` | Shows versions and diffs, reverts, restores from the trash, and takes and reads snapshots. | | `mirabase-branches` | Changes many files on a branch, checkpoints, shows the diff for review, merges, and reviews Agent proposals. | | `mirabase-sync` | Keeps a local folder in sync through the CLI, or follows changes through the change feed and webhooks. | | `mirabase-recall` | Searches, builds a context pack for a task, answers with citations, and reads the full Entry behind a hit. | | `mirabase-memories` | Keeps, corrects, reviews, and forgets memories, with the right scope. | | `mirabase-access` | Gives each Agent its own limited key, sets read and write roots, write modes, and label scopes, and rotates and revokes keys. | | `mirabase-project-memory` | Scenario: a coding Agent keeps one repository's conventions, decisions, and progress across sessions. | | `mirabase-knowledge-base` | Scenario: loads a folder of documents into a Space, reloads it after the documents change, and answers from those documents with citations. | - Every description lists example requests in English and Chinese and says what the skill is not for, so the Agent loads the right one. - Every action that cannot be undone (purging, forgetting a memory, revoking a key, merging over conflicts) asks the user first. The skills never print or store a key, and treat what the tools return as data, not instructions. - All descriptions together are about 1,700 tokens; each skill's file is 1,300 to 2,150 tokens, read only when it is used (counted with `cl100k_base`). ## Scenario skills **Project memory (`mirabase-project-memory`)**: each repository has a Space of its own, such as `ext:acme-web`. At the start of a session the Agent calls `mira.context` with `purpose: "coding"` to read the project's conventions, decisions, and where the last session stopped. While working it records each convention and decision as one project memory, plus a short decision record when the reasoning matters. At the end it updates the progress memory for that line of work with `mira.memory.correct` (one per line of work). Code, diffs, and logs stay in the repository, not in Mirabase. **Knowledge base (`mirabase-knowledge-base`)**: each knowledge base has a Space of its own. Its loader script (Node 18 or newer, no dependencies) writes the documents of a folder under `/kb/`; unchanged files create no new version, and files deleted locally are listed, never deleted. Documents are written with `memory_exclude`, so they are searched and cited as written rather than distilled into memories. Answers come from `mira.answer`: with `answered`, the Agent gives the answer and the paths of the files it cites; with `abstained`, it says the retrieved passages do not support an answer instead of filling the gap from general knowledge. ## Install (Coming soon) > **Coming soon** The official skills ship with the open-source repository; source available when the open-source repository is published. Once it is, install them for your Agent host: Claude Code: ```bash export MIRABASE_API_KEY="mb_live_..." # From the root of the open-source repository. The plugin folder adds the MCP server, the skills, and the hooks. claude --plugin-dir clients/agent-plugin ``` Codex: ```bash export MIRABASE_API_KEY="mb_live_..." codex mcp add mirabase --url https://api.mirabase.dev/mcp --bearer-token-env-var MIRABASE_API_KEY # Then paste the section in clients/agent-plugin/codex/AGENTS.md into your project's AGENTS.md. ``` Agent Skills: ```agent skills # From the root of the open-source repository: copy all eleven skills into the host's skills directory. SKILLS_DIR=~/.claude/skills # Claude Code without the plugin; other hosts document their own mkdir -p "$SKILLS_DIR" && cp -R clients/agent-plugin/skills/* "$SKILLS_DIR"/ # Then add the MCP server: https://api.mirabase.dev/mcp, Streamable HTTP, # header "Authorization: Bearer $MIRABASE_API_KEY". ``` - Claude Code: the plugin folder adds the MCP server, every skill, and hooks. The hooks read memory at session start, and save the text of user and assistant messages to the Space named by `MIRABASE_SPACE` (the default Space) before the context is compacted, when the session ends, and every 20 messages, masking what looks like a credential. Set `MIRABASE_CAPTURE=off` to stop saving. - Codex: give it the rules through the project's `AGENTS.md`. The plugin's `codex/AGENTS.md` is a short section to paste in, covering the storage rules and both scenarios; if your Codex version loads Agent Skills, you can also copy the skill folders as for other hosts. - Other hosts that support Agent Skills (the Agent Skills tab above): copy the skill folders. If you copy only some, always include the entry skill `mirabase`, which the others refer to. > **Note:** Until then, the MCP server works on its own: the `instructions` in its handshake response already say when to read, when to save, and where, and a client that supports the field passes them to the model. See [Connect an Agent (MCP)](https://mirabase.io/developers/agents.md). ## Next steps - [Build on Mirabase](https://mirabase.io/developers/build.md): write your own skill, and see how skills, the SDKs, webhooks, and provider plugins fit together. - [Connect an Agent (MCP)](https://mirabase.io/developers/agents.md): every tool the skills call, with its parameters. - [Permissions](https://mirabase.io/developers/permissions.md): set each Agent's write mode and its read and write roots. --- # Build on Mirabase What the SDKs, MCP, skills, skills stored in a Space, webhooks, and provider plugins are each for and how they combine; the core calls of an application; and how to write and check a skill of your own. ## Ways to build | Piece | Who uses it, for what | | --- | --- | | [SDKs](https://mirabase.io/developers/sdks.md) (TypeScript, Python) | Your application code calls `/v2`: write files and conversations, get context packs, answer with citations. | | [MCP server](https://mirabase.io/developers/agents.md) | Agents read and write files, search, get context, answer, and manage memory through the `mira.*` tools, with the same permissions as `/v2`. Branches, access management, and binary uploads are REST only. | | [Skills](https://mirabase.io/developers/skills.md) | Agent hosts load them, so the Agent knows when to call which tool, in what order, and what to ask the user first. | | Skills in a Space | Any Agent that calls `mira.context`: context packs offer the skills stored in the Space, with nothing to install on each Agent. | | [Webhooks and the change feed](https://mirabase.io/developers/sync.md) | Your services run their own processing when files in a Space change, such as rebuilding an index or notifying a team. | | Provider plugins | A self-hosted engine uses them to replace the embedding, rerank, answer, distill, classify, OCR, transcription, or web search implementation. The hosted service loads no plugins. | ### Choosing a piece - Your product calls Mirabase: use an SDK. - An Agent calls Mirabase: connect MCP, and install skills that tell it how. - One procedure for every Agent of a team: store the skill in a Space. - Changes in Mirabase must trigger your own systems: use webhooks or the change feed. - A different model in your own deployment: write a provider plugin. ## The core loop The program below shows four common calls: write a file by path, store a conversation, get a context pack for a task to give your own model, or get an answer with citations directly. It runs in a Space of its own (`ext:example-core-loop`), so your other data is untouched. It needs only `MIRABASE_API_KEY`, for a key that can create a Space, read, write, and answer. TypeScript: ```ts import { Mirabase } from "@mirabase/sdk/developer"; const mb = new Mirabase(); // reads MIRABASE_API_KEY // A Space of its own, created on the first run; the client reads and writes that Space only. const space = await mb.spaceFor("example-core-loop", { name: "Core loop example" }); // 1. A file at a stable path. The same bytes again create no new version. await space.files.write( "/handbook/travel.md", "# Travel policy\n\nHotels up to 180 euros a night are approved automatically.\nBook economy for flights under six hours.\n", ); // 2. A conversation. Memories are distilled from it in the background. await space.conversations.add( [ { role: "user", content: "I'm going to Berlin for the trade fair on 12 March. I prefer hotels near the fair." }, { role: "assistant", content: "Noted: Berlin, 12 March, a hotel close to the fair." }, ], { sessionId: "core-loop-demo", redactSecrets: true }, ); await space.spaces.waitUntil({ waitTimeoutMs: 120_000 }); // searchable by meaning // 3. Context for your own model: memories and passages within a token budget, each with a citation id. const pack = await space.context("Book a hotel for the Berlin trip within policy.", { budget_tokens: 1500 }); // API field names stay snake_case // ...send pack.items to your model; afterwards report the citation ids it actually used: // await space.context.feedback(pack.pack_id, usedCitationIds); // 4. Or a cited answer from Mirabase. It abstains when the evidence is not there. const answer = await space.answer("How much can a hotel cost per night without approval?"); console.log(answer.status, answer.answer, answer.citations.map((citation) => citation.path ?? citation.url ?? citation.entry_id)); ``` Python: ```python from mirabase import Mirabase mb = Mirabase() # reads MIRABASE_API_KEY # A Space of its own, created on the first run; the client reads and writes that Space only. space = mb.space_for("example-core-loop", name="Core loop example") # 1. A file at a stable path. The same bytes again create no new version. space.files.write( "/handbook/travel.md", "# Travel policy\n\nHotels up to 180 euros a night are approved automatically.\n" "Book economy for flights under six hours.\n", ) # 2. A conversation. Memories are distilled from it in the background. space.conversations.add( [ {"role": "user", "content": "I'm going to Berlin for the trade fair on 12 March. I prefer hotels near the fair."}, {"role": "assistant", "content": "Noted: Berlin, 12 March, a hotel close to the fair."}, ], session_id="core-loop-demo", redact_secrets=True, ) space.spaces.wait_until(timeout=120) # searchable by meaning # 3. Context for your own model: memories and passages within a token budget, each with a citation id. pack = space.context("Book a hotel for the Berlin trip within policy.", budget_tokens=1500) # ...send pack["items"] to your model; afterwards report the citation ids it actually used: # space.context.feedback(pack["pack_id"], used_citation_ids) # 4. Or a cited answer from Mirabase. It abstains when the evidence is not there. answer = space.answer("How much can a hotel cost per night without approval?") print(answer["status"], answer["answer"], [c.get("path") or c.get("url") or c["entry_id"] for c in answer["citations"]]) ``` - `spaceFor` (`space_for` in Python) creates the Space on the first run and finds the same one afterwards; the client it returns reads and writes that Space only. With one Space per end user, and your server picking the client for the signed-in user, each user's data stays apart. Pinning a client is a default, not a permission boundary: the key itself can still read every Space it can see. For a hard boundary, issue a key limited to that user's Space; see [Permissions](https://mirabase.io/developers/permissions.md). - Text up to 64 KiB can be found by its words as soon as it is written, and by meaning once processing finishes; to wait for that, call `waitUntil` (`wait_until` in Python). - `context.feedback` reports which items your model used. It sends citation ids only, never content. - The full runnable version is `examples/core-loop` in the open-source repository; source available when the open-source repository is published. ## Write a skill The skill template is a small working skill, `changelog`: it drafts a changelog entry from what changed in a Space and the decisions stored there, and writes it to `/changelog/.md` once the user approves. Copy it, then change it in this order: 1. Name the folder and `name` the same: lowercase words joined by hyphens, at most 64 characters. 2. Write the description first: an Agent decides whether to load a skill from its description alone, and the description stays in context all the time. Say what the skill does, give two or three real user requests, and name the neighbouring skills under “Not for”. Keep it under 650 characters. 3. Write the steps: name the exact tool or endpoint in each, and say what to do on the likely errors. For every action that cannot be undone or that reaches outside, say to ask the user first. 4. Delete the template's comments: the whole file is read every time the skill loads. 5. Before you tune the description, write the trigger file: requests that should load your skill, and close ones that should load another. The check that comes with the template confirms that every `mira.*` tool and `/v2` endpoint your skill names exists, and scores your requests and the official ones with a lexical router that sees only names and descriptions. If your description takes requests meant for another skill, change the description, not the request. Source for the template and the check available when the open-source repository is published. ## Store a skill in a Space A file written to `/.mirabase/skills//SKILL.md` becomes a skills source for context packs: when an Agent calls `mira.context`, an item whose `source` is `skills` is a one-line summary of the skill's description, and the Agent reads the full file with `mira.files.read` before following it. A team's procedures can then reach every Agent through the Space, with nothing to install on each one. The official skills have the Agent ask the user before following a skill from a Space for the first time, and again after it changes, and never run scripts stored in a Space. curl: ```bash curl -X PUT "https://api.mirabase.dev/v2/spaces/ext:team-handbook/files?path=/.mirabase/skills/changelog/SKILL.md" \ -H "Authorization: Bearer $MIRABASE_API_KEY" \ -H "Content-Type: text/markdown" \ --data-binary @changelog/SKILL.md ``` TypeScript: ```ts import { readFile } from "node:fs/promises"; import { Mirabase } from "@mirabase/sdk/developer"; const team = new Mirabase().space("ext:team-handbook"); // the Space whose Agents should see the skill await team.files.write("/.mirabase/skills/changelog/SKILL.md", await readFile("changelog/SKILL.md", "utf8")); ``` Python: ```python from pathlib import Path from mirabase import Mirabase team = Mirabase().space("ext:team-handbook") # the Space whose Agents should see the skill team.files.write("/.mirabase/skills/changelog/SKILL.md", Path("changelog/SKILL.md").read_text()) ``` - Only that level counts: the `SKILL.md` in each folder under `/.mirabase/skills/`. Other files in the same folder are the skill's own reference material, for Agents to read, never to run. - The skills source has its own share of a pack's budget. At a small budget the summary may not fit, and `route` reports `budget_too_small` for that source, so keep descriptions short. > **Warning:** A skill stored in a Space is content like any other: whoever can write the Space can change what Agents are told. Give write access to that folder only to members you trust (limit the others with write roots; see [Permissions](https://mirabase.io/developers/permissions.md)), and keep rules that must never change in the Agent's own skills folder. ## React to changes To run your own processing when files change (rebuild derived files, mirror to another system, notify a team), let Mirabase push changes with a [webhook](https://mirabase.io/developers/sync.md#webhooks), or long-poll the [change feed](https://mirabase.io/developers/sync.md#loop) from a cursor. Both carry the same events; a webhook needs a public HTTPS address, the change feed does not. ## Provider plugins (self-hosted) A self-hosted Mirabase engine calls models and tools through ports: embedding, rerank, answer, distill, classify, OCR, transcription, and web search. A plugin is an ES module that exports `{ name, register(api) }` and registers an implementation for a port in `register`; a deployment loads it with the `MIRABASE_PROVIDER_PLUGINS` environment variable and selects it with that port's variable. - A plugin runs inside the engine with the engine's permissions. Load only code you wrote or reviewed. The hosted service loads no plugins. - A conformance kit checks each port's contract (a reranker returns the candidates' own `index`, cancellation stops at once, and so on) and does not depend on a test framework. - The plugin interface, each port's contract, and an example plugin are in `docs/providers.md` in the open-source repository; source available when the open-source repository is published. ## Next steps - [Skills](https://mirabase.io/developers/skills.md): the official skills and the two scenario skills. - [SDKs](https://mirabase.io/developers/sdks.md): install an SDK, and see its error types and retries. - [Retrieval and context](https://mirabase.io/developers/retrieval.md): a context pack's budget, sources, and feedback.