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
+32
View File
@@ -0,0 +1,32 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// MCPOAuthRepository persists OAuth clients (per service) and tokens
// (per user + service) for the MCP OAuth2 authorization-code flow.
type MCPOAuthRepository interface {
// GetClient returns the registered OAuth client for a service, or
// (nil, nil) when none has been registered yet.
GetClient(ctx context.Context, tenantID uint64, serviceID string) (*types.MCPOAuthClient, error)
// SaveClient creates or updates the registered OAuth client for a service.
SaveClient(ctx context.Context, client *types.MCPOAuthClient) error
// DeleteClient removes the registered OAuth client for a service.
DeleteClient(ctx context.Context, tenantID uint64, serviceID string) error
// GetToken returns the stored token for (tenant, user, service), or
// (nil, nil) when the user has not authorized yet.
GetToken(ctx context.Context, tenantID uint64, userID, serviceID string) (*types.MCPOAuthToken, error)
// SaveToken creates or updates the per-user token for a service.
SaveToken(ctx context.Context, token *types.MCPOAuthToken) error
// DeleteToken removes the per-user token for a service (revoke /
// re-authorize).
DeleteToken(ctx context.Context, tenantID uint64, userID, serviceID string) error
}
+35
View File
@@ -43,6 +43,22 @@ type MCPService struct {
// MCPHeaders represents HTTP headers as a map
type MCPHeaders map[string]string
// MCPAuthType enumerates the authentication strategies for an MCP service.
type MCPAuthType string
const (
// MCPAuthNone means no authentication (or only static custom headers).
MCPAuthNone MCPAuthType = ""
// MCPAuthAPIKey injects a static API key header (X-API-Key).
MCPAuthAPIKey MCPAuthType = "api_key"
// MCPAuthBearer injects a static Authorization: Bearer <token> header.
MCPAuthBearer MCPAuthType = "bearer"
// MCPAuthOAuth performs the MCP OAuth2 authorization-code flow
// (discovery + dynamic client registration + PKCE) per user. Tokens are
// stored per (tenant, user, service) in mcp_oauth_tokens.
MCPAuthOAuth MCPAuthType = "oauth"
)
// MCPAuthConfig represents authentication configuration for MCP service.
//
// Secret fields (APIKey, Token) are persisted in this struct but are NEVER
@@ -50,10 +66,29 @@ type MCPHeaders map[string]string
// dto.MCPServiceResponse which omits them by construction. Credential
// mutations happen through the dedicated /credentials subresource handled
// by MCPCredentialsHandler.
//
// OAuth note: the OAuth strategy stores no secret in this struct. The
// per-user access/refresh tokens live in mcp_oauth_tokens and the
// dynamically registered client lives in mcp_oauth_clients. The fields here
// (Scopes, AuthServerMetadataURL) are non-secret OAuth configuration.
type MCPAuthConfig struct {
// AuthType selects the authentication strategy. Empty ("") is treated as
// none for backward compatibility with rows that pre-date this field.
AuthType MCPAuthType `json:"auth_type,omitempty"`
APIKey string `json:"api_key,omitempty"`
Token string `json:"token,omitempty"`
CustomHeaders map[string]string `json:"custom_headers,omitempty"`
// Scopes are the OAuth scopes requested during authorization. Optional.
Scopes []string `json:"scopes,omitempty"`
// AuthServerMetadataURL optionally pins the OAuth authorization server
// metadata URL. When empty, the server is discovered automatically from
// the MCP URL (RFC 9728 / RFC 8414).
AuthServerMetadataURL string `json:"auth_server_metadata_url,omitempty"`
}
// IsOAuth reports whether this service uses the OAuth strategy.
func (c *MCPAuthConfig) IsOAuth() bool {
return c != nil && c.AuthType == MCPAuthOAuth
}
// MCPAdvancedConfig represents advanced configuration for MCP service
+139
View File
@@ -0,0 +1,139 @@
package types
import (
"time"
"github.com/Tencent/WeKnora/internal/utils"
"github.com/google/uuid"
"gorm.io/gorm"
)
// MCPOAuthClient stores the OAuth client credentials obtained for an MCP
// service. For servers that support RFC 7591 Dynamic Client Registration the
// client_id (and optional client_secret) is registered once per service and
// reused across all users of that service, avoiding a registration round-trip
// on every authorization.
//
// One row per (tenant_id, service_id). The client_secret is encrypted at rest
// (AES-256-GCM) when SYSTEM_AES_KEY is configured.
type MCPOAuthClient struct {
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:idx_mcp_oauth_clients_tenant_svc"`
ServiceID string `json:"service_id" gorm:"type:varchar(36);not null;uniqueIndex:idx_mcp_oauth_clients_tenant_svc;index"`
ClientID string `json:"client_id" gorm:"type:varchar(512);not null"`
ClientSecret string `json:"-" gorm:"type:text"`
RedirectURI string `json:"redirect_uri" gorm:"type:varchar(1024)"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// TableName pins the table name. GORM's default naming would otherwise turn
// "MCPOAuthClient" into "mcpo_auth_clients" (treating "MCPO" as one token),
// which does not match the migration table "mcp_oauth_clients".
func (MCPOAuthClient) TableName() string { return "mcp_oauth_clients" }
// BeforeCreate sets the primary key and encrypts the client secret.
func (m *MCPOAuthClient) BeforeCreate(tx *gorm.DB) error {
if m.ID == "" {
m.ID = uuid.New().String()
}
m.encryptSecret()
return nil
}
// BeforeSave re-encrypts the secret on update paths.
func (m *MCPOAuthClient) BeforeSave(tx *gorm.DB) error {
m.encryptSecret()
return nil
}
// AfterFind decrypts the client secret after loading.
func (m *MCPOAuthClient) AfterFind(tx *gorm.DB) error {
if plain, ok := utils.DecryptStoredSecretLenient(m.ClientSecret); ok {
m.ClientSecret = plain
} else {
m.ClientSecret = ""
}
return nil
}
func (m *MCPOAuthClient) encryptSecret() {
if m.ClientSecret == "" {
return
}
if key := utils.GetAESKey(); key != nil {
if enc, err := utils.EncryptAESGCM(m.ClientSecret, key); err == nil {
m.ClientSecret = enc
}
}
}
// MCPOAuthToken stores a per-user OAuth token for an MCP service. The agent
// connects to the MCP server on behalf of the invoking user, so tokens are
// isolated by (tenant_id, user_id, service_id).
//
// AccessToken and RefreshToken are encrypted at rest (AES-256-GCM) when
// SYSTEM_AES_KEY is configured.
type MCPOAuthToken struct {
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:idx_mcp_oauth_tokens_tenant_user_svc"`
UserID string `json:"user_id" gorm:"type:varchar(64);not null;uniqueIndex:idx_mcp_oauth_tokens_tenant_user_svc;index"`
ServiceID string `json:"service_id" gorm:"type:varchar(36);not null;uniqueIndex:idx_mcp_oauth_tokens_tenant_user_svc;index"`
AccessToken string `json:"-" gorm:"type:text"`
RefreshToken string `json:"-" gorm:"type:text"`
TokenType string `json:"token_type" gorm:"type:varchar(32)"`
ExpiresAt time.Time `json:"expires_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// TableName pins the table name (see MCPOAuthClient.TableName); the default
// would be "mcpo_auth_tokens" instead of the migration's "mcp_oauth_tokens".
func (MCPOAuthToken) TableName() string { return "mcp_oauth_tokens" }
// BeforeCreate sets the primary key and encrypts secrets.
func (m *MCPOAuthToken) BeforeCreate(tx *gorm.DB) error {
if m.ID == "" {
m.ID = uuid.New().String()
}
m.encryptSecrets()
return nil
}
// BeforeSave re-encrypts secrets on update paths.
func (m *MCPOAuthToken) BeforeSave(tx *gorm.DB) error {
m.encryptSecrets()
return nil
}
// AfterFind decrypts secrets after loading.
func (m *MCPOAuthToken) AfterFind(tx *gorm.DB) error {
if plain, ok := utils.DecryptStoredSecretLenient(m.AccessToken); ok {
m.AccessToken = plain
} else {
m.AccessToken = ""
}
if plain, ok := utils.DecryptStoredSecretLenient(m.RefreshToken); ok {
m.RefreshToken = plain
} else {
m.RefreshToken = ""
}
return nil
}
func (m *MCPOAuthToken) encryptSecrets() {
key := utils.GetAESKey()
if key == nil {
return
}
if m.AccessToken != "" {
if enc, err := utils.EncryptAESGCM(m.AccessToken, key); err == nil {
m.AccessToken = enc
}
}
if m.RefreshToken != "" {
if enc, err := utils.EncryptAESGCM(m.RefreshToken, key); err == nil {
m.RefreshToken = enc
}
}
}