第 64 章:工具的路由与调度

卷五协议验证日期:2026-05-17,基于 Agent 工具编排架构
单个 Agent 只有一套工具。当工具有几十个、来源各异(内置、MCP、子 Agent),就需要路由和调度。
路线图
1 | graph LR |
工具来源的三层架构
1 | graph TD |
实现 ToolRouter
1 | // → src/my-agent/tools/router.ts |
并行工具调度
当模型同时请求多个工具调用时,判断哪些可以并行:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47// → src/my-agent/tools/scheduler.ts
export class ParallelScheduler {
constructor(private router: ToolRouter) {}
async executeAll(toolCalls: ToolUseBlock[]): Promise<ToolResultBlock[]> {
// 分析依赖——如果两个工具操作同一文件,必须串行
const groups = this.partitionIntoGroups(toolCalls);
const results: ToolResultBlock[] = [];
for (const group of groups) {
if (group.length === 1) {
// 单个工具直接执行
results.push(await this.router.execute(group[0]));
} else {
// 组内并行执行
const groupResults = await Promise.all(
group.map(tc => this.router.execute(tc))
);
results.push(...groupResults);
}
}
return results;
}
private partitionIntoGroups(toolCalls: ToolUseBlock[]): ToolUseBlock[][] {
// 简化:检测读/写冲突
const groups: ToolUseBlock[][] = [];
let current: ToolUseBlock[] = [];
for (const tc of toolCalls) {
const descriptor = this.router.getDescriptor(tc.name);
if (descriptor?.readOnly) {
current.push(tc); // 只读工具可以并行
} else {
if (current.length > 0) {
groups.push(current);
current = [];
}
groups.push([tc]); // 写操作单独执行
}
}
if (current.length > 0) groups.push(current);
return groups;
}
}
子 Agent 调度
1 | // → src/my-agent/subagent/spawner.ts |
工具注册示例
1 | // → src/my-agent/tools/registry-example.ts |
试试看
任务 1:注册三个 MCP Server,让 Agent 同时使用它们的工具。验证工具前缀(mcp__)不冲突。
任务 2:实现工具执行的超时和重试——一个工具超时后,自动重试一次。
任务 3:创建两个子 Agent——一个搜索代码,一个审查代码——让它们并行工作并汇总结果。
常见错误
| 现象 | 原因 | 解法 |
|---|---|---|
| 工具名冲突 | 两个来源的工具同名 | 用前缀区分(mcp__, agent__) |
| 子 Agent 用错模型 | 默认用了主 Agent 的模型 | 显式指定子 Agent 用小模型 |
| 递归创建子 Agent | 子 Agent 又创建子 Agent | 设置 maxDepth 上限 |
| 并行执行写冲突 | 两个工具同时写同一文件 | 依赖检测 + 串行化 |
检查点
- 理解了工具来源的三层架构(内置/MCP/子Agent)
- 实现了 ToolRouter(前缀、注册、路由执行)
- 实现了 ParallelScheduler(依赖检测、分组执行)
- 实现了 SubAgentSpawner(深度限制、独立循环)
- 能注册混合来源的 10+ 个工具