feat(agent): human-in-the-loop approval for MCP tool calls (#1173)

Add an opt-in human approval gate so Agent runs pause before executing
MCP tools that operators flag as dangerous, surface an approval card in
the chat UI, and only resume after the user approves (optionally with
edited args) or rejects.

Backend
- New mcp_tool_approvals table + repo/service to mark per-tool approval
  required (PG migration 000042 + sqlite init).
- approval.Gate coordinates RequestAndWait / Resolve with sync.Once
  delivery, configurable timeout, and Redis Pub/Sub fan-out so multi-
  replica deployments work without sticky sessions.
- MCPTool.Execute integrates the gate; uses a round-level ApprovalCtx
  (without the per-tool 60s timeout) for the wait, and re-derives a
  fresh 60s exec ctx after approval so CallTool keeps a full window.
- New SSE response types (tool_approval_required / _resolved) and
  EventBus events plumb approval state to AgentStreamDisplay.
- REST: list/set per-tool approval flag, resolve pending approval.
- Configurable via agent.tool_approval_timeout_seconds (yaml) or
  WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT env (accepts seconds or Go
  duration).

Frontend
- MCP settings: per-tool "require approval" switch on the test panel.
- Chat: ToolApprovalCard renders the pause point with editable JSON
  args, validation feedback, mm:ss countdown that turns warning/danger
  near deadline, and a resolved state that retains context.
- i18n strings added for zh-CN / en-US / ko-KR / ru-RU.

Docs
- docs/zh/mcp-approval.md covering behavior, config, API, deployment
  considerations (Redis cross-instance, restart limitations).
This commit is contained in:
wizardchen
2026-05-10 21:23:49 +08:00
committed by lyingbug
parent c1826030ab
commit 5510ea8f5a
36 changed files with 1814 additions and 36 deletions
+127 -3
View File
@@ -1,9 +1,12 @@
package handler
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"github.com/Tencent/WeKnora/internal/agent/approval"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
@@ -14,13 +17,21 @@ import (
// MCPServiceHandler handles MCP service related HTTP requests
type MCPServiceHandler struct {
mcpServiceService interfaces.MCPServiceService
mcpServiceService interfaces.MCPServiceService
mcpToolApprovalService interfaces.MCPToolApprovalService
toolApprovalGate *approval.Gate
}
// NewMCPServiceHandler creates a new MCP service handler
func NewMCPServiceHandler(mcpServiceService interfaces.MCPServiceService) *MCPServiceHandler {
func NewMCPServiceHandler(
mcpServiceService interfaces.MCPServiceService,
mcpToolApprovalService interfaces.MCPToolApprovalService,
toolApprovalGate *approval.Gate,
) *MCPServiceHandler {
return &MCPServiceHandler{
mcpServiceService: mcpServiceService,
mcpServiceService: mcpServiceService,
mcpToolApprovalService: mcpToolApprovalService,
toolApprovalGate: toolApprovalGate,
}
}
@@ -445,3 +456,116 @@ func (h *MCPServiceHandler) GetMCPServiceResources(c *gin.Context) {
"data": resources,
})
}
// ListMCPToolApprovals returns persisted require_approval flags for tools on an MCP service.
func (h *MCPServiceHandler) ListMCPToolApprovals(c *gin.Context) {
ctx := c.Request.Context()
serviceID := secutils.SanitizeForLog(c.Param("id"))
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
return
}
if h.mcpToolApprovalService == nil {
c.Error(errors.NewInternalServerError("MCP tool approval is not configured"))
return
}
rows, err := h.mcpToolApprovalService.ListByService(ctx, tenantID, serviceID)
if err != nil {
c.Error(errors.NewNotFoundError(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": rows})
}
type setMCPToolApprovalBody struct {
RequireApproval bool `json:"require_approval"`
}
// SetMCPToolApproval sets whether a tool requires human approval before the agent may call it.
func (h *MCPServiceHandler) SetMCPToolApproval(c *gin.Context) {
ctx := c.Request.Context()
serviceID := secutils.SanitizeForLog(c.Param("id"))
rawName := c.Param("tool_name")
toolName, err := url.PathUnescape(rawName)
if err != nil {
toolName = rawName
}
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
return
}
if h.mcpToolApprovalService == nil {
c.Error(errors.NewInternalServerError("MCP tool approval is not configured"))
return
}
var body setMCPToolApprovalBody
if err := c.ShouldBindJSON(&body); err != nil {
c.Error(errors.NewBadRequestError(err.Error()))
return
}
if err := h.mcpToolApprovalService.SetRequireApproval(ctx, tenantID, serviceID, toolName, body.RequireApproval); err != nil {
c.Error(errors.NewInternalServerError(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
type resolveToolApprovalBody struct {
Decision string `json:"decision" binding:"required"` // approve | reject
ModifiedArgs json.RawMessage `json:"modified_args"`
Reason string `json:"reason"`
}
// ResolveToolApproval completes a pending MCP tool approval (agent execution resumes).
func (h *MCPServiceHandler) ResolveToolApproval(c *gin.Context) {
ctx := c.Request.Context()
pendingID := c.Param("pending_id")
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
return
}
if h.toolApprovalGate == nil {
c.Error(errors.NewInternalServerError("Tool approval gate is not configured"))
return
}
var body resolveToolApprovalBody
if err := c.ShouldBindJSON(&body); err != nil {
c.Error(errors.NewBadRequestError(err.Error()))
return
}
dec := approval.Decision{Reason: body.Reason}
switch body.Decision {
case "approve":
dec.Approved = true
if len(body.ModifiedArgs) > 0 {
var probe map[string]interface{}
if err := json.Unmarshal(body.ModifiedArgs, &probe); err != nil {
c.Error(errors.NewBadRequestError("modified_args must be a JSON object"))
return
}
dec.ModifiedArgs = body.ModifiedArgs
}
case "reject":
dec.Approved = false
default:
c.Error(errors.NewBadRequestError("decision must be approve or reject"))
return
}
if err := h.toolApprovalGate.Resolve(tenantID, pendingID, dec); err != nil {
if err == approval.ErrPendingNotFound {
c.Error(errors.NewNotFoundError("pending approval not found or already completed"))
return
}
if err == approval.ErrTenantMismatch {
c.Error(errors.NewBadRequestError("tenant mismatch"))
return
}
logger.ErrorWithFields(ctx, err, map[string]interface{}{"pending_id": pendingID})
c.Error(errors.NewInternalServerError(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
@@ -2,6 +2,7 @@ package session
import (
"context"
"encoding/json"
"fmt"
"sync"
"time"
@@ -66,6 +67,8 @@ func (h *AgentStreamHandler) Subscribe() {
h.eventBus.On(event.EventError, h.handleError)
h.eventBus.On(event.EventSessionTitle, h.handleSessionTitle)
h.eventBus.On(event.EventAgentComplete, h.handleComplete)
h.eventBus.On(event.EventToolApprovalRequired, h.handleToolApprovalRequired)
h.eventBus.On(event.EventToolApprovalResolved, h.handleToolApprovalResolved)
}
// handleThought handles agent thought events
@@ -210,6 +213,60 @@ func (h *AgentStreamHandler) handleToolResult(ctx context.Context, evt event.Eve
return nil
}
func toolApprovalDataToMap(v interface{}) map[string]interface{} {
b, err := json.Marshal(v)
if err != nil {
return map[string]interface{}{}
}
var m map[string]interface{}
if err := json.Unmarshal(b, &m); err != nil {
return map[string]interface{}{}
}
return m
}
// handleToolApprovalRequired persists MCP tool human-approval prompts for SSE / replay (issue #1173).
func (h *AgentStreamHandler) handleToolApprovalRequired(ctx context.Context, evt event.Event) error {
data, ok := evt.Data.(event.ToolApprovalRequiredData)
if !ok {
return nil
}
meta := toolApprovalDataToMap(data)
meta["pending_id"] = data.PendingID
if err := h.streamManager.AppendEvent(h.ctx, h.sessionID, h.assistantMessageID, interfaces.StreamEvent{
ID: evt.ID,
Type: types.ResponseTypeToolApprovalRequired,
Content: "MCP tool requires human approval",
Done: true,
Timestamp: time.Now(),
Data: meta,
}); err != nil {
logger.GetLogger(h.ctx).Error("Append tool approval required event failed", "error", err)
}
return nil
}
// handleToolApprovalResolved persists the outcome of a tool approval (issue #1173).
func (h *AgentStreamHandler) handleToolApprovalResolved(ctx context.Context, evt event.Event) error {
data, ok := evt.Data.(event.ToolApprovalResolvedData)
if !ok {
return nil
}
meta := toolApprovalDataToMap(data)
meta["pending_id"] = data.PendingID
if err := h.streamManager.AppendEvent(h.ctx, h.sessionID, h.assistantMessageID, interfaces.StreamEvent{
ID: evt.ID,
Type: types.ResponseTypeToolApprovalResolved,
Content: "MCP tool approval resolved",
Done: true,
Timestamp: time.Now(),
Data: meta,
}); err != nil {
logger.GetLogger(h.ctx).Error("Append tool approval resolved event failed", "error", err)
}
return nil
}
// handleReferences handles knowledge references events
func (h *AgentStreamHandler) handleReferences(ctx context.Context, evt event.Event) error {
data, ok := evt.Data.(event.AgentReferencesData)