- 方案第 4 章 P0-P8 拆为 9 份独立阶段计划书,原文件只保留索引与横切章节 - 《项目完善报告》《评审与收编清单》内容拆入各阶段计划书后删除 - 统一缺陷台账 F-01…F-76(历史 71 条 + 方案补充 5 条),保留历史编号对照 - 新增 README 作为路线图索引:阶段清单、执行顺序、第 0 天清扫、台账、迭代约定
683 lines
35 KiB
Markdown
683 lines
35 KiB
Markdown
> **文档类型**: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,带 `## 技能:<name>` 分隔标题 |
|
||
| 修改语义 | `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.<skill>.<script>"}` 走同一个 Gateway,执行体是 `sandbox.Runner`。这样"所有工具来源统一收敛到 `tool.Spec`"的架构目标在 P6 闭环,而不需要 P1 先造半成品。
|
||
|
||
**回滚**:`skills.mode=expose` 时恢复旧行为(把 Skill 注册为工具),用于对比与紧急回退;P6 完成后移除该开关。
|
||
|
||
## 涉及的代码模块
|
||
|
||
| 类型 | 文件 | 改动要点 |
|
||
|---|---|---|
|
||
| 新增 | `internal/domain/tool/spec.go` | Spec/RetryPolicy/ResultPolicy |
|
||
| 新增 | `internal/domain/tool/gateway.go` | Gateway 接口 + 12 步流水线编排 |
|
||
| 新增 | `internal/domain/tool/registry.go` | 注册表、命名空间、版本 |
|
||
| 新增 | `internal/domain/tool/errors.go` | 错误归类(`Classify`) |
|
||
| 新增 | `internal/domain/tool/ports.go` | Invoker/Result/SchemaValidator |
|
||
| 新增 | `internal/infrastructure/tool/schema.go` | JSON Schema 校验(`santhosh-tekuri/jsonschema/v6`) |
|
||
| 新增 | `internal/infrastructure/tool/retry.go` | backoff + 幂等键 |
|
||
| 新增 | `internal/infrastructure/tool/breaker.go` | 滑动窗口熔断 |
|
||
| 新增 | `internal/infrastructure/tool/ratelimit.go` | 令牌桶(本地 + Redis) |
|
||
| 新增 | `internal/infrastructure/tool/degrade.go` | 降级阶梯 L3–L5 |
|
||
| 新增 | `internal/infrastructure/tool/truncate.go` | head_tail 截断 |
|
||
| 新增 | `internal/infrastructure/tool/mcp_adapter.go` | MCP ServerTool → Spec |
|
||
| 修改 | `internal/infrastructure/ai/mcp_sse_client.go` | schema 透传、pending 泄漏、加锁、错误而非 nil |
|
||
| 修改 | `internal/infrastructure/ai/tools.go` | `SkillTool` 不注册为 function tool(见 4.2.8);新增 `SkillSpec` 描述;stdio/local 注册 Spec |
|
||
| 新增 | `internal/domain/skill/loader.go`、`internal/infrastructure/skill/fs_loader.go` | Skill 加载与 instruction 注入 |
|
||
| 修改 | `internal/infrastructure/ai/openai_client.go` | `encodeTools` 用真实 schema |
|
||
| 修改 | `internal/infrastructure/ai/eino_adapter.go` | `toolDefs` 改为从 Registry 取 Spec |
|
||
| 修改 | `internal/infrastructure/adk/tool_loop.go` | 失败不再中断 run,改为 tool 消息 `is_error` |
|
||
| 修改 | `internal/domain/agent/model/config.go` | Tool 配置扩展(timeout/retry/fallback/effect) |
|
||
| 修改 | `internal/app/bootstrap/bootstrap.go` | 装配 Registry + Gateway |
|
||
| 修改 | `configs/agent/*.yaml` | 显式声明工具策略(示例见下) |
|
||
|
||
## 配置示例
|
||
|
||
```yaml
|
||
# configs/application.yaml 新增
|
||
tool-defaults:
|
||
timeout: 30s
|
||
retry:
|
||
max-attempts: 3
|
||
base-delay: 200ms
|
||
max-delay: 5s
|
||
multiplier: 2
|
||
jitter: 0.2
|
||
result:
|
||
max-bytes: 32768
|
||
strategy: head_tail
|
||
circuit-breaker:
|
||
window: 10
|
||
failure-threshold: 5
|
||
open-for: 30s
|
||
|
||
# configs/agent/xxx.yaml 单个工具覆盖
|
||
tools:
|
||
- name: baidu-search.search
|
||
timeout: 8s
|
||
effect: read
|
||
fallback: [echoLocalTool]
|
||
retry: {max-attempts: 2}
|
||
- name: crm.updateOrder
|
||
effect: write
|
||
idempotency: key
|
||
approval: required # P6 生效
|
||
```
|
||
|
||
## 验收标准
|
||
|
||
1. **故障注入测试集 ≥ 15 个场景**(超时、429、5xx、连接重置、坏 JSON、schema 不符、空结果、超大结果、重复注册、并发注册),全部断言:run **不失败**、错误被归类、降级动作符合预期。
|
||
2. 失败注入 30% 时,任务成功率从当前 ~70% 提升到 **≥ 95%**(同一评测集)。
|
||
3. 重试间隔符合退避公式(测试用 mock clock,断言 200/400/800ms ± jitter)。
|
||
4. 写类工具重放同一幂等键,实际执行次数 = 1。
|
||
5. 熔断:连续 5 次失败后 30s 内直接快速失败(P99 延迟从 30s 降到 < 5ms)。
|
||
6. 工具描述与 schema 100% 透传到模型(抓包断言 `parameters.properties` 非空)。
|
||
7. `go test -race` 通过,Router 无 data race。
|
||
8. **Skill 只注入不暴露**:抓包断言 `tools` 数组不含 `skill_*`;system prompt 含 `SKILL.md` 正文与 `## 技能:` 标题;`skills.mode=expose` 时回到旧行为(回滚开关可用)。
|
||
|
||
## 测试策略
|
||
|
||
- `internal/infrastructure/tool/testdata/` 下用 `httptest` 起**可编程 SSE MCP Server**(按脚本返回失败/延迟/坏 schema)。
|
||
- 单测覆盖:`backoff` 表驱动、`Classify` 表驱动、截断边界(0B/32KB/1MB)、幂等键碰撞。
|
||
- 集成测试:真实 MCP(baidu-search)跑 10 次,记录成功率与 p95。
|
||
- 混沌:在 CI 中把注入概率设为 0.3 跑评测集,失败则阻断合并。
|
||
|
||
## 风险与回滚
|
||
|
||
| 风险 | 缓解 |
|
||
|---|---|
|
||
| 真实 MCP 返回的 schema 不规范(draft-04/缺 type) | 校验前做 schema 归一化;校验失败按 `schema` 类处理并降级,不阻断 |
|
||
| 重试放大下游压力 | 默认仅 3 次 + 全抖动;熔断 + 令牌桶双限流 |
|
||
| 参数"自愈"让模型陷入改参循环 | 硬限 1 次,且计入 Run 的 tool 预算 |
|
||
| 引入 JSON Schema 库增大体积 | `santhosh-tekuri/jsonschema/v6` 无第三方依赖,约 400KB |
|
||
|
||
---
|
||
|
||
---
|
||
|
||
## 附录:本阶段收编的缺陷(13 条)
|
||
|
||
编号 `F-xx` 是全局缺陷台账,索引见 [`README.md`](README.md)。状态含义:✅ 本阶段完整解决;🟡 本阶段部分解决(说明见条末);❌ 未解决(需单独立项)。
|
||
|
||
### F-10 工具描述全部丢失,模型只能看到兜底描述
|
||
|
||
**位置**:
|
||
|
||
- 接口定义:`ToolDescriptor` in `internal/domain/agent/ports/ports.go`
|
||
- 消费方:`toolDefs` in `internal/infrastructure/ai/eino_adapter.go` `toolDefs()`
|
||
- 工具实现:`internal/infrastructure/ai/tools.go`(`MCPTool`、`SkillTool`)、`eino_adapter.go`(`EinoTool`)
|
||
|
||
**问题概述**:`toolDefs()` 里用 `tool.(ports.ToolDescriptor)` 取描述,但**项目中没有任何类型实现了 `Description() string`**:
|
||
|
||
```go
|
||
desc := ""
|
||
if d, ok := tool.(ports.ToolDescriptor); ok {
|
||
desc = d.Description() // 永远走不到
|
||
}
|
||
defs = append(defs, OpenAIToolDef{Name: tool.Name(), Description: desc})
|
||
```
|
||
|
||
`SkillTool` 虽然有 `Description` 字段,但没有 `Description()` 方法;`MCPTool` 和 `EinoTool` 连字段都没有。结果所有工具描述都是空,`fallbackDescription` 统一返回「外部工具 X,参数 query 为自由文本」。
|
||
|
||
**影响**:模型无法区分各工具用途(比如百度搜索、drawio 绘图工具都被描述成同样的自由文本),工具选择准确率显著下降,而这是当前 demo 场景(多工具 + 多 Agent)的核心体验问题。
|
||
|
||
**修复方案**:
|
||
|
||
- 给 `SkillTool` 加 `func (t SkillTool) Description() string { return t.Description }`。
|
||
- 给 `EinoTool` 增加 `Description` 字段并实现方法;在 `MCPToolRouter.RegisterAndExpand` 从 `tools/list` 的 `description` 填充。
|
||
- 给 `MCPTool` 实现 `Description()` 并保存 SSE 配置里的描述。
|
||
- 保留 `eino_adapter.go` 的类型断言,同时提供统一的描述访问方式,避免以后再漏。
|
||
|
||
> **归属**:P1 | **状态**:✅ | **历史编号**:P0-3
|
||
|
||
### F-11 MCP `pending` map 在超时/提前返回路径泄漏
|
||
|
||
**位置**:`callRPC` in `internal/infrastructure/ai/mcp_sse_client.go`
|
||
|
||
```go
|
||
c.mu.Lock()
|
||
postURL := c.postURL
|
||
c.pending[id] = ch
|
||
c.mu.Unlock()
|
||
if postURL == "" {
|
||
return nil, fmt.Errorf("mcp post url is not set") // <- 未删除 pending[id]
|
||
}
|
||
...
|
||
select {
|
||
case msg, ok := <-ch:
|
||
...
|
||
case <-waitCtx.Done():
|
||
return nil, fmt.Errorf("mcp call %s timeout: %w", method, waitCtx.Err()) // <- 未删除 pending[id]
|
||
}
|
||
```
|
||
|
||
**问题概述**:`pending[id]` 在注册后,只有在 `handleMessage` 收到响应或 `signalStreamErr` 广播时才会被删除。超时、`postURL` 为空等提前返回路径都不会清理。
|
||
|
||
**影响**:MCP Server 慢/挂掉时,每次超时都会在 `pending` 里留下一个带缓冲 channel,长跑进程持续占用内存,属于慢性内存泄漏。残留条目还会让 `signalStreamErr` 在断线时向已无人等待的 channel 写入。
|
||
|
||
**修复方案**:在 `callRPC` 内用 `defer` 清理:
|
||
|
||
```go
|
||
c.mu.Lock()
|
||
c.pending[id] = ch
|
||
c.mu.Unlock()
|
||
defer func() {
|
||
c.mu.Lock()
|
||
delete(c.pending, id)
|
||
c.mu.Unlock()
|
||
}()
|
||
```
|
||
|
||
注意避免重复关闭 channel;推荐让「所有权持有者」关闭,或用 `sync.Once`。
|
||
|
||
> **归属**:P1 | **状态**:✅ | **历史编号**:P0-4
|
||
|
||
### F-12 `ensureStarted` 并发首次调用会失败
|
||
|
||
**位置**:`ensureStarted` in `internal/infrastructure/ai/mcp_sse_client.go`
|
||
|
||
```go
|
||
c.mu.Lock()
|
||
if c.started { // goroutine B 看到 true
|
||
c.mu.Unlock()
|
||
return nil // <- B 直接返回成功
|
||
}
|
||
...
|
||
c.started = true // A 先标记,再在锁外做耗时连接
|
||
c.mu.Unlock() // <- B 此刻可能已经进入 callRPC
|
||
```
|
||
|
||
**问题概述**:第一个调用者(A)在锁内置 `started = true` 后释放锁,然后在锁外做 `openSSE`、等待 `endpoint`、`initialize`(可能数百毫秒到数秒)。此时第二个并发调用者(B)会看到 `started == true` 而直接返回 nil,随后 B 进入 `callRPC` 时 `postURL` 仍为空,报 `mcp post url is not set`。
|
||
|
||
**影响**:并发首次调用工具(如 parallel workflow 同时触发工具,或第一个请求尚未完成时的第二个请求)会随机失败。当前 demo 不易触发,但一旦上线就是间歇性报错。
|
||
|
||
**修复方案**:把「标记」与「完成」分开,使用 `sync.Once` + 初始化结果,或引入 `started`/`ready` 两个状态 + `sync.Cond`,让并发调用者等待初始化完成或拿到同一个初始化错误。
|
||
|
||
> **归属**:P1 | **状态**:🟡 | **历史编号**:P0-5
|
||
>
|
||
> P1 先修并发正确性(`sync.Once` 或双状态),P6 的 MCP 生命周期重构会重写这段
|
||
|
||
### F-13 重复注册 MCP SSE 工具导致第二张表拿到不可调用占位工具
|
||
|
||
**位置**:`RegisterAndExpand` in `internal/infrastructure/ai/mcp_sse_client.go` 与 `BuildTools` in `internal/infrastructure/ai/tools.go`
|
||
|
||
```go
|
||
if _, exists := r.clients[mcp.ToolName]; exists {
|
||
return nil // <- 第二次注册直接返回 nil
|
||
}
|
||
```
|
||
|
||
`BuildTools` 里:
|
||
|
||
```go
|
||
ts := f.router.RegisterAndExpand(t)
|
||
if len(ts) == 0 { continue } // 展开为空 -> 被跳过
|
||
...
|
||
if len(expanded) > 0 { return expanded, nil }
|
||
return tools, nil // <- 回退成原始 MCPTool 占位符
|
||
```
|
||
|
||
**问题概述**:`MCPToolRouter` 在 `bootstrap.Build` 中是全局单例。当前两个示例表都配置了同名 `baidu-search` SSE 工具。第二张表注册时命中 `exists` 分支返回 nil,`BuildTools` 的 `expanded` 为空,于是回退返回原始 `MCPTool{ToolName:"baidu-search"}`(不是 `tools/list` 发现的真实工具)。
|
||
|
||
**影响**:第二张表拿到的是配置名 `baidu-search` 这个占位工具,而不是 `tools/list` 发现的真实工具名。由于 `CallTool` 会先查 `r.clients[name]`(第 565 行),而 `baidu-search` 恰好在第一张表注册时已写入 `clients`,所以调用不会走 `case MCPTool:` 分支,而是被转发成 `tools/call {name:"baidu-search"}`——但 `baidu-search` 只是「服务端标签」,不是 MCP Server 上真实存在的工具名,服务端会返回「工具不存在」,最终表现为「Agent 一调工具就报错」。注意:这与 F-37 的 stdio/local「transport not supported」是两条不同的错误路径。
|
||
|
||
**修复方案**(任一):
|
||
|
||
1. `RegisterAndExpand` 命中已存在时,返回该 client 已展开的真实工具列表(需要缓存 `expandedByServer`)。
|
||
2. `BuildTools` 在 `len(ts) == 0` 时不要静默跳过,而是报错提示「工具已被注册」。
|
||
3. 更彻底:把 MCP client 的复用键改为 `baseURI+endpoint`,工具名到 client 的映射独立维护。
|
||
|
||
推荐方案 1 或 3,并为「多表共享同名 MCP」补测试。
|
||
|
||
---
|
||
|
||
> **归属**:P1 | **状态**:✅ | **历史编号**:P0-9
|
||
>
|
||
> 同名注册命中即返回错误;P6 用 `server.tool` 命名空间彻底隔离
|
||
|
||
### F-14 Skill 工具只暴露、不可执行
|
||
|
||
**位置**:`internal/infrastructure/ai/tools.go`(`SkillFactory`)、`CallTool` in `internal/infrastructure/ai/mcp_sse_client.go`
|
||
|
||
**问题概述**:Skill 被解析为 `SkillTool`(实现了 `ports.Tool`),会作为 function 暴露给模型;但它没有注册到 `MCPToolRouter` 的 `clients` map 中,运行时 `CallTool` 找不到客户端,返回 `tool %q is not callable in current runtime`。
|
||
|
||
**影响**:模型一旦选择 skill 工具就必然失败,用户侧看到「工具调用报错」。当前两个示例 skill(battle-plan、pdf)实际都不可用。
|
||
|
||
**修复方案**:
|
||
|
||
- 明确 Skill 的执行语义:要么实现本地执行器(按 `SKILL.md` 指令执行脚本/读取文档),要么在装配阶段就不要把 Skill 暴露为 function。
|
||
- 短期最稳:把 Skill 从 tool 列表移除,改为注入 instruction 上下文;长期:新增 `SkillToolExecutor` 注册到 `ToolRouter`。
|
||
- 无论选哪种,都应消除「暴露但不可执行」的不一致状态。
|
||
|
||
> **归属**:P1 | **状态**:✅ | **历史编号**:P1-1
|
||
>
|
||
> 2026-11-02 决策:P1 只注入 instruction(4.2.8),P6 沙箱就绪后再做成可调用工具
|
||
|
||
### F-15 工具参数 schema 硬编码为 `query`
|
||
|
||
**位置**:`encodeTools` in `internal/infrastructure/ai/openai_client.go`
|
||
|
||
**问题概述**:所有工具的参数 schema 都被写成单一 `query: string`:
|
||
|
||
```go
|
||
"parameters": map[string]any{
|
||
"type": "object",
|
||
"properties": map[string]any{
|
||
"query": map[string]any{"type": "string", ...},
|
||
},
|
||
},
|
||
```
|
||
|
||
但真实 MCP 工具的 `inputSchema` 各异(百度搜索可能要求 `query`,其他工具可能是别的字段)。
|
||
|
||
**影响**:模型按 schema 生成的参数可能与 MCP Server 期望不符,工具调用失败;同时丢失了 MCP `tools/list` 返回的真实 schema。
|
||
|
||
**修复方案**:`MCPToolRouter.RegisterAndExpand` 在 `tools/list` 时同时保留 `inputSchema`;`EinoChatModel.toolDefs` 传递完整 schema;`encodeTools` 直接使用它。若暂时拿不到 schema,至少保留参数名与描述。
|
||
|
||
> **归属**:P1 | **状态**:✅ | **历史编号**:P1-9
|
||
|
||
### F-16 `MCPToolRouter` 无锁
|
||
|
||
**位置**:`MCPToolRouter` in `internal/infrastructure/ai/mcp_sse_client.go`
|
||
|
||
**问题概述**:`clients` / `tools` / `registered` / `listFailures` 都是普通 map,没有任何互斥保护。当前写入只发生在启动阶段(单 goroutine),运行时只读,勉强安全;但一旦支持热更新、延迟注册或并发 `BuildTools`,就是数据竞争。
|
||
|
||
**影响**:潜在 `fatal error: concurrent map read and map write`,进程直接崩溃。
|
||
|
||
**修复方案**:给 `MCPToolRouter` 加 `sync.RWMutex`,所有读写走锁;`CallTool` 读路径用 RLock。
|
||
|
||
> **归属**:P1 | **状态**:✅ | **历史编号**:P2-10
|
||
|
||
### F-17 MCP 启动期工具发现失败时,会把「服务端标签」当工具暴露给模型且不告警
|
||
|
||
**位置**:`RegisterAndExpand` in `internal/infrastructure/ai/mcp_sse_client.go`、`BuildTools` in `internal/infrastructure/ai/tools.go`
|
||
|
||
```go
|
||
names, err := client.ListTools(ctx)
|
||
if err != nil {
|
||
r.listFailures[mcp.ToolName] = err // 只记录,从不读取、从不告警
|
||
r.tools = append(r.tools, mcp) // 把配置名当工具塞回去
|
||
return []ports.Tool{mcp}
|
||
}
|
||
```
|
||
|
||
**问题概述**:MCP Server 启动时不可达/超时(或如 F-13 的重复注册)时,`BuildTools` 会把 `MCPTool{ToolName:"baidu-search"}` 作为「工具」返回给 ChatModel。模型看到一个名为 `baidu-search` 的 function,但该名字不是服务端真实工具,运行时 `tools/call` 必然失败;`listFailures` 只写不读,启动既不失败也不打日志。
|
||
|
||
**影响**:把不可用工具暴露给模型导致运行期报错;「降级保留占位工具」的初衷(启动不中断 + 错误清晰)没有达成,属于静默劣化。
|
||
|
||
**修复方案**:启动期区分「连接失败」与「无工具」,失败时记 `listFailures` 并打警告日志,或按 `required` 语义 fail fast;不要把配置名当可调用工具暴露;若保留占位,运行时应给出「MCP Server 未就绪」的明确错误。
|
||
|
||
> **归属**:P1 | **状态**:✅ | **历史编号**:P1-14
|
||
>
|
||
> `listFailures` 参与告警与 fail fast;探活逻辑在 P6 重写
|
||
|
||
### F-18 `io.ReadAll` 无上限读取上游响应体
|
||
|
||
**位置**:`Generate` in `internal/infrastructure/ai/openai_client.go`、`openSSE` in `internal/infrastructure/ai/mcp_sse_client.go`
|
||
|
||
**问题概述**:三处都用 `io.ReadAll` 把响应体一次性读入内存,没有任何大小限制。`truncate(...,400)` 只截断错误文案,读入本身仍是全量。
|
||
|
||
**影响**:异常/恶意上游返回超大响应(或错误页)时可导致内存快速膨胀,属于 DoS 面;对非流式 `Generate` 尤其明显。
|
||
|
||
**修复方案**:用 `io.LimitReader`(如 4~8 MiB)限制读取并在超限时返回明确错误;错误体只需读几百字节。
|
||
|
||
> **归属**:P1 | **状态**:🟡 | **历史编号**:P2-22
|
||
>
|
||
> 入站有 `MaxBytesReader`;出站 `io.LimitReader` 上限写进 P1 的模型客户端加固
|
||
|
||
### F-19 流式请求没有发送 `Accept: text/event-stream`
|
||
|
||
**位置**:`do` in `internal/infrastructure/ai/openai_client.go` `do()`
|
||
|
||
```go
|
||
func (c *OpenAIClient) do(ctx context.Context, body []byte) (*http.Response, error) {
|
||
...
|
||
req.Header.Set("Accept", "application/json") // 流式/非流式共用
|
||
```
|
||
|
||
**问题概述**:`do()` 被 `Generate` 与 `Stream` 共用,`Accept` 恒为 `application/json`,流式调用没有声明 `text/event-stream`。
|
||
|
||
**影响**:OpenAI 官方端点通常宽容,但部分兼容实现/网关会依据 `Accept` 决定是否返回 SSE,可能表现为流式请求拿不到事件流或直接被拒。
|
||
|
||
**修复方案**:`do()` 增加 `accept string` 参数,流式传 `text/event-stream`、非流式传 `application/json`;或校验返回的 `Content-Type` 并给出明确错误。
|
||
|
||
> **归属**:P1 | **状态**:🟡 | **历史编号**:P2-23
|
||
>
|
||
> `Accept: text/event-stream` 写进 P1 的模型客户端加固
|
||
|
||
### F-20 `MCPToolRouter` 的 `registered` / `listFailures` 是死字段,`notify` 不校验状态码
|
||
|
||
**位置**:`MCPToolRouter` in `internal/infrastructure/ai/mcp_sse_client.go`、`notify` 在 `:458-485`
|
||
|
||
**问题概述**:
|
||
|
||
- `registered map[string]struct{}` 只写不读(第 548 行写、无任何读取);
|
||
- `listFailures map[string]error` 只写不读(第 540 行写、无任何读取);
|
||
- `notify()` 丢弃响应体后不检查 `StatusCode`。
|
||
|
||
**影响**:死字段误导读者;`notifications/initialized` 若被服务端拒绝(4xx/5xx),客户端仍认为握手成功,后续调用才报莫名的错。
|
||
|
||
**修复方案**:删除死字段(或让 `listFailures` 真正参与启动告警);`notify` 增加状态码校验。
|
||
|
||
> **归属**:P1 | **状态**:🟡 | **历史编号**:P3-15
|
||
>
|
||
> `listFailures` 改为告警后自然解决;`notify` 的状态码校验在 P1 补
|
||
|
||
### F-21 任一工具失败即整轮失败(`executeToolCalls`)
|
||
|
||
**位置**:`(*Agent).executeToolCalls` in `internal/infrastructure/adk/adapter.go`
|
||
|
||
**问题概述**:工具调用循环里任何一个工具返回错误,`executeToolCalls` 直接 `return nil, fmt.Errorf("tool %q: %w", call.Name, err)`,整个 run 终止,没有重试、没有降级、没有把失败结果作为 observation 回灌给模型。
|
||
|
||
**影响**:一个下游 5xx、一次限流、一次超时就能让整轮对话失败;而模型其实完全有能力基于「工具不可用」这个observation 给出替代答案。
|
||
|
||
**修复方案**:P1 的 `tool.Gateway` 把失败分类后走六层降级(P1 设计中的 L0–L6)。L5 结构化降级之后必须把结果作为工具输出回灌给模型,而不是让 run 失败——「工具故障是模型要处理的信息,不是 run 的终态」。
|
||
|
||
> **归属**:P1 | **状态**:✅
|
||
|
||
### F-22 工具调用无单次超时,只靠 HTTP 客户端整体超时
|
||
|
||
**位置**:`internal/infrastructure/ai/mcp_sse_client.go` 的 `RequestTimeout`(默认 300s)
|
||
|
||
**问题概述**:工具级超时只有一个默认 300 秒的 `RequestTimeout`,实际调用路径上没有被单独施加 deadline 的地方;一次工具挂起会一直占用一个 step,直到外层 HTTP 客户端超时。
|
||
|
||
**影响**:单个慢工具能把整个 run 拖到分钟级;并发场景下直接耗尽连接与 goroutine。
|
||
|
||
**修复方案**:P1 的 `tool.Spec.Timeout` 成为唯一事实源(默认 30s,可按工具覆盖),Gateway 在 `Invoke` 前用 `context.WithTimeout` 施加 deadline;超时归类为 `timeout`(可重试),并计入 `Budget.MaxWallClock`。
|
||
|
||
> **归属**:P1 | **状态**:✅
|