> **文档类型**:plan(阶段计划书)| **所属路线图**:[`README.md`](README.md) > **阶段**:P1 · 工具网关:把「能调通」变成「调不坏」 | **预估**:10–12 人日 | **本文件对应**:总方案 `../agent-platform-upgrade-plan.md` 的第 4.2 节 > **本阶段收编缺陷**:F-10、F-11、F-12、F-13、F-14、F-15、F-16、F-17、F-18、F-19、F-20、F-21、F-22(共 13 条,明细见文末附录) > 上一阶段:[`P0`](P0-运行时内核.md) | 下一阶段:[`P2`](P2-会话持久化.md) # 4.2 P1 · 工具网关:把"能调通"变成"调不坏" ## 目标 工具调用从"一次 try-call,失败即整轮失败"升级为**带 schema 校验、超时、指数退避、熔断、分级降级**的网关。这是面试官 A 第一个追问点("模型调工具报错、参数不符合 schema、下游超时,代码怎么做异常处理")的直接答案。 ## 当前问题 | 证据 | 问题 | |---|---| | `encodeTools` in `internal/infrastructure/ai/openai_client.go` | 所有工具只暴露一个 `query` 字符串参数,模型无法填结构化参数,也没有可校验的 schema(F-15) | | `(*MCPSSEClient).ListTools` in `internal/infrastructure/ai/mcp_sse_client.go` | `tools/list` 只取 name,丢弃 `description`/`inputSchema`(F-10) | | `(*Agent).executeToolCalls` in `internal/infrastructure/adk/adapter.go` | 任一工具失败 `return nil, err`,整轮终止(F-21) | | `tools.go` `normalizeTimeout` | 默认 300s,无单工具超时控制(F-22) | | `(*MCPSSEClient).callRPC` in `internal/infrastructure/ai/mcp_sse_client.go` | `pending` map 泄漏(F-11) | | `MCPToolRouter` in `internal/infrastructure/ai/mcp_sse_client.go` | Router 无锁(F-16) | | `ai/tools.go` 的 `SkillTool` | Skill 注册成工具但没有 `Invoke`,调用即空转;本阶段改为只注入 instruction(见 4.2.8) | | 全局 | 无重试、无熔断、无幂等、无结果大小限制 | ## 设计 ### 4.2.1 `ToolSpec`:工具的完整契约 ```go // internal/domain/tool/spec.go package tool type SideEffect string const ( EffectRead SideEffect = "read" // 可随意重试 EffectWrite SideEffect = "write" // 重试需幂等键 EffectDestructive SideEffect = "destructive" // 默认需人工确认 EffectExternal SideEffect = "external" // 外发(邮件/Webhook) ) type Spec struct { Name string // 全局唯一,`server.tool` 命名空间 Title string Description string // 必填,模型靠它选工具 InputSchema json.RawMessage // JSON Schema 2020-12,来自 MCP tools/list OutputSchema json.RawMessage // 可选,有则校验 SideEffect SideEffect Timeout time.Duration // 默认 30s Retry RetryPolicy Idempotency IdempotencyMode // none | key | natural Result ResultPolicy // 截断/摘要 Approval ApprovalPolicy // P6 使用,P1 仅占位 Visibility Visibility // model | human_only(P6 使用) Version string // 工具契约版本,用于缓存与审计 } type RetryPolicy struct { MaxAttempts int // 默认 3(含首次) BaseDelay time.Duration // 200ms MaxDelay time.Duration // 5s Multiplier float64 // 2.0 Jitter float64 // 0.2,full jitter RetryOn []ErrorClass // 默认 transient/rate_limited/timeout } type ResultPolicy struct { MaxBytes int // 默认 32768 MaxLines int // 默认 2000 Strategy string // truncate | head_tail | summarize(P7) } ``` ### 4.2.2 错误分类(重试与降级的前提) 统一 `Failure` 结构,贯穿 P0 运行时、P1 工具、P5 工作流: ```go // internal/domain/runtime/errors.go type ErrorClass string const ( ErrTransient ErrorClass = "transient" // 网络抖动、连接重置 ErrRateLimited ErrorClass = "rate_limited" // 429 / 限流 ErrTimeout ErrorClass = "timeout" // 单工具超时 ErrInvalidInput ErrorClass = "invalid_input" // 参数不符合 schema ErrNotFound ErrorClass = "not_found" // 资源不存在 ErrPermission ErrorClass = "permission" // 鉴权/策略拒绝 ErrUpstream ErrorClass = "upstream" // 下游 4xx(非 429) ErrSchema ErrorClass = "schema" // 返回结果不符合 OutputSchema ErrInternal ErrorClass = "internal" // 本地 bug ) type Failure struct { Class ErrorClass Code string // TOOL_TIMEOUT / TOOL_SCHEMA_INVALID / ... Message string ToolName string Attempt int Retryable bool Cause error } ``` | 错误类 | 典型来源 | 可重试 | 默认降级动作 | |---|---|---|---| | `transient` | 连接重置、EOF | ✅ | 指数退避重试 | | `rate_limited` | 429 | ✅(尊重 `Retry-After`) | 退避 + 限流排队 | | `timeout` | 单工具 deadline | ✅ | 重试 1 次后换备用工具 | | `invalid_input` | schema 校验失败 | ❌(但可让模型修参) | 回灌错误给模型修复重试 1 次 | | `not_found` | 404 / 空结果 | ❌ | 走备用工具 | | `permission` | 策略拒绝/401/403 | ❌ | 直接终止该工具,转人工或拒绝 | | `upstream` | 下游 400/500 非临时 | ⚠️ 仅 5xx | 熔断计数 | | `schema` | 返回体不符 OutputSchema | ❌ | 保留原始结果 + 标记 `_validation_warning` | | `internal` | 本地 panic/序列化 | ❌ | 终止该工具并告警 | ### 4.2.3 网关流水线(12 步,顺序即设计) ``` 调用请求 │ 1. Resolve 查注册表,取 Spec;未注册 → not_found(不再"静默失败") 2. Visibility 模型可见性检查(P6 生效,P1 恒 true) 3. ValidateArgs 按 InputSchema 校验 + 轻量类型纠正("5"→5) 4. SizeGuard 参数体积上限(默认 64KB) 5. Approval 需人工确认 → 挂起 Run(P6) 6. Breaker 熔断器状态检查(open → 直接走降级 L4) 7. RateLimit 每工具/每租户令牌桶 8. Invoke 带 per-call timeout 执行(ctx 派生) 9. ValidateResult 有 OutputSchema 则校验 10. Normalize 截断/head-tail/合并多段文本 11. Classify 错误归类为 Failure 12. Retry/Degrade 退避重试 → 降级阶梯 │ 调用结果(永不 panic,永不静默丢错) ``` ```go // internal/domain/tool/gateway.go type Invocation struct { RunID string SessionID string TenantID string UserID string ToolName string Args json.RawMessage IdempotencyKey string // sha256(run_id + tool + args) } type Result struct { Content string // 归一化后的文本,喂给模型的就是它 Raw json.RawMessage // 原始返回,落审计 Degraded bool // 是否走过降级阶梯(L4/L5) Attempts int } type Gateway interface { // Invoke 是模型工具调用的唯一出口:失败已归类为 Failure 并走完降级阶梯。 Invoke(ctx context.Context, inv Invocation) (Result, error) // Specs 返回当前可见的工具集(P1 返回全部,P6 按 Subject 过滤)。 Specs(ctx context.Context) []Spec } ``` `adk/tool_loop.go` 改造后不再直接调 `router.CallTool`,而是 `gw.Invoke(...)`——这是"所有工具来源收敛到一个出口"的落地形态。 ```go // internal/domain/tool/registry.go type Registration struct { Spec Spec Invoker func(ctx context.Context, args json.RawMessage) (string, error) } type Registry interface { Register(reg Registration) error // 同名返回 ErrDuplicateTool,不再静默成功 Get(name string) (Registration, bool) List() []Spec } ``` 三种工具来源(MCP / Skill / 内置 Go 函数)都只需产出 `Registration`,`Gateway` 不关心它从哪来。 ### 4.2.4 重试算法(面试可讲的细节) ```go func backoff(p RetryPolicy, attempt int, retryAfter time.Duration) time.Duration { if retryAfter > 0 { return min(retryAfter, p.MaxDelay) } // 尊重服务端 d := float64(p.BaseDelay) * math.Pow(p.Multiplier, float64(attempt-1)) if d > float64(p.MaxDelay) { d = float64(p.MaxDelay) } // full jitter:避免重试风暴同步 return time.Duration(rand.Float64() * d * (1 + p.Jitter)) } ``` 三条容易漏的工程细节: 1. **只对幂等操作重试**:`EffectRead` 直接重试;`EffectWrite` 必须带幂等键(`run_id + tool + sha256(args)`,Redis 存 24h),重放时返回缓存结果而不是再执行一次。 2. **重试要计入 Step 的 `Attempt` 与事件**(`tool.retry`),否则线上无法判断"慢"是网络还是下游。 3. **总耗时要受 Run 预算约束**:`attempt` 循环内每轮检查 `rc.Deadline()`,避免重试把 3 分钟预算吃光。 ### 4.2.5 降级阶梯(L0–L6) | 级别 | 动作 | 触发 | 用户感知 | |---|---|---|---| | L0 | **参数自愈**:把校验错误作为 tool 结果回灌,让模型改参重试(限 1 次) | `invalid_input` | 无感,多 1 次 LLM 调用 | | L1 | **退避重试** | `transient`/`rate_limited`/`timeout` | 无感,延迟增加 | | L2 | **熔断短路** | 滑动窗口 10 次失败 ≥5 | 立即失败,不再排队 | | L3 | **备用工具**(`fallback: [search_backup]`) | L1 耗尽 / `not_found` | 结果来源变化,需在结果里标注 | | L4 | **陈旧/缓存结果**(read-only,`stale-while-error`) | 熔断开 + 有缓存 | 结果标注 `stale: true` | | L5 | **结构化降级**:返回 `{"status":"unavailable","reason":"..."}` 给模型 | 以上皆失败 | 模型自行改计划(例如换关键词/跳过) | | L6 | **人工兜底**:写类/外发类不可降级 → 转审批队列,Run 挂起 | `permission` 或 `destructive` 失败 | 提示"已转人工处理" | **关键决策**:L5 之后 **run 不失败**,只有预算耗尽或显式致命错误才失败。这是"异常收敛"的核心——把工具故障转化为模型的输入,而不是系统的异常。 ### 4.2.6 MCP schema 透传(修复 F-10) ```go // ai/mcp_sse_client.go 改造 type ServerTool struct { Name string `json:"name"` Description string `json:"description"` InputSchema json.RawMessage `json:"inputSchema"` Annotations struct { SideEffect string `json:"sideEffectHint"` // 非标准字段,可选 } `json:"annotations"` } func (c *MCPSSEClient) ListTools(ctx context.Context) ([]ServerTool, error) ``` `RegisterAndExpand` 改用 `[]ServerTool`,注册为 `tool.Registration{Spec, Invoker}`;同名冲突返回错误而非 `nil`(修复 F-13);`pending` map 在 defer 中删除(修复 F-11);`MCPToolRouter` 加 `sync.RWMutex`(修复 F-16)。 同时修复 `encodeTools`: ```go // 现状:encodeTools in internal/infrastructure/ai/openai_client.go 让所有工具共用 {query: string} // 改为: func encodeTools(specs []tool.Spec) []map[string]any { out := make([]map[string]any, 0, len(specs)) for _, s := range specs { schema := s.InputSchema if len(schema) == 0 { schema = json.RawMessage(`{"type":"object","properties":{},"additionalProperties":false}`) } out = append(out, map[string]any{ "type": "function", "function": map[string]any{ "name": s.Name, "description": s.Description, "parameters": schema, "strict": true, // OpenAI 结构化输出约束 }, }) } return out } ``` ### 4.2.7 结果校验与规整 - 有 `OutputSchema` 且校验失败:**不丢弃结果**,保留原文并在 tool 消息上加 `{"_validation_warning": "..."}`,同时发 `tool.result` 事件带 `valid=false`。理由:线上工具常返回"多一个字段/少一个字段",直接判失败比容错更伤可用性。 - 截断策略:`head_tail`(保留前 24KB + 后 8KB,中间标注省略字节数),对日志/HTML 类结果体验最好。 - 大结果**标记为"可摘要"**:P7 接 LLM 摘要,P1 先只截断。 ### 4.2.8 Skill 的定位:本阶段只做 instruction 注入(已决策) **决策**:P1 阶段 `SKILL.md` 只作为**提示词侧的能力包**注入 system instruction,不注册为 function tool。"Skill 可被调用"这件事延后到 P6 沙箱就绪之后。 三条理由: 1. **Skill 的产物是方法论,不是函数**。`SKILL.md` 给的是步骤、判据与参考文档,没有稳定的输入/输出契约。当前 `SkillTool` 只暴露一个自由文本 `query`,模型"调用"它等于请求一段说明,却要付一次模型往返和一次工具调用预算——收益低于直接把正文放进上下文。 2. **现在根本没有执行面**。`SkillTool` 没有 `Invoke`,脚本与附件无人执行。把"看起来能调、实际调不出东西"的工具注册给模型,正是缺陷 F-14 指出的功能谎言;先删暴露面,才是诚实的降级。 3. **可调用 Skill 必须先有沙箱**。真正的 Skill 要跑脚本(生成 drawio、转 PDF、执行分析),只能落在 P6 的 `sandbox.Runner` 里。在沙箱之前实现,只能是宿主机 `exec.Command`——正好是 P6 要消除的风险面。 **P1 的落地方式**: | 动作 | 位置 | 说明 | |---|---|---| | 新增端口 | `internal/domain/skill/loader.go` | `Loader{Load(name string) (Skill, error)}`;`Skill{Name, Description, Instruction, Resources, Scripts}` | | 新增适配器 | `internal/infrastructure/skill/fs_loader.go` | 读 `SKILL.md`(YAML front matter + 正文),解析 `scripts/`、`resources/` | | 修改装配 | `armory/agent_node.go` | 构造 instruction 时把选中 Skill 的正文追加到 system prompt,带 `## 技能:` 分隔标题 | | 修改语义 | `ChatModelConfig.ToolSkillsList` | 字段名不变,含义从"注册成工具"改为"注入为技能";行为变更需 release note + 开关 `skills.mode: inject|expose`,默认 `inject` | | 保留不暴露 | `ai/tools.go` 的 `SkillTool` | 保留类型但**不注册**到模型可见工具集,`Visibility: human_only` 占位,`Invoke` 留给 P6 | 注入的正文计入 P4 的 token 预算(单个 Skill 正文建议 ≤ 4k token,超出截断并告警);同一 Skill 在一次 Run 内只注入一次,避免重复占用预算。 **P6 的升级路径(本阶段只预留接口)**: ```go // internal/domain/skill/exec.go(P6 引入) type Runner interface { Run(ctx context.Context, skill Skill, script string, args []string) (Result, error) } ``` `SKILL.md` 增加可选 front matter `scripts: [{name, entry, timeout}]`;P6 把每个 script 包装成 `tool.Spec{Name: "skill..