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:
wizardchen
2026-06-22 20:15:52 +08:00
committed by lyingbug
parent c25d762ed1
commit 7f3f219f58
27 changed files with 1920 additions and 686 deletions
@@ -0,0 +1,90 @@
package repository
import (
"context"
"errors"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// mcpOAuthRepository implements interfaces.MCPOAuthRepository.
type mcpOAuthRepository struct {
db *gorm.DB
}
// NewMCPOAuthRepository creates a new MCP OAuth repository.
func NewMCPOAuthRepository(db *gorm.DB) interfaces.MCPOAuthRepository {
return &mcpOAuthRepository{db: db}
}
func (r *mcpOAuthRepository) GetClient(
ctx context.Context, tenantID uint64, serviceID string,
) (*types.MCPOAuthClient, error) {
var client types.MCPOAuthClient
err := r.db.WithContext(ctx).
Where("tenant_id = ? AND service_id = ?", tenantID, serviceID).
First(&client).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, err
}
return &client, nil
}
func (r *mcpOAuthRepository) SaveClient(ctx context.Context, client *types.MCPOAuthClient) error {
client.UpdatedAt = time.Now()
return r.db.WithContext(ctx).
Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "service_id"}},
DoUpdates: clause.AssignmentColumns([]string{"client_id", "client_secret", "redirect_uri", "updated_at"}),
}).
Create(client).Error
}
func (r *mcpOAuthRepository) DeleteClient(ctx context.Context, tenantID uint64, serviceID string) error {
return r.db.WithContext(ctx).
Where("tenant_id = ? AND service_id = ?", tenantID, serviceID).
Delete(&types.MCPOAuthClient{}).Error
}
func (r *mcpOAuthRepository) GetToken(
ctx context.Context, tenantID uint64, userID, serviceID string,
) (*types.MCPOAuthToken, error) {
var token types.MCPOAuthToken
err := r.db.WithContext(ctx).
Where("tenant_id = ? AND user_id = ? AND service_id = ?", tenantID, userID, serviceID).
First(&token).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, err
}
return &token, nil
}
func (r *mcpOAuthRepository) SaveToken(ctx context.Context, token *types.MCPOAuthToken) error {
token.UpdatedAt = time.Now()
return r.db.WithContext(ctx).
Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "user_id"}, {Name: "service_id"}},
DoUpdates: clause.AssignmentColumns([]string{
"access_token", "refresh_token", "token_type", "expires_at", "updated_at",
}),
}).
Create(token).Error
}
func (r *mcpOAuthRepository) DeleteToken(
ctx context.Context, tenantID uint64, userID, serviceID string,
) error {
return r.db.WithContext(ctx).
Where("tenant_id = ? AND user_id = ? AND service_id = ?", tenantID, userID, serviceID).
Delete(&types.MCPOAuthToken{}).Error
}
+41 -5
View File
@@ -18,16 +18,19 @@ import (
type mcpServiceService struct {
mcpServiceRepo interfaces.MCPServiceRepository
mcpManager *mcp.MCPManager
oauthRepo interfaces.MCPOAuthRepository
}
// NewMCPServiceService creates a new MCP service service
func NewMCPServiceService(
mcpServiceRepo interfaces.MCPServiceRepository,
mcpManager *mcp.MCPManager,
oauthRepo interfaces.MCPOAuthRepository,
) interfaces.MCPServiceService {
return &mcpServiceService{
mcpServiceRepo: mcpServiceRepo,
mcpManager: mcpManager,
oauthRepo: oauthRepo,
}
}
@@ -168,14 +171,36 @@ func (s *mcpServiceService) UpdateMCPService(ctx context.Context, service *types
maps.Copy(preHeaders, existing.AuthConfig.CustomHeaders)
}
preAuthType := types.MCPAuthNone
if existing.AuthConfig != nil {
preAuthType = existing.AuthConfig.AuthType
}
// CustomHeaders flows through main PUT (it's structural, not a secret) —
// nil preserves, non-nil replaces. Other AuthConfig fields (APIKey/Token)
// are never accepted via main PUT; the handler strips them up front.
if service.AuthConfig != nil && service.AuthConfig.CustomHeaders != nil {
//
// auth_type / scopes / auth_server_metadata_url are non-secret OAuth
// configuration and also flow through here.
if service.AuthConfig != nil {
if existing.AuthConfig == nil {
existing.AuthConfig = &types.MCPAuthConfig{}
}
existing.AuthConfig.CustomHeaders = service.AuthConfig.CustomHeaders
if service.AuthConfig.CustomHeaders != nil {
existing.AuthConfig.CustomHeaders = service.AuthConfig.CustomHeaders
}
// Only overwrite OAuth config when explicitly provided, so a partial
// PUT that carries only custom_headers does not wipe an existing
// auth_type / scopes. (Empty/absent is treated as "no change".)
if service.AuthConfig.AuthType != types.MCPAuthNone {
existing.AuthConfig.AuthType = service.AuthConfig.AuthType
}
if service.AuthConfig.Scopes != nil {
existing.AuthConfig.Scopes = service.AuthConfig.Scopes
}
if service.AuthConfig.AuthServerMetadataURL != "" {
existing.AuthConfig.AuthServerMetadataURL = service.AuthConfig.AuthServerMetadataURL
}
}
// Merge updates: only update fields that are provided (non-zero or explicitly set)
@@ -257,6 +282,9 @@ func (s *mcpServiceService) UpdateMCPService(ctx context.Context, service *types
if !maps.Equal(currHeaders, preHeaders) {
configChanged = true
}
if existing.AuthConfig != nil && existing.AuthConfig.AuthType != preAuthType {
configChanged = true
}
name := secutils.SanitizeForLog(existing.Name)
// Close existing client connection if:
// 1. Service is now disabled (need to close connection)
@@ -321,10 +349,18 @@ func (s *mcpServiceService) TestMCPService(
return nil, fmt.Errorf("MCP service not found")
}
// Create temporary client for testing
// Create temporary client for testing. For OAuth services, wire the
// per-user token store so the test connects with the current user's
// authorization (and surfaces an authorization-required message when the
// user has not authorized yet).
config := &mcp.ClientConfig{
Service: service,
}
if service.AuthConfig.IsOAuth() {
config.OAuthRepo = s.oauthRepo
config.TenantID, _ = types.TenantIDFromContext(ctx)
config.UserID, _ = types.UserIDFromContext(ctx)
}
client, err := mcp.NewMCPClient(config)
if err != nil {
@@ -397,7 +433,7 @@ func (s *mcpServiceService) GetMCPServiceTools(
}
// Get or create client
client, err := s.mcpManager.GetOrCreateClient(service)
client, err := s.mcpManager.GetOrCreateClient(ctx, service)
if err != nil {
return nil, fmt.Errorf("failed to get MCP client: %w", err)
}
@@ -535,7 +571,7 @@ func (s *mcpServiceService) GetMCPServiceResources(
}
// Get or create client
client, err := s.mcpManager.GetOrCreateClient(service)
client, err := s.mcpManager.GetOrCreateClient(ctx, service)
if err != nil {
return nil, fmt.Errorf("failed to get MCP client: %w", err)
}
@@ -111,7 +111,8 @@ func newTestService() (*mcpServiceService, *fakeMCPRepo) {
repo := newFakeMCPRepo()
svc := &mcpServiceService{
mcpServiceRepo: repo,
mcpManager: mcp.NewMCPManager(),
mcpManager: mcp.NewMCPManager(nil),
oauthRepo: nil,
}
return svc, repo
}