> ## Documentation Index
> Fetch the complete documentation index at: https://ahvn.top/llms.txt
> Use this file to discover all available pages before exploring further.

# HeavenBase MCP

> 将空的 HeavenBase 工作区暴露为 MCP，其余交给 agent：无需 schema、无需代码，只需数据。

<Note>
  *最好的画布，是空白的画布。*
</Note>

在本教程中，我们创建一个空的 HeavenBase 工作区，并将其暴露为 MCP 服务器。这样，任何使用 HeavenBase MCP 的 agent 都能把它当作数据平面与结构化记忆服务。由 agent 决定如何存储观察结果、存储什么、以及如何查询；MCP 服务器负责其余部分。

教程结束时，我们将运行一个玩具电商场景：agent 即时定义 Product、Customer、Order 实体，并通过日常操作维护数据库，例如添加商品、注册客户、记录订单。最后，agent 回答业务分析问题，例如「售价低于 \$100 的商品占比多少？」以及「根据 Alice 的订单历史，我该向她推荐什么？」

<br />

## 1. 创建空工作区

创建一个 Python 文件：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# serve_space.py
import heavenbase as hb

# If you've already run this tutorial once, this drops the existing workspace so you can start fresh.
# Remove this line if you want the workspace to persist across server restarts.
hb.HeavenBase("my-space", preset="debug").drop()

ws = hb.HeavenBase("my-space", preset="debug")

print(
    ws.to_mcp_json(
        name="my-space-mcp",
        profile="agent",
        transport="http",
        host="127.0.0.1",
        port=7001
    )
)

ws.serve(
    name="my-space-mcp",
    profile="agent",
    transport="http",
    host="127.0.0.1",
    port=7001
)
```

无需实体、字段或 schema。HeavenBase 的通用 MCP 工具会动态处理一切。

<Warning>
  `hb.HeavenBase("my-space", preset="debug").drop()` 会在服务器启动前清空演示工作区。教程需要可重复执行请保留此行；若希望工作区数据在服务器重启后仍保留，请删除该行。
</Warning>

`preset` 参数控制后端配置。`debug` 预设使用 SQLite 与内存存储，便于轻量、免 Docker 搭建。`local-lts` 预设使用本机 Postgres、LanceDB 与 Elasticsearch，更稳健且仍在本机运行。两种预设均支持完整 MCP 工具集：`debug` 侧重易用，`local-lts` 在更大数据量下性能更好。

`profile` 参数选择服务器暴露的工作区 MCP 工具集。HeavenBase 内置目前提供 `full`（可信管理流程）、`agent`（首日 schema 与数据工作）、`memory`（笔记式记忆）与 `memstate`（项目级记忆状态）。

本页使用 `profile="agent"`，因为 agent 可用其定义实体、检查 schema、upsert 行、patch 行、计数、查询并解释路由，同时省略批量操作、存在性检查与删除。

<br />

## 2. 运行

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
python serve_space.py
```

服务器会打印客户端配置并开始监听：

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "mcpServers": {
    "my-space-mcp": {
      "transport": "http",
      "url": "http://127.0.0.1:7001/mcp"
    }
  }
}
```

示例使用 `/mcp` 上的 Streamable HTTP。HeavenBase 支持常见 MCP 传输方式。每个服务器进程只使用一种传输，客户端连接对应端点：

| Transport       | Python serve call   | Client endpoint             |
| --------------- | ------------------- | --------------------------- |
| Streamable HTTP | `transport="http"`  | `http://127.0.0.1:7001/mcp` |
| SSE             | `transport="sse"`   | `http://127.0.0.1:7001/sse` |
| stdio           | `transport="stdio"` | command transport, no URL   |

在 Python 中，对 `ws.to_mcp_json(...)` 与 `ws.serve(...)` 传入相同 transport。例如，仅支持 SSE 的客户端需要 `/sse` 时，两处均使用 `transport="sse"`。

<Note>
  工作区 MCP 服务器绑定实时工作区对象。外部 agent 使用时请保持 `serve_space.py` 运行。与持久化的 Toolkit 注册表引用不同，空工作区 MCP 服务器是暴露该脚本所创建工作区的常驻进程。
</Note>

<br />

## 3. 连接你的 Agent

将服务器添加到你常用的编程 agent：

<Tabs>
  <Tab title="Claude Code">
    使用 Claude Code CLI 添加 HTTP 服务器：

    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    claude mcp add --transport http my-space-mcp http://127.0.0.1:7001/mcp
    claude mcp list
    ```

    Claude Code 将本地作用域 MCP 服务器保存在 `~/.claude.json`。若需在仓库内共享，在项目根目录用相同命令加 `--scope project`，或创建 `.mcp.json`：

    ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
    {
      "mcpServers": {
        "my-space-mcp": {
          "type": "http",
          "url": "http://127.0.0.1:7001/mcp"
        }
      }
    }
    ```

    开启新的 Claude Code 会话，运行 `/mcp`，在让 agent 使用算术工具前确认 `my-space-mcp` 已连接。
  </Tab>

  <Tab title="Codex">
    Codex 支持三种方式：CLI、配置文件与 GUI（Codex App 或 IDE 扩展）。

    GUI（Codex App）：Settings > MCP servers > + Add server，然后填写：

    * **Name:** `my-space-mcp`
    * Select **Streamable HTTP**
    * **URL:** `http://127.0.0.1:7001/mcp`

    Config file (`~/.codex/config.toml`):

    ```toml theme={"theme":{"light":"github-light","dark":"github-dark"}}
    [mcp_servers.my-space-mcp]
    url = "http://127.0.0.1:7001/mcp"
    ```

    CLI:

    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    codex mcp add my-space-mcp --url http://127.0.0.1:7001/mcp
    codex mcp list
    ```

    <Note>
      若添加 HTTP MCP 服务器后 Codex 构建仍不显示，请在 `~/.codex/config.toml` 中启用 `experimental_use_rmcp_client` 功能：

      ```toml theme={"theme":{"light":"github-light","dark":"github-dark"}}
      [features]
      experimental_use_rmcp_client = true
      ```
    </Note>

    开启新的 Codex 会话，或在 TUI 中运行 `/mcp`，确认 `my-space-mcp` 出现且已发现其工具。
  </Tab>

  <Tab title="Cursor">
    服务器仅属于一个仓库时用项目级配置，希望在所有项目中可用时用全局配置：

    * **Project:** `.cursor/mcp.json`
    * **Global:** `~/.cursor/mcp.json`

    粘贴以下配置：

    ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
    {
      "mcpServers": {
        "my-space-mcp": {
          "type": "http",
          "url": "http://127.0.0.1:7001/mcp"
        }
      }
    }
    ```

    也可打开 Cursor Settings > Features > MCP > Add new global MCP server，然后填写：

    * **Name:** `my-space-mcp`
    * **Type:** `http`
    * **URL:** `http://127.0.0.1:7001/mcp`

    重新加载 Cursor 或打开新对话，在 MCP 设置面板中确认 `my-space-mcp` 已启用。
  </Tab>

  <Tab title="VS Code / Copilot">
    按 `Ctrl+Shift+P`（Windows/Linux）或 `Cmd+Shift+P`（macOS），运行 **MCP: Add Server**，选择 **HTTP**，然后填写：

    * **URL:** `http://127.0.0.1:7001/mcp`
    * **Name:** `my-space-mcp`

    工作区级配置请添加 `.vscode/mcp.json`。VS Code 使用 `servers` 键，而非 `mcpServers`：

    ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
    {
      "servers": {
        "my-space-mcp": {
          "type": "http",
          "url": "http://127.0.0.1:7001/mcp"
        }
      }
    }
    ```

    重新加载 VS Code 窗口，或从命令面板运行 **MCP: List Servers**，确认 `my-space-mcp` 正在运行。
  </Tab>

  <Tab title="OpenCode">
    将远程 MCP 服务器添加到项目 `opencode.json` / `opencode.jsonc`，或全局配置 `~/.config/opencode/opencode.json`：

    ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
    {
      "$schema": "https://opencode.ai/config.json",
      "mcp": {
        "my-space-mcp": {
          "type": "remote",
          "url": "http://127.0.0.1:7001/mcp",
          "enabled": true
        }
      }
    }
    ```

    在 Windows 上，全局配置路径为 `%APPDATA%\opencode\config.jsonc`。重启 OpenCode 或运行 `opencode mcp list` 确认服务器可用，然后在提示中引用 `my-space-mcp`。
  </Tab>

  <Tab title="OpenClaw">
    在 `~/.openclaw/openclaw.json` 的 `mcp.servers` 下添加服务器：

    ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
    {
      "mcp": {
        "servers": {
          "my-space-mcp": {
            "url": "http://127.0.0.1:7001/mcp",
            "transport": "streamable-http"
          }
        }
      }
    }
    ```

    或用 CLI 写入相同条目：

    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    openclaw config set mcp.servers.my-space-mcp '{"url":"http://127.0.0.1:7001/mcp","transport":"streamable-http"}'
    openclaw mcp list
    ```

    OpenClaw 会热应用大部分 MCP 配置变更。若已有会话已加载工具，请开启新的 agent 会话。
  </Tab>

  <Tab title="Hermes">
    在 `~/.hermes/config.yaml` 中添加 HTTP 服务器：

    ```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
    mcp_servers:
      my-space-mcp:
        url: "http://127.0.0.1:7001/mcp"
        enabled: true
    ```

    保存文件后重新加载或重启 Hermes，然后让它列出可用 MCP 工具，确认算术工具已出现。
  </Tab>

  <Tab title="LM Studio">
    在 LM Studio 中打开 Program/Developer 面板，选择 **Install > Edit mcp.json** 并添加服务器。LM Studio 采用与 Cursor 相同的 `mcp.json` 写法：

    ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
    {
      "mcpServers": {
        "my-space-mcp": {
          "type": "http",
          "url": "http://127.0.0.1:7001/mcp"
        }
      }
    }
    ```

    保存文件，若 LM Studio 显示开关则启用服务器，并开启新对话且启用工具调用。
  </Tab>

  <Tab title="HeavenBase">
    HeavenBase 自带 LLM 聊天/会话界面，可用 `--mcp` 从注册表直接连接 MCP 服务器：

    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    hb llm chat --mcp quickstart.my-space-mcp "How many entities do I have now in the workspace?"
    hb llm session --mcp quickstart.my-space-mcp
    ```

    也可让 HeavenBase 指向正在运行的 HTTP MCP 端点：

    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    hb llm session --mcp http://127.0.0.1:7001/mcp
    ```

    在交互式会话中，用 `/mcp SOURCE` 添加另一个 MCP 源。
  </Tab>

  <Tab title="OpenAI Agents SDK">
    安装 SDK，以 Streamable HTTP 启动 HeavenBase 服务器，然后用 `MCPServerStreamableHttp` 连接：

    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    pip install openai-agents
    hb mcp serve quickstart.my-space-mcp --transport http
    ```

    ```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
    from agents import Agent, ModelSettings, OpenAIChatCompletionsModel, Runner
    from agents.mcp import MCPServerStreamableHttp

    import heavenbase as hb

    async with MCPServerStreamableHttp(
        name="my-space-mcp",
        params={"url": "http://127.0.0.1:7001/mcp"},
        cache_tools_list=True,
    ) as server:
        llm = hb.LLM(preset="chat")
        model_args = llm.to_args()
        model_name = model_args.pop("model")

        agent = Agent(
            name="MathAgent",
            instructions="Use the MCP math tools when they help.",
            model=OpenAIChatCompletionsModel(
                model=model_name,
                openai_client=llm.to_aclient(),
            ),
            model_settings=ModelSettings(**model_args),
            mcp_servers=[server],
            mcp_config={"include_server_in_tool_names": False},
        )

        result = await Runner.run(agent, "What's 42 * 73?")
        print(result.final_output)
    ```

    若你的 SDK 版本仅提供 `MCPServerSse`，请用 `hb mcp serve quickstart.my-space-mcp --transport sse` 启动 HeavenBase，并连接 `http://127.0.0.1:7001/sse`。
  </Tab>
</Tabs>

<br />

## 4. Agent Profile 与工作区 MCP 工具

本教程使用 `profile="agent"`，即 HeavenBase 面向首日工作区的默认 MCP 表面。它暴露一套经精选的 schema 与数据工具集，由 [Catalog](/zh/features/catalog) 与 MetaSchema 支撑：智能体 (Agent) 通过 schema 工具检查工作区结构，并通过 Catalog 感知的列举与描述发现具体行。

| Tool              | 能力说明                                                                           |
| ----------------- | ------------------------------------------------------------------------------ |
| `define_entity`   | 根据 JSON 兼容 schema 创建实体定义。写入描述字段、逻辑类型与路由的 MetaSchema 行。                         |
| `list_entities`   | 列出工作区中已注册的实体 id——智能体在定位具体数据前使用的 schema 侧目录。                                    |
| `describe_entity` | 从 MetaSchema 返回某一实体的字段、逻辑类型、路由计划与放置元数据。在智能体需要某一实体完整形态时，于 `list_entities` 之后使用。 |
| `upsert`          | 为某一实体插入或替换一行。成功的非系统写入会更新 Catalog 行，便于后续发现。                                     |
| `get`             | 按对象 ID 获取一行。                                                                   |
| `set`             | 修补一行并返回更新后的行。                                                                  |
| `count`           | 统计某一实体的行数。                                                                     |
| `query`           | 运行带过滤、投影、排序与限制的 JSON 查询 (Query)。                                               |
| `explain`         | 展示查询的路由与处理器计划。                                                                 |

`agent` profile 有意省略批量变更、批量读取、存在性检查与删除。仅在可信管理流程中使用 `profile="full"`。

保持面向模型的 profile 精简，并通过应用代码承载破坏性操作。同一工作区可暴露多个 MCP 工具集，每个使用不同 profile：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
workspace = hb.HeavenBase("support", preset="debug")
agent_tools = workspace.to_mcp(name="support-agent", profile="agent")
admin_tools = workspace.to_mcp(name="support-admin", profile="full")
memory = workspace.to_mcp(name="support-memory", profile="memory")
memstate = workspace.to_mcp(name="support-memstate", profile="memstate")
```

`agent` profile 足以让首日智能体定义 schema、写入与修补行、读取上下文、统计行数、查询并检查路由计划。`memory` profile 是五工具笔记表面（`remember`、`recall`、`search_memory`、`list_memory`、`set_memory`）。`memstate` profile 用于带版本的项目记忆（`memstate_*` 动词）。`full` profile 为可信代码路径增加批量操作、存在性检查与删除。启用可选 database 扩展时，HeavenBase 还提供 `database` profile，用于读/查询流程以及 `run_snippet` 与 `suggest_sql`。

<br />

## 5. 动手体验：玩具电商场景

按顺序将下方每条提示复制到 agent 对话中。每个代码块是一条可粘贴发送的消息。

<Steps>
  <Step title="设置工作区上下文">
    告诉 agent 使用哪个 MCP 服务器：

    ```text wrap theme={"theme":{"light":"github-light","dark":"github-dark"}}
    Use the `my-space-mcp` MCP for maintaining an e-commerce knowledgebase.
    ```

    开启新会话时，建议先粘贴此提示，以设定最小工作区上下文。
  </Step>

  <Step title="定义业务模型">
    请 agent 逐个创建核心实体：

    ```text wrap theme={"theme":{"light":"github-light","dark":"github-dark"}}
    Create a Product entity schema with name, price, category (textual), and availability (default to true).
    ```

    ```text wrap theme={"theme":{"light":"github-light","dark":"github-dark"}}
    Create a Customer entity schema with name, email, address (textual), profile (list of texts about the customer).
    ```

    ```text wrap theme={"theme":{"light":"github-light","dark":"github-dark"}}
    Create an Order entity schema with order_id, customer_id (reference), product_id (reference), quantity. One order row holds one product; use multiple rows when an order has multiple products.
    ```
  </Step>

  <Step title="日常运营">
    向工作区写入目录商品、客户与订单：

    ```text wrap theme={"theme":{"light":"github-light","dark":"github-dark"}}
    Add a product: "Ergonomic Keyboard" priced at $89.99 in category "electronics".
    ```

    ```text wrap theme={"theme":{"light":"github-light","dark":"github-dark"}}
    Add a product: "27-inch 4K Monitor" priced at $349.00 in category "electronics".
    ```

    ```text wrap theme={"theme":{"light":"github-light","dark":"github-dark"}}
    Add a product: "Bamboo Desk Organizer" priced at $24.50 in category "office".
    ```

    ```text wrap theme={"theme":{"light":"github-light","dark":"github-dark"}}
    Bob (bob@gmail.com, 456 Oak St) registered but hasn't ordered anything yet.
    ```

    ```text wrap theme={"theme":{"light":"github-light","dark":"github-dark"}}
    Bob searched for "chair" and didn't find anything.
    ```

    ```text wrap theme={"theme":{"light":"github-light","dark":"github-dark"}}
    Alice (alice@gmail.com, 123 Maple St) ordered 2 keyboards and 1 monitor.
    ```

    ```text wrap theme={"theme":{"light":"github-light","dark":"github-dark"}}
    Add a product: "Mesh Office Chair" priced at $199.99 in category "office".
    ```

    ```text wrap theme={"theme":{"light":"github-light","dark":"github-dark"}}
    Add a product: "Wooden Chair" priced at $39.99 in category "office".
    ```

    ```text wrap theme={"theme":{"light":"github-light","dark":"github-dark"}}
    Add a product: "Wireless Mouse" priced at $49.99 in category "electronics".
    ```

    ```text wrap theme={"theme":{"light":"github-light","dark":"github-dark"}}
    Update Bob's address to 789 Pine St.
    ```

    ```text wrap theme={"theme":{"light":"github-light","dark":"github-dark"}}
    Wood chair is out of stock.
    ```
  </Step>

  <Step title="分析问题">
    提出分析问题。每条提示下方为预期答案。

    ```text wrap theme={"theme":{"light":"github-light","dark":"github-dark"}}
    What percentage of products in my store cost less than $100?
    ```

    <Check>
      66.67% (4 out of 6 products)
    </Check>

    ```text wrap theme={"theme":{"light":"github-light","dark":"github-dark"}}
    List all products in the electronics category sorted by price ascending.
    ```

    <Check>
      Wireless Mouse (\$49.99), Ergonomic Keyboard (\$89.99), 27-inch 4K Monitor (\$349.00)
    </Check>

    ```text wrap theme={"theme":{"light":"github-light","dark":"github-dark"}}
    What's the best-selling product based on total quantity ordered?
    ```

    <Check>
      Ergonomic Keyboard (2)
    </Check>

    ```text wrap theme={"theme":{"light":"github-light","dark":"github-dark"}}
    How many active customers (at least one order) do I have?
    ```

    <Check>
      1 (Alice)
    </Check>

    ```text wrap theme={"theme":{"light":"github-light","dark":"github-dark"}}
    What products should I recommend to Alice and Bob based on their profiles and order history? Write a short recommendation pop-up for each of them.
    ```

    <Check>
      * Hi Alice — complete your desk setup
      * You already run a keyboard-and-monitor setup. Add a Wireless Mouse (\$49.99) for a matched input stack, and a Bamboo Desk Organizer (\$24.50) to tidy cables and accessories.
      * Suggested add-ons: Wireless Mouse · Bamboo Desk Organizer

      <br />

      * Hi Bob — we found chairs for you
      * You searched for a chair earlier. The Wooden Chair isn't available right now, but the Mesh Office Chair (\$199.99) is — ergonomic mesh for long sessions.
      * Suggested for you: Mesh Office Chair
    </Check>
  </Step>
</Steps>

现在你拥有供 agent 使用的持久、可查询、结构化记忆平面。这个电商玩具示例全程无需你编写任何 CRUD 函数或业务逻辑：agent 检查可用工具、即时定义实体、写入数据，并通过同一 MCP 接口运行查询。

<br />

## 进一步探索

<Tip>
  **相关资源：**

  * [首个 MCP](/zh/quickstart/first-mcp) - 通用 MCP 算术工具包演示
  * [30 分钟开发者工作坊：任务清单管理器](/zh/quickstart/sublinear-workshop) - 构建 Sublinear，一款 Agent 式任务清单管理器
  * [工作区](/zh/features/workspace) - 工作区生命周期与配置
  * [MCP 工具集 (Toolkit) 参考](/zh/reference/mcp-toolkit/overview) - 工作区 MCP 工具、profile 与 CLI
  * [后端](/zh/features/backends) - SQLite、PostgreSQL、MySQL 等
</Tip>

<br />
