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:
wizardchen
2025-11-09 03:27:24 +08:00
parent 83721f98d4
commit 77b6133e2a
34 changed files with 3577 additions and 1063 deletions
+341
View File
@@ -0,0 +1,341 @@
package mcp
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/mark3labs/mcp-go/client"
"github.com/mark3labs/mcp-go/client/transport"
"github.com/mark3labs/mcp-go/mcp"
)
// MCPClient defines the interface for MCP client implementations
type MCPClient interface {
// Connect establishes connection to the MCP service
Connect(ctx context.Context) error
// Disconnect closes the connection to the MCP service
Disconnect() error
// Initialize performs the MCP initialize handshake
Initialize(ctx context.Context) (*InitializeResult, error)
// ListTools retrieves the list of available tools from the MCP service
ListTools(ctx context.Context) ([]*types.MCPTool, error)
// ListResources retrieves the list of available resources from the MCP service
ListResources(ctx context.Context) ([]*types.MCPResource, error)
// CallTool calls a tool on the MCP service
CallTool(ctx context.Context, name string, args map[string]interface{}) (*CallToolResult, error)
// ReadResource reads a resource from the MCP service
ReadResource(ctx context.Context, uri string) (*ReadResourceResult, error)
// IsConnected returns true if the client is connected
IsConnected() bool
// GetServiceID returns the service ID this client is connected to
GetServiceID() string
}
// ClientConfig represents configuration for creating an MCP client
type ClientConfig struct {
Service *types.MCPService
}
// mcpGoClient wraps mark3labs/mcp-go client to implement our MCPClient interface
type mcpGoClient struct {
service *types.MCPService
client *client.Client
connected bool
initialized bool
}
// NewMCPClient creates a new MCP client based on the transport type
func NewMCPClient(config *ClientConfig) (MCPClient, error) {
// Create HTTP client with timeout
timeout := 30 * time.Second
if config.Service.AdvancedConfig != nil && config.Service.AdvancedConfig.Timeout > 0 {
timeout = time.Duration(config.Service.AdvancedConfig.Timeout) * time.Second
}
httpClient := &http.Client{
Timeout: timeout,
}
// Build headers
headers := make(map[string]string)
for key, value := range config.Service.Headers {
headers[key] = value
}
// Add auth headers
if config.Service.AuthConfig != nil {
if config.Service.AuthConfig.APIKey != "" {
headers["X-API-Key"] = config.Service.AuthConfig.APIKey
}
if config.Service.AuthConfig.Token != "" {
headers["Authorization"] = "Bearer " + config.Service.AuthConfig.Token
}
if config.Service.AuthConfig.CustomHeaders != nil {
for key, value := range config.Service.AuthConfig.CustomHeaders {
headers[key] = value
}
}
}
// Create client based on transport type
var mcpClient *client.Client
var err error
switch config.Service.TransportType {
case types.MCPTransportSSE:
mcpClient, err = client.NewSSEMCPClient(config.Service.URL,
client.WithHTTPClient(httpClient),
client.WithHeaders(headers),
)
if err != nil {
return nil, fmt.Errorf("failed to create SSE client: %w", err)
}
case types.MCPTransportHTTPStreamable:
// For HTTP streamable, we need to use transport options
mcpClient, err = client.NewStreamableHttpClient(config.Service.URL,
transport.WithHTTPBasicClient(httpClient),
transport.WithHTTPHeaders(headers),
)
if err != nil {
return nil, fmt.Errorf("failed to create HTTP streamable client: %w", err)
}
default:
return nil, ErrUnsupportedTransport
}
return &mcpGoClient{
service: config.Service,
client: mcpClient,
}, nil
}
// Connect establishes connection to the MCP service
func (c *mcpGoClient) Connect(ctx context.Context) error {
if c.connected {
return ErrAlreadyConnected
}
// Start the client
if err := c.client.Start(ctx); err != nil {
return fmt.Errorf("failed to start client: %w", err)
}
c.connected = true
logger.GetLogger(ctx).Infof("MCP client connected to %s", c.service.URL)
return nil
}
// Disconnect closes the connection
func (c *mcpGoClient) Disconnect() error {
if !c.connected {
return nil
}
// Close the client
if c.client != nil {
c.client.Close()
}
c.connected = false
c.initialized = false
return nil
}
// Initialize performs the MCP initialize handshake
func (c *mcpGoClient) Initialize(ctx context.Context) (*InitializeResult, error) {
if !c.connected {
return nil, ErrNotConnected
}
// Initialize the client
req := mcp.InitializeRequest{
Params: mcp.InitializeParams{
ProtocolVersion: mcp.LATEST_PROTOCOL_VERSION,
Capabilities: mcp.ClientCapabilities{},
ClientInfo: mcp.Implementation{
Name: "WeKnora",
Version: "1.0.0",
},
},
}
result, err := c.client.Initialize(ctx, req)
if err != nil {
return nil, fmt.Errorf("failed to initialize: %w", err)
}
c.initialized = true
return &InitializeResult{
ProtocolVersion: result.ProtocolVersion,
ServerInfo: ServerInfo{
Name: result.ServerInfo.Name,
Version: result.ServerInfo.Version,
},
}, nil
}
// ListTools retrieves the list of available tools
func (c *mcpGoClient) ListTools(ctx context.Context) ([]*types.MCPTool, error) {
if !c.initialized {
return nil, ErrNotConnected
}
req := mcp.ListToolsRequest{}
result, err := c.client.ListTools(ctx, req)
if err != nil {
return nil, fmt.Errorf("failed to list tools: %w", err)
}
// Convert to our types
tools := make([]*types.MCPTool, len(result.Tools))
for i, tool := range result.Tools {
// Convert InputSchema
var inputSchema map[string]interface{}
// Convert InputSchema to map
data, err := json.Marshal(tool.InputSchema)
if err == nil {
var schemaMap map[string]interface{}
if err := json.Unmarshal(data, &schemaMap); err == nil {
inputSchema = schemaMap
}
}
tools[i] = &types.MCPTool{
Name: tool.Name,
Description: tool.Description,
InputSchema: inputSchema,
}
}
return tools, nil
}
// ListResources retrieves the list of available resources
func (c *mcpGoClient) ListResources(ctx context.Context) ([]*types.MCPResource, error) {
if !c.initialized {
return nil, ErrNotConnected
}
req := mcp.ListResourcesRequest{}
result, err := c.client.ListResources(ctx, req)
if err != nil {
return nil, fmt.Errorf("failed to list resources: %w", err)
}
// Convert to our types
resources := make([]*types.MCPResource, len(result.Resources))
for i, resource := range result.Resources {
resources[i] = &types.MCPResource{
URI: resource.URI,
Name: resource.Name,
Description: resource.Description,
MimeType: resource.MIMEType,
}
}
return resources, nil
}
// CallTool calls a tool on the MCP service
func (c *mcpGoClient) CallTool(ctx context.Context, name string, args map[string]interface{}) (*CallToolResult, error) {
if !c.initialized {
return nil, ErrNotConnected
}
req := mcp.CallToolRequest{
Params: mcp.CallToolParams{
Name: name,
Arguments: args,
},
}
result, err := c.client.CallTool(ctx, req)
if err != nil {
return nil, fmt.Errorf("failed to call tool: %w", err)
}
// Convert to our types
content := make([]ContentItem, 0, len(result.Content))
for _, item := range result.Content {
if textContent, ok := mcp.AsTextContent(item); ok {
content = append(content, ContentItem{
Type: "text",
Text: textContent.Text,
})
} else if imageContent, ok := mcp.AsImageContent(item); ok {
content = append(content, ContentItem{
Type: "image",
Data: imageContent.Data,
MimeType: imageContent.MIMEType,
})
}
}
return &CallToolResult{
IsError: result.IsError,
Content: content,
}, nil
}
// ReadResource reads a resource from the MCP service
func (c *mcpGoClient) ReadResource(ctx context.Context, uri string) (*ReadResourceResult, error) {
if !c.initialized {
return nil, ErrNotConnected
}
req := mcp.ReadResourceRequest{
Params: mcp.ReadResourceParams{
URI: uri,
},
}
result, err := c.client.ReadResource(ctx, req)
if err != nil {
return nil, fmt.Errorf("failed to read resource: %w", err)
}
// Convert to our types
contents := make([]ResourceContent, 0, len(result.Contents))
for _, item := range result.Contents {
if textContent, ok := mcp.AsTextResourceContents(item); ok {
contents = append(contents, ResourceContent{
URI: textContent.URI,
MimeType: textContent.MIMEType,
Text: textContent.Text,
})
} else if blobContent, ok := mcp.AsBlobResourceContents(item); ok {
contents = append(contents, ResourceContent{
URI: blobContent.URI,
MimeType: blobContent.MIMEType,
Blob: blobContent.Blob,
})
}
}
return &ReadResourceResult{
Contents: contents,
}, nil
}
// IsConnected returns true if the client is connected
func (c *mcpGoClient) IsConnected() bool {
return c.connected
}
// GetServiceID returns the service ID
func (c *mcpGoClient) GetServiceID() string {
return c.service.ID
}
+33
View File
@@ -0,0 +1,33 @@
package mcp
import "errors"
var (
// ErrUnsupportedTransport is returned when transport type is not supported
ErrUnsupportedTransport = errors.New("unsupported transport type")
// ErrNotConnected is returned when operation requires connection but client is not connected
ErrNotConnected = errors.New("client not connected")
// ErrAlreadyConnected is returned when trying to connect an already connected client
ErrAlreadyConnected = errors.New("client already connected")
// ErrInitializeFailed is returned when MCP initialize handshake fails
ErrInitializeFailed = errors.New("MCP initialize handshake failed")
// ErrToolNotFound is returned when requested tool is not found
ErrToolNotFound = errors.New("tool not found")
// ErrResourceNotFound is returned when requested resource is not found
ErrResourceNotFound = errors.New("resource not found")
// ErrInvalidResponse is returned when server response is invalid
ErrInvalidResponse = errors.New("invalid response from server")
// ErrTimeout is returned when operation times out
ErrTimeout = errors.New("operation timed out")
// ErrConnectionClosed is returned when connection is closed unexpectedly
ErrConnectionClosed = errors.New("connection closed")
)
+192
View File
@@ -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
}
+66
View File
@@ -0,0 +1,66 @@
package mcp
// InitializeResult represents the result of initialize request
type InitializeResult struct {
ProtocolVersion string `json:"protocolVersion"`
Capabilities ServerCapabilities `json:"capabilities"`
ServerInfo ServerInfo `json:"serverInfo"`
}
// ServerCapabilities represents server capabilities
type ServerCapabilities struct {
Tools *ToolsCapability `json:"tools,omitempty"`
Resources *ResourcesCapability `json:"resources,omitempty"`
Prompts *PromptsCapability `json:"prompts,omitempty"`
Logging map[string]interface{} `json:"logging,omitempty"`
Experimental map[string]interface{} `json:"experimental,omitempty"`
}
// ToolsCapability represents tools capability
type ToolsCapability struct {
ListChanged bool `json:"listChanged,omitempty"`
}
// ResourcesCapability represents resources capability
type ResourcesCapability struct {
Subscribe bool `json:"subscribe,omitempty"`
ListChanged bool `json:"listChanged,omitempty"`
}
// PromptsCapability represents prompts capability
type PromptsCapability struct {
ListChanged bool `json:"listChanged,omitempty"`
}
// ServerInfo represents information about the server
type ServerInfo struct {
Name string `json:"name"`
Version string `json:"version"`
}
// CallToolResult represents the result of tools/call request
type CallToolResult struct {
Content []ContentItem `json:"content"`
IsError bool `json:"isError,omitempty"`
}
// ContentItem represents a content item in tool result
type ContentItem struct {
Type string `json:"type"` // "text", "image", "resource"
Text string `json:"text,omitempty"`
Data string `json:"data,omitempty"`
MimeType string `json:"mimeType,omitempty"`
}
// ReadResourceResult represents the result of resources/read request
type ReadResourceResult struct {
Contents []ResourceContent `json:"contents"`
}
// ResourceContent represents resource content
type ResourceContent struct {
URI string `json:"uri"`
MimeType string `json:"mimeType,omitempty"`
Text string `json:"text,omitempty"`
Blob string `json:"blob,omitempty"` // Base64 encoded
}