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
+7 -3
View File
@@ -27,10 +27,10 @@ type FunctionCall struct {
// ChatResponse chat response
type ChatResponse struct {
Content string `json:"content"`
Content string `json:"content"`
ToolCalls []LLMToolCall `json:"tool_calls,omitempty"`
FinishReason string `json:"finish_reason,omitempty"`
Usage TokenUsage `json:"usage"`
FinishReason string `json:"finish_reason,omitempty"`
Usage TokenUsage `json:"usage"`
}
// Response type
@@ -57,6 +57,10 @@ const (
ResponseTypeAgentQuery ResponseType = "agent_query"
// Complete response type (agent complete)
ResponseTypeComplete ResponseType = "complete"
// ToolApprovalRequired: MCP tool marked dangerous — UI must collect user approval before execution continues
ResponseTypeToolApprovalRequired ResponseType = "tool_approval_required"
// ToolApprovalResolved: user approved/rejected (or timeout); informational for UI replay
ResponseTypeToolApprovalResolved ResponseType = "tool_approval_resolved"
)
// StreamResponse stream response
@@ -0,0 +1,21 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// MCPToolApprovalRepository persists per-tool approval requirements.
type MCPToolApprovalRepository interface {
ListByService(ctx context.Context, tenantID uint64, serviceID string) ([]*types.MCPToolApproval, error)
IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error)
Upsert(ctx context.Context, row *types.MCPToolApproval) error
}
// MCPToolApprovalService is the business layer for MCP tool approval flags.
type MCPToolApprovalService interface {
ListByService(ctx context.Context, tenantID uint64, serviceID string) ([]*types.MCPToolApproval, error)
SetRequireApproval(ctx context.Context, tenantID uint64, serviceID, toolName string, require bool) error
IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error)
}
+25 -3
View File
@@ -30,9 +30,9 @@ type MCPService struct {
Headers MCPHeaders `json:"headers" gorm:"type:json"`
AuthConfig *MCPAuthConfig `json:"auth_config" gorm:"type:json"`
AdvancedConfig *MCPAdvancedConfig `json:"advanced_config" gorm:"type:json"`
StdioConfig *MCPStdioConfig `json:"stdio_config,omitempty" gorm:"type:json"` // Required for stdio transport
EnvVars MCPEnvVars `json:"env_vars,omitempty" gorm:"type:json"` // Environment variables for stdio
IsBuiltin bool `json:"is_builtin" gorm:"default:false"` // Whether this is a builtin MCP service (visible to all tenants)
StdioConfig *MCPStdioConfig `json:"stdio_config,omitempty" gorm:"type:json"` // Required for stdio transport
EnvVars MCPEnvVars `json:"env_vars,omitempty" gorm:"type:json"` // Environment variables for stdio
IsBuiltin bool `json:"is_builtin" gorm:"default:false"` // Whether this is a builtin MCP service (visible to all tenants)
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
@@ -69,6 +69,28 @@ type MCPTool struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema json.RawMessage `json:"inputSchema"` // JSON Schema for tool parameters
// RequireApproval when true: agent execution pauses until the user approves in UI (issue #1173).
RequireApproval bool `json:"require_approval,omitempty"`
}
// MCPToolApproval persists per-tool "danger / needs human approval" for an MCP service.
// Tool list itself comes from MCP ListTools; this table only stores overrides.
type MCPToolApproval struct {
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:idx_mcp_tool_approvals_tenant_svc_tool"`
ServiceID string `json:"service_id" gorm:"type:varchar(36);not null;uniqueIndex:idx_mcp_tool_approvals_tenant_svc_tool;index"`
ToolName string `json:"tool_name" gorm:"type:varchar(512);not null;uniqueIndex:idx_mcp_tool_approvals_tenant_svc_tool"`
RequireApproval bool `json:"require_approval" gorm:"not null;default:false"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// BeforeCreate sets ID for MCPToolApproval.
func (m *MCPToolApproval) BeforeCreate(tx *gorm.DB) error {
if m.ID == "" {
m.ID = uuid.New().String()
}
return nil
}
// MCPResource represents a resource exposed by an MCP service