|
| 1 | +// Package connection implements MCP connection handling. |
| 2 | +package connection |
| 3 | + |
| 4 | +import ( |
| 5 | + "context" |
| 6 | + "fmt" |
| 7 | + "sync" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/co-browser/agent-browser/internal/log" |
| 11 | + mcpclient "github.com/co-browser/agent-browser/internal/mcp/client" |
| 12 | + "github.com/co-browser/agent-browser/internal/mcp/config" |
| 13 | + "github.com/mark3labs/mcp-go/mcp" |
| 14 | +) |
| 15 | + |
| 16 | +// MCPConnection represents a connection to a remote MCP server |
| 17 | +type MCPConnection struct { |
| 18 | + Client *mcpclient.SSEMCPClient |
| 19 | + URL string |
| 20 | + Ctx context.Context |
| 21 | + Cancel context.CancelFunc |
| 22 | + Tools []mcp.Tool |
| 23 | + mu sync.RWMutex |
| 24 | +} |
| 25 | + |
| 26 | +// GetTools returns the tools list in a thread-safe way |
| 27 | +func (c *MCPConnection) GetTools() []mcp.Tool { |
| 28 | + c.mu.RLock() |
| 29 | + defer c.mu.RUnlock() |
| 30 | + return c.Tools |
| 31 | +} |
| 32 | + |
| 33 | +// RemoteConnections stores active connections to remote servers |
| 34 | +var RemoteConnections = make(map[string]*MCPConnection) |
| 35 | +var ConnectionsMutex sync.RWMutex |
| 36 | + |
| 37 | +// ConnectToRemoteServer establishes a connection to a remote MCP server |
| 38 | +func ConnectToRemoteServer(ctx context.Context, logger log.Logger, remote config.RemoteMCPServer) (*MCPConnection, error) { |
| 39 | + // Check for existing connection |
| 40 | + ConnectionsMutex.RLock() |
| 41 | + existingConn, alreadyConnected := RemoteConnections[remote.URL] |
| 42 | + ConnectionsMutex.RUnlock() |
| 43 | + |
| 44 | + if alreadyConnected && existingConn.Ctx != nil && existingConn.Ctx.Err() == nil { |
| 45 | + // Verify connection is actually healthy before reusing |
| 46 | + if existingConn.Client != nil { |
| 47 | + checkCtx, checkCancel := context.WithTimeout(existingConn.Ctx, 3*time.Second) |
| 48 | + toolsRequest := mcp.ListToolsRequest{} |
| 49 | + _, err := existingConn.Client.ListTools(checkCtx, toolsRequest) |
| 50 | + checkCancel() |
| 51 | + if err == nil { |
| 52 | + logger.Debug().Str("url", remote.URL).Msg("Reusing existing healthy connection") |
| 53 | + return existingConn, nil |
| 54 | + } |
| 55 | + logger.Warn().Err(err).Str("url", remote.URL).Msg("Existing connection found but failed health check, proceeding to reconnect.") |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + // Create new connection |
| 60 | + logger.Debug().Str("url", remote.URL).Msg("Creating new MCP client") |
| 61 | + mcpClient, err := mcpclient.NewSSEMCPClient(remote.URL) |
| 62 | + if err != nil { |
| 63 | + return nil, fmt.Errorf("failed to create client for %s: %w", remote.URL, err) |
| 64 | + } |
| 65 | + |
| 66 | + // Create connection context |
| 67 | + connCtx, baseCancel := context.WithCancel(ctx) |
| 68 | + cancel := func() { |
| 69 | + logger.Warn().Str("url", remote.URL).Msgf("Cancelling connection context") |
| 70 | + baseCancel() |
| 71 | + } |
| 72 | + |
| 73 | + // Start client |
| 74 | + logger.Debug().Str("url", remote.URL).Msg("Starting new MCP client") |
| 75 | + if err := mcpClient.Start(connCtx); err != nil { |
| 76 | + cancel() |
| 77 | + return nil, fmt.Errorf("failed to start client: %w", err) |
| 78 | + } |
| 79 | + |
| 80 | + // Initialize the client |
| 81 | + logger.Debug().Str("url", remote.URL).Msg("Initializing new MCP client") |
| 82 | + initRequest := mcp.InitializeRequest{} |
| 83 | + initRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION |
| 84 | + initRequest.Params.ClientInfo = mcp.Implementation{ |
| 85 | + Name: "cobrowser-agent", |
| 86 | + Version: "1.0.0", |
| 87 | + } |
| 88 | + if _, err := mcpClient.Initialize(connCtx, initRequest); err != nil { |
| 89 | + cancel() |
| 90 | + mcpClient.Close() |
| 91 | + return nil, fmt.Errorf("failed to initialize client: %w", err) |
| 92 | + } |
| 93 | + |
| 94 | + // Get initial tools list |
| 95 | + logger.Debug().Str("url", remote.URL).Msg("Listing tools from new MCP client") |
| 96 | + toolsRequest := mcp.ListToolsRequest{} |
| 97 | + toolsResult, err := mcpClient.ListTools(connCtx, toolsRequest) |
| 98 | + if err != nil { |
| 99 | + cancel() |
| 100 | + mcpClient.Close() |
| 101 | + return nil, fmt.Errorf("failed to list tools: %w", err) |
| 102 | + } |
| 103 | + |
| 104 | + // Create the new connection object |
| 105 | + newConn := &MCPConnection{ |
| 106 | + Client: mcpClient, |
| 107 | + URL: remote.URL, |
| 108 | + Ctx: connCtx, |
| 109 | + Cancel: cancel, |
| 110 | + Tools: toolsResult.Tools, |
| 111 | + } |
| 112 | + |
| 113 | + // Replace any existing connection |
| 114 | + ConnectionsMutex.Lock() |
| 115 | + connToReplace, existsNow := RemoteConnections[remote.URL] |
| 116 | + var oldConnToCleanup *MCPConnection |
| 117 | + if existsNow && connToReplace != nil { |
| 118 | + if connToReplace != newConn { |
| 119 | + logger.Warn().Str("url", remote.URL).Msg("Marking existing connection for cleanup.") |
| 120 | + oldConnToCleanup = connToReplace |
| 121 | + } |
| 122 | + } else if alreadyConnected && existingConn != nil { |
| 123 | + if existingConn != newConn { |
| 124 | + logger.Info().Str("url", remote.URL).Msg("Marking previous connection for cleanup.") |
| 125 | + oldConnToCleanup = existingConn |
| 126 | + } |
| 127 | + } |
| 128 | + |
| 129 | + // Store the new connection |
| 130 | + RemoteConnections[remote.URL] = newConn |
| 131 | + ConnectionsMutex.Unlock() |
| 132 | + |
| 133 | + // Clean up old connection asynchronously if necessary |
| 134 | + if oldConnToCleanup != nil { |
| 135 | + go func(connToClose *MCPConnection) { |
| 136 | + logger.Info().Str("url", connToClose.URL).Msg("Starting asynchronous cleanup of old connection...") |
| 137 | + time.Sleep(50 * time.Millisecond) |
| 138 | + if connToClose.Cancel != nil { |
| 139 | + logger.Info().Str("url", connToClose.URL).Msg("Asynchronously cancelling old connection context.") |
| 140 | + connToClose.Cancel() |
| 141 | + } |
| 142 | + if connToClose.Client != nil { |
| 143 | + logger.Info().Str("url", connToClose.URL).Msg("Asynchronously closing old connection client.") |
| 144 | + connToClose.Client.Close() |
| 145 | + } |
| 146 | + logger.Info().Str("url", connToClose.URL).Msg("Asynchronous cleanup of old connection finished.") |
| 147 | + }(oldConnToCleanup) |
| 148 | + } |
| 149 | + |
| 150 | + logger.Info(). |
| 151 | + Str("url", remote.URL). |
| 152 | + Int("tool_count", len(newConn.Tools)). |
| 153 | + Msg("Successfully established and stored new MCP connection") |
| 154 | + |
| 155 | + return newConn, nil |
| 156 | +} |
| 157 | + |
| 158 | +// CleanupConnections closes all active connections |
| 159 | +func CleanupConnections(logger log.Logger) { |
| 160 | + ConnectionsMutex.Lock() |
| 161 | + defer ConnectionsMutex.Unlock() |
| 162 | + |
| 163 | + for url, conn := range RemoteConnections { |
| 164 | + if conn.Cancel != nil { |
| 165 | + conn.Cancel() |
| 166 | + } |
| 167 | + if conn.Client != nil { |
| 168 | + conn.Client.Close() |
| 169 | + } |
| 170 | + delete(RemoteConnections, url) |
| 171 | + } |
| 172 | + |
| 173 | + logger.Info().Msg("All connections cleaned up") |
| 174 | +} |
0 commit comments