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:
@@ -0,0 +1,40 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
)
|
||||
|
||||
type execCtxKey struct{}
|
||||
|
||||
// ToolExecContext is attached to context during agent tool execution (per tool call).
|
||||
type ToolExecContext struct {
|
||||
SessionID string
|
||||
AssistantMessageID string
|
||||
RequestID string
|
||||
ToolCallID string
|
||||
EventBus *event.EventBus
|
||||
// ApprovalCtx is the parent ctx WITHOUT defaultToolExecTimeout; used when the tool
|
||||
// must wait for human approval that may exceed normal tool exec timeout (issue #1173).
|
||||
// Falls back to the per-tool execCtx when nil.
|
||||
ApprovalCtx context.Context
|
||||
}
|
||||
|
||||
// WithToolExecContext returns ctx that carries ToolExecContext for MCP approval and similar features.
|
||||
func WithToolExecContext(ctx context.Context, meta *ToolExecContext) context.Context {
|
||||
if meta == nil {
|
||||
return ctx
|
||||
}
|
||||
return context.WithValue(ctx, execCtxKey{}, meta)
|
||||
}
|
||||
|
||||
// ToolExecFromContext returns metadata attached by the agent engine, if any.
|
||||
func ToolExecFromContext(ctx context.Context) (*ToolExecContext, bool) {
|
||||
v := ctx.Value(execCtxKey{})
|
||||
if v == nil {
|
||||
return nil, false
|
||||
}
|
||||
meta, ok := v.(*ToolExecContext)
|
||||
return meta, ok && meta != nil
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent/approval"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/mcp"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
@@ -19,14 +20,16 @@ type MCPTool struct {
|
||||
service *types.MCPService
|
||||
mcpTool *types.MCPTool
|
||||
mcpManager *mcp.MCPManager
|
||||
gate approval.MCPApproval // optional human approval before CallTool (issue #1173)
|
||||
}
|
||||
|
||||
// NewMCPTool creates a new MCP tool wrapper
|
||||
func NewMCPTool(service *types.MCPService, mcpTool *types.MCPTool, mcpManager *mcp.MCPManager) *MCPTool {
|
||||
func NewMCPTool(service *types.MCPService, mcpTool *types.MCPTool, mcpManager *mcp.MCPManager, gate approval.MCPApproval) *MCPTool {
|
||||
return &MCPTool{
|
||||
service: service,
|
||||
mcpTool: mcpTool,
|
||||
mcpManager: mcpManager,
|
||||
gate: gate,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,13 +96,77 @@ func (t *MCPTool) Execute(ctx context.Context, args json.RawMessage) (*types.Too
|
||||
// Parse args from json.RawMessage
|
||||
var input MCPInput
|
||||
if err := json.Unmarshal(args, &input); err != nil {
|
||||
logger.Errorf(ctx, "[Tool][DatabaseQuery] Failed to parse args: %v", err)
|
||||
logger.Errorf(ctx, "[Tool][MCPTool] Failed to parse args: %v", err)
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: fmt.Sprintf("Failed to parse args: %v", err),
|
||||
}, err
|
||||
}
|
||||
|
||||
// Human approval gate for dangerous tools (issue #1173)
|
||||
if t.gate != nil {
|
||||
if meta, ok := ToolExecFromContext(ctx); ok && meta != nil && meta.EventBus != nil {
|
||||
tenantID, _ := types.TenantIDFromContext(ctx)
|
||||
if t.gate.NeedsApproval(ctx, tenantID, t.service.ID, t.mcpTool.Name) {
|
||||
// Use ApprovalCtx (round-level ctx WITHOUT defaultToolExecTimeout) so
|
||||
// human approval can legitimately wait longer than the per-tool 60s.
|
||||
// User-stop / request cancel still propagates because ApprovalCtx is a
|
||||
// child of the request ctx.
|
||||
waitCtx := ctx
|
||||
if meta.ApprovalCtx != nil {
|
||||
waitCtx = meta.ApprovalCtx
|
||||
}
|
||||
decision, waitErr := t.gate.RequestAndWait(waitCtx, approval.PendingRequest{
|
||||
TenantID: tenantID,
|
||||
SessionID: meta.SessionID,
|
||||
AssistantMessageID: meta.AssistantMessageID,
|
||||
RequestID: meta.RequestID,
|
||||
EventBus: meta.EventBus,
|
||||
ServiceID: t.service.ID,
|
||||
ServiceName: t.service.Name,
|
||||
MCPToolName: t.mcpTool.Name,
|
||||
RegisteredToolName: t.Name(),
|
||||
Description: t.mcpTool.Description,
|
||||
Args: args,
|
||||
ToolCallID: meta.ToolCallID,
|
||||
})
|
||||
if waitErr != nil {
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: fmt.Sprintf("Tool approval failed: %v", waitErr),
|
||||
}, nil
|
||||
}
|
||||
if !decision.Approved {
|
||||
msg := decision.Reason
|
||||
if msg == "" {
|
||||
msg = "tool execution rejected by user"
|
||||
}
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: msg,
|
||||
}, nil
|
||||
}
|
||||
if len(decision.ModifiedArgs) > 0 {
|
||||
args = decision.ModifiedArgs
|
||||
if err := json.Unmarshal(args, &input); err != nil {
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: fmt.Sprintf("Invalid modified_args after approval: %v", err),
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
// Approval may have consumed most/all of the per-tool 60s 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)
|
||||
defer freshCancel()
|
||||
ctx = freshCtx
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get or create MCP client
|
||||
client, err := t.mcpManager.GetOrCreateClient(t.service)
|
||||
if err != nil {
|
||||
@@ -326,6 +393,7 @@ func RegisterMCPTools(
|
||||
registry *ToolRegistry,
|
||||
services []*types.MCPService,
|
||||
mcpManager *mcp.MCPManager,
|
||||
gate approval.MCPApproval,
|
||||
) error {
|
||||
if len(services) == 0 {
|
||||
return nil
|
||||
@@ -393,7 +461,7 @@ func RegisterMCPTools(
|
||||
|
||||
// Register each tool
|
||||
for _, mcpTool := range mcpTools {
|
||||
tool := NewMCPTool(service, mcpTool, mcpManager)
|
||||
tool := NewMCPTool(service, mcpTool, mcpManager, gate)
|
||||
toolName := tool.Name()
|
||||
|
||||
// Check for name collision before registering (first-wins policy).
|
||||
|
||||
Reference in New Issue
Block a user