diff --git a/CLAUDE.md b/CLAUDE.md index a97a24b23..b2a819fa5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -146,6 +146,7 @@ tail -f ~/Library/Logs/mcpproxy/main.log # main log (macOS; Linux: ~/.mcpproxy/ - **Windows installer**: [docs/github-actions-windows-wix-research.md](docs/github-actions-windows-wix-research.md). **Prerelease** (`next` branch + `v*-rc.*` tags, opt-in, off stable channels): [docs/prerelease-builds.md](docs/prerelease-builds.md). ## Recent Changes +- 132-client-oauth-login (PR-3): Go 1.26, Vue 3 Web UI, Swift macOS app, docs — Connect can write a client's browser sign-in address. `connect.ClientDef.SupportsBrowserLogin` is true only for `claude-code` (the one real-client check that passed; add a client only after a recorded check in `specs/132-client-oauth-login/verification/real-clients.md`). `CredentialIntent.Auth` / `ConnectOptions.Auth` = `key` (default) | `oauth`: `oauth` writes `/oauth/` with no header/credential, never calls the minter, masks nothing, is refused (`*connect.AuthChoiceError`, HTTP 400, CLI exit 1) when `mcp_oauth_enabled` is off (`Service.WithMCPOAuthEnabled`), the client is unsupported, the build is the server edition (`browserLoginEditionSupported`) or with keyless/profile/mode; `urlPointsHere` lets status, Disconnect and Undo recognise it; Connect never revokes the API key (`auth_note`). Undo of an `oauth` connect is authorised by a record beside the config (`internal/connect/undo_record.go`) plus `.undo.state` (`undo_state.go`: a created-file record counts only while the state is settled and names its generation); every config writer runs under `lockConfig` (process mutex + directory flock on Unix, `dirlock_*.go`); a config that never had an `oauth` connect gets no extra file. Payload: `supports_browser_login`, `browser_login_available` (client list/status/preview), `auth` (result, preview, status). CLI `mcpproxy connect --auth key|oauth`; Web UI choice in `ClientConnectList.vue` and macOS `ConnectClientView` only when `browser_login_available`. Docs: `docs/features/client-oauth-login.md` "Connecting a client to browser login". **No new dependencies.** - 132-client-oauth-login (PR-1): Go 1.26, backend + docs — opt-in (`mcp_oauth_enabled`, default off, env `MCPPROXY_MCP_OAUTH_ENABLED`) OAuth 2.1 authorization server so MCP clients can sign in through the browser beside API keys: public clients, PKCE S256, DCR, RFC 9728/8414 metadata, RFC 8707 `resource`; loopback peers and Hosts only; personal edition only. Addresses `/mcp/oauth` and `/mcp/oauth/` (`internal/server/oauth_login_*.go`, access token `mcp_oat_`, refresh `mcp_ort_`, replay of a rotated refresh token revokes the login), admin REST `/api/v1/oauth/authorizations/{id}/approve|deny|preview` and logins on `/clients` (`internal/httpapi/oauth_login.go`, `clients_logins.go`), runtime in `internal/runtime/oauth_login_*.go`, wire rules in `internal/mcplogin/`, lazy buckets (off and never used: nothing stored; a client registration already persists a row, approval writes only an audit activity row, the login is stored at token exchange). No consent page yet (PR-2). Gate: `scripts/test-client-oauth-e2e.sh`. Docs: `docs/features/client-oauth-login.md`. **No new dependencies.** - 125-skills-over-mcp (PR-5): Go 1.26, backend + docs — native skills extension on `/mcp/s/` only (`internal/server/skills_native.go`): with `enable_skills` on and the server not excluded the instance is built with `WithExtensions`+`WithResourceCapabilities`; an interceptor (inside `singleServerSessionGuard`, in front of the transport) answers `skills/list`, `skills/get`, `resources/read` from `ListAvailableSkills`/`AvailableSkillFile`, byte for byte (a mutating output policy withholds instead of rewriting), one `skill_access` row each (tool = method). Transport checks are reused, not copied: the request is first sent through the transport with its method replaced by `ping`, and a refusal is replayed unchanged. Endpoint lifecycle (`mcp_single_server.go`): instance, transport and generation acquired together under `singleServersMu` (`acquireSingleServerEndpoint`), retirement detaches all three and advances the generation baked into session ids (`newSingleServerSessionIDs(server, gen)`), retired GET streams end, the upstream name rides on the request (`withSingleServerEndpoint`, `singleServerNameFor(ctx, srv)`); retired from `RefreshSkillsAvailability` and lazily on acquisition. Docs: `docs/features/skills.md` "Native skills on single-server endpoints". **No new dependencies.** - 126-day-two-activation (PR-A): Go 1.26, backend + docs — telemetry schema 17, instrumentation only (no onboarding, UI or API change). Install anchor: `storage.EnsureInstallAnchor` (own bucket `install_anchor`, written once in `runtime.New` after the Spec 080 shutdown marker and Spec 123 OAuth boot sweep, before any other startup write, only when `config.db` held no record other than `meta/schema_version` at open, `BoltDB.WasEmptyAtOpen`; never from onboarding writes; recorded with telemetry off; read once per process for both `day_two` and `window_age`). `upstream_outcomes {succeeded, unusable, succeeded_non_starter, coverage, window_age}` (`internal/telemetry/upstream_outcomes.go`): one outcome per LOGICAL call that dispatched (dispatch counts requests), begun right after `noteUpstreamDispatched` and deferred (`upstreamOutcome` in `internal/server/mcp_upstream_telemetry.go`) on the wrapper, direct routing and `code_execution` sub-calls, guarded by an AST test; part of the drained window (retries byte-identical); `coverage` from the persisted `outcome_window_undelivered` marker (`outcome_window.go`: set by the first outcome after start or a Drain, cleared after a 2xx only if nothing was counted since that drain, both under the outcome window's own mutex, never `deliveryMu`), `window_age` = install age when the window opened (start or Drain), `install_origin: fresh` personal only. `day_two {install_origin, install_age, success_scope_ever}` personal only (`day_two.go`: UTC calendar-date buckets; `success_scope.go` forward-only ordinal in the activation bucket). `runtime.StarterClassifier` (default false, `SetStarterClassifier` for PR-B) + `Runtime.RecordUpstreamOutcome`. `ScanForPII` closed-object rule `day_two_field_invalid`. Docs: `docs/features/telemetry.md` "Schema v17". **No new dependencies.** diff --git a/cmd/mcpproxy/connect_auth_flag_test.go b/cmd/mcpproxy/connect_auth_flag_test.go new file mode 100644 index 000000000..9ad834bb4 --- /dev/null +++ b/cmd/mcpproxy/connect_auth_flag_test.go @@ -0,0 +1,161 @@ +//go:build !server + +package main + +import ( + "encoding/json" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/require" + + clioutput "github.com/smart-mcp-proxy/mcpproxy-go/internal/cli/output" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/connect" +) + +// Spec 132 PR-3: `mcpproxy connect --auth key|oauth`. + +func seedClaudeCode(t *testing.T, home string) string { + t.Helper() + path := filepath.Join(home, ".claude.json") + require.NoError(t, os.WriteFile(path, []byte("{}\n"), 0o644)) + return path +} + +// connectAuthEnv is connectTestEnv with browser login switched on or off in the +// CLI's config file. +func connectAuthEnv(t *testing.T, oauthOn bool) (home string) { + t.Helper() + home, cfg := connectTestEnv(t, true) + cfg.MCPOAuthEnabled = oauthOn + require.NoError(t, config.SaveConfig(cfg, configFile)) + return home +} + +func TestConnectAuthFlag_HelpJSONListsIt(t *testing.T) { + if os.Getenv("MCPPROXY_CONNECT_AUTH_HELP_JSON_HELPER") == "1" { + root := &cobra.Command{Use: "mcpproxy"} + root.AddCommand(GetConnectCommand()) + clioutput.SetupHelpJSON(root) + root.SetArgs([]string{"connect", "--help-json"}) + require.NoError(t, root.Execute()) + return + } + cmd := exec.Command(os.Args[0], "-test.run=^TestConnectAuthFlag_HelpJSONListsIt$") + cmd.Env = append(os.Environ(), "MCPPROXY_CONNECT_AUTH_HELP_JSON_HELPER=1") + out, err := cmd.CombinedOutput() + require.NoError(t, err, string(out)) + var payload struct { + Flags []struct { + Name string `json:"name"` + Default string `json:"default"` + } `json:"flags"` + } + require.NoError(t, json.Unmarshal(out, &payload), string(out)) + found := false + for _, f := range payload.Flags { + if f.Name == "auth" { + found = true + require.Equal(t, "key", f.Default) + } + } + require.True(t, found, "--help-json must list --auth: %s", out) +} + +func TestConnectAuthFlag_OAuthWritesOnlyTheAddress(t *testing.T) { + home := connectAuthEnv(t, true) + path := seedClaudeCode(t, home) + + out, err := runConnectArgs(t, "claude-code", "--auth", "oauth") + require.NoError(t, err, out) + + raw, err := os.ReadFile(path) + require.NoError(t, err) + body := string(raw) + require.Contains(t, body, "/mcp/oauth/claude-code") + for _, bad := range []string{"headers", "X-API-Key", "mcp_cli_", "mcp_oat_", "cli-test-admin-key"} { + require.NotContains(t, body, bad) + } + require.NotContains(t, out, "Credential:", "no credential line for a browser login") + require.Contains(t, out, "Sign-in: browser") + require.Contains(t, out, "does not revoke") + require.Contains(t, out, "Next: ") +} + +func TestConnectAuthFlag_KeyIsTheDefault(t *testing.T) { + home := connectAuthEnv(t, true) + path := seedClaudeCode(t, home) + out, err := runConnectArgs(t, "claude-code", "--auth", "key") + require.NoError(t, err, out) + require.Contains(t, out, "Credential: mcp_cli_••••") + require.NotContains(t, out, "Sign-in:") + raw, _ := os.ReadFile(path) + require.NotContains(t, string(raw), "/mcp/oauth") +} + +func TestConnectAuthFlag_Refusals(t *testing.T) { + t.Run("feature off", func(t *testing.T) { + home := connectAuthEnv(t, false) + path := seedClaudeCode(t, home) + out, err := runConnectArgs(t, "claude-code", "--auth", "oauth") + require.Error(t, err, out) + require.Contains(t, err.Error(), "mcp_oauth_enabled") + require.Equal(t, ExitCodeGeneralError, classifyError(err)) + raw, _ := os.ReadFile(path) + require.Equal(t, "{}\n", string(raw)) + }) + t.Run("unsupported client", func(t *testing.T) { + home := connectAuthEnv(t, true) + path := seedCursor(t, home) + out, err := runConnectArgs(t, "cursor", "--auth", "oauth") + require.Error(t, err, out) + require.Contains(t, err.Error(), "does not support browser login") + require.Equal(t, ExitCodeGeneralError, classifyError(err)) + raw, _ := os.ReadFile(path) + require.Equal(t, "{}\n", string(raw)) + }) + t.Run("unknown value", func(t *testing.T) { + connectAuthEnv(t, true) + _, err := runConnectArgs(t, "claude-code", "--auth", "magic") + require.Error(t, err) + require.Contains(t, err.Error(), "--auth must be key or oauth") + require.Equal(t, ExitCodeGeneralError, classifyError(err)) + }) + t.Run("combined with a binding", func(t *testing.T) { + connectAuthEnv(t, true) + for _, extra := range [][]string{{"--keyless"}, {"--profile", "ro"}, {"--lock", "--profile", "ro"}, {"--switchable"}} { + _, err := runConnectArgs(t, append([]string{"claude-code", "--auth", "oauth"}, extra...)...) + require.Error(t, err, strings.Join(extra, " ")) + require.Contains(t, err.Error(), "--auth oauth cannot be combined") + } + }) +} + +// A daemon refusal (HTTP 400) of an oauth write exits 1 and prints its text. +func TestConnectAuthFlag_DaemonSendsAuthAndPrintsRefusal(t *testing.T) { + connectAuthEnv(t, true) + var body map[string]any + fakeConnectDaemon(t, 400, `{"success":false,"error":"browser login is off: set mcp_oauth_enabled to true first"}`, &body) + _, err := runConnectArgs(t, "cursor", "--auth", "oauth") + require.Error(t, err) + require.Equal(t, "oauth", body["auth"]) + require.Contains(t, err.Error(), "mcp_oauth_enabled") + require.Equal(t, ExitCodeGeneralError, classifyError(err)) + + // The default sends no auth at all. + body = nil + fakeConnectDaemon(t, 200, `{"success":true,"data":{"success":true,"client":"cursor","action":"created","message":"ok","credential":"mcp_cli_••••","token_name":"client-cursor","mode":"switchable"}}`, &body) + _, err = runConnectArgs(t, "cursor") + require.NoError(t, err) + require.NotContains(t, body, "auth") +} + +func TestConnectAuthLine(t *testing.T) { + require.Equal(t, "", connectAuthLine(&connect.ConnectResult{})) + require.Contains(t, connectAuthLine(&connect.ConnectResult{Auth: "oauth"}), "Sign-in: browser") +} diff --git a/cmd/mcpproxy/connect_auth_reconcile_test.go b/cmd/mcpproxy/connect_auth_reconcile_test.go new file mode 100644 index 000000000..cf76fd736 --- /dev/null +++ b/cmd/mcpproxy/connect_auth_reconcile_test.go @@ -0,0 +1,43 @@ +//go:build !server + +package main + +import ( + "os" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/connect" +) + +// A browser-login connect, refused or not, never finalises a staged key +// rotation in the offline path either. +func TestConnectAuthFlag_OfflineOAuthDoesNotReconcileAKeyRotation(t *testing.T) { + for _, featureOn := range []bool{false, true} { + home := connectAuthEnv(t, featureOn) + path := seedClaudeCode(t, home) + cfg, err := loadConnectConfig() + require.NoError(t, err) + backend, err := newOfflineConnectBackend(cfg) + require.NoError(t, err) + + first, err := backend.connect("claude-code", "", false, connect.CredentialIntent{}) + require.NoError(t, err) + require.True(t, first.Success) + m := backend.clients.ConnectMinter() + issued, err := m.Issue("claude-code", connect.CredentialIntent{}) + require.NoError(t, err) + m.Release("claude-code", issued) + require.NoError(t, os.WriteFile(path, []byte(`{"mcpServers":{"mcpproxy":{"type":"http","url":"http://127.0.0.1:1/mcp","headers":{"X-API-Key":"`+issued.Secret+`"}}}}`), 0o644)) + view, err := backend.clients.Get("claude-code") + require.NoError(t, err) + require.True(t, view.RotationPending) + + _, _ = backend.connect("claude-code", "", true, connect.CredentialIntent{Auth: connect.AuthOAuth}) + view, err = backend.clients.Get("claude-code") + require.NoError(t, err) + require.True(t, view.RotationPending, "featureOn=%v: the staged rotation must survive an oauth connect", featureOn) + backend.close() + } +} diff --git a/cmd/mcpproxy/connect_cmd.go b/cmd/mcpproxy/connect_cmd.go index ebba86eb1..43145ae2a 100644 --- a/cmd/mcpproxy/connect_cmd.go +++ b/cmd/mcpproxy/connect_cmd.go @@ -39,11 +39,20 @@ existing binding unless you pass --profile. With require_mcp_auth off, a named binding is refused unless an anonymous caller could not reach more than the client (the refusal lists the fixes); --keyless writes no credential. +--auth oauth (Spec 132, experimental) writes only the client's browser sign-in +address, /oauth/, with no header and no credential; the +client signs in through the browser and you approve it on the consent page. +It is refused while mcp_oauth_enabled is off, for a client that has not passed a +real-client check (today only claude-code), in the server edition, and together +with --profile, --lock, --switchable or --keyless. Connect never revokes the +client's existing API key. To switch an existing entry, add --force. + Examples: mcpproxy connect --list # Show all clients and their status mcpproxy connect claude-code # Register in Claude Code mcpproxy connect cursor --profile ro # Bind Cursor to profile "ro" (locked) mcpproxy connect cursor --profile work --switchable + mcpproxy connect claude-code --auth oauth # Browser sign-in address only, no credential (needs mcp_oauth_enabled) mcpproxy connect cursor --force # Overwrite existing entry mcpproxy connect codex --name my-proxy # Custom server name mcpproxy connect opencode # Register in OpenCode @@ -94,7 +103,9 @@ func runConnect(cmd *cobra.Command, args []string) error { return fmt.Errorf("failed to load config: %w", err) } - svc := connect.NewService(cfg.Listen, cfg.APIKey).WithRequireMCPAuth(cfg.RequireMCPAuth) + svc := connect.NewService(cfg.Listen, cfg.APIKey).WithRequireMCPAuth(cfg.RequireMCPAuth). + WithMCPOAuthEnabled(func() bool { return cfg.MCPOAuthEnabled }). + WithTLSEnabled(func() bool { return cfg.TLS != nil && cfg.TLS.Enabled }) format := clioutput.ResolveFormat(globalOutputFormat, globalJSONOutput) formatter, err := clioutput.NewFormatter(format) @@ -344,9 +355,18 @@ func printConnectResult(result *connect.ConnectResult, formatter clioutput.Outpu if line := connectCredentialLine(result); line != "" { fmt.Println(line) } + if line := connectAuthLine(result); line != "" { + fmt.Println(line) + if result.AuthNote != "" { + fmt.Printf("Note: %s\n", result.AuthNote) + } + } if line := disconnectCredentialLine(result); line != "" { fmt.Println(line) } + if result.CleanupError != "" { + fmt.Printf("Cleanup: the entry was removed but its undo records could not be removed (%s)\n", result.CleanupError) + } // FR-037: Config shows the home-shortened display_path; the full // path is still available via -o json's config_path. fmt.Printf("Config: %s\n", connectResultDisplayPath(result)) diff --git a/cmd/mcpproxy/connect_credential.go b/cmd/mcpproxy/connect_credential.go index 2b74da31e..c184ec2f4 100644 --- a/cmd/mcpproxy/connect_credential.go +++ b/cmd/mcpproxy/connect_credential.go @@ -33,6 +33,7 @@ var ( connectLock bool connectSwitchable bool connectKeyless bool + connectAuth = connect.AuthKey ) func addConnectCredentialFlags(cmd *cobra.Command) { @@ -42,6 +43,9 @@ func addConnectCredentialFlags(cmd *cobra.Command) { cmd.Flags().BoolVar(&connectLock, "lock", false, "Lock the client to its profile: it can never switch (default for a named profile)") cmd.Flags().BoolVar(&connectSwitchable, "switchable", false, "Let the client switch profiles within its profile's switchable_to (default for all servers)") cmd.Flags().BoolVar(&connectKeyless, "keyless", false, "Write an entry with no credential (only while require_mcp_auth is off; the client is unidentified)") + cmd.Flags().StringVar(&connectAuth, "auth", connect.AuthKey, + `How the client signs in: "key" writes an API-key entry, "oauth" writes only the client's browser sign-in address `+ + `(no credential; needs mcp_oauth_enabled and a client that supports it, currently claude-code)`) cmd.MarkFlagsMutuallyExclusive("lock", "switchable") } @@ -49,6 +53,16 @@ func addConnectCredentialFlags(cmd *cobra.Command) { // the combinations that cannot work before anything is read or written. func connectIntentFromFlags(cmd *cobra.Command) (connect.CredentialIntent, error) { intent := connect.CredentialIntent{Keyless: connectKeyless, Surface: string(profile.SurfaceCLI)} + switch connectAuth { + case connect.AuthKey: + case connect.AuthOAuth: + if connectKeyless || connectLock || connectSwitchable || cmd.Flags().Changed("profile") { + return intent, newFlagValidationError("--auth oauth cannot be combined with --profile, --lock, --switchable or --keyless: the access is chosen on the consent page") + } + intent.Auth = connect.AuthOAuth + default: + return intent, newFlagValidationError("--auth must be key or oauth, got %q", connectAuth) + } profileGiven := cmd.Flags().Changed("profile") if profileGiven { p := connectProfile @@ -108,11 +122,13 @@ type connectRequestBody struct { Profile *string `json:"profile,omitempty"` Mode *string `json:"mode,omitempty"` Keyless bool `json:"keyless,omitempty"` + Auth string `json:"auth,omitempty"` } func (d *daemonConnectBackend) connect(clientID, serverName string, force bool, intent connect.CredentialIntent) (*connect.ConnectResult, error) { body, err := json.Marshal(connectRequestBody{ ServerName: serverName, Force: force, Profile: intent.Profile, Mode: intent.Mode, Keyless: intent.Keyless, + Auth: intent.Auth, }) if err != nil { return nil, err @@ -128,7 +144,14 @@ func (d *daemonConnectBackend) connect(clientID, serverName string, force bool, if err != nil { return nil, err } - return parseConnectResponse(resp.StatusCode, raw, clientID) + res, perr := parseConnectResponse(resp.StatusCode, raw, clientID) + if perr != nil && intent.Auth == connect.AuthOAuth && resp.StatusCode == http.StatusBadRequest { + // A refused auth choice is the caller's input, not a config error: its + // text mentions the config switch, which the exit-code heuristics + // would otherwise read as a config-file failure. + return nil, flagValidationError{perr} + } + return res, perr } // disconnect asks the daemon to remove the entry; the daemon also revokes the @@ -243,6 +266,8 @@ func newOfflineConnectBackend(cfg *config.Config) (*offlineConnectBackend, error }) svc := connect.NewService(cfg.Listen, cfg.APIKey). WithRequireMCPAuth(config.EffectiveRequireMCPAuth(cfg)). + WithMCPOAuthEnabled(func() bool { return cfg.MCPOAuthEnabled }). + WithTLSEnabled(func() bool { return cfg.TLS != nil && cfg.TLS.Enabled }). WithCredentialMinter(clients.ConnectMinter()) clients.SetConfigReader(svc) return &offlineConnectBackend{sm: sm, svc: svc, clients: clients}, nil @@ -255,7 +280,11 @@ func (o *offlineConnectBackend) connect(clientID, serverName string, force bool, // secret may already be in the client config) before staging another one, // which would silently replace it. Best effort: an unreadable config keeps // both secrets, exactly as the daemon's reconciler does. - _ = o.clients.ReconcileClient(context.Background(), clientID) + // A browser-login connect never touches the client's API key, so it skips + // the reconcile (and a refused one has not even been allowed to start one). + if oauth, authErr := o.svc.CheckAuth(clientID, intent); authErr == nil && !oauth { + _ = o.clients.ReconcileClient(context.Background(), clientID) + } return o.svc.ConnectWithOptions(clientID, serverName, connect.ConnectOptions{Force: force, Intent: intent}) } @@ -305,10 +334,13 @@ func describeConnectFailure(err error, clientID string) error { var guardErr *runtime.BindingGuardError var conflict *connectConflictError var val *runtime.ValidationError + var authChoice *connect.AuthChoiceError var busy *runtime.ConnectInProgressError var superseded *runtime.CredentialSupersededError var b strings.Builder switch { + case errors.As(err, &authChoice): + b.WriteString(authChoice.Error()) case errors.As(err, &busy): b.WriteString(busy.Error()) case errors.As(err, &superseded): @@ -346,6 +378,16 @@ func guardFixText(fix runtime.GuardFix, guardErr *runtime.BindingGuardError) str return guardFixLine(fix, name) } +// connectAuthLine is the line a browser-login connect prints in place of the +// credential line: the config holds only the sign-in address. Empty for an +// API-key entry. +func connectAuthLine(r *connect.ConnectResult) string { + if r.Auth != connect.AuthOAuth { + return "" + } + return "Sign-in: browser (the config holds only the address; no credential was written)" +} + // connectCredentialLine is the credential line of a successful connect: // // Credential: mcp_cli_•••• (token client-cursor, profile ro, locked) diff --git a/docs/api/rest-api.md b/docs/api/rest-api.md index c93413b7e..c3578e3d9 100644 --- a/docs/api/rest-api.md +++ b/docs/api/rest-api.md @@ -1379,6 +1379,15 @@ profile; `409 binding_bypassable_without_auth` (`bindings`, `fixes`) when the binding would be bypassable while `require_mcp_auth` is off; `409` with `conflicting_token` when `client-` is held by a regular agent token. +**Browser login (Spec 132).** The body also accepts `auth`: `"key"` (default) or +`"oauth"`. `"oauth"` writes only the client's sign-in address +(`http://127.0.0.1:8080/mcp/oauth/`), no header and no credential, and never calls the +credential store; the result carries `auth: "oauth"` and an `auth_note` saying the client's +existing API key is not revoked. Refused with `400` and nothing written while `mcp_oauth_enabled` +is off, for a client without `supports_browser_login`, in the server edition, with an unknown +value, and together with `keyless`, `profile` or `mode`. See +[Browser Login for MCP Clients](../features/client-oauth-login.md#connecting-a-client-to-browser-login). + #### PUT /api/v1/clients/{client}/binding Reassigns a client's profile and/or mode (personal edition, administrator @@ -1411,6 +1420,13 @@ so on macOS this may raise an App-Data prompt; a denial returns `403` + remediation. Optional `?server_name=` mirrors the name a subsequent connect would use. +`?auth=oauth` previews the browser-login entry (Spec 132): `auth: "oauth"`, no `credential`, +`auth_note`, and `browser_login_available`; the same refusals as the write answer `400`. The +`precondition_token` binds the choice. `GET /api/v1/connect` and `GET /api/v1/connect/{client}` +carry `supports_browser_login` and `browser_login_available` (the client passed a real-client +check and the feature is available: on, personal edition, loopback or wildcard listener); the per-client read adds +`auth: "oauth"` when the entry holds the sign-in address. All three are omitted when false. + Spec 091 adds three response fields: | Field | Type | Meaning | @@ -1446,8 +1462,44 @@ component and cannot escape the config dir (defense against path injection). Safety semantics: - Undo **refuses with `409 Conflict`** when the config changed since the - connect (it verifies the current file is byte-identical to what that connect - wrote) — it never clobbers later edits. Fall back to + connect (a browser-login connect records the SHA-256 of the file it wrote in a + small sidecar `.undo.`, or `.undo.new.` when + it created the file, beside the backup. Two browser-login connects that race + to create the same file each keep their own record and the file is untouched + if it matches either, never otherwise: connect takes no lock across read, + backup and write, so a racing pair is resolved fail-closed, not serialised; the file counts as untouched only if its + digest still equals it, and the sidecar is removed when the undo succeeds or + the entry is disconnected) — it never clobbers later edits. A record that is + malformed, unreadable or bound to another client, entry or backup is also a + conflict. A browser-login connect stages its record, marks the config's undo state + pending, writes the config, then commits a new generation, publishes the record + and retires the older records of that entry. The state lives in + `.undo.state` (`current` generation id, `pending` flag); a created-file + record authorises an Undo only while the state is readable, not pending and + names the generation the record carries (and is strictly well formed), so a + record that outlives its retirement, or a crash mid-write, can never authorise + a replaced file (Undo answers conflict). Every writer of one config (connect, + disconnect and undo; each OpenCode candidate file under its own lock) holds a + process-wide mutex keyed by the symlink-resolved path and, on Unix, an + exclusive advisory lock on the config's directory (no file is created; a + writer waits at most about 10 seconds and then fails with nothing written), so + no two writers interleave their state steps. On Windows only the in-process + mutex applies. A pending state carries its writer's owner token as defence in + depth: a commit or rollback that finds another owner changes nothing (a writer + that already wrote the config then leaves the state pending), and a pending + state found at the start of a write is a crashed writer's and is taken over. + The state is parsed strictly (exact fields and types, a single JSON value). The + state and record files are fsynced before their rename and the directory after + it. A failure before the write restores the previous state + exactly. An API-key connect, a disconnect or an undo moves the state along only + if the file already exists; an install that never used browser login gets no + new file. A problem after a successful write is reported as `cleanup_error`; a + post-write verification error names the backup and the record note. A connect that cannot list the config's directory (a browser-login connect refuses before writing + anything; an API-key connect proceeds as before) or an Undo that cannot (it answers conflict) + fails closed; a disconnect reports `cleanup_error` and still succeeds. A backup name that + already has another entry's or client's record is skipped, like a name that exists. + An API-key connect writes no sidecar and, like a backup that has + none, is checked by replaying the key-path write, exactly as before. Fall back to `DELETE /connect/{client}` for a surgical entry removal. - A vanished backup returns `404`; a `backup_name` that is a path (contains a directory separator) or does not match `.bak.*` for that client diff --git a/docs/cli-management-commands.md b/docs/cli-management-commands.md index aecc96fd7..36819ebd4 100644 --- a/docs/cli-management-commands.md +++ b/docs/cli-management-commands.md @@ -531,6 +531,13 @@ credential is valid on MCP endpoints only, so it cannot open the REST API. - `--keyless` - write an entry with no credential; only possible while `require_mcp_auth` is off, and the client is then unidentified. It cannot be combined with `--profile`, `--lock` or `--switchable` +- `--auth key|oauth` - how the client signs in (default `key`). `oauth` writes + only the client's browser sign-in address (`/oauth/`), + no header and no credential; it needs `mcp_oauth_enabled` and a client that + passed a real-client check (today `claude-code`), is refused in the server + edition and together with `--profile`, `--lock`, `--switchable` or + `--keyless`, and never revokes the client's existing API key. See + [Browser Login for MCP Clients](features/client-oauth-login.md#connecting-a-client-to-browser-login) - `--force` - overwrite an existing entry; `--name` - server name in the client config; `--all` - connect every supported client with the same options (a refusal for one client is reported and never aborts the others) diff --git a/docs/cli/profile-commands.md b/docs/cli/profile-commands.md index 4f1de7a5f..e89a041a9 100644 --- a/docs/cli/profile-commands.md +++ b/docs/cli/profile-commands.md @@ -38,6 +38,7 @@ Registers MCPProxy in an AI client's MCP configuration. Connect **never writes t | `--profile ` | The profile the client's credential binds to; `all` is the built-in All servers scope. A new credential defaults to `all` (switchable); a reconnect keeps the client's existing binding unless `--profile` is given | | `--lock` / `--switchable` | Lock the client to its profile so it can never switch (the default for a named profile), or let it switch within the profile's `switchable_to` (the default for `all`) | | `--keyless` | Write an entry with no credential. Only possible while `require_mcp_auth` is off, and the client is then unidentified. Cannot be combined with `--profile`, `--lock` or `--switchable` | +| `--auth key\|oauth` | How the client signs in. `key` (the default) writes an API-key entry as above. `oauth` ([browser login](../features/client-oauth-login.md#connecting-a-client-to-browser-login), experimental) writes only the client's sign-in address `/oauth/` with no header and no credential. Refused (exit 1, nothing written) while `mcp_oauth_enabled` is off, for a client that has not passed a real-client check (today only `claude-code`), in the server edition, and together with `--profile`, `--lock`, `--switchable` or `--keyless`. Switching an existing entry needs `--force`. Connect never revokes the client's existing API key | | `--force`, `--name`, `--all` | Overwrite an existing entry; the server name in the client config; connect every supported client with the same options (a refusal for one client never aborts the others) | The credential is shown masked; the secret is written only into the client's config file. Reconnecting over an active credential is a **staged rotation**: the old secret keeps working until the new config has been written. diff --git a/docs/features/client-oauth-login.md b/docs/features/client-oauth-login.md index 2efd54966..5549825f5 100644 --- a/docs/features/client-oauth-login.md +++ b/docs/features/client-oauth-login.md @@ -3,7 +3,7 @@ id: client-oauth-login title: Browser Login for MCP Clients sidebar_label: Browser Login for MCP Clients sidebar_position: 7 -description: Let MCP clients sign in to MCPProxy through the browser (OAuth 2.1 with PKCE) next to API keys. Opt-in, loopback only, personal edition. Backend and admin REST only in this release. +description: Let MCP clients sign in to MCPProxy through the browser (OAuth 2.1 with PKCE) next to API keys. Opt-in, loopback only, personal edition. Connect can write the sign-in address for clients that passed a real-client check (Claude Code so far). keywords: [oauth, browser login, mcp client, pkce, dynamic client registration, rfc 9728, rfc 8414, rfc 8707, cursor, claude code, vscode] --- @@ -180,6 +180,74 @@ consent page can approve one. See [credential lifecycle over MCP](./mcp-credenti with `DELETE /api/v1/clients//logins/`; the next request on that login, including on an open session, is refused. Forgetting a client removes all its logins. +## Connecting a client to browser login + +Connect can write the sign-in address instead of an API key. The client is given only +`http://127.0.0.1:8080/mcp/oauth/`; there is no header, no bridge argument and no +credential in its config file, and the client credential store is not touched. + +```bash +mcpproxy connect claude-code --auth oauth # key is the default: --auth key +mcpproxy connect claude-code --auth oauth --force # switch an entry that is already there +``` + +In the Web UI and the macOS app, the Connect form shows **API key** (selected) or **Sign in +with browser** after the diff and the backup notice, and before the Connect button. It is +shown only while browser login is on and only for a client in the table below; while the +switch is off the form is the one it always was. Choosing the browser shows the exact entry +that will be written and the note below, and hides the profile and keyless controls: the +access is chosen on the consent page. + +What Connect does with `--auth oauth` (REST `auth: "oauth"`, preview `?auth=oauth`): + +- It is **refused**, with nothing written, while `mcp_oauth_enabled` is off, for a client that + is not in the table, in the server edition, when the core listens on a specific non-loopback + address (browser login is loopback only), and together with `--profile`, `--lock`, + `--switchable` or `--keyless`. +- The address follows the listener: `https://` when `tls.enabled` is on, and `127.0.0.1` when the + core listens on a wildcard (`0.0.0.0`, `[::]`, `:8080`). What the API-key path writes is unchanged. +- The preview and the result carry `auth: "oauth"`, no credential and no masked value. The + preview token binds the choice, so a key write cannot ride an oauth preview. +- **Reconnecting replaces the one entry, it never adds a second.** Key to browser and + browser to key both need `--force` (the Web UI and the app do this when you confirm the + replace). +- **Connect never revokes an API key.** After switching to the browser the client's existing + key keeps working until you revoke it (Revoke API key on the Clients page). The preview and + the result say so. `mcpproxy disconnect ` removes the entry and revokes the client's + API key as before; it does not revoke browser logins (use the Clients page or + `mcpproxy client revoke-login `). +- Disconnect, Undo and the status read recognise an entry written this way. Undo of an oauth + connect restores the earlier config and revokes nothing, since the connect minted nothing. + Undo of a browser-login connect trusts a digest of the file recorded in a sidecar beside the backup + (`.undo.`, removed on a successful Undo or Disconnect), so any edit of the + address, in either direction, is a conflict. A record of a file Connect created is valid only for + the generation named in `.undo.state`, which every later write of that config moves on, + so a stale record never authorises an Undo (it fails closed instead). An API-key connect writes no sidecar and is undone + exactly as before. +- `GET /api/v1/connect` and `GET /api/v1/connect/{client}` report `supports_browser_login` and + `browser_login_available` (the client is in the table **and** the feature is on, this is the + personal edition and the listener is loopback or a wildcard). Both fields are absent otherwise, + so with the feature off the payloads are exactly what they were. A status read of a client whose entry holds the address + reports `auth: "oauth"`. + +### Clients checked so far + +A client is marked as supporting browser login only after a recorded check with the real +client (`specs/132-client-oauth-login/verification/real-clients.md`). Passing the MCP SDK is +not enough. + +| Client | Offered by Connect | What was verified | +|---|---|---| +| Claude Code | **yes** (`claude-code`) | Claude Code CLI 2.1.318 on macOS completed the login flow over plain HTTP loopback: it accepted the `http://127.0.0.1` issuer, registered itself, sent the authorize request for the per-client address (`resource` equal to it), and after approval reported "Connected" and made MCP calls with the token. **Not** verified: token refresh, the order of the metadata requests, the browser-and-callback path (the check pasted the redirect URL at the CLI prompt), tool calls inside an interactive session, the generic `/mcp/oauth` address, Windows and Linux | +| Cursor | no | not verified (needs its real config and a GUI) | +| VS Code, GitHub Copilot | no | not verified (needs its real settings and a GUI) | +| MCP Inspector | not a Connect client | not verified (needs a TTY and a browser) | +| MCP TypeScript SDK 1.32.2 | not a Connect client | login, refresh and tool calls verified with a script | +| Every other Connect client | no | not checked | + +Until a client is checked, use its API key. A client can still be pointed at an address by +hand; Connect just does not offer it. + ## Turning it off Set `mcp_oauth_enabled` back to `false` (or the variable to `false`). After the feature has @@ -200,4 +268,4 @@ The issuer is `http://127.0.0.1:`, not HTTPS. The specifications ask for H non-loopback issuers; loopback HTTP is the common local-tool case. Client behaviour is checked in `specs/132-client-oauth-login/verification/real-clients.md`; the MCP TypeScript SDK client flow and the Claude Code CLI login flow are verified so far (Cursor, VS -Code and MCP Inspector are not). +Code and MCP Inspector are not; see [Clients checked so far](#clients-checked-so-far)). diff --git a/docs/features/connect-clients.md b/docs/features/connect-clients.md index 8d8158c62..b10cb1135 100644 --- a/docs/features/connect-clients.md +++ b/docs/features/connect-clients.md @@ -132,6 +132,7 @@ touched and its live sessions are notified. |----|-----------------|-----| | Connect a client to a profile | Connect sheet: choose a profile and Locked or Switchable | `mcpproxy connect cursor --profile work-readonly --lock` | | Connect without a credential (only while `require_mcp_auth` is off) | "Keyless" in the advanced options | `mcpproxy connect cursor --keyless` | +| Connect with a browser sign-in instead of a key (experimental; Claude Code only so far) | Connect sheet: "Sign in with browser", shown only while browser login is on | `mcpproxy connect claude-code --auth oauth`; see [Browser Login](./client-oauth-login.md#connecting-a-client-to-browser-login) | | Move a client to another profile, or lock it | The profile chip on the client's row, the lock switch; the macOS tray Clients submenu | `mcpproxy client set-profile cursor work-full`, `client lock`, `client unlock` | | Move every client of one profile to another | Bulk move on the Clients page | `mcpproxy client set-profile --from-profile X --to-profile Y` | | Add a client that has no config file (a script, a CI job) | "Other client": the credential and a header snippet are shown once | `mcpproxy client add ci-bot --profile work-readonly` | diff --git a/frontend/src/components/ClientConnectList.vue b/frontend/src/components/ClientConnectList.vue index 2b2fecea8..3fd56e390 100644 --- a/frontend/src/components/ClientConnectList.vue +++ b/frontend/src/components/ClientConnectList.vue @@ -216,10 +216,46 @@ class="text-[11px] font-mono whitespace-pre-wrap break-all rounded bg-base-300/60 border-l-2 border-success px-2 py-1.5 leading-relaxed" >{{ previews[client.id]!.entry_text }} + +
+ How {{ client.name }} signs in + + +
+
+

+ No credential is written. {{ client.name }} gets only the sign-in address; the first time it connects, your browser opens a page where you approve it. +

+

{{ previews[client.id]!.auth_note }}

+
-
+

MCPProxy writes a client credential for {{ client.name }}. The admin API key is never written.

@@ -264,7 +300,7 @@ >{{ MGMT_NOTICE }}

-
+
Advanced