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
@@ -10,6 +10,7 @@ import (
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// MCPToolApprovalRepository implements interfaces.MCPToolApprovalRepository.
@@ -51,29 +52,35 @@ func (r *MCPToolApprovalRepository) IsRequired(ctx context.Context, tenantID uin
return row.RequireApproval, nil
}
// Upsert creates or updates the approval flag for a tool.
// Upsert creates or updates the approval flag for a tool atomically.
// Uses ON CONFLICT against the (tenant_id, service_id, tool_name) unique index
// so concurrent writers don't race the prior SELECT-then-INSERT path into
// duplicate-key 500s.
func (r *MCPToolApprovalRepository) Upsert(ctx context.Context, row *types.MCPToolApproval) error {
if row == nil {
return errors.New("row is nil")
}
var existing types.MCPToolApproval
err := r.db.WithContext(ctx).
Where("tenant_id = ? AND service_id = ? AND tool_name = ?", row.TenantID, row.ServiceID, row.ToolName).
First(&existing).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
if row.ID == "" {
row.ID = uuid.New().String()
}
if err := r.db.WithContext(ctx).Create(row).Error; err != nil {
return fmt.Errorf("create mcp tool approval: %w", err)
}
return nil
if row.ID == "" {
row.ID = uuid.New().String()
}
now := time.Now()
row.UpdatedAt = now
if row.CreatedAt.IsZero() {
row.CreatedAt = now
}
err := r.db.WithContext(ctx).Clauses(clause.OnConflict{
Columns: []clause.Column{
{Name: "tenant_id"},
{Name: "service_id"},
{Name: "tool_name"},
},
DoUpdates: clause.Assignments(map[string]interface{}{
"require_approval": row.RequireApproval,
"updated_at": now,
}),
}).Create(row).Error
if err != nil {
return fmt.Errorf("get mcp tool approval for upsert: %w", err)
return fmt.Errorf("upsert mcp tool approval: %w", err)
}
return r.db.WithContext(ctx).Model(&existing).Updates(map[string]interface{}{
"require_approval": row.RequireApproval,
"updated_at": time.Now(),
}).Error
return nil
}