From d7dd4b147ffe9994b8df40478a3da6aa1f519de1 Mon Sep 17 00:00:00 2001 From: Felipe Santos Date: Mon, 23 Nov 2026 17:59:25 -0300 Subject: [PATCH 1/2] feat(import): parse claude code oauth blocks Claude Code configs can carry an oauth block per server (clientId, clientSecret, scopes, callbackPort, authServerMetadataUrl), but the import parser ignored it, so those servers arrived without OAuth and needed manual setup. Parse the block, map it to OAuthConfig and warn on the parts that do not translate. Field mapping: - clientId, clientSecret and authServerMetadataUrl map 1:1. - scopes arrives as a space-separated string and becomes a list. - callbackPort pins only a port; mcpproxy pins the whole redirect URL, so the port is dropped with a warning instead of half-applied. - An empty clientId stays empty: mcpproxy falls back to DCR or public-client PKCE, which is what a server without a static client needs. - Unknown keys in the block warn and are ignored rather than refused: this is a foreign file format, and new Claude Code fields should surface as ignored, not break the import. Daemon-mode apply needs the AddServerRequest oauth field from #1972; config-file mode and the parse and map pipeline are complete here. --- internal/configimport/claude_code.go | 57 +++++++++++++-- internal/configimport/claude_code_test.go | 89 +++++++++++++++++++++++ internal/configimport/mapper.go | 36 +++++++++ internal/configimport/mapper_test.go | 71 ++++++++++++++++++ 4 files changed, 247 insertions(+), 6 deletions(-) diff --git a/internal/configimport/claude_code.go b/internal/configimport/claude_code.go index 33074c554..f8510716e 100644 --- a/internal/configimport/claude_code.go +++ b/internal/configimport/claude_code.go @@ -3,6 +3,8 @@ package configimport import ( "encoding/json" "fmt" + "slices" + "strings" ) // ClaudeCodeConfig represents the Claude Code configuration file structure. @@ -12,12 +14,50 @@ type ClaudeCodeConfig struct { // ClaudeCodeServerConfig represents a single server in Claude Code config. type ClaudeCodeServerConfig struct { - Type string `json:"type,omitempty"` // stdio, http, sse, websocket - Command string `json:"command,omitempty"` - Args []string `json:"args,omitempty"` - Env map[string]string `json:"env,omitempty"` - URL string `json:"url,omitempty"` - Headers map[string]string `json:"headers,omitempty"` + Type string `json:"type,omitempty"` // stdio, http, sse, websocket + Command string `json:"command,omitempty"` + Args []string `json:"args,omitempty"` + Env map[string]string `json:"env,omitempty"` + URL string `json:"url,omitempty"` + Headers map[string]string `json:"headers,omitempty"` + OAuth *ClaudeCodeOAuthConfig `json:"oauth,omitempty"` +} + +// ClaudeCodeOAuthConfig is the oauth block in Claude Code configs +// (https://code.claude.com/docs/en/mcp). Scopes is a space-separated string +// there, not a list. Unknown keys are collected for a warning instead of a +// refusal: this is a foreign file format, and new Claude Code fields should +// surface as "ignored", not break the import. +type ClaudeCodeOAuthConfig struct { + ClientID string `json:"clientId,omitempty"` + ClientSecret string `json:"clientSecret,omitempty"` + Scopes string `json:"scopes,omitempty"` + CallbackPort int `json:"callbackPort,omitempty"` + AuthServerMetadataURL string `json:"authServerMetadataUrl,omitempty"` + UnknownKeys []string `json:"-"` +} + +// UnmarshalJSON decodes the known fields and records everything else. +func (c *ClaudeCodeOAuthConfig) UnmarshalJSON(data []byte) error { + type plain ClaudeCodeOAuthConfig + var p plain + if err := json.Unmarshal(data, &p); err != nil { + return err + } + *c = ClaudeCodeOAuthConfig(p) + + var keys map[string]json.RawMessage + if err := json.Unmarshal(data, &keys); err != nil { + return err + } + for k := range keys { + switch k { + case "clientId", "clientSecret", "scopes", "callbackPort", "authServerMetadataUrl": + default: + c.UnknownKeys = append(c.UnknownKeys, k) + } + } + return nil } // ClaudeCodeParser parses Claude Code configuration files. @@ -67,6 +107,7 @@ func (p *ClaudeCodeParser) Parse(content []byte) ([]*ParsedServer, error) { "url": serverCfg.URL, "headers": serverCfg.Headers, "protocol": protocol, + "oauth": serverCfg.OAuth, }, Warnings: []string{}, } @@ -78,6 +119,10 @@ func (p *ClaudeCodeParser) Parse(content []byte) ([]*ParsedServer, error) { if (protocol == "http" || protocol == "sse" || protocol == "websocket") && serverCfg.URL == "" { parsed.Warnings = append(parsed.Warnings, fmt.Sprintf("%s server missing url field", protocol)) } + if serverCfg.OAuth != nil && len(serverCfg.OAuth.UnknownKeys) > 0 { + slices.Sort(serverCfg.OAuth.UnknownKeys) + parsed.Warnings = append(parsed.Warnings, fmt.Sprintf("oauth block has unknown keys %s; they were ignored", strings.Join(serverCfg.OAuth.UnknownKeys, ", "))) + } servers = append(servers, parsed) } diff --git a/internal/configimport/claude_code_test.go b/internal/configimport/claude_code_test.go index 631f4131e..5179277b6 100644 --- a/internal/configimport/claude_code_test.go +++ b/internal/configimport/claude_code_test.go @@ -2,6 +2,7 @@ package configimport import ( "os" + "strings" "testing" ) @@ -76,6 +77,94 @@ func TestClaudeCodeParser_Parse(t *testing.T) { } }) + t.Run("oauth_block", func(t *testing.T) { + content := []byte(`{ + "mcpServers": { + "remote": { + "type": "http", + "url": "https://example.com/mcp", + "oauth": { + "clientId": "example-client", + "clientSecret": "example-secret", + "scopes": "read write", + "callbackPort": 8080, + "authServerMetadataUrl": "https://auth.example.com/.well-known/oauth-authorization-server" + } + } + } + }`) + + servers, err := parser.Parse(content) + if err != nil { + t.Fatalf("Parse() error = %v", err) + } + if len(servers) != 1 { + t.Fatalf("Parse() returned %d servers, want 1", len(servers)) + } + + oauth, ok := servers[0].Fields["oauth"].(*ClaudeCodeOAuthConfig) + if !ok || oauth == nil { + t.Fatal("oauth field should be *ClaudeCodeOAuthConfig") + } + if oauth.ClientID != "example-client" { + t.Errorf("clientId = %s, want example-client", oauth.ClientID) + } + if oauth.ClientSecret != "example-secret" { + t.Errorf("clientSecret = %s, want example-secret", oauth.ClientSecret) + } + if oauth.Scopes != "read write" { + t.Errorf("scopes = %s, want 'read write'", oauth.Scopes) + } + if oauth.CallbackPort != 8080 { + t.Errorf("callbackPort = %d, want 8080", oauth.CallbackPort) + } + if oauth.AuthServerMetadataURL != "https://auth.example.com/.well-known/oauth-authorization-server" { + t.Errorf("authServerMetadataUrl = %s", oauth.AuthServerMetadataURL) + } + if len(oauth.UnknownKeys) != 0 { + t.Errorf("UnknownKeys = %v, want none", oauth.UnknownKeys) + } + if len(servers[0].Warnings) != 0 { + t.Errorf("warnings = %v, want none", servers[0].Warnings) + } + }) + + t.Run("oauth_unknown_keys_warned", func(t *testing.T) { + content := []byte(`{ + "mcpServers": { + "remote": { + "type": "http", + "url": "https://example.com/mcp", + "oauth": { + "clientId": "example-client", + "futureField": true + } + } + } + }`) + + servers, err := parser.Parse(content) + if err != nil { + t.Fatalf("Parse() error = %v", err) + } + oauth, _ := servers[0].Fields["oauth"].(*ClaudeCodeOAuthConfig) + if oauth == nil { + t.Fatal("oauth field should be set") + } + if len(oauth.UnknownKeys) != 1 || oauth.UnknownKeys[0] != "futureField" { + t.Errorf("UnknownKeys = %v, want [futureField]", oauth.UnknownKeys) + } + found := false + for _, w := range servers[0].Warnings { + if strings.Contains(w, "futureField") { + found = true + } + } + if !found { + t.Errorf("no warning mentions futureField: %v", servers[0].Warnings) + } + }) + t.Run("invalid_json", func(t *testing.T) { content := []byte(`{invalid json}`) _, err := parser.Parse(content) diff --git a/internal/configimport/mapper.go b/internal/configimport/mapper.go index 6f50af04a..528949b10 100644 --- a/internal/configimport/mapper.go +++ b/internal/configimport/mapper.go @@ -2,6 +2,7 @@ package configimport import ( "fmt" + "strings" "time" "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" @@ -80,6 +81,18 @@ func MapToServerConfig(parsed *ParsedServer, now time.Time) (*config.ServerConfi server.OAuth = oauth warnings = append(warnings, "OAuth credentials imported; you may need to reconfigure") } + case FormatClaudeCode: + if oauth := mapClaudeCodeOAuth(parsed.Fields); oauth != nil { + if raw, ok := parsed.Fields["oauth"].(*ClaudeCodeOAuthConfig); ok && raw.CallbackPort != 0 { + // mcpproxy has no port-only callback pin; oauth.redirect_uri + // is the full URL, so half a pin would fail validation. Claude + // Code also just allocates the port for its own callback, so + // leaving it unset matches the source behavior. + warnings = append(warnings, fmt.Sprintf("oauth.callbackPort %d has no mcpproxy equivalent and was dropped; set oauth.redirect_uri in config or the web UI if you need a fixed callback", raw.CallbackPort)) + } + server.OAuth = oauth + warnings = append(warnings, "OAuth credentials imported; you may need to reconfigure") + } } // Track skipped fields @@ -125,6 +138,29 @@ func mapGeminiOAuth(fields map[string]interface{}) *config.OAuthConfig { } } +// mapClaudeCodeOAuth extracts OAuth config from Claude Code's oauth field. +// Claude Code's dialect: scopes is a space-separated string and the auth +// server is named by authServerMetadataUrl. An empty client_id stays empty: +// mcpproxy falls back to DCR or public-client PKCE, which is what a server +// without a static client needs anyway. +func mapClaudeCodeOAuth(fields map[string]interface{}) *config.OAuthConfig { + oauth, ok := fields["oauth"].(*ClaudeCodeOAuthConfig) + if !ok || oauth == nil { + return nil + } + + if oauth.ClientID != "" || oauth.ClientSecret != "" || oauth.Scopes != "" || oauth.AuthServerMetadataURL != "" { + return &config.OAuthConfig{ + ClientID: oauth.ClientID, + ClientSecret: oauth.ClientSecret, + Scopes: strings.Fields(oauth.Scopes), + AuthServerMetadataURL: oauth.AuthServerMetadataURL, + } + } + + return nil +} + // getSkippedFields returns a list of fields that couldn't be mapped. func getSkippedFields(parsed *ParsedServer) []string { skipped := []string{} diff --git a/internal/configimport/mapper_test.go b/internal/configimport/mapper_test.go index 72426eeb7..f24253583 100644 --- a/internal/configimport/mapper_test.go +++ b/internal/configimport/mapper_test.go @@ -199,6 +199,77 @@ func TestMapToServerConfig(t *testing.T) { } }) + t.Run("claude_code_oauth", func(t *testing.T) { + parsed := &ParsedServer{ + Name: "oauth-server", + SourceFormat: FormatClaudeCode, + Fields: map[string]interface{}{ + "url": "https://example.com/mcp", + "protocol": "http", + "oauth": &ClaudeCodeOAuthConfig{ + ClientID: "claude-client", + ClientSecret: "claude-secret", + Scopes: "read write", + CallbackPort: 8080, + AuthServerMetadataURL: "https://auth.example.com/.well-known/oauth-authorization-server", + }, + }, + } + + server, _, warnings := MapToServerConfig(parsed, now) + + if server.OAuth == nil { + t.Fatal("OAuth should be set") + } + if server.OAuth.ClientID != "claude-client" { + t.Errorf("OAuth.ClientID = %s, want claude-client", server.OAuth.ClientID) + } + if server.OAuth.ClientSecret != "claude-secret" { + t.Errorf("OAuth.ClientSecret = %s, want claude-secret", server.OAuth.ClientSecret) + } + // Claude Code writes scopes as a space-separated string; mcpproxy wants []string. + if len(server.OAuth.Scopes) != 2 || server.OAuth.Scopes[0] != "read" || server.OAuth.Scopes[1] != "write" { + t.Errorf("OAuth.Scopes = %v, want [read write]", server.OAuth.Scopes) + } + if server.OAuth.AuthServerMetadataURL != "https://auth.example.com/.well-known/oauth-authorization-server" { + t.Errorf("OAuth.AuthServerMetadataURL = %s", server.OAuth.AuthServerMetadataURL) + } + // callbackPort has no mcpproxy equivalent: mcpproxy pins redirects with + // redirect_uri (full URL), and half a pin would fail validation. + var portWarned bool + for _, w := range warnings { + if strings.Contains(w, "callbackPort") && strings.Contains(w, "dropped") { + portWarned = true + } + } + if !portWarned { + t.Errorf("dropping callbackPort must be warned about, got %v", warnings) + } + }) + + t.Run("claude_code_oauth_without_client_id", func(t *testing.T) { + parsed := &ParsedServer{ + Name: "oauth-server", + SourceFormat: FormatClaudeCode, + Fields: map[string]interface{}{ + "url": "https://example.com/mcp", + "protocol": "http", + "oauth": &ClaudeCodeOAuthConfig{ + AuthServerMetadataURL: "https://auth.example.com/.well-known/oauth-authorization-server", + }, + }, + } + + server, _, _ := MapToServerConfig(parsed, now) + + if server.OAuth == nil { + t.Fatal("OAuth should be set even without a client_id; mcpproxy falls back to DCR or public-client PKCE") + } + if server.OAuth.ClientID != "" { + t.Errorf("OAuth.ClientID = %s, want empty", server.OAuth.ClientID) + } + }) + t.Run("gemini_oauth_usable_redirect_uri_preserved", func(t *testing.T) { parsed := &ParsedServer{ Name: "oauth-server", From 5e574203556ff4cdabc2183597661d793184be15 Mon Sep 17 00:00:00 2001 From: Felipe Santos Date: Tue, 24 Nov 2026 11:36:33 -0300 Subject: [PATCH 2/2] fix(import): warn about Claude Code oauth settings that cannot be imported --- internal/configimport/claude_code.go | 78 ++++++++++++----------- internal/configimport/claude_code_test.go | 51 +++++++++------ internal/configimport/detector.go | 18 ++++++ internal/configimport/detector_test.go | 27 ++++++++ internal/configimport/mapper.go | 53 +++++++++------ internal/configimport/mapper_test.go | 55 ++++++++++++++-- 6 files changed, 202 insertions(+), 80 deletions(-) diff --git a/internal/configimport/claude_code.go b/internal/configimport/claude_code.go index f8510716e..c31c78848 100644 --- a/internal/configimport/claude_code.go +++ b/internal/configimport/claude_code.go @@ -14,50 +14,58 @@ type ClaudeCodeConfig struct { // ClaudeCodeServerConfig represents a single server in Claude Code config. type ClaudeCodeServerConfig struct { - Type string `json:"type,omitempty"` // stdio, http, sse, websocket - Command string `json:"command,omitempty"` - Args []string `json:"args,omitempty"` - Env map[string]string `json:"env,omitempty"` - URL string `json:"url,omitempty"` - Headers map[string]string `json:"headers,omitempty"` - OAuth *ClaudeCodeOAuthConfig `json:"oauth,omitempty"` + Type string `json:"type,omitempty"` // stdio, http, sse, websocket + Command string `json:"command,omitempty"` + Args []string `json:"args,omitempty"` + Env map[string]string `json:"env,omitempty"` + URL string `json:"url,omitempty"` + Headers map[string]string `json:"headers,omitempty"` + // Raw so that a malformed block costs only this server its OAuth settings. + OAuth json.RawMessage `json:"oauth,omitempty"` } // ClaudeCodeOAuthConfig is the oauth block in Claude Code configs // (https://code.claude.com/docs/en/mcp). Scopes is a space-separated string -// there, not a list. Unknown keys are collected for a warning instead of a -// refusal: this is a foreign file format, and new Claude Code fields should -// surface as "ignored", not break the import. +// there, not a list. The client secret is not part of it: Claude Code keeps it +// in the system keychain. type ClaudeCodeOAuthConfig struct { - ClientID string `json:"clientId,omitempty"` - ClientSecret string `json:"clientSecret,omitempty"` - Scopes string `json:"scopes,omitempty"` - CallbackPort int `json:"callbackPort,omitempty"` - AuthServerMetadataURL string `json:"authServerMetadataUrl,omitempty"` - UnknownKeys []string `json:"-"` + ClientID string `json:"clientId,omitempty"` + Scopes string `json:"scopes,omitempty"` + CallbackPort int `json:"callbackPort,omitempty"` + AuthServerMetadataURL string `json:"authServerMetadataUrl,omitempty"` } -// UnmarshalJSON decodes the known fields and records everything else. -func (c *ClaudeCodeOAuthConfig) UnmarshalJSON(data []byte) error { - type plain ClaudeCodeOAuthConfig - var p plain - if err := json.Unmarshal(data, &p); err != nil { - return err +var claudeCodeOAuthKeys = []string{"clientId", "scopes", "callbackPort", "authServerMetadataUrl"} + +// parseClaudeCodeOAuth decodes an oauth block. This is a foreign file format, +// so a malformed block or an unknown key is a warning, never a failed import. +func parseClaudeCodeOAuth(raw json.RawMessage) (*ClaudeCodeOAuthConfig, []string) { + if len(raw) == 0 || string(raw) == "null" { + return nil, nil } - *c = ClaudeCodeOAuthConfig(p) + var oauth ClaudeCodeOAuthConfig var keys map[string]json.RawMessage - if err := json.Unmarshal(data, &keys); err != nil { - return err + err := json.Unmarshal(raw, &oauth) + if err == nil { + err = json.Unmarshal(raw, &keys) + } + if err != nil { + return nil, []string{fmt.Sprintf("oauth block is malformed and was ignored: %v", err)} } + + var unknown []string for k := range keys { - switch k { - case "clientId", "clientSecret", "scopes", "callbackPort", "authServerMetadataUrl": - default: - c.UnknownKeys = append(c.UnknownKeys, k) + // Case-insensitive, like the decoder above. + if !slices.ContainsFunc(claudeCodeOAuthKeys, func(known string) bool { return strings.EqualFold(k, known) }) { + unknown = append(unknown, k) } } - return nil + if len(unknown) == 0 { + return &oauth, nil + } + slices.Sort(unknown) + return &oauth, []string{fmt.Sprintf("oauth block has unknown keys %s; they were ignored", strings.Join(unknown, ", "))} } // ClaudeCodeParser parses Claude Code configuration files. @@ -97,6 +105,8 @@ func (p *ClaudeCodeParser) Parse(content []byte) ([]*ParsedServer, error) { } } + oauth, warnings := parseClaudeCodeOAuth(serverCfg.OAuth) + parsed := &ParsedServer{ Name: name, SourceFormat: FormatClaudeCode, @@ -107,9 +117,9 @@ func (p *ClaudeCodeParser) Parse(content []byte) ([]*ParsedServer, error) { "url": serverCfg.URL, "headers": serverCfg.Headers, "protocol": protocol, - "oauth": serverCfg.OAuth, + "oauth": oauth, }, - Warnings: []string{}, + Warnings: append([]string{}, warnings...), } // Validate required fields based on protocol @@ -119,10 +129,6 @@ func (p *ClaudeCodeParser) Parse(content []byte) ([]*ParsedServer, error) { if (protocol == "http" || protocol == "sse" || protocol == "websocket") && serverCfg.URL == "" { parsed.Warnings = append(parsed.Warnings, fmt.Sprintf("%s server missing url field", protocol)) } - if serverCfg.OAuth != nil && len(serverCfg.OAuth.UnknownKeys) > 0 { - slices.Sort(serverCfg.OAuth.UnknownKeys) - parsed.Warnings = append(parsed.Warnings, fmt.Sprintf("oauth block has unknown keys %s; they were ignored", strings.Join(serverCfg.OAuth.UnknownKeys, ", "))) - } servers = append(servers, parsed) } diff --git a/internal/configimport/claude_code_test.go b/internal/configimport/claude_code_test.go index 5179277b6..9e58ca53f 100644 --- a/internal/configimport/claude_code_test.go +++ b/internal/configimport/claude_code_test.go @@ -4,6 +4,7 @@ import ( "os" "strings" "testing" + "time" ) func TestClaudeCodeParser_Parse(t *testing.T) { @@ -85,7 +86,6 @@ func TestClaudeCodeParser_Parse(t *testing.T) { "url": "https://example.com/mcp", "oauth": { "clientId": "example-client", - "clientSecret": "example-secret", "scopes": "read write", "callbackPort": 8080, "authServerMetadataUrl": "https://auth.example.com/.well-known/oauth-authorization-server" @@ -109,9 +109,6 @@ func TestClaudeCodeParser_Parse(t *testing.T) { if oauth.ClientID != "example-client" { t.Errorf("clientId = %s, want example-client", oauth.ClientID) } - if oauth.ClientSecret != "example-secret" { - t.Errorf("clientSecret = %s, want example-secret", oauth.ClientSecret) - } if oauth.Scopes != "read write" { t.Errorf("scopes = %s, want 'read write'", oauth.Scopes) } @@ -121,9 +118,6 @@ func TestClaudeCodeParser_Parse(t *testing.T) { if oauth.AuthServerMetadataURL != "https://auth.example.com/.well-known/oauth-authorization-server" { t.Errorf("authServerMetadataUrl = %s", oauth.AuthServerMetadataURL) } - if len(oauth.UnknownKeys) != 0 { - t.Errorf("UnknownKeys = %v, want none", oauth.UnknownKeys) - } if len(servers[0].Warnings) != 0 { t.Errorf("warnings = %v, want none", servers[0].Warnings) } @@ -136,7 +130,8 @@ func TestClaudeCodeParser_Parse(t *testing.T) { "type": "http", "url": "https://example.com/mcp", "oauth": { - "clientId": "example-client", + "ClientID": "example-client", + "clientSecret": "example-secret", "futureField": true } } @@ -148,20 +143,38 @@ func TestClaudeCodeParser_Parse(t *testing.T) { t.Fatalf("Parse() error = %v", err) } oauth, _ := servers[0].Fields["oauth"].(*ClaudeCodeOAuthConfig) - if oauth == nil { - t.Fatal("oauth field should be set") + if oauth == nil || oauth.ClientID != "example-client" { + t.Fatalf("oauth = %+v, want the known field in another case applied", oauth) } - if len(oauth.UnknownKeys) != 1 || oauth.UnknownKeys[0] != "futureField" { - t.Errorf("UnknownKeys = %v, want [futureField]", oauth.UnknownKeys) + // Only the unknown key, and never its value. + if len(servers[0].Warnings) != 1 || !strings.Contains(servers[0].Warnings[0], "unknown keys clientSecret, futureField;") { + t.Errorf("warnings = %v, want one naming clientSecret and futureField", servers[0].Warnings) } - found := false - for _, w := range servers[0].Warnings { - if strings.Contains(w, "futureField") { - found = true + }) + + t.Run("oauth_malformed_keeps_servers", func(t *testing.T) { + for _, block := range []string{`false`, `"x"`, `[]`, `{"scopes":["read"]}`, `{"callbackPort":"8080"}`} { + content := []byte(`{"mcpServers":{ + "bad": {"type":"http","url":"https://bad.example.com/mcp","oauth":` + block + `}, + "good": {"type":"http","url":"https://good.example.com/mcp"} + }}`) + + servers, err := parser.Parse(content) + if err != nil { + t.Fatalf("%s: Parse() error = %v", block, err) + } + if len(servers) != 2 { + t.Fatalf("%s: Parse() returned %d servers, want 2", block, len(servers)) + } + for _, s := range servers { + warned := len(s.Warnings) == 1 && strings.Contains(s.Warnings[0], "malformed") + if warned != (s.Name == "bad") { + t.Errorf("%s: %s warnings = %v", block, s.Name, s.Warnings) + } + if server, _, _ := MapToServerConfig(s, time.Now()); server.OAuth != nil { + t.Errorf("%s: %s OAuth = %+v, want nil", block, s.Name, server.OAuth) + } } - } - if !found { - t.Errorf("no warning mentions futureField: %v", servers[0].Warnings) } }) diff --git a/internal/configimport/detector.go b/internal/configimport/detector.go index 6ce985783..3f4d368e5 100644 --- a/internal/configimport/detector.go +++ b/internal/configimport/detector.go @@ -270,6 +270,24 @@ func tryDetectJSON(content []byte) *DetectionResult { } } + // Claude Code: an oauth object. Gemini has one too, told apart by its + // "enabled" key; Cursor's equivalent is "auth". + for _, server := range serversMap { + serverMap, ok := server.(map[string]interface{}) + if !ok { + continue + } + if oauth, hasOAuth := serverMap["oauth"].(map[string]interface{}); hasOAuth { + if _, isGemini := oauth["enabled"]; !isGemini { + return &DetectionResult{ + Format: FormatClaudeCode, + Confidence: "medium", + Indicators: []string{"json_format", "mcpServers_key", "oauth_object"}, + } + } + } + } + // Default fallback: Cursor IDE is the most generic JSON format // Claude Desktop requires command-only servers (no url), check for that allStdio := true diff --git a/internal/configimport/detector_test.go b/internal/configimport/detector_test.go index 3ffed947e..4fee5e016 100644 --- a/internal/configimport/detector_test.go +++ b/internal/configimport/detector_test.go @@ -26,6 +26,33 @@ func TestDetectFormat(t *testing.T) { wantFormat: FormatClaudeDesktop, wantConfidence: "high", }, + { + name: "claude_code_sse_with_oauth", + content: `{ + "mcpServers": { + "remote": { + "type": "sse", + "url": "https://example.com/sse", + "oauth": {"clientId": "example-client", "callbackPort": 8080} + } + } + }`, + wantFormat: FormatClaudeCode, + wantConfidence: "medium", + }, + { + name: "gemini_oauth_is_not_claude_code", + content: `{ + "mcpServers": { + "remote": { + "url": "https://example.com/sse", + "oauth": {"enabled": true, "clientId": "example-client"} + } + } + }`, + wantFormat: FormatCursor, + wantConfidence: "low", + }, { name: "claude_desktop_stdio_only", content: `{ diff --git a/internal/configimport/mapper.go b/internal/configimport/mapper.go index 528949b10..ce07b0b0d 100644 --- a/internal/configimport/mapper.go +++ b/internal/configimport/mapper.go @@ -82,14 +82,9 @@ func MapToServerConfig(parsed *ParsedServer, now time.Time) (*config.ServerConfi warnings = append(warnings, "OAuth credentials imported; you may need to reconfigure") } case FormatClaudeCode: - if oauth := mapClaudeCodeOAuth(parsed.Fields); oauth != nil { - if raw, ok := parsed.Fields["oauth"].(*ClaudeCodeOAuthConfig); ok && raw.CallbackPort != 0 { - // mcpproxy has no port-only callback pin; oauth.redirect_uri - // is the full URL, so half a pin would fail validation. Claude - // Code also just allocates the port for its own callback, so - // leaving it unset matches the source behavior. - warnings = append(warnings, fmt.Sprintf("oauth.callbackPort %d has no mcpproxy equivalent and was dropped; set oauth.redirect_uri in config or the web UI if you need a fixed callback", raw.CallbackPort)) - } + oauth, oauthWarnings := mapClaudeCodeOAuth(parsed.Fields) + warnings = append(warnings, oauthWarnings...) + if oauth != nil { server.OAuth = oauth warnings = append(warnings, "OAuth credentials imported; you may need to reconfigure") } @@ -138,27 +133,43 @@ func mapGeminiOAuth(fields map[string]interface{}) *config.OAuthConfig { } } -// mapClaudeCodeOAuth extracts OAuth config from Claude Code's oauth field. +// mapClaudeCodeOAuth extracts OAuth config from Claude Code's oauth field, with +// a warning for everything that could not be carried over. // Claude Code's dialect: scopes is a space-separated string and the auth // server is named by authServerMetadataUrl. An empty client_id stays empty: // mcpproxy falls back to DCR or public-client PKCE, which is what a server // without a static client needs anyway. -func mapClaudeCodeOAuth(fields map[string]interface{}) *config.OAuthConfig { - oauth, ok := fields["oauth"].(*ClaudeCodeOAuthConfig) - if !ok || oauth == nil { - return nil +func mapClaudeCodeOAuth(fields map[string]interface{}) (*config.OAuthConfig, []string) { + src, ok := fields["oauth"].(*ClaudeCodeOAuthConfig) + if !ok || src == nil { + return nil, nil } - if oauth.ClientID != "" || oauth.ClientSecret != "" || oauth.Scopes != "" || oauth.AuthServerMetadataURL != "" { - return &config.OAuthConfig{ - ClientID: oauth.ClientID, - ClientSecret: oauth.ClientSecret, - Scopes: strings.Fields(oauth.Scopes), - AuthServerMetadataURL: oauth.AuthServerMetadataURL, - } + var warnings []string + if src.CallbackPort != 0 { + // mcpproxy has no port-only callback pin; oauth.redirect_uri is the + // full URL, so half a pin would fail validation. + warnings = append(warnings, fmt.Sprintf("oauth.callbackPort %d has no mcpproxy equivalent and was dropped; set oauth.redirect_uri in config or the web UI if you need a fixed callback", src.CallbackPort)) } - return nil + oauth := &config.OAuthConfig{ + ClientID: src.ClientID, + Scopes: strings.Fields(src.Scopes), + AuthServerMetadataURL: src.AuthServerMetadataURL, + } + // The only value here that Validate can reject; its error does not echo it. + if err := oauth.Validate(); err != nil { + warnings = append(warnings, fmt.Sprintf("oauth.authServerMetadataUrl is not usable by mcpproxy and was dropped: %v", err)) + oauth.AuthServerMetadataURL = "" + } + if oauth.ClientID != "" { + warnings = append(warnings, "Claude Code does not store the OAuth client secret in its config; set oauth.client_secret if this client has one") + } + + if oauth.ClientID == "" && len(oauth.Scopes) == 0 && oauth.AuthServerMetadataURL == "" { + return nil, warnings + } + return oauth, warnings } // getSkippedFields returns a list of fields that couldn't be mapped. diff --git a/internal/configimport/mapper_test.go b/internal/configimport/mapper_test.go index f24253583..58dd43db0 100644 --- a/internal/configimport/mapper_test.go +++ b/internal/configimport/mapper_test.go @@ -208,7 +208,6 @@ func TestMapToServerConfig(t *testing.T) { "protocol": "http", "oauth": &ClaudeCodeOAuthConfig{ ClientID: "claude-client", - ClientSecret: "claude-secret", Scopes: "read write", CallbackPort: 8080, AuthServerMetadataURL: "https://auth.example.com/.well-known/oauth-authorization-server", @@ -224,9 +223,6 @@ func TestMapToServerConfig(t *testing.T) { if server.OAuth.ClientID != "claude-client" { t.Errorf("OAuth.ClientID = %s, want claude-client", server.OAuth.ClientID) } - if server.OAuth.ClientSecret != "claude-secret" { - t.Errorf("OAuth.ClientSecret = %s, want claude-secret", server.OAuth.ClientSecret) - } // Claude Code writes scopes as a space-separated string; mcpproxy wants []string. if len(server.OAuth.Scopes) != 2 || server.OAuth.Scopes[0] != "read" || server.OAuth.Scopes[1] != "write" { t.Errorf("OAuth.Scopes = %v, want [read write]", server.OAuth.Scopes) @@ -245,6 +241,57 @@ func TestMapToServerConfig(t *testing.T) { if !portWarned { t.Errorf("dropping callbackPort must be warned about, got %v", warnings) } + if !strings.Contains(strings.Join(warnings, "\n"), "oauth.client_secret") { + t.Errorf("the missing client secret must be warned about, got %v", warnings) + } + }) + + t.Run("claude_code_oauth_callback_port_only", func(t *testing.T) { + parsed := &ParsedServer{ + Name: "oauth-server", + SourceFormat: FormatClaudeCode, + Fields: map[string]interface{}{ + "url": "https://example.com/mcp", + "protocol": "http", + "oauth": &ClaudeCodeOAuthConfig{CallbackPort: 8080}, + }, + } + + server, _, warnings := MapToServerConfig(parsed, now) + + if server.OAuth != nil { + t.Errorf("OAuth = %+v, want nil", server.OAuth) + } + if len(warnings) != 1 || !strings.Contains(warnings[0], "callbackPort 8080") { + t.Errorf("warnings = %v, want only the dropped callbackPort", warnings) + } + }) + + t.Run("claude_code_oauth_invalid_metadata_url_dropped", func(t *testing.T) { + for _, bad := range []string{"http://auth.example.com/meta", "https://user:hunter2@auth.example.com/meta", "https://auth.example.com/meta?token=hunter2"} { + parsed := &ParsedServer{ + Name: "oauth-server", + SourceFormat: FormatClaudeCode, + Fields: map[string]interface{}{ + "url": "https://example.com/mcp", + "protocol": "http", + "oauth": &ClaudeCodeOAuthConfig{ClientID: "claude-client", AuthServerMetadataURL: bad}, + }, + } + + server, _, warnings := MapToServerConfig(parsed, now) + + if server.OAuth == nil || server.OAuth.ClientID != "claude-client" || server.OAuth.AuthServerMetadataURL != "" { + t.Errorf("%s: OAuth = %+v, want client id without metadata URL", bad, server.OAuth) + } + joined := strings.Join(warnings, "\n") + if !strings.Contains(joined, "authServerMetadataUrl") { + t.Errorf("%s: no warning about the dropped URL: %v", bad, warnings) + } + if strings.Contains(joined, "hunter2") { + t.Errorf("%s: warning echoes the URL: %v", bad, warnings) + } + } }) t.Run("claude_code_oauth_without_client_id", func(t *testing.T) {