feat: Add MCP services support and enhance migration scripts
- Introduced new MCP services functionality, including management routes and integration with the agent service. - Updated Docker Compose configuration to include a new SQL migration for MCP services. - Enhanced Makefile with new migration commands for versioning and creating migrations. - Improved chat component to handle selected MCP services in message processing. - Updated migration documentation to reflect new strategies and added MCP services migration files.
This commit is contained in:
@@ -0,0 +1,192 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// MCPManager manages MCP client connections
|
||||
type MCPManager struct {
|
||||
clients map[string]MCPClient // serviceID -> client
|
||||
clientsMu sync.RWMutex
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
// NewMCPManager creates a new MCP manager
|
||||
func NewMCPManager() *MCPManager {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
manager := &MCPManager{
|
||||
clients: make(map[string]MCPClient),
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
}
|
||||
|
||||
// Start cleanup goroutine
|
||||
go manager.cleanupIdleConnections()
|
||||
|
||||
return manager
|
||||
}
|
||||
|
||||
// GetOrCreateClient gets an existing client or creates a new one
|
||||
func (m *MCPManager) GetOrCreateClient(service *types.MCPService) (MCPClient, error) {
|
||||
// Check if client already exists
|
||||
m.clientsMu.RLock()
|
||||
client, exists := m.clients[service.ID]
|
||||
m.clientsMu.RUnlock()
|
||||
|
||||
if exists && client.IsConnected() {
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// Create new client
|
||||
m.clientsMu.Lock()
|
||||
defer m.clientsMu.Unlock()
|
||||
|
||||
// Double check after acquiring write lock
|
||||
client, exists = m.clients[service.ID]
|
||||
if exists && client.IsConnected() {
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// Create new client
|
||||
config := &ClientConfig{
|
||||
Service: service,
|
||||
}
|
||||
|
||||
client, err := NewMCPClient(config)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create MCP client: %w", err)
|
||||
}
|
||||
|
||||
// Connect to service
|
||||
ctx, cancel := context.WithTimeout(m.ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := client.Connect(ctx); err != nil {
|
||||
return nil, fmt.Errorf("failed to connect to MCP service: %w", err)
|
||||
}
|
||||
|
||||
// Initialize
|
||||
if _, err := client.Initialize(ctx); err != nil {
|
||||
client.Disconnect()
|
||||
return nil, fmt.Errorf("failed to initialize MCP client: %w", err)
|
||||
}
|
||||
|
||||
// Store client
|
||||
m.clients[service.ID] = client
|
||||
|
||||
logger.GetLogger(ctx).Infof("MCP client created and initialized for service: %s", service.Name)
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// GetClient gets an existing client
|
||||
func (m *MCPManager) GetClient(serviceID string) (MCPClient, bool) {
|
||||
m.clientsMu.RLock()
|
||||
defer m.clientsMu.RUnlock()
|
||||
|
||||
client, exists := m.clients[serviceID]
|
||||
return client, exists
|
||||
}
|
||||
|
||||
// CloseClient closes and removes a specific client
|
||||
func (m *MCPManager) CloseClient(serviceID string) error {
|
||||
m.clientsMu.Lock()
|
||||
defer m.clientsMu.Unlock()
|
||||
|
||||
client, exists := m.clients[serviceID]
|
||||
if !exists {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := client.Disconnect(); err != nil {
|
||||
logger.GetLogger(m.ctx).Errorf("Failed to disconnect MCP client %s: %v", serviceID, err)
|
||||
}
|
||||
|
||||
delete(m.clients, serviceID)
|
||||
logger.GetLogger(m.ctx).Infof("MCP client closed: %s", serviceID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// CloseAll closes all clients
|
||||
func (m *MCPManager) CloseAll() {
|
||||
m.clientsMu.Lock()
|
||||
defer m.clientsMu.Unlock()
|
||||
|
||||
for serviceID, client := range m.clients {
|
||||
if err := client.Disconnect(); err != nil {
|
||||
logger.GetLogger(m.ctx).Errorf("Failed to disconnect MCP client %s: %v", serviceID, err)
|
||||
}
|
||||
}
|
||||
|
||||
m.clients = make(map[string]MCPClient)
|
||||
logger.GetLogger(m.ctx).Info("All MCP clients closed")
|
||||
}
|
||||
|
||||
// Shutdown gracefully shuts down the manager
|
||||
func (m *MCPManager) Shutdown() {
|
||||
m.cancel()
|
||||
m.CloseAll()
|
||||
}
|
||||
|
||||
// cleanupIdleConnections periodically cleans up disconnected clients
|
||||
func (m *MCPManager) cleanupIdleConnections() {
|
||||
ticker := time.NewTicker(5 * time.Minute)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-m.ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
m.removeDisconnectedClients()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// removeDisconnectedClients removes clients that are no longer connected
|
||||
func (m *MCPManager) removeDisconnectedClients() {
|
||||
m.clientsMu.Lock()
|
||||
defer m.clientsMu.Unlock()
|
||||
|
||||
for serviceID, client := range m.clients {
|
||||
if !client.IsConnected() {
|
||||
delete(m.clients, serviceID)
|
||||
logger.GetLogger(m.ctx).Infof("Removed disconnected MCP client: %s", serviceID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GetActiveClients returns the number of active clients
|
||||
func (m *MCPManager) GetActiveClients() int {
|
||||
m.clientsMu.RLock()
|
||||
defer m.clientsMu.RUnlock()
|
||||
|
||||
count := 0
|
||||
for _, client := range m.clients {
|
||||
if client.IsConnected() {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// ListActiveServices returns IDs of services with active connections
|
||||
func (m *MCPManager) ListActiveServices() []string {
|
||||
m.clientsMu.RLock()
|
||||
defer m.clientsMu.RUnlock()
|
||||
|
||||
services := make([]string, 0, len(m.clients))
|
||||
for serviceID, client := range m.clients {
|
||||
if client.IsConnected() {
|
||||
services = append(services, serviceID)
|
||||
}
|
||||
}
|
||||
return services
|
||||
}
|
||||
Reference in New Issue
Block a user