From d3d496398977d07891e6e049d08bc74e382c5f77 Mon Sep 17 00:00:00 2001 From: Guo-Yixin Date: Fri, 16 Oct 2026 04:17:33 -0500 Subject: [PATCH] fix(mcp): avoid replaying tools after ambiguous call failures (#4124) * fix(mcp): avoid replaying tools after ambiguous call failures * test(mcp): cover negotiated handshakes and OAuth call failures --- internal/agent/tools/mcp_call_retry_test.go | 189 ++++++++++++++++++++ internal/agent/tools/mcp_oauth.go | 3 + internal/agent/tools/mcp_tool.go | 2 +- internal/mcp/client.go | 13 +- internal/mcp/client_call_error_test.go | 87 +++++++++ internal/mcp/errors.go | 22 ++- internal/mcp/errors_test.go | 40 +++++ website-docs/03-features/08-mcp.md | 6 + 8 files changed, 359 insertions(+), 3 deletions(-) create mode 100644 internal/agent/tools/mcp_call_retry_test.go create mode 100644 internal/mcp/client_call_error_test.go create mode 100644 internal/mcp/errors_test.go diff --git a/internal/agent/tools/mcp_call_retry_test.go b/internal/agent/tools/mcp_call_retry_test.go new file mode 100644 index 00000000..993ebff7 --- /dev/null +++ b/internal/agent/tools/mcp_call_retry_test.go @@ -0,0 +1,189 @@ +package tools + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + + "github.com/Tencent/WeKnora/internal/agent/approval" + "github.com/Tencent/WeKnora/internal/event" + internalmcp "github.com/Tencent/WeKnora/internal/mcp" + "github.com/Tencent/WeKnora/internal/modelcontext" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/utils" + sdkmcp "github.com/mark3labs/mcp-go/mcp" + sdkserver "github.com/mark3labs/mcp-go/server" + "github.com/stretchr/testify/require" +) + +type retryApprovalGate struct { + proxyApprovalGate + approvals atomic.Int32 +} + +func (g *retryApprovalGate) RequestAndWait( + ctx context.Context, request approval.PendingRequest, +) (approval.Decision, error) { + g.approvals.Add(1) + return g.proxyApprovalGate.RequestAndWait(ctx, request) +} + +func TestMCPCallRetryDoesNotRepeatAmbiguousExecution(t *testing.T) { + utils.SetSSRFWhitelistFromRaw("127.0.0.1") + t.Cleanup(utils.ResetSSRFWhitelistForTest) + tests := []struct { + name string + wantRequests int32 + wantExecuted int32 + wantSuccess bool + wantUnknown bool + }{ + {name: "http_error_after_execution", wantRequests: 1, wantExecuted: 1, wantUnknown: true}, + {name: "connection_lost_after_execution", wantRequests: 1, wantExecuted: 1, wantUnknown: true}, + {name: "rpc_error_after_execution", wantRequests: 1, wantExecuted: 1, wantUnknown: true}, + {name: "cancel_after_execution", wantRequests: 1, wantExecuted: 1, wantUnknown: true}, + {name: "expired_session", wantRequests: 2, wantExecuted: 1, wantSuccess: true}, + {name: "repeated_expired_session", wantRequests: 2}, + {name: "authorization_rejection", wantRequests: 2}, + {name: "tool_error", wantRequests: 1, wantExecuted: 1}, + {name: "success", wantRequests: 1, wantExecuted: 1, wantSuccess: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctx, cancel := context.WithCancel(catalogTestContext()) + t.Cleanup(cancel) + var requests, executed, handshakes atomic.Int32 + server := sdkserver.NewMCPServer("Orders", "1", sdkserver.WithToolCapabilities(false)) + server.AddTool( + sdkmcp.NewTool("create_order"), + func(context.Context, sdkmcp.CallToolRequest) (*sdkmcp.CallToolResult, error) { + executed.Add(1) + if tt.name == "tool_error" { + return sdkmcp.NewToolResultError("order refused"), nil + } + return sdkmcp.NewToolResultText("order created"), nil + }, + ) + transport := sdkserver.NewStreamableHTTPServer(server, sdkserver.WithDisableStreaming(true)) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + transport.ServeHTTP(w, r) + return + } + body, err := io.ReadAll(r.Body) + if err != nil { + t.Errorf("read request: %v", err) + return + } + r.Body = io.NopCloser(bytes.NewReader(body)) + var request struct { + ID json.RawMessage `json:"id"` + Method string `json:"method"` + } + if err := json.Unmarshal(body, &request); err != nil { + t.Errorf("decode request: %v", err) + return + } + // Count the handshake selected by either the legacy or modern SDK. + if request.Method == "initialize" || request.Method == "server/discover" { + handshakes.Add(1) + } + if request.Method != "tools/call" { + transport.ServeHTTP(w, r) + return + } + attempt := requests.Add(1) + if tt.name == "authorization_rejection" { + http.Error(w, "authorization required", http.StatusUnauthorized) + return + } + if tt.name == "repeated_expired_session" || (tt.name == "expired_session" && attempt == 1) { + http.Error(w, "session expired", http.StatusNotFound) + return + } + // Execute the real SDK tool first, then lose/replace its response. + // This models a committed write whose result never reaches the client. + if attempt == 1 { + switch tt.name { + case "http_error_after_execution", "connection_lost_after_execution", + "rpc_error_after_execution", "cancel_after_execution": + recorder := httptest.NewRecorder() + transport.ServeHTTP(recorder, r) + switch tt.name { + case "http_error_after_execution": + http.Error(w, "response lost at gateway", http.StatusBadGateway) + case "connection_lost_after_execution": + conn, _, err := w.(http.Hijacker).Hijack() + if err != nil { + t.Errorf("hijack response: %v", err) + return + } + _ = conn.Close() + case "rpc_error_after_execution": + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "jsonrpc": "2.0", "id": request.ID, + "error": map[string]any{"code": -32603, "message": "post-write failure"}, + }) + case "cancel_after_execution": + cancel() + } + return + } + } + transport.ServeHTTP(w, r) + })) + t.Cleanup(upstream.Close) + manager := internalmcp.NewMCPManager(nil) + t.Cleanup(manager.Shutdown) + service := &types.MCPService{ + ID: "orders", Name: "Orders", TenantID: 7, Enabled: true, + URL: &upstream.URL, TransportType: types.MCPTransportHTTPStreamable, + } + registry, gate := NewToolRegistry(), &retryApprovalGate{} + _, err := RegisterMCPTools(ctx, registry, []*types.MCPService{service}, manager, gate, 0, nil, nil) + require.NoError(t, err) + tool := describeTool(ctx, t, registry, service.ID, "create_order") + ctx = WithToolExecContext(ctx, &ToolExecContext{ + EventBus: event.NewEventBus(), ToolCallID: "create-order", ApprovalCtx: ctx, + }) + args, err := json.Marshal(map[string]any{"tool_ref": tool.ToolRef, "arguments": map[string]any{}}) + require.NoError(t, err) + result, err := registry.ExecuteTool(ctx, ToolCallMCPTool, args) + require.NoError(t, err) + t.Logf("requests=%d, server executions=%d, approvals=%d", + requests.Load(), executed.Load(), gate.approvals.Load()) + require.Equal(t, tt.wantRequests, requests.Load(), "one approval must not authorize blind replays") + require.Equal(t, tt.wantExecuted, executed.Load()) + require.EqualValues(t, 1, gate.approvals.Load()) + require.Equal(t, tt.wantSuccess, result.Success) + visible := modelcontext.NewRegistry(true).ModelToolResultForTool(ToolCallMCPTool, result) + if tt.wantUnknown { + require.Contains(t, visible, "outcome is unknown") + require.Contains(t, visible, "Verify") + require.NotContains(t, visible, "Failed to connect") + } else { + require.NotContains(t, visible, "outcome is unknown") + } + if tt.name == "expired_session" || tt.name == "repeated_expired_session" { + require.EqualValues(t, 2, handshakes.Load(), "retain bounded recovery of rejected sessions") + } + if tt.wantUnknown && tt.name != "cancel_after_execution" { + // A subsequent deliberate call remains possible, with a new approval. + ctx = WithToolExecContext(ctx, &ToolExecContext{ + EventBus: event.NewEventBus(), ToolCallID: "verified-retry", ApprovalCtx: ctx, + }) + result, err = registry.ExecuteTool(ctx, ToolCallMCPTool, args) + require.NoError(t, err) + require.True(t, result.Success, result.Error) + require.EqualValues(t, 2, executed.Load()) + require.EqualValues(t, 2, gate.approvals.Load()) + } + }) + } +} diff --git a/internal/agent/tools/mcp_oauth.go b/internal/agent/tools/mcp_oauth.go index aef190fd..fa245f49 100644 --- a/internal/agent/tools/mcp_oauth.go +++ b/internal/agent/tools/mcp_oauth.go @@ -234,6 +234,9 @@ func emitMCPOAuthRequiredNotice( // oauthAwareConnectError turns a low-level MCP connect/call error into a // message the agent (and ultimately the user) can act on. func oauthAwareConnectError(service *types.MCPService, err error) string { + if errors.Is(err, mcp.ErrToolCallOutcomeUnknown) { + return fmt.Sprintf("MCP tool call failed: %v", err) + } if service.AuthConfig.IsOAuth() && isAuthorizationRequired(err) { return fmt.Sprintf( "MCP service %q requires OAuth authorization. Please open the service settings "+ diff --git a/internal/agent/tools/mcp_tool.go b/internal/agent/tools/mcp_tool.go index 1e81b4f3..ccdc13e0 100644 --- a/internal/agent/tools/mcp_tool.go +++ b/internal/agent/tools/mcp_tool.go @@ -318,7 +318,7 @@ func (t *MCPTool) Execute(ctx context.Context, args json.RawMessage) (*types.Too } result, err := client.CallTool(callCtx, t.mcpTool.Name, input) - if err != nil && !isStdio { + if err != nil && !isStdio && callCtx.Err() == nil && mcp.IsToolCallRetrySafe(err) { logger.GetLogger(callCtx).Warnf("MCP tool call failed, retrying with fresh connection: %v", err) _ = client.Disconnect() diff --git a/internal/mcp/client.go b/internal/mcp/client.go index b3c548b0..ebc7dde2 100644 --- a/internal/mcp/client.go +++ b/internal/mcp/client.go @@ -818,11 +818,22 @@ func (c *mcpGoClient) CallTool(ctx context.Context, name string, args map[string } } + var callErr error result, err := oauthCall(ctx, c, func() (*mcp.CallToolResult, error) { - return c.client.CallTool(ctx, req) + result, err := c.client.CallTool(ctx, req) + callErr = err + return result, err }) if err != nil { c.checkErrorAndDisconnectIfNeeded(err) + // Inspect the actual call error, not a preflight/refresh error from + // oauthCall. A rejected authorization did not execute the tool. + if callErr != nil && !IsToolCallRetrySafe(callErr) { + return nil, fmt.Errorf( + "%w; it may already have completed. Verify the remote outcome before retrying: %w", + ErrToolCallOutcomeUnknown, err, + ) + } return nil, fmt.Errorf("failed to call tool: %w", err) } diff --git a/internal/mcp/client_call_error_test.go b/internal/mcp/client_call_error_test.go new file mode 100644 index 00000000..c577d936 --- /dev/null +++ b/internal/mcp/client_call_error_test.go @@ -0,0 +1,87 @@ +package mcp + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/utils" + sdkmcp "github.com/mark3labs/mcp-go/mcp" + sdkserver "github.com/mark3labs/mcp-go/server" + "github.com/stretchr/testify/require" +) + +func TestCallToolOAuthRefreshFailureDoesNotClaimUnknownExecution(t *testing.T) { + for _, expired := range []bool{true, false} { + name := "after_resource_401" + if expired { + name = "before_call" + } + t.Run(name, func(t *testing.T) { + utils.SetSSRFWhitelistFromRaw("127.0.0.1") + t.Cleanup(utils.ResetSSRFWhitelistForTest) + runtime, repo, refreshes, closeIssuer := newOAuthLifecycleFixture(t, http.StatusServiceUnavailable, + map[string]any{"error": "temporarily_unavailable"}) + t.Cleanup(closeIssuer) + row := repo.tokens[fakeOAuthKey(7, runtime.principal, "svc-1")] + row.ExpiresAt = time.Now().Add(time.Hour) + if expired { + row.ExpiresAt = time.Now().Add(-time.Minute) + } + server := sdkserver.NewMCPServer("orders", "1", sdkserver.WithToolCapabilities(false)) + var executed atomic.Int32 + server.AddTool(sdkmcp.NewTool("write"), + func(context.Context, sdkmcp.CallToolRequest) (*sdkmcp.CallToolResult, error) { + executed.Add(1) + return sdkmcp.NewToolResultText("write completed"), nil + }) + transport := sdkserver.NewStreamableHTTPServer(server, sdkserver.WithDisableStreaming(true)) + var calls atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + r.Body = io.NopCloser(bytes.NewReader(body)) + var request struct { + Method string `json:"method"` + } + _ = json.Unmarshal(body, &request) + if request.Method == "tools/call" { + calls.Add(1) + http.Error(w, "authorization required", http.StatusUnauthorized) + return + } + transport.ServeHTTP(w, r) + })) + t.Cleanup(upstream.Close) + client, err := NewMCPClient(&ClientConfig{Service: &types.MCPService{ + ID: "orders", Enabled: true, URL: &upstream.URL, TransportType: types.MCPTransportHTTPStreamable, + }}) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, client.Disconnect()) }) + require.NoError(t, client.Connect(context.Background())) + _, err = client.Initialize(context.Background()) + require.NoError(t, err) + client.(*mcpGoClient).oauth = runtime + _, err = client.CallTool(context.Background(), "write", map[string]any{}) + require.Error(t, err) + var temporary *OAuthRefreshTemporaryError + require.ErrorAs(t, err, &temporary) + require.EqualValues(t, 1, refreshes.Load(), "exercise the failed token refresh") + require.False(t, errors.Is(err, ErrToolCallOutcomeUnknown), + "token refresh failures are not evidence of an attempted write") + require.Zero(t, executed.Load(), "authorization rejects the request before the write handler") + if expired { + require.Zero(t, calls.Load()) + } else { + require.EqualValues(t, 1, calls.Load(), "401 rejects the call before execution") + } + }) + } +} diff --git a/internal/mcp/errors.go b/internal/mcp/errors.go index 5ff32944..7f9e5d9e 100644 --- a/internal/mcp/errors.go +++ b/internal/mcp/errors.go @@ -1,6 +1,10 @@ package mcp -import "errors" +import ( + "errors" + + "github.com/mark3labs/mcp-go/client/transport" +) var ( // ErrUnsupportedTransport is returned when transport type is not supported @@ -29,4 +33,20 @@ var ( // ErrConnectionClosed is returned when connection is closed unexpectedly ErrConnectionClosed = errors.New("connection closed") + + // ErrToolCallOutcomeUnknown means a call was attempted but its response + // does not establish whether the server executed the tool. + ErrToolCallOutcomeUnknown = errors.New("MCP tool execution outcome is unknown") ) + +// IsToolCallRetrySafe identifies rejections before tool execution. A missing +// local connection sends no request; a terminated HTTP session is rejected +// with 404 and requires initialization. Typed authorization failures also +// reject the request and may require in-conversation authorization recovery. +// Other transport/RPC failures may occur after a side effect and must not +// authorize an automatic replay. +func IsToolCallRetrySafe(err error) bool { + return !errors.Is(err, ErrToolCallOutcomeUnknown) && + (errors.Is(err, ErrNotConnected) || errors.Is(err, transport.ErrSessionTerminated) || + isOAuthAuthorizationFailure(err)) +} diff --git a/internal/mcp/errors_test.go b/internal/mcp/errors_test.go new file mode 100644 index 00000000..66ed3dbf --- /dev/null +++ b/internal/mcp/errors_test.go @@ -0,0 +1,40 @@ +package mcp + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/mark3labs/mcp-go/client/transport" + "github.com/stretchr/testify/require" +) + +func TestIsToolCallRetrySafe(t *testing.T) { + tests := []struct { + name string + err error + safe bool + }{ + {name: "nil"}, + {name: "not_connected", err: fmt.Errorf("call: %w", ErrNotConnected), safe: true}, + { + name: "expired_session", + err: fmt.Errorf("call: %w", transport.NewError(transport.ErrSessionTerminated)), + safe: true, + }, + {name: "timeout", err: transport.NewError(context.DeadlineExceeded)}, + {name: "cancel", err: fmt.Errorf("call: %w", context.Canceled)}, + {name: "eof", err: errors.New("unexpected EOF")}, + {name: "session_text", err: transport.NewError(errors.New("Invalid session ID"))}, + {name: "authorization_required", err: &transport.AuthorizationRequiredError{}, safe: true}, + {name: "oauth_required", err: &transport.OAuthAuthorizationRequiredError{}, safe: true}, + {name: "reauthorization_required", err: &OAuthReauthorizationRequiredError{}, safe: true}, + {name: "unknown", err: errors.Join(ErrToolCallOutcomeUnknown, ErrNotConnected)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + require.Equal(t, tt.safe, IsToolCallRetrySafe(tt.err)) + }) + } +} diff --git a/website-docs/03-features/08-mcp.md b/website-docs/03-features/08-mcp.md index e055d52f..4d5ab5c3 100644 --- a/website-docs/03-features/08-mcp.md +++ b/website-docs/03-features/08-mcp.md @@ -344,6 +344,12 @@ Agent 启动时由 `internal/application/service/agent_service.go` 按 Agent 配 Mention 只是优先选择,不改变 Agent 的 `all / selected / none` 范围。全量函数暴露保留为兼容路径,不是生产默认。 +##### 工具调用失败与重试 + +远端工具可能已经执行操作,但响应在网络中丢失,或服务端在操作完成后返回错误。此时 WeKnora 会提示执行结果不确定,在同一次调用中不自动重复提交工具。请先在远端系统核实操作是否已完成,再决定是否重新调用;新调用仍按原有工具审批策略处理。 + +客户端尚未连接,或服务端因会话失效返回 HTTP 404 时,保留最多一次重连重试;请求取消后不发起该重试。OAuth 401 的刷新和重试仍按原有授权流程处理。 + ##### 持久目录的管理 {#mcp-tool-directory} 设置页先保存连接,再编辑使用说明、同步工具。已有目录可离线查看;连接或认证修改后旧快照标为 `stale`,需要刷新才能用于运行时,刷新失败不会用不完整目录覆盖上一份快照。