feat(mcp): add OAuth2 authorization for MCP services
Support connecting to MCP servers that require OAuth2, with a Cursor-like zero-config flow: the user provides only a URL and the system performs metadata discovery, dynamic client registration (DCR), and the authorization code flow with PKCE on first connect. - Persist per-user access/refresh tokens and per-service DCR client credentials, encrypted at rest (AES-256-GCM) - Store the PKCE verifier/state during the flow via Redis with an in-memory fallback for Lite mode - Cache MCP clients per (service, user) so tokens stay user-isolated - Add endpoints for authorize-url, callback, status, and token revoke; the callback is allowlisted for unauthenticated access - Surface a structured "authorization required" hint when a tool call hits an unauthorized MCP service - Frontend: add an auth-type selector with OAuth config, inline authorization status/actions, and render the connection test result inline in the editor drawer instead of a stacked centered dialog
This commit is contained in:
+57
-22
@@ -3,29 +3,34 @@ package mcp
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// MCPManager manages MCP client connections
|
||||
type MCPManager struct {
|
||||
clients map[string]MCPClient // serviceID -> client
|
||||
clients map[string]MCPClient // cacheKey -> client
|
||||
clientsMu sync.RWMutex
|
||||
oauthRepo interfaces.MCPOAuthRepository
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
// NewMCPManager creates a new MCP manager
|
||||
func NewMCPManager() *MCPManager {
|
||||
// NewMCPManager creates a new MCP manager. oauthRepo is used to wire per-user
|
||||
// OAuth token stores for OAuth-enabled MCP services.
|
||||
func NewMCPManager(oauthRepo interfaces.MCPOAuthRepository) *MCPManager {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
manager := &MCPManager{
|
||||
clients: make(map[string]MCPClient),
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
clients: make(map[string]MCPClient),
|
||||
oauthRepo: oauthRepo,
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
}
|
||||
|
||||
// Start cleanup goroutine
|
||||
@@ -34,10 +39,23 @@ func NewMCPManager() *MCPManager {
|
||||
return manager
|
||||
}
|
||||
|
||||
// cacheKey computes the connection-cache key for a service. OAuth services are
|
||||
// keyed per user (each user connects with their own token); all other services
|
||||
// share a single connection per service ID.
|
||||
func cacheKey(service *types.MCPService, userID string) string {
|
||||
if service.AuthConfig.IsOAuth() {
|
||||
return service.ID + "\x00" + userID
|
||||
}
|
||||
return service.ID
|
||||
}
|
||||
|
||||
// GetOrCreateClient gets an existing client or creates a new one
|
||||
// Caches and reuses existing connections for SSE/HTTP Streamable
|
||||
// Note: Stdio transport is disabled for security reasons
|
||||
func (m *MCPManager) GetOrCreateClient(service *types.MCPService) (MCPClient, error) {
|
||||
//
|
||||
// For OAuth-enabled services the connection is keyed per user (derived from
|
||||
// ctx) so each user connects with their own token.
|
||||
func (m *MCPManager) GetOrCreateClient(ctx context.Context, service *types.MCPService) (MCPClient, error) {
|
||||
// Check if service is enabled
|
||||
if !service.Enabled {
|
||||
return nil, fmt.Errorf("MCP service %s is not enabled", service.Name)
|
||||
@@ -48,9 +66,20 @@ func (m *MCPManager) GetOrCreateClient(service *types.MCPService) (MCPClient, er
|
||||
return nil, fmt.Errorf("stdio transport is disabled for security reasons; please use SSE or HTTP Streamable transport instead")
|
||||
}
|
||||
|
||||
var tenantID uint64
|
||||
var userID string
|
||||
if service.AuthConfig.IsOAuth() {
|
||||
tenantID, _ = types.TenantIDFromContext(ctx)
|
||||
userID, _ = types.UserIDFromContext(ctx)
|
||||
if userID == "" {
|
||||
return nil, fmt.Errorf("user context is required to connect to OAuth MCP service %s", service.Name)
|
||||
}
|
||||
}
|
||||
key := cacheKey(service, userID)
|
||||
|
||||
// For SSE/HTTP Streamable, check if client already exists and reuse
|
||||
m.clientsMu.RLock()
|
||||
client, exists := m.clients[service.ID]
|
||||
client, exists := m.clients[key]
|
||||
m.clientsMu.RUnlock()
|
||||
|
||||
if exists && client.IsConnected() {
|
||||
@@ -62,14 +91,17 @@ func (m *MCPManager) GetOrCreateClient(service *types.MCPService) (MCPClient, er
|
||||
defer m.clientsMu.Unlock()
|
||||
|
||||
// Double check after acquiring write lock
|
||||
client, exists = m.clients[service.ID]
|
||||
client, exists = m.clients[key]
|
||||
if exists && client.IsConnected() {
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// Create new client
|
||||
config := &ClientConfig{
|
||||
Service: service,
|
||||
Service: service,
|
||||
TenantID: tenantID,
|
||||
UserID: userID,
|
||||
OAuthRepo: m.oauthRepo,
|
||||
}
|
||||
|
||||
client, err := NewMCPClient(config)
|
||||
@@ -89,7 +121,7 @@ func (m *MCPManager) GetOrCreateClient(service *types.MCPService) (MCPClient, er
|
||||
}
|
||||
|
||||
// Store client (only for non-stdio transports)
|
||||
m.clients[service.ID] = client
|
||||
m.clients[key] = client
|
||||
|
||||
logger.GetLogger(m.ctx).Infof("MCP client created and initialized for service: %s", service.Name)
|
||||
return client, nil
|
||||
@@ -128,22 +160,25 @@ func (m *MCPManager) GetClient(serviceID string) (MCPClient, bool) {
|
||||
return client, exists
|
||||
}
|
||||
|
||||
// CloseClient closes and removes a specific client
|
||||
// CloseClient closes and removes all cached connections for a service. For
|
||||
// OAuth services this spans every per-user connection (keys are prefixed with
|
||||
// the service ID).
|
||||
func (m *MCPManager) CloseClient(serviceID string) error {
|
||||
m.clientsMu.Lock()
|
||||
defer m.clientsMu.Unlock()
|
||||
|
||||
client, exists := m.clients[serviceID]
|
||||
if !exists {
|
||||
return nil
|
||||
for key, client := range m.clients {
|
||||
// Match the plain service-ID key as well as per-user OAuth keys
|
||||
// ("<serviceID>\x00<userID>").
|
||||
if key != serviceID && !strings.HasPrefix(key, serviceID+"\x00") {
|
||||
continue
|
||||
}
|
||||
if err := client.Disconnect(); err != nil {
|
||||
logger.GetLogger(m.ctx).Errorf("Failed to disconnect MCP client %s: %v", key, err)
|
||||
}
|
||||
delete(m.clients, key)
|
||||
logger.GetLogger(m.ctx).Infof("MCP client closed: %s", key)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user