返回结构化的工具结果并路由嵌套调用
给一个工具加一个输出 schema 和注解,并用 ctx.executeTool 运行其他工具,让同一个 tool_call 门也适用于嵌套调用。
一个会执行的工具返回数据也返回文本:给脚本的机器可读的 structuredContent,与供模型阅读的 content 并列。这个页面的工具用注解声明风险,并通过 ctx.executeTool() 相互运行,而那些嵌套调用与模型发出的调用一样,经过同一道 tool_call 门。下面的行为是通过一个真实会话已观察到的;模型是一个重放脚本的 faux provider。
运行它
非零退出是一个结果,不是一个失败的工具:tools.ts 里的 runCommand 捕获 exec 的拒绝,并把退出码作为数据返回。当结果是数据时,声明一个 outputSchema 并返回一个匹配的 structuredContent;下面的调用方从 outcome.result 读回那个值。注解是一个许可扩展能读到的提示——没有提示时,needsApproval 为 true(approval.ts):
pi.on("tool_call", async (event, ctx) => {
const hints = pi.getAllTools().find((tool) => tool.name === event.toolName)?.annotations;
const needsApproval =
hints?.destructiveHint === true ||
(!hints?.readOnlyHint && ((hints?.destructiveHint ?? true) || (hints?.openWorldHint ?? true)));
if (needsApproval && !(await ctx.ui.confirm("Allow tool call?", event.toolName))) {
return { block: true, reason: `${event.toolName} was not approved` };
}
});嵌套调用使用 ctx,即这个工具的第五个参数(tools.ts)。executeTool() 验证参数并经过 tool_call;它从不因工具失败而拒绝:
async execute(_id, _params, signal, onUpdate, ctx) {
const checks = await ctx.executeTool("run_checks", {}, { signal, onUpdate });
const tests = await ctx.executeTool("failing_tests", {}, { signal, onUpdate });预期结果
| 工具或钩子 | 来自 tools.test.ts 的断言 |
|---|---|
run_checks |
非零的命令退出是 isError: false,退出码在 details 里 |
failing_tests |
text reads 1 file(s) with failing tests;structuredContent 携带文件列表 |
review_diff |
isError: false;内容包含 src/auth/refresh.ts,来自 outcome.result.structuredContent |
spy tool_call |
sees review_diff, then run_checks, then failing_tests——嵌套调用经过同一道门 |
| approval | readOnlyHint: true is not asked about;一个没有提示的工具在没有 UI 时被阻止 |
| dynamic | a deferred tool is inactive until review_diff calls setActiveTools() |
| renderer | the registerToolRenderer extension loads and registers without error |
机制与局限
有文档记载: exposure 决定声明——direct 和 model-only 在注册时激活,而 codemode、deferred 和 hidden 等待 setActiveTools()。缺失的注解提示取 MCP 默认值(非只读、可能破坏、可能开放世界),所以一个未声明的工具会被当作危险的。一个数据结果把 outputSchema 与 structuredContent 配对;当你有数据并且有错误时返回 isError: true,没有数据时抛出。嵌套的 executeTool() 调用经过 tool_call / tool_result 处理器,且不添加转录记录条目。
已观察: tools.test.ts 通过一个真实的 AgentSession 断言上面每一行。侦察那一行是承重的:尽管模型只要了 review_diff,第 16 章的守卫也会看到 run_checks 和 failing_tests。
局限: 注解是未经核实的提示——没有任何东西检查一个假的 readOnlyHint——所以它们为一个守卫提供信息,而不是约束一次调用,而暴露方式、注解和渲染是三个独立的机制。registerToolRenderer() 出现在 1.0.1,并且必须返回一个 pi-tui Component,不是一个普通对象。faux 模型展示的是机制,不是一个真实模型的工具选择。
完整源码与测试 。
Understand this example
Copy this prompt into your AI tool. No code runs here.
Apply this example
Copy this prompt into your AI tool. No code runs here.