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
@@ -0,0 +1,79 @@
package repository
import (
"context"
"errors"
"fmt"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
"gorm.io/gorm"
)
// MCPToolApprovalRepository implements interfaces.MCPToolApprovalRepository.
type MCPToolApprovalRepository struct {
db *gorm.DB
}
// NewMCPToolApprovalRepository creates a repository backed by GORM.
func NewMCPToolApprovalRepository(db *gorm.DB) interfaces.MCPToolApprovalRepository {
return &MCPToolApprovalRepository{db: db}
}
// ListByService returns all stored approval rows for an MCP service (may be empty).
func (r *MCPToolApprovalRepository) ListByService(ctx context.Context, tenantID uint64, serviceID string) ([]*types.MCPToolApproval, error) {
var rows []*types.MCPToolApproval
err := r.db.WithContext(ctx).
Where("tenant_id = ? AND service_id = ?", tenantID, serviceID).
Order("tool_name ASC").
Find(&rows).Error
if err != nil {
return nil, fmt.Errorf("list mcp tool approvals: %w", err)
}
return rows, nil
}
// IsRequired returns true when a row exists with require_approval = true.
func (r *MCPToolApprovalRepository) IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) {
var row types.MCPToolApproval
err := r.db.WithContext(ctx).
Select("require_approval").
Where("tenant_id = ? AND service_id = ? AND tool_name = ?", tenantID, serviceID, toolName).
First(&row).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("get mcp tool approval: %w", err)
}
return row.RequireApproval, nil
}
// Upsert creates or updates the approval flag for a tool.
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 err != nil {
return fmt.Errorf("get mcp tool approval for upsert: %w", err)
}
return r.db.WithContext(ctx).Model(&existing).Updates(map[string]interface{}{
"require_approval": row.RequireApproval,
"updated_at": time.Now(),
}).Error
}
@@ -8,6 +8,7 @@ import (
"strconv"
"github.com/Tencent/WeKnora/internal/agent"
"github.com/Tencent/WeKnora/internal/agent/approval"
"github.com/Tencent/WeKnora/internal/agent/skills"
"github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/config"
@@ -59,6 +60,7 @@ type agentService struct {
webSearchStateService interfaces.WebSearchStateService
wikiPageService interfaces.WikiPageService
tenantService interfaces.TenantService
toolApprovalGate approval.MCPApproval
}
// NewAgentService creates a new agent service
@@ -78,6 +80,7 @@ func NewAgentService(
webSearchStateService interfaces.WebSearchStateService,
wikiPageService interfaces.WikiPageService,
tenantService interfaces.TenantService,
toolApprovalGate approval.MCPApproval,
) interfaces.AgentService {
return &agentService{
cfg: cfg,
@@ -95,6 +98,7 @@ func NewAgentService(
webSearchStateService: webSearchStateService,
wikiPageService: wikiPageService,
tenantService: tenantService,
toolApprovalGate: toolApprovalGate,
}
}
@@ -223,7 +227,7 @@ func (s *agentService) registerMCPTools(
}
}
if len(enabledServices) > 0 {
if err := tools.RegisterMCPTools(ctx, toolRegistry, enabledServices, s.mcpManager); err != nil {
if err := tools.RegisterMCPTools(ctx, toolRegistry, enabledServices, s.mcpManager, s.toolApprovalGate); err != nil {
logger.Warnf(ctx, "Failed to register MCP tools: %v", err)
} else {
logger.Infof(ctx, "Registered MCP tools from %d enabled services", len(enabledServices))
@@ -0,0 +1,59 @@
package service
import (
"context"
"fmt"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
type mcpToolApprovalService struct {
repo interfaces.MCPToolApprovalRepository
mcpRepo interfaces.MCPServiceRepository
}
// NewMCPToolApprovalService constructs the MCP tool approval service.
func NewMCPToolApprovalService(
repo interfaces.MCPToolApprovalRepository,
mcpRepo interfaces.MCPServiceRepository,
) interfaces.MCPToolApprovalService {
return &mcpToolApprovalService{repo: repo, mcpRepo: mcpRepo}
}
func (s *mcpToolApprovalService) ListByService(ctx context.Context, tenantID uint64, serviceID string) ([]*types.MCPToolApproval, error) {
svc, err := s.mcpRepo.GetByID(ctx, tenantID, serviceID)
if err != nil {
return nil, err
}
if svc == nil {
return nil, fmt.Errorf("mcp service not found")
}
return s.repo.ListByService(ctx, tenantID, serviceID)
}
func (s *mcpToolApprovalService) SetRequireApproval(
ctx context.Context, tenantID uint64, serviceID, toolName string, require bool,
) error {
if toolName == "" {
return fmt.Errorf("tool_name is required")
}
svc, err := s.mcpRepo.GetByID(ctx, tenantID, serviceID)
if err != nil {
return err
}
if svc == nil {
return fmt.Errorf("mcp service not found")
}
row := &types.MCPToolApproval{
TenantID: tenantID,
ServiceID: serviceID,
ToolName: toolName,
RequireApproval: require,
}
return s.repo.Upsert(ctx, row)
}
func (s *mcpToolApprovalService) IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) {
return s.repo.IsRequired(ctx, tenantID, serviceID, toolName)
}