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

# MCP 工具集 (Toolkit) 参考

> HeavenBase MCP 工具集 (Toolkit) 工具与 schema 的完整参考。

## 工具集 (Toolkit) API

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

toolkit = hb.Toolkit("math-tools", namespace="demo", version="1")
```

| Method                                                   | Purpose                                                                               |
| -------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| `Toolkit.add(item, name=...)`                            | 添加 callable、`Capsule` 或 `Tool`。                                                       |
| `Toolkit.tool(name=...)`                                 | 将函数添加到工具集 (Toolkit) 的装饰器。                                                             |
| `Toolkit.run(tool_name, **kwargs)`                       | 本地运行一个工具。                                                                             |
| `Toolkit.register(registry_config=..., on_conflict=...)` | 保存每个工具的主 Capsule 与 serializer Capsule，再存储工具集 (Toolkit) manifest。默认为 `overwrite=True`。 |
| `Toolkit.run_to_str(tool_name, **kwargs)`                | 运行一个工具并通过 serializer Capsule 返回序列化字符串。                                                |
| `Toolkit.load(..., registry_config=...)`                 | 按 id 或 namespace/name/version 从注册表记录加载工具集 (Toolkit)。                                  |
| `Toolkit.to_fastmcp()`                                   | 构建进程内 FastMCP 服务器。                                                                    |
| `Toolkit.from_fastmcp(server, name=...)`                 | 将 FastMCP 服务器导入为工具集 (Toolkit) 客户端。                                                    |
| `Toolkit.to_mcp_json(...)`                               | 返回 MCP 客户端配置 JSON。                                                                    |
| `Toolkit.serve(...)`                                     | 运行 FastMCP 服务器。                                                                       |
| `Toolkit.to_anthropic_tools(...)`                        | 导出带 `allowed_callers` 的 programmatic tool 定义。                                         |

## Capsule API

| Method                                   | Purpose                                    |          |                |                                           |
| ---------------------------------------- | ------------------------------------------ | -------- | -------------- | ----------------------------------------- |
| `Capsule.from_func(func, ...)`           | 将 callable 捕获为 Capsule manifest。           |          |                |                                           |
| `capsule.register(registry_config=...)`  | 在默认或配置的注册表中存储 Capsule。                     |          |                |                                           |
| `Capsule.load(..., registry_config=...)` | 按 id 或 namespace/name/version 加载。          |          |                |                                           |
| `capsule.to_func()`                      | 用 source、import path、再受信任二进制回退恢复 callable。 |          |                |                                           |
| `capsule.run(**kwargs)`                  | 恢复并调用函数。                                   |          |                |                                           |
| `capsule(*args, **kwargs)`               | 像被包装的 Python 函数一样调用 Capsule。               |          |                |                                           |
| \`capsule.to\_str("json"                 | "yaml"                                     | "source" | "docstring")\` | 将 Capsule manifest 或 callable 元数据转换为文本表示。 |
| `Capsule.from_str(text, format="json")`  | 从 JSON 或 YAML manifest 字符串恢复 Capsule。      |          |                |                                           |

## CLI

| Command                            | Purpose                                               |
| ---------------------------------- | ----------------------------------------------------- |
| `hb setup`                         | 初始化全局 HeavenBase 配置、默认工作区与 Capsule/工具集 (Toolkit) 注册表。 |
| `hb mcp list`                      | 列出已注册工具集 (Toolkit)。                                   |
| `hb mcp capsules`                  | 列出已注册 Capsule。                                        |
| `hb mcp show REF`                  | 显示一条工具集 (Toolkit) 记录。                                 |
| `hb mcp tools REF`                 | 列出工具集 (Toolkit) 中的工具。                                 |
| `hb mcp call REF TOOL --args JSON` | 从控制台调用一个工具。                                           |
| `hb mcp mcp-json REF`              | 打印 MCP 客户端配置 JSON。                                    |
| `hb mcp serve REF`                 | 将工具集 (Toolkit) 作为 MCP 提供。                             |
| `hb mcp remove REF`                | 对工具集 (Toolkit) 注册表行做 tombstone。                       |

## Callable 序列化

内部 callable 序列化位于 `heavenbase.extensions.system.capsule.serialize`：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from heavenbase.extensions.system.capsule.serialize import CallableSerialization

payload = CallableSerialization.from_func(add, include_cloudpickle=False).to_dict()
capsule = CallableSerialization.from_dict(payload).to_capsule()
```

通用 JSON 序列化对 callable 使用相同策略；无法捕获的 callable 回退为轻量引用。

## 注册表与元数据实体

Capsule 与工具集 (Toolkit) 作为必需 `system` 扩展拥有的系统实体持久化：

| Entity id     | Contents                                                           |
| ------------- | ------------------------------------------------------------------ |
| `sys-capsule` | 活跃 Capsule manifest 行，含身份、manifest 载荷、能力、指纹，以及覆盖时的 `last_reason`。  |
| `sys-toolkit` | 活跃工具集 (Toolkit) manifest，每个工具有序的主 Capsule 与 serializer Capsule 引用。 |

工作区还会将 `mcp_profile`、`mcp_serializer`、`toolkit_family`、`storage_profile`、`sql_dialect` 与 `database_dialect` 元数据镜像到 `sys-metaschema` 行。

## 工作区 MCP 工具

`workspace.to_mcp(...)` 与 `workspace.serve(...)` 会组装已注册的工具集 family，并暴露这些核心工作区工具：

| Tool              | Purpose                                  |
| ----------------- | ---------------------------------------- |
| `define_entity`   | 从 JSON 创建新实体 (Entity) 定义。                |
| `list_entities`   | 列出已注册实体 id。                              |
| `describe_entity` | 返回一个实体定义与路由 (Routing) 计划。                |
| `upsert`          | 插入或替换一行。                                 |
| `upsert_many`     | 插入或替换多行并按输入顺序返回 id。                      |
| `get`             | 按 id 获取一行。                               |
| `get_many`        | 按 id 顺序获取多行。                             |
| `set`             | 应用一行补丁。                                  |
| `set_many`        | 应用多行补丁并按输入顺序返回 id。                       |
| `delete`          | 删除一个目标。                                  |
| `delete_many`     | 按输入顺序删除多个目标。                             |
| `exists`          | 检查一个 id。                                 |
| `exists_many`     | 按输入顺序检查多个 id。                            |
| `count`           | 统计一种实体类型的行数。                             |
| `query`           | 执行 JSON 查询 (Query) spec。                 |
| `explain`         | 解释 JSON 查询 (Query) 的路由与处理器 (Handler) 选择。 |

HeavenBase 尚未暴露通用 MCP `alter_entity` 或 `undefine_entity` 工具，因为在智能体 (Agent) 能安全变更或删除实体定义之前，实体迁移、物理清理、目录 (Catalog) 更新与恢复语义必须显式化。

## 工作区 MCP profile

MCP 暴露使用声明式 `ProfileSpec` 对象（配置位于 `heavenbase.mcp.profiles.<name>` 或 `hb.ext.register_profile`）。Profile 组合工具组、工具集 family（`WorkspaceToolkitFamilySpec`）、实体/Skill 范围与已注册 serializer。

| Profile    | Tools                                                           | Serializer | Owner                      |
| ---------- | --------------------------------------------------------------- | ---------- | -------------------------- |
| `full`     | 全部工作区工具                                                         | `jstr`     | system toolkit             |
| `agent`    | 精选 inspect/read/write/query 面，外加可选 `list_skills` / `read_skill` | `markdown` | system + `agent` extension |
| `memory`   | `remember`、`recall`、`search_memory`、`list_memory`、`set_memory`  | `jstr`     | `memory` extension         |
| `memstate` | `memstate_*` 动词                                                 | `jstr`     | `memory` extension         |
| `database` | read/query 组外加 `run_snippet`、`suggest_sql`                      | `jstr`     | `database` extension       |

Profile、serializer 与 family spec 会镜像到 `sys-metaschema` 并按工作区重新加载；可选扩展 family 在首次使用时自动启用其扩展。

简单 memory 工作流：`remember` 记摘要或决策，`recall`/`list_memory` 精确检索与浏览，`search_memory` 模糊查找，`set_memory` 精确键修正。

Memstate 风格 memory 工作流使用 `profile="memstate"`。它将键前缀为 `project.<project_id>.<keypath>`，用 `memstate_get` 返回当前行，为 `memstate_history` 保留先前版本，写入时报告冲突的前值，用 `memstate_delete` 创建 tombstone。

## 提供选项

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
workspace.serve(
    name="notes",
    transport="http",
    host="127.0.0.1",
    port=7001,
    wait=True,
)
```

默认位于 `heavenbase.mcp`：

| Config key                 | Default     |
| -------------------------- | ----------- |
| `heavenbase.mcp.transport` | `http`      |
| `heavenbase.mcp.host`      | `127.0.0.1` |
| `heavenbase.mcp.port`      | `7001`      |
| `heavenbase.mcp.wait`      | `true`      |

## 健康检查

用 FastMCP 客户端验证服务器能否列出并调用工具：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from fastmcp import Client

server = toolkit.to_fastmcp()

async with Client(server) as client:
    tools = await client.list_tools()
    result = await client.call_tool("add", {"left": 2, "right": 3})
```

`result.structured_content` 在标量 Python 返回值下于 `result` 键包含工具返回值。

## Anthropic programmatic tools

Anthropic programmatic tool calling 是与 MCP connector tools 独立的导出路径：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
tool_defs = toolkit.to_anthropic_tools(allowed_callers=["code_execution"])
```

每条定义包含 `allowed_callers`、`name`、`description` 与 `input_schema`。从 code execution 调用时，工具执行适配器应返回字符串。

## 相关页面

* [Capsules](/features/capsules)
* [Toolkits](/features/toolkits)
* [HeavenBase MCP](/zh/quickstart/heavenbase-mcp)
* [首个 MCP](/zh/quickstart/first-mcp)

<br />
