> For AI agents: the complete documentation index is available at /apps-plugin/docs/llms.txt, the full documentation bundle is available at /apps-plugin/docs/llms-full.txt.

# 端工具（Client Tool）开发

端工具把端侧可执行的能力暴露给 Agent。Agent 根据用户意图选择工具，宿主调用对应 handler，handler 返回真实执行结果。适合端侧计算、读取应用存储或调用公开宿主 API；需要服务端凭证的业务仍放在 Server Tool 中。

端工具没有界面，不等同于 Page 中的点击回调，也不能直接读取另一个 Page 的 React state。需要 Agent 改变已打开页面时，使用[全页事件](/apps-plugin/docs/frontend-development/full-page.md#响应-agent-事件)。

## 接入所需文件

| 文件                            | 职责                                         |
| ----------------------------- | ------------------------------------------ |
| 项目根目录 `tools.json`            | 工具名称、描述、输入输出 schema、执行类型与可选卡片绑定；支持端工具与远程工具 |
| `src/app.config.ts` 的 `tools` | 把端工具名称映射到源码入口                              |
| `src/tools/<name>/index.ts`   | 默认导出的 handler 函数                           |
| `skill/<domain>/SKILL.md`     | 说明何时调用工具、参数来源及失败处理                         |

`tools.json` 中写 `tool_type: "client"`，才表示端工具；省略该字段时当前构建转换按 `server` 处理。声明工具不会自动实现 handler，只有源码文件也不能代替 Agent 可见的工具声明。

## JSB 调用限制

端工具在独立的 ToolRuntime 中执行，可调用的 JSB 受白名单限制。当前 Android 和 iOS 允许以下业务 JSB；表中名称是宿主方法名，业务仍通过 `@doubao-dev/framework/api` 中对应的公开 API 调用。

| 类别      | 允许的 JSB                                                                                                      |
| ------- | ------------------------------------------------------------------------------------------------------------ |
| 账号与登录   | `doubao.getAccountInfo`、`doubao.login`                                                                       |
| 设置与授权状态 | `doubao.getSetting`、`doubao.getAppAuthorizeSetting`、`doubao.getSystemSetting`                                |
| 系统与设备   | `doubao.getSystemInfo`、`doubao.getDeviceInfo`                                                                |
| 网络与定位   | `doubao.request`、`doubao.getLocation`                                                                        |
| 埋点      | `doubao.reportEvent`                                                                                         |
| 存储      | `doubao.setStorage`、`doubao.getStorage`、`doubao.removeStorage`、`doubao.clearStorage`、`doubao.getStorageInfo` |

工具结果回传由 Framework 处理，业务只需返回符合协议的结果对象。

不在白名单中的 JSB 会被拒绝，包括 `navigateTo`、`redirectTo`、`reLaunch`、`navigateBack`、`openPage` 等路由能力。SDK 导出了某个 API，或该 API 能在 Page / Widget 中使用，不代表它能在端工具中调用；需要页面跳转时，应在支持该路由能力的 Page / Widget 交互中完成。

白名单放行也不代表调用必然成功：仍需满足接口权限、用户授权、宿主支持和限流等条件。在 `tools.json` 中声明 `permissions` 不能扩大端工具的 JSB 白名单；业务需要处理实际调用失败。

## 实现一个最小端工具

以下示例在端侧计算整数分金额。它只演示计算，不会创建订单或扣款。前提是已有可运行的应用插件项目和 `src/app.ts`。

### 声明工具

在项目根目录 `tools.json` 中加入：

```json
{
  "tools": [
    {
      "name": "calculate_total",
      "description": "Calculate an amount in integer cents when the user explicitly provides unit price and quantity. Does not create orders or charge money.",
      "tool_type": "client",
      "inputSchema": {
        "type": "object",
        "properties": {
          "unit_price_cents": { "type": "integer", "description": "Non-negative unit price in cents" },
          "quantity": { "type": "integer", "description": "Positive item count" }
        },
        "required": ["unit_price_cents", "quantity"]
      },
      "outputSchema": {
        "type": "object",
        "properties": {
          "total_cents": { "type": "integer" }
        },
        "required": ["total_cents"]
      }
    }
  ]
}
```

`inputSchema` 和 `outputSchema` 本身都必须是 JSON 对象。这里 `outputSchema.type` 为 `object`；绑定卡片时则需要描述对象数组，见下文。Schema 描述不替代 handler 的运行时校验。

字段说明：

| 字段                             | 格式与用途                        |
| ------------------------------ | ---------------------------- |
| `tools`                        | 根对象中的非空工具数组，工具名称不能重复         |
| `name` / `description`         | 工具的稳定名称和能力描述                 |
| `tool_type`                    | `client` 为端工具，`server` 为远程工具 |
| `inputSchema` / `outputSchema` | JSON 对象，分别描述输入参数和结构化结果       |
| `permissions`                  | 可选的权限 scope 字符串数组            |
| `_meta.ui`                     | 可选的卡片绑定与过期策略，见下文             |

这里使用的是平台支持的 JSON Schema 子集，不支持 `enum`、数值上下界（`minimum` / `maximum`，即 min/max）等校验能力。不要在 schema 中添加这些约束；将可选值和取值范围写入字段 `description`，并在业务代码中校验。此限制同时适用于 `tools.json` 的 `inputSchema`、`outputSchema` 和 `events.json` 的 `payloadSchema`。

### 注册入口

将以下 `tools` 配置合入已有 `src/app.config.ts`，保留现有 Page / Widget 配置：

```ts
import { defineAppConfig } from '@doubao-dev/framework/config';

export default defineAppConfig({
  appId: 'your-app-id',
  name: 'Amount Calculator',
  tools: [{ entry: 'tools/calculate-total/index', name: 'calculate_total' }]
});
```

`entry` 相对于 `src/`，不写 `.ts` 后缀。显式 `name` 必须与 `tools.json` 的 `name` 一致；省略 `name` 时默认使用入口目录名。仅靠扫描 `src/tools/` 不能替代 `app.config.ts.tools` 注册。

### 编写 handler

创建 `src/tools/calculate-total/index.ts`：

```ts
export default function calculateTotal(input: Record<string, unknown>) {
  const { unit_price_cents: unitPrice, quantity } = input;
  if (
    typeof unitPrice !== 'number' ||
    !Number.isSafeInteger(unitPrice) ||
    unitPrice < 0 ||
    typeof quantity !== 'number' ||
    !Number.isSafeInteger(quantity) ||
    quantity <= 0
  ) {
    return {
      isError: true,
      content: [
        { type: 'text', text: 'Provide a non-negative integer price and a positive integer quantity.' }
      ]
    };
  }

  // Integer cents avoid fractional currency rounding; reject unsafe totals before returning a result.
  const total = unitPrice * quantity;
  if (!Number.isSafeInteger(total)) {
    return { isError: true, content: [{ type: 'text', text: 'The total exceeds the supported range.' }] };
  }

  return {
    content: [{ type: 'text', text: `Total: ${total} cents. No order was placed.` }],
    structuredContent: { total_cents: total }
  };
}
```

handler 接收已经解析的对象，不需要 `JSON.parse(input)`；可以返回结果对象或 Promise。端工具使用默认导出的函数。

当前返回值必须包含 `content` 数组，其中每个块为 `{ type: 'text', text: string }`；`structuredContent` 可为对象或对象数组。预期的业务失败可以返回 `isError: true` 和可恢复的文本说明；抛错或返回不合法结果会作为调用失败反馈。不要返回一个字符串代替整个结果对象。

## 可选：让工具结果展示为卡片

在最小例子通过后再接入卡片。需要同时修改三个位置：

1. 在 `app.config.ts.widgets` 注册 Widget，使用稳定 `id`，例如 `AmountCard`；需要 Web 预览时设置 `web: true`。
2. 在该工具声明中加入 `_meta: { "ui": { "widgetId": "AmountCard" } }`，把 `outputSchema` 改为下列对象数组 schema。
3. 把成功返回的 `structuredContent` 改为对应实体数组；错误分支仍返回 `isError: true`，不伪造成功实体。

```json
{
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "calculation_id": { "type": "string", "x-db-is-entity-id": true },
      "total_cents": { "type": "integer" }
    },
    "required": ["calculation_id", "total_cents"]
  }
}
```

成功结果中的数组可写为：

```ts
structuredContent: [{ calculation_id: `${unitPrice}:${quantity}`, total_cents: total }];
```

这里用计算输入组成演示标识；真实业务应使用领域内稳定的实体 ID。Widget 按单个实体读取 View Data，例如 `useViewData<{ calculation_id: string; total_cents: number }>()`。Widget 入口和完整实现方式见[卡片开发](/apps-plugin/docs/frontend-development/widget.md)。

| 字段                                           | 使用约束                                               |
| -------------------------------------------- | -------------------------------------------------- |
| `_meta.ui.widgetId`                          | 与注册的 Widget ID 一致，不使用源码路径或 `widgetPath`            |
| `x-db-is-entity-id`                          | 卡片实体的顶层字段中必须且只能有一个标记为 `true`                       |
| `x-db-is-refresh-key`                        | 标记实体刷新键；使用 `same_conversation` 时必须且只能标记同一个实体 ID 字段 |
| `_meta.ui.expirePolicy: "same_conversation"` | 配合 Widget 和刷新键声明会话内过期策略；连续调用时验证旧卡与新卡表现             |
| `x-db-llm-modifiable`                        | 用于输出数组字段，允许模型从真实结果中筛选；不能用它授权编造结果                   |
| `permissions`                                | 工具所需 scope 的声明；不能代替宿主授权流程或用户同意                     |

不要在 schema 中声明保留字段 `entity_type`。当前运行时为成功返回的实体数组补充 `entity_type: <tool name>`，构建工具生成对应的实体和卡片绑定配置。

## 验证与排障

| 用例                                                | 预期结果                                    |
| ------------------------------------------------- | --------------------------------------- |
| 工具面板直接输入 `{"unit_price_cents":1250,"quantity":3}` | 真实执行 handler，返回 `3750`；不需要 Agent 决定是否调用 |
| 对话请求同一计算                                          | Agent Trace 中工具名和参数一致，结果来自本次调用          |
| 直接输入数量 `0`                                        | 返回业务错误，不产生成功实体或成功卡片                     |
| 对话只给单价，不给数量                                       | Skill 引导 Agent 追问，不猜数量                  |
| 使用会话内卡片过期策略连续调用                                   | 新卡数据正确，旧卡按声明的策略处理                       |

找不到工具时，检查 `tool_type`、`tools.json.name`、`app.config.ts.tools[].name` 和入口文件；提示 handler 必须为函数时检查默认导出；提示 MCP result 不合法时检查 `content` 和 `structuredContent`。Web 工具调试的入口、结果面板和真机验收边界见[本地调试与预览](/apps-plugin/docs/development-tools/local-debugging.md)。

运行时隔离、输入解析与错误处理的完整说明见[端工具、事件与页面上下文](/apps-plugin/docs/client-framework/agent-interaction.md)。
