Skip to content
Open
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
73 changes: 73 additions & 0 deletions cmd/mcpproxy/upstream_add_config_mode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,76 @@ func TestParseAddJSONTrustMode(t *testing.T) {
assert.Equal(t, "stdio", req.Protocol)
})
}

// TestParseAddJSONOAuthAndUnknownKeys: add-json dropped oauth (and any other
// key it did not name) while reporting success.
func TestParseAddJSONOAuthAndUnknownKeys(t *testing.T) {
t.Run("oauth carried through", func(t *testing.T) {
req, err := parseAddJSONRequest("ha", `{"url":"https://ha.example.com/api/mcp","oauth":{"client_id":"http://127.0.0.1:8765/","redirect_uri":"http://127.0.0.1:8765/oauth/callback"}}`)
require.NoError(t, err)
require.NotNil(t, req.OAuth)
assert.Equal(t, "http://127.0.0.1:8765/", req.OAuth.ClientID)
assert.Equal(t, "http://127.0.0.1:8765/oauth/callback", req.OAuth.RedirectURI)
})

t.Run("invalid oauth refused", func(t *testing.T) {
_, err := parseAddJSONRequest("ha", `{"url":"https://ha.example.com/api/mcp","oauth":{"redirect_uri":"https://example.com/cb"}}`)
require.Error(t, err)
})

t.Run("refresh replay without token endpoint refused", func(t *testing.T) {
_, err := parseAddJSONRequest("srv", `{"url":"https://example.com/mcp","oauth":{"client_id":"x","refresh_replay_enabled":true}}`)
require.Error(t, err)
assert.Contains(t, err.Error(), "token_endpoint")
})

t.Run("unknown top-level keys are reported, not refused", func(t *testing.T) {
req, unknown, err := parseAddJSON("srv", `{"url":"https://example.com/mcp","isolation":{},"enabled":true}`)
require.NoError(t, err)
require.NotNil(t, req)
assert.Equal(t, "https://example.com/mcp", req.URL)
assert.Equal(t, []string{"enabled", "isolation"}, unknown)

msg := addJSONUnknownKeysWarning(unknown)
assert.Contains(t, msg, `"enabled", "isolation"`)
assert.Contains(t, msg, "oauth")
assert.Contains(t, msg, "ignored")

_, unknown, err = parseAddJSON("srv", `{"url":"https://example.com/mcp"}`)
require.NoError(t, err)
assert.Empty(t, unknown)
})

t.Run("unknown key inside oauth refused", func(t *testing.T) {
_, err := parseAddJSONRequest("srv", `{"url":"https://example.com/mcp","oauth":{"clientId":"x"}}`)
require.Error(t, err)
assert.Contains(t, err.Error(), "clientId")
})

t.Run("type is an alias for protocol", func(t *testing.T) {
req, err := parseAddJSONRequest("srv", `{"type":"http","url":"https://example.com/mcp"}`)
require.NoError(t, err)
assert.Equal(t, "http", req.Protocol)

_, err = parseAddJSONRequest("srv", `{"type":"http","protocol":"sse","url":"https://example.com/mcp"}`)
require.Error(t, err)
})
}

// TestUpstreamAddConfigModeKeepsOAuth: the no-daemon path writes the oauth
// block to the config, like the daemon path does.
func TestUpstreamAddConfigModeKeepsOAuth(t *testing.T) {
cfg := config.DefaultConfig()
cfg.DataDir = t.TempDir()
req := &cliclient.AddServerRequest{
Name: "ha",
URL: "https://ha.example.com/api/mcp",
Protocol: "http",
OAuth: &config.OAuthConfig{ClientID: "http://127.0.0.1:8765/"},
}
added, err := runUpstreamAddConfigMode(req, cfg)
require.NoError(t, err)
require.True(t, added)
require.NotNil(t, cfg.Servers[0].OAuth)
assert.Equal(t, "http://127.0.0.1:8765/", cfg.Servers[0].OAuth.ClientID)
}
106 changes: 90 additions & 16 deletions cmd/mcpproxy/upstream_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ import (
"os/exec"
"os/signal"
"path/filepath"
"slices"
"sort"
"strconv"
"strings"
"syscall"
"time"
Expand Down Expand Up @@ -124,9 +126,14 @@ Examples:
Short: "Add an upstream server using JSON configuration",
Long: `Add a new upstream MCP server using a JSON configuration object.

Accepted keys: url, command, args, env, headers, working_dir, protocol
(or its alias type), trust_mode, oauth. Any other top-level key is ignored
with a warning on stderr; an unknown key inside oauth is refused.

Examples:
mcpproxy upstream add-json weather '{"url":"https://api.weather.com/mcp","headers":{"Authorization":"Bearer token"}}'
mcpproxy upstream add-json sqlite '{"command":"uvx","args":["mcp-server-sqlite","--db","mydb.db"]}'`,
mcpproxy upstream add-json sqlite '{"command":"uvx","args":["mcp-server-sqlite","--db","mydb.db"]}'
mcpproxy upstream add-json ha '{"url":"https://ha.example.com/api/mcp","oauth":{"client_id":"http://127.0.0.1:8765/","redirect_uri":"http://127.0.0.1:8765/oauth/callback"}}'`,
Args: cobra.ExactArgs(2),
RunE: runUpstreamAddJSON,
}
Expand Down Expand Up @@ -1818,6 +1825,7 @@ func runUpstreamAddConfigMode(req *cliclient.AddServerRequest, globalConfig *con
Enabled: true,
Quarantined: quarantined,
TrustMode: req.TrustMode,
OAuth: req.OAuth,
}
if req.Quarantined != nil {
// A stated --quarantine/--no-quarantine is written to the file as an
Expand Down Expand Up @@ -1956,24 +1964,65 @@ func runUpstreamRemoveConfigMode(serverName string, globalConfig *config.Config)
// — the operator believed the tier had been applied. A bogus value is refused
// with the same vocabulary every other write seam uses instead of being
// silently downgraded.
//
// The same happened to oauth, and to every other key the struct did not name,
// so any key outside addJSONKeys is now reported on stderr (the server is still
// added: refusing would break payloads that used to succeed), while an unknown
// key inside oauth is refused (oauth was never carried before). "type" (the Claude Desktop / VS Code spelling) is accepted as
// an alias for protocol so configs pasted from those clients still work.
func parseAddJSONRequest(serverName, jsonStr string) (*cliclient.AddServerRequest, error) {
req, _, err := parseAddJSON(serverName, jsonStr)
return req, err
}

// parseAddJSON is parseAddJSONRequest plus the sorted top-level keys it did not
// apply, so the caller can warn about them.
func parseAddJSON(serverName, jsonStr string) (*cliclient.AddServerRequest, []string, error) {
var keys map[string]json.RawMessage
if err := json.Unmarshal([]byte(jsonStr), &keys); err != nil {
return nil, nil, fmt.Errorf("invalid JSON: %w", err)
}
var unknown []string
for k := range keys {
if !slices.Contains(addJSONKeys, k) {
unknown = append(unknown, k)
delete(keys, k) // reported, not decoded: the strict decode below is for oauth
}
}
sort.Strings(unknown)
known, err := json.Marshal(keys)
if err != nil {
return nil, nil, fmt.Errorf("invalid JSON: %w", err)
}
jsonStr = string(known)

var jsonConfig struct {
URL string `json:"url"`
Command string `json:"command"`
Args []string `json:"args"`
Env map[string]string `json:"env"`
Headers map[string]string `json:"headers"`
WorkingDir string `json:"working_dir"`
Protocol string `json:"protocol"`
TrustMode string `json:"trust_mode"`
URL string `json:"url"`
Command string `json:"command"`
Args []string `json:"args"`
Env map[string]string `json:"env"`
Headers map[string]string `json:"headers"`
WorkingDir string `json:"working_dir"`
Protocol string `json:"protocol"`
Type string `json:"type"`
TrustMode string `json:"trust_mode"`
OAuth *config.OAuthConfig `json:"oauth"`
}
dec := json.NewDecoder(strings.NewReader(jsonStr))
dec.DisallowUnknownFields() // catches a misspelled key inside oauth
if err := dec.Decode(&jsonConfig); err != nil {
return nil, nil, fmt.Errorf("invalid JSON: %w", err)
}

if err := json.Unmarshal([]byte(jsonStr), &jsonConfig); err != nil {
return nil, fmt.Errorf("invalid JSON: %w", err)
protocol := jsonConfig.Protocol
if jsonConfig.Type != "" {
if protocol != "" && protocol != jsonConfig.Type {
return nil, nil, fmt.Errorf("conflicting protocol %q and type %q: set only one", protocol, jsonConfig.Type)
}
protocol = jsonConfig.Type
}

// Auto-detect protocol
protocol := jsonConfig.Protocol
if protocol == "" {
if jsonConfig.Command != "" {
protocol = "stdio"
Expand All @@ -1984,10 +2033,16 @@ func parseAddJSONRequest(serverName, jsonStr string) (*cliclient.AddServerReques

// Validate
if jsonConfig.URL == "" && jsonConfig.Command == "" {
return nil, fmt.Errorf("JSON must contain either 'url' or 'command'")
return nil, nil, fmt.Errorf("JSON must contain either 'url' or 'command'")
}
if err := validateTrustModeFlag(jsonConfig.TrustMode); err != nil {
return nil, err
return nil, nil, err
}
if err := jsonConfig.OAuth.Validate(); err != nil {
return nil, nil, err
}
if err := jsonConfig.OAuth.ValidateRefreshReplay(); err != nil {
return nil, nil, err
}

return &cliclient.AddServerRequest{
Expand All @@ -2000,9 +2055,24 @@ func parseAddJSONRequest(serverName, jsonStr string) (*cliclient.AddServerReques
WorkingDir: jsonConfig.WorkingDir,
Protocol: protocol,
TrustMode: jsonConfig.TrustMode,
}, nil
OAuth: jsonConfig.OAuth,
}, unknown, nil
}

// addJSONUnknownKeysWarning is the stderr line for top-level keys add-json did
// not apply.
func addJSONUnknownKeysWarning(unknown []string) string {
quoted := make([]string, len(unknown))
for i, k := range unknown {
quoted[i] = strconv.Quote(k)
}
return fmt.Sprintf("warning: ignored unsupported key(s) %s: add-json accepts only %s",
strings.Join(quoted, ", "), strings.Join(addJSONKeys, ", "))
}

// addJSONKeys are the top-level keys `upstream add-json` understands.
var addJSONKeys = []string{"args", "command", "env", "headers", "oauth", "protocol", "trust_mode", "type", "url", "working_dir"}

// runUpstreamAddJSON handles the 'upstream add-json' command
func runUpstreamAddJSON(cmd *cobra.Command, args []string) error {
serverName := args[0]
Expand All @@ -2013,10 +2083,13 @@ func runUpstreamAddJSON(cmd *cobra.Command, args []string) error {
return err
}

req, err := parseAddJSONRequest(serverName, jsonStr)
req, unknown, err := parseAddJSON(serverName, jsonStr)
if err != nil {
return err
}
if len(unknown) > 0 {
fmt.Fprintln(os.Stderr, addJSONUnknownKeysWarning(unknown))
}

// Create context
ctx := reqcontext.WithMetadata(context.Background(), reqcontext.SourceCLI)
Expand Down Expand Up @@ -2445,6 +2518,7 @@ func applyImportedServersDaemonMode(ctx context.Context, client *cliclient.Clien
Headers: s.Server.Headers,
WorkingDir: s.Server.WorkingDir,
Protocol: s.Server.Protocol,
OAuth: s.Server.OAuth,
}

// Use the quarantine state from the import result (controlled by --no-quarantine flag)
Expand Down
26 changes: 26 additions & 0 deletions cmd/mcpproxy/upstream_import_effects_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,32 @@ func TestApplyImportedServersConfigModeFailureReportsNoWrites(t *testing.T) {
require.Equal(t, "sentinel", string(contents))
}

func TestApplyImportedServersDaemonModeCarriesOauth(t *testing.T) {
var gotOAuth *config.OAuthConfig
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req cliclient.AddServerRequest
_ = json.NewDecoder(r.Body).Decode(&req)
gotOAuth = req.OAuth
_, _ = w.Write([]byte(`{"success":true,"data":{}}`))
}))
defer server.Close()
client := cliclient.NewClientWithAPIKey(server.URL, "scratch-key", nil)
oauth := &config.OAuthConfig{
ClientID: "example-client",
Scopes: []string{"example-scope"},
AuthServerMetadataURL: "https://auth.example.com/.well-known/oauth-authorization-server",
}
items := []*configimport.ImportedServer{{Server: &config.ServerConfig{Name: "example", Protocol: "http", URL: "https://example.com/mcp", OAuth: oauth}}}
applied, failed, err := applyImportedServersDaemonMode(context.Background(), client, items)
require.NoError(t, err)
require.Empty(t, failed)
require.Len(t, applied, 1)
require.NotNil(t, gotOAuth)
require.Equal(t, "example-client", gotOAuth.ClientID)
require.Equal(t, []string{"example-scope"}, gotOAuth.Scopes)
require.Equal(t, "https://auth.example.com/.well-known/oauth-authorization-server", gotOAuth.AuthServerMetadataURL)
}

func TestApplyImportedServersDaemonModeContinuesAfterFailure(t *testing.T) {
var added []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand Down
16 changes: 15 additions & 1 deletion docs/cli-management-commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,11 @@ mcpproxy upstream add-json <name> '<json>'
- `headers` - HTTP headers (object)
- `env` - Environment variables (object)
- `working_dir` - Working directory (for stdio)
- `protocol` - Transport type (auto-detected if not specified)
- `protocol` - Transport type (auto-detected if not specified); `type` is accepted as an alias, so configs copied from Claude Desktop or VS Code work as-is
- `trust_mode` - Per-server trust tier: `auto`, `scan` or `manual`
- `oauth` - OAuth settings, the same block as in `mcp_config.json` (`client_id`, `client_secret`, `redirect_uri`, `scopes`, `extra_params`, …), validated before the server is added

Any other top-level key is not applied: the command prints a warning on stderr that lists those keys and the accepted ones, and still adds the server (a later release will refuse them). An unknown key inside `oauth` is refused with an error that names it.

**Examples:**
```bash
Expand All @@ -242,6 +246,16 @@ mcpproxy upstream add-json complex-server '{
"env": {"NODE_ENV": "production", "PORT": "3000"},
"working_dir": "/opt/mcp-server"
}'

# OAuth provider without Dynamic Client Registration (e.g. Home Assistant,
# where the client_id is a URL and the redirect must share its host and port)
mcpproxy upstream add-json home-assistant '{
"url": "https://ha.example.com/api/mcp",
"oauth": {
"client_id": "http://127.0.0.1:8765/",
"redirect_uri": "http://127.0.0.1:8765/oauth/callback"
}
}'
```

**Behavior:**
Expand Down
4 changes: 3 additions & 1 deletion internal/cliclient/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"time"

"github.com/smart-mcp-proxy/mcpproxy-go/internal/codescripts"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/config"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/reqcontext"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/socket"
Expand Down Expand Up @@ -1511,7 +1512,8 @@ type AddServerRequest struct {
// Empty is omitted from the wire so the daemon applies its own default; a
// non-empty value is validated CLI-side before the request is built and
// again by the REST layer (GH #938).
TrustMode string `json:"trust_mode,omitempty"`
TrustMode string `json:"trust_mode,omitempty"`
OAuth *config.OAuthConfig `json:"oauth,omitempty"`
}

// AddServerResult represents the result of adding a server.
Expand Down
Loading
Loading