fix(agent): 加固 MCP 工具人审批的跨实例与并发语义

- 跨实例 Resolve 通过 Redis reply channel 接收 owning 实例的 ack
  (ok / not_found / tenant_mismatch / user_mismatch / already_resolved),
  HTTP 不再静默 200,超时退化为 NotFound。
- PendingRequest 增加 UserID,Resolve 校验会话所有者,避免同租户
  其他用户越权批准/篡改参数。
- 新增 ErrAlreadyResolved,timer/ctx 命中后再次 Resolve 返回 400 而
  不是静默成功;waiter.deliver 暴露胜出语义。
- NeedsApproval 默认 fail-close(DB 故障要求审批),可经
  WEKNORA_AGENT_TOOL_APPROVAL_FAIL_OPEN=true 回退。
- Pub/Sub 增加 OriginID 自过滤、退避重连、namespace 后缀,避免自回
  环噪声与多部署串扰。
- 工具执行超时常量统一通过 ToolExecContext.ExecTimeout 注入,
  mcp_tool.go 不再硬编码 60s。
- handler 修正 path 二次解码、错误用 errors.Is、modified_args=null 的
  静默清空、ListMCPToolApprovals 的 404/500 误判。
- repository 用 clause.OnConflict 做原子 upsert,消除并发 500。
- 增加 NotFound / TenantMismatch / UserMismatch / AlreadyResolved /
  Race 等用例。
This commit is contained in:
wizardchen
2026-05-10 21:41:02 +08:00
committed by lyingbug
parent 5510ea8f5a
commit 6d0f09d75f
7 changed files with 416 additions and 88 deletions
+7 -2
View File
@@ -118,6 +118,7 @@ func (t *MCPTool) Execute(ctx context.Context, args json.RawMessage) (*types.Too
}
decision, waitErr := t.gate.RequestAndWait(waitCtx, approval.PendingRequest{
TenantID: tenantID,
UserID: meta.UserID,
SessionID: meta.SessionID,
AssistantMessageID: meta.AssistantMessageID,
RequestID: meta.RequestID,
@@ -155,11 +156,15 @@ func (t *MCPTool) Execute(ctx context.Context, args json.RawMessage) (*types.Too
}, nil
}
}
// Approval may have consumed most/all of the per-tool 60s budget set by the
// Approval may have consumed most/all of the per-tool exec budget set by the
// agent engine (act.go). Re-derive a fresh tool-exec ctx from ApprovalCtx so
// the actual MCP CallTool gets a full timeout window. (issue #1173 follow-up)
if meta.ApprovalCtx != nil {
freshCtx, freshCancel := context.WithTimeout(meta.ApprovalCtx, 60*time.Second)
freshTimeout := meta.ExecTimeout
if freshTimeout <= 0 {
freshTimeout = 60 * time.Second
}
freshCtx, freshCancel := context.WithTimeout(meta.ApprovalCtx, freshTimeout)
defer freshCancel()
ctx = freshCtx
}