feat(mcp): implement reconnection logic for MCP tool calls and tool listing

- Added a reconnection retry mechanism for MCP tool calls and tool listing operations to handle stale connections.
- Enhanced error logging to provide clearer feedback during reconnection attempts.
- Updated comments for clarity on the retry behavior and connection management.
This commit is contained in:
wizardchen
2026-03-31 11:45:05 +08:00
committed by lyingbug
parent 1f01183057
commit aed88d4d9d
2 changed files with 50 additions and 14 deletions
+36 -6
View File
@@ -122,8 +122,23 @@ func (t *MCPTool) Execute(ctx context.Context, args json.RawMessage) (*types.Too
}()
}
// Call the tool via MCP
// Call the tool via MCP (with one reconnection retry on failure)
result, err := client.CallTool(ctx, t.mcpTool.Name, input)
if err != nil && !isStdio {
logger.GetLogger(ctx).Warnf("MCP tool call failed, retrying with fresh connection: %v", err)
_ = client.Disconnect()
client, err = t.mcpManager.GetOrCreateClient(t.service)
if err != nil {
logger.GetLogger(ctx).Errorf("Failed to reconnect MCP client: %v", err)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to reconnect to MCP service: %v", err),
}, nil
}
result, err = client.CallTool(ctx, t.mcpTool.Name, input)
}
if err != nil {
logger.GetLogger(ctx).Errorf("MCP tool call failed: %v", err)
return &types.ToolResult{
@@ -350,11 +365,26 @@ func RegisterMCPTools(
}()
}
// List tools from the service with timeout
// Create a new context with timeout for this specific operation
// List tools from the service with timeout.
// If the cached connection is stale, disconnect and retry once.
listCtx, cancel := context.WithTimeout(ctx, listToolsTimeout)
tools, err := client.ListTools(listCtx)
cancel() // Cancel after ListTools completes
mcpTools, err := client.ListTools(listCtx)
cancel()
if err != nil && !isStdio {
logger.GetLogger(ctx).Warnf("Failed to list tools from MCP service %s (will retry with fresh connection): %v", service.Name, err)
_ = client.Disconnect()
client, err = mcpManager.GetOrCreateClient(service)
if err != nil {
logger.GetLogger(ctx).Errorf("Failed to reconnect MCP client for service %s: %v", service.Name, err)
continue
}
retryCtx, retryCancel := context.WithTimeout(ctx, listToolsTimeout)
mcpTools, err = client.ListTools(retryCtx)
retryCancel()
}
if err != nil {
logger.GetLogger(ctx).Errorf("Failed to list tools from MCP service %s: %v", service.Name, err)
@@ -362,7 +392,7 @@ func RegisterMCPTools(
}
// Register each tool
for _, mcpTool := range tools {
for _, mcpTool := range mcpTools {
tool := NewMCPTool(service, mcpTool, mcpManager)
toolName := tool.Name()
+14 -8
View File
@@ -140,16 +140,22 @@ func (c *mcpGoClient) onConnectionLost(err error) {
logger.Warnf(context.Background(), "MCP server connection has been lost, URL:%s, error:%v", *c.service.URL, err)
}
// checkErrorAndDisconnectIfNeeded Check for errors and call Disconnect when reconnection is required
// checkErrorAndDisconnectIfNeeded checks for transport errors that indicate the
// session is no longer valid and proactively disconnects the client so that
// subsequent GetOrCreateClient calls will establish a fresh connection.
// Both SSE and HTTP Streamable transports use server-assigned sessions
// (via Mcp-Session-Id header) that can expire or be invalidated.
func (c *mcpGoClient) checkErrorAndDisconnectIfNeeded(err error) {
var transportErr *transport.Error
// In SSE transport type, connection loss does not always actively trigger onConnectionLost (a go-mcp issue).
// Once the connection is lost, the session becomes invalid.
// Without reconnecting, it will continuously cause "Invalid session ID" errors.
if c.service.TransportType == types.MCPTransportSSE &&
errors.As(err, &transportErr) &&
transportErr.Err != nil &&
strings.Contains(transportErr.Err.Error(), "Invalid session ID") {
if !errors.As(err, &transportErr) || transportErr.Err == nil {
return
}
errMsg := transportErr.Err.Error()
// Known session invalidation errors from MCP servers:
// - "Invalid session ID" — server recognises the header but rejects the value
// - "No active connection" — server has no record of the session at all
if strings.Contains(errMsg, "Invalid session ID") ||
strings.Contains(errMsg, "No active connection") {
_ = c.Disconnect()
}
}