Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 52 additions & 1 deletion internal/configimport/claude_code.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package configimport
import (
"encoding/json"
"fmt"
"slices"
"strings"
)

// ClaudeCodeConfig represents the Claude Code configuration file structure.
Expand All @@ -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.
Expand Down Expand Up @@ -57,6 +105,8 @@ func (p *ClaudeCodeParser) Parse(content []byte) ([]*ParsedServer, error) {
}
}

oauth, warnings := parseClaudeCodeOAuth(serverCfg.OAuth)

parsed := &ParsedServer{
Name: name,
SourceFormat: FormatClaudeCode,
Expand All @@ -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
Expand Down
102 changes: 102 additions & 0 deletions internal/configimport/claude_code_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package configimport

import (
"os"
"strings"
"testing"
"time"
)

func TestClaudeCodeParser_Parse(t *testing.T) {
Expand Down Expand Up @@ -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)
Expand Down
18 changes: 18 additions & 0 deletions internal/configimport/detector.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 27 additions & 0 deletions internal/configimport/detector_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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: `{
Expand Down
47 changes: 47 additions & 0 deletions internal/configimport/mapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package configimport

import (
"fmt"
"strings"
"time"

"github.com/smart-mcp-proxy/mcpproxy-go/internal/config"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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{}
Expand Down
Loading
Loading