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,258 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/mcp"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// MCPTool wraps an MCP service tool to implement the Tool interface
|
||||
type MCPTool struct {
|
||||
service *types.MCPService
|
||||
mcpTool *types.MCPTool
|
||||
mcpManager *mcp.MCPManager
|
||||
}
|
||||
|
||||
// NewMCPTool creates a new MCP tool wrapper
|
||||
func NewMCPTool(service *types.MCPService, mcpTool *types.MCPTool, mcpManager *mcp.MCPManager) *MCPTool {
|
||||
return &MCPTool{
|
||||
service: service,
|
||||
mcpTool: mcpTool,
|
||||
mcpManager: mcpManager,
|
||||
}
|
||||
}
|
||||
|
||||
// Name returns the unique name for this tool
|
||||
// Format: mcp_{service_name}_{tool_name}
|
||||
func (t *MCPTool) Name() string {
|
||||
// Sanitize service name and tool name to create a valid identifier
|
||||
serviceName := sanitizeName(t.service.Name)
|
||||
toolName := sanitizeName(t.mcpTool.Name)
|
||||
return fmt.Sprintf("mcp_%s_%s", serviceName, toolName)
|
||||
}
|
||||
|
||||
// Description returns the tool description
|
||||
func (t *MCPTool) Description() string {
|
||||
serviceDesc := fmt.Sprintf("[MCP Service: %s] ", t.service.Name)
|
||||
if t.mcpTool.Description != "" {
|
||||
return serviceDesc + t.mcpTool.Description
|
||||
}
|
||||
return serviceDesc + t.mcpTool.Name
|
||||
}
|
||||
|
||||
// Parameters returns the JSON Schema for tool parameters
|
||||
func (t *MCPTool) Parameters() map[string]interface{} {
|
||||
if t.mcpTool.InputSchema != nil {
|
||||
return t.mcpTool.InputSchema
|
||||
}
|
||||
|
||||
// Return a default schema if none provided
|
||||
return map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{},
|
||||
}
|
||||
}
|
||||
|
||||
// Execute executes the MCP tool
|
||||
func (t *MCPTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
|
||||
logger.GetLogger(ctx).Infof("Executing MCP tool: %s from service: %s", t.mcpTool.Name, t.service.Name)
|
||||
|
||||
// Get or create MCP client
|
||||
client, err := t.mcpManager.GetOrCreateClient(t.service)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("Failed to get MCP client: %v", err)
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: fmt.Sprintf("Failed to connect to MCP service: %v", err),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Call the tool via MCP
|
||||
result, err := client.CallTool(ctx, t.mcpTool.Name, args)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("MCP tool call failed: %v", err)
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: fmt.Sprintf("Tool execution failed: %v", err),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Check if result indicates error
|
||||
if result.IsError {
|
||||
errorMsg := extractContentText(result.Content)
|
||||
logger.GetLogger(ctx).Warnf("MCP tool returned error: %s", errorMsg)
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: errorMsg,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Extract text content from result
|
||||
output := extractContentText(result.Content)
|
||||
|
||||
// Build structured data from result
|
||||
data := make(map[string]interface{})
|
||||
data["content_items"] = result.Content
|
||||
|
||||
logger.GetLogger(ctx).Infof("MCP tool executed successfully: %s", t.mcpTool.Name)
|
||||
|
||||
return &types.ToolResult{
|
||||
Success: true,
|
||||
Output: output,
|
||||
Data: data,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// extractContentText extracts text content from MCP content items
|
||||
func extractContentText(content []mcp.ContentItem) string {
|
||||
var textParts []string
|
||||
|
||||
for _, item := range content {
|
||||
switch item.Type {
|
||||
case "text":
|
||||
if item.Text != "" {
|
||||
textParts = append(textParts, item.Text)
|
||||
}
|
||||
case "image":
|
||||
// For images, include a description
|
||||
mimeType := item.MimeType
|
||||
if mimeType == "" {
|
||||
mimeType = "image"
|
||||
}
|
||||
textParts = append(textParts, fmt.Sprintf("[Image: %s]", mimeType))
|
||||
case "resource":
|
||||
// For resources, include a reference
|
||||
textParts = append(textParts, fmt.Sprintf("[Resource: %s]", item.MimeType))
|
||||
default:
|
||||
// For other types, try to include any text or data
|
||||
if item.Text != "" {
|
||||
textParts = append(textParts, item.Text)
|
||||
} else if item.Data != "" {
|
||||
textParts = append(textParts, fmt.Sprintf("[Data: %s]", item.Type))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(textParts) == 0 {
|
||||
return "Tool executed successfully (no text output)"
|
||||
}
|
||||
|
||||
return strings.Join(textParts, "\n")
|
||||
}
|
||||
|
||||
// sanitizeName sanitizes a name to create a valid identifier
|
||||
func sanitizeName(name string) string {
|
||||
// Replace invalid characters with underscores
|
||||
name = strings.ToLower(name)
|
||||
name = strings.ReplaceAll(name, " ", "_")
|
||||
name = strings.ReplaceAll(name, "-", "_")
|
||||
|
||||
// Remove any non-alphanumeric characters except underscores
|
||||
var result strings.Builder
|
||||
for _, char := range name {
|
||||
if (char >= 'a' && char <= 'z') || (char >= '0' && char <= '9') || char == '_' {
|
||||
result.WriteRune(char)
|
||||
}
|
||||
}
|
||||
|
||||
return result.String()
|
||||
}
|
||||
|
||||
// RegisterMCPTools registers MCP tools from given services
|
||||
func RegisterMCPTools(registry *ToolRegistry, services []*types.MCPService, mcpManager *mcp.MCPManager) error {
|
||||
if len(services) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
for _, service := range services {
|
||||
if !service.Enabled {
|
||||
continue
|
||||
}
|
||||
|
||||
// Get or create client
|
||||
client, err := mcpManager.GetOrCreateClient(service)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("Failed to create MCP client for service %s: %v", service.Name, err)
|
||||
continue
|
||||
}
|
||||
|
||||
// List tools from the service
|
||||
tools, err := client.ListTools(ctx)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("Failed to list tools from MCP service %s: %v", service.Name, err)
|
||||
continue
|
||||
}
|
||||
|
||||
// Register each tool
|
||||
for _, mcpTool := range tools {
|
||||
tool := NewMCPTool(service, mcpTool, mcpManager)
|
||||
registry.RegisterTool(tool)
|
||||
logger.GetLogger(ctx).Infof("Registered MCP tool: %s from service: %s", tool.Name(), service.Name)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetMCPToolsInfo returns information about available MCP tools
|
||||
func GetMCPToolsInfo(services []*types.MCPService, mcpManager *mcp.MCPManager) (map[string][]string, error) {
|
||||
result := make(map[string][]string)
|
||||
ctx := context.Background()
|
||||
|
||||
for _, service := range services {
|
||||
if !service.Enabled {
|
||||
continue
|
||||
}
|
||||
|
||||
client, err := mcpManager.GetOrCreateClient(service)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
tools, err := client.ListTools(ctx)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
toolNames := make([]string, len(tools))
|
||||
for i, tool := range tools {
|
||||
toolNames[i] = tool.Name
|
||||
}
|
||||
|
||||
result[service.Name] = toolNames
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// SerializeMCPToolResult serializes an MCP tool result for display
|
||||
func SerializeMCPToolResult(result *types.ToolResult) (string, error) {
|
||||
if result == nil {
|
||||
return "", fmt.Errorf("result is nil")
|
||||
}
|
||||
|
||||
if !result.Success {
|
||||
return fmt.Sprintf("Error: %s", result.Error), nil
|
||||
}
|
||||
|
||||
output := result.Output
|
||||
if output == "" {
|
||||
output = "Success (no output)"
|
||||
}
|
||||
|
||||
// If there's structured data, try to format it nicely
|
||||
if result.Data != nil {
|
||||
if dataBytes, err := json.MarshalIndent(result.Data, "", " "); err == nil {
|
||||
output += "\n\nStructured Data:\n" + string(dataBytes)
|
||||
}
|
||||
}
|
||||
|
||||
return output, nil
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// mcpServiceRepository implements the MCPServiceRepository interface
|
||||
type mcpServiceRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewMCPServiceRepository creates a new MCP service repository
|
||||
func NewMCPServiceRepository(db *gorm.DB) interfaces.MCPServiceRepository {
|
||||
return &mcpServiceRepository{db: db}
|
||||
}
|
||||
|
||||
// Create creates a new MCP service
|
||||
func (r *mcpServiceRepository) Create(ctx context.Context, service *types.MCPService) error {
|
||||
return r.db.WithContext(ctx).Create(service).Error
|
||||
}
|
||||
|
||||
// GetByID retrieves an MCP service by ID and tenant ID
|
||||
func (r *mcpServiceRepository) GetByID(ctx context.Context, tenantID uint, id string) (*types.MCPService, error) {
|
||||
var service types.MCPService
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("id = ? AND tenant_id = ?", id, tenantID).
|
||||
First(&service).Error
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &service, nil
|
||||
}
|
||||
|
||||
// List retrieves all MCP services for a tenant
|
||||
func (r *mcpServiceRepository) List(ctx context.Context, tenantID uint) ([]*types.MCPService, error) {
|
||||
var services []*types.MCPService
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ?", tenantID).
|
||||
Order("created_at DESC").
|
||||
Find(&services).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return services, nil
|
||||
}
|
||||
|
||||
// ListEnabled retrieves all enabled MCP services for a tenant
|
||||
func (r *mcpServiceRepository) ListEnabled(ctx context.Context, tenantID uint) ([]*types.MCPService, error) {
|
||||
var services []*types.MCPService
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND enabled = ?", tenantID, true).
|
||||
Order("created_at DESC").
|
||||
Find(&services).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return services, nil
|
||||
}
|
||||
|
||||
// ListByIDs retrieves MCP services by multiple IDs for a tenant
|
||||
func (r *mcpServiceRepository) ListByIDs(ctx context.Context, tenantID uint, ids []string) ([]*types.MCPService, error) {
|
||||
if len(ids) == 0 {
|
||||
return []*types.MCPService{}, nil
|
||||
}
|
||||
|
||||
var services []*types.MCPService
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND id IN ?", tenantID, ids).
|
||||
Find(&services).Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return services, nil
|
||||
}
|
||||
|
||||
// Update updates an MCP service
|
||||
func (r *mcpServiceRepository) Update(ctx context.Context, service *types.MCPService) error {
|
||||
// Build update map with only non-zero fields (except enabled which should always be updated if set)
|
||||
updateMap := make(map[string]interface{})
|
||||
updateMap["updated_at"] = service.UpdatedAt
|
||||
|
||||
// Always include enabled field if it's being updated (service layer ensures it's set correctly)
|
||||
updateMap["enabled"] = service.Enabled
|
||||
|
||||
if service.Name != "" {
|
||||
updateMap["name"] = service.Name
|
||||
}
|
||||
// Description can be empty, so we check if it's different from existing
|
||||
// For now, we'll always update it if provided
|
||||
updateMap["description"] = service.Description
|
||||
|
||||
if service.TransportType != "" {
|
||||
updateMap["transport_type"] = service.TransportType
|
||||
}
|
||||
if service.URL != "" {
|
||||
updateMap["url"] = service.URL
|
||||
}
|
||||
if service.Headers != nil {
|
||||
updateMap["headers"] = service.Headers
|
||||
}
|
||||
if service.AuthConfig != nil {
|
||||
updateMap["auth_config"] = service.AuthConfig
|
||||
}
|
||||
if service.AdvancedConfig != nil {
|
||||
updateMap["advanced_config"] = service.AdvancedConfig
|
||||
}
|
||||
|
||||
return r.db.WithContext(ctx).
|
||||
Model(&types.MCPService{}).
|
||||
Where("id = ? AND tenant_id = ?", service.ID, service.TenantID).
|
||||
Updates(updateMap).Error
|
||||
}
|
||||
|
||||
// Delete deletes an MCP service (soft delete)
|
||||
func (r *mcpServiceRepository) Delete(ctx context.Context, tenantID uint, id string) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("id = ? AND tenant_id = ?", id, tenantID).
|
||||
Delete(&types.MCPService{}).Error
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/mcp"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/models/rerank"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
@@ -25,6 +26,8 @@ type agentService struct {
|
||||
knowledgeBaseService interfaces.KnowledgeBaseService
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
chunkService interfaces.ChunkService
|
||||
mcpServiceService interfaces.MCPServiceService
|
||||
mcpManager *mcp.MCPManager
|
||||
eventBus *event.EventBus
|
||||
db *gorm.DB
|
||||
}
|
||||
@@ -36,6 +39,8 @@ func NewAgentService(
|
||||
knowledgeBaseService interfaces.KnowledgeBaseService,
|
||||
knowledgeService interfaces.KnowledgeService,
|
||||
chunkService interfaces.ChunkService,
|
||||
mcpServiceService interfaces.MCPServiceService,
|
||||
mcpManager *mcp.MCPManager,
|
||||
eventBus *event.EventBus,
|
||||
db *gorm.DB,
|
||||
) interfaces.AgentService {
|
||||
@@ -45,6 +50,8 @@ func NewAgentService(
|
||||
knowledgeBaseService: knowledgeBaseService,
|
||||
knowledgeService: knowledgeService,
|
||||
chunkService: chunkService,
|
||||
mcpServiceService: mcpServiceService,
|
||||
mcpManager: mcpManager,
|
||||
eventBus: eventBus,
|
||||
db: db,
|
||||
}
|
||||
@@ -91,6 +98,36 @@ func (s *agentService) CreateAgentEngine(
|
||||
return nil, fmt.Errorf("failed to register tools: %w", err)
|
||||
}
|
||||
|
||||
// Register MCP tools from enabled services for this tenant
|
||||
tenantID := uint(0)
|
||||
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint); ok {
|
||||
tenantID = tid
|
||||
}
|
||||
if tenantID > 0 && s.mcpServiceService != nil && s.mcpManager != nil {
|
||||
// Get enabled MCP services for this tenant
|
||||
mcpServices, err := s.mcpServiceService.ListMCPServices(ctx, tenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to list MCP services: %v", err)
|
||||
} else {
|
||||
// Filter enabled services
|
||||
enabledServices := make([]*types.MCPService, 0)
|
||||
for _, svc := range mcpServices {
|
||||
if svc.Enabled {
|
||||
enabledServices = append(enabledServices, svc)
|
||||
}
|
||||
}
|
||||
|
||||
// Register MCP tools
|
||||
if len(enabledServices) > 0 {
|
||||
if err := tools.RegisterMCPTools(toolRegistry, enabledServices, s.mcpManager); err != nil {
|
||||
logger.Warnf(ctx, "Failed to register MCP tools: %v", err)
|
||||
} else {
|
||||
logger.Infof(ctx, "Registered MCP tools from %d enabled services", len(enabledServices))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get knowledge base detailed information for prompt
|
||||
kbInfos, err := s.getKnowledgeBaseInfos(ctx, config.KnowledgeBases)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/mcp"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// mcpServiceService implements MCPServiceService interface
|
||||
type mcpServiceService struct {
|
||||
mcpServiceRepo interfaces.MCPServiceRepository
|
||||
mcpManager *mcp.MCPManager
|
||||
}
|
||||
|
||||
// NewMCPServiceService creates a new MCP service service
|
||||
func NewMCPServiceService(
|
||||
mcpServiceRepo interfaces.MCPServiceRepository,
|
||||
mcpManager *mcp.MCPManager,
|
||||
) interfaces.MCPServiceService {
|
||||
return &mcpServiceService{
|
||||
mcpServiceRepo: mcpServiceRepo,
|
||||
mcpManager: mcpManager,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateMCPService creates a new MCP service
|
||||
func (s *mcpServiceService) CreateMCPService(ctx context.Context, service *types.MCPService) error {
|
||||
// Set default advanced config if not provided
|
||||
if service.AdvancedConfig == nil {
|
||||
service.AdvancedConfig = types.GetDefaultAdvancedConfig()
|
||||
}
|
||||
|
||||
// Set timestamps
|
||||
service.CreatedAt = time.Now()
|
||||
service.UpdatedAt = time.Now()
|
||||
|
||||
if err := s.mcpServiceRepo.Create(ctx, service); err != nil {
|
||||
logger.GetLogger(ctx).Errorf("Failed to create MCP service: %v", err)
|
||||
return fmt.Errorf("failed to create MCP service: %w", err)
|
||||
}
|
||||
|
||||
logger.GetLogger(ctx).Infof("MCP service created: %s (ID: %s)", service.Name, service.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetMCPServiceByID retrieves an MCP service by ID
|
||||
func (s *mcpServiceService) GetMCPServiceByID(ctx context.Context, tenantID uint, id string) (*types.MCPService, error) {
|
||||
service, err := s.mcpServiceRepo.GetByID(ctx, tenantID, id)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("Failed to get MCP service: %v", err)
|
||||
return nil, fmt.Errorf("failed to get MCP service: %w", err)
|
||||
}
|
||||
|
||||
if service == nil {
|
||||
return nil, fmt.Errorf("MCP service not found")
|
||||
}
|
||||
|
||||
return service, nil
|
||||
}
|
||||
|
||||
// ListMCPServices lists all MCP services for a tenant
|
||||
func (s *mcpServiceService) ListMCPServices(ctx context.Context, tenantID uint) ([]*types.MCPService, error) {
|
||||
services, err := s.mcpServiceRepo.List(ctx, tenantID)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("Failed to list MCP services: %v", err)
|
||||
return nil, fmt.Errorf("failed to list MCP services: %w", err)
|
||||
}
|
||||
|
||||
// Mask sensitive data for list view
|
||||
for _, service := range services {
|
||||
service.MaskSensitiveData()
|
||||
}
|
||||
|
||||
return services, nil
|
||||
}
|
||||
|
||||
// ListMCPServicesByIDs retrieves multiple MCP services by IDs
|
||||
func (s *mcpServiceService) ListMCPServicesByIDs(ctx context.Context, tenantID uint, ids []string) ([]*types.MCPService, error) {
|
||||
if len(ids) == 0 {
|
||||
return []*types.MCPService{}, nil
|
||||
}
|
||||
|
||||
services, err := s.mcpServiceRepo.ListByIDs(ctx, tenantID, ids)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("Failed to list MCP services by IDs: %v", err)
|
||||
return nil, fmt.Errorf("failed to list MCP services by IDs: %w", err)
|
||||
}
|
||||
|
||||
return services, nil
|
||||
}
|
||||
|
||||
// UpdateMCPService updates an MCP service
|
||||
func (s *mcpServiceService) UpdateMCPService(ctx context.Context, service *types.MCPService) error {
|
||||
// Check if service exists
|
||||
existing, err := s.mcpServiceRepo.GetByID(ctx, service.TenantID, service.ID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get MCP service: %w", err)
|
||||
}
|
||||
if existing == nil {
|
||||
return fmt.Errorf("MCP service not found")
|
||||
}
|
||||
|
||||
// Merge updates: only update fields that are provided (non-zero or explicitly set)
|
||||
// This ensures that false values for enabled field are properly updated
|
||||
// Handler ensures that service.Enabled is only set if "enabled" key exists in the request
|
||||
// So we can safely update enabled field if service.Name is empty (indicating partial update)
|
||||
// or if we're updating other fields (indicating full update)
|
||||
// For enabled field, we'll update it if this is a partial update (only enabled) or if it's explicitly set
|
||||
if service.Name == "" {
|
||||
// Partial update - only update enabled field
|
||||
existing.Enabled = service.Enabled
|
||||
} else {
|
||||
// Full update - update all fields including enabled
|
||||
existing.Name = service.Name
|
||||
if service.Description != existing.Description {
|
||||
existing.Description = service.Description
|
||||
}
|
||||
existing.Enabled = service.Enabled
|
||||
if service.TransportType != "" {
|
||||
existing.TransportType = service.TransportType
|
||||
}
|
||||
if service.URL != "" {
|
||||
existing.URL = service.URL
|
||||
}
|
||||
if service.Headers != nil {
|
||||
existing.Headers = service.Headers
|
||||
}
|
||||
if service.AuthConfig != nil {
|
||||
existing.AuthConfig = service.AuthConfig
|
||||
}
|
||||
if service.AdvancedConfig != nil {
|
||||
existing.AdvancedConfig = service.AdvancedConfig
|
||||
}
|
||||
}
|
||||
|
||||
// Update timestamp
|
||||
existing.UpdatedAt = time.Now()
|
||||
|
||||
if err := s.mcpServiceRepo.Update(ctx, existing); err != nil {
|
||||
logger.GetLogger(ctx).Errorf("Failed to update MCP service: %v", err)
|
||||
return fmt.Errorf("failed to update MCP service: %w", err)
|
||||
}
|
||||
|
||||
// Close existing client connection to force reconnect with new config
|
||||
s.mcpManager.CloseClient(service.ID)
|
||||
|
||||
logger.GetLogger(ctx).Infof("MCP service updated: %s (ID: %s)", existing.Name, service.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteMCPService deletes an MCP service
|
||||
func (s *mcpServiceService) DeleteMCPService(ctx context.Context, tenantID uint, id string) error {
|
||||
// Check if service exists
|
||||
existing, err := s.mcpServiceRepo.GetByID(ctx, tenantID, id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get MCP service: %w", err)
|
||||
}
|
||||
if existing == nil {
|
||||
return fmt.Errorf("MCP service not found")
|
||||
}
|
||||
|
||||
// Close client connection
|
||||
s.mcpManager.CloseClient(id)
|
||||
|
||||
if err := s.mcpServiceRepo.Delete(ctx, tenantID, id); err != nil {
|
||||
logger.GetLogger(ctx).Errorf("Failed to delete MCP service: %v", err)
|
||||
return fmt.Errorf("failed to delete MCP service: %w", err)
|
||||
}
|
||||
|
||||
logger.GetLogger(ctx).Infof("MCP service deleted: %s (ID: %s)", existing.Name, id)
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestMCPService tests the connection to an MCP service and returns available tools/resources
|
||||
func (s *mcpServiceService) TestMCPService(ctx context.Context, tenantID uint, id string) (*types.MCPTestResult, error) {
|
||||
// Get service
|
||||
service, err := s.mcpServiceRepo.GetByID(ctx, tenantID, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get MCP service: %w", err)
|
||||
}
|
||||
if service == nil {
|
||||
return nil, fmt.Errorf("MCP service not found")
|
||||
}
|
||||
|
||||
// Create temporary client for testing
|
||||
config := &mcp.ClientConfig{
|
||||
Service: service,
|
||||
}
|
||||
|
||||
client, err := mcp.NewMCPClient(config)
|
||||
if err != nil {
|
||||
return &types.MCPTestResult{
|
||||
Success: false,
|
||||
Message: fmt.Sprintf("Failed to create client: %v", err),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Connect
|
||||
testCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := client.Connect(testCtx); err != nil {
|
||||
return &types.MCPTestResult{
|
||||
Success: false,
|
||||
Message: fmt.Sprintf("Connection failed: %v", err),
|
||||
}, nil
|
||||
}
|
||||
defer client.Disconnect()
|
||||
|
||||
// Initialize
|
||||
initResult, err := client.Initialize(testCtx)
|
||||
if err != nil {
|
||||
return &types.MCPTestResult{
|
||||
Success: false,
|
||||
Message: fmt.Sprintf("Initialization failed: %v", err),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// List tools
|
||||
tools, err := client.ListTools(testCtx)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Warnf("Failed to list tools: %v", err)
|
||||
tools = []*types.MCPTool{}
|
||||
}
|
||||
|
||||
// List resources
|
||||
resources, err := client.ListResources(testCtx)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Warnf("Failed to list resources: %v", err)
|
||||
resources = []*types.MCPResource{}
|
||||
}
|
||||
|
||||
return &types.MCPTestResult{
|
||||
Success: true,
|
||||
Message: fmt.Sprintf("Connected successfully to %s v%s", initResult.ServerInfo.Name, initResult.ServerInfo.Version),
|
||||
Tools: tools,
|
||||
Resources: resources,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetMCPServiceTools retrieves the list of tools from an MCP service
|
||||
func (s *mcpServiceService) GetMCPServiceTools(ctx context.Context, tenantID uint, id string) ([]*types.MCPTool, error) {
|
||||
// Get service
|
||||
service, err := s.mcpServiceRepo.GetByID(ctx, tenantID, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get MCP service: %w", err)
|
||||
}
|
||||
if service == nil {
|
||||
return nil, fmt.Errorf("MCP service not found")
|
||||
}
|
||||
|
||||
// Get or create client
|
||||
client, err := s.mcpManager.GetOrCreateClient(service)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get MCP client: %w", err)
|
||||
}
|
||||
|
||||
// List tools
|
||||
tools, err := client.ListTools(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to list tools: %w", err)
|
||||
}
|
||||
|
||||
return tools, nil
|
||||
}
|
||||
|
||||
// GetMCPServiceResources retrieves the list of resources from an MCP service
|
||||
func (s *mcpServiceService) GetMCPServiceResources(ctx context.Context, tenantID uint, id string) ([]*types.MCPResource, error) {
|
||||
// Get service
|
||||
service, err := s.mcpServiceRepo.GetByID(ctx, tenantID, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get MCP service: %w", err)
|
||||
}
|
||||
if service == nil {
|
||||
return nil, fmt.Errorf("MCP service not found")
|
||||
}
|
||||
|
||||
// Get or create client
|
||||
client, err := s.mcpManager.GetOrCreateClient(service)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get MCP client: %w", err)
|
||||
}
|
||||
|
||||
// List resources
|
||||
resources, err := client.ListResources(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to list resources: %w", err)
|
||||
}
|
||||
|
||||
return resources, nil
|
||||
}
|
||||
@@ -6,6 +6,7 @@ package container
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"slices"
|
||||
"strconv"
|
||||
@@ -32,10 +33,12 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/application/service/llmcontext"
|
||||
"github.com/Tencent/WeKnora/internal/application/service/retriever"
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/database"
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
"github.com/Tencent/WeKnora/internal/handler"
|
||||
"github.com/Tencent/WeKnora/internal/handler/session"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/mcp"
|
||||
"github.com/Tencent/WeKnora/internal/models/embedding"
|
||||
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
|
||||
"github.com/Tencent/WeKnora/internal/router"
|
||||
@@ -90,6 +93,10 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(repository.NewUserRepository))
|
||||
must(container.Provide(repository.NewAuthTokenRepository))
|
||||
must(container.Provide(neo4jRepo.NewNeo4jRepository))
|
||||
must(container.Provide(repository.NewMCPServiceRepository))
|
||||
|
||||
// MCP manager for managing MCP client connections
|
||||
must(container.Provide(mcp.NewMCPManager))
|
||||
|
||||
// Business service layer
|
||||
must(container.Provide(service.NewTenantService))
|
||||
@@ -103,6 +110,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(service.NewUserService))
|
||||
must(container.Provide(service.NewChunkExtractService))
|
||||
must(container.Provide(service.NewMessageService))
|
||||
must(container.Provide(service.NewMCPServiceService))
|
||||
|
||||
// Agent service layer (requires event bus)
|
||||
must(container.Provide(event.NewEventBus))
|
||||
@@ -139,6 +147,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(handler.NewInitializationHandler))
|
||||
must(container.Provide(handler.NewAuthHandler))
|
||||
must(container.Provide(handler.NewSystemHandler))
|
||||
must(container.Provide(handler.NewMCPServiceHandler))
|
||||
|
||||
// Router configuration
|
||||
must(container.Provide(router.NewRouter))
|
||||
@@ -211,9 +220,11 @@ func initContextStorage(redisClient *redis.Client) (llmcontext.ContextStorage, e
|
||||
// - Error if connection fails
|
||||
func initDatabase(cfg *config.Config) (*gorm.DB, error) {
|
||||
var dialector gorm.Dialector
|
||||
var migrateDSN string
|
||||
switch os.Getenv("DB_DRIVER") {
|
||||
case "postgres":
|
||||
dsn := fmt.Sprintf(
|
||||
// DSN for GORM (key-value format)
|
||||
gormDSN := fmt.Sprintf(
|
||||
"host=%s port=%s user=%s password=%s dbname=%s sslmode=%s",
|
||||
os.Getenv("DB_HOST"),
|
||||
os.Getenv("DB_PORT"),
|
||||
@@ -222,7 +233,29 @@ func initDatabase(cfg *config.Config) (*gorm.DB, error) {
|
||||
os.Getenv("DB_NAME"),
|
||||
"disable",
|
||||
)
|
||||
dialector = postgres.Open(dsn)
|
||||
dialector = postgres.Open(gormDSN)
|
||||
|
||||
// DSN for golang-migrate (URL format)
|
||||
// URL-encode password to handle special characters like !@#
|
||||
dbPassword := os.Getenv("DB_PASSWORD")
|
||||
encodedPassword := url.QueryEscape(dbPassword)
|
||||
|
||||
migrateDSN = fmt.Sprintf(
|
||||
"postgres://%s:%s@%s:%s/%s?sslmode=disable",
|
||||
os.Getenv("DB_USER"),
|
||||
encodedPassword, // Use encoded password
|
||||
os.Getenv("DB_HOST"),
|
||||
os.Getenv("DB_PORT"),
|
||||
os.Getenv("DB_NAME"),
|
||||
)
|
||||
|
||||
// Debug log (don't log password)
|
||||
logger.Infof(context.Background(), "DB Config: user=%s host=%s port=%s dbname=%s",
|
||||
os.Getenv("DB_USER"),
|
||||
os.Getenv("DB_HOST"),
|
||||
os.Getenv("DB_PORT"),
|
||||
os.Getenv("DB_NAME"),
|
||||
)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported database driver: %s", os.Getenv("DB_DRIVER"))
|
||||
}
|
||||
@@ -231,6 +264,19 @@ func initDatabase(cfg *config.Config) (*gorm.DB, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Run database migrations automatically (optional, can be disabled via env var)
|
||||
// To disable auto-migration, set AUTO_MIGRATE=false
|
||||
if os.Getenv("AUTO_MIGRATE") != "false" {
|
||||
logger.Infof(context.Background(), "Running database migrations...")
|
||||
if err := database.RunMigrations(migrateDSN); err != nil {
|
||||
// Log warning but don't fail startup - migrations might be handled externally
|
||||
logger.Warnf(context.Background(), "Database migration failed: %v", err)
|
||||
logger.Warnf(context.Background(), "Continuing with application startup. Please run migrations manually if needed.")
|
||||
}
|
||||
} else {
|
||||
logger.Infof(context.Background(), "Auto-migration is disabled (AUTO_MIGRATE=false)")
|
||||
}
|
||||
|
||||
// Auto-migrate database tables
|
||||
err = db.AutoMigrate(
|
||||
&types.User{},
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/golang-migrate/migrate/v4"
|
||||
_ "github.com/golang-migrate/migrate/v4/database/postgres"
|
||||
_ "github.com/golang-migrate/migrate/v4/source/file"
|
||||
)
|
||||
|
||||
// RunMigrations executes all pending database migrations
|
||||
// This should be called during application startup
|
||||
func RunMigrations(dsn string) error {
|
||||
// Use versioned migrations directory
|
||||
migrationsPath := "file://migrations/versioned"
|
||||
|
||||
m, err := migrate.New(migrationsPath, dsn)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create migrate instance: %w", err)
|
||||
}
|
||||
defer m.Close()
|
||||
|
||||
// Get current version before migration
|
||||
oldVersion, _, _ := m.Version()
|
||||
|
||||
// Run all pending migrations
|
||||
if err := m.Up(); err != nil && err != migrate.ErrNoChange {
|
||||
return fmt.Errorf("failed to run migrations: %w", err)
|
||||
}
|
||||
|
||||
// Get current version after migration
|
||||
version, dirty, err := m.Version()
|
||||
if err != nil && err != migrate.ErrNilVersion {
|
||||
return fmt.Errorf("failed to get migration version: %w", err)
|
||||
}
|
||||
|
||||
if oldVersion != version {
|
||||
logger.Infof(context.Background(), "Database migrated from version %d to %d", oldVersion, version)
|
||||
} else {
|
||||
logger.Infof(context.Background(), "Database is up to date (version: %d)", version)
|
||||
}
|
||||
|
||||
if dirty {
|
||||
logger.Warnf(context.Background(), "Database is in dirty state! Manual intervention may be required.")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetMigrationVersion returns the current migration version
|
||||
func GetMigrationVersion() (uint, bool, error) {
|
||||
dbURL := fmt.Sprintf(
|
||||
"postgres://%s:%s@%s:%s/%s?sslmode=disable",
|
||||
os.Getenv("DB_USER"),
|
||||
os.Getenv("DB_PASSWORD"),
|
||||
os.Getenv("DB_HOST"),
|
||||
os.Getenv("DB_PORT"),
|
||||
os.Getenv("DB_NAME"),
|
||||
)
|
||||
|
||||
migrationsPath := "file://migrations/versioned"
|
||||
|
||||
m, err := migrate.New(migrationsPath, dbURL)
|
||||
if err != nil {
|
||||
return 0, false, fmt.Errorf("failed to create migrate instance: %w", err)
|
||||
}
|
||||
defer m.Close()
|
||||
|
||||
version, dirty, err := m.Version()
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
|
||||
return version, dirty, nil
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// MCPServiceHandler handles MCP service related HTTP requests
|
||||
type MCPServiceHandler struct {
|
||||
mcpServiceService interfaces.MCPServiceService
|
||||
}
|
||||
|
||||
// NewMCPServiceHandler creates a new MCP service handler
|
||||
func NewMCPServiceHandler(mcpServiceService interfaces.MCPServiceService) *MCPServiceHandler {
|
||||
return &MCPServiceHandler{
|
||||
mcpServiceService: mcpServiceService,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateMCPService creates a new MCP service
|
||||
// POST /api/mcp-services
|
||||
func (h *MCPServiceHandler) CreateMCPService(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
var service types.MCPService
|
||||
if err := c.ShouldBindJSON(&service); err != nil {
|
||||
logger.Error(ctx, "Failed to parse MCP service request", err)
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
tenantID := c.GetUint(types.TenantIDContextKey.String())
|
||||
if tenantID == 0 {
|
||||
logger.Error(ctx, "Tenant ID is empty")
|
||||
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
|
||||
return
|
||||
}
|
||||
service.TenantID = tenantID
|
||||
|
||||
if err := h.mcpServiceService.CreateMCPService(ctx, &service); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{"service_name": service.Name})
|
||||
c.Error(errors.NewInternalServerError("Failed to create MCP service: " + err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "MCP service created successfully: %s", service.Name)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": service,
|
||||
})
|
||||
}
|
||||
|
||||
// ListMCPServices lists all MCP services for a tenant
|
||||
// GET /api/mcp-services
|
||||
func (h *MCPServiceHandler) ListMCPServices(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
tenantID := c.GetUint(types.TenantIDContextKey.String())
|
||||
if tenantID == 0 {
|
||||
logger.Error(ctx, "Tenant ID is empty")
|
||||
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
|
||||
return
|
||||
}
|
||||
|
||||
services, err := h.mcpServiceService.ListMCPServices(ctx, tenantID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{"tenant_id": tenantID})
|
||||
c.Error(errors.NewInternalServerError("Failed to list MCP services: " + err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": services,
|
||||
})
|
||||
}
|
||||
|
||||
// GetMCPService retrieves a single MCP service
|
||||
// GET /api/mcp-services/:id
|
||||
func (h *MCPServiceHandler) GetMCPService(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
serviceID := c.Param("id")
|
||||
|
||||
tenantID := c.GetUint(types.TenantIDContextKey.String())
|
||||
if tenantID == 0 {
|
||||
logger.Error(ctx, "Tenant ID is empty")
|
||||
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
|
||||
return
|
||||
}
|
||||
|
||||
service, err := h.mcpServiceService.GetMCPServiceByID(ctx, tenantID, serviceID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{"service_id": serviceID})
|
||||
c.Error(errors.NewNotFoundError("MCP service not found"))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": service,
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateMCPService updates an MCP service
|
||||
// PUT /api/mcp-services/:id
|
||||
func (h *MCPServiceHandler) UpdateMCPService(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
serviceID := c.Param("id")
|
||||
|
||||
tenantID := c.GetUint(types.TenantIDContextKey.String())
|
||||
if tenantID == 0 {
|
||||
logger.Error(ctx, "Tenant ID is empty")
|
||||
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
|
||||
return
|
||||
}
|
||||
|
||||
// Use map to handle partial updates, including false values
|
||||
var updateData map[string]interface{}
|
||||
if err := c.ShouldBindJSON(&updateData); err != nil {
|
||||
logger.Error(ctx, "Failed to parse MCP service update request", err)
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// Convert map to MCPService struct for validation and processing
|
||||
var service types.MCPService
|
||||
service.ID = serviceID
|
||||
service.TenantID = tenantID
|
||||
|
||||
// Track which fields are being updated
|
||||
updateFields := make(map[string]bool)
|
||||
|
||||
// Map the update data to service struct
|
||||
if name, ok := updateData["name"].(string); ok {
|
||||
service.Name = name
|
||||
updateFields["name"] = true
|
||||
}
|
||||
if desc, ok := updateData["description"].(string); ok {
|
||||
service.Description = desc
|
||||
updateFields["description"] = true
|
||||
}
|
||||
if enabled, ok := updateData["enabled"].(bool); ok {
|
||||
service.Enabled = enabled
|
||||
updateFields["enabled"] = true
|
||||
}
|
||||
if transportType, ok := updateData["transport_type"].(string); ok {
|
||||
service.TransportType = types.MCPTransportType(transportType)
|
||||
}
|
||||
if url, ok := updateData["url"].(string); ok {
|
||||
service.URL = url
|
||||
}
|
||||
if headers, ok := updateData["headers"].(map[string]interface{}); ok {
|
||||
service.Headers = make(types.MCPHeaders)
|
||||
for k, v := range headers {
|
||||
if str, ok := v.(string); ok {
|
||||
service.Headers[k] = str
|
||||
}
|
||||
}
|
||||
}
|
||||
if authConfig, ok := updateData["auth_config"].(map[string]interface{}); ok {
|
||||
service.AuthConfig = &types.MCPAuthConfig{}
|
||||
if apiKey, ok := authConfig["api_key"].(string); ok {
|
||||
service.AuthConfig.APIKey = apiKey
|
||||
}
|
||||
if token, ok := authConfig["token"].(string); ok {
|
||||
service.AuthConfig.Token = token
|
||||
}
|
||||
}
|
||||
if advancedConfig, ok := updateData["advanced_config"].(map[string]interface{}); ok {
|
||||
service.AdvancedConfig = &types.MCPAdvancedConfig{}
|
||||
if timeout, ok := advancedConfig["timeout"].(float64); ok {
|
||||
service.AdvancedConfig.Timeout = int(timeout)
|
||||
}
|
||||
if retryCount, ok := advancedConfig["retry_count"].(float64); ok {
|
||||
service.AdvancedConfig.RetryCount = int(retryCount)
|
||||
}
|
||||
if retryDelay, ok := advancedConfig["retry_delay"].(float64); ok {
|
||||
service.AdvancedConfig.RetryDelay = int(retryDelay)
|
||||
}
|
||||
}
|
||||
|
||||
if err := h.mcpServiceService.UpdateMCPService(ctx, &service); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{"service_id": serviceID})
|
||||
c.Error(errors.NewInternalServerError("Failed to update MCP service: " + err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "MCP service updated successfully: %s", serviceID)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": service,
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteMCPService deletes an MCP service
|
||||
// DELETE /api/mcp-services/:id
|
||||
func (h *MCPServiceHandler) DeleteMCPService(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
serviceID := c.Param("id")
|
||||
|
||||
tenantID := c.GetUint(types.TenantIDContextKey.String())
|
||||
if tenantID == 0 {
|
||||
logger.Error(ctx, "Tenant ID is empty")
|
||||
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.mcpServiceService.DeleteMCPService(ctx, tenantID, serviceID); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{"service_id": serviceID})
|
||||
c.Error(errors.NewInternalServerError("Failed to delete MCP service: " + err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "MCP service deleted successfully: %s", serviceID)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "MCP service deleted successfully",
|
||||
})
|
||||
}
|
||||
|
||||
// TestMCPService tests connection to an MCP service
|
||||
// POST /api/mcp-services/:id/test
|
||||
func (h *MCPServiceHandler) TestMCPService(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
serviceID := c.Param("id")
|
||||
|
||||
tenantID := c.GetUint(types.TenantIDContextKey.String())
|
||||
if tenantID == 0 {
|
||||
logger.Error(ctx, "Tenant ID is empty")
|
||||
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Testing MCP service: %s", serviceID)
|
||||
|
||||
result, err := h.mcpServiceService.TestMCPService(ctx, tenantID, serviceID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{"service_id": serviceID})
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": types.MCPTestResult{
|
||||
Success: false,
|
||||
Message: "Test failed: " + err.Error(),
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "MCP service test completed: %s, success: %v", serviceID, result.Success)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": result,
|
||||
})
|
||||
}
|
||||
|
||||
// GetMCPServiceTools retrieves tools from an MCP service
|
||||
// GET /api/mcp-services/:id/tools
|
||||
func (h *MCPServiceHandler) GetMCPServiceTools(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
serviceID := c.Param("id")
|
||||
|
||||
tenantID := c.GetUint(types.TenantIDContextKey.String())
|
||||
if tenantID == 0 {
|
||||
logger.Error(ctx, "Tenant ID is empty")
|
||||
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
|
||||
return
|
||||
}
|
||||
|
||||
tools, err := h.mcpServiceService.GetMCPServiceTools(ctx, tenantID, serviceID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{"service_id": serviceID})
|
||||
c.Error(errors.NewInternalServerError("Failed to get MCP service tools: " + err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": tools,
|
||||
})
|
||||
}
|
||||
|
||||
// GetMCPServiceResources retrieves resources from an MCP service
|
||||
// GET /api/mcp-services/:id/resources
|
||||
func (h *MCPServiceHandler) GetMCPServiceResources(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
serviceID := c.Param("id")
|
||||
|
||||
tenantID := c.GetUint(types.TenantIDContextKey.String())
|
||||
if tenantID == 0 {
|
||||
logger.Error(ctx, "Tenant ID is empty")
|
||||
c.Error(errors.NewBadRequestError("Tenant ID cannot be empty"))
|
||||
return
|
||||
}
|
||||
|
||||
resources, err := h.mcpServiceService.GetMCPServiceResources(ctx, tenantID, serviceID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{"service_id": serviceID})
|
||||
c.Error(errors.NewInternalServerError("Failed to get MCP service resources: " + err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": resources,
|
||||
})
|
||||
}
|
||||
@@ -57,6 +57,7 @@ type CreateKnowledgeQARequest struct {
|
||||
KnowledgeBaseIDs []string `json:"knowledge_base_ids"` // Selected knowledge base ID for this request
|
||||
AgentEnabled bool `json:"agent_enabled"` // Whether agent mode is enabled for this request
|
||||
SummaryModelID string `json:"summary_model_id"` // Optional summary model ID for this request (overrides session default)
|
||||
MCPServiceIDs []string `json:"mcp_service_ids"` // Optional MCP service IDs to use in agent mode
|
||||
}
|
||||
|
||||
// SearchKnowledgeRequest defines the request structure for searching knowledge without LLM summarization
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -39,6 +39,7 @@ type RouterParams struct {
|
||||
AuthHandler *handler.AuthHandler
|
||||
InitializationHandler *handler.InitializationHandler
|
||||
SystemHandler *handler.SystemHandler
|
||||
MCPServiceHandler *handler.MCPServiceHandler
|
||||
}
|
||||
|
||||
// NewRouter 创建新的路由
|
||||
@@ -85,6 +86,7 @@ func NewRouter(params RouterParams) *gin.Engine {
|
||||
RegisterEvaluationRoutes(v1, params.EvaluationHandler)
|
||||
RegisterInitializationRoutes(v1, params.InitializationHandler)
|
||||
RegisterSystemRoutes(v1, params.SystemHandler)
|
||||
RegisterMCPServiceRoutes(v1, params.MCPServiceHandler)
|
||||
}
|
||||
|
||||
return r
|
||||
@@ -294,3 +296,26 @@ func RegisterSystemRoutes(r *gin.RouterGroup, handler *handler.SystemHandler) {
|
||||
systemRoutes.GET("/info", handler.GetSystemInfo)
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterMCPServiceRoutes registers MCP service routes
|
||||
func RegisterMCPServiceRoutes(r *gin.RouterGroup, handler *handler.MCPServiceHandler) {
|
||||
mcpServices := r.Group("/mcp-services")
|
||||
{
|
||||
// Create MCP service
|
||||
mcpServices.POST("", handler.CreateMCPService)
|
||||
// List MCP services
|
||||
mcpServices.GET("", handler.ListMCPServices)
|
||||
// Get MCP service by ID
|
||||
mcpServices.GET("/:id", handler.GetMCPService)
|
||||
// Update MCP service
|
||||
mcpServices.PUT("/:id", handler.UpdateMCPService)
|
||||
// Delete MCP service
|
||||
mcpServices.DELETE("/:id", handler.DeleteMCPService)
|
||||
// Test MCP service connection
|
||||
mcpServices.POST("/:id/test", handler.TestMCPService)
|
||||
// Get MCP service tools
|
||||
mcpServices.GET("/:id/tools", handler.GetMCPServiceTools)
|
||||
// Get MCP service resources
|
||||
mcpServices.GET("/:id/resources", handler.GetMCPServiceResources)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package interfaces
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// MCPServiceRepository defines the interface for MCP service data access
|
||||
type MCPServiceRepository interface {
|
||||
// Create creates a new MCP service
|
||||
Create(ctx context.Context, service *types.MCPService) error
|
||||
|
||||
// GetByID retrieves an MCP service by ID and tenant ID
|
||||
GetByID(ctx context.Context, tenantID uint, id string) (*types.MCPService, error)
|
||||
|
||||
// List retrieves all MCP services for a tenant
|
||||
List(ctx context.Context, tenantID uint) ([]*types.MCPService, error)
|
||||
|
||||
// ListEnabled retrieves all enabled MCP services for a tenant
|
||||
ListEnabled(ctx context.Context, tenantID uint) ([]*types.MCPService, error)
|
||||
|
||||
// ListByIDs retrieves MCP services by multiple IDs for a tenant
|
||||
ListByIDs(ctx context.Context, tenantID uint, ids []string) ([]*types.MCPService, error)
|
||||
|
||||
// Update updates an MCP service
|
||||
Update(ctx context.Context, service *types.MCPService) error
|
||||
|
||||
// Delete deletes an MCP service (soft delete)
|
||||
Delete(ctx context.Context, tenantID uint, id string) error
|
||||
}
|
||||
|
||||
// MCPServiceService defines the interface for MCP service business logic
|
||||
type MCPServiceService interface {
|
||||
// CreateMCPService creates a new MCP service
|
||||
CreateMCPService(ctx context.Context, service *types.MCPService) error
|
||||
|
||||
// GetMCPServiceByID retrieves an MCP service by ID
|
||||
GetMCPServiceByID(ctx context.Context, tenantID uint, id string) (*types.MCPService, error)
|
||||
|
||||
// ListMCPServices lists all MCP services for a tenant
|
||||
ListMCPServices(ctx context.Context, tenantID uint) ([]*types.MCPService, error)
|
||||
|
||||
// ListMCPServicesByIDs retrieves multiple MCP services by IDs
|
||||
ListMCPServicesByIDs(ctx context.Context, tenantID uint, ids []string) ([]*types.MCPService, error)
|
||||
|
||||
// UpdateMCPService updates an MCP service
|
||||
UpdateMCPService(ctx context.Context, service *types.MCPService) error
|
||||
|
||||
// DeleteMCPService deletes an MCP service
|
||||
DeleteMCPService(ctx context.Context, tenantID uint, id string) error
|
||||
|
||||
// TestMCPService tests the connection to an MCP service and returns available tools/resources
|
||||
TestMCPService(ctx context.Context, tenantID uint, id string) (*types.MCPTestResult, error)
|
||||
|
||||
// GetMCPServiceTools retrieves the list of tools from an MCP service
|
||||
GetMCPServiceTools(ctx context.Context, tenantID uint, id string) ([]*types.MCPTool, error)
|
||||
|
||||
// GetMCPServiceResources retrieves the list of resources from an MCP service
|
||||
GetMCPServiceResources(ctx context.Context, tenantID uint, id string) ([]*types.MCPResource, error)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// MCPTransportType represents the transport type for MCP service
|
||||
type MCPTransportType string
|
||||
|
||||
const (
|
||||
MCPTransportSSE MCPTransportType = "sse" // Server-Sent Events
|
||||
MCPTransportHTTPStreamable MCPTransportType = "http-streamable" // HTTP Streamable
|
||||
)
|
||||
|
||||
// MCPService represents an MCP (Model Context Protocol) service configuration
|
||||
type MCPService struct {
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
TenantID uint `json:"tenant_id" gorm:"index"`
|
||||
Name string `json:"name" gorm:"type:varchar(255);not null"`
|
||||
Description string `json:"description" gorm:"type:text"`
|
||||
Enabled bool `json:"enabled" gorm:"default:true;index"`
|
||||
TransportType MCPTransportType `json:"transport_type" gorm:"type:varchar(50);not null"`
|
||||
URL string `json:"url" gorm:"type:varchar(512);not null"`
|
||||
Headers MCPHeaders `json:"headers" gorm:"type:json"`
|
||||
AuthConfig *MCPAuthConfig `json:"auth_config" gorm:"type:json"`
|
||||
AdvancedConfig *MCPAdvancedConfig `json:"advanced_config" gorm:"type:json"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
|
||||
}
|
||||
|
||||
// MCPHeaders represents HTTP headers as a map
|
||||
type MCPHeaders map[string]string
|
||||
|
||||
// MCPAuthConfig represents authentication configuration for MCP service
|
||||
type MCPAuthConfig struct {
|
||||
APIKey string `json:"api_key,omitempty"`
|
||||
Token string `json:"token,omitempty"`
|
||||
CustomHeaders map[string]string `json:"custom_headers,omitempty"`
|
||||
}
|
||||
|
||||
// MCPAdvancedConfig represents advanced configuration for MCP service
|
||||
type MCPAdvancedConfig struct {
|
||||
Timeout int `json:"timeout"` // Timeout in seconds, default: 30
|
||||
RetryCount int `json:"retry_count"` // Number of retries, default: 3
|
||||
RetryDelay int `json:"retry_delay"` // Delay between retries in seconds, default: 1
|
||||
}
|
||||
|
||||
// MCPTool represents a tool exposed by an MCP service
|
||||
type MCPTool struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
InputSchema map[string]interface{} `json:"inputSchema"` // JSON Schema for tool parameters
|
||||
}
|
||||
|
||||
// MCPResource represents a resource exposed by an MCP service
|
||||
type MCPResource struct {
|
||||
URI string `json:"uri"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
MimeType string `json:"mimeType,omitempty"`
|
||||
}
|
||||
|
||||
// MCPTestResult represents the result of testing an MCP service connection
|
||||
type MCPTestResult struct {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Tools []*MCPTool `json:"tools,omitempty"`
|
||||
Resources []*MCPResource `json:"resources,omitempty"`
|
||||
}
|
||||
|
||||
// BeforeCreate is a GORM hook that runs before creating a new MCP service
|
||||
func (m *MCPService) BeforeCreate(tx *gorm.DB) error {
|
||||
if m.ID == "" {
|
||||
m.ID = uuid.New().String()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Value implements driver.Valuer interface for MCPHeaders
|
||||
func (h MCPHeaders) Value() (driver.Value, error) {
|
||||
if h == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return json.Marshal(h)
|
||||
}
|
||||
|
||||
// Scan implements sql.Scanner interface for MCPHeaders
|
||||
func (h *MCPHeaders) Scan(value interface{}) error {
|
||||
if value == nil {
|
||||
*h = nil
|
||||
return nil
|
||||
}
|
||||
b, ok := value.([]byte)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(b, h)
|
||||
}
|
||||
|
||||
// Value implements driver.Valuer interface for MCPAuthConfig
|
||||
func (c *MCPAuthConfig) Value() (driver.Value, error) {
|
||||
if c == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return json.Marshal(c)
|
||||
}
|
||||
|
||||
// Scan implements sql.Scanner interface for MCPAuthConfig
|
||||
func (c *MCPAuthConfig) Scan(value interface{}) error {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
b, ok := value.([]byte)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(b, c)
|
||||
}
|
||||
|
||||
// Value implements driver.Valuer interface for MCPAdvancedConfig
|
||||
func (c *MCPAdvancedConfig) Value() (driver.Value, error) {
|
||||
if c == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return json.Marshal(c)
|
||||
}
|
||||
|
||||
// Scan implements sql.Scanner interface for MCPAdvancedConfig
|
||||
func (c *MCPAdvancedConfig) Scan(value interface{}) error {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
b, ok := value.([]byte)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(b, c)
|
||||
}
|
||||
|
||||
// GetDefaultAdvancedConfig returns default advanced configuration
|
||||
func GetDefaultAdvancedConfig() *MCPAdvancedConfig {
|
||||
return &MCPAdvancedConfig{
|
||||
Timeout: 30,
|
||||
RetryCount: 3,
|
||||
RetryDelay: 1,
|
||||
}
|
||||
}
|
||||
|
||||
// MaskSensitiveData masks sensitive information in the MCP service for display
|
||||
func (m *MCPService) MaskSensitiveData() {
|
||||
if m.AuthConfig != nil {
|
||||
if m.AuthConfig.APIKey != "" {
|
||||
m.AuthConfig.APIKey = maskString(m.AuthConfig.APIKey)
|
||||
}
|
||||
if m.AuthConfig.Token != "" {
|
||||
m.AuthConfig.Token = maskString(m.AuthConfig.Token)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// maskString masks a string, showing only first 4 and last 4 characters
|
||||
func maskString(s string) string {
|
||||
if len(s) <= 8 {
|
||||
return "****"
|
||||
}
|
||||
return s[:4] + "****" + s[len(s)-4:]
|
||||
}
|
||||
Reference in New Issue
Block a user