# 5 分钟快速开始

按路径写入和读取文件，编辑后查看版本，对比并回滚；让 Agent 在分支上修改后合并；获取引用到文件版本的回答；通过 MCP 连接 Agent。

## 准备工作

> **说明：** TypeScript SDK 的包名是 `@mirabase/sdk`，示例从 `@mirabase/sdk/developer` 导入，需要 Node.js 20.3 或更新版本，只提供 ES 模块：把各步的示例依次存入 `quickstart.mjs`，用 `node quickstart.mjs` 运行。Python SDK 的包名是 `mirabase`，需要 Python 3.11 或更新版本。两者均为 0.x 版本，方法名在 1.0 之前仍可能调整。目前提供的是候选版本，见 [SDK](https://mirabase.io/zh/developers/sdks.md#install)。每一步的示例都接着上一步写，沿用前面定义的变量；`mirabase`（TypeScript）和 `mb`（Python）是第 1 步创建的客户端，其他页面的示例也用它们。

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
# curl 示例用 jq 读取字段，例如：
# macOS: brew install jq
# Debian 或 Ubuntu: sudo apt-get install jq

# 后续的 curl 示例都用 $SPACE_ID，default 表示你的默认 Space。
export SPACE_ID=default
```

需要 Space id 的地方都可以写 `default`，它表示你自己的默认 Space；Key 只能看到一个 Space 时，表示那个 Space。SDK 在不指定 Space 时使用默认 Space。curl 示例需要 bash 或 zsh：`$'…'` 会把 `\n` 转换为换行符。

## 第 1 步：注册并创建 API Key

打开 [控制台](https://console.mirabase.dev)，登录并接受条款。登录方式以登录页实际提供的方式为准，同一个已验证邮箱无论用哪种方式，都归到同一账户。首次登录会自动创建你的租户和默认 Space。然后在 API Key 页面创建一个 API Key。明文只显示一次，请立即保存。将其放入环境变量，然后确认它可用：

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` 是这个 Key 当前具备的能力。详见 [认证与 API Key](https://mirabase.io/zh/developers/authentication.md)。

> **说明：** 注册受容量限制。当天的新账户名额用完或注册暂时关闭时，无法创建新账户，控制台会说明原因，请稍后再试。新账户需要审批：审批通过前可以登录并创建 Key，但用 Key 调用 API 会返回 403 `account_pending_approval`；通过后所有 Key 立即可用，无需重新创建。

## 第 2 步：按路径写入文件

[`PUT /v2/spaces/{space_id}/files`](https://mirabase.io/zh/developers/api/files.md#files-write) 的请求体就是文件内容，无需预先创建上级目录。响应返回时写入已提交，立即可读：

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`：这个文件的稳定身份，改名和移动都不变。
- `version_id`：这次写入产生的不可变版本。后面的步骤用它对比和回滚。
- `entry.knowledge.state`：`searchable` 表示词法检索已经能找到这段文本，处理完成后变为 `indexed`。

## 第 3 步：读取文件

按同一路径读取，得到写入的原始字节。`ETag` 就是这次读到的版本，下一步用它做条件写入。

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
```

## 第 4 步：编辑文件并查看版本

`PATCH` 按原文精确替换文本，并生成一个新版本。带上 `If-Match` 后，如果其他调用方或 Agent 在此期间写入过这个文件，请求会失败并返回 412，不会覆盖对方的修改。版本列表按从新到旧排列，`updated_from` 指向上一个版本。

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"])
```

## 第 5 步：对比并回滚

对比第 1 个版本和最新版本，得到统一格式的 diff。回滚会把旧版本的内容写成一个新版本，之前的所有版本都会保留，因此回滚本身也可以再回滚。

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.
```

## 第 6 步：让 Agent 在分支上工作

Agent 的修改先写在分支上，主线保持不变。检查点记录分支当前的状态，分支可以回滚到该检查点。合并前先查看分支相对主线的 diff，确认后再合并；`on_conflict: "abort"` 表示主线上同一路径已被改动时整个合并不生效。实际使用时，请给 Agent [单独签发一个权限收窄的 API Key](https://mirabase.io/zh/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"])
```

分支的有效期、回滚和大规模合并见 [分支与检查点](https://mirabase.io/zh/developers/branches.md)。

## 第 7 步：就文件提问并获取引用

[`POST /v2/retrieval/answer`](https://mirabase.io/zh/developers/api/retrieval.md#retrieval-answer) 从文件、知识和记忆中选取证据，由模型生成回答，并在正文里用 `[cN]` 标注引用。每条引用指向一个 Entry 的具体版本：这里的 `version_id` 是第 5 步回滚产生的版本。证据不足时返回 `abstained`，不会编造回答。

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
}
```

## 第 8 步：通过 MCP 连接 Agent

Agent 通过 MCP 读写同一批文件，读到的版本与 API 和 SDK 返回的一致。在 Claude Code 或 Codex 里添加 Mirabase，或把 JSON 配置填入任意支持远程 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_..."
      }
    }
  }
}
```

连接后可以让 Agent 执行：“读取 Mirabase 中的 /notes/launch.md 和 /notes/checklist.md，列出发布前还剩哪些事项。”MCP 工具支持列出、读取、写入、编辑和删除文件，并涵盖检索、回答和记忆；版本和分支目前通过 API 和 SDK 使用。工具清单见 [连接 Agent（MCP）](https://mirabase.io/zh/developers/agents.md#tools)。

## 下一步

1. 了解 [Entry、版本、文件、知识和记忆](https://mirabase.io/zh/developers/concepts.md) 的关系。
2. [检索](https://mirabase.io/zh/developers/retrieval.md#search) 文件，或用 [上下文](https://mirabase.io/zh/developers/retrieval.md#context) 为自己的模型获取证据。
3. [写入一条记忆](https://mirabase.io/zh/developers/memory.md#create)，或 [导入一段对话](https://mirabase.io/zh/developers/memory.md#conversation)，让服务从中提炼记忆。
4. 为每个最终用户 [单独建一个 Space](https://mirabase.io/zh/developers/concepts.md#space-per-user)，用你自己的用户 id 找到它。
5. 让 Agent 的写入 [先经过提案和审核](https://mirabase.io/zh/developers/files.md#proposals)，或 [限制它可写入的目录](https://mirabase.io/zh/developers/permissions.md#roots)。
6. 使用 [变更流和快照](https://mirabase.io/zh/developers/sync.md) 保持 Space 同步。
