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:
+19
-9
@@ -165,7 +165,7 @@ func formatToolHint(name string, args map[string]any) string {
|
||||
// When ParallelToolCalls is enabled and there are 2+ tool calls, they execute concurrently.
|
||||
func (e *AgentEngine) executeToolCalls(
|
||||
ctx context.Context, response *types.ChatResponse,
|
||||
step *types.AgentStep, iteration int, sessionID string,
|
||||
step *types.AgentStep, iteration int, sessionID, assistantMessageID string,
|
||||
) {
|
||||
if len(response.ToolCalls) == 0 {
|
||||
return
|
||||
@@ -177,12 +177,12 @@ func (e *AgentEngine) executeToolCalls(
|
||||
|
||||
// Use parallel execution when enabled and there are multiple tool calls
|
||||
if e.config.ParallelToolCalls && n >= 2 {
|
||||
e.executeToolCallsParallel(ctx, response, step, iteration, sessionID)
|
||||
e.executeToolCallsParallel(ctx, response, step, iteration, sessionID, assistantMessageID)
|
||||
return
|
||||
}
|
||||
|
||||
for i, tc := range response.ToolCalls {
|
||||
e.executeSingleToolCall(ctx, tc, i, step, iteration, round, sessionID)
|
||||
e.executeSingleToolCall(ctx, tc, i, step, iteration, round, sessionID, assistantMessageID)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,7 +190,7 @@ func (e *AgentEngine) executeToolCalls(
|
||||
// collecting results in original order.
|
||||
func (e *AgentEngine) executeToolCallsParallel(
|
||||
ctx context.Context, response *types.ChatResponse,
|
||||
step *types.AgentStep, iteration int, sessionID string,
|
||||
step *types.AgentStep, iteration int, sessionID, assistantMessageID string,
|
||||
) {
|
||||
round := iteration + 1
|
||||
n := len(response.ToolCalls)
|
||||
@@ -203,7 +203,7 @@ func (e *AgentEngine) executeToolCallsParallel(
|
||||
for i, tc := range response.ToolCalls {
|
||||
i, tc := i, tc // capture loop vars
|
||||
g.Go(func() error {
|
||||
toolCall := e.runToolCall(gCtx, tc, i, iteration, round, sessionID)
|
||||
toolCall := e.runToolCall(gCtx, tc, i, iteration, round, sessionID, assistantMessageID)
|
||||
mu.Lock()
|
||||
results[i] = toolCall
|
||||
mu.Unlock()
|
||||
@@ -258,9 +258,9 @@ func (e *AgentEngine) executeToolCallsParallel(
|
||||
// executeSingleToolCall runs one tool call sequentially (original behavior).
|
||||
func (e *AgentEngine) executeSingleToolCall(
|
||||
ctx context.Context, tc types.LLMToolCall, i int,
|
||||
step *types.AgentStep, iteration, round int, sessionID string,
|
||||
step *types.AgentStep, iteration, round int, sessionID, assistantMessageID string,
|
||||
) {
|
||||
toolCall := e.runToolCall(ctx, tc, i, iteration, round, sessionID)
|
||||
toolCall := e.runToolCall(ctx, tc, i, iteration, round, sessionID, assistantMessageID)
|
||||
step.ToolCalls = append(step.ToolCalls, toolCall)
|
||||
|
||||
result := toolCall.Result
|
||||
@@ -304,7 +304,7 @@ func (e *AgentEngine) executeSingleToolCall(
|
||||
// It returns the completed ToolCall struct. Safe to call from multiple goroutines.
|
||||
func (e *AgentEngine) runToolCall(
|
||||
ctx context.Context, tc types.LLMToolCall, i int,
|
||||
iteration, round int, sessionID string,
|
||||
iteration, round int, sessionID, assistantMessageID string,
|
||||
) types.ToolCall {
|
||||
tc.ID = agenttools.NormalizeToolCallID(tc.ID, tc.Function.Name, i)
|
||||
total := "?" // unknown in isolation; callers log the batch size
|
||||
@@ -392,7 +392,17 @@ func (e *AgentEngine) runToolCall(
|
||||
},
|
||||
})
|
||||
|
||||
execCtx, toolCancel := context.WithTimeout(toolCtx, defaultToolExecTimeout)
|
||||
toolExecCtx := agenttools.WithToolExecContext(toolCtx, &agenttools.ToolExecContext{
|
||||
SessionID: sessionID,
|
||||
AssistantMessageID: assistantMessageID,
|
||||
EventBus: e.eventBus,
|
||||
ToolCallID: tc.ID,
|
||||
// ApprovalCtx keeps the round-level ctx without the per-tool 60s timeout,
|
||||
// so MCP tool human-approval (issue #1173) can legitimately block longer.
|
||||
ApprovalCtx: toolCtx,
|
||||
})
|
||||
|
||||
execCtx, toolCancel := context.WithTimeout(toolExecCtx, defaultToolExecTimeout)
|
||||
result, err := e.toolRegistry.ExecuteTool(
|
||||
execCtx, tc.Function.Name,
|
||||
json.RawMessage(tc.Function.Arguments),
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
// Package approval implements human-in-the-loop gating for dangerous MCP tool calls (issue #1173).
|
||||
package approval
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// pubsubChannel is the Redis channel used to fan-out Resolve calls across
|
||||
// backend replicas (issue #1173 cross-instance support).
|
||||
const pubsubChannel = "weknora:mcp_approval:resolve"
|
||||
|
||||
// resolveMessage is the JSON payload published when one instance receives a
|
||||
// Resolve API call but the pending wait may live on another instance.
|
||||
type resolveMessage struct {
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
PendingID string `json:"pending_id"`
|
||||
Approved bool `json:"approved"`
|
||||
ModifiedArgs json.RawMessage `json:"modified_args,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
TimedOut bool `json:"timed_out,omitempty"`
|
||||
Canceled bool `json:"canceled,omitempty"`
|
||||
}
|
||||
|
||||
// Checker answers whether a concrete MCP tool requires human approval before execution.
|
||||
type Checker interface {
|
||||
IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error)
|
||||
}
|
||||
|
||||
// Decision is the outcome of a pending tool approval.
|
||||
type Decision struct {
|
||||
Approved bool
|
||||
ModifiedArgs json.RawMessage // optional JSON object; when set and Approved, replaces original args
|
||||
Reason string
|
||||
TimedOut bool
|
||||
ContextCanceled bool
|
||||
}
|
||||
|
||||
// PendingRequest carries everything needed to block and notify the UI.
|
||||
type PendingRequest struct {
|
||||
TenantID uint64
|
||||
SessionID string
|
||||
AssistantMessageID string
|
||||
RequestID string
|
||||
EventBus *event.EventBus
|
||||
ServiceID string
|
||||
ServiceName string
|
||||
MCPToolName string // name on MCP server
|
||||
RegisteredToolName string // registry name e.g. mcp_svc_tool
|
||||
Description string
|
||||
Args json.RawMessage
|
||||
ToolCallID string
|
||||
}
|
||||
|
||||
// MCPApproval is the surface used by MCPTool (mockable in tests).
|
||||
type MCPApproval interface {
|
||||
NeedsApproval(ctx context.Context, tenantID uint64, serviceID, toolName string) bool
|
||||
RequestAndWait(ctx context.Context, req PendingRequest) (Decision, error)
|
||||
}
|
||||
|
||||
var _ MCPApproval = (*Gate)(nil)
|
||||
|
||||
// Gate coordinates wait/resolve for MCP tool approvals.
|
||||
//
|
||||
// Pending waiters live in-memory on the instance that started RequestAndWait.
|
||||
// When a redis client is supplied, Resolve calls hitting any replica are
|
||||
// published over Redis Pub/Sub so the owning instance can deliver the decision
|
||||
// (issue #1173 cross-instance support). Without redis, the gate degrades to
|
||||
// single-process behavior (deployments must use sticky sessions).
|
||||
type Gate struct {
|
||||
mu sync.Mutex
|
||||
pending map[string]*waiter
|
||||
checker Checker
|
||||
timeout time.Duration
|
||||
rdb *redis.Client // optional; nil disables cross-instance fan-out
|
||||
}
|
||||
|
||||
type waiter struct {
|
||||
ch chan Decision
|
||||
tenantID uint64
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (w *waiter) deliver(d Decision) {
|
||||
if w == nil {
|
||||
return
|
||||
}
|
||||
w.once.Do(func() {
|
||||
select {
|
||||
case w.ch <- d:
|
||||
default:
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
var (
|
||||
// ErrPendingNotFound is returned when Resolve is called with an unknown id.
|
||||
ErrPendingNotFound = errors.New("tool approval pending not found")
|
||||
// ErrTenantMismatch is returned when Resolve tenant does not match the pending request.
|
||||
ErrTenantMismatch = errors.New("tenant mismatch for tool approval")
|
||||
)
|
||||
|
||||
// NewGate builds a gate. checker may be nil (disables gating). cfg may be nil
|
||||
// (defaults apply). rdb may be nil (single-instance mode).
|
||||
func NewGate(cfg *config.Config, checker Checker, rdb *redis.Client) *Gate {
|
||||
timeout := 10 * time.Minute
|
||||
if cfg != nil && cfg.Agent != nil && cfg.Agent.ToolApprovalTimeoutSeconds > 0 {
|
||||
timeout = time.Duration(cfg.Agent.ToolApprovalTimeoutSeconds) * time.Second
|
||||
}
|
||||
g := &Gate{
|
||||
pending: make(map[string]*waiter),
|
||||
checker: checker,
|
||||
timeout: timeout,
|
||||
rdb: rdb,
|
||||
}
|
||||
if rdb != nil {
|
||||
go g.runSubscriber()
|
||||
}
|
||||
return g
|
||||
}
|
||||
|
||||
// runSubscriber listens for cross-instance Resolve fan-outs and delivers
|
||||
// decisions to local waiters. Runs for the lifetime of the process.
|
||||
func (g *Gate) runSubscriber() {
|
||||
ctx := context.Background()
|
||||
for {
|
||||
sub := g.rdb.Subscribe(ctx, pubsubChannel)
|
||||
ch := sub.Channel()
|
||||
for msg := range ch {
|
||||
var m resolveMessage
|
||||
if err := json.Unmarshal([]byte(msg.Payload), &m); err != nil {
|
||||
logger.GetLogger(ctx).Warnf("mcp approval pubsub: bad payload: %v", err)
|
||||
continue
|
||||
}
|
||||
if err := g.deliverLocal(m.TenantID, m.PendingID, Decision{
|
||||
Approved: m.Approved,
|
||||
ModifiedArgs: m.ModifiedArgs,
|
||||
Reason: m.Reason,
|
||||
TimedOut: m.TimedOut,
|
||||
ContextCanceled: m.Canceled,
|
||||
}); err != nil && !errors.Is(err, ErrPendingNotFound) {
|
||||
logger.GetLogger(ctx).Warnf("mcp approval pubsub deliver: %v", err)
|
||||
}
|
||||
}
|
||||
_ = sub.Close()
|
||||
// Reconnect after brief backoff if Redis hiccups.
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
// NeedsApproval returns whether execution should pause for human confirmation.
|
||||
func (g *Gate) NeedsApproval(ctx context.Context, tenantID uint64, serviceID, toolName string) bool {
|
||||
if g == nil || g.checker == nil || tenantID == 0 || serviceID == "" || toolName == "" {
|
||||
return false
|
||||
}
|
||||
ok, err := g.checker.IsRequired(ctx, tenantID, serviceID, toolName)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Warnf("mcp tool approval check failed (skip gate): %v", err)
|
||||
return false
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
// RequestAndWait emits a UI event, then blocks until Resolve, timeout, or ctx cancellation.
|
||||
func (g *Gate) RequestAndWait(ctx context.Context, req PendingRequest) (Decision, error) {
|
||||
if g == nil {
|
||||
return Decision{Approved: true}, nil
|
||||
}
|
||||
if g.checker == nil {
|
||||
return Decision{Approved: true}, nil
|
||||
}
|
||||
if req.EventBus == nil {
|
||||
return Decision{}, fmt.Errorf("tool approval: EventBus is nil")
|
||||
}
|
||||
|
||||
pendingID := uuid.New().String()
|
||||
w := &waiter{
|
||||
ch: make(chan Decision, 1),
|
||||
tenantID: req.TenantID,
|
||||
}
|
||||
|
||||
g.mu.Lock()
|
||||
g.pending[pendingID] = w
|
||||
g.mu.Unlock()
|
||||
|
||||
defer func() {
|
||||
g.mu.Lock()
|
||||
delete(g.pending, pendingID)
|
||||
g.mu.Unlock()
|
||||
}()
|
||||
|
||||
var argsObj interface{}
|
||||
if len(req.Args) > 0 {
|
||||
_ = json.Unmarshal(req.Args, &argsObj)
|
||||
}
|
||||
|
||||
timeoutSec := int(g.timeout / time.Second)
|
||||
if timeoutSec < 1 {
|
||||
timeoutSec = 1
|
||||
}
|
||||
|
||||
evtData := event.ToolApprovalRequiredData{
|
||||
PendingID: pendingID,
|
||||
TenantID: req.TenantID,
|
||||
SessionID: req.SessionID,
|
||||
AssistantMessageID: req.AssistantMessageID,
|
||||
ServiceID: req.ServiceID,
|
||||
ServiceName: req.ServiceName,
|
||||
MCPToolName: req.MCPToolName,
|
||||
RegisteredToolName: req.RegisteredToolName,
|
||||
Description: req.Description,
|
||||
Args: argsObj,
|
||||
ArgsJSON: string(req.Args),
|
||||
TimeoutSeconds: timeoutSec,
|
||||
RequestedAtUnix: time.Now().Unix(),
|
||||
ToolCallID: req.ToolCallID,
|
||||
RequestID: req.RequestID,
|
||||
}
|
||||
|
||||
if err := req.EventBus.Emit(ctx, event.Event{
|
||||
ID: pendingID + "-approval-required",
|
||||
Type: event.EventToolApprovalRequired,
|
||||
SessionID: req.SessionID,
|
||||
Data: evtData,
|
||||
Metadata: map[string]interface{}{
|
||||
"assistant_message_id": req.AssistantMessageID,
|
||||
"pending_id": pendingID,
|
||||
},
|
||||
RequestID: req.RequestID,
|
||||
}); err != nil {
|
||||
return Decision{}, fmt.Errorf("emit tool approval required: %w", err)
|
||||
}
|
||||
|
||||
timer := time.NewTimer(g.timeout)
|
||||
defer timer.Stop()
|
||||
|
||||
emitResolved := func(d Decision) {
|
||||
if req.EventBus == nil {
|
||||
return
|
||||
}
|
||||
_ = req.EventBus.Emit(context.WithoutCancel(ctx), event.Event{
|
||||
ID: pendingID + "-approval-resolved",
|
||||
Type: event.EventToolApprovalResolved,
|
||||
SessionID: req.SessionID,
|
||||
Data: event.ToolApprovalResolvedData{
|
||||
PendingID: pendingID,
|
||||
Approved: d.Approved,
|
||||
Reason: d.Reason,
|
||||
TimedOut: d.TimedOut,
|
||||
Canceled: d.ContextCanceled,
|
||||
},
|
||||
Metadata: map[string]interface{}{
|
||||
"assistant_message_id": req.AssistantMessageID,
|
||||
},
|
||||
RequestID: req.RequestID,
|
||||
})
|
||||
}
|
||||
|
||||
var d Decision
|
||||
select {
|
||||
case d = <-w.ch:
|
||||
emitResolved(d)
|
||||
return d, nil
|
||||
case <-timer.C:
|
||||
d = Decision{Approved: false, Reason: "approval timeout", TimedOut: true}
|
||||
w.deliver(d)
|
||||
d = <-w.ch
|
||||
emitResolved(d)
|
||||
return d, nil
|
||||
case <-ctx.Done():
|
||||
d = Decision{Approved: false, Reason: "request canceled", ContextCanceled: true}
|
||||
w.deliver(d)
|
||||
d = <-w.ch
|
||||
emitResolved(d)
|
||||
return d, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve completes a pending approval. tenantID must match the tenant that
|
||||
// started the wait. If the waiter is not on this instance and Redis Pub/Sub
|
||||
// is configured, the decision is fanned out to all replicas (best-effort).
|
||||
func (g *Gate) Resolve(tenantID uint64, pendingID string, d Decision) error {
|
||||
if g == nil {
|
||||
return fmt.Errorf("gate is nil")
|
||||
}
|
||||
switch err := g.deliverLocal(tenantID, pendingID, d); {
|
||||
case err == nil:
|
||||
return nil
|
||||
case errors.Is(err, ErrTenantMismatch):
|
||||
return err
|
||||
case errors.Is(err, ErrPendingNotFound):
|
||||
if g.rdb == nil {
|
||||
return err
|
||||
}
|
||||
// Fan out to other replicas.
|
||||
payload, mErr := json.Marshal(resolveMessage{
|
||||
TenantID: tenantID,
|
||||
PendingID: pendingID,
|
||||
Approved: d.Approved,
|
||||
ModifiedArgs: d.ModifiedArgs,
|
||||
Reason: d.Reason,
|
||||
TimedOut: d.TimedOut,
|
||||
Canceled: d.ContextCanceled,
|
||||
})
|
||||
if mErr != nil {
|
||||
return fmt.Errorf("encode pubsub payload: %w", mErr)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
if pErr := g.rdb.Publish(ctx, pubsubChannel, payload).Err(); pErr != nil {
|
||||
return fmt.Errorf("publish approval resolve: %w", pErr)
|
||||
}
|
||||
// Best-effort: the owning instance will deliver and emit Resolved.
|
||||
return nil
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// deliverLocal attempts to satisfy a waiter on this instance only.
|
||||
func (g *Gate) deliverLocal(tenantID uint64, pendingID string, d Decision) error {
|
||||
g.mu.Lock()
|
||||
w, ok := g.pending[pendingID]
|
||||
if !ok {
|
||||
g.mu.Unlock()
|
||||
return ErrPendingNotFound
|
||||
}
|
||||
if w.tenantID != tenantID {
|
||||
g.mu.Unlock()
|
||||
return ErrTenantMismatch
|
||||
}
|
||||
g.mu.Unlock()
|
||||
|
||||
w.deliver(d)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Adapter makes MCPToolApprovalService satisfy Checker without importing the service package here.
|
||||
type Adapter struct {
|
||||
Svc interface {
|
||||
IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error)
|
||||
}
|
||||
}
|
||||
|
||||
// IsRequired implements Checker.
|
||||
func (a *Adapter) IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) {
|
||||
if a == nil || a.Svc == nil {
|
||||
return false, nil
|
||||
}
|
||||
return a.Svc.IsRequired(ctx, tenantID, serviceID, toolName)
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package approval
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type stubChecker struct {
|
||||
required bool
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *stubChecker) IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) {
|
||||
return s.required, s.err
|
||||
}
|
||||
|
||||
func TestGate_RequestAndWait_Approve(t *testing.T) {
|
||||
bus := event.NewEventBus()
|
||||
g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 2}}, &stubChecker{required: true}, nil)
|
||||
|
||||
ctx := context.Background()
|
||||
req := PendingRequest{
|
||||
TenantID: 1,
|
||||
SessionID: "s1",
|
||||
AssistantMessageID: "m1",
|
||||
EventBus: bus,
|
||||
ServiceID: "svc",
|
||||
ServiceName: "svcname",
|
||||
MCPToolName: "danger_tool",
|
||||
RegisteredToolName: "mcp_svcname_danger_tool",
|
||||
Description: "desc",
|
||||
Args: json.RawMessage(`{"a":1}`),
|
||||
ToolCallID: "tc1",
|
||||
}
|
||||
|
||||
bus.On(event.EventToolApprovalRequired, func(_ context.Context, evt event.Event) error {
|
||||
data, ok := evt.Data.(event.ToolApprovalRequiredData)
|
||||
require.True(t, ok)
|
||||
require.NotEmpty(t, data.PendingID)
|
||||
go func() {
|
||||
_ = g.Resolve(1, data.PendingID, Decision{Approved: true, ModifiedArgs: json.RawMessage(`{"a":2}`)})
|
||||
}()
|
||||
return nil
|
||||
})
|
||||
|
||||
d, err := g.RequestAndWait(ctx, req)
|
||||
require.NoError(t, err)
|
||||
require.True(t, d.Approved)
|
||||
require.JSONEq(t, `{"a":2}`, string(d.ModifiedArgs))
|
||||
}
|
||||
|
||||
func TestGate_RequestAndWait_Timeout(t *testing.T) {
|
||||
g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 1}}, &stubChecker{required: true}, nil)
|
||||
ctx := context.Background()
|
||||
req := PendingRequest{
|
||||
TenantID: 1,
|
||||
SessionID: "s1",
|
||||
AssistantMessageID: "m1",
|
||||
EventBus: event.NewEventBus(),
|
||||
ServiceID: "svc",
|
||||
ServiceName: "svcname",
|
||||
MCPToolName: "t",
|
||||
RegisteredToolName: "mcp_svcname_t",
|
||||
Args: json.RawMessage(`{}`),
|
||||
}
|
||||
d, err := g.RequestAndWait(ctx, req)
|
||||
require.NoError(t, err)
|
||||
require.False(t, d.Approved)
|
||||
require.True(t, d.TimedOut)
|
||||
}
|
||||
|
||||
func TestGate_NeedsApproval_NoChecker(t *testing.T) {
|
||||
g := NewGate(nil, nil, nil)
|
||||
require.False(t, g.NeedsApproval(context.Background(), 1, "x", "y"))
|
||||
}
|
||||
@@ -397,7 +397,7 @@ loop:
|
||||
// every exit path (break/continue/next) without having to sprinkle
|
||||
// manual finish calls throughout the many branches below.
|
||||
outcome, iterErr := e.runReActIteration(ctx, state, &messages, tools,
|
||||
sessionID, query, &emptyRetries, &consecutiveSameContent, &lastResponseContent)
|
||||
sessionID, messageID, query, &emptyRetries, &consecutiveSameContent, &lastResponseContent)
|
||||
if iterErr != nil {
|
||||
return state, iterErr
|
||||
}
|
||||
@@ -451,7 +451,7 @@ func (e *AgentEngine) runReActIteration(
|
||||
state *types.AgentState,
|
||||
messagesPtr *[]chat.Message,
|
||||
tools []chat.Tool,
|
||||
sessionID, query string,
|
||||
sessionID, assistantMessageID, query string,
|
||||
emptyRetries, consecutiveSameContent *int,
|
||||
lastResponseContent *string,
|
||||
) (outcome iterOutcome, retErr error) {
|
||||
@@ -625,7 +625,7 @@ func (e *AgentEngine) runReActIteration(
|
||||
}
|
||||
|
||||
// 3. Act: Execute tool calls
|
||||
e.executeToolCalls(ctx, response, &step, state.CurrentRound, sessionID)
|
||||
e.executeToolCalls(ctx, response, &step, state.CurrentRound, sessionID, assistantMessageID)
|
||||
toolCallCount = len(step.ToolCalls)
|
||||
|
||||
// 4. Observe: Add tool results to messages and write to context
|
||||
|
||||
@@ -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