# 基于 Mirabase 开发

SDK、MCP、技能、Space 中的技能、Webhook 和供应商插件各自的作用与组合方式；一个应用的核心调用流程；如何编写并检查自己的技能。

## 扩展方式

| 方式 | 谁用它、做什么 |
| --- | --- |
| [SDK](https://mirabase.io/zh/developers/sdks.md)（TypeScript、Python） | 你的应用代码调用 `/v2`：写入文件和对话，获取上下文包，带引用回答。 |
| [MCP 服务](https://mirabase.io/zh/developers/agents.md) | Agent 通过 `mira.*` 工具读写文件、检索、获取上下文、回答和管理记忆，权限与 `/v2` 相同。分支、访问管理和二进制上传只能通过 REST。 |
| [技能](https://mirabase.io/zh/developers/skills.md) | Agent 平台加载技能，按技能决定何时调用哪个工具、按什么顺序、先问用户什么。 |
| Space 中的技能 | 调用 `mira.context` 的任何 Agent：上下文包会推荐存在 Space 中的技能，无需在每个 Agent 上安装。 |
| [Webhook 与变更流](https://mirabase.io/zh/developers/sync.md) | 你的服务在 Space 中的文件变化时运行自己的处理，例如重新生成索引或通知团队。 |
| 供应商插件 | 自部署的引擎用它替换嵌入、重排、回答、提炼、分类、OCR、转写或联网搜索的实现。托管服务不加载插件。 |

### 选择扩展方式

- 你的产品调用 Mirabase：用 SDK。
- Agent 调用 Mirabase：连接 MCP，并安装技能告诉它如何使用。
- 同一套做法要提供给一个团队的所有 Agent：把技能存在 Space 中。
- Mirabase 中的变化要触发你自己的系统：用 Webhook 或变更流。
- 在自己的部署中更换模型：写一个供应商插件。

## 核心调用流程

下面的程序演示四类常用调用：按路径写入文件，保存对话，为任务获取上下文包交给自己的模型，或直接获取带引用的回答。它在一个独立的 Space（`ext:example-core-loop`）中运行，不影响你的其他数据；只需设置 `MIRABASE_API_KEY`，Key 需要能创建 Space、读取、写入和回答。

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`（Python 为 `space_for`）在首次运行时创建 Space，之后找到同一个 Space；它返回的客户端只读写这个 Space。为每个最终用户建一个 Space，并在服务端按已登录用户选择对应的客户端，即可把不同用户的数据分开。绑定 Space 只会设置客户端默认访问的 Space，实际可访问的范围由 Key 的权限决定：Key 本身仍能读取它可见的所有 Space，需要硬边界时，签发只允许访问该用户 Space 的 Key，见 [权限](https://mirabase.io/zh/developers/permissions.md)。
- 不超过 64 KiB 的文本写入后即可按词检索，处理完成后即可按语义检索；需要等待时可调用 `waitUntil`（Python 为 `wait_until`）。
- `context.feedback` 回报模型实际用到的条目，只发送引用 id，不发送内容。
- 可运行的完整版本是开源仓库中的 `examples/core-loop`，源代码在开源仓库发布后提供。

## 编写技能

技能模板是一个可运行的小技能 `changelog`：根据 Space 中的变更和已保存的决定起草更新日志，经用户确认后写入 `/changelog/<version>.md`。复制它，再按下列顺序修改：

1. 文件夹名与 `name` 相同：小写单词，用连字符连接，不超过 64 个字符。
2. 先写描述：Agent 只根据描述决定是否加载技能，而且描述常驻上下文。写清做什么，给出两三个用户的真实请求，并用“Not for”指明相邻的技能。不超过 650 个字符。
3. 写步骤：每一步写出确切的工具名或接口，并说明常见错误的处理方式。不可撤销或对外发出的操作，写明先征得用户同意。
4. 删除模板中的注释：技能每次加载都会读取全部内容。
5. 在调整描述之前写好触发测试：应当加载这个技能的请求，以及应当加载其他技能的相近请求。

模板附带的检查会确认技能提到的每个 `mira.*` 工具和 `/v2` 接口都存在，并用一个只看名称和描述的词法路由器为你的请求和官方请求打分；如果你的描述误匹配了本应由其他技能处理的请求，应修改描述，而不是修改请求。模板与检查工具的源代码在开源仓库发布后提供。

## 把技能存在 Space 中

写入 `/.mirabase/skills/<name>/SKILL.md` 的文件会被上下文包当作技能来源：Agent 调用 `mira.context` 时，`items` 中 `source` 为 `skills` 的条目是技能描述的一行摘要，Agent 在使用前用 `mira.files.read` 读取完整文件。这样，一个团队的约定可以随 Space 提供给所有 Agent，而不必在每个 Agent 上安装。官方技能要求 Agent 在第一次使用某个 Space 中的技能前、以及该技能更改后，先征得用户同意，并且从不运行 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())
```

- 只认这一层：`/.mirabase/skills/` 下每个文件夹中的 `SKILL.md`。同一文件夹中的其他文件是技能自己的参考资料，Agent 只读取，不执行。
- 技能来源在上下文包中有自己的预算份额。预算较小时摘要可能放不下，`route` 中这一来源会报告 `budget_too_small`，所以描述要短。

> **注意：** 存在 Space 中的技能和其他内容一样：能写这个 Space 的人就能改变 Agent 收到的指示。只把这个文件夹的写入权限交给可信的成员（用写入根路径限制其他成员，见 [权限](https://mirabase.io/zh/developers/permissions.md)），不能更改的规则放在 Agent 自己的技能目录中。

## 响应变化

需要在文件变化时运行自己的处理（重新生成派生文件、同步到其他系统、通知团队），用 [Webhook](https://mirabase.io/zh/developers/sync.md#webhooks) 让 Mirabase 推送变更，或用 [变更流](https://mirabase.io/zh/developers/sync.md#loop) 从游标开始长轮询。两者给出相同的事件；Webhook 需要一个公网 HTTPS 地址，变更流不需要。

## 供应商插件（自部署）

自部署的 Mirabase 引擎通过提供方接口调用模型和工具：嵌入、重排、回答、提炼、分类、OCR、转写和联网搜索。插件是一个 ES 模块，导出 `{ name, register(api) }`，在 `register` 中为某个提供方接口登记一个实现；部署时用环境变量 `MIRABASE_PROVIDER_PLUGINS` 加载，再用该接口对应的变量选择它。

- 插件在引擎进程中运行，权限与引擎相同。只加载自己编写或审查过的代码。托管服务不加载任何插件。
- 一致性检查套件逐项核对每个提供方接口的契约（例如重排必须返回候选自己的 `index`、取消时立即停止），不依赖测试框架。
- 插件接口、各提供方接口的契约和示例插件见开源仓库中的 `docs/providers.md`，源代码在开源仓库发布后提供。

## 下一步

- [技能](https://mirabase.io/zh/developers/skills.md)：官方技能和两个场景技能。
- [SDK](https://mirabase.io/zh/developers/sdks.md)：安装 SDK，了解错误类型和重试。
- [检索与上下文](https://mirabase.io/zh/developers/retrieval.md)：上下文包的预算、来源和反馈。
