feat(mcp): drive auth by AuthType and auto-detect OAuth on test

Select the auth header for the configured strategy only, instead of
emitting both X-API-Key and Authorization whenever the fields happened
to be set (which double-authed after switching strategies). AuthType=""
keeps the legacy infer-from-fields behavior for pre-existing rows.

Add a configurable api_key_header (non-secret, defaults to X-API-Key) so
services expecting the key in a different header work without plaintext
custom headers.

On connection test, upgrade a bare 401 that advertises RFC 9728
protected-resource metadata into an explicit OAuthRequired signal so the
UI can guide the user to switch to OAuth 2.0. Surface the server's
description from the initialize handshake in the test result.
This commit is contained in:
wizardchen
2026-06-29 20:48:59 +08:00
committed by lyingbug
parent c29761331c
commit f2686e9e39
16 changed files with 546 additions and 155 deletions
+36 -12
View File
@@ -2,6 +2,7 @@ package service
import (
"context"
"errors"
"fmt"
"maps"
"slices"
@@ -172,8 +173,10 @@ func (s *mcpServiceService) UpdateMCPService(ctx context.Context, service *types
}
preAuthType := types.MCPAuthNone
preAPIKeyHeader := ""
if existing.AuthConfig != nil {
preAuthType = existing.AuthConfig.AuthType
preAPIKeyHeader = existing.AuthConfig.APIKeyHeader
}
// CustomHeaders flows through main PUT (it's structural, not a secret) —
@@ -195,6 +198,11 @@ func (s *mcpServiceService) UpdateMCPService(ctx context.Context, service *types
if service.AuthConfig.AuthType != types.MCPAuthNone {
existing.AuthConfig.AuthType = service.AuthConfig.AuthType
}
// APIKeyHeader is non-secret; empty means "use default X-API-Key", so a
// partial PUT that omits it is treated as no-change (mirrors scopes).
if service.AuthConfig.APIKeyHeader != "" {
existing.AuthConfig.APIKeyHeader = service.AuthConfig.APIKeyHeader
}
if service.AuthConfig.Scopes != nil {
existing.AuthConfig.Scopes = service.AuthConfig.Scopes
}
@@ -282,7 +290,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 {
if existing.AuthConfig != nil &&
(existing.AuthConfig.AuthType != preAuthType ||
existing.AuthConfig.APIKeyHeader != preAPIKeyHeader) {
configChanged = true
}
name := secutils.SanitizeForLog(existing.Name)
@@ -335,6 +345,26 @@ func (s *mcpServiceService) DeleteMCPService(ctx context.Context, tenantID uint6
}
// TestMCPService tests the connection to an MCP service and returns available tools/resources
// mcpTestFailure builds a failed MCPTestResult, upgrading a generic connection
// error into an explicit "OAuth required" signal when the server answered with
// an RFC 9728 OAuth challenge. This lets the UI guide the user to switch the
// auth strategy to OAuth instead of showing a bare 401.
func mcpTestFailure(err error, prefix string) *types.MCPTestResult {
var oerr *mcp.OAuthRequiredError
if errors.As(err, &oerr) {
return &types.MCPTestResult{
Success: false,
OAuthRequired: true,
Message: "This MCP server requires OAuth authorization. " +
"Switch the auth method to OAuth 2.0 and authorize.",
}
}
return &types.MCPTestResult{
Success: false,
Message: fmt.Sprintf("%s: %v", prefix, err),
}
}
func (s *mcpServiceService) TestMCPService(
ctx context.Context,
tenantID uint64,
@@ -375,20 +405,14 @@ func (s *mcpServiceService) TestMCPService(
defer cancel()
if err := client.Connect(testCtx); err != nil {
return &types.MCPTestResult{
Success: false,
Message: fmt.Sprintf("Connection failed: %v", err),
}, nil
return mcpTestFailure(err, "Connection failed"), 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
return mcpTestFailure(err, "Initialization failed"), nil
}
// List tools
@@ -412,8 +436,9 @@ func (s *mcpServiceService) TestMCPService(
initResult.ServerInfo.Name,
initResult.ServerInfo.Version,
),
Tools: tools,
Resources: resources,
Description: initResult.ServerInfo.Description,
Tools: tools,
Resources: resources,
}, nil
}
@@ -584,4 +609,3 @@ func (s *mcpServiceService) GetMCPServiceResources(
return resources, nil
}
+17 -15
View File
@@ -21,21 +21,21 @@ import (
// only a boolean per credential field so the frontend can render a
// "configured / not configured" badge without an additional round-trip.
type MCPServiceResponse struct {
ID string `json:"id"`
TenantID uint64 `json:"tenant_id"`
Name string `json:"name"`
Description string `json:"description"`
Enabled bool `json:"enabled"`
TransportType types.MCPTransportType `json:"transport_type"`
URL *string `json:"url,omitempty"`
Headers types.MCPHeaders `json:"headers,omitempty"`
AuthConfig *MCPAuthConfigResponse `json:"auth_config,omitempty"`
AdvancedConfig *types.MCPAdvancedConfig `json:"advanced_config,omitempty"`
StdioConfig *types.MCPStdioConfig `json:"stdio_config,omitempty"`
EnvVars types.MCPEnvVars `json:"env_vars,omitempty"`
IsBuiltin bool `json:"is_builtin"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ID string `json:"id"`
TenantID uint64 `json:"tenant_id"`
Name string `json:"name"`
Description string `json:"description"`
Enabled bool `json:"enabled"`
TransportType types.MCPTransportType `json:"transport_type"`
URL *string `json:"url,omitempty"`
Headers types.MCPHeaders `json:"headers,omitempty"`
AuthConfig *MCPAuthConfigResponse `json:"auth_config,omitempty"`
AdvancedConfig *types.MCPAdvancedConfig `json:"advanced_config,omitempty"`
StdioConfig *types.MCPStdioConfig `json:"stdio_config,omitempty"`
EnvVars types.MCPEnvVars `json:"env_vars,omitempty"`
IsBuiltin bool `json:"is_builtin"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// Credentials is the per-field "configured?" map. Embedded on the main
// response so the credential UI doesn't need a follow-up GET. The
// frontend never sees the actual secret value — only whether one is
@@ -50,6 +50,7 @@ type MCPServiceResponse struct {
// echo back so the UI can render the current strategy.
type MCPAuthConfigResponse struct {
AuthType types.MCPAuthType `json:"auth_type,omitempty"`
APIKeyHeader string `json:"api_key_header,omitempty"`
CustomHeaders map[string]string `json:"custom_headers,omitempty"`
Scopes []string `json:"scopes,omitempty"`
AuthServerMetadataURL string `json:"auth_server_metadata_url,omitempty"`
@@ -90,6 +91,7 @@ func NewMCPServiceResponse(svc *types.MCPService) *MCPServiceResponse {
if svc.AuthConfig != nil {
resp.AuthConfig = &MCPAuthConfigResponse{
AuthType: svc.AuthConfig.AuthType,
APIKeyHeader: svc.AuthConfig.APIKeyHeader,
CustomHeaders: svc.AuthConfig.CustomHeaders,
Scopes: svc.AuthConfig.Scopes,
AuthServerMetadataURL: svc.AuthConfig.AuthServerMetadataURL,
+5
View File
@@ -303,6 +303,11 @@ func (h *MCPServiceHandler) UpdateMCPService(c *gin.Context) {
if authType, ok := authConfig["auth_type"].(string); ok {
service.AuthConfig.AuthType = types.MCPAuthType(authType)
}
// api_key_header is non-secret structural config (header name for the
// api_key strategy); flows through the main PUT like custom_headers.
if apiKeyHeader, ok := authConfig["api_key_header"].(string); ok {
service.AuthConfig.APIKeyHeader = apiKeyHeader
}
if scopes, ok := authConfig["scopes"].([]interface{}); ok {
list := make([]string, 0, len(scopes))
for _, s := range scopes {
+85 -17
View File
@@ -67,6 +67,80 @@ type mcpGoClient struct {
initialized bool
}
// applyAuthHeaders injects the auth header for the SELECTED strategy only —
// driven by AuthType so static API key / bearer are mutually exclusive (the old
// code emitted both whenever the fields happened to be set, which double-authed
// after a strategy switch). OAuth is handled separately by the caller.
// CustomHeaders are always layered on top regardless of strategy and may
// override the strategy header.
func applyAuthHeaders(headers map[string]string, ac *types.MCPAuthConfig) {
if ac == nil {
return
}
switch ac.AuthType {
case types.MCPAuthAPIKey:
if ac.APIKey != "" {
name := ac.APIKeyHeader
if name == "" {
name = "X-API-Key"
}
headers[name] = ac.APIKey
}
case types.MCPAuthBearer:
if ac.Token != "" {
headers["Authorization"] = "Bearer " + ac.Token
}
case types.MCPAuthNone:
// Backward compatibility for rows that predate AuthType: infer from
// whichever static credential is set, preserving the historical
// behavior so existing services keep authenticating after upgrade.
if ac.APIKey != "" {
headers["X-API-Key"] = ac.APIKey
}
if ac.Token != "" {
headers["Authorization"] = "Bearer " + ac.Token
}
}
for key, value := range ac.CustomHeaders {
headers[key] = value
}
}
// OAuthRequiredError signals that the target MCP server requires OAuth
// authorization — it answered the connect/initialize handshake with a 401 that
// advertised RFC 9728 protected-resource metadata — even though the service was
// NOT configured to use OAuth. Callers use this to guide the user to switch the
// auth strategy to OAuth instead of surfacing a generic "401" failure.
type OAuthRequiredError struct {
// MetadataURL is the RFC 9728 protected-resource metadata URL advertised by
// the server via the WWW-Authenticate header. Non-empty by construction
// (asOAuthRequired only wraps when the server advertised it).
MetadataURL string
Err error
}
func (e *OAuthRequiredError) Error() string {
return fmt.Sprintf("the MCP server requires OAuth authorization: %v", e.Err)
}
func (e *OAuthRequiredError) Unwrap() error { return e.Err }
// asOAuthRequired inspects err for a transport-level authorization-required
// signal that carries RFC 9728 protected-resource metadata. It returns a
// non-nil *OAuthRequiredError ONLY when the server advertised a metadata URL —
// a bare 401 without metadata is treated as an ordinary auth failure (e.g. a
// wrong/missing API key) so we don't misdirect the user toward OAuth.
func asOAuthRequired(err error) *OAuthRequiredError {
if err == nil {
return nil
}
var authErr *transport.AuthorizationRequiredError
if errors.As(err, &authErr) && authErr.ResourceMetadataURL != "" {
return &OAuthRequiredError{MetadataURL: authErr.ResourceMetadataURL, Err: err}
}
return nil
}
// NewMCPClient creates a new MCP client based on the transport type
func NewMCPClient(config *ClientConfig) (MCPClient, error) {
// Create HTTP client with timeout
@@ -84,21 +158,7 @@ func NewMCPClient(config *ClientConfig) (MCPClient, error) {
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
}
}
}
applyAuthHeaders(headers, config.Service.AuthConfig)
// Build OAuth config when this service uses the OAuth strategy. The
// client_id comes from the dynamically-registered client persisted at
@@ -229,6 +289,9 @@ func (c *mcpGoClient) Connect(ctx context.Context) error {
// Start the client
if err := c.client.Start(ctx); err != nil {
if oerr := asOAuthRequired(err); oerr != nil {
return oerr
}
return fmt.Errorf("failed to start client: %w", err)
}
c.connected = true
@@ -277,6 +340,9 @@ func (c *mcpGoClient) Initialize(ctx context.Context) (*InitializeResult, error)
result, err := c.client.Initialize(ctx, req)
if err != nil {
c.checkErrorAndDisconnectIfNeeded(err)
if oerr := asOAuthRequired(err); oerr != nil {
return nil, oerr
}
return nil, fmt.Errorf("failed to initialize: %w", err)
}
@@ -285,8 +351,10 @@ func (c *mcpGoClient) Initialize(ctx context.Context) (*InitializeResult, error)
return &InitializeResult{
ProtocolVersion: result.ProtocolVersion,
ServerInfo: ServerInfo{
Name: result.ServerInfo.Name,
Version: result.ServerInfo.Version,
Name: result.ServerInfo.Name,
Version: result.ServerInfo.Version,
Title: result.ServerInfo.Title,
Description: result.ServerInfo.Description,
},
}, nil
}
+123
View File
@@ -0,0 +1,123 @@
package mcp
import (
"errors"
"fmt"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/mark3labs/mcp-go/client/transport"
)
func TestAsOAuthRequired(t *testing.T) {
t.Run("nil error", func(t *testing.T) {
if got := asOAuthRequired(nil); got != nil {
t.Fatalf("got %v, want nil", got)
}
})
t.Run("401 with RFC 9728 metadata is treated as OAuth required", func(t *testing.T) {
meta := "https://example.com/.well-known/oauth-protected-resource"
err := fmt.Errorf("wrap: %w", &transport.AuthorizationRequiredError{ResourceMetadataURL: meta})
got := asOAuthRequired(err)
if got == nil {
t.Fatal("expected non-nil OAuthRequiredError")
}
if got.MetadataURL != meta {
t.Errorf("MetadataURL = %q, want %q", got.MetadataURL, meta)
}
})
t.Run("bare 401 without metadata is NOT OAuth required", func(t *testing.T) {
err := &transport.AuthorizationRequiredError{ResourceMetadataURL: ""}
if got := asOAuthRequired(err); got != nil {
t.Fatalf("got %v, want nil (bare 401 should not suggest OAuth)", got)
}
})
t.Run("unrelated error is ignored", func(t *testing.T) {
if got := asOAuthRequired(errors.New("connection refused")); got != nil {
t.Fatalf("got %v, want nil", got)
}
})
}
func TestApplyAuthHeaders(t *testing.T) {
tests := []struct {
name string
ac *types.MCPAuthConfig
want map[string]string
}{
{
name: "nil config injects nothing",
ac: nil,
want: map[string]string{},
},
{
name: "api_key uses default X-API-Key header",
ac: &types.MCPAuthConfig{AuthType: types.MCPAuthAPIKey, APIKey: "k1"},
want: map[string]string{"X-API-Key": "k1"},
},
{
name: "api_key honors custom header name (e.g. raw token in Authorization)",
ac: &types.MCPAuthConfig{
AuthType: types.MCPAuthAPIKey,
APIKey: "f7bfde",
APIKeyHeader: "Authorization",
},
want: map[string]string{"Authorization": "f7bfde"},
},
{
name: "bearer adds Bearer prefix",
ac: &types.MCPAuthConfig{AuthType: types.MCPAuthBearer, Token: "t1"},
want: map[string]string{"Authorization": "Bearer t1"},
},
{
name: "selected strategy is exclusive — stale token is not emitted",
ac: &types.MCPAuthConfig{
AuthType: types.MCPAuthAPIKey,
APIKey: "k1",
Token: "stale",
},
want: map[string]string{"X-API-Key": "k1"},
},
{
name: "empty AuthType keeps legacy behavior (infer from fields)",
ac: &types.MCPAuthConfig{
AuthType: types.MCPAuthNone,
APIKey: "k1",
Token: "t1",
},
want: map[string]string{"X-API-Key": "k1", "Authorization": "Bearer t1"},
},
{
name: "custom headers are always layered on top",
ac: &types.MCPAuthConfig{
AuthType: types.MCPAuthBearer,
Token: "t1",
CustomHeaders: map[string]string{"X-Trace": "abc"},
},
want: map[string]string{"Authorization": "Bearer t1", "X-Trace": "abc"},
},
{
name: "oauth strategy emits no static header (handled elsewhere)",
ac: &types.MCPAuthConfig{AuthType: types.MCPAuthOAuth, Token: "ignored"},
want: map[string]string{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
headers := map[string]string{}
applyAuthHeaders(headers, tt.ac)
if len(headers) != len(tt.want) {
t.Fatalf("header count = %d, want %d (%v)", len(headers), len(tt.want), headers)
}
for k, v := range tt.want {
if headers[k] != v {
t.Errorf("header[%q] = %q, want %q", k, headers[k], v)
}
}
})
}
}
+4 -2
View File
@@ -34,8 +34,10 @@ type PromptsCapability struct {
// ServerInfo represents information about the server
type ServerInfo struct {
Name string `json:"name"`
Version string `json:"version"`
Name string `json:"name"`
Version string `json:"version"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
}
// CallToolResult represents the result of tools/call request
+19 -7
View File
@@ -74,8 +74,15 @@ const (
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"`
AuthType MCPAuthType `json:"auth_type,omitempty"`
APIKey string `json:"api_key,omitempty"`
// APIKeyHeader is the header name that carries APIKey when AuthType is
// api_key. Empty defaults to "X-API-Key". This is non-secret structural
// config (the secret is APIKey), so it is not encrypted and is safe to echo
// back in responses. It lets services that expect the key in a different
// header (e.g. the raw token directly in "Authorization") work without
// resorting to plaintext custom headers.
APIKeyHeader string `json:"api_key_header,omitempty"`
Token string `json:"token,omitempty"`
CustomHeaders map[string]string `json:"custom_headers,omitempty"`
// Scopes are the OAuth scopes requested during authorization. Optional.
@@ -146,10 +153,16 @@ type MCPResource struct {
// 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"`
Success bool `json:"success"`
Message string `json:"message,omitempty"`
Description string `json:"description,omitempty"`
// OAuthRequired is true when the connection failed because the server
// requires OAuth authorization (RFC 9728), even though the service was not
// configured for OAuth. The UI uses it to guide the user to switch the auth
// strategy to OAuth.
OAuthRequired bool `json:"oauth_required,omitempty"`
Tools []*MCPTool `json:"tools,omitempty"`
Resources []*MCPResource `json:"resources,omitempty"`
}
// BeforeCreate is a GORM hook that runs before creating a new MCP service
@@ -317,4 +330,3 @@ func GetDefaultAdvancedConfig() *MCPAdvancedConfig {
// compile-time invariant of the DTO instead of a runtime call that handlers
// must remember to make. Builtin-service field stripping is also implemented
// there.