diff --git a/internal/configimport/claude_code.go b/internal/configimport/claude_code.go index 33074c554..c31c78848 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. @@ -18,6 +20,52 @@ type ClaudeCodeServerConfig struct { 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. The client secret is not part of it: Claude Code keeps it +// in the system keychain. +type ClaudeCodeOAuthConfig struct { + ClientID string `json:"clientId,omitempty"` + Scopes string `json:"scopes,omitempty"` + CallbackPort int `json:"callbackPort,omitempty"` + AuthServerMetadataURL string `json:"authServerMetadataUrl,omitempty"` +} + +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 + } + + var oauth ClaudeCodeOAuthConfig + var keys map[string]json.RawMessage + 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 { + // Case-insensitive, like the decoder above. + if !slices.ContainsFunc(claudeCodeOAuthKeys, func(known string) bool { return strings.EqualFold(k, known) }) { + unknown = append(unknown, k) + } + } + 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. @@ -57,6 +105,8 @@ func (p *ClaudeCodeParser) Parse(content []byte) ([]*ParsedServer, error) { } } + oauth, warnings := parseClaudeCodeOAuth(serverCfg.OAuth) + parsed := &ParsedServer{ Name: name, SourceFormat: FormatClaudeCode, @@ -67,8 +117,9 @@ func (p *ClaudeCodeParser) Parse(content []byte) ([]*ParsedServer, error) { "url": serverCfg.URL, "headers": serverCfg.Headers, "protocol": protocol, + "oauth": oauth, }, - Warnings: []string{}, + Warnings: append([]string{}, warnings...), } // Validate required fields based on protocol diff --git a/internal/configimport/claude_code_test.go b/internal/configimport/claude_code_test.go index 631f4131e..9e58ca53f 100644 --- a/internal/configimport/claude_code_test.go +++ b/internal/configimport/claude_code_test.go @@ -2,7 +2,9 @@ package configimport import ( "os" + "strings" "testing" + "time" ) func TestClaudeCodeParser_Parse(t *testing.T) { @@ -76,6 +78,106 @@ 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", + "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.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(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", + "clientSecret": "example-secret", + "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 || oauth.ClientID != "example-client" { + t.Fatalf("oauth = %+v, want the known field in another case applied", oauth) + } + // 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) + } + }) + + 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) + } + } + } + }) + t.Run("invalid_json", func(t *testing.T) { content := []byte(`{invalid json}`) _, err := parser.Parse(content) 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 6f50af04a..ce07b0b0d 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,13 @@ 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: + 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") + } } // Track skipped fields @@ -125,6 +133,45 @@ func mapGeminiOAuth(fields map[string]interface{}) *config.OAuthConfig { } } +// 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, []string) { + src, ok := fields["oauth"].(*ClaudeCodeOAuthConfig) + if !ok || src == nil { + return nil, nil + } + + 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)) + } + + 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. func getSkippedFields(parsed *ParsedServer) []string { skipped := []string{} diff --git a/internal/configimport/mapper_test.go b/internal/configimport/mapper_test.go index 72426eeb7..58dd43db0 100644 --- a/internal/configimport/mapper_test.go +++ b/internal/configimport/mapper_test.go @@ -199,6 +199,124 @@ 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", + 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) + } + // 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) + } + 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) { + 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",