From 2306fb8615d3abe686b33b21b42c013a43262913 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 18:34:47 +0200 Subject: [PATCH 01/42] feat(oauth): opt-in switch and default-off gate for browser login (Spec 132 PR-1a) Related #1971 --- docs/configuration/config-file.md | 1 + internal/config/config.go | 10 + internal/config/loader.go | 16 ++ internal/config/mcp_oauth_test.go | 50 ++++ internal/config/process_overrides.go | 1 + internal/mcplogin/doc.go | 7 + internal/runtime/config_hotreload.go | 2 +- .../server/oauth_login_default_off_test.go | 241 ++++++++++++++++++ internal/server/oauth_login_routes.go | 108 ++++++++ internal/server/oauth_login_routes_test.go | 34 +++ .../server/oauth_login_server_edition_test.go | 30 +++ internal/server/server.go | 9 +- oas/docs.go | 2 +- oas/swagger.yaml | 7 + 14 files changed, 515 insertions(+), 3 deletions(-) create mode 100644 internal/config/mcp_oauth_test.go create mode 100644 internal/mcplogin/doc.go create mode 100644 internal/server/oauth_login_default_off_test.go create mode 100644 internal/server/oauth_login_routes.go create mode 100644 internal/server/oauth_login_routes_test.go create mode 100644 internal/server/oauth_login_server_edition_test.go diff --git a/docs/configuration/config-file.md b/docs/configuration/config-file.md index 3335879f3..9c981104d 100644 --- a/docs/configuration/config-file.md +++ b/docs/configuration/config-file.md @@ -64,6 +64,7 @@ MCPProxy uses a JSON configuration file located at `~/.mcpproxy/mcp_config.json` | `trusted_proxies` | string[] | `[]` (trust nobody) | CIDRs or IP addresses whose `X-Forwarded-For`, `X-Real-IP`, `X-Forwarded-Proto` and `X-Forwarded-Host` headers are believed. Headers from any other peer are ignored and the direct `RemoteAddr` is used. Env `MCPPROXY_TRUSTED_PROXIES` (comma list). Live (hot-reload, no restart). Validation: `trusted_proxies[N] "value" is not a valid CIDR or IP address` — refused identically at boot, `PATCH /api/v1/config` and `/config/apply`. See [Reverse Proxy Deployment](/operations/reverse-proxy#trusted_proxies-forwarded-headers) | | `require_mcp_auth` | boolean | `false` | Require an API key on the `/mcp` endpoint (off by default for client compatibility). Enable when exposing MCPProxy beyond localhost. **Server edition:** forced to `true` whenever `server_edition.enabled` is `true` — an explicit `false` is not an error, but boot logs `require_mcp_auth: false is overridden to true because server_edition.enabled is true` and `mcpproxy doctor` reports the same finding | | `mcp_reject_query_apikey` | boolean | `false` | Refuse a `?apikey=` query parameter on every MCP endpoint (`/mcp*` and the legacy `/v1/tool_code` aliases) with a 401, forcing clients onto `Authorization: Bearer ` or `X-API-Key` so tokens stop appearing in access logs, proxy logs and browser history (a URL already sent is still logged in transit; the option makes the client fail until it is migrated). MCP endpoints only: the REST API, the Web UI and `/events` keep accepting the query form. Entries written by an older Connect wizard with `?apikey=` in the URL (Codex, the generic fallback) must be reconnected first; current versions write an `X-API-Key` header. Live, no restart | +| `mcp_oauth_enabled` | boolean | `false` | Experimental. Opt-in browser login (OAuth 2.1 + PKCE) for MCP clients, served only to loopback peers and loopback `Host` values, personal edition only. With it off nothing changes: no new route behaves differently and nothing is stored. Env `MCPPROXY_MCP_OAUTH_ENABLED=true\|false` overrides it for the process (never persisted). Live, no restart. **Not functional yet in this release:** the endpoints (`/mcp/oauth`, `/oauth/register`, `/oauth/authorize`, `/oauth/token` and the two `/.well-known/oauth-*` documents) answer `501 Not Implemented` when enabled | | `enable_socket` | boolean | `true` | Enable the Unix socket/named pipe the tray uses. Socket connections are trusted **without the API key**, including stdio servers spawned under `none` or `sandbox` isolation, which can then mint agent tokens. Set `false` on headless installs and whenever untrusted stdio servers run outside `docker` isolation. | | `forward_client_headers` | boolean | `true` | Master switch for [client header forwarding](/configuration/upstream-servers#client-header-forwarding). Nothing is forwarded until a server lists names in `forward_headers`. Env `MCPPROXY_FORWARD_CLIENT_HEADERS=false` disables it for the process (never persisted). | diff --git a/internal/config/config.go b/internal/config/config.go index 0cb27965d..5739f2e56 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -405,6 +405,11 @@ type Config struct { // MCP endpoints: the Web UI and its SSE stream (/events) still use the // query form. Live, no restart needed. MCPRejectQueryAPIKey bool `json:"mcp_reject_query_apikey,omitempty" mapstructure:"mcp-reject-query-apikey"` + // MCPOAuthEnabled turns on browser login (OAuth 2.1 + PKCE) for MCP + // clients on the loopback listener (Spec 132). Experimental, default false: + // with it off nothing changes. Env override MCPPROXY_MCP_OAUTH_ENABLED is + // process-only and never persisted. Live, no restart needed. + MCPOAuthEnabled bool `json:"mcp_oauth_enabled,omitempty" mapstructure:"mcp-oauth-enabled"` // TrustedHosts lists non-loopback Host header values accepted on loopback // listeners (GH #898). DNS-rebinding protection rejects requests whose Host // header is not a loopback address when mcpproxy listens on loopback; a @@ -2775,6 +2780,11 @@ func NormalizeForwardHeaders(cfg *Config) []ForwardHeaderNormalization { return out } +// EnvMCPOAuthEnabled is the process-only environment override for +// Config.MCPOAuthEnabled (Spec 132). Accepts true|1 / false|0; anything else +// is ignored. Never persisted. +const EnvMCPOAuthEnabled = "MCPPROXY_MCP_OAUTH_ENABLED" + // EnvForwardClientHeaders is the environment kill switch for client header // forwarding (Spec 112 FR-003): false|0|off disables it for the process. const EnvForwardClientHeaders = "MCPPROXY_FORWARD_CLIENT_HEADERS" diff --git a/internal/config/loader.go b/internal/config/loader.go index 4ebd70da4..d377de193 100644 --- a/internal/config/loader.go +++ b/internal/config/loader.go @@ -937,6 +937,20 @@ func applyTLSEnvOverrides(cfg *Config) { } envOverride(b, cfg, FieldForwardClientHeaders, fwd != nil, fwd) + // Spec 132: MCPPROXY_MCP_OAUTH_ENABLED switches browser login on or off for + // this process. Only the documented vocabulary overrides; a typo leaves the + // file value. + var mcpOAuth *bool + switch strings.ToLower(strings.TrimSpace(os.Getenv(EnvMCPOAuthEnabled))) { + case trueValue, "1": + on := true + mcpOAuth = &on + case falseValue, "0": + off := false + mcpOAuth = &off + } + envOverride(b, cfg, FieldMCPOAuthEnabled, mcpOAuth != nil, derefBool(mcpOAuth)) + // Override trusted hosts for reverse-proxy deployments (GH #898). // Comma-separated list of Host header values accepted on loopback listeners. var hosts []string @@ -1109,3 +1123,5 @@ func envNonNegativeDuration(name, want string) (bool, *Duration) { dur := Duration(d) return true, &dur } + +func derefBool(p *bool) bool { return p != nil && *p } diff --git a/internal/config/mcp_oauth_test.go b/internal/config/mcp_oauth_test.go new file mode 100644 index 000000000..8ad5e4b61 --- /dev/null +++ b/internal/config/mcp_oauth_test.go @@ -0,0 +1,50 @@ +package config + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Spec 132: the opt-in browser login switch is off by default, never written +// to disk while off, and its env override is process-only. +func TestConfig_MCPOAuthEnabled_DefaultOffAndOmitted(t *testing.T) { + t.Cleanup(ResetProcessOverrides) + ResetProcessOverrides() + t.Setenv(EnvMCPOAuthEnabled, "") + + assert.False(t, DefaultConfig().MCPOAuthEnabled) + + dir := t.TempDir() + path := filepath.Join(dir, "mcp_config.json") + require.NoError(t, SaveConfig(DefaultConfig(), path)) + raw, err := os.ReadFile(path) + require.NoError(t, err) + assert.NotContains(t, string(raw), "mcp_oauth_enabled") + + // Env override turns it on for this process only. + t.Setenv(EnvMCPOAuthEnabled, "true") + cfg, err := LoadFromFile(path) + require.NoError(t, err) + assert.True(t, cfg.MCPOAuthEnabled, "env overrides the file value") + + require.NoError(t, SaveConfig(cfg, path)) + raw, err = os.ReadFile(path) + require.NoError(t, err) + assert.NotContains(t, string(raw), "mcp_oauth_enabled", "the env override is not persisted") + + // A file value of true is honoured and persisted. + t.Setenv(EnvMCPOAuthEnabled, "") + ResetProcessOverrides() + cfg, err = LoadFromFile(path) + require.NoError(t, err) + assert.False(t, cfg.MCPOAuthEnabled) + cfg.MCPOAuthEnabled = true + require.NoError(t, SaveConfig(cfg, path)) + raw, err = os.ReadFile(path) + require.NoError(t, err) + assert.Contains(t, string(raw), `"mcp_oauth_enabled": true`) +} diff --git a/internal/config/process_overrides.go b/internal/config/process_overrides.go index 57ea1ed13..20e8fefe0 100644 --- a/internal/config/process_overrides.go +++ b/internal/config/process_overrides.go @@ -85,6 +85,7 @@ var ( FieldHTTPReadTimeout = scalar("http_read_timeout", func(c *Config) **Duration { return &c.HTTPReadTimeout }) FieldHTTPWriteTimeout = scalar("http_write_timeout", func(c *Config) **Duration { return &c.HTTPWriteTimeout }) FieldHTTPIdleTimeout = scalar("http_idle_timeout", func(c *Config) **Duration { return &c.HTTPIdleTimeout }) + FieldMCPOAuthEnabled = scalar("mcp_oauth_enabled", func(c *Config) *bool { return &c.MCPOAuthEnabled }) FieldForwardClientHeaders = scalar("forward_client_headers", func(c *Config) **bool { return &c.ForwardClientHeaders }) FieldLogLevel = Field[string]{ diff --git a/internal/mcplogin/doc.go b/internal/mcplogin/doc.go new file mode 100644 index 000000000..732f3de34 --- /dev/null +++ b/internal/mcplogin/doc.go @@ -0,0 +1,7 @@ +// Package mcplogin holds the pure protocol logic for opt-in browser login +// (OAuth 2.1 + PKCE) of MCP clients against the local mcpproxy (Spec 132). +// +// Scope: protocol rules only. No HTTP wiring, no storage and no new external +// dependencies. From this repository it may import only internal/auth, +// internal/clientidentity and internal/upstream/limiter. +package mcplogin diff --git a/internal/runtime/config_hotreload.go b/internal/runtime/config_hotreload.go index 97b18f94c..78f52dc2a 100644 --- a/internal/runtime/config_hotreload.go +++ b/internal/runtime/config_hotreload.go @@ -611,7 +611,7 @@ func (r *ConfigApplyResult) FormatChangedFields() string { // adopted into the live config, and reported by its JSON key. var undiffedHotConfigFields = []string{ "EnableTray", "TopK", "MaxResultSizeChars", "InitTimeout", "ForwardProxyEnv", - "RequireMCPAuth", "MCPRejectQueryAPIKey", "CheckServerRepo", "DockerRecovery", + "RequireMCPAuth", "MCPRejectQueryAPIKey", "MCPOAuthEnabled", "CheckServerRepo", "DockerRecovery", "RegistriesLocked", "AllowPrivateRegistryFetch", "Features", "ToolResponseSessionRiskWarning", "OAuthExpiryWarningHours", "ActivityRetentionDays", "ActivityMaxRecords", "ActivityMaxSizeMB", diff --git a/internal/server/oauth_login_default_off_test.go b/internal/server/oauth_login_default_off_test.go new file mode 100644 index 000000000..73ca7f42a --- /dev/null +++ b/internal/server/oauth_login_default_off_test.go @@ -0,0 +1,241 @@ +package server + +import ( + "fmt" + "net/http" + "net/http/httptest" + "sort" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.etcd.io/bbolt" + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +const oauthLoginTestAPIKey = "test-api-key-oauth-login" + +func newOAuthLoginTestServer(t *testing.T, mutate func(*config.Config)) *Server { + t.Helper() + cfg := config.DefaultConfig() + cfg.DataDir = t.TempDir() + cfg.Listen = "127.0.0.1:0" + cfg.APIKey = oauthLoginTestAPIKey + if mutate != nil { + mutate(cfg) + } + srv, err := NewServer(cfg, zap.NewNop()) + require.NoError(t, err) + t.Cleanup(func() { _ = srv.Shutdown() }) + return srv +} + +// oauthLoginTestMuxes builds the mux as startCustomHTTPServer shapes it around +// the browser-login routes: the /mcp catch-all chain (real host validation and +// MCP auth middleware around a sentinel) and the real root handler. withRoutes +// adds the Spec 132 registrations. +func oauthLoginTestMux(s *Server, withRoutes bool) *http.ServeMux { + sentinel := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = fmt.Fprintf(w, "mcp-chain %s %s", r.Method, r.URL.Path) + }) + mcpHandler := s.hostValidationMiddleware(s.mcpAuthMiddleware(sentinel)) + rootHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/" { + http.Redirect(w, r, "/ui/", http.StatusFound) + return + } + http.NotFound(w, r) + }) + mux := http.NewServeMux() + mux.Handle("/mcp", mcpHandler) + mux.Handle("/mcp/", mcpHandler) + mux.Handle("/", rootHandler) + if withRoutes { + s.registerOAuthLoginRoutes(mux, mcpHandler, rootHandler) + } + return mux +} + +var oauthLoginTestPaths = []string{ + "/mcp/oauth", "/mcp/oauth/", "/mcp/oauth/cursor", + "/oauth", "/oauth/", "/oauth/x", + "/oauth/register", "/oauth/authorize", "/oauth/token", + "/.well-known/oauth-authorization-server", + "/.well-known/oauth-protected-resource", + "/.well-known/oauth-protected-resource/mcp/oauth", + "/.well-known/oauth-protected-resource/mcp/oauth/cursor", + "/.well-known/x", +} + +type oauthLoginResp struct { + code int + body string + location string + wwwAuthenticate string +} + +func doOAuthLoginReq(mux http.Handler, method, path, remote string, hdr map[string]string) oauthLoginResp { + req := httptest.NewRequest(method, path, http.NoBody) + req.RemoteAddr = remote + for k, v := range hdr { + req.Header.Set(k, v) + } + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + return oauthLoginResp{ + code: rec.Code, + body: rec.Body.String(), + location: rec.Header().Get("Location"), + wwwAuthenticate: rec.Header().Get("WWW-Authenticate"), + } +} + +func TestOAuthLogin_DefaultOff_RoutesUnchanged(t *testing.T) { + creds := map[string]map[string]string{ + "none": nil, + "admin": {"X-API-Key": oauthLoginTestAPIKey}, + "garbage": {"Authorization": "Bearer garbage-token"}, + } + for _, requireAuth := range []bool{false, true} { + srv := newOAuthLoginTestServer(t, func(c *config.Config) { c.RequireMCPAuth = requireAuth }) + full := oauthLoginTestMux(srv, true) + ref := oauthLoginTestMux(srv, false) + for _, path := range oauthLoginTestPaths { + for _, method := range []string{http.MethodGet, http.MethodPost} { + for credName, hdr := range creds { + for _, remote := range []string{"192.0.2.1:4000", "127.0.0.1:4000"} { + name := fmt.Sprintf("require=%v %s %s cred=%s peer=%s", requireAuth, method, path, credName, remote) + want := doOAuthLoginReq(ref, method, path, remote, hdr) + got := doOAuthLoginReq(full, method, path, remote, hdr) + assert.Equal(t, want, got, name) + } + } + } + } + } +} + +func bucketSnapshot(t *testing.T, db *bbolt.DB) (buckets []string, metaKeys []string) { + t.Helper() + require.NoError(t, db.View(func(tx *bbolt.Tx) error { + if err := tx.ForEach(func(name []byte, b *bbolt.Bucket) error { + buckets = append(buckets, string(name)) + return nil + }); err != nil { + return err + } + if meta := tx.Bucket([]byte(storage.MetaBucket)); meta != nil { + return meta.ForEach(func(k, _ []byte) error { + metaKeys = append(metaKeys, string(k)) + return nil + }) + } + return nil + })) + sort.Strings(buckets) + sort.Strings(metaKeys) + return buckets, metaKeys +} + +func TestOAuthLogin_DefaultOff_NoStorage(t *testing.T) { + srv := newOAuthLoginTestServer(t, nil) + db := srv.runtime.StorageManager().GetDB() + require.NotNil(t, db) + beforeBuckets, beforeMeta := bucketSnapshot(t, db) + + mux := oauthLoginTestMux(srv, true) + for _, path := range oauthLoginTestPaths { + for _, method := range []string{http.MethodGet, http.MethodPost} { + doOAuthLoginReq(mux, method, path, "127.0.0.1:4000", nil) + doOAuthLoginReq(mux, method, path, "127.0.0.1:4000", map[string]string{"X-API-Key": oauthLoginTestAPIKey}) + doOAuthLoginReq(mux, method, path, "127.0.0.1:4000", map[string]string{"Authorization": "Bearer garbage-token"}) + } + } + + afterBuckets, afterMeta := bucketSnapshot(t, db) + assert.Equal(t, beforeBuckets, afterBuckets, "bucket list must not change") + assert.Equal(t, beforeMeta, afterMeta, "MetaBucket keys must not change") +} + +// Patterns the gate guards (the ones registered by registerOAuthLoginRoutes). +var oauthLoginGatedPaths = []string{ + "/mcp/oauth", "/mcp/oauth/", "/mcp/oauth/cursor", + "/oauth/register", "/oauth/authorize", "/oauth/token", + "/.well-known/oauth-authorization-server", + "/.well-known/oauth-protected-resource/mcp/oauth", + "/.well-known/oauth-protected-resource/mcp/oauth/cursor", +} + +func TestOAuthLogin_Gate_OffAndEverUsed_404(t *testing.T) { + srv := newOAuthLoginTestServer(t, nil) + srv.oauthLoginEverUsed = func() bool { return true } + mux := oauthLoginTestMux(srv, true) + for _, path := range oauthLoginGatedPaths { + got := doOAuthLoginReq(mux, http.MethodGet, path, "127.0.0.1:4000", nil) + assert.Equal(t, http.StatusNotFound, got.code, path) + assert.NotContains(t, got.body, "mcp-chain", path) + } +} + +func TestOAuthLogin_Gate_On(t *testing.T) { + srv := newOAuthLoginTestServer(t, func(c *config.Config) { c.MCPOAuthEnabled = true }) + mux := oauthLoginTestMux(srv, true) + + for _, path := range oauthLoginGatedPaths { + req := httptest.NewRequest(http.MethodGet, path, http.NoBody) + req.RemoteAddr = "127.0.0.1:4000" + req.Host = "127.0.0.1:8080" + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + assert.Equal(t, http.StatusNotImplemented, rec.Code, "loopback peer+host "+path) + assert.Contains(t, rec.Header().Get("Content-Type"), "application/json", path) + + req = httptest.NewRequest(http.MethodGet, path, http.NoBody) + req.RemoteAddr = "[::1]:4000" + req.Host = "localhost:8080" + rec = httptest.NewRecorder() + mux.ServeHTTP(rec, req) + assert.Equal(t, http.StatusNotImplemented, rec.Code, "ipv6 loopback peer "+path) + + req = httptest.NewRequest(http.MethodGet, path, http.NoBody) + req.RemoteAddr = "192.0.2.1:4000" + req.Host = "127.0.0.1:8080" + rec = httptest.NewRecorder() + mux.ServeHTTP(rec, req) + assert.Equal(t, http.StatusNotFound, rec.Code, "non-loopback peer "+path) + + req = httptest.NewRequest(http.MethodGet, path, http.NoBody) + req.RemoteAddr = "127.0.0.1:4000" + req.Host = "example.com" + rec = httptest.NewRecorder() + mux.ServeHTTP(rec, req) + assert.Equal(t, http.StatusNotFound, rec.Code, "non-loopback host "+path) + } +} + +// The gate reads the live config on every request: flipping the switch needs +// no restart and leaves no cached state. +func TestOAuthLogin_Gate_FollowsLiveConfig(t *testing.T) { + srv := newOAuthLoginTestServer(t, nil) + mux := oauthLoginTestMux(srv, true) + get := func() int { + req := httptest.NewRequest(http.MethodGet, "/oauth/token", http.NoBody) + req.RemoteAddr = "127.0.0.1:4000" + req.Host = "127.0.0.1:8080" + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + return rec.Code + } + assert.Equal(t, http.StatusNotFound, get(), "off: previous behaviour (root handler 404)") + + cfg := srv.runtime.Config() + require.NotNil(t, cfg) + on := *cfg + on.MCPOAuthEnabled = true + srv.runtime.UpdateConfig(&on, "") + assert.Equal(t, http.StatusNotImplemented, get(), "on") +} diff --git a/internal/server/oauth_login_routes.go b/internal/server/oauth_login_routes.go new file mode 100644 index 000000000..2cefe21e0 --- /dev/null +++ b/internal/server/oauth_login_routes.go @@ -0,0 +1,108 @@ +package server + +import ( + "encoding/json" + "net/http" + "net/netip" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/httpx" +) + +// Spec 132: opt-in browser login for MCP clients. This file holds only the +// routing switch. With mcp_oauth_enabled off (the default) and the feature +// never used, every pattern below answers exactly as it did before the +// patterns were registered (the previous handler is called). The gate decides +// per request from the live config; nothing is cached. + +// oauthLoginExactPatterns and oauthLoginSubtreePatterns are the ONLY patterns +// registered for browser login. `/oauth/` and `/.well-known/` subtrees are +// deliberately not registered: ServeMux would add trailing-slash redirects +// that do not exist today. +var ( + // oauthLoginMCPPatterns fall back to the /mcp/ catch-all chain when off. + oauthLoginMCPPatterns = []string{"/mcp/oauth", "/mcp/oauth/"} + // oauthLoginRootPatterns fall back to the root handler when off. + oauthLoginRootPatterns = []string{ + "/oauth/register", + "/oauth/authorize", + "/oauth/token", + "/.well-known/oauth-authorization-server", + "/.well-known/oauth-protected-resource/mcp/oauth", + "/.well-known/oauth-protected-resource/mcp/oauth/", + } +) + +// peerIsLoopback reports whether the TCP peer of r is a loopback address. +// Unix-socket / named-pipe peers, empty and malformed addresses are not. +func peerIsLoopback(r *http.Request) bool { + ap, err := netip.ParseAddrPort(r.RemoteAddr) + if err != nil { + return false + } + return ap.Addr().Unmap().IsLoopback() +} + +// oauthLoginEverUsedNow reports whether browser login has ever been used on +// this install. It is injectable for tests. +// TODO(Spec 132): read the storage marker `oauth_login_ever_used` once the +// storage slice lands; until then the feature can never have been used. +func (s *Server) oauthLoginEverUsedNow() bool { + if s.oauthLoginEverUsed != nil { + return s.oauthLoginEverUsed() + } + return false +} + +// oauthLoginGate wraps the browser-login handler `served`. prev is the handler +// that answered the same path before this change. +// +// off, never used -> prev +// off, used -> 404 +// on -> served, only for a loopback peer, a loopback Host and +// the personal edition; otherwise 404 +func (s *Server) oauthLoginGate(prev, served http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + cfg := s.liveConfig() + if cfg == nil || !cfg.MCPOAuthEnabled { + if s.oauthLoginEverUsedNow() { + http.NotFound(w, r) + return + } + prev.ServeHTTP(w, r) + return + } + if !peerIsLoopback(r) || !httpx.IsLoopbackHost(r.Host) || config.ServerEditionEnabled(cfg) { + http.NotFound(w, r) + return + } + served.ServeHTTP(w, r) + }) +} + +// oauthLoginNotImplemented is the `served` stub of this slice. +func oauthLoginNotImplemented() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusNotImplemented) + _ = json.NewEncoder(w).Encode(map[string]string{ + "error": "not_implemented", + "error_description": "browser login (mcp_oauth_enabled) is not functional in this release", + }) + }) +} + +// registerOAuthLoginRoutes registers the browser-login patterns on mux. +// mcpHandler is the existing /mcp/ catch-all chain, rootHandler the existing +// "/" handler; each is the off-state fallback of its patterns. +func (s *Server) registerOAuthLoginRoutes(mux *http.ServeMux, mcpHandler, rootHandler http.Handler) { + served := oauthLoginNotImplemented() + mcpGate := s.oauthLoginGate(mcpHandler, served) + for _, p := range oauthLoginMCPPatterns { + mux.Handle(p, mcpGate) + } + rootGate := s.oauthLoginGate(rootHandler, served) + for _, p := range oauthLoginRootPatterns { + mux.Handle(p, rootGate) + } +} diff --git a/internal/server/oauth_login_routes_test.go b/internal/server/oauth_login_routes_test.go new file mode 100644 index 000000000..f5eb0ed0d --- /dev/null +++ b/internal/server/oauth_login_routes_test.go @@ -0,0 +1,34 @@ +package server + +import ( + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestPeerIsLoopback(t *testing.T) { + cases := []struct { + remote string + want bool + }{ + {"127.0.0.1:5000", true}, + {"127.5.6.7:5000", true}, + {"[::1]:5000", true}, + {"[::ffff:127.0.0.1]:5000", true}, + {"192.0.2.1:5000", false}, + {"10.0.0.5:5000", false}, + {"[2001:db8::1]:5000", false}, + {"", false}, + {"@", false}, + {"/tmp/mcpproxy.sock", false}, + {"127.0.0.1", false}, // no port + {"not-an-address", false}, + {"localhost:5000", false}, // names are not peer addresses + } + for _, c := range cases { + r := httptest.NewRequest("GET", "/", nil) + r.RemoteAddr = c.remote + assert.Equal(t, c.want, peerIsLoopback(r), "remote=%q", c.remote) + } +} diff --git a/internal/server/oauth_login_server_edition_test.go b/internal/server/oauth_login_server_edition_test.go new file mode 100644 index 000000000..017ef1212 --- /dev/null +++ b/internal/server/oauth_login_server_edition_test.go @@ -0,0 +1,30 @@ +//go:build server + +package server + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" +) + +// Server edition never serves browser login, even with the switch on. +func TestOAuthLogin_Gate_ServerEdition_404(t *testing.T) { + srv := newOAuthLoginTestServer(t, func(c *config.Config) { + c.MCPOAuthEnabled = true + c.ServerEdition = &config.ServerEditionConfig{Enabled: true} + }) + mux := oauthLoginTestMux(srv, true) + for _, path := range oauthLoginGatedPaths { + req := httptest.NewRequest(http.MethodGet, path, http.NoBody) + req.RemoteAddr = "127.0.0.1:4000" + req.Host = "127.0.0.1:8080" + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + assert.Equal(t, http.StatusNotFound, rec.Code, path) + } +} diff --git a/internal/server/server.go b/internal/server/server.go index 85e2cf072..15f9184a1 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -122,6 +122,9 @@ type Server struct { // mcp_reject_query_apikey warning, so a client retrying in a loop logs // once per queryAPIKeyRejectLogInterval, not once per request. queryAPIKeyRejectLogged atomic.Int64 + // oauthLoginEverUsed reports whether browser login was ever used on this + // install (Spec 132). nil means never; tests inject it. + oauthLoginEverUsed func() bool // createAfterConfigRead is a Spec 116 test seam (nil in production): it // runs in the create path after the runtime configuration was read and // before the new server is published. @@ -3751,7 +3754,7 @@ func (s *Server) startCustomHTTPServer(ctx context.Context, streamableServer *se selectiveProtectedWebUIHandler := s.createSelectiveWebUIProtectedHandler(http.StripPrefix("/ui", webUIHandler)) mux.Handle("/ui/", selectiveProtectedWebUIHandler) // Redirect root to web UI - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + rootHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/" { http.Redirect(w, r, "/ui/", http.StatusFound) return @@ -3765,6 +3768,10 @@ func (s *Server) startCustomHTTPServer(ctx context.Context, streamableServer *se } http.NotFound(w, r) }) + mux.Handle("/", rootHandler) + // Spec 132: opt-in browser login. Behaves exactly like the handlers above + // until mcp_oauth_enabled is switched on (or the feature has been used). + s.registerOAuthLoginRoutes(mux, mcpHandler, rootHandler) s.logger.Info("Registered Web UI endpoints", zap.Strings("ui_endpoints", []string{"/ui/", "/"})) // Determine actual TCP address for logging diff --git a/oas/docs.go b/oas/docs.go index 3ec71de28..7fc4734a5 100644 --- a/oas/docs.go +++ b/oas/docs.go @@ -6,7 +6,7 @@ import "github.com/swaggo/swag/v2" const docTemplate = `{ "schemes": {{ marshal .Schemes }}, - "components": {"schemas":{"auth.CredentialIssuer":{"properties":{"actor_kind":{"type":"string"},"actor_name":{"type":"string"},"surface":{"type":"string"}},"type":"object"},"config.AgentTokenRateLimit":{"description":"AgentTokenRateLimit caps how many upstream tool calls ONE agent token may\nmake: PerMinute on average, Burst at once (issue #1699). Every token is\ncounted separately, and a token's own rate_limit (set when it is created)\nreplaces this default for that token. Only agent-token callers are\nlimited; the admin API key, the unix socket and an unauthenticated /mcp\ncaller are not. Absent or per_minute 0 = no limit (default, zero behavior\nchange). The counters are in memory: a restart gives every token a full\nallowance again. Hot-reloadable. File/API-configured only, no env scheme.","properties":{"burst":{"description":"Burst is how many calls a token may make at once after a quiet spell.\n0 = the PerMinute value.","type":"integer"},"per_minute":{"description":"PerMinute is the sustained rate. 0 = no limit.","type":"integer"}},"type":"object"},"config.AuditLogConfig":{"description":"AuditLog configures the Spec 107 edition-neutral audit sink\n(internal/audit). nil means \"use the per-edition/per-transport\ndefault\" (EffectiveAuditLog); restart-pinned (bound at sink\nconstruction). See audit_log.go.","properties":{"compress":{"type":"boolean"},"enabled":{"type":"boolean"},"max_age_days":{"type":"integer"},"max_backups":{"type":"integer"},"max_size_mb":{"type":"integer"},"path":{"type":"string"},"stdout":{"type":"boolean"}},"type":"object"},"config.ConcurrencyDefaults":{"description":"ServerConcurrencyDefaults is scope (b) of FR-020: the blanket per-server\ndefault set inherited by every server that does not override a setting.\nAbsent (the default) = no per-server limiting unless a server configures\nit explicitly. File/API-configured only — no env scheme (FR-022).","properties":{"max_concurrent_requests":{"type":"integer"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"}},"type":"object"},"config.Config":{"properties":{"activity_cleanup_interval_min":{"description":"Background cleanup interval in minutes (default: 60)","type":"integer"},"activity_max_records":{"description":"Max records before pruning (default: 400000)","type":"integer"},"activity_max_response_size":{"description":"Response truncation limit in bytes (default: 65536)","type":"integer"},"activity_max_size_mb":{"description":"ActivityMaxSizeMB caps the total activity-log size in MB before the\noldest records are pruned. Omit the key for the 256MB default; set it to\n0 to disable the size cap.","type":"integer"},"activity_retention_days":{"description":"Activity logging settings (RFC-003)","type":"integer"},"advertise_upstream_servers":{"description":"AdvertiseUpstreamServers controls whether MCP clients are told the\nnames of the upstream servers they can reach — in the initialize\ninstructions and the retrieve_tools description — so agents use the\nproxied tools instead of falling back to shell CLIs. Names are always\nfiltered to the caller's profile and agent-token scope. Default true;\nset false to keep server names out of client context. Read live.","type":"boolean"},"agent_token_rate_limit":{"$ref":"#/components/schemas/config.AgentTokenRateLimit"},"aggregate_upstream_prompts":{"description":"AggregateUpstreamPrompts, when true, aggregates every connected upstream\nserver's advertised MCP prompts into mcpproxy's own prompts/list\n(exposed as \"\u003cserver\u003e__\u003cprompt\u003e\"). OFF by default: users are safe by\ndefault and opt in deliberately. EnablePrompts still governs the built-in\nprompts + the prompts capability; this flag gates ONLY the upstream\naggregation performed by RefreshPrompts. Hot-reloadable.","type":"boolean"},"allow_private_registry_fetch":{"description":"AllowPrivateRegistryFetch opts out of the registry SSRF guard (MCP-1076,\nCWE-918). By default (false) registry fetches refuse any host that is — or\nresolves to — a non-routable address (loopback, RFC1918/CGNAT private,\nlink-local incl. the 169.254.169.254 cloud-metadata endpoint), so a\nmalicious or typo'd registry source cannot turn the daemon into a\nrequest-forgery vector against internal services.\n\nThis opt-out is BLANKET (all-or-nothing): setting it true disables the\nguard for EVERY non-routable range at once — loopback, RFC1918/CGNAT\nprivate, link-local AND the 169.254.169.254 cloud-metadata endpoint. There\nis no way to allow only loopback; enabling it for a localhost dev registry\nalso re-opens the cloud-metadata SSRF vector. Set true ONLY when you\nintentionally run a trusted registry mirror on an internal/private address,\nideally on a host with no cloud-metadata exposure. The change takes effect\nonly on daemon (re)start or config reload.","type":"boolean"},"allow_server_add":{"type":"boolean"},"allow_server_remove":{"type":"boolean"},"anonymous_profile":{"description":"AnonymousProfile confines every caller whose request authenticates as\ncredential kind \"anonymous\" (no credential, or an unrecognised\nnon-agent token accepted by the require_mcp_auth:false back-compat\nbranch) to the named profile (Spec 108 FR-008). Empty (default) means\nunconfined, legacy anonymous behaviour. A name that does not match any\nconfigured profile resolves anonymous callers to deny-all and is\nreported as a validation warning (data-model.md §1).","type":"string"},"api_key":{"description":"Security settings","type":"string"},"audit_log":{"$ref":"#/components/schemas/config.AuditLogConfig"},"call_tool_timeout":{"type":"string"},"check_server_repo":{"description":"Repository detection settings","type":"boolean"},"code_execution_max_parallel":{"description":"Default concurrency for call_tools() batches (1-32, default: 8)","type":"integer"},"code_execution_max_tool_calls":{"description":"Max tool calls per execution (0 = unlimited, default: 0)","type":"integer"},"code_execution_pool_size":{"description":"JavaScript runtime pool size (default: 10)","type":"integer"},"code_execution_timeout_ms":{"description":"Timeout in milliseconds (default: 120000, max: 600000)","type":"integer"},"data_dir":{"type":"string"},"debug_search":{"type":"boolean"},"direct_tool_response_mode":{"description":"DirectToolResponseMode selects the serialization of the DIRECT\nenumeration surface (Spec 102). Valid values: \"\" (= full), \"full\"\n(default: today's schema-bearing entries), \"deferred\" (description +\ncompact signature, with a minimal permissive input schema; upstream\ninputSchema and outputSchema are stripped and recovered on demand via\ndescribe_tool).\n\nDeliberately NOT an extension of tool_response_mode: reusing that axis\nwould silently change /mcp/all output for every deployment already\nrunning compact, which FR-015 forbids. Serialization-only — it never\nchanges WHICH tools are listed, only how (FR-008). Hot-reloadable.","type":"string"},"disable_management":{"type":"boolean"},"docker_isolation":{"$ref":"#/components/schemas/config.DockerIsolationConfig"},"docker_recovery":{"$ref":"#/components/schemas/config.DockerRecoveryConfig"},"enable_code_execution":{"description":"Code execution settings","type":"boolean"},"enable_prompts":{"description":"Prompts settings","type":"boolean"},"enable_skills":{"description":"EnableSkills, when true, makes mcpproxy read the skills that upstream\nservers expose through the MCP skills extension. OFF by default. Unlike\nEnablePrompts this is hot-reloadable. No CLI flag, no environment\nvariable.","type":"boolean"},"enable_socket":{"description":"Enable Unix socket/named pipe for local IPC (default: true)","type":"boolean"},"enable_tray":{"description":"Deprecated: EnableTray is unused and has no runtime effect. Kept for backward compatibility.","type":"boolean"},"environment":{"$ref":"#/components/schemas/secureenv.EnvConfig"},"features":{"$ref":"#/components/schemas/config.FeatureFlags"},"forward_client_headers":{"description":"ForwardClientHeaders is the global switch for client header forwarding\n(Spec 112): copying allowlisted headers from the inbound /mcp request into\nthe upstream tools/call request. nil (absent) means enabled; because every\nper-server forward_headers allowlist is empty by default, the default\nforwards nothing. false disables forwarding for every server. Read via\nIsClientHeaderForwardingEnabled(); MCPPROXY_FORWARD_CLIENT_HEADERS\noverrides it for the process. Distinct from ForwardedHeaders/trusted_proxies\n(Spec 107), which trusts inbound X-Forwarded-*.","type":"boolean"},"forward_proxy_env":{"description":"ForwardProxyEnv opts in to forwarding the ambient HTTP(S)/ALL/NO/FTP proxy\nenvironment variables to spawned stdio upstream servers (MCP-2769). OFF by\ndefault: proxy URLs commonly embed credentials (http://user:pass@proxy), so\nforwarding them to every upstream is a credential-leak risk. When enabled,\nvalues are forwarded with their userinfo (credentials) redacted.","type":"boolean"},"health_check_interval":{"description":"Discovery \u0026 health-check cadence (spec 074, #608). Both are *Duration\ntri-state pointers: nil = inherit the built-in default; a pointer to 0s =\nthe loop is disabled; a positive value = that interval. Defaults live only\nin the resolvers (ResolveHealthCheckInterval / ResolveToolDiscoveryInterval)\nso an unset key behaves exactly as before this feature (SC-005). Validated\nin Validate(): health-check ∈ {0} ∪ [5s,1h]; tool-discovery ∈ {0} ∪ [30s,24h].","type":"string"},"http_idle_timeout":{"description":"HTTPIdleTimeout caps how long an idle keep-alive connection is kept open.\nUnset = 180s. \"0s\" removes the dedicated idle deadline, but net/http then\nfalls back to ReadTimeout — idle is fully unbounded only when\nhttp_read_timeout is also \"0s\". Requires a restart.","type":"string"},"http_read_timeout":{"description":"HTTPReadTimeout caps how long reading a whole request (headers + body)\nmay take. Unset = 120s; \"0s\" disables it. Requires a restart.","type":"string"},"http_write_timeout":{"description":"HTTPWriteTimeout caps how long producing a whole response may take on\nnon-streaming endpoints (REST, Web UI, health). Unset = 120s; \"0s\"\ndisables it globally. MCP and SSE /events routes are exempt by design.","type":"string"},"init_timeout":{"description":"InitTimeout is the global default deadline for an upstream's MCP\n` + "`" + `initialize` + "`" + ` handshake (MCP-3322 / GH #760). *Duration tri-state: nil =\ninherit the built-in 30s default; a positive value = that deadline. A\nper-server InitTimeout overrides this. Resolved by ResolveInitTimeout;\nvalidated to {0} ∪ [1s, 30m] in Validate(). Servers doing legitimate\nfirst-run warmup (cache/index build) before answering ` + "`" + `initialize` + "`" + ` can\nraise this so they are not killed mid-startup.","type":"string"},"instructions":{"description":"Instructions text returned in the MCP initialize response to guide AI agents.\nWhen empty, a built-in default is used that explains retrieve_tools workflow.","type":"string"},"intent_declaration":{"$ref":"#/components/schemas/config.IntentDeclarationConfig"},"listen":{"type":"string"},"logging":{"$ref":"#/components/schemas/config.LogConfig"},"max_concurrent_requests":{"description":"Concurrency limits (spec 093, GH #955). Scope (a) of FR-020: the GLOBAL\nAGGREGATE limiter — one proxy-wide cap on concurrently running upstream\ntool calls, with its own bounded wait queue. Tri-state pointers: absent =\nthe limiter does not exist (default, zero behavior change); an explicit 0\nmax also disables it; positive = that cap. This scope is NEVER a\nper-server inheritance source — per-server values come from\nServerConcurrencyDefaults / the per-server overrides — but a server's\neffective concurrency is bounded by BOTH its own limiter and this one.\nResolved by ResolveGlobalConcurrency; hot-reloadable; overridable via\nMCPPROXY_MAX_CONCURRENT_REQUESTS / _QUEUE_SIZE / _QUEUE_TIMEOUT (FR-022).","type":"integer"},"max_result_size_chars":{"description":"MaxResultSizeChars is advertised on every tool as\n` + "`" + `_meta.anthropic/maxResultSizeChars` + "`" + `; it raises Claude Code's\ninline-response ceiling from 50k to up to 500k chars. Omit the key for\nthe 500000 default; set it to 0 to disable the annotation.","type":"integer"},"mcpServers":{"items":{"$ref":"#/components/schemas/config.ServerConfig"},"type":"array","uniqueItems":false},"mcp_reject_query_apikey":{"description":"MCPRejectQueryAPIKey makes every MCP endpoint (/mcp*) refuse a request that\ncarries a ?apikey= query parameter, with a 401, instead of honouring it. A credential in a URL ends up in access logs,\nproxy logs and browser history; MCP clients can send Authorization:\nBearer or X-API-Key instead. Default false (the query form keeps\nworking, for clients that can only configure a URL). It covers only the\nMCP endpoints: the Web UI and its SSE stream (/events) still use the\nquery form. Live, no restart needed.","type":"boolean"},"oauth_expiry_warning_hours":{"description":"Health status settings","type":"number"},"oauth_token_encryption_key":{"description":"OAuthTokenEncryptionKey seals the upstream OAuth tokens stored in\nconfig.db (Spec 123). Empty (the default) leaves them as plain JSON. It\ntakes a secret reference (${file:/abs/path}, ${env:NAME},\n${keyring:NAME}) or a literal standard-base64 32-byte key; the\nMCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY[_FILE] variables override it. The key\nis resolved only where config.db is opened (ResolveOAuthTokenKey), never\nstored on Config, and is restart-gated, so every save writes the field\nas configured.","type":"string"},"observability":{"$ref":"#/components/schemas/config.ObservabilityConfig"},"output_sanitisation":{"$ref":"#/components/schemas/config.OutputSanitisationConfig"},"output_validation":{"$ref":"#/components/schemas/config.OutputValidationConfig"},"profiles":{"description":"Profiles are optional named, server-scoped views exposed at /mcp/p/\u003cname\u003e\n(Spec 057). Absent/empty is fully supported — /mcp is unchanged and configs\nwithout this key serialize byte-identically (SC-004).","items":{"$ref":"#/components/schemas/config.ProfileConfig"},"type":"array","uniqueItems":false},"quarantine_enabled":{"description":"QuarantineEnabled controls whether quarantine is active. It gates two\nthings together:\n 1. Server-level auto-quarantine for newly added servers (issue #370).\n When true, servers added via the upstream_servers MCP tool or the\n REST API default to quarantined=true; when false, they default to\n quarantined=false. Explicit per-request values always win.\n 2. Tool-level quarantine (Spec 032): per-tool SHA-256 approval of\n tool descriptions/schemas.\nWhen nil (default), quarantine is enabled (secure by default). Set to\nexplicit false to opt out of both. Per-server SkipQuarantine still\napplies for the tool-level check on individual servers.","type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"read_only_mode":{"type":"boolean"},"registries":{"description":"Registries configuration for MCP server discovery","items":{"$ref":"#/components/schemas/config.RegistryEntry"},"type":"array","uniqueItems":false},"registries_locked":{"description":"RegistriesLocked is an enterprise stub knob (MCP-866): when true, runtime\nadditions of custom registries (e.g. ` + "`" + `registry add-source` + "`" + `, the REST/MCP\nadd-source surface) are rejected so an administrator can pin the discovery\nsources. Built-in defaults are unaffected. Documented but otherwise inert\nbeyond the add-source rejection.","type":"boolean"},"require_mcp_auth":{"description":"Require authentication on /mcp endpoint (default: false)","type":"boolean"},"reveal_secret_headers":{"description":"RevealSecretHeaders, when true, disables the redaction of the\nsecret-bearing server fields — sensitive header values (Authorization,\nX-API-Key, Cookie, …), env-var secrets, and URL query credentials — in\nresponses from the ` + "`" + `upstream_servers` + "`" + ` MCP tool, the ` + "`" + `/api/v1/servers` + "`" + `\nREST API, and the SSE event stream. It also lets URL secrets echoed\ninto last_error / health.detail through unscrubbed.\n\nDefault false — sensitive values are surfaced masked as\n` + "`" + `••••\u003clast2\u003e (\u003cN\u003e chars)` + "`" + ` (error strings use ` + "`" + `***REDACTED***` + "`" + `) so an\nMCP agent cannot read Bearer tokens / API keys / URL secrets out of\nanother upstream's config (PR #425, issue #872). ${env:…}/${keyring:…}\nreferences are labels, not secrets, and pass through unchanged.\n\nThe Web UI / macOS tray edit forms work without seeing the real\nvalues: PATCH /api/v1/servers/{id} deep-merges (omitted keys are\npreserved, see ` + "`" + `headers_remove` + "`" + ` / ` + "`" + `env_remove` + "`" + ` for explicit\ndeletes), so clients compute a diff and only send the keys that\nactually changed. Redacted-but-unchanged values never round-trip\n— the backend keeps the real string. Set this to true if a\ndownstream tool genuinely needs raw values in the response.","type":"boolean"},"routing_mode":{"description":"Routing mode (Spec 031): how MCP tools are exposed to clients\nValid values: \"retrieve_tools\" (default), \"direct\", \"code_execution\"","type":"string"},"security":{"$ref":"#/components/schemas/config.SecurityConfig"},"sensitive_data_detection":{"$ref":"#/components/schemas/config.SensitiveDataDetectionConfig"},"server_concurrency_defaults":{"$ref":"#/components/schemas/config.ConcurrencyDefaults"},"session_retention_days":{"description":"SessionRetentionDays is how long a work session is listed and kept whole\nin the activity log (Spec 124, default 7). Read at start.","type":"integer"},"telemetry":{"$ref":"#/components/schemas/config.TelemetryConfig"},"tls":{"$ref":"#/components/schemas/config.TLSConfig"},"tokenizer":{"$ref":"#/components/schemas/config.TokenizerConfig"},"tool_call_max_records_per_server":{"description":"Calls retained per server (default: 1000)","type":"integer"},"tool_call_max_response_size":{"description":"Bounds for the per-server tool-call history behind GET /api/v1/tool-calls\n(#1176). It is a recent-debugging window, not an audit log — the activity\nlog is the durable record — and it kept every upstream response whole,\nper server, forever. A non-positive value means \"use the default\", not\n\"disable\": this store must never be unbounded again, so there is\ndeliberately no off switch.","type":"integer"},"tool_discovery_interval":{"type":"string"},"tool_response_limit":{"type":"integer"},"tool_response_mode":{"description":"Tool response mode (Spec 085): how retrieve_tools serializes results.\nValid values: \"\" (= full), \"full\" (default: today's schema-bearing\nentries), \"compact\" (signature + first-sentence entries). Orthogonal to\nrouting_mode — routing_mode selects the tool SURFACE, this selects the\nSERIALIZATION within the retrieve_tools surface. Serialization-only: it\nnever affects the query, ranking, or result set. Hot-reloadable.","type":"string"},"tool_response_session_risk_warning":{"description":"ToolResponseSessionRiskWarning controls whether the prose ` + "`" + `warning` + "`" + ` field\nis included in the ` + "`" + `session_risk` + "`" + ` object returned by ` + "`" + `retrieve_tools` + "`" + `.\nThe structured fields (level, lethal_trifecta, has_open_world_tools, etc.)\nare always included. Default: false (quiet for LLM clients) — see issue #406.\nMost tools lack annotations, so the MCP-spec defaults treat them as fully\npermissive across all three risk axes, which makes the prose warning fire\non almost every call and wastes tokens.","type":"boolean"},"tools_limit":{"type":"integer"},"toon_min_savings_pct":{"description":"ToonMinSavingsPct is the minimum byte-savings percentage (validated\n1-90; 0/unset → 15) the complete TOON emission (marker + hint + body)\nmust achieve over the exact passthrough emission for adaptive mode to\nencode a block. Byte savings approximate token savings for the tabular\npayload class; the spec-083 profiler reports true token deltas.\nGlobal-only (no per-server override, FR-001).","type":"integer"},"toon_output":{"description":"ToonOutput selects the TOON encoding mode for call_tool_* result text\nblocks (spec 084): \"off\" (default — responses byte-identical to\npre-feature behavior), \"adaptive\" (encode only tabular-uniform payloads\nthat beat compact JSON by ToonMinSavingsPct), or \"always\"\n(benchmark/debug only — encodes every JSON-parseable block and can\nINCREASE token cost). Per-server override: ServerConfig.ToonOutput.\nResolved by ResolveToonOutput; hot-reloadable.","type":"string"},"top_k":{"description":"Deprecated: TopK is superseded by ToolsLimit and has no runtime effect. Kept for backward compatibility.","type":"integer"},"tray_endpoint":{"description":"Tray endpoint override (unix:// or npipe://)","type":"string"},"trusted_hosts":{"description":"TrustedHosts lists non-loopback Host header values accepted on loopback\nlisteners (GH #898). DNS-rebinding protection rejects requests whose Host\nheader is not a loopback address when mcpproxy listens on loopback; a\nreverse proxy (nginx → 127.0.0.1) forwarding the public domain in Host\ntrips it. Entries are hostnames, case-insensitive; an entry without a\nport matches any port, with a port it must match exactly; a leading dot\n(\".example.com\") is a subdomain wildcard. The single entry \"*\" disables\nHost and Origin validation entirely. The same list also validates the\nOrigin header when present (MCP spec DNS-rebinding defense). Empty\n(default) keeps full protection. Env override: MCPPROXY_TRUSTED_HOSTS\n(comma-separated).","items":{"type":"string"},"type":"array","uniqueItems":false},"trusted_proxies":{"description":"TrustedProxies lists the CIDRs or IP addresses whose X-Forwarded-For /\nX-Real-IP / X-Forwarded-Proto / X-Forwarded-Host headers are believed\n(Spec 107 FR-027). Empty (default) trusts nobody. Edition-neutral, live\n(hot-reloadable). Env override: MCPPROXY_TRUSTED_PROXIES (comma-separated).\nThe one reader is ForwardedHeaders; validation is validateTrustedProxies.","items":{"type":"string"},"type":"array","uniqueItems":false},"update_check":{"$ref":"#/components/schemas/config.UpdateCheckConfig"}},"type":"object"},"config.CustomPattern":{"properties":{"category":{"description":"Category (defaults to \"custom\")","type":"string"},"keywords":{"description":"Keywords to match (mutually exclusive with Regex)","items":{"type":"string"},"type":"array","uniqueItems":false},"name":{"description":"Unique identifier for this pattern","type":"string"},"regex":{"description":"Regex pattern (mutually exclusive with Keywords)","type":"string"},"severity":{"description":"Risk level: critical, high, medium, low","type":"string"}},"type":"object"},"config.DeepScanConfig":{"description":"DeepScan is the opt-in \"deep scan\" layer (Spec 077 US3). It subsumes the\ndeprecated top-level scanner_fetch_package_source / scanner_disable_no_new_privileges\nkeys (migrated on load) and gates the heavy Docker-based scanners + source\nextraction. Disabled by default (FR-006): only the deterministic in-process\nbaseline scanner runs. A deep-scan failure NEVER changes the baseline verdict\n(FR-007/FR-008).","properties":{"disable_no_new_privileges":{"description":"DisableNoNewPrivileges, when true, omits the ` + "`" + `--security-opt\nno-new-privileges` + "`" + ` flag from scanner container runs (snap-docker/AppArmor\nescape hatch). Absorbs the deprecated top-level\nscanner_disable_no_new_privileges. Default false.","type":"boolean"},"enabled":{"description":"Enabled is the master opt-in for the heavy layer (FR-006). Default false.","type":"boolean"},"fetch_package_source":{"description":"FetchPackageSource controls whether the scanner fetches the PUBLISHED\nsource of package-runner servers (npx/uvx) — without executing it — when\nno local source is available. Absorbs the deprecated top-level\nscanner_fetch_package_source. Default (nil) is ENABLED within deep scan.","type":"boolean"},"scanners":{"description":"Scanners optionally restricts which deep scanners may run under the\numbrella (by scanner id). Empty ⇒ all enabled deep scanners are eligible.","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"config.DockerIsolationConfig":{"description":"Docker isolation settings","properties":{"cpu_limit":{"description":"CPU limit for containers","type":"string"},"default_images":{"additionalProperties":{"type":"string"},"description":"Map of runtime type to Docker image","type":"object"},"enable_cache_volume":{"description":"Mount shared cache volumes for faster restarts (default: true)","type":"boolean"},"enabled":{"description":"Global enable/disable for Docker isolation (legacy; superseded by Mode)","type":"boolean"},"extra_args":{"description":"Additional docker run arguments","items":{"type":"string"},"type":"array","uniqueItems":false},"log_driver":{"description":"Docker log driver (default: json-file)","type":"string"},"log_max_files":{"description":"Maximum number of log files (default: 3)","type":"string"},"log_max_size":{"description":"Maximum size of log files (default: 100m)","type":"string"},"memory_limit":{"description":"Memory limit for containers","type":"string"},"mode":{"description":"Isolation mode: \"docker\" | \"sandbox\" | \"none\" (MCP-34.2). Unset per-server inherits the global mode; unset globally falls back to the legacy \"enabled\" flag (true ⇒ docker, false ⇒ none)","type":"string","x-enum-varnames":["IsolationModeDocker","IsolationModeSandbox","IsolationModeNone"]},"network_mode":{"description":"Docker network mode (default: bridge)","type":"string"},"registry":{"description":"Custom registry (defaults to docker.io)","type":"string"},"timeout":{"description":"Container startup timeout","type":"string"}},"type":"object"},"config.DockerRecoveryConfig":{"description":"Docker recovery settings","properties":{"enabled":{"description":"Enable Docker recovery monitoring (default: true)","type":"boolean"},"max_retries":{"description":"Maximum retry attempts (0 = unlimited)","type":"integer"},"notify_on_failure":{"description":"Show notification on recovery failure (default: true)","type":"boolean"},"notify_on_retry":{"description":"Show notification on each retry (default: false)","type":"boolean"},"notify_on_start":{"description":"Show notification when recovery starts (default: true)","type":"boolean"},"notify_on_success":{"description":"Show notification on successful recovery (default: true)","type":"boolean"},"persistent_state":{"description":"Save recovery state across restarts (default: true)","type":"boolean"}},"type":"object"},"config.FeatureFlags":{"description":"Deprecated: Features flags are unused and have no runtime effect. Kept for backward compatibility.","properties":{"enable_async_storage":{"type":"boolean"},"enable_caching":{"type":"boolean"},"enable_contract_tests":{"type":"boolean"},"enable_debug_logging":{"description":"Development features","type":"boolean"},"enable_docker_isolation":{"type":"boolean"},"enable_event_bus":{"type":"boolean"},"enable_health_checks":{"type":"boolean"},"enable_metrics":{"type":"boolean"},"enable_oauth":{"description":"Security features","type":"boolean"},"enable_observability":{"description":"Observability features","type":"boolean"},"enable_quarantine":{"type":"boolean"},"enable_runtime":{"description":"Runtime features","type":"boolean"},"enable_search":{"description":"Storage features","type":"boolean"},"enable_sse":{"type":"boolean"},"enable_tracing":{"type":"boolean"},"enable_tray":{"type":"boolean"},"enable_web_ui":{"description":"UI features","type":"boolean"}},"type":"object"},"config.IntentDeclarationConfig":{"description":"Intent declaration settings (Spec 018)","properties":{"strict_server_validation":{"description":"StrictServerValidation controls whether server annotation mismatches\ncause rejection (true) or just warnings (false).\nDefault: true (reject mismatches)","type":"boolean"}},"type":"object"},"config.IsolationConfig":{"description":"Per-server isolation settings","properties":{"enabled":{"description":"Enable Docker isolation for this server (nil = inherit global; legacy, superseded by Mode)","type":"boolean"},"extra_args":{"description":"Additional docker run arguments for this server","items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"description":"Custom Docker image (overrides default)","type":"string"},"log_driver":{"description":"Docker log driver override for this server","type":"string"},"log_max_files":{"description":"Maximum number of log files override","type":"string"},"log_max_size":{"description":"Maximum size of log files override","type":"string"},"mode":{"$ref":"#/components/schemas/config.IsolationMode"},"network_mode":{"description":"Custom network mode for this server","type":"string"},"working_dir":{"description":"Custom working directory in container","type":"string"}},"type":"object"},"config.IsolationMode":{"description":"Isolation mode: \"docker\" | \"sandbox\" | \"none\" (MCP-34.2). Unset per-server inherits the global mode; unset globally falls back to the legacy \"enabled\" flag (true ⇒ docker, false ⇒ none)","type":"string","x-enum-varnames":["IsolationModeDocker","IsolationModeSandbox","IsolationModeNone"]},"config.LogConfig":{"description":"Logging configuration","properties":{"compress":{"type":"boolean"},"enable_console":{"type":"boolean"},"enable_file":{"type":"boolean"},"filename":{"type":"string"},"json_format":{"type":"boolean"},"level":{"type":"string"},"log_dir":{"description":"Custom log directory","type":"string"},"max_age":{"description":"days","type":"integer"},"max_backups":{"description":"number of backup files","type":"integer"},"max_size":{"description":"MB","type":"integer"}},"type":"object"},"config.MetricsExporterConfig":{"description":"Metrics gates the Prometheus /metrics scrape endpoint (MCP-32). Disabled\nby default — operators opt in for k8s/enterprise deployments.","properties":{"enabled":{"description":"Enabled exposes /metrics on the existing HTTP listener when true.\nThe endpoint is admin-authenticated (SEC-07): scrapers must present the\nglobal API key, via X-API-Key or an Authorization: Bearer header.","type":"boolean"}},"type":"object"},"config.OAuthConfig":{"description":"OAuth configuration (keep even when empty to signal OAuth requirement)","properties":{"auth_server_metadata_url":{"type":"string"},"authorization_endpoint":{"description":"Spec 113-b: optional per-server discovery overrides. Each is an absolute\nhttps URL (http only on a loopback host) with no query, fragment or\nuserinfo; validated at write time only (ValidateOAuthEndpointOverrides).\nThe endpoint overrides rewrite the matching fields of the authorization\nserver metadata mcp-go reads; AuthServerMetadataURL replaces discovery.","type":"string"},"callback_base_url":{"type":"string"},"client_id":{"type":"string"},"client_secret":{"type":"string"},"extra_params":{"additionalProperties":{"type":"string"},"description":"Additional OAuth parameters (e.g., RFC 8707 resource)","type":"object"},"pkce_enabled":{"type":"boolean"},"redirect_uri":{"type":"string"},"refresh_replay_enabled":{"description":"Opt in only when token_endpoint supports idempotent refresh replay for at least 30 seconds.","type":"boolean"},"registration_endpoint":{"type":"string"},"scopes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"token_endpoint":{"type":"string"}},"type":"object"},"config.ObservabilityConfig":{"description":"Observability settings (Spec 069): usage aggregate cache/persistence cadence.","properties":{"metrics":{"$ref":"#/components/schemas/config.MetricsExporterConfig"},"tracing":{"$ref":"#/components/schemas/config.TracingExporterConfig"},"usage_cache_ttl":{"description":"UsageCacheTTL bounds the freshness of the usage endpoint's read cache for\nwide windows (FR-005). Default 5s.","type":"string"},"usage_persist_interval":{"description":"UsagePersistInterval is how often the actor-owned usage aggregate snapshot\nis flushed to storage. Default 30s.","type":"string"}},"type":"object"},"config.OutputSanitisationConfig":{"description":"Output sanitisation settings (Spec 054 Track B)","properties":{"max_redactions":{"description":"cap on redactions per response; default 100","type":"integer"},"response_action":{"description":"\"spotlight\" | \"redact\" | \"block\"; default \"spotlight\"","type":"string"},"spotlight_untrusted":{"description":"wrap untrusted output in spotlight markers; default true","type":"boolean"},"strip_classes":{"description":"classes to strip: ansi/c0c1/bidi/zero_width","items":{"type":"string"},"type":"array","uniqueItems":false},"strip_control_chars":{"description":"strip control-character classes; default false","type":"boolean"}},"type":"object"},"config.OutputValidationConfig":{"description":"Output-schema validation settings (Spec 056)","properties":{"max_bytes":{"description":"structured payload byte cap; default 5\u003c\u003c20","type":"integer"},"max_depth":{"description":"nesting depth cap; default 64","type":"integer"},"missing_structured_content":{"description":"\"allow\" | \"block\"; default \"allow\"","type":"string"},"mode":{"description":"\"off\" | \"warn\" | \"strict\"; default \"warn\"","type":"string"}},"type":"object"},"config.ProfileConfig":{"properties":{"code_execution":{"description":"CodeExecution: nil = inherit the global enable_code_execution gate;\nnon-nil narrows it (a profile can only narrow, never widen, FR-006).","type":"boolean"},"description":{"description":"\u003c= 500 chars (FR-001)","type":"string"},"management_tools":{"description":"ManagementTools: nil = legacy/inherit (FR-016); non-nil sets the\nprofile-level visibility of upstream_servers/quarantine_security.","type":"boolean"},"max_tier":{"description":"MaxTier caps the tier a tool may run at under this profile: \"\" (no\ncap) | \"read\" | \"write\" | \"destructive\" (FR-001).","type":"string"},"name":{"description":"slug (Spec 057 rules unchanged)","type":"string"},"servers":{"description":"references to mcpServers[].name","items":{"type":"string"},"type":"array","uniqueItems":false},"switchable_to":{"description":"SwitchableTo is the list of profile names a session under this\nprofile may ` + "`" + `set_profile` + "`" + ` into (FR-022). nil = legacy/none (research\nD6); a non-nil EMPTY list is an explicit \"none\" and must round-trip as\n` + "`" + `[]` + "`" + `, never be dropped by omitempty — hence the pointer (see the\nMarshalJSON note below, and profiles_v3_test.go's switchable_to round\ntrip case).","items":{"type":"string"},"type":"array","uniqueItems":false},"title":{"description":"display only, \u003c= 80 chars (FR-001)","type":"string"},"tools":{"$ref":"#/components/schemas/config.ProfileToolRules"},"unannotated":{"description":"Unannotated is this profile's handling of a tool whose effective\nannotations carry no tier hint: \"\" (unset, see EffectiveUnannotated) |\n\"deny\" | \"as_write\" | \"as_read\" (FR-001, FR-003).","type":"string"}},"type":"object"},"config.ProfileToolRules":{"description":"Tools holds the allow/deny/classify rule set (FR-001, FR-004, FR-005).","properties":{"allow":{"items":{"type":"string"},"type":"array","uniqueItems":false},"classify":{"additionalProperties":{"type":"string"},"type":"object"},"deny":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"config.RegistryEntry":{"properties":{"count":{"description":"number or string","type":"string"},"description":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"},"protocol":{"type":"string"},"provenance":{"description":"Provenance is the trust tag for this registry (MCP-866):\nRegistryProvenanceOfficial for built-in defaults, RegistryProvenanceCustom\nfor user-added registries. It is authoritatively (re)computed by the\nregistries merge from whether the ID is a shipped default — a user cannot\nclaim \"official\" by writing it into their config.","type":"string"},"requires_key":{"description":"RequiresKey marks a registry that needs an API key to be queried. When\ntrue and no key is configured, the registry is skipped/marked unavailable\nrather than failing the whole search (FR-008).","type":"boolean"},"servers_url":{"type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"url":{"type":"string"}},"type":"object"},"config.SecurityConfig":{"description":"Security scanner settings (Spec 039)","properties":{"auto_baseline_scan":{"description":"AutoBaselineScan is the kill-switch for the AUTOMATIC, informational\nPass-1 baseline scan: the free in-process TPA scan mcpproxy runs for every\nnewly admitted server (any trust mode) and, once per installation, over\npre-existing servers that have never been scanned.\n\nInformational ONLY: the resulting verdict populates the security badge and\nthe scan summary, and NEVER gates quarantine or approval. The\ntrust_mode:\"scan\" admission gate is a separate path and is unaffected by\nthis flag.\n\nDefault (nil) is ENABLED. Set to false to suppress every automatic scan\n(manual scans keep working). Env override: MCPPROXY_AUTO_BASELINE_SCAN,\nwhich wins over this field on every path.","type":"boolean"},"auto_rescan_on_change":{"description":"AutoRescanOnChange is the finer switch for the automatic, informational\nrescan that follows a tool-definition hash change: the in-process TPA scan\nof the changed (or newly pending) tool, recorded as hold evidence, and a\ndebounced informational server rescan that brings the review screen's scan\ncoverage back to \"current\".\n\nEvidence and freshness ONLY: this switch approves nothing. Under \"manual\"\nevery change is held for review whatever the verdict (RT-02); under\n\"scan\" the gate's own synchronous scan approves a clean change that\npasses the spec 120 structural gate (spec 119 FR-004), and this switch\ndoes not affect that path. Runs in every trust mode except \"auto\".\n\nDefault (nil) is ENABLED. It only takes effect while auto_baseline_scan is\nalso enabled, so a user can keep the admission scan and turn off per-change\nrescans with this key alone. Env override: MCPPROXY_AUTO_RESCAN_ON_CHANGE,\nwhich wins over this field on every path.","type":"boolean"},"deep_scan":{"$ref":"#/components/schemas/config.DeepScanConfig"},"integrity_check_interval":{"type":"string"},"integrity_check_on_restart":{"type":"boolean"},"require_signed_bundle":{"description":"RequireSignedBundle makes the detached signature sidecar mandatory for\nfile-dropped bundles (FR-007). Default false (maintainer decision D2):\nexisting unsigned drops keep working, but an unsigned external bundle\nalways runs with DEGRADED coverage (scan-mode auto-approval suspended).","type":"boolean"},"runtime_read_only":{"type":"boolean"},"runtime_tmpfs_size":{"type":"string"},"scan_timeout_default":{"type":"string"},"scanner_disable_no_new_privileges":{"description":"Deprecated (Spec 077 US3): migrated on load into DeepScan.DisableNoNewPrivileges\n(see migrateDeepScanConfig). Retained only so existing configs that still carry\nthe top-level key parse; consumers MUST read the effective value via\nSecurityConfig.IsDisableNoNewPrivileges. Cleared after migration.\n\nScannerDisableNoNewPrivileges, when true, omits the\n` + "`" + `--security-opt no-new-privileges` + "`" + ` flag from scanner container runs.\n\nBackground: snap-installed Docker on Ubuntu confines dockerd under the\n` + "`" + `snap.docker.dockerd` + "`" + ` AppArmor profile. When runc tries to transition\nthe container into the inner ` + "`" + `docker-default` + "`" + ` profile to exec the\nentrypoint, AppArmor refuses the transition because NO_NEW_PRIVS\nforbids privilege/profile changes on exec — the result is EPERM\n(\"operation not permitted\") and every scanner fails immediately.\n\nSet this to true ONLY on hosts hitting that incompatibility. Scanner\ncontainers still run with read-only rootfs, tmpfs /tmp, no-network by\ndefault, and read-only source mounts, so the marginal isolation loss\nis small. The preferred fix remains replacing snap docker with a\ndistro-packaged docker.","type":"boolean"},"scanner_fetch_package_source":{"description":"Deprecated (Spec 077 US3): migrated on load into DeepScan.FetchPackageSource\n(see migrateDeepScanConfig). Retained only so existing configs that still carry\nthe top-level key parse; consumers MUST read the effective value via\nSecurityConfig.EffectiveFetchPackageSource. Cleared after migration.\n\nScannerFetchPackageSource controls whether the scanner fetches the\nPUBLISHED source of package-runner servers (npx/uvx) — without executing\nit — when no local source is available (no Docker container, no local\npackage cache, no working_dir). This is the primary quarantine/scan\ntarget: a quarantined-on-add server is never run locally, so without this\nthe scan degrades to tool-definitions-only (no real source-level\nanalysis). See MCP-2206.\n\nFetching uses ` + "`" + `npm pack --ignore-scripts` + "`" + ` (npm) and ` + "`" + `uv pip download` + "`" + ` /\n` + "`" + `pip download` + "`" + ` with ` + "`" + `--only-binary=:all:` + "`" + ` (Python), which only download +\nunpack archives and NEVER run install, build, or setup.py — a scanner must\nnot execute the untrusted code it is scanning. The Python\n` + "`" + `--only-binary=:all:` + "`" + ` flag is required because downloading an sdist would\ninvoke its build backend (setup.py); packages with no wheel fall back to\ntool-definitions-only instead. Extraction is hardened against path\ntraversal and decompression bombs.\n\nDefault (nil) is ENABLED. Set to false on air-gapped deployments to\nforbid the scanner's network egress; such servers then fall back to the\ntool-definitions-only scan with no regression.","type":"boolean"},"scanner_registry_url":{"type":"string"},"tpa_active_root":{"description":"TPAActiveRoot declares which signing authority's bundles may activate\n(FR-004b): \"publisher\" (default, the keys embedded in this binary) or\n\"operator\" (TPAOperatorSigners). A bundle verified by the other root is\nrefused as authority_not_active, so whoever can write the bundle path\ncannot choose the authority.","type":"string"},"tpa_bundle_path":{"description":"TPABundlePath is the filesystem path to the tpa-db scanner-bundle.json\nthe offline TPA scanner runs (spec 086 FR-019: the signature-DB location\nMUST be configuration-driven, not hardcoded). Empty (the default) runs the\ncorpus embedded in this build.\n\nEnv override: MCPPROXY_TPA_BUNDLE_PATH. Hot-reloadable — the path is\nre-read on every config.reloaded event via\nscanner.Service.ApplySecurityConfig, so a corpus refresh needs no restart.\nA configured bundle that fails to read/parse/version-check/compile is\nREFUSED and the previously active corpus stays live (fail-closed, never\nfail-empty); the reason is logged and surfaced in the security overview's\nsignature_bundle.load_error.","type":"string"},"tpa_fetch_enabled":{"description":"TPAFetchEnabled opts in to the network fetch leg. Default false; the\nenvironment override is MCPPROXY_TPA_FETCH_ENABLED (EnvTPAFetchEnabled).","type":"boolean"},"tpa_fetch_url":{"description":"TPAFetchURL is the channel URL: a GitHub Releases \"latest\" API URL or a\ndirect bundle URL. Empty (the default) means the fetch leg is off; no URL\nis compiled into the binary.","type":"string"},"tpa_operator_baseline":{"description":"TPAOperatorBaseline seeds the operator authority's anti-downgrade\nwatermark (FR-009b): an operator-signed bundle must carry a sequence\nABOVE it (a rollback target may sit at it). It survives a data-directory\nwipe because it lives here. Absent means the operator authority has no\nanti-downgrade floor and an active operator bundle runs DEGRADED.","type":"integer"},"tpa_operator_epoch":{"description":"TPAOperatorEpoch is the operator authority's trust epoch (FR-005a).\nBumping it (after an operator key compromise) re-baselines the operator\nwatermark and retires prior-epoch pins. Absent means 0.","type":"integer"},"tpa_operator_signers":{"description":"TPAOperatorSigners lists operator Ed25519 public keys, each the standard\nbase64 encoding of the 32 raw key bytes (FR-004). Their key ids are the\nlowercase-hex SHA-256 of those bytes. Malformed or duplicate entries are\nrejected on write and dropped (with a log) on load.","items":{"type":"string"},"type":"array","uniqueItems":false},"tpa_refresh_interval":{"description":"TPARefreshInterval is the cadence of the refresh cycle (the network-free\nfile leg, then the optional fetch leg). Absent or 0 means 24h; the runtime\nclamps to at least 1h. There is no refresh-enable key: the file leg is\nidempotent and always on.","type":"string"},"tpa_stale_after_days":{"description":"TPAStaleAfterDays is the age in days after which the active bundle reads\nas stale. Absent means 30; an explicit 0 disables the stale flag and the\ndoctor stale warning.","type":"integer"}},"type":"object"},"config.SensitiveDataDetectionConfig":{"description":"Sensitive data detection settings (Spec 026)","properties":{"categories":{"additionalProperties":{"type":"boolean"},"description":"Enable/disable specific detection categories","type":"object"},"custom_patterns":{"description":"User-defined detection patterns","items":{"$ref":"#/components/schemas/config.CustomPattern"},"type":"array","uniqueItems":false},"enabled":{"description":"Enable sensitive data detection (default: true)","type":"boolean"},"entropy_threshold":{"description":"Shannon entropy threshold for high-entropy detection (default: 4.5)","type":"number"},"max_payload_size_kb":{"description":"Max size to scan before truncating (default: 1024)","type":"integer"},"scan_requests":{"description":"Scan tool call arguments (default: true)","type":"boolean"},"scan_responses":{"description":"Scan tool responses (default: true)","type":"boolean"},"sensitive_keywords":{"description":"Keywords to flag","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"config.ServerConfig":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges is the per-server intent to auto-approve tool\nchanges/additions (disabling per-server rug-pull protection). Supersedes\nskip_quarantine. MCP-2930 only ACCEPTS, persists, and migrates this flag — it\nis NOT yet consulted at runtime; auto-approval is still governed by\nSkipQuarantine until the trust-baseline behavior change (MCP-2931) migrates the\nruntime consumers onto it.\nTri-state pointer (mirrors QuarantineEnabled): nil = unset (inherit/migrate\nfrom legacy skip_quarantine), explicit true/false = honored as-is so an\nexplicit auto_approve_tool_changes:false overrides a legacy skip_quarantine:true.\nRead via IsAutoApproveToolChanges().","type":"boolean"},"command":{"type":"string"},"created":{"type":"string"},"disabled_tools":{"description":"Denylist: these tools are hidden; mutually exclusive with enabled_tools","items":{"type":"string"},"type":"array","uniqueItems":false},"enabled":{"type":"boolean"},"enabled_tools":{"description":"Allowlist: only these tools are exposed; mutually exclusive with disabled_tools","items":{"type":"string"},"type":"array","uniqueItems":false},"env":{"additionalProperties":{"type":"string"},"type":"object"},"expose_prompts":{"description":"ExposePrompts overrides whether this server's advertised MCP prompts are\naggregated into mcpproxy's prompts/list. nil (default) inherits the\ndefault-aggregate behavior (included if the server advertises\nCapabilities.Prompts); false excludes it regardless of capability.","type":"boolean"},"expose_skills":{"description":"ExposeSkills overrides whether this server's skills (MCP skills\nextension) are read when Config.EnableSkills is on. nil (default)\ninherits (included if the server supports skills); false excludes it.","type":"boolean"},"forward_headers":{"description":"ForwardHeaders lists inbound MCP-client header NAMES (never values) that\nare copied into this server's upstream tools/call requests (Spec 112).\nExact names, case-insensitive, at most 32, no wildcards. Empty forwards\nnothing. Only HTTP-based transports (http, streamable-http) forward; the\ndeny list (Authorization, Host, hop-by-hop, ...) is enforced at runtime\nregardless of what is configured here.","items":{"type":"string"},"type":"array","uniqueItems":false},"headers":{"additionalProperties":{"type":"string"},"description":"For HTTP servers","type":"object"},"health_check_interval":{"description":"Per-server discovery \u0026 health-check overrides (spec 074). Same *Duration\ntri-state as the global keys: nil = inherit the global value (or default),\npointer to 0s = disabled for this server, positive = that interval.\nHealthCheckInterval is fully wired into the per-server health loop;\nToolDiscoveryInterval is accepted/validated and round-trips for\nforward-compat, but the periodic index sweep is governed by the global\ncadence in this iteration (see spec 074 plan §C).","type":"string"},"init_timeout":{"description":"InitTimeout overrides the global init_timeout for this server's MCP\n` + "`" + `initialize` + "`" + ` handshake deadline (MCP-3322 / GH #760). *Duration tri-state:\nnil = inherit the global value (or 30s default), positive = that deadline.\nResolved by Config.ResolveInitTimeout; validated to {0} ∪ [1s, 30m]. Raise\nthis for upstreams that do legitimate first-run warmup (e.g. caching many\nchannels/users) before responding to ` + "`" + `initialize` + "`" + `.","type":"string"},"isolation":{"$ref":"#/components/schemas/config.IsolationConfig"},"launcher_wait_timeout":{"description":"LauncherWaitTimeout caps how long mcpproxy will wait for a locally-launched\nHTTP/SSE upstream's URL to become reachable after Spawn(). Only consulted\nwhen the server is configured with both Command and an HTTP/SSE URL — i.e.,\nmcpproxy starts the process AND connects via network. Stdio servers ignore\nthis field. Zero or unset → 30s default.","type":"string"},"max_concurrent_requests":{"description":"Per-server concurrency overrides — scope (c) of FR-020 (spec 093, #955).\nTri-state per setting, exactly like HealthCheckInterval: absent = inherit\nthe per-server default set (server_concurrency_defaults), explicit 0 =\ndisable that setting for this server (0 max = no per-server limiter at\nall; 0 queue_size = no pending capacity, shed immediately at the cap),\npositive = override. The global aggregate limiter is never inherited from\nhere — it applies on top, so effective concurrency is min(per-server,\nglobal). Resolved by Config.ResolveServerConcurrency.","type":"integer"},"name":{"type":"string"},"oauth":{"$ref":"#/components/schemas/config.OAuthConfig"},"protocol":{"description":"stdio, http, sse, streamable-http, auto","type":"string"},"quarantined":{"description":"Security quarantine status","type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_on_use":{"description":"Attempt reconnection when a tool call targets a disconnected server","type":"boolean"},"shared":{"description":"Server edition: shared with all users","type":"boolean"},"skip_quarantine":{"description":"SkipQuarantine is DEPRECATED (MCP-2930): use AutoApproveToolChanges instead.\nKept for back-compat parsing; on config load a legacy skip_quarantine:true is\nmigrated to auto_approve_tool_changes:true only when the new field is unset\n(see normalizeServerQuarantineFlags).","type":"boolean"},"source_registry_id":{"description":"SourceRegistryID records which registry this server was added from (empty\nfor manually-configured servers). MCP-866: surfaced in the approval /\nquarantine view so a reviewer can see a server's origin.","type":"string"},"source_registry_provenance":{"description":"SourceRegistryProvenance records the source registry's provenance at add\ntime (RegistryProvenanceOfficial / RegistryProvenanceCustom). It is purely\ninformational (MCP-1072) — surfaced so a reviewer can see a server's origin\n— and no longer gates quarantine or skip_quarantine.","type":"string"},"tool_argument_error_mode":{"description":"ToolArgumentErrorMode stores the per-upstream argument-error policy.\nEmpty and detailed retain detailed errors; redacted opts into redaction.\nUpdates omit/keep an empty value; detailed explicitly resets the policy.","type":"string"},"tool_discovery_interval":{"type":"string"},"toon_output":{"description":"ToonOutput overrides the global toon_output mode for this server's\ntools (spec 084, FR-001). Plain string, not a pointer: \"\"/absent =\ninherit the global value; \"off\"|\"adaptive\"|\"always\" = override (\"off\"\nis the explicit force-off). Resolved by Config.ResolveToonOutput.","type":"string"},"trust_mode":{"description":"TrustMode is the per-server trust tier: auto|scan|manual. Supersedes\nauto_approve_tool_changes (spec 086). An empty value is derived from the\nlegacy fields at load via normalizeServerQuarantineFlags; the single\nresolution point is EffectiveTrustMode(), which treats an empty value as\nscan (DefaultTrustMode, spec 119) and an unrecognized value as manual\n(fail closed). Read via\nEffectiveTrustMode(), never the raw string.","type":"string"},"updated":{"type":"string"},"url":{"type":"string"},"working_dir":{"description":"Working directory for stdio servers","type":"string"}},"type":"object"},"config.TLSConfig":{"description":"TLS configuration","properties":{"cert_file":{"description":"CertFile is the absolute path of an operator-provided server certificate\n(PEM, leaf first), served instead of a generated one. Needs KeyFile.","type":"string"},"certs_dir":{"description":"Directory for certificates","type":"string"},"enabled":{"description":"Enable HTTPS","type":"boolean"},"extra_sans":{"description":"ExtraSANs are DNS names and IP addresses added to the generated server\ncertificate, which is signed by the same local CA. Not used with CertFile.","items":{"type":"string"},"type":"array","uniqueItems":false},"hsts":{"description":"Enable HTTP Strict Transport Security","type":"boolean"},"key_file":{"description":"KeyFile is the absolute path of the private key for CertFile (PEM).","type":"string"},"require_client_cert":{"description":"Enable mTLS","type":"boolean"}},"type":"object"},"config.TelemetryConfig":{"description":"Telemetry settings (Spec 036)","properties":{"anonymous_id":{"description":"Auto-generated UUIDv4","type":"string"},"anonymous_id_created_at":{"description":"Spec 042 (Tier 2) additions — all default-zero, all backwards-compatible.","type":"string"},"enabled":{"description":"Default: true (opt-out)","type":"boolean"},"endpoint":{"description":"Override for testing","type":"string"},"last_reported_version":{"description":"Upgrade funnel","type":"string"},"last_startup_outcome":{"description":"success|port_conflict|db_locked|...","type":"string"},"notice_shown":{"description":"First-run notice flag","type":"boolean"}},"type":"object"},"config.TokenizerConfig":{"description":"Tokenizer configuration for token counting","properties":{"default_model":{"description":"Default model for tokenization (e.g., \"gpt-4\")","type":"string"},"enabled":{"description":"Enable token counting","type":"boolean"},"encoding":{"description":"Default encoding (e.g., \"cl100k_base\")","type":"string"}},"type":"object"},"config.TracingExporterConfig":{"description":"Tracing gates the OpenTelemetry OTLP trace exporter (MCP-32). Disabled by\ndefault.","properties":{"enabled":{"description":"Enabled turns on OTLP trace export for tool calls and upstream hops.","type":"boolean"},"endpoint":{"description":"Endpoint is the collector address as host:port (no scheme), e.g.\n\"localhost:4318\" for http or \"localhost:4317\" for grpc.","type":"string"},"protocol":{"description":"Protocol selects the OTLP transport: \"http\" or \"grpc\".","type":"string"},"sample_rate":{"description":"SampleRate is the head-based trace sampling ratio in [0,1]. Default 0.1.\nOmit the key for the 0.1 default; set it to 0 to sample nothing.","type":"number"}},"type":"object"},"config.UpdateCheckConfig":{"description":"Update-check settings (Spec 079 FR-012): config-file control of the\nbackground upgrade-awareness checker (internal/updatecheck). nil =\nenabled on the stable channel (existing default behavior). The existing\nenvironment switches keep working and WIN over these keys (FR-014):\nMCPPROXY_DISABLE_AUTO_UPDATE=true force-disables even when\nenabled=true, and MCPPROXY_ALLOW_PRERELEASE_UPDATES=true force-selects\nthe rc channel even when channel=stable.","properties":{"channel":{"description":"Channel selects which releases are offered as updates: \"stable\"\n(default; prereleases never offered) or \"rc\" (prereleases included).\nEmpty resolves to stable. Validated in ValidateDetailed.\n\nNOTE: for a RELEASED build the running binary's own version is\nauthoritative and overrides this field — a stable build is never\noffered an RC (even with channel=rc), and an RC build always tracks the\nrc channel. This field only takes effect on dev/unstamped builds. See\ninternal/updatecheck.Checker.IncludePrereleases.","type":"string"},"enabled":{"description":"Enabled gates all update checking. Tri-state: nil/absent = enabled\n(default true, matching pre-079 behavior). When false, no network\ncheck is performed and no upgrade nudge appears on any surface\n(FR-015) — /api/v1/info omits the update object entirely.","type":"boolean"}},"type":"object"},"configimport.FailedServer":{"properties":{"details":{"type":"string"},"error":{"type":"string"},"name":{"type":"string"}},"type":"object"},"configimport.ImportSummary":{"properties":{"failed":{"type":"integer"},"imported":{"type":"integer"},"skipped":{"type":"integer"},"total":{"type":"integer"}},"type":"object"},"configimport.SkippedServer":{"properties":{"name":{"type":"string"},"reason":{"description":"\"already_exists\", \"filtered_out\", \"invalid_name\", \"self_reference\"","type":"string"}},"type":"object"},"connect.ConnectResult":{"description":"The full result; its action mirrors the top-level one","properties":{"action":{"description":"\"created\", \"updated\", \"already_exists\", \"removed\", \"not_found\"","type":"string"},"backup_path":{"type":"string"},"client":{"type":"string"},"config_path":{"type":"string"},"credential":{"description":"Credential is the masked client credential the write embedded\n(` + "`" + `mcp_cli_••••` + "`" + `); the real secret is never returned (FR-024). Empty for a\nkeyless entry, a disconnect and every refusal.","type":"string"},"credential_revoke_error":{"description":"CredentialRevokeError is set when a disconnect removed the entry but\nrevoking the client credential failed. The disconnect still succeeded;\nthe credential is still active and ` + "`" + `mcpproxy client forget \u003cid\u003e` + "`" + `\nretries the revoke.","type":"string"},"credential_revoked":{"description":"CredentialRevoked names the credential that was revoked: by an undo,\nbecause the restored config no longer holds it (plan D16), or by a\ndisconnect, which cuts the client off (a later undo of that disconnect\ndoes not bring the credential back).","type":"string"},"display_path":{"description":"DisplayPath is ConfigPath with the home directory shortened to \"~\"\n(FR-037). Populated for every result whose ConfigPath is known.","type":"string"},"keyless":{"description":"Keyless is true when the entry was written with no credential.","type":"boolean"},"message":{"type":"string"},"mode":{"type":"string"},"profile":{"description":"Profile and Mode are the binding of the credential this write minted or\nkept. Profile \"\" means the built-in All servers scope.","type":"string"},"reload_hint":{"description":"ReloadHint is this client's instruction for making the write take\neffect (FR-037/FR-042), e.g. \"Restart Cursor to load MCPProxy\". Empty\nfor an unknown client.","type":"string"},"rotation":{"description":"Rotation is \"finalized\" when the write replaced an active credential's\nsecret (staged rotation, FR-021a), empty otherwise.","type":"string"},"server_name":{"type":"string"},"success":{"type":"boolean"},"token_name":{"description":"TokenName is the client credential's token name (` + "`" + `client-\u003cid\u003e` + "`" + `).","type":"string"}},"type":"object"},"contracts.APIResponse":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.ActivityDetailResponse":{"properties":{"activity":{"$ref":"#/components/schemas/contracts.ActivityRecord"}},"type":"object"},"contracts.ActivityListResponse":{"properties":{"activities":{"items":{"$ref":"#/components/schemas/contracts.ActivityRecord"},"type":"array","uniqueItems":false},"limit":{"type":"integer"},"offset":{"type":"integer"},"total":{"type":"integer"}},"type":"object"},"contracts.ActivityPerServer":{"properties":{"calls":{"description":"Calls counted per storage.CountsAsCall","type":"integer"},"errors":{"description":"Of those calls, how many failed","type":"integer"},"last_call_at":{"description":"LastCallAt is RFC3339, or \"\" if the server had no call in the period\n(PerServer only lists servers that did, so this is always set).","type":"string"},"name":{"description":"Server name","type":"string"}},"type":"object"},"contracts.ActivityRecord":{"description":"Activity is the stored row; absent on a session_start or session_end\nrow.","properties":{"agent_name":{"description":"Agent token name when auth_type is \"agent\"","type":"string"},"arguments":{"description":"Tool call arguments","type":"object"},"auth_type":{"description":"\"admin\", \"agent\", \"user\" or \"admin_user\"; empty without an auth context or on another caller's row for a scoped caller","type":"string"},"block_reason":{"description":"Typed cause of a profile policy refusal","type":"string"},"client_id":{"description":"Client id from the client-credential binding","type":"string"},"client_name":{"description":"Self-reported clientInfo.name (advisory)","type":"string"},"detection_types":{"description":"List of detection types found","items":{"type":"string"},"type":"array","uniqueItems":false},"duration_ms":{"description":"Execution duration in milliseconds","type":"integer"},"error_class":{"description":"Call-error taxonomy (Spec 113-c FR-045): what failed and whose fault it\nis. Absent on success and on records written before Spec 113.","type":"string"},"error_message":{"description":"Error details if status is \"error\"","type":"string"},"fault_domain":{"description":"upstream|proxy|client","type":"string"},"has_sensitive_data":{"description":"Sensitive data detection fields (Spec 026)","type":"boolean"},"id":{"description":"Unique identifier (ULID format)","type":"string"},"max_severity":{"description":"Highest severity level detected (critical, high, medium, low)","type":"string"},"metadata":{"description":"Additional context-specific data","type":"object"},"parent_id":{"description":"Correlation id of the parent call (the code_execution whose sandbox issued this sub-call)","type":"string"},"profile":{"description":"Scope attribution (Spec 108 FR-029): the profile, client and token in\neffect when the call ran. Stamped at write time, never rewritten. For a\nscoped (non-admin) caller the profile/profile_source/client_id/token_name\nof a row it did not make are blanked (binding disclosure is admin-only);\nclient_name is self-reported and stays. Absent on records written before\nSpec 108 and on records with no MCP/REST request context.","type":"string"},"profile_source":{"description":"pin|binding|url|session|anonymous|none","type":"string"},"request_bytes":{"description":"Byte sizes measured pre-truncation, mirroring storage.ActivityRecord\n(Spec 069 A1). They are the only cost signal a bodies-off export carries:\nwith payloads suppressed there is no text left to measure, so a consumer\naccounting for a record it cannot read has nothing else to go on. They are\nbyte LENGTHS, not token counts — the basis for an explicit estimate, never\na measured figure (spec 103, contracts/replay-input.md).\n\nZero means UNKNOWN, not free: legacy records predate the measurement and\ncode-execution sub-calls record both as zero. Hence omitempty — an absent\nkey tells a consumer to fall to exclusion accounting, whereas a present\nzero would read as a costless call and silently understate the workload.","type":"integer"},"request_id":{"description":"HTTP request ID for correlation","type":"string"},"response":{"description":"Tool response (potentially truncated)","type":"string"},"response_bytes":{"description":"Raw upstream response size in bytes before truncation","type":"integer"},"response_truncated":{"description":"True if response was truncated","type":"boolean"},"server_name":{"description":"Name of upstream MCP server","type":"string"},"session_id":{"description":"MCP transport session ID (regenerated on every reconnect)","type":"string"},"source":{"$ref":"#/components/schemas/contracts.ActivitySource"},"status":{"description":"Result status: \"success\", \"error\", \"blocked\", \"rejected\"","type":"string"},"timestamp":{"description":"When activity occurred","type":"string"},"token_name":{"description":"Agent/client token name","type":"string"},"tool_name":{"description":"Name of tool called","type":"string"},"type":{"$ref":"#/components/schemas/contracts.ActivityType"},"upstream_http_status":{"description":"Upstream HTTP status when known","type":"integer"},"work_session_id":{"description":"Spec 082: one client, one project, across reconnects","type":"string"}},"type":"object"},"contracts.ActivityRetentionReport":{"description":"ActivityRetention (Spec 124 FR-035) reports whether the activity caps\nhold the whole work-session retention window. Administrators only.","properties":{"cause":{"description":"Cause is age_cap, record_cap or size_cap.","type":"string"},"observed_at":{"description":"ObservedAt is when the shortfall was last observed.","type":"string"},"oldest_complete_session_at":{"description":"OldestCompleteSessionAt is the start of the oldest session that still\nhas all of its rows: complete history reaches back to here.","type":"string"},"raise":{"description":"Raise names the settings to raise for the cause.","items":{"type":"string"},"type":"array","uniqueItems":false},"shortfall":{"description":"Shortfall is true when a work session inside the window lost rows\nbecause a cap was reached, and a full window has not passed since.","type":"boolean"},"window_days":{"description":"WindowDays is the work-session retention window.","type":"integer"}},"type":"object"},"contracts.ActivitySource":{"description":"How activity was triggered: \"mcp\", \"cli\", \"api\"","type":"string","x-enum-varnames":["ActivitySourceMCP","ActivitySourceCLI","ActivitySourceAPI"]},"contracts.ActivitySummaryResponse":{"properties":{"blocked_count":{"description":"Count of blocked activities","type":"integer"},"call_count":{"description":"CallCount is how many of those records are CALLS THE USER MADE, as\ndefined once in storage.CountsAsCall and shared with the usage aggregate\nbehind the Usage tab (audit finding F1, #1046). TotalCount answers \"how\nmany rows does the Activity Log have\"; CallCount answers \"how many calls\nwere there\". They are different questions — quarantine auto-approvals,\nsystem start, security scans and management chatter are events, not calls\n— and printing either one under the other's label is how the same instance\ncame to report 51 calls on one screen and 19 on another.","type":"integer"},"call_error_count":{"description":"CallErrorCount is the failures within CallCount, so an error RATE computed\nfrom this response has one denominator. It is not ErrorCount: a policy\nblock is a failed call but carries status \"blocked\", and a shed call is an\nerror in neither sense because it never ran.","type":"integer"},"end_time":{"description":"End of the period (RFC3339)","type":"string"},"error_count":{"description":"Count of error activities","type":"integer"},"other_count":{"description":"OtherCount is every record whose status is outside the four-value\nvocabulary above, so that\n\n\tsuccess + error + blocked + rejected + other == total\n\nholds by construction. The status field is a CLOSED vocabulary for tool\ncalls, but the activity log is wider than tool calls: a quarantine change\nstores its ACTION there (\"approved\", \"auto_approved\"), a policy decision\nstores its DECISION (\"allow\"). Those rows were counted in the total and in\nnone of the four buckets, so the Activity Log's own status tiles summed to\nless than the denominator printed beside them — 15+4+0+0 under a \"42\"\n(audit finding F2, #1046). The residual now has a name and a tile.","type":"integer"},"per_server":{"description":"PerServer covers EVERY server with at least one call in the period\n(unlike TopServers, which is capped at 5 and carries no error counts).\nSpec 109 FR-013: the server-card stats line and the macOS Servers rows\nread this — one ` + "`" + `GET /activity/summary` + "`" + ` response per page load — rather\nthan issuing a per-server activity query each. Computed in the same\ncounting pass as the totals above, from the same CountsAsCall/\nIsManagementBuiltin definitions TopServers already uses.","items":{"$ref":"#/components/schemas/contracts.ActivityPerServer"},"type":"array","uniqueItems":false},"period":{"description":"Time period (1h, 24h, 7d, 30d)","type":"string"},"rejected_count":{"description":"RejectedCount is the number of calls shed by a concurrency limiter, or\nrefused because an agent token was over its call budget, before they\nreached an upstream (spec 093, issue #1699). Counted separately from\nerrors: it is proxy backpressure, not an upstream fault, and it is the\nsignal an operator right-sizes max_concurrent_requests and the rate\nlimits against.","type":"integer"},"start_time":{"description":"Start of the period (RFC3339)","type":"string"},"success_count":{"description":"Count of successful activities","type":"integer"},"top_servers":{"description":"Top servers by activity count","items":{"$ref":"#/components/schemas/contracts.ActivityTopServer"},"type":"array","uniqueItems":false},"top_tools":{"description":"Top tools by activity count","items":{"$ref":"#/components/schemas/contracts.ActivityTopTool"},"type":"array","uniqueItems":false},"total_count":{"description":"Total activity count","type":"integer"}},"type":"object"},"contracts.ActivityTopServer":{"properties":{"count":{"description":"Activity count","type":"integer"},"name":{"description":"Server name","type":"string"}},"type":"object"},"contracts.ActivityTopTool":{"properties":{"count":{"description":"Activity count","type":"integer"},"server":{"description":"Server name","type":"string"},"tool":{"description":"Tool name","type":"string"}},"type":"object"},"contracts.ActivityType":{"description":"Type of activity","type":"string","x-enum-varnames":["ActivityTypeToolCall","ActivityTypePolicyDecision","ActivityTypeQuarantineChange","ActivityTypeServerChange"]},"contracts.AddFromRegistryRequest":{"properties":{"enabled":{"description":"defaults to true when nil","type":"boolean"},"env":{"additionalProperties":{"type":"string"},"description":"overrides + required-input values","type":"object"},"name":{"description":"optional name override","type":"string"}},"type":"object"},"contracts.AddRegistrySourceRequest":{"properties":{"id":{"description":"derived from the host when empty","type":"string"},"name":{"description":"defaults to the id","type":"string"},"protocol":{"description":"defaults to modelcontextprotocol/registry","type":"string"},"url":{"description":"required https registry URL","type":"string"}},"type":"object"},"contracts.AttentionFix":{"properties":{"label":{"type":"string"},"target":{"type":"string"},"verb":{"type":"string"}},"type":"object"},"contracts.AttentionItem":{"properties":{"detail":{"type":"string"},"fix":{"$ref":"#/components/schemas/contracts.AttentionFix"},"id":{"description":"kind:type:subject[:state]","type":"string"},"kind":{"type":"string"},"rank":{"type":"integer"},"since":{"type":"string"},"subject":{"$ref":"#/components/schemas/contracts.AttentionSubject"},"summary":{"type":"string"}},"type":"object"},"contracts.AttentionSubject":{"properties":{"id":{"type":"string"},"name":{"type":"string"},"type":{"description":"server|tool|client|setting","type":"string"}},"type":"object"},"contracts.ConfigApplyResult":{"properties":{"applied_immediately":{"type":"boolean"},"changed_fields":{"items":{"type":"string"},"type":"array","uniqueItems":false},"requires_restart":{"type":"boolean"},"restart_reason":{"type":"string"},"success":{"type":"boolean"},"validation_errors":{"items":{"$ref":"#/components/schemas/contracts.ValidationError"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.DCRStatus":{"properties":{"attempted":{"type":"boolean"},"error":{"type":"string"},"status_code":{"type":"integer"},"success":{"type":"boolean"}},"type":"object"},"contracts.DeepScanDescriptor":{"description":"DeepScan reports the opt-in \"deep scan\" layer status (Spec 077 US3),\nSEPARATELY from the baseline verdict above. Always emitted on a computed\nsummary — when deep scan is off (the default) it reports enabled=false\nplus any enabled-but-skipped Docker scanners. It never influences Status.","properties":{"available":{"type":"boolean"},"enabled":{"type":"boolean"},"ran":{"type":"boolean"},"scanners_failed":{"items":{"$ref":"#/components/schemas/contracts.DeepScanScannerFailure"},"type":"array","uniqueItems":false},"skipped_scanners":{"description":"SkippedScanners lists Docker scanners the user enabled that are skipped\nbecause security.deep_scan.enabled is false (informational).","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.DeepScanScannerFailure":{"properties":{"id":{"type":"string"},"reason":{"type":"string"}},"type":"object"},"contracts.DeprecatedConfigWarning":{"properties":{"field":{"type":"string"},"message":{"type":"string"},"replacement":{"type":"string"}},"type":"object"},"contracts.Diagnostic":{"description":"Spec 044 — structured diagnostic error and stable error code. Both\nare populated when the server is in a failed state and the error\nhas been classified by internal/diagnostics. Healthy servers omit\nthese fields.","properties":{"cause":{"type":"string"},"code":{"type":"string"},"detected_at":{"type":"string"},"docs_url":{"type":"string"},"fix_steps":{"items":{"$ref":"#/components/schemas/contracts.DiagnosticFixStep"},"type":"array","uniqueItems":false},"severity":{"type":"string"},"user_message":{"type":"string"}},"type":"object"},"contracts.DiagnosticFixStep":{"properties":{"command":{"type":"string"},"destructive":{"type":"boolean"},"fixer_key":{"type":"string"},"label":{"type":"string"},"type":{"type":"string"},"url":{"type":"string"}},"type":"object"},"contracts.Diagnostics":{"properties":{"activity_retention":{"$ref":"#/components/schemas/contracts.ActivityRetentionReport"},"deprecated_configs":{"description":"Deprecated config fields found","items":{"$ref":"#/components/schemas/contracts.DeprecatedConfigWarning"},"type":"array","uniqueItems":false},"docker_status":{"$ref":"#/components/schemas/contracts.DockerStatus"},"missing_secrets":{"description":"Renamed to avoid conflict","items":{"$ref":"#/components/schemas/contracts.MissingSecretInfo"},"type":"array","uniqueItems":false},"oauth_issues":{"description":"OAuth parameter mismatches","items":{"$ref":"#/components/schemas/contracts.OAuthIssue"},"type":"array","uniqueItems":false},"oauth_required":{"items":{"$ref":"#/components/schemas/contracts.OAuthRequirement"},"type":"array","uniqueItems":false},"oauth_token_storage":{"$ref":"#/components/schemas/contracts.OAuthTokenStorageReport"},"runtime_warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false},"timestamp":{"type":"string"},"total_issues":{"type":"integer"},"upstream_errors":{"items":{"$ref":"#/components/schemas/contracts.UpstreamError"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.DockerStatus":{"properties":{"available":{"type":"boolean"},"error":{"type":"string"},"version":{"type":"string"}},"type":"object"},"contracts.EditRegistrySourceRequest":{"properties":{"name":{"description":"new display name","type":"string"},"servers_url":{"description":"explicit servers-collection URL","type":"string"},"url":{"description":"new base/servers https URL","type":"string"}},"type":"object"},"contracts.ErrorResponse":{"properties":{"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.FindingCounts":{"properties":{"dangerous":{"description":"Tool poisoning, active prompt injection","type":"integer"},"info":{"description":"Low-severity CVEs, informational","type":"integer"},"total":{"type":"integer"},"warning":{"description":"Rug pull, supply chain CVEs with exploits","type":"integer"}},"type":"object"},"contracts.GetConfigResponse":{"properties":{"config":{"description":"The configuration object","type":"object"},"config_path":{"description":"Path to config file","type":"string"}},"type":"object"},"contracts.GetRegistriesResponse":{"properties":{"registries":{"items":{"$ref":"#/components/schemas/contracts.Registry"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GetServerLogsResponse":{"properties":{"count":{"type":"integer"},"logs":{"items":{"$ref":"#/components/schemas/contracts.LogEntry"},"type":"array","uniqueItems":false},"server_name":{"type":"string"}},"type":"object"},"contracts.GetServerToolCallsResponse":{"properties":{"server_name":{"type":"string"},"tool_calls":{"items":{"$ref":"#/components/schemas/contracts.ToolCallRecord"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GetServerToolsResponse":{"properties":{"count":{"type":"integer"},"incarnation":{"description":"Incarnation is the committed incarnation of the server the tools were\nread for (Spec 116 FR-017), captured before they were fetched; omitted\nwhen unknown.","type":"integer"},"server_name":{"type":"string"},"tools":{"items":{"$ref":"#/components/schemas/contracts.Tool"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.GetServersResponse":{"properties":{"servers":{"items":{"$ref":"#/components/schemas/contracts.Server"},"type":"array","uniqueItems":false},"stats":{"$ref":"#/components/schemas/contracts.ServerStats"}},"type":"object"},"contracts.GetSessionDetailResponse":{"properties":{"session":{"$ref":"#/components/schemas/contracts.MCPSession"}},"type":"object"},"contracts.GetSessionsResponse":{"properties":{"limit":{"type":"integer"},"offset":{"type":"integer"},"sessions":{"items":{"$ref":"#/components/schemas/contracts.MCPSession"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GetToolCallDetailResponse":{"properties":{"tool_call":{"$ref":"#/components/schemas/contracts.ToolCallRecord"}},"type":"object"},"contracts.GetToolCallsResponse":{"properties":{"limit":{"type":"integer"},"offset":{"type":"integer"},"tool_calls":{"items":{"$ref":"#/components/schemas/contracts.ToolCallRecord"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GlobalToolsResponse":{"properties":{"counts":{"$ref":"#/components/schemas/contracts.ViewAsCounts"},"failed_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"partial":{"type":"boolean"},"stats":{"$ref":"#/components/schemas/contracts.GlobalToolsStats"},"tools":{"items":{"$ref":"#/components/schemas/contracts.Tool"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.GlobalToolsStats":{"properties":{"disabled":{"type":"integer"},"enabled":{"type":"integer"},"pending_approval":{"type":"integer"},"total":{"type":"integer"}},"type":"object"},"contracts.HealthStatus":{"description":"Unified health status calculated by the backend","properties":{"action":{"description":"Action is the suggested fix action: \"login\", \"restart\", \"enable\", \"approve\", \"view_logs\", \"set_secret\", \"configure\", \"edit_url\", or \"\" (none)\nInvariant: Action always equals Actions[0], or \"\" when Actions is empty.","type":"string"},"actions":{"description":"Actions lists every applicable next step in priority order (FR-012):\nlogin \u003e set_secret \u003e configure \u003e edit_url \u003e approve \u003e restart \u003e\nview_logs \u003e enable. Always non-nil (empty slice, never null).","items":{"type":"string"},"type":"array","uniqueItems":false},"admin_state":{"description":"AdminState indicates the admin state: \"enabled\", \"disabled\", or \"quarantined\"","type":"string"},"detail":{"description":"Detail is an optional longer explanation of the status","type":"string"},"level":{"description":"Level indicates the health level: \"healthy\", \"degraded\", or \"unhealthy\"","type":"string"},"status":{"description":"Status is the ONE status vocabulary rendered as text on every surface\n(Web UI, macOS, tray, CLI) — Spec 109 FR-010/FR-011. Values: \"ready\",\n\"connecting\", \"sign_in_required\", \"needs_review\", \"needs_secret\",\n\"needs_config\", \"error\", \"disabled\". Unlike Level (a severity signal for\nbadge/tray coloring only), no renderer may print Level as text.","type":"string"},"summary":{"description":"Summary is a human-readable status message (e.g., \"Connected (5 tools)\")","type":"string"},"usable":{"description":"Usable reports whether the server can currently serve tool calls. True\nonly when Status == \"ready\".","type":"boolean"}},"type":"object"},"contracts.InfoEndpoints":{"description":"Available API endpoints","properties":{"http":{"description":"HTTP endpoint address (e.g., \"127.0.0.1:8080\")","type":"string"},"socket":{"description":"Unix socket path (empty if disabled)","type":"string"}},"type":"object"},"contracts.InfoResponse":{"properties":{"endpoints":{"$ref":"#/components/schemas/contracts.InfoEndpoints"},"launched_by":{"description":"LaunchedBy is the durable launch provenance of the running core (Spec\n092 FR-001a): \"tray\" when a tray spawned it, \"installer\" when the macOS\nPKG postinstall did, \"\" when user-launched or unknown. Always present\n(possibly empty) so a tray can distinguish \"old core, not mine\" from\n\"old core I may supersede\".","type":"string"},"listen_addr":{"description":"Listen address (e.g., \"127.0.0.1:8080\")","type":"string"},"pid":{"description":"PID is the operating-system process id of the running core (Spec 092\nFR-002). A tray that merely ATTACHED to a core holds no Process handle\nfor it, so without this there is no mechanism at all to stop a stale\ncore — the consent action would have nothing to act on and could only\nprint instructions. Paired with LaunchedBy it is what lets a newer tray\nsupersede a core an older tray started.","type":"integer"},"update":{"$ref":"#/components/schemas/contracts.UpdateInfo"},"update_policy":{"$ref":"#/components/schemas/contracts.UpdatePolicy"},"version":{"description":"Current MCPProxy version","type":"string"},"web_ui_url":{"description":"URL to access the web control panel","type":"string"}},"type":"object"},"contracts.IsolationConfig":{"properties":{"cpu_limit":{"type":"string"},"enabled":{"description":"Enabled is the EFFECTIVE isolation state for this server: whether its\nprocess is actually CONFINED, after the global setting, the per-server\noverride, the structural gates and the host's capabilities. It is NOT the\nraw per-server override — read EnabledOverride for that (GH #1142).\n\nREAD-ONLY. The write surfaces reject an ` + "`" + `enabled` + "`" + ` key precisely because\nit is derived: echoing it back would convert \"inherits the global\nsetting\" into a permanent explicit override. Write EnabledOverride.\n\nIt stays a non-pointer bool that is always present on the wire: the macOS\ntray decodes it as a non-optional Swift Bool, so omitting or nulling the\nkey would fail Codable for the whole server payload. Older clients that\nread this field now simply get a true answer.","type":"boolean"},"enabled_override":{"description":"EnabledOverride is the RAW per-server ` + "`" + `isolation.enabled` + "`" + ` override, as\npersisted. Absent means \"inherit the global setting\" — which is a\ndistinct state from an explicit false, and the distinction the reporting\nbug used to destroy.","type":"boolean"},"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"memory_limit":{"type":"string"},"mode_override":{"description":"ModeOverride is the RAW per-server ` + "`" + `isolation.mode` + "`" + ` override\n(\"docker\" | \"sandbox\" | \"none\"). Absent means \"inherit\".","type":"string"},"network_mode":{"type":"string"},"timeout":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"contracts.IsolationDefaults":{"description":"IsolationDefaults exposes the resolved baseline values that\nwould apply when no per-server override is set. Populated on\nlist/get responses; never consumed on PATCH requests.","properties":{"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"network_mode":{"type":"string"},"runtime_type":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"contracts.IsolationEffective":{"description":"IsolationEffective exposes the resolved isolation state (and the rule\nthat decided it) so clients can distinguish \"inherits global\" from an\nexplicit per-server choice. Read-only; never consumed on PATCH.","properties":{"global_mode":{"description":"GlobalMode is what \"inherit\" resolves to right now.","type":"string"},"inherited":{"description":"Inherited is true when the server sets neither ` + "`" + `isolation.enabled` + "`" + ` nor\n` + "`" + `isolation.mode` + "`" + `, so its state tracks the global setting.","type":"boolean"},"isolated":{"description":"Isolated reports whether the process is actually CONFINED. It is NOT\nsimply Mode != \"none\": \"sandbox\" on a host that cannot enforce Landlock\n(any non-Linux OS, or a kernel without the LSM) runs the server\nunconfined, and Source then says \"sandbox-unavailable\" (GH #1142).","type":"boolean"},"mode":{"description":"Mode is the effective isolation mode: \"docker\" | \"sandbox\" | \"none\" —\nexactly what the spawn path branches on.","type":"string"},"source":{"description":"Source names the deciding rule: \"global\", \"server-mode\",\n\"server-opt-out\", \"server-opt-in-ignored\", \"not-stdio\",\n\"already-docker\", \"sandbox-unavailable\" or \"unsupported-mode\".\nTreat an unrecognized value as \"global\".","type":"string"}},"type":"object"},"contracts.LogEntry":{"properties":{"fields":{"type":"object"},"level":{"type":"string"},"message":{"type":"string"},"server":{"type":"string"},"timestamp":{"type":"string"}},"type":"object"},"contracts.MCPSession":{"properties":{"client_id":{"description":"Scope attribution (Spec 108 FR-033). ClientID and TokenName are the\ncredential the session initialized with; Profile and ProfileSource are\nthe session's latest effective resolution. Empty on legacy sessions.","type":"string"},"client_name":{"type":"string"},"client_version":{"type":"string"},"end_time":{"type":"string"},"experimental":{"items":{"type":"string"},"type":"array","uniqueItems":false},"has_roots":{"description":"MCP Client Capabilities","type":"boolean"},"has_sampling":{"type":"boolean"},"id":{"type":"string"},"last_activity":{"type":"string"},"profile":{"type":"string"},"profile_source":{"type":"string"},"start_time":{"type":"string"},"status":{"type":"string"},"token_name":{"type":"string"},"tool_call_count":{"type":"integer"},"total_tokens":{"type":"integer"},"work_session_id":{"type":"string"},"workspace_name":{"description":"Workspace / work session (Spec 082). WorkspaceName is the project's\nbasename — the full local path is never exposed. WorkSessionID groups the\nreconnects that make up one stretch of user work.","type":"string"}},"type":"object"},"contracts.MetadataStatus":{"properties":{"authorization_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"error":{"type":"string"},"found":{"type":"boolean"},"url_checked":{"type":"string"}},"type":"object"},"contracts.MissingSecretInfo":{"properties":{"secret_name":{"type":"string"},"used_by":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.NPMPackageInfo":{"properties":{"exists":{"type":"boolean"},"install_cmd":{"type":"string"}},"type":"object"},"contracts.OAuthConfig":{"properties":{"auth_server_metadata_url":{"type":"string"},"auth_url":{"type":"string"},"authorization_endpoint":{"description":"Spec 113-b operator overrides of OAuth discovery (https-or-loopback URLs,\nnever credentials). Empty means \"use discovery\".","type":"string"},"client_id":{"type":"string"},"extra_params":{"additionalProperties":{"type":"string"},"type":"object"},"pkce_enabled":{"type":"boolean"},"redirect_port":{"type":"integer"},"refresh_replay_enabled":{"type":"boolean"},"registration_endpoint":{"type":"string"},"scopes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"token_endpoint":{"type":"string"},"token_expires_at":{"description":"When the OAuth token expires","type":"string"},"token_url":{"type":"string"},"token_valid":{"description":"Whether token is currently valid","type":"boolean"}},"type":"object"},"contracts.OAuthErrorDetails":{"description":"Structured discovery/failure details","properties":{"authorization_server_metadata":{"$ref":"#/components/schemas/contracts.MetadataStatus"},"dcr_status":{"$ref":"#/components/schemas/contracts.DCRStatus"},"protected_resource_metadata":{"$ref":"#/components/schemas/contracts.MetadataStatus"},"server_url":{"type":"string"}},"type":"object"},"contracts.OAuthFlowError":{"properties":{"correlation_id":{"description":"Flow tracking ID for log correlation","type":"string"},"debug_hint":{"description":"CLI command for log lookup","type":"string"},"details":{"$ref":"#/components/schemas/contracts.OAuthErrorDetails"},"error_code":{"description":"Machine-readable error code (e.g., OAUTH_NO_METADATA)","type":"string"},"error_type":{"description":"Category of OAuth runtime failure","type":"string"},"message":{"description":"Human-readable error description","type":"string"},"request_id":{"description":"HTTP request ID (from PR #237)","type":"string"},"server_name":{"description":"Server that failed OAuth","type":"string"},"success":{"description":"Always false","type":"boolean"},"suggestion":{"description":"Actionable remediation hint","type":"string"}},"type":"object"},"contracts.OAuthIssue":{"properties":{"documentation_url":{"type":"string"},"error":{"type":"string"},"issue":{"type":"string"},"missing_params":{"items":{"type":"string"},"type":"array","uniqueItems":false},"resolution":{"type":"string"},"server_name":{"type":"string"}},"type":"object"},"contracts.OAuthRequirement":{"properties":{"expires_at":{"type":"string"},"message":{"type":"string"},"server_name":{"type":"string"},"state":{"type":"string"}},"type":"object"},"contracts.OAuthStartResponse":{"properties":{"auth_url":{"description":"Authorization URL (always included for manual use)","type":"string"},"browser_error":{"description":"Error message if browser launch failed","type":"string"},"browser_opened":{"description":"Whether browser launch succeeded","type":"boolean"},"correlation_id":{"description":"UUID for tracking this flow","type":"string"},"message":{"description":"Human-readable status message","type":"string"},"server_name":{"description":"Name of the server being authenticated","type":"string"},"success":{"description":"Always true for successful start","type":"boolean"}},"type":"object"},"contracts.OAuthTokenStorageReport":{"description":"OAuthTokenStorage (Spec 123 FR-030) reports the state of the stored\nupstream OAuth rows: encryption on or off, the public key id, the row\ncounts by state, the undecryptable servers and the compaction advice.\nIt never carries key material or the key reference.","properties":{"compaction_advised":{"description":"CompactionAdvised mirrors the compaction marker: freed pages may still\nhold old plaintext until ` + "`" + `mcpproxy db compact --keep-backup=false` + "`" + `.","type":"boolean"},"encryption_enabled":{"description":"EncryptionEnabled is true when an encryption key is configured.","type":"boolean"},"key_id":{"description":"KeyID is the public, non-secret id of the configured key (administrator only).","type":"string"},"key_source_in_data_dir":{"description":"KeySourceInDataDir is true when the key file lies inside the data directory.","type":"boolean"},"key_source_kind":{"description":"KeySourceKind is how the key was obtained: literal, env, env_file,\nref_file, ref_env or ref_keyring (administrator only).","type":"string"},"plaintext":{"description":"Plaintext counts valid JSON rows; Sealed counts envelopes the configured\nkey opens; Undecryptable counts everything else.","type":"integer"},"sealed":{"type":"integer"},"servers":{"description":"Servers lists the undecryptable rows by server.","items":{"$ref":"#/components/schemas/contracts.OAuthTokenStorageServer"},"type":"array","uniqueItems":false},"undecryptable":{"type":"integer"},"undecryptable_by_reason":{"$ref":"#/components/schemas/contracts.OAuthTokenUndecryptableByReason"},"warnings":{"description":"Warnings are stable codes: literal_key, key_file_in_data_dir,\nplaintext_rows_with_key, compaction_advised, backup_file_present\n(administrator only).","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.OAuthTokenStorageServer":{"properties":{"bucket_key":{"type":"string"},"reason":{"type":"string"},"row_key_id":{"description":"RowKeyID is the key id in the row's envelope (administrator only).","type":"string"},"server":{"type":"string"}},"type":"object"},"contracts.OAuthTokenUndecryptableByReason":{"description":"UndecryptableByReason breaks Undecryptable down by reason.","properties":{"auth_failed":{"type":"integer"},"key_mismatch":{"type":"integer"},"malformed":{"type":"integer"},"no_key":{"type":"integer"},"unsupported_version":{"type":"integer"}},"type":"object"},"contracts.PreflightPolicy":{"properties":{"exclude_destructive":{"type":"boolean"},"exclude_open_world":{"type":"boolean"},"read_only_only":{"type":"boolean"}},"type":"object"},"contracts.PreflightReason":{"type":"string","x-enum-varnames":["PreflightReasonServerInitializing","PreflightReasonServerUnhealthy","PreflightReasonServerDisabled","PreflightReasonServerQuarantined","PreflightReasonToolPendingApproval","PreflightReasonToolChanged","PreflightReasonToolBlockedByUser","PreflightReasonOAuthRequired","PreflightReasonHashMismatch","PreflightReasonServerNotInScope","PreflightReasonToolDeniedByConfig","PreflightReasonMissingAnnotation","PreflightReasonPolicyFiltered","PreflightReasonNotFound","PreflightReasonServerNotConfigured","PreflightReasonToolBlockedByProfile","PreflightReasonTokenPermissionDenied"]},"contracts.PreflightRequest":{"properties":{"policy":{"$ref":"#/components/schemas/contracts.PreflightPolicy"},"profile":{"description":"Profile evaluates under a named profile's server scope and tool policy;\nit can only narrow a credential's own pin. Unknown: 400.","type":"string"},"tools":{"description":"Tools is 1..100 entries BEFORE dedup; duplicates are collapsed, and\nduplicate ids carrying different pins are a validation error.","items":{"$ref":"#/components/schemas/contracts.PreflightToolRef"},"type":"array","uniqueItems":false},"wait_ms":{"description":"WaitMS polls local state for up to this many milliseconds (cap 10000)\nwhile every failure is retryable-class.","type":"integer"}},"type":"object"},"contracts.PreflightResponse":{"properties":{"checked_at":{"type":"string"},"tools":{"description":"Tools are ordered by first occurrence of each unique id in the request.","items":{"$ref":"#/components/schemas/contracts.PreflightToolResult"},"type":"array","uniqueItems":false},"verdict":{"$ref":"#/components/schemas/contracts.PreflightVerdict"},"waited_ms":{"description":"WaitedMS is present when wait_ms was requested (0 when the wait\nsemaphore was exhausted and the request resolved immediately).","type":"integer"}},"type":"object"},"contracts.PreflightStatus":{"type":"string","x-enum-varnames":["PreflightStatusReady","PreflightStatusUnavailable"]},"contracts.PreflightToolRef":{"properties":{"id":{"description":"ID is a canonical \"\u003cserver\u003e:\u003ctool\u003e\" id. A malformed id is answered with a\nper-ID not_found carrying a format hint, never a request-level error.","type":"string"},"pin_hash":{"description":"PinHash is \"sha256/v{N}:{hex}\" — the schema version is embedded so a\nproxy-side hash-algorithm bump is distinguishable from upstream drift.","type":"string"}},"type":"object"},"contracts.PreflightToolResult":{"properties":{"action":{"type":"string"},"detail":{"type":"string"},"did_you_mean":{"description":"DidYouMean carries up to 3 nearest caller-visible ids on not_found. It\nnever crosses a scope boundary and never names a quarantined server's\ntools.","items":{"type":"string"},"type":"array","uniqueItems":false},"hash":{"description":"Hash is the tool's current pin (\"sha256/v{N}:{hex}\") — operator tier,\nready results only. Never disclosed to an agent token.","type":"string"},"id":{"type":"string"},"reason":{"$ref":"#/components/schemas/contracts.PreflightReason"},"remediation":{"type":"string"},"retryable":{"type":"boolean"},"status":{"$ref":"#/components/schemas/contracts.PreflightStatus"}},"type":"object"},"contracts.PreflightVerdict":{"type":"string","x-enum-varnames":["PreflightVerdictReady","PreflightVerdictDegradedRetryable","PreflightVerdictBlocked","PreflightVerdictUnknownIDs"]},"contracts.QuarantineStats":{"description":"Tool quarantine metrics for this server","properties":{"blocked_count":{"description":"Number of disabled (blocked) tools","type":"integer"},"changed_count":{"description":"Number of tools whose description/schema changed since approval","type":"integer"},"pending_count":{"description":"Number of newly discovered tools awaiting approval","type":"integer"}},"type":"object"},"contracts.RefreshRegistryResponse":{"properties":{"cleared":{"description":"number of cached entries dropped","type":"integer"},"registry_id":{"type":"string"}},"type":"object"},"contracts.Registry":{"properties":{"count":{"description":"number or string","type":"string"},"description":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"},"protocol":{"type":"string"},"provenance":{"description":"Provenance is the trust tag (MCP-866): \"official/trusted\" for built-in\ndefaults, \"custom/unverified\" for user-added registries.","type":"string"},"servers_url":{"type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"trusted":{"description":"Trusted indicates whether this is an official, shipped-by-default\nregistry. Trust is derived from membership in the default set, never\nfrom self-assertion in config.","type":"boolean"},"url":{"type":"string"}},"type":"object"},"contracts.RegistryCacheInfo":{"properties":{"age_seconds":{"type":"number"},"stale":{"type":"boolean"}},"type":"object"},"contracts.RegistryUnavailable":{"properties":{"reason":{"type":"string"}},"type":"object"},"contracts.ReplayToolCallRequest":{"properties":{"arguments":{"description":"Modified arguments for replay","type":"object"}},"type":"object"},"contracts.ReplayToolCallResponse":{"properties":{"error":{"description":"Error if replay failed","type":"string"},"new_call_id":{"description":"ID of the newly created call","type":"string"},"new_tool_call":{"$ref":"#/components/schemas/contracts.ToolCallRecord"},"replayed_from":{"description":"Original call ID","type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.RepositoryInfo":{"description":"Detected package info","properties":{"npm":{"$ref":"#/components/schemas/contracts.NPMPackageInfo"}},"type":"object"},"contracts.RepositoryServer":{"properties":{"connect_url":{"description":"Alternative connection URL","type":"string"},"created_at":{"type":"string"},"description":{"type":"string"},"id":{"type":"string"},"install_cmd":{"description":"Installation command","type":"string"},"name":{"type":"string"},"registry":{"description":"Which registry this came from","type":"string"},"repository_info":{"$ref":"#/components/schemas/contracts.RepositoryInfo"},"source_code_url":{"description":"Source repository URL","type":"string"},"updated_at":{"type":"string"},"url":{"description":"MCP endpoint for remote servers only","type":"string"}},"type":"object"},"contracts.SearchRegistryServersResponse":{"properties":{"cache":{"$ref":"#/components/schemas/contracts.RegistryCacheInfo"},"query":{"type":"string"},"registry_id":{"type":"string"},"servers":{"items":{"$ref":"#/components/schemas/contracts.RepositoryServer"},"type":"array","uniqueItems":false},"tag":{"type":"string"},"total":{"type":"integer"},"unavailable":{"$ref":"#/components/schemas/contracts.RegistryUnavailable"}},"type":"object"},"contracts.SearchResult":{"properties":{"matches":{"type":"integer"},"score":{"type":"number"},"snippet":{"type":"string"},"tool":{"$ref":"#/components/schemas/contracts.Tool"}},"type":"object"},"contracts.SearchToolsResponse":{"properties":{"query":{"type":"string"},"results":{"items":{"$ref":"#/components/schemas/contracts.SearchResult"},"type":"array","uniqueItems":false},"took":{"type":"string"},"total":{"type":"integer"}},"type":"object"},"contracts.SecurityScanSummary":{"description":"Latest security scan results summary","properties":{"deep_scan":{"$ref":"#/components/schemas/contracts.DeepScanDescriptor"},"finding_counts":{"$ref":"#/components/schemas/contracts.FindingCounts"},"last_scan_at":{"type":"string"},"risk_score":{"description":"0-100","type":"integer"},"scanners_failed":{"type":"integer"},"scanners_run":{"description":"Scanner coverage for the primary (baseline) scan pass — informational only.\nSpec 077 US3 (FR-008/FR-014): Status is derived SOLELY from the\ndeterministic baseline findings; a failed Docker deep scanner no longer\ndowngrades a clean verdict. That failure is surfaced via DeepScan instead.","type":"integer"},"scanners_total":{"type":"integer"},"status":{"description":"\"clean\", \"warnings\", \"dangerous\", \"failed\", \"not_scanned\", \"scanning\"","type":"string"}},"type":"object"},"contracts.Server":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"authenticated":{"description":"OAuth authentication status","type":"boolean"},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges mirrors config.ServerConfig.AutoApproveToolChanges\n(MCP-2930): the per-server intent to auto-approve new/changed tools past\nthe trust baseline. Tri-state *bool — nil means \"never set\" (omitted from\nthe payload), so the Web UI toggle (MCP-2932) can distinguish unset from\nan explicit false. Read-only on the GET path; PATCH/POST accept it via\nAddServerRequest.","type":"boolean"},"command":{"type":"string"},"connected":{"type":"boolean"},"connected_at":{"type":"string"},"connecting":{"type":"boolean"},"created":{"type":"string"},"diagnostic":{"$ref":"#/components/schemas/contracts.Diagnostic"},"enabled":{"type":"boolean"},"env":{"additionalProperties":{"type":"string"},"type":"object"},"error_code":{"type":"string"},"expose_prompts":{"description":"ExposePrompts mirrors config.ServerConfig.ExposePrompts (F9): the per-server\nprompt-aggregation override. Tri-state *bool — nil/omitted means \"inherit\ndefault aggregation\". Surfaced on GET so a caller that PATCHed the override\ncan read it back; PATCH/POST accept it via AddServerRequest.","type":"boolean"},"expose_skills":{"description":"ExposeSkills mirrors config.ServerConfig.ExposeSkills: the per-server\nskills override. Tri-state *bool; nil/omitted means \"inherit\".","type":"boolean"},"forward_headers":{"description":"ForwardHeaders mirrors config.ServerConfig.ForwardHeaders (Spec 112): the\nallowlist of inbound MCP client header NAMES forwarded to this server on\ntools/call. Names only, never values. Omitted when empty.","items":{"type":"string"},"type":"array","uniqueItems":false},"generation":{"description":"Generation is the server's committed config generation (Spec 116\nFR-017): it changes whenever the server's configuration changes.","type":"integer"},"headers":{"additionalProperties":{"type":"string"},"type":"object"},"health":{"$ref":"#/components/schemas/contracts.HealthStatus"},"id":{"type":"string"},"incarnation":{"description":"Incarnation changes only when the name is removed and created again\n(Spec 116 FR-017). Approval endpoints accept it back as\nexpected_incarnation and answer 409 server_replaced on a mismatch.","type":"integer"},"init_timeout":{"description":"InitTimeout mirrors config.ServerConfig.InitTimeout (MCP-3322 / GH #760):\nthe per-server MCP ` + "`" + `initialize` + "`" + ` handshake deadline override. Serialized as\na duration string (e.g. \"120s\"); nil/omitted means \"inherit the global\ndefault\". Surfaced on the GET path so clients can read back a configured\noverride; PATCH/POST accept it via AddServerRequest.","type":"string"},"isolation":{"$ref":"#/components/schemas/contracts.IsolationConfig"},"isolation_defaults":{"$ref":"#/components/schemas/contracts.IsolationDefaults"},"isolation_effective":{"$ref":"#/components/schemas/contracts.IsolationEffective"},"last_error":{"type":"string"},"last_reconnect_at":{"type":"string"},"last_retry_time":{"type":"string"},"max_concurrent_requests":{"description":"Spec 093 (GH #955) — per-server concurrency overrides, scope (c) of\nFR-020. Each setting is tri-state: nil (omitted) means \"inherit\nserver_concurrency_defaults\", 0 disables that setting for this server,\npositive overrides it. Surfaced on the GET path so a caller can read back\nwhat it set; PATCH/POST accept them via AddServerRequest. The effective\nconcurrency for a server is additionally bounded by the global aggregate\nlimiter, which is NOT an inheritance source for these fields.","type":"integer"},"name":{"type":"string"},"oauth":{"$ref":"#/components/schemas/contracts.OAuthConfig"},"oauth_status":{"description":"OAuth status: \"authenticated\", \"expired\", \"error\", \"none\"","type":"string"},"protocol":{"type":"string"},"quarantine":{"$ref":"#/components/schemas/contracts.QuarantineStats"},"quarantined":{"type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_count":{"type":"integer"},"reconnect_on_use":{"description":"Attempt reconnection when a tool call targets this disconnected server","type":"boolean"},"retry_count":{"type":"integer"},"retry_stopped":{"description":"RetryStopped reports that automatic reconnection has been given up for\ngood because the failure is deterministic and unrecoverable — a missing\nbinary, an image without the interpreter, an unparseable config (GH\n#1145). It is NOT ordinary exponential backoff, which keeps retrying;\nnothing will happen until the user fixes the config or restarts the\nserver. RetryStoppedCode is the stable MCPX_* code that proved it and\nRetryStoppedReason the catalog message explaining how to fix it. All three\nare omitted for servers that are healthy or still retrying.","type":"boolean"},"retry_stopped_code":{"type":"string"},"retry_stopped_reason":{"type":"string"},"security_scan":{"$ref":"#/components/schemas/contracts.SecurityScanSummary"},"should_retry":{"type":"boolean"},"source_registry_id":{"description":"MCP-901 — registry provenance of an upstream that was added from a\nregistry. SourceRegistryID names the source registry (empty for\nmanually-configured servers); SourceRegistryProvenance is the trust tag\nrecorded at add time (\"official/trusted\" or \"custom/unverified\"). Both\nare projected from config.ServerConfig so the approval/quarantine view\ncan render an \"added from \u003cregistry\u003e · unverified\" origin badge. Optional\nand omitted when empty — clients that pre-date this treat them as absent.","type":"string"},"source_registry_provenance":{"type":"string"},"status":{"type":"string"},"token_expires_at":{"description":"When the OAuth token expires (ISO 8601)","type":"string"},"tool_argument_error_mode":{"type":"string"},"tool_count":{"type":"integer"},"tool_list_token_size":{"description":"Token size for this server's tools","type":"integer"},"trust_mode":{"description":"TrustMode mirrors config.ServerConfig.TrustMode (spec 086): the per-server\ntrust tier (\"auto\"/\"scan\"/\"manual\"). Surfaced on the GET path so clients can\nread back the persisted mode; PATCH/POST accept it via AddServerRequest.\nOmitted when empty (server predates the field / relies on legacy flags).","type":"string"},"updated":{"type":"string"},"url":{"type":"string"},"user_logged_out":{"description":"True if user explicitly logged out (prevents auto-reconnection)","type":"boolean"},"working_dir":{"type":"string"}},"type":"object"},"contracts.ServerActionResponse":{"properties":{"action":{"type":"string"},"async":{"type":"boolean"},"server":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.ServerStats":{"properties":{"connected_servers":{"type":"integer"},"docker_containers":{"type":"integer"},"quarantined_servers":{"type":"integer"},"token_metrics":{"$ref":"#/components/schemas/contracts.ServerTokenMetrics"},"total_servers":{"type":"integer"},"total_tools":{"type":"integer"}},"type":"object"},"contracts.ServerTokenMetrics":{"properties":{"average_query_result_size":{"description":"Typical retrieve_tools output (tokens)","type":"integer"},"estimated":{"description":"Estimated (Spec 109-k FR-070-ish, url-filter-contract.md / audit F-Token):\ntrue while AverageQueryResultSize is a synthetic simulation (a sample of\nthe first ` + "`" + `tools_limit` + "`" + ` tools' schemas — no real retrieve_tools call has\ncompleted yet in this runtime's usage aggregate); false once at least one\nreal retrieve_tools call has, at which point AverageQueryResultSize is\nderived from the real observed average response size instead. The Web\nUI and macOS render an \"estimate\" label while this is true.","type":"boolean"},"per_server_tool_list_sizes":{"additionalProperties":{"type":"integer"},"description":"Token size per server","type":"object"},"saved_tokens":{"description":"Difference","type":"integer"},"saved_tokens_percentage":{"description":"Percentage saved","type":"number"},"total_server_tool_list_size":{"description":"All upstream tools combined (tokens)","type":"integer"}},"type":"object"},"contracts.SkillContentResponse":{"properties":{"digest":{"type":"string"},"next_offset":{"description":"NextOffset is the byte offset of the next chunk; absent at the end.","type":"integer"},"offset":{"type":"integer"},"size":{"type":"integer"},"text":{"type":"string"}},"type":"object"},"contracts.SkillEntry":{"properties":{"approved_at":{"description":"ApprovedAt is omitted when the skill was never approved.","type":"string"},"approved_by":{"type":"string"},"approved_files":{"description":"ApprovedFiles is the file set of the approved copy; omitted when the\nskill has no approved copy. ` + "`" + `skills show --diff` + "`" + ` compares it with Files.","items":{"$ref":"#/components/schemas/contracts.SkillFileInfo"},"type":"array","uniqueItems":false},"approved_hash":{"type":"string"},"available":{"type":"boolean"},"blocked":{"type":"boolean"},"current_hash":{"type":"string"},"description":{"type":"string"},"files":{"items":{"$ref":"#/components/schemas/contracts.SkillFileInfo"},"type":"array","uniqueItems":false},"id":{"type":"string"},"listed":{"type":"boolean"},"name":{"type":"string"},"path":{"type":"string"},"scan":{"$ref":"#/components/schemas/contracts.SkillScanInfo"},"status":{"type":"string"},"total_size":{"type":"integer"},"unusable_reason":{"type":"string"},"uri":{"type":"string"}},"type":"object"},"contracts.SkillFileInfo":{"properties":{"digest":{"type":"string"},"path":{"type":"string"},"size":{"type":"integer"},"text":{"type":"boolean"}},"type":"object"},"contracts.SkillScanFinding":{"properties":{"evidence":{"type":"string"},"file":{"type":"string"},"offset":{"type":"integer"},"rule":{"type":"string"},"severity":{"type":"string"}},"type":"object"},"contracts.SkillScanInfo":{"properties":{"complete":{"type":"boolean"},"findings":{"items":{"$ref":"#/components/schemas/contracts.SkillScanFinding"},"type":"array","uniqueItems":false},"findings_truncated":{"description":"FindingsTruncated is true when more findings existed than are listed.","type":"boolean"},"incomplete":{"description":"Incomplete says why Complete is false: size_cap, time_limit, coverage or\ninterrupted; empty when the scan is complete.","type":"string"},"scanned_at":{"description":"ScannedAt is omitted when no scan of the current content exists.","type":"string"},"verdict":{"type":"string"}},"type":"object"},"contracts.SkillsApproveRequest":{"properties":{"expected_hashes":{"additionalProperties":{"type":"string"},"description":"ExpectedHashes maps each skill path to the current_hash the reviewer\nsaw. A skill without an entry is refused as unreviewed.","type":"object"},"expected_incarnation":{"description":"ExpectedIncarnation binds the approval to the server the reviewer saw;\n0 (or absent) binds to the incarnation current when the request starts.","type":"integer"},"skills":{"description":"Skills are skill paths (the part of the id after \"\u003cserver\u003e:\"), 1 to 200.","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.SkillsApproveResponse":{"properties":{"approved":{"description":"Approved counts the skills newly approved; a skill already approved for\nits current content is not counted.","type":"integer"}},"type":"object"},"contracts.SkillsBlockRequest":{"properties":{"expected_incarnation":{"type":"integer"},"skills":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.SkillsBlockResponse":{"properties":{"changed":{"description":"Changed counts the skills whose blocked mark changed.","type":"integer"}},"type":"object"},"contracts.SkillsErrorResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.SkillsListResponse":{"properties":{"enabled":{"type":"boolean"},"error":{"type":"string"},"expose_skills":{"type":"boolean"},"incarnation":{"description":"Incarnation is the server's approval incarnation: send it back as\nexpected_incarnation on approve, block and unblock.","type":"integer"},"last_refresh":{"type":"string"},"server":{"type":"string"},"skills":{"items":{"$ref":"#/components/schemas/contracts.SkillEntry"},"type":"array","uniqueItems":false},"supported":{"type":"boolean"},"truncated":{"type":"boolean"}},"type":"object"},"contracts.SkillsStaleReviewResponse":{"properties":{"changed":{"items":{"type":"string"},"type":"array","uniqueItems":false},"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"},"unreviewed":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.SkillsUnusableResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"skills":{"items":{"type":"string"},"type":"array","uniqueItems":false},"success":{"type":"boolean"}},"type":"object"},"contracts.SuccessResponse":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"success":{"type":"boolean"}},"type":"object"},"contracts.Tier":{"description":"Tier is computed by AnnotationTier (Spec 109 FR-028/X11) from\nAnnotations — read|write|destructive|unannotated. Set by every producer\nof a Tool (enrichServerTools, the global tools handler); never left for\na consuming surface to compute.","type":"string","x-enum-varnames":["TierRead","TierWrite","TierDestructive","TierUnannotated","TierUnknown"]},"contracts.TokenMetrics":{"description":"Token usage metrics (nil for older records)","properties":{"encoding":{"description":"Encoding used (e.g., cl100k_base)","type":"string"},"estimated_cost":{"description":"Optional cost estimate","type":"number"},"input_tokens":{"description":"Tokens in the request","type":"integer"},"model":{"description":"Model used for tokenization","type":"string"},"output_tokens":{"description":"Tokens in the response","type":"integer"},"total_tokens":{"description":"Total tokens (input + output)","type":"integer"},"truncated_tokens":{"description":"Tokens removed by truncation","type":"integer"},"was_truncated":{"description":"Whether response was truncated","type":"boolean"}},"type":"object"},"contracts.Tool":{"properties":{"access":{"$ref":"#/components/schemas/contracts.ToolAccess"},"annotations":{"$ref":"#/components/schemas/contracts.ToolAnnotation"},"approval_status":{"type":"string"},"config_denied":{"description":"ConfigDenied is true when the tool is denied by the server's static\nenabled_tools / disabled_tools config. The user cannot override this toggle.","type":"boolean"},"description":{"type":"string"},"disabled":{"description":"Disabled mirrors ToolApprovalRecord.Disabled so per-tool enable state is\navailable without a second round-trip to the approvals endpoint. Absent\nin the JSON when false (default) to keep responses compact.","type":"boolean"},"hash":{"description":"Hash is the tool's current stored hash rendered in the preflight pin\nformat \"sha256/v{N}:{hex}\" (Spec 098 FR-011), where N is the approval\nrecord's HashSchemaVersion. It is the authoring surface for\n` + "`" + `POST /api/v1/preflight` + "`" + ` pins and ` + "`" + `mcpproxy tools preflight --pin` + "`" + `:\ncopy the value straight into a pin.\n\nDisclosure is OPERATOR TIER ONLY — same rule as the preflight per-tool\nresult. The field is omitted for agent-token callers and for tools with\nno stored hash (no approval record yet, or a record written before\nhashes existed).","type":"string"},"held_reason":{"description":"HeldReason, HeldVerdict and HeldSignals mirror the same-named fields on\nstorage.ToolApprovalRecord: the offline-scan evidence that made\ntrust_mode: scan hold this tool for review (spec 086 FR-018). HeldSignals\nnames the matched deterministic check ids, e.g.\n\"tpa.TPA-2026-0001.hidden_instruction\", so a reviewer can see WHY the tool\nis held. All three are omitted for tools that are not held by the scan gate\n(including every record written before the field existed).","type":"string"},"held_signals":{"items":{"type":"string"},"type":"array","uniqueItems":false},"held_verdict":{"type":"string"},"last_used":{"type":"string"},"name":{"type":"string"},"profile_tier":{"description":"ProfileTier and Access are present only in a view-as listing (a tools\nlisting with ?client= or ?profile=, Spec 108 FR-032). ProfileTier is the\ntool's tier under the viewed subject's profile (Tier above stays the\nintrinsic tier); Access is the subject's verdict for the tool. Absent\notherwise, so an ordinary listing is byte-identical to before.","type":"string","x-enum-varnames":["TierRead","TierWrite","TierDestructive","TierUnannotated","TierUnknown"]},"schema":{"type":"object"},"server_incarnation":{"description":"ServerIncarnation is the committed incarnation of the server this row\nwas read for (Spec 116 FR-017), captured before the tools were fetched.\nA client echoes it as expected_incarnation on a per-tool decision, so a\nstale row is refused (409 server_replaced) after a same-name re-add.\nOmitted when the server has no committed incarnation.","type":"integer"},"server_name":{"type":"string"},"tier":{"$ref":"#/components/schemas/contracts.Tier"},"usage":{"type":"integer"}},"type":"object"},"contracts.ToolAccess":{"properties":{"callable":{"type":"boolean"},"reason":{"type":"string"},"visible":{"type":"boolean"}},"type":"object"},"contracts.ToolAnnotation":{"description":"Tool behavior hints snapshot","properties":{"destructiveHint":{"type":"boolean"},"idempotentHint":{"type":"boolean"},"openWorldHint":{"type":"boolean"},"readOnlyHint":{"type":"boolean"},"title":{"type":"string"}},"type":"object"},"contracts.ToolCallRecord":{"description":"The new tool call record","properties":{"annotations":{"$ref":"#/components/schemas/contracts.ToolAnnotation"},"arguments":{"description":"Tool arguments","type":"object"},"arguments_truncated":{"description":"ArgumentsTruncated marks Arguments as a placeholder rather than the\narguments the tool was called with. Replaying such a record without\nsupplying arguments explicitly is refused.","type":"boolean"},"config_path":{"description":"Active config file path","type":"string"},"duration":{"description":"Duration in nanoseconds","type":"integer"},"error":{"description":"Error message (failure only)","type":"string"},"execution_type":{"description":"\"direct\" or \"code_execution\"","type":"string"},"id":{"description":"Unique identifier","type":"string"},"mcp_client_name":{"description":"MCP client name from InitializeRequest","type":"string"},"mcp_client_version":{"description":"MCP client version","type":"string"},"mcp_session_id":{"description":"MCP session identifier","type":"string"},"metrics":{"$ref":"#/components/schemas/contracts.TokenMetrics"},"parent_call_id":{"description":"Links nested calls to parent code_execution","type":"string"},"request_id":{"description":"Request correlation ID","type":"string"},"response":{"description":"Tool response (success only)","type":"object"},"response_bytes":{"description":"Marshalled response size before truncation","type":"integer"},"response_truncated":{"description":"ResponseTruncated and ResponseBytes describe a STORAGE-side cut (#1176):\nthe caller received the response whole, and only the persisted copy was\nshortened to tool_call_max_response_size. When ResponseTruncated is true\nthe Response object carries {truncated, original_bytes, preview, note}\ninstead of the upstream result, and ResponseBytes is its size before the\ncut.","type":"boolean"},"server_id":{"description":"Server identity hash","type":"string"},"server_name":{"description":"Human-readable server name","type":"string"},"timestamp":{"description":"When the call was made","type":"string"},"tool_name":{"description":"Tool name (without server prefix)","type":"string"}},"type":"object"},"contracts.UpdateInfo":{"description":"Update information (if available)","properties":{"available":{"description":"Whether an update is available","type":"boolean"},"behind_summary":{"description":"Spec 079 FR-002 — how far behind the running build is. All four are\nadditive (FR-021) and absent when the delta could not be resolved, in\nwhich case every surface renders its pre-delta wording.","type":"string"},"check_error":{"description":"Error message if update check failed","type":"string"},"checked_at":{"description":"When the update check was performed","type":"string"},"install_channel":{"description":"Detected install channel (homebrew, dmg, deb, rpm, docker, go-install, windows-installer, tarball, unknown) — Spec 079 FR-008","type":"string"},"is_prerelease":{"description":"Whether the latest version is a prerelease","type":"boolean"},"latest_version":{"description":"Latest version available (e.g., \"v1.2.3\")","type":"string"},"nudges_suppressed":{"description":"UI surfaces must stay quiet (CI / non-interactive context); machine-readable fields still report the facts — Spec 079 FR-019","type":"boolean"},"release_url":{"description":"URL to the release page","type":"string"},"releases_behind":{"description":"Releases on the offered channel between the running and offered versions","type":"integer"},"releases_behind_saturated":{"description":"ReleasesBehind is a lower bound: the running build predates the scanned release window","type":"boolean"},"update_command":{"description":"One-line update command for the channel; only set when an update is available and the channel has one — Spec 079 FR-009","type":"string"},"weeks_behind":{"description":"Whole weeks between the two releases' publish dates; 0 is a real value, absent means unknown","type":"integer"}},"type":"object"},"contracts.UpdatePolicy":{"description":"UpdatePolicy is the effective, hot-reloadable update policy (Spec 092\nFR-015). Always present: the ` + "`" + `update` + "`" + ` object above is omitted both when\nupdate checking is disabled AND when no check has produced a result\nyet, so its absence cannot tell a client whether it is allowed to run\nits own (e.g. Sparkle feed) check. This field states the answer.","properties":{"channel":{"description":"Channel is the tracked release channel: \"stable\" or \"rc\".","type":"string"},"enabled":{"description":"Enabled is the effective automatic-check kill switch: update_check.enabled\nwith MCPPROXY_DISABLE_AUTO_UPDATE=true winning over it. A user-initiated\n\"Check for Updates\" stays available regardless.","type":"boolean"},"nudges_suppressed":{"description":"NudgesSuppressed asks UI surfaces to stay quiet (CI / non-interactive)\nwhile machine-readable fields keep reporting the facts.","type":"boolean"}},"type":"object"},"contracts.UpstreamError":{"properties":{"error_message":{"type":"string"},"server_name":{"type":"string"},"timestamp":{"type":"string"}},"type":"object"},"contracts.UsageAggregateResponse":{"properties":{"freshness_ms":{"description":"age of the underlying snapshot in ms","type":"integer"},"generated_at":{"type":"string"},"other":{"$ref":"#/components/schemas/contracts.UsageOtherBucket"},"timeline":{"items":{"$ref":"#/components/schemas/contracts.UsageTimeBucket"},"type":"array","uniqueItems":false},"token_source":{"description":"\"bytes\" (size-based proxy, FR-006)","type":"string"},"tokens_saved":{"description":"echoed from ServerTokenMetrics (FR-007)","type":"integer"},"tokens_saved_estimated":{"description":"TokensSavedEstimated echoes ServerTokenMetrics.Estimated (Spec 109-k):\ntrue while TokensSaved is a synthetic simulation rather than derived\nfrom a real retrieve_tools call. Dropped (false, the zero value) for a\nscoped caller along with TokensSaved itself, above.","type":"boolean"},"tokens_saved_percentage":{"type":"number"},"tools":{"items":{"$ref":"#/components/schemas/contracts.UsageToolStat"},"type":"array","uniqueItems":false},"total_calls":{"description":"TotalCalls and TotalErrors are the headline counts for the window: the sum\nof the timeline this same response carries, so the tiles and the histogram\nunder them cannot disagree. They are NOT the sum of Tools — that list is\nlifetime-cumulative, upstream-only and truncated to top-N, and summing it\nclient-side is what made the Usage tab print a third number for the same\n24 hours (audit finding F1, #1046). The population is\nstorage.CountsAsCall, shared with ActivitySummaryResponse.CallCount.\n\nTwo bounds on how exactly this matches the Activity Log's own count.\nBoth are bounded and disclosed, unlike the population mismatch they\nreplace, which was unbounded and silent:\n\n - Window granularity is the timeline's: whole hour buckets, so the span\n is the requested window rounded up to a bucket edge.\n - This response is served from a snapshot behind a short read cache\n (observability.usage_cache_ttl, 5s by default) so the endpoint never\n scans the activity log per request, while the summary endpoint counts\n live. Calls that land inside that window appear on the Activity Log\n first. FreshnessMs and GeneratedAt say how old the figures are, and\n the Usage tab prints it (\"Updated 3s ago\").","type":"integer"},"total_errors":{"type":"integer"},"window":{"type":"string"}},"type":"object"},"contracts.UsageOtherBucket":{"description":"present only when the list was truncated to top-N","properties":{"calls":{"type":"integer"},"tools_folded":{"type":"integer"},"total_resp_bytes":{"type":"integer"}},"type":"object"},"contracts.UsageTimeBucket":{"properties":{"calls":{"type":"integer"},"errors":{"type":"integer"},"start":{"type":"string"},"total_resp_bytes":{"type":"integer"}},"type":"object"},"contracts.UsageToolStat":{"properties":{"avg_req_bytes":{"description":"null when no sized request calls","type":"integer"},"avg_resp_bytes":{"description":"null when sized_calls == 0 (only legacy 0-byte calls)","type":"integer"},"blocked":{"type":"integer"},"calls":{"type":"integer"},"error_rate":{"type":"number"},"errors":{"type":"integer"},"last_used":{"type":"string"},"p50_exceeds":{"type":"boolean"},"p50_ms":{"description":"P50Ms and P95Ms are read off a fixed latency histogram, so they are BUCKET\nBOUNDS, not measured durations: the true percentile is at or below the\nvalue, and a client must render it as a bound (\"≤ 5 ms\"). P50Exceeds /\nP95Exceeds flip that reading for the unbounded overflow bucket, where the\nvalue is the last bound and the truth is above it (\"\u003e 10 s\").","type":"integer"},"p95_exceeds":{"type":"boolean"},"p95_ms":{"type":"integer"},"rejected":{"description":"spec 093: shed by a concurrency limit; never executed, so excluded from calls/latency","type":"integer"},"server":{"type":"string"},"sized_calls":{"description":"calls with known response size (basis for avg_resp_bytes)","type":"integer"},"tool":{"type":"string"},"total_req_bytes":{"type":"integer"},"total_resp_bytes":{"type":"integer"}},"type":"object"},"contracts.ValidateConfigResponse":{"properties":{"errors":{"items":{"$ref":"#/components/schemas/contracts.ValidationError"},"type":"array","uniqueItems":false},"valid":{"type":"boolean"}},"type":"object"},"contracts.ValidationError":{"properties":{"field":{"type":"string"},"message":{"type":"string"}},"type":"object"},"contracts.ViewAsCounts":{"description":"Counts is present only for a NON-administrator profile view-as (Spec 108\nFR-032): the response then lists only the visible rows, and this is the\nonly trace of the rest, with no per-server, per-tier or per-reason\nbreakdown.","properties":{"hidden":{"type":"integer"},"visible":{"type":"integer"}},"type":"object"},"contracts.WorkSession":{"properties":{"attempts":{"description":"Attempts, Failures and PolicyBlocks are lifetime counts of the session.\nPolicyBlocks are included in Failures.","type":"integer"},"client_id":{"type":"string"},"client_name":{"type":"string"},"connection_count":{"description":"Administrators only.","type":"integer"},"duration_ms":{"type":"integer"},"ended_at":{"type":"string"},"failures":{"type":"integer"},"first_failure_at":{"type":"string"},"id":{"type":"string"},"last_activity_at":{"type":"string"},"last_failure":{"$ref":"#/components/schemas/contracts.WorkSessionFailure"},"ownerless":{"type":"boolean"},"policy_blocks":{"type":"integer"},"profile":{"description":"Profile is returned to administrators only.","type":"string"},"profile_source":{"type":"string"},"project_name":{"description":"ProjectName is the basename of the client's workspace, when it\ndisclosed one.","type":"string"},"rebuilt":{"type":"boolean"},"run_name":{"type":"string"},"started_at":{"type":"string"},"status":{"description":"Status is \"active\" or \"ended\".","type":"string"},"stored_failures":{"description":"StoredFailures counts the failures whose rows are still in the log;\nit is what the timeline can navigate.","type":"integer"},"surface":{"type":"string"},"token_name":{"type":"string"},"truncated_start_at":{"type":"string"}},"type":"object"},"contracts.WorkSessionEnvelope":{"properties":{"data":{"$ref":"#/components/schemas/contracts.WorkSession"},"success":{"type":"boolean"}},"type":"object"},"contracts.WorkSessionFailure":{"properties":{"at":{"type":"string"},"error_class":{"type":"string"},"error_code":{"type":"string"},"policy_block":{"description":"PolicyBlock is true when the failure was a refusal by MCPProxy itself.","type":"boolean"},"reason":{"description":"Reason is at most 200 characters and never contains argument or\nresponse bodies.","type":"string"},"server":{"type":"string"},"tool":{"type":"string"}},"type":"object"},"contracts.WorkSessionListEnvelope":{"properties":{"data":{"$ref":"#/components/schemas/contracts.WorkSessionListResponse"},"success":{"type":"boolean"}},"type":"object"},"contracts.WorkSessionListResponse":{"properties":{"limit":{"type":"integer"},"offset":{"type":"integer"},"sessions":{"items":{"$ref":"#/components/schemas/contracts.WorkSession"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.WorkSessionTimelineEnvelope":{"properties":{"data":{"$ref":"#/components/schemas/contracts.WorkSessionTimelineResponse"},"success":{"type":"boolean"}},"type":"object"},"contracts.WorkSessionTimelineResponse":{"properties":{"earlier_failures_not_stored":{"type":"boolean"},"failure_index":{"description":"FailureIndex is the 1-based number of the failure at or before the\nposition among the stored failures in reach (0 when none), and\nFailureTotal their count.","type":"integer"},"failure_total":{"type":"integer"},"has_after":{"type":"boolean"},"has_before":{"type":"boolean"},"lifetime_failures":{"description":"LifetimeFailures is the session's lifetime failure count in reach.\nEarlierFailuresNotStored says some of them are no longer in the log.","type":"integer"},"position":{"description":"Position is the index of the row the page is positioned at; TotalRows\nis the number of rows in the caller's view.","type":"integer"},"rows":{"items":{"$ref":"#/components/schemas/contracts.WorkSessionTimelineRow"},"type":"array","uniqueItems":false},"session":{"$ref":"#/components/schemas/contracts.WorkSession"},"total_rows":{"type":"integer"}},"type":"object"},"contracts.WorkSessionTimelineRow":{"properties":{"activity":{"$ref":"#/components/schemas/contracts.ActivityRecord"},"at":{"description":"At is the time of the row.","type":"string"},"bodies_removed":{"description":"BodiesRemoved is true when retention removed the row's argument and\nresponse bodies to keep the row.","type":"boolean"},"failed":{"description":"Failed marks the counted row of a failed attempt; PolicyBlock marks a\nrefusal by MCPProxy itself.","type":"boolean"},"index":{"description":"Index is the row's position in the caller's view of the timeline.","type":"integer"},"kind":{"type":"string"},"policy_block":{"type":"boolean"},"precedes_session":{"description":"PrecedesSession marks an upstream event from before the session\nstarted: the latest event of a server the session then failed on,\nstill unresolved when the session began (release QA F2, SC-005).","type":"boolean"}},"type":"object"},"data":{"properties":{"data":{"$ref":"#/components/schemas/contracts.InfoResponse"}},"type":"object"},"httpapi.AccessExplanationData":{"properties":{"first_failure":{"type":"string","x-enum-varnames":["StepCredential","StepProfile","StepServerInScope","StepToolRule","StepTierCap","StepTokenPermission","StepGlobalGate","StepServerState","StepToolApproval"]},"fixes":{"items":{"$ref":"#/components/schemas/runtime.Fix"},"type":"array","uniqueItems":false},"profile":{"$ref":"#/components/schemas/runtime.ExplainProfileView"},"steps":{"items":{"$ref":"#/components/schemas/runtime.ExplainStepView"},"type":"array","uniqueItems":false},"subject":{"$ref":"#/components/schemas/runtime.ExplainSubjectView"},"tool":{"type":"string"},"verdict":{"$ref":"#/components/schemas/profile.ExplainVerdict"}},"type":"object"},"httpapi.AccessSuggestionsData":{"properties":{"already_fixed":{"description":"AlreadyFixed counts groups the explainer now allows (they drop out).","type":"integer"},"blocked_calls":{"description":"BlockedCalls counts every profile-refused call in the window.","type":"integer"},"non_profile_blocked":{"description":"NonProfileBlocked counts blocked calls with a cause outside profiles.","type":"integer"},"patches":{"items":{"$ref":"#/components/schemas/runtime.ProfilePatch"},"type":"array","uniqueItems":false},"profile_removed":{"description":"ProfileRemoved counts groups whose profile no longer exists (they drop out).","type":"integer"},"since":{"type":"string"},"suggestions":{"items":{"$ref":"#/components/schemas/runtime.AccessSuggestion"},"type":"array","uniqueItems":false},"unattributed":{"description":"Unattributed counts profile refusals whose record names no profile.","type":"integer"},"until":{"type":"string"},"window":{"type":"string"}},"type":"object"},"httpapi.AddServerRequest":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges is the per-server intent to auto-approve\nnew/changed tools past the trust baseline (MCP-2930). Tri-state *bool:\na nil pointer means \"leave unchanged\" on PATCH; a present value\n(including false) is applied. Mirrors config.ServerConfig's *bool\nsemantics — do NOT collapse to a plain bool, or an omitted field would\nsilently reset a previously-set value.","type":"boolean"},"command":{"type":"string"},"enabled":{"type":"boolean"},"env":{"additionalProperties":{"type":"string"},"type":"object"},"expose_prompts":{"description":"ExposePrompts is the per-server override for prompt aggregation (F9):\nwhether this server's advertised MCP prompts are merged into mcpproxy's\nprompts/list. Tri-state *bool mirroring config.ServerConfig.ExposePrompts —\na nil pointer means \"leave unchanged\" on PATCH (and \"inherit the default\naggregate behavior\" on create); a present value (including false) is applied.","type":"boolean"},"expose_skills":{"description":"ExposeSkills is the per-server skills override (MCP skills extension).\nTri-state *bool mirroring config.ServerConfig.ExposeSkills: nil means\n\"leave unchanged\" on PATCH and \"inherit\" on create.","type":"boolean"},"forward_headers":{"description":"ForwardHeaders is the per-server allowlist of inbound MCP client header\nNAMES forwarded to this server on tools/call (Spec 112). Names only, never\nvalues. On PATCH a nil slice (field omitted) leaves the stored allowlist\nunchanged and an empty array ([]) clears it. Invalid, denied, duplicate\nand static-header-colliding names are rejected with 400.","items":{"type":"string"},"type":"array","uniqueItems":false},"headers":{"additionalProperties":{"type":"string"},"type":"object"},"init_timeout":{"description":"InitTimeout is the per-server MCP ` + "`" + `initialize` + "`" + ` handshake deadline override\n(MCP-3322 / GH #760), serialized as a duration string (e.g. \"120s\"). A nil\npointer means \"leave unchanged\" on PATCH; a present value is applied.\nMirrors config.ServerConfig.InitTimeout's *Duration tri-state.","type":"string"},"isolation":{"$ref":"#/components/schemas/httpapi.IsolationRequest"},"max_concurrent_requests":{"description":"MaxConcurrentRequests / QueueSize / QueueTimeout are the per-server\nconcurrency overrides (spec 093 / GH #955, FR-020 scope (c)). Each is\ntri-state: a nil pointer means \"leave unchanged\" on PATCH and \"inherit\nserver_concurrency_defaults\" on create; an explicit 0 disables that\nsetting for this server; a positive value overrides it. Do NOT collapse\nthem to plain values — an omitted field would then silently reset a\nconfigured limit.","type":"integer"},"name":{"type":"string"},"protocol":{"type":"string"},"quarantined":{"type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_on_use":{"type":"boolean"},"tool_argument_error_mode":{"description":"Empty preserves an update; detailed explicitly resets a redacted policy.","type":"string"},"trust_mode":{"description":"TrustMode is the per-server trust tier (spec 086): \"auto\", \"scan\", or\n\"manual\". Empty means \"leave unchanged\" on PATCH (and inherit the migrated\ndefault on create). A non-empty value is applied to ServerConfig.TrustMode\nand resolved by EffectiveTrustMode (an unrecognized value fails closed to\nmanual). This is the REST seam for changing the trust tier via\nPOST/PATCH /api/v1/servers.","type":"string"},"url":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"httpapi.BindingGuardResponse":{"properties":{"bindings":{"items":{"$ref":"#/components/schemas/httpapi.GuardBinding"},"type":"array","uniqueItems":false},"code":{"description":"binding_bypassable_without_auth","type":"string"},"error":{"description":"Human-readable, byte-stable refusal text","type":"string"},"fixes":{"items":{"$ref":"#/components/schemas/httpapi.GuardFixOption"},"type":"array","uniqueItems":false},"request_id":{"type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.BulkAssignRequest":{"properties":{"from_profile":{"type":"string"},"mode":{"type":"string"},"to_profile":{"type":"string"}},"type":"object"},"httpapi.BulkAssignResponse":{"properties":{"moved":{"items":{"type":"string"},"type":"array","uniqueItems":false},"skipped":{"items":{"$ref":"#/components/schemas/httpapi.BulkAssignSkipped"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.BulkAssignSkipped":{"properties":{"client_id":{"type":"string"},"code":{"type":"string"},"error":{"type":"string"}},"type":"object"},"httpapi.BundleRollbackRefusedResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"rejection":{"$ref":"#/components/schemas/scanner.BundleRejection"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"httpapi.CanonicalConfigPath":{"properties":{"description":{"description":"Brief description","type":"string"},"exists":{"description":"Whether the file exists","type":"boolean"},"format":{"description":"Format identifier (e.g., \"claude_desktop\")","type":"string"},"name":{"description":"Display name (e.g., \"Claude Desktop\")","type":"string"},"os":{"description":"Operating system (darwin, windows, linux)","type":"string"},"path":{"description":"Full path to the config file","type":"string"}},"type":"object"},"httpapi.CanonicalConfigPathsResponse":{"properties":{"os":{"description":"Current operating system","type":"string"},"paths":{"description":"List of canonical config paths","items":{"$ref":"#/components/schemas/httpapi.CanonicalConfigPath"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ClientBindingErrorResponse":{"properties":{"code":{"type":"string"},"error":{"type":"string"},"field":{"type":"string"},"request_id":{"type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.ClientBindingResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"warnings":{"items":{"$ref":"#/components/schemas/httpapi.ClientWarning"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ClientSnippet":{"properties":{"generic_http":{"type":"string"},"header_name":{"type":"string"}},"type":"object"},"httpapi.ClientWarning":{"properties":{"action":{"$ref":"#/components/schemas/runtime.WarningAction"},"bindings":{"items":{"$ref":"#/components/schemas/runtime.BindingRef"},"type":"array","uniqueItems":false},"client_id":{"type":"string"},"code":{"$ref":"#/components/schemas/profile.WarningCode"},"fixes":{"items":{"$ref":"#/components/schemas/runtime.GuardFix"},"type":"array","uniqueItems":false},"message":{"type":"string"},"severity":{"$ref":"#/components/schemas/profile.WarningSeverity"}},"type":"object"},"httpapi.ConnectConflictResponse":{"properties":{"action":{"description":"already_exists | precondition_failed","type":"string"},"data":{"$ref":"#/components/schemas/connect.ConnectResult"},"error":{"description":"Human-readable message","type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.ConnectRequest":{"properties":{"force":{"description":"Overwrite existing entry","type":"boolean"},"keyless":{"type":"boolean"},"mode":{"type":"string"},"precondition_token":{"description":"PreconditionToken is the opaque token from the preview this write was\nconfirmed against (Spec 091 FR-005). When present, the core rechecks it\nat write time and responds 409 with action \"precondition_failed\" —\nwriting nothing — if the config or the entry MCPProxy would write has\ndrifted since; the caller then re-previews instead of retrying. Absent\nmeans exactly the pre-091 behavior. A replace-classified flow sends this\nTOGETHER with force=true: the token, not the absence of force, is the\noverwrite safety.","type":"string"},"profile":{"description":"Profile, Mode and Keyless are the client-credential intent (Spec 108\nFR-024). Profile names the profile the client's credential binds to;\n\"\" is the built-in All servers scope. Omitted means \"not specified\": a\nfresh credential defaults to All servers and a reconnect keeps the\nclient's existing binding (a reconnect never silently widens a locked\nclient). Mode is locked|switchable (default locked for a named profile,\nswitchable for All servers). Keyless writes a credential-less entry and\nis only possible while require_mcp_auth is off; it cannot carry a\nprofile or mode.","type":"string"},"server_name":{"description":"Defaults to \"mcpproxy\"","type":"string"}},"type":"object"},"httpapi.CreateClientRequest":{"properties":{"display_name":{"type":"string"},"expires_in":{"description":"ExpiresIn is a duration like 30d or 720h; default and cap are 365 days.","type":"string"},"id":{"type":"string"},"mode":{"type":"string"},"profile":{"type":"string"},"purpose":{"description":"Purpose is the stated, unenforced task brief (Spec 115), at most 500\ncharacters; screened for secrets before anything is stored.","type":"string"}},"type":"object"},"httpapi.CreateClientResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"credential":{"type":"string"},"snippet":{"$ref":"#/components/schemas/httpapi.ClientSnippet"}},"type":"object"},"httpapi.EffectiveToolsData":{"properties":{"counts":{"$ref":"#/components/schemas/runtime.EffectiveCounts"},"profile":{"type":"string"},"stale_classification_reasons":{"additionalProperties":{"type":"string"},"description":"StaleClassificationReasons maps each stale classify entry to why it no\nlonger applies: profile.StaleClassificationAnnotated or\nprofile.StaleClassificationMissing. It is computed over the UNFILTERED\ntool set, so a server or reason filter never changes it. Administrators\nonly.","type":"object"},"stale_classifications":{"description":"StaleClassifications lists classify entries for tools that are now\nannotated or no longer exist (FR-005). Administrators only.","items":{"type":"string"},"type":"array","uniqueItems":false},"tools":{"items":{"$ref":"#/components/schemas/runtime.EffectiveTool"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.EnvFieldPreview":{"properties":{"empty_or_placeholder":{"type":"boolean"},"name":{"type":"string"},"secret_like":{"type":"boolean"},"value_present":{"type":"boolean"}},"type":"object"},"httpapi.FinalizeClientResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"rotation":{"$ref":"#/components/schemas/httpapi.RotationState"}},"type":"object"},"httpapi.ForgetClientResponse":{"properties":{"disconnect_error":{"type":"string"},"disconnected":{"type":"boolean"},"revoked":{"type":"string"}},"type":"object"},"httpapi.GuardBinding":{"properties":{"client_id":{"type":"string"},"mode":{"type":"string"},"profile":{"type":"string"},"token_name":{"type":"string"}},"type":"object"},"httpapi.GuardFixOption":{"properties":{"kind":{"type":"string"},"target":{"type":"string"}},"type":"object"},"httpapi.HeaderFieldPreview":{"properties":{"empty_or_placeholder":{"type":"boolean"},"name":{"type":"string"},"secret_like":{"type":"boolean"},"value_present":{"type":"boolean"}},"type":"object"},"httpapi.ImportFromPathRequest":{"properties":{"format":{"description":"Optional format hint","type":"string"},"path":{"description":"File path to import from","type":"string"},"rename":{"additionalProperties":{"type":"string"},"description":"Rename maps a server name → new name. Applied after parsing so the\ncaller can disambiguate cross-source name collisions (Spec 046 v2 —\ne.g. \"mcpproxy\" → \"mcpproxy_claude_code\"). Keys are matched against\neither the raw source name (OriginalName) or the sanitized name shown\nin the preview (Server.Name); these differ for names that need\nsanitizing (e.g. \"Figma Desktop\" → \"Figma_Desktop\"). Keys not present\nin the imported set are ignored.","type":"object"},"server_names":{"description":"Optional: import only these servers","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportRequest":{"properties":{"allow_paste_fallback":{"description":"AllowPasteFallback opts into detecting a bare URL or a single command\nline (FR-064) when Format/format detection would otherwise fail — see\nconfigimport.ImportOptions.AllowPasteFallback for why this must stay\nopt-in (review round 4 F-E). Only the interactive Paste tab sets this;\nevery other caller of this endpoint (the general \"Import config\"\npanel, or a direct API call) leaves it false and gets a clear\n\"unable to detect configuration format\" error for a plain one-liner\ninstead of it being silently guessed at and, on apply, added as a\nreal server with no confirmation step.","type":"boolean"},"content":{"description":"Raw JSON or TOML content","type":"string"},"env_override":{"additionalProperties":{"type":"string"},"description":"EnvOverride/HeaderOverride (Spec 109 FR-064/065, PR review round 4\nF-A/F-D fix): the Paste tab's per-field Value/Secret edits — a plain\nvalue the user typed, or a keyring ref path if they chose Secret —\nkeyed by field name. Applied to the matching imported server's\nEnv/Headers ONLY when preview=false, directly on the server this\nrequest's own raw Content parses to server-side. This is what lets\nthe apply call carry the user's edited env/header values without\never round-tripping the redacted preview: url/command/args on apply\nalways come from re-parsing Content here, never from a client-held\npreview response, so a credential embedded in a URL query param or\nargv flag (which the preview necessarily redacted for display) is\nnever overwritten with the masked placeholder.","type":"object"},"format":{"description":"Optional format hint","type":"string"},"header_override":{"additionalProperties":{"type":"string"},"type":"object"},"server_names":{"description":"Optional: import only these servers","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportResponse":{"properties":{"failed":{"items":{"$ref":"#/components/schemas/configimport.FailedServer"},"type":"array","uniqueItems":false},"format":{"type":"string"},"format_name":{"type":"string"},"imported":{"items":{"$ref":"#/components/schemas/httpapi.ImportedServerResponse"},"type":"array","uniqueItems":false},"skipped":{"items":{"$ref":"#/components/schemas/configimport.SkippedServer"},"type":"array","uniqueItems":false},"summary":{"$ref":"#/components/schemas/configimport.ImportSummary"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportedServerResponse":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"command":{"type":"string"},"env":{"items":{"$ref":"#/components/schemas/httpapi.EnvFieldPreview"},"type":"array","uniqueItems":false},"fields_skipped":{"items":{"type":"string"},"type":"array","uniqueItems":false},"headers":{"items":{"$ref":"#/components/schemas/httpapi.HeaderFieldPreview"},"type":"array","uniqueItems":false},"name":{"type":"string"},"original_name":{"type":"string"},"protocol":{"type":"string"},"source_format":{"type":"string"},"summary":{"description":"Summary, Tags, Env and Headers are the Spec 109 FR-064 preview\nenrichment (contracts/rest-api.md \"Import preview\"). Summary and Tags\nare built from the already-redacted URL/Command/Args above, so a\nsecret embedded in argv or a URL query never reaches Summary either.\nEnv/Headers never carry the raw value — only its presence and two\nbooleans a surface uses to default the Value/Secret toggle (FR-065).","type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"url":{"type":"string"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.IsolationRequest":{"description":"Isolation carries per-server Docker isolation overrides (enabled,\nmode_override, image, network_mode, extra_args, working_dir). A nil\npointer means \"do not touch isolation config\". A present object is\napplied field-by-field ON TOP of the persisted overrides, so omitting a\nfield leaves it alone; clear an individual override by sending it\nexplicitly (` + "`" + `\"enabled\": null` + "`" + `, ` + "`" + `\"image\": \"\"` + "`" + `).","properties":{"enabled":{"description":"Enabled exists ONLY to detect and reject an echoed-back read. It is the\neffective state on the read surface and is never writable; see validate().","type":"boolean"},"enabled_override":{"description":"EnabledOverride is the tri-state per-server override — the RAW value, the\nsame one reads return as ` + "`" + `enabled_override` + "`" + `. It has THREE meaningful wire\nstates, and collapsing them is what silently un-isolated servers\n(GH #1142):\n - absent → leave the persisted override untouched\n - null → clear the override, back to inheriting the global\n - true / false → set an explicit opt-in / opt-out","type":"boolean"},"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"mode_override":{"description":"ModeOverride sets ` + "`" + `isolation.mode` + "`" + ` (\"docker\" | \"sandbox\" | \"none\").\nnil leaves the persisted value alone; an empty string clears it. An\nunrecognized value is rejected with a 400 rather than persisted.","type":"string"},"network_mode":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"httpapi.OnboardingMarkRequest":{"properties":{"connect_step_status":{"description":"ConnectStepStatus is one of: \"\", \"completed\", \"skipped\". Empty\npreserves the existing value. The stored enum is wider (Spec 080\nFR-001): a \"skipped\" request for a previously untouched connect step\nis upgraded server-side to \"completed_external\" when the install\nshows positive evidence of an external connection (Spec 080 FR-002).\n\"completed_external\" is NOT accepted from clients — it must never be\npersisted without that server-verified evidence (edge case: \"never\nguess completed_external without positive evidence\").","type":"string"},"connected_client_id":{"description":"ConnectedClientID records a successful connect write for this client id\n(Spec 109-b FR-042, review round 6). The REST connect endpoint\n(POST /api/v1/connect/{client}) already records this itself on success;\nthis field exists so ` + "`" + `mcpproxy connect` + "`" + ` — which writes the client's\nconfig file directly, without going through that endpoint, so the\ncommand still works when no daemon is running — can relay the same\nevent to a daemon that IS running, keeping ClientConnectedAt in sync\nacross both surfaces. Must be a known id from the fixed connect client\nregistry (internal/connect.GetAllClients); any other value is rejected,\nmatching the field's \"bounded by the registry\" invariant\n(data-model.md §7).","type":"string"},"disconnected_client_id":{"description":"DisconnectedClientID relays a successful local CLI disconnect to a running\ndaemon, which cannot observe the CLI's direct config-file edit itself.\nLike ConnectedClientID, it is bounded to the fixed client registry.","type":"string"},"engaged":{"description":"Engaged marks the wizard as engaged (completed or explicitly skipped).\nOnce true, the wizard does not auto-show again.","type":"boolean"},"mark_shown":{"description":"MarkShown records the wizard's first display time if not already set.","type":"boolean"},"server_step_status":{"description":"ServerStepStatus is one of: \"\", \"completed\", \"skipped\". Empty\npreserves the existing value.","type":"string"}},"type":"object"},"httpapi.OnboardingStateResponse":{"properties":{"configured_server_count":{"description":"ConfiguredServerCount is the number of upstream MCP servers configured\nin mcpproxy (counts both enabled and disabled).","type":"integer"},"connected_client_count":{"description":"ConnectedClientCount is the number of supported clients currently\npointing at mcpproxy.","type":"integer"},"connected_client_ids":{"description":"ConnectedClientIDs are the identifiers of supported clients currently\npointing at mcpproxy. Drawn exclusively from the fixed adapter table —\nuser-entered values never appear here.","items":{"type":"string"},"type":"array","uniqueItems":false},"first_mcp_client_ever":{"description":"FirstMCPClientEver is true once any MCP client has successfully completed\nan ` + "`" + `initialize` + "`" + ` round-trip with this mcpproxy. Sourced from the Spec 044\nactivation bucket. Drives the Verify tab's \"green check\" state.","type":"boolean"},"has_configured_server":{"description":"HasConfiguredServer is true if at least one upstream MCP server is\nconfigured (regardless of current connection health).","type":"boolean"},"has_connected_client":{"description":"HasConnectedClient is true if at least one supported AI client currently\nhas mcpproxy registered in its config.","type":"boolean"},"has_usable_server":{"description":"HasUsableServer is true once at least one enabled, non-quarantined\nserver has usable health and at least one approved (non-disabled) tool.\nThis is the real \"the wizard has something to try\" signal:\nHasConfiguredServer only means a server entry exists, even while every\none of them sits quarantined, requires sign-in, or has zero approved\ntools. The Servers step and Setup badge use this instead of\nHasConfiguredServer, which is kept above for compatibility.\nHealthStatus.Usable is the shared\nreadiness contract used by every UI surface (Spec 109-c, tasks.md T051).","type":"boolean"},"incomplete_tab_count":{"description":"IncompleteTabCount is the number of wizard tabs whose state is incomplete.\nDrives the sidebar Setup entry's badge. Formula:\n +1 if HasConnectedClient == false\n +1 if HasUsableServer == false\n +1 if FirstMCPClientEver == false","type":"integer"},"mcp_clients_seen_ever":{"description":"MCPClientsSeenEver is the capped list of recognized client names that\nhave ever called this mcpproxy. Names come from the MCP ` + "`" + `initialize` + "`" + `\npayload's ` + "`" + `clientInfo.name` + "`" + ` field, sanitized. Surfaces on the Verify tab\nso the user can see whether their real IDE — not a test client — has\nconnected.","items":{"type":"string"},"type":"array","uniqueItems":false},"should_show_wizard":{"description":"ShouldShowWizard is the derived flag the frontend uses to decide\nwhether to auto-show. True when not engaged and IncompleteTabCount \u003e 0\n(Spec 046 v2 — semantics widened to also count the Verify tab).","type":"boolean"},"state":{"$ref":"#/components/schemas/storage.OnboardingState"},"usable_servers":{"description":"UsableServers lists the names behind HasUsableServer, for the Verify\nstep's suggested-prompt generator (FR-042): prompts are only built from\ntools of servers in this list, never from a quarantined or toolless one.","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileConflictResponse":{"properties":{"code":{"type":"string"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"description":"Always false","type":"boolean"},"used_by":{"$ref":"#/components/schemas/httpapi.ProfileUsedByData"}},"type":"object"},"httpapi.ProfileDeleteData":{"properties":{"anonymous_profile_moved_to":{"type":"string"},"deleted":{"type":"string"},"moved":{"$ref":"#/components/schemas/runtime.MovedRefs"}},"type":"object"},"httpapi.ProfileListData":{"properties":{"anonymous_profile":{"type":"string"},"profiles":{"items":{"$ref":"#/components/schemas/runtime.ProfileView"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileRenameData":{"properties":{"moved":{"$ref":"#/components/schemas/runtime.MovedRefs"},"profile":{"$ref":"#/components/schemas/runtime.ProfileView"}},"type":"object"},"httpapi.ProfileTryData":{"properties":{"hidden":{"items":{"$ref":"#/components/schemas/runtime.TryHidden"},"type":"array","uniqueItems":false},"hidden_by_profile":{"type":"integer"},"hidden_truncated":{"type":"boolean"},"results":{"items":{"additionalProperties":{},"type":"object"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileUsedByData":{"properties":{"anonymous_profile":{"type":"boolean"},"clients":{"items":{"$ref":"#/components/schemas/runtime.UsedByClient"},"type":"array","uniqueItems":false},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileViewData":{"properties":{"blocked_24h":{"type":"integer"},"calls_24h":{"type":"integer"},"code_execution":{"type":"boolean"},"description":{"type":"string"},"effective_code_execution":{"type":"boolean"},"effective_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"effective_unannotated":{"type":"string"},"is_legacy":{"type":"boolean"},"management_tools":{"type":"boolean"},"max_tier":{"type":"string"},"name":{"type":"string"},"servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"switchable_to":{"items":{"type":"string"},"type":"array","uniqueItems":false},"title":{"type":"string"},"tool_count":{"description":"ToolCount is the v2 field: indexed tools on the effective servers.\nDeprecated: use tool_counts.","type":"integer"},"tool_counts":{"$ref":"#/components/schemas/runtime.ToolCounts"},"tools":{"$ref":"#/components/schemas/config.ProfileToolRules"},"unannotated":{"type":"string"},"used_by":{"$ref":"#/components/schemas/runtime.UsedBy"}},"type":"object"},"httpapi.ProfileWriteData":{"properties":{"profile":{"$ref":"#/components/schemas/runtime.ProfileView"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.PutClientBindingRequest":{"properties":{"mode":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.RenameProfileRequest":{"properties":{"new_name":{"type":"string"}},"type":"object"},"httpapi.RotateClientRequest":{"properties":{"precondition_token":{"description":"PreconditionToken is the token of GET /connect/{client}/preview; it\nbinds a supported client's rotation to what the preview showed.","type":"string"}},"type":"object"},"httpapi.RotateClientResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"connect":{"$ref":"#/components/schemas/connect.ConnectResult"},"credential":{"type":"string"},"rotation":{"$ref":"#/components/schemas/httpapi.RotationState"},"snippet":{"$ref":"#/components/schemas/httpapi.ClientSnippet"}},"type":"object"},"httpapi.RotationState":{"properties":{"state":{"type":"string"}},"type":"object"},"httpapi.SetActiveProfileRequest":{"properties":{"active_profile":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.StaleReviewErrorResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"stale_tools":{"$ref":"#/components/schemas/httpapi.StaleToolsDetail"},"success":{"type":"boolean"}},"type":"object"},"httpapi.StaleToolsDetail":{"properties":{"changed":{"items":{"type":"string"},"type":"array","uniqueItems":false},"missing_blocks":{"items":{"type":"string"},"type":"array","uniqueItems":false},"unreviewed":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.TryProfileRequest":{"properties":{"limit":{"type":"integer"},"profile":{"$ref":"#/components/schemas/config.ProfileConfig"},"query":{"type":"string"}},"type":"object"},"httpapi.UndoConnectRequest":{"properties":{"backup_name":{"description":"BackupName is the bare filename (filepath.Base) of the backup returned as\nbackup_path by the preceding connect — a name, never a path. Undo resolves\nthe full path server-side by joining it with the client's own config\ndirectory, so a client-supplied value can never contribute a directory\ncomponent (traversal is impossible by construction). Empty means the\nconnect created the file (no prior file existed), so undo removes it.","type":"string"},"server_name":{"description":"Defaults to \"mcpproxy\"","type":"string"}},"type":"object"},"httpapi.UpdateFailureRequest":{"properties":{"stage":{"description":"Stage is the failure stage of the update session.","enum":["appcast","download","install","other"],"type":"string"}},"type":"object"},"httpapi.UpgradeAdminKeyHoldersRequest":{"properties":{"apply":{"type":"boolean"},"mode":{"type":"string"},"precondition_token":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.approveToolsRequest":{"properties":{"approve_all":{"type":"boolean"},"expected_hashes":{"additionalProperties":{"type":"string"},"description":"ExpectedHashes binds the approval to the reviewed definitions (Spec\n117 PR-2, #1566): tool name -\u003e the review's current_hash. Absent or\nnull is an unbound (legacy) request; {} is bound.","type":["object","null"]},"expected_incarnation":{"description":"ExpectedIncarnation binds the approval to the server the client\nreviewed (Spec 116 FR-017); 409 server_replaced on a mismatch. It is\nindependent of ExpectedHashes and the two may be sent together.","type":"integer"},"tools":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.attentionResponse":{"properties":{"count":{"type":"integer"},"generated_at":{"type":"string"},"items":{"items":{"$ref":"#/components/schemas/contracts.AttentionItem"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.bundleRollbackRequest":{"properties":{"digest":{"description":"Digest is the full 64-character lowercase hex SHA-256 of the target.","type":"string"},"embedded":{"description":"Embedded rolls back to the corpus compiled into this binary.","type":"boolean"},"path":{"description":"Path is where to find the target bundle (a hint only).","type":"string"}},"type":"object"},"httpapi.clientPresence":{"properties":{"active_sessions":{"type":"integer"},"blocked_24h":{"type":"integer"},"calls_24h":{"type":"integer"},"config_path":{"type":"string"},"connected":{"type":"boolean"},"connection_unverified":{"type":"boolean"},"credential_checked_at":{"type":"string"},"credential_state":{"$ref":"#/components/schemas/profile.CredentialState"},"display_name":{"type":"string"},"display_path":{"type":"string"},"expires_at":{"type":"string"},"icon":{"type":"string"},"id":{"type":"string"},"installed":{"type":"boolean"},"issuer":{"$ref":"#/components/schemas/auth.CredentialIssuer"},"kind":{"type":"string"},"last_seen":{"type":"string"},"lease":{"type":"boolean"},"profile":{"type":"string"},"profile_missing":{"type":"boolean"},"profile_mode":{"type":"string"},"profile_source":{"description":"profile_source is pin (locked) or binding (switchable) and is empty when\ncredential_state is not client.","type":"string"},"profile_state":{"type":"string"},"profile_title":{"type":"string"},"purpose":{"type":"string"},"reload_hint":{"type":"string"},"revoked_at":{"description":"Spec 115 lifecycle fields of the client's credential record (additive):\nwhen it was revoked, who issued it, its stated (unenforced) purpose,\nwhether it is a task lease (lifetime at issue \u003c= 24h) and whether its\nprofile still exists (ok | dangling | none).","type":"string"},"rotation_pending":{"type":"boolean"},"sessions":{"items":{"$ref":"#/components/schemas/httpapi.clientSession"},"type":"array","uniqueItems":false},"state":{"type":"string"},"token_name":{"type":"string"}},"type":"object"},"httpapi.clientSession":{"properties":{"id":{"type":"string"},"last_activity":{"type":"string"},"profile":{"description":"Profile and ProfileSource are the session's latest effective resolution\n(Spec 108-e FR-033); empty on legacy sessions.","type":"string"},"profile_source":{"type":"string"},"started_at":{"type":"string"},"work_session_id":{"type":"string"}},"type":"object"},"httpapi.clientsResponse":{"properties":{"clients":{"items":{"$ref":"#/components/schemas/httpapi.clientPresence"},"type":"array","uniqueItems":false},"routing":{},"warnings":{"items":{"$ref":"#/components/schemas/httpapi.ClientWarning"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.expectedIncarnationBody":{"properties":{"expected_incarnation":{"type":"integer"}},"type":"object"},"httpapi.securityApproveRequest":{"properties":{"block":{"items":{"type":"string"},"type":"array","uniqueItems":false},"expected_hashes":{"additionalProperties":{"type":"string"},"description":"ExpectedHashes binds the approval to the reviewed definitions (Spec\n117 PR-2, #1566): tool name -\u003e the review's current_hash. Absent or\nnull is an unbound (legacy) request; {} binds to the empty snapshot.\nIndependent of ExpectedIncarnation: a request may carry both, and the\ntwo refusals stay distinct (review_out_of_date vs server_replaced).","type":["object","null"]},"expected_incarnation":{"description":"ExpectedIncarnation binds the approval to the server the client\nreviewed (Spec 116 FR-017): a remove and re-add since then is refused\nwith 409 server_replaced and the replacement stays quarantined.","type":"integer"},"force":{"type":"boolean"}},"type":"object"},"management.BulkOperationResult":{"properties":{"errors":{"additionalProperties":{"type":"string"},"description":"Map of server name to error message","type":"object"},"failed":{"description":"Number of failed operations","type":"integer"},"successful":{"description":"Number of successful operations","type":"integer"},"total":{"description":"Total servers processed","type":"integer"}},"type":"object"},"observability.HealthResponse":{"properties":{"components":{"items":{"$ref":"#/components/schemas/observability.HealthStatus"},"type":"array","uniqueItems":false},"status":{"description":"\"healthy\" or \"unhealthy\"","type":"string"},"timestamp":{"type":"string"}},"type":"object"},"observability.HealthStatus":{"properties":{"error":{"type":"string"},"latency":{"type":"string"},"name":{"type":"string"},"status":{"description":"\"healthy\" or \"unhealthy\"","type":"string"}},"type":"object"},"observability.ReadinessResponse":{"properties":{"components":{"items":{"$ref":"#/components/schemas/observability.HealthStatus"},"type":"array","uniqueItems":false},"status":{"description":"\"ready\" or \"not_ready\"","type":"string"},"timestamp":{"type":"string"}},"type":"object"},"profile.AccessStepStatus":{"type":"string","x-enum-varnames":["AccessStepPass","AccessStepFail","AccessStepSkip"]},"profile.AccessSubjectKind":{"type":"string","x-enum-varnames":["AccessSubjectClient","AccessSubjectProfile","AccessSubjectToken","AccessSubjectAnonymous"]},"profile.BlockReason":{"type":"string","x-enum-varnames":["BlockReasonTier","BlockReasonRule","BlockReasonUnannotated","BlockReasonCodeExecution","BlockReasonManagement","BlockReasonServerScope"]},"profile.CredentialState":{"description":"Spec 108-f ClientView additions (data-model §7). The Spec 109 fields above\nare unchanged; everything below is additive.\n\ncredential_state is what the client's connection carries (client |\nadmin_key | none | revoked | expired | unknown). The stat-only list never\nreads a config: it reports the token store, else the last on-demand\nobservation (credential_checked_at says when), else unknown.","type":"string","x-enum-varnames":["CredentialStateClient","CredentialStateAdminKey","CredentialStateNone","CredentialStateRevoked","CredentialStateExpired","CredentialStateUnknown"]},"profile.ExplainStep":{"type":"string","x-enum-varnames":["StepCredential","StepProfile","StepServerInScope","StepToolRule","StepTierCap","StepTokenPermission","StepGlobalGate","StepServerState","StepToolApproval"]},"profile.ExplainVerdict":{"type":"string","x-enum-varnames":["ExplainVerdictAllowed","ExplainVerdictBlocked","ExplainVerdictHidden"]},"profile.FixAction":{"type":"string","x-enum-varnames":["FixAllowInProfile","FixClassifyInProfile","FixAddServerToProfile","FixMoveClient","FixEditToken","FixEnableServer","FixApproveTool","FixChangeSetting","FixReconnectClient"]},"profile.WarningCode":{"type":"string","x-enum-varnames":["WarningAnonymousDeniedByBindingGuard","WarningClientHoldsAdminKey","WarningClientCredentialExpiring","WarningClientRotationPending","WarningProfileMissing","WarningClientTokenNameConflict"]},"profile.WarningSeverity":{"type":"string","x-enum-varnames":["WarningSeverityWarn","WarningSeverityInfo"]},"runtime.AccessSuggestion":{"properties":{"block_reason":{"$ref":"#/components/schemas/profile.BlockReason"},"clients":{"items":{"type":"string"},"type":"array","uniqueItems":false},"count":{"type":"integer"},"first_seen":{"type":"string"},"fixes":{"description":"Fixes are the access explainer's remediations of the first failing step,\nin preference order. Empty for a deny rule and for the built-in tools.","items":{"$ref":"#/components/schemas/runtime.Fix"},"type":"array","uniqueItems":false},"last_seen":{"type":"string"},"needs_input":{"description":"NeedsInput names what a person must supply before a change is\napply-ready (classify: \"tier\").","items":{"type":"string"},"type":"array","uniqueItems":false},"note":{"type":"string"},"profile":{"type":"string"},"server":{"type":"string"},"suggestion":{"$ref":"#/components/schemas/runtime.SuggestionKind"},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false},"tool":{"description":"\"server:tool\", or the built-in name","type":"string"},"warning":{"description":"Warning is set for profile_code_execution and profile_management: both\nchange what a profile can do beyond tool access.","type":"string"}},"type":"object"},"runtime.BindingRef":{"properties":{"client_id":{"type":"string"},"mode":{"type":"string"},"profile":{"type":"string"},"token_name":{"type":"string"}},"type":"object"},"runtime.EffectiveCounts":{"properties":{"by_reason":{"additionalProperties":{"type":"integer"},"type":"object"},"callable":{"type":"integer"},"hidden":{"type":"integer"},"visible":{"type":"integer"}},"type":"object"},"runtime.EffectiveTool":{"properties":{"access":{"$ref":"#/components/schemas/runtime.ToolAccessView"},"classification_stale":{"type":"boolean"},"intrinsic_tier":{"type":"string"},"profile_tier":{"type":"string"},"server":{"type":"string"},"tool":{"type":"string"}},"type":"object"},"runtime.ExplainProfileView":{"properties":{"name":{"type":"string"},"source":{"type":"string"}},"type":"object"},"runtime.ExplainStepView":{"properties":{"detail":{"type":"string"},"status":{"$ref":"#/components/schemas/profile.AccessStepStatus"},"step":{"$ref":"#/components/schemas/profile.ExplainStep"}},"type":"object"},"runtime.ExplainSubjectView":{"properties":{"kind":{"$ref":"#/components/schemas/profile.AccessSubjectKind"},"name":{"type":"string"}},"type":"object"},"runtime.Fix":{"properties":{"action":{"$ref":"#/components/schemas/profile.FixAction"},"label":{"type":"string"},"profile":{"description":"Profile is set for move_client only: the destination profile slug the fix\nmoves the client to. Target stays the client id (UIs navigate by it) and\nLabel carries the title, so neither can name the slug.","type":"string"},"step":{"type":"string","x-enum-varnames":["StepCredential","StepProfile","StepServerInScope","StepToolRule","StepTierCap","StepTokenPermission","StepGlobalGate","StepServerState","StepToolApproval"]},"target":{"type":"string"}},"type":"object"},"runtime.GuardFix":{"properties":{"kind":{"type":"string"},"target":{"type":"string"}},"type":"object"},"runtime.MovedRefs":{"properties":{"clients":{"items":{"type":"string"},"type":"array","uniqueItems":false},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"runtime.ProfilePatch":{"properties":{"changes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"profile":{"type":"string"},"proposed":{"$ref":"#/components/schemas/config.ProfileConfig"}},"type":"object"},"runtime.ProfileView":{"properties":{"blocked_24h":{"type":"integer"},"calls_24h":{"type":"integer"},"code_execution":{"type":"boolean"},"description":{"type":"string"},"effective_code_execution":{"type":"boolean"},"effective_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"effective_unannotated":{"type":"string"},"is_legacy":{"type":"boolean"},"management_tools":{"type":"boolean"},"max_tier":{"type":"string"},"name":{"type":"string"},"servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"switchable_to":{"items":{"type":"string"},"type":"array","uniqueItems":false},"title":{"type":"string"},"tool_count":{"description":"ToolCount is the v2 field: indexed tools on the effective servers.\nDeprecated: use tool_counts.","type":"integer"},"tool_counts":{"$ref":"#/components/schemas/runtime.ToolCounts"},"tools":{"$ref":"#/components/schemas/config.ProfileToolRules"},"unannotated":{"type":"string"},"used_by":{"$ref":"#/components/schemas/runtime.UsedBy"}},"type":"object"},"runtime.SuggestionKind":{"type":"string","x-enum-varnames":["SuggestAllow","SuggestAddServer","SuggestClassify","SuggestNone"]},"runtime.ToolAccessView":{"properties":{"callable":{"type":"boolean"},"reason":{"type":"string"},"visible":{"type":"boolean"}},"type":"object"},"runtime.ToolCounts":{"properties":{"destructive":{"type":"integer"},"read":{"type":"integer"},"unannotated_hidden":{"type":"integer"},"write":{"type":"integer"}},"type":"object"},"runtime.TryHidden":{"properties":{"reason":{"type":"string"},"server":{"type":"string"},"tool":{"type":"string"}},"type":"object"},"runtime.UsedBy":{"properties":{"anonymous_profile":{"type":"boolean"},"clients":{"items":{"$ref":"#/components/schemas/runtime.UsedByClient"},"type":"array","uniqueItems":false},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"runtime.UsedByClient":{"properties":{"id":{"type":"string"},"mode":{"type":"string"}},"type":"object"},"runtime.WarningAction":{"properties":{"kind":{"type":"string"},"target":{"type":"string"}},"type":"object"},"scanner.BundleInfo":{"properties":{"authority":{"description":"Authority is the signing root serving this bundle: \"publisher\" (the\nembedded default, or verified against a publisher key), \"operator\", or \"\"\nfor an unsigned external bundle.","type":"string"},"bundle_version":{"description":"BundleVersion / SchemaVersion are the corpus's own declared versions.","type":"string"},"coverage_degraded":{"description":"CoverageDegraded suspends scan-mode auto-approval; DegradedReason says\nwhy (one of the Degraded* constants).","type":"boolean"},"declared_skipped":{"type":"integer"},"degraded_reason":{"type":"string"},"fingerprint":{"description":"Fingerprint is the first 12 hex chars of the SHA-256 of the corpus bytes:\na stable identity an operator (or automation) can compare across hosts\nwithout shipping the whole file around.","type":"string"},"full_digest":{"description":"FullDigest is the complete lowercase-hex SHA-256 of the bundle bytes —\nthe ONLY value rollback accepts (FR-010). Fingerprint stays the 12-hex\nhuman label beside it.","type":"string"},"generated_at":{"description":"GeneratedAt is the corpus freshness stamp. It is the bundle's own\n` + "`" + `generated_at` + "`" + ` key when present; for a file-sourced bundle without one it\nfalls back to the file's modification time, so a years-stale corpus is\ndistinguishable from a fresh export.","type":"string"},"last_activated_at":{"description":"LastActivatedAt is when the serving external bundle was activated; nil\nfor the embedded default.","type":"string"},"last_checked_at":{"description":"LastCheckedAt is the end of the most recent pipeline run, including\nno-op runs the idempotence short-circuit skipped.","type":"string"},"last_rejection":{"$ref":"#/components/schemas/scanner.BundleRejection"},"load_error":{"description":"LoadError is the reason the LAST configured-path load failed, if any. The\npreviously active (or embedded) corpus stays live — a bundle problem must\nnever leave the scanner with no signatures — but the failure is surfaced\nhere rather than swallowed.","type":"string"},"loaded_at":{"description":"LoadedAt is when this corpus became active in this process.","type":"string"},"path":{"description":"Path is the configured filesystem path, when Source is \"file\".","type":"string"},"pinned":{"description":"Pinned is true while an operator rollback pin governs activation.","type":"boolean"},"refresh":{"$ref":"#/components/schemas/scanner.BundleRefreshStatus"},"reprotect":{"$ref":"#/components/schemas/scanner.BundleReprotectStatus"},"rollback":{"description":"Rollback is true when the active bundle was activated by an explicit\nrollback.","type":"boolean"},"runnable_rules":{"description":"RunnableRules is how many rules are LIVE in the offline tier; SkippedRules\nand DeclaredSkipped are the not-runnable / bundle-declared-skipped\nremainder (FR-006/FR-007) — un-evaluated coverage, never clean coverage.","type":"integer"},"schema_version":{"type":"string"},"sequence":{"description":"Sequence is the manifest sequence as published (decimal string), \"\" when\nthe bundle carries none.","type":"string"},"signature_count":{"description":"SignatureCount is the bundle's self-declared signature count.","type":"integer"},"signature_verified":{"description":"SignatureVerified reports whether the active bundle's detached signature\nverified. Always false for the embedded default (it is binary-trusted).","type":"boolean"},"skipped_rules":{"type":"integer"},"source":{"description":"Source is BundleSourceEmbedded, BundleSourceFile or BundleSourceFetch.","type":"string"},"stale":{"description":"Stale and StaleAfterDays are computed at read time next to\nStalenessDays; a future generated_at is never stale. StaleAfterDays nil\nmeans the flag is not evaluated.","type":"boolean"},"stale_after_days":{"type":"integer"},"staleness_days":{"description":"StalenessDays is the whole days since GeneratedAt (nil when unknown).","type":"integer"},"trust_epoch":{"description":"TrustEpoch is the epoch the bundle was published under.","type":"integer"}},"type":"object"},"scanner.BundleRefreshStatus":{"description":"Refresh is the refresh-cycle status (nil before any cycle or setting is\nknown). Reprotect is the post-activation re-protection sweep status,\nset from the server through SetReprotectStatus.","properties":{"consecutive_failures":{"type":"integer"},"fetch_enabled":{"type":"boolean"},"fetch_host":{"description":"FetchHost is the host of the configured fetch URL (\"\" when none).","type":"string"},"fetch_reason":{"type":"string"},"fetch_state":{"description":"FetchState and FetchReason are the fetch leg's own last answer (one of the\nRefreshOutcome* values and its reason), kept apart from LastOutcome: a file\nactivation owns the merged cycle outcome but must not hide a fetch leg that\ncannot run (B16 warning 3).","type":"string"},"interval_seconds":{"type":"integer"},"last_attempt_at":{"type":"string"},"last_outcome":{"type":"string"},"last_reason":{"type":"string"},"last_trigger":{"description":"LastTrigger, LastOutcome and LastReason use the closed vocabularies above.","type":"string"},"next_check_at":{"type":"string"}},"type":"object"},"scanner.BundleRejection":{"description":"LastRejection is the most recent refused candidate. It is retained\nacross a later successful load so \"what did it refuse, and when\"\nsurvives.","properties":{"at":{"type":"string"},"detail":{"description":"Detail is a short human string (which ceiling, which key id, which\nepoch, the bundlesig contract code). Never parsed.","type":"string"},"reason":{"description":"Reason is one of the Reject* constants; the only field to branch on.","type":"string"}},"type":"object"},"scanner.BundleReprotectStatus":{"properties":{"last_completed_at":{"type":"string"},"reason":{"description":"Reason qualifies suspended and failed (for example\nReprotectReasonAutoBaselineScanOff).","type":"string"},"servers_scanned":{"type":"integer"},"servers_with_hits":{"type":"integer"},"state":{"description":"State is one of the ReprotectState* constants.","type":"string"}},"type":"object"},"secureenv.EnvConfig":{"description":"Environment configuration for secure variable filtering","properties":{"allowed_system_vars":{"items":{"type":"string"},"type":"array","uniqueItems":false},"custom_vars":{"additionalProperties":{"type":"string"},"type":"object"},"enhance_path":{"description":"Enable PATH enhancement for Launchd scenarios","type":"boolean"},"forward_proxy_env":{"description":"ForwardProxyEnv opts in to forwarding the ambient HTTP(S)/ALL/NO/FTP proxy\nenvironment variables to spawned upstream servers (MCP-2769). It is OFF by\ndefault and deliberately kept out of the AllowedSystemVars default list:\nproxy URLs frequently carry credentials (http://user:pass@proxy), so\nforwarding them to every stdio upstream is a credential-leak risk. When\nenabled, values are forwarded with their userinfo (credentials) redacted.","type":"boolean"},"inherit_system_safe":{"type":"boolean"}},"type":"object"},"storage.ClientCredentialObservation":{"properties":{"at":{"type":"string"},"state":{"type":"string"}},"type":"object"},"storage.OnboardingState":{"description":"State is the persisted wizard engagement record. Engaged is true once\nthe wizard was shown and the user completed or skipped it.","properties":{"client_connected_at":{"additionalProperties":{"type":"string"},"description":"ClientConnectedAt records, per client id from the fixed connect client\nregistry (internal/connect.GetAllClients — never user input), the last\ntime a connect write succeeded for that client (Spec 109-b FR-042).\nWritten by the connect success path through UpdateOnboardingState so a\nconcurrent onboarding/mark write can never drop it. Consumed by the\nVerify step / presence layer to tell \"connected, never seen\" apart from\n\"connected seconds ago, hasn't reconnected yet\".","type":"object"},"client_credential_observed":{"additionalProperties":{"$ref":"#/components/schemas/storage.ClientCredentialObservation"},"description":"ClientCredentialObserved records, per client id, the LAST credential\nclassification an on-demand read produced (Spec 108-f FR-025, F11): what\nthe client's config held (client | admin_key | none | revoked | expired)\nand when it was read. The stat-only GET /clients listing never reads a\nconfig (Spec 075: no macOS App-Data prompt from a list), so this is how\nit still reports a client that holds the admin key across restarts. It is\nwritten only when the classification CHANGES, by every on-demand read\n(GET /clients/{id}, GET /connect/{client}, the admin-key upgrade preview,\na connect write) and deleted on disconnect. Additive: an older binary\nignores it, and a record without it reads as \"unknown\".","type":"object"},"client_disconnected_at":{"additionalProperties":{"type":"string"},"type":"object"},"client_last_seen":{"additionalProperties":{"type":"string"},"description":"ClientLastSeen records the latest MCP initialize for a recognised client\nalias. It is intentionally kept with onboarding state: presence is a\nlocal UI concern and must still work when telemetry is disabled.","type":"object"},"connect_step_status":{"description":"ConnectStepStatus is one of: \"\", \"completed\", \"completed_external\",\n\"skipped\" (Spec 080 FR-001). \"completed_external\" records a dismissal\nwhere the connect step was untouched but the install was already\nconnected outside the wizard (CLI, ConnectModal, manual config).","type":"string"},"engaged":{"description":"Engaged is true once the wizard was shown and the user completed or\nskipped it. Once true, the wizard does not auto-show again, even if\nstate regresses (e.g. user disconnects all clients).","type":"boolean"},"engaged_at":{"description":"EngagedAt is the timestamp of completion or explicit skip.","type":"string"},"first_shown_at":{"description":"FirstShownAt is the timestamp of first wizard render.","type":"string"},"server_step_status":{"description":"ServerStepStatus is one of: \"\", \"completed\", \"skipped\".","type":"string"}},"type":"object"},"telemetry.DiagnosticsCounters":{"properties":{"current_error_codes":{"additionalProperties":{"type":"integer"},"description":"CurrentErrorCodes is the STANDING state at heartbeat time: stable MCPX_\ncode -\u003e number of configured servers currently in that state. It is not\na counter and is never persisted — it is recomputed each heartbeat from\nthe supervisor's live stateview.\n\nSchema v11 (MCP-2967). It exists because error_code_counts_24h became\nedge-triggered in the same change: previously the supervisor re-counted\nevery standing failure on its 30s reconcile ticker, so a parked install\ninflated the counter by ~2880/day/server. Edge-triggering alone would\nhave swung the error to the other side — the 24h window decays, this\nstruct is omitempty via isZero(), so a permanently broken install would\nemit once and then disappear from the payload entirely, and absent reads\nas zero. The two fields answer different questions and are only correct\ntogether: \"how often did something newly break\" and \"how many servers\nare broken right now\".\n\nSafe: only MCPX_* enum constants as keys, never server names, URLs,\ncommands, or free text; values are non-negative server counts.","type":"object"},"error_code_counts_24h":{"additionalProperties":{"type":"integer"},"description":"ErrorCodeCounts24h maps stable MCPX_ code strings to 24h occurrence counts.\nSafe: only MCPX_* enum constants are stored here, never free text, paths,\nserver names, or user-entered values.","type":"object"},"fix_attempted_24h":{"description":"FixAttempted24h counts POST /api/v1/diagnostics/fix calls in the last 24h.","type":"integer"},"fix_succeeded_24h":{"description":"FixSucceeded24h counts fix invocations with outcome=\"success\" in the last 24h.","type":"integer"},"unique_codes_ever":{"description":"UniqueCodesEver is the cardinality of the all-time error code set.\nBounded by the MCPX_ catalog size (~30 codes), never approaches PII risk.","type":"integer"}},"type":"object"},"telemetry.FeedbackContext":{"properties":{"anonymous_id":{"description":"AnonymousID is the install's telemetry anonymous ID (heartbeat value).","type":"string"},"arch":{"type":"string"},"connected_server_count":{"type":"integer"},"diagnostics":{"$ref":"#/components/schemas/telemetry.DiagnosticsCounters"},"edition":{"type":"string"},"go_version":{"type":"string"},"last_error_code":{"description":"LastErrorCode is the most recent MCPX_* error code.","type":"string"},"last_startup_outcome":{"description":"LastStartupOutcome is the previous startup's outcome word.","type":"string"},"machine_id":{"description":"MachineID is the hashed machine identifier (heartbeat value).","type":"string"},"os":{"type":"string"},"previous_shutdown":{"description":"PreviousShutdown is how the previous run ended (clean, crash, ...).","type":"string"},"routing_mode":{"type":"string"},"server_count":{"type":"integer"},"tool_count":{"type":"integer"},"uptime_minutes":{"description":"UptimeMinutes is the daemon's uptime. Omitted from short-lived CLI\nsubmissions, where the process uptime says nothing about the daemon.","type":"integer"},"version":{"type":"string"}},"type":"object"},"telemetry.FeedbackRequest":{"properties":{"category":{"description":"bug, feature, other","type":"string"},"context":{"$ref":"#/components/schemas/telemetry.FeedbackContext"},"email":{"type":"string"},"message":{"type":"string"}},"type":"object"},"telemetry.FeedbackResponse":{"properties":{"error":{"type":"string"},"issue_url":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}},"securitySchemes":{"ApiKeyAuth":{"description":"API key authentication via query parameter. Use ?apikey=your-key","in":"query","name":"apikey","type":"apiKey"}}}, + "components": {"schemas":{"auth.CredentialIssuer":{"properties":{"actor_kind":{"type":"string"},"actor_name":{"type":"string"},"surface":{"type":"string"}},"type":"object"},"config.AgentTokenRateLimit":{"description":"AgentTokenRateLimit caps how many upstream tool calls ONE agent token may\nmake: PerMinute on average, Burst at once (issue #1699). Every token is\ncounted separately, and a token's own rate_limit (set when it is created)\nreplaces this default for that token. Only agent-token callers are\nlimited; the admin API key, the unix socket and an unauthenticated /mcp\ncaller are not. Absent or per_minute 0 = no limit (default, zero behavior\nchange). The counters are in memory: a restart gives every token a full\nallowance again. Hot-reloadable. File/API-configured only, no env scheme.","properties":{"burst":{"description":"Burst is how many calls a token may make at once after a quiet spell.\n0 = the PerMinute value.","type":"integer"},"per_minute":{"description":"PerMinute is the sustained rate. 0 = no limit.","type":"integer"}},"type":"object"},"config.AuditLogConfig":{"description":"AuditLog configures the Spec 107 edition-neutral audit sink\n(internal/audit). nil means \"use the per-edition/per-transport\ndefault\" (EffectiveAuditLog); restart-pinned (bound at sink\nconstruction). See audit_log.go.","properties":{"compress":{"type":"boolean"},"enabled":{"type":"boolean"},"max_age_days":{"type":"integer"},"max_backups":{"type":"integer"},"max_size_mb":{"type":"integer"},"path":{"type":"string"},"stdout":{"type":"boolean"}},"type":"object"},"config.ConcurrencyDefaults":{"description":"ServerConcurrencyDefaults is scope (b) of FR-020: the blanket per-server\ndefault set inherited by every server that does not override a setting.\nAbsent (the default) = no per-server limiting unless a server configures\nit explicitly. File/API-configured only — no env scheme (FR-022).","properties":{"max_concurrent_requests":{"type":"integer"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"}},"type":"object"},"config.Config":{"properties":{"activity_cleanup_interval_min":{"description":"Background cleanup interval in minutes (default: 60)","type":"integer"},"activity_max_records":{"description":"Max records before pruning (default: 400000)","type":"integer"},"activity_max_response_size":{"description":"Response truncation limit in bytes (default: 65536)","type":"integer"},"activity_max_size_mb":{"description":"ActivityMaxSizeMB caps the total activity-log size in MB before the\noldest records are pruned. Omit the key for the 256MB default; set it to\n0 to disable the size cap.","type":"integer"},"activity_retention_days":{"description":"Activity logging settings (RFC-003)","type":"integer"},"advertise_upstream_servers":{"description":"AdvertiseUpstreamServers controls whether MCP clients are told the\nnames of the upstream servers they can reach — in the initialize\ninstructions and the retrieve_tools description — so agents use the\nproxied tools instead of falling back to shell CLIs. Names are always\nfiltered to the caller's profile and agent-token scope. Default true;\nset false to keep server names out of client context. Read live.","type":"boolean"},"agent_token_rate_limit":{"$ref":"#/components/schemas/config.AgentTokenRateLimit"},"aggregate_upstream_prompts":{"description":"AggregateUpstreamPrompts, when true, aggregates every connected upstream\nserver's advertised MCP prompts into mcpproxy's own prompts/list\n(exposed as \"\u003cserver\u003e__\u003cprompt\u003e\"). OFF by default: users are safe by\ndefault and opt in deliberately. EnablePrompts still governs the built-in\nprompts + the prompts capability; this flag gates ONLY the upstream\naggregation performed by RefreshPrompts. Hot-reloadable.","type":"boolean"},"allow_private_registry_fetch":{"description":"AllowPrivateRegistryFetch opts out of the registry SSRF guard (MCP-1076,\nCWE-918). By default (false) registry fetches refuse any host that is — or\nresolves to — a non-routable address (loopback, RFC1918/CGNAT private,\nlink-local incl. the 169.254.169.254 cloud-metadata endpoint), so a\nmalicious or typo'd registry source cannot turn the daemon into a\nrequest-forgery vector against internal services.\n\nThis opt-out is BLANKET (all-or-nothing): setting it true disables the\nguard for EVERY non-routable range at once — loopback, RFC1918/CGNAT\nprivate, link-local AND the 169.254.169.254 cloud-metadata endpoint. There\nis no way to allow only loopback; enabling it for a localhost dev registry\nalso re-opens the cloud-metadata SSRF vector. Set true ONLY when you\nintentionally run a trusted registry mirror on an internal/private address,\nideally on a host with no cloud-metadata exposure. The change takes effect\nonly on daemon (re)start or config reload.","type":"boolean"},"allow_server_add":{"type":"boolean"},"allow_server_remove":{"type":"boolean"},"anonymous_profile":{"description":"AnonymousProfile confines every caller whose request authenticates as\ncredential kind \"anonymous\" (no credential, or an unrecognised\nnon-agent token accepted by the require_mcp_auth:false back-compat\nbranch) to the named profile (Spec 108 FR-008). Empty (default) means\nunconfined, legacy anonymous behaviour. A name that does not match any\nconfigured profile resolves anonymous callers to deny-all and is\nreported as a validation warning (data-model.md §1).","type":"string"},"api_key":{"description":"Security settings","type":"string"},"audit_log":{"$ref":"#/components/schemas/config.AuditLogConfig"},"call_tool_timeout":{"type":"string"},"check_server_repo":{"description":"Repository detection settings","type":"boolean"},"code_execution_max_parallel":{"description":"Default concurrency for call_tools() batches (1-32, default: 8)","type":"integer"},"code_execution_max_tool_calls":{"description":"Max tool calls per execution (0 = unlimited, default: 0)","type":"integer"},"code_execution_pool_size":{"description":"JavaScript runtime pool size (default: 10)","type":"integer"},"code_execution_timeout_ms":{"description":"Timeout in milliseconds (default: 120000, max: 600000)","type":"integer"},"data_dir":{"type":"string"},"debug_search":{"type":"boolean"},"direct_tool_response_mode":{"description":"DirectToolResponseMode selects the serialization of the DIRECT\nenumeration surface (Spec 102). Valid values: \"\" (= full), \"full\"\n(default: today's schema-bearing entries), \"deferred\" (description +\ncompact signature, with a minimal permissive input schema; upstream\ninputSchema and outputSchema are stripped and recovered on demand via\ndescribe_tool).\n\nDeliberately NOT an extension of tool_response_mode: reusing that axis\nwould silently change /mcp/all output for every deployment already\nrunning compact, which FR-015 forbids. Serialization-only — it never\nchanges WHICH tools are listed, only how (FR-008). Hot-reloadable.","type":"string"},"disable_management":{"type":"boolean"},"docker_isolation":{"$ref":"#/components/schemas/config.DockerIsolationConfig"},"docker_recovery":{"$ref":"#/components/schemas/config.DockerRecoveryConfig"},"enable_code_execution":{"description":"Code execution settings","type":"boolean"},"enable_prompts":{"description":"Prompts settings","type":"boolean"},"enable_skills":{"description":"EnableSkills, when true, makes mcpproxy read the skills that upstream\nservers expose through the MCP skills extension. OFF by default. Unlike\nEnablePrompts this is hot-reloadable. No CLI flag, no environment\nvariable.","type":"boolean"},"enable_socket":{"description":"Enable Unix socket/named pipe for local IPC (default: true)","type":"boolean"},"enable_tray":{"description":"Deprecated: EnableTray is unused and has no runtime effect. Kept for backward compatibility.","type":"boolean"},"environment":{"$ref":"#/components/schemas/secureenv.EnvConfig"},"features":{"$ref":"#/components/schemas/config.FeatureFlags"},"forward_client_headers":{"description":"ForwardClientHeaders is the global switch for client header forwarding\n(Spec 112): copying allowlisted headers from the inbound /mcp request into\nthe upstream tools/call request. nil (absent) means enabled; because every\nper-server forward_headers allowlist is empty by default, the default\nforwards nothing. false disables forwarding for every server. Read via\nIsClientHeaderForwardingEnabled(); MCPPROXY_FORWARD_CLIENT_HEADERS\noverrides it for the process. Distinct from ForwardedHeaders/trusted_proxies\n(Spec 107), which trusts inbound X-Forwarded-*.","type":"boolean"},"forward_proxy_env":{"description":"ForwardProxyEnv opts in to forwarding the ambient HTTP(S)/ALL/NO/FTP proxy\nenvironment variables to spawned stdio upstream servers (MCP-2769). OFF by\ndefault: proxy URLs commonly embed credentials (http://user:pass@proxy), so\nforwarding them to every upstream is a credential-leak risk. When enabled,\nvalues are forwarded with their userinfo (credentials) redacted.","type":"boolean"},"health_check_interval":{"description":"Discovery \u0026 health-check cadence (spec 074, #608). Both are *Duration\ntri-state pointers: nil = inherit the built-in default; a pointer to 0s =\nthe loop is disabled; a positive value = that interval. Defaults live only\nin the resolvers (ResolveHealthCheckInterval / ResolveToolDiscoveryInterval)\nso an unset key behaves exactly as before this feature (SC-005). Validated\nin Validate(): health-check ∈ {0} ∪ [5s,1h]; tool-discovery ∈ {0} ∪ [30s,24h].","type":"string"},"http_idle_timeout":{"description":"HTTPIdleTimeout caps how long an idle keep-alive connection is kept open.\nUnset = 180s. \"0s\" removes the dedicated idle deadline, but net/http then\nfalls back to ReadTimeout — idle is fully unbounded only when\nhttp_read_timeout is also \"0s\". Requires a restart.","type":"string"},"http_read_timeout":{"description":"HTTPReadTimeout caps how long reading a whole request (headers + body)\nmay take. Unset = 120s; \"0s\" disables it. Requires a restart.","type":"string"},"http_write_timeout":{"description":"HTTPWriteTimeout caps how long producing a whole response may take on\nnon-streaming endpoints (REST, Web UI, health). Unset = 120s; \"0s\"\ndisables it globally. MCP and SSE /events routes are exempt by design.","type":"string"},"init_timeout":{"description":"InitTimeout is the global default deadline for an upstream's MCP\n` + "`" + `initialize` + "`" + ` handshake (MCP-3322 / GH #760). *Duration tri-state: nil =\ninherit the built-in 30s default; a positive value = that deadline. A\nper-server InitTimeout overrides this. Resolved by ResolveInitTimeout;\nvalidated to {0} ∪ [1s, 30m] in Validate(). Servers doing legitimate\nfirst-run warmup (cache/index build) before answering ` + "`" + `initialize` + "`" + ` can\nraise this so they are not killed mid-startup.","type":"string"},"instructions":{"description":"Instructions text returned in the MCP initialize response to guide AI agents.\nWhen empty, a built-in default is used that explains retrieve_tools workflow.","type":"string"},"intent_declaration":{"$ref":"#/components/schemas/config.IntentDeclarationConfig"},"listen":{"type":"string"},"logging":{"$ref":"#/components/schemas/config.LogConfig"},"max_concurrent_requests":{"description":"Concurrency limits (spec 093, GH #955). Scope (a) of FR-020: the GLOBAL\nAGGREGATE limiter — one proxy-wide cap on concurrently running upstream\ntool calls, with its own bounded wait queue. Tri-state pointers: absent =\nthe limiter does not exist (default, zero behavior change); an explicit 0\nmax also disables it; positive = that cap. This scope is NEVER a\nper-server inheritance source — per-server values come from\nServerConcurrencyDefaults / the per-server overrides — but a server's\neffective concurrency is bounded by BOTH its own limiter and this one.\nResolved by ResolveGlobalConcurrency; hot-reloadable; overridable via\nMCPPROXY_MAX_CONCURRENT_REQUESTS / _QUEUE_SIZE / _QUEUE_TIMEOUT (FR-022).","type":"integer"},"max_result_size_chars":{"description":"MaxResultSizeChars is advertised on every tool as\n` + "`" + `_meta.anthropic/maxResultSizeChars` + "`" + `; it raises Claude Code's\ninline-response ceiling from 50k to up to 500k chars. Omit the key for\nthe 500000 default; set it to 0 to disable the annotation.","type":"integer"},"mcpServers":{"items":{"$ref":"#/components/schemas/config.ServerConfig"},"type":"array","uniqueItems":false},"mcp_oauth_enabled":{"description":"MCPOAuthEnabled turns on browser login (OAuth 2.1 + PKCE) for MCP\nclients on the loopback listener (Spec 132). Experimental, default false:\nwith it off nothing changes. Env override MCPPROXY_MCP_OAUTH_ENABLED is\nprocess-only and never persisted. Live, no restart needed.","type":"boolean"},"mcp_reject_query_apikey":{"description":"MCPRejectQueryAPIKey makes every MCP endpoint (/mcp*) refuse a request that\ncarries a ?apikey= query parameter, with a 401, instead of honouring it. A credential in a URL ends up in access logs,\nproxy logs and browser history; MCP clients can send Authorization:\nBearer or X-API-Key instead. Default false (the query form keeps\nworking, for clients that can only configure a URL). It covers only the\nMCP endpoints: the Web UI and its SSE stream (/events) still use the\nquery form. Live, no restart needed.","type":"boolean"},"oauth_expiry_warning_hours":{"description":"Health status settings","type":"number"},"oauth_token_encryption_key":{"description":"OAuthTokenEncryptionKey seals the upstream OAuth tokens stored in\nconfig.db (Spec 123). Empty (the default) leaves them as plain JSON. It\ntakes a secret reference (${file:/abs/path}, ${env:NAME},\n${keyring:NAME}) or a literal standard-base64 32-byte key; the\nMCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY[_FILE] variables override it. The key\nis resolved only where config.db is opened (ResolveOAuthTokenKey), never\nstored on Config, and is restart-gated, so every save writes the field\nas configured.","type":"string"},"observability":{"$ref":"#/components/schemas/config.ObservabilityConfig"},"output_sanitisation":{"$ref":"#/components/schemas/config.OutputSanitisationConfig"},"output_validation":{"$ref":"#/components/schemas/config.OutputValidationConfig"},"profiles":{"description":"Profiles are optional named, server-scoped views exposed at /mcp/p/\u003cname\u003e\n(Spec 057). Absent/empty is fully supported — /mcp is unchanged and configs\nwithout this key serialize byte-identically (SC-004).","items":{"$ref":"#/components/schemas/config.ProfileConfig"},"type":"array","uniqueItems":false},"quarantine_enabled":{"description":"QuarantineEnabled controls whether quarantine is active. It gates two\nthings together:\n 1. Server-level auto-quarantine for newly added servers (issue #370).\n When true, servers added via the upstream_servers MCP tool or the\n REST API default to quarantined=true; when false, they default to\n quarantined=false. Explicit per-request values always win.\n 2. Tool-level quarantine (Spec 032): per-tool SHA-256 approval of\n tool descriptions/schemas.\nWhen nil (default), quarantine is enabled (secure by default). Set to\nexplicit false to opt out of both. Per-server SkipQuarantine still\napplies for the tool-level check on individual servers.","type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"read_only_mode":{"type":"boolean"},"registries":{"description":"Registries configuration for MCP server discovery","items":{"$ref":"#/components/schemas/config.RegistryEntry"},"type":"array","uniqueItems":false},"registries_locked":{"description":"RegistriesLocked is an enterprise stub knob (MCP-866): when true, runtime\nadditions of custom registries (e.g. ` + "`" + `registry add-source` + "`" + `, the REST/MCP\nadd-source surface) are rejected so an administrator can pin the discovery\nsources. Built-in defaults are unaffected. Documented but otherwise inert\nbeyond the add-source rejection.","type":"boolean"},"require_mcp_auth":{"description":"Require authentication on /mcp endpoint (default: false)","type":"boolean"},"reveal_secret_headers":{"description":"RevealSecretHeaders, when true, disables the redaction of the\nsecret-bearing server fields — sensitive header values (Authorization,\nX-API-Key, Cookie, …), env-var secrets, and URL query credentials — in\nresponses from the ` + "`" + `upstream_servers` + "`" + ` MCP tool, the ` + "`" + `/api/v1/servers` + "`" + `\nREST API, and the SSE event stream. It also lets URL secrets echoed\ninto last_error / health.detail through unscrubbed.\n\nDefault false — sensitive values are surfaced masked as\n` + "`" + `••••\u003clast2\u003e (\u003cN\u003e chars)` + "`" + ` (error strings use ` + "`" + `***REDACTED***` + "`" + `) so an\nMCP agent cannot read Bearer tokens / API keys / URL secrets out of\nanother upstream's config (PR #425, issue #872). ${env:…}/${keyring:…}\nreferences are labels, not secrets, and pass through unchanged.\n\nThe Web UI / macOS tray edit forms work without seeing the real\nvalues: PATCH /api/v1/servers/{id} deep-merges (omitted keys are\npreserved, see ` + "`" + `headers_remove` + "`" + ` / ` + "`" + `env_remove` + "`" + ` for explicit\ndeletes), so clients compute a diff and only send the keys that\nactually changed. Redacted-but-unchanged values never round-trip\n— the backend keeps the real string. Set this to true if a\ndownstream tool genuinely needs raw values in the response.","type":"boolean"},"routing_mode":{"description":"Routing mode (Spec 031): how MCP tools are exposed to clients\nValid values: \"retrieve_tools\" (default), \"direct\", \"code_execution\"","type":"string"},"security":{"$ref":"#/components/schemas/config.SecurityConfig"},"sensitive_data_detection":{"$ref":"#/components/schemas/config.SensitiveDataDetectionConfig"},"server_concurrency_defaults":{"$ref":"#/components/schemas/config.ConcurrencyDefaults"},"session_retention_days":{"description":"SessionRetentionDays is how long a work session is listed and kept whole\nin the activity log (Spec 124, default 7). Read at start.","type":"integer"},"telemetry":{"$ref":"#/components/schemas/config.TelemetryConfig"},"tls":{"$ref":"#/components/schemas/config.TLSConfig"},"tokenizer":{"$ref":"#/components/schemas/config.TokenizerConfig"},"tool_call_max_records_per_server":{"description":"Calls retained per server (default: 1000)","type":"integer"},"tool_call_max_response_size":{"description":"Bounds for the per-server tool-call history behind GET /api/v1/tool-calls\n(#1176). It is a recent-debugging window, not an audit log — the activity\nlog is the durable record — and it kept every upstream response whole,\nper server, forever. A non-positive value means \"use the default\", not\n\"disable\": this store must never be unbounded again, so there is\ndeliberately no off switch.","type":"integer"},"tool_discovery_interval":{"type":"string"},"tool_response_limit":{"type":"integer"},"tool_response_mode":{"description":"Tool response mode (Spec 085): how retrieve_tools serializes results.\nValid values: \"\" (= full), \"full\" (default: today's schema-bearing\nentries), \"compact\" (signature + first-sentence entries). Orthogonal to\nrouting_mode — routing_mode selects the tool SURFACE, this selects the\nSERIALIZATION within the retrieve_tools surface. Serialization-only: it\nnever affects the query, ranking, or result set. Hot-reloadable.","type":"string"},"tool_response_session_risk_warning":{"description":"ToolResponseSessionRiskWarning controls whether the prose ` + "`" + `warning` + "`" + ` field\nis included in the ` + "`" + `session_risk` + "`" + ` object returned by ` + "`" + `retrieve_tools` + "`" + `.\nThe structured fields (level, lethal_trifecta, has_open_world_tools, etc.)\nare always included. Default: false (quiet for LLM clients) — see issue #406.\nMost tools lack annotations, so the MCP-spec defaults treat them as fully\npermissive across all three risk axes, which makes the prose warning fire\non almost every call and wastes tokens.","type":"boolean"},"tools_limit":{"type":"integer"},"toon_min_savings_pct":{"description":"ToonMinSavingsPct is the minimum byte-savings percentage (validated\n1-90; 0/unset → 15) the complete TOON emission (marker + hint + body)\nmust achieve over the exact passthrough emission for adaptive mode to\nencode a block. Byte savings approximate token savings for the tabular\npayload class; the spec-083 profiler reports true token deltas.\nGlobal-only (no per-server override, FR-001).","type":"integer"},"toon_output":{"description":"ToonOutput selects the TOON encoding mode for call_tool_* result text\nblocks (spec 084): \"off\" (default — responses byte-identical to\npre-feature behavior), \"adaptive\" (encode only tabular-uniform payloads\nthat beat compact JSON by ToonMinSavingsPct), or \"always\"\n(benchmark/debug only — encodes every JSON-parseable block and can\nINCREASE token cost). Per-server override: ServerConfig.ToonOutput.\nResolved by ResolveToonOutput; hot-reloadable.","type":"string"},"top_k":{"description":"Deprecated: TopK is superseded by ToolsLimit and has no runtime effect. Kept for backward compatibility.","type":"integer"},"tray_endpoint":{"description":"Tray endpoint override (unix:// or npipe://)","type":"string"},"trusted_hosts":{"description":"TrustedHosts lists non-loopback Host header values accepted on loopback\nlisteners (GH #898). DNS-rebinding protection rejects requests whose Host\nheader is not a loopback address when mcpproxy listens on loopback; a\nreverse proxy (nginx → 127.0.0.1) forwarding the public domain in Host\ntrips it. Entries are hostnames, case-insensitive; an entry without a\nport matches any port, with a port it must match exactly; a leading dot\n(\".example.com\") is a subdomain wildcard. The single entry \"*\" disables\nHost and Origin validation entirely. The same list also validates the\nOrigin header when present (MCP spec DNS-rebinding defense). Empty\n(default) keeps full protection. Env override: MCPPROXY_TRUSTED_HOSTS\n(comma-separated).","items":{"type":"string"},"type":"array","uniqueItems":false},"trusted_proxies":{"description":"TrustedProxies lists the CIDRs or IP addresses whose X-Forwarded-For /\nX-Real-IP / X-Forwarded-Proto / X-Forwarded-Host headers are believed\n(Spec 107 FR-027). Empty (default) trusts nobody. Edition-neutral, live\n(hot-reloadable). Env override: MCPPROXY_TRUSTED_PROXIES (comma-separated).\nThe one reader is ForwardedHeaders; validation is validateTrustedProxies.","items":{"type":"string"},"type":"array","uniqueItems":false},"update_check":{"$ref":"#/components/schemas/config.UpdateCheckConfig"}},"type":"object"},"config.CustomPattern":{"properties":{"category":{"description":"Category (defaults to \"custom\")","type":"string"},"keywords":{"description":"Keywords to match (mutually exclusive with Regex)","items":{"type":"string"},"type":"array","uniqueItems":false},"name":{"description":"Unique identifier for this pattern","type":"string"},"regex":{"description":"Regex pattern (mutually exclusive with Keywords)","type":"string"},"severity":{"description":"Risk level: critical, high, medium, low","type":"string"}},"type":"object"},"config.DeepScanConfig":{"description":"DeepScan is the opt-in \"deep scan\" layer (Spec 077 US3). It subsumes the\ndeprecated top-level scanner_fetch_package_source / scanner_disable_no_new_privileges\nkeys (migrated on load) and gates the heavy Docker-based scanners + source\nextraction. Disabled by default (FR-006): only the deterministic in-process\nbaseline scanner runs. A deep-scan failure NEVER changes the baseline verdict\n(FR-007/FR-008).","properties":{"disable_no_new_privileges":{"description":"DisableNoNewPrivileges, when true, omits the ` + "`" + `--security-opt\nno-new-privileges` + "`" + ` flag from scanner container runs (snap-docker/AppArmor\nescape hatch). Absorbs the deprecated top-level\nscanner_disable_no_new_privileges. Default false.","type":"boolean"},"enabled":{"description":"Enabled is the master opt-in for the heavy layer (FR-006). Default false.","type":"boolean"},"fetch_package_source":{"description":"FetchPackageSource controls whether the scanner fetches the PUBLISHED\nsource of package-runner servers (npx/uvx) — without executing it — when\nno local source is available. Absorbs the deprecated top-level\nscanner_fetch_package_source. Default (nil) is ENABLED within deep scan.","type":"boolean"},"scanners":{"description":"Scanners optionally restricts which deep scanners may run under the\numbrella (by scanner id). Empty ⇒ all enabled deep scanners are eligible.","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"config.DockerIsolationConfig":{"description":"Docker isolation settings","properties":{"cpu_limit":{"description":"CPU limit for containers","type":"string"},"default_images":{"additionalProperties":{"type":"string"},"description":"Map of runtime type to Docker image","type":"object"},"enable_cache_volume":{"description":"Mount shared cache volumes for faster restarts (default: true)","type":"boolean"},"enabled":{"description":"Global enable/disable for Docker isolation (legacy; superseded by Mode)","type":"boolean"},"extra_args":{"description":"Additional docker run arguments","items":{"type":"string"},"type":"array","uniqueItems":false},"log_driver":{"description":"Docker log driver (default: json-file)","type":"string"},"log_max_files":{"description":"Maximum number of log files (default: 3)","type":"string"},"log_max_size":{"description":"Maximum size of log files (default: 100m)","type":"string"},"memory_limit":{"description":"Memory limit for containers","type":"string"},"mode":{"description":"Isolation mode: \"docker\" | \"sandbox\" | \"none\" (MCP-34.2). Unset per-server inherits the global mode; unset globally falls back to the legacy \"enabled\" flag (true ⇒ docker, false ⇒ none)","type":"string","x-enum-varnames":["IsolationModeDocker","IsolationModeSandbox","IsolationModeNone"]},"network_mode":{"description":"Docker network mode (default: bridge)","type":"string"},"registry":{"description":"Custom registry (defaults to docker.io)","type":"string"},"timeout":{"description":"Container startup timeout","type":"string"}},"type":"object"},"config.DockerRecoveryConfig":{"description":"Docker recovery settings","properties":{"enabled":{"description":"Enable Docker recovery monitoring (default: true)","type":"boolean"},"max_retries":{"description":"Maximum retry attempts (0 = unlimited)","type":"integer"},"notify_on_failure":{"description":"Show notification on recovery failure (default: true)","type":"boolean"},"notify_on_retry":{"description":"Show notification on each retry (default: false)","type":"boolean"},"notify_on_start":{"description":"Show notification when recovery starts (default: true)","type":"boolean"},"notify_on_success":{"description":"Show notification on successful recovery (default: true)","type":"boolean"},"persistent_state":{"description":"Save recovery state across restarts (default: true)","type":"boolean"}},"type":"object"},"config.FeatureFlags":{"description":"Deprecated: Features flags are unused and have no runtime effect. Kept for backward compatibility.","properties":{"enable_async_storage":{"type":"boolean"},"enable_caching":{"type":"boolean"},"enable_contract_tests":{"type":"boolean"},"enable_debug_logging":{"description":"Development features","type":"boolean"},"enable_docker_isolation":{"type":"boolean"},"enable_event_bus":{"type":"boolean"},"enable_health_checks":{"type":"boolean"},"enable_metrics":{"type":"boolean"},"enable_oauth":{"description":"Security features","type":"boolean"},"enable_observability":{"description":"Observability features","type":"boolean"},"enable_quarantine":{"type":"boolean"},"enable_runtime":{"description":"Runtime features","type":"boolean"},"enable_search":{"description":"Storage features","type":"boolean"},"enable_sse":{"type":"boolean"},"enable_tracing":{"type":"boolean"},"enable_tray":{"type":"boolean"},"enable_web_ui":{"description":"UI features","type":"boolean"}},"type":"object"},"config.IntentDeclarationConfig":{"description":"Intent declaration settings (Spec 018)","properties":{"strict_server_validation":{"description":"StrictServerValidation controls whether server annotation mismatches\ncause rejection (true) or just warnings (false).\nDefault: true (reject mismatches)","type":"boolean"}},"type":"object"},"config.IsolationConfig":{"description":"Per-server isolation settings","properties":{"enabled":{"description":"Enable Docker isolation for this server (nil = inherit global; legacy, superseded by Mode)","type":"boolean"},"extra_args":{"description":"Additional docker run arguments for this server","items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"description":"Custom Docker image (overrides default)","type":"string"},"log_driver":{"description":"Docker log driver override for this server","type":"string"},"log_max_files":{"description":"Maximum number of log files override","type":"string"},"log_max_size":{"description":"Maximum size of log files override","type":"string"},"mode":{"$ref":"#/components/schemas/config.IsolationMode"},"network_mode":{"description":"Custom network mode for this server","type":"string"},"working_dir":{"description":"Custom working directory in container","type":"string"}},"type":"object"},"config.IsolationMode":{"description":"Isolation mode: \"docker\" | \"sandbox\" | \"none\" (MCP-34.2). Unset per-server inherits the global mode; unset globally falls back to the legacy \"enabled\" flag (true ⇒ docker, false ⇒ none)","type":"string","x-enum-varnames":["IsolationModeDocker","IsolationModeSandbox","IsolationModeNone"]},"config.LogConfig":{"description":"Logging configuration","properties":{"compress":{"type":"boolean"},"enable_console":{"type":"boolean"},"enable_file":{"type":"boolean"},"filename":{"type":"string"},"json_format":{"type":"boolean"},"level":{"type":"string"},"log_dir":{"description":"Custom log directory","type":"string"},"max_age":{"description":"days","type":"integer"},"max_backups":{"description":"number of backup files","type":"integer"},"max_size":{"description":"MB","type":"integer"}},"type":"object"},"config.MetricsExporterConfig":{"description":"Metrics gates the Prometheus /metrics scrape endpoint (MCP-32). Disabled\nby default — operators opt in for k8s/enterprise deployments.","properties":{"enabled":{"description":"Enabled exposes /metrics on the existing HTTP listener when true.\nThe endpoint is admin-authenticated (SEC-07): scrapers must present the\nglobal API key, via X-API-Key or an Authorization: Bearer header.","type":"boolean"}},"type":"object"},"config.OAuthConfig":{"description":"OAuth configuration (keep even when empty to signal OAuth requirement)","properties":{"auth_server_metadata_url":{"type":"string"},"authorization_endpoint":{"description":"Spec 113-b: optional per-server discovery overrides. Each is an absolute\nhttps URL (http only on a loopback host) with no query, fragment or\nuserinfo; validated at write time only (ValidateOAuthEndpointOverrides).\nThe endpoint overrides rewrite the matching fields of the authorization\nserver metadata mcp-go reads; AuthServerMetadataURL replaces discovery.","type":"string"},"callback_base_url":{"type":"string"},"client_id":{"type":"string"},"client_secret":{"type":"string"},"extra_params":{"additionalProperties":{"type":"string"},"description":"Additional OAuth parameters (e.g., RFC 8707 resource)","type":"object"},"pkce_enabled":{"type":"boolean"},"redirect_uri":{"type":"string"},"refresh_replay_enabled":{"description":"Opt in only when token_endpoint supports idempotent refresh replay for at least 30 seconds.","type":"boolean"},"registration_endpoint":{"type":"string"},"scopes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"token_endpoint":{"type":"string"}},"type":"object"},"config.ObservabilityConfig":{"description":"Observability settings (Spec 069): usage aggregate cache/persistence cadence.","properties":{"metrics":{"$ref":"#/components/schemas/config.MetricsExporterConfig"},"tracing":{"$ref":"#/components/schemas/config.TracingExporterConfig"},"usage_cache_ttl":{"description":"UsageCacheTTL bounds the freshness of the usage endpoint's read cache for\nwide windows (FR-005). Default 5s.","type":"string"},"usage_persist_interval":{"description":"UsagePersistInterval is how often the actor-owned usage aggregate snapshot\nis flushed to storage. Default 30s.","type":"string"}},"type":"object"},"config.OutputSanitisationConfig":{"description":"Output sanitisation settings (Spec 054 Track B)","properties":{"max_redactions":{"description":"cap on redactions per response; default 100","type":"integer"},"response_action":{"description":"\"spotlight\" | \"redact\" | \"block\"; default \"spotlight\"","type":"string"},"spotlight_untrusted":{"description":"wrap untrusted output in spotlight markers; default true","type":"boolean"},"strip_classes":{"description":"classes to strip: ansi/c0c1/bidi/zero_width","items":{"type":"string"},"type":"array","uniqueItems":false},"strip_control_chars":{"description":"strip control-character classes; default false","type":"boolean"}},"type":"object"},"config.OutputValidationConfig":{"description":"Output-schema validation settings (Spec 056)","properties":{"max_bytes":{"description":"structured payload byte cap; default 5\u003c\u003c20","type":"integer"},"max_depth":{"description":"nesting depth cap; default 64","type":"integer"},"missing_structured_content":{"description":"\"allow\" | \"block\"; default \"allow\"","type":"string"},"mode":{"description":"\"off\" | \"warn\" | \"strict\"; default \"warn\"","type":"string"}},"type":"object"},"config.ProfileConfig":{"properties":{"code_execution":{"description":"CodeExecution: nil = inherit the global enable_code_execution gate;\nnon-nil narrows it (a profile can only narrow, never widen, FR-006).","type":"boolean"},"description":{"description":"\u003c= 500 chars (FR-001)","type":"string"},"management_tools":{"description":"ManagementTools: nil = legacy/inherit (FR-016); non-nil sets the\nprofile-level visibility of upstream_servers/quarantine_security.","type":"boolean"},"max_tier":{"description":"MaxTier caps the tier a tool may run at under this profile: \"\" (no\ncap) | \"read\" | \"write\" | \"destructive\" (FR-001).","type":"string"},"name":{"description":"slug (Spec 057 rules unchanged)","type":"string"},"servers":{"description":"references to mcpServers[].name","items":{"type":"string"},"type":"array","uniqueItems":false},"switchable_to":{"description":"SwitchableTo is the list of profile names a session under this\nprofile may ` + "`" + `set_profile` + "`" + ` into (FR-022). nil = legacy/none (research\nD6); a non-nil EMPTY list is an explicit \"none\" and must round-trip as\n` + "`" + `[]` + "`" + `, never be dropped by omitempty — hence the pointer (see the\nMarshalJSON note below, and profiles_v3_test.go's switchable_to round\ntrip case).","items":{"type":"string"},"type":"array","uniqueItems":false},"title":{"description":"display only, \u003c= 80 chars (FR-001)","type":"string"},"tools":{"$ref":"#/components/schemas/config.ProfileToolRules"},"unannotated":{"description":"Unannotated is this profile's handling of a tool whose effective\nannotations carry no tier hint: \"\" (unset, see EffectiveUnannotated) |\n\"deny\" | \"as_write\" | \"as_read\" (FR-001, FR-003).","type":"string"}},"type":"object"},"config.ProfileToolRules":{"description":"Tools holds the allow/deny/classify rule set (FR-001, FR-004, FR-005).","properties":{"allow":{"items":{"type":"string"},"type":"array","uniqueItems":false},"classify":{"additionalProperties":{"type":"string"},"type":"object"},"deny":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"config.RegistryEntry":{"properties":{"count":{"description":"number or string","type":"string"},"description":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"},"protocol":{"type":"string"},"provenance":{"description":"Provenance is the trust tag for this registry (MCP-866):\nRegistryProvenanceOfficial for built-in defaults, RegistryProvenanceCustom\nfor user-added registries. It is authoritatively (re)computed by the\nregistries merge from whether the ID is a shipped default — a user cannot\nclaim \"official\" by writing it into their config.","type":"string"},"requires_key":{"description":"RequiresKey marks a registry that needs an API key to be queried. When\ntrue and no key is configured, the registry is skipped/marked unavailable\nrather than failing the whole search (FR-008).","type":"boolean"},"servers_url":{"type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"url":{"type":"string"}},"type":"object"},"config.SecurityConfig":{"description":"Security scanner settings (Spec 039)","properties":{"auto_baseline_scan":{"description":"AutoBaselineScan is the kill-switch for the AUTOMATIC, informational\nPass-1 baseline scan: the free in-process TPA scan mcpproxy runs for every\nnewly admitted server (any trust mode) and, once per installation, over\npre-existing servers that have never been scanned.\n\nInformational ONLY: the resulting verdict populates the security badge and\nthe scan summary, and NEVER gates quarantine or approval. The\ntrust_mode:\"scan\" admission gate is a separate path and is unaffected by\nthis flag.\n\nDefault (nil) is ENABLED. Set to false to suppress every automatic scan\n(manual scans keep working). Env override: MCPPROXY_AUTO_BASELINE_SCAN,\nwhich wins over this field on every path.","type":"boolean"},"auto_rescan_on_change":{"description":"AutoRescanOnChange is the finer switch for the automatic, informational\nrescan that follows a tool-definition hash change: the in-process TPA scan\nof the changed (or newly pending) tool, recorded as hold evidence, and a\ndebounced informational server rescan that brings the review screen's scan\ncoverage back to \"current\".\n\nEvidence and freshness ONLY: this switch approves nothing. Under \"manual\"\nevery change is held for review whatever the verdict (RT-02); under\n\"scan\" the gate's own synchronous scan approves a clean change that\npasses the spec 120 structural gate (spec 119 FR-004), and this switch\ndoes not affect that path. Runs in every trust mode except \"auto\".\n\nDefault (nil) is ENABLED. It only takes effect while auto_baseline_scan is\nalso enabled, so a user can keep the admission scan and turn off per-change\nrescans with this key alone. Env override: MCPPROXY_AUTO_RESCAN_ON_CHANGE,\nwhich wins over this field on every path.","type":"boolean"},"deep_scan":{"$ref":"#/components/schemas/config.DeepScanConfig"},"integrity_check_interval":{"type":"string"},"integrity_check_on_restart":{"type":"boolean"},"require_signed_bundle":{"description":"RequireSignedBundle makes the detached signature sidecar mandatory for\nfile-dropped bundles (FR-007). Default false (maintainer decision D2):\nexisting unsigned drops keep working, but an unsigned external bundle\nalways runs with DEGRADED coverage (scan-mode auto-approval suspended).","type":"boolean"},"runtime_read_only":{"type":"boolean"},"runtime_tmpfs_size":{"type":"string"},"scan_timeout_default":{"type":"string"},"scanner_disable_no_new_privileges":{"description":"Deprecated (Spec 077 US3): migrated on load into DeepScan.DisableNoNewPrivileges\n(see migrateDeepScanConfig). Retained only so existing configs that still carry\nthe top-level key parse; consumers MUST read the effective value via\nSecurityConfig.IsDisableNoNewPrivileges. Cleared after migration.\n\nScannerDisableNoNewPrivileges, when true, omits the\n` + "`" + `--security-opt no-new-privileges` + "`" + ` flag from scanner container runs.\n\nBackground: snap-installed Docker on Ubuntu confines dockerd under the\n` + "`" + `snap.docker.dockerd` + "`" + ` AppArmor profile. When runc tries to transition\nthe container into the inner ` + "`" + `docker-default` + "`" + ` profile to exec the\nentrypoint, AppArmor refuses the transition because NO_NEW_PRIVS\nforbids privilege/profile changes on exec — the result is EPERM\n(\"operation not permitted\") and every scanner fails immediately.\n\nSet this to true ONLY on hosts hitting that incompatibility. Scanner\ncontainers still run with read-only rootfs, tmpfs /tmp, no-network by\ndefault, and read-only source mounts, so the marginal isolation loss\nis small. The preferred fix remains replacing snap docker with a\ndistro-packaged docker.","type":"boolean"},"scanner_fetch_package_source":{"description":"Deprecated (Spec 077 US3): migrated on load into DeepScan.FetchPackageSource\n(see migrateDeepScanConfig). Retained only so existing configs that still carry\nthe top-level key parse; consumers MUST read the effective value via\nSecurityConfig.EffectiveFetchPackageSource. Cleared after migration.\n\nScannerFetchPackageSource controls whether the scanner fetches the\nPUBLISHED source of package-runner servers (npx/uvx) — without executing\nit — when no local source is available (no Docker container, no local\npackage cache, no working_dir). This is the primary quarantine/scan\ntarget: a quarantined-on-add server is never run locally, so without this\nthe scan degrades to tool-definitions-only (no real source-level\nanalysis). See MCP-2206.\n\nFetching uses ` + "`" + `npm pack --ignore-scripts` + "`" + ` (npm) and ` + "`" + `uv pip download` + "`" + ` /\n` + "`" + `pip download` + "`" + ` with ` + "`" + `--only-binary=:all:` + "`" + ` (Python), which only download +\nunpack archives and NEVER run install, build, or setup.py — a scanner must\nnot execute the untrusted code it is scanning. The Python\n` + "`" + `--only-binary=:all:` + "`" + ` flag is required because downloading an sdist would\ninvoke its build backend (setup.py); packages with no wheel fall back to\ntool-definitions-only instead. Extraction is hardened against path\ntraversal and decompression bombs.\n\nDefault (nil) is ENABLED. Set to false on air-gapped deployments to\nforbid the scanner's network egress; such servers then fall back to the\ntool-definitions-only scan with no regression.","type":"boolean"},"scanner_registry_url":{"type":"string"},"tpa_active_root":{"description":"TPAActiveRoot declares which signing authority's bundles may activate\n(FR-004b): \"publisher\" (default, the keys embedded in this binary) or\n\"operator\" (TPAOperatorSigners). A bundle verified by the other root is\nrefused as authority_not_active, so whoever can write the bundle path\ncannot choose the authority.","type":"string"},"tpa_bundle_path":{"description":"TPABundlePath is the filesystem path to the tpa-db scanner-bundle.json\nthe offline TPA scanner runs (spec 086 FR-019: the signature-DB location\nMUST be configuration-driven, not hardcoded). Empty (the default) runs the\ncorpus embedded in this build.\n\nEnv override: MCPPROXY_TPA_BUNDLE_PATH. Hot-reloadable — the path is\nre-read on every config.reloaded event via\nscanner.Service.ApplySecurityConfig, so a corpus refresh needs no restart.\nA configured bundle that fails to read/parse/version-check/compile is\nREFUSED and the previously active corpus stays live (fail-closed, never\nfail-empty); the reason is logged and surfaced in the security overview's\nsignature_bundle.load_error.","type":"string"},"tpa_fetch_enabled":{"description":"TPAFetchEnabled opts in to the network fetch leg. Default false; the\nenvironment override is MCPPROXY_TPA_FETCH_ENABLED (EnvTPAFetchEnabled).","type":"boolean"},"tpa_fetch_url":{"description":"TPAFetchURL is the channel URL: a GitHub Releases \"latest\" API URL or a\ndirect bundle URL. Empty (the default) means the fetch leg is off; no URL\nis compiled into the binary.","type":"string"},"tpa_operator_baseline":{"description":"TPAOperatorBaseline seeds the operator authority's anti-downgrade\nwatermark (FR-009b): an operator-signed bundle must carry a sequence\nABOVE it (a rollback target may sit at it). It survives a data-directory\nwipe because it lives here. Absent means the operator authority has no\nanti-downgrade floor and an active operator bundle runs DEGRADED.","type":"integer"},"tpa_operator_epoch":{"description":"TPAOperatorEpoch is the operator authority's trust epoch (FR-005a).\nBumping it (after an operator key compromise) re-baselines the operator\nwatermark and retires prior-epoch pins. Absent means 0.","type":"integer"},"tpa_operator_signers":{"description":"TPAOperatorSigners lists operator Ed25519 public keys, each the standard\nbase64 encoding of the 32 raw key bytes (FR-004). Their key ids are the\nlowercase-hex SHA-256 of those bytes. Malformed or duplicate entries are\nrejected on write and dropped (with a log) on load.","items":{"type":"string"},"type":"array","uniqueItems":false},"tpa_refresh_interval":{"description":"TPARefreshInterval is the cadence of the refresh cycle (the network-free\nfile leg, then the optional fetch leg). Absent or 0 means 24h; the runtime\nclamps to at least 1h. There is no refresh-enable key: the file leg is\nidempotent and always on.","type":"string"},"tpa_stale_after_days":{"description":"TPAStaleAfterDays is the age in days after which the active bundle reads\nas stale. Absent means 30; an explicit 0 disables the stale flag and the\ndoctor stale warning.","type":"integer"}},"type":"object"},"config.SensitiveDataDetectionConfig":{"description":"Sensitive data detection settings (Spec 026)","properties":{"categories":{"additionalProperties":{"type":"boolean"},"description":"Enable/disable specific detection categories","type":"object"},"custom_patterns":{"description":"User-defined detection patterns","items":{"$ref":"#/components/schemas/config.CustomPattern"},"type":"array","uniqueItems":false},"enabled":{"description":"Enable sensitive data detection (default: true)","type":"boolean"},"entropy_threshold":{"description":"Shannon entropy threshold for high-entropy detection (default: 4.5)","type":"number"},"max_payload_size_kb":{"description":"Max size to scan before truncating (default: 1024)","type":"integer"},"scan_requests":{"description":"Scan tool call arguments (default: true)","type":"boolean"},"scan_responses":{"description":"Scan tool responses (default: true)","type":"boolean"},"sensitive_keywords":{"description":"Keywords to flag","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"config.ServerConfig":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges is the per-server intent to auto-approve tool\nchanges/additions (disabling per-server rug-pull protection). Supersedes\nskip_quarantine. MCP-2930 only ACCEPTS, persists, and migrates this flag — it\nis NOT yet consulted at runtime; auto-approval is still governed by\nSkipQuarantine until the trust-baseline behavior change (MCP-2931) migrates the\nruntime consumers onto it.\nTri-state pointer (mirrors QuarantineEnabled): nil = unset (inherit/migrate\nfrom legacy skip_quarantine), explicit true/false = honored as-is so an\nexplicit auto_approve_tool_changes:false overrides a legacy skip_quarantine:true.\nRead via IsAutoApproveToolChanges().","type":"boolean"},"command":{"type":"string"},"created":{"type":"string"},"disabled_tools":{"description":"Denylist: these tools are hidden; mutually exclusive with enabled_tools","items":{"type":"string"},"type":"array","uniqueItems":false},"enabled":{"type":"boolean"},"enabled_tools":{"description":"Allowlist: only these tools are exposed; mutually exclusive with disabled_tools","items":{"type":"string"},"type":"array","uniqueItems":false},"env":{"additionalProperties":{"type":"string"},"type":"object"},"expose_prompts":{"description":"ExposePrompts overrides whether this server's advertised MCP prompts are\naggregated into mcpproxy's prompts/list. nil (default) inherits the\ndefault-aggregate behavior (included if the server advertises\nCapabilities.Prompts); false excludes it regardless of capability.","type":"boolean"},"expose_skills":{"description":"ExposeSkills overrides whether this server's skills (MCP skills\nextension) are read when Config.EnableSkills is on. nil (default)\ninherits (included if the server supports skills); false excludes it.","type":"boolean"},"forward_headers":{"description":"ForwardHeaders lists inbound MCP-client header NAMES (never values) that\nare copied into this server's upstream tools/call requests (Spec 112).\nExact names, case-insensitive, at most 32, no wildcards. Empty forwards\nnothing. Only HTTP-based transports (http, streamable-http) forward; the\ndeny list (Authorization, Host, hop-by-hop, ...) is enforced at runtime\nregardless of what is configured here.","items":{"type":"string"},"type":"array","uniqueItems":false},"headers":{"additionalProperties":{"type":"string"},"description":"For HTTP servers","type":"object"},"health_check_interval":{"description":"Per-server discovery \u0026 health-check overrides (spec 074). Same *Duration\ntri-state as the global keys: nil = inherit the global value (or default),\npointer to 0s = disabled for this server, positive = that interval.\nHealthCheckInterval is fully wired into the per-server health loop;\nToolDiscoveryInterval is accepted/validated and round-trips for\nforward-compat, but the periodic index sweep is governed by the global\ncadence in this iteration (see spec 074 plan §C).","type":"string"},"init_timeout":{"description":"InitTimeout overrides the global init_timeout for this server's MCP\n` + "`" + `initialize` + "`" + ` handshake deadline (MCP-3322 / GH #760). *Duration tri-state:\nnil = inherit the global value (or 30s default), positive = that deadline.\nResolved by Config.ResolveInitTimeout; validated to {0} ∪ [1s, 30m]. Raise\nthis for upstreams that do legitimate first-run warmup (e.g. caching many\nchannels/users) before responding to ` + "`" + `initialize` + "`" + `.","type":"string"},"isolation":{"$ref":"#/components/schemas/config.IsolationConfig"},"launcher_wait_timeout":{"description":"LauncherWaitTimeout caps how long mcpproxy will wait for a locally-launched\nHTTP/SSE upstream's URL to become reachable after Spawn(). Only consulted\nwhen the server is configured with both Command and an HTTP/SSE URL — i.e.,\nmcpproxy starts the process AND connects via network. Stdio servers ignore\nthis field. Zero or unset → 30s default.","type":"string"},"max_concurrent_requests":{"description":"Per-server concurrency overrides — scope (c) of FR-020 (spec 093, #955).\nTri-state per setting, exactly like HealthCheckInterval: absent = inherit\nthe per-server default set (server_concurrency_defaults), explicit 0 =\ndisable that setting for this server (0 max = no per-server limiter at\nall; 0 queue_size = no pending capacity, shed immediately at the cap),\npositive = override. The global aggregate limiter is never inherited from\nhere — it applies on top, so effective concurrency is min(per-server,\nglobal). Resolved by Config.ResolveServerConcurrency.","type":"integer"},"name":{"type":"string"},"oauth":{"$ref":"#/components/schemas/config.OAuthConfig"},"protocol":{"description":"stdio, http, sse, streamable-http, auto","type":"string"},"quarantined":{"description":"Security quarantine status","type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_on_use":{"description":"Attempt reconnection when a tool call targets a disconnected server","type":"boolean"},"shared":{"description":"Server edition: shared with all users","type":"boolean"},"skip_quarantine":{"description":"SkipQuarantine is DEPRECATED (MCP-2930): use AutoApproveToolChanges instead.\nKept for back-compat parsing; on config load a legacy skip_quarantine:true is\nmigrated to auto_approve_tool_changes:true only when the new field is unset\n(see normalizeServerQuarantineFlags).","type":"boolean"},"source_registry_id":{"description":"SourceRegistryID records which registry this server was added from (empty\nfor manually-configured servers). MCP-866: surfaced in the approval /\nquarantine view so a reviewer can see a server's origin.","type":"string"},"source_registry_provenance":{"description":"SourceRegistryProvenance records the source registry's provenance at add\ntime (RegistryProvenanceOfficial / RegistryProvenanceCustom). It is purely\ninformational (MCP-1072) — surfaced so a reviewer can see a server's origin\n— and no longer gates quarantine or skip_quarantine.","type":"string"},"tool_argument_error_mode":{"description":"ToolArgumentErrorMode stores the per-upstream argument-error policy.\nEmpty and detailed retain detailed errors; redacted opts into redaction.\nUpdates omit/keep an empty value; detailed explicitly resets the policy.","type":"string"},"tool_discovery_interval":{"type":"string"},"toon_output":{"description":"ToonOutput overrides the global toon_output mode for this server's\ntools (spec 084, FR-001). Plain string, not a pointer: \"\"/absent =\ninherit the global value; \"off\"|\"adaptive\"|\"always\" = override (\"off\"\nis the explicit force-off). Resolved by Config.ResolveToonOutput.","type":"string"},"trust_mode":{"description":"TrustMode is the per-server trust tier: auto|scan|manual. Supersedes\nauto_approve_tool_changes (spec 086). An empty value is derived from the\nlegacy fields at load via normalizeServerQuarantineFlags; the single\nresolution point is EffectiveTrustMode(), which treats an empty value as\nscan (DefaultTrustMode, spec 119) and an unrecognized value as manual\n(fail closed). Read via\nEffectiveTrustMode(), never the raw string.","type":"string"},"updated":{"type":"string"},"url":{"type":"string"},"working_dir":{"description":"Working directory for stdio servers","type":"string"}},"type":"object"},"config.TLSConfig":{"description":"TLS configuration","properties":{"cert_file":{"description":"CertFile is the absolute path of an operator-provided server certificate\n(PEM, leaf first), served instead of a generated one. Needs KeyFile.","type":"string"},"certs_dir":{"description":"Directory for certificates","type":"string"},"enabled":{"description":"Enable HTTPS","type":"boolean"},"extra_sans":{"description":"ExtraSANs are DNS names and IP addresses added to the generated server\ncertificate, which is signed by the same local CA. Not used with CertFile.","items":{"type":"string"},"type":"array","uniqueItems":false},"hsts":{"description":"Enable HTTP Strict Transport Security","type":"boolean"},"key_file":{"description":"KeyFile is the absolute path of the private key for CertFile (PEM).","type":"string"},"require_client_cert":{"description":"Enable mTLS","type":"boolean"}},"type":"object"},"config.TelemetryConfig":{"description":"Telemetry settings (Spec 036)","properties":{"anonymous_id":{"description":"Auto-generated UUIDv4","type":"string"},"anonymous_id_created_at":{"description":"Spec 042 (Tier 2) additions — all default-zero, all backwards-compatible.","type":"string"},"enabled":{"description":"Default: true (opt-out)","type":"boolean"},"endpoint":{"description":"Override for testing","type":"string"},"last_reported_version":{"description":"Upgrade funnel","type":"string"},"last_startup_outcome":{"description":"success|port_conflict|db_locked|...","type":"string"},"notice_shown":{"description":"First-run notice flag","type":"boolean"}},"type":"object"},"config.TokenizerConfig":{"description":"Tokenizer configuration for token counting","properties":{"default_model":{"description":"Default model for tokenization (e.g., \"gpt-4\")","type":"string"},"enabled":{"description":"Enable token counting","type":"boolean"},"encoding":{"description":"Default encoding (e.g., \"cl100k_base\")","type":"string"}},"type":"object"},"config.TracingExporterConfig":{"description":"Tracing gates the OpenTelemetry OTLP trace exporter (MCP-32). Disabled by\ndefault.","properties":{"enabled":{"description":"Enabled turns on OTLP trace export for tool calls and upstream hops.","type":"boolean"},"endpoint":{"description":"Endpoint is the collector address as host:port (no scheme), e.g.\n\"localhost:4318\" for http or \"localhost:4317\" for grpc.","type":"string"},"protocol":{"description":"Protocol selects the OTLP transport: \"http\" or \"grpc\".","type":"string"},"sample_rate":{"description":"SampleRate is the head-based trace sampling ratio in [0,1]. Default 0.1.\nOmit the key for the 0.1 default; set it to 0 to sample nothing.","type":"number"}},"type":"object"},"config.UpdateCheckConfig":{"description":"Update-check settings (Spec 079 FR-012): config-file control of the\nbackground upgrade-awareness checker (internal/updatecheck). nil =\nenabled on the stable channel (existing default behavior). The existing\nenvironment switches keep working and WIN over these keys (FR-014):\nMCPPROXY_DISABLE_AUTO_UPDATE=true force-disables even when\nenabled=true, and MCPPROXY_ALLOW_PRERELEASE_UPDATES=true force-selects\nthe rc channel even when channel=stable.","properties":{"channel":{"description":"Channel selects which releases are offered as updates: \"stable\"\n(default; prereleases never offered) or \"rc\" (prereleases included).\nEmpty resolves to stable. Validated in ValidateDetailed.\n\nNOTE: for a RELEASED build the running binary's own version is\nauthoritative and overrides this field — a stable build is never\noffered an RC (even with channel=rc), and an RC build always tracks the\nrc channel. This field only takes effect on dev/unstamped builds. See\ninternal/updatecheck.Checker.IncludePrereleases.","type":"string"},"enabled":{"description":"Enabled gates all update checking. Tri-state: nil/absent = enabled\n(default true, matching pre-079 behavior). When false, no network\ncheck is performed and no upgrade nudge appears on any surface\n(FR-015) — /api/v1/info omits the update object entirely.","type":"boolean"}},"type":"object"},"configimport.FailedServer":{"properties":{"details":{"type":"string"},"error":{"type":"string"},"name":{"type":"string"}},"type":"object"},"configimport.ImportSummary":{"properties":{"failed":{"type":"integer"},"imported":{"type":"integer"},"skipped":{"type":"integer"},"total":{"type":"integer"}},"type":"object"},"configimport.SkippedServer":{"properties":{"name":{"type":"string"},"reason":{"description":"\"already_exists\", \"filtered_out\", \"invalid_name\", \"self_reference\"","type":"string"}},"type":"object"},"connect.ConnectResult":{"description":"The full result; its action mirrors the top-level one","properties":{"action":{"description":"\"created\", \"updated\", \"already_exists\", \"removed\", \"not_found\"","type":"string"},"backup_path":{"type":"string"},"client":{"type":"string"},"config_path":{"type":"string"},"credential":{"description":"Credential is the masked client credential the write embedded\n(` + "`" + `mcp_cli_••••` + "`" + `); the real secret is never returned (FR-024). Empty for a\nkeyless entry, a disconnect and every refusal.","type":"string"},"credential_revoke_error":{"description":"CredentialRevokeError is set when a disconnect removed the entry but\nrevoking the client credential failed. The disconnect still succeeded;\nthe credential is still active and ` + "`" + `mcpproxy client forget \u003cid\u003e` + "`" + `\nretries the revoke.","type":"string"},"credential_revoked":{"description":"CredentialRevoked names the credential that was revoked: by an undo,\nbecause the restored config no longer holds it (plan D16), or by a\ndisconnect, which cuts the client off (a later undo of that disconnect\ndoes not bring the credential back).","type":"string"},"display_path":{"description":"DisplayPath is ConfigPath with the home directory shortened to \"~\"\n(FR-037). Populated for every result whose ConfigPath is known.","type":"string"},"keyless":{"description":"Keyless is true when the entry was written with no credential.","type":"boolean"},"message":{"type":"string"},"mode":{"type":"string"},"profile":{"description":"Profile and Mode are the binding of the credential this write minted or\nkept. Profile \"\" means the built-in All servers scope.","type":"string"},"reload_hint":{"description":"ReloadHint is this client's instruction for making the write take\neffect (FR-037/FR-042), e.g. \"Restart Cursor to load MCPProxy\". Empty\nfor an unknown client.","type":"string"},"rotation":{"description":"Rotation is \"finalized\" when the write replaced an active credential's\nsecret (staged rotation, FR-021a), empty otherwise.","type":"string"},"server_name":{"type":"string"},"success":{"type":"boolean"},"token_name":{"description":"TokenName is the client credential's token name (` + "`" + `client-\u003cid\u003e` + "`" + `).","type":"string"}},"type":"object"},"contracts.APIResponse":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.ActivityDetailResponse":{"properties":{"activity":{"$ref":"#/components/schemas/contracts.ActivityRecord"}},"type":"object"},"contracts.ActivityListResponse":{"properties":{"activities":{"items":{"$ref":"#/components/schemas/contracts.ActivityRecord"},"type":"array","uniqueItems":false},"limit":{"type":"integer"},"offset":{"type":"integer"},"total":{"type":"integer"}},"type":"object"},"contracts.ActivityPerServer":{"properties":{"calls":{"description":"Calls counted per storage.CountsAsCall","type":"integer"},"errors":{"description":"Of those calls, how many failed","type":"integer"},"last_call_at":{"description":"LastCallAt is RFC3339, or \"\" if the server had no call in the period\n(PerServer only lists servers that did, so this is always set).","type":"string"},"name":{"description":"Server name","type":"string"}},"type":"object"},"contracts.ActivityRecord":{"description":"Activity is the stored row; absent on a session_start or session_end\nrow.","properties":{"agent_name":{"description":"Agent token name when auth_type is \"agent\"","type":"string"},"arguments":{"description":"Tool call arguments","type":"object"},"auth_type":{"description":"\"admin\", \"agent\", \"user\" or \"admin_user\"; empty without an auth context or on another caller's row for a scoped caller","type":"string"},"block_reason":{"description":"Typed cause of a profile policy refusal","type":"string"},"client_id":{"description":"Client id from the client-credential binding","type":"string"},"client_name":{"description":"Self-reported clientInfo.name (advisory)","type":"string"},"detection_types":{"description":"List of detection types found","items":{"type":"string"},"type":"array","uniqueItems":false},"duration_ms":{"description":"Execution duration in milliseconds","type":"integer"},"error_class":{"description":"Call-error taxonomy (Spec 113-c FR-045): what failed and whose fault it\nis. Absent on success and on records written before Spec 113.","type":"string"},"error_message":{"description":"Error details if status is \"error\"","type":"string"},"fault_domain":{"description":"upstream|proxy|client","type":"string"},"has_sensitive_data":{"description":"Sensitive data detection fields (Spec 026)","type":"boolean"},"id":{"description":"Unique identifier (ULID format)","type":"string"},"max_severity":{"description":"Highest severity level detected (critical, high, medium, low)","type":"string"},"metadata":{"description":"Additional context-specific data","type":"object"},"parent_id":{"description":"Correlation id of the parent call (the code_execution whose sandbox issued this sub-call)","type":"string"},"profile":{"description":"Scope attribution (Spec 108 FR-029): the profile, client and token in\neffect when the call ran. Stamped at write time, never rewritten. For a\nscoped (non-admin) caller the profile/profile_source/client_id/token_name\nof a row it did not make are blanked (binding disclosure is admin-only);\nclient_name is self-reported and stays. Absent on records written before\nSpec 108 and on records with no MCP/REST request context.","type":"string"},"profile_source":{"description":"pin|binding|url|session|anonymous|none","type":"string"},"request_bytes":{"description":"Byte sizes measured pre-truncation, mirroring storage.ActivityRecord\n(Spec 069 A1). They are the only cost signal a bodies-off export carries:\nwith payloads suppressed there is no text left to measure, so a consumer\naccounting for a record it cannot read has nothing else to go on. They are\nbyte LENGTHS, not token counts — the basis for an explicit estimate, never\na measured figure (spec 103, contracts/replay-input.md).\n\nZero means UNKNOWN, not free: legacy records predate the measurement and\ncode-execution sub-calls record both as zero. Hence omitempty — an absent\nkey tells a consumer to fall to exclusion accounting, whereas a present\nzero would read as a costless call and silently understate the workload.","type":"integer"},"request_id":{"description":"HTTP request ID for correlation","type":"string"},"response":{"description":"Tool response (potentially truncated)","type":"string"},"response_bytes":{"description":"Raw upstream response size in bytes before truncation","type":"integer"},"response_truncated":{"description":"True if response was truncated","type":"boolean"},"server_name":{"description":"Name of upstream MCP server","type":"string"},"session_id":{"description":"MCP transport session ID (regenerated on every reconnect)","type":"string"},"source":{"$ref":"#/components/schemas/contracts.ActivitySource"},"status":{"description":"Result status: \"success\", \"error\", \"blocked\", \"rejected\"","type":"string"},"timestamp":{"description":"When activity occurred","type":"string"},"token_name":{"description":"Agent/client token name","type":"string"},"tool_name":{"description":"Name of tool called","type":"string"},"type":{"$ref":"#/components/schemas/contracts.ActivityType"},"upstream_http_status":{"description":"Upstream HTTP status when known","type":"integer"},"work_session_id":{"description":"Spec 082: one client, one project, across reconnects","type":"string"}},"type":"object"},"contracts.ActivityRetentionReport":{"description":"ActivityRetention (Spec 124 FR-035) reports whether the activity caps\nhold the whole work-session retention window. Administrators only.","properties":{"cause":{"description":"Cause is age_cap, record_cap or size_cap.","type":"string"},"observed_at":{"description":"ObservedAt is when the shortfall was last observed.","type":"string"},"oldest_complete_session_at":{"description":"OldestCompleteSessionAt is the start of the oldest session that still\nhas all of its rows: complete history reaches back to here.","type":"string"},"raise":{"description":"Raise names the settings to raise for the cause.","items":{"type":"string"},"type":"array","uniqueItems":false},"shortfall":{"description":"Shortfall is true when a work session inside the window lost rows\nbecause a cap was reached, and a full window has not passed since.","type":"boolean"},"window_days":{"description":"WindowDays is the work-session retention window.","type":"integer"}},"type":"object"},"contracts.ActivitySource":{"description":"How activity was triggered: \"mcp\", \"cli\", \"api\"","type":"string","x-enum-varnames":["ActivitySourceMCP","ActivitySourceCLI","ActivitySourceAPI"]},"contracts.ActivitySummaryResponse":{"properties":{"blocked_count":{"description":"Count of blocked activities","type":"integer"},"call_count":{"description":"CallCount is how many of those records are CALLS THE USER MADE, as\ndefined once in storage.CountsAsCall and shared with the usage aggregate\nbehind the Usage tab (audit finding F1, #1046). TotalCount answers \"how\nmany rows does the Activity Log have\"; CallCount answers \"how many calls\nwere there\". They are different questions — quarantine auto-approvals,\nsystem start, security scans and management chatter are events, not calls\n— and printing either one under the other's label is how the same instance\ncame to report 51 calls on one screen and 19 on another.","type":"integer"},"call_error_count":{"description":"CallErrorCount is the failures within CallCount, so an error RATE computed\nfrom this response has one denominator. It is not ErrorCount: a policy\nblock is a failed call but carries status \"blocked\", and a shed call is an\nerror in neither sense because it never ran.","type":"integer"},"end_time":{"description":"End of the period (RFC3339)","type":"string"},"error_count":{"description":"Count of error activities","type":"integer"},"other_count":{"description":"OtherCount is every record whose status is outside the four-value\nvocabulary above, so that\n\n\tsuccess + error + blocked + rejected + other == total\n\nholds by construction. The status field is a CLOSED vocabulary for tool\ncalls, but the activity log is wider than tool calls: a quarantine change\nstores its ACTION there (\"approved\", \"auto_approved\"), a policy decision\nstores its DECISION (\"allow\"). Those rows were counted in the total and in\nnone of the four buckets, so the Activity Log's own status tiles summed to\nless than the denominator printed beside them — 15+4+0+0 under a \"42\"\n(audit finding F2, #1046). The residual now has a name and a tile.","type":"integer"},"per_server":{"description":"PerServer covers EVERY server with at least one call in the period\n(unlike TopServers, which is capped at 5 and carries no error counts).\nSpec 109 FR-013: the server-card stats line and the macOS Servers rows\nread this — one ` + "`" + `GET /activity/summary` + "`" + ` response per page load — rather\nthan issuing a per-server activity query each. Computed in the same\ncounting pass as the totals above, from the same CountsAsCall/\nIsManagementBuiltin definitions TopServers already uses.","items":{"$ref":"#/components/schemas/contracts.ActivityPerServer"},"type":"array","uniqueItems":false},"period":{"description":"Time period (1h, 24h, 7d, 30d)","type":"string"},"rejected_count":{"description":"RejectedCount is the number of calls shed by a concurrency limiter, or\nrefused because an agent token was over its call budget, before they\nreached an upstream (spec 093, issue #1699). Counted separately from\nerrors: it is proxy backpressure, not an upstream fault, and it is the\nsignal an operator right-sizes max_concurrent_requests and the rate\nlimits against.","type":"integer"},"start_time":{"description":"Start of the period (RFC3339)","type":"string"},"success_count":{"description":"Count of successful activities","type":"integer"},"top_servers":{"description":"Top servers by activity count","items":{"$ref":"#/components/schemas/contracts.ActivityTopServer"},"type":"array","uniqueItems":false},"top_tools":{"description":"Top tools by activity count","items":{"$ref":"#/components/schemas/contracts.ActivityTopTool"},"type":"array","uniqueItems":false},"total_count":{"description":"Total activity count","type":"integer"}},"type":"object"},"contracts.ActivityTopServer":{"properties":{"count":{"description":"Activity count","type":"integer"},"name":{"description":"Server name","type":"string"}},"type":"object"},"contracts.ActivityTopTool":{"properties":{"count":{"description":"Activity count","type":"integer"},"server":{"description":"Server name","type":"string"},"tool":{"description":"Tool name","type":"string"}},"type":"object"},"contracts.ActivityType":{"description":"Type of activity","type":"string","x-enum-varnames":["ActivityTypeToolCall","ActivityTypePolicyDecision","ActivityTypeQuarantineChange","ActivityTypeServerChange"]},"contracts.AddFromRegistryRequest":{"properties":{"enabled":{"description":"defaults to true when nil","type":"boolean"},"env":{"additionalProperties":{"type":"string"},"description":"overrides + required-input values","type":"object"},"name":{"description":"optional name override","type":"string"}},"type":"object"},"contracts.AddRegistrySourceRequest":{"properties":{"id":{"description":"derived from the host when empty","type":"string"},"name":{"description":"defaults to the id","type":"string"},"protocol":{"description":"defaults to modelcontextprotocol/registry","type":"string"},"url":{"description":"required https registry URL","type":"string"}},"type":"object"},"contracts.AttentionFix":{"properties":{"label":{"type":"string"},"target":{"type":"string"},"verb":{"type":"string"}},"type":"object"},"contracts.AttentionItem":{"properties":{"detail":{"type":"string"},"fix":{"$ref":"#/components/schemas/contracts.AttentionFix"},"id":{"description":"kind:type:subject[:state]","type":"string"},"kind":{"type":"string"},"rank":{"type":"integer"},"since":{"type":"string"},"subject":{"$ref":"#/components/schemas/contracts.AttentionSubject"},"summary":{"type":"string"}},"type":"object"},"contracts.AttentionSubject":{"properties":{"id":{"type":"string"},"name":{"type":"string"},"type":{"description":"server|tool|client|setting","type":"string"}},"type":"object"},"contracts.ConfigApplyResult":{"properties":{"applied_immediately":{"type":"boolean"},"changed_fields":{"items":{"type":"string"},"type":"array","uniqueItems":false},"requires_restart":{"type":"boolean"},"restart_reason":{"type":"string"},"success":{"type":"boolean"},"validation_errors":{"items":{"$ref":"#/components/schemas/contracts.ValidationError"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.DCRStatus":{"properties":{"attempted":{"type":"boolean"},"error":{"type":"string"},"status_code":{"type":"integer"},"success":{"type":"boolean"}},"type":"object"},"contracts.DeepScanDescriptor":{"description":"DeepScan reports the opt-in \"deep scan\" layer status (Spec 077 US3),\nSEPARATELY from the baseline verdict above. Always emitted on a computed\nsummary — when deep scan is off (the default) it reports enabled=false\nplus any enabled-but-skipped Docker scanners. It never influences Status.","properties":{"available":{"type":"boolean"},"enabled":{"type":"boolean"},"ran":{"type":"boolean"},"scanners_failed":{"items":{"$ref":"#/components/schemas/contracts.DeepScanScannerFailure"},"type":"array","uniqueItems":false},"skipped_scanners":{"description":"SkippedScanners lists Docker scanners the user enabled that are skipped\nbecause security.deep_scan.enabled is false (informational).","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.DeepScanScannerFailure":{"properties":{"id":{"type":"string"},"reason":{"type":"string"}},"type":"object"},"contracts.DeprecatedConfigWarning":{"properties":{"field":{"type":"string"},"message":{"type":"string"},"replacement":{"type":"string"}},"type":"object"},"contracts.Diagnostic":{"description":"Spec 044 — structured diagnostic error and stable error code. Both\nare populated when the server is in a failed state and the error\nhas been classified by internal/diagnostics. Healthy servers omit\nthese fields.","properties":{"cause":{"type":"string"},"code":{"type":"string"},"detected_at":{"type":"string"},"docs_url":{"type":"string"},"fix_steps":{"items":{"$ref":"#/components/schemas/contracts.DiagnosticFixStep"},"type":"array","uniqueItems":false},"severity":{"type":"string"},"user_message":{"type":"string"}},"type":"object"},"contracts.DiagnosticFixStep":{"properties":{"command":{"type":"string"},"destructive":{"type":"boolean"},"fixer_key":{"type":"string"},"label":{"type":"string"},"type":{"type":"string"},"url":{"type":"string"}},"type":"object"},"contracts.Diagnostics":{"properties":{"activity_retention":{"$ref":"#/components/schemas/contracts.ActivityRetentionReport"},"deprecated_configs":{"description":"Deprecated config fields found","items":{"$ref":"#/components/schemas/contracts.DeprecatedConfigWarning"},"type":"array","uniqueItems":false},"docker_status":{"$ref":"#/components/schemas/contracts.DockerStatus"},"missing_secrets":{"description":"Renamed to avoid conflict","items":{"$ref":"#/components/schemas/contracts.MissingSecretInfo"},"type":"array","uniqueItems":false},"oauth_issues":{"description":"OAuth parameter mismatches","items":{"$ref":"#/components/schemas/contracts.OAuthIssue"},"type":"array","uniqueItems":false},"oauth_required":{"items":{"$ref":"#/components/schemas/contracts.OAuthRequirement"},"type":"array","uniqueItems":false},"oauth_token_storage":{"$ref":"#/components/schemas/contracts.OAuthTokenStorageReport"},"runtime_warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false},"timestamp":{"type":"string"},"total_issues":{"type":"integer"},"upstream_errors":{"items":{"$ref":"#/components/schemas/contracts.UpstreamError"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.DockerStatus":{"properties":{"available":{"type":"boolean"},"error":{"type":"string"},"version":{"type":"string"}},"type":"object"},"contracts.EditRegistrySourceRequest":{"properties":{"name":{"description":"new display name","type":"string"},"servers_url":{"description":"explicit servers-collection URL","type":"string"},"url":{"description":"new base/servers https URL","type":"string"}},"type":"object"},"contracts.ErrorResponse":{"properties":{"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.FindingCounts":{"properties":{"dangerous":{"description":"Tool poisoning, active prompt injection","type":"integer"},"info":{"description":"Low-severity CVEs, informational","type":"integer"},"total":{"type":"integer"},"warning":{"description":"Rug pull, supply chain CVEs with exploits","type":"integer"}},"type":"object"},"contracts.GetConfigResponse":{"properties":{"config":{"description":"The configuration object","type":"object"},"config_path":{"description":"Path to config file","type":"string"}},"type":"object"},"contracts.GetRegistriesResponse":{"properties":{"registries":{"items":{"$ref":"#/components/schemas/contracts.Registry"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GetServerLogsResponse":{"properties":{"count":{"type":"integer"},"logs":{"items":{"$ref":"#/components/schemas/contracts.LogEntry"},"type":"array","uniqueItems":false},"server_name":{"type":"string"}},"type":"object"},"contracts.GetServerToolCallsResponse":{"properties":{"server_name":{"type":"string"},"tool_calls":{"items":{"$ref":"#/components/schemas/contracts.ToolCallRecord"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GetServerToolsResponse":{"properties":{"count":{"type":"integer"},"incarnation":{"description":"Incarnation is the committed incarnation of the server the tools were\nread for (Spec 116 FR-017), captured before they were fetched; omitted\nwhen unknown.","type":"integer"},"server_name":{"type":"string"},"tools":{"items":{"$ref":"#/components/schemas/contracts.Tool"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.GetServersResponse":{"properties":{"servers":{"items":{"$ref":"#/components/schemas/contracts.Server"},"type":"array","uniqueItems":false},"stats":{"$ref":"#/components/schemas/contracts.ServerStats"}},"type":"object"},"contracts.GetSessionDetailResponse":{"properties":{"session":{"$ref":"#/components/schemas/contracts.MCPSession"}},"type":"object"},"contracts.GetSessionsResponse":{"properties":{"limit":{"type":"integer"},"offset":{"type":"integer"},"sessions":{"items":{"$ref":"#/components/schemas/contracts.MCPSession"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GetToolCallDetailResponse":{"properties":{"tool_call":{"$ref":"#/components/schemas/contracts.ToolCallRecord"}},"type":"object"},"contracts.GetToolCallsResponse":{"properties":{"limit":{"type":"integer"},"offset":{"type":"integer"},"tool_calls":{"items":{"$ref":"#/components/schemas/contracts.ToolCallRecord"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GlobalToolsResponse":{"properties":{"counts":{"$ref":"#/components/schemas/contracts.ViewAsCounts"},"failed_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"partial":{"type":"boolean"},"stats":{"$ref":"#/components/schemas/contracts.GlobalToolsStats"},"tools":{"items":{"$ref":"#/components/schemas/contracts.Tool"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.GlobalToolsStats":{"properties":{"disabled":{"type":"integer"},"enabled":{"type":"integer"},"pending_approval":{"type":"integer"},"total":{"type":"integer"}},"type":"object"},"contracts.HealthStatus":{"description":"Unified health status calculated by the backend","properties":{"action":{"description":"Action is the suggested fix action: \"login\", \"restart\", \"enable\", \"approve\", \"view_logs\", \"set_secret\", \"configure\", \"edit_url\", or \"\" (none)\nInvariant: Action always equals Actions[0], or \"\" when Actions is empty.","type":"string"},"actions":{"description":"Actions lists every applicable next step in priority order (FR-012):\nlogin \u003e set_secret \u003e configure \u003e edit_url \u003e approve \u003e restart \u003e\nview_logs \u003e enable. Always non-nil (empty slice, never null).","items":{"type":"string"},"type":"array","uniqueItems":false},"admin_state":{"description":"AdminState indicates the admin state: \"enabled\", \"disabled\", or \"quarantined\"","type":"string"},"detail":{"description":"Detail is an optional longer explanation of the status","type":"string"},"level":{"description":"Level indicates the health level: \"healthy\", \"degraded\", or \"unhealthy\"","type":"string"},"status":{"description":"Status is the ONE status vocabulary rendered as text on every surface\n(Web UI, macOS, tray, CLI) — Spec 109 FR-010/FR-011. Values: \"ready\",\n\"connecting\", \"sign_in_required\", \"needs_review\", \"needs_secret\",\n\"needs_config\", \"error\", \"disabled\". Unlike Level (a severity signal for\nbadge/tray coloring only), no renderer may print Level as text.","type":"string"},"summary":{"description":"Summary is a human-readable status message (e.g., \"Connected (5 tools)\")","type":"string"},"usable":{"description":"Usable reports whether the server can currently serve tool calls. True\nonly when Status == \"ready\".","type":"boolean"}},"type":"object"},"contracts.InfoEndpoints":{"description":"Available API endpoints","properties":{"http":{"description":"HTTP endpoint address (e.g., \"127.0.0.1:8080\")","type":"string"},"socket":{"description":"Unix socket path (empty if disabled)","type":"string"}},"type":"object"},"contracts.InfoResponse":{"properties":{"endpoints":{"$ref":"#/components/schemas/contracts.InfoEndpoints"},"launched_by":{"description":"LaunchedBy is the durable launch provenance of the running core (Spec\n092 FR-001a): \"tray\" when a tray spawned it, \"installer\" when the macOS\nPKG postinstall did, \"\" when user-launched or unknown. Always present\n(possibly empty) so a tray can distinguish \"old core, not mine\" from\n\"old core I may supersede\".","type":"string"},"listen_addr":{"description":"Listen address (e.g., \"127.0.0.1:8080\")","type":"string"},"pid":{"description":"PID is the operating-system process id of the running core (Spec 092\nFR-002). A tray that merely ATTACHED to a core holds no Process handle\nfor it, so without this there is no mechanism at all to stop a stale\ncore — the consent action would have nothing to act on and could only\nprint instructions. Paired with LaunchedBy it is what lets a newer tray\nsupersede a core an older tray started.","type":"integer"},"update":{"$ref":"#/components/schemas/contracts.UpdateInfo"},"update_policy":{"$ref":"#/components/schemas/contracts.UpdatePolicy"},"version":{"description":"Current MCPProxy version","type":"string"},"web_ui_url":{"description":"URL to access the web control panel","type":"string"}},"type":"object"},"contracts.IsolationConfig":{"properties":{"cpu_limit":{"type":"string"},"enabled":{"description":"Enabled is the EFFECTIVE isolation state for this server: whether its\nprocess is actually CONFINED, after the global setting, the per-server\noverride, the structural gates and the host's capabilities. It is NOT the\nraw per-server override — read EnabledOverride for that (GH #1142).\n\nREAD-ONLY. The write surfaces reject an ` + "`" + `enabled` + "`" + ` key precisely because\nit is derived: echoing it back would convert \"inherits the global\nsetting\" into a permanent explicit override. Write EnabledOverride.\n\nIt stays a non-pointer bool that is always present on the wire: the macOS\ntray decodes it as a non-optional Swift Bool, so omitting or nulling the\nkey would fail Codable for the whole server payload. Older clients that\nread this field now simply get a true answer.","type":"boolean"},"enabled_override":{"description":"EnabledOverride is the RAW per-server ` + "`" + `isolation.enabled` + "`" + ` override, as\npersisted. Absent means \"inherit the global setting\" — which is a\ndistinct state from an explicit false, and the distinction the reporting\nbug used to destroy.","type":"boolean"},"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"memory_limit":{"type":"string"},"mode_override":{"description":"ModeOverride is the RAW per-server ` + "`" + `isolation.mode` + "`" + ` override\n(\"docker\" | \"sandbox\" | \"none\"). Absent means \"inherit\".","type":"string"},"network_mode":{"type":"string"},"timeout":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"contracts.IsolationDefaults":{"description":"IsolationDefaults exposes the resolved baseline values that\nwould apply when no per-server override is set. Populated on\nlist/get responses; never consumed on PATCH requests.","properties":{"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"network_mode":{"type":"string"},"runtime_type":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"contracts.IsolationEffective":{"description":"IsolationEffective exposes the resolved isolation state (and the rule\nthat decided it) so clients can distinguish \"inherits global\" from an\nexplicit per-server choice. Read-only; never consumed on PATCH.","properties":{"global_mode":{"description":"GlobalMode is what \"inherit\" resolves to right now.","type":"string"},"inherited":{"description":"Inherited is true when the server sets neither ` + "`" + `isolation.enabled` + "`" + ` nor\n` + "`" + `isolation.mode` + "`" + `, so its state tracks the global setting.","type":"boolean"},"isolated":{"description":"Isolated reports whether the process is actually CONFINED. It is NOT\nsimply Mode != \"none\": \"sandbox\" on a host that cannot enforce Landlock\n(any non-Linux OS, or a kernel without the LSM) runs the server\nunconfined, and Source then says \"sandbox-unavailable\" (GH #1142).","type":"boolean"},"mode":{"description":"Mode is the effective isolation mode: \"docker\" | \"sandbox\" | \"none\" —\nexactly what the spawn path branches on.","type":"string"},"source":{"description":"Source names the deciding rule: \"global\", \"server-mode\",\n\"server-opt-out\", \"server-opt-in-ignored\", \"not-stdio\",\n\"already-docker\", \"sandbox-unavailable\" or \"unsupported-mode\".\nTreat an unrecognized value as \"global\".","type":"string"}},"type":"object"},"contracts.LogEntry":{"properties":{"fields":{"type":"object"},"level":{"type":"string"},"message":{"type":"string"},"server":{"type":"string"},"timestamp":{"type":"string"}},"type":"object"},"contracts.MCPSession":{"properties":{"client_id":{"description":"Scope attribution (Spec 108 FR-033). ClientID and TokenName are the\ncredential the session initialized with; Profile and ProfileSource are\nthe session's latest effective resolution. Empty on legacy sessions.","type":"string"},"client_name":{"type":"string"},"client_version":{"type":"string"},"end_time":{"type":"string"},"experimental":{"items":{"type":"string"},"type":"array","uniqueItems":false},"has_roots":{"description":"MCP Client Capabilities","type":"boolean"},"has_sampling":{"type":"boolean"},"id":{"type":"string"},"last_activity":{"type":"string"},"profile":{"type":"string"},"profile_source":{"type":"string"},"start_time":{"type":"string"},"status":{"type":"string"},"token_name":{"type":"string"},"tool_call_count":{"type":"integer"},"total_tokens":{"type":"integer"},"work_session_id":{"type":"string"},"workspace_name":{"description":"Workspace / work session (Spec 082). WorkspaceName is the project's\nbasename — the full local path is never exposed. WorkSessionID groups the\nreconnects that make up one stretch of user work.","type":"string"}},"type":"object"},"contracts.MetadataStatus":{"properties":{"authorization_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"error":{"type":"string"},"found":{"type":"boolean"},"url_checked":{"type":"string"}},"type":"object"},"contracts.MissingSecretInfo":{"properties":{"secret_name":{"type":"string"},"used_by":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.NPMPackageInfo":{"properties":{"exists":{"type":"boolean"},"install_cmd":{"type":"string"}},"type":"object"},"contracts.OAuthConfig":{"properties":{"auth_server_metadata_url":{"type":"string"},"auth_url":{"type":"string"},"authorization_endpoint":{"description":"Spec 113-b operator overrides of OAuth discovery (https-or-loopback URLs,\nnever credentials). Empty means \"use discovery\".","type":"string"},"client_id":{"type":"string"},"extra_params":{"additionalProperties":{"type":"string"},"type":"object"},"pkce_enabled":{"type":"boolean"},"redirect_port":{"type":"integer"},"refresh_replay_enabled":{"type":"boolean"},"registration_endpoint":{"type":"string"},"scopes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"token_endpoint":{"type":"string"},"token_expires_at":{"description":"When the OAuth token expires","type":"string"},"token_url":{"type":"string"},"token_valid":{"description":"Whether token is currently valid","type":"boolean"}},"type":"object"},"contracts.OAuthErrorDetails":{"description":"Structured discovery/failure details","properties":{"authorization_server_metadata":{"$ref":"#/components/schemas/contracts.MetadataStatus"},"dcr_status":{"$ref":"#/components/schemas/contracts.DCRStatus"},"protected_resource_metadata":{"$ref":"#/components/schemas/contracts.MetadataStatus"},"server_url":{"type":"string"}},"type":"object"},"contracts.OAuthFlowError":{"properties":{"correlation_id":{"description":"Flow tracking ID for log correlation","type":"string"},"debug_hint":{"description":"CLI command for log lookup","type":"string"},"details":{"$ref":"#/components/schemas/contracts.OAuthErrorDetails"},"error_code":{"description":"Machine-readable error code (e.g., OAUTH_NO_METADATA)","type":"string"},"error_type":{"description":"Category of OAuth runtime failure","type":"string"},"message":{"description":"Human-readable error description","type":"string"},"request_id":{"description":"HTTP request ID (from PR #237)","type":"string"},"server_name":{"description":"Server that failed OAuth","type":"string"},"success":{"description":"Always false","type":"boolean"},"suggestion":{"description":"Actionable remediation hint","type":"string"}},"type":"object"},"contracts.OAuthIssue":{"properties":{"documentation_url":{"type":"string"},"error":{"type":"string"},"issue":{"type":"string"},"missing_params":{"items":{"type":"string"},"type":"array","uniqueItems":false},"resolution":{"type":"string"},"server_name":{"type":"string"}},"type":"object"},"contracts.OAuthRequirement":{"properties":{"expires_at":{"type":"string"},"message":{"type":"string"},"server_name":{"type":"string"},"state":{"type":"string"}},"type":"object"},"contracts.OAuthStartResponse":{"properties":{"auth_url":{"description":"Authorization URL (always included for manual use)","type":"string"},"browser_error":{"description":"Error message if browser launch failed","type":"string"},"browser_opened":{"description":"Whether browser launch succeeded","type":"boolean"},"correlation_id":{"description":"UUID for tracking this flow","type":"string"},"message":{"description":"Human-readable status message","type":"string"},"server_name":{"description":"Name of the server being authenticated","type":"string"},"success":{"description":"Always true for successful start","type":"boolean"}},"type":"object"},"contracts.OAuthTokenStorageReport":{"description":"OAuthTokenStorage (Spec 123 FR-030) reports the state of the stored\nupstream OAuth rows: encryption on or off, the public key id, the row\ncounts by state, the undecryptable servers and the compaction advice.\nIt never carries key material or the key reference.","properties":{"compaction_advised":{"description":"CompactionAdvised mirrors the compaction marker: freed pages may still\nhold old plaintext until ` + "`" + `mcpproxy db compact --keep-backup=false` + "`" + `.","type":"boolean"},"encryption_enabled":{"description":"EncryptionEnabled is true when an encryption key is configured.","type":"boolean"},"key_id":{"description":"KeyID is the public, non-secret id of the configured key (administrator only).","type":"string"},"key_source_in_data_dir":{"description":"KeySourceInDataDir is true when the key file lies inside the data directory.","type":"boolean"},"key_source_kind":{"description":"KeySourceKind is how the key was obtained: literal, env, env_file,\nref_file, ref_env or ref_keyring (administrator only).","type":"string"},"plaintext":{"description":"Plaintext counts valid JSON rows; Sealed counts envelopes the configured\nkey opens; Undecryptable counts everything else.","type":"integer"},"sealed":{"type":"integer"},"servers":{"description":"Servers lists the undecryptable rows by server.","items":{"$ref":"#/components/schemas/contracts.OAuthTokenStorageServer"},"type":"array","uniqueItems":false},"undecryptable":{"type":"integer"},"undecryptable_by_reason":{"$ref":"#/components/schemas/contracts.OAuthTokenUndecryptableByReason"},"warnings":{"description":"Warnings are stable codes: literal_key, key_file_in_data_dir,\nplaintext_rows_with_key, compaction_advised, backup_file_present\n(administrator only).","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.OAuthTokenStorageServer":{"properties":{"bucket_key":{"type":"string"},"reason":{"type":"string"},"row_key_id":{"description":"RowKeyID is the key id in the row's envelope (administrator only).","type":"string"},"server":{"type":"string"}},"type":"object"},"contracts.OAuthTokenUndecryptableByReason":{"description":"UndecryptableByReason breaks Undecryptable down by reason.","properties":{"auth_failed":{"type":"integer"},"key_mismatch":{"type":"integer"},"malformed":{"type":"integer"},"no_key":{"type":"integer"},"unsupported_version":{"type":"integer"}},"type":"object"},"contracts.PreflightPolicy":{"properties":{"exclude_destructive":{"type":"boolean"},"exclude_open_world":{"type":"boolean"},"read_only_only":{"type":"boolean"}},"type":"object"},"contracts.PreflightReason":{"type":"string","x-enum-varnames":["PreflightReasonServerInitializing","PreflightReasonServerUnhealthy","PreflightReasonServerDisabled","PreflightReasonServerQuarantined","PreflightReasonToolPendingApproval","PreflightReasonToolChanged","PreflightReasonToolBlockedByUser","PreflightReasonOAuthRequired","PreflightReasonHashMismatch","PreflightReasonServerNotInScope","PreflightReasonToolDeniedByConfig","PreflightReasonMissingAnnotation","PreflightReasonPolicyFiltered","PreflightReasonNotFound","PreflightReasonServerNotConfigured","PreflightReasonToolBlockedByProfile","PreflightReasonTokenPermissionDenied"]},"contracts.PreflightRequest":{"properties":{"policy":{"$ref":"#/components/schemas/contracts.PreflightPolicy"},"profile":{"description":"Profile evaluates under a named profile's server scope and tool policy;\nit can only narrow a credential's own pin. Unknown: 400.","type":"string"},"tools":{"description":"Tools is 1..100 entries BEFORE dedup; duplicates are collapsed, and\nduplicate ids carrying different pins are a validation error.","items":{"$ref":"#/components/schemas/contracts.PreflightToolRef"},"type":"array","uniqueItems":false},"wait_ms":{"description":"WaitMS polls local state for up to this many milliseconds (cap 10000)\nwhile every failure is retryable-class.","type":"integer"}},"type":"object"},"contracts.PreflightResponse":{"properties":{"checked_at":{"type":"string"},"tools":{"description":"Tools are ordered by first occurrence of each unique id in the request.","items":{"$ref":"#/components/schemas/contracts.PreflightToolResult"},"type":"array","uniqueItems":false},"verdict":{"$ref":"#/components/schemas/contracts.PreflightVerdict"},"waited_ms":{"description":"WaitedMS is present when wait_ms was requested (0 when the wait\nsemaphore was exhausted and the request resolved immediately).","type":"integer"}},"type":"object"},"contracts.PreflightStatus":{"type":"string","x-enum-varnames":["PreflightStatusReady","PreflightStatusUnavailable"]},"contracts.PreflightToolRef":{"properties":{"id":{"description":"ID is a canonical \"\u003cserver\u003e:\u003ctool\u003e\" id. A malformed id is answered with a\nper-ID not_found carrying a format hint, never a request-level error.","type":"string"},"pin_hash":{"description":"PinHash is \"sha256/v{N}:{hex}\" — the schema version is embedded so a\nproxy-side hash-algorithm bump is distinguishable from upstream drift.","type":"string"}},"type":"object"},"contracts.PreflightToolResult":{"properties":{"action":{"type":"string"},"detail":{"type":"string"},"did_you_mean":{"description":"DidYouMean carries up to 3 nearest caller-visible ids on not_found. It\nnever crosses a scope boundary and never names a quarantined server's\ntools.","items":{"type":"string"},"type":"array","uniqueItems":false},"hash":{"description":"Hash is the tool's current pin (\"sha256/v{N}:{hex}\") — operator tier,\nready results only. Never disclosed to an agent token.","type":"string"},"id":{"type":"string"},"reason":{"$ref":"#/components/schemas/contracts.PreflightReason"},"remediation":{"type":"string"},"retryable":{"type":"boolean"},"status":{"$ref":"#/components/schemas/contracts.PreflightStatus"}},"type":"object"},"contracts.PreflightVerdict":{"type":"string","x-enum-varnames":["PreflightVerdictReady","PreflightVerdictDegradedRetryable","PreflightVerdictBlocked","PreflightVerdictUnknownIDs"]},"contracts.QuarantineStats":{"description":"Tool quarantine metrics for this server","properties":{"blocked_count":{"description":"Number of disabled (blocked) tools","type":"integer"},"changed_count":{"description":"Number of tools whose description/schema changed since approval","type":"integer"},"pending_count":{"description":"Number of newly discovered tools awaiting approval","type":"integer"}},"type":"object"},"contracts.RefreshRegistryResponse":{"properties":{"cleared":{"description":"number of cached entries dropped","type":"integer"},"registry_id":{"type":"string"}},"type":"object"},"contracts.Registry":{"properties":{"count":{"description":"number or string","type":"string"},"description":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"},"protocol":{"type":"string"},"provenance":{"description":"Provenance is the trust tag (MCP-866): \"official/trusted\" for built-in\ndefaults, \"custom/unverified\" for user-added registries.","type":"string"},"servers_url":{"type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"trusted":{"description":"Trusted indicates whether this is an official, shipped-by-default\nregistry. Trust is derived from membership in the default set, never\nfrom self-assertion in config.","type":"boolean"},"url":{"type":"string"}},"type":"object"},"contracts.RegistryCacheInfo":{"properties":{"age_seconds":{"type":"number"},"stale":{"type":"boolean"}},"type":"object"},"contracts.RegistryUnavailable":{"properties":{"reason":{"type":"string"}},"type":"object"},"contracts.ReplayToolCallRequest":{"properties":{"arguments":{"description":"Modified arguments for replay","type":"object"}},"type":"object"},"contracts.ReplayToolCallResponse":{"properties":{"error":{"description":"Error if replay failed","type":"string"},"new_call_id":{"description":"ID of the newly created call","type":"string"},"new_tool_call":{"$ref":"#/components/schemas/contracts.ToolCallRecord"},"replayed_from":{"description":"Original call ID","type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.RepositoryInfo":{"description":"Detected package info","properties":{"npm":{"$ref":"#/components/schemas/contracts.NPMPackageInfo"}},"type":"object"},"contracts.RepositoryServer":{"properties":{"connect_url":{"description":"Alternative connection URL","type":"string"},"created_at":{"type":"string"},"description":{"type":"string"},"id":{"type":"string"},"install_cmd":{"description":"Installation command","type":"string"},"name":{"type":"string"},"registry":{"description":"Which registry this came from","type":"string"},"repository_info":{"$ref":"#/components/schemas/contracts.RepositoryInfo"},"source_code_url":{"description":"Source repository URL","type":"string"},"updated_at":{"type":"string"},"url":{"description":"MCP endpoint for remote servers only","type":"string"}},"type":"object"},"contracts.SearchRegistryServersResponse":{"properties":{"cache":{"$ref":"#/components/schemas/contracts.RegistryCacheInfo"},"query":{"type":"string"},"registry_id":{"type":"string"},"servers":{"items":{"$ref":"#/components/schemas/contracts.RepositoryServer"},"type":"array","uniqueItems":false},"tag":{"type":"string"},"total":{"type":"integer"},"unavailable":{"$ref":"#/components/schemas/contracts.RegistryUnavailable"}},"type":"object"},"contracts.SearchResult":{"properties":{"matches":{"type":"integer"},"score":{"type":"number"},"snippet":{"type":"string"},"tool":{"$ref":"#/components/schemas/contracts.Tool"}},"type":"object"},"contracts.SearchToolsResponse":{"properties":{"query":{"type":"string"},"results":{"items":{"$ref":"#/components/schemas/contracts.SearchResult"},"type":"array","uniqueItems":false},"took":{"type":"string"},"total":{"type":"integer"}},"type":"object"},"contracts.SecurityScanSummary":{"description":"Latest security scan results summary","properties":{"deep_scan":{"$ref":"#/components/schemas/contracts.DeepScanDescriptor"},"finding_counts":{"$ref":"#/components/schemas/contracts.FindingCounts"},"last_scan_at":{"type":"string"},"risk_score":{"description":"0-100","type":"integer"},"scanners_failed":{"type":"integer"},"scanners_run":{"description":"Scanner coverage for the primary (baseline) scan pass — informational only.\nSpec 077 US3 (FR-008/FR-014): Status is derived SOLELY from the\ndeterministic baseline findings; a failed Docker deep scanner no longer\ndowngrades a clean verdict. That failure is surfaced via DeepScan instead.","type":"integer"},"scanners_total":{"type":"integer"},"status":{"description":"\"clean\", \"warnings\", \"dangerous\", \"failed\", \"not_scanned\", \"scanning\"","type":"string"}},"type":"object"},"contracts.Server":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"authenticated":{"description":"OAuth authentication status","type":"boolean"},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges mirrors config.ServerConfig.AutoApproveToolChanges\n(MCP-2930): the per-server intent to auto-approve new/changed tools past\nthe trust baseline. Tri-state *bool — nil means \"never set\" (omitted from\nthe payload), so the Web UI toggle (MCP-2932) can distinguish unset from\nan explicit false. Read-only on the GET path; PATCH/POST accept it via\nAddServerRequest.","type":"boolean"},"command":{"type":"string"},"connected":{"type":"boolean"},"connected_at":{"type":"string"},"connecting":{"type":"boolean"},"created":{"type":"string"},"diagnostic":{"$ref":"#/components/schemas/contracts.Diagnostic"},"enabled":{"type":"boolean"},"env":{"additionalProperties":{"type":"string"},"type":"object"},"error_code":{"type":"string"},"expose_prompts":{"description":"ExposePrompts mirrors config.ServerConfig.ExposePrompts (F9): the per-server\nprompt-aggregation override. Tri-state *bool — nil/omitted means \"inherit\ndefault aggregation\". Surfaced on GET so a caller that PATCHed the override\ncan read it back; PATCH/POST accept it via AddServerRequest.","type":"boolean"},"expose_skills":{"description":"ExposeSkills mirrors config.ServerConfig.ExposeSkills: the per-server\nskills override. Tri-state *bool; nil/omitted means \"inherit\".","type":"boolean"},"forward_headers":{"description":"ForwardHeaders mirrors config.ServerConfig.ForwardHeaders (Spec 112): the\nallowlist of inbound MCP client header NAMES forwarded to this server on\ntools/call. Names only, never values. Omitted when empty.","items":{"type":"string"},"type":"array","uniqueItems":false},"generation":{"description":"Generation is the server's committed config generation (Spec 116\nFR-017): it changes whenever the server's configuration changes.","type":"integer"},"headers":{"additionalProperties":{"type":"string"},"type":"object"},"health":{"$ref":"#/components/schemas/contracts.HealthStatus"},"id":{"type":"string"},"incarnation":{"description":"Incarnation changes only when the name is removed and created again\n(Spec 116 FR-017). Approval endpoints accept it back as\nexpected_incarnation and answer 409 server_replaced on a mismatch.","type":"integer"},"init_timeout":{"description":"InitTimeout mirrors config.ServerConfig.InitTimeout (MCP-3322 / GH #760):\nthe per-server MCP ` + "`" + `initialize` + "`" + ` handshake deadline override. Serialized as\na duration string (e.g. \"120s\"); nil/omitted means \"inherit the global\ndefault\". Surfaced on the GET path so clients can read back a configured\noverride; PATCH/POST accept it via AddServerRequest.","type":"string"},"isolation":{"$ref":"#/components/schemas/contracts.IsolationConfig"},"isolation_defaults":{"$ref":"#/components/schemas/contracts.IsolationDefaults"},"isolation_effective":{"$ref":"#/components/schemas/contracts.IsolationEffective"},"last_error":{"type":"string"},"last_reconnect_at":{"type":"string"},"last_retry_time":{"type":"string"},"max_concurrent_requests":{"description":"Spec 093 (GH #955) — per-server concurrency overrides, scope (c) of\nFR-020. Each setting is tri-state: nil (omitted) means \"inherit\nserver_concurrency_defaults\", 0 disables that setting for this server,\npositive overrides it. Surfaced on the GET path so a caller can read back\nwhat it set; PATCH/POST accept them via AddServerRequest. The effective\nconcurrency for a server is additionally bounded by the global aggregate\nlimiter, which is NOT an inheritance source for these fields.","type":"integer"},"name":{"type":"string"},"oauth":{"$ref":"#/components/schemas/contracts.OAuthConfig"},"oauth_status":{"description":"OAuth status: \"authenticated\", \"expired\", \"error\", \"none\"","type":"string"},"protocol":{"type":"string"},"quarantine":{"$ref":"#/components/schemas/contracts.QuarantineStats"},"quarantined":{"type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_count":{"type":"integer"},"reconnect_on_use":{"description":"Attempt reconnection when a tool call targets this disconnected server","type":"boolean"},"retry_count":{"type":"integer"},"retry_stopped":{"description":"RetryStopped reports that automatic reconnection has been given up for\ngood because the failure is deterministic and unrecoverable — a missing\nbinary, an image without the interpreter, an unparseable config (GH\n#1145). It is NOT ordinary exponential backoff, which keeps retrying;\nnothing will happen until the user fixes the config or restarts the\nserver. RetryStoppedCode is the stable MCPX_* code that proved it and\nRetryStoppedReason the catalog message explaining how to fix it. All three\nare omitted for servers that are healthy or still retrying.","type":"boolean"},"retry_stopped_code":{"type":"string"},"retry_stopped_reason":{"type":"string"},"security_scan":{"$ref":"#/components/schemas/contracts.SecurityScanSummary"},"should_retry":{"type":"boolean"},"source_registry_id":{"description":"MCP-901 — registry provenance of an upstream that was added from a\nregistry. SourceRegistryID names the source registry (empty for\nmanually-configured servers); SourceRegistryProvenance is the trust tag\nrecorded at add time (\"official/trusted\" or \"custom/unverified\"). Both\nare projected from config.ServerConfig so the approval/quarantine view\ncan render an \"added from \u003cregistry\u003e · unverified\" origin badge. Optional\nand omitted when empty — clients that pre-date this treat them as absent.","type":"string"},"source_registry_provenance":{"type":"string"},"status":{"type":"string"},"token_expires_at":{"description":"When the OAuth token expires (ISO 8601)","type":"string"},"tool_argument_error_mode":{"type":"string"},"tool_count":{"type":"integer"},"tool_list_token_size":{"description":"Token size for this server's tools","type":"integer"},"trust_mode":{"description":"TrustMode mirrors config.ServerConfig.TrustMode (spec 086): the per-server\ntrust tier (\"auto\"/\"scan\"/\"manual\"). Surfaced on the GET path so clients can\nread back the persisted mode; PATCH/POST accept it via AddServerRequest.\nOmitted when empty (server predates the field / relies on legacy flags).","type":"string"},"updated":{"type":"string"},"url":{"type":"string"},"user_logged_out":{"description":"True if user explicitly logged out (prevents auto-reconnection)","type":"boolean"},"working_dir":{"type":"string"}},"type":"object"},"contracts.ServerActionResponse":{"properties":{"action":{"type":"string"},"async":{"type":"boolean"},"server":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.ServerStats":{"properties":{"connected_servers":{"type":"integer"},"docker_containers":{"type":"integer"},"quarantined_servers":{"type":"integer"},"token_metrics":{"$ref":"#/components/schemas/contracts.ServerTokenMetrics"},"total_servers":{"type":"integer"},"total_tools":{"type":"integer"}},"type":"object"},"contracts.ServerTokenMetrics":{"properties":{"average_query_result_size":{"description":"Typical retrieve_tools output (tokens)","type":"integer"},"estimated":{"description":"Estimated (Spec 109-k FR-070-ish, url-filter-contract.md / audit F-Token):\ntrue while AverageQueryResultSize is a synthetic simulation (a sample of\nthe first ` + "`" + `tools_limit` + "`" + ` tools' schemas — no real retrieve_tools call has\ncompleted yet in this runtime's usage aggregate); false once at least one\nreal retrieve_tools call has, at which point AverageQueryResultSize is\nderived from the real observed average response size instead. The Web\nUI and macOS render an \"estimate\" label while this is true.","type":"boolean"},"per_server_tool_list_sizes":{"additionalProperties":{"type":"integer"},"description":"Token size per server","type":"object"},"saved_tokens":{"description":"Difference","type":"integer"},"saved_tokens_percentage":{"description":"Percentage saved","type":"number"},"total_server_tool_list_size":{"description":"All upstream tools combined (tokens)","type":"integer"}},"type":"object"},"contracts.SkillContentResponse":{"properties":{"digest":{"type":"string"},"next_offset":{"description":"NextOffset is the byte offset of the next chunk; absent at the end.","type":"integer"},"offset":{"type":"integer"},"size":{"type":"integer"},"text":{"type":"string"}},"type":"object"},"contracts.SkillEntry":{"properties":{"approved_at":{"description":"ApprovedAt is omitted when the skill was never approved.","type":"string"},"approved_by":{"type":"string"},"approved_files":{"description":"ApprovedFiles is the file set of the approved copy; omitted when the\nskill has no approved copy. ` + "`" + `skills show --diff` + "`" + ` compares it with Files.","items":{"$ref":"#/components/schemas/contracts.SkillFileInfo"},"type":"array","uniqueItems":false},"approved_hash":{"type":"string"},"available":{"type":"boolean"},"blocked":{"type":"boolean"},"current_hash":{"type":"string"},"description":{"type":"string"},"files":{"items":{"$ref":"#/components/schemas/contracts.SkillFileInfo"},"type":"array","uniqueItems":false},"id":{"type":"string"},"listed":{"type":"boolean"},"name":{"type":"string"},"path":{"type":"string"},"scan":{"$ref":"#/components/schemas/contracts.SkillScanInfo"},"status":{"type":"string"},"total_size":{"type":"integer"},"unusable_reason":{"type":"string"},"uri":{"type":"string"}},"type":"object"},"contracts.SkillFileInfo":{"properties":{"digest":{"type":"string"},"path":{"type":"string"},"size":{"type":"integer"},"text":{"type":"boolean"}},"type":"object"},"contracts.SkillScanFinding":{"properties":{"evidence":{"type":"string"},"file":{"type":"string"},"offset":{"type":"integer"},"rule":{"type":"string"},"severity":{"type":"string"}},"type":"object"},"contracts.SkillScanInfo":{"properties":{"complete":{"type":"boolean"},"findings":{"items":{"$ref":"#/components/schemas/contracts.SkillScanFinding"},"type":"array","uniqueItems":false},"findings_truncated":{"description":"FindingsTruncated is true when more findings existed than are listed.","type":"boolean"},"incomplete":{"description":"Incomplete says why Complete is false: size_cap, time_limit, coverage or\ninterrupted; empty when the scan is complete.","type":"string"},"scanned_at":{"description":"ScannedAt is omitted when no scan of the current content exists.","type":"string"},"verdict":{"type":"string"}},"type":"object"},"contracts.SkillsApproveRequest":{"properties":{"expected_hashes":{"additionalProperties":{"type":"string"},"description":"ExpectedHashes maps each skill path to the current_hash the reviewer\nsaw. A skill without an entry is refused as unreviewed.","type":"object"},"expected_incarnation":{"description":"ExpectedIncarnation binds the approval to the server the reviewer saw;\n0 (or absent) binds to the incarnation current when the request starts.","type":"integer"},"skills":{"description":"Skills are skill paths (the part of the id after \"\u003cserver\u003e:\"), 1 to 200.","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.SkillsApproveResponse":{"properties":{"approved":{"description":"Approved counts the skills newly approved; a skill already approved for\nits current content is not counted.","type":"integer"}},"type":"object"},"contracts.SkillsBlockRequest":{"properties":{"expected_incarnation":{"type":"integer"},"skills":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.SkillsBlockResponse":{"properties":{"changed":{"description":"Changed counts the skills whose blocked mark changed.","type":"integer"}},"type":"object"},"contracts.SkillsErrorResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.SkillsListResponse":{"properties":{"enabled":{"type":"boolean"},"error":{"type":"string"},"expose_skills":{"type":"boolean"},"incarnation":{"description":"Incarnation is the server's approval incarnation: send it back as\nexpected_incarnation on approve, block and unblock.","type":"integer"},"last_refresh":{"type":"string"},"server":{"type":"string"},"skills":{"items":{"$ref":"#/components/schemas/contracts.SkillEntry"},"type":"array","uniqueItems":false},"supported":{"type":"boolean"},"truncated":{"type":"boolean"}},"type":"object"},"contracts.SkillsStaleReviewResponse":{"properties":{"changed":{"items":{"type":"string"},"type":"array","uniqueItems":false},"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"},"unreviewed":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.SkillsUnusableResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"skills":{"items":{"type":"string"},"type":"array","uniqueItems":false},"success":{"type":"boolean"}},"type":"object"},"contracts.SuccessResponse":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"success":{"type":"boolean"}},"type":"object"},"contracts.Tier":{"description":"Tier is computed by AnnotationTier (Spec 109 FR-028/X11) from\nAnnotations — read|write|destructive|unannotated. Set by every producer\nof a Tool (enrichServerTools, the global tools handler); never left for\na consuming surface to compute.","type":"string","x-enum-varnames":["TierRead","TierWrite","TierDestructive","TierUnannotated","TierUnknown"]},"contracts.TokenMetrics":{"description":"Token usage metrics (nil for older records)","properties":{"encoding":{"description":"Encoding used (e.g., cl100k_base)","type":"string"},"estimated_cost":{"description":"Optional cost estimate","type":"number"},"input_tokens":{"description":"Tokens in the request","type":"integer"},"model":{"description":"Model used for tokenization","type":"string"},"output_tokens":{"description":"Tokens in the response","type":"integer"},"total_tokens":{"description":"Total tokens (input + output)","type":"integer"},"truncated_tokens":{"description":"Tokens removed by truncation","type":"integer"},"was_truncated":{"description":"Whether response was truncated","type":"boolean"}},"type":"object"},"contracts.Tool":{"properties":{"access":{"$ref":"#/components/schemas/contracts.ToolAccess"},"annotations":{"$ref":"#/components/schemas/contracts.ToolAnnotation"},"approval_status":{"type":"string"},"config_denied":{"description":"ConfigDenied is true when the tool is denied by the server's static\nenabled_tools / disabled_tools config. The user cannot override this toggle.","type":"boolean"},"description":{"type":"string"},"disabled":{"description":"Disabled mirrors ToolApprovalRecord.Disabled so per-tool enable state is\navailable without a second round-trip to the approvals endpoint. Absent\nin the JSON when false (default) to keep responses compact.","type":"boolean"},"hash":{"description":"Hash is the tool's current stored hash rendered in the preflight pin\nformat \"sha256/v{N}:{hex}\" (Spec 098 FR-011), where N is the approval\nrecord's HashSchemaVersion. It is the authoring surface for\n` + "`" + `POST /api/v1/preflight` + "`" + ` pins and ` + "`" + `mcpproxy tools preflight --pin` + "`" + `:\ncopy the value straight into a pin.\n\nDisclosure is OPERATOR TIER ONLY — same rule as the preflight per-tool\nresult. The field is omitted for agent-token callers and for tools with\nno stored hash (no approval record yet, or a record written before\nhashes existed).","type":"string"},"held_reason":{"description":"HeldReason, HeldVerdict and HeldSignals mirror the same-named fields on\nstorage.ToolApprovalRecord: the offline-scan evidence that made\ntrust_mode: scan hold this tool for review (spec 086 FR-018). HeldSignals\nnames the matched deterministic check ids, e.g.\n\"tpa.TPA-2026-0001.hidden_instruction\", so a reviewer can see WHY the tool\nis held. All three are omitted for tools that are not held by the scan gate\n(including every record written before the field existed).","type":"string"},"held_signals":{"items":{"type":"string"},"type":"array","uniqueItems":false},"held_verdict":{"type":"string"},"last_used":{"type":"string"},"name":{"type":"string"},"profile_tier":{"description":"ProfileTier and Access are present only in a view-as listing (a tools\nlisting with ?client= or ?profile=, Spec 108 FR-032). ProfileTier is the\ntool's tier under the viewed subject's profile (Tier above stays the\nintrinsic tier); Access is the subject's verdict for the tool. Absent\notherwise, so an ordinary listing is byte-identical to before.","type":"string","x-enum-varnames":["TierRead","TierWrite","TierDestructive","TierUnannotated","TierUnknown"]},"schema":{"type":"object"},"server_incarnation":{"description":"ServerIncarnation is the committed incarnation of the server this row\nwas read for (Spec 116 FR-017), captured before the tools were fetched.\nA client echoes it as expected_incarnation on a per-tool decision, so a\nstale row is refused (409 server_replaced) after a same-name re-add.\nOmitted when the server has no committed incarnation.","type":"integer"},"server_name":{"type":"string"},"tier":{"$ref":"#/components/schemas/contracts.Tier"},"usage":{"type":"integer"}},"type":"object"},"contracts.ToolAccess":{"properties":{"callable":{"type":"boolean"},"reason":{"type":"string"},"visible":{"type":"boolean"}},"type":"object"},"contracts.ToolAnnotation":{"description":"Tool behavior hints snapshot","properties":{"destructiveHint":{"type":"boolean"},"idempotentHint":{"type":"boolean"},"openWorldHint":{"type":"boolean"},"readOnlyHint":{"type":"boolean"},"title":{"type":"string"}},"type":"object"},"contracts.ToolCallRecord":{"description":"The new tool call record","properties":{"annotations":{"$ref":"#/components/schemas/contracts.ToolAnnotation"},"arguments":{"description":"Tool arguments","type":"object"},"arguments_truncated":{"description":"ArgumentsTruncated marks Arguments as a placeholder rather than the\narguments the tool was called with. Replaying such a record without\nsupplying arguments explicitly is refused.","type":"boolean"},"config_path":{"description":"Active config file path","type":"string"},"duration":{"description":"Duration in nanoseconds","type":"integer"},"error":{"description":"Error message (failure only)","type":"string"},"execution_type":{"description":"\"direct\" or \"code_execution\"","type":"string"},"id":{"description":"Unique identifier","type":"string"},"mcp_client_name":{"description":"MCP client name from InitializeRequest","type":"string"},"mcp_client_version":{"description":"MCP client version","type":"string"},"mcp_session_id":{"description":"MCP session identifier","type":"string"},"metrics":{"$ref":"#/components/schemas/contracts.TokenMetrics"},"parent_call_id":{"description":"Links nested calls to parent code_execution","type":"string"},"request_id":{"description":"Request correlation ID","type":"string"},"response":{"description":"Tool response (success only)","type":"object"},"response_bytes":{"description":"Marshalled response size before truncation","type":"integer"},"response_truncated":{"description":"ResponseTruncated and ResponseBytes describe a STORAGE-side cut (#1176):\nthe caller received the response whole, and only the persisted copy was\nshortened to tool_call_max_response_size. When ResponseTruncated is true\nthe Response object carries {truncated, original_bytes, preview, note}\ninstead of the upstream result, and ResponseBytes is its size before the\ncut.","type":"boolean"},"server_id":{"description":"Server identity hash","type":"string"},"server_name":{"description":"Human-readable server name","type":"string"},"timestamp":{"description":"When the call was made","type":"string"},"tool_name":{"description":"Tool name (without server prefix)","type":"string"}},"type":"object"},"contracts.UpdateInfo":{"description":"Update information (if available)","properties":{"available":{"description":"Whether an update is available","type":"boolean"},"behind_summary":{"description":"Spec 079 FR-002 — how far behind the running build is. All four are\nadditive (FR-021) and absent when the delta could not be resolved, in\nwhich case every surface renders its pre-delta wording.","type":"string"},"check_error":{"description":"Error message if update check failed","type":"string"},"checked_at":{"description":"When the update check was performed","type":"string"},"install_channel":{"description":"Detected install channel (homebrew, dmg, deb, rpm, docker, go-install, windows-installer, tarball, unknown) — Spec 079 FR-008","type":"string"},"is_prerelease":{"description":"Whether the latest version is a prerelease","type":"boolean"},"latest_version":{"description":"Latest version available (e.g., \"v1.2.3\")","type":"string"},"nudges_suppressed":{"description":"UI surfaces must stay quiet (CI / non-interactive context); machine-readable fields still report the facts — Spec 079 FR-019","type":"boolean"},"release_url":{"description":"URL to the release page","type":"string"},"releases_behind":{"description":"Releases on the offered channel between the running and offered versions","type":"integer"},"releases_behind_saturated":{"description":"ReleasesBehind is a lower bound: the running build predates the scanned release window","type":"boolean"},"update_command":{"description":"One-line update command for the channel; only set when an update is available and the channel has one — Spec 079 FR-009","type":"string"},"weeks_behind":{"description":"Whole weeks between the two releases' publish dates; 0 is a real value, absent means unknown","type":"integer"}},"type":"object"},"contracts.UpdatePolicy":{"description":"UpdatePolicy is the effective, hot-reloadable update policy (Spec 092\nFR-015). Always present: the ` + "`" + `update` + "`" + ` object above is omitted both when\nupdate checking is disabled AND when no check has produced a result\nyet, so its absence cannot tell a client whether it is allowed to run\nits own (e.g. Sparkle feed) check. This field states the answer.","properties":{"channel":{"description":"Channel is the tracked release channel: \"stable\" or \"rc\".","type":"string"},"enabled":{"description":"Enabled is the effective automatic-check kill switch: update_check.enabled\nwith MCPPROXY_DISABLE_AUTO_UPDATE=true winning over it. A user-initiated\n\"Check for Updates\" stays available regardless.","type":"boolean"},"nudges_suppressed":{"description":"NudgesSuppressed asks UI surfaces to stay quiet (CI / non-interactive)\nwhile machine-readable fields keep reporting the facts.","type":"boolean"}},"type":"object"},"contracts.UpstreamError":{"properties":{"error_message":{"type":"string"},"server_name":{"type":"string"},"timestamp":{"type":"string"}},"type":"object"},"contracts.UsageAggregateResponse":{"properties":{"freshness_ms":{"description":"age of the underlying snapshot in ms","type":"integer"},"generated_at":{"type":"string"},"other":{"$ref":"#/components/schemas/contracts.UsageOtherBucket"},"timeline":{"items":{"$ref":"#/components/schemas/contracts.UsageTimeBucket"},"type":"array","uniqueItems":false},"token_source":{"description":"\"bytes\" (size-based proxy, FR-006)","type":"string"},"tokens_saved":{"description":"echoed from ServerTokenMetrics (FR-007)","type":"integer"},"tokens_saved_estimated":{"description":"TokensSavedEstimated echoes ServerTokenMetrics.Estimated (Spec 109-k):\ntrue while TokensSaved is a synthetic simulation rather than derived\nfrom a real retrieve_tools call. Dropped (false, the zero value) for a\nscoped caller along with TokensSaved itself, above.","type":"boolean"},"tokens_saved_percentage":{"type":"number"},"tools":{"items":{"$ref":"#/components/schemas/contracts.UsageToolStat"},"type":"array","uniqueItems":false},"total_calls":{"description":"TotalCalls and TotalErrors are the headline counts for the window: the sum\nof the timeline this same response carries, so the tiles and the histogram\nunder them cannot disagree. They are NOT the sum of Tools — that list is\nlifetime-cumulative, upstream-only and truncated to top-N, and summing it\nclient-side is what made the Usage tab print a third number for the same\n24 hours (audit finding F1, #1046). The population is\nstorage.CountsAsCall, shared with ActivitySummaryResponse.CallCount.\n\nTwo bounds on how exactly this matches the Activity Log's own count.\nBoth are bounded and disclosed, unlike the population mismatch they\nreplace, which was unbounded and silent:\n\n - Window granularity is the timeline's: whole hour buckets, so the span\n is the requested window rounded up to a bucket edge.\n - This response is served from a snapshot behind a short read cache\n (observability.usage_cache_ttl, 5s by default) so the endpoint never\n scans the activity log per request, while the summary endpoint counts\n live. Calls that land inside that window appear on the Activity Log\n first. FreshnessMs and GeneratedAt say how old the figures are, and\n the Usage tab prints it (\"Updated 3s ago\").","type":"integer"},"total_errors":{"type":"integer"},"window":{"type":"string"}},"type":"object"},"contracts.UsageOtherBucket":{"description":"present only when the list was truncated to top-N","properties":{"calls":{"type":"integer"},"tools_folded":{"type":"integer"},"total_resp_bytes":{"type":"integer"}},"type":"object"},"contracts.UsageTimeBucket":{"properties":{"calls":{"type":"integer"},"errors":{"type":"integer"},"start":{"type":"string"},"total_resp_bytes":{"type":"integer"}},"type":"object"},"contracts.UsageToolStat":{"properties":{"avg_req_bytes":{"description":"null when no sized request calls","type":"integer"},"avg_resp_bytes":{"description":"null when sized_calls == 0 (only legacy 0-byte calls)","type":"integer"},"blocked":{"type":"integer"},"calls":{"type":"integer"},"error_rate":{"type":"number"},"errors":{"type":"integer"},"last_used":{"type":"string"},"p50_exceeds":{"type":"boolean"},"p50_ms":{"description":"P50Ms and P95Ms are read off a fixed latency histogram, so they are BUCKET\nBOUNDS, not measured durations: the true percentile is at or below the\nvalue, and a client must render it as a bound (\"≤ 5 ms\"). P50Exceeds /\nP95Exceeds flip that reading for the unbounded overflow bucket, where the\nvalue is the last bound and the truth is above it (\"\u003e 10 s\").","type":"integer"},"p95_exceeds":{"type":"boolean"},"p95_ms":{"type":"integer"},"rejected":{"description":"spec 093: shed by a concurrency limit; never executed, so excluded from calls/latency","type":"integer"},"server":{"type":"string"},"sized_calls":{"description":"calls with known response size (basis for avg_resp_bytes)","type":"integer"},"tool":{"type":"string"},"total_req_bytes":{"type":"integer"},"total_resp_bytes":{"type":"integer"}},"type":"object"},"contracts.ValidateConfigResponse":{"properties":{"errors":{"items":{"$ref":"#/components/schemas/contracts.ValidationError"},"type":"array","uniqueItems":false},"valid":{"type":"boolean"}},"type":"object"},"contracts.ValidationError":{"properties":{"field":{"type":"string"},"message":{"type":"string"}},"type":"object"},"contracts.ViewAsCounts":{"description":"Counts is present only for a NON-administrator profile view-as (Spec 108\nFR-032): the response then lists only the visible rows, and this is the\nonly trace of the rest, with no per-server, per-tier or per-reason\nbreakdown.","properties":{"hidden":{"type":"integer"},"visible":{"type":"integer"}},"type":"object"},"contracts.WorkSession":{"properties":{"attempts":{"description":"Attempts, Failures and PolicyBlocks are lifetime counts of the session.\nPolicyBlocks are included in Failures.","type":"integer"},"client_id":{"type":"string"},"client_name":{"type":"string"},"connection_count":{"description":"Administrators only.","type":"integer"},"duration_ms":{"type":"integer"},"ended_at":{"type":"string"},"failures":{"type":"integer"},"first_failure_at":{"type":"string"},"id":{"type":"string"},"last_activity_at":{"type":"string"},"last_failure":{"$ref":"#/components/schemas/contracts.WorkSessionFailure"},"ownerless":{"type":"boolean"},"policy_blocks":{"type":"integer"},"profile":{"description":"Profile is returned to administrators only.","type":"string"},"profile_source":{"type":"string"},"project_name":{"description":"ProjectName is the basename of the client's workspace, when it\ndisclosed one.","type":"string"},"rebuilt":{"type":"boolean"},"run_name":{"type":"string"},"started_at":{"type":"string"},"status":{"description":"Status is \"active\" or \"ended\".","type":"string"},"stored_failures":{"description":"StoredFailures counts the failures whose rows are still in the log;\nit is what the timeline can navigate.","type":"integer"},"surface":{"type":"string"},"token_name":{"type":"string"},"truncated_start_at":{"type":"string"}},"type":"object"},"contracts.WorkSessionEnvelope":{"properties":{"data":{"$ref":"#/components/schemas/contracts.WorkSession"},"success":{"type":"boolean"}},"type":"object"},"contracts.WorkSessionFailure":{"properties":{"at":{"type":"string"},"error_class":{"type":"string"},"error_code":{"type":"string"},"policy_block":{"description":"PolicyBlock is true when the failure was a refusal by MCPProxy itself.","type":"boolean"},"reason":{"description":"Reason is at most 200 characters and never contains argument or\nresponse bodies.","type":"string"},"server":{"type":"string"},"tool":{"type":"string"}},"type":"object"},"contracts.WorkSessionListEnvelope":{"properties":{"data":{"$ref":"#/components/schemas/contracts.WorkSessionListResponse"},"success":{"type":"boolean"}},"type":"object"},"contracts.WorkSessionListResponse":{"properties":{"limit":{"type":"integer"},"offset":{"type":"integer"},"sessions":{"items":{"$ref":"#/components/schemas/contracts.WorkSession"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.WorkSessionTimelineEnvelope":{"properties":{"data":{"$ref":"#/components/schemas/contracts.WorkSessionTimelineResponse"},"success":{"type":"boolean"}},"type":"object"},"contracts.WorkSessionTimelineResponse":{"properties":{"earlier_failures_not_stored":{"type":"boolean"},"failure_index":{"description":"FailureIndex is the 1-based number of the failure at or before the\nposition among the stored failures in reach (0 when none), and\nFailureTotal their count.","type":"integer"},"failure_total":{"type":"integer"},"has_after":{"type":"boolean"},"has_before":{"type":"boolean"},"lifetime_failures":{"description":"LifetimeFailures is the session's lifetime failure count in reach.\nEarlierFailuresNotStored says some of them are no longer in the log.","type":"integer"},"position":{"description":"Position is the index of the row the page is positioned at; TotalRows\nis the number of rows in the caller's view.","type":"integer"},"rows":{"items":{"$ref":"#/components/schemas/contracts.WorkSessionTimelineRow"},"type":"array","uniqueItems":false},"session":{"$ref":"#/components/schemas/contracts.WorkSession"},"total_rows":{"type":"integer"}},"type":"object"},"contracts.WorkSessionTimelineRow":{"properties":{"activity":{"$ref":"#/components/schemas/contracts.ActivityRecord"},"at":{"description":"At is the time of the row.","type":"string"},"bodies_removed":{"description":"BodiesRemoved is true when retention removed the row's argument and\nresponse bodies to keep the row.","type":"boolean"},"failed":{"description":"Failed marks the counted row of a failed attempt; PolicyBlock marks a\nrefusal by MCPProxy itself.","type":"boolean"},"index":{"description":"Index is the row's position in the caller's view of the timeline.","type":"integer"},"kind":{"type":"string"},"policy_block":{"type":"boolean"},"precedes_session":{"description":"PrecedesSession marks an upstream event from before the session\nstarted: the latest event of a server the session then failed on,\nstill unresolved when the session began (release QA F2, SC-005).","type":"boolean"}},"type":"object"},"data":{"properties":{"data":{"$ref":"#/components/schemas/contracts.InfoResponse"}},"type":"object"},"httpapi.AccessExplanationData":{"properties":{"first_failure":{"type":"string","x-enum-varnames":["StepCredential","StepProfile","StepServerInScope","StepToolRule","StepTierCap","StepTokenPermission","StepGlobalGate","StepServerState","StepToolApproval"]},"fixes":{"items":{"$ref":"#/components/schemas/runtime.Fix"},"type":"array","uniqueItems":false},"profile":{"$ref":"#/components/schemas/runtime.ExplainProfileView"},"steps":{"items":{"$ref":"#/components/schemas/runtime.ExplainStepView"},"type":"array","uniqueItems":false},"subject":{"$ref":"#/components/schemas/runtime.ExplainSubjectView"},"tool":{"type":"string"},"verdict":{"$ref":"#/components/schemas/profile.ExplainVerdict"}},"type":"object"},"httpapi.AccessSuggestionsData":{"properties":{"already_fixed":{"description":"AlreadyFixed counts groups the explainer now allows (they drop out).","type":"integer"},"blocked_calls":{"description":"BlockedCalls counts every profile-refused call in the window.","type":"integer"},"non_profile_blocked":{"description":"NonProfileBlocked counts blocked calls with a cause outside profiles.","type":"integer"},"patches":{"items":{"$ref":"#/components/schemas/runtime.ProfilePatch"},"type":"array","uniqueItems":false},"profile_removed":{"description":"ProfileRemoved counts groups whose profile no longer exists (they drop out).","type":"integer"},"since":{"type":"string"},"suggestions":{"items":{"$ref":"#/components/schemas/runtime.AccessSuggestion"},"type":"array","uniqueItems":false},"unattributed":{"description":"Unattributed counts profile refusals whose record names no profile.","type":"integer"},"until":{"type":"string"},"window":{"type":"string"}},"type":"object"},"httpapi.AddServerRequest":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges is the per-server intent to auto-approve\nnew/changed tools past the trust baseline (MCP-2930). Tri-state *bool:\na nil pointer means \"leave unchanged\" on PATCH; a present value\n(including false) is applied. Mirrors config.ServerConfig's *bool\nsemantics — do NOT collapse to a plain bool, or an omitted field would\nsilently reset a previously-set value.","type":"boolean"},"command":{"type":"string"},"enabled":{"type":"boolean"},"env":{"additionalProperties":{"type":"string"},"type":"object"},"expose_prompts":{"description":"ExposePrompts is the per-server override for prompt aggregation (F9):\nwhether this server's advertised MCP prompts are merged into mcpproxy's\nprompts/list. Tri-state *bool mirroring config.ServerConfig.ExposePrompts —\na nil pointer means \"leave unchanged\" on PATCH (and \"inherit the default\naggregate behavior\" on create); a present value (including false) is applied.","type":"boolean"},"expose_skills":{"description":"ExposeSkills is the per-server skills override (MCP skills extension).\nTri-state *bool mirroring config.ServerConfig.ExposeSkills: nil means\n\"leave unchanged\" on PATCH and \"inherit\" on create.","type":"boolean"},"forward_headers":{"description":"ForwardHeaders is the per-server allowlist of inbound MCP client header\nNAMES forwarded to this server on tools/call (Spec 112). Names only, never\nvalues. On PATCH a nil slice (field omitted) leaves the stored allowlist\nunchanged and an empty array ([]) clears it. Invalid, denied, duplicate\nand static-header-colliding names are rejected with 400.","items":{"type":"string"},"type":"array","uniqueItems":false},"headers":{"additionalProperties":{"type":"string"},"type":"object"},"init_timeout":{"description":"InitTimeout is the per-server MCP ` + "`" + `initialize` + "`" + ` handshake deadline override\n(MCP-3322 / GH #760), serialized as a duration string (e.g. \"120s\"). A nil\npointer means \"leave unchanged\" on PATCH; a present value is applied.\nMirrors config.ServerConfig.InitTimeout's *Duration tri-state.","type":"string"},"isolation":{"$ref":"#/components/schemas/httpapi.IsolationRequest"},"max_concurrent_requests":{"description":"MaxConcurrentRequests / QueueSize / QueueTimeout are the per-server\nconcurrency overrides (spec 093 / GH #955, FR-020 scope (c)). Each is\ntri-state: a nil pointer means \"leave unchanged\" on PATCH and \"inherit\nserver_concurrency_defaults\" on create; an explicit 0 disables that\nsetting for this server; a positive value overrides it. Do NOT collapse\nthem to plain values — an omitted field would then silently reset a\nconfigured limit.","type":"integer"},"name":{"type":"string"},"protocol":{"type":"string"},"quarantined":{"type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_on_use":{"type":"boolean"},"tool_argument_error_mode":{"description":"Empty preserves an update; detailed explicitly resets a redacted policy.","type":"string"},"trust_mode":{"description":"TrustMode is the per-server trust tier (spec 086): \"auto\", \"scan\", or\n\"manual\". Empty means \"leave unchanged\" on PATCH (and inherit the migrated\ndefault on create). A non-empty value is applied to ServerConfig.TrustMode\nand resolved by EffectiveTrustMode (an unrecognized value fails closed to\nmanual). This is the REST seam for changing the trust tier via\nPOST/PATCH /api/v1/servers.","type":"string"},"url":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"httpapi.BindingGuardResponse":{"properties":{"bindings":{"items":{"$ref":"#/components/schemas/httpapi.GuardBinding"},"type":"array","uniqueItems":false},"code":{"description":"binding_bypassable_without_auth","type":"string"},"error":{"description":"Human-readable, byte-stable refusal text","type":"string"},"fixes":{"items":{"$ref":"#/components/schemas/httpapi.GuardFixOption"},"type":"array","uniqueItems":false},"request_id":{"type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.BulkAssignRequest":{"properties":{"from_profile":{"type":"string"},"mode":{"type":"string"},"to_profile":{"type":"string"}},"type":"object"},"httpapi.BulkAssignResponse":{"properties":{"moved":{"items":{"type":"string"},"type":"array","uniqueItems":false},"skipped":{"items":{"$ref":"#/components/schemas/httpapi.BulkAssignSkipped"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.BulkAssignSkipped":{"properties":{"client_id":{"type":"string"},"code":{"type":"string"},"error":{"type":"string"}},"type":"object"},"httpapi.BundleRollbackRefusedResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"rejection":{"$ref":"#/components/schemas/scanner.BundleRejection"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"httpapi.CanonicalConfigPath":{"properties":{"description":{"description":"Brief description","type":"string"},"exists":{"description":"Whether the file exists","type":"boolean"},"format":{"description":"Format identifier (e.g., \"claude_desktop\")","type":"string"},"name":{"description":"Display name (e.g., \"Claude Desktop\")","type":"string"},"os":{"description":"Operating system (darwin, windows, linux)","type":"string"},"path":{"description":"Full path to the config file","type":"string"}},"type":"object"},"httpapi.CanonicalConfigPathsResponse":{"properties":{"os":{"description":"Current operating system","type":"string"},"paths":{"description":"List of canonical config paths","items":{"$ref":"#/components/schemas/httpapi.CanonicalConfigPath"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ClientBindingErrorResponse":{"properties":{"code":{"type":"string"},"error":{"type":"string"},"field":{"type":"string"},"request_id":{"type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.ClientBindingResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"warnings":{"items":{"$ref":"#/components/schemas/httpapi.ClientWarning"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ClientSnippet":{"properties":{"generic_http":{"type":"string"},"header_name":{"type":"string"}},"type":"object"},"httpapi.ClientWarning":{"properties":{"action":{"$ref":"#/components/schemas/runtime.WarningAction"},"bindings":{"items":{"$ref":"#/components/schemas/runtime.BindingRef"},"type":"array","uniqueItems":false},"client_id":{"type":"string"},"code":{"$ref":"#/components/schemas/profile.WarningCode"},"fixes":{"items":{"$ref":"#/components/schemas/runtime.GuardFix"},"type":"array","uniqueItems":false},"message":{"type":"string"},"severity":{"$ref":"#/components/schemas/profile.WarningSeverity"}},"type":"object"},"httpapi.ConnectConflictResponse":{"properties":{"action":{"description":"already_exists | precondition_failed","type":"string"},"data":{"$ref":"#/components/schemas/connect.ConnectResult"},"error":{"description":"Human-readable message","type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.ConnectRequest":{"properties":{"force":{"description":"Overwrite existing entry","type":"boolean"},"keyless":{"type":"boolean"},"mode":{"type":"string"},"precondition_token":{"description":"PreconditionToken is the opaque token from the preview this write was\nconfirmed against (Spec 091 FR-005). When present, the core rechecks it\nat write time and responds 409 with action \"precondition_failed\" —\nwriting nothing — if the config or the entry MCPProxy would write has\ndrifted since; the caller then re-previews instead of retrying. Absent\nmeans exactly the pre-091 behavior. A replace-classified flow sends this\nTOGETHER with force=true: the token, not the absence of force, is the\noverwrite safety.","type":"string"},"profile":{"description":"Profile, Mode and Keyless are the client-credential intent (Spec 108\nFR-024). Profile names the profile the client's credential binds to;\n\"\" is the built-in All servers scope. Omitted means \"not specified\": a\nfresh credential defaults to All servers and a reconnect keeps the\nclient's existing binding (a reconnect never silently widens a locked\nclient). Mode is locked|switchable (default locked for a named profile,\nswitchable for All servers). Keyless writes a credential-less entry and\nis only possible while require_mcp_auth is off; it cannot carry a\nprofile or mode.","type":"string"},"server_name":{"description":"Defaults to \"mcpproxy\"","type":"string"}},"type":"object"},"httpapi.CreateClientRequest":{"properties":{"display_name":{"type":"string"},"expires_in":{"description":"ExpiresIn is a duration like 30d or 720h; default and cap are 365 days.","type":"string"},"id":{"type":"string"},"mode":{"type":"string"},"profile":{"type":"string"},"purpose":{"description":"Purpose is the stated, unenforced task brief (Spec 115), at most 500\ncharacters; screened for secrets before anything is stored.","type":"string"}},"type":"object"},"httpapi.CreateClientResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"credential":{"type":"string"},"snippet":{"$ref":"#/components/schemas/httpapi.ClientSnippet"}},"type":"object"},"httpapi.EffectiveToolsData":{"properties":{"counts":{"$ref":"#/components/schemas/runtime.EffectiveCounts"},"profile":{"type":"string"},"stale_classification_reasons":{"additionalProperties":{"type":"string"},"description":"StaleClassificationReasons maps each stale classify entry to why it no\nlonger applies: profile.StaleClassificationAnnotated or\nprofile.StaleClassificationMissing. It is computed over the UNFILTERED\ntool set, so a server or reason filter never changes it. Administrators\nonly.","type":"object"},"stale_classifications":{"description":"StaleClassifications lists classify entries for tools that are now\nannotated or no longer exist (FR-005). Administrators only.","items":{"type":"string"},"type":"array","uniqueItems":false},"tools":{"items":{"$ref":"#/components/schemas/runtime.EffectiveTool"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.EnvFieldPreview":{"properties":{"empty_or_placeholder":{"type":"boolean"},"name":{"type":"string"},"secret_like":{"type":"boolean"},"value_present":{"type":"boolean"}},"type":"object"},"httpapi.FinalizeClientResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"rotation":{"$ref":"#/components/schemas/httpapi.RotationState"}},"type":"object"},"httpapi.ForgetClientResponse":{"properties":{"disconnect_error":{"type":"string"},"disconnected":{"type":"boolean"},"revoked":{"type":"string"}},"type":"object"},"httpapi.GuardBinding":{"properties":{"client_id":{"type":"string"},"mode":{"type":"string"},"profile":{"type":"string"},"token_name":{"type":"string"}},"type":"object"},"httpapi.GuardFixOption":{"properties":{"kind":{"type":"string"},"target":{"type":"string"}},"type":"object"},"httpapi.HeaderFieldPreview":{"properties":{"empty_or_placeholder":{"type":"boolean"},"name":{"type":"string"},"secret_like":{"type":"boolean"},"value_present":{"type":"boolean"}},"type":"object"},"httpapi.ImportFromPathRequest":{"properties":{"format":{"description":"Optional format hint","type":"string"},"path":{"description":"File path to import from","type":"string"},"rename":{"additionalProperties":{"type":"string"},"description":"Rename maps a server name → new name. Applied after parsing so the\ncaller can disambiguate cross-source name collisions (Spec 046 v2 —\ne.g. \"mcpproxy\" → \"mcpproxy_claude_code\"). Keys are matched against\neither the raw source name (OriginalName) or the sanitized name shown\nin the preview (Server.Name); these differ for names that need\nsanitizing (e.g. \"Figma Desktop\" → \"Figma_Desktop\"). Keys not present\nin the imported set are ignored.","type":"object"},"server_names":{"description":"Optional: import only these servers","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportRequest":{"properties":{"allow_paste_fallback":{"description":"AllowPasteFallback opts into detecting a bare URL or a single command\nline (FR-064) when Format/format detection would otherwise fail — see\nconfigimport.ImportOptions.AllowPasteFallback for why this must stay\nopt-in (review round 4 F-E). Only the interactive Paste tab sets this;\nevery other caller of this endpoint (the general \"Import config\"\npanel, or a direct API call) leaves it false and gets a clear\n\"unable to detect configuration format\" error for a plain one-liner\ninstead of it being silently guessed at and, on apply, added as a\nreal server with no confirmation step.","type":"boolean"},"content":{"description":"Raw JSON or TOML content","type":"string"},"env_override":{"additionalProperties":{"type":"string"},"description":"EnvOverride/HeaderOverride (Spec 109 FR-064/065, PR review round 4\nF-A/F-D fix): the Paste tab's per-field Value/Secret edits — a plain\nvalue the user typed, or a keyring ref path if they chose Secret —\nkeyed by field name. Applied to the matching imported server's\nEnv/Headers ONLY when preview=false, directly on the server this\nrequest's own raw Content parses to server-side. This is what lets\nthe apply call carry the user's edited env/header values without\never round-tripping the redacted preview: url/command/args on apply\nalways come from re-parsing Content here, never from a client-held\npreview response, so a credential embedded in a URL query param or\nargv flag (which the preview necessarily redacted for display) is\nnever overwritten with the masked placeholder.","type":"object"},"format":{"description":"Optional format hint","type":"string"},"header_override":{"additionalProperties":{"type":"string"},"type":"object"},"server_names":{"description":"Optional: import only these servers","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportResponse":{"properties":{"failed":{"items":{"$ref":"#/components/schemas/configimport.FailedServer"},"type":"array","uniqueItems":false},"format":{"type":"string"},"format_name":{"type":"string"},"imported":{"items":{"$ref":"#/components/schemas/httpapi.ImportedServerResponse"},"type":"array","uniqueItems":false},"skipped":{"items":{"$ref":"#/components/schemas/configimport.SkippedServer"},"type":"array","uniqueItems":false},"summary":{"$ref":"#/components/schemas/configimport.ImportSummary"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportedServerResponse":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"command":{"type":"string"},"env":{"items":{"$ref":"#/components/schemas/httpapi.EnvFieldPreview"},"type":"array","uniqueItems":false},"fields_skipped":{"items":{"type":"string"},"type":"array","uniqueItems":false},"headers":{"items":{"$ref":"#/components/schemas/httpapi.HeaderFieldPreview"},"type":"array","uniqueItems":false},"name":{"type":"string"},"original_name":{"type":"string"},"protocol":{"type":"string"},"source_format":{"type":"string"},"summary":{"description":"Summary, Tags, Env and Headers are the Spec 109 FR-064 preview\nenrichment (contracts/rest-api.md \"Import preview\"). Summary and Tags\nare built from the already-redacted URL/Command/Args above, so a\nsecret embedded in argv or a URL query never reaches Summary either.\nEnv/Headers never carry the raw value — only its presence and two\nbooleans a surface uses to default the Value/Secret toggle (FR-065).","type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"url":{"type":"string"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.IsolationRequest":{"description":"Isolation carries per-server Docker isolation overrides (enabled,\nmode_override, image, network_mode, extra_args, working_dir). A nil\npointer means \"do not touch isolation config\". A present object is\napplied field-by-field ON TOP of the persisted overrides, so omitting a\nfield leaves it alone; clear an individual override by sending it\nexplicitly (` + "`" + `\"enabled\": null` + "`" + `, ` + "`" + `\"image\": \"\"` + "`" + `).","properties":{"enabled":{"description":"Enabled exists ONLY to detect and reject an echoed-back read. It is the\neffective state on the read surface and is never writable; see validate().","type":"boolean"},"enabled_override":{"description":"EnabledOverride is the tri-state per-server override — the RAW value, the\nsame one reads return as ` + "`" + `enabled_override` + "`" + `. It has THREE meaningful wire\nstates, and collapsing them is what silently un-isolated servers\n(GH #1142):\n - absent → leave the persisted override untouched\n - null → clear the override, back to inheriting the global\n - true / false → set an explicit opt-in / opt-out","type":"boolean"},"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"mode_override":{"description":"ModeOverride sets ` + "`" + `isolation.mode` + "`" + ` (\"docker\" | \"sandbox\" | \"none\").\nnil leaves the persisted value alone; an empty string clears it. An\nunrecognized value is rejected with a 400 rather than persisted.","type":"string"},"network_mode":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"httpapi.OnboardingMarkRequest":{"properties":{"connect_step_status":{"description":"ConnectStepStatus is one of: \"\", \"completed\", \"skipped\". Empty\npreserves the existing value. The stored enum is wider (Spec 080\nFR-001): a \"skipped\" request for a previously untouched connect step\nis upgraded server-side to \"completed_external\" when the install\nshows positive evidence of an external connection (Spec 080 FR-002).\n\"completed_external\" is NOT accepted from clients — it must never be\npersisted without that server-verified evidence (edge case: \"never\nguess completed_external without positive evidence\").","type":"string"},"connected_client_id":{"description":"ConnectedClientID records a successful connect write for this client id\n(Spec 109-b FR-042, review round 6). The REST connect endpoint\n(POST /api/v1/connect/{client}) already records this itself on success;\nthis field exists so ` + "`" + `mcpproxy connect` + "`" + ` — which writes the client's\nconfig file directly, without going through that endpoint, so the\ncommand still works when no daemon is running — can relay the same\nevent to a daemon that IS running, keeping ClientConnectedAt in sync\nacross both surfaces. Must be a known id from the fixed connect client\nregistry (internal/connect.GetAllClients); any other value is rejected,\nmatching the field's \"bounded by the registry\" invariant\n(data-model.md §7).","type":"string"},"disconnected_client_id":{"description":"DisconnectedClientID relays a successful local CLI disconnect to a running\ndaemon, which cannot observe the CLI's direct config-file edit itself.\nLike ConnectedClientID, it is bounded to the fixed client registry.","type":"string"},"engaged":{"description":"Engaged marks the wizard as engaged (completed or explicitly skipped).\nOnce true, the wizard does not auto-show again.","type":"boolean"},"mark_shown":{"description":"MarkShown records the wizard's first display time if not already set.","type":"boolean"},"server_step_status":{"description":"ServerStepStatus is one of: \"\", \"completed\", \"skipped\". Empty\npreserves the existing value.","type":"string"}},"type":"object"},"httpapi.OnboardingStateResponse":{"properties":{"configured_server_count":{"description":"ConfiguredServerCount is the number of upstream MCP servers configured\nin mcpproxy (counts both enabled and disabled).","type":"integer"},"connected_client_count":{"description":"ConnectedClientCount is the number of supported clients currently\npointing at mcpproxy.","type":"integer"},"connected_client_ids":{"description":"ConnectedClientIDs are the identifiers of supported clients currently\npointing at mcpproxy. Drawn exclusively from the fixed adapter table —\nuser-entered values never appear here.","items":{"type":"string"},"type":"array","uniqueItems":false},"first_mcp_client_ever":{"description":"FirstMCPClientEver is true once any MCP client has successfully completed\nan ` + "`" + `initialize` + "`" + ` round-trip with this mcpproxy. Sourced from the Spec 044\nactivation bucket. Drives the Verify tab's \"green check\" state.","type":"boolean"},"has_configured_server":{"description":"HasConfiguredServer is true if at least one upstream MCP server is\nconfigured (regardless of current connection health).","type":"boolean"},"has_connected_client":{"description":"HasConnectedClient is true if at least one supported AI client currently\nhas mcpproxy registered in its config.","type":"boolean"},"has_usable_server":{"description":"HasUsableServer is true once at least one enabled, non-quarantined\nserver has usable health and at least one approved (non-disabled) tool.\nThis is the real \"the wizard has something to try\" signal:\nHasConfiguredServer only means a server entry exists, even while every\none of them sits quarantined, requires sign-in, or has zero approved\ntools. The Servers step and Setup badge use this instead of\nHasConfiguredServer, which is kept above for compatibility.\nHealthStatus.Usable is the shared\nreadiness contract used by every UI surface (Spec 109-c, tasks.md T051).","type":"boolean"},"incomplete_tab_count":{"description":"IncompleteTabCount is the number of wizard tabs whose state is incomplete.\nDrives the sidebar Setup entry's badge. Formula:\n +1 if HasConnectedClient == false\n +1 if HasUsableServer == false\n +1 if FirstMCPClientEver == false","type":"integer"},"mcp_clients_seen_ever":{"description":"MCPClientsSeenEver is the capped list of recognized client names that\nhave ever called this mcpproxy. Names come from the MCP ` + "`" + `initialize` + "`" + `\npayload's ` + "`" + `clientInfo.name` + "`" + ` field, sanitized. Surfaces on the Verify tab\nso the user can see whether their real IDE — not a test client — has\nconnected.","items":{"type":"string"},"type":"array","uniqueItems":false},"should_show_wizard":{"description":"ShouldShowWizard is the derived flag the frontend uses to decide\nwhether to auto-show. True when not engaged and IncompleteTabCount \u003e 0\n(Spec 046 v2 — semantics widened to also count the Verify tab).","type":"boolean"},"state":{"$ref":"#/components/schemas/storage.OnboardingState"},"usable_servers":{"description":"UsableServers lists the names behind HasUsableServer, for the Verify\nstep's suggested-prompt generator (FR-042): prompts are only built from\ntools of servers in this list, never from a quarantined or toolless one.","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileConflictResponse":{"properties":{"code":{"type":"string"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"description":"Always false","type":"boolean"},"used_by":{"$ref":"#/components/schemas/httpapi.ProfileUsedByData"}},"type":"object"},"httpapi.ProfileDeleteData":{"properties":{"anonymous_profile_moved_to":{"type":"string"},"deleted":{"type":"string"},"moved":{"$ref":"#/components/schemas/runtime.MovedRefs"}},"type":"object"},"httpapi.ProfileListData":{"properties":{"anonymous_profile":{"type":"string"},"profiles":{"items":{"$ref":"#/components/schemas/runtime.ProfileView"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileRenameData":{"properties":{"moved":{"$ref":"#/components/schemas/runtime.MovedRefs"},"profile":{"$ref":"#/components/schemas/runtime.ProfileView"}},"type":"object"},"httpapi.ProfileTryData":{"properties":{"hidden":{"items":{"$ref":"#/components/schemas/runtime.TryHidden"},"type":"array","uniqueItems":false},"hidden_by_profile":{"type":"integer"},"hidden_truncated":{"type":"boolean"},"results":{"items":{"additionalProperties":{},"type":"object"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileUsedByData":{"properties":{"anonymous_profile":{"type":"boolean"},"clients":{"items":{"$ref":"#/components/schemas/runtime.UsedByClient"},"type":"array","uniqueItems":false},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileViewData":{"properties":{"blocked_24h":{"type":"integer"},"calls_24h":{"type":"integer"},"code_execution":{"type":"boolean"},"description":{"type":"string"},"effective_code_execution":{"type":"boolean"},"effective_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"effective_unannotated":{"type":"string"},"is_legacy":{"type":"boolean"},"management_tools":{"type":"boolean"},"max_tier":{"type":"string"},"name":{"type":"string"},"servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"switchable_to":{"items":{"type":"string"},"type":"array","uniqueItems":false},"title":{"type":"string"},"tool_count":{"description":"ToolCount is the v2 field: indexed tools on the effective servers.\nDeprecated: use tool_counts.","type":"integer"},"tool_counts":{"$ref":"#/components/schemas/runtime.ToolCounts"},"tools":{"$ref":"#/components/schemas/config.ProfileToolRules"},"unannotated":{"type":"string"},"used_by":{"$ref":"#/components/schemas/runtime.UsedBy"}},"type":"object"},"httpapi.ProfileWriteData":{"properties":{"profile":{"$ref":"#/components/schemas/runtime.ProfileView"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.PutClientBindingRequest":{"properties":{"mode":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.RenameProfileRequest":{"properties":{"new_name":{"type":"string"}},"type":"object"},"httpapi.RotateClientRequest":{"properties":{"precondition_token":{"description":"PreconditionToken is the token of GET /connect/{client}/preview; it\nbinds a supported client's rotation to what the preview showed.","type":"string"}},"type":"object"},"httpapi.RotateClientResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"connect":{"$ref":"#/components/schemas/connect.ConnectResult"},"credential":{"type":"string"},"rotation":{"$ref":"#/components/schemas/httpapi.RotationState"},"snippet":{"$ref":"#/components/schemas/httpapi.ClientSnippet"}},"type":"object"},"httpapi.RotationState":{"properties":{"state":{"type":"string"}},"type":"object"},"httpapi.SetActiveProfileRequest":{"properties":{"active_profile":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.StaleReviewErrorResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"stale_tools":{"$ref":"#/components/schemas/httpapi.StaleToolsDetail"},"success":{"type":"boolean"}},"type":"object"},"httpapi.StaleToolsDetail":{"properties":{"changed":{"items":{"type":"string"},"type":"array","uniqueItems":false},"missing_blocks":{"items":{"type":"string"},"type":"array","uniqueItems":false},"unreviewed":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.TryProfileRequest":{"properties":{"limit":{"type":"integer"},"profile":{"$ref":"#/components/schemas/config.ProfileConfig"},"query":{"type":"string"}},"type":"object"},"httpapi.UndoConnectRequest":{"properties":{"backup_name":{"description":"BackupName is the bare filename (filepath.Base) of the backup returned as\nbackup_path by the preceding connect — a name, never a path. Undo resolves\nthe full path server-side by joining it with the client's own config\ndirectory, so a client-supplied value can never contribute a directory\ncomponent (traversal is impossible by construction). Empty means the\nconnect created the file (no prior file existed), so undo removes it.","type":"string"},"server_name":{"description":"Defaults to \"mcpproxy\"","type":"string"}},"type":"object"},"httpapi.UpdateFailureRequest":{"properties":{"stage":{"description":"Stage is the failure stage of the update session.","enum":["appcast","download","install","other"],"type":"string"}},"type":"object"},"httpapi.UpgradeAdminKeyHoldersRequest":{"properties":{"apply":{"type":"boolean"},"mode":{"type":"string"},"precondition_token":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.approveToolsRequest":{"properties":{"approve_all":{"type":"boolean"},"expected_hashes":{"additionalProperties":{"type":"string"},"description":"ExpectedHashes binds the approval to the reviewed definitions (Spec\n117 PR-2, #1566): tool name -\u003e the review's current_hash. Absent or\nnull is an unbound (legacy) request; {} is bound.","type":["object","null"]},"expected_incarnation":{"description":"ExpectedIncarnation binds the approval to the server the client\nreviewed (Spec 116 FR-017); 409 server_replaced on a mismatch. It is\nindependent of ExpectedHashes and the two may be sent together.","type":"integer"},"tools":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.attentionResponse":{"properties":{"count":{"type":"integer"},"generated_at":{"type":"string"},"items":{"items":{"$ref":"#/components/schemas/contracts.AttentionItem"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.bundleRollbackRequest":{"properties":{"digest":{"description":"Digest is the full 64-character lowercase hex SHA-256 of the target.","type":"string"},"embedded":{"description":"Embedded rolls back to the corpus compiled into this binary.","type":"boolean"},"path":{"description":"Path is where to find the target bundle (a hint only).","type":"string"}},"type":"object"},"httpapi.clientPresence":{"properties":{"active_sessions":{"type":"integer"},"blocked_24h":{"type":"integer"},"calls_24h":{"type":"integer"},"config_path":{"type":"string"},"connected":{"type":"boolean"},"connection_unverified":{"type":"boolean"},"credential_checked_at":{"type":"string"},"credential_state":{"$ref":"#/components/schemas/profile.CredentialState"},"display_name":{"type":"string"},"display_path":{"type":"string"},"expires_at":{"type":"string"},"icon":{"type":"string"},"id":{"type":"string"},"installed":{"type":"boolean"},"issuer":{"$ref":"#/components/schemas/auth.CredentialIssuer"},"kind":{"type":"string"},"last_seen":{"type":"string"},"lease":{"type":"boolean"},"profile":{"type":"string"},"profile_missing":{"type":"boolean"},"profile_mode":{"type":"string"},"profile_source":{"description":"profile_source is pin (locked) or binding (switchable) and is empty when\ncredential_state is not client.","type":"string"},"profile_state":{"type":"string"},"profile_title":{"type":"string"},"purpose":{"type":"string"},"reload_hint":{"type":"string"},"revoked_at":{"description":"Spec 115 lifecycle fields of the client's credential record (additive):\nwhen it was revoked, who issued it, its stated (unenforced) purpose,\nwhether it is a task lease (lifetime at issue \u003c= 24h) and whether its\nprofile still exists (ok | dangling | none).","type":"string"},"rotation_pending":{"type":"boolean"},"sessions":{"items":{"$ref":"#/components/schemas/httpapi.clientSession"},"type":"array","uniqueItems":false},"state":{"type":"string"},"token_name":{"type":"string"}},"type":"object"},"httpapi.clientSession":{"properties":{"id":{"type":"string"},"last_activity":{"type":"string"},"profile":{"description":"Profile and ProfileSource are the session's latest effective resolution\n(Spec 108-e FR-033); empty on legacy sessions.","type":"string"},"profile_source":{"type":"string"},"started_at":{"type":"string"},"work_session_id":{"type":"string"}},"type":"object"},"httpapi.clientsResponse":{"properties":{"clients":{"items":{"$ref":"#/components/schemas/httpapi.clientPresence"},"type":"array","uniqueItems":false},"routing":{},"warnings":{"items":{"$ref":"#/components/schemas/httpapi.ClientWarning"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.expectedIncarnationBody":{"properties":{"expected_incarnation":{"type":"integer"}},"type":"object"},"httpapi.securityApproveRequest":{"properties":{"block":{"items":{"type":"string"},"type":"array","uniqueItems":false},"expected_hashes":{"additionalProperties":{"type":"string"},"description":"ExpectedHashes binds the approval to the reviewed definitions (Spec\n117 PR-2, #1566): tool name -\u003e the review's current_hash. Absent or\nnull is an unbound (legacy) request; {} binds to the empty snapshot.\nIndependent of ExpectedIncarnation: a request may carry both, and the\ntwo refusals stay distinct (review_out_of_date vs server_replaced).","type":["object","null"]},"expected_incarnation":{"description":"ExpectedIncarnation binds the approval to the server the client\nreviewed (Spec 116 FR-017): a remove and re-add since then is refused\nwith 409 server_replaced and the replacement stays quarantined.","type":"integer"},"force":{"type":"boolean"}},"type":"object"},"management.BulkOperationResult":{"properties":{"errors":{"additionalProperties":{"type":"string"},"description":"Map of server name to error message","type":"object"},"failed":{"description":"Number of failed operations","type":"integer"},"successful":{"description":"Number of successful operations","type":"integer"},"total":{"description":"Total servers processed","type":"integer"}},"type":"object"},"observability.HealthResponse":{"properties":{"components":{"items":{"$ref":"#/components/schemas/observability.HealthStatus"},"type":"array","uniqueItems":false},"status":{"description":"\"healthy\" or \"unhealthy\"","type":"string"},"timestamp":{"type":"string"}},"type":"object"},"observability.HealthStatus":{"properties":{"error":{"type":"string"},"latency":{"type":"string"},"name":{"type":"string"},"status":{"description":"\"healthy\" or \"unhealthy\"","type":"string"}},"type":"object"},"observability.ReadinessResponse":{"properties":{"components":{"items":{"$ref":"#/components/schemas/observability.HealthStatus"},"type":"array","uniqueItems":false},"status":{"description":"\"ready\" or \"not_ready\"","type":"string"},"timestamp":{"type":"string"}},"type":"object"},"profile.AccessStepStatus":{"type":"string","x-enum-varnames":["AccessStepPass","AccessStepFail","AccessStepSkip"]},"profile.AccessSubjectKind":{"type":"string","x-enum-varnames":["AccessSubjectClient","AccessSubjectProfile","AccessSubjectToken","AccessSubjectAnonymous"]},"profile.BlockReason":{"type":"string","x-enum-varnames":["BlockReasonTier","BlockReasonRule","BlockReasonUnannotated","BlockReasonCodeExecution","BlockReasonManagement","BlockReasonServerScope"]},"profile.CredentialState":{"description":"Spec 108-f ClientView additions (data-model §7). The Spec 109 fields above\nare unchanged; everything below is additive.\n\ncredential_state is what the client's connection carries (client |\nadmin_key | none | revoked | expired | unknown). The stat-only list never\nreads a config: it reports the token store, else the last on-demand\nobservation (credential_checked_at says when), else unknown.","type":"string","x-enum-varnames":["CredentialStateClient","CredentialStateAdminKey","CredentialStateNone","CredentialStateRevoked","CredentialStateExpired","CredentialStateUnknown"]},"profile.ExplainStep":{"type":"string","x-enum-varnames":["StepCredential","StepProfile","StepServerInScope","StepToolRule","StepTierCap","StepTokenPermission","StepGlobalGate","StepServerState","StepToolApproval"]},"profile.ExplainVerdict":{"type":"string","x-enum-varnames":["ExplainVerdictAllowed","ExplainVerdictBlocked","ExplainVerdictHidden"]},"profile.FixAction":{"type":"string","x-enum-varnames":["FixAllowInProfile","FixClassifyInProfile","FixAddServerToProfile","FixMoveClient","FixEditToken","FixEnableServer","FixApproveTool","FixChangeSetting","FixReconnectClient"]},"profile.WarningCode":{"type":"string","x-enum-varnames":["WarningAnonymousDeniedByBindingGuard","WarningClientHoldsAdminKey","WarningClientCredentialExpiring","WarningClientRotationPending","WarningProfileMissing","WarningClientTokenNameConflict"]},"profile.WarningSeverity":{"type":"string","x-enum-varnames":["WarningSeverityWarn","WarningSeverityInfo"]},"runtime.AccessSuggestion":{"properties":{"block_reason":{"$ref":"#/components/schemas/profile.BlockReason"},"clients":{"items":{"type":"string"},"type":"array","uniqueItems":false},"count":{"type":"integer"},"first_seen":{"type":"string"},"fixes":{"description":"Fixes are the access explainer's remediations of the first failing step,\nin preference order. Empty for a deny rule and for the built-in tools.","items":{"$ref":"#/components/schemas/runtime.Fix"},"type":"array","uniqueItems":false},"last_seen":{"type":"string"},"needs_input":{"description":"NeedsInput names what a person must supply before a change is\napply-ready (classify: \"tier\").","items":{"type":"string"},"type":"array","uniqueItems":false},"note":{"type":"string"},"profile":{"type":"string"},"server":{"type":"string"},"suggestion":{"$ref":"#/components/schemas/runtime.SuggestionKind"},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false},"tool":{"description":"\"server:tool\", or the built-in name","type":"string"},"warning":{"description":"Warning is set for profile_code_execution and profile_management: both\nchange what a profile can do beyond tool access.","type":"string"}},"type":"object"},"runtime.BindingRef":{"properties":{"client_id":{"type":"string"},"mode":{"type":"string"},"profile":{"type":"string"},"token_name":{"type":"string"}},"type":"object"},"runtime.EffectiveCounts":{"properties":{"by_reason":{"additionalProperties":{"type":"integer"},"type":"object"},"callable":{"type":"integer"},"hidden":{"type":"integer"},"visible":{"type":"integer"}},"type":"object"},"runtime.EffectiveTool":{"properties":{"access":{"$ref":"#/components/schemas/runtime.ToolAccessView"},"classification_stale":{"type":"boolean"},"intrinsic_tier":{"type":"string"},"profile_tier":{"type":"string"},"server":{"type":"string"},"tool":{"type":"string"}},"type":"object"},"runtime.ExplainProfileView":{"properties":{"name":{"type":"string"},"source":{"type":"string"}},"type":"object"},"runtime.ExplainStepView":{"properties":{"detail":{"type":"string"},"status":{"$ref":"#/components/schemas/profile.AccessStepStatus"},"step":{"$ref":"#/components/schemas/profile.ExplainStep"}},"type":"object"},"runtime.ExplainSubjectView":{"properties":{"kind":{"$ref":"#/components/schemas/profile.AccessSubjectKind"},"name":{"type":"string"}},"type":"object"},"runtime.Fix":{"properties":{"action":{"$ref":"#/components/schemas/profile.FixAction"},"label":{"type":"string"},"profile":{"description":"Profile is set for move_client only: the destination profile slug the fix\nmoves the client to. Target stays the client id (UIs navigate by it) and\nLabel carries the title, so neither can name the slug.","type":"string"},"step":{"type":"string","x-enum-varnames":["StepCredential","StepProfile","StepServerInScope","StepToolRule","StepTierCap","StepTokenPermission","StepGlobalGate","StepServerState","StepToolApproval"]},"target":{"type":"string"}},"type":"object"},"runtime.GuardFix":{"properties":{"kind":{"type":"string"},"target":{"type":"string"}},"type":"object"},"runtime.MovedRefs":{"properties":{"clients":{"items":{"type":"string"},"type":"array","uniqueItems":false},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"runtime.ProfilePatch":{"properties":{"changes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"profile":{"type":"string"},"proposed":{"$ref":"#/components/schemas/config.ProfileConfig"}},"type":"object"},"runtime.ProfileView":{"properties":{"blocked_24h":{"type":"integer"},"calls_24h":{"type":"integer"},"code_execution":{"type":"boolean"},"description":{"type":"string"},"effective_code_execution":{"type":"boolean"},"effective_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"effective_unannotated":{"type":"string"},"is_legacy":{"type":"boolean"},"management_tools":{"type":"boolean"},"max_tier":{"type":"string"},"name":{"type":"string"},"servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"switchable_to":{"items":{"type":"string"},"type":"array","uniqueItems":false},"title":{"type":"string"},"tool_count":{"description":"ToolCount is the v2 field: indexed tools on the effective servers.\nDeprecated: use tool_counts.","type":"integer"},"tool_counts":{"$ref":"#/components/schemas/runtime.ToolCounts"},"tools":{"$ref":"#/components/schemas/config.ProfileToolRules"},"unannotated":{"type":"string"},"used_by":{"$ref":"#/components/schemas/runtime.UsedBy"}},"type":"object"},"runtime.SuggestionKind":{"type":"string","x-enum-varnames":["SuggestAllow","SuggestAddServer","SuggestClassify","SuggestNone"]},"runtime.ToolAccessView":{"properties":{"callable":{"type":"boolean"},"reason":{"type":"string"},"visible":{"type":"boolean"}},"type":"object"},"runtime.ToolCounts":{"properties":{"destructive":{"type":"integer"},"read":{"type":"integer"},"unannotated_hidden":{"type":"integer"},"write":{"type":"integer"}},"type":"object"},"runtime.TryHidden":{"properties":{"reason":{"type":"string"},"server":{"type":"string"},"tool":{"type":"string"}},"type":"object"},"runtime.UsedBy":{"properties":{"anonymous_profile":{"type":"boolean"},"clients":{"items":{"$ref":"#/components/schemas/runtime.UsedByClient"},"type":"array","uniqueItems":false},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"runtime.UsedByClient":{"properties":{"id":{"type":"string"},"mode":{"type":"string"}},"type":"object"},"runtime.WarningAction":{"properties":{"kind":{"type":"string"},"target":{"type":"string"}},"type":"object"},"scanner.BundleInfo":{"properties":{"authority":{"description":"Authority is the signing root serving this bundle: \"publisher\" (the\nembedded default, or verified against a publisher key), \"operator\", or \"\"\nfor an unsigned external bundle.","type":"string"},"bundle_version":{"description":"BundleVersion / SchemaVersion are the corpus's own declared versions.","type":"string"},"coverage_degraded":{"description":"CoverageDegraded suspends scan-mode auto-approval; DegradedReason says\nwhy (one of the Degraded* constants).","type":"boolean"},"declared_skipped":{"type":"integer"},"degraded_reason":{"type":"string"},"fingerprint":{"description":"Fingerprint is the first 12 hex chars of the SHA-256 of the corpus bytes:\na stable identity an operator (or automation) can compare across hosts\nwithout shipping the whole file around.","type":"string"},"full_digest":{"description":"FullDigest is the complete lowercase-hex SHA-256 of the bundle bytes —\nthe ONLY value rollback accepts (FR-010). Fingerprint stays the 12-hex\nhuman label beside it.","type":"string"},"generated_at":{"description":"GeneratedAt is the corpus freshness stamp. It is the bundle's own\n` + "`" + `generated_at` + "`" + ` key when present; for a file-sourced bundle without one it\nfalls back to the file's modification time, so a years-stale corpus is\ndistinguishable from a fresh export.","type":"string"},"last_activated_at":{"description":"LastActivatedAt is when the serving external bundle was activated; nil\nfor the embedded default.","type":"string"},"last_checked_at":{"description":"LastCheckedAt is the end of the most recent pipeline run, including\nno-op runs the idempotence short-circuit skipped.","type":"string"},"last_rejection":{"$ref":"#/components/schemas/scanner.BundleRejection"},"load_error":{"description":"LoadError is the reason the LAST configured-path load failed, if any. The\npreviously active (or embedded) corpus stays live — a bundle problem must\nnever leave the scanner with no signatures — but the failure is surfaced\nhere rather than swallowed.","type":"string"},"loaded_at":{"description":"LoadedAt is when this corpus became active in this process.","type":"string"},"path":{"description":"Path is the configured filesystem path, when Source is \"file\".","type":"string"},"pinned":{"description":"Pinned is true while an operator rollback pin governs activation.","type":"boolean"},"refresh":{"$ref":"#/components/schemas/scanner.BundleRefreshStatus"},"reprotect":{"$ref":"#/components/schemas/scanner.BundleReprotectStatus"},"rollback":{"description":"Rollback is true when the active bundle was activated by an explicit\nrollback.","type":"boolean"},"runnable_rules":{"description":"RunnableRules is how many rules are LIVE in the offline tier; SkippedRules\nand DeclaredSkipped are the not-runnable / bundle-declared-skipped\nremainder (FR-006/FR-007) — un-evaluated coverage, never clean coverage.","type":"integer"},"schema_version":{"type":"string"},"sequence":{"description":"Sequence is the manifest sequence as published (decimal string), \"\" when\nthe bundle carries none.","type":"string"},"signature_count":{"description":"SignatureCount is the bundle's self-declared signature count.","type":"integer"},"signature_verified":{"description":"SignatureVerified reports whether the active bundle's detached signature\nverified. Always false for the embedded default (it is binary-trusted).","type":"boolean"},"skipped_rules":{"type":"integer"},"source":{"description":"Source is BundleSourceEmbedded, BundleSourceFile or BundleSourceFetch.","type":"string"},"stale":{"description":"Stale and StaleAfterDays are computed at read time next to\nStalenessDays; a future generated_at is never stale. StaleAfterDays nil\nmeans the flag is not evaluated.","type":"boolean"},"stale_after_days":{"type":"integer"},"staleness_days":{"description":"StalenessDays is the whole days since GeneratedAt (nil when unknown).","type":"integer"},"trust_epoch":{"description":"TrustEpoch is the epoch the bundle was published under.","type":"integer"}},"type":"object"},"scanner.BundleRefreshStatus":{"description":"Refresh is the refresh-cycle status (nil before any cycle or setting is\nknown). Reprotect is the post-activation re-protection sweep status,\nset from the server through SetReprotectStatus.","properties":{"consecutive_failures":{"type":"integer"},"fetch_enabled":{"type":"boolean"},"fetch_host":{"description":"FetchHost is the host of the configured fetch URL (\"\" when none).","type":"string"},"fetch_reason":{"type":"string"},"fetch_state":{"description":"FetchState and FetchReason are the fetch leg's own last answer (one of the\nRefreshOutcome* values and its reason), kept apart from LastOutcome: a file\nactivation owns the merged cycle outcome but must not hide a fetch leg that\ncannot run (B16 warning 3).","type":"string"},"interval_seconds":{"type":"integer"},"last_attempt_at":{"type":"string"},"last_outcome":{"type":"string"},"last_reason":{"type":"string"},"last_trigger":{"description":"LastTrigger, LastOutcome and LastReason use the closed vocabularies above.","type":"string"},"next_check_at":{"type":"string"}},"type":"object"},"scanner.BundleRejection":{"description":"LastRejection is the most recent refused candidate. It is retained\nacross a later successful load so \"what did it refuse, and when\"\nsurvives.","properties":{"at":{"type":"string"},"detail":{"description":"Detail is a short human string (which ceiling, which key id, which\nepoch, the bundlesig contract code). Never parsed.","type":"string"},"reason":{"description":"Reason is one of the Reject* constants; the only field to branch on.","type":"string"}},"type":"object"},"scanner.BundleReprotectStatus":{"properties":{"last_completed_at":{"type":"string"},"reason":{"description":"Reason qualifies suspended and failed (for example\nReprotectReasonAutoBaselineScanOff).","type":"string"},"servers_scanned":{"type":"integer"},"servers_with_hits":{"type":"integer"},"state":{"description":"State is one of the ReprotectState* constants.","type":"string"}},"type":"object"},"secureenv.EnvConfig":{"description":"Environment configuration for secure variable filtering","properties":{"allowed_system_vars":{"items":{"type":"string"},"type":"array","uniqueItems":false},"custom_vars":{"additionalProperties":{"type":"string"},"type":"object"},"enhance_path":{"description":"Enable PATH enhancement for Launchd scenarios","type":"boolean"},"forward_proxy_env":{"description":"ForwardProxyEnv opts in to forwarding the ambient HTTP(S)/ALL/NO/FTP proxy\nenvironment variables to spawned upstream servers (MCP-2769). It is OFF by\ndefault and deliberately kept out of the AllowedSystemVars default list:\nproxy URLs frequently carry credentials (http://user:pass@proxy), so\nforwarding them to every stdio upstream is a credential-leak risk. When\nenabled, values are forwarded with their userinfo (credentials) redacted.","type":"boolean"},"inherit_system_safe":{"type":"boolean"}},"type":"object"},"storage.ClientCredentialObservation":{"properties":{"at":{"type":"string"},"state":{"type":"string"}},"type":"object"},"storage.OnboardingState":{"description":"State is the persisted wizard engagement record. Engaged is true once\nthe wizard was shown and the user completed or skipped it.","properties":{"client_connected_at":{"additionalProperties":{"type":"string"},"description":"ClientConnectedAt records, per client id from the fixed connect client\nregistry (internal/connect.GetAllClients — never user input), the last\ntime a connect write succeeded for that client (Spec 109-b FR-042).\nWritten by the connect success path through UpdateOnboardingState so a\nconcurrent onboarding/mark write can never drop it. Consumed by the\nVerify step / presence layer to tell \"connected, never seen\" apart from\n\"connected seconds ago, hasn't reconnected yet\".","type":"object"},"client_credential_observed":{"additionalProperties":{"$ref":"#/components/schemas/storage.ClientCredentialObservation"},"description":"ClientCredentialObserved records, per client id, the LAST credential\nclassification an on-demand read produced (Spec 108-f FR-025, F11): what\nthe client's config held (client | admin_key | none | revoked | expired)\nand when it was read. The stat-only GET /clients listing never reads a\nconfig (Spec 075: no macOS App-Data prompt from a list), so this is how\nit still reports a client that holds the admin key across restarts. It is\nwritten only when the classification CHANGES, by every on-demand read\n(GET /clients/{id}, GET /connect/{client}, the admin-key upgrade preview,\na connect write) and deleted on disconnect. Additive: an older binary\nignores it, and a record without it reads as \"unknown\".","type":"object"},"client_disconnected_at":{"additionalProperties":{"type":"string"},"type":"object"},"client_last_seen":{"additionalProperties":{"type":"string"},"description":"ClientLastSeen records the latest MCP initialize for a recognised client\nalias. It is intentionally kept with onboarding state: presence is a\nlocal UI concern and must still work when telemetry is disabled.","type":"object"},"connect_step_status":{"description":"ConnectStepStatus is one of: \"\", \"completed\", \"completed_external\",\n\"skipped\" (Spec 080 FR-001). \"completed_external\" records a dismissal\nwhere the connect step was untouched but the install was already\nconnected outside the wizard (CLI, ConnectModal, manual config).","type":"string"},"engaged":{"description":"Engaged is true once the wizard was shown and the user completed or\nskipped it. Once true, the wizard does not auto-show again, even if\nstate regresses (e.g. user disconnects all clients).","type":"boolean"},"engaged_at":{"description":"EngagedAt is the timestamp of completion or explicit skip.","type":"string"},"first_shown_at":{"description":"FirstShownAt is the timestamp of first wizard render.","type":"string"},"server_step_status":{"description":"ServerStepStatus is one of: \"\", \"completed\", \"skipped\".","type":"string"}},"type":"object"},"telemetry.DiagnosticsCounters":{"properties":{"current_error_codes":{"additionalProperties":{"type":"integer"},"description":"CurrentErrorCodes is the STANDING state at heartbeat time: stable MCPX_\ncode -\u003e number of configured servers currently in that state. It is not\na counter and is never persisted — it is recomputed each heartbeat from\nthe supervisor's live stateview.\n\nSchema v11 (MCP-2967). It exists because error_code_counts_24h became\nedge-triggered in the same change: previously the supervisor re-counted\nevery standing failure on its 30s reconcile ticker, so a parked install\ninflated the counter by ~2880/day/server. Edge-triggering alone would\nhave swung the error to the other side — the 24h window decays, this\nstruct is omitempty via isZero(), so a permanently broken install would\nemit once and then disappear from the payload entirely, and absent reads\nas zero. The two fields answer different questions and are only correct\ntogether: \"how often did something newly break\" and \"how many servers\nare broken right now\".\n\nSafe: only MCPX_* enum constants as keys, never server names, URLs,\ncommands, or free text; values are non-negative server counts.","type":"object"},"error_code_counts_24h":{"additionalProperties":{"type":"integer"},"description":"ErrorCodeCounts24h maps stable MCPX_ code strings to 24h occurrence counts.\nSafe: only MCPX_* enum constants are stored here, never free text, paths,\nserver names, or user-entered values.","type":"object"},"fix_attempted_24h":{"description":"FixAttempted24h counts POST /api/v1/diagnostics/fix calls in the last 24h.","type":"integer"},"fix_succeeded_24h":{"description":"FixSucceeded24h counts fix invocations with outcome=\"success\" in the last 24h.","type":"integer"},"unique_codes_ever":{"description":"UniqueCodesEver is the cardinality of the all-time error code set.\nBounded by the MCPX_ catalog size (~30 codes), never approaches PII risk.","type":"integer"}},"type":"object"},"telemetry.FeedbackContext":{"properties":{"anonymous_id":{"description":"AnonymousID is the install's telemetry anonymous ID (heartbeat value).","type":"string"},"arch":{"type":"string"},"connected_server_count":{"type":"integer"},"diagnostics":{"$ref":"#/components/schemas/telemetry.DiagnosticsCounters"},"edition":{"type":"string"},"go_version":{"type":"string"},"last_error_code":{"description":"LastErrorCode is the most recent MCPX_* error code.","type":"string"},"last_startup_outcome":{"description":"LastStartupOutcome is the previous startup's outcome word.","type":"string"},"machine_id":{"description":"MachineID is the hashed machine identifier (heartbeat value).","type":"string"},"os":{"type":"string"},"previous_shutdown":{"description":"PreviousShutdown is how the previous run ended (clean, crash, ...).","type":"string"},"routing_mode":{"type":"string"},"server_count":{"type":"integer"},"tool_count":{"type":"integer"},"uptime_minutes":{"description":"UptimeMinutes is the daemon's uptime. Omitted from short-lived CLI\nsubmissions, where the process uptime says nothing about the daemon.","type":"integer"},"version":{"type":"string"}},"type":"object"},"telemetry.FeedbackRequest":{"properties":{"category":{"description":"bug, feature, other","type":"string"},"context":{"$ref":"#/components/schemas/telemetry.FeedbackContext"},"email":{"type":"string"},"message":{"type":"string"}},"type":"object"},"telemetry.FeedbackResponse":{"properties":{"error":{"type":"string"},"issue_url":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}},"securitySchemes":{"ApiKeyAuth":{"description":"API key authentication via query parameter. Use ?apikey=your-key","in":"query","name":"apikey","type":"apiKey"}}}, "info": {"contact":{"name":"MCPProxy Support","url":"https://github.com/smart-mcp-proxy/mcpproxy-go"},"description":"{{escape .Description}}","license":{"name":"MIT","url":"https://opensource.org/licenses/MIT"},"title":"{{.Title}}","version":"{{.Version}}"}, "externalDocs": {"description":"","url":""}, "paths": {"/api/v1/access/explain":{"get":{"description":"For one subject (exactly one of client=\u003cid\u003e, token=\u003cname\u003e, profile=\u003cname\u003e or anonymous=true) and one upstream tool (server:tool), returns the ordered chain of gates a real call would meet - credential, profile, server_in_scope, tool_rule, tier_cap, token_permission, global_gate, server_state, tool_approval - the overall verdict (allowed, blocked, hidden), the first failing step and the fixes for it in preference order. The chain is the one every discovery and dispatch path walks, so ` + "`" + `allowed` + "`" + ` equals what a real call does. Built-in management tools are not explained (400). A client credential is explained with client=, never token=. Administrators only.","parameters":[{"description":"Upstream tool as server:tool","in":"query","name":"tool","required":true,"schema":{"type":"string"}},{"description":"Client id","in":"query","name":"client","schema":{"type":"string"}},{"description":"Regular agent token name","in":"query","name":"token","schema":{"type":"string"}},{"description":"Profile name","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Explain an anonymous (credential-less) caller","in":"query","name":"anonymous","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The explanation"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Not exactly one subject, a built-in tool, or token=client-\u003cid\u003e"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"client / token / profile not found"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Explain why a tool is or is not reachable","tags":["access"]}},"/api/v1/access/suggest":{"get":{"description":"Reads the profile refusals in the activity log over a look-back window and groups them by profile, tool and block reason. Each group is re-checked with the access explainer, so tools that are already reachable drop out, and carries the explainer's fixes. A deny-rule block is reported and never offered for widening; an unannotated tool is never given a tier. Nothing is applied. patch=true also returns the proposed profile document per profile (the body PUT /api/v1/profiles/{name} takes).","parameters":[{"description":"Look-back window: a duration such as 90m, 24h or 7d (default 24h; the audit-log retention is the only limit)","in":"query","name":"since","schema":{"type":"string"}},{"description":"Only refusals under this profile","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Only refusals of this token","in":"query","name":"token","schema":{"type":"string"}},{"description":"Also return the proposed profile document per profile","in":"query","name":"patch","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The suggestions"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid since"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Suggest profile changes from blocked calls","tags":["access"]}},"/api/v1/activity":{"get":{"description":"Returns paginated list of activity records with optional filtering","parameters":[{"description":"Filter by activity type(s), comma-separated for multiple (Spec 024)","in":"query","name":"type","schema":{"enum":["tool_call","policy_decision","quarantine_change","server_change","system_start","system_stop","internal_tool_call","config_change","preflight","prompt_get","profile_change","upstream_event"],"type":"string"}},{"description":"Filter by server name","in":"query","name":"server","schema":{"type":"string"}},{"description":"Filter by tool name","in":"query","name":"tool","schema":{"type":"string"}},{"description":"Filter by MCP transport session ID","in":"query","name":"session_id","schema":{"type":"string"}},{"description":"Filter by work session (one client, one project, across reconnects)","in":"query","name":"work_session_id","schema":{"type":"string"}},{"description":"Filter by status","in":"query","name":"status","schema":{"enum":["success","error","blocked","rejected"],"type":"string"}},{"description":"Filter by intent operation type (Spec 018)","in":"query","name":"intent_type","schema":{"enum":["read","write","destructive"],"type":"string"}},{"description":"Filter by HTTP request ID for log correlation (Spec 021)","in":"query","name":"request_id","schema":{"type":"string"}},{"description":"Filter by parent call id — returns the sub-calls one code_execution issued","in":"query","name":"parent_id","schema":{"type":"string"}},{"description":"Filter by call-error class (Spec 113-c)","in":"query","name":"error_class","schema":{"enum":["network","timeout","http","jsonrpc","tool_error","session_terminated","auth","proxy_policy","proxy_internal","cancelled"],"type":"string"}},{"description":"Filter by fault domain (Spec 113-c)","in":"query","name":"fault_domain","schema":{"enum":["upstream","proxy","client"],"type":"string"}},{"description":"Include successful call_tool_* internal tool calls (default: false, excluded to avoid duplicates)","in":"query","name":"include_call_tool","schema":{"type":"boolean"}},{"description":"Filter by sensitive data detection (true=has detections, false=no detections)","in":"query","name":"sensitive_data","schema":{"type":"boolean"}},{"description":"Filter by specific detection type (e.g., 'aws_access_key', 'credit_card')","in":"query","name":"detection_type","schema":{"type":"string"}},{"description":"Filter by severity level","in":"query","name":"severity","schema":{"enum":["critical","high","medium","low"],"type":"string"}},{"description":"Alias of token (Spec 028)","in":"query","name":"agent","schema":{"type":"string"}},{"description":"Filter by the token in effect for the call; - selects records with no token (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Filter by the profile in effect for the call; - selects records with no profile (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Filter by client id; - selects records with no client (Spec 108)","in":"query","name":"client","schema":{"type":"string"}},{"description":"Filter by the client's self-reported name (advisory; Spec 108)","in":"query","name":"client_name","schema":{"type":"string"}},{"description":"Filter by auth type (Spec 028)","in":"query","name":"auth_type","schema":{"enum":["admin","agent"],"type":"string"}},{"description":"Filter activities after this time (RFC3339)","in":"query","name":"start_time","schema":{"type":"string"}},{"description":"Filter activities before this time (RFC3339)","in":"query","name":"end_time","schema":{"type":"string"}},{"description":"Maximum records to return (1-100, default 50)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Pagination offset (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Omit arguments, response and metadata except a contextual whitelist (intent.reason, intent.operation_type, decision, reason, client_name, client_version) (default: false). For clients that render summary fields only; has_sensitive_data is still derived before metadata is dropped.","in":"query","name":"exclude_payloads","schema":{"type":"boolean"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"List activity records","tags":["Activity"]}},"/api/v1/activity/export":{"get":{"description":"Exports activity records in JSON Lines or CSV format for compliance","parameters":[{"description":"Export format: json (default) or csv","in":"query","name":"format","schema":{"type":"string"}},{"description":"Filter by activity type","in":"query","name":"type","schema":{"type":"string"}},{"description":"Filter by server name","in":"query","name":"server","schema":{"type":"string"}},{"description":"Filter by tool name","in":"query","name":"tool","schema":{"type":"string"}},{"description":"Filter by MCP transport session ID","in":"query","name":"session_id","schema":{"type":"string"}},{"description":"Filter by work session (one client, one project, across reconnects)","in":"query","name":"work_session_id","schema":{"type":"string"}},{"description":"Filter by status","in":"query","name":"status","schema":{"type":"string"}},{"description":"Filter by HTTP request ID for log correlation (Spec 021)","in":"query","name":"request_id","schema":{"type":"string"}},{"description":"Filter by parent call id — exports the sub-calls one code_execution issued","in":"query","name":"parent_id","schema":{"type":"string"}},{"description":"Filter by call-error class (Spec 113-c)","in":"query","name":"error_class","schema":{"enum":["network","timeout","http","jsonrpc","tool_error","session_terminated","auth","proxy_policy","proxy_internal","cancelled"],"type":"string"}},{"description":"Filter by fault domain (Spec 113-c)","in":"query","name":"fault_domain","schema":{"enum":["upstream","proxy","client"],"type":"string"}},{"description":"Alias of token (Spec 028)","in":"query","name":"agent","schema":{"type":"string"}},{"description":"Filter by the token in effect for the call; - selects records with no token (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Filter by the profile in effect for the call; - selects records with no profile (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Filter by client id; - selects records with no client (Spec 108)","in":"query","name":"client","schema":{"type":"string"}},{"description":"Filter by the client's self-reported name (advisory; Spec 108)","in":"query","name":"client_name","schema":{"type":"string"}},{"description":"Filter activities after this time (RFC3339)","in":"query","name":"start_time","schema":{"type":"string"}},{"description":"Filter activities before this time (RFC3339)","in":"query","name":"end_time","schema":{"type":"string"}},{"description":"Maximum records to export (1-50000, default 10000)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Pagination offset (default 0)","in":"query","name":"offset","schema":{"type":"integer"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"type":"string"}},"application/x-ndjson":{"schema":{"type":"string"}},"text/csv":{"schema":{"type":"string"}}},"description":"Streamed activity records"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Export activity records","tags":["Activity"]}},"/api/v1/activity/summary":{"get":{"description":"Returns aggregated activity statistics for a time period","parameters":[{"description":"Time period: 1h, 24h (default), 7d, 30d","in":"query","name":"period","schema":{"type":"string"}},{"description":"Group by: server, tool (optional)","in":"query","name":"group_by","schema":{"type":"string"}},{"description":"Alias of token (Spec 028)","in":"query","name":"agent","schema":{"type":"string"}},{"description":"Count only records made under this token; - selects records with no token (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Count only records made under this profile; - selects records with no profile (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Count only records made by this client id; - selects records with no client (Spec 108)","in":"query","name":"client","schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Get activity summary statistics","tags":["Activity"]}},"/api/v1/activity/usage":{"get":{"description":"Returns the actor-owned usage aggregate (per-tool rollup + timeline + tokens-saved headline) for the Web UI usage graphs (Spec 069). Served from an in-memory snapshot — never a per-request full-log scan. Per-tool metrics are lifetime-cumulative; ` + "`" + `window` + "`" + ` scopes the timeline and filters the tool list to tools active within the span.","parameters":[{"description":"Time window for timeline + tool-list membership","in":"query","name":"window","schema":{"enum":["24h","7d","all"],"type":"string"}},{"description":"Filter to one server","in":"query","name":"server","schema":{"type":"string"}},{"description":"Filter to one tool","in":"query","name":"tool","schema":{"type":"string"}},{"description":"Filter to tools with activity of this status","in":"query","name":"status","schema":{"enum":["success","error","blocked","rejected"],"type":"string"}},{"description":"Top-N tools by sort key; remainder folded into 'other' (default 20)","in":"query","name":"top","schema":{"type":"integer"}},{"description":"Ranking key for the per-tool list","in":"query","name":"sort","schema":{"enum":["calls","resp_bytes","error_rate","p95"],"type":"string"}},{"description":"Alias of token (Spec 028)","in":"query","name":"agent","schema":{"type":"string"}},{"description":"Restrict to calls made under this token; - selects records with no token. Computed from a window-bounded scan (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Restrict to calls made under this profile; - selects records with no profile. Computed from a window-bounded scan (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Restrict to calls made by this client id; - selects records with no client. Computed from a window-bounded scan (Spec 108)","in":"query","name":"client","schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Get usage statistics aggregate","tags":["Activity"]}},"/api/v1/activity/{id}":{"get":{"description":"Returns full details for a single activity record","parameters":[{"description":"Activity record ID (ULID)","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Not Found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Get activity record details","tags":["Activity"]}},"/api/v1/annotations/coverage":{"get":{"description":"Reports how many upstream tools have MCP annotations vs don't, broken down by server","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Annotation coverage report"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get annotation coverage report","tags":["annotations"]}},"/api/v1/attention":{"get":{"description":"One list, one count, every surface (Web UI, macOS tray/Home, CLI) reads from it. Filtered per caller: an administrator sees every item; a scoped caller (agent token, or a non-admin server-edition OAuth user session) sees only server items whose server it may enumerate (for a profile-pinned token: servers within its pin); every other subject type (client, setting) and the skill_review kind (Spec 125 held skills) are administrator-only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.attentionResponse"}}},"description":"The needs-attention list"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the needs-attention list","tags":["attention"]}},"/api/v1/catalog/search":{"get":{"description":"Fans out to every enabled catalog source (registry) in parallel, merges, de-duplicates and ranks the results (FR-060/061). An empty q returns official + popular sections instead of a flat list. Open to any authenticated caller — added is the only field filtered per caller scope (FR-007).","parameters":[{"description":"Free-text search","in":"query","name":"q","schema":{"type":"string"}},{"description":"Narrow to one catalog source id","in":"query","name":"source","schema":{"type":"string"}},{"description":"Not supported: catalog entries carry no tags; a non-empty value returns 400","in":"query","name":"tag","schema":{"type":"string"}},{"description":"Max results (default 20, max 50)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"tag filtering is not supported"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"configured servers could not be listed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Search the server catalog across every enabled source","tags":["catalog"]}},"/api/v1/clients":{"get":{"description":"Lists every client row (supported, other and custom) with its presence, its credential and its profile binding, plus response-level warnings. The list is content-read-free (Spec 075): credential_state comes from the token store, else the last on-demand observation (credential_checked_at), else unknown. It runs only the time-based half of the rotation reconciler. The profile and client filters match the CURRENT binding and are applied AFTER warnings are computed over the full set.","parameters":[{"description":"Rows whose active credential is bound to this profile; - = bound to All servers","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Exact client id","in":"query","name":"client","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Client rows, routing and warnings"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List clients","tags":["clients"]},"post":{"description":"Creates a per-client credential for a client that is NOT in the connect registry (a script, a CI job, an editor without a connect adapter). The secret (mcp_cli_...) is returned ONCE, with a paste-ready snippet that carries it in the X-API-Key header. The id follows the client-id rule (lower-case letters, digits, '-' or '_', at most 56 characters) and must not be a supported client's id. A named profile binds the credential locked unless mode says otherwise. Refused with 409 binding_bypassable_without_auth when the binding would be bypassable while require_mcp_auth is off (FR-008a), and 409 conflicting_token when a regular token holds client-\u003cid\u003e. Every value (id, display_name, profile, mode, expires_in, purpose) passes the shared secret-shaped input screen first: a credential, the API key or a detector-flagged secret answers 400 secret_in_argument naming the field, and nothing is minted. A malformed body answers a sanitized 400 that never echoes a caller key or value. Writes one profile_change record with change issue (Spec 115) and publishes credentials.changed. Personal edition only.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.CreateClientRequest"}}},"description":"id (required), optional display_name, profile, mode, expires_in and purpose","required":true},"responses":{"201":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The new client row, its credential (once) and a snippet"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"binding_bypassable_without_auth, or conflicting_token (ClientCredentialConflictResponse)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add a custom client","tags":["clients"]}},"/api/v1/clients/bulk-assign":{"post":{"description":"Moves every client credential bound to from_profile (\"\" = All servers) onto to_profile (\"\" = All servers). The guard and the credential precondition apply PER CLIENT: a refused client is reported in skipped[] with the code the single operation returns, the others move and each writes its own assign record and emits client.binding_changed. Personal edition only.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BulkAssignRequest"}}},"description":"from_profile and to_profile (both required; empty = All servers) and optional mode","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Moved client ids and the clients that were skipped"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Move every client of one profile to another","tags":["clients"]}},"/api/v1/clients/upgrade-admin-key-holders":{"post":{"description":"Without apply: classifies every supported client whose config still holds the instance admin API key (an on-demand read per client) and returns preview[] (display path, what would change, the masked credential mcp_cli_••••, the binding and a precondition_token per client), a combined precondition_token, and guard when the whole request would be refused by FR-008a; next_step is rotate_admin_api_key when nothing holds the key. Nothing is written or minted. With apply=true: recomputes the preview, refuses with 409 precondition_failed when a sent precondition_token no longer matches, runs the FR-008a guard over the WHOLE request (409 binding_bypassable_without_auth, nothing minted, no file written), then connects each client with force bound to its own token; one client's failure does not stop the others. Each mint writes its own assign record. The guard only applies when a named profile is given. Personal edition only.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.UpgradeAdminKeyHoldersRequest"}}},"description":"Optional profile and mode for every upgraded client; apply and precondition_token"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"UpgradePreview (no apply) or UpgradeResult (apply)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"precondition_failed, or binding_bypassable_without_auth"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Upgrade every client that holds the admin API key","tags":["clients"]}},"/api/v1/clients/{client}":{"delete":{"description":"Revokes the client's credential; it stops authenticating at once. With disconnect=true a SUPPORTED client's mcpproxy entry is removed from its config FIRST, but the credential is revoked either way: revocation never waits for a config write, so a failed write (for example a macOS App-Data denial) leaves the client cut off and is reported as disconnected:false with disconnect_error. A client with no credential record is 409 no_client_credential. disconnect=true on a custom client is ignored. Writes one forget record naming the revoked token. The FR-008a guard is not involved: revoking only removes a binding.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}},{"description":"Also remove the entry from the client's config (supported clients)","in":"query","name":"disconnect","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Revoked token name and what happened to the config entry"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"no_client_credential"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Forget a client (revoke its credential)","tags":["clients"]},"get":{"description":"Returns one client row with its sessions (newest 20, each with its latest effective profile). This is the only read that may open the client's config file: it runs the full rotation reconciler first, classifies the credential the config holds and records the observation. No scope filter is honoured on this route.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Client row"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"client not found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get one client","tags":["clients"]}},"/api/v1/clients/{client}/binding":{"put":{"description":"Changes the profile binding (and optionally the locked/switchable mode) of a\nclient that holds an active client credential. One service operation shared by\nevery surface: it updates the credential in the token store, clears the stored\nset_profile selection of every live session of that credential, sends\nnotifications/tools/list_changed to each, emits client.binding_changed and writes\none profile_change activity record. It never touches the client's config file.\nA client without an active client credential (none, admin key, revoked or expired)\nis refused with 409 no_client_credential and nothing is minted or written. A\nreassignment that would leave the binding bypassable while require_mcp_auth is off\nis refused with 409 binding_bypassable_without_auth (FR-008a). Personal edition only.","parameters":[{"description":"Client id (lower-case letters, digits, '-' or '_', at most 56 characters)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.PutClientBindingRequest"}}},"description":"profile (required; empty = All servers) and optional mode (locked|switchable)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The client row after the change, with its warnings"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"no_client_credential, connect_in_progress (a connect of this client is mid-write), or binding_bypassable_without_auth with bindings and fixes"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Reassign a client's profile and/or mode","tags":["clients"]}},"/api/v1/clients/{client}/rotate":{"post":{"description":"Replaces a client's secret without ever invalidating the old one mid-flight (FR-021a). A SUPPORTED client is rewritten through connect: staged rotation, binding kept, finalized when the config write succeeds, rolled back (the old secret keeps working) when it fails; a preview's precondition_token binds the call, a mismatch is the connect 409 precondition_failed. A CUSTOM client gets a new secret returned ONCE with a snippet; both secrets authenticate until POST /clients/{client}/rotate/finalize or 24 hours. A client with no active credential is 409 no_client_credential. The FR-008a guard is not involved: a rotation never changes a binding's reach. Writes one rotate record when it finalizes.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.RotateClientRequest"}}},"description":"Optional precondition_token of a connect preview"},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The client row and the rotation state"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required (or macOS App-Data block)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectConflictResponse"}}},"description":"no_client_credential, precondition_failed, connect_in_progress (another connect of this client is mid-write), or credential_superseded (the written credential was replaced or revoked before it could be finalized; reconnect)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Rotate a client's credential","tags":["clients"]}},"/api/v1/clients/{client}/rotate/finalize":{"post":{"description":"Promotes a client's pending secret: the old secret stops authenticating. Idempotent: with no rotation in progress it is a no-op success. A client with no client credential is 409 no_client_credential. Writes one rotate record when it promotes.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The client row; rotation.state is finalized"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"no_client_credential, or connect_in_progress (a connect of this client is mid-write)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Finalize a staged rotation","tags":["clients"]}},"/api/v1/code/scripts":{"get":{"description":"List the stored scripts available to the code_execution tool. Scripts are ` + "`" + `\u003cname\u003e.js` + "`" + ` / ` + "`" + `\u003cname\u003e.ts` + "`" + ` files in the ` + "`" + `scripts/` + "`" + ` directory next to the active configuration file. Entries are advisory: ` + "`" + `ok` + "`" + ` scripts are invocable, ` + "`" + `ambiguous` + "`" + ` names have both extensions, and ` + "`" + `invalid` + "`" + ` ones report why (empty, oversized, unreadable, non-regular). Read-only — there is no write surface for stored scripts. Administrator-only (Spec 105 FR-012): an agent token, whatever its server scope, is refused with 403 — the listing is the enumeration the missing-script error withholds from a scoped caller.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Stored scripts and the directory they were read from"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot list stored scripts"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List stored code-execution scripts","tags":["code"]}},"/api/v1/config":{"get":{"description":"Retrieves the current MCPProxy configuration including all server definitions, global settings, and runtime parameters","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetConfigResponse"}}},"description":"Configuration retrieved successfully"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read the configuration document"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get current configuration","tags":["config"]},"patch":{"description":"Deep-merges only the fields present in the request body onto the live in-memory configuration and routes the result through the existing apply pipeline (validation, change detection, disk persistence, hot-reload). Fields the client omits — including masked secrets such as ` + "`" + `api_key` + "`" + ` and secret request headers — are preserved verbatim. Nested objects are merged recursively; arrays and scalars replace wholesale.","requestBody":{"content":{"application/json":{"schema":{"type":"object"}}},"description":"Partial configuration with only the fields to change","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ConfigApplyResult"}}},"description":"Configuration patch applied (inspect validation_errors for rejected values)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload or empty patch"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate configuration)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"binding_bypassable_without_auth: the patch would let a client bound to a named profile escape it while require_mcp_auth is off (FR-008a); nothing was written"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"telemetry.enabled is locked while an environment variable (DO_NOT_TRACK, CI, MCPPROXY_TELEMETRY=false) disables telemetry; nothing was written (FR-044a)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to read or apply configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Partially update configuration","tags":["config"]}},"/api/v1/config/apply":{"post":{"description":"Applies a new MCPProxy configuration. Validates and persists the configuration to disk. Some changes apply immediately, while others may require a restart. Returns detailed information about applied changes and restart requirements.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.Config"}}},"description":"Configuration to apply","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ConfigApplyResult"}}},"description":"Configuration applied successfully with change details"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate configuration)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"binding_bypassable_without_auth: the write would let a client bound to a named profile escape it while require_mcp_auth is off (FR-008a); nothing was written"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"telemetry.enabled is locked while an environment variable (DO_NOT_TRACK, CI, MCPPROXY_TELEMETRY=false) disables telemetry; nothing was written (FR-044a)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to apply configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Apply configuration","tags":["config"]}},"/api/v1/config/docker-isolation":{"patch":{"description":"Convenience endpoint to flip ` + "`" + `docker_isolation.enabled` + "`" + ` without resending the full config. Persists to disk via the existing config writer — the file watcher then hot-reloads the change. Returns the new state and whether a restart is required for existing connections to pick it up.","requestBody":{"content":{"application/json":{"schema":{"properties":{"enabled":{"type":"boolean"}},"type":"object"}}},"description":"New isolation state","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ConfigApplyResult"}}},"description":"Isolation toggle applied"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate configuration)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"binding_bypassable_without_auth (FR-008a); nothing was written"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to apply configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Toggle global Docker isolation","tags":["config"]}},"/api/v1/config/validate":{"post":{"description":"Validates a provided MCPProxy configuration without applying it. Checks for syntax errors, invalid server definitions, conflicting settings, and other configuration issues.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.Config"}}},"description":"Configuration to validate","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ValidateConfigResponse"}}},"description":"Configuration validation result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Validation failed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Validate configuration","tags":["config"]}},"/api/v1/connect":{"get":{"description":"Returns the connection status for all known MCP client applications.\nEach entry indicates whether the client config file exists and whether\nMCPProxy is currently registered in it. This stat-only listing never reads\na client config (Spec 075), so a client whose config exists reports\ncredential_state \"unknown\"; GET /connect/{client} resolves it.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"List of ClientStatus objects"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List client connection status","tags":["connect"]}},"/api/v1/connect/{client}":{"delete":{"description":"Remove the MCPProxy entry from the specified client's configuration file.\nCreates a backup of the existing config before modifying.\nAlso revokes the client's credential (it stops authenticating at once); the result names it in credential_revoked, or reports credential_revoke_error when the revoke failed after the entry was removed. Undoing a disconnect does not restore the credential: a later connect mints a new one.","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectRequest"}}},"description":"Optional parameters (server_name)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectResult"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Permission denied (macOS App-Data block)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client or entry not found"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Disconnect MCPProxy from a client","tags":["connect"]},"get":{"description":"Resolves one client's status by reading its config file on demand.\nThis is the only Connect endpoint that opens a client config file, so\non macOS it is the sole place an App-Data privacy prompt may legitimately\nappear (scoped to this user action). Resolves access_state to\naccessible|absent|denied|malformed and populates remediation when denied.\nFor a connected client it also resolves credential_state (Spec 108 FR-025):\nclient (an active per-client credential), admin_key (the instance admin API\nkey), none, revoked (a rotated-away or revoked credential) or expired. The\ncredential value is classified and never echoed.","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ClientStatus"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get a single client's connection status (on-demand)","tags":["connect"]},"post":{"description":"Register MCPProxy as an MCP server in the specified client's configuration file.\nCreates a backup of the existing config before modifying.\nOptionally accepts precondition_token from a preview (Spec 091): when supplied,\nthe core rechecks the raw pre-write state and the entry it would write, and\nrefuses a drifted write with 409 before taking any backup. The 409 body's\naction discriminates the two conflict kinds: \"precondition_failed\" (stale\npreview — re-preview, do not retry) vs \"already_exists\" (entry present — pass\nforce=true). force=true never rescues a stale token.\n\nSpec 108 FR-024: the entry carries a per-client mcp_cli_ credential bound to the\nrequested profile (default: All servers, switchable; a reconnect keeps the client's\nexisting binding unless a profile is given), never the instance admin API key.\nReconnecting over an active credential is a staged rotation: the old secret keeps\nworking until the config write succeeds. keyless=true writes no credential and is\nonly possible while require_mcp_auth is off (400 otherwise, and with a profile).\nA write that would let the client escape its profile by omitting its credential\nwhile require_mcp_auth is off is refused with 409 binding_bypassable_without_auth\n(nothing minted or written); a token named client-\u003cid\u003e held by a regular agent\ntoken is refused with 409 conflicting_token.","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectRequest"}}},"description":"Optional connection parameters (server_name, force, precondition_token, profile, mode, keyless)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectResult (credential is the masked mcp_cli_ value, with token_name, profile, mode, keyless and rotation)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Bad request; field names the offending input (profile, mode, keyless)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Permission denied (macOS App-Data block)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectConflictResponse"}}},"description":"Conflict: action=already_exists (use force=true) or action=precondition_failed (preview is stale; re-preview); or binding_bypassable_without_auth (BindingGuardResponse); or conflicting_token (ClientCredentialConflictResponse); or connect_in_progress (another connect of this client is mid-write) or credential_superseded (the written credential was replaced or revoked before it could be finalized; reconnect)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable (or no credential store wired while require_mcp_auth is on)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Connect MCPProxy to a client","tags":["connect"]}},"/api/v1/connect/{client}/preview":{"get":{"description":"Returns the exact entry a subsequent connect would add to the client's\nconfig — target path, server key, entry name, and entry contents — WITHOUT\nmodifying the file or creating a backup (Spec 078 US1). The per-client credential\nis masked in the payload (credential, always starting mcp_cli_; contains_api_key is\nalways false since connect never writes the admin API key); profile, mode and\nkeyless echo the requested intent.\nentry_exists distinguishes a create from an overwrite of a same-named entry.\nReads the config on demand to classify create-vs-overwrite, so on macOS this\nmay raise an App-Data privacy prompt; a denial returns 403 + remediation.\nSpec 091 adds three fields: existing_entry_summary (present only when\nentry_exists — a sanitized, non-secret projection of the entry being replaced:\nits name, type, endpoint with query/userinfo stripped, command, and header and\nenv NAMES, never values); precondition_token (always present — an opaque keyed\ndigest of the raw pre-write state and the pending entry, echoed back on POST\nconnect to detect drift); and connect_refusal (present when the write would\nrefuse regardless of intent, e.g. a non-create-capable client with no config —\ntreat its presence as \"Connect unavailable\").","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}},{"description":"Entry name to preview (defaults to mcpproxy); mirror the value passed to POST connect","in":"query","name":"server_name","schema":{"type":"string"}},{"description":"Profile the client credential would bind to (empty = All servers); mirror POST connect","in":"query","name":"profile","schema":{"type":"string"}},{"description":"locked|switchable; mirror POST connect","in":"query","name":"mode","schema":{"enum":["locked","switchable"],"type":"string"}},{"description":"Preview a credential-less entry (only while require_mcp_auth is off)","in":"query","name":"keyless","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectPreview"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid intent (field names the input; keyless with auth on or with a profile)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required or access denied by macOS App Data"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Preview the change a connect would make (no write)","tags":["connect"]}},"/api/v1/connect/{client}/undo":{"post":{"description":"Reverts the connect that produced the named backup (Spec 078 US3):\nrestores the client config byte-for-byte from that backup, or — when\nbackup_name is empty because the connect created the file — deletes the\ncreated file. backup_name is the bare filename of the backup the connect\nreturned (never a path); undo resolves the full path server-side inside\nthe client's own config directory, so a client value cannot escape it.\nRefuses with 409 when the config changed since the connect (undo never\nclobbers later edits; use DELETE /connect/{client} for a surgical entry\nremoval instead). Takes its own safety backup first; its path is returned\nas backup_path in the result. Undo is \"as if the connect never happened\": a\nclient credential the connect minted or rotated is revoked unless the restored\nconfig still holds it, and the result names it in credential_revoked.","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.UndoConnectRequest"}}},"description":"Undo parameters (server_name, backup_name = the bare filename of the backup the preceding connect returned)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectResult (action restored|deleted)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (e.g. backup_name is a path, or not a backup of this client's config)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Permission denied (macOS App-Data block)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client or backup no longer exists"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Config changed since connect; undo refused"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Undo a connect, restoring the pre-connect config","tags":["connect"]}},"/api/v1/diagnostics":{"get":{"description":"Get comprehensive health diagnostics including upstream errors, OAuth requirements, missing secrets, and Docker status","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.Diagnostics"}}},"description":"Health diagnostics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get health diagnostics","tags":["diagnostics"]}},"/api/v1/docker/status":{"get":{"description":"Retrieve current Docker availability and recovery status","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Docker status information"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get Docker status","tags":["docker"]}},"/api/v1/doctor":{"get":{"description":"Get comprehensive health diagnostics including upstream errors, OAuth requirements, missing secrets, and Docker status","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.Diagnostics"}}},"description":"Health diagnostics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get health diagnostics","tags":["diagnostics"]}},"/api/v1/feedback":{"post":{"description":"Submit a bug report, feature request, or general feedback","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/telemetry.FeedbackRequest"}}},"description":"Feedback request","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/telemetry.FeedbackResponse"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"additionalProperties":{"type":"string"},"type":"object"}}},"description":"Bad Request"},"429":{"content":{"application/json":{"schema":{"additionalProperties":{"type":"string"},"type":"object"}}},"description":"Too Many Requests"},"500":{"content":{"application/json":{"schema":{"additionalProperties":{"type":"string"},"type":"object"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyAuth":[]}],"summary":"Submit feedback","tags":["feedback"]}},"/api/v1/index/search":{"get":{"description":"Search across all upstream MCP server tools using BM25 keyword search","parameters":[{"description":"Search query","in":"query","name":"q","required":true,"schema":{"type":"string"}},{"description":"Maximum number of results","in":"query","name":"limit","schema":{"default":10,"maximum":100,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SearchToolsResponse"}}},"description":"Search results"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing query parameter)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Search for tools","tags":["tools"]}},"/api/v1/info":{"get":{"description":"Get essential server metadata including version, web UI URL, endpoint addresses, and update availability\nweb_ui_url carries the ?apikey= credential ONLY for an authenticated admin; a scoped agent token receives the bare URL\nThis endpoint is designed for tray-core communication and version checking\nUse refresh=true query parameter to force an immediate update check against GitHub\nThe launched_by field reports durable launch provenance (\"tray\", \"installer\", or \"\" for user-launched/unknown)","parameters":[{"description":"Force immediate update check against GitHub","in":"query","name":"refresh","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Server information with optional update info"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server information","tags":["status"]}},"/api/v1/onboarding/mark":{"post":{"description":"Updates wizard engagement and per-step status. Once engaged is\ntrue, the wizard does not auto-show again, even if state regresses.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.OnboardingMarkRequest"}}},"description":"Mark request","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Updated OnboardingStateResponse"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read onboarding state"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Mark onboarding wizard state (Spec 046)","tags":["onboarding"]}},"/api/v1/onboarding/state":{"get":{"description":"Returns the wizard engagement record alongside live predicates\n(whether any client is connected, whether any server is configured),\nplus a derived ShouldShowWizard flag the frontend can rely on.","responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OnboardingStateResponse"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read onboarding state"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get onboarding wizard state and predicates (Spec 046)","tags":["onboarding"]}},"/api/v1/preflight":{"post":{"description":"Deterministic, side-effect-free availability check for a caller-supplied list of tool IDs (Spec 098). Performs zero upstream calls and mutates no runtime state. HTTP status reports whether the CHECK executed: a fully blocked set is still 200, with the availability verdict in the body. Every executed preflight writes an activity record before the response is returned.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.PreflightRequest"}}},"description":"Tool IDs (1-100 before dedup), optional profile, annotation policy filters and wait budget","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Preflight verdict and per-tool results"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Validation error (malformed, oversized, doubled or unknown-field body; empty or oversized tool list; conflicting duplicate pins; unknown profile; wait_ms out of range)"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Missing or invalid credentials"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Runtime unavailable, evaluator infrastructure read failure, or the activity record could not be persisted"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Preflight required tools","tags":["tools"]}},"/api/v1/profiles":{"get":{"description":"Lists every profile as a ProfileView: the config fields as stored, the derived effective values, visible tool counts by tier, 24 h calls and blocked calls, and (administrators only) used_by and the anonymous_profile. A caller that is not an administrator sees only the profiles its entitlement reaches, with servers, rules and switchable_to narrowed to what it may see; an unreachable profile is omitted, never shown empty.","responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Profile list"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Configuration unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List configured profiles","tags":["profiles"]},"post":{"description":"Adds a profile. The body is a ProfileConfig. A name that already exists is 409 profile_exists; ` + "`" + `active` + "`" + ` and ` + "`" + `try` + "`" + ` are reserved by the REST API; a fatal validation rule is 400 with the offending field and the unchanged FR-007 text. A write that would let a client bound to a named profile escape it while require_mcp_auth is off is refused 409 binding_bypassable_without_auth (FR-008a) and nothing is written. Writes one profile_change record.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.ProfileConfig"}}},"description":"The profile","required":true},"responses":{"201":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Created, with the validator's warnings"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ProfileConflictResponse"}}},"description":"profile_exists, or binding_bypassable_without_auth (BindingGuardResponse)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Create a profile","tags":["profiles"]}},"/api/v1/profiles/active":{"get":{"description":"Deprecated (Spec 108 FR-039; sends a Deprecation header, successor GET /api/v1/profiles). Get the server-level default active profile used by UI surfaces (Web UI / tray). Empty string means \"all servers\". Note: within a live MCP session, the set_profile tool selection takes precedence over this default.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Active profile"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the default active profile","tags":["profiles"]},"put":{"description":"Deprecated (Spec 108 FR-039; sends a Deprecation header, successor GET /api/v1/profiles). Set the server-level default active profile for UI surfaces. The slug must match a configured profile; pass an empty string to clear. This does not affect live MCP sessions, which use the set_profile tool.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.SetActiveProfileRequest"}}},"description":"Profile slug to activate (empty clears)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Active profile updated"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request body"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot change the active profile)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown profile"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Set the default active profile","tags":["profiles"]}},"/api/v1/profiles/try":{"post":{"description":"Evaluates a DRAFT profile against a query exactly as retrieve_tools would (policy is applied before the limit) and returns the hits plus what the draft hides (hidden_by_profile and up to 100 {server, tool, reason}). The draft is validated as if it replaced the same-named profile, or was appended under a placeholder name when it has none. Nothing is persisted, no record is written, no event is published and the FR-008a guard does not run. Administrators only.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.TryProfileRequest"}}},"description":"draft profile, query and optional limit (default 10, max 50)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Search result under the draft"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid draft; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Try a draft profile","tags":["profiles"]}},"/api/v1/profiles/{name}":{"delete":{"description":"Deletes a profile. 409 profile_in_use (with used_by) while clients or tokens point at it, unless reassign_to names another existing profile (every pin moves there) or force is set (pins are left dangling, which the resolver treats as deny-all). 409 profile_is_anonymous_profile whenever it is the anonymous_profile and reassign_to is absent, even with force. Both paths remove the name from every switchable_to. Guarded by FR-008a. Writes one ` + "`" + `delete` + "`" + ` record.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}},{"description":"Another existing profile that takes over the pins","in":"query","name":"reassign_to","schema":{"type":"string"}},{"description":"Delete although in use, leaving pins dangling","in":"query","name":"force","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Deleted"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"reassign_to does not name another existing profile"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ProfileConflictResponse"}}},"description":"profile_in_use, profile_is_anonymous_profile, or binding_bypassable_without_auth (BindingGuardResponse)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Delete a profile","tags":["profiles"]},"get":{"description":"Returns the ProfileView of the named profile. A caller that is not an administrator gets the same 404 for an unreachable profile as for an unknown one.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The profile"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get one profile","tags":["profiles"]},"put":{"description":"Replaces the named profile with the body (a ProfileConfig whose name, when sent non-empty, must equal the path; 409 name_mismatch otherwise - a rename has its own route; an omitted or empty name takes the path's). A write whose only change is tools.classify is recorded as ` + "`" + `classify` + "`" + `. Guarded by FR-008a like a create.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.ProfileConfig"}}},"description":"The profile","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Updated, with the validator's warnings"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ProfileConflictResponse"}}},"description":"name_mismatch, or binding_bypassable_without_auth (BindingGuardResponse)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Replace a profile","tags":["profiles"]}},"/api/v1/profiles/{name}/effective-tools":{"get":{"description":"One row per catalog tool with the verdict of the access chain (the same rendering GET /tools?profile= uses): server, tool, intrinsic_tier, profile_tier, access{visible, callable, reason} and classification_stale. With client=\u003cid\u003e the client's credential is evaluated UNDER this profile (\"what would Cursor get here\"). An administrator gets every row plus counts.callable, counts.by_reason and stale_classifications; every other caller gets only visible rows and counts{visible, hidden}, and client= and reason= are refused 403. An unreachable profile answers exactly like an unknown one.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}},{"description":"Evaluate this client's credential under the profile (administrators only)","in":"query","name":"client","schema":{"type":"string"}},{"description":"Keep only this server's rows","in":"query","name":"server","schema":{"type":"string"}},{"description":"Keep only rows with this access reason (administrators only)","in":"query","name":"reason","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Effective tools"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"operation requires admin access"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found / client not found"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Effective tools of a profile","tags":["profiles"]}},"/api/v1/profiles/{name}/rename":{"post":{"description":"Renames a profile and moves every reference to it - token pins, client bindings, other profiles' switchable_to and the anonymous_profile - in one write (D19). Tokens move first, so a failure part-way never widens a scope. Guarded by FR-008a. Writes one ` + "`" + `rename` + "`" + ` record.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.RenameProfileRequest"}}},"description":"new_name","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Renamed; moved lists the clients and tokens that followed"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ProfileConflictResponse"}}},"description":"profile_exists, or binding_bypassable_without_auth (BindingGuardResponse)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Rename a profile","tags":["profiles"]}},"/api/v1/registries":{"get":{"description":"Retrieves list of all MCP server registries that can be browsed for discovering and installing new upstream servers. Includes registry metadata, server counts, and API endpoints.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetRegistriesResponse"}}},"description":"Registries retrieved successfully"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to list registries"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List available MCP server registries","tags":["registries"]},"post":{"description":"Adds a generic modelcontextprotocol/registry v0.1 https endpoint as a custom registry (MCP-866). The source is always tagged custom/unverified, so every server discovered through it lands quarantined and can never skip quarantine.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.AddRegistrySourceRequest"}}},"description":"Registry source (https url + optional protocol/id/name)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Registry source added"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"invalid_registry_url"},"403":{"content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/contracts.ErrorResponse"},{"$ref":"#/components/schemas/contracts.ErrorResponse"}]}}},"description":"Forbidden (agent tokens cannot mutate registries)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_shadows_builtin | duplicate_registry"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add a user-supplied registry source","tags":["registries"]}},"/api/v1/registries/{id}":{"delete":{"description":"Removes a custom/unverified registry previously added via add-source (MCP-1057). Built-in registries are refused with registry_shadows_builtin; an unknown id yields registry_not_found. The change is persisted copy-on-write.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Registry source removed"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID is required"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registries_locked"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_not_found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_shadows_builtin"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Remove a user-added custom registry source","tags":["registries"]},"put":{"description":"Updates a custom registry previously added via add-source (MCP-1072): name, url, servers-url. Empty fields are left unchanged. Built-in registries are refused with registry_shadows_builtin; an unknown id yields registry_not_found; a non-https url yields invalid_registry_url. The change is persisted copy-on-write.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.EditRegistrySourceRequest"}}},"description":"Fields to update (name/url/servers_url; empty = unchanged)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Registry source updated"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID is required | invalid_registry_url"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registries_locked"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_not_found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_shadows_builtin"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Edit a user-added custom registry source","tags":["registries"]}},"/api/v1/registries/{id}/refresh":{"post":{"description":"Invalidates the cached server lists for a registry so the next search re-fetches fresh data from the source (spec 070 FR-007). Returns how many cache entries were dropped.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.RefreshRegistryResponse"}}},"description":"Registry cache refreshed"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID is required"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to refresh registry cache"}},"summary":"Refresh a registry's cached server list","tags":["registries"]}},"/api/v1/registries/{id}/servers":{"get":{"description":"Searches for MCP servers within a specific registry by keyword or tag. Returns server metadata including installation commands, source code URLs, and npm package information for easy discovery and installation.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Search query keyword","in":"query","name":"q","schema":{"type":"string"}},{"description":"Filter by tag","in":"query","name":"tag","schema":{"type":"string"}},{"description":"Maximum number of results (default 10)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SearchRegistryServersResponse"}}},"description":"Servers retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to search servers"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Search MCP servers in a registry","tags":["registries"]}},"/api/v1/registries/{id}/servers/{serverId}/add":{"post":{"description":"Resolves a registry server reference server-side, re-derives a validated config, and persists it quarantined (spec 070 keystone). The client never sends a config blob — command/args/url and the quarantine flag are derived from the registry entry, not the request.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Server ID within the registry","in":"path","name":"serverId","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.AddFromRegistryRequest"}}},"description":"Optional overrides (name, env, enabled)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server added (quarantined)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"no_install_info | missing_required_input | duplicate_name"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot add servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_not_found | server_not_found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add an upstream server from a registry reference","tags":["registries"]}},"/api/v1/review":{"get":{"description":"Returns one row per quarantined server, trusted server with pending or changed tools, or (Spec 125) server with held skills (kind skill_review; skills_pending / skills_changed counts). Scoped callers see only servers they may enumerate (for a profile-pinned token: servers within its pin), with count recomputed; held-skill counts and skill_review rows are administrator-only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Review queue"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to load review queue"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the server review queue","tags":["review"]}},"/api/v1/routing":{"get":{"description":"Get the current routing mode and available MCP endpoints.\nrouting_mode is what /mcp is actually serving; pending_routing_mode carries a\nrestart-pending value persisted on disk (empty when there is none).\ntool_response_mode and direct_tool_response_mode report the two serialization axes, resolved.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Routing mode information"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get routing mode information","tags":["status"]}},"/api/v1/secrets":{"post":{"description":"Stores a secret value in the operating system's secure keyring. The secret can then be referenced in configuration using ${keyring:secret-name} syntax. Automatically notifies runtime to restart affected servers.","requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{},"type":"object"}}},"description":"Secret stored successfully with reference syntax"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload, missing name/value, or unsupported type"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Secret resolver not available or failed to store secret"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Store a secret in OS keyring","tags":["secrets"]}},"/api/v1/secrets/{name}":{"delete":{"description":"Deletes a secret from the operating system's secure keyring. Automatically notifies runtime to restart affected servers. Only keyring type is supported for security.","parameters":[{"description":"Name of the secret to delete","in":"path","name":"name","required":true,"schema":{"type":"string"}},{"description":"Secret type (only 'keyring' supported, defaults to 'keyring')","in":"query","name":"type","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{},"type":"object"}}},"description":"Secret deleted successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Missing secret name or unsupported type"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Secret resolver not available or failed to delete secret"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Delete a secret from OS keyring","tags":["secrets"]}},"/api/v1/security/bundle":{"get":{"description":"Reports the offline TPA signature corpus this install is serving: full SHA-256 digest, sequence, authority, trust epoch, signature verification, staleness (with the stale flag and its threshold), degraded coverage with its reason, rollback pin, and the last refused candidate. Also carries the refresh status (last checked and activated times, last cycle outcome, next check, consecutive failures; the fetch host only, never the URL) and the post-activation re-protection sweep status. Admin only.","responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Bundle status"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the TPA signature bundle status","tags":["security"]}},"/api/v1/security/bundle/history":{"get":{"description":"Append-only list of bundle activations, oldest first, each with its full SHA-256 digest. It is the trustworthy source of the digest to name in a rollback. Admin only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Activation history (data is an array of TPABundleActivation)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"History could not be read"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the TPA signature bundle activation history","tags":["security"]}},"/api/v1/security/bundle/refresh":{"post":{"description":"Runs one refresh cycle immediately: the local file leg (always network-free) followed by the optional fetch leg when security.tpa_fetch_enabled is on and a trusted signer and URL are configured. A cycle already in flight is joined, so one download and at most one activation happen per distinct candidate. The response is the resulting bundle status; the cycle outcome is in its refresh block (activated, unchanged, not_modified, rejected, fetch_unavailable, channel_invalid, superseded, disabled). Network failures are reported as fetch_unavailable and never as a rejection; last-known-good keeps serving. Unlike reload, refresh may make an outbound request. Admin API key only.","responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Updated bundle status; the refresh block holds the cycle outcome"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Refresh the TPA signature bundle now","tags":["security"]}},"/api/v1/security/bundle/reload":{"post":{"description":"Re-runs the single-flight bundle pipeline against the configured source and current policy. A refused candidate leaves last-known-good serving and is reported as last_rejection in the returned status. Admin API key only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Updated bundle status"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Reload the TPA signature bundle","tags":["security"]}},"/api/v1/security/bundle/rollback":{"post":{"description":"The one operator override of the downgrade watermark. Exactly one of embedded or path must be given, and digest must be the FULL 64-character lowercase hex SHA-256 of the target (the 12-character fingerprint is refused). On success the target serves and is pinned. A refusal (for example rollback_target_mismatch) returns 409 with the rejection reason and last-known-good keeps serving. Admin API key only; agent tokens are refused.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.bundleRollbackRequest"}}},"description":"Rollback target","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Updated bundle status"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Usage error: both or neither of embedded/path, or digest is not 64 lowercase hex"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BundleRollbackRefusedResponse"}}},"description":"Rollback refused; the response carries the rejection reason"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal error"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Roll the TPA signature bundle back to a named artifact","tags":["security"]}},"/api/v1/security/bundle/unpin":{"post":{"description":"Clears the rollback pin and re-validates the serving bundle under the normal downgrade watermark, so a rolled-back target below the watermark no longer serves. A quiet no-op when nothing is pinned. Admin API key only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Updated bundle status"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"The unpin could not be recorded"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Clear the TPA signature bundle rollback pin","tags":["security"]}},"/api/v1/servers":{"get":{"description":"Get a list of all configured upstream MCP servers with their connection status and statistics","parameters":[{"description":"Restrict to the profile's effective servers; tool_count becomes the number of that server's tools visible under the profile (Spec 108 FR-032)","in":"query","name":"profile","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServersResponse"}}},"description":"Server list with statistics"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unsupported scope filter (client/token), or '-' on a server filter"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown or unreachable profile"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List all upstream MCP servers","tags":["servers"]},"post":{"description":"Add a new MCP upstream server to the configuration. New servers are quarantined by default for security. Isolation: ` + "`" + `isolation.enabled` + "`" + ` is READ-ONLY (it reports the effective state on reads) and is rejected with 400; set the per-server override via ` + "`" + `isolation.enabled_override` + "`" + ` (true | false | null to clear, omit to leave unchanged). An unrecognized ` + "`" + `isolation.mode_override` + "`" + ` is rejected with 400.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.AddServerRequest"}}},"description":"Server configuration","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server added successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid configuration"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Conflict - server with this name already exists"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add a new upstream server","tags":["servers"]}},"/api/v1/servers/disable_all":{"post":{"description":"Disable all configured upstream MCP servers with partial failure handling","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/management.BulkOperationResult"}}},"description":"Bulk disable results with success/failure counts"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Disable all servers","tags":["servers"]}},"/api/v1/servers/enable_all":{"post":{"description":"Enable all configured upstream MCP servers with partial failure handling","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/management.BulkOperationResult"}}},"description":"Bulk enable results with success/failure counts"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable all servers","tags":["servers"]}},"/api/v1/servers/import":{"post":{"description":"Import MCP server configurations from a Claude Desktop, Claude Code, Cursor IDE, Codex CLI, or Gemini CLI configuration file","parameters":[{"description":"If true, return preview without importing","in":"query","name":"preview","schema":{"type":"boolean"}},{"description":"Force format (claude-desktop, claude-code, cursor, codex, gemini)","in":"query","name":"format","schema":{"type":"string"}},{"description":"Comma-separated list of server names to import","in":"query","name":"server_names","schema":{"type":"string"}}],"requestBody":{"content":{"multipart/form-data":{"schema":{"type":"file"}}},"description":"Configuration file to import","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportResponse"}}},"description":"Import result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid file or format"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Import servers from uploaded configuration file","tags":["servers"]}},"/api/v1/servers/import/json":{"post":{"description":"Import MCP server configurations from raw JSON or TOML content (useful for pasting configurations)","parameters":[{"description":"If true, return preview without importing","in":"query","name":"preview","schema":{"type":"boolean"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportRequest"}}},"description":"Import request with content","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportResponse"}}},"description":"Import result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid content or format"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Import servers from JSON/TOML content","tags":["servers"]}},"/api/v1/servers/import/path":{"post":{"description":"Import MCP server configurations by reading a file from the server's filesystem. A preview (preview=true) of a file with no MCP servers (empty, {}, or no/empty server map) answers 200 with an empty imported list; an apply of such a file and a malformed file still answer 400.","parameters":[{"description":"If true, return preview without importing","in":"query","name":"preview","schema":{"type":"boolean"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportFromPathRequest"}}},"description":"Import request with file path","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportResponse"}}},"description":"Import result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid path or format"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"File not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Import servers from a file path","tags":["servers"]}},"/api/v1/servers/import/paths":{"get":{"description":"Returns well-known configuration file paths for supported formats with existence check","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.CanonicalConfigPathsResponse"}}},"description":"Canonical config paths"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get canonical config file paths","tags":["servers"]}},"/api/v1/servers/reconnect":{"post":{"description":"Force reconnection to all upstream MCP servers","parameters":[{"description":"Reason for reconnection","in":"query","name":"reason","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"All servers reconnected successfully"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Reconnect all servers","tags":["servers"]}},"/api/v1/servers/restart_all":{"post":{"description":"Restart all configured upstream MCP servers sequentially with partial failure handling","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/management.BulkOperationResult"}}},"description":"Bulk restart results with success/failure counts"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Restart all servers","tags":["servers"]}},"/api/v1/servers/{id}":{"delete":{"description":"Remove an MCP upstream server from the configuration. This stops the server if running and removes it from config.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server removed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Remove an upstream server","tags":["servers"]},"patch":{"description":"Update specific fields of an existing upstream MCP server configuration. Isolation: ` + "`" + `isolation.enabled` + "`" + ` is READ-ONLY (it reports the effective state on reads) and is rejected with 400; set the per-server override via ` + "`" + `isolation.enabled_override` + "`" + ` (true | false | null to clear, omit to leave unchanged). An unrecognized ` + "`" + `isolation.mode_override` + "`" + ` is rejected with 400.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.AddServerRequest"}}},"description":"Fields to update (all optional)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server updated successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - no fields or invalid body"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Partially update an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/config-to-secret":{"post":{"description":"Atomically reads the real value from the server config, stores it in the OS keyring, and rewrites the config field to ` + "`" + `${keyring:\u003cname\u003e}` + "`" + `. Unblocks the UI's Convert-to-secret affordance for values the API redacts on the read path.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{},"type":"object"}}},"description":"Secret stored, config updated with reference"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad scope/key/secret_name, or value is already a reference / empty"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or key not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Secret resolver or config update failed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Convert a header / env value to a keyring secret","tags":["servers"]}},"/api/v1/servers/{id}/disable":{"post":{"description":"Disable a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server disabled successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Disable an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/discover-tools":{"post":{"description":"Manually trigger tool discovery and indexing for a specific upstream MCP server. This forces an immediate refresh of the server's tool cache.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Tool discovery triggered successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot discover tools)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to discover tools"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Discover tools for a specific server","tags":["servers"]}},"/api/v1/servers/{id}/enable":{"post":{"description":"Enable a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server enabled successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/login":{"post":{"description":"Initiate OAuth authentication flow for a specific upstream MCP server. Returns structured OAuth start response with correlation ID for tracking.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.OAuthStartResponse"}}},"description":"OAuth login initiated successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.OAuthFlowError"}}},"description":"OAuth error (client_id required, DCR failed, etc.)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Trigger OAuth login for server","tags":["servers"]}},"/api/v1/servers/{id}/logout":{"post":{"description":"Clear OAuth authentication token and disconnect a specific upstream MCP server. The server will need to re-authenticate before tools can be used again.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"OAuth logout completed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled or read-only mode)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Clear OAuth token and disconnect server","tags":["servers"]}},"/api/v1/servers/{id}/logs":{"get":{"description":"Retrieve log entries for a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Number of log lines to retrieve","in":"query","name":"tail","schema":{"default":100,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServerLogsResponse"}}},"description":"Server logs retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server logs","tags":["servers"]}},"/api/v1/servers/{id}/quarantine":{"post":{"description":"Place a specific upstream MCP server in quarantine to prevent tool execution","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server quarantined successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Quarantine a server","tags":["servers"]}},"/api/v1/servers/{id}/refresh":{"post":{"description":"Re-discover and re-index a specific upstream MCP server's tools without changing any security state. Alias of discover-tools, named for the upstream_servers 'refresh' operation; use it to make just-approved tools searchable immediately.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Tool refresh triggered successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot refresh)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to refresh tools"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Refresh a server's tools","tags":["servers"]}},"/api/v1/servers/{id}/restart":{"post":{"description":"Restart the connection to a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server restarted successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Restart an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/review":{"get":{"description":"Returns redacted server configuration, captured tool definitions, annotations, scan verdicts, and diffs. Scoped callers receive the same 404 for invisible and missing servers.","parameters":[{"description":"Server name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server review"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to load server review"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get review details for a server","tags":["review"]}},"/api/v1/servers/{id}/security/approve":{"post":{"description":"Saves the integrity baseline and optionally blocks selected tools atomically before unquarantining the server. With expected_hashes (tool name -\u003e the review's current_hash; {} for an empty review) the approval is bound to the reviewed definitions: when a tool the approval would make reachable (pending, or approved and enabled, minus block) changed or appeared since the review, or a block target no longer exists, the response is 409 review_out_of_date, nothing is written and the server stays quarantined. Tools listed after the approval wait for review.","parameters":[{"description":"Server name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.securityApproveRequest"}}},"description":"Force approval and tool names to keep disabled"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server approved"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request or unknown tool block target"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not configured"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.StaleReviewErrorResponse"}}},"description":"Dangerous scan verdict requires force, approval failed, the review is out of date (error_code review_out_of_date), or server_replaced (the server was removed or re-added since expected_incarnation)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Approve a server after security review","tags":["security"]}},"/api/v1/servers/{id}/skills":{"get":{"description":"Lists the skills of one upstream server. An administrator sees every record: status, hashes, files, scan result and the availability an agent would see. A scoped agent token with the server in its reach sees only the available skills, as the approved copy (id, uri, path, name, description, status \"approved\", approved_hash, files, total_size; contracts.SkillsAgentListResponse) and nothing about any other skill; a server outside its reach is 404. With enable_skills off the answer is {\"enabled\": false, \"skills\": []} and no upstream is contacted.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsListResponse"}}},"description":"Skills of the server"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found, or outside the caller's reach"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List the skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/skills/approve":{"post":{"description":"Administrator only. Approves the named skills for exactly the content the reviewer saw: expected_hashes maps each skill path to the current_hash from the listing, and expected_incarnation (the listing's incarnation) binds the approval to the server that was reviewed. When a hash differs, or a named skill has no expected hash, the response is 409 review_out_of_date with the changed and unreviewed names and nothing is approved; 409 server_replaced when the server was removed or replaced since the review; 422 skill_unusable for a skill that cannot be approved (a failed check or a dynamic file list). A skill already approved for its current content is left as it is and not counted. The blocked mark is never touched. A scoped agent token is refused with 403.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsApproveRequest"}}},"description":"Skills to approve, with the review binding","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsApproveResponse"}}},"description":"Number of skills newly approved (inside the data envelope)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or skill not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsStaleReviewResponse"}}},"description":"review_out_of_date, server_replaced or skills_disabled"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsUnusableResponse"}}},"description":"skill_unusable"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Approve skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/skills/block":{"post":{"description":"Administrator only. Sets the blocked mark on the named skills: a blocked skill is never offered to an agent, and no refresh, content change or automatic approval clears the mark. expected_incarnation is optional (0 binds to the current server). 409 server_replaced when the server was removed or replaced since it was reviewed. A scoped agent token is refused with 403.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsBlockRequest"}}},"description":"Skills to block","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsBlockResponse"}}},"description":"Number of skills whose mark changed (inside the data envelope)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or skill not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"server_replaced or skills_disabled"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Block skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/skills/content":{"get":{"description":"Returns a chunk of one stored text file of a skill. An administrator reads the current copy by default; a scoped agent token with the server in its reach reads the approved copy of an available skill only (copy is forced to approved), and gets one 404 for every other skill or file. A server outside its reach is 404. Offsets are byte positions; a chunk never splits a UTF-8 character, so it can be a few bytes shorter than limit. next_offset is absent at the end of the file. 404 for an unknown skill or file (or with enable_skills off), 415 for a binary file, 409 stored_copy_damaged when the stored bytes no longer match their digest.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Skill path, e.g. hf-cli","in":"query","name":"skill","required":true,"schema":{"type":"string"}},{"description":"File path inside the skill (default SKILL.md)","in":"query","name":"file","schema":{"type":"string"}},{"description":"current (default) or approved","in":"query","name":"copy","schema":{"type":"string"}},{"description":"Byte offset to start at (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Maximum bytes (default and maximum 65536)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillContentResponse"}}},"description":"A chunk of the file"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad parameters"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"output_blocked: the output sanitisation policy withholds the text (scoped caller)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server, skill or file not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"stored_copy_damaged (administrator)"},"415":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"The file is binary"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Read one text file of a skill","tags":["servers"]}},"/api/v1/servers/{id}/skills/refresh":{"post":{"description":"Administrator only. Reads the server's skills from the upstream again, verifies every file and returns the listing once applied. A refresh that is already running is joined. 409 skills_disabled when enable_skills is off; 409 skills_not_supported when the server does not announce the skills extension.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsListResponse"}}},"description":"Skills of the server after the refresh"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"skills_disabled, skills_not_supported or refresh_superseded"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Refresh failed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Refresh the skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/skills/unblock":{"post":{"description":"Administrator only. Clears the blocked mark on the named skills. The skill's approval state is not changed: a skill that is not approved stays unavailable. expected_incarnation is optional (0 binds to the current server). 409 server_replaced when the server was removed or replaced since it was reviewed. A scoped agent token is refused with 403.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsBlockRequest"}}},"description":"Skills to unblock","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsBlockResponse"}}},"description":"Number of skills whose mark changed (inside the data envelope)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or skill not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"server_replaced or skills_disabled"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Unblock skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/tool-calls":{"get":{"description":"Retrieves tool call history filtered by upstream server ID. Returns recent tool executions for the specified server including timestamps, arguments, results, and errors. Useful for server-specific debugging and monitoring.","parameters":[{"description":"Upstream server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Maximum number of records to return (1-100, default 50)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServerToolCallsResponse"}}},"description":"Server tool calls retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get server tool calls"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call history for specific server","tags":["tool-calls"]}},"/api/v1/servers/{id}/tools":{"get":{"description":"Retrieve all available tools for a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServerToolsResponse"}}},"description":"Server tools retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server kept being removed or replaced while its tools were read"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/approve":{"post":{"description":"Approves the given pending/changed tools (or all of them with approve_all). With expected_hashes (tool name -\u003e the review's current_hash) the approval is bound to the reviewed definitions: when a requested tool (approve_all: any pending or changed tool) no longer matches, the response is 409 review_out_of_date and nothing is approved.","parameters":[{"description":"Server name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.approveToolsRequest"}}},"description":"Tools to approve, or approve_all, with an optional review binding","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Approval outcome"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.StaleReviewErrorResponse"}}},"description":"The review is out of date; nothing was approved"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Approve tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/block":{"post":{"description":"Atomically approves AND disables the given tools (or all pending/changed tools when block_all=true) for a server. The approve and disable land in a single write per tool, so a tool is never left in the approved+enabled state. The \"blocked\" field counts tools actually blocked. An optional expected_incarnation binds the write to the reviewed server (Spec 116): a remove and re-add since then answers 409 server_replaced and writes nothing.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Block result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server was removed or re-added since expected_incarnation"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Block (approve+disable) tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/disable_all":{"post":{"description":"Bulk-toggles every known tool of a server. The \"changed\" field","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.expectedIncarnationBody"}}},"description":"Optional incarnation of the reviewed server (Spec 116)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Operation result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server was removed or re-added since expected_incarnation"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable or disable all tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/enable_all":{"post":{"description":"Bulk-toggles every known tool of a server. The \"changed\" field","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.expectedIncarnationBody"}}},"description":"Optional incarnation of the reviewed server (Spec 116)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Operation result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server was removed or re-added since expected_incarnation"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable or disable all tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/unquarantine":{"post":{"description":"Remove a specific upstream MCP server from quarantine to allow tool execution","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.expectedIncarnationBody"}}},"description":"Optional incarnation of the reviewed server (Spec 116)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server unquarantined successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server was removed or re-added since expected_incarnation"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Unquarantine a server","tags":["servers"]}},"/api/v1/sessions":{"get":{"description":"Retrieves paginated list of active and recent MCP client sessions. Each session represents a connection from an MCP client to MCPProxy, tracking initialization time, tool calls, and connection status.","parameters":[{"description":"Maximum number of sessions to return (1-100, default 10)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Number of sessions to skip for pagination (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Filter by session status","in":"query","name":"status","schema":{"enum":["active","closed"],"type":"string"}},{"description":"Filter by the session's latest effective profile; - selects sessions with none (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Filter by the client id the session's credential is bound to; - selects sessions with none (Spec 108)","in":"query","name":"client","schema":{"type":"string"}},{"description":"Filter by the token name the session initialized with; - selects sessions with none (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Alias of token","in":"query","name":"agent","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetSessionsResponse"}}},"description":"Sessions retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid status filter, token and agent naming different tokens, or client_name (not supported here; filter by client)"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read MCP session history"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get sessions"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get active MCP sessions","tags":["sessions"]}},"/api/v1/sessions/{id}":{"get":{"description":"Retrieves detailed information about a specific MCP client session including initialization parameters, connection status, tool call count, and activity timestamps.","parameters":[{"description":"Session ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetSessionDetailResponse"}}},"description":"Session details retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Session ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read MCP session history"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Session not found"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get MCP session details by ID","tags":["sessions"]}},"/api/v1/stats/tokens":{"get":{"description":"Retrieve token savings statistics across all servers and sessions","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Token statistics"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read deployment-wide token statistics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get token savings statistics","tags":["stats"]}},"/api/v1/status":{"get":{"description":"Get comprehensive server status including running state, listen address, upstream statistics, and timestamp. For a scoped caller (an agent token; for a profile-pinned token, its allowed_servers intersected with the pin) upstream_stats lists only the servers it may enumerate and every counter is recomputed over them.\ntelemetry (admin only): effective telemetry state {enabled, source: env|config|default, disabled_by}","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server status information"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server status","tags":["status"]}},"/api/v1/telemetry/payload":{"get":{"description":"Render the exact JSON heartbeat payload that mcpproxy would next send to the telemetry endpoint, without making a network call. Counters in the payload reflect the current in-memory state. Spec 042.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Telemetry heartbeat payload"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read the deployment telemetry payload"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Telemetry service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Preview next telemetry heartbeat payload","tags":["telemetry"]}},"/api/v1/telemetry/update-failure":{"post":{"description":"Records one terminal update-session failure, identified only by its\nstage (appcast, download, install, other). The body carries no error\ntext, URL, or version — the stage is the only value transmitted.\nReturns 204 both when the occurrence was durably persisted and when\ntelemetry is inactive at event time (config opt-out, environment\nopt-out, CI, or dev build), in which case nothing is recorded.\nCallers cannot and need not distinguish the two.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.UpdateFailureRequest"}}},"description":"Update failure stage","required":true},"responses":{"204":{"description":"Accepted (recorded, or a deliberate no-op while telemetry is inactive)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Malformed body, unknown field, trailing value, or stage outside the closed set"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Persistence failure"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Record a desktop auto-update failure occurrence (Spec 095)","tags":["telemetry"]}},"/api/v1/tool-calls":{"get":{"description":"Retrieves paginated tool call history across all upstream servers or filtered by session ID. Includes execution timestamps, arguments, results, and error information for debugging and auditing.","parameters":[{"description":"Maximum number of records to return (1-100, default 50)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Number of records to skip for pagination (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Filter tool calls by MCP session ID","in":"query","name":"session_id","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetToolCallsResponse"}}},"description":"Tool calls retrieved successfully"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get tool calls"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call history","tags":["tool-calls"]}},"/api/v1/tool-calls/{id}":{"get":{"description":"Retrieves detailed information about a specific tool call execution including full request arguments, response data, execution time, and any errors encountered.","parameters":[{"description":"Tool call ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetToolCallDetailResponse"}}},"description":"Tool call details retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call not found"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call details by ID","tags":["tool-calls"]}},"/api/v1/tool-calls/{id}/replay":{"post":{"description":"Re-executes a previous tool call with optional modified arguments. Useful for debugging and testing tool behavior with different inputs. Creates a new tool call record linked to the original.","parameters":[{"description":"Original tool call ID to replay","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ReplayToolCallRequest"}}},"description":"Optional modified arguments for replay"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ReplayToolCallResponse"}}},"description":"Tool call replayed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call ID required or invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Replay refused: tool quarantined or not callable, server quarantined, outside the profile policy, or the token lacks the tool's permission tier"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"429":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Shed by a concurrency limit or an agent token call rate limit (Retry-After header carries the wait hint)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to replay tool call"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Replay a tool call","tags":["tool-calls"]}},"/api/v1/tools":{"get":{"description":"Consolidated, read-only listing of all tools from every configured server (including disabled servers and disabled/config-denied tools), enriched with approval state and 30-day usage. Backs the global Tools page and the CLI global ` + "`" + `tools list` + "`" + ` (spec 050, issue #437).","parameters":[{"description":"View-as (administrator only): the tools this client would see, each with its access verdict {visible, callable, reason} and profile_tier (Spec 108 FR-032)","in":"query","name":"client","schema":{"type":"string"}},{"description":"View-as: the tools this profile would expose. An administrator gets every row with a verdict; any other caller gets only the visible rows plus counts {visible, hidden} (Spec 108 FR-032)","in":"query","name":"profile","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GlobalToolsResponse"}}},"description":"All tools across all servers"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unsupported scope filter (token), both client and profile, or '-' on a tools filter"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"client= requires administrator credentials"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown or unreachable client / profile"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Could not enumerate servers"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List every tool across all servers","tags":["tools"]}},"/api/v1/tools/call":{"post":{"description":"Execute a tool on an upstream MCP server (wrapper around MCP tool calls)","requestBody":{"content":{"application/json":{"schema":{"properties":{"arguments":{"type":"object"},"tool_name":{"type":"string"}},"type":"object"}}},"description":"Tool call request with tool name and arguments","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Tool call result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (invalid payload or missing tool name)"},"429":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Shed by a concurrency limit or an agent token call rate limit (Retry-After header carries the wait hint)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error or tool execution failure"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Call a tool","tags":["tools"]}},"/api/v1/work-sessions":{"get":{"description":"Lists work sessions (one agent's run of work) with their failure facts. An agent token sees only its own sessions, and only the part of each that touched servers in its reach.","parameters":[{"description":"Only sessions with at least one failure","in":"query","name":"failed","schema":{"type":"boolean"}},{"description":"With failed: count policy blocks as failures (default true)","in":"query","name":"include_blocked","schema":{"type":"boolean"}},{"description":"Filter by agent token name","in":"query","name":"token","schema":{"type":"string"}},{"description":"Filter by client id","in":"query","name":"client","schema":{"type":"string"}},{"description":"Filter by profile (administrators only)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Filter by run name","in":"query","name":"run","schema":{"type":"string"}},{"description":"Filter by the error class of the last failure","in":"query","name":"error_class","schema":{"type":"string"}},{"description":"Only sessions active at or after this time (RFC3339)","in":"query","name":"since","schema":{"type":"string"}},{"description":"Only sessions active at or before this time (RFC3339)","in":"query","name":"until","schema":{"type":"string"}},{"description":"last_activity (default) or last_failure","in":"query","name":"sort","schema":{"enum":["last_activity","last_failure"],"type":"string"}},{"description":"Page size (default 25, max 100)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Page offset","in":"query","name":"offset","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.WorkSessionListEnvelope"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad Request"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List work sessions","tags":["activity"]}},"/api/v1/work-sessions/{id}":{"get":{"parameters":[{"description":"Work session id","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.WorkSessionEnvelope"}}},"description":"OK"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Not Found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get one work session","tags":["activity"]}},"/api/v1/work-sessions/{id}/timeline":{"get":{"description":"Returns the session's activity rows and the upstream events of the servers it called, in time order, positioned at a failure, a row or the end. Bodies are omitted unless include_bodies is set.","parameters":[{"description":"Work session id","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"first_failure (default), failure:\u003cn\u003e, row:\u003cactivity id\u003e or end","in":"query","name":"at","schema":{"type":"string"}},{"description":"Rows before the position (default 20, max 250)","in":"query","name":"before","schema":{"type":"integer"}},{"description":"Rows after the position (default 20, max 250)","in":"query","name":"after","schema":{"type":"integer"}},{"description":"Include argument and response bodies","in":"query","name":"include_bodies","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.WorkSessionTimelineEnvelope"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad Request"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Not Found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get a work session's timeline","tags":["activity"]}},"/healthz":{"get":{"description":"Get comprehensive health status including all component health (Kubernetes-compatible liveness probe)","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.HealthResponse"}}},"description":"Service is healthy"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.HealthResponse"}}},"description":"Service is unhealthy"}},"summary":"Get health status","tags":["health"]}},"/readyz":{"get":{"description":"Get readiness status including all component readiness checks (Kubernetes-compatible readiness probe)","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.ReadinessResponse"}}},"description":"Service is ready"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.ReadinessResponse"}}},"description":"Service is not ready"}},"summary":"Get readiness status","tags":["health"]}}}, diff --git a/oas/swagger.yaml b/oas/swagger.yaml index ec320b055..e40653240 100644 --- a/oas/swagger.yaml +++ b/oas/swagger.yaml @@ -295,6 +295,13 @@ components: inline-response ceiling from 50k to up to 500k chars. Omit the key for the 500000 default; set it to 0 to disable the annotation. type: integer + mcp_oauth_enabled: + description: |- + MCPOAuthEnabled turns on browser login (OAuth 2.1 + PKCE) for MCP + clients on the loopback listener (Spec 132). Experimental, default false: + with it off nothing changes. Env override MCPPROXY_MCP_OAUTH_ENABLED is + process-only and never persisted. Live, no restart needed. + type: boolean mcp_reject_query_apikey: description: |- MCPRejectQueryAPIKey makes every MCP endpoint (/mcp*) refuse a request that From e0dc9b9a8f1e63f7f841ed1e3fdfec99f11b5616 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 18:43:54 +0200 Subject: [PATCH 02/42] fix(oauth): refuse browser login in every server-edition build (Spec 132 PR-1a) Related #1971 --- .../server/oauth_login_default_off_test.go | 59 --------------- internal/server/oauth_login_edition.go | 6 ++ internal/server/oauth_login_edition_server.go | 6 ++ internal/server/oauth_login_gate_on_test.go | 75 +++++++++++++++++++ internal/server/oauth_login_routes.go | 3 +- .../server/oauth_login_server_edition_test.go | 52 +++++++++---- 6 files changed, 126 insertions(+), 75 deletions(-) create mode 100644 internal/server/oauth_login_edition.go create mode 100644 internal/server/oauth_login_edition_server.go create mode 100644 internal/server/oauth_login_gate_on_test.go diff --git a/internal/server/oauth_login_default_off_test.go b/internal/server/oauth_login_default_off_test.go index 73ca7f42a..1f08716ce 100644 --- a/internal/server/oauth_login_default_off_test.go +++ b/internal/server/oauth_login_default_off_test.go @@ -180,62 +180,3 @@ func TestOAuthLogin_Gate_OffAndEverUsed_404(t *testing.T) { assert.NotContains(t, got.body, "mcp-chain", path) } } - -func TestOAuthLogin_Gate_On(t *testing.T) { - srv := newOAuthLoginTestServer(t, func(c *config.Config) { c.MCPOAuthEnabled = true }) - mux := oauthLoginTestMux(srv, true) - - for _, path := range oauthLoginGatedPaths { - req := httptest.NewRequest(http.MethodGet, path, http.NoBody) - req.RemoteAddr = "127.0.0.1:4000" - req.Host = "127.0.0.1:8080" - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - assert.Equal(t, http.StatusNotImplemented, rec.Code, "loopback peer+host "+path) - assert.Contains(t, rec.Header().Get("Content-Type"), "application/json", path) - - req = httptest.NewRequest(http.MethodGet, path, http.NoBody) - req.RemoteAddr = "[::1]:4000" - req.Host = "localhost:8080" - rec = httptest.NewRecorder() - mux.ServeHTTP(rec, req) - assert.Equal(t, http.StatusNotImplemented, rec.Code, "ipv6 loopback peer "+path) - - req = httptest.NewRequest(http.MethodGet, path, http.NoBody) - req.RemoteAddr = "192.0.2.1:4000" - req.Host = "127.0.0.1:8080" - rec = httptest.NewRecorder() - mux.ServeHTTP(rec, req) - assert.Equal(t, http.StatusNotFound, rec.Code, "non-loopback peer "+path) - - req = httptest.NewRequest(http.MethodGet, path, http.NoBody) - req.RemoteAddr = "127.0.0.1:4000" - req.Host = "example.com" - rec = httptest.NewRecorder() - mux.ServeHTTP(rec, req) - assert.Equal(t, http.StatusNotFound, rec.Code, "non-loopback host "+path) - } -} - -// The gate reads the live config on every request: flipping the switch needs -// no restart and leaves no cached state. -func TestOAuthLogin_Gate_FollowsLiveConfig(t *testing.T) { - srv := newOAuthLoginTestServer(t, nil) - mux := oauthLoginTestMux(srv, true) - get := func() int { - req := httptest.NewRequest(http.MethodGet, "/oauth/token", http.NoBody) - req.RemoteAddr = "127.0.0.1:4000" - req.Host = "127.0.0.1:8080" - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - return rec.Code - } - assert.Equal(t, http.StatusNotFound, get(), "off: previous behaviour (root handler 404)") - - cfg := srv.runtime.Config() - require.NotNil(t, cfg) - on := *cfg - on.MCPOAuthEnabled = true - srv.runtime.UpdateConfig(&on, "") - assert.Equal(t, http.StatusNotImplemented, get(), "on") -} diff --git a/internal/server/oauth_login_edition.go b/internal/server/oauth_login_edition.go new file mode 100644 index 000000000..76db4aac6 --- /dev/null +++ b/internal/server/oauth_login_edition.go @@ -0,0 +1,6 @@ +//go:build !server + +package server + +// oauthLoginEditionSupported: the personal edition may serve browser login (Spec 132). +const oauthLoginEditionSupported = true diff --git a/internal/server/oauth_login_edition_server.go b/internal/server/oauth_login_edition_server.go new file mode 100644 index 000000000..fa37bbeec --- /dev/null +++ b/internal/server/oauth_login_edition_server.go @@ -0,0 +1,6 @@ +//go:build server + +package server + +// oauthLoginEditionSupported: a server-edition binary never serves browser login, whatever the config (Spec 132). +const oauthLoginEditionSupported = false diff --git a/internal/server/oauth_login_gate_on_test.go b/internal/server/oauth_login_gate_on_test.go new file mode 100644 index 000000000..fbdea267c --- /dev/null +++ b/internal/server/oauth_login_gate_on_test.go @@ -0,0 +1,75 @@ +//go:build !server + +package server + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" +) + +// Personal edition only: a server-edition binary never serves browser login. + +func TestOAuthLogin_Gate_On(t *testing.T) { + srv := newOAuthLoginTestServer(t, func(c *config.Config) { c.MCPOAuthEnabled = true }) + mux := oauthLoginTestMux(srv, true) + + for _, path := range oauthLoginGatedPaths { + req := httptest.NewRequest(http.MethodGet, path, http.NoBody) + req.RemoteAddr = "127.0.0.1:4000" + req.Host = "127.0.0.1:8080" + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + assert.Equal(t, http.StatusNotImplemented, rec.Code, "loopback peer+host "+path) + assert.Contains(t, rec.Header().Get("Content-Type"), "application/json", path) + + req = httptest.NewRequest(http.MethodGet, path, http.NoBody) + req.RemoteAddr = "[::1]:4000" + req.Host = "localhost:8080" + rec = httptest.NewRecorder() + mux.ServeHTTP(rec, req) + assert.Equal(t, http.StatusNotImplemented, rec.Code, "ipv6 loopback peer "+path) + + req = httptest.NewRequest(http.MethodGet, path, http.NoBody) + req.RemoteAddr = "192.0.2.1:4000" + req.Host = "127.0.0.1:8080" + rec = httptest.NewRecorder() + mux.ServeHTTP(rec, req) + assert.Equal(t, http.StatusNotFound, rec.Code, "non-loopback peer "+path) + + req = httptest.NewRequest(http.MethodGet, path, http.NoBody) + req.RemoteAddr = "127.0.0.1:4000" + req.Host = "example.com" + rec = httptest.NewRecorder() + mux.ServeHTTP(rec, req) + assert.Equal(t, http.StatusNotFound, rec.Code, "non-loopback host "+path) + } +} + +// The gate reads the live config on every request: flipping the switch needs +// no restart and leaves no cached state. +func TestOAuthLogin_Gate_FollowsLiveConfig(t *testing.T) { + srv := newOAuthLoginTestServer(t, nil) + mux := oauthLoginTestMux(srv, true) + get := func() int { + req := httptest.NewRequest(http.MethodGet, "/oauth/token", http.NoBody) + req.RemoteAddr = "127.0.0.1:4000" + req.Host = "127.0.0.1:8080" + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + return rec.Code + } + assert.Equal(t, http.StatusNotFound, get(), "off: previous behaviour (root handler 404)") + + cfg := srv.runtime.Config() + require.NotNil(t, cfg) + on := *cfg + on.MCPOAuthEnabled = true + srv.runtime.UpdateConfig(&on, "") + assert.Equal(t, http.StatusNotImplemented, get(), "on") +} diff --git a/internal/server/oauth_login_routes.go b/internal/server/oauth_login_routes.go index 2cefe21e0..582dec735 100644 --- a/internal/server/oauth_login_routes.go +++ b/internal/server/oauth_login_routes.go @@ -5,7 +5,6 @@ import ( "net/http" "net/netip" - "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" "github.com/smart-mcp-proxy/mcpproxy-go/internal/httpx" ) @@ -72,7 +71,7 @@ func (s *Server) oauthLoginGate(prev, served http.Handler) http.Handler { prev.ServeHTTP(w, r) return } - if !peerIsLoopback(r) || !httpx.IsLoopbackHost(r.Host) || config.ServerEditionEnabled(cfg) { + if !peerIsLoopback(r) || !httpx.IsLoopbackHost(r.Host) || !oauthLoginEditionSupported { http.NotFound(w, r) return } diff --git a/internal/server/oauth_login_server_edition_test.go b/internal/server/oauth_login_server_edition_test.go index 017ef1212..5121e484e 100644 --- a/internal/server/oauth_login_server_edition_test.go +++ b/internal/server/oauth_login_server_edition_test.go @@ -12,19 +12,43 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" ) -// Server edition never serves browser login, even with the switch on. -func TestOAuthLogin_Gate_ServerEdition_404(t *testing.T) { - srv := newOAuthLoginTestServer(t, func(c *config.Config) { - c.MCPOAuthEnabled = true - c.ServerEdition = &config.ServerEditionConfig{Enabled: true} - }) - mux := oauthLoginTestMux(srv, true) - for _, path := range oauthLoginGatedPaths { - req := httptest.NewRequest(http.MethodGet, path, http.NoBody) - req.RemoteAddr = "127.0.0.1:4000" - req.Host = "127.0.0.1:8080" - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - assert.Equal(t, http.StatusNotFound, rec.Code, path) +// A server-edition binary never serves browser login, whatever the config: +// no server_edition block, enabled=false and enabled=true all answer 404. +func TestOAuthLogin_Gate_ServerEditionBuild_404(t *testing.T) { + cases := map[string]func(*config.Config){ + "block absent": func(c *config.Config) { c.ServerEdition = nil }, + "enabled=false": func(c *config.Config) { c.ServerEdition = &config.ServerEditionConfig{Enabled: false} }, + "enabled=true": func(c *config.Config) { c.ServerEdition = &config.ServerEditionConfig{Enabled: true} }, + } + for name, edit := range cases { + t.Run(name, func(t *testing.T) { + srv := newOAuthLoginTestServer(t, func(c *config.Config) { + c.MCPOAuthEnabled = true + edit(c) + }) + mux := oauthLoginTestMux(srv, true) + for _, path := range oauthLoginGatedPaths { + req := httptest.NewRequest(http.MethodGet, path, http.NoBody) + req.RemoteAddr = "127.0.0.1:4000" + req.Host = "127.0.0.1:8080" + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + assert.Equal(t, http.StatusNotFound, rec.Code, path) + } + }) } } + +// Switch off and never used: the server build still delegates to the previous +// handler (unchanged behaviour). +func TestOAuthLogin_Gate_ServerEditionBuild_OffDelegates(t *testing.T) { + srv := newOAuthLoginTestServer(t, nil) + mux := oauthLoginTestMux(srv, true) + req := httptest.NewRequest(http.MethodGet, "/mcp/oauth/cursor", http.NoBody) + req.RemoteAddr = "127.0.0.1:4000" + req.Host = "127.0.0.1:8080" + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + assert.Equal(t, http.StatusOK, rec.Code) + assert.Contains(t, rec.Body.String(), "mcp-chain GET /mcp/oauth/cursor") +} From bfcc55068edffd8c3c188c461baaa465f1f8be64 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 18:50:41 +0200 Subject: [PATCH 03/42] feat(oauth): protocol logic for browser login (Spec 132 PR-1b) Related #1971 --- internal/mcplogin/limits.go | 66 ++++ internal/mcplogin/limits_test.go | 75 ++++ internal/mcplogin/metadata.go | 31 ++ internal/mcplogin/metadata_test.go | 43 +++ internal/mcplogin/pkce.go | 35 ++ internal/mcplogin/pkce_test.go | 70 ++++ internal/mcplogin/redirect.go | 156 ++++++++ internal/mcplogin/redirect_test.go | 105 ++++++ internal/mcplogin/registration.go | 123 +++++++ internal/mcplogin/registration_test.go | 103 ++++++ internal/mcplogin/requests.go | 337 ++++++++++++++++++ internal/mcplogin/requests_test.go | 259 ++++++++++++++ internal/mcplogin/resource.go | 65 ++++ internal/mcplogin/resource_test.go | 84 +++++ .../testdata/authorization_server.json | 19 + .../testdata/protected_resource_client.json | 9 + .../testdata/protected_resource_generic.json | 9 + internal/mcplogin/token.go | 200 +++++++++++ internal/mcplogin/token_test.go | 131 +++++++ 19 files changed, 1920 insertions(+) create mode 100644 internal/mcplogin/limits.go create mode 100644 internal/mcplogin/limits_test.go create mode 100644 internal/mcplogin/metadata.go create mode 100644 internal/mcplogin/metadata_test.go create mode 100644 internal/mcplogin/pkce.go create mode 100644 internal/mcplogin/pkce_test.go create mode 100644 internal/mcplogin/redirect.go create mode 100644 internal/mcplogin/redirect_test.go create mode 100644 internal/mcplogin/registration.go create mode 100644 internal/mcplogin/registration_test.go create mode 100644 internal/mcplogin/requests.go create mode 100644 internal/mcplogin/requests_test.go create mode 100644 internal/mcplogin/resource.go create mode 100644 internal/mcplogin/resource_test.go create mode 100644 internal/mcplogin/testdata/authorization_server.json create mode 100644 internal/mcplogin/testdata/protected_resource_client.json create mode 100644 internal/mcplogin/testdata/protected_resource_generic.json create mode 100644 internal/mcplogin/token.go create mode 100644 internal/mcplogin/token_test.go diff --git a/internal/mcplogin/limits.go b/internal/mcplogin/limits.go new file mode 100644 index 000000000..e32f9dc5c --- /dev/null +++ b/internal/mcplogin/limits.go @@ -0,0 +1,66 @@ +package mcplogin + +import ( + "math" + "time" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/upstream/limiter" +) + +const ( + // MaxBodyBytes is the largest request body register and token accept. + MaxBodyBytes = 16 << 10 + // MaxPendingRegistrations caps registrations that are not yet approved. + MaxPendingRegistrations = 50 + // MaxPendingRequests caps pending authorization requests. + MaxPendingRequests = 20 +) + +// Endpoint names the rate-limited public endpoints. +const ( + // EndpointRegister is POST /oauth/register. + EndpointRegister = "register" + // EndpointAuthorize is GET /oauth/authorize. + EndpointAuthorize = "authorize" + // EndpointToken is POST /oauth/token. + EndpointToken = "token" +) + +// rateFor returns the default budget of an endpoint. +func rateFor(endpoint string) (limiter.RateSpec, bool) { + switch endpoint { + case EndpointRegister: + return limiter.RateSpec{PerMinute: 10, Burst: 5}, true + case EndpointAuthorize: + return limiter.RateSpec{PerMinute: 30, Burst: 10}, true + case EndpointToken: + return limiter.RateSpec{PerMinute: 60, Burst: 20}, true + } + return limiter.RateSpec{}, false +} + +// Limiter rate limits the public OAuth endpoints per endpoint and remote +// address. It is safe for concurrent use. +type Limiter struct { + rates *limiter.TokenRates +} + +// NewLimiter returns a Limiter with the default rates. now is the clock; nil +// means time.Now. +func NewLimiter(now func() time.Time) *Limiter { + return &Limiter{rates: limiter.NewTokenRates(now)} +} + +// Allow charges one call of endpoint from remoteIP. When refused, +// retryAfterSeconds is at least 1. An unknown endpoint is not limited. +func (l *Limiter) Allow(endpoint, remoteIP string) (ok bool, retryAfterSeconds int) { + spec, known := rateFor(endpoint) + if !known { + return true, 0 + } + d := l.rates.Allow(endpoint+"|"+remoteIP, &spec) + if d.Allowed { + return true, 0 + } + return false, max(1, int(math.Ceil(d.RetryAfter.Seconds()))) +} diff --git a/internal/mcplogin/limits_test.go b/internal/mcplogin/limits_test.go new file mode 100644 index 000000000..19086b867 --- /dev/null +++ b/internal/mcplogin/limits_test.go @@ -0,0 +1,75 @@ +package mcplogin + +import ( + "sync" + "testing" + "time" +) + +type fakeClock struct { + mu sync.Mutex + t time.Time +} + +func (c *fakeClock) now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.t } +func (c *fakeClock) advance(d time.Duration) { + c.mu.Lock() + c.t = c.t.Add(d) + c.mu.Unlock() +} + +func TestLimiterBurstRefillRetryAfter(t *testing.T) { + clk := &fakeClock{t: time.Unix(1000, 0)} + l := NewLimiter(clk.now) + for i := 0; i < 5; i++ { + if ok, _ := l.Allow(EndpointRegister, "1.2.3.4"); !ok { + t.Fatalf("burst call %d refused", i) + } + } + ok, retry := l.Allow(EndpointRegister, "1.2.3.4") + if ok || retry < 1 { + t.Fatalf("expected refusal with retry>=1, got %v %d", ok, retry) + } + if ok, _ := l.Allow(EndpointRegister, "5.6.7.8"); !ok { + t.Fatal("other ip shares bucket") + } + if ok, _ := l.Allow(EndpointAuthorize, "1.2.3.4"); !ok { + t.Fatal("other endpoint shares bucket") + } + clk.advance(6 * time.Second) // 10/min -> 1 per 6 s + if ok, _ := l.Allow(EndpointRegister, "1.2.3.4"); !ok { + t.Fatal("refill failed") + } + if ok, _ := l.Allow(EndpointRegister, "1.2.3.4"); ok { + t.Fatal("only one token should have refilled") + } +} + +func TestLimiterDefaults(t *testing.T) { + clk := &fakeClock{t: time.Unix(1000, 0)} + l := NewLimiter(clk.now) + count := func(ep string) int { + n := 0 + for { + if ok, _ := l.Allow(ep, "9.9.9.9"); !ok { + return n + } + n++ + } + } + if got := count(EndpointAuthorize); got != 10 { + t.Errorf("authorize burst %d", got) + } + if got := count(EndpointToken); got != 20 { + t.Errorf("token burst %d", got) + } + if ok, _ := l.Allow("unknown", "1.1.1.1"); !ok { + t.Error("unknown endpoint must not be limited") + } +} + +func TestLimitConstants(t *testing.T) { + if MaxBodyBytes != 16<<10 || MaxPendingRegistrations != 50 || MaxPendingRequests != 20 { + t.Fatal("constants") + } +} diff --git a/internal/mcplogin/metadata.go b/internal/mcplogin/metadata.go new file mode 100644 index 000000000..d1a7168c4 --- /dev/null +++ b/internal/mcplogin/metadata.go @@ -0,0 +1,31 @@ +package mcplogin + +// ProtectedResourceMetadata is the RFC 9728 document for one OAuth resource +// path: the generic address when clientID is empty, else that client's. +func ProtectedResourceMetadata(origin, clientID string) map[string]any { + return map[string]any{ + "resource": origin + ResourcePath(clientID), + "authorization_servers": []string{origin}, + "bearer_methods_supported": []string{"header"}, + } +} + +// AuthorizationServerMetadata is the RFC 8414 document for this instance. +func AuthorizationServerMetadata(origin string) map[string]any { + return map[string]any{ + "issuer": origin, + "authorization_endpoint": origin + "/oauth/authorize", + "token_endpoint": origin + "/oauth/token", + "registration_endpoint": origin + "/oauth/register", + "response_types_supported": []string{"code"}, + "grant_types_supported": []string{"authorization_code", "refresh_token"}, + "code_challenge_methods_supported": []string{"S256"}, + "token_endpoint_auth_methods_supported": []string{"none"}, + } +} + +// Challenge is the WWW-Authenticate value that points an unauthenticated +// client at the protected-resource metadata of its address. +func Challenge(origin, clientID string) string { + return `Bearer resource_metadata="` + origin + "/.well-known/oauth-protected-resource" + ResourcePath(clientID) + `"` +} diff --git a/internal/mcplogin/metadata_test.go b/internal/mcplogin/metadata_test.go new file mode 100644 index 000000000..d9b52b219 --- /dev/null +++ b/internal/mcplogin/metadata_test.go @@ -0,0 +1,43 @@ +package mcplogin + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" +) + +func golden(t *testing.T, name string, v any) { + t.Helper() + got, err := json.MarshalIndent(v, "", " ") // maps marshal with sorted keys + if err != nil { + t.Fatal(err) + } + want, err := os.ReadFile(filepath.Join("testdata", name)) + if err != nil { + t.Fatal(err) + } + if string(got)+"\n" != string(want) { + t.Fatalf("%s mismatch:\n%s\nwant:\n%s", name, got, want) + } +} + +func TestProtectedResourceMetadataGolden(t *testing.T) { + golden(t, "protected_resource_client.json", ProtectedResourceMetadata("http://127.0.0.1:8080", "cursor")) + golden(t, "protected_resource_generic.json", ProtectedResourceMetadata("http://127.0.0.1:8080", "")) +} + +func TestAuthorizationServerMetadataGolden(t *testing.T) { + golden(t, "authorization_server.json", AuthorizationServerMetadata("http://127.0.0.1:8080")) +} + +func TestChallenge(t *testing.T) { + if got := Challenge("http://127.0.0.1:8080", "cursor"); got != + `Bearer resource_metadata="http://127.0.0.1:8080/.well-known/oauth-protected-resource/mcp/oauth/cursor"` { + t.Fatal(got) + } + if got := Challenge("http://127.0.0.1:8080", ""); got != + `Bearer resource_metadata="http://127.0.0.1:8080/.well-known/oauth-protected-resource/mcp/oauth"` { + t.Fatal(got) + } +} diff --git a/internal/mcplogin/pkce.go b/internal/mcplogin/pkce.go new file mode 100644 index 000000000..f4c3d7d8a --- /dev/null +++ b/internal/mcplogin/pkce.go @@ -0,0 +1,35 @@ +package mcplogin + +import ( + "crypto/sha256" + "crypto/subtle" + "encoding/base64" +) + +// VerifyS256 reports whether challenge is the S256 transform of verifier +// (RFC 7636): the verifier is 43 to 128 characters of the unreserved set and +// the challenge is base64url(sha256(verifier)) without padding. +func VerifyS256(verifier, challenge string) bool { + if len(verifier) < 43 || len(verifier) > 128 { + return false + } + for i := 0; i < len(verifier); i++ { + c := verifier[i] + switch { + case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9', + c == '-', c == '.', c == '_', c == '~': + default: + return false + } + } + if !ValidChallenge(challenge) { + return false + } + sum := sha256.Sum256([]byte(verifier)) + want := base64.RawURLEncoding.EncodeToString(sum[:]) + return subtle.ConstantTimeCompare([]byte(want), []byte(challenge)) == 1 +} + +// ValidChallenge reports whether s is shaped like an S256 challenge: 43 +// base64url characters. +func ValidChallenge(s string) bool { return validBase64URL(s, 43) } diff --git a/internal/mcplogin/pkce_test.go b/internal/mcplogin/pkce_test.go new file mode 100644 index 000000000..15a53d86b --- /dev/null +++ b/internal/mcplogin/pkce_test.go @@ -0,0 +1,70 @@ +package mcplogin + +import ( + "crypto/sha256" + "encoding/base64" + "strings" + "testing" +) + +func challengeOf(v string) string { + sum := sha256.Sum256([]byte(v)) + return base64.RawURLEncoding.EncodeToString(sum[:]) +} + +func TestVerifyS256RFCVector(t *testing.T) { + v := "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk" + c := "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" + if !VerifyS256(v, c) { + t.Fatal("RFC vector must verify") + } + if !ValidChallenge(c) { + t.Fatal("challenge must be valid") + } +} + +func TestVerifyS256Rejects(t *testing.T) { + v := "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk" + c := "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" + if VerifyS256(v+"x", c) { + t.Error("wrong verifier") + } + if VerifyS256(v, c[:42]+"A") { + t.Error("wrong challenge") + } + if VerifyS256(strings.Repeat("a", 42), challengeOf(strings.Repeat("a", 42))) || + VerifyS256(strings.Repeat("a", 129), challengeOf(strings.Repeat("a", 129))) { + t.Error("length bounds") + } + if VerifyS256(v[:42]+"!", challengeOf(v[:42]+"!")) || VerifyS256(v[:42]+" ", challengeOf(v[:42]+" ")) { + t.Error("bad chars") + } + if VerifyS256("", "") { + t.Error("empty") + } +} + +func TestVerifyS256Bounds(t *testing.T) { + for _, n := range []int{43, 128} { + v := strings.Repeat("a", n) + if !VerifyS256(v, challengeOf(v)) { + t.Errorf("length %d should be valid", n) + } + } + v := "a-._~" + strings.Repeat("Z", 40) + if !VerifyS256(v, challengeOf(v)) { + t.Error("unreserved set") + } +} + +func TestValidChallenge(t *testing.T) { + good := strings.Repeat("A", 43) + if !ValidChallenge(good) { + t.Error("good") + } + for _, bad := range []string{"", good[:42], good + "A", good[:42] + "=", good[:42] + "+", good[:42] + "/"} { + if ValidChallenge(bad) { + t.Errorf("%q accepted", bad) + } + } +} diff --git a/internal/mcplogin/redirect.go b/internal/mcplogin/redirect.go new file mode 100644 index 000000000..70d219796 --- /dev/null +++ b/internal/mcplogin/redirect.go @@ -0,0 +1,156 @@ +package mcplogin + +import ( + "errors" + "fmt" + "net/url" + "sort" + "strings" +) + +// MaxRedirectURIs is the most redirect URIs one registration may carry. +const MaxRedirectURIs = 5 + +// ErrRedirectCount is returned when there are no redirect URIs or too many. +var ErrRedirectCount = errors.New("mcplogin: redirect_uris must hold 1 to 5 entries") + +func isLoopbackHost(h string) bool { + return h == "127.0.0.1" || h == "[::1]" || h == "localhost" +} + +// parseRedirect parses one redirect URI and enforces the shape rules shared +// by registration and matching. +func parseRedirect(raw string) (*url.URL, error) { + u, err := url.Parse(raw) + if err != nil { + return nil, fmt.Errorf("redirect uri is not a valid URL") + } + if !u.IsAbs() || u.Opaque != "" { + return nil, fmt.Errorf("redirect uri must be an absolute URL") + } + if u.Fragment != "" || strings.Contains(raw, "#") { + return nil, fmt.Errorf("redirect uri must not have a fragment") + } + if u.User != nil { + return nil, fmt.Errorf("redirect uri must not carry credentials") + } + switch u.Scheme { + case "http": + if !isLoopbackHost(u.Host[:hostEnd(u.Host)]) { + return nil, fmt.Errorf("http redirect uri must use 127.0.0.1, [::1] or localhost") + } + case "https": + if u.Hostname() == "" { + return nil, fmt.Errorf("https redirect uri needs a host") + } + default: + return nil, fmt.Errorf("redirect uri scheme %q is not allowed", u.Scheme) + } + return u, nil +} + +// hostEnd returns the index where the port starts in a host[:port] string +// (len(h) when there is none), understanding bracketed IPv6. +func hostEnd(h string) int { + if strings.HasPrefix(h, "[") { + if i := strings.Index(h, "]"); i >= 0 { + return i + 1 + } + return len(h) + } + if i := strings.LastIndex(h, ":"); i >= 0 { + return i + } + return len(h) +} + +func isLoopbackURL(u *url.URL) bool { + return u.Scheme == "http" && isLoopbackHost(u.Host[:hostEnd(u.Host)]) +} + +// ValidateRegisteredRedirects checks the redirect URIs of a registration: 1 to +// 5 entries, each an absolute URL without fragment or user info, either http +// on 127.0.0.1, [::1] or localhost, or https with a host. Custom schemes are +// refused. +func ValidateRegisteredRedirects(uris []string) error { + if len(uris) < 1 || len(uris) > MaxRedirectURIs { + return ErrRedirectCount + } + for _, raw := range uris { + if _, err := parseRedirect(raw); err != nil { + return err + } + } + return nil +} + +// MatchRedirect finds the registered URI that the presented redirect URI +// stands for. https must match exactly; loopback http matches on scheme, host, +// path and query with the port ignored (RFC 8252 section 7.3). For loopback the +// presented URI is returned, since it names the port the client listens on. +func MatchRedirect(registered []string, presented string) (matched string, ok bool) { + p, err := parseRedirect(presented) + if err != nil { + return "", false + } + for _, reg := range registered { + if p.Scheme == "https" { + if reg == presented { + return presented, true + } + continue + } + r, err := parseRedirect(reg) + if err != nil || !isLoopbackURL(r) { + continue + } + if r.Scheme == p.Scheme && r.Hostname() == p.Hostname() && + r.EscapedPath() == p.EscapedPath() && r.RawQuery == p.RawQuery { + return presented, true + } + } + return "", false +} + +// BuildRedirect parses base, keeps its existing query and appends params +// percent-encoded. The order is deterministic: code, error, error_description +// and iss first, then state, then any other key alphabetically. Which keys are +// present is decided entirely by the map. +func BuildRedirect(base string, params map[string]string) (string, error) { + u, err := url.Parse(base) + if err != nil || !u.IsAbs() { + return "", errors.New("mcplogin: invalid redirect base") + } + order := []string{"code", "error", "error_description", "iss"} + var keys []string + seen := map[string]bool{} + for _, k := range order { + if _, ok := params[k]; ok { + keys = append(keys, k) + seen[k] = true + } + } + var rest []string + for k := range params { + if !seen[k] && k != "state" { + rest = append(rest, k) + } + } + sort.Strings(rest) + keys = append(keys, rest...) + if _, ok := params["state"]; ok { + keys = append(keys, "state") + } + var b strings.Builder + b.WriteString(u.RawQuery) + for _, k := range keys { + if b.Len() > 0 { + b.WriteByte('&') + } + b.WriteString(url.QueryEscape(k)) + b.WriteByte('=') + b.WriteString(url.QueryEscape(params[k])) + } + u.RawQuery = b.String() + return u.String(), nil +} diff --git a/internal/mcplogin/redirect_test.go b/internal/mcplogin/redirect_test.go new file mode 100644 index 000000000..618546a94 --- /dev/null +++ b/internal/mcplogin/redirect_test.go @@ -0,0 +1,105 @@ +package mcplogin + +import ( + "strings" + "testing" +) + +func TestValidateRegisteredRedirects(t *testing.T) { + ok := [][]string{ + {"http://127.0.0.1/cb"}, + {"http://127.0.0.1:8123/cb?x=1"}, + {"http://[::1]:9/cb"}, + {"http://localhost:1/cb"}, + {"https://example.com/cb"}, + {"http://127.0.0.1/a", "https://example.com/b"}, + {"https://a/1", "https://a/2", "https://a/3", "https://a/4", "https://a/5"}, + } + for _, c := range ok { + if err := ValidateRegisteredRedirects(c); err != nil { + t.Errorf("%v: %v", c, err) + } + } + bad := [][]string{ + nil, + {}, + {"https://a/1", "https://a/2", "https://a/3", "https://a/4", "https://a/5", "https://a/6"}, + {"http://example.com/cb"}, + {"http://127.0.0.2/cb"}, + {"http://localhost.evil.com/cb"}, + {"cursor://callback"}, + {"vscode://x/y"}, + {"https://example.com/cb#frag"}, + {"http://127.0.0.1/cb#"}, + {"https://user:pw@example.com/cb"}, + {"https:///cb"}, + {"/relative"}, + {""}, + {"https://example.com/cb", "bad"}, + } + for _, c := range bad { + if err := ValidateRegisteredRedirects(c); err == nil { + t.Errorf("%v accepted", c) + } + } +} + +func TestMatchRedirect(t *testing.T) { + reg := []string{"http://127.0.0.1/cb", "https://app.example.com/cb", "http://localhost/x?y=1", "http://[::1]/v6"} + cases := []struct { + in, want string + ok bool + }{ + {"http://127.0.0.1:54321/cb", "http://127.0.0.1:54321/cb", true}, + {"http://127.0.0.1/cb", "http://127.0.0.1/cb", true}, + {"http://127.0.0.1:54321/other", "", false}, + {"http://localhost:1/x?y=1", "http://localhost:1/x?y=1", true}, + {"http://localhost:1/x?y=2", "", false}, + {"http://localhost:1/x", "", false}, + {"http://[::1]:7/v6", "http://[::1]:7/v6", true}, + {"http://127.0.0.1:1/cb#f", "", false}, + {"https://app.example.com/cb", "https://app.example.com/cb", true}, + {"https://app.example.com:444/cb", "", false}, + {"https://app.example.com/cb/", "", false}, + {"http://app.example.com/cb", "", false}, + {"https://127.0.0.1/cb", "", false}, + {"http://localhost:1/cb", "", false}, + {"", "", false}, + {"garbage", "", false}, + } + for _, c := range cases { + got, ok := MatchRedirect(reg, c.in) + if ok != c.ok || got != c.want { + t.Errorf("%q: got %q %v", c.in, got, ok) + } + } +} + +func TestBuildRedirect(t *testing.T) { + got, err := BuildRedirect("http://127.0.0.1:5/cb?keep=1", map[string]string{"code": "abc", "state": "a b&c=d/é"}) + if err != nil { + t.Fatal(err) + } + want := "http://127.0.0.1:5/cb?keep=1&code=abc&state=a+b%26c%3Dd%2F%C3%A9" + if got != want { + t.Fatalf("got %s want %s", got, want) + } + got, _ = BuildRedirect("https://a/cb", map[string]string{"state": "s", "error": "access_denied"}) + if got != "https://a/cb?error=access_denied&state=s" { + t.Fatalf("order: %s", got) + } + got, _ = BuildRedirect("https://a/cb", map[string]string{"code": "c"}) + if got != "https://a/cb?code=c" { + t.Fatalf("no state: %s", got) + } + got, _ = BuildRedirect("https://a/cb", map[string]string{"code": "c", "state": ""}) + if got != "https://a/cb?code=c&state=" { + t.Fatalf("empty passed key kept: %s", got) + } + if _, err := BuildRedirect("::bad", nil); err == nil { + t.Fatal("bad base") + } + if got, _ := BuildRedirect("https://a/cb", nil); !strings.HasPrefix(got, "https://a/cb") { + t.Fatal(got) + } +} diff --git a/internal/mcplogin/registration.go b/internal/mcplogin/registration.go new file mode 100644 index 000000000..a953669fd --- /dev/null +++ b/internal/mcplogin/registration.go @@ -0,0 +1,123 @@ +package mcplogin + +import ( + "time" + "unicode/utf8" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/clientidentity" +) + +// RFC 7591 error codes used by registration. +const ( + // ErrCodeInvalidRedirectURI is the error code for a refused redirect URI. + ErrCodeInvalidRedirectURI = "invalid_redirect_uri" + // ErrCodeInvalidClientMetadata is the error code for other refused metadata. + ErrCodeInvalidClientMetadata = "invalid_client_metadata" +) + +const ( + maxNameBytes = 128 + maxSoftwareBytes = 64 +) + +// RegistrationRequest is the JSON body of POST /oauth/register. +type RegistrationRequest struct { + RedirectURIs []string `json:"redirect_uris"` + ClientName string `json:"client_name"` + SoftwareID string `json:"software_id"` + SoftwareVersion string `json:"software_version"` + TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"` + GrantTypes []string `json:"grant_types"` + ResponseTypes []string `json:"response_types"` +} + +// Registration is a validated registration with its effective values. The +// caller assigns ClientID (see NewClientID) before storing or answering. +type Registration struct { + ClientID string + RedirectURIs []string + ClientName string + SoftwareID string + SoftwareVersion string + TokenEndpointAuthMethod string + GrantTypes []string + ResponseTypes []string +} + +// RegError is a registration refusal, shaped for an RFC 7591 error answer. +type RegError struct { + // Code is ErrCodeInvalidRedirectURI or ErrCodeInvalidClientMetadata. + Code string + // Description is a human-readable reason. + Description string +} + +// Error implements error. +func (e *RegError) Error() string { return e.Code + ": " + e.Description } + +// truncateUTF8 cuts s to at most max bytes without splitting a character. +func truncateUTF8(s string, max int) string { + if len(s) <= max { + return s + } + s = s[:max] + for len(s) > 0 && !utf8.ValidString(s) { + s = s[:len(s)-1] + } + return s +} + +func sanitize(s string, max int) string { + return truncateUTF8(clientidentity.SanitizeDisplay(s), max) +} + +// ValidateRegistration checks a request and returns the registration with the +// effective values: method "none", grants authorization_code and +// refresh_token, response type code. A request that asks for anything else is +// refused rather than silently changed. +func ValidateRegistration(req RegistrationRequest) (Registration, *RegError) { + if err := ValidateRegisteredRedirects(req.RedirectURIs); err != nil { + return Registration{}, &RegError{Code: ErrCodeInvalidRedirectURI, Description: err.Error()} + } + if m := req.TokenEndpointAuthMethod; m != "" && m != "none" { + return Registration{}, &RegError{Code: ErrCodeInvalidClientMetadata, + Description: "only token_endpoint_auth_method \"none\" is supported"} + } + for _, g := range req.GrantTypes { + if g != "authorization_code" && g != "refresh_token" { + return Registration{}, &RegError{Code: ErrCodeInvalidClientMetadata, + Description: "only the authorization_code and refresh_token grant types are supported"} + } + } + for _, r := range req.ResponseTypes { + if r != "code" { + return Registration{}, &RegError{Code: ErrCodeInvalidClientMetadata, + Description: "only the code response type is supported"} + } + } + return Registration{ + RedirectURIs: append([]string(nil), req.RedirectURIs...), + ClientName: sanitize(req.ClientName, maxNameBytes), + SoftwareID: sanitize(req.SoftwareID, maxSoftwareBytes), + SoftwareVersion: sanitize(req.SoftwareVersion, maxSoftwareBytes), + TokenEndpointAuthMethod: "none", + GrantTypes: []string{"authorization_code", "refresh_token"}, + ResponseTypes: []string{"code"}, + }, nil +} + +// NewClientID returns a fresh registration client id: 22 base62 characters. +func NewClientID() (string, error) { return randomBase62(22) } + +// Response is the RFC 7591 201 body. It never carries a client_secret. +func (r Registration) Response(issuedAt time.Time) map[string]any { + return map[string]any{ + "client_id": r.ClientID, + "client_id_issued_at": issuedAt.Unix(), + "redirect_uris": r.RedirectURIs, + "client_name": r.ClientName, + "token_endpoint_auth_method": r.TokenEndpointAuthMethod, + "grant_types": r.GrantTypes, + "response_types": r.ResponseTypes, + } +} diff --git a/internal/mcplogin/registration_test.go b/internal/mcplogin/registration_test.go new file mode 100644 index 000000000..096342e6b --- /dev/null +++ b/internal/mcplogin/registration_test.go @@ -0,0 +1,103 @@ +package mcplogin + +import ( + "strings" + "testing" + "time" +) + +func TestValidateRegistrationOK(t *testing.T) { + reg, rerr := ValidateRegistration(RegistrationRequest{ + RedirectURIs: []string{"http://127.0.0.1:1/cb"}, + ClientName: " My\x07 Client ", + SoftwareID: "sw", SoftwareVersion: "1.0", + TokenEndpointAuthMethod: "none", + GrantTypes: []string{"refresh_token", "authorization_code"}, + ResponseTypes: []string{"code"}, + }) + if rerr != nil { + t.Fatal(rerr) + } + if reg.ClientName != "my client" || reg.TokenEndpointAuthMethod != "none" || + len(reg.GrantTypes) != 2 || reg.GrantTypes[0] != "authorization_code" || + len(reg.ResponseTypes) != 1 || reg.ResponseTypes[0] != "code" { + t.Fatalf("%+v", reg) + } + if _, rerr := ValidateRegistration(RegistrationRequest{RedirectURIs: []string{"https://a/cb"}}); rerr != nil { + t.Fatal(rerr) + } +} + +func TestValidateRegistrationRefusals(t *testing.T) { + base := func() RegistrationRequest { return RegistrationRequest{RedirectURIs: []string{"https://a/cb"}} } + type tc struct { + mod func(*RegistrationRequest) + code string + } + cases := map[string]tc{ + "no redirects": {func(r *RegistrationRequest) { r.RedirectURIs = nil }, ErrCodeInvalidRedirectURI}, + "fragment": {func(r *RegistrationRequest) { r.RedirectURIs = []string{"https://a/cb#x"} }, ErrCodeInvalidRedirectURI}, + "http non-loop": {func(r *RegistrationRequest) { r.RedirectURIs = []string{"http://a/cb"} }, ErrCodeInvalidRedirectURI}, + "custom scheme": {func(r *RegistrationRequest) { r.RedirectURIs = []string{"x://cb"} }, ErrCodeInvalidRedirectURI}, + "secret basic": {func(r *RegistrationRequest) { r.TokenEndpointAuthMethod = "client_secret_basic" }, ErrCodeInvalidClientMetadata}, + "secret post": {func(r *RegistrationRequest) { r.TokenEndpointAuthMethod = "client_secret_post" }, ErrCodeInvalidClientMetadata}, + "implicit grant": {func(r *RegistrationRequest) { r.GrantTypes = []string{"implicit"} }, ErrCodeInvalidClientMetadata}, + "client creds": {func(r *RegistrationRequest) { + r.GrantTypes = []string{"authorization_code", "client_credentials"} + }, ErrCodeInvalidClientMetadata}, + "token response": {func(r *RegistrationRequest) { r.ResponseTypes = []string{"token"} }, ErrCodeInvalidClientMetadata}, + "code+token": {func(r *RegistrationRequest) { r.ResponseTypes = []string{"code", "token"} }, ErrCodeInvalidClientMetadata}, + } + for name, c := range cases { + r := base() + c.mod(&r) + _, rerr := ValidateRegistration(r) + if rerr == nil || rerr.Code != c.code || rerr.Description == "" { + t.Errorf("%s: %+v", name, rerr) + } + } +} + +func TestValidateRegistrationCaps(t *testing.T) { + r := RegistrationRequest{ + RedirectURIs: []string{"https://a/cb"}, ClientName: strings.Repeat("é", 200), + SoftwareID: strings.Repeat("s", 200), SoftwareVersion: strings.Repeat("v", 200), + } + reg, rerr := ValidateRegistration(r) + if rerr != nil { + t.Fatal(rerr) + } + if len(reg.ClientName) > 128 || len(reg.SoftwareID) > 64 || len(reg.SoftwareVersion) > 64 { + t.Fatalf("caps: %d %d %d", len(reg.ClientName), len(reg.SoftwareID), len(reg.SoftwareVersion)) + } + if !strings.HasPrefix(reg.ClientName, "é") || strings.ContainsRune(reg.ClientName, '\uFFFD') { + t.Fatal("truncation must keep valid utf-8") + } +} + +func TestNewClientID(t *testing.T) { + a, err := NewClientID() + if err != nil || len(a) != 22 { + t.Fatalf("%q %v", a, err) + } + b, _ := NewClientID() + if a == b { + t.Fatal("same id") + } +} + +func TestRegistrationResponse(t *testing.T) { + reg, _ := ValidateRegistration(RegistrationRequest{RedirectURIs: []string{"https://a/cb"}, ClientName: "X"}) + reg.ClientID = "abc" + m := reg.Response(time.Unix(1700000000, 0)) + if m["client_id"] != "abc" || m["client_id_issued_at"] != int64(1700000000) || + m["token_endpoint_auth_method"] != "none" || m["client_name"] != "x" { + t.Fatalf("%v", m) + } + if _, has := m["client_secret"]; has { + t.Fatal("client_secret present") + } + if uris, _ := m["redirect_uris"].([]string); len(uris) != 1 { + t.Fatalf("%v", m["redirect_uris"]) + } +} diff --git a/internal/mcplogin/requests.go b/internal/mcplogin/requests.go new file mode 100644 index 000000000..ded4f94c0 --- /dev/null +++ b/internal/mcplogin/requests.go @@ -0,0 +1,337 @@ +package mcplogin + +import ( + "errors" + "sort" + "sync" + "time" +) + +// Lifetimes of the in-memory login state. +const ( + // RequestLifetime is how long an authorization request lives. + RequestLifetime = 10 * time.Minute + // CodeLifetime is how long an authorization code is usable. + CodeLifetime = 60 * time.Second + // TombstoneLifetime is how long a consumed code is remembered so that a + // second presentation can be told from an unknown code. + TombstoneLifetime = 10 * time.Minute +) + +// Errors returned by Store. +var ( + // ErrTooManyPending means MaxPendingRequests requests are already pending. + ErrTooManyPending = errors.New("mcplogin: too many pending authorization requests") + // ErrRequestNotFound means the request does not exist or has expired. + ErrRequestNotFound = errors.New("mcplogin: authorization request not found") + // ErrAlreadyDecided means the request left the pending state already. + ErrAlreadyDecided = errors.New("mcplogin: authorization request already decided") + // ErrCodeUnknown means the code is unknown, expired, cancelled or burned. + ErrCodeUnknown = errors.New("mcplogin: authorization code unknown") + // ErrCodeReused means a consumed code was presented again inside the + // tombstone window. Consume returns the grant id it produced. + ErrCodeReused = errors.New("mcplogin: authorization code already used") +) + +// Status is the state of an authorization request. +type Status string + +// Request states. A request is decided once: pending moves to approved or +// denied, and an approved request can still become cancelled until its code is +// consumed. Consumed is the final state of a request whose code was exchanged. +const ( + // StatusPending awaits the administrator's decision. + StatusPending Status = "pending" + // StatusApproved has a code issued and not yet exchanged. + StatusApproved Status = "approved" + // StatusDenied was refused by the administrator. + StatusDenied Status = "denied" + // StatusExpired ran out of time. + StatusExpired Status = "expired" + // StatusCancelled was withdrawn (client revoked or forgotten, feature off). + StatusCancelled Status = "cancelled" + // StatusConsumed had its code exchanged. + StatusConsumed Status = "consumed" +) + +// Decision is what the administrator chose when approving a request. +type Decision struct { + // ClientID is the client hub id the login is for. + ClientID string + // NewClient is true when approval creates the client. + NewClient bool + // DisplayName is the display name of a new client. + DisplayName string + // Profile is the profile the client is bound to. + Profile string + // Mode is the binding mode. + Mode string + // BindingRevision is the binding revision the consent page displayed. + BindingRevision string + // ReplaceGrantID is the earlier login to revoke on success, if any. + ReplaceGrantID string + // ActorKind and ActorName identify the approving administrator. + ActorKind string + ActorName string +} + +// Request is one authorization request, kept in memory only. +type Request struct { + ID string + RegistrationID string + RedirectURI string + State string + CodeChallenge string + Resource string + Issuer string + // PathClient is the client id from the resource path, empty for the + // generic address. + PathClient string + Status Status + Decision Decision + CreatedAt time.Time + ExpiresAt time.Time +} + +type codeEntry struct { + requestID string + expiresAt time.Time + consumed bool + consumedAt time.Time + grantID string // empty when the commit failed +} + +// Store holds authorization requests and their codes. It is safe for +// concurrent use; one mutex guards everything and nothing blocks under it +// except the commit callback of Consume, which is its single-use boundary. +type Store struct { + key []byte + now func() time.Time + mu sync.Mutex + reqs map[string]*Request + codes map[string]*codeEntry // keyed by HashSecret(kind code) +} + +// NewStore returns an empty Store. key hashes codes; now is the clock (nil +// means time.Now). +func NewStore(key []byte, now func() time.Time) *Store { + if now == nil { + now = time.Now + } + return &Store{key: key, now: now, reqs: map[string]*Request{}, codes: map[string]*codeEntry{}} +} + +// live returns the request with lazy expiry applied. Caller holds s.mu. +func (s *Store) live(id string) *Request { + r := s.reqs[id] + if r == nil { + return nil + } + if (r.Status == StatusPending || r.Status == StatusApproved) && !s.now().Before(r.ExpiresAt) { + r.Status = StatusExpired + } + if r.Status == StatusExpired { + return nil + } + return r +} + +func (s *Store) pendingCountLocked() int { + n := 0 + for id := range s.reqs { + if r := s.live(id); r != nil && r.Status == StatusPending { + n++ + } + } + return n +} + +// Create stores a new pending request built from req (ID, Status, CreatedAt +// and ExpiresAt are assigned here). It fails with ErrTooManyPending at the cap. +func (s *Store) Create(req Request) (Request, error) { + id, err := randomBase62(22) + if err != nil { + return Request{}, err + } + s.mu.Lock() + defer s.mu.Unlock() + if s.pendingCountLocked() >= MaxPendingRequests { + return Request{}, ErrTooManyPending + } + now := s.now() + req.ID = id + req.Status = StatusPending + req.Decision = Decision{} + req.CreatedAt = now + req.ExpiresAt = now.Add(RequestLifetime) + s.reqs[id] = &req + return req, nil +} + +// Get returns a copy of the request. An expired request reads as not found. +func (s *Store) Get(id string) (Request, bool) { + s.mu.Lock() + defer s.mu.Unlock() + r := s.live(id) + if r == nil { + return Request{}, false + } + return *r, true +} + +// ListPending returns the pending requests, oldest first. +func (s *Store) ListPending() []Request { + s.mu.Lock() + defer s.mu.Unlock() + var out []Request + for id := range s.reqs { + if r := s.live(id); r != nil && r.Status == StatusPending { + out = append(out, *r) + } + } + sort.Slice(out, func(i, j int) bool { + if out[i].CreatedAt.Equal(out[j].CreatedAt) { + return out[i].ID < out[j].ID + } + return out[i].CreatedAt.Before(out[j].CreatedAt) + }) + return out +} + +// Approve moves a pending request to approved, records the decision and +// returns the single-use code (valid CodeLifetime). A request that is no +// longer pending gives ErrAlreadyDecided. +func (s *Store) Approve(id string, d Decision) (string, error) { + code, err := randomSecret() + if err != nil { + return "", err + } + s.mu.Lock() + defer s.mu.Unlock() + r := s.live(id) + if r == nil { + return "", ErrRequestNotFound + } + if r.Status != StatusPending { + return "", ErrAlreadyDecided + } + r.Status = StatusApproved + r.Decision = d + s.codes[HashSecret(s.key, KindCode, code)] = &codeEntry{requestID: id, expiresAt: s.now().Add(CodeLifetime)} + return code, nil +} + +// Deny moves a pending request to denied. +func (s *Store) Deny(id string) error { + s.mu.Lock() + defer s.mu.Unlock() + r := s.live(id) + if r == nil { + return ErrRequestNotFound + } + if r.Status != StatusPending { + return ErrAlreadyDecided + } + r.Status = StatusDenied + return nil +} + +func (s *Store) cancelWhere(match func(*Request) bool) int { + n := 0 + for id := range s.reqs { + r := s.live(id) + if r == nil || (r.Status != StatusPending && r.Status != StatusApproved) { + continue + } + if match(r) { + r.Status = StatusCancelled + n++ + } + } + return n +} + +// CancelForClient cancels the pending and approved-but-unconsumed requests +// whose path client or decided client is clientID. Their codes become unusable. +func (s *Store) CancelForClient(clientID string) int { + s.mu.Lock() + defer s.mu.Unlock() + return s.cancelWhere(func(r *Request) bool { + return r.PathClient == clientID || (r.Status == StatusApproved && r.Decision.ClientID == clientID) + }) +} + +// CancelAll cancels every pending and approved-but-unconsumed request. +func (s *Store) CancelAll() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.cancelWhere(func(*Request) bool { return true }) +} + +// Consume exchanges a code. Under the store lock it checks that the code is +// known, unexpired, unconsumed and that its request is still approved, then +// calls commit with a copy of the request. On success the request is consumed +// and a tombstone {consumed_at, grant_id} is kept for TombstoneLifetime. If +// commit fails the code is burned too (single use) and the error is returned. +// Presenting a consumed code again inside the tombstone window returns +// ErrCodeReused together with the grant id it produced; afterwards the code is +// unknown. +func (s *Store) Consume(code string, commit func(Request) (grantID string, err error)) (Request, string, error) { + h := HashSecret(s.key, KindCode, code) + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + e := s.codes[h] + if e == nil { + return Request{}, "", ErrCodeUnknown + } + if e.consumed { + if now.Before(e.consumedAt.Add(TombstoneLifetime)) { + if e.grantID == "" { + return Request{}, "", ErrCodeUnknown + } + return Request{}, e.grantID, ErrCodeReused + } + delete(s.codes, h) + return Request{}, "", ErrCodeUnknown + } + if !now.Before(e.expiresAt) { + delete(s.codes, h) + return Request{}, "", ErrCodeUnknown + } + r := s.live(e.requestID) + if r == nil || r.Status != StatusApproved { + delete(s.codes, h) + return Request{}, "", ErrCodeUnknown + } + e.consumed = true + e.consumedAt = now + r.Status = StatusConsumed + grantID, err := commit(*r) + if err != nil { + return Request{}, "", err + } + e.grantID = grantID + return *r, grantID, nil +} + +// Sweep removes expired requests and codes and tombstones past their window. +func (s *Store) Sweep() { + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + for id, r := range s.reqs { + if !now.Before(r.ExpiresAt) { + delete(s.reqs, id) + } + } + for h, e := range s.codes { + if e.consumed { + if !now.Before(e.consumedAt.Add(TombstoneLifetime)) { + delete(s.codes, h) + } + } else if !now.Before(e.expiresAt) { + delete(s.codes, h) + } + } +} diff --git a/internal/mcplogin/requests_test.go b/internal/mcplogin/requests_test.go new file mode 100644 index 000000000..413c14c6b --- /dev/null +++ b/internal/mcplogin/requests_test.go @@ -0,0 +1,259 @@ +package mcplogin + +import ( + "errors" + "sync" + "sync/atomic" + "testing" + "time" +) + +func newTestStore() (*Store, *fakeClock) { + clk := &fakeClock{t: time.Unix(1000, 0)} + return NewStore(testKey, clk.now), clk +} + +func (s *Store) size() int { + s.mu.Lock() + defer s.mu.Unlock() + return len(s.reqs) + len(s.codes) +} + +func mkReq(pathClient string) Request { + return Request{RegistrationID: "reg1", RedirectURI: "http://127.0.0.1:1/cb", State: "st", + CodeChallenge: "ch", Resource: "http://127.0.0.1:8080/mcp/oauth", Issuer: "http://127.0.0.1:8080", PathClient: pathClient} +} + +func mustCreate(t *testing.T, s *Store, pc string) Request { + t.Helper() + r, err := s.Create(mkReq(pc)) + if err != nil { + t.Fatal(err) + } + return r +} + +func TestCreateGetList(t *testing.T) { + s, clk := newTestStore() + r := mustCreate(t, s, "") + if len(r.ID) != 22 || r.Status != StatusPending || !r.ExpiresAt.Equal(clk.now().Add(RequestLifetime)) { + t.Fatalf("%+v", r) + } + g, ok := s.Get(r.ID) + if !ok || g.ID != r.ID { + t.Fatal("get") + } + if len(s.ListPending()) != 1 { + t.Fatal("list") + } + clk.advance(RequestLifetime) + if _, ok := s.Get(r.ID); ok { + t.Fatal("expired must read as not found") + } + if len(s.ListPending()) != 0 { + t.Fatal("expired listed") + } + if _, err := s.Approve(r.ID, Decision{ClientID: "c"}); !errors.Is(err, ErrRequestNotFound) { + t.Fatalf("approve expired: %v", err) + } +} + +func TestCap(t *testing.T) { + s, _ := newTestStore() + for i := 0; i < MaxPendingRequests; i++ { + mustCreate(t, s, "") + } + if _, err := s.Create(mkReq("")); !errors.Is(err, ErrTooManyPending) { + t.Fatalf("%v", err) + } +} + +func TestCapIgnoresDecided(t *testing.T) { + s, _ := newTestStore() + var first Request + for i := 0; i < MaxPendingRequests; i++ { + r := mustCreate(t, s, "") + if i == 0 { + first = r + } + } + if err := s.Deny(first.ID); err != nil { + t.Fatal(err) + } + if _, err := s.Create(mkReq("")); err != nil { + t.Fatalf("slot should be free: %v", err) + } +} + +func TestDecidedOnceRace(t *testing.T) { + s, _ := newTestStore() + r := mustCreate(t, s, "") + var wins, losses int32 + var wg sync.WaitGroup + for i := 0; i < 16; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + var err error + if i%2 == 0 { + _, err = s.Approve(r.ID, Decision{ClientID: "c"}) + } else { + err = s.Deny(r.ID) + } + if err == nil { + atomic.AddInt32(&wins, 1) + } else if errors.Is(err, ErrAlreadyDecided) { + atomic.AddInt32(&losses, 1) + } else { + t.Errorf("unexpected %v", err) + } + }(i) + } + wg.Wait() + if wins != 1 || losses != 15 { + t.Fatalf("wins %d losses %d", wins, losses) + } +} + +func TestApproveConsumeHappyPath(t *testing.T) { + s, _ := newTestStore() + r := mustCreate(t, s, "cursor") + code, err := s.Approve(r.ID, Decision{ClientID: "cursor", ActorKind: "admin", ActorName: "a"}) + if err != nil || code == "" { + t.Fatal(err) + } + g, _ := s.Get(r.ID) + if g.Status != StatusApproved || g.Decision.ClientID != "cursor" { + t.Fatalf("%+v", g) + } + if _, err := s.Approve(r.ID, Decision{}); !errors.Is(err, ErrAlreadyDecided) { + t.Fatal(err) + } + if err := s.Deny(r.ID); !errors.Is(err, ErrAlreadyDecided) { + t.Fatal(err) + } + var seen Request + got, gid, err := s.Consume(code, func(q Request) (string, error) { seen = q; return "grant1", nil }) + if err != nil || gid != "grant1" || got.ID != r.ID || seen.Decision.ClientID != "cursor" { + t.Fatalf("%+v %q %v", got, gid, err) + } + if g, _ := s.Get(r.ID); g.Status != StatusConsumed { + t.Fatalf("status %s", g.Status) + } +} + +func TestConsumeReuse(t *testing.T) { + s, clk := newTestStore() + r := mustCreate(t, s, "") + code, _ := s.Approve(r.ID, Decision{ClientID: "c"}) + calls := 0 + commit := func(Request) (string, error) { calls++; return "g1", nil } + if _, _, err := s.Consume(code, commit); err != nil { + t.Fatal(err) + } + clk.advance(5 * time.Minute) + _, gid, err := s.Consume(code, commit) + if !errors.Is(err, ErrCodeReused) || gid != "g1" || calls != 1 { + t.Fatalf("%v %q %d", err, gid, calls) + } + clk.advance(6 * time.Minute) + if _, gid, err := s.Consume(code, commit); !errors.Is(err, ErrCodeUnknown) || gid != "" { + t.Fatalf("%v %q", err, gid) + } +} + +func TestConsumeExpiryAndUnknown(t *testing.T) { + s, clk := newTestStore() + r := mustCreate(t, s, "") + code, _ := s.Approve(r.ID, Decision{ClientID: "c"}) + if _, _, err := s.Consume("nope", nil); !errors.Is(err, ErrCodeUnknown) { + t.Fatal(err) + } + clk.advance(CodeLifetime) + called := false + if _, _, err := s.Consume(code, func(Request) (string, error) { called = true; return "g", nil }); !errors.Is(err, ErrCodeUnknown) || called { + t.Fatalf("%v %v", err, called) + } +} + +func TestConsumeCommitErrorBurnsCode(t *testing.T) { + s, _ := newTestStore() + r := mustCreate(t, s, "") + code, _ := s.Approve(r.ID, Decision{ClientID: "c"}) + boom := errors.New("boom") + if _, _, err := s.Consume(code, func(Request) (string, error) { return "", boom }); !errors.Is(err, boom) { + t.Fatal(err) + } + called := false + _, gid, err := s.Consume(code, func(Request) (string, error) { called = true; return "g", nil }) + if called || gid != "" || !errors.Is(err, ErrCodeUnknown) { + t.Fatalf("code reusable after failed commit: %v %q %v", err, gid, called) + } +} + +func TestCancelForClient(t *testing.T) { + s, _ := newTestStore() + pathReq := mustCreate(t, s, "cursor") + decided := mustCreate(t, s, "") + code, _ := s.Approve(decided.ID, Decision{ClientID: "cursor"}) + other := mustCreate(t, s, "other") + if n := s.CancelForClient("cursor"); n != 2 { + t.Fatalf("cancelled %d", n) + } + if g, _ := s.Get(pathReq.ID); g.Status != StatusCancelled { + t.Fatal("path req") + } + if g, _ := s.Get(decided.ID); g.Status != StatusCancelled { + t.Fatal("decided req") + } + if g, _ := s.Get(other.ID); g.Status != StatusPending { + t.Fatal("other touched") + } + called := false + if _, _, err := s.Consume(code, func(Request) (string, error) { called = true; return "g", nil }); !errors.Is(err, ErrCodeUnknown) || called { + t.Fatalf("cancelled code usable: %v", err) + } + if _, err := s.Approve(pathReq.ID, Decision{ClientID: "x"}); !errors.Is(err, ErrAlreadyDecided) { + t.Fatalf("approve cancelled: %v", err) + } +} + +func TestCancelAllAndAfterConsume(t *testing.T) { + s, _ := newTestStore() + a := mustCreate(t, s, "") + b := mustCreate(t, s, "x") + code, _ := s.Approve(b.ID, Decision{ClientID: "x"}) + consumedReq := mustCreate(t, s, "") + c2, _ := s.Approve(consumedReq.ID, Decision{ClientID: "y"}) + if _, _, err := s.Consume(c2, func(Request) (string, error) { return "g", nil }); err != nil { + t.Fatal(err) + } + if n := s.CancelAll(); n != 2 { + t.Fatalf("cancelled %d", n) + } + if g, _ := s.Get(a.ID); g.Status != StatusCancelled { + t.Fatal("a") + } + if _, _, err := s.Consume(code, func(Request) (string, error) { return "g", nil }); !errors.Is(err, ErrCodeUnknown) { + t.Fatal(err) + } + if _, gid, err := s.Consume(c2, nil); !errors.Is(err, ErrCodeReused) || gid != "g" { + t.Fatalf("%v %q", err, gid) + } + if n := s.CancelForClient("y"); n != 0 { + t.Fatalf("consumed request must not be cancelled: %d", n) + } +} + +func TestSweep(t *testing.T) { + s, clk := newTestStore() + mustCreate(t, s, "") + r := mustCreate(t, s, "") + code, _ := s.Approve(r.ID, Decision{ClientID: "c"}) + _, _, _ = s.Consume(code, func(Request) (string, error) { return "g", nil }) + clk.advance(RequestLifetime + TombstoneLifetime) + s.Sweep() + if n := s.size(); n != 0 { + t.Fatalf("left %d entries", n) + } +} diff --git a/internal/mcplogin/resource.go b/internal/mcplogin/resource.go new file mode 100644 index 000000000..d10ae2bb7 --- /dev/null +++ b/internal/mcplogin/resource.go @@ -0,0 +1,65 @@ +package mcplogin + +import ( + "net/http" + "net/url" + "strings" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// resourceBase is the path of the generic OAuth-protected MCP endpoint. +const resourceBase = "/mcp/oauth" + +// Origin returns "scheme://host" for the request: https when the connection is +// TLS, else http; the host is r.Host lowercased and otherwise verbatim. It is +// used as the issuer and as the resource prefix, so "localhost" and +// "127.0.0.1" are different origins by design. +func Origin(r *http.Request) string { + scheme := "http" + if r.TLS != nil { + scheme = "https" + } + return scheme + "://" + strings.ToLower(r.Host) +} + +// ResourcePath returns "/mcp/oauth" for an empty client id, else +// "/mcp/oauth/". +func ResourcePath(clientID string) string { + if clientID == "" { + return resourceBase + } + return resourceBase + "/" + clientID +} + +// ParseResourcePath accepts exactly /mcp/oauth, /mcp/oauth/, /mcp/oauth/ +// and /mcp/oauth// where id passes auth.ValidClientID. Nothing deeper. +func ParseResourcePath(path string) (clientID string, generic, ok bool) { + if path == resourceBase || path == resourceBase+"/" { + return "", true, true + } + rest, found := strings.CutPrefix(path, resourceBase+"/") + if !found { + return "", false, false + } + rest = strings.TrimSuffix(rest, "/") + if !auth.ValidClientID(rest) { + return "", false, false + } + return rest, false, true +} + +// ParseResource checks that resource is a URL on exactly the given origin with +// an OAuth resource path, no query and no fragment. +func ParseResource(origin, resource string) (clientID string, generic, ok bool) { + rest, found := strings.CutPrefix(resource, origin) + if !found || !strings.HasPrefix(rest, "/") { + return "", false, false + } + u, err := url.Parse(resource) + if err != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || + strings.ContainsAny(resource, "?#") || u.User != nil { + return "", false, false + } + return ParseResourcePath(rest) +} diff --git a/internal/mcplogin/resource_test.go b/internal/mcplogin/resource_test.go new file mode 100644 index 000000000..7e8a342fe --- /dev/null +++ b/internal/mcplogin/resource_test.go @@ -0,0 +1,84 @@ +package mcplogin + +import ( + "crypto/tls" + "net/http" + "net/http/httptest" + "testing" +) + +type resCase struct { + id string + generic bool + ok bool +} + +func TestOrigin(t *testing.T) { + r := httptest.NewRequest("GET", "/x", nil) + r.Host = "127.0.0.1:8080" + if Origin(r) != "http://127.0.0.1:8080" { + t.Fatal(Origin(r)) + } + r.TLS = &tls.ConnectionState{} + r.Host = "LocalHost:8443" + if Origin(r) != "https://localhost:8443" { + t.Fatal(Origin(r)) + } + if Origin(&http.Request{Host: "a"}) != "http://a" { + t.Fatal("plain request") + } +} + +func TestResourcePath(t *testing.T) { + if ResourcePath("") != "/mcp/oauth" || ResourcePath("cursor") != "/mcp/oauth/cursor" { + t.Fatal("ResourcePath") + } +} + +func TestParseResourcePath(t *testing.T) { + cases := map[string]resCase{ + "/mcp/oauth": {"", true, true}, + "/mcp/oauth/": {"", true, true}, + "/mcp/oauth/cursor": {"cursor", false, true}, + "/mcp/oauth/cursor/": {"cursor", false, true}, + "/mcp/oauth/cursor/x": {}, + "/mcp/oauth//": {}, + "/mcp/oauth/Bad": {}, + "/mcp/oauth/-x": {}, + "/mcp/oauthx": {}, + "/mcp": {}, + "/mcp/oauth/a/b/c": {}, + "": {}, + } + for p, want := range cases { + id, gen, ok := ParseResourcePath(p) + if (resCase{id, gen, ok}) != want { + t.Errorf("%q: got %q %v %v", p, id, gen, ok) + } + } +} + +func TestParseResource(t *testing.T) { + o := "http://127.0.0.1:8080" + cases := map[string]resCase{ + o + "/mcp/oauth": {"", true, true}, + o + "/mcp/oauth/cursor": {"cursor", false, true}, + o + "/mcp/oauth/cursor/": {"cursor", false, true}, + "http://localhost:8080/mcp/oauth": {}, + "https://127.0.0.1:8080/mcp/oauth": {}, + o + "/mcp/oauth?x=1": {}, + o + "/mcp/oauth?": {}, + o + "/mcp/oauth#f": {}, + o + "/mcp/oauth/cursor/x": {}, + o + "/mcp": {}, + "/mcp/oauth": {}, + "::bad": {}, + "": {}, + } + for in, want := range cases { + id, gen, ok := ParseResource(o, in) + if (resCase{id, gen, ok}) != want { + t.Errorf("%q: got %q %v %v", in, id, gen, ok) + } + } +} diff --git a/internal/mcplogin/testdata/authorization_server.json b/internal/mcplogin/testdata/authorization_server.json new file mode 100644 index 000000000..0d7159f69 --- /dev/null +++ b/internal/mcplogin/testdata/authorization_server.json @@ -0,0 +1,19 @@ +{ + "authorization_endpoint": "http://127.0.0.1:8080/oauth/authorize", + "code_challenge_methods_supported": [ + "S256" + ], + "grant_types_supported": [ + "authorization_code", + "refresh_token" + ], + "issuer": "http://127.0.0.1:8080", + "registration_endpoint": "http://127.0.0.1:8080/oauth/register", + "response_types_supported": [ + "code" + ], + "token_endpoint": "http://127.0.0.1:8080/oauth/token", + "token_endpoint_auth_methods_supported": [ + "none" + ] +} diff --git a/internal/mcplogin/testdata/protected_resource_client.json b/internal/mcplogin/testdata/protected_resource_client.json new file mode 100644 index 000000000..85aa69f6f --- /dev/null +++ b/internal/mcplogin/testdata/protected_resource_client.json @@ -0,0 +1,9 @@ +{ + "authorization_servers": [ + "http://127.0.0.1:8080" + ], + "bearer_methods_supported": [ + "header" + ], + "resource": "http://127.0.0.1:8080/mcp/oauth/cursor" +} diff --git a/internal/mcplogin/testdata/protected_resource_generic.json b/internal/mcplogin/testdata/protected_resource_generic.json new file mode 100644 index 000000000..c951da24d --- /dev/null +++ b/internal/mcplogin/testdata/protected_resource_generic.json @@ -0,0 +1,9 @@ +{ + "authorization_servers": [ + "http://127.0.0.1:8080" + ], + "bearer_methods_supported": [ + "header" + ], + "resource": "http://127.0.0.1:8080/mcp/oauth" +} diff --git a/internal/mcplogin/token.go b/internal/mcplogin/token.go new file mode 100644 index 000000000..dca8dbbc3 --- /dev/null +++ b/internal/mcplogin/token.go @@ -0,0 +1,200 @@ +package mcplogin + +import ( + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "encoding/hex" + "errors" + "strings" +) + +const ( + // AccessTokenPrefix starts every browser-login access token. + AccessTokenPrefix = "mcp_oat_" + // RefreshTokenPrefix starts every browser-login refresh token. + RefreshTokenPrefix = "mcp_ort_" + + // GrantIDLen is the length of a grant id (base62 characters). + GrantIDLen = 22 + + secretLen = 43 // 32 random bytes, base64url without padding + macLen = 22 // 16 bytes, base64url without padding + macBytes = 16 + prefixShow = 12 + + base62Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +) + +// Hash kinds for HashSecret. Each has its own label, so a hash made for one +// kind can never equal a hash made for another. +const ( + // KindAccess labels hashes of access tokens. + KindAccess = "access" + // KindRefresh labels hashes of refresh-token secrets. + KindRefresh = "refresh" + // KindCode labels hashes of authorization codes. + KindCode = "code" +) + +// ErrBadKey is returned when a token key is empty. +var ErrBadKey = errors.New("mcplogin: token key is empty") + +// ErrBadGrantID is returned when a grant id is not GrantIDLen base62 characters. +var ErrBadGrantID = errors.New("mcplogin: malformed grant id") + +// randomBytes reads n bytes from crypto/rand. +func randomBytes(n int) ([]byte, error) { + b := make([]byte, n) + if _, err := rand.Read(b); err != nil { + return nil, err + } + return b, nil +} + +// randomBase62 returns n unbiased random base62 characters. Bytes at or above +// 248 (the largest multiple of 62 that fits in a byte) are rejected. +func randomBase62(n int) (string, error) { + out := make([]byte, 0, n) + buf := make([]byte, n+n/2+8) + for len(out) < n { + if _, err := rand.Read(buf); err != nil { + return "", err + } + for _, c := range buf { + if c >= 248 { + continue + } + out = append(out, base62Alphabet[int(c)%62]) + if len(out) == n { + break + } + } + } + return string(out), nil +} + +func randomSecret() (string, error) { + b, err := randomBytes(32) + if err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(b), nil +} + +// NewAccessToken returns a fresh access token: "mcp_oat_" plus 43 base64url +// characters (32 random bytes). +func NewAccessToken() (string, error) { + s, err := randomSecret() + if err != nil { + return "", err + } + return AccessTokenPrefix + s, nil +} + +// NewGrantID returns a fresh grant id of GrantIDLen base62 characters. +func NewGrantID() (string, error) { return randomBase62(GrantIDLen) } + +func validBase62(s string, n int) bool { + if len(s) != n { + return false + } + for i := 0; i < len(s); i++ { + if strings.IndexByte(base62Alphabet, s[i]) < 0 { + return false + } + } + return true +} + +func validBase64URL(s string, n int) bool { + if len(s) != n { + return false + } + for i := 0; i < len(s); i++ { + c := s[i] + switch { + case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9', c == '-', c == '_': + default: + return false + } + } + return true +} + +func refreshMAC(key []byte, grantID, secret string) string { + m := hmac.New(sha256.New, key) + m.Write([]byte("mcplogin|ort|v1|" + grantID + "|" + secret)) + return base64.RawURLEncoding.EncodeToString(m.Sum(nil)[:macBytes]) +} + +// NewRefreshToken issues "mcp_ort___" for a grant. It +// returns the whole token and the secret part, which the caller stores hashed. +func NewRefreshToken(key []byte, grantID string) (token, secret string, err error) { + if len(key) == 0 { + return "", "", ErrBadKey + } + if !validBase62(grantID, GrantIDLen) { + return "", "", ErrBadGrantID + } + secret, err = randomSecret() + if err != nil { + return "", "", err + } + return RefreshTokenPrefix + grantID + "_" + secret + "_" + refreshMAC(key, grantID, secret), secret, nil +} + +// ParseRefreshToken splits a refresh token by fixed field lengths (the secret +// and the MAC may themselves contain '_') and verifies the MAC in constant +// time. ok is false for every malformed token and for a bad MAC, with nothing +// to tell the two apart. +func ParseRefreshToken(key []byte, token string) (grantID, secret string, ok bool) { + if len(key) == 0 || !strings.HasPrefix(token, RefreshTokenPrefix) { + return "", "", false + } + rest := token[len(RefreshTokenPrefix):] + if len(rest) != GrantIDLen+1+secretLen+1+macLen { + return "", "", false + } + grantID = rest[:GrantIDLen] + secret = rest[GrantIDLen+1 : GrantIDLen+1+secretLen] + mac := rest[GrantIDLen+1+secretLen+1:] + if rest[GrantIDLen] != '_' || rest[GrantIDLen+1+secretLen] != '_' || + !validBase62(grantID, GrantIDLen) || !validBase64URL(secret, secretLen) || !validBase64URL(mac, macLen) { + return "", "", false + } + if !hmac.Equal([]byte(mac), []byte(refreshMAC(key, grantID, secret))) { + return "", "", false + } + return grantID, secret, true +} + +// HashSecret returns the hex HMAC-SHA256 of secret under key, labelled by +// kind (KindAccess, KindRefresh, KindCode), so hashes of different kinds, and +// agent-token hashes, never collide. +func HashSecret(key []byte, kind, secret string) string { + m := hmac.New(sha256.New, key) + m.Write([]byte("mcplogin|hash|v1|" + kind + "|" + secret)) + return hex.EncodeToString(m.Sum(nil)) +} + +// SecretEqual compares two strings in constant time. +func SecretEqual(a, b string) bool { + return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1 +} + +// DisplayPrefix returns the first 12 characters of a token, safe to show. +func DisplayPrefix(token string) string { + if len(token) <= prefixShow { + return token + } + return token[:prefixShow] +} + +// IsAccessToken reports whether s carries the access-token prefix. +func IsAccessToken(s string) bool { return strings.HasPrefix(s, AccessTokenPrefix) } + +// IsRefreshToken reports whether s carries the refresh-token prefix. +func IsRefreshToken(s string) bool { return strings.HasPrefix(s, RefreshTokenPrefix) } diff --git a/internal/mcplogin/token_test.go b/internal/mcplogin/token_test.go new file mode 100644 index 000000000..ce7f81cd2 --- /dev/null +++ b/internal/mcplogin/token_test.go @@ -0,0 +1,131 @@ +package mcplogin + +import ( + "strings" + "testing" +) + +var testKey = []byte("0123456789abcdef0123456789abcdef") + +func TestAccessToken(t *testing.T) { + a, err := NewAccessToken() + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(a, AccessTokenPrefix) || len(a) != len(AccessTokenPrefix)+43 { + t.Fatalf("bad access token %q", a) + } + if !IsAccessToken(a) || IsRefreshToken(a) { + t.Fatal("prefix checks wrong") + } + b, _ := NewAccessToken() + if a == b { + t.Fatal("tokens must differ") + } +} + +func TestGrantID(t *testing.T) { + g, err := NewGrantID() + if err != nil || len(g) != 22 { + t.Fatalf("grant id %q %v", g, err) + } + for _, c := range g { + if !strings.ContainsRune(base62Alphabet, c) { + t.Fatalf("non base62 %q", g) + } + } +} + +func TestRefreshTokenRoundTrip(t *testing.T) { + g, _ := NewGrantID() + tok, secret, err := NewRefreshToken(testKey, g) + if err != nil { + t.Fatal(err) + } + if !IsRefreshToken(tok) || IsAccessToken(tok) { + t.Fatal("prefix checks wrong") + } + if len(tok) != len(RefreshTokenPrefix)+22+1+43+1+22 { + t.Fatalf("length %d", len(tok)) + } + gid, sec, ok := ParseRefreshToken(testKey, tok) + if !ok || gid != g || sec != secret { + t.Fatalf("round trip failed: %v %q %q", ok, gid, sec) + } + tok2, secret2, _ := NewRefreshToken(testKey, g) + if tok2 == tok || secret2 == secret { + t.Fatal("two tokens of one grant must differ") + } +} + +func TestNewRefreshTokenRejectsBadGrantID(t *testing.T) { + if _, _, err := NewRefreshToken(testKey, "short"); err == nil { + t.Fatal("bad grant id accepted") + } + if _, _, err := NewRefreshToken(nil, strings.Repeat("a", 22)); err == nil { + t.Fatal("empty key accepted") + } +} + +func TestParseRefreshTokenRejects(t *testing.T) { + g, _ := NewGrantID() + tok, _, _ := NewRefreshToken(testKey, g) + other := []byte("ffffffffffffffffffffffffffffffff") + otherTok, _, _ := NewRefreshToken(other, g) + flip := func(s string, i int) string { + b := []byte(s) + if b[i] == 'A' { + b[i] = 'B' + } else { + b[i] = 'A' + } + return string(b) + } + p := len(RefreshTokenPrefix) + cases := map[string]string{ + "empty": "", + "wrong prefix": "mcp_oat_" + tok[p:], + "short": tok[:len(tok)-1], + "long": tok + "A", + "grant": flip(tok, p+3), + "secret": flip(tok, p+22+1+5), + "mac": flip(tok, len(tok)-3), + "other key": otherTok, + "no seps": strings.ReplaceAll(tok, "_", "-"), + } + for name, c := range cases { + if _, _, ok := ParseRefreshToken(testKey, c); ok { + t.Errorf("%s: accepted", name) + } + } + if _, _, ok := ParseRefreshToken(nil, tok); ok { + t.Error("nil key accepted") + } +} + +func TestHashSecretKinds(t *testing.T) { + s := "secret" + hs := map[string]bool{} + for _, k := range []string{"access", "refresh", "code"} { + h := HashSecret(testKey, k, s) + if len(h) != 64 || hs[h] { + t.Fatalf("kind %s: bad or colliding hash", k) + } + hs[h] = true + if h != HashSecret(testKey, k, s) { + t.Fatal("not deterministic") + } + } + if HashSecret(testKey, "access", s) == HashSecret(testKey, "access", s+"x") { + t.Fatal("collision") + } +} + +func TestSecretEqualAndPrefix(t *testing.T) { + if !SecretEqual("a", "a") || SecretEqual("a", "b") || SecretEqual("a", "ab") { + t.Fatal("SecretEqual wrong") + } + if DisplayPrefix("mcp_oat_abcdefgh") != "mcp_oat_abcd" || DisplayPrefix("abc") != "abc" { + t.Fatal("DisplayPrefix wrong") + } +} From 1251d0acc77bf33557f9056947fe7544cce9e713 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 18:54:23 +0200 Subject: [PATCH 04/42] fix(oauth): tighten redirect matching and bound in-memory state (Spec 132 PR-1b) Related #1971 --- internal/mcplogin/limits.go | 54 ++++++++++++++-- internal/mcplogin/redirect.go | 20 +++++- internal/mcplogin/registration.go | 9 ++- internal/mcplogin/registration_test.go | 9 ++- internal/mcplogin/requests.go | 16 +++-- internal/mcplogin/requests_test.go | 8 +-- internal/mcplogin/review_fixes_test.go | 90 ++++++++++++++++++++++++++ 7 files changed, 187 insertions(+), 19 deletions(-) create mode 100644 internal/mcplogin/review_fixes_test.go diff --git a/internal/mcplogin/limits.go b/internal/mcplogin/limits.go index e32f9dc5c..00c93a78d 100644 --- a/internal/mcplogin/limits.go +++ b/internal/mcplogin/limits.go @@ -2,6 +2,7 @@ package mcplogin import ( "math" + "sync" "time" "github.com/smart-mcp-proxy/mcpproxy-go/internal/upstream/limiter" @@ -39,26 +40,71 @@ func rateFor(endpoint string) (limiter.RateSpec, bool) { return limiter.RateSpec{}, false } +const ( + // MaxTrackedKeys caps the distinct endpoint|address keys the Limiter keeps. + MaxTrackedKeys = 4096 + // idleAfter is how long a key must be unseen before it may be dropped. It + // exceeds the time any bucket needs to refill completely, so dropping an + // idle key never hands a caller extra budget. + idleAfter = time.Minute +) + // Limiter rate limits the public OAuth endpoints per endpoint and remote -// address. It is safe for concurrent use. +// address, over at most MaxTrackedKeys keys. It is safe for concurrent use. type Limiter struct { rates *limiter.TokenRates + now func() time.Time + mu sync.Mutex + seen map[string]time.Time } // NewLimiter returns a Limiter with the default rates. now is the clock; nil // means time.Now. func NewLimiter(now func() time.Time) *Limiter { - return &Limiter{rates: limiter.NewTokenRates(now)} + if now == nil { + now = time.Now + } + return &Limiter{rates: limiter.NewTokenRates(now), now: now, seen: map[string]time.Time{}} +} + +// admit records key as seen now. For an unseen key at the cap it prunes idle +// keys first and, if the limiter is still full, refuses with the seconds until +// the oldest key becomes idle. Active keys are never evicted. +func (l *Limiter) admit(key string) (bool, int) { + l.mu.Lock() + defer l.mu.Unlock() + now := l.now() + if _, known := l.seen[key]; !known && len(l.seen) >= MaxTrackedKeys { + oldest := now + for k, t := range l.seen { + if now.Sub(t) >= idleAfter { + delete(l.seen, k) + } else if t.Before(oldest) { + oldest = t + } + } + if len(l.seen) >= MaxTrackedKeys { + wait := idleAfter - now.Sub(oldest) + return false, max(1, int(math.Ceil(wait.Seconds()))) + } + } + l.seen[key] = now + return true, 0 } // Allow charges one call of endpoint from remoteIP. When refused, -// retryAfterSeconds is at least 1. An unknown endpoint is not limited. +// retryAfterSeconds is at least 1. An unknown endpoint is not limited. A new +// address is refused while the limiter is full of active ones. func (l *Limiter) Allow(endpoint, remoteIP string) (ok bool, retryAfterSeconds int) { spec, known := rateFor(endpoint) if !known { return true, 0 } - d := l.rates.Allow(endpoint+"|"+remoteIP, &spec) + key := endpoint + "|" + remoteIP + if ok, retry := l.admit(key); !ok { + return false, retry + } + d := l.rates.Allow(key, &spec) if d.Allowed { return true, 0 } diff --git a/internal/mcplogin/redirect.go b/internal/mcplogin/redirect.go index 70d219796..8bf3fbc07 100644 --- a/internal/mcplogin/redirect.go +++ b/internal/mcplogin/redirect.go @@ -68,6 +68,23 @@ func isLoopbackURL(u *url.URL) bool { return u.Scheme == "http" && isLoopbackHost(u.Host[:hostEnd(u.Host)]) } +// stripPort removes the port from the authority of an already validated URI +// string and leaves every other byte alone, so two loopback URIs compare equal +// only when they differ by port at most. +func stripPort(raw string) string { + i := strings.Index(raw, "://") + if i < 0 { + return raw + } + start := i + 3 + end := len(raw) + if j := strings.IndexAny(raw[start:], "/?#"); j >= 0 { + end = start + j + } + auth := raw[start:end] + return raw[:start] + auth[:hostEnd(auth)] + raw[end:] +} + // ValidateRegisteredRedirects checks the redirect URIs of a registration: 1 to // 5 entries, each an absolute URL without fragment or user info, either http // on 127.0.0.1, [::1] or localhost, or https with a host. Custom schemes are @@ -104,8 +121,7 @@ func MatchRedirect(registered []string, presented string) (matched string, ok bo if err != nil || !isLoopbackURL(r) { continue } - if r.Scheme == p.Scheme && r.Hostname() == p.Hostname() && - r.EscapedPath() == p.EscapedPath() && r.RawQuery == p.RawQuery { + if isLoopbackURL(p) && stripPort(reg) == stripPort(presented) { return presented, true } } diff --git a/internal/mcplogin/registration.go b/internal/mcplogin/registration.go index a953669fd..9936c6ac3 100644 --- a/internal/mcplogin/registration.go +++ b/internal/mcplogin/registration.go @@ -111,7 +111,7 @@ func NewClientID() (string, error) { return randomBase62(22) } // Response is the RFC 7591 201 body. It never carries a client_secret. func (r Registration) Response(issuedAt time.Time) map[string]any { - return map[string]any{ + m := map[string]any{ "client_id": r.ClientID, "client_id_issued_at": issuedAt.Unix(), "redirect_uris": r.RedirectURIs, @@ -120,4 +120,11 @@ func (r Registration) Response(issuedAt time.Time) map[string]any { "grant_types": r.GrantTypes, "response_types": r.ResponseTypes, } + if r.SoftwareID != "" { + m["software_id"] = r.SoftwareID + } + if r.SoftwareVersion != "" { + m["software_version"] = r.SoftwareVersion + } + return m } diff --git a/internal/mcplogin/registration_test.go b/internal/mcplogin/registration_test.go index 096342e6b..9740fdc9c 100644 --- a/internal/mcplogin/registration_test.go +++ b/internal/mcplogin/registration_test.go @@ -87,13 +87,20 @@ func TestNewClientID(t *testing.T) { } func TestRegistrationResponse(t *testing.T) { - reg, _ := ValidateRegistration(RegistrationRequest{RedirectURIs: []string{"https://a/cb"}, ClientName: "X"}) + reg, _ := ValidateRegistration(RegistrationRequest{RedirectURIs: []string{"https://a/cb"}, ClientName: "X", SoftwareID: " SW\x07", SoftwareVersion: "1.0"}) reg.ClientID = "abc" m := reg.Response(time.Unix(1700000000, 0)) if m["client_id"] != "abc" || m["client_id_issued_at"] != int64(1700000000) || m["token_endpoint_auth_method"] != "none" || m["client_name"] != "x" { t.Fatalf("%v", m) } + if m["software_id"] != "sw" || m["software_version"] != "1.0" { + t.Fatalf("software fields: %v", m) + } + bare, _ := ValidateRegistration(RegistrationRequest{RedirectURIs: []string{"https://a/cb"}}) + if _, has := bare.Response(time.Unix(1, 0))["software_id"]; has { + t.Fatal("empty software_id must be omitted") + } if _, has := m["client_secret"]; has { t.Fatal("client_secret present") } diff --git a/internal/mcplogin/requests.go b/internal/mcplogin/requests.go index ded4f94c0..6a707deaa 100644 --- a/internal/mcplogin/requests.go +++ b/internal/mcplogin/requests.go @@ -155,6 +155,7 @@ func (s *Store) Create(req Request) (Request, error) { } s.mu.Lock() defer s.mu.Unlock() + s.sweepLocked() if s.pendingCountLocked() >= MaxPendingRequests { return Request{}, ErrTooManyPending } @@ -208,6 +209,7 @@ func (s *Store) Approve(id string, d Decision) (string, error) { } s.mu.Lock() defer s.mu.Unlock() + s.sweepLocked() r := s.live(id) if r == nil { return "", ErrRequestNotFound @@ -275,11 +277,13 @@ func (s *Store) CancelAll() int { // commit fails the code is burned too (single use) and the error is returned. // Presenting a consumed code again inside the tombstone window returns // ErrCodeReused together with the grant id it produced; afterwards the code is -// unknown. +// unknown. This holds for a code whose commit failed as well, with an empty +// grant id: callers must treat an empty grant id as "nothing to revoke". func (s *Store) Consume(code string, commit func(Request) (grantID string, err error)) (Request, string, error) { h := HashSecret(s.key, KindCode, code) s.mu.Lock() defer s.mu.Unlock() + s.sweepLocked() now := s.now() e := s.codes[h] if e == nil { @@ -287,9 +291,6 @@ func (s *Store) Consume(code string, commit func(Request) (grantID string, err e } if e.consumed { if now.Before(e.consumedAt.Add(TombstoneLifetime)) { - if e.grantID == "" { - return Request{}, "", ErrCodeUnknown - } return Request{}, e.grantID, ErrCodeReused } delete(s.codes, h) @@ -319,6 +320,13 @@ func (s *Store) Consume(code string, commit func(Request) (grantID string, err e func (s *Store) Sweep() { s.mu.Lock() defer s.mu.Unlock() + s.sweepLocked() +} + +// sweepLocked drops dead entries. Create, Approve and Consume call it, so the +// maps stay bounded by what is live (at most MaxPendingRequests pending plus +// ten minutes of decided state) without an external janitor. Caller holds s.mu. +func (s *Store) sweepLocked() { now := s.now() for id, r := range s.reqs { if !now.Before(r.ExpiresAt) { diff --git a/internal/mcplogin/requests_test.go b/internal/mcplogin/requests_test.go index 413c14c6b..efb2d5471 100644 --- a/internal/mcplogin/requests_test.go +++ b/internal/mcplogin/requests_test.go @@ -13,12 +13,6 @@ func newTestStore() (*Store, *fakeClock) { return NewStore(testKey, clk.now), clk } -func (s *Store) size() int { - s.mu.Lock() - defer s.mu.Unlock() - return len(s.reqs) + len(s.codes) -} - func mkReq(pathClient string) Request { return Request{RegistrationID: "reg1", RedirectURI: "http://127.0.0.1:1/cb", State: "st", CodeChallenge: "ch", Resource: "http://127.0.0.1:8080/mcp/oauth", Issuer: "http://127.0.0.1:8080", PathClient: pathClient} @@ -186,7 +180,7 @@ func TestConsumeCommitErrorBurnsCode(t *testing.T) { } called := false _, gid, err := s.Consume(code, func(Request) (string, error) { called = true; return "g", nil }) - if called || gid != "" || !errors.Is(err, ErrCodeUnknown) { + if called || gid != "" || !errors.Is(err, ErrCodeReused) { t.Fatalf("code reusable after failed commit: %v %q %v", err, gid, called) } } diff --git a/internal/mcplogin/review_fixes_test.go b/internal/mcplogin/review_fixes_test.go new file mode 100644 index 000000000..303623e15 --- /dev/null +++ b/internal/mcplogin/review_fixes_test.go @@ -0,0 +1,90 @@ +package mcplogin + +import ( + "fmt" + "testing" + "time" +) + +func (s *Store) size() int { + s.mu.Lock() + defer s.mu.Unlock() + return len(s.reqs) + len(s.codes) +} + +func (l *Limiter) tracked() int { + l.mu.Lock() + defer l.mu.Unlock() + return len(l.seen) +} + +func TestMatchRedirectDiffersByPortOnly(t *testing.T) { + reg := []string{"http://localhost/cb"} + for _, in := range []string{ + "http://localhost:54321/cb?", + "HTTP://localhost:54321/cb", + "http://LOCALHOST:54321/cb", + "http://localhost:54321/CB", + } { + if got, ok := MatchRedirect(reg, in); ok { + t.Errorf("%q matched as %q", in, got) + } + } + if _, ok := MatchRedirect([]string{"http://localhost:1/cb"}, "http://localhost:54321/cb"); !ok { + t.Error("registered port must be ignored too") + } + if _, ok := MatchRedirect([]string{"http://[::1]/cb"}, "http://[::1]:5/cb"); !ok { + t.Error("ipv6 port") + } +} + +func TestStoreStaysBounded(t *testing.T) { + s, clk := newTestStore() + for round := 0; round < 5; round++ { + for i := 0; i < MaxPendingRequests; i++ { + mustCreate(t, s, "") + } + clk.advance(RequestLifetime + time.Second) + } + if n := s.size(); n > MaxPendingRequests { + t.Fatalf("store grew to %d entries", n) + } +} + +func TestStoreCodesStayBounded(t *testing.T) { + s, clk := newTestStore() + for round := 0; round < 5; round++ { + r := mustCreate(t, s, "") + code, _ := s.Approve(r.ID, Decision{ClientID: "c"}) + clk.advance(RequestLifetime + TombstoneLifetime) + _, _, _ = s.Consume(code, nil) + } + mustCreate(t, s, "") + if n := s.size(); n > 3 { + t.Fatalf("store grew to %d entries", n) + } +} + +func TestLimiterBoundedKeys(t *testing.T) { + clk := &fakeClock{t: time.Unix(1000, 0)} + l := NewLimiter(clk.now) + for i := 0; i < MaxTrackedKeys; i++ { + if ok, _ := l.Allow(EndpointToken, fmt.Sprintf("ip-%d", i)); !ok { + t.Fatalf("key %d refused", i) + } + } + ok, retry := l.Allow(EndpointToken, "newcomer") + if ok || retry < 1 { + t.Fatalf("full limiter must refuse new key: %v %d", ok, retry) + } + if ok, _ := l.Allow(EndpointToken, "ip-0"); !ok { + t.Fatal("known key must still be served") + } + clk.advance(2 * time.Minute) + if ok, _ := l.Allow(EndpointToken, "newcomer"); !ok { + t.Fatal("idle keys should have been pruned") + } + if n := l.tracked(); n > 2 { + t.Fatalf("tracked %d", n) + } +} From fb7d861c6277d39cc492bd1b36ea4c4de460f386 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 18:57:23 +0200 Subject: [PATCH 05/42] fix(oauth): align code and request expiry, make limiter admission atomic (Spec 132 PR-1b) Related #1971 --- internal/mcplogin/limits.go | 10 +++--- internal/mcplogin/requests.go | 6 +++- internal/mcplogin/review_fixes_test.go | 49 ++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 5 deletions(-) diff --git a/internal/mcplogin/limits.go b/internal/mcplogin/limits.go index 00c93a78d..9c267a669 100644 --- a/internal/mcplogin/limits.go +++ b/internal/mcplogin/limits.go @@ -70,9 +70,7 @@ func NewLimiter(now func() time.Time) *Limiter { // admit records key as seen now. For an unseen key at the cap it prunes idle // keys first and, if the limiter is still full, refuses with the seconds until // the oldest key becomes idle. Active keys are never evicted. -func (l *Limiter) admit(key string) (bool, int) { - l.mu.Lock() - defer l.mu.Unlock() +func (l *Limiter) admitLocked(key string) (bool, int) { now := l.now() if _, known := l.seen[key]; !known && len(l.seen) >= MaxTrackedKeys { oldest := now @@ -101,7 +99,11 @@ func (l *Limiter) Allow(endpoint, remoteIP string) (ok bool, retryAfterSeconds i return true, 0 } key := endpoint + "|" + remoteIP - if ok, retry := l.admit(key); !ok { + // One lock spans admission and the bucket charge, so a key cannot be + // pruned between the two and leave a bucket that seen does not know. + l.mu.Lock() + defer l.mu.Unlock() + if ok, retry := l.admitLocked(key); !ok { return false, retry } d := l.rates.Allow(key, &spec) diff --git a/internal/mcplogin/requests.go b/internal/mcplogin/requests.go index 6a707deaa..5c4768035 100644 --- a/internal/mcplogin/requests.go +++ b/internal/mcplogin/requests.go @@ -217,9 +217,13 @@ func (s *Store) Approve(id string, d Decision) (string, error) { if r.Status != StatusPending { return "", ErrAlreadyDecided } + now := s.now() r.Status = StatusApproved r.Decision = d - s.codes[HashSecret(s.key, KindCode, code)] = &codeEntry{requestID: id, expiresAt: s.now().Add(CodeLifetime)} + // Pending expiry and approved-code expiry are separate: an approved + // request lives exactly as long as its code. + r.ExpiresAt = now.Add(CodeLifetime) + s.codes[HashSecret(s.key, KindCode, code)] = &codeEntry{requestID: id, expiresAt: now.Add(CodeLifetime)} return code, nil } diff --git a/internal/mcplogin/review_fixes_test.go b/internal/mcplogin/review_fixes_test.go index 303623e15..6cfd39681 100644 --- a/internal/mcplogin/review_fixes_test.go +++ b/internal/mcplogin/review_fixes_test.go @@ -1,7 +1,9 @@ package mcplogin import ( + "errors" "fmt" + "sync" "testing" "time" ) @@ -88,3 +90,50 @@ func TestLimiterBoundedKeys(t *testing.T) { t.Fatalf("tracked %d", n) } } + +func TestApprovedCodeLivesFullLifetime(t *testing.T) { + s, clk := newTestStore() + r := mustCreate(t, s, "") + clk.advance(RequestLifetime - 10*time.Second) + code, err := s.Approve(r.ID, Decision{ClientID: "c"}) + if err != nil { + t.Fatal(err) + } + clk.advance(50 * time.Second) + if _, _, err := s.Consume(code, func(Request) (string, error) { return "g", nil }); err != nil { + t.Fatalf("code died early: %v", err) + } + r2 := mustCreate(t, s, "") + code2, _ := s.Approve(r2.ID, Decision{ClientID: "c"}) + clk.advance(CodeLifetime + time.Second) + if _, _, err := s.Consume(code2, func(Request) (string, error) { return "g", nil }); !errors.Is(err, ErrCodeUnknown) { + t.Fatalf("expired code: %v", err) + } +} + +func TestLimiterBucketsStayBoundedConcurrently(t *testing.T) { + clk := &fakeClock{t: time.Unix(1000, 0)} + l := NewLimiter(clk.now) + var wg sync.WaitGroup + for g := 0; g < 8; g++ { + wg.Add(1) + go func(g int) { + defer wg.Done() + for i := 0; i < MaxTrackedKeys; i++ { + l.Allow(EndpointToken, fmt.Sprintf("ip-%d-%d", g, i)) + if i%500 == 0 { + clk.advance(30 * time.Second) + } + } + }(g) + } + wg.Wait() + l.mu.Lock() + defer l.mu.Unlock() + if len(l.seen) > MaxTrackedKeys || l.rates.Len() > MaxTrackedKeys { + t.Fatalf("seen %d buckets %d", len(l.seen), l.rates.Len()) + } + if l.rates.Len() > len(l.seen) { + t.Fatalf("bucket without seen entry: seen %d buckets %d", len(l.seen), l.rates.Len()) + } +} From 8f51f22a04951e815b65ef8beeeb85861675b18d Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 19:09:23 +0200 Subject: [PATCH 06/42] feat(oauth): storage for browser logins and one binding writer (Spec 132 PR-1c) Related #1971 --- internal/storage/agent_token_repin.go | 112 ++- internal/storage/client_binding.go | 298 ++++++ internal/storage/client_binding_dual_test.go | 365 +++++++ internal/storage/client_credentials.go | 37 +- internal/storage/oauth_login.go | 937 ++++++++++++++++++ .../storage/oauth_login_client_ops_test.go | 171 ++++ internal/storage/oauth_login_test.go | 610 ++++++++++++ 7 files changed, 2497 insertions(+), 33 deletions(-) create mode 100644 internal/storage/client_binding.go create mode 100644 internal/storage/client_binding_dual_test.go create mode 100644 internal/storage/oauth_login.go create mode 100644 internal/storage/oauth_login_client_ops_test.go create mode 100644 internal/storage/oauth_login_test.go diff --git a/internal/storage/agent_token_repin.go b/internal/storage/agent_token_repin.go index 2e404000c..f519ca530 100644 --- a/internal/storage/agent_token_repin.go +++ b/internal/storage/agent_token_repin.go @@ -26,6 +26,12 @@ func (m *Manager) RepinProfile(from, to string) (before []auth.AgentToken, err e // repinProfile is RepinProfile with a per-record hook (called before each // record is written) so a test can inject a failure part-way through the tx. +// +// Spec 132: a client's pin is written through writeClientBindingTx, so its +// browser-login binding entry moves with its API-key record, and an entry of a +// client that has NO API-key record moves too. Such an entry is reported in +// `before` as a record with an empty TokenHash (Kind=client, ClientID set) that +// RestorePins recognises. func (m *Manager) repinProfile(from, to string, hook func(written int) error) ([]auth.AgentToken, error) { if from == "" || to == "" { return nil, fmt.Errorf("repin needs a source and a target profile") @@ -36,47 +42,87 @@ func (m *Manager) repinProfile(from, to string, hook func(written int) error) ([ var before []auth.AgentToken err := m.db.db.Update(func(tx *bbolt.Tx) error { before = nil - tokenBucket := tx.Bucket([]byte(AgentTokensBucket)) - if tokenBucket == nil { - return nil - } type rewrite struct { key []byte data []byte old auth.AgentToken } var work []rewrite + var clientWork []auth.AgentToken // kind=client records: via the binding writer + clientsWithRecord := map[string]bool{} // Collect first: bbolt forbids Put while a ForEach is iterating. - if err := tokenBucket.ForEach(func(k, v []byte) error { - var t auth.AgentToken - if json.Unmarshal(v, &t) != nil { - return nil - } - if t.UserID != "" || t.ProfilePin != from { + if tokenBucket := tx.Bucket([]byte(AgentTokensBucket)); tokenBucket != nil { + if err := tokenBucket.ForEach(func(k, v []byte) error { + var t auth.AgentToken + if json.Unmarshal(v, &t) != nil { + return nil + } + if t.Kind == auth.KindClient && t.ClientID != "" { + clientsWithRecord[t.ClientID] = true + } + if t.UserID != "" || t.ProfilePin != from { + return nil + } + old := t + if t.Kind == auth.KindClient && t.ClientID != "" { + clientWork = append(clientWork, old) + return nil + } + // Regular (non-client) agent token: plain pin rewrite. + t.ProfilePin = to + data, marshalErr := json.Marshal(t) + if marshalErr != nil { + return marshalErr + } + work = append(work, rewrite{key: append([]byte(nil), k...), data: data, old: old}) return nil + }); err != nil { + return err } - old := t - t.ProfilePin = to - data, marshalErr := json.Marshal(t) - if marshalErr != nil { - return marshalErr + } + // Browser-login-only clients: entries pinned to `from` whose client has + // no API-key record. + var oauthOnly []auth.AgentToken + if err := oauthForEach(tx, OAuthClientBindingsBucket, func(id string, b OAuthClientBinding) error { + if b.ProfilePin == from && !clientsWithRecord[id] { + oauthOnly = append(oauthOnly, auth.AgentToken{ + Name: auth.ClientTokenName(id), Kind: auth.KindClient, ClientID: id, + ProfilePin: b.ProfilePin, ProfileMode: b.ProfileMode, + }) } - work = append(work, rewrite{key: append([]byte(nil), k...), data: data, old: old}) return nil }); err != nil { return err } - for i, w := range work { + + i := 0 + step := func() error { if hook != nil { if err := hook(i); err != nil { return err } } - if err := tokenBucket.Put(w.key, w.data); err != nil { + i++ + return nil + } + for _, w := range work { + if err := step(); err != nil { + return err + } + if err := tx.Bucket([]byte(AgentTokensBucket)).Put(w.key, w.data); err != nil { return fmt.Errorf("failed to repin agent token: %w", err) } before = append(before, w.old) } + for _, old := range append(clientWork, oauthOnly...) { + if err := step(); err != nil { + return err + } + if err := writeClientBindingTx(tx, old.ClientID, to, old.ProfileMode); err != nil { + return fmt.Errorf("failed to repin client binding: %w", err) + } + before = append(before, old) + } return nil }) if err != nil { @@ -87,7 +133,8 @@ func (m *Manager) repinProfile(from, to string, hook func(written int) error) ([ // RestorePins puts back the ProfilePin of each record RepinProfile returned, // in one transaction (the rollback of a repin whose config write failed). A -// record that no longer exists is left alone. +// record that no longer exists is left alone. Client records, and the entries +// of browser-login-only clients (empty TokenHash), go through the binding writer. func (m *Manager) RestorePins(before []auth.AgentToken) error { if len(before) == 0 { return nil @@ -95,11 +142,24 @@ func (m *Manager) RestorePins(before []auth.AgentToken) error { m.mu.Lock() defer m.mu.Unlock() return m.db.db.Update(func(tx *bbolt.Tx) error { - tokenBucket := tx.Bucket([]byte(AgentTokensBucket)) - if tokenBucket == nil { - return nil - } for i := range before { + if before[i].TokenHash == "" && before[i].Kind == auth.KindClient && before[i].ClientID != "" { + // Browser-login-only client: its entry, if it still exists. + b, err := getOAuthBindingTx(tx, before[i].ClientID) + if err != nil { + return err + } + if b != nil { + if err := writeClientBindingTx(tx, before[i].ClientID, before[i].ProfilePin, b.ProfileMode); err != nil { + return err + } + } + continue + } + tokenBucket := tx.Bucket([]byte(AgentTokensBucket)) + if tokenBucket == nil { + continue + } key := []byte(before[i].TokenHash) v := tokenBucket.Get(key) if v == nil { @@ -109,6 +169,12 @@ func (m *Manager) RestorePins(before []auth.AgentToken) error { if json.Unmarshal(v, &t) != nil || t.UserID != "" { continue } + if t.Kind == auth.KindClient && t.ClientID != "" { + if err := writeClientBindingTx(tx, t.ClientID, before[i].ProfilePin, t.ProfileMode); err != nil { + return fmt.Errorf("failed to restore client binding: %w", err) + } + continue + } t.ProfilePin = before[i].ProfilePin data, err := json.Marshal(t) if err != nil { diff --git a/internal/storage/client_binding.go b/internal/storage/client_binding.go new file mode 100644 index 000000000..ec81e014f --- /dev/null +++ b/internal/storage/client_binding.go @@ -0,0 +1,298 @@ +package storage + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "time" + + "go.etcd.io/bbolt" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// Spec 132 research R4: a client's binding (profile pin + mode) lives in the +// API-key record (agent_tokens, Kind=client) and, for a client with browser +// logins, in an oauth_client_bindings entry. writeClientBindingTx is the ONE +// place that writes a client's pin/mode into either store, so the two never +// drift; every writer of a binding calls it inside its own transaction. + +func bindingRevision(clientID, pin, mode string) string { + sum := sha256.Sum256([]byte(clientID + "|" + pin + "|" + mode)) + return hex.EncodeToString(sum[:8]) +} + +// writeClientBindingTx writes (pin, mode) on the client's API-key record when +// there is one AND on its oauth_client_bindings entry when there is one, and +// fails with ErrClientCredentialNotFound only when NEITHER exists. It never +// creates an oauth_client_bindings entry by itself and never touches the +// record's PriorProfile* snapshot. +func writeClientBindingTx(tx *bbolt.Tx, clientID, pin, mode string) error { + return writeClientBindingOptsTx(tx, clientID, pin, mode, false) +} + +// writeClientBindingOptsTx is writeClientBindingTx with the option to clear +// the API-key record's PriorProfile* snapshot in the same write (a binding +// change makes the mint-time snapshot stale). +func writeClientBindingOptsTx(tx *bbolt.Tx, clientID, pin, mode string, clearPrior bool) error { + found := false + hash, tok, err := findClientTokenRecordLocked(tx, clientID) + if err != nil { + return err + } + if tok != nil && tok.Kind == auth.KindClient { + tok.ProfilePin, tok.ProfileMode = pin, mode + if clearPrior { + tok.PriorProfilePin, tok.PriorProfileMode = "", "" + } + data, err := json.Marshal(tok) + if err != nil { + return fmt.Errorf("failed to marshal client credential: %w", err) + } + if err := tx.Bucket([]byte(AgentTokensBucket)).Put(hash, data); err != nil { + return fmt.Errorf("failed to store client binding: %w", err) + } + found = true + } + b, err := getOAuthBindingTx(tx, clientID) + if err != nil { + return err + } + if b != nil { + b.ProfilePin, b.ProfileMode, b.UpdatedAt = pin, mode, time.Now().UTC() + if err := oauthPutJSON(tx, OAuthClientBindingsBucket, clientID, b); err != nil { + return err + } + found = true + } + if !found { + return ErrClientCredentialNotFound + } + return nil +} + +// RepairOAuthClientBindings makes every client that has both an API-key record +// and an oauth_client_bindings entry agree, taking the API-key record as the +// truth. It returns the ids it repaired (the caller logs them). +func (m *Manager) RepairOAuthClientBindings() (repaired []string, err error) { + m.mu.Lock() + defer m.mu.Unlock() + err = m.db.db.Update(func(tx *bbolt.Tx) error { + repaired = nil + var todo []struct{ id, pin, mode string } + if err := oauthForEach(tx, OAuthClientBindingsBucket, func(id string, b OAuthClientBinding) error { + _, tok, err := findClientTokenRecordLocked(tx, id) + if err != nil { + return err + } + if tok == nil || tok.Kind != auth.KindClient { + return nil + } + if tok.ProfilePin != b.ProfilePin || tok.ProfileMode != b.ProfileMode { + todo = append(todo, struct{ id, pin, mode string }{id, tok.ProfilePin, tok.ProfileMode}) + } + return nil + }); err != nil { + return err + } + for _, r := range todo { + if err := writeClientBindingTx(tx, r.id, r.pin, r.mode); err != nil { + return err + } + repaired = append(repaired, r.id) + } + return nil + }) + if err != nil { + return nil, err + } + return repaired, nil +} + +// forgetClientLoginsTx deletes every grant record of the client with its +// access index entries, the client's oauth_client_bindings entry, and the +// registrations left with no grant record. It reports how many grants it deleted. +func forgetClientLoginsTx(tx *bbolt.Tx, clientID string) (int, error) { + gb := tx.Bucket([]byte(OAuthGrantsBucket)) + n := 0 + if gb != nil { + var mine []OAuthGrant + regStays := map[string]bool{} + if err := oauthForEach(tx, OAuthGrantsBucket, func(_ string, g OAuthGrant) error { + if g.Client == clientID { + mine = append(mine, g) + } else { + regStays[g.RegistrationID] = true + } + return nil + }); err != nil { + return 0, err + } + rb := tx.Bucket([]byte(OAuthRegistrationsBucket)) + for _, g := range mine { + if err := gb.Delete([]byte(g.GrantID)); err != nil { + return 0, err + } + if err := deleteAccessIndexTx(tx, g.AccessHash); err != nil { + return 0, err + } + if rb != nil && !regStays[g.RegistrationID] { + if err := rb.Delete([]byte(g.RegistrationID)); err != nil { + return 0, err + } + } + } + n = len(mine) + } + if bb := tx.Bucket([]byte(OAuthClientBindingsBucket)); bb != nil { + if err := bb.Delete([]byte(clientID)); err != nil { + return 0, err + } + } + return n, nil +} + +// ForgetClientLogins deletes the client's browser logins and binding entry in +// one transaction (see forgetClientLoginsTx). It never touches the API-key +// record. It reports how many grants it deleted. +func (m *Manager) ForgetClientLogins(clientID string) (int, error) { + if !auth.ValidClientID(clientID) { + return 0, fmt.Errorf("invalid client id %q", clientID) + } + m.mu.Lock() + defer m.mu.Unlock() + n := 0 + err := m.db.db.Update(func(tx *bbolt.Tx) error { + var err error + n, err = forgetClientLoginsTx(tx, clientID) + return err + }) + return n, err +} + +// clientHasLoginRecordsTx reports whether the client has a binding entry or a +// grant record. +func clientHasLoginRecordsTx(tx *bbolt.Tx, clientID string) (bool, error) { + b, err := getOAuthBindingTx(tx, clientID) + if err != nil || b != nil { + return b != nil, err + } + found := false + err = oauthForEach(tx, OAuthGrantsBucket, func(_ string, g OAuthGrant) error { + if g.Client == clientID { + found = true + } + return nil + }) + return found, err +} + +// revokeClientAPIKeyTx soft-revokes the client's kind=client record (the +// exact effect of ForgetClientCredential) and returns it; nil when there is none. +func revokeClientAPIKeyTx(tx *bbolt.Tx, clientID string) (*auth.AgentToken, error) { + primaryHash, tok, err := findClientTokenRecordLocked(tx, clientID) + if err != nil { + return nil, err + } + if tok == nil || tok.Kind != auth.KindClient { + return nil, nil + } + markRevoked(tok, time.Now()) + tok.PriorProfilePin, tok.PriorProfileMode = "", "" + data, err := json.Marshal(tok) + if err != nil { + return nil, fmt.Errorf("failed to marshal client credential: %w", err) + } + if err := tx.Bucket([]byte(AgentTokensBucket)).Put(primaryHash, data); err != nil { + return nil, fmt.Errorf("failed to store revoked client credential: %w", err) + } + return tok, nil +} + +// ForgetClient is the client FORGET: it revokes the API-key record the way +// ForgetClientCredential does (the record stays as a revoked tombstone that +// reserves the name) and, in the same transaction, deletes every browser login, +// the OAuth binding entry and the registrations left without a grant. The +// returned record is nil for a client that had only browser logins. +// ErrClientCredentialNotFound means the client had nothing at all. +func (m *Manager) ForgetClient(clientID string) (*auth.AgentToken, error) { + if !auth.ValidClientID(clientID) { + return nil, fmt.Errorf("invalid client id %q", clientID) + } + m.mu.Lock() + defer m.mu.Unlock() + var revoked *auth.AgentToken + err := m.db.db.Update(func(tx *bbolt.Tx) error { + hadLogins, err := clientHasLoginRecordsTx(tx, clientID) + if err != nil { + return err + } + revoked, err = revokeClientAPIKeyTx(tx, clientID) + if err != nil { + return err + } + if revoked == nil && !hadLogins { + return ErrClientCredentialNotFound + } + _, err = forgetClientLoginsTx(tx, clientID) + return err + }) + if err != nil { + return nil, err + } + return revoked, nil +} + +// RevokeClient is the client REVOKE: the API-key record (when there is one) is +// revoked as ForgetClientCredential does, and every grant of the client is +// marked revoked with reason client_revoked. Everything is kept for display. +// The returned record is nil for a client with only browser logins. +// ErrClientCredentialNotFound means the client had nothing at all. +func (m *Manager) RevokeClient(clientID string, now time.Time) (*auth.AgentToken, error) { + if !auth.ValidClientID(clientID) { + return nil, fmt.Errorf("invalid client id %q", clientID) + } + m.mu.Lock() + defer m.mu.Unlock() + var revoked *auth.AgentToken + err := m.db.db.Update(func(tx *bbolt.Tx) error { + hadLogins, err := clientHasLoginRecordsTx(tx, clientID) + if err != nil { + return err + } + revoked, err = revokeClientAPIKeyTx(tx, clientID) + if err != nil { + return err + } + if revoked == nil && !hadLogins { + return ErrClientCredentialNotFound + } + var mine []OAuthGrant + if err := oauthForEach(tx, OAuthGrantsBucket, func(_ string, g OAuthGrant) error { + if g.Client == clientID { + mine = append(mine, g) + } + return nil + }); err != nil { + return err + } + for i := range mine { + if _, err := revokeGrantTx(tx, &mine[i], OAuthRevokeClientRevoked, now); err != nil { + return err + } + } + return nil + }) + if err != nil { + return nil, err + } + return revoked, nil +} + +// RevokeClientAPIKey revokes the API-key record only; grants and the OAuth +// binding entry are untouched. It is ForgetClientCredential under a name that +// says what it does now that a client can hold other credentials. +func (m *Manager) RevokeClientAPIKey(clientID string) (*auth.AgentToken, error) { + return m.forgetClientCredential(clientID, false) +} diff --git a/internal/storage/client_binding_dual_test.go b/internal/storage/client_binding_dual_test.go new file mode 100644 index 000000000..eca716f59 --- /dev/null +++ b/internal/storage/client_binding_dual_test.go @@ -0,0 +1,365 @@ +package storage + +import ( + "encoding/json" + "errors" + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "sort" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.etcd.io/bbolt" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// bindings returns the (pin, mode) held by the client's raw API-key record and +// by its oauth_client_bindings entry ("" / "" and ok=false when absent). +func bindings(t *testing.T, m *Manager, clientID string) (apiPin, apiMode string, apiOK bool, oPin, oMode string, oOK bool) { + t.Helper() + require.NoError(t, m.db.db.View(func(tx *bbolt.Tx) error { + _, tok, err := findClientTokenRecordLocked(tx, clientID) + require.NoError(t, err) + if tok != nil && tok.Kind == auth.KindClient { + apiPin, apiMode, apiOK = tok.ProfilePin, tok.ProfileMode, true + } + b, err := getOAuthBindingTx(tx, clientID) + require.NoError(t, err) + if b != nil { + oPin, oMode, oOK = b.ProfilePin, b.ProfileMode, true + } + return nil + })) + return +} + +func assertEqualBindings(t *testing.T, m *Manager, clientID, pin, mode string) { + t.Helper() + apiPin, apiMode, apiOK, oPin, oMode, oOK := bindings(t, m, clientID) + require.True(t, apiOK && oOK, "both records must exist") + assert.Equal(t, pin, apiPin, "api pin") + assert.Equal(t, mode, apiMode, "api mode") + assert.Equal(t, pin, oPin, "oauth pin") + assert.Equal(t, mode, oMode, "oauth mode") +} + +// clientWithBoth: an API-key client that also got a first browser login. +func clientWithBoth(t *testing.T, m *Manager, clientID, mode, pin string) { + t.Helper() + mintTestClient(t, m, clientID, mode, pin) + now := time.Now().UTC() + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg-"+clientID, now))) + rev, err := m.ClientBindingRevision(clientID) + require.NoError(t, err) + _, err = m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("grant-"+clientID, "reg-"+clientID, clientID, now), Client: clientID, + ExpectedBindingRevision: rev, Now: now, + }) + require.NoError(t, err) +} + +func TestWriteClientBindingTx(t *testing.T) { + t.Run("both records in one tx", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "ro") + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + return writeClientBindingTx(tx, "cursor", "full", auth.ProfileModeSwitchable) + })) + assertEqualBindings(t, m, "cursor", "full", auth.ProfileModeSwitchable) + }) + + t.Run("OAuth-only client", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "ro", auth.ProfileModeLocked, time.Now()) + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + return writeClientBindingTx(tx, "webonly", "full", auth.ProfileModeLocked) + })) + _, _, apiOK, oPin, oMode, oOK := bindings(t, m, "webonly") + assert.False(t, apiOK) + assert.True(t, oOK) + assert.Equal(t, "full", oPin) + assert.Equal(t, auth.ProfileModeLocked, oMode) + }) + + t.Run("API-key-only client never gets an OAuth entry", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + mintTestClient(t, m, "cursor", auth.ProfileModeLocked, "ro") + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + return writeClientBindingTx(tx, "cursor", "full", auth.ProfileModeLocked) + })) + _, _, _, _, _, oOK := bindings(t, m, "cursor") + assert.False(t, oOK) + assert.Empty(t, oauthBucketNames(t, m)) + }) + + t.Run("fails when neither exists", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + err := m.db.db.Update(func(tx *bbolt.Tx) error { + return writeClientBindingTx(tx, "ghost", "x", auth.ProfileModeLocked) + }) + assert.ErrorIs(t, err, ErrClientCredentialNotFound) + }) +} + +func TestUpdateClientCredentialBinding_KeepsOAuthEntryEqual(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "ro") + _, _, err := m.UpdateClientCredentialBinding("cursor", "full", auth.ProfileModeSwitchable) + require.NoError(t, err) + assertEqualBindings(t, m, "cursor", "full", auth.ProfileModeSwitchable) + + // A refused update writes neither record. + _, _, err = m.UpdateClientCredentialBinding("cursor", "", auth.ProfileModeLocked) + require.Error(t, err) + assertEqualBindings(t, m, "cursor", "full", auth.ProfileModeSwitchable) +} + +func TestMintForOAuthOnlyClient_SnapshotsAndRollbackRestores(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "ro", auth.ProfileModeLocked, time.Now()) + + rec := mintTestClient(t, m, "webonly", auth.ProfileModeSwitchable, "") + require.NotEmpty(t, rec) + // One binding: the requested (wider) one on both records. + assertEqualBindings(t, m, "webonly", "", auth.ProfileModeSwitchable) + tok, err := m.GetAgentTokenByName("client-webonly") + require.NoError(t, err) + assert.Equal(t, "ro", tok.PriorProfilePin, "the OAuth binding was snapshotted") + assert.Equal(t, auth.ProfileModeLocked, tok.PriorProfileMode) + + // An aborted/undone connect restores the snapshot to the OAuth entry and + // leaves the grant alone. + _, err = m.ForgetClientCredentialRestoringPrior("webonly") + require.NoError(t, err) + assertEqualBindings(t, m, "webonly", "ro", auth.ProfileModeLocked) + g, err := m.GetOAuthGrant("g1") + require.NoError(t, err) + assert.False(t, g.Revoked) + b, _ := m.GetOAuthClientBinding("webonly") + require.NotNil(t, b) +} + +func TestReconnectKeepsBothRecordsEqual(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "ro") + + _, err := m.RevokeClientAPIKey("cursor") + require.NoError(t, err) + assertEqualBindings(t, m, "cursor", "ro", auth.ProfileModeLocked) + + // Re-mint over the revoked tombstone with a new binding. + mintTestClient(t, m, "cursor", auth.ProfileModeLocked, "full") + assertEqualBindings(t, m, "cursor", "full", auth.ProfileModeLocked) + + // Undo of that reconnect puts the tombstone's old binding back on both. + _, err = m.ForgetClientCredentialRestoringPrior("cursor") + require.NoError(t, err) + assertEqualBindings(t, m, "cursor", "ro", auth.ProfileModeLocked) +} + +func TestRepinProfile_MovesOAuthOnlyClientAndRestorePinsRestores(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "old", auth.ProfileModeLocked, time.Now()) + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "old") + commitNew(t, m, "r2", "g2", "other", "keep", auth.ProfileModeLocked, time.Now()) + + before, err := m.RepinProfile("old", "new") + require.NoError(t, err) + require.Len(t, before, 2, "the API-key client and the OAuth-only client") + + _, _, apiOK, oPin, oMode, oOK := bindings(t, m, "webonly") + assert.False(t, apiOK) + assert.True(t, oOK) + assert.Equal(t, "new", oPin) + assert.Equal(t, auth.ProfileModeLocked, oMode) + assertEqualBindings(t, m, "cursor", "new", auth.ProfileModeLocked) + _, _, _, oPin, _, _ = bindings(t, m, "other") + assert.Equal(t, "keep", oPin, "an unrelated client does not move") + + require.NoError(t, m.RestorePins(before)) + _, _, _, oPin, _, _ = bindings(t, m, "webonly") + assert.Equal(t, "old", oPin) + assertEqualBindings(t, m, "cursor", "old", auth.ProfileModeLocked) +} + +func TestRepinProfile_FailureLeavesOAuthEntriesUnchanged(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "old", auth.ProfileModeLocked, time.Now()) + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "old") + + boom := errors.New("boom") + _, err := m.repinProfile("old", "new", func(written int) error { + if written == 1 { + return boom + } + return nil + }) + require.ErrorIs(t, err, boom) + assertEqualBindings(t, m, "cursor", "old", auth.ProfileModeLocked) + _, _, _, oPin, _, _ := bindings(t, m, "webonly") + assert.Equal(t, "old", oPin) +} + +func TestRepairOAuthClientBindings_TakesAPIKeyRecord(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "ro") + clientWithBoth(t, m, "zed", auth.ProfileModeSwitchable, "") + commitNew(t, m, "r", "g1", "webonly", "x", auth.ProfileModeLocked, time.Now()) + + // Drift the OAuth entry of cursor behind the writer's back. + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + return oauthPutJSON(tx, OAuthClientBindingsBucket, "cursor", &OAuthClientBinding{ + ProfilePin: "stale", ProfileMode: auth.ProfileModeSwitchable, UpdatedAt: time.Now(), + }) + })) + repaired, err := m.RepairOAuthClientBindings() + require.NoError(t, err) + assert.Equal(t, []string{"cursor"}, repaired) + assertEqualBindings(t, m, "cursor", "ro", auth.ProfileModeLocked) + + repaired, err = m.RepairOAuthClientBindings() + require.NoError(t, err) + assert.Empty(t, repaired) +} + +// TestDowngradeView_APIKeyRecordStaysCurrent (FR-028): a binary that predates +// browser logins reads only the agent_tokens record, so after a reassign, a +// rename and a reconnect the raw record must carry the current pin and mode. +func TestDowngradeView_APIKeyRecordStaysCurrent(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "p1") + + raw := func() (pin, mode string) { + var rec auth.AgentToken + require.NoError(t, m.db.db.View(func(tx *bbolt.Tx) error { + return tx.Bucket([]byte(AgentTokensBucket)).ForEach(func(_, v []byte) error { + var t auth.AgentToken + if json.Unmarshal(v, &t) == nil && t.Name == "client-cursor" { + rec = t + } + return nil + }) + })) + return rec.ProfilePin, rec.ProfileMode + } + + // reassign + _, _, err := m.UpdateClientCredentialBinding("cursor", "p2", auth.ProfileModeLocked) + require.NoError(t, err) + pin, mode := raw() + assert.Equal(t, "p2", pin) + assert.Equal(t, auth.ProfileModeLocked, mode) + + // rename + _, err = m.RepinProfile("p2", "p3") + require.NoError(t, err) + pin, _ = raw() + assert.Equal(t, "p3", pin) + + // reconnect (revoke key, mint again with another binding) + _, err = m.RevokeClientAPIKey("cursor") + require.NoError(t, err) + mintTestClient(t, m, "cursor", auth.ProfileModeSwitchable, "") + pin, mode = raw() + assert.Equal(t, "", pin) + assert.Equal(t, auth.ProfileModeSwitchable, mode) + assertEqualBindings(t, m, "cursor", "", auth.ProfileModeSwitchable) +} + +// TestClientBindingFieldsWrittenOnlyByAllowListedFunctions is the source test of +// research R4: an assignment to, or a composite-literal key of, ProfilePin or +// ProfileMode in this package's non-test code may appear only in the functions +// below. A new writer must go through writeClientBindingTx instead. +func TestClientBindingFieldsWrittenOnlyByAllowListedFunctions(t *testing.T) { + allowed := map[string]string{ + // THE writer of a client's pin/mode in both stores. + "writeClientBindingOptsTx": "the one binding writer", + // Builds the brand-new record literal; the OAuth entry is then synced + // through writeClientBindingTx in the same transaction. + "MintClientCredentialWith": "new client record literal", + // Assigns pin/mode on a COPY only to validate invariants and to return + // the after-snapshot; the stored write is writeClientBindingOptsTx. + "UpdateClientCredentialBinding": "validation copy and returned snapshot", + // Sets the restored binding on the returned (already stored) record; + // the stored restore is writeClientBindingTx. + "forgetClientCredential": "returned snapshot of the restored binding", + // Regular (non-client) agent tokens are rewritten directly; client + // records and OAuth-only entries go through writeClientBindingTx. The + // pseudo-record for an OAuth-only entry is a literal here. + "repinProfile": "plain pin rewrite of regular tokens, pseudo-record literal", + "RestorePins": "plain pin restore of regular tokens", + // Creates the OAuth-side entry at a client's first login (the only + // creator of oauth_client_bindings entries). + "CommitOAuthLogin": "creates the oauth_client_bindings entry", + } + + files, err := filepath.Glob("*.go") + require.NoError(t, err) + fset := token.NewFileSet() + isBindingField := func(name string) bool { return name == "ProfilePin" || name == "ProfileMode" } + var violations []string + used := map[string]bool{} + + for _, f := range files { + if strings.HasSuffix(f, "_test.go") { + continue + } + src, err := os.ReadFile(f) + require.NoError(t, err) + file, err := parser.ParseFile(fset, f, src, 0) + require.NoError(t, err) + for _, decl := range file.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + ast.Inspect(fn.Body, func(n ast.Node) bool { + var pos token.Pos + hit := false + switch x := n.(type) { + case *ast.AssignStmt: + for _, lhs := range x.Lhs { + if sel, ok := lhs.(*ast.SelectorExpr); ok && isBindingField(sel.Sel.Name) { + hit, pos = true, sel.Pos() + } + } + case *ast.KeyValueExpr: + if id, ok := x.Key.(*ast.Ident); ok && isBindingField(id.Name) { + hit, pos = true, id.Pos() + } + } + if hit { + if _, ok := allowed[fn.Name.Name]; ok { + used[fn.Name.Name] = true + } else { + violations = append(violations, fset.Position(pos).String()+" in "+fn.Name.Name) + } + } + return true + }) + } + } + sort.Strings(violations) + assert.Empty(t, violations, "route the write through writeClientBindingTx or justify a new allow-list entry") + for name := range allowed { + assert.True(t, used[name], "allow-list entry %s is stale (no such write any more); remove it", name) + } +} diff --git a/internal/storage/client_credentials.go b/internal/storage/client_credentials.go index 1b5d2ff84..c68d52606 100644 --- a/internal/storage/client_credentials.go +++ b/internal/storage/client_credentials.go @@ -205,6 +205,13 @@ func (m *Manager) MintClientCredentialWith(clientID, rawToken string, hmacKey [] if pendingBucket != nil && existing.PendingHash != "" { _ = pendingBucket.Delete([]byte(existing.PendingHash)) } + } else if ob, obErr := getOAuthBindingTx(tx, clientID); obErr != nil { + return obErr + } else if ob != nil { + // A client with only browser logins: snapshot its binding so an + // aborted or undone connect can put it back on the OAuth entry + // (Spec 132 R4). With no OAuth entry nothing is read or written. + token.PriorProfilePin, token.PriorProfileMode = ob.ProfilePin, ob.ProfileMode } count := tokenBucket.Stats().KeyN @@ -216,7 +223,12 @@ func (m *Manager) MintClientCredentialWith(clientID, rawToken string, hmacKey [] if err != nil { return fmt.Errorf("failed to marshal client credential: %w", err) } - return tokenBucket.Put([]byte(hash), data) + if err := tokenBucket.Put([]byte(hash), data); err != nil { + return err + } + // Keep one binding: the requested pin/mode also goes to the client's + // OAuth entry when it has one (Spec 132 R4). + return writeClientBindingTx(tx, clientID, pin, mode) }) if err != nil { return nil, err @@ -249,7 +261,7 @@ func (m *Manager) UpdateClientCredentialBinding(clientID, pin, mode string) (bef if tokenBucket == nil { return ErrClientCredentialNotFound } - primaryHash, existing, err := findClientTokenRecordLocked(tx, clientID) + _, existing, err := findClientTokenRecordLocked(tx, clientID) if err != nil { return err } @@ -272,11 +284,10 @@ func (m *Manager) UpdateClientCredentialBinding(clientID, pin, mode string) (bef if err := auth.ValidateTokenInvariants(&updated, auth.KindClient); err != nil { return fmt.Errorf("binding update produced an invalid client credential record: %w", err) } - data, err := json.Marshal(updated) - if err != nil { - return fmt.Errorf("failed to marshal client credential: %w", err) - } - if err := tokenBucket.Put(primaryHash, data); err != nil { + // `updated` only validates the result and is returned as the new + // snapshot; the stored write is the one binding writer, which also + // keeps the client's OAuth entry equal. + if err := writeClientBindingOptsTx(tx, clientID, pin, mode, true); err != nil { return fmt.Errorf("failed to store client binding: %w", err) } before, after = &snapshot, &updated @@ -560,9 +571,7 @@ func (m *Manager) forgetClientCredential(clientID string, restorePrior bool) (*a return ErrClientCredentialNotFound } markRevoked(tok, time.Now()) - if restorePrior && tok.PriorProfileMode != "" { - tok.ProfilePin, tok.ProfileMode = tok.PriorProfilePin, tok.PriorProfileMode - } + priorPin, priorMode := tok.PriorProfilePin, tok.PriorProfileMode tok.PriorProfilePin, tok.PriorProfileMode = "", "" data, err := json.Marshal(tok) if err != nil { @@ -571,6 +580,14 @@ func (m *Manager) forgetClientCredential(clientID string, restorePrior bool) (*a if err := tokenBucket.Put(primaryHash, data); err != nil { return fmt.Errorf("failed to store revoked client credential: %w", err) } + if restorePrior && priorMode != "" { + // Roll back the aborted connect's binding on BOTH records through + // the one binding writer; browser-login grants are not touched. + if err := writeClientBindingTx(tx, clientID, priorPin, priorMode); err != nil { + return err + } + tok.ProfilePin, tok.ProfileMode = priorPin, priorMode + } revoked = tok return nil }) diff --git a/internal/storage/oauth_login.go b/internal/storage/oauth_login.go new file mode 100644 index 000000000..49e1a8faa --- /dev/null +++ b/internal/storage/oauth_login.go @@ -0,0 +1,937 @@ +package storage + +import ( + "crypto/subtle" + "encoding/json" + "errors" + "fmt" + "sort" + "time" + "unicode/utf8" + + "go.etcd.io/bbolt" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// Spec 132 (browser login for MCP clients), storage layer. +// +// HARD RULE (FR-002, research R10): nothing here creates a bucket or a key +// unless a browser-login write actually happens. Every bucket below is LAZY: +// it is created with CreateBucketIfNotExists on a write path, never from +// initBuckets, and every reader treats a nil bucket as empty. A database that +// never saw a browser login therefore stays byte-for-byte what it was. +const ( + // OAuthRegistrationsBucket holds dynamic client registrations, key client_id. + OAuthRegistrationsBucket = "oauth_registrations" + // OAuthGrantsBucket holds browser-login grants, key grant_id. + OAuthGrantsBucket = "oauth_grants" + // OAuthGrantAccessIndexBucket maps access-token hash -> grant id. It is a + // sibling bucket (not a nested one) so ForEach over OAuthGrantsBucket only + // ever sees grant rows. + OAuthGrantAccessIndexBucket = "oauth_grant_access_index" + // OAuthClientBindingsBucket holds the binding copy of a client that has at + // least one grant record, key client id. + OAuthClientBindingsBucket = "oauth_client_bindings" + // OAuthLoginEverUsedKey is the MetaBucket marker holding the RFC 3339 time + // of the first stored grant. Never deleted. + OAuthLoginEverUsedKey = "oauth_login_ever_used" +) + +// Registration states (data-model.md). A denial is not a state. +const ( + OAuthRegistrationPending = "pending" + OAuthRegistrationAuthorized = "authorized" + OAuthRegistrationApproved = "approved" +) + +// Grant revoke reasons. +const ( + OAuthRevokeAdmin = "admin" + OAuthRevokeClientRevoked = "client_revoked" + OAuthRevokeReplaced = "replaced" + OAuthRevokeReplay = "replay" +) + +// Bounds from the data model. +const ( + // MaxUnapprovedOAuthRegistrations caps pending + authorized rows together. + MaxUnapprovedOAuthRegistrations = 50 + // OAuthPendingRegistrationTTL is how long a pending row lives from created_at. + OAuthPendingRegistrationTTL = 15 * time.Minute + // OAuthAuthorizedRegistrationTTL is how long an authorized row lives from authorized_at. + OAuthAuthorizedRegistrationTTL = 24 * time.Hour + // OAuthDeadGrantRetention is how long a revoked or lapsed grant is kept for display. + OAuthDeadGrantRetention = 30 * 24 * time.Hour +) + +// OAuthBindingAbsent is the revision of a client that has neither an API-key +// record nor a browser-login binding. +const OAuthBindingAbsent = "absent" + +// Sentinel errors of the browser-login storage surface. +var ( + // ErrOAuthRegistrationGone: the registration is not stored (evicted, swept + // or deleted with its last grant); it is never recreated from a code. + ErrOAuthRegistrationGone = errors.New("oauth registration not found") + // ErrOAuthClientExists: a decision that creates a new client found the id + // already held by an API-key record or a browser-login binding. + ErrOAuthClientExists = errors.New("client already exists") + // ErrOAuthBindingChanged: the client's binding revision is no longer the + // one the decision was made against. + ErrOAuthBindingChanged = errors.New("client binding changed since it was reviewed") + // ErrOAuthGrantNotFound: no such grant. + ErrOAuthGrantNotFound = errors.New("oauth grant not found") +) + +// OAuthActor names who approved a login. +type OAuthActor struct { + Kind string `json:"kind"` + Name string `json:"name,omitempty"` +} + +// OAuthRegistration is a dynamic client registration (data-model.md). +type OAuthRegistration struct { + ClientID string `json:"client_id"` + ReportedName string `json:"reported_name,omitempty"` + RedirectURIs []string `json:"redirect_uris"` + SoftwareID string `json:"software_id,omitempty"` + SoftwareVersion string `json:"software_version,omitempty"` + TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"` + GrantTypes []string `json:"grant_types"` + State string `json:"state"` + CreatedAt time.Time `json:"created_at"` + AuthorizedAt *time.Time `json:"authorized_at,omitempty"` +} + +// OAuthGrant is one browser login (data-model.md). +type OAuthGrant struct { + GrantID string `json:"grant_id"` + RegistrationID string `json:"registration_id"` + Client string `json:"client"` + RedirectURI string `json:"redirect_uri"` + Resource string `json:"resource"` + Issuer string `json:"issuer"` + RefreshHash string `json:"refresh_hash"` + RefreshPrefix string `json:"refresh_prefix"` + AccessHash string `json:"access_hash"` + AccessExpiresAt time.Time `json:"access_expires_at"` + RefreshExpiresAt time.Time `json:"refresh_expires_at"` + ApprovedAt time.Time `json:"approved_at"` + ApprovedBy OAuthActor `json:"approved_by"` + LastUsedAt *time.Time `json:"last_used_at,omitempty"` + ObservedClientName string `json:"observed_client_name,omitempty"` + ObservedAt *time.Time `json:"observed_at,omitempty"` + DisplayPrefix string `json:"display_prefix"` + Revoked bool `json:"revoked"` + RevokedAt *time.Time `json:"revoked_at,omitempty"` + RevokeReason string `json:"revoke_reason,omitempty"` + UserID string `json:"user_id,omitempty"` +} + +// OAuthClientBinding is the binding copy kept for a client with browser logins. +type OAuthClientBinding struct { + ProfilePin string `json:"profile_pin"` + ProfileMode string `json:"profile_mode"` + DisplayName string `json:"display_name,omitempty"` + UpdatedAt time.Time `json:"updated_at"` +} + +// Refresh rotation outcomes. +type RefreshOutcome int + +const ( + // RefreshInvalid: unknown, revoked or lapsed grant. Nothing was written. + RefreshInvalid RefreshOutcome = iota + // RefreshRotated: the presented secret was current; the grant rotated. + RefreshRotated + // RefreshReplay: the presented secret was an old one; the grant is revoked. + RefreshReplay +) + +// --- small bucket helpers (all nil-tolerant on the read side) --- + +func oauthGetJSON(tx *bbolt.Tx, bucket, key string, out any) (bool, error) { + b := tx.Bucket([]byte(bucket)) + if b == nil { + return false, nil + } + v := b.Get([]byte(key)) + if v == nil { + return false, nil + } + if err := json.Unmarshal(v, out); err != nil { + return false, fmt.Errorf("failed to unmarshal %s/%s: %w", bucket, key, err) + } + return true, nil +} + +func oauthPutJSON(tx *bbolt.Tx, bucket, key string, v any) error { + b, err := tx.CreateBucketIfNotExists([]byte(bucket)) + if err != nil { + return fmt.Errorf("failed to create %s bucket: %w", bucket, err) + } + data, err := json.Marshal(v) + if err != nil { + return fmt.Errorf("failed to marshal %s/%s: %w", bucket, key, err) + } + return b.Put([]byte(key), data) +} + +func oauthForEach[T any](tx *bbolt.Tx, bucket string, fn func(key string, v T) error) error { + b := tx.Bucket([]byte(bucket)) + if b == nil { + return nil + } + return b.ForEach(func(k, raw []byte) error { + var v T + if err := json.Unmarshal(raw, &v); err != nil { + return nil // skip unparseable rows, like the agent token scans + } + return fn(string(k), v) + }) +} + +func getOAuthBindingTx(tx *bbolt.Tx, clientID string) (*OAuthClientBinding, error) { + var b OAuthClientBinding + ok, err := oauthGetJSON(tx, OAuthClientBindingsBucket, clientID, &b) + if err != nil || !ok { + return nil, err + } + return &b, nil +} + +func getOAuthGrantTx(tx *bbolt.Tx, id string) (*OAuthGrant, error) { + var g OAuthGrant + ok, err := oauthGetJSON(tx, OAuthGrantsBucket, id, &g) + if err != nil || !ok { + return nil, err + } + return &g, nil +} + +func putOAuthGrantTx(tx *bbolt.Tx, g *OAuthGrant) error { + return oauthPutJSON(tx, OAuthGrantsBucket, g.GrantID, g) +} + +func deleteAccessIndexTx(tx *bbolt.Tx, accessHash string) error { + if accessHash == "" { + return nil + } + b := tx.Bucket([]byte(OAuthGrantAccessIndexBucket)) + if b == nil { + return nil + } + return b.Delete([]byte(accessHash)) +} + +func putAccessIndexTx(tx *bbolt.Tx, accessHash, grantID string) error { + if accessHash == "" { + return nil + } + b, err := tx.CreateBucketIfNotExists([]byte(OAuthGrantAccessIndexBucket)) + if err != nil { + return fmt.Errorf("failed to create %s bucket: %w", OAuthGrantAccessIndexBucket, err) + } + return b.Put([]byte(accessHash), []byte(grantID)) +} + +// revokeGrantTx marks g revoked (no-op when already revoked) and drops its +// access index entry. Reports whether it changed anything. +func revokeGrantTx(tx *bbolt.Tx, g *OAuthGrant, reason string, now time.Time) (bool, error) { + if g.Revoked { + return false, nil + } + at := now.UTC() + g.Revoked = true + g.RevokedAt = &at + g.RevokeReason = reason + if err := deleteAccessIndexTx(tx, g.AccessHash); err != nil { + return false, err + } + if err := putOAuthGrantTx(tx, g); err != nil { + return false, err + } + return true, nil +} + +// --- registrations --- + +// CreateOAuthRegistration stores a new pending registration. At most +// MaxUnapprovedOAuthRegistrations rows may be pending or authorized together; +// when the cap is exceeded the OLDEST such row is dropped in the same +// transaction (approved rows are never evicted). +func (m *Manager) CreateOAuthRegistration(reg OAuthRegistration) error { + if reg.ClientID == "" { + return fmt.Errorf("registration needs a client id") + } + reg.State = OAuthRegistrationPending + reg.AuthorizedAt = nil + if reg.CreatedAt.IsZero() { + reg.CreatedAt = time.Now() + } + reg.CreatedAt = reg.CreatedAt.UTC() + + m.mu.Lock() + defer m.mu.Unlock() + return m.db.db.Update(func(tx *bbolt.Tx) error { + if err := oauthPutJSON(tx, OAuthRegistrationsBucket, reg.ClientID, ®); err != nil { + return err + } + type row struct { + id string + at time.Time + } + var open []row + if err := oauthForEach(tx, OAuthRegistrationsBucket, func(key string, r OAuthRegistration) error { + if r.State != OAuthRegistrationApproved && key != reg.ClientID { + open = append(open, row{key, r.CreatedAt}) + } + return nil + }); err != nil { + return err + } + // The new row counts toward the cap. + excess := len(open) + 1 - MaxUnapprovedOAuthRegistrations + if excess <= 0 { + return nil + } + sort.Slice(open, func(i, j int) bool { + if open[i].at.Equal(open[j].at) { + return open[i].id < open[j].id + } + return open[i].at.Before(open[j].at) + }) + b := tx.Bucket([]byte(OAuthRegistrationsBucket)) + for _, r := range open[:excess] { + if err := b.Delete([]byte(r.id)); err != nil { + return err + } + } + return nil + }) +} + +// GetOAuthRegistration returns the registration, or ErrOAuthRegistrationGone. +func (m *Manager) GetOAuthRegistration(id string) (*OAuthRegistration, error) { + m.mu.RLock() + defer m.mu.RUnlock() + var reg OAuthRegistration + var found bool + err := m.db.db.View(func(tx *bbolt.Tx) error { + var err error + found, err = oauthGetJSON(tx, OAuthRegistrationsBucket, id, ®) + return err + }) + if err != nil { + return nil, err + } + if !found { + return nil, ErrOAuthRegistrationGone + } + return ®, nil +} + +// MarkOAuthRegistrationAuthorized moves pending -> authorized and stamps +// authorized_at. An authorized row keeps its first stamp; an approved row is +// left alone. +func (m *Manager) MarkOAuthRegistrationAuthorized(id string, at time.Time) error { + m.mu.Lock() + defer m.mu.Unlock() + return m.db.db.Update(func(tx *bbolt.Tx) error { + var reg OAuthRegistration + ok, err := oauthGetJSON(tx, OAuthRegistrationsBucket, id, ®) + if err != nil { + return err + } + if !ok { + return ErrOAuthRegistrationGone + } + if reg.State != OAuthRegistrationPending { + return nil + } + t := at.UTC() + reg.State = OAuthRegistrationAuthorized + reg.AuthorizedAt = &t + return oauthPutJSON(tx, OAuthRegistrationsBucket, id, ®) + }) +} + +// SweepOAuthRegistrations deletes pending rows older than 15 minutes (from +// created_at) and authorized rows older than 24 hours (from authorized_at). +// Approved rows are never swept. It returns how many rows it deleted. +func (m *Manager) SweepOAuthRegistrations(now time.Time) (int, error) { + m.mu.Lock() + defer m.mu.Unlock() + deleted := 0 + err := m.db.db.Update(func(tx *bbolt.Tx) error { + b := tx.Bucket([]byte(OAuthRegistrationsBucket)) + if b == nil { + return nil + } + var drop []string + if err := oauthForEach(tx, OAuthRegistrationsBucket, func(key string, r OAuthRegistration) error { + switch r.State { + case OAuthRegistrationPending: + if now.Sub(r.CreatedAt) > OAuthPendingRegistrationTTL { + drop = append(drop, key) + } + case OAuthRegistrationAuthorized: + at := r.CreatedAt + if r.AuthorizedAt != nil { + at = *r.AuthorizedAt + } + if now.Sub(at) > OAuthAuthorizedRegistrationTTL { + drop = append(drop, key) + } + } + return nil + }); err != nil { + return err + } + for _, k := range drop { + if err := b.Delete([]byte(k)); err != nil { + return err + } + } + deleted = len(drop) + return nil + }) + return deleted, err +} + +// ListOAuthRegistrations returns every stored registration. +func (m *Manager) ListOAuthRegistrations() ([]OAuthRegistration, error) { + m.mu.RLock() + defer m.mu.RUnlock() + var out []OAuthRegistration + err := m.db.db.View(func(tx *bbolt.Tx) error { + return oauthForEach(tx, OAuthRegistrationsBucket, func(_ string, r OAuthRegistration) error { + out = append(out, r) + return nil + }) + }) + return out, err +} + +// --- binding revision --- + +// clientBindingRevisionTx is the revision of the client's current binding: +// the first 8 bytes of sha256(client|pin|mode), hex. The API-key record wins +// over the browser-login entry; a client with neither is OAuthBindingAbsent. +func clientBindingRevisionTx(tx *bbolt.Tx, clientID string) (string, error) { + pin, mode, exists, err := currentClientBindingTx(tx, clientID) + if err != nil { + return "", err + } + if !exists { + return OAuthBindingAbsent, nil + } + return bindingRevision(clientID, pin, mode), nil +} + +// currentClientBindingTx reads a client's binding: from the API-key (kind +// client) record when there is one, else from the browser-login entry. +func currentClientBindingTx(tx *bbolt.Tx, clientID string) (pin, mode string, exists bool, err error) { + _, tok, err := findClientTokenRecordLocked(tx, clientID) + if err != nil { + return "", "", false, err + } + if tok != nil && tok.Kind == auth.KindClient { + return tok.ProfilePin, tok.ProfileMode, true, nil + } + b, err := getOAuthBindingTx(tx, clientID) + if err != nil { + return "", "", false, err + } + if b != nil { + return b.ProfilePin, b.ProfileMode, true, nil + } + return "", "", false, nil +} + +// ClientBindingRevision returns the binding revision the consent page shows +// and sends back; see clientBindingRevisionTx. +func (m *Manager) ClientBindingRevision(clientID string) (string, error) { + m.mu.RLock() + defer m.mu.RUnlock() + var rev string + err := m.db.db.View(func(tx *bbolt.Tx) error { + var err error + rev, err = clientBindingRevisionTx(tx, clientID) + return err + }) + return rev, err +} + +// --- grants --- + +// CommitLoginInput is everything the token exchange hands to CommitOAuthLogin. +type CommitLoginInput struct { + // Grant is the prepared grant; Client and RegistrationID must be set. + Grant OAuthGrant + // Client is the Clients hub client id (must equal Grant.Client). + Client string + // NewClient: the decision creates a client; the id must be absent. + NewClient bool + // Pin, Mode, DisplayName are the binding of a NEW client. An existing + // API-key client's entry is always copied from its current record. + Pin, Mode, DisplayName string + // ExpectedBindingRevision is the revision the consent page displayed. + ExpectedBindingRevision string + // ReplaceGrantID, when set, names a login of the same client to revoke + // with reason "replaced". + ReplaceGrantID string + // Now stamps the binding entry and the ever-used marker. + Now time.Time +} + +// CommitOAuthLogin stores a browser login in ONE transaction (research R15): +// it re-checks the registration, the new-client id and the binding revision, +// creates the OAuth-side binding when the client has none, promotes the +// registration to approved, stores the grant, revokes the replaced login and +// writes the ever-used marker. Any failed check leaves the database untouched. +func (m *Manager) CommitOAuthLogin(in CommitLoginInput) (OAuthGrant, error) { + g := in.Grant + if in.Client == "" { + in.Client = g.Client + } + if g.Client == "" { + g.Client = in.Client + } + if g.GrantID == "" || g.RegistrationID == "" || !auth.ValidClientID(in.Client) || g.Client != in.Client { + return OAuthGrant{}, fmt.Errorf("invalid login: grant id, registration id and a matching client id are required") + } + now := in.Now + if now.IsZero() { + now = time.Now() + } + now = now.UTC() + + m.mu.Lock() + defer m.mu.Unlock() + + var stored OAuthGrant + err := m.db.db.Update(func(tx *bbolt.Tx) error { + // (1) the registration must still exist. + var reg OAuthRegistration + ok, err := oauthGetJSON(tx, OAuthRegistrationsBucket, g.RegistrationID, ®) + if err != nil { + return err + } + if !ok { + return ErrOAuthRegistrationGone + } + + // (2) a decision that creates a client needs the id absent everywhere. + _, anyRecord, err := findClientTokenRecordLocked(tx, in.Client) + if err != nil { + return err + } + existingBinding, err := getOAuthBindingTx(tx, in.Client) + if err != nil { + return err + } + if in.NewClient && (anyRecord != nil || existingBinding != nil) { + return ErrOAuthClientExists + } + + // (3) the binding the administrator reviewed is still the binding. + rev, err := clientBindingRevisionTx(tx, in.Client) + if err != nil { + return err + } + if rev != in.ExpectedBindingRevision { + return ErrOAuthBindingChanged + } + if !in.NewClient && rev == OAuthBindingAbsent { + // An existing-client decision whose client vanished: there is no + // binding to copy and none to create from input. + return ErrOAuthBindingChanged + } + + // (4) create the OAuth-side binding when the client has none. + if existingBinding == nil { + nb := OAuthClientBinding{UpdatedAt: now} + if in.NewClient { + if in.Mode != auth.ProfileModeLocked && in.Mode != auth.ProfileModeSwitchable { + return fmt.Errorf("invalid profile mode %q", in.Mode) + } + if in.Mode == auth.ProfileModeLocked && in.Pin == "" { + return fmt.Errorf("a locked client binding requires a non-empty profile") + } + if utf8.RuneCountInString(in.DisplayName) > auth.MaxClientDisplayName { + return fmt.Errorf("client display name is too long") + } + nb.ProfilePin, nb.ProfileMode, nb.DisplayName = in.Pin, in.Mode, in.DisplayName + } else { + pin, mode, exists, err := currentClientBindingTx(tx, in.Client) + if err != nil { + return err + } + if !exists { + return ErrOAuthBindingChanged + } + nb.ProfilePin, nb.ProfileMode = pin, mode + if anyRecord != nil { + nb.DisplayName = anyRecord.DisplayName + } + } + if err := oauthPutJSON(tx, OAuthClientBindingsBucket, in.Client, &nb); err != nil { + return err + } + } + + // (5) the registration becomes approved. + reg.State = OAuthRegistrationApproved + if err := oauthPutJSON(tx, OAuthRegistrationsBucket, reg.ClientID, ®); err != nil { + return err + } + + // (6) the grant. + if prev, err := getOAuthGrantTx(tx, g.GrantID); err != nil { + return err + } else if prev != nil { + return fmt.Errorf("grant %s already exists", g.GrantID) + } + g.Revoked, g.RevokedAt, g.RevokeReason = false, nil, "" + if err := putOAuthGrantTx(tx, &g); err != nil { + return err + } + if err := putAccessIndexTx(tx, g.AccessHash, g.GrantID); err != nil { + return err + } + + // (7) the replaced login, only when it belongs to the same client. + if in.ReplaceGrantID != "" && in.ReplaceGrantID != g.GrantID { + old, err := getOAuthGrantTx(tx, in.ReplaceGrantID) + if err != nil { + return err + } + if old != nil && old.Client == in.Client { + if _, err := revokeGrantTx(tx, old, OAuthRevokeReplaced, now); err != nil { + return err + } + } + } + + // (8) the ever-used marker, kept once. + meta, err := tx.CreateBucketIfNotExists([]byte(MetaBucket)) + if err != nil { + return err + } + if meta.Get([]byte(OAuthLoginEverUsedKey)) == nil { + if err := meta.Put([]byte(OAuthLoginEverUsedKey), []byte(now.Format(time.RFC3339))); err != nil { + return err + } + } + stored = g + return nil + }) + if err != nil { + return OAuthGrant{}, err + } + return stored, nil +} + +// GetOAuthGrant returns the grant, or ErrOAuthGrantNotFound. +func (m *Manager) GetOAuthGrant(id string) (*OAuthGrant, error) { + m.mu.RLock() + defer m.mu.RUnlock() + var g *OAuthGrant + err := m.db.db.View(func(tx *bbolt.Tx) error { + var err error + g, err = getOAuthGrantTx(tx, id) + return err + }) + if err != nil { + return nil, err + } + if g == nil { + return nil, ErrOAuthGrantNotFound + } + return g, nil +} + +// ListOAuthGrants returns every stored grant. +func (m *Manager) ListOAuthGrants() ([]OAuthGrant, error) { + m.mu.RLock() + defer m.mu.RUnlock() + var out []OAuthGrant + err := m.db.db.View(func(tx *bbolt.Tx) error { + return oauthForEach(tx, OAuthGrantsBucket, func(_ string, g OAuthGrant) error { + out = append(out, g) + return nil + }) + }) + return out, err +} + +// ListOAuthGrantsForClient returns the grants of one client, newest approval first. +func (m *Manager) ListOAuthGrantsForClient(clientID string) ([]OAuthGrant, error) { + all, err := m.ListOAuthGrants() + if err != nil { + return nil, err + } + var out []OAuthGrant + for _, g := range all { + if g.Client == clientID { + out = append(out, g) + } + } + sort.Slice(out, func(i, j int) bool { return out[i].ApprovedAt.After(out[j].ApprovedAt) }) + return out, nil +} + +// GetOAuthGrantByAccessHash resolves an access-token hash to its grant through +// the index, re-checking that the grant still carries that hash. A missing or +// stale entry is ErrOAuthGrantNotFound. Revocation and expiry are the +// caller's decision (it needs the grant to report them). +func (m *Manager) GetOAuthGrantByAccessHash(hash string) (*OAuthGrant, error) { + if hash == "" { + return nil, ErrOAuthGrantNotFound + } + m.mu.RLock() + defer m.mu.RUnlock() + var g *OAuthGrant + err := m.db.db.View(func(tx *bbolt.Tx) error { + idx := tx.Bucket([]byte(OAuthGrantAccessIndexBucket)) + if idx == nil { + return nil + } + id := idx.Get([]byte(hash)) + if id == nil { + return nil + } + cand, err := getOAuthGrantTx(tx, string(id)) + if err != nil || cand == nil { + return err + } + if subtle.ConstantTimeCompare([]byte(cand.AccessHash), []byte(hash)) == 1 { + g = cand + } + return nil + }) + if err != nil { + return nil, err + } + if g == nil { + return nil, ErrOAuthGrantNotFound + } + return g, nil +} + +// RotateOAuthRefresh is the refresh-token exchange, in one transaction. The +// caller has already verified the token's MAC; storage sees hashes only. +// +// - unknown, revoked or lapsed grant: RefreshInvalid, nothing written, the +// lifetime is not extended; +// - presented hash equals the current one (constant time): rotate; +// - anything else: the grant is revoked with reason "replay". +func (m *Manager) RotateOAuthRefresh(grantID, presentedSecretHash, newRefreshHash, newRefreshPrefix, newAccessHash string, now time.Time, accessTTL, refreshTTL time.Duration) (RefreshOutcome, OAuthGrant, error) { + now = now.UTC() + m.mu.Lock() + defer m.mu.Unlock() + + // Refuse an unknown, revoked or lapsed grant in a read-only transaction: + // a refused refresh must not commit anything (and never extends a lifetime). + live := false + if err := m.db.db.View(func(tx *bbolt.Tx) error { + g, err := getOAuthGrantTx(tx, grantID) + live = err == nil && g != nil && !g.Revoked && g.RefreshExpiresAt.After(now) + return err + }); err != nil { + return RefreshInvalid, OAuthGrant{}, err + } + if !live { + return RefreshInvalid, OAuthGrant{}, nil + } + + outcome := RefreshInvalid + var result OAuthGrant + err := m.db.db.Update(func(tx *bbolt.Tx) error { + g, err := getOAuthGrantTx(tx, grantID) + if err != nil { + return err + } + if g == nil || g.Revoked || !g.RefreshExpiresAt.After(now) { + return nil + } + if presentedSecretHash != "" && subtle.ConstantTimeCompare([]byte(presentedSecretHash), []byte(g.RefreshHash)) == 1 { + if err := deleteAccessIndexTx(tx, g.AccessHash); err != nil { + return err + } + g.RefreshHash = newRefreshHash + g.RefreshPrefix = newRefreshPrefix + g.AccessHash = newAccessHash + g.AccessExpiresAt = now.Add(accessTTL) + g.RefreshExpiresAt = now.Add(refreshTTL) + if err := putOAuthGrantTx(tx, g); err != nil { + return err + } + if err := putAccessIndexTx(tx, g.AccessHash, g.GrantID); err != nil { + return err + } + outcome, result = RefreshRotated, *g + return nil + } + if _, err := revokeGrantTx(tx, g, OAuthRevokeReplay, now); err != nil { + return err + } + outcome, result = RefreshReplay, *g + return nil + }) + if err != nil { + return RefreshInvalid, OAuthGrant{}, err + } + return outcome, result, nil +} + +// RevokeOAuthGrant revokes one grant. It reports whether the grant changed +// (an already revoked grant is not an error and keeps its first reason). +func (m *Manager) RevokeOAuthGrant(id, reason string, now time.Time) (bool, error) { + m.mu.Lock() + defer m.mu.Unlock() + changed := false + err := m.db.db.Update(func(tx *bbolt.Tx) error { + g, err := getOAuthGrantTx(tx, id) + if err != nil { + return err + } + if g == nil { + return ErrOAuthGrantNotFound + } + changed, err = revokeGrantTx(tx, g, reason, now) + return err + }) + return changed, err +} + +// TouchOAuthGrant stamps last_used_at and, when non-empty, the observed client +// name. Best effort, off the request path, like UpdateAgentTokenLastUsedByHash. +func (m *Manager) TouchOAuthGrant(id string, lastUsedAt time.Time, observedName string) error { + m.mu.Lock() + defer m.mu.Unlock() + return m.db.db.Update(func(tx *bbolt.Tx) error { + g, err := getOAuthGrantTx(tx, id) + if err != nil { + return err + } + if g == nil { + return ErrOAuthGrantNotFound + } + t := lastUsedAt.UTC() + g.LastUsedAt = &t + if observedName != "" { + g.ObservedClientName = observedName + g.ObservedAt = &t + } + return putOAuthGrantTx(tx, g) + }) +} + +// SweepOAuthGrants deletes grants that were revoked, or whose refresh token +// lapsed, more than 30 days ago. A registration whose last grant record goes +// is deleted with it, and so is the binding entry of a client whose last grant +// record goes. It returns the number of grants deleted. +func (m *Manager) SweepOAuthGrants(now time.Time) (int, error) { + m.mu.Lock() + defer m.mu.Unlock() + deleted := 0 + err := m.db.db.Update(func(tx *bbolt.Tx) error { + gb := tx.Bucket([]byte(OAuthGrantsBucket)) + if gb == nil { + return nil + } + var dead []OAuthGrant + survivingReg := map[string]bool{} + survivingClient := map[string]bool{} + if err := oauthForEach(tx, OAuthGrantsBucket, func(_ string, g OAuthGrant) error { + var since time.Time + if g.Revoked { + if g.RevokedAt != nil { + since = *g.RevokedAt + } else { + since = g.ApprovedAt + } + } else if !g.RefreshExpiresAt.After(now) { + since = g.RefreshExpiresAt + } + if !since.IsZero() && now.Sub(since) > OAuthDeadGrantRetention { + dead = append(dead, g) + return nil + } + survivingReg[g.RegistrationID] = true + survivingClient[g.Client] = true + return nil + }); err != nil { + return err + } + for _, g := range dead { + if err := gb.Delete([]byte(g.GrantID)); err != nil { + return err + } + if err := deleteAccessIndexTx(tx, g.AccessHash); err != nil { + return err + } + if !survivingReg[g.RegistrationID] { + if rb := tx.Bucket([]byte(OAuthRegistrationsBucket)); rb != nil { + if err := rb.Delete([]byte(g.RegistrationID)); err != nil { + return err + } + } + } + if !survivingClient[g.Client] { + if bb := tx.Bucket([]byte(OAuthClientBindingsBucket)); bb != nil { + if err := bb.Delete([]byte(g.Client)); err != nil { + return err + } + } + } + } + deleted = len(dead) + return nil + }) + return deleted, err +} + +// OAuthLoginEverUsed reports whether a browser login was ever stored. +func (m *Manager) OAuthLoginEverUsed() (bool, error) { + m.mu.RLock() + defer m.mu.RUnlock() + used := false + err := m.db.db.View(func(tx *bbolt.Tx) error { + meta := tx.Bucket([]byte(MetaBucket)) + used = meta != nil && meta.Get([]byte(OAuthLoginEverUsedKey)) != nil + return nil + }) + return used, err +} + +// GetOAuthClientBinding returns a client's browser-login binding entry, or nil +// when it has none. +func (m *Manager) GetOAuthClientBinding(clientID string) (*OAuthClientBinding, error) { + m.mu.RLock() + defer m.mu.RUnlock() + var b *OAuthClientBinding + err := m.db.db.View(func(tx *bbolt.Tx) error { + var err error + b, err = getOAuthBindingTx(tx, clientID) + return err + }) + return b, err +} + +// ListOAuthClientBindings returns every browser-login binding entry by client id. +func (m *Manager) ListOAuthClientBindings() (map[string]OAuthClientBinding, error) { + m.mu.RLock() + defer m.mu.RUnlock() + out := map[string]OAuthClientBinding{} + err := m.db.db.View(func(tx *bbolt.Tx) error { + return oauthForEach(tx, OAuthClientBindingsBucket, func(k string, b OAuthClientBinding) error { + out[k] = b + return nil + }) + }) + return out, err +} diff --git a/internal/storage/oauth_login_client_ops_test.go b/internal/storage/oauth_login_client_ops_test.go new file mode 100644 index 000000000..8c58799c1 --- /dev/null +++ b/internal/storage/oauth_login_client_ops_test.go @@ -0,0 +1,171 @@ +package storage + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// twoLoginClient: an API-key client with two browser logins on two registrations, +// plus a bystander client with one login, so deletions can be checked for reach. +func twoLoginClient(t *testing.T, m *Manager) { + t.Helper() + now := time.Now().UTC() + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "ro") // grant-cursor on reg-cursor + rev, err := m.ClientBindingRevision("cursor") + require.NoError(t, err) + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg-cursor-2", now))) + _, err = m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("grant-cursor-2", "reg-cursor-2", "cursor", now), Client: "cursor", + ExpectedBindingRevision: rev, Now: now, + }) + require.NoError(t, err) + commitNew(t, m, "reg-by", "grant-by", "bystander", "", auth.ProfileModeSwitchable, now) +} + +func TestForgetClient_DeletesLoginsBindingAndOrphanRegistrations(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + twoLoginClient(t, m) + + rec, err := m.ForgetClient("cursor") + require.NoError(t, err) + require.NotNil(t, rec) + assert.True(t, rec.Revoked, "the API key is revoked exactly as ForgetClientCredential does") + + gs, err := m.ListOAuthGrantsForClient("cursor") + require.NoError(t, err) + assert.Empty(t, gs) + _, err = m.GetOAuthGrantByAccessHash("ah-grant-cursor") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + b, _ := m.GetOAuthClientBinding("cursor") + assert.Nil(t, b) + for _, id := range []string{"reg-cursor", "reg-cursor-2"} { + _, err = m.GetOAuthRegistration(id) + assert.ErrorIs(t, err, ErrOAuthRegistrationGone, id) + } + + // The bystander is untouched. + _, err = m.GetOAuthGrant("grant-by") + require.NoError(t, err) + _, err = m.GetOAuthRegistration("reg-by") + require.NoError(t, err) + b, _ = m.GetOAuthClientBinding("bystander") + assert.NotNil(t, b) + used, _ := m.OAuthLoginEverUsed() + assert.True(t, used) +} + +func TestForgetClient_OAuthOnlyClientAndNothing(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "", auth.ProfileModeSwitchable, time.Now()) + + rec, err := m.ForgetClient("webonly") + require.NoError(t, err) + assert.Nil(t, rec, "no API-key record") + _, err = m.GetOAuthGrant("g1") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + + _, err = m.ForgetClient("webonly") + assert.ErrorIs(t, err, ErrClientCredentialNotFound, "nothing left") +} + +func TestForgetClientLogins_LeavesAPIKeyAlone(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + twoLoginClient(t, m) + + n, err := m.ForgetClientLogins("cursor") + require.NoError(t, err) + assert.Equal(t, 2, n) + rec, err := m.GetAgentTokenByName("client-cursor") + require.NoError(t, err) + assert.False(t, rec.Revoked) + b, _ := m.GetOAuthClientBinding("cursor") + assert.Nil(t, b) +} + +func TestRevokeClient_RevokesKeyAndAllGrantsKeepsRecords(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + twoLoginClient(t, m) + now := time.Now().UTC() + + rec, err := m.RevokeClient("cursor", now) + require.NoError(t, err) + require.NotNil(t, rec) + assert.True(t, rec.Revoked) + + gs, err := m.ListOAuthGrantsForClient("cursor") + require.NoError(t, err) + require.Len(t, gs, 2) + for _, g := range gs { + assert.True(t, g.Revoked, g.GrantID) + assert.Equal(t, OAuthRevokeClientRevoked, g.RevokeReason) + require.NotNil(t, g.RevokedAt) + } + _, err = m.GetOAuthGrantByAccessHash("ah-grant-cursor") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound, "revoked grants leave the access index") + b, _ := m.GetOAuthClientBinding("cursor") + assert.NotNil(t, b, "the binding entry is kept for display") + _, err = m.GetOAuthRegistration("reg-cursor") + assert.NoError(t, err) + + by, err := m.GetOAuthGrant("grant-by") + require.NoError(t, err) + assert.False(t, by.Revoked) + + // An OAuth-only client revokes too; nothing at all is NotFound. + commitNew(t, m, "r", "g1", "webonly", "", auth.ProfileModeSwitchable, now) + rec, err = m.RevokeClient("webonly", now) + require.NoError(t, err) + assert.Nil(t, rec) + g, _ := m.GetOAuthGrant("g1") + assert.True(t, g.Revoked) + _, err = m.RevokeClient("ghost", now) + assert.ErrorIs(t, err, ErrClientCredentialNotFound) +} + +func TestRevokeClientAPIKey_LeavesGrantsAndBinding(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + twoLoginClient(t, m) + + rec, err := m.RevokeClientAPIKey("cursor") + require.NoError(t, err) + assert.True(t, rec.Revoked) + + gs, err := m.ListOAuthGrantsForClient("cursor") + require.NoError(t, err) + require.Len(t, gs, 2) + for _, g := range gs { + assert.False(t, g.Revoked) + } + b, _ := m.GetOAuthClientBinding("cursor") + require.NotNil(t, b) + assert.Equal(t, "ro", b.ProfilePin) +} + +func TestConnectRollbackLeavesGrantsUntouched(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + twoLoginClient(t, m) + _, err := m.RevokeClientAPIKey("cursor") + require.NoError(t, err) + mintTestClient(t, m, "cursor", auth.ProfileModeSwitchable, "") // connect + _, err = m.ForgetClientCredentialRestoringPrior("cursor") // undo + require.NoError(t, err) + + gs, err := m.ListOAuthGrantsForClient("cursor") + require.NoError(t, err) + require.Len(t, gs, 2) + for _, g := range gs { + assert.False(t, g.Revoked) + } + assertEqualBindings(t, m, "cursor", "ro", auth.ProfileModeLocked) +} diff --git a/internal/storage/oauth_login_test.go b/internal/storage/oauth_login_test.go new file mode 100644 index 000000000..9fbd6ddb1 --- /dev/null +++ b/internal/storage/oauth_login_test.go @@ -0,0 +1,610 @@ +package storage + +import ( + "fmt" + "sort" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.etcd.io/bbolt" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// dumpDB returns every key/value of every bucket plus the bucket names, so a +// test can assert that a failed or read-only call left the database as it was. +func dumpDB(t *testing.T, m *Manager) map[string]string { + t.Helper() + out := map[string]string{} + require.NoError(t, m.db.db.View(func(tx *bbolt.Tx) error { + return tx.ForEach(func(name []byte, b *bbolt.Bucket) error { + out["bucket:"+string(name)] = "" + return b.ForEach(func(k, v []byte) error { + out[string(name)+"/"+string(k)] = string(v) + return nil + }) + }) + })) + return out +} + +func oauthBucketNames(t *testing.T, m *Manager) []string { + t.Helper() + var names []string + require.NoError(t, m.db.db.View(func(tx *bbolt.Tx) error { + return tx.ForEach(func(name []byte, _ *bbolt.Bucket) error { + switch string(name) { + case OAuthRegistrationsBucket, OAuthGrantsBucket, OAuthGrantAccessIndexBucket, OAuthClientBindingsBucket: + names = append(names, string(name)) + } + return nil + }) + })) + sort.Strings(names) + return names +} + +// dbTxID is the id of the latest committed transaction: a read transaction +// sees the newest meta page, and every committed write transaction (even an +// empty one) advances it. +func dbTxID(t *testing.T, m *Manager) int { + t.Helper() + tx, err := m.db.db.Begin(false) + require.NoError(t, err) + defer func() { _ = tx.Rollback() }() + return tx.ID() +} + +func newTestReg(id string, created time.Time) OAuthRegistration { + return OAuthRegistration{ + ClientID: id, ReportedName: "Test Client", RedirectURIs: []string{"http://127.0.0.1:9999/cb"}, + TokenEndpointAuthMethod: "none", GrantTypes: []string{"authorization_code", "refresh_token"}, + CreatedAt: created, + } +} + +func newTestGrant(id, reg, client string, now time.Time) OAuthGrant { + return OAuthGrant{ + GrantID: id, RegistrationID: reg, Client: client, + RedirectURI: "http://127.0.0.1:9999/cb", Resource: "http://127.0.0.1:8080/mcp/oauth", Issuer: "http://127.0.0.1:8080", + RefreshHash: "rh-" + id, RefreshPrefix: "mcp_ort_" + id, AccessHash: "ah-" + id, + AccessExpiresAt: now.Add(time.Hour), RefreshExpiresAt: now.Add(30 * 24 * time.Hour), + ApprovedAt: now, ApprovedBy: OAuthActor{Kind: "admin", Name: "algis"}, DisplayPrefix: "mcp_oat_" + id, + } +} + +// commitNew commits a login for a brand-new client. +func commitNew(t *testing.T, m *Manager, regID, grantID, client, pin, mode string, now time.Time) OAuthGrant { + t.Helper() + require.NoError(t, m.CreateOAuthRegistration(newTestReg(regID, now))) + g, err := m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant(grantID, regID, client, now), Client: client, NewClient: true, + Pin: pin, Mode: mode, DisplayName: "Custom", ExpectedBindingRevision: OAuthBindingAbsent, Now: now, + }) + require.NoError(t, err) + return g +} + +// TestOAuthLoginLazyBuckets: opening a database and calling every READ function +// (and the sweeps and writers that find nothing to do) creates no OAuth bucket +// and no marker (Spec 132 FR-002). +func TestOAuthLoginLazyBuckets(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + before := dumpDB(t, m) + now := time.Now() + + _, err := m.GetOAuthRegistration("x") + assert.ErrorIs(t, err, ErrOAuthRegistrationGone) + regs, err := m.ListOAuthRegistrations() + require.NoError(t, err) + assert.Empty(t, regs) + _, err = m.GetOAuthGrant("x") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + _, err = m.GetOAuthGrantByAccessHash("h") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + gs, err := m.ListOAuthGrants() + require.NoError(t, err) + assert.Empty(t, gs) + gs, err = m.ListOAuthGrantsForClient("cursor") + require.NoError(t, err) + assert.Empty(t, gs) + used, err := m.OAuthLoginEverUsed() + require.NoError(t, err) + assert.False(t, used) + rev, err := m.ClientBindingRevision("cursor") + require.NoError(t, err) + assert.Equal(t, OAuthBindingAbsent, rev) + b, err := m.GetOAuthClientBinding("cursor") + require.NoError(t, err) + assert.Nil(t, b) + bs, err := m.ListOAuthClientBindings() + require.NoError(t, err) + assert.Empty(t, bs) + + // Writers that find nothing. + n, err := m.SweepOAuthRegistrations(now) + require.NoError(t, err) + assert.Zero(t, n) + n, err = m.SweepOAuthGrants(now) + require.NoError(t, err) + assert.Zero(t, n) + outcome, _, err := m.RotateOAuthRefresh("g", "h", "n", "p", "a", now, time.Hour, time.Hour) + require.NoError(t, err) + assert.Equal(t, RefreshInvalid, outcome) + _, err = m.RevokeOAuthGrant("g", OAuthRevokeAdmin, now) + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + assert.ErrorIs(t, m.TouchOAuthGrant("g", now, ""), ErrOAuthGrantNotFound) + assert.ErrorIs(t, m.MarkOAuthRegistrationAuthorized("r", now), ErrOAuthRegistrationGone) + rep, err := m.RepairOAuthClientBindings() + require.NoError(t, err) + assert.Empty(t, rep) + _, err = m.ForgetClient("cursor") + assert.ErrorIs(t, err, ErrClientCredentialNotFound) + _, err = m.RevokeClient("cursor", now) + assert.ErrorIs(t, err, ErrClientCredentialNotFound) + _, err = m.ForgetClientLogins("cursor") + require.NoError(t, err) + _, err = m.RepinProfile("a", "b") + require.NoError(t, err) + + assert.Empty(t, oauthBucketNames(t, m), "no OAuth bucket may exist") + assert.Equal(t, before, dumpDB(t, m), "no key may appear") + + // The existing API-key writers must not create them either. + mintTestClient(t, m, "cursor", auth.ProfileModeLocked, "ro") + _, _, err = m.UpdateClientCredentialBinding("cursor", "full", auth.ProfileModeSwitchable) + require.NoError(t, err) + _, err = m.RepinProfile("full", "x") + require.NoError(t, err) + _, err = m.ForgetClientCredential("cursor") + require.NoError(t, err) + assert.Empty(t, oauthBucketNames(t, m)) + used, err = m.OAuthLoginEverUsed() + require.NoError(t, err) + assert.False(t, used) +} + +func TestOAuthRegistration_CreateGetStateSweep(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + + require.NoError(t, m.CreateOAuthRegistration(newTestReg("p1", now.Add(-20*time.Minute)))) + require.NoError(t, m.CreateOAuthRegistration(newTestReg("p2", now.Add(-5*time.Minute)))) + require.NoError(t, m.CreateOAuthRegistration(newTestReg("a1", now.Add(-48*time.Hour)))) + require.NoError(t, m.CreateOAuthRegistration(newTestReg("a2", now.Add(-48*time.Hour)))) + + r, err := m.GetOAuthRegistration("p2") + require.NoError(t, err) + assert.Equal(t, OAuthRegistrationPending, r.State) + assert.Equal(t, "Test Client", r.ReportedName) + + require.NoError(t, m.MarkOAuthRegistrationAuthorized("a1", now.Add(-25*time.Hour))) + require.NoError(t, m.MarkOAuthRegistrationAuthorized("a2", now.Add(-time.Hour))) + r, err = m.GetOAuthRegistration("a1") + require.NoError(t, err) + assert.Equal(t, OAuthRegistrationAuthorized, r.State) + require.NotNil(t, r.AuthorizedAt) + + // A second authorize does not extend the clock. + require.NoError(t, m.MarkOAuthRegistrationAuthorized("a1", now)) + r, _ = m.GetOAuthRegistration("a1") + assert.WithinDuration(t, now.Add(-25*time.Hour), *r.AuthorizedAt, time.Second) + + // An approved row survives any sweep. + commitNew(t, m, "ok", "g1ok", "cursor", "", auth.ProfileModeSwitchable, now.Add(-100*24*time.Hour)) + + n, err := m.SweepOAuthRegistrations(now) + require.NoError(t, err) + assert.Equal(t, 2, n, "pending older than 15 min and authorized older than 24 h") + _, err = m.GetOAuthRegistration("p1") + assert.ErrorIs(t, err, ErrOAuthRegistrationGone) + _, err = m.GetOAuthRegistration("a1") + assert.ErrorIs(t, err, ErrOAuthRegistrationGone) + for _, id := range []string{"p2", "a2", "ok"} { + _, err = m.GetOAuthRegistration(id) + assert.NoError(t, err, id) + } + r, _ = m.GetOAuthRegistration("ok") + assert.Equal(t, OAuthRegistrationApproved, r.State) +} + +func TestOAuthRegistration_CapDropsOldestNonApproved(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + base := time.Now().UTC().Add(-time.Hour) + + // One approved row, the oldest of all: it is never evicted. + commitNew(t, m, "approved", "gapproved", "cursor", "", auth.ProfileModeSwitchable, base.Add(-time.Hour)) + + for i := 0; i < MaxUnapprovedOAuthRegistrations; i++ { + require.NoError(t, m.CreateOAuthRegistration(newTestReg(fmt.Sprintf("r%02d", i), base.Add(time.Duration(i)*time.Second)))) + } + // r00 is authorized: authorized and pending count together. + require.NoError(t, m.MarkOAuthRegistrationAuthorized("r00", base)) + + regs, err := m.ListOAuthRegistrations() + require.NoError(t, err) + assert.Len(t, regs, MaxUnapprovedOAuthRegistrations+1) + + require.NoError(t, m.CreateOAuthRegistration(newTestReg("new", base.Add(time.Hour)))) + regs, err = m.ListOAuthRegistrations() + require.NoError(t, err) + assert.Len(t, regs, MaxUnapprovedOAuthRegistrations+1, "still 50 unapproved + 1 approved") + _, err = m.GetOAuthRegistration("r00") + assert.ErrorIs(t, err, ErrOAuthRegistrationGone, "the oldest non-approved row (here authorized) is dropped") + for _, id := range []string{"r01", "new", "approved"} { + _, err = m.GetOAuthRegistration(id) + assert.NoError(t, err, id) + } +} + +func TestCommitOAuthLogin_NewClient(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + + used, _ := m.OAuthLoginEverUsed() + require.False(t, used) + + g := commitNew(t, m, "reg1", "grant1", "myclient", "ro", auth.ProfileModeLocked, now) + assert.Equal(t, "grant1", g.GrantID) + + reg, err := m.GetOAuthRegistration("reg1") + require.NoError(t, err) + assert.Equal(t, OAuthRegistrationApproved, reg.State) + + got, err := m.GetOAuthGrant("grant1") + require.NoError(t, err) + assert.Equal(t, "http://127.0.0.1:9999/cb", got.RedirectURI) + assert.Equal(t, "myclient", got.Client) + + b, err := m.GetOAuthClientBinding("myclient") + require.NoError(t, err) + require.NotNil(t, b) + assert.Equal(t, "ro", b.ProfilePin) + assert.Equal(t, auth.ProfileModeLocked, b.ProfileMode) + assert.Equal(t, "Custom", b.DisplayName) + + byHash, err := m.GetOAuthGrantByAccessHash("ah-grant1") + require.NoError(t, err) + assert.Equal(t, "grant1", byHash.GrantID) + + used, err = m.OAuthLoginEverUsed() + require.NoError(t, err) + assert.True(t, used) + + rev, err := m.ClientBindingRevision("myclient") + require.NoError(t, err) + assert.Equal(t, bindingRevision("myclient", "ro", auth.ProfileModeLocked), rev) + assert.Len(t, rev, 16) + + // The marker keeps the FIRST login's time. + var first string + require.NoError(t, m.db.db.View(func(tx *bbolt.Tx) error { + first = string(tx.Bucket([]byte(MetaBucket)).Get([]byte(OAuthLoginEverUsedKey))) + return nil + })) + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg2", now))) + _, err = m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("grant2", "reg2", "myclient", now), Client: "myclient", + ExpectedBindingRevision: rev, Now: now.Add(time.Hour), + }) + require.NoError(t, err) + require.NoError(t, m.db.db.View(func(tx *bbolt.Tx) error { + assert.Equal(t, first, string(tx.Bucket([]byte(MetaBucket)).Get([]byte(OAuthLoginEverUsedKey)))) + return nil + })) +} + +func TestCommitOAuthLogin_ExistingAPIKeyClientGetsEntryFromCurrentRecord(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + mintTestClient(t, m, "cursor", auth.ProfileModeLocked, "ro") + + rev, err := m.ClientBindingRevision("cursor") + require.NoError(t, err) + assert.Equal(t, bindingRevision("cursor", "ro", auth.ProfileModeLocked), rev) + + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg", now))) + // Pin/Mode in the input are ignored for an existing client. + _, err = m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("g1", "reg", "cursor", now), Client: "cursor", + Pin: "full", Mode: auth.ProfileModeSwitchable, ExpectedBindingRevision: rev, Now: now, + }) + require.NoError(t, err) + + b, err := m.GetOAuthClientBinding("cursor") + require.NoError(t, err) + require.NotNil(t, b) + assert.Equal(t, "ro", b.ProfilePin) + assert.Equal(t, auth.ProfileModeLocked, b.ProfileMode) + rec, err := m.GetAgentTokenByName("client-cursor") + require.NoError(t, err) + assert.Equal(t, b.ProfilePin, rec.ProfilePin) + assert.Equal(t, b.ProfileMode, rec.ProfileMode) +} + +func TestCommitOAuthLogin_FailedChecksWriteNothing(t *testing.T) { + now := time.Now().UTC() + + t.Run("registration gone", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + before := dumpDB(t, m) + _, err := m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("g", "missing", "c1", now), Client: "c1", NewClient: true, + Pin: "", Mode: auth.ProfileModeSwitchable, ExpectedBindingRevision: OAuthBindingAbsent, Now: now, + }) + assert.ErrorIs(t, err, ErrOAuthRegistrationGone) + assert.Equal(t, before, dumpDB(t, m)) + assert.Empty(t, oauthBucketNames(t, m)) + }) + + t.Run("new client id held by an API key", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + mintTestClient(t, m, "cursor", auth.ProfileModeSwitchable, "") + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg", now))) + before := dumpDB(t, m) + _, err := m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("g", "reg", "cursor", now), Client: "cursor", NewClient: true, + Mode: auth.ProfileModeSwitchable, ExpectedBindingRevision: OAuthBindingAbsent, Now: now, + }) + assert.ErrorIs(t, err, ErrOAuthClientExists) + assert.Equal(t, before, dumpDB(t, m)) + }) + + t.Run("stale binding revision", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + mintTestClient(t, m, "cursor", auth.ProfileModeLocked, "ro") + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg", now))) + before := dumpDB(t, m) + _, err := m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("g", "reg", "cursor", now), Client: "cursor", + ExpectedBindingRevision: bindingRevision("cursor", "other", auth.ProfileModeLocked), Now: now, + }) + assert.ErrorIs(t, err, ErrOAuthBindingChanged) + assert.Equal(t, before, dumpDB(t, m)) + }) + + t.Run("existing-client decision whose client vanished", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg", now))) + before := dumpDB(t, m) + _, err := m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("g", "reg", "ghost", now), Client: "ghost", + ExpectedBindingRevision: OAuthBindingAbsent, Now: now, + }) + assert.ErrorIs(t, err, ErrOAuthBindingChanged) + assert.Equal(t, before, dumpDB(t, m)) + }) + + t.Run("invalid new-client binding writes nothing", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg", now))) + before := dumpDB(t, m) + _, err := m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("g", "reg", "c1", now), Client: "c1", NewClient: true, + Mode: auth.ProfileModeLocked, Pin: "", ExpectedBindingRevision: OAuthBindingAbsent, Now: now, + }) + require.Error(t, err) + assert.Equal(t, before, dumpDB(t, m)) + }) +} + +func TestCommitOAuthLogin_TwoNewClientCommitsSecondFails(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + require.NoError(t, m.CreateOAuthRegistration(newTestReg("regA", now))) + require.NoError(t, m.CreateOAuthRegistration(newTestReg("regB", now))) + in := func(reg, grant string) CommitLoginInput { + return CommitLoginInput{ + Grant: newTestGrant(grant, reg, "newc", now), Client: "newc", NewClient: true, + Mode: auth.ProfileModeSwitchable, ExpectedBindingRevision: OAuthBindingAbsent, Now: now, + } + } + _, err := m.CommitOAuthLogin(in("regA", "gA")) + require.NoError(t, err) + before := dumpDB(t, m) + _, err = m.CommitOAuthLogin(in("regB", "gB")) + assert.ErrorIs(t, err, ErrOAuthClientExists, "the second is not turned into an existing-client login") + assert.Equal(t, before, dumpDB(t, m)) +} + +func TestCommitOAuthLogin_ReplaceGrant(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + commitNew(t, m, "reg1", "old1", "myclient", "", auth.ProfileModeSwitchable, now) + commitNew(t, m, "reg2", "other", "otherclient", "", auth.ProfileModeSwitchable, now) + rev, _ := m.ClientBindingRevision("myclient") + + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg3", now))) + _, err := m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("new1", "reg3", "myclient", now), Client: "myclient", + ExpectedBindingRevision: rev, ReplaceGrantID: "old1", Now: now, + }) + require.NoError(t, err) + old, err := m.GetOAuthGrant("old1") + require.NoError(t, err) + assert.True(t, old.Revoked) + assert.Equal(t, OAuthRevokeReplaced, old.RevokeReason) + _, err = m.GetOAuthGrantByAccessHash("ah-old1") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound, "a revoked grant leaves the access index") + + // A grant of ANOTHER client is ignored. + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg4", now))) + _, err = m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("new2", "reg4", "myclient", now), Client: "myclient", + ExpectedBindingRevision: rev, ReplaceGrantID: "other", Now: now, + }) + require.NoError(t, err) + o, err := m.GetOAuthGrant("other") + require.NoError(t, err) + assert.False(t, o.Revoked) +} + +func TestRotateOAuthRefresh(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + commitNew(t, m, "reg1", "grant1", "myclient", "", auth.ProfileModeSwitchable, now) + + t.Run("current secret rotates", func(t *testing.T) { + later := now.Add(time.Hour) + out, g, err := m.RotateOAuthRefresh("grant1", "rh-grant1", "rh2", "mcp_ort_zz", "ah2", later, 15*time.Minute, 30*24*time.Hour) + require.NoError(t, err) + assert.Equal(t, RefreshRotated, out) + assert.Equal(t, "rh2", g.RefreshHash) + assert.Equal(t, "ah2", g.AccessHash) + assert.WithinDuration(t, later.Add(15*time.Minute), g.AccessExpiresAt, time.Second) + assert.WithinDuration(t, later.Add(30*24*time.Hour), g.RefreshExpiresAt, time.Second) + _, err = m.GetOAuthGrantByAccessHash("ah-grant1") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound, "the old access token is gone") + byNew, err := m.GetOAuthGrantByAccessHash("ah2") + require.NoError(t, err) + assert.Equal(t, "grant1", byNew.GrantID) + }) + + t.Run("an old secret revokes the grant as replay", func(t *testing.T) { + out, g, err := m.RotateOAuthRefresh("grant1", "rh-grant1", "rh3", "p", "ah3", now.Add(2*time.Hour), time.Minute, time.Hour) + require.NoError(t, err) + assert.Equal(t, RefreshReplay, out) + assert.True(t, g.Revoked) + assert.Equal(t, OAuthRevokeReplay, g.RevokeReason) + _, err = m.GetOAuthGrantByAccessHash("ah2") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + }) + + t.Run("a revoked grant is invalid and nothing is written", func(t *testing.T) { + before := dumpDB(t, m) + out, _, err := m.RotateOAuthRefresh("grant1", "rh2", "rh4", "p", "ah4", now.Add(3*time.Hour), time.Minute, time.Hour) + require.NoError(t, err) + assert.Equal(t, RefreshInvalid, out) + assert.Equal(t, before, dumpDB(t, m)) + }) +} + +func TestRotateOAuthRefresh_UnknownAndLapsedWriteNothing(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + commitNew(t, m, "reg1", "grant1", "myclient", "", auth.ProfileModeSwitchable, now) + + before := dumpDB(t, m) + txBefore := dbTxID(t, m) + + out, _, err := m.RotateOAuthRefresh("nope", "rh-grant1", "x", "p", "y", now, time.Minute, time.Hour) + require.NoError(t, err) + assert.Equal(t, RefreshInvalid, out) + + // The refresh lapsed: even the CURRENT secret is refused and the + // lifetime is not extended. + lapsed := now.Add(31 * 24 * time.Hour) + out, _, err = m.RotateOAuthRefresh("grant1", "rh-grant1", "x", "p", "y", lapsed, time.Minute, time.Hour) + require.NoError(t, err) + assert.Equal(t, RefreshInvalid, out) + out, _, err = m.RotateOAuthRefresh("grant1", "wrong", "x", "p", "y", lapsed, time.Minute, time.Hour) + require.NoError(t, err) + assert.Equal(t, RefreshInvalid, out, "a wrong secret on a lapsed grant is not a replay either") + + assert.Equal(t, before, dumpDB(t, m)) + g, err := m.GetOAuthGrant("grant1") + require.NoError(t, err) + assert.False(t, g.Revoked) + assert.WithinDuration(t, now.Add(30*24*time.Hour), g.RefreshExpiresAt, time.Second) + assert.Equal(t, txBefore, dbTxID(t, m), "no write transaction was committed") +} + +func TestRevokeTouchOAuthGrant(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + commitNew(t, m, "reg1", "grant1", "myclient", "", auth.ProfileModeSwitchable, now) + + require.NoError(t, m.TouchOAuthGrant("grant1", now.Add(time.Minute), "Claude Code")) + g, _ := m.GetOAuthGrant("grant1") + require.NotNil(t, g.LastUsedAt) + assert.Equal(t, "Claude Code", g.ObservedClientName) + require.NoError(t, m.TouchOAuthGrant("grant1", now.Add(2*time.Minute), "")) + g, _ = m.GetOAuthGrant("grant1") + assert.Equal(t, "Claude Code", g.ObservedClientName, "an empty name keeps the observed one") + + changed, err := m.RevokeOAuthGrant("grant1", OAuthRevokeAdmin, now) + require.NoError(t, err) + assert.True(t, changed) + changed, err = m.RevokeOAuthGrant("grant1", OAuthRevokeReplay, now) + require.NoError(t, err) + assert.False(t, changed) + g, _ = m.GetOAuthGrant("grant1") + assert.Equal(t, OAuthRevokeAdmin, g.RevokeReason, "the first reason stays") + _, err = m.GetOAuthGrantByAccessHash("ah-grant1") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) +} + +func TestSweepOAuthGrants_RetentionAndCascade(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + old := now.Add(-70 * 24 * time.Hour) + + // client "a": one revoked-long-ago grant (its registration is not shared). + commitNew(t, m, "regA", "gA", "clienta", "", auth.ProfileModeSwitchable, old) + _, err := m.RevokeOAuthGrant("gA", OAuthRevokeAdmin, old) + require.NoError(t, err) + + // client "b": one live grant and one lapsed-long-ago grant on two registrations. + commitNew(t, m, "regB1", "gB1", "clientb", "", auth.ProfileModeSwitchable, now) + revB, _ := m.ClientBindingRevision("clientb") + require.NoError(t, m.CreateOAuthRegistration(newTestReg("regB2", old))) + lapsed := newTestGrant("gB2", "regB2", "clientb", old) // refresh lapsed 40 days ago + _, err = m.CommitOAuthLogin(CommitLoginInput{Grant: lapsed, Client: "clientb", ExpectedBindingRevision: revB, Now: old}) + require.NoError(t, err) + + // client "c": revoked 10 days ago: kept for display. + commitNew(t, m, "regC", "gC", "clientc", "", auth.ProfileModeSwitchable, now) + _, err = m.RevokeOAuthGrant("gC", OAuthRevokeAdmin, now.Add(-10*24*time.Hour)) + require.NoError(t, err) + + n, err := m.SweepOAuthGrants(now) + require.NoError(t, err) + assert.Equal(t, 2, n) + + _, err = m.GetOAuthGrant("gA") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + _, err = m.GetOAuthGrant("gB2") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + for _, id := range []string{"gB1", "gC"} { + _, err = m.GetOAuthGrant(id) + assert.NoError(t, err, id) + } + + // Last grant record of a registration: the registration goes. + _, err = m.GetOAuthRegistration("regA") + assert.ErrorIs(t, err, ErrOAuthRegistrationGone) + _, err = m.GetOAuthRegistration("regB2") + assert.ErrorIs(t, err, ErrOAuthRegistrationGone) + for _, id := range []string{"regB1", "regC"} { + _, err = m.GetOAuthRegistration(id) + assert.NoError(t, err, id) + } + + // Last grant record of a client: its binding entry goes; others stay. + b, _ := m.GetOAuthClientBinding("clienta") + assert.Nil(t, b) + for _, id := range []string{"clientb", "clientc"} { + b, _ = m.GetOAuthClientBinding(id) + assert.NotNil(t, b, id) + } + used, _ := m.OAuthLoginEverUsed() + assert.True(t, used, "the marker is never deleted") +} From 6d74c98e18d4f038c4d7176912ae50ae5f7a4b16 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 19:13:46 +0200 Subject: [PATCH 07/42] test(oauth): scope the no-storage check to browser-login state (Spec 132 PR-1a) Related #1971 --- .../server/oauth_login_default_off_test.go | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/internal/server/oauth_login_default_off_test.go b/internal/server/oauth_login_default_off_test.go index 1f08716ce..f18449d5d 100644 --- a/internal/server/oauth_login_default_off_test.go +++ b/internal/server/oauth_login_default_off_test.go @@ -5,6 +5,7 @@ import ( "net/http" "net/http/httptest" "sort" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -145,7 +146,7 @@ func TestOAuthLogin_DefaultOff_NoStorage(t *testing.T) { srv := newOAuthLoginTestServer(t, nil) db := srv.runtime.StorageManager().GetDB() require.NotNil(t, db) - beforeBuckets, beforeMeta := bucketSnapshot(t, db) + beforeBuckets, _ := bucketSnapshot(t, db) mux := oauthLoginTestMux(srv, true) for _, path := range oauthLoginTestPaths { @@ -156,9 +157,24 @@ func TestOAuthLogin_DefaultOff_NoStorage(t *testing.T) { } } + // Only browser-login state is asserted: unrelated runtime startup tasks + // (e.g. the work-session backfill) may write to the database concurrently. afterBuckets, afterMeta := bucketSnapshot(t, db) - assert.Equal(t, beforeBuckets, afterBuckets, "bucket list must not change") - assert.Equal(t, beforeMeta, afterMeta, "MetaBucket keys must not change") + before := map[string]bool{} + for _, name := range beforeBuckets { + before[name] = true + } + for _, name := range afterBuckets { + if strings.HasPrefix(name, "oauth_") && !before[name] { + t.Errorf("browser login created bucket %q while off", name) + } + } + for _, name := range []string{"oauth_registrations", "oauth_grants", "oauth_grant_access_index", "oauth_client_bindings"} { + assert.NotContains(t, afterBuckets, name, "lazy browser-login bucket must not exist") + } + for _, key := range afterMeta { + assert.False(t, strings.HasPrefix(key, "oauth_login"), "MetaBucket key %q must not exist", key) + } } // Patterns the gate guards (the ones registered by registerOAuthLoginRoutes). From 143494ceac0cf6f08c7348f7daa6d0b3f0c6088d Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 19:24:26 +0200 Subject: [PATCH 08/42] fix(oauth): harden browser-login storage after review (Spec 132 PR-1c) Related #1971 --- internal/storage/agent_token_repin.go | 175 ++++++++---- internal/storage/client_binding.go | 68 ++++- internal/storage/client_binding_dual_test.go | 93 +----- .../storage/client_binding_hardening_test.go | 266 ++++++++++++++++++ .../storage/client_binding_source_test.go | 211 ++++++++++++++ internal/storage/client_credentials.go | 2 +- internal/storage/oauth_login.go | 202 +++++++++---- .../storage/oauth_login_client_ops_test.go | 4 +- .../storage/oauth_login_hardening_test.go | 160 +++++++++++ internal/storage/oauth_login_test.go | 16 +- 10 files changed, 975 insertions(+), 222 deletions(-) create mode 100644 internal/storage/client_binding_hardening_test.go create mode 100644 internal/storage/client_binding_source_test.go create mode 100644 internal/storage/oauth_login_hardening_test.go diff --git a/internal/storage/agent_token_repin.go b/internal/storage/agent_token_repin.go index f519ca530..4b361115c 100644 --- a/internal/storage/agent_token_repin.go +++ b/internal/storage/agent_token_repin.go @@ -9,6 +9,30 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" ) +// repinRestoreMarker marks a record in RepinProfile's `before` slice as a +// browser-login restore entry rather than a stored token record. It is carried +// in AgentToken.MatchedGeneration, a field that is never persisted (json:"-") +// and never set on a stored record, so a real record cannot be mistaken for it +// whatever its TokenHash is. +const repinRestoreMarker = "spec132-repin-binding-restore" + +// repinRestoreEntry builds the restore entry of one client RepinProfile moved +// and whose binding lives (also) in an oauth_client_bindings entry. It carries +// the OLD binding in ProfilePin/ProfileMode and what repin WROTE in +// PriorProfilePin/PriorProfileMode, so RestorePins can compare-and-set. +func repinRestoreEntry(clientID, oldPin, oldMode, wrotePin, wroteMode string) auth.AgentToken { + return auth.AgentToken{ + Name: auth.ClientTokenName(clientID), Kind: auth.KindClient, ClientID: clientID, + ProfilePin: oldPin, ProfileMode: oldMode, + PriorProfilePin: wrotePin, PriorProfileMode: wroteMode, + MatchedGeneration: repinRestoreMarker, + } +} + +func isRepinRestoreEntry(t *auth.AgentToken) bool { + return t.MatchedGeneration == repinRestoreMarker && t.Kind == auth.KindClient && t.ClientID != "" +} + // RepinProfile rewrites ProfilePin from -> to on EVERY stored ownerless token // naming `from` — regular agent tokens and client credentials alike, revoked // and expired ones included — in one transaction (Spec 108 D19). It is the @@ -20,18 +44,19 @@ import ( // restore exactly those pins with RestorePins. An empty source or target is // refused before anything is written (a locked client credential cannot hold // an empty pin). +// +// Spec 132: a client's pin is written through writeClientBindingTx, so its +// browser-login binding entry moves with its API-key record, and an entry of a +// client that has NO API-key record moves too. For every client that has an +// entry, `before` ends with a restore entry (see repinRestoreEntry) that +// RestorePins applies compare-and-set. Existing records come first, in bbolt +// key order, exactly as before. func (m *Manager) RepinProfile(from, to string) (before []auth.AgentToken, err error) { return m.repinProfile(from, to, nil) } // repinProfile is RepinProfile with a per-record hook (called before each // record is written) so a test can inject a failure part-way through the tx. -// -// Spec 132: a client's pin is written through writeClientBindingTx, so its -// browser-login binding entry moves with its API-key record, and an entry of a -// client that has NO API-key record moves too. Such an entry is reported in -// `before` as a record with an empty TokenHash (Kind=client, ClientID set) that -// RestorePins recognises. func (m *Manager) repinProfile(from, to string, hook func(written int) error) ([]auth.AgentToken, error) { if from == "" || to == "" { return nil, fmt.Errorf("repin needs a source and a target profile") @@ -43,12 +68,12 @@ func (m *Manager) repinProfile(from, to string, hook func(written int) error) ([ err := m.db.db.Update(func(tx *bbolt.Tx) error { before = nil type rewrite struct { - key []byte - data []byte - old auth.AgentToken + key []byte + data []byte // direct rewrite of a regular token; nil for a client record + old auth.AgentToken + client bool } - var work []rewrite - var clientWork []auth.AgentToken // kind=client records: via the binding writer + var work []rewrite // ONE list, in bbolt key order clientsWithRecord := map[string]bool{} // Collect first: bbolt forbids Put while a ForEach is iterating. if tokenBucket := tx.Bucket([]byte(AgentTokensBucket)); tokenBucket != nil { @@ -57,38 +82,37 @@ func (m *Manager) repinProfile(from, to string, hook func(written int) error) ([ if json.Unmarshal(v, &t) != nil { return nil } - if t.Kind == auth.KindClient && t.ClientID != "" { + isClient := t.Kind == auth.KindClient && t.ClientID != "" + if isClient { clientsWithRecord[t.ClientID] = true } if t.UserID != "" || t.ProfilePin != from { return nil } old := t - if t.Kind == auth.KindClient && t.ClientID != "" { - clientWork = append(clientWork, old) - return nil - } - // Regular (non-client) agent token: plain pin rewrite. - t.ProfilePin = to - data, marshalErr := json.Marshal(t) - if marshalErr != nil { - return marshalErr + var data []byte + if !isClient { + // Regular (non-client) agent token: plain pin rewrite. + t.ProfilePin = to + var marshalErr error + if data, marshalErr = json.Marshal(t); marshalErr != nil { + return marshalErr + } } - work = append(work, rewrite{key: append([]byte(nil), k...), data: data, old: old}) + work = append(work, rewrite{key: append([]byte(nil), k...), data: data, old: old, client: isClient}) return nil }); err != nil { return err } } // Browser-login-only clients: entries pinned to `from` whose client has - // no API-key record. - var oauthOnly []auth.AgentToken + // no API-key record. They come after every existing record. + var oauthOnly []OAuthClientBinding + var oauthOnlyIDs []string if err := oauthForEach(tx, OAuthClientBindingsBucket, func(id string, b OAuthClientBinding) error { if b.ProfilePin == from && !clientsWithRecord[id] { - oauthOnly = append(oauthOnly, auth.AgentToken{ - Name: auth.ClientTokenName(id), Kind: auth.KindClient, ClientID: id, - ProfilePin: b.ProfilePin, ProfileMode: b.ProfileMode, - }) + oauthOnly = append(oauthOnly, b) + oauthOnlyIDs = append(oauthOnlyIDs, id) } return nil }); err != nil { @@ -105,24 +129,45 @@ func (m *Manager) repinProfile(from, to string, hook func(written int) error) ([ i++ return nil } + var restores []auth.AgentToken for _, w := range work { if err := step(); err != nil { return err } - if err := tx.Bucket([]byte(AgentTokensBucket)).Put(w.key, w.data); err != nil { + if !w.client { + if err := tx.Bucket([]byte(AgentTokensBucket)).Put(w.key, w.data); err != nil { + return fmt.Errorf("failed to repin agent token: %w", err) + } + before = append(before, w.old) + continue + } + // A client record: through the binding writer so its OAuth entry + // moves too. When it has an entry, the mint-time rollback snapshot + // is stale after this move and is cleared in the same write, so a + // later connect rollback cannot put a pre-reassignment binding back + // on the existing browser logins. + entry, err := getOAuthBindingTx(tx, w.old.ClientID) + if err != nil { + return err + } + if err := writeClientBindingOptsTx(tx, w.old.ClientID, to, w.old.ProfileMode, entry != nil); err != nil { return fmt.Errorf("failed to repin agent token: %w", err) } before = append(before, w.old) + if entry != nil { + restores = append(restores, repinRestoreEntry(w.old.ClientID, w.old.ProfilePin, w.old.ProfileMode, to, w.old.ProfileMode)) + } } - for _, old := range append(clientWork, oauthOnly...) { + for j, id := range oauthOnlyIDs { if err := step(); err != nil { return err } - if err := writeClientBindingTx(tx, old.ClientID, to, old.ProfileMode); err != nil { - return fmt.Errorf("failed to repin client binding: %w", err) + if err := writeClientBindingTx(tx, id, to, oauthOnly[j].ProfileMode); err != nil { + return fmt.Errorf("failed to repin agent token: %w", err) } - before = append(before, old) + restores = append(restores, repinRestoreEntry(id, oauthOnly[j].ProfilePin, oauthOnly[j].ProfileMode, to, oauthOnly[j].ProfileMode)) } + before = append(before, restores...) return nil }) if err != nil { @@ -133,8 +178,15 @@ func (m *Manager) repinProfile(from, to string, hook func(written int) error) ([ // RestorePins puts back the ProfilePin of each record RepinProfile returned, // in one transaction (the rollback of a repin whose config write failed). A -// record that no longer exists is left alone. Client records, and the entries -// of browser-login-only clients (empty TokenHash), go through the binding writer. +// record that no longer exists is left alone. +// +// Stored records are restored by hash, as before. The restore entries for +// browser-login bindings are compare-and-set: the entry is restored only if it +// still holds exactly what repin wrote (and a current API-key record of that +// client holds that or the old binding); an entry that is gone is not +// re-created, and one that changed since (re-created client, new mint, an +// administrator's reassignment) is left alone. They do not depend on the +// original API-key record still existing. func (m *Manager) RestorePins(before []auth.AgentToken) error { if len(before) == 0 { return nil @@ -143,18 +195,8 @@ func (m *Manager) RestorePins(before []auth.AgentToken) error { defer m.mu.Unlock() return m.db.db.Update(func(tx *bbolt.Tx) error { for i := range before { - if before[i].TokenHash == "" && before[i].Kind == auth.KindClient && before[i].ClientID != "" { - // Browser-login-only client: its entry, if it still exists. - b, err := getOAuthBindingTx(tx, before[i].ClientID) - if err != nil { - return err - } - if b != nil { - if err := writeClientBindingTx(tx, before[i].ClientID, before[i].ProfilePin, b.ProfileMode); err != nil { - return err - } - } - continue + if isRepinRestoreEntry(&before[i]) { + continue // second pass, after the records } tokenBucket := tx.Bucket([]byte(AgentTokensBucket)) if tokenBucket == nil { @@ -169,12 +211,6 @@ func (m *Manager) RestorePins(before []auth.AgentToken) error { if json.Unmarshal(v, &t) != nil || t.UserID != "" { continue } - if t.Kind == auth.KindClient && t.ClientID != "" { - if err := writeClientBindingTx(tx, t.ClientID, before[i].ProfilePin, t.ProfileMode); err != nil { - return fmt.Errorf("failed to restore client binding: %w", err) - } - continue - } t.ProfilePin = before[i].ProfilePin data, err := json.Marshal(t) if err != nil { @@ -184,6 +220,39 @@ func (m *Manager) RestorePins(before []auth.AgentToken) error { return fmt.Errorf("failed to restore agent token pin: %w", err) } } + for i := range before { + if isRepinRestoreEntry(&before[i]) { + if err := restoreRepinnedClientTx(tx, &before[i]); err != nil { + return err + } + } + } return nil }) } + +// restoreRepinnedClientTx is the compare-and-set restore of one client's +// browser-login binding (see RestorePins). +func restoreRepinnedClientTx(tx *bbolt.Tx, p *auth.AgentToken) error { + oldPin, oldMode := p.ProfilePin, p.ProfileMode + wrotePin, wroteMode := p.PriorProfilePin, p.PriorProfileMode + entry, err := getOAuthBindingTx(tx, p.ClientID) + if err != nil { + return err + } + if entry == nil || entry.ProfilePin != wrotePin || entry.ProfileMode != wroteMode { + return nil // gone (not re-created) or changed since: leave it alone + } + _, tok, err := findClientTokenRecordLocked(tx, p.ClientID) + if err != nil { + return err + } + if tok != nil && tok.Kind == auth.KindClient { + wrote := tok.ProfilePin == wrotePin && tok.ProfileMode == wroteMode + old := tok.ProfilePin == oldPin && tok.ProfileMode == oldMode // already restored by hash + if !wrote && !old { + return nil // the API-key record moved on its own + } + } + return writeClientBindingTx(tx, p.ClientID, oldPin, oldMode) +} diff --git a/internal/storage/client_binding.go b/internal/storage/client_binding.go index ec81e014f..fe1a79d3c 100644 --- a/internal/storage/client_binding.go +++ b/internal/storage/client_binding.go @@ -23,6 +23,17 @@ func bindingRevision(clientID, pin, mode string) string { return hex.EncodeToString(sum[:8]) } +// validateClientBinding: mode is locked or switchable, and locked needs a pin. +func validateClientBinding(pin, mode string) error { + if mode != auth.ProfileModeLocked && mode != auth.ProfileModeSwitchable { + return fmt.Errorf("invalid profile mode %q", mode) + } + if mode == auth.ProfileModeLocked && pin == "" { + return fmt.Errorf("a locked client binding requires a non-empty profile") + } + return nil +} + // writeClientBindingTx writes (pin, mode) on the client's API-key record when // there is one AND on its oauth_client_bindings entry when there is one, and // fails with ErrClientCredentialNotFound only when NEITHER exists. It never @@ -36,6 +47,10 @@ func writeClientBindingTx(tx *bbolt.Tx, clientID, pin, mode string) error { // the API-key record's PriorProfile* snapshot in the same write (a binding // change makes the mint-time snapshot stale). func writeClientBindingOptsTx(tx *bbolt.Tx, clientID, pin, mode string, clearPrior bool) error { + // Validate before ANY write so neither copy can be left half-updated. + if err := validateClientBinding(pin, mode); err != nil { + return err + } found := false hash, tok, err := findClientTokenRecordLocked(tx, clientID) if err != nil { @@ -75,13 +90,13 @@ func writeClientBindingOptsTx(tx *bbolt.Tx, clientID, pin, mode string, clearPri // RepairOAuthClientBindings makes every client that has both an API-key record // and an oauth_client_bindings entry agree, taking the API-key record as the // truth. It returns the ids it repaired (the caller logs them). -func (m *Manager) RepairOAuthClientBindings() (repaired []string, err error) { - m.mu.Lock() - defer m.mu.Unlock() - err = m.db.db.Update(func(tx *bbolt.Tx) error { - repaired = nil - var todo []struct{ id, pin, mode string } - if err := oauthForEach(tx, OAuthClientBindingsBucket, func(id string, b OAuthClientBinding) error { +// +// An API-key binding that is itself invalid (unknown mode, locked without a +// pin) is NOT copied: that client is skipped and returned in `skipped`. +func (m *Manager) RepairOAuthClientBindings() (repaired, skipped []string, err error) { + type fix struct{ id, pin, mode string } + collect := func(tx *bbolt.Tx) (todo []fix, skip []string, err error) { + err = oauthForEach(tx, OAuthClientBindingsBucket, func(id string, b OAuthClientBinding) error { _, tok, err := findClientTokenRecordLocked(tx, id) if err != nil { return err @@ -89,13 +104,42 @@ func (m *Manager) RepairOAuthClientBindings() (repaired []string, err error) { if tok == nil || tok.Kind != auth.KindClient { return nil } - if tok.ProfilePin != b.ProfilePin || tok.ProfileMode != b.ProfileMode { - todo = append(todo, struct{ id, pin, mode string }{id, tok.ProfilePin, tok.ProfileMode}) + if tok.ProfilePin == b.ProfilePin && tok.ProfileMode == b.ProfileMode { + return nil + } + if validateClientBinding(tok.ProfilePin, tok.ProfileMode) != nil { + skip = append(skip, id) + return nil } + todo = append(todo, fix{id, tok.ProfilePin, tok.ProfileMode}) return nil - }); err != nil { + }) + return todo, skip, err + } + + m.mu.Lock() + defer m.mu.Unlock() + + // View first: with nothing to repair no write transaction is opened. + var skip []string + needWrite := false + if err := m.db.db.View(func(tx *bbolt.Tx) error { + todo, s, err := collect(tx) + needWrite, skip = len(todo) > 0, s + return err + }); err != nil { + return nil, nil, err + } + if !needWrite { + return nil, skip, nil + } + err = m.db.db.Update(func(tx *bbolt.Tx) error { + repaired = nil + todo, s, err := collect(tx) + if err != nil { return err } + skip = s for _, r := range todo { if err := writeClientBindingTx(tx, r.id, r.pin, r.mode); err != nil { return err @@ -105,9 +149,9 @@ func (m *Manager) RepairOAuthClientBindings() (repaired []string, err error) { return nil }) if err != nil { - return nil, err + return nil, nil, err } - return repaired, nil + return repaired, skip, nil } // forgetClientLoginsTx deletes every grant record of the client with its diff --git a/internal/storage/client_binding_dual_test.go b/internal/storage/client_binding_dual_test.go index eca716f59..057d60277 100644 --- a/internal/storage/client_binding_dual_test.go +++ b/internal/storage/client_binding_dual_test.go @@ -3,13 +3,6 @@ package storage import ( "encoding/json" "errors" - "go/ast" - "go/parser" - "go/token" - "os" - "path/filepath" - "sort" - "strings" "testing" "time" @@ -180,7 +173,7 @@ func TestRepinProfile_MovesOAuthOnlyClientAndRestorePinsRestores(t *testing.T) { before, err := m.RepinProfile("old", "new") require.NoError(t, err) - require.Len(t, before, 2, "the API-key client and the OAuth-only client") + require.Len(t, before, 3, "API-key record, plus restore entries for both clients") _, _, apiOK, oPin, oMode, oOK := bindings(t, m, "webonly") assert.False(t, apiOK) @@ -229,12 +222,12 @@ func TestRepairOAuthClientBindings_TakesAPIKeyRecord(t *testing.T) { ProfilePin: "stale", ProfileMode: auth.ProfileModeSwitchable, UpdatedAt: time.Now(), }) })) - repaired, err := m.RepairOAuthClientBindings() + repaired, _, err := m.RepairOAuthClientBindings() require.NoError(t, err) assert.Equal(t, []string{"cursor"}, repaired) assertEqualBindings(t, m, "cursor", "ro", auth.ProfileModeLocked) - repaired, err = m.RepairOAuthClientBindings() + repaired, _, err = m.RepairOAuthClientBindings() require.NoError(t, err) assert.Empty(t, repaired) } @@ -283,83 +276,3 @@ func TestDowngradeView_APIKeyRecordStaysCurrent(t *testing.T) { assert.Equal(t, auth.ProfileModeSwitchable, mode) assertEqualBindings(t, m, "cursor", "", auth.ProfileModeSwitchable) } - -// TestClientBindingFieldsWrittenOnlyByAllowListedFunctions is the source test of -// research R4: an assignment to, or a composite-literal key of, ProfilePin or -// ProfileMode in this package's non-test code may appear only in the functions -// below. A new writer must go through writeClientBindingTx instead. -func TestClientBindingFieldsWrittenOnlyByAllowListedFunctions(t *testing.T) { - allowed := map[string]string{ - // THE writer of a client's pin/mode in both stores. - "writeClientBindingOptsTx": "the one binding writer", - // Builds the brand-new record literal; the OAuth entry is then synced - // through writeClientBindingTx in the same transaction. - "MintClientCredentialWith": "new client record literal", - // Assigns pin/mode on a COPY only to validate invariants and to return - // the after-snapshot; the stored write is writeClientBindingOptsTx. - "UpdateClientCredentialBinding": "validation copy and returned snapshot", - // Sets the restored binding on the returned (already stored) record; - // the stored restore is writeClientBindingTx. - "forgetClientCredential": "returned snapshot of the restored binding", - // Regular (non-client) agent tokens are rewritten directly; client - // records and OAuth-only entries go through writeClientBindingTx. The - // pseudo-record for an OAuth-only entry is a literal here. - "repinProfile": "plain pin rewrite of regular tokens, pseudo-record literal", - "RestorePins": "plain pin restore of regular tokens", - // Creates the OAuth-side entry at a client's first login (the only - // creator of oauth_client_bindings entries). - "CommitOAuthLogin": "creates the oauth_client_bindings entry", - } - - files, err := filepath.Glob("*.go") - require.NoError(t, err) - fset := token.NewFileSet() - isBindingField := func(name string) bool { return name == "ProfilePin" || name == "ProfileMode" } - var violations []string - used := map[string]bool{} - - for _, f := range files { - if strings.HasSuffix(f, "_test.go") { - continue - } - src, err := os.ReadFile(f) - require.NoError(t, err) - file, err := parser.ParseFile(fset, f, src, 0) - require.NoError(t, err) - for _, decl := range file.Decls { - fn, ok := decl.(*ast.FuncDecl) - if !ok || fn.Body == nil { - continue - } - ast.Inspect(fn.Body, func(n ast.Node) bool { - var pos token.Pos - hit := false - switch x := n.(type) { - case *ast.AssignStmt: - for _, lhs := range x.Lhs { - if sel, ok := lhs.(*ast.SelectorExpr); ok && isBindingField(sel.Sel.Name) { - hit, pos = true, sel.Pos() - } - } - case *ast.KeyValueExpr: - if id, ok := x.Key.(*ast.Ident); ok && isBindingField(id.Name) { - hit, pos = true, id.Pos() - } - } - if hit { - if _, ok := allowed[fn.Name.Name]; ok { - used[fn.Name.Name] = true - } else { - violations = append(violations, fset.Position(pos).String()+" in "+fn.Name.Name) - } - } - return true - }) - } - } - sort.Strings(violations) - assert.Empty(t, violations, "route the write through writeClientBindingTx or justify a new allow-list entry") - for name := range allowed { - assert.True(t, used[name], "allow-list entry %s is stale (no such write any more); remove it", name) - } -} diff --git a/internal/storage/client_binding_hardening_test.go b/internal/storage/client_binding_hardening_test.go new file mode 100644 index 000000000..48d8524e0 --- /dev/null +++ b/internal/storage/client_binding_hardening_test.go @@ -0,0 +1,266 @@ +package storage + +import ( + "encoding/json" + "errors" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.etcd.io/bbolt" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +func jsonUnmarshal(b []byte, v any) error { return json.Unmarshal(b, v) } + +func putTokenForTest(tx *bbolt.Tx, hash []byte, tok *auth.AgentToken) error { + data, err := json.Marshal(tok) + if err != nil { + return err + } + return tx.Bucket([]byte(AgentTokensBucket)).Put(hash, data) +} + +// TestWriteClientBindingTx_ValidatesBeforeAnyWrite: an invalid binding is an +// error and neither copy is touched, for API-key-only, OAuth-only and dual clients. +func TestWriteClientBindingTx_ValidatesBeforeAnyWrite(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + mintTestClient(t, m, "keyonly", auth.ProfileModeLocked, "ro") + commitNew(t, m, "r", "g1", "webonly", "ro", auth.ProfileModeLocked, time.Now()) + clientWithBoth(t, m, "both", auth.ProfileModeLocked, "ro") + + for _, id := range []string{"keyonly", "webonly", "both"} { + for _, bad := range []struct{ pin, mode string }{ + {"x", "sticky"}, {"", auth.ProfileModeLocked}, {"x", ""}, + } { + before := dumpDB(t, m) + err := m.db.db.Update(func(tx *bbolt.Tx) error { + return writeClientBindingTx(tx, id, bad.pin, bad.mode) + }) + require.Error(t, err, "%s %+v", id, bad) + assert.Equal(t, before, dumpDB(t, m), "%s: the transaction rolled back", id) + } + } + + // A revoked/expired tombstone is still updated as before. + _, err := m.RevokeClientAPIKey("keyonly") + require.NoError(t, err) + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + return writeClientBindingTx(tx, "keyonly", "full", auth.ProfileModeLocked) + })) + pin, mode, _, _, _, _ := bindings(t, m, "keyonly") + assert.Equal(t, "full", pin) + assert.Equal(t, auth.ProfileModeLocked, mode) +} + +func TestRepairOAuthClientBindings_InvalidAPIKeyBindingIsSkipped(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "ro") + clientWithBoth(t, m, "zed", auth.ProfileModeLocked, "ro") + // Corrupt cursor's API-key record (locked, empty pin) and drift zed's entry. + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + hash, tok, err := findClientTokenRecordLocked(tx, "cursor") + require.NoError(t, err) + tok.ProfilePin = "" + return putTokenForTest(tx, hash, tok) + })) + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + return oauthPutJSON(tx, OAuthClientBindingsBucket, "zed", &OAuthClientBinding{ProfilePin: "stale", ProfileMode: auth.ProfileModeLocked}) + })) + + repaired, skipped, err := m.RepairOAuthClientBindings() + require.NoError(t, err) + assert.Equal(t, []string{"zed"}, repaired) + assert.Equal(t, []string{"cursor"}, skipped) + _, _, _, oPin, _, _ := bindings(t, m, "cursor") + assert.Equal(t, "ro", oPin, "the invalid binding was not copied") +} + +func TestUpdateClientCredentialBinding_ErrorTextUnchangedForAPIKeyOnly(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + mintTestClient(t, m, "cursor", auth.ProfileModeLocked, "ro") + // Refusals keep their pre-slice text. + _, _, err := m.UpdateClientCredentialBinding("cursor", "", auth.ProfileModeLocked) + require.EqualError(t, err, "a locked client credential requires a non-empty profile") + _, _, err = m.UpdateClientCredentialBinding("cursor", "ro", "sticky") + require.EqualError(t, err, `invalid profile mode "sticky"`) + // The writer's own wording is never doubled. + err = m.db.db.Update(func(tx *bbolt.Tx) error { return writeClientBindingTx(tx, "cursor", "x", "sticky") }) + require.EqualError(t, err, `invalid profile mode "sticky"`) +} + +// TestRepinProfile_KeepsKeyOrderForRecordsAndHooks: existing records are handled +// in ONE list in bbolt key order, whether regular token or client, so `before` +// and the hook order are what they were before Spec 132. +func TestRepinProfile_KeepsKeyOrderForRecordsAndHooks(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + mintTestClient(t, m, "cursor", auth.ProfileModeLocked, "p") + + keyOrder := func() []string { + var names []string + require.NoError(t, m.db.db.View(func(tx *bbolt.Tx) error { + return tx.Bucket([]byte(AgentTokensBucket)).ForEach(func(_, v []byte) error { + var tk auth.AgentToken + require.NoError(t, jsonUnmarshal(v, &tk)) + names = append(names, tk.Name) + return nil + }) + })) + return names + } + // Add agent tokens pinned to p until the client record sits in the middle. + for i := 0; i < 30; i++ { + tok, raw := makeTestToken("agent-" + string(rune('a'+i))) + tok.ProfilePin = "p" + require.NoError(t, m.CreateAgentToken(tok, raw, testHMACKey)) + names := keyOrder() + if len(names) >= 3 && names[0] != "client-cursor" && names[len(names)-1] != "client-cursor" { + break + } + } + want := keyOrder() + require.NotEqual(t, "client-cursor", want[0]) + require.NotEqual(t, "client-cursor", want[len(want)-1]) + + var hooked []int + before, err := m.repinProfile("p", "q", func(w int) error { hooked = append(hooked, w); return nil }) + require.NoError(t, err) + var gotNames []string + for _, b := range before { + gotNames = append(gotNames, b.Name) + } + assert.Equal(t, want, gotNames, "before is in bbolt key order, clients and tokens interleaved") + var seq []int + for i := range want { + seq = append(seq, i) + } + assert.Equal(t, seq, hooked) +} + +// TestRepinProfile_ClearsStaleRollbackSnapshotOfClientWithLogins: after a connect +// mint over an OAuth-only client and a reassignment, rolling the connect back must +// not bring the pre-reassignment binding back onto the existing logins. +func TestRepinProfile_ClearsStaleRollbackSnapshotOfClientWithLogins(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "", auth.ProfileModeSwitchable, time.Now()) + mintTestClient(t, m, "webonly", auth.ProfileModeLocked, "ro") // snapshot: switchable, unpinned + + _, err := m.RepinProfile("ro", "restricted") + require.NoError(t, err) + _, err = m.ForgetClientCredentialRestoringPrior("webonly") + require.NoError(t, err) + + _, _, _, oPin, oMode, oOK := bindings(t, m, "webonly") + require.True(t, oOK) + assert.Equal(t, "restricted", oPin) + assert.Equal(t, auth.ProfileModeLocked, oMode) + g, err := m.GetOAuthGrant("g1") + require.NoError(t, err) + assert.False(t, g.Revoked) +} + +func TestRestorePins_OAuthSideIsCompareAndSet(t *testing.T) { + t.Run("a: dual client, API-key record removed, entry still restored", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "ro") + before, err := m.RepinProfile("ro", "full") + require.NoError(t, err) + require.NoError(t, m.DeleteAgentToken("client-cursor")) + require.NoError(t, m.RestorePins(before)) + _, _, apiOK, oPin, oMode, oOK := bindings(t, m, "cursor") + assert.False(t, apiOK) + require.True(t, oOK) + assert.Equal(t, "ro", oPin) + assert.Equal(t, auth.ProfileModeLocked, oMode) + }) + + t.Run("a2: dual client with its record present restores both", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "ro") + before, err := m.RepinProfile("ro", "full") + require.NoError(t, err) + require.NoError(t, m.RestorePins(before)) + assertEqualBindings(t, m, "cursor", "ro", auth.ProfileModeLocked) + }) + + t.Run("b: forgotten and re-created client keeps its new binding", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "A", auth.ProfileModeLocked, time.Now()) + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + _, err = m.ForgetClient("webonly") + require.NoError(t, err) + commitNew(t, m, "r2", "g2", "webonly", "P", auth.ProfileModeLocked, time.Now()) + require.NoError(t, m.RestorePins(before)) + _, _, _, oPin, _, _ := bindings(t, m, "webonly") + assert.Equal(t, "P", oPin) + }) + + t.Run("b2: a forgotten entry is not re-created", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "A", auth.ProfileModeLocked, time.Now()) + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + _, err = m.ForgetClient("webonly") + require.NoError(t, err) + require.NoError(t, m.RestorePins(before)) + _, _, _, _, _, oOK := bindings(t, m, "webonly") + assert.False(t, oOK) + }) + + t.Run("c: a connect minted after the repin keeps both copies", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "A", auth.ProfileModeLocked, time.Now()) + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + mintTestClient(t, m, "webonly", auth.ProfileModeLocked, "P") + require.NoError(t, m.RestorePins(before)) + assertEqualBindings(t, m, "webonly", "P", auth.ProfileModeLocked) + }) + + t.Run("d: a stored record with an empty hash is not a restore entry", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "A", auth.ProfileModeLocked, time.Now()) + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + require.Len(t, before, 1) + assert.True(t, isRepinRestoreEntry(&before[0])) + + // Same shape, no marker: ignored entirely. + lookalike := auth.AgentToken{Name: "client-webonly", Kind: auth.KindClient, ClientID: "webonly", + ProfilePin: "A", ProfileMode: auth.ProfileModeLocked, TokenHash: ""} + assert.False(t, isRepinRestoreEntry(&lookalike)) + require.NoError(t, m.RestorePins([]auth.AgentToken{lookalike})) + _, _, _, oPin, _, _ := bindings(t, m, "webonly") + assert.Equal(t, "B", oPin) + + // The real entry still restores. + require.NoError(t, m.RestorePins(before)) + _, _, _, oPin, _, _ = bindings(t, m, "webonly") + assert.Equal(t, "A", oPin) + }) +} + +func TestRepinProfile_FailureKeepsErrorTextAndRollsBack(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + mintTestClient(t, m, "cursor", auth.ProfileModeLocked, "p") + boom := errors.New("boom") + _, err := m.repinProfile("p", "q", func(int) error { return boom }) + require.ErrorIs(t, err, boom) + pin, _, _, _, _, _ := bindings(t, m, "cursor") + assert.Equal(t, "p", pin) +} diff --git a/internal/storage/client_binding_source_test.go b/internal/storage/client_binding_source_test.go new file mode 100644 index 000000000..996aa8326 --- /dev/null +++ b/internal/storage/client_binding_source_test.go @@ -0,0 +1,211 @@ +package storage + +import ( + "go/ast" + "go/parser" + "go/token" + "io/fs" + "os" + "path/filepath" + "sort" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// bindingWriteSites parses one Go source and counts every direct write to a +// ProfilePin / ProfileMode field, keyed by "|", where +// shape is "assign:" for an assignment to a selector (e.g. +// "assign:tok.ProfilePin") and "literal:" for a composite-literal key. +func bindingWriteSites(t *testing.T, filename string, src []byte) map[string]int { + t.Helper() + fset := token.NewFileSet() + file, err := parser.ParseFile(fset, filename, src, 0) + require.NoError(t, err) + isField := func(n string) bool { return n == "ProfilePin" || n == "ProfileMode" } + out := map[string]int{} + for _, decl := range file.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + ast.Inspect(fn.Body, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.AssignStmt: + for _, lhs := range x.Lhs { + if sel, ok := lhs.(*ast.SelectorExpr); ok && isField(sel.Sel.Name) { + recv := "?" + if id, ok := sel.X.(*ast.Ident); ok { + recv = id.Name + } + out[fn.Name.Name+"|assign:"+recv+"."+sel.Sel.Name]++ + } + } + case *ast.KeyValueExpr: + if id, ok := x.Key.(*ast.Ident); ok && isField(id.Name) { + out[fn.Name.Name+"|literal:"+id.Name]++ + } + } + return true + }) + } + return out +} + +// allowedBindingWriteSites lists EVERY direct write to a client's pin/mode in +// this package's non-test code, by exact site (function, shape) and count, so a +// new mutation inside an allow-listed function fails too. A new writer must go +// through writeClientBindingTx (research R4). +var allowedBindingWriteSites = map[string]int{ + // THE writer of a client's pin/mode in both stores (API-key record, then + // the OAuth entry). + "writeClientBindingOptsTx|assign:tok.ProfilePin": 1, // tok.ProfilePin, tok.ProfileMode = pin, mode + "writeClientBindingOptsTx|assign:tok.ProfileMode": 1, + "writeClientBindingOptsTx|assign:b.ProfilePin": 1, // the OAuth entry + "writeClientBindingOptsTx|assign:b.ProfileMode": 1, + + // Builds the brand-new client record literal; the OAuth entry is then + // synced through writeClientBindingTx in the same transaction. + "MintClientCredentialWith|literal:ProfileMode": 1, + "MintClientCredentialWith|literal:ProfilePin": 1, + + // Assigns on a COPY only to validate the invariants and to return the + // after-snapshot; the stored write is writeClientBindingOptsTx. + "UpdateClientCredentialBinding|assign:updated.ProfilePin": 1, + "UpdateClientCredentialBinding|assign:updated.ProfileMode": 1, + + // Sets the restored binding on the RETURNED record, which is already + // stored; the stored restore is writeClientBindingTx. + "forgetClientCredential|assign:tok.ProfilePin": 1, + "forgetClientCredential|assign:tok.ProfileMode": 1, + + // Regular (non-client) agent tokens are rewritten directly by repin; client + // records go through the writer. + "repinProfile|assign:t.ProfilePin": 1, + // The restore entry carries the OLD binding in these fields. + "repinRestoreEntry|literal:ProfilePin": 1, + "repinRestoreEntry|literal:ProfileMode": 1, + + // Restores a stored record's pin by hash, exactly as before Spec 132 (the + // mode is never changed by a repin; browser-login entries are restored + // compare-and-set through writeClientBindingTx). + "RestorePins|assign:t.ProfilePin": 1, + + // The only creator of oauth_client_bindings entries (a client's first login). + "CommitOAuthLogin|assign:nb.ProfilePin": 2, // new-client branch and existing-client branch + "CommitOAuthLogin|assign:nb.ProfileMode": 2, +} + +func TestClientBindingFieldsWrittenOnlyByAllowListedSites(t *testing.T) { + files, err := filepath.Glob("*.go") + require.NoError(t, err) + got := map[string]int{} + for _, f := range files { + if strings.HasSuffix(f, "_test.go") { + continue + } + src, err := os.ReadFile(f) + require.NoError(t, err) + for k, n := range bindingWriteSites(t, f, src) { + got[k] += n + } + } + assert.Equal(t, allowedBindingWriteSites, got, + "a direct write to ProfilePin/ProfileMode appeared, disappeared or was duplicated: "+ + "route it through writeClientBindingTx, or justify the allow-list change") +} + +// TestBindingWriteSiteChecker_DetectsBypass proves the checker sees a direct +// mutation added inside an allow-listed function and in a new function. +func TestBindingWriteSiteChecker_DetectsBypass(t *testing.T) { + src := []byte(`package storage + +func writeClientBindingOptsTx() { + tok.ProfilePin, tok.ProfileMode = pin, mode + tok.ProfilePin = "second write" +} + +func sneaky() { + rec.ProfileMode = "locked" + _ = AgentToken{ProfilePin: "x"} +} +`) + got := bindingWriteSites(t, "synthetic.go", src) + assert.Equal(t, 2, got["writeClientBindingOptsTx|assign:tok.ProfilePin"], "the duplicate is counted") + assert.Equal(t, 1, got["sneaky|assign:rec.ProfileMode"]) + assert.Equal(t, 1, got["sneaky|literal:ProfilePin"]) + assert.NotEqual(t, allowedBindingWriteSites["writeClientBindingOptsTx|assign:tok.ProfilePin"], + got["writeClientBindingOptsTx|assign:tok.ProfilePin"], "exceeds the allow-list count") + _, allowed := allowedBindingWriteSites["sneaky|assign:rec.ProfileMode"] + assert.False(t, allowed) +} + +// TestNoProductionCodeCreatesClientRecordsThroughCreateAgentToken: CreateAgentToken +// stores a whole record and would bypass the binding writer for a Kind=client +// record. Client records are minted only through MintClientCredential*, so no +// non-test caller of CreateAgentToken may mention KindClient or set a Kind. +func TestNoProductionCodeCreatesClientRecordsThroughCreateAgentToken(t *testing.T) { + roots := []string{"..", filepath.Join("..", "..", "cmd")} + var offenders []string + calls := 0 + for _, root := range roots { + require.NoError(t, filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { + return nil + } + src, err := os.ReadFile(path) + if err != nil || !strings.Contains(string(src), "CreateAgentToken(") { + return err + } + file, err := parser.ParseFile(token.NewFileSet(), path, src, 0) + if err != nil { + return nil + } + for _, decl := range file.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil || fn.Name.Name == "CreateAgentToken" { + continue + } + callsHere, setsKind := false, false + ast.Inspect(fn.Body, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.CallExpr: + if sel, ok := x.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "CreateAgentToken" { + callsHere = true + } + case *ast.SelectorExpr: + if x.Sel.Name == "KindClient" { + setsKind = true + } + case *ast.KeyValueExpr: + if id, ok := x.Key.(*ast.Ident); ok && id.Name == "Kind" { + setsKind = true + } + case *ast.AssignStmt: + for _, l := range x.Lhs { + if sel, ok := l.(*ast.SelectorExpr); ok && sel.Sel.Name == "Kind" { + setsKind = true + } + } + } + return true + }) + if callsHere { + calls++ + if setsKind { + offenders = append(offenders, path+" "+fn.Name.Name) + } + } + } + return nil + })) + } + sort.Strings(offenders) + assert.Empty(t, offenders) + assert.Positive(t, calls, "the walk must actually find the callers (guards against a vacuous pass)") +} diff --git a/internal/storage/client_credentials.go b/internal/storage/client_credentials.go index c68d52606..80caab4f3 100644 --- a/internal/storage/client_credentials.go +++ b/internal/storage/client_credentials.go @@ -288,7 +288,7 @@ func (m *Manager) UpdateClientCredentialBinding(clientID, pin, mode string) (bef // snapshot; the stored write is the one binding writer, which also // keeps the client's OAuth entry equal. if err := writeClientBindingOptsTx(tx, clientID, pin, mode, true); err != nil { - return fmt.Errorf("failed to store client binding: %w", err) + return err } before, after = &snapshot, &updated return nil diff --git a/internal/storage/oauth_login.go b/internal/storage/oauth_login.go index 49e1a8faa..f515a409d 100644 --- a/internal/storage/oauth_login.go +++ b/internal/storage/oauth_login.go @@ -82,6 +82,9 @@ var ( ErrOAuthBindingChanged = errors.New("client binding changed since it was reviewed") // ErrOAuthGrantNotFound: no such grant. ErrOAuthGrantNotFound = errors.New("oauth grant not found") + // ErrOAuthRegistrationExists: CreateOAuthRegistration found the client id + // already stored (an approved registration must never be overwritten). + ErrOAuthRegistrationExists = errors.New("oauth registration already exists") ) // OAuthActor names who approved a login. @@ -275,6 +278,14 @@ func (m *Manager) CreateOAuthRegistration(reg OAuthRegistration) error { m.mu.Lock() defer m.mu.Unlock() return m.db.db.Update(func(tx *bbolt.Tx) error { + // An id that is already stored (above all an approved registration + // with live grants) is never overwritten. + var existing OAuthRegistration + if found, err := oauthGetJSON(tx, OAuthRegistrationsBucket, reg.ClientID, &existing); err != nil { + return err + } else if found { + return ErrOAuthRegistrationExists + } if err := oauthPutJSON(tx, OAuthRegistrationsBucket, reg.ClientID, ®); err != nil { return err } @@ -282,7 +293,9 @@ func (m *Manager) CreateOAuthRegistration(reg OAuthRegistration) error { id string at time.Time } - var open []row + // The new row takes part in the "oldest non-approved" choice, so a + // backdated insert cannot evict a newer row while surviving itself. + open := []row{{reg.ClientID, reg.CreatedAt}} if err := oauthForEach(tx, OAuthRegistrationsBucket, func(key string, r OAuthRegistration) error { if r.State != OAuthRegistrationApproved && key != reg.ClientID { open = append(open, row{key, r.CreatedAt}) @@ -291,8 +304,7 @@ func (m *Manager) CreateOAuthRegistration(reg OAuthRegistration) error { }); err != nil { return err } - // The new row counts toward the cap. - excess := len(open) + 1 - MaxUnapprovedOAuthRegistrations + excess := len(open) - MaxUnapprovedOAuthRegistrations if excess <= 0 { return nil } @@ -363,30 +375,26 @@ func (m *Manager) MarkOAuthRegistrationAuthorized(id string, at time.Time) error func (m *Manager) SweepOAuthRegistrations(now time.Time) (int, error) { m.mu.Lock() defer m.mu.Unlock() + + // View first: with nothing to sweep no write transaction is opened (an + // empty Update still commits a meta page). + any := false + if err := m.db.db.View(func(tx *bbolt.Tx) error { + drop, err := registrationsToSweepTx(tx, now) + any = len(drop) > 0 + return err + }); err != nil || !any { + return 0, err + } + deleted := 0 err := m.db.db.Update(func(tx *bbolt.Tx) error { b := tx.Bucket([]byte(OAuthRegistrationsBucket)) if b == nil { return nil } - var drop []string - if err := oauthForEach(tx, OAuthRegistrationsBucket, func(key string, r OAuthRegistration) error { - switch r.State { - case OAuthRegistrationPending: - if now.Sub(r.CreatedAt) > OAuthPendingRegistrationTTL { - drop = append(drop, key) - } - case OAuthRegistrationAuthorized: - at := r.CreatedAt - if r.AuthorizedAt != nil { - at = *r.AuthorizedAt - } - if now.Sub(at) > OAuthAuthorizedRegistrationTTL { - drop = append(drop, key) - } - } - return nil - }); err != nil { + drop, err := registrationsToSweepTx(tx, now) + if err != nil { return err } for _, k := range drop { @@ -400,6 +408,28 @@ func (m *Manager) SweepOAuthRegistrations(now time.Time) (int, error) { return deleted, err } +func registrationsToSweepTx(tx *bbolt.Tx, now time.Time) ([]string, error) { + var drop []string + err := oauthForEach(tx, OAuthRegistrationsBucket, func(key string, r OAuthRegistration) error { + switch r.State { + case OAuthRegistrationPending: + if now.Sub(r.CreatedAt) > OAuthPendingRegistrationTTL { + drop = append(drop, key) + } + case OAuthRegistrationAuthorized: + at := r.CreatedAt + if r.AuthorizedAt != nil { + at = *r.AuthorizedAt + } + if now.Sub(at) > OAuthAuthorizedRegistrationTTL { + drop = append(drop, key) + } + } + return nil + }) + return drop, err +} + // ListOAuthRegistrations returns every stored registration. func (m *Manager) ListOAuthRegistrations() ([]OAuthRegistration, error) { m.mu.RLock() @@ -450,6 +480,23 @@ func currentClientBindingTx(tx *bbolt.Tx, clientID string) (pin, mode string, ex return "", "", false, nil } +// CurrentClientBinding returns the binding the client is held to: the API-key +// record's pin and mode when the client has one, else its browser-login entry; +// found=false when it has neither. The browser-login request path MUST read the +// binding through this function and never from the OAuth entry alone: an older +// binary that knows nothing of browser logins may have changed the API-key +// record while the entry stayed behind, and the API-key record is the truth. +func (m *Manager) CurrentClientBinding(clientID string) (pin, mode string, found bool, err error) { + m.mu.RLock() + defer m.mu.RUnlock() + err = m.db.db.View(func(tx *bbolt.Tx) error { + var e error + pin, mode, found, e = currentClientBindingTx(tx, clientID) + return e + }) + return pin, mode, found, err +} + // ClientBindingRevision returns the binding revision the consent page shows // and sends back; see clientBindingRevisionTx. func (m *Manager) ClientBindingRevision(clientID string) (string, error) { @@ -491,6 +538,12 @@ type CommitLoginInput struct { // creates the OAuth-side binding when the client has none, promotes the // registration to approved, stores the grant, revokes the replaced login and // writes the ever-used marker. Any failed check leaves the database untouched. +// +// What it does NOT detect: a revoke or forget of an EXISTING client between +// approval and exchange. The binding revision covers pin and mode only, and a +// revoke changes neither. The caller must prevent that by cancelling the +// pending request (and any unconsumed code) under the binding write lock when +// it revokes or forgets the client (research R15). func (m *Manager) CommitOAuthLogin(in CommitLoginInput) (OAuthGrant, error) { g := in.Grant if in.Client == "" { @@ -554,11 +607,8 @@ func (m *Manager) CommitOAuthLogin(in CommitLoginInput) (OAuthGrant, error) { if existingBinding == nil { nb := OAuthClientBinding{UpdatedAt: now} if in.NewClient { - if in.Mode != auth.ProfileModeLocked && in.Mode != auth.ProfileModeSwitchable { - return fmt.Errorf("invalid profile mode %q", in.Mode) - } - if in.Mode == auth.ProfileModeLocked && in.Pin == "" { - return fmt.Errorf("a locked client binding requires a non-empty profile") + if err := validateClientBinding(in.Pin, in.Mode); err != nil { + return err } if utf8.RuneCountInString(in.DisplayName) > auth.MaxClientDisplayName { return fmt.Errorf("client display name is too long") @@ -572,6 +622,9 @@ func (m *Manager) CommitOAuthLogin(in CommitLoginInput) (OAuthGrant, error) { if !exists { return ErrOAuthBindingChanged } + if err := validateClientBinding(pin, mode); err != nil { + return err + } nb.ProfilePin, nb.ProfileMode = pin, mode if anyRecord != nil { nb.DisplayName = anyRecord.DisplayName @@ -683,11 +736,27 @@ func (m *Manager) ListOAuthGrantsForClient(clientID string) ([]OAuthGrant, error return out, nil } -// GetOAuthGrantByAccessHash resolves an access-token hash to its grant through -// the index, re-checking that the grant still carries that hash. A missing or -// stale entry is ErrOAuthGrantNotFound. Revocation and expiry are the -// caller's decision (it needs the grant to report them). -func (m *Manager) GetOAuthGrantByAccessHash(hash string) (*OAuthGrant, error) { +// AuthenticateOAuthAccess resolves an access-token hash to its grant and +// enforces validity itself: the hash must match (constant time), the grant must +// not be revoked, and both the access and the refresh lifetime must end +// strictly after now (so a lapsed-but-unswept grant, and the exact expiry +// instant, fail). Every failure is the one uniform ErrOAuthGrantNotFound. +func (m *Manager) AuthenticateOAuthAccess(accessHash string, now time.Time) (*OAuthGrant, error) { + g, err := m.getOAuthGrantByAccessHash(accessHash) + if err != nil { + return nil, err + } + if g.Revoked || !g.AccessExpiresAt.After(now) || !g.RefreshExpiresAt.After(now) { + return nil, ErrOAuthGrantNotFound + } + return g, nil +} + +// getOAuthGrantByAccessHash resolves an access-token hash to a NON-revoked +// grant through the index, re-checking that the grant still carries that hash. +// Expiry is not checked here; authentication goes through +// AuthenticateOAuthAccess. +func (m *Manager) getOAuthGrantByAccessHash(hash string) (*OAuthGrant, error) { if hash == "" { return nil, ErrOAuthGrantNotFound } @@ -707,7 +776,7 @@ func (m *Manager) GetOAuthGrantByAccessHash(hash string) (*OAuthGrant, error) { if err != nil || cand == nil { return err } - if subtle.ConstantTimeCompare([]byte(cand.AccessHash), []byte(hash)) == 1 { + if !cand.Revoked && subtle.ConstantTimeCompare([]byte(cand.AccessHash), []byte(hash)) == 1 { g = cand } return nil @@ -722,10 +791,14 @@ func (m *Manager) GetOAuthGrantByAccessHash(hash string) (*OAuthGrant, error) { } // RotateOAuthRefresh is the refresh-token exchange, in one transaction. The -// caller has already verified the token's MAC; storage sees hashes only. +// caller has already verified the token's MAC; storage sees hashes only. That +// MAC must bind the grant id AND the secret: storage cannot tell an old +// authentic secret from a forged one, so any non-current secret presented for a +// live grant revokes it as a replay. // // - unknown, revoked or lapsed grant: RefreshInvalid, nothing written, the // lifetime is not extended; +// - an empty presented hash: RefreshInvalid, nothing written (never a replay); // - presented hash equals the current one (constant time): rotate; // - anything else: the grant is revoked with reason "replay". func (m *Manager) RotateOAuthRefresh(grantID, presentedSecretHash, newRefreshHash, newRefreshPrefix, newAccessHash string, now time.Time, accessTTL, refreshTTL time.Duration) (RefreshOutcome, OAuthGrant, error) { @@ -738,7 +811,7 @@ func (m *Manager) RotateOAuthRefresh(grantID, presentedSecretHash, newRefreshHas live := false if err := m.db.db.View(func(tx *bbolt.Tx) error { g, err := getOAuthGrantTx(tx, grantID) - live = err == nil && g != nil && !g.Revoked && g.RefreshExpiresAt.After(now) + live = err == nil && presentedSecretHash != "" && g != nil && !g.Revoked && g.RefreshExpiresAt.After(now) return err }); err != nil { return RefreshInvalid, OAuthGrant{}, err @@ -830,6 +903,32 @@ func (m *Manager) TouchOAuthGrant(id string, lastUsedAt time.Time, observedName }) } +// deadGrantsTx lists the grants past the retention window and the registration +// and client ids still referenced by a surviving grant. +func deadGrantsTx(tx *bbolt.Tx, now time.Time) (dead []OAuthGrant, survivingReg, survivingClient map[string]bool, err error) { + survivingReg, survivingClient = map[string]bool{}, map[string]bool{} + err = oauthForEach(tx, OAuthGrantsBucket, func(_ string, g OAuthGrant) error { + var since time.Time + if g.Revoked { + if g.RevokedAt != nil { + since = *g.RevokedAt + } else { + since = g.ApprovedAt + } + } else if !g.RefreshExpiresAt.After(now) { + since = g.RefreshExpiresAt + } + if !since.IsZero() && now.Sub(since) > OAuthDeadGrantRetention { + dead = append(dead, g) + return nil + } + survivingReg[g.RegistrationID] = true + survivingClient[g.Client] = true + return nil + }) + return dead, survivingReg, survivingClient, err +} + // SweepOAuthGrants deletes grants that were revoked, or whose refresh token // lapsed, more than 30 days ago. A registration whose last grant record goes // is deleted with it, and so is the binding entry of a client whose last grant @@ -837,34 +936,25 @@ func (m *Manager) TouchOAuthGrant(id string, lastUsedAt time.Time, observedName func (m *Manager) SweepOAuthGrants(now time.Time) (int, error) { m.mu.Lock() defer m.mu.Unlock() + + // View first: with nothing to delete no write transaction is opened. + any := false + if err := m.db.db.View(func(tx *bbolt.Tx) error { + dead, _, _, err := deadGrantsTx(tx, now) + any = len(dead) > 0 + return err + }); err != nil || !any { + return 0, err + } + deleted := 0 err := m.db.db.Update(func(tx *bbolt.Tx) error { gb := tx.Bucket([]byte(OAuthGrantsBucket)) if gb == nil { return nil } - var dead []OAuthGrant - survivingReg := map[string]bool{} - survivingClient := map[string]bool{} - if err := oauthForEach(tx, OAuthGrantsBucket, func(_ string, g OAuthGrant) error { - var since time.Time - if g.Revoked { - if g.RevokedAt != nil { - since = *g.RevokedAt - } else { - since = g.ApprovedAt - } - } else if !g.RefreshExpiresAt.After(now) { - since = g.RefreshExpiresAt - } - if !since.IsZero() && now.Sub(since) > OAuthDeadGrantRetention { - dead = append(dead, g) - return nil - } - survivingReg[g.RegistrationID] = true - survivingClient[g.Client] = true - return nil - }); err != nil { + dead, survivingReg, survivingClient, err := deadGrantsTx(tx, now) + if err != nil { return err } for _, g := range dead { diff --git a/internal/storage/oauth_login_client_ops_test.go b/internal/storage/oauth_login_client_ops_test.go index 8c58799c1..e600af47c 100644 --- a/internal/storage/oauth_login_client_ops_test.go +++ b/internal/storage/oauth_login_client_ops_test.go @@ -40,7 +40,7 @@ func TestForgetClient_DeletesLoginsBindingAndOrphanRegistrations(t *testing.T) { gs, err := m.ListOAuthGrantsForClient("cursor") require.NoError(t, err) assert.Empty(t, gs) - _, err = m.GetOAuthGrantByAccessHash("ah-grant-cursor") + _, err = m.getOAuthGrantByAccessHash("ah-grant-cursor") assert.ErrorIs(t, err, ErrOAuthGrantNotFound) b, _ := m.GetOAuthClientBinding("cursor") assert.Nil(t, b) @@ -109,7 +109,7 @@ func TestRevokeClient_RevokesKeyAndAllGrantsKeepsRecords(t *testing.T) { assert.Equal(t, OAuthRevokeClientRevoked, g.RevokeReason) require.NotNil(t, g.RevokedAt) } - _, err = m.GetOAuthGrantByAccessHash("ah-grant-cursor") + _, err = m.getOAuthGrantByAccessHash("ah-grant-cursor") assert.ErrorIs(t, err, ErrOAuthGrantNotFound, "revoked grants leave the access index") b, _ := m.GetOAuthClientBinding("cursor") assert.NotNil(t, b, "the binding entry is kept for display") diff --git a/internal/storage/oauth_login_hardening_test.go b/internal/storage/oauth_login_hardening_test.go new file mode 100644 index 000000000..cdb0181df --- /dev/null +++ b/internal/storage/oauth_login_hardening_test.go @@ -0,0 +1,160 @@ +package storage + +import ( + "fmt" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.etcd.io/bbolt" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +func TestAuthenticateOAuthAccess(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + g := commitNew(t, m, "reg1", "grant1", "myclient", "", auth.ProfileModeSwitchable, now) + + got, err := m.AuthenticateOAuthAccess("ah-grant1", now) + require.NoError(t, err) + assert.Equal(t, "grant1", got.GrantID) + + _, err = m.AuthenticateOAuthAccess("ah-grant1", g.AccessExpiresAt) + assert.ErrorIs(t, err, ErrOAuthGrantNotFound, "at the expiry instant the token is no longer valid") + _, err = m.AuthenticateOAuthAccess("ah-grant1", g.AccessExpiresAt.Add(-time.Nanosecond)) + assert.NoError(t, err) + _, err = m.AuthenticateOAuthAccess("", now) + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + _, err = m.AuthenticateOAuthAccess("nope", now) + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + + // Lapsed refresh, not yet swept: refused even with a live access expiry. + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg2", now))) + lapsed := newTestGrant("grant2", "reg2", "myclient", now) + lapsed.AccessExpiresAt = now.Add(time.Hour) + lapsed.RefreshExpiresAt = now.Add(time.Minute) + rev, _ := m.ClientBindingRevision("myclient") + _, err = m.CommitOAuthLogin(CommitLoginInput{Grant: lapsed, Client: "myclient", ExpectedBindingRevision: rev, Now: now}) + require.NoError(t, err) + _, err = m.AuthenticateOAuthAccess("ah-grant2", now) + require.NoError(t, err) + _, err = m.AuthenticateOAuthAccess("ah-grant2", now.Add(2*time.Minute)) + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + + // Revoked. + _, err = m.RevokeOAuthGrant("grant1", OAuthRevokeAdmin, now) + require.NoError(t, err) + _, err = m.AuthenticateOAuthAccess("ah-grant1", now) + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + // A stale index entry pointing at a revoked grant never resolves either. + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + return putAccessIndexTx(tx, "ah-grant1", "grant1") + })) + _, err = m.getOAuthGrantByAccessHash("ah-grant1") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) +} + +func TestCreateOAuthRegistration_DuplicateIDRefused(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + commitNew(t, m, "reg1", "grant1", "myclient", "", auth.ProfileModeSwitchable, now) + before := dumpDB(t, m) + + err := m.CreateOAuthRegistration(newTestReg("reg1", now.Add(time.Hour))) + assert.ErrorIs(t, err, ErrOAuthRegistrationExists) + assert.Equal(t, before, dumpDB(t, m), "nothing written") + r, err := m.GetOAuthRegistration("reg1") + require.NoError(t, err) + assert.Equal(t, OAuthRegistrationApproved, r.State) + g, err := m.GetOAuthGrant("grant1") + require.NoError(t, err) + assert.False(t, g.Revoked) +} + +func TestCreateOAuthRegistration_BackdatedInsertDoesNotEvictNewer(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + base := time.Now().UTC().Add(-time.Hour) + for i := 0; i < MaxUnapprovedOAuthRegistrations; i++ { + require.NoError(t, m.CreateOAuthRegistration(newTestReg(fmt.Sprintf("r%02d", i), base.Add(time.Duration(i)*time.Second)))) + } + // Older than every existing row: it is itself the oldest and goes; no + // newer row is evicted in its place. + require.NoError(t, m.CreateOAuthRegistration(newTestReg("ancient", base.Add(-time.Hour)))) + _, err := m.GetOAuthRegistration("ancient") + assert.ErrorIs(t, err, ErrOAuthRegistrationGone) + regs, err := m.ListOAuthRegistrations() + require.NoError(t, err) + assert.Len(t, regs, MaxUnapprovedOAuthRegistrations) + _, err = m.GetOAuthRegistration("r00") + assert.NoError(t, err) +} + +func TestRotateOAuthRefresh_EmptyPresentedHashIsInvalidNotReplay(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + commitNew(t, m, "reg1", "grant1", "myclient", "", auth.ProfileModeSwitchable, now) + before := dumpDB(t, m) + tx := dbTxID(t, m) + out, _, err := m.RotateOAuthRefresh("grant1", "", "x", "p", "y", now, time.Minute, time.Hour) + require.NoError(t, err) + assert.Equal(t, RefreshInvalid, out) + assert.Equal(t, before, dumpDB(t, m)) + assert.Equal(t, tx, dbTxID(t, m)) +} + +// TestNoopCallsCommitNoWriteTransaction: with nothing to do, the sweeps and +// the repair open no Update transaction (an empty one still commits a meta page). +func TestNoopCallsCommitNoWriteTransaction(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + now := time.Now().UTC() + check := func(name string) { + tx := dbTxID(t, m) + _, err := m.SweepOAuthRegistrations(now) + require.NoError(t, err) + _, err = m.SweepOAuthGrants(now) + require.NoError(t, err) + _, _, err = m.RepairOAuthClientBindings() + require.NoError(t, err) + assert.Equal(t, tx, dbTxID(t, m), name) + } + check("fresh database") + + // With live data and nothing expired or drifted, still no write. + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "ro") + check("live data") +} + +func TestCurrentClientBinding(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + _, _, found, err := m.CurrentClientBinding("cursor") + require.NoError(t, err) + assert.False(t, found) + + commitNew(t, m, "r", "g1", "webonly", "ro", auth.ProfileModeLocked, time.Now()) + pin, mode, found, err := m.CurrentClientBinding("webonly") + require.NoError(t, err) + assert.True(t, found) + assert.Equal(t, "ro", pin) + assert.Equal(t, auth.ProfileModeLocked, mode) + + // The API-key record wins over a stale OAuth entry (older binary). + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "ro") + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + return oauthPutJSON(tx, OAuthClientBindingsBucket, "cursor", &OAuthClientBinding{ + ProfilePin: "stale", ProfileMode: auth.ProfileModeSwitchable, + }) + })) + pin, mode, found, err = m.CurrentClientBinding("cursor") + require.NoError(t, err) + assert.True(t, found) + assert.Equal(t, "ro", pin) + assert.Equal(t, auth.ProfileModeLocked, mode) +} diff --git a/internal/storage/oauth_login_test.go b/internal/storage/oauth_login_test.go index 9fbd6ddb1..05ad2defd 100644 --- a/internal/storage/oauth_login_test.go +++ b/internal/storage/oauth_login_test.go @@ -103,7 +103,7 @@ func TestOAuthLoginLazyBuckets(t *testing.T) { assert.Empty(t, regs) _, err = m.GetOAuthGrant("x") assert.ErrorIs(t, err, ErrOAuthGrantNotFound) - _, err = m.GetOAuthGrantByAccessHash("h") + _, err = m.getOAuthGrantByAccessHash("h") assert.ErrorIs(t, err, ErrOAuthGrantNotFound) gs, err := m.ListOAuthGrants() require.NoError(t, err) @@ -138,7 +138,7 @@ func TestOAuthLoginLazyBuckets(t *testing.T) { assert.ErrorIs(t, err, ErrOAuthGrantNotFound) assert.ErrorIs(t, m.TouchOAuthGrant("g", now, ""), ErrOAuthGrantNotFound) assert.ErrorIs(t, m.MarkOAuthRegistrationAuthorized("r", now), ErrOAuthRegistrationGone) - rep, err := m.RepairOAuthClientBindings() + rep, _, err := m.RepairOAuthClientBindings() require.NoError(t, err) assert.Empty(t, rep) _, err = m.ForgetClient("cursor") @@ -269,7 +269,7 @@ func TestCommitOAuthLogin_NewClient(t *testing.T) { assert.Equal(t, auth.ProfileModeLocked, b.ProfileMode) assert.Equal(t, "Custom", b.DisplayName) - byHash, err := m.GetOAuthGrantByAccessHash("ah-grant1") + byHash, err := m.getOAuthGrantByAccessHash("ah-grant1") require.NoError(t, err) assert.Equal(t, "grant1", byHash.GrantID) @@ -438,7 +438,7 @@ func TestCommitOAuthLogin_ReplaceGrant(t *testing.T) { require.NoError(t, err) assert.True(t, old.Revoked) assert.Equal(t, OAuthRevokeReplaced, old.RevokeReason) - _, err = m.GetOAuthGrantByAccessHash("ah-old1") + _, err = m.getOAuthGrantByAccessHash("ah-old1") assert.ErrorIs(t, err, ErrOAuthGrantNotFound, "a revoked grant leaves the access index") // A grant of ANOTHER client is ignored. @@ -468,9 +468,9 @@ func TestRotateOAuthRefresh(t *testing.T) { assert.Equal(t, "ah2", g.AccessHash) assert.WithinDuration(t, later.Add(15*time.Minute), g.AccessExpiresAt, time.Second) assert.WithinDuration(t, later.Add(30*24*time.Hour), g.RefreshExpiresAt, time.Second) - _, err = m.GetOAuthGrantByAccessHash("ah-grant1") + _, err = m.getOAuthGrantByAccessHash("ah-grant1") assert.ErrorIs(t, err, ErrOAuthGrantNotFound, "the old access token is gone") - byNew, err := m.GetOAuthGrantByAccessHash("ah2") + byNew, err := m.getOAuthGrantByAccessHash("ah2") require.NoError(t, err) assert.Equal(t, "grant1", byNew.GrantID) }) @@ -481,7 +481,7 @@ func TestRotateOAuthRefresh(t *testing.T) { assert.Equal(t, RefreshReplay, out) assert.True(t, g.Revoked) assert.Equal(t, OAuthRevokeReplay, g.RevokeReason) - _, err = m.GetOAuthGrantByAccessHash("ah2") + _, err = m.getOAuthGrantByAccessHash("ah2") assert.ErrorIs(t, err, ErrOAuthGrantNotFound) }) @@ -547,7 +547,7 @@ func TestRevokeTouchOAuthGrant(t *testing.T) { assert.False(t, changed) g, _ = m.GetOAuthGrant("grant1") assert.Equal(t, OAuthRevokeAdmin, g.RevokeReason, "the first reason stays") - _, err = m.GetOAuthGrantByAccessHash("ah-grant1") + _, err = m.getOAuthGrantByAccessHash("ah-grant1") assert.ErrorIs(t, err, ErrOAuthGrantNotFound) } From 8ecda0aa41e33c785927b2c3a702481bddb079d6 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 19:28:12 +0200 Subject: [PATCH 09/42] fix(oauth): validate bindings only where a browser-login copy exists (Spec 132 PR-1c) Related #1971 --- internal/storage/client_binding.go | 18 ++-- .../storage/client_binding_hardening_test.go | 9 +- .../storage/client_binding_legacy_test.go | 101 ++++++++++++++++++ 3 files changed, 119 insertions(+), 9 deletions(-) create mode 100644 internal/storage/client_binding_legacy_test.go diff --git a/internal/storage/client_binding.go b/internal/storage/client_binding.go index fe1a79d3c..ed4e2a075 100644 --- a/internal/storage/client_binding.go +++ b/internal/storage/client_binding.go @@ -47,10 +47,20 @@ func writeClientBindingTx(tx *bbolt.Tx, clientID, pin, mode string) error { // the API-key record's PriorProfile* snapshot in the same write (a binding // change makes the mint-time snapshot stale). func writeClientBindingOptsTx(tx *bbolt.Tx, clientID, pin, mode string, clearPrior bool) error { - // Validate before ANY write so neither copy can be left half-updated. - if err := validateClientBinding(pin, mode); err != nil { + // Validation applies only where a browser-login copy would be written: a + // client with just an API-key record is written exactly as before Spec 132 + // (one malformed legacy tombstone must not block a profile rename). A client + // with an OAuth entry is validated before ANY write, so neither copy can be + // left half-updated. + b, err := getOAuthBindingTx(tx, clientID) + if err != nil { return err } + if b != nil { + if err := validateClientBinding(pin, mode); err != nil { + return err + } + } found := false hash, tok, err := findClientTokenRecordLocked(tx, clientID) if err != nil { @@ -70,10 +80,6 @@ func writeClientBindingOptsTx(tx *bbolt.Tx, clientID, pin, mode string, clearPri } found = true } - b, err := getOAuthBindingTx(tx, clientID) - if err != nil { - return err - } if b != nil { b.ProfilePin, b.ProfileMode, b.UpdatedAt = pin, mode, time.Now().UTC() if err := oauthPutJSON(tx, OAuthClientBindingsBucket, clientID, b); err != nil { diff --git a/internal/storage/client_binding_hardening_test.go b/internal/storage/client_binding_hardening_test.go index 48d8524e0..4c3d726c6 100644 --- a/internal/storage/client_binding_hardening_test.go +++ b/internal/storage/client_binding_hardening_test.go @@ -32,7 +32,9 @@ func TestWriteClientBindingTx_ValidatesBeforeAnyWrite(t *testing.T) { commitNew(t, m, "r", "g1", "webonly", "ro", auth.ProfileModeLocked, time.Now()) clientWithBoth(t, m, "both", auth.ProfileModeLocked, "ro") - for _, id := range []string{"keyonly", "webonly", "both"} { + // (An API-key-only client is deliberately NOT validated: it is written as + // before Spec 132, see TestAPIKeyOnlyClientsAreNotValidated.) + for _, id := range []string{"webonly", "both"} { for _, bad := range []struct{ pin, mode string }{ {"x", "sticky"}, {"", auth.ProfileModeLocked}, {"x", ""}, } { @@ -89,8 +91,9 @@ func TestUpdateClientCredentialBinding_ErrorTextUnchangedForAPIKeyOnly(t *testin require.EqualError(t, err, "a locked client credential requires a non-empty profile") _, _, err = m.UpdateClientCredentialBinding("cursor", "ro", "sticky") require.EqualError(t, err, `invalid profile mode "sticky"`) - // The writer's own wording is never doubled. - err = m.db.db.Update(func(tx *bbolt.Tx) error { return writeClientBindingTx(tx, "cursor", "x", "sticky") }) + // The writer's own wording is never doubled (OAuth-side validation). + commitNew(t, m, "r", "g1", "webonly", "ro", auth.ProfileModeLocked, time.Now()) + err = m.db.db.Update(func(tx *bbolt.Tx) error { return writeClientBindingTx(tx, "webonly", "x", "sticky") }) require.EqualError(t, err, `invalid profile mode "sticky"`) } diff --git a/internal/storage/client_binding_legacy_test.go b/internal/storage/client_binding_legacy_test.go new file mode 100644 index 000000000..dcaf12c7e --- /dev/null +++ b/internal/storage/client_binding_legacy_test.go @@ -0,0 +1,101 @@ +package storage + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.etcd.io/bbolt" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// rawEditClient rewrites the client's stored API-key record without any validation. +func rawEditClient(t *testing.T, m *Manager, id string, edit func(*auth.AgentToken)) { + t.Helper() + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + hash, tok, err := findClientTokenRecordLocked(tx, id) + require.NoError(t, err) + require.NotNil(t, tok) + edit(tok) + return putTokenForTest(tx, hash, tok) + })) +} + +var badPriors = []struct{ name, pin, mode string }{ + {"invalid mode", "p", "sticky"}, + {"locked with an empty pin", "", auth.ProfileModeLocked}, +} + +// TestAPIKeyOnlyClientsAreNotValidated: a client with no browser login behaves +// exactly as before Spec 132, even when its stored binding is malformed, so one +// bad legacy record cannot block a profile rename or a connect rollback. +func TestAPIKeyOnlyClientsAreNotValidated(t *testing.T) { + t.Run("repin over an invalid mode", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + mintTestClient(t, m, "cursor", auth.ProfileModeLocked, "p") + rawEditClient(t, m, "cursor", func(tk *auth.AgentToken) { tk.ProfileMode = "sticky" }) + + before, err := m.RepinProfile("p", "q") + require.NoError(t, err) + require.Len(t, before, 1, "only the client record, no restore entries") + assert.Equal(t, "p", before[0].ProfilePin) + assert.Equal(t, "sticky", before[0].ProfileMode) + pin, mode, _, _, _, _ := bindings(t, m, "cursor") + assert.Equal(t, "q", pin) + assert.Equal(t, "sticky", mode, "the mode is left as it was") + require.NoError(t, m.RestorePins(before)) + pin, _, _, _, _, _ = bindings(t, m, "cursor") + assert.Equal(t, "p", pin) + }) + + for _, prior := range badPriors { + t.Run("connect rollback with a prior that is "+prior.name, func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + mintTestClient(t, m, "cursor", auth.ProfileModeSwitchable, "") + rawEditClient(t, m, "cursor", func(tk *auth.AgentToken) { + tk.PriorProfilePin, tk.PriorProfileMode = prior.pin, prior.mode + }) + rec, err := m.ForgetClientCredentialRestoringPrior("cursor") + require.NoError(t, err) + assert.True(t, rec.Revoked) + assert.Equal(t, prior.pin, rec.ProfilePin) + assert.Equal(t, prior.mode, rec.ProfileMode) + pin, mode, _, _, _, _ := bindings(t, m, "cursor") + assert.Equal(t, prior.pin, pin) + assert.Equal(t, prior.mode, mode) + }) + } +} + +// TestDualClientsWithInvalidBindingsFailClosed: with a browser-login copy the +// same malformed values are refused and nothing is written. +func TestDualClientsWithInvalidBindingsFailClosed(t *testing.T) { + t.Run("repin", func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + clientWithBoth(t, m, "cursor", auth.ProfileModeLocked, "p") + rawEditClient(t, m, "cursor", func(tk *auth.AgentToken) { tk.ProfileMode = "sticky" }) + before := dumpDB(t, m) + _, err := m.RepinProfile("p", "q") + require.Error(t, err) + assert.Equal(t, before, dumpDB(t, m)) + }) + + for _, prior := range badPriors { + t.Run("rollback with a prior that is "+prior.name, func(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + clientWithBoth(t, m, "cursor", auth.ProfileModeSwitchable, "") + rawEditClient(t, m, "cursor", func(tk *auth.AgentToken) { + tk.PriorProfilePin, tk.PriorProfileMode = prior.pin, prior.mode + }) + before := dumpDB(t, m) + _, err := m.ForgetClientCredentialRestoringPrior("cursor") + require.Error(t, err) + assert.Equal(t, before, dumpDB(t, m)) + }) + } +} From 5716d19a085f45f3b9532cf01cdc1de577c46041 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 19:36:05 +0200 Subject: [PATCH 10/42] fix(oauth): restore pins by binding incarnation, keep connect snapshots (Spec 132 PR-1c) Related #1971 --- internal/storage/agent_token_repin.go | 220 ++++++++++------- internal/storage/client_binding.go | 14 +- .../storage/client_binding_hardening_test.go | 13 +- .../storage/client_binding_restore_test.go | 224 ++++++++++++++++++ .../storage/client_binding_source_test.go | 2 +- internal/storage/oauth_login.go | 6 +- 6 files changed, 387 insertions(+), 92 deletions(-) create mode 100644 internal/storage/client_binding_restore_test.go diff --git a/internal/storage/agent_token_repin.go b/internal/storage/agent_token_repin.go index 4b361115c..9744c0c42 100644 --- a/internal/storage/agent_token_repin.go +++ b/internal/storage/agent_token_repin.go @@ -16,16 +16,16 @@ import ( // whatever its TokenHash is. const repinRestoreMarker = "spec132-repin-binding-restore" -// repinRestoreEntry builds the restore entry of one client RepinProfile moved -// and whose binding lives (also) in an oauth_client_bindings entry. It carries -// the OLD binding in ProfilePin/ProfileMode and what repin WROTE in -// PriorProfilePin/PriorProfileMode, so RestorePins can compare-and-set. -func repinRestoreEntry(clientID, oldPin, oldMode, wrotePin, wroteMode string) auth.AgentToken { +// repinRestoreEntry is the restore entry of one client whose binding also lives +// in an oauth_client_bindings entry. It carries the client id, the OLD pin and +// mode (ProfilePin/ProfileMode) and, in MatchedPrefix (never persisted), the +// WriteID that repin's own write produced on that entry: RestorePins restores +// only while the entry still has exactly that incarnation. +func repinRestoreEntry(clientID, oldPin, oldMode, writeID string) auth.AgentToken { return auth.AgentToken{ Name: auth.ClientTokenName(clientID), Kind: auth.KindClient, ClientID: clientID, ProfilePin: oldPin, ProfileMode: oldMode, - PriorProfilePin: wrotePin, PriorProfileMode: wroteMode, - MatchedGeneration: repinRestoreMarker, + MatchedGeneration: repinRestoreMarker, MatchedPrefix: writeID, } } @@ -48,9 +48,13 @@ func isRepinRestoreEntry(t *auth.AgentToken) bool { // Spec 132: a client's pin is written through writeClientBindingTx, so its // browser-login binding entry moves with its API-key record, and an entry of a // client that has NO API-key record moves too. For every client that has an -// entry, `before` ends with a restore entry (see repinRestoreEntry) that -// RestorePins applies compare-and-set. Existing records come first, in bbolt -// key order, exactly as before. +// entry, `before` ends with a restore entry (see repinRestoreEntry). Existing +// records come first, in bbolt key order, exactly as before. +// +// A repin never touches PriorProfilePin/PriorProfileMode: that snapshot is the +// binding the client had before its connect, and undoing the connect returns the +// client to exactly that, whatever profile renames happened since — the same as +// for an API-key tombstone before Spec 132. func (m *Manager) RepinProfile(from, to string) (before []auth.AgentToken, err error) { return m.repinProfile(from, to, nil) } @@ -129,6 +133,14 @@ func (m *Manager) repinProfile(from, to string, hook func(written int) error) ([ i++ return nil } + // captureWriteID reads the incarnation repin's own write just produced. + captureWriteID := func(id string) (string, bool, error) { + e, err := getOAuthBindingTx(tx, id) + if err != nil || e == nil { + return "", false, err + } + return e.WriteID, true, nil + } var restores []auth.AgentToken for _, w := range work { if err := step(); err != nil { @@ -142,20 +154,17 @@ func (m *Manager) repinProfile(from, to string, hook func(written int) error) ([ continue } // A client record: through the binding writer so its OAuth entry - // moves too. When it has an entry, the mint-time rollback snapshot - // is stale after this move and is cleared in the same write, so a - // later connect rollback cannot put a pre-reassignment binding back - // on the existing browser logins. - entry, err := getOAuthBindingTx(tx, w.old.ClientID) - if err != nil { - return err - } - if err := writeClientBindingOptsTx(tx, w.old.ClientID, to, w.old.ProfileMode, entry != nil); err != nil { + // (if any) moves too. + if err := writeClientBindingTx(tx, w.old.ClientID, to, w.old.ProfileMode); err != nil { return fmt.Errorf("failed to repin agent token: %w", err) } before = append(before, w.old) - if entry != nil { - restores = append(restores, repinRestoreEntry(w.old.ClientID, w.old.ProfilePin, w.old.ProfileMode, to, w.old.ProfileMode)) + wid, has, err := captureWriteID(w.old.ClientID) + if err != nil { + return err + } + if has { + restores = append(restores, repinRestoreEntry(w.old.ClientID, w.old.ProfilePin, w.old.ProfileMode, wid)) } } for j, id := range oauthOnlyIDs { @@ -165,7 +174,11 @@ func (m *Manager) repinProfile(from, to string, hook func(written int) error) ([ if err := writeClientBindingTx(tx, id, to, oauthOnly[j].ProfileMode); err != nil { return fmt.Errorf("failed to repin agent token: %w", err) } - restores = append(restores, repinRestoreEntry(id, oauthOnly[j].ProfilePin, oauthOnly[j].ProfileMode, to, oauthOnly[j].ProfileMode)) + wid, _, err := captureWriteID(id) + if err != nil { + return err + } + restores = append(restores, repinRestoreEntry(id, oauthOnly[j].ProfilePin, oauthOnly[j].ProfileMode, wid)) } before = append(before, restores...) return nil @@ -176,17 +189,54 @@ func (m *Manager) repinProfile(from, to string, hook func(written int) error) ([ return before, nil } +// restoreRecordPinTx puts back the stored pin of one record by hash, exactly as +// before Spec 132 (the mode is never changed by a repin). A record that no +// longer exists, or is owned, is left alone. +func restoreRecordPinTx(tx *bbolt.Tx, rec *auth.AgentToken) error { + tokenBucket := tx.Bucket([]byte(AgentTokensBucket)) + if tokenBucket == nil { + return nil + } + key := []byte(rec.TokenHash) + v := tokenBucket.Get(key) + if v == nil { + return nil + } + var t auth.AgentToken + if json.Unmarshal(v, &t) != nil || t.UserID != "" { + return nil + } + t.ProfilePin = rec.ProfilePin + data, err := json.Marshal(t) + if err != nil { + return err + } + if err := tokenBucket.Put(key, data); err != nil { + return fmt.Errorf("failed to restore agent token pin: %w", err) + } + return nil +} + // RestorePins puts back the ProfilePin of each record RepinProfile returned, // in one transaction (the rollback of a repin whose config write failed). A -// record that no longer exists is left alone. +// record that no longer exists is left alone. Regular tokens are restored by +// hash. // -// Stored records are restored by hash, as before. The restore entries for -// browser-login bindings are compare-and-set: the entry is restored only if it -// still holds exactly what repin wrote (and a current API-key record of that -// client holds that or the old binding); an entry that is gone is not -// re-created, and one that changed since (re-created client, new mint, an -// administrator's reassignment) is left alone. They do not depend on the -// original API-key record still existing. +// For a CLIENT, ONE decision is made before either copy is touched, from the +// client's oauth_client_bindings entry as it is now: +// +// - no entry: restore the API-key record by hash, unconditionally, as before +// Spec 132; an entry is never created; +// - entry and a restore entry in `before`: restore the old pin and mode on +// both copies (through the binding writer, so it also works when the +// API-key record is gone) only if the entry's WriteID is still the one +// repin's own write produced; anything that wrote the binding since +// (reassignment, new mint, forget and re-create, even with the same pin and +// mode) restores neither copy, nor the record by hash; +// - entry but no restore entry (the client got its first browser login after +// the repin): restore both copies only if the record from `before` still +// exists and the entry equals that record's CURRENT pin and mode; else +// leave both alone. func (m *Manager) RestorePins(before []auth.AgentToken) error { if len(before) == 0 { return nil @@ -194,65 +244,73 @@ func (m *Manager) RestorePins(before []auth.AgentToken) error { m.mu.Lock() defer m.mu.Unlock() return m.db.db.Update(func(tx *bbolt.Tx) error { - for i := range before { - if isRepinRestoreEntry(&before[i]) { - continue // second pass, after the records - } - tokenBucket := tx.Bucket([]byte(AgentTokensBucket)) - if tokenBucket == nil { - continue + restoreEntries := map[string]*auth.AgentToken{} + clientRecords := map[string]*auth.AgentToken{} + var clientOrder []string + seen := map[string]bool{} + note := func(id string) { + if !seen[id] { + seen[id] = true + clientOrder = append(clientOrder, id) } - key := []byte(before[i].TokenHash) - v := tokenBucket.Get(key) - if v == nil { - continue - } - var t auth.AgentToken - if json.Unmarshal(v, &t) != nil || t.UserID != "" { - continue + } + for i := range before { + b := &before[i] + switch { + case isRepinRestoreEntry(b): + restoreEntries[b.ClientID] = b + note(b.ClientID) + case b.Kind == auth.KindClient && b.ClientID != "" && b.TokenHash != "": + clientRecords[b.ClientID] = b + note(b.ClientID) + default: + if b.TokenHash == "" { + continue + } + if err := restoreRecordPinTx(tx, b); err != nil { + return err + } } - t.ProfilePin = before[i].ProfilePin - data, err := json.Marshal(t) + } + for _, id := range clientOrder { + entry, err := getOAuthBindingTx(tx, id) if err != nil { return err } - if err := tokenBucket.Put(key, data); err != nil { - return fmt.Errorf("failed to restore agent token pin: %w", err) - } - } - for i := range before { - if isRepinRestoreEntry(&before[i]) { - if err := restoreRepinnedClientTx(tx, &before[i]); err != nil { - return err + rec, e := clientRecords[id], restoreEntries[id] + switch { + case entry == nil: + if rec != nil { + if err := restoreRecordPinTx(tx, rec); err != nil { + return err + } + } + case e != nil: + if entry.WriteID != "" && entry.WriteID == e.MatchedPrefix { + if err := writeClientBindingTx(tx, id, e.ProfilePin, e.ProfileMode); err != nil { + return err + } + } + default: // entry, no restore entry; rec is non-nil here + cur := tx.Bucket([]byte(AgentTokensBucket)) + if cur == nil { + continue + } + v := cur.Get([]byte(rec.TokenHash)) + if v == nil { + continue + } + var t auth.AgentToken + if json.Unmarshal(v, &t) != nil || t.UserID != "" { + continue + } + if t.ProfilePin == entry.ProfilePin && t.ProfileMode == entry.ProfileMode { + if err := writeClientBindingTx(tx, id, rec.ProfilePin, rec.ProfileMode); err != nil { + return err + } } } } return nil }) } - -// restoreRepinnedClientTx is the compare-and-set restore of one client's -// browser-login binding (see RestorePins). -func restoreRepinnedClientTx(tx *bbolt.Tx, p *auth.AgentToken) error { - oldPin, oldMode := p.ProfilePin, p.ProfileMode - wrotePin, wroteMode := p.PriorProfilePin, p.PriorProfileMode - entry, err := getOAuthBindingTx(tx, p.ClientID) - if err != nil { - return err - } - if entry == nil || entry.ProfilePin != wrotePin || entry.ProfileMode != wroteMode { - return nil // gone (not re-created) or changed since: leave it alone - } - _, tok, err := findClientTokenRecordLocked(tx, p.ClientID) - if err != nil { - return err - } - if tok != nil && tok.Kind == auth.KindClient { - wrote := tok.ProfilePin == wrotePin && tok.ProfileMode == wroteMode - old := tok.ProfilePin == oldPin && tok.ProfileMode == oldMode // already restored by hash - if !wrote && !old { - return nil // the API-key record moved on its own - } - } - return writeClientBindingTx(tx, p.ClientID, oldPin, oldMode) -} diff --git a/internal/storage/client_binding.go b/internal/storage/client_binding.go index ed4e2a075..654f31225 100644 --- a/internal/storage/client_binding.go +++ b/internal/storage/client_binding.go @@ -1,6 +1,7 @@ package storage import ( + "crypto/rand" "crypto/sha256" "encoding/hex" "encoding/json" @@ -23,6 +24,17 @@ func bindingRevision(clientID, pin, mode string) string { return hex.EncodeToString(sum[:8]) } +// putOAuthBindingTx is the only writer of an oauth_client_bindings entry: it +// stamps a fresh WriteID on every write. +func putOAuthBindingTx(tx *bbolt.Tx, clientID string, b *OAuthClientBinding) error { + var raw [8]byte + if _, err := rand.Read(raw[:]); err != nil { + return fmt.Errorf("failed to generate binding write id: %w", err) + } + b.WriteID = hex.EncodeToString(raw[:]) + return oauthPutJSON(tx, OAuthClientBindingsBucket, clientID, b) +} + // validateClientBinding: mode is locked or switchable, and locked needs a pin. func validateClientBinding(pin, mode string) error { if mode != auth.ProfileModeLocked && mode != auth.ProfileModeSwitchable { @@ -82,7 +94,7 @@ func writeClientBindingOptsTx(tx *bbolt.Tx, clientID, pin, mode string, clearPri } if b != nil { b.ProfilePin, b.ProfileMode, b.UpdatedAt = pin, mode, time.Now().UTC() - if err := oauthPutJSON(tx, OAuthClientBindingsBucket, clientID, b); err != nil { + if err := putOAuthBindingTx(tx, clientID, b); err != nil { return err } found = true diff --git a/internal/storage/client_binding_hardening_test.go b/internal/storage/client_binding_hardening_test.go index 4c3d726c6..9105955fc 100644 --- a/internal/storage/client_binding_hardening_test.go +++ b/internal/storage/client_binding_hardening_test.go @@ -146,10 +146,10 @@ func TestRepinProfile_KeepsKeyOrderForRecordsAndHooks(t *testing.T) { assert.Equal(t, seq, hooked) } -// TestRepinProfile_ClearsStaleRollbackSnapshotOfClientWithLogins: after a connect -// mint over an OAuth-only client and a reassignment, rolling the connect back must -// not bring the pre-reassignment binding back onto the existing logins. -func TestRepinProfile_ClearsStaleRollbackSnapshotOfClientWithLogins(t *testing.T) { +// TestRepinProfile_LeavesConnectSnapshotAlone documents the semantics: undoing a +// connect returns the client to its PRE-CONNECT binding, whatever profile rename +// happened in between, exactly as for an API-key tombstone. Grants are untouched. +func TestRepinProfile_LeavesConnectSnapshotAlone(t *testing.T) { m, cleanup := setupTestStorageForAgentTokens(t) defer cleanup() commitNew(t, m, "r", "g1", "webonly", "", auth.ProfileModeSwitchable, time.Now()) @@ -160,10 +160,7 @@ func TestRepinProfile_ClearsStaleRollbackSnapshotOfClientWithLogins(t *testing.T _, err = m.ForgetClientCredentialRestoringPrior("webonly") require.NoError(t, err) - _, _, _, oPin, oMode, oOK := bindings(t, m, "webonly") - require.True(t, oOK) - assert.Equal(t, "restricted", oPin) - assert.Equal(t, auth.ProfileModeLocked, oMode) + assertEqualBindings(t, m, "webonly", "", auth.ProfileModeSwitchable) g, err := m.GetOAuthGrant("g1") require.NoError(t, err) assert.False(t, g.Revoked) diff --git a/internal/storage/client_binding_restore_test.go b/internal/storage/client_binding_restore_test.go new file mode 100644 index 000000000..f41f85f31 --- /dev/null +++ b/internal/storage/client_binding_restore_test.go @@ -0,0 +1,224 @@ +package storage + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.etcd.io/bbolt" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// assertCopiesAgree: after any RestorePins, every client that has both an +// API-key record and an OAuth entry holds the same pin and mode in both. +func assertCopiesAgree(t *testing.T, m *Manager) { + t.Helper() + entries, err := m.ListOAuthClientBindings() + require.NoError(t, err) + for id, e := range entries { + apiPin, apiMode, apiOK, _, _, _ := bindings(t, m, id) + if apiOK { + assert.Equal(t, apiPin, e.ProfilePin, "%s pin copies differ", id) + assert.Equal(t, apiMode, e.ProfileMode, "%s mode copies differ", id) + } + } +} + +func restoreAndCheck(t *testing.T, m *Manager, before []auth.AgentToken) { + t.Helper() + require.NoError(t, m.RestorePins(before)) + assertCopiesAgree(t, m) +} + +// firstLogin gives an existing API-key client its first browser login. +func firstLogin(t *testing.T, m *Manager, clientID string) { + t.Helper() + now := time.Now().UTC() + require.NoError(t, m.CreateOAuthRegistration(newTestReg("reg-"+clientID, now))) + rev, err := m.ClientBindingRevision(clientID) + require.NoError(t, err) + _, err = m.CommitOAuthLogin(CommitLoginInput{ + Grant: newTestGrant("grant-"+clientID, "reg-"+clientID, clientID, now), Client: clientID, + ExpectedBindingRevision: rev, Now: now, + }) + require.NoError(t, err) +} + +func TestRestorePins_DecisionTable(t *testing.T) { + locked := auth.ProfileModeLocked + newMgr := func(t *testing.T) *Manager { + m, cleanup := setupTestStorageForAgentTokens(t) + t.Cleanup(cleanup) + return m + } + + t.Run("a: an administrator reassigned in between", func(t *testing.T) { + m := newMgr(t) + clientWithBoth(t, m, "cursor", locked, "A") + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + _, _, err = m.UpdateClientCredentialBinding("cursor", "C", locked) + require.NoError(t, err) + restoreAndCheck(t, m, before) + assertEqualBindings(t, m, "cursor", "C", locked) + }) + + t.Run("b: forgotten and re-created with the same value", func(t *testing.T) { + m := newMgr(t) + commitNew(t, m, "r", "g1", "webonly", "A", locked, time.Now()) + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + _, err = m.ForgetClient("webonly") + require.NoError(t, err) + commitNew(t, m, "r2", "g2", "webonly", "B", locked, time.Now()) + restoreAndCheck(t, m, before) + _, _, _, oPin, _, oOK := bindings(t, m, "webonly") + require.True(t, oOK) + assert.Equal(t, "B", oPin, "a different incarnation is never restored") + }) + + t.Run("c: a connect minted an API key bound to the same value", func(t *testing.T) { + m := newMgr(t) + commitNew(t, m, "r", "g1", "webonly", "A", locked, time.Now()) + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + mintTestClient(t, m, "webonly", locked, "B") + restoreAndCheck(t, m, before) + assertEqualBindings(t, m, "webonly", "B", locked) + }) + + t.Run("d: the client got its first login after the repin", func(t *testing.T) { + m := newMgr(t) + mintTestClient(t, m, "cursor", locked, "A") + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + require.Len(t, before, 1, "no restore entry: it had no entry at repin time") + firstLogin(t, m, "cursor") + assertEqualBindings(t, m, "cursor", "B", locked) + restoreAndCheck(t, m, before) + assertEqualBindings(t, m, "cursor", "A", locked) + }) + + t.Run("d2: first login, entry differs from the record: left alone", func(t *testing.T) { + m := newMgr(t) + mintTestClient(t, m, "cursor", locked, "A") + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + firstLogin(t, m, "cursor") + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + return putOAuthBindingTx(tx, "cursor", &OAuthClientBinding{ProfilePin: "Z", ProfileMode: locked}) + })) + require.NoError(t, m.RestorePins(before)) + apiPin, _, _, oPin, _, _ := bindings(t, m, "cursor") + assert.Equal(t, "B", apiPin) + assert.Equal(t, "Z", oPin) + }) + + t.Run("e: plain rollback of a dual client", func(t *testing.T) { + m := newMgr(t) + clientWithBoth(t, m, "cursor", locked, "A") + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + assertEqualBindings(t, m, "cursor", "B", locked) + restoreAndCheck(t, m, before) + assertEqualBindings(t, m, "cursor", "A", locked) + }) + + t.Run("f: dual client, API-key record removed", func(t *testing.T) { + m := newMgr(t) + clientWithBoth(t, m, "cursor", locked, "A") + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + require.NoError(t, m.DeleteAgentToken("client-cursor")) + restoreAndCheck(t, m, before) + _, _, apiOK, oPin, _, oOK := bindings(t, m, "cursor") + assert.False(t, apiOK) + require.True(t, oOK) + assert.Equal(t, "A", oPin) + }) + + t.Run("f2: an entry that is gone is not re-created", func(t *testing.T) { + m := newMgr(t) + commitNew(t, m, "r", "g1", "webonly", "A", locked, time.Now()) + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + _, err = m.ForgetClient("webonly") + require.NoError(t, err) + restoreAndCheck(t, m, before) + _, _, _, _, _, oOK := bindings(t, m, "webonly") + assert.False(t, oOK) + }) + + t.Run("g: a same-value repin and restore changes nothing", func(t *testing.T) { + m := newMgr(t) + commitNew(t, m, "r", "g1", "webonly", "", auth.ProfileModeSwitchable, time.Now()) + mintTestClient(t, m, "webonly", locked, "P") // snapshot: unpinned, switchable + before, err := m.RepinProfile("P", "P") + require.NoError(t, err) + restoreAndCheck(t, m, before) + assertEqualBindings(t, m, "webonly", "P", locked) + tok, err := m.GetAgentTokenByName("client-webonly") + require.NoError(t, err) + assert.Equal(t, "", tok.PriorProfilePin) + assert.Equal(t, auth.ProfileModeSwitchable, tok.PriorProfileMode, "the connect snapshot is untouched") + }) + + t.Run("h: an API-key-only install is as before", func(t *testing.T) { + m := newMgr(t) + mintTestClient(t, m, "cursor", locked, "A") + tok, raw := makeTestToken("agent-one") + tok.ProfilePin = "A" + require.NoError(t, m.CreateAgentToken(tok, raw, testHMACKey)) + + before, err := m.RepinProfile("A", "B") + require.NoError(t, err) + require.Len(t, before, 2, "the two records only: no restore entries") + for i := range before { + assert.False(t, isRepinRestoreEntry(&before[i])) + assert.Equal(t, "A", before[i].ProfilePin) + } + // Unconditional, as before: even a record that moved on is put back. + _, _, err = m.UpdateClientCredentialBinding("cursor", "C", locked) + require.NoError(t, err) + restoreAndCheck(t, m, before) + pin, _, _, _, _, oOK := bindings(t, m, "cursor") + assert.Equal(t, "A", pin) + assert.False(t, oOK, "no entry is ever created") + assert.Empty(t, oauthBucketNames(t, m)) + got, err := m.GetAgentTokenByName("agent-one") + require.NoError(t, err) + assert.Equal(t, "A", got.ProfilePin) + }) +} + +// TestBindingWriteIDChangesOnEveryWrite: a deleted-and-recreated entry never has +// the old id, even with the same pin and mode; ClientBindingRevision ignores it. +func TestBindingWriteIDChangesOnEveryWrite(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "A", auth.ProfileModeLocked, time.Now()) + id := func() string { + b, err := m.GetOAuthClientBinding("webonly") + require.NoError(t, err) + require.NotNil(t, b) + require.Len(t, b.WriteID, 16) + return b.WriteID + } + first := id() + rev, _ := m.ClientBindingRevision("webonly") + + require.NoError(t, m.db.db.Update(func(tx *bbolt.Tx) error { + return writeClientBindingTx(tx, "webonly", "A", auth.ProfileModeLocked) // same value + })) + second := id() + assert.NotEqual(t, first, second) + rev2, _ := m.ClientBindingRevision("webonly") + assert.Equal(t, rev, rev2) + + _, err := m.ForgetClient("webonly") + require.NoError(t, err) + commitNew(t, m, "r2", "g2", "webonly", "A", auth.ProfileModeLocked, time.Now()) + assert.NotEqual(t, second, id()) +} diff --git a/internal/storage/client_binding_source_test.go b/internal/storage/client_binding_source_test.go index 996aa8326..f0fa3c1a1 100644 --- a/internal/storage/client_binding_source_test.go +++ b/internal/storage/client_binding_source_test.go @@ -91,7 +91,7 @@ var allowedBindingWriteSites = map[string]int{ // Restores a stored record's pin by hash, exactly as before Spec 132 (the // mode is never changed by a repin; browser-login entries are restored // compare-and-set through writeClientBindingTx). - "RestorePins|assign:t.ProfilePin": 1, + "restoreRecordPinTx|assign:t.ProfilePin": 1, // The only creator of oauth_client_bindings entries (a client's first login). "CommitOAuthLogin|assign:nb.ProfilePin": 2, // new-client branch and existing-client branch diff --git a/internal/storage/oauth_login.go b/internal/storage/oauth_login.go index f515a409d..ba001f97b 100644 --- a/internal/storage/oauth_login.go +++ b/internal/storage/oauth_login.go @@ -138,6 +138,10 @@ type OAuthClientBinding struct { ProfileMode string `json:"profile_mode"` DisplayName string `json:"display_name,omitempty"` UpdatedAt time.Time `json:"updated_at"` + // WriteID is the entry's incarnation: a fresh random id on EVERY write, so a + // deleted-and-recreated entry never carries an old id even with identical + // pin and mode. Storage-internal; it is not part of ClientBindingRevision. + WriteID string `json:"write_id,omitempty"` } // Refresh rotation outcomes. @@ -630,7 +634,7 @@ func (m *Manager) CommitOAuthLogin(in CommitLoginInput) (OAuthGrant, error) { nb.DisplayName = anyRecord.DisplayName } } - if err := oauthPutJSON(tx, OAuthClientBindingsBucket, in.Client, &nb); err != nil { + if err := putOAuthBindingTx(tx, in.Client, &nb); err != nil { return err } } From f51b746846a21db4b20afce5c6b148f0a81e55be Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 20:32:34 +0200 Subject: [PATCH 11/42] feat(oauth): browser-login service, client views and guard (Spec 132 PR-1d) Related #1971 --- cmd/generate-types/main.go | 8 +- frontend/src/types/contracts.ts | 8 +- internal/auth/agent_token.go | 91 +- internal/auth/client_auth_context_test.go | 80 ++ internal/auth/context.go | 21 +- internal/auth/credential_kind_sites_test.go | 100 +++ .../httpapi/oauth_login_event_scope_test.go | 30 + internal/httpapi/sse_scope.go | 4 + internal/httpapi/sse_scope_reveal_test.go | 2 + internal/mcplogin/peek.go | 22 + internal/mcplogin/peek_test.go | 44 + internal/profile/contract.go | 7 + .../profile/contract_enums_golden_test.go | 3 +- internal/profile/testdata/contract/enums.json | 5 +- internal/runtime/activity_attribution.go | 7 + .../activity_attribution_grant_test.go | 33 + internal/runtime/binding_guard.go | 25 +- internal/runtime/binding_guard_oauth.go | 156 ++++ internal/runtime/binding_guard_oauth_test.go | 157 ++++ internal/runtime/binding_guard_wiring.go | 13 + internal/runtime/clients_service.go | 74 +- internal/runtime/clients_service_oauth.go | 450 ++++++++++ internal/runtime/clients_service_reconcile.go | 2 +- internal/runtime/clients_service_upgrade.go | 10 +- internal/runtime/commit.go | 10 + internal/runtime/config_funnel.go | 20 +- internal/runtime/credentials_service.go | 53 +- internal/runtime/credentials_service_oauth.go | 194 +++++ internal/runtime/events.go | 9 + internal/runtime/oauth_login_clients_test.go | 535 ++++++++++++ internal/runtime/oauth_login_consent.go | 822 ++++++++++++++++++ internal/runtime/oauth_login_exchange_test.go | 649 ++++++++++++++ .../runtime/oauth_login_failclosed_test.go | 77 ++ internal/runtime/oauth_login_fixture_test.go | 230 +++++ internal/runtime/oauth_login_service.go | 468 ++++++++++ internal/runtime/oauth_login_service_test.go | 456 ++++++++++ internal/runtime/oauth_login_tokens.go | 357 ++++++++ internal/runtime/profiles_service.go | 11 + internal/runtime/profiles_service_oauth.go | 47 + internal/runtime/runtime.go | 23 + internal/server/mcp.go | 3 + internal/server/mcp_activity_attribution.go | 6 + .../server/oauth_login_attribution_test.go | 42 + internal/server/profile_binding_guard.go | 31 +- .../profile_binding_guard_oauth_test.go | 86 ++ internal/server/session_store.go | 4 + internal/server/session_store_grant.go | 15 + internal/storage/client_binding_update.go | 46 + .../storage/client_binding_update_test.go | 49 ++ 49 files changed, 5547 insertions(+), 48 deletions(-) create mode 100644 internal/auth/client_auth_context_test.go create mode 100644 internal/auth/credential_kind_sites_test.go create mode 100644 internal/httpapi/oauth_login_event_scope_test.go create mode 100644 internal/mcplogin/peek.go create mode 100644 internal/mcplogin/peek_test.go create mode 100644 internal/runtime/activity_attribution_grant_test.go create mode 100644 internal/runtime/binding_guard_oauth.go create mode 100644 internal/runtime/binding_guard_oauth_test.go create mode 100644 internal/runtime/clients_service_oauth.go create mode 100644 internal/runtime/credentials_service_oauth.go create mode 100644 internal/runtime/oauth_login_clients_test.go create mode 100644 internal/runtime/oauth_login_consent.go create mode 100644 internal/runtime/oauth_login_exchange_test.go create mode 100644 internal/runtime/oauth_login_failclosed_test.go create mode 100644 internal/runtime/oauth_login_fixture_test.go create mode 100644 internal/runtime/oauth_login_service.go create mode 100644 internal/runtime/oauth_login_service_test.go create mode 100644 internal/runtime/oauth_login_tokens.go create mode 100644 internal/runtime/profiles_service_oauth.go create mode 100644 internal/server/oauth_login_attribution_test.go create mode 100644 internal/server/profile_binding_guard_oauth_test.go create mode 100644 internal/server/session_store_grant.go create mode 100644 internal/storage/client_binding_update.go create mode 100644 internal/storage/client_binding_update_test.go diff --git a/cmd/generate-types/main.go b/cmd/generate-types/main.go index a1083fd19..d9c8f363f 100644 --- a/cmd/generate-types/main.go +++ b/cmd/generate-types/main.go @@ -923,6 +923,9 @@ export const ProfileChangeRotate = 'rotate' as const; export const ProfileChangeAnonymous = 'anonymous' as const; export const ProfileChangeIssue = 'issue' as const; export const ProfileChangeRevoke = 'revoke' as const; +export const ProfileChangeApprove = 'approve' as const; +export const ProfileChangeDeny = 'deny' as const; +export const ProfileChangeReplayRevoke = 'replay_revoke' as const; export type ProfileChangeKind = | typeof ProfileChangeCreate | typeof ProfileChangeUpdate @@ -936,7 +939,10 @@ export type ProfileChangeKind = | typeof ProfileChangeRotate | typeof ProfileChangeAnonymous | typeof ProfileChangeIssue - | typeof ProfileChangeRevoke; + | typeof ProfileChangeRevoke + | typeof ProfileChangeApprove + | typeof ProfileChangeDeny + | typeof ProfileChangeReplayRevoke; export const RotationFinalized = 'finalized' as const; export const RotationRolledBack = 'rolled_back' as const; diff --git a/frontend/src/types/contracts.ts b/frontend/src/types/contracts.ts index 3e6a44f99..aed26e6f9 100644 --- a/frontend/src/types/contracts.ts +++ b/frontend/src/types/contracts.ts @@ -868,6 +868,9 @@ export const ProfileChangeRotate = 'rotate' as const; export const ProfileChangeAnonymous = 'anonymous' as const; export const ProfileChangeIssue = 'issue' as const; export const ProfileChangeRevoke = 'revoke' as const; +export const ProfileChangeApprove = 'approve' as const; +export const ProfileChangeDeny = 'deny' as const; +export const ProfileChangeReplayRevoke = 'replay_revoke' as const; export type ProfileChangeKind = | typeof ProfileChangeCreate | typeof ProfileChangeUpdate @@ -881,7 +884,10 @@ export type ProfileChangeKind = | typeof ProfileChangeRotate | typeof ProfileChangeAnonymous | typeof ProfileChangeIssue - | typeof ProfileChangeRevoke; + | typeof ProfileChangeRevoke + | typeof ProfileChangeApprove + | typeof ProfileChangeDeny + | typeof ProfileChangeReplayRevoke; export const RotationFinalized = 'finalized' as const; export const RotationRolledBack = 'rolled_back' as const; diff --git a/internal/auth/agent_token.go b/internal/auth/agent_token.go index fd8614d44..a09820ec3 100644 --- a/internal/auth/agent_token.go +++ b/internal/auth/agent_token.go @@ -340,29 +340,96 @@ func (t *AgentToken) AuthContext() *AuthContext { if t == nil { return nil } - return &AuthContext{ - Type: AuthTypeAgent, + return ClientAuthContext(ClientIdentity{ AgentName: t.Name, + TokenKind: normalizeKind(t.Kind), + ClientID: t.ClientID, + ProfilePin: t.ProfilePin, + ProfileMode: t.ProfileMode, + CredentialKind: CredentialKindAgentToken, TokenPrefix: t.authenticatedPrefix(), TokenGeneration: t.MatchedGeneration, AllowedServers: t.AllowedServers, Permissions: t.Permissions, - ProfilePin: t.ProfilePin, - Email: t.OwnerEmail, - Provider: t.OwnerProvider, - Role: t.OwnerRole, - CredentialKind: CredentialKindAgentToken, - TokenKind: normalizeKind(t.Kind), - ClientID: t.ClientID, - ProfileMode: t.ProfileMode, - RateLimit: t.RateLimit.clone(), + RateLimit: t.RateLimit, // UserID carries the owning tenant (server edition). Without it an // agent-token request had no tenant identity at all, so its activity // could not be attributed or scoped. It does NOT confer the user tier: // Type stays AuthTypeAgent, so IsUser()/IsAdmin() remain false, and // every per-user surface must gate on IsUser() rather than on a // non-empty UserID. - UserID: t.UserID, + UserID: t.UserID, + Email: t.OwnerEmail, + Provider: t.OwnerProvider, + Role: t.OwnerRole, + }) +} + +// ClientIdentity is everything the one AuthContext builder needs. Both the +// stored-token path ((*AgentToken).AuthContext) and a browser login (Spec 132) +// fill it, so no path can silently drop a field. +type ClientIdentity struct { + // AgentName is the context's AgentName. Empty means ClientTokenName(ClientID) + // (what a client credential's record is named, so activity and filters match). + AgentName string + // TokenKind is KindAgent or KindClient. Empty means KindClient. + TokenKind string + // ClientID, ProfilePin and ProfileMode are the client binding. + ClientID, ProfilePin, ProfileMode string + // CredentialKind is the source credential (agent_token or oauth). + CredentialKind CredentialKind + // GrantID is the browser-login grant id (oauth only). + GrantID string + // TokenPrefix is the display prefix; TokenGeneration identifies the + // authenticated secret (a browser login uses its grant id). + TokenPrefix, TokenGeneration string + // AllowedServers and Permissions are the token's own scope. For a browser + // login (CredentialKindOAuth) nil means "*" and all three tiers: its + // reach comes from the client's profile binding only. + AllowedServers, Permissions []string + // RateLimit is the credential's own call budget (copied, never aliased). + RateLimit *TokenRateLimit + // UserID, Email, Provider and Role are the owning tenant (server edition). + UserID, Email, Provider, Role string +} + +// ClientAuthContext is the single builder of the agent-tier AuthContext. +func ClientAuthContext(id ClientIdentity) *AuthContext { + kind := id.TokenKind + if kind == "" { + kind = KindClient + } + name := id.AgentName + if name == "" && id.ClientID != "" { + name = ClientTokenName(id.ClientID) + } + servers, perms := id.AllowedServers, id.Permissions + if id.CredentialKind == CredentialKindOAuth { + if servers == nil { + servers = []string{"*"} + } + if perms == nil { + perms = []string{PermRead, PermWrite, PermDestructive} + } + } + return &AuthContext{ + Type: AuthTypeAgent, + AgentName: name, + TokenPrefix: id.TokenPrefix, + TokenGeneration: id.TokenGeneration, + AllowedServers: servers, + Permissions: perms, + ProfilePin: id.ProfilePin, + Email: id.Email, + Provider: id.Provider, + Role: id.Role, + CredentialKind: id.CredentialKind, + GrantID: id.GrantID, + TokenKind: kind, + ClientID: id.ClientID, + ProfileMode: id.ProfileMode, + RateLimit: id.RateLimit.clone(), + UserID: id.UserID, } } diff --git a/internal/auth/client_auth_context_test.go b/internal/auth/client_auth_context_test.go new file mode 100644 index 000000000..ec8e24b39 --- /dev/null +++ b/internal/auth/client_auth_context_test.go @@ -0,0 +1,80 @@ +package auth + +import ( + "reflect" + "testing" + "time" +) + +// TestAgentTokenAuthContext_PinnedStructs pins EVERY field of the context a +// client credential and a regular agent token produce, so moving +// (*AgentToken).AuthContext onto ClientAuthContext (Spec 132 R3) cannot change +// what the mcp_cli_ and mcp_agt_ paths have always produced. +func TestAgentTokenAuthContext_PinnedStructs(t *testing.T) { + rl := &TokenRateLimit{PerMinute: 30, Burst: 5} + client := &AgentToken{ + Name: ClientTokenName("cursor"), TokenPrefix: "mcp_cli_old1", MatchedPrefix: "mcp_cli_new2", + MatchedGeneration: "gen-abc", AllowedServers: []string{"*"}, + Permissions: []string{PermRead, PermWrite, PermDestructive}, + Kind: KindClient, ClientID: "cursor", ProfilePin: "dev", ProfileMode: ProfileModeLocked, + RateLimit: rl, ExpiresAt: time.Now().Add(time.Hour), + } + want := &AuthContext{ + Type: AuthTypeAgent, AgentName: "client-cursor", TokenPrefix: "mcp_cli_new2", TokenGeneration: "gen-abc", + AllowedServers: []string{"*"}, Permissions: []string{PermRead, PermWrite, PermDestructive}, + ProfilePin: "dev", TokenKind: KindClient, ClientID: "cursor", ProfileMode: ProfileModeLocked, + RateLimit: &TokenRateLimit{PerMinute: 30, Burst: 5}, CredentialKind: CredentialKindAgentToken, + } + if got := client.AuthContext(); !reflect.DeepEqual(got, want) { + t.Fatalf("client credential context drifted:\n got %+v\nwant %+v", got, want) + } + + regular := &AgentToken{ + Name: "ci", TokenPrefix: "mcp_agt_abcd", AllowedServers: []string{"srv"}, Permissions: []string{PermRead}, + ProfilePin: "p", UserID: "u1", OwnerEmail: "a@b.c", OwnerProvider: "github", OwnerRole: "user", + } + wantReg := &AuthContext{ + Type: AuthTypeAgent, AgentName: "ci", TokenPrefix: "mcp_agt_abcd", AllowedServers: []string{"srv"}, + Permissions: []string{PermRead}, ProfilePin: "p", Email: "a@b.c", Provider: "github", Role: "user", + UserID: "u1", TokenKind: KindAgent, CredentialKind: CredentialKindAgentToken, + } + if got := regular.AuthContext(); !reflect.DeepEqual(got, wantReg) { + t.Fatalf("agent token context drifted:\n got %+v\nwant %+v", got, wantReg) + } + if got := client.AuthContext(); got.RateLimit == rl { + t.Fatal("the context must not alias the record's rate limit") + } +} + +// TestClientAuthContext_BrowserLogin: a browser login is the same caller a +// client credential is, apart from kind, grant id, prefix and generation. +func TestClientAuthContext_BrowserLogin(t *testing.T) { + ac := ClientAuthContext(ClientIdentity{ + ClientID: "cursor", ProfilePin: "dev", ProfileMode: ProfileModeSwitchable, + CredentialKind: CredentialKindOAuth, GrantID: "G1", TokenPrefix: "mcp_oat_abcd", TokenGeneration: "G1", + }) + want := &AuthContext{ + Type: AuthTypeAgent, AgentName: "client-cursor", TokenPrefix: "mcp_oat_abcd", TokenGeneration: "G1", + AllowedServers: []string{"*"}, Permissions: []string{PermRead, PermWrite, PermDestructive}, + ProfilePin: "dev", TokenKind: KindClient, ClientID: "cursor", ProfileMode: ProfileModeSwitchable, + CredentialKind: CredentialKindOAuth, GrantID: "G1", + } + if !reflect.DeepEqual(ac, want) { + t.Fatalf("browser-login context:\n got %+v\nwant %+v", ac, want) + } + if !ac.IsClientCredential() || ac.IsAdmin() || ac.IsUser() { + t.Fatal("a browser login is a client credential and nothing more") + } +} + +func TestCredentialKind_IsScopedClientCredential(t *testing.T) { + for k, want := range map[CredentialKind]bool{ + CredentialKindAgentToken: true, CredentialKindOAuth: true, CredentialKindAPIKey: false, + CredentialKindSocket: false, CredentialKindCookie: false, CredentialKindBearerJWT: false, + CredentialKindAnonymous: false, "": false, + } { + if got := k.IsScopedClientCredential(); got != want { + t.Errorf("%q.IsScopedClientCredential() = %v, want %v", k, got, want) + } + } +} diff --git a/internal/auth/context.go b/internal/auth/context.go index 63ee01bb5..86dfbdcd5 100644 --- a/internal/auth/context.go +++ b/internal/auth/context.go @@ -26,10 +26,21 @@ const ( CredentialKindAPIKey CredentialKind = "api_key" // the global API key (header, bearer or ?apikey=) CredentialKindBearerJWT CredentialKind = "bearer_jwt" // a user JWT minted by POST /auth/token CredentialKindAgentToken CredentialKind = "agent_token" // an mcp_agt_ agent token + CredentialKindOAuth CredentialKind = "oauth" // an mcp_oat_ browser-login access token (Spec 132) CredentialKindCookie CredentialKind = "cookie" // the mcpproxy_session cookie CredentialKindAnonymous CredentialKind = "anonymous" // no credential (require_mcp_auth: false back-compat) ) +// IsScopedClientCredential reports whether the kind is a credential scoped by +// an agent-token style binding: an mcp_agt_/mcp_cli_ token or a browser-login +// access token. Every "scoped caller, not an administrator" decision that +// would compare against CredentialKindAgentToken goes through it, so a browser +// login is treated exactly like the same client's mcp_cli_ credential (Spec 132 +// R3). +func (k CredentialKind) IsScopedClientCredential() bool { + return k == CredentialKindAgentToken || k == CredentialKindOAuth +} + // AuthContext carries authentication identity through request context. type AuthContext struct { Type string // "admin", "agent", "user", or "admin_user" @@ -39,9 +50,13 @@ type AuthContext struct { // its hash). Internal: it keys a work session on the credential's // generation (Spec 124 FR-009) and is never returned or logged. TokenGeneration string - AllowedServers []string // Servers this token can access (nil = all for admin) - Permissions []string // Permission tiers (nil = all for admin) - ProfilePin string // Profile this agent token is pinned to (Profiles v2 T3; empty if unpinned) + // GrantID is the browser-login grant that authenticated this request + // (Spec 132; empty for every other credential). Activity rows carry it so + // two logins of one client can be told apart. + GrantID string + AllowedServers []string // Servers this token can access (nil = all for admin) + Permissions []string // Permission tiers (nil = all for admin) + ProfilePin string // Profile this agent token is pinned to (Profiles v2 T3; empty if unpinned) // TokenKind, ClientID and ProfileMode are the Spec 108-c client- // credential identity, copied from AgentToken at authentication diff --git a/internal/auth/credential_kind_sites_test.go b/internal/auth/credential_kind_sites_test.go new file mode 100644 index 000000000..699003f1d --- /dev/null +++ b/internal/auth/credential_kind_sites_test.go @@ -0,0 +1,100 @@ +package auth + +import ( + "go/ast" + "go/parser" + "go/token" + "io/fs" + "path/filepath" + "sort" + "strings" + "testing" +) + +// credentialKindAgentTokenSites classifies every use of CredentialKindAgentToken +// in non-test Go code under internal/ and cmd/ (Spec 132 R3, T025). A browser +// login carries CredentialKindOAuth, so any code that asked "is this the agent +// token kind?" to mean "scoped caller" would silently treat a login as +// something else. Each site is therefore either: +// +// - also_oauth: the decision must also hold for CredentialKindOAuth. The code +// goes through CredentialKind.IsScopedClientCredential (or an equivalent +// that includes oauth) instead of comparing with the constant. +// - api_key_only: the site is specific to a stored mcp_agt_/mcp_cli_ token. +// +// Key: "#". +var credentialKindAgentTokenSites = map[string]struct{ class, reason string }{ + "internal/auth/context.go#IsScopedClientCredential": {"also_oauth", + "the helper every scoped-caller decision goes through; it matches agent_token AND oauth"}, + "internal/auth/agent_token.go#AuthContext": {"api_key_only", + "builds the context of a STORED token; a browser login is built by ClientAuthContext with CredentialKindOAuth"}, + "internal/runtime/clients_service.go#ActorFromContext": {"api_key_only", + "fallback label for a REST context that never stamped a credential kind; the browser-login context always stamps oauth, so this branch is unreachable for it"}, +} + +func TestCredentialKindAgentTokenSitesClassified(t *testing.T) { + root, err := filepath.Abs("../..") + if err != nil { + t.Fatal(err) + } + found := map[string]bool{} + fset := token.NewFileSet() + for _, top := range []string{"internal", "cmd"} { + _ = filepath.WalkDir(filepath.Join(root, top), func(path string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { + return nil + } + file, perr := parser.ParseFile(fset, path, nil, 0) + if perr != nil { + t.Errorf("parse %s: %v", path, perr) + return nil + } + rel, _ := filepath.Rel(root, path) + rel = filepath.ToSlash(rel) + for _, decl := range file.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + ast.Inspect(fn.Body, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.SelectorExpr: + if x.Sel.Name == "CredentialKindAgentToken" { + found[rel+"#"+fn.Name.Name] = true + } + case *ast.Ident: + if x.Name == "CredentialKindAgentToken" { + found[rel+"#"+fn.Name.Name] = true + } + } + return true + }) + } + return nil + }) + } + + var keys []string + for k := range found { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + entry, ok := credentialKindAgentTokenSites[k] + if !ok { + t.Errorf("unclassified use of CredentialKindAgentToken at %s: classify it in credentialKindAgentTokenSites as also_oauth or api_key_only", k) + continue + } + if entry.class != "also_oauth" && entry.class != "api_key_only" { + t.Errorf("%s: class %q must be also_oauth or api_key_only", k, entry.class) + } + if strings.TrimSpace(entry.reason) == "" { + t.Errorf("%s: a classification needs a one-line reason", k) + } + } + for k := range credentialKindAgentTokenSites { + if !found[k] { + t.Errorf("stale entry %s: the site no longer uses CredentialKindAgentToken", k) + } + } +} diff --git a/internal/httpapi/oauth_login_event_scope_test.go b/internal/httpapi/oauth_login_event_scope_test.go new file mode 100644 index 000000000..4f0f162b3 --- /dev/null +++ b/internal/httpapi/oauth_login_event_scope_test.go @@ -0,0 +1,30 @@ +package httpapi + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + internalRuntime "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" +) + +// Spec 132: a sign-in request names a client and the label it reported, and +// its decision tells which request was approved. Only an administrator sees +// either; a scoped caller never does. +func TestSSE_OAuthLoginEventsAreAdminOnly(t *testing.T) { + scoped := auth.WithAuthContext(context.Background(), &auth.AuthContext{ + Type: auth.AuthTypeAgent, AgentName: "bot", AllowedServers: []string{"alpha"}, Permissions: []string{auth.PermRead}, + }) + admin := auth.WithAuthContext(context.Background(), &auth.AuthContext{Type: auth.AuthTypeAdmin}) + for _, evt := range []internalRuntime.Event{ + {Type: internalRuntime.EventTypeOAuthAuthorizationPending, + Payload: map[string]any{"request_id": "r1", "client_id": "cursor", "client_label": "Cursor IDE"}}, + {Type: internalRuntime.EventTypeOAuthAuthorizationDecided, + Payload: map[string]any{"request_id": "r1", "status": "approved"}}, + } { + require.False(t, eventVisibleToCaller(scoped, evt), "%s must be dropped for a scoped caller", evt.Type) + require.True(t, eventVisibleToCaller(admin, evt), "%s reaches an administrator", evt.Type) + } +} diff --git a/internal/httpapi/sse_scope.go b/internal/httpapi/sse_scope.go index 1ae1d9cf6..581b45e3e 100644 --- a/internal/httpapi/sse_scope.go +++ b/internal/httpapi/sse_scope.go @@ -178,6 +178,10 @@ var adminConfigEventTypes = map[internalRuntime.EventType]struct{}{ // A credential lifecycle invalidation names identities and their // profiles (Spec 115 FR-024): administrator-only, like the binding event. internalRuntime.EventTypeCredentialsChanged: {}, + // A browser sign-in request names a client and the label it reported + // (Spec 132): administrator-only, like the credential invalidation. + internalRuntime.EventTypeOAuthAuthorizationPending: {}, + internalRuntime.EventTypeOAuthAuthorizationDecided: {}, // A skills catalog change carries per-state counts of every skill of a // server, available or not (Spec 125 FR-019a): until agents are offered // skills it is an administrator-only invalidation. diff --git a/internal/httpapi/sse_scope_reveal_test.go b/internal/httpapi/sse_scope_reveal_test.go index 734310fa5..2eed30c5b 100644 --- a/internal/httpapi/sse_scope_reveal_test.go +++ b/internal/httpapi/sse_scope_reveal_test.go @@ -598,6 +598,8 @@ func TestSSE_EveryRuntimeEventTypeIsClassified(t *testing.T) { "client.binding_changed": "administrator-only client -> profile binding change (Spec 108 FR-026); dropped for scoped callers", "profiles.changed": "administrator-only profile change invalidation (Spec 108-f FR-038): names profiles a scoped caller may not reach; dropped for scoped callers", "credentials.changed": "administrator-only credential lifecycle invalidation (Spec 115 FR-024): names identities and profiles; dropped for scoped callers", + "oauth.authorization_pending": "administrator-only browser-login request (Spec 132): names a client and its sanitised label; dropped for scoped callers", + "oauth.authorization_decided": "administrator-only browser-login decision (Spec 132): request id and status; dropped for scoped callers", "skills.changed": "administrator-only skills catalog invalidation (Spec 125 FR-019a): carries per-state skill counts; dropped for scoped callers", "activity.skill_quarantine_change": "administrator-only skill approval row (Spec 125 FR-019a): names skills that may be unapproved, even on a visible server; dropped for scoped callers", "activity.skill_access": "administrator-only skill access row (Spec 125 FR-019a): names the id its caller asked for, which may be a held skill on a visible server; dropped for scoped callers", diff --git a/internal/mcplogin/peek.go b/internal/mcplogin/peek.go new file mode 100644 index 000000000..cfe171842 --- /dev/null +++ b/internal/mcplogin/peek.go @@ -0,0 +1,22 @@ +package mcplogin + +// PeekCode returns a copy of the request an unconsumed, unexpired code belongs +// to, while that request is still approved. It consumes nothing and changes +// nothing: the token endpoint uses it to compare the request's origin with the +// stored issuer BEFORE the code's single use is spent (a mismatch must leave +// the code usable). ok is false for an unknown, expired, consumed or cancelled +// code, with nothing to tell the cases apart. +func (s *Store) PeekCode(code string) (Request, bool) { + h := HashSecret(s.key, KindCode, code) + s.mu.Lock() + defer s.mu.Unlock() + e := s.codes[h] + if e == nil || e.consumed || !s.now().Before(e.expiresAt) { + return Request{}, false + } + r := s.live(e.requestID) + if r == nil || r.Status != StatusApproved { + return Request{}, false + } + return *r, true +} diff --git a/internal/mcplogin/peek_test.go b/internal/mcplogin/peek_test.go new file mode 100644 index 000000000..9099fd6d2 --- /dev/null +++ b/internal/mcplogin/peek_test.go @@ -0,0 +1,44 @@ +package mcplogin + +import "testing" + +// PeekCode lets the token endpoint compare the request's origin with the +// stored issuer BEFORE the single-use code is consumed (Spec 132): a mismatch +// must leave the code usable. +func TestPeekCode(t *testing.T) { + s, clk := newTestStore() + r := mustCreate(t, s, "cursor") + code, err := s.Approve(r.ID, Decision{ClientID: "cursor"}) + if err != nil { + t.Fatal(err) + } + + got, ok := s.PeekCode(code) + if !ok || got.ID != r.ID || got.Issuer != r.Issuer || got.Status != StatusApproved { + t.Fatalf("peek of a live code: %+v ok=%v", got, ok) + } + if _, ok := s.PeekCode("nope"); ok { + t.Fatal("an unknown code must not peek") + } + // Peeking consumes nothing. + if _, _, err := s.Consume(code, func(Request) (string, error) { return "g1", nil }); err != nil { + t.Fatalf("consume after peek: %v", err) + } + if _, ok := s.PeekCode(code); ok { + t.Fatal("a consumed code must not peek") + } + + r2 := mustCreate(t, s, "") + code2, _ := s.Approve(r2.ID, Decision{ClientID: "c"}) + clk.advance(CodeLifetime) + if _, ok := s.PeekCode(code2); ok { + t.Fatal("an expired code must not peek") + } + + r3 := mustCreate(t, s, "") + code3, _ := s.Approve(r3.ID, Decision{ClientID: "c"}) + s.CancelAll() + if _, ok := s.PeekCode(code3); ok { + t.Fatal("a cancelled request's code must not peek") + } +} diff --git a/internal/profile/contract.go b/internal/profile/contract.go index 0788c810c..d3434e04d 100644 --- a/internal/profile/contract.go +++ b/internal/profile/contract.go @@ -216,6 +216,13 @@ const ( // page's Forget action. ChangeIssue ChangeKind = "issue" ChangeRevoke ChangeKind = "revoke" + // ChangeApprove, ChangeDeny and ChangeReplayRevoke are the Spec 132 browser + // login records: an administrator approved or denied a sign-in request + // (before any login exists), and an authentic refresh token that was + // already spent came back, so its login was revoked (reason replay). + ChangeApprove ChangeKind = "approve" + ChangeDeny ChangeKind = "deny" + ChangeReplayRevoke ChangeKind = "replay_revoke" ) // Credential error codes of the `credentials` admin MCP tool (Spec 115, diff --git a/internal/profile/contract_enums_golden_test.go b/internal/profile/contract_enums_golden_test.go index 195743285..c5d1a398d 100644 --- a/internal/profile/contract_enums_golden_test.go +++ b/internal/profile/contract_enums_golden_test.go @@ -57,7 +57,8 @@ func enumFamilies() map[string][]string { "explain_verdict": strs(ExplainVerdictAllowed, ExplainVerdictBlocked, ExplainVerdictHidden), "change_kind": strs(ChangeCreate, ChangeUpdate, ChangeDelete, ChangeRename, ChangeClassify, ChangeAssign, ChangeLock, ChangeUnlock, ChangeForget, - ChangeRotate, ChangeAnonymous, ChangeIssue, ChangeRevoke), + ChangeRotate, ChangeAnonymous, ChangeIssue, ChangeRevoke, ChangeApprove, + ChangeDeny, ChangeReplayRevoke), "rotation_state": {RotationFinalized, RotationRolledBack, RotationPending}, "surface": strs(SurfaceWeb, SurfaceMacOS, SurfaceCLI, SurfaceMCP, SurfaceAPI), "warning_code": strs(WarningAnonymousDeniedByBindingGuard, WarningClientHoldsAdminKey, diff --git a/internal/profile/testdata/contract/enums.json b/internal/profile/testdata/contract/enums.json index f68e2f0bf..8a74d9772 100644 --- a/internal/profile/testdata/contract/enums.json +++ b/internal/profile/testdata/contract/enums.json @@ -37,7 +37,10 @@ "rotate", "anonymous", "issue", - "revoke" + "revoke", + "approve", + "deny", + "replay_revoke" ], "credential_error_code": [ "secret_in_argument", diff --git a/internal/runtime/activity_attribution.go b/internal/runtime/activity_attribution.go index 0dc946e06..0409c9364 100644 --- a/internal/runtime/activity_attribution.go +++ b/internal/runtime/activity_attribution.go @@ -35,6 +35,10 @@ type ActivityAttribution struct { // scoped caller recognises its own policy_decision and prompt_get rows), // never in any API shape, export or SSE frame for another caller. TokenPrefix string + // GrantID is the browser-login grant that authenticated the request (Spec + // 132): it lands as metadata.grant_id so two logins of one client can be + // told apart. Not a secret. + GrantID string // WorkSessionID is the work session of the request (Spec 124 D1). It is // resolved at the emit site because only the request knows the credential, @@ -85,6 +89,7 @@ func (a ActivityAttribution) payload() map[string]any { set("client_version", a.ClientVersion) set("token_name", a.TokenName) set("_token_prefix", a.TokenPrefix) + set("grant_id", a.GrantID) set("_work_session_id", a.WorkSessionID) set("_user_id", a.UserID) set("run_name", a.RunName) @@ -114,6 +119,7 @@ func attributionFromPayload(payload map[string]any) ActivityAttribution { ClientVersion: getStringPayload(m, "client_version"), TokenName: getStringPayload(m, "token_name"), TokenPrefix: getStringPayload(m, "_token_prefix"), + GrantID: getStringPayload(m, "grant_id"), WorkSessionID: getStringPayload(m, "_work_session_id"), UserID: getStringPayload(m, "_user_id"), RunName: getStringPayload(m, "run_name"), @@ -175,6 +181,7 @@ func applyAttribution(rec *storage.ActivityRecord, a ActivityAttribution) { } setMetadataIfAbsent("client_name", a.ClientName) setMetadataIfAbsent("client_version", a.ClientVersion) + setMetadataIfAbsent("grant_id", a.GrantID) } // NewUsageAggregate returns an empty aggregate at the current admission diff --git a/internal/runtime/activity_attribution_grant_test.go b/internal/runtime/activity_attribution_grant_test.go new file mode 100644 index 000000000..5f0765588 --- /dev/null +++ b/internal/runtime/activity_attribution_grant_test.go @@ -0,0 +1,33 @@ +package runtime + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" +) + +// A browser login's grant id rides on the attribution and lands as +// metadata.grant_id on the record (Spec 132 R3): two logins of one client can +// be told apart in the log. The grant id is not a secret. +func TestActivityAttribution_GrantIDRoundTripsToMetadata(t *testing.T) { + a := testAttribution() + a.GrantID = "grantAAAAAAAAAAAAAAAAAA" + assert.Equal(t, "grantAAAAAAAAAAAAAAAAAA", attributionFromPayload(map[string]any{attributionPayloadKey: a.payload()}).GrantID) + assert.NotContains(t, ActivityAttribution{Profile: "p"}.payload(), "grant_id", "no grant, no key") + + store, cleanup := setupTestStorage(t) + defer cleanup() + svc := NewActivityService(store, zap.NewNop()) + svc.handleEvent(Event{ + Type: EventTypeActivityToolCallCompleted, Timestamp: time.Now().UTC(), + Payload: map[string]any{ + "server_name": "github", "tool_name": "list_issues", "session_id": "s1", "request_id": "r1", + "source": "mcp", "status": "success", "duration_ms": int64(5), "attribution": a.payload(), + }, + }) + rec := onlyRecord(t, store) + require.Equal(t, "grantAAAAAAAAAAAAAAAAAA", rec.Metadata["grant_id"]) +} diff --git a/internal/runtime/binding_guard.go b/internal/runtime/binding_guard.go index 319335c2f..2c0cc8fe8 100644 --- a/internal/runtime/binding_guard.go +++ b/internal/runtime/binding_guard.go @@ -44,6 +44,11 @@ type GuardFix struct { type GuardState struct { Config *config.Config Tokens []auth.AgentToken + // OAuthBindings are the browser-login binding entries (Spec 132 R5), each + // with its liveness. Every producer of a current or candidate state fills + // it from storage; a storage read error refuses the change. The evaluators + // read the combined view through EffectiveTokens. + OAuthBindings []OAuthBinding } // BindingGuard evaluates FR-008a. Implementations must be safe for concurrent @@ -155,15 +160,17 @@ func BindingRefOf(t *auth.AgentToken) BindingRef { func (ConservativeBindingGuard) BindingGuardDelta(current, candidate GuardState) []BindingRef { now := time.Now() already := make(map[string]bool) - for i := range current.Tokens { - t := ¤t.Tokens[i] + currentTokens := current.EffectiveTokens(now) + for i := range currentTokens { + t := ¤tTokens[i] if conservativeBypassable(current, t, now) { already[t.Name] = true } } var out []BindingRef - for i := range candidate.Tokens { - t := &candidate.Tokens[i] + candidateTokens := candidate.EffectiveTokens(now) + for i := range candidateTokens { + t := &candidateTokens[i] if conservativeBypassable(candidate, t, now) && !already[t.Name] { out = append(out, BindingRefOf(t)) } @@ -197,15 +204,17 @@ type bindingIdentity struct{ name, pin, mode string } func (StrictOfflineBindingGuard) BindingGuardDelta(current, candidate GuardState) []BindingRef { now := time.Now() already := make(map[bindingIdentity]bool) - for i := range current.Tokens { - t := ¤t.Tokens[i] + currentTokens := current.EffectiveTokens(now) + for i := range currentTokens { + t := ¤tTokens[i] if conservativeBypassable(current, t, now) { already[bindingIdentity{t.Name, t.ProfilePin, t.ProfileMode}] = true } } var out []BindingRef - for i := range candidate.Tokens { - t := &candidate.Tokens[i] + candidateTokens := candidate.EffectiveTokens(now) + for i := range candidateTokens { + t := &candidateTokens[i] if conservativeBypassable(candidate, t, now) && !already[bindingIdentity{t.Name, t.ProfilePin, t.ProfileMode}] { out = append(out, BindingRefOf(t)) } diff --git a/internal/runtime/binding_guard_oauth.go b/internal/runtime/binding_guard_oauth.go new file mode 100644 index 000000000..fd0aea3cd --- /dev/null +++ b/internal/runtime/binding_guard_oauth.go @@ -0,0 +1,156 @@ +package runtime + +import ( + "fmt" + "sort" + "time" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// Spec 132 R5: a client that holds browser logins but no API key has no token +// record, so the binding guard (which reads auth.AgentToken only) would not see +// its binding. GuardState therefore carries the OAuth-side bindings next to the +// token records, and every guard treats a live named one as an active binding. + +// OAuthBinding is one browser-login binding entry as the guard sees it. Live is +// true while the client has at least one grant that is not revoked and whose +// refresh token has not expired. +type OAuthBinding struct { + ClientID string `json:"client_id"` + Pin string `json:"pin"` + Mode string `json:"mode"` + Live bool `json:"live"` +} + +// OAuthBindingSource is the browser-login storage surface the guard producers +// read; *storage.Manager implements it. A store that does not (a test fake, an +// older store) contributes no OAuth bindings. +type OAuthBindingSource interface { + ListOAuthClientBindings() (map[string]storage.OAuthClientBinding, error) + ListOAuthGrants() ([]storage.OAuthGrant, error) +} + +// LoadOAuthBindings reads every browser-login binding with its liveness, sorted +// by client id. src is any value; one that does not implement +// OAuthBindingSource yields nil. A read error is returned and the caller MUST +// refuse the change (fail closed): it must never be read as "no bindings". +// On a database that never used browser login this is two read transactions +// over absent buckets and no write. +func LoadOAuthBindings(src any, now time.Time) ([]OAuthBinding, error) { + s, ok := src.(OAuthBindingSource) + if !ok || s == nil { + return nil, nil + } + bindings, err := s.ListOAuthClientBindings() + if err != nil { + return nil, fmt.Errorf("cannot read browser-login bindings: %w", err) + } + if len(bindings) == 0 { + return nil, nil + } + grants, err := s.ListOAuthGrants() + if err != nil { + return nil, fmt.Errorf("cannot read browser-login grants: %w", err) + } + live := map[string]bool{} + for i := range grants { + g := &grants[i] + if !g.Revoked && g.RefreshExpiresAt.After(now) { + live[g.Client] = true + } + } + out := make([]OAuthBinding, 0, len(bindings)) + for id, b := range bindings { + out = append(out, OAuthBinding{ClientID: id, Pin: b.ProfilePin, Mode: b.ProfileMode, Live: live[id]}) + } + sort.Slice(out, func(i, j int) bool { return out[i].ClientID < out[j].ClientID }) + return out, nil +} + +// ActiveOAuthBinding reports whether b counts as an active named binding: a +// live entry with a named pin and a binding mode. +func ActiveOAuthBinding(b OAuthBinding) bool { + return b.Live && b.Pin != "" && + (b.Mode == auth.ProfileModeLocked || b.Mode == auth.ProfileModeSwitchable) +} + +// EffectiveTokens returns the guarded records the evaluators walk: Tokens, plus +// one synthetic client record for every live named OAuth binding whose client +// has no ACTIVE guarded token (a client with both credentials counts once, as +// its API-key record). The binding of a client that has an API-key record, in +// any state, is that record's: it is the truth for the request path +// (storage.CurrentClientBinding), so a stale entry never decides. With no OAuth +// bindings the result is Tokens itself, unchanged. +func (s GuardState) EffectiveTokens(now time.Time) []auth.AgentToken { + if len(s.OAuthBindings) == 0 { + return s.Tokens + } + byName := make(map[string]*auth.AgentToken, len(s.Tokens)) + for i := range s.Tokens { + byName[s.Tokens[i].Name] = &s.Tokens[i] + } + var extra []auth.AgentToken + for _, b := range s.OAuthBindings { + if !b.Live { + continue + } + name := auth.ClientTokenName(b.ClientID) + pin, mode := b.Pin, b.Mode + if rec := byName[name]; rec != nil && rec.Kind == auth.KindClient { + if ActiveGuardedBinding(rec, now) { + continue // counted once, as the API-key record + } + pin, mode = rec.ProfilePin, rec.ProfileMode + } + if !ActiveOAuthBinding(OAuthBinding{ClientID: b.ClientID, Pin: pin, Mode: mode, Live: true}) { + continue + } + extra = append(extra, auth.AgentToken{ + Name: name, Kind: auth.KindClient, ClientID: b.ClientID, + ProfilePin: pin, ProfileMode: mode, ExpiresAt: now.AddDate(100, 0, 0), + }) + } + if len(extra) == 0 { + return s.Tokens + } + out := make([]auth.AgentToken, 0, len(s.Tokens)+len(extra)) + out = append(out, s.Tokens...) + return append(out, extra...) +} + +// withOAuthClient returns bindings with client's entry added or replaced by e +// (a first approval's candidate entry, Live: true). +func withOAuthClient(bindings []OAuthBinding, e OAuthBinding) []OAuthBinding { + out := make([]OAuthBinding, 0, len(bindings)+1) + replaced := false + for _, b := range bindings { + if b.ClientID == e.ClientID { + out = append(out, e) + replaced = true + continue + } + out = append(out, b) + } + if !replaced { + out = append(out, e) + } + return out +} + +// repinOAuthBindings returns bindings with every pin naming from moved to to +// (a profile rename or reassign rewrites both copies). +func repinOAuthBindings(bindings []OAuthBinding, from, to string) []OAuthBinding { + if len(bindings) == 0 { + return bindings + } + out := make([]OAuthBinding, len(bindings)) + copy(out, bindings) + for i := range out { + if out[i].Pin == from { + out[i].Pin = to + } + } + return out +} diff --git a/internal/runtime/binding_guard_oauth_test.go b/internal/runtime/binding_guard_oauth_test.go new file mode 100644 index 000000000..55b6f64cc --- /dev/null +++ b/internal/runtime/binding_guard_oauth_test.go @@ -0,0 +1,157 @@ +package runtime + +import ( + "errors" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +func oauthB(client, pin, mode string, live bool) OAuthBinding { + return OAuthBinding{ClientID: client, Pin: pin, Mode: mode, Live: live} +} + +func authOff() *config.Config { return &config.Config{} } + +// With no OAuth bindings the effective token list IS the token list. +func TestGuardState_EffectiveTokensWithoutOAuthIsIdentical(t *testing.T) { + toks := []auth.AgentToken{strictTok("cursor", "ro", auth.ProfileModeLocked)} + st := GuardState{Config: authOff(), Tokens: toks} + got := st.EffectiveTokens(time.Now()) + require.Equal(t, toks, got) + if len(got) > 0 { + require.Same(t, &toks[0], &got[0], "no copy when there is nothing to add") + } +} + +func TestBindingGuard_OAuthOnlyClientIsAnActiveNamedBinding(t *testing.T) { + cur := GuardState{Config: authOff()} + live := GuardState{Config: authOff(), OAuthBindings: []OAuthBinding{oauthB("cursor", "ro", auth.ProfileModeLocked, true)}} + + for name, g := range map[string]BindingGuard{"conservative": ConservativeBindingGuard{}, "strict": StrictOfflineBindingGuard{}} { + t.Run(name, func(t *testing.T) { + // A first approval: the candidate adds the entry with Live: true. + delta := g.BindingGuardDelta(cur, live) + require.Len(t, delta, 1) + require.Equal(t, BindingRef{ClientID: "cursor", TokenName: "client-cursor", Profile: "ro", Mode: auth.ProfileModeLocked}, delta[0]) + + // Lapsed or revoked: not a binding. + lapsed := GuardState{Config: authOff(), OAuthBindings: []OAuthBinding{oauthB("cursor", "ro", auth.ProfileModeLocked, false)}} + require.Empty(t, g.BindingGuardDelta(cur, lapsed)) + // All servers (no pin) is not a named binding. + open := GuardState{Config: authOff(), OAuthBindings: []OAuthBinding{oauthB("cursor", "", auth.ProfileModeSwitchable, true)}} + require.Empty(t, g.BindingGuardDelta(cur, open)) + // require_mcp_auth on never refuses. + authOn := GuardState{Config: &config.Config{RequireMCPAuth: true}, OAuthBindings: live.OAuthBindings} + require.Empty(t, g.BindingGuardDelta(cur, authOn)) + // An unchanged live binding is not NEW. + require.Empty(t, g.BindingGuardDelta(live, live)) + }) + } +} + +// A client with both credentials counts once, and the API-key record decides +// the binding (it is the truth for the request path too). +func TestBindingGuard_ClientWithBothCredentialsCountsOnce(t *testing.T) { + g := ConservativeBindingGuard{} + api := strictTok("cursor", "ro", auth.ProfileModeLocked) + cur := GuardState{Config: authOff()} + both := GuardState{ + Config: authOff(), Tokens: []auth.AgentToken{api}, + OAuthBindings: []OAuthBinding{oauthB("cursor", "ro", auth.ProfileModeLocked, true)}, + } + delta := g.BindingGuardDelta(cur, both) + require.Len(t, delta, 1, "one client, one ref") + + // The record wins over a stale entry. + stale := GuardState{ + Config: authOff(), Tokens: []auth.AgentToken{api}, + OAuthBindings: []OAuthBinding{oauthB("cursor", "other", auth.ProfileModeSwitchable, true)}, + } + delta = g.BindingGuardDelta(cur, stale) + require.Len(t, delta, 1) + require.Equal(t, "ro", delta[0].Profile) + + // A revoked API record leaves the live login binding in force. + revoked := api + revoked.Revoked = true + login := GuardState{ + Config: authOff(), Tokens: []auth.AgentToken{revoked}, + OAuthBindings: []OAuthBinding{oauthB("cursor", "ro", auth.ProfileModeLocked, true)}, + } + require.Len(t, g.BindingGuardDelta(cur, login), 1) +} + +func TestBindingGuard_NoOAuthBindingsKeepsTodaysResult(t *testing.T) { + cur := GuardState{Config: authOff(), Tokens: []auth.AgentToken{strictTok("cursor", "ro", auth.ProfileModeLocked)}} + cand := GuardState{Config: authOff(), Tokens: []auth.AgentToken{strictTok("cursor", "ro", auth.ProfileModeLocked), strictTok("codex", "ro", auth.ProfileModeLocked)}} + for _, g := range []BindingGuard{ConservativeBindingGuard{}, StrictOfflineBindingGuard{}} { + require.Len(t, g.BindingGuardDelta(cur, cand), 1) + } +} + +type fakeOAuthSource struct { + bindings map[string]storage.OAuthClientBinding + grants []storage.OAuthGrant + err error +} + +func (f fakeOAuthSource) ListOAuthClientBindings() (map[string]storage.OAuthClientBinding, error) { + return f.bindings, f.err +} +func (f fakeOAuthSource) ListOAuthGrants() ([]storage.OAuthGrant, error) { return f.grants, f.err } + +func TestLoadOAuthBindings_LiveMeansAGrantNotRevokedAndNotLapsed(t *testing.T) { + now := time.Now() + src := fakeOAuthSource{ + bindings: map[string]storage.OAuthClientBinding{ + "live": {ProfilePin: "p", ProfileMode: auth.ProfileModeLocked}, + "dead": {ProfilePin: "p", ProfileMode: auth.ProfileModeLocked}, + "lap": {ProfilePin: "p", ProfileMode: auth.ProfileModeLocked}, + "none": {ProfilePin: "p", ProfileMode: auth.ProfileModeLocked}, + }, + grants: []storage.OAuthGrant{ + {GrantID: "g1", Client: "live", RefreshExpiresAt: now.Add(time.Hour)}, + {GrantID: "g2", Client: "dead", RefreshExpiresAt: now.Add(time.Hour), Revoked: true}, + {GrantID: "g3", Client: "lap", RefreshExpiresAt: now.Add(-time.Hour)}, + {GrantID: "g4", Client: "dead", RefreshExpiresAt: now.Add(time.Hour), Revoked: true}, + {GrantID: "g5", Client: "live", RefreshExpiresAt: now.Add(-time.Hour)}, + }, + } + got, err := LoadOAuthBindings(src, now) + require.NoError(t, err) + require.Equal(t, []OAuthBinding{ + {ClientID: "dead", Pin: "p", Mode: auth.ProfileModeLocked}, + {ClientID: "lap", Pin: "p", Mode: auth.ProfileModeLocked}, + {ClientID: "live", Pin: "p", Mode: auth.ProfileModeLocked, Live: true}, + {ClientID: "none", Pin: "p", Mode: auth.ProfileModeLocked}, + }, got) +} + +// A storage read error refuses the change instead of guessing (fail closed), +// and a store that has no browser-login storage contributes nothing. +func TestLoadOAuthBindings_ErrorIsReturnedAndNonStoreIsNil(t *testing.T) { + _, err := LoadOAuthBindings(fakeOAuthSource{err: errors.New("boom")}, time.Now()) + require.Error(t, err) + got, err := LoadOAuthBindings(struct{}{}, time.Now()) + require.NoError(t, err) + require.Nil(t, got) + got, err = LoadOAuthBindings(nil, time.Now()) + require.NoError(t, err) + require.Nil(t, got) +} + +// On a database that never used browser login the read is empty and writes +// nothing (no bucket is created by the read path). +func TestLoadOAuthBindings_NeverUsedDatabaseIsEmpty(t *testing.T) { + store, cleanup := setupTestStorage(t) + defer cleanup() + got, err := LoadOAuthBindings(store, time.Now()) + require.NoError(t, err) + require.Empty(t, got) +} diff --git a/internal/runtime/binding_guard_wiring.go b/internal/runtime/binding_guard_wiring.go index dbe1b0e8b..78b016768 100644 --- a/internal/runtime/binding_guard_wiring.go +++ b/internal/runtime/binding_guard_wiring.go @@ -1,6 +1,8 @@ package runtime import ( + "time" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" ) @@ -53,3 +55,14 @@ func (r *Runtime) guardedBindingSnapshot() ([]auth.AgentToken, error) { } return guardedOnly(all), nil } + +// oauthBindingSnapshot returns the browser-login bindings every FR-008a path +// evaluates next to the token records (Spec 132 R5). A read error is returned, +// never swallowed: the guard fails closed. +func (r *Runtime) oauthBindingSnapshot() ([]OAuthBinding, error) { + sm := r.StorageManager() + if sm == nil { + return nil, nil + } + return LoadOAuthBindings(sm, time.Now()) +} diff --git a/internal/runtime/clients_service.go b/internal/runtime/clients_service.go index a5b259b5c..d79039feb 100644 --- a/internal/runtime/clients_service.go +++ b/internal/runtime/clients_service.go @@ -43,6 +43,10 @@ type ClientsService struct { notifier BindingNotifier reader ClientConfigReader + // cancelLogins cancels a client's pending and approved browser sign-in + // requests (Spec 132). Called under mu after a revoke or forget. + cancelLogins func(clientID string) + // upgrade is the connect port behind the admin-key upgrade, observe the // sink for on-demand credential classifications (Spec 108-f). upgrade AdminKeyUpgradePort @@ -139,6 +143,10 @@ type ClientCredentialView struct { ExpiresAt *time.Time `json:"expires_at,omitempty"` ConnectedAt *time.Time `json:"connected_at,omitempty"` RotationPending bool `json:"rotation_pending,omitempty"` + // Credentials and BrowserLoginDisabled exist only once browser login was + // used (Spec 132); until then a view is exactly what it always was. + Credentials []ClientCredentialEntry `json:"credentials,omitempty"` + BrowserLoginDisabled *bool `json:"browser_login_disabled,omitempty"` } // ValidationError is a 400 {error, field} refusal. @@ -385,8 +393,18 @@ func guardedOnly(all []auth.AgentToken) []auth.AgentToken { func (s *ClientsService) checkGuard(all []auth.AgentToken, clientID string, next *auth.AgentToken) error { cfg := s.cfg() - current := GuardState{Config: cfg, Tokens: guardedOnly(all)} - candidate := GuardState{Config: cfg, Tokens: candidateTokens(all, clientID, next)} + // Spec 132 R5: the browser-login bindings are part of both states. A read + // error refuses the change (fail closed). + oauth, err := s.loadOAuthBindings() + if err != nil { + return err + } + candOAuth := oauth + if next != nil { + candOAuth = repinOAuthClient(oauth, clientID, next.ProfilePin, next.ProfileMode) + } + current := GuardState{Config: cfg, Tokens: guardedOnly(all), OAuthBindings: oauth} + candidate := GuardState{Config: cfg, Tokens: candidateTokens(all, clientID, next), OAuthBindings: candOAuth} return CheckBindingGuard(s.guard(), current, candidate) } @@ -421,6 +439,10 @@ type changeRecord struct { clientID string tokenName string diff map[string]interface{} + // meta is merged into the record's metadata after the fixed keys (it never + // replaces one): the Spec 132 rows carry request_id, grant_id, trigger and + // approved_by this way. + meta map[string]interface{} } func surfaceSource(s profile.Surface) storage.ActivitySource { @@ -458,6 +480,11 @@ func writeChangeRecord(ctx context.Context, activity func(*storage.ActivityRecor if len(c.diff) > 0 { meta["diff"] = c.diff } + for k, v := range c.meta { + if _, fixed := meta[k]; !fixed { + meta[k] = v + } + } rec := &storage.ActivityRecord{ Type: storage.ActivityTypeProfileChange, Source: surfaceSource(a.Surface), @@ -545,6 +572,11 @@ func (s *ClientsService) setBindingLocked(ctx context.Context, a Actor, clientID // The credential precondition (409) comes before request validation (400) // so a client without an active credential always gets no_client_credential. if state := s.stateOf(rec); state != profile.CredentialStateClient { + // Spec 132: a client with browser logins and no active API key is + // still a client; its binding changes through the one binding writer. + if v, handled, err := s.setOAuthBindingLocked(ctx, a, all, rec, clientID, profileName, modeArg); handled { + return v, err + } return nil, &NoClientCredentialError{ClientID: clientID, State: state} } if profileName != "" && !s.profileExists(s.cfg(), profileName) { @@ -604,6 +636,7 @@ func (s *ClientsService) BulkAssign(ctx context.Context, a Actor, from, to strin ids = append(ids, t.ClientID) } } + ids = append(ids, s.oauthOnlyBindingClients(all, from)...) sort.Strings(ids) for _, id := range ids { if s.connectInFlight(id) { @@ -644,11 +677,25 @@ func (s *ClientsService) List() ([]ClientCredentialView, error) { if err != nil { return nil, err } + st, err := s.loadOAuthState() + if err != nil { + return nil, err + } var out []ClientCredentialView for i := range all { if all[i].Kind == auth.KindClient { - out = append(out, *s.view(&all[i])) + v := s.view(&all[i]) + st.decorate(v, &all[i], s.now()) + out = append(out, *v) + } + } + for id, b := range st.bindings { + if rec := clientRecord(all, id); rec != nil && rec.Kind == auth.KindClient { + continue } + v := s.oauthOnlyView(id, b) + st.decorate(v, nil, s.now()) + out = append(out, *v) } sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID }) return out, nil @@ -661,10 +708,21 @@ func (s *ClientsService) Get(clientID string) (*ClientCredentialView, error) { return nil, err } rec := clientRecord(all, clientID) + st, err := s.loadOAuthState() + if err != nil { + return nil, err + } if rec == nil || rec.Kind != auth.KindClient { + if b, ok := st.bindings[clientID]; ok { + v := s.oauthOnlyView(clientID, b) + st.decorate(v, nil, s.now()) + return v, nil + } return nil, nil } - return s.view(rec), nil + v := s.view(rec) + st.decorate(v, rec, s.now()) + return v, nil } // Forget revokes a client's credential (change=forget). disconnected records @@ -710,6 +768,10 @@ func (s *ClientsService) forgetRecordLocked(ctx context.Context, a Actor, client forget := s.store.ForgetClientCredential if restorePrior { forget = s.store.ForgetClientCredentialRestoringPrior + } else if o := s.oauthStore(); s.hasLoginRecords(o, clientID) { + // Spec 132: forget deletes the client's browser logins, revoke marks + // them revoked; both cover the API key exactly as before. + forget = s.oauthForgetFunc(o, change) } // The restore path rewrites the revoked record's binding, so capture the // binding it held when revoked for the audit record. @@ -731,6 +793,10 @@ func (s *ClientsService) forgetRecordLocked(ctx context.Context, a Actor, client if !restorePrior { heldPin = revoked.ProfilePin } + // Revoking or forgetting a client also cancels its pending and approved + // sign-in requests, under the same mutex the token exchange commits under + // (Spec 132 R15). + s.cancelLoginRequests(clientID) s.writeChange(ctx, a, changeRecord{ change: change, profile: heldPin, previousProfile: heldPin, clientID: clientID, tokenName: revoked.Name, diff: diff, diff --git a/internal/runtime/clients_service_oauth.go b/internal/runtime/clients_service_oauth.go new file mode 100644 index 000000000..15cd1e1aa --- /dev/null +++ b/internal/runtime/clients_service_oauth.go @@ -0,0 +1,450 @@ +package runtime + +import ( + "context" + "errors" + "fmt" + "sort" + "time" + + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// Spec 132: a client holds an API key, browser logins, or both. The binding is +// one per client; this file is where ClientsService learns about the OAuth side +// without changing a byte of what it does for a client that never used it: every +// entry point first asks whether the store has browser-login storage AND whether +// the client (or the install) has any. + +// oauthClientStore is the browser-login storage surface ClientsService uses +// beyond ClientCredentialStore; *storage.Manager implements it. A store that +// does not (a test fake) keeps every behaviour exactly as it was. +type oauthClientStore interface { + OAuthBindingSource + GetOAuthClientBinding(clientID string) (*storage.OAuthClientBinding, error) + ListOAuthRegistrations() ([]storage.OAuthRegistration, error) + OAuthLoginEverUsed() (bool, error) + ForgetClient(clientID string) (*auth.AgentToken, error) + RevokeClient(clientID string, now time.Time) (*auth.AgentToken, error) + RevokeClientAPIKey(clientID string) (*auth.AgentToken, error) + UpdateOAuthClientBinding(clientID, pin, mode string) (beforePin, beforeMode string, err error) + RepairOAuthClientBindings() (repaired, skipped []string, err error) +} + +func (s *ClientsService) oauthStore() oauthClientStore { + o, _ := s.store.(oauthClientStore) + return o +} + +// SetLoginCanceler installs the hook that cancels a client's pending and +// approved sign-in requests; it runs under the service's mutex (the same one +// the token exchange commits under) after a revoke or forget. +func (s *ClientsService) SetLoginCanceler(fn func(clientID string)) { + s.cancelLogins = func(id string) { + if fn != nil { + fn(id) + } + } +} + +func (s *ClientsService) cancelLoginRequests(clientID string) { + if s.cancelLogins != nil { + s.cancelLogins(clientID) + } +} + +// hasLoginRecords reports whether the client has browser-login storage. +func (s *ClientsService) hasLoginRecords(o oauthClientStore, clientID string) bool { + if o == nil { + return false + } + b, err := o.GetOAuthClientBinding(clientID) + return err == nil && b != nil +} + +// loadOAuthBindings reads the OAuth side of a guard state (fail closed: an error +// refuses the change). +func (s *ClientsService) loadOAuthBindings() ([]OAuthBinding, error) { + return LoadOAuthBindings(s.store, s.now()) +} + +// oauthBindingsBestEffort is loadOAuthBindings for an advisory view (the +// warnings list): an unreadable store yields no bindings instead of an error, +// because nothing is being refused. +func (s *ClientsService) oauthBindingsBestEffort() []OAuthBinding { + b, err := s.loadOAuthBindings() + if err != nil { + s.logger.Warn("cannot read browser-login bindings for the warnings", zap.Error(err)) + return nil + } + return b +} + +// repinOAuthClient returns bindings with the client's entry set to (pin, mode). +func repinOAuthClient(bindings []OAuthBinding, clientID, pin, mode string) []OAuthBinding { + if len(bindings) == 0 { + return bindings + } + out := make([]OAuthBinding, len(bindings)) + copy(out, bindings) + for i := range out { + if out[i].ClientID == clientID { + out[i].Pin, out[i].Mode = pin, mode + } + } + return out +} + +// --- views ---------------------------------------------------------------------- + +// ClientCredentialEntry is one credential of a client in the Clients views +// (contracts/rest-admin.md): the API key or a browser login. A secret, a hash or +// a token never appears here. +type ClientCredentialEntry struct { + // Kind is api_key or browser_login. + Kind string `json:"kind"` + Prefix string `json:"prefix,omitempty"` + // GrantID names a browser login. + GrantID string `json:"grant_id,omitempty"` + // State is active|expired|revoked for an API key and active|lapsed|revoked + // for a login. + State string `json:"state"` + ExpiresAt *time.Time `json:"expires_at,omitempty"` + ApprovedAt *time.Time `json:"approved_at,omitempty"` + LastUsedAt *time.Time `json:"last_used_at,omitempty"` + ReportedName string `json:"reported_name,omitempty"` + RedirectHost string `json:"redirect_host,omitempty"` + ObservedName string `json:"observed_name,omitempty"` + NameMismatch *bool `json:"name_mismatch,omitempty"` +} + +// Browser-login states of a grant. +const ( + GrantStateActive = "active" + GrantStateLapsed = "lapsed" + GrantStateRevoked = "revoked" +) + +// GrantStateOf classifies a grant: revoked over lapsed over active. +func GrantStateOf(g *storage.OAuthGrant, now time.Time) string { + switch { + case g.Revoked: + return GrantStateRevoked + case !g.RefreshExpiresAt.After(now): + return GrantStateLapsed + default: + return GrantStateActive + } +} + +// oauthClientsState is what the views need from the browser-login storage. It +// is inactive (the zero value) for an install that never used the feature, and +// then every view is exactly what it was before Spec 132. +type oauthClientsState struct { + active bool + disabled bool + bindings map[string]storage.OAuthClientBinding + grants map[string][]storage.OAuthGrant + reported map[string]string // registration id -> reported name +} + +func (s *ClientsService) loadOAuthState() (oauthClientsState, error) { + o := s.oauthStore() + if o == nil { + return oauthClientsState{}, nil + } + bindings, err := o.ListOAuthClientBindings() + if err != nil { + return oauthClientsState{}, fmt.Errorf("cannot read browser-login bindings: %w", err) + } + used := len(bindings) > 0 + if !used { + if used, err = o.OAuthLoginEverUsed(); err != nil { + return oauthClientsState{}, fmt.Errorf("cannot read the browser-login marker: %w", err) + } + } + if !used { + return oauthClientsState{}, nil + } + grants, err := o.ListOAuthGrants() + if err != nil { + return oauthClientsState{}, fmt.Errorf("cannot read browser logins: %w", err) + } + regs, err := o.ListOAuthRegistrations() + if err != nil { + return oauthClientsState{}, fmt.Errorf("cannot read browser-login registrations: %w", err) + } + st := oauthClientsState{active: true, bindings: bindings, grants: map[string][]storage.OAuthGrant{}, reported: map[string]string{}} + if c := s.cfg(); c == nil || !c.MCPOAuthEnabled { + st.disabled = true + } + for i := range regs { + st.reported[regs[i].ClientID] = regs[i].ReportedName + } + sort.SliceStable(grants, func(i, j int) bool { return grants[i].ApprovedAt.After(grants[j].ApprovedAt) }) + for i := range grants { + st.grants[grants[i].Client] = append(st.grants[grants[i].Client], grants[i]) + } + return st, nil +} + +// decorate adds the credentials list and browser_login_disabled to a view. It +// is a no-op while the feature was never used. +func (st oauthClientsState) decorate(v *ClientCredentialView, rec *auth.AgentToken, now time.Time) { + if !st.active { + return + } + creds := []ClientCredentialEntry{} + if rec != nil && rec.Kind == auth.KindClient { + e := ClientCredentialEntry{Kind: "api_key", Prefix: rec.TokenPrefix, State: CredentialStateOf(rec, now), LastUsedAt: rec.LastUsedAt} + if !rec.ExpiresAt.IsZero() { + exp := rec.ExpiresAt + e.ExpiresAt = &exp + } + creds = append(creds, e) + } + grants := st.grants[v.ID] + for i := range grants { + g := &grants[i] + mismatch := OAuthNameMismatch(g.ObservedClientName, st.reported[g.RegistrationID], g.Client) + approved := g.ApprovedAt + exp := g.RefreshExpiresAt + creds = append(creds, ClientCredentialEntry{ + Kind: CredentialKindBrowserLogin, GrantID: g.GrantID, State: GrantStateOf(g, now), + Prefix: g.DisplayPrefix, ExpiresAt: &exp, ApprovedAt: &approved, LastUsedAt: g.LastUsedAt, + ReportedName: st.reported[g.RegistrationID], RedirectHost: redirectHost(g.RedirectURI), + ObservedName: g.ObservedClientName, NameMismatch: &mismatch, + }) + } + v.Credentials = creds + disabled := st.disabled && len(grants) > 0 + v.BrowserLoginDisabled = &disabled +} + +// oauthOnlyView is the view of a client that has browser logins and no API-key +// record. +func (s *ClientsService) oauthOnlyView(id string, b storage.OAuthClientBinding) *ClientCredentialView { + return &ClientCredentialView{ + ID: id, DisplayName: b.DisplayName, TokenName: auth.ClientTokenName(id), + Profile: b.ProfilePin, Mode: b.ProfileMode, CredentialState: profile.CredentialStateNone, + } +} + +// --- binding change --------------------------------------------------------------- + +// setOAuthBindingLocked is setBindingLocked for a client without an ACTIVE API +// key that has browser-login storage (s.mu held). handled is false when the +// client has none, and the caller answers no_client_credential as before. The +// one binding writer keeps an existing API-key record equal. +func (s *ClientsService) setOAuthBindingLocked(ctx context.Context, a Actor, all []auth.AgentToken, rec *auth.AgentToken, clientID, profileName string, modeArg *string) (view *ClientCredentialView, handled bool, err error) { + o := s.oauthStore() + if o == nil { + return nil, false, nil + } + entry, err := o.GetOAuthClientBinding(clientID) + if err != nil { + return nil, true, err + } + if entry == nil { + return nil, false, nil + } + curPin, curMode := entry.ProfilePin, entry.ProfileMode + if rec != nil && rec.Kind == auth.KindClient { + curPin, curMode = rec.ProfilePin, rec.ProfileMode // the record wins + } + if profileName != "" && !s.profileExists(s.cfg(), profileName) { + return nil, true, &ValidationError{Field: "profile", Message: fmt.Sprintf("unknown profile %q", profileName)} + } + mode, err := resolveMode(profileName, modeArg, curMode) + if err != nil { + return nil, true, err + } + state, err := s.loadOAuthState() + if err != nil { + return nil, true, err + } + if curPin == profileName && curMode == mode { + v := s.oauthOnlyView(clientID, *entry) + v.Profile, v.Mode = curPin, curMode + state.decorate(v, rec, s.now()) + return v, true, nil + } + // The guard judges the whole candidate: the API-key record (when there is + // one, whatever its state) and the browser-login entry both move. + oauth, err := s.loadOAuthBindings() + if err != nil { + return nil, true, err + } + cfg := s.cfg() + tokens := guardedOnly(all) + candTokens := tokens + if rec != nil && rec.Kind == auth.KindClient { + next := *rec + next.ProfilePin, next.ProfileMode = profileName, mode + candTokens = candidateTokens(all, clientID, &next) + } + if err := CheckBindingGuard(s.guard(), + GuardState{Config: cfg, Tokens: tokens, OAuthBindings: oauth}, + GuardState{Config: cfg, Tokens: candTokens, OAuthBindings: repinOAuthClient(oauth, clientID, profileName, mode)}); err != nil { + return nil, true, err + } + if _, _, err := o.UpdateOAuthClientBinding(clientID, profileName, mode); err != nil { + if errors.Is(err, storage.ErrClientCredentialNotFound) { + return nil, false, nil + } + return nil, true, err + } + before := &auth.AgentToken{Name: auth.ClientTokenName(clientID), Kind: auth.KindClient, ClientID: clientID, ProfilePin: curPin, ProfileMode: curMode} + after := &auth.AgentToken{Name: auth.ClientTokenName(clientID), Kind: auth.KindClient, ClientID: clientID, ProfilePin: profileName, ProfileMode: mode} + change, diff := bindingChange(before, after) + s.writeChange(ctx, a, changeRecord{ + change: change, profile: profileName, previousProfile: curPin, + clientID: clientID, tokenName: after.Name, diff: diff, + }) + s.announce(before, after) + v := s.oauthOnlyView(clientID, *entry) + v.Profile, v.Mode = profileName, mode + state, _ = s.loadOAuthState() + state.decorate(v, rec, s.now()) + return v, true, nil +} + +// oauthOnlyBindingClients returns the ids of clients with a browser-login entry +// but no kind=client API-key record whose binding pin is from, sorted. +func (s *ClientsService) oauthOnlyBindingClients(all []auth.AgentToken, from string) []string { + o := s.oauthStore() + if o == nil { + return nil + } + bindings, err := o.ListOAuthClientBindings() + if err != nil || len(bindings) == 0 { + return nil + } + var ids []string + for id, b := range bindings { + if rec := clientRecord(all, id); rec != nil && rec.Kind == auth.KindClient { + continue // listed through its record + } + if b.ProfilePin == from { + ids = append(ids, id) + } + } + sort.Strings(ids) + return ids +} + +// --- forget and revoke -------------------------------------------------------------- + +// oauthForgetFunc is the store call a forget or revoke makes for a client that +// has browser-login storage: ForgetClient deletes grants and the entry, +// RevokeClient marks the key and every grant revoked and keeps them for +// display. It returns the API-key record, or a revoked stand-in carrying the +// binding for a client that has none (so the surfaces and the audit record read +// the same). +func (s *ClientsService) oauthForgetFunc(o oauthClientStore, change profile.ChangeKind) func(string) (*auth.AgentToken, error) { + return func(clientID string) (*auth.AgentToken, error) { + entry, _ := o.GetOAuthClientBinding(clientID) + var rec *auth.AgentToken + var err error + if change == profile.ChangeRevoke { + rec, err = o.RevokeClient(clientID, s.now().UTC()) + } else { + rec, err = o.ForgetClient(clientID) + } + if err != nil { + return nil, err + } + if rec == nil { + standIn := &auth.AgentToken{ + Name: auth.ClientTokenName(clientID), Kind: auth.KindClient, ClientID: clientID, + Revoked: true, ExpiresAt: time.Time{}, + } + if entry != nil { + standIn.ProfilePin, standIn.ProfileMode, standIn.DisplayName = entry.ProfilePin, entry.ProfileMode, entry.DisplayName + } + rec = standIn + } + return rec, nil + } +} + +// RevokeAPIKey revokes the client's API key alone: its browser logins and its +// binding stay (Spec 132). It writes a `revoke` record and emits +// credentials.changed. A client with no active API key is +// *NoClientCredentialError. +func (s *ClientsService) RevokeAPIKey(ctx context.Context, a Actor, clientID string) (*ClientCredentialView, error) { + if !auth.ValidClientID(clientID) { + return nil, &ValidationError{Field: "id", Message: fmt.Sprintf("invalid client id %q", clientID)} + } + s.mu.Lock() + defer s.mu.Unlock() + all, err := s.records() + if err != nil { + return nil, err + } + rec := clientRecord(all, clientID) + if state := s.stateOf(rec); rec == nil || rec.Kind != auth.KindClient || rec.Revoked { + return nil, &NoClientCredentialError{ClientID: clientID, State: state} + } + var revoked *auth.AgentToken + if o := s.oauthStore(); o != nil { + revoked, err = o.RevokeClientAPIKey(clientID) + } else { + revoked, err = s.store.ForgetClientCredential(clientID) + } + if err != nil { + if errors.Is(err, storage.ErrClientCredentialNotFound) { + return nil, &NoClientCredentialError{ClientID: clientID, State: profile.CredentialStateNone} + } + return nil, err + } + s.writeChange(ctx, a, changeRecord{ + change: profile.ChangeRevoke, profile: revoked.ProfilePin, previousProfile: revoked.ProfilePin, + clientID: clientID, tokenName: revoked.Name, + diff: map[string]interface{}{"credential_kind": "api_key", "via": viaOf(a), "changed": true}, + }) + if s.publish != nil { + s.publish(newEvent(EventTypeCredentialsChanged, map[string]any{ + "kind": CredentialKindClient, "id": clientID, "token_name": revoked.Name, + "change": string(profile.ChangeRevoke), "profile": revoked.ProfilePin, + })) + } + if s.notifier != nil { + s.notifier.NotifyBindingChanged(revoked.Name) + } + v := s.view(revoked) + if st, lerr := s.loadOAuthState(); lerr == nil { + st.decorate(v, revoked, s.now()) + } + return v, nil +} + +// --- startup --------------------------------------------------------------------------- + +// repairOAuthBindings makes every client that has both an API-key record and a +// browser-login entry agree (the record is the truth) and logs what it did at +// WARN. It runs once at startup, before serving. On a database that never used +// browser login it opens no write transaction. +func (r *Runtime) repairOAuthBindings() { + sm := r.storageManager + if sm == nil { + return + } + repaired, skipped, err := sm.RepairOAuthClientBindings() + if err != nil { + r.logger.Warn("browser login: cannot check client bindings at startup", zap.Error(err)) + return + } + if len(repaired) > 0 { + r.logger.Warn("browser login: repaired client bindings that differed from the API-key record", + zap.Strings("clients", repaired)) + } + if len(skipped) > 0 { + r.logger.Warn("browser login: left client bindings alone because the API-key binding is invalid", + zap.Strings("clients", skipped)) + } +} diff --git a/internal/runtime/clients_service_reconcile.go b/internal/runtime/clients_service_reconcile.go index 6d0f27b27..6138b92cc 100644 --- a/internal/runtime/clients_service_reconcile.go +++ b/internal/runtime/clients_service_reconcile.go @@ -155,7 +155,7 @@ func (s *ClientsService) Warnings(states map[string]profile.CredentialState) []W Message: fmt.Sprintf("anonymous callers are denied while %s could be bypassed without auth", strings.Join(names, ", ")), Action: &WarningAction{Kind: string(profile.FixChangeSetting), Target: "require_mcp_auth"}, Bindings: active, - Fixes: g.BindingGuardFixes(GuardState{Config: cfg, Tokens: guardedOnly(all)}, active), + Fixes: g.BindingGuardFixes(GuardState{Config: cfg, Tokens: guardedOnly(all), OAuthBindings: s.oauthBindingsBestEffort()}, active), }) } now := s.now() diff --git a/internal/runtime/clients_service_upgrade.go b/internal/runtime/clients_service_upgrade.go index ec04ccf22..6f14e674b 100644 --- a/internal/runtime/clients_service_upgrade.go +++ b/internal/runtime/clients_service_upgrade.go @@ -260,8 +260,13 @@ func (s *ClientsService) upgradeGuard(rows []UpgradeRow, req UpgradeRequest) err return err } cfg := s.cfg() - current := GuardState{Config: cfg, Tokens: guardedOnly(all)} + oauth, err := s.loadOAuthBindings() + if err != nil { + return err + } + current := GuardState{Config: cfg, Tokens: guardedOnly(all), OAuthBindings: oauth} tokens := guardedOnly(all) + candOAuth := oauth now := s.now().UTC() for _, r := range rows { next := auth.AgentToken{ @@ -269,8 +274,9 @@ func (s *ClientsService) upgradeGuard(rows []UpgradeRow, req UpgradeRequest) err ProfilePin: *req.Profile, ProfileMode: mode, CreatedAt: now, ExpiresAt: now.Add(clientCredentialTTL), } tokens = candidateTokens(tokens, r.ClientID, &next) + candOAuth = repinOAuthClient(candOAuth, r.ClientID, next.ProfilePin, next.ProfileMode) } - return CheckBindingGuard(s.guard(), current, GuardState{Config: cfg, Tokens: tokens}) + return CheckBindingGuard(s.guard(), current, GuardState{Config: cfg, Tokens: tokens, OAuthBindings: candOAuth}) } // PreviewAdminKeyUpgrade classifies every supported client that holds the admin diff --git a/internal/runtime/commit.go b/internal/runtime/commit.go index a392cf4cc..09c3f73b6 100644 --- a/internal/runtime/commit.go +++ b/internal/runtime/commit.go @@ -956,6 +956,16 @@ func (r *Runtime) commitLocked(reason string, fn func(tx *CommitTx) error) (*Com h(reason) } + // Spec 132 R15: a commit in which browser login goes from on to off cancels + // every pending and approved sign-in request BEFORE the new configuration + // becomes visible, on the API update path and the file-reload path alike + // (both end here). It does not depend on config.reloaded, which is + // asynchronous and may be dropped. It takes the request store's mutex only: + // see the lock-order note on OAuthLoginService. + if base.Config != nil && base.Config.MCPOAuthEnabled && !tx.next.MCPOAuthEnabled && r.oauthLoginService != nil { + r.oauthLoginService.CancelAll("feature_disabled") + } + // Step 8: publish. snap, perr := r.configSvc.Publish(prepared) if perr != nil { diff --git a/internal/runtime/config_funnel.go b/internal/runtime/config_funnel.go index b768f38df..55a9cd6eb 100644 --- a/internal/runtime/config_funnel.go +++ b/internal/runtime/config_funnel.go @@ -103,13 +103,21 @@ func (r *Runtime) MutateConfig( if err != nil { return fail(fmt.Errorf("cannot inspect client bindings: %w", err)) } + oauthCurrent, err := r.oauthBindingSnapshot() + if err != nil { + return fail(fmt.Errorf("cannot inspect browser-login bindings: %w", err)) + } + oauthCandidate := oauthCurrent + if tokens.active() { + oauthCandidate = repinOAuthBindings(oauthCurrent, tokens.From, tokens.To) + } candidateTokens := current if tokens.active() { candidateTokens = rewriteClientPins(current, tokens.From, tokens.To) } if err := CheckBindingGuard(r.BindingGuard(), - GuardState{Config: r.Config(), Tokens: current}, - GuardState{Config: desired, Tokens: candidateTokens}); err != nil { + GuardState{Config: r.Config(), Tokens: current, OAuthBindings: oauthCurrent}, + GuardState{Config: desired, Tokens: candidateTokens, OAuthBindings: oauthCandidate}); err != nil { return fail(err) } @@ -219,8 +227,12 @@ func (r *Runtime) GuardedApplyConfig(newCfg *config.Config, cfgPath string) (*Co if err != nil { return nil, fmt.Errorf("cannot inspect client bindings: %w", err) } - current := GuardState{Config: r.Config(), Tokens: tokens} - candidate := GuardState{Config: newCfg, Tokens: tokens} + oauth, err := r.oauthBindingSnapshot() + if err != nil { + return nil, fmt.Errorf("cannot inspect browser-login bindings: %w", err) + } + current := GuardState{Config: r.Config(), Tokens: tokens, OAuthBindings: oauth} + candidate := GuardState{Config: newCfg, Tokens: tokens, OAuthBindings: oauth} if err := CheckBindingGuard(r.BindingGuard(), current, candidate); err != nil { return nil, err } diff --git a/internal/runtime/credentials_service.go b/internal/runtime/credentials_service.go index 93439d2a7..3649fe1d2 100644 --- a/internal/runtime/credentials_service.go +++ b/internal/runtime/credentials_service.go @@ -44,6 +44,8 @@ type CredentialsService struct { mu *sync.Mutex logger *zap.Logger generate func() (string, error) + // oauth revokes one browser login (Spec 132). Nil in tests that do not wire it. + oauth *OAuthLoginService } // CredentialTokenStore is the token-store surface the service needs. Every @@ -180,6 +182,15 @@ type CredentialView struct { // RateLimit is the token's own call budget (issue #1699), set at issue // time. Absent when the token has none and follows agent_token_rate_limit. RateLimit *auth.TokenRateLimit `json:"rate_limit,omitempty"` + + // The fields below describe a browser login (kind browser_login, Spec 132); + // they are empty for every other kind. ID is the grant id and Client the + // Clients hub id. + Client string `json:"client,omitempty"` + ReportedName string `json:"reported_name,omitempty"` + RedirectHost string `json:"redirect_host,omitempty"` + ObservedName string `json:"observed_name,omitempty"` + NameMismatch *bool `json:"name_mismatch,omitempty"` } // CredentialStateOf classifies a record: revoked over expired over active. @@ -339,6 +350,8 @@ type IssueTokenRequest struct { // token name (the OWNERLESS namespace only, data-model §9). type CredentialRef struct { Client, Token string + // Grant, with Client, names ONE browser login of the client (Spec 132). + Grant string // EnforceWriteGates (MCP) re-checks read_only_mode and disable_management // under bindingWriteMu, so a mutation queued behind a config write that // turns a gate on is refused (the handler's check alone is a TOCTOU). @@ -712,7 +725,11 @@ func (s *CredentialsService) IssueToken(ctx context.Context, a Actor, req IssueT if req.EnforceGuard { current := guardedOnly(all) next := append(append([]auth.AgentToken(nil), current...), candidate) - if err := CheckBindingGuard(s.guard(), GuardState{Config: cfg, Tokens: current}, GuardState{Config: cfg, Tokens: next}); err != nil { + oauth, err := LoadOAuthBindings(s.tokens, s.now()) + if err != nil { + return nil, err // fail closed: an unreadable browser-login store refuses the issue + } + if err := CheckBindingGuard(s.guard(), GuardState{Config: cfg, Tokens: current, OAuthBindings: oauth}, GuardState{Config: cfg, Tokens: next, OAuthBindings: oauth}); err != nil { return nil, err } } @@ -986,11 +1003,17 @@ func (s *CredentialsService) Revoke(ctx context.Context, a Actor, ref Credential if (ref.Client == "") == (ref.Token == "") { return nil, credErr(profile.CredentialErrorCodeInvalidArgument, "client", "exactly one of client or token is required", 400) } + if ref.Grant != "" && ref.Client == "" { + return nil, credErr(profile.CredentialErrorCodeInvalidArgument, "grant", "a grant is revoked together with its client", 400) + } s.mu.Lock() defer s.mu.Unlock() if err := s.writeGateError(ref.EnforceWriteGates); err != nil { return nil, err } + if ref.Grant != "" { + return s.revokeGrantLocked(ctx, ref.Client, ref.Grant) + } if ref.Client != "" { return s.revokeClientLocked(ctx, a, ref.Client) } @@ -1117,15 +1140,28 @@ func (s *CredentialsService) revokeClientLocked(ctx context.Context, a Actor, cl return nil, err } rec := clientRecord(all, clientID) - if rec == nil || rec.Kind != auth.KindClient { + hasKey := rec != nil && rec.Kind == auth.KindClient + // Spec 132: a client with browser logins is a client even without an API + // key, and revoking it revokes every login too. + hasLogins := s.clients.hasLoginRecords(s.clients.oauthStore(), clientID) + if !hasKey && !hasLogins { return nil, s.notFound("client", clientID) } cfg := s.cfg() - if rec.Revoked { + if hasKey && rec.Revoked && (!hasLogins || !s.hasLiveGrant(clientID, s.now())) { return &RevokeResult{View: ViewOf(rec, cfg, s.now()), ClientConfigUntouched: true}, nil } + var view CredentialView + if hasKey { + view = ViewOf(rec, cfg, s.now()) + } else { + st, err := s.clients.loadOAuthState() + if err != nil { + return nil, err + } + view = s.oauthOnlyCredentialView(clientID, st.bindings[clientID], st.grants[clientID]) + } diff := map[string]interface{}{"via": viaOf(a), "changed": true, "client_config_untouched": true} - view := ViewOf(rec, cfg, s.now()) for k, v := range lifecycleDiff(view, a) { if _, set := diff[k]; !set { diff[k] = v @@ -1171,6 +1207,10 @@ func (s *CredentialsService) List(f CredentialFilter) ([]CredentialView, error) } out = append(out, v) } + out, err = s.listOAuth(f, out) + if err != nil { + return nil, err + } sort.Slice(out, func(i, j int) bool { if out[i].Kind != out[j].Kind { return out[i].Kind < out[j].Kind @@ -1204,6 +1244,11 @@ func (s *CredentialsService) Get(ref CredentialRef) (*CredentialView, error) { return nil, fmt.Errorf("cannot read credentials: %w", err) } if rec == nil || (kind == "client") != (rec.Kind == auth.KindClient) { + if kind == "client" { + if v, err := s.getOAuthOnlyClient(ref.Client); err != nil || v != nil { + return v, err + } + } label := ref.Token if kind == "client" { label = ref.Client diff --git a/internal/runtime/credentials_service_oauth.go b/internal/runtime/credentials_service_oauth.go new file mode 100644 index 000000000..f30906a42 --- /dev/null +++ b/internal/runtime/credentials_service_oauth.go @@ -0,0 +1,194 @@ +package runtime + +import ( + "context" + "errors" + "sort" + "time" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// Spec 132: the credentials service lists and revokes browser logins next to +// the API keys and tokens it already owns. It never issues one: a login exists +// only through the consent page. + +// CredentialStateLapsed is the state of a browser login whose refresh token +// expired. +const CredentialStateLapsed = "lapsed" + +// SetOAuthLogin installs the browser-login service used to revoke one login. +func (s *CredentialsService) SetOAuthLogin(o *OAuthLoginService) { s.oauth = o } + +// grantView projects a grant to its safe view: no token, no hash. +func (s *CredentialsService) grantView(g *storage.OAuthGrant, st oauthClientsState, binding *storage.OAuthClientBinding) CredentialView { + now := s.now() + exp := g.RefreshExpiresAt + mismatch := OAuthNameMismatch(g.ObservedClientName, st.reported[g.RegistrationID], g.Client) + v := CredentialView{ + Kind: CredentialKindBrowserLogin, ID: g.GrantID, Client: g.Client, TokenName: auth.ClientTokenName(g.Client), + State: GrantStateOf(g, now), CreatedAt: g.ApprovedAt, ExpiresAt: &exp, RevokedAt: g.RevokedAt, + LastUsedAt: g.LastUsedAt, TokenPrefix: g.DisplayPrefix, ReportedName: st.reported[g.RegistrationID], + RedirectHost: redirectHost(g.RedirectURI), ObservedName: g.ObservedClientName, NameMismatch: &mismatch, + } + if binding != nil { + v.Profile, v.Binding, v.ProfileState = binding.ProfilePin, binding.ProfileMode, ProfileStateOf(binding.ProfilePin, s.cfg()) + } else { + v.ProfileState = ProfileStateNone + } + return v +} + +// oauthOnlyCredentialView is the view of a client that has browser logins and +// no API-key record: its state is the best state of its logins. +func (s *CredentialsService) oauthOnlyCredentialView(id string, b storage.OAuthClientBinding, grants []storage.OAuthGrant) CredentialView { + now := s.now() + v := CredentialView{ + Kind: CredentialKindClient, ID: id, TokenName: auth.ClientTokenName(id), DisplayName: b.DisplayName, + Profile: b.ProfilePin, Binding: b.ProfileMode, ProfileState: ProfileStateOf(b.ProfilePin, s.cfg()), + State: CredentialStateRevoked, CreatedAt: b.UpdatedAt, + } + sawExpired := false + for i := range grants { + g := &grants[i] + if v.CreatedAt.IsZero() || g.ApprovedAt.Before(v.CreatedAt) { + v.CreatedAt = g.ApprovedAt + } + if g.LastUsedAt != nil && (v.LastUsedAt == nil || g.LastUsedAt.After(*v.LastUsedAt)) { + t := *g.LastUsedAt + v.LastUsedAt = &t + } + switch GrantStateOf(g, now) { + case GrantStateActive: + v.State = CredentialStateActive + case GrantStateLapsed: + sawExpired = true + } + } + if v.State != CredentialStateActive && sawExpired { + v.State = CredentialStateExpired + } + return v +} + +// listOAuth adds the browser logins (and the clients that have only logins) to +// a List result. It adds nothing while the feature was never used. +func (s *CredentialsService) listOAuth(f CredentialFilter, out []CredentialView) ([]CredentialView, error) { + if s.clients == nil { + return out, nil + } + st, err := s.clients.loadOAuthState() + if err != nil { + return nil, err + } + if !st.active { + return out, nil + } + have := map[string]bool{} + for _, v := range out { + if v.Kind == CredentialKindClient { + have[v.ID] = true + } + } + add := func(v CredentialView) { + if f.Kind != "" && f.Kind != "all" && f.Kind != v.Kind { + return + } + if f.Profile != "" && f.Profile != v.Profile { + return + } + if f.State != "" && f.State != "all" && f.State != v.State { + return + } + out = append(out, v) + } + if !f.ExcludeClients { + for id, b := range st.bindings { + if !have[id] { + add(s.oauthOnlyCredentialView(id, b, st.grants[id])) + } + } + for id, gs := range st.grants { + b := st.bindings[id] + for i := range gs { + add(s.grantView(&gs[i], st, &b)) + } + } + } + sort.Slice(out, func(i, j int) bool { + if out[i].Kind != out[j].Kind { + return out[i].Kind < out[j].Kind + } + return out[i].ID < out[j].ID + }) + return out, nil +} + +// getOAuthOnlyClient answers Get(client) for a client with browser logins and +// no API-key record; nil when it has none. +func (s *CredentialsService) getOAuthOnlyClient(clientID string) (*CredentialView, error) { + if s.clients == nil { + return nil, nil + } + st, err := s.clients.loadOAuthState() + if err != nil { + return nil, err + } + b, ok := st.bindings[clientID] + if !ok { + return nil, nil + } + v := s.oauthOnlyCredentialView(clientID, b, st.grants[clientID]) + return &v, nil +} + +// revokeGrantLocked revokes one browser login (s.mu held): the login service +// writes the `revoke` record and the credentials.changed event itself. +func (s *CredentialsService) revokeGrantLocked(ctx context.Context, clientID, grantID string) (*RevokeResult, error) { + if s.oauth == nil || s.clients == nil { + return nil, ErrCredentialsUnavailable + } + if !auth.ValidClientID(clientID) { + return nil, credErr(profile.CredentialErrorCodeInvalidArgument, "client", + `invalid argument "client": must be lower-case letters, digits, '-' or '_', at most 56 characters`, 400) + } + changed, err := s.oauth.revokeGrantLocked(ctx, clientID, grantID) + if err != nil { + if errors.Is(err, ErrOAuthGrantNotFound) { + return nil, credErr(profile.CredentialErrorCodeIdentityNotFound, "grant", "browser login not found", 404) + } + return nil, err + } + st, err := s.clients.loadOAuthState() + if err != nil { + return nil, err + } + b := st.bindings[clientID] + for i := range st.grants[clientID] { + if g := &st.grants[clientID][i]; g.GrantID == grantID { + return &RevokeResult{View: s.grantView(g, st, &b), Changed: changed, ClientConfigUntouched: true}, nil + } + } + return nil, credErr(profile.CredentialErrorCodeIdentityNotFound, "grant", "browser login not found", 404) +} + +// hasLiveGrant reports whether the client has a browser login that is neither +// revoked nor lapsed. +func (s *CredentialsService) hasLiveGrant(clientID string, now time.Time) bool { + o := s.clients.oauthStore() + if o == nil { + return false + } + gs, err := o.ListOAuthGrants() + if err != nil { + return false + } + for i := range gs { + if gs[i].Client == clientID && GrantStateOf(&gs[i], now) == GrantStateActive { + return true + } + } + return false +} diff --git a/internal/runtime/events.go b/internal/runtime/events.go index 86ff2eea3..8f3fd6ead 100644 --- a/internal/runtime/events.go +++ b/internal/runtime/events.go @@ -54,6 +54,15 @@ const ( // prefix, purpose or expiry: subscribers refetch. It names identities and // profiles, so it is administrator-only on SSE. EventTypeCredentialsChanged EventType = "credentials.changed" + // EventTypeOAuthAuthorizationPending is emitted (Spec 132) when a browser + // sign-in request waits for an administrator. Payload: {request_id, + // client_id, client_label}; the label is the sanitised, unverified name the + // client reported. It names a client, so it is administrator-only on SSE. + EventTypeOAuthAuthorizationPending EventType = "oauth.authorization_pending" + // EventTypeOAuthAuthorizationDecided is emitted (Spec 132) when a sign-in + // request leaves the pending state. Payload: {request_id, status} with + // status approved, denied or cancelled. Administrator-only on SSE. + EventTypeOAuthAuthorizationDecided EventType = "oauth.authorization_decided" // Activity logging events (RFC-003) // EventTypeActivityToolCallStarted is emitted when a tool execution begins. diff --git a/internal/runtime/oauth_login_clients_test.go b/internal/runtime/oauth_login_clients_test.go new file mode 100644 index 000000000..0ee4d95c5 --- /dev/null +++ b/internal/runtime/oauth_login_clients_test.go @@ -0,0 +1,535 @@ +package runtime + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// commitOAuthOnlyClient stores a client that has only a browser login. +func commitOAuthOnlyClient(t *testing.T, sm *storage.Manager, regID, grantID, client, pin, mode string) { + t.Helper() + now := time.Now().UTC() + require.NoError(t, sm.CreateOAuthRegistration(storage.OAuthRegistration{ + ClientID: regID, ReportedName: "App", RedirectURIs: []string{"http://127.0.0.1:9/cb"}, + TokenEndpointAuthMethod: "none", GrantTypes: []string{"authorization_code", "refresh_token"}, CreatedAt: now, + })) + _, err := sm.CommitOAuthLogin(storage.CommitLoginInput{ + Grant: storage.OAuthGrant{ + GrantID: grantID, RegistrationID: regID, Client: client, RedirectURI: "http://127.0.0.1:9/cb", + Resource: "http://127.0.0.1:8080/mcp/oauth/" + client, Issuer: "http://127.0.0.1:8080", + RefreshHash: "rh-" + grantID, AccessHash: "ah-" + grantID, + AccessExpiresAt: now.Add(time.Hour), RefreshExpiresAt: now.Add(24 * time.Hour), + ApprovedAt: now, DisplayPrefix: "mcp_oat_" + grantID[:4], + }, + Client: client, NewClient: true, Pin: pin, Mode: mode, ExpectedBindingRevision: storage.OAuthBindingAbsent, Now: now, + }) + require.NoError(t, err) +} + +// --- views ------------------------------------------------------------------------------------------ + +// While browser login was never used a view is EXACTLY what it was: no new +// field is set, so the JSON carries no new key. +func TestClientViews_UnchangedWhenNeverUsed(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + + list, err := fx.clients.List() + require.NoError(t, err) + require.Len(t, list, 1) + got, err := fx.clients.Get("codex") + require.NoError(t, err) + require.NotNil(t, got) + for _, v := range []ClientCredentialView{list[0], *got} { + assert.Nil(t, v.Credentials) + assert.Nil(t, v.BrowserLoginDisabled) + raw, err := json.Marshal(v) + require.NoError(t, err) + assert.NotContains(t, string(raw), "credentials") + assert.NotContains(t, string(raw), "browser_login_disabled") + } + + cl, err := fx.creds.List(CredentialFilter{}) + require.NoError(t, err) + require.Len(t, cl, 1) + assert.Equal(t, CredentialKindClient, cl[0].Kind) + raw, _ := json.Marshal(cl[0]) + assert.NotContains(t, string(raw), "reported_name") + + ghost, err := fx.clients.Get("ghost") + require.NoError(t, err) + assert.Nil(t, ghost) + used, _ := fx.sm.OAuthLoginEverUsed() + assert.False(t, used) +} + +func TestClientViews_ListCredentialsOnceUsed(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + fx.loginNew("cursor", "rw") + gid := fx.grants()[0].GrantID + require.NoError(t, fx.sm.TouchOAuthGrant(gid, fx.clock.Now(), "totally-other-app")) + + list, err := fx.clients.List() + require.NoError(t, err) + require.Len(t, list, 2) + byID := map[string]ClientCredentialView{} + for _, v := range list { + byID[v.ID] = v + } + // An API-key-only client carries its api_key entry and the flag, no logins. + codex := byID["codex"] + require.Len(t, codex.Credentials, 1) + assert.Equal(t, "api_key", codex.Credentials[0].Kind) + assert.Equal(t, "active", codex.Credentials[0].State) + require.NotNil(t, codex.BrowserLoginDisabled) + assert.False(t, *codex.BrowserLoginDisabled) + + // The OAuth-only client is a row of the hub. + cur := byID["cursor"] + assert.Equal(t, "rw", cur.Profile) + assert.Equal(t, auth.ProfileModeLocked, cur.Mode) + assert.Equal(t, profile.CredentialStateNone, cur.CredentialState, "it has no API key") + assert.Equal(t, "client-cursor", cur.TokenName) + require.Len(t, cur.Credentials, 1) + e := cur.Credentials[0] + assert.Equal(t, "browser_login", e.Kind) + assert.Equal(t, gid, e.GrantID) + assert.Equal(t, "active", e.State) + assert.Equal(t, "cursor ide", e.ReportedName) + assert.Equal(t, "127.0.0.1", e.RedirectHost) + assert.Equal(t, "totally-other-app", e.ObservedName) + require.NotNil(t, e.NameMismatch) + assert.True(t, *e.NameMismatch, "advisory only") + assert.NotNil(t, e.ApprovedAt) + + // The matching name clears the warning. + require.NoError(t, fx.sm.TouchOAuthGrant(gid, fx.clock.Now(), "cursor")) + got, err := fx.clients.Get("cursor") + require.NoError(t, err) + require.NotNil(t, got) + assert.False(t, *got.Credentials[0].NameMismatch) + assert.False(t, *got.BrowserLoginDisabled) + + // The switch off after use: logins stay listed, flagged. + fx.cfg.MCPOAuthEnabled = false + got, err = fx.clients.Get("cursor") + require.NoError(t, err) + assert.True(t, *got.BrowserLoginDisabled) + codex2, _ := fx.clients.Get("codex") + assert.False(t, *codex2.BrowserLoginDisabled, "only a client that has logins is flagged") + + // A lapsed login says so. + fx.clock.Advance(OAuthRefreshTokenTTL + time.Hour) + got, _ = fx.clients.Get("cursor") + assert.Equal(t, "lapsed", got.Credentials[0].State) +} + +func TestCredentialsService_ListsAndGetsBrowserLogins(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + fx.loginNew("cursor", "rw") + gid := fx.grants()[0].GrantID + + all, err := fx.creds.List(CredentialFilter{}) + require.NoError(t, err) + kinds := map[string]CredentialView{} + for _, v := range all { + kinds[v.Kind+"/"+v.ID] = v + } + login := kinds["browser_login/"+gid] + assert.Equal(t, "cursor", login.Client) + assert.Equal(t, "active", login.State) + assert.Equal(t, "rw", login.Profile) + assert.Contains(t, kinds, "client/codex") + assert.Equal(t, "active", kinds["client/cursor"].State, "an OAuth-only client is a client") + + only, err := fx.creds.List(CredentialFilter{Kind: "browser_login"}) + require.NoError(t, err) + require.Len(t, only, 1) + none, err := fx.creds.List(CredentialFilter{ExcludeClients: true}) + require.NoError(t, err) + assert.Empty(t, none, "the server edition has no client credentials and no logins") + + v, err := fx.creds.Get(CredentialRef{Client: "cursor"}) + require.NoError(t, err) + assert.Equal(t, "rw", v.Profile) + _, err = fx.creds.Get(CredentialRef{Client: "ghost"}) + require.Error(t, err) +} + +// --- binding for a client that has only logins --------------------------------------------------------- + +func TestSetBinding_OAuthOnlyClient(t *testing.T) { + fx := newOAuthFx(t) + fx.loginNew("cursor", "ro") + + v, err := fx.clients.SetBinding(fx.ctx(), fx.actor(), "cursor", "rw", nil) + require.NoError(t, err) + assert.Equal(t, "rw", v.Profile) + pin, mode, found, err := fx.sm.CurrentClientBinding("cursor") + require.NoError(t, err) + require.True(t, found) + assert.Equal(t, "rw", pin) + assert.Equal(t, auth.ProfileModeLocked, mode) + rows := fx.changeRows("assign") + require.Len(t, rows, 1) + assert.Equal(t, "cursor", rows[0]["client_id"]) + assert.Equal(t, "rw", rows[0]["profile"]) + assert.Equal(t, "ro", rows[0]["previous_profile"]) + assert.NotEmpty(t, fx.eventsOf(EventTypeClientBindingChanged)) + + sw := auth.ProfileModeSwitchable + _, err = fx.clients.SetBinding(fx.ctx(), fx.actor(), "cursor", "rw", &sw) + require.NoError(t, err) + assert.Len(t, fx.changeRows("unlock"), 1) + + _, err = fx.clients.SetBinding(fx.ctx(), fx.actor(), "cursor", "ghost", nil) + var ve *ValidationError + require.True(t, errors.As(err, &ve)) + // A client with nothing at all is still no_client_credential. + _, err = fx.clients.SetBinding(fx.ctx(), fx.actor(), "ghost", "rw", nil) + var nc *NoClientCredentialError + require.True(t, errors.As(err, &nc)) +} + +func TestSetBinding_OAuthOnlyClientIsJudgedByTheGuard(t *testing.T) { + fx := newOAuthFx(t) + fx.loginNew("cursor", "ro") + fx.guard = StrictOfflineBindingGuard{} + fx.cfg.RequireMCPAuth = false + + _, err := fx.clients.SetBinding(fx.ctx(), fx.actor(), "cursor", "rw", nil) + var ge *BindingGuardError + require.ErrorAs(t, err, &ge, "the live login is an active named binding for the guard") + pin, _, _, _ := fx.sm.CurrentClientBinding("cursor") + assert.Equal(t, "ro", pin, "a refused change writes nothing") + assert.Empty(t, fx.changeRows("assign")) +} + +func TestBulkAssign_MovesOAuthOnlyClients(t *testing.T) { + fx := newOAuthFx(t) + fx.loginNew("cursor", "ro") + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + + moved, skipped, err := fx.clients.BulkAssign(fx.ctx(), fx.actor(), "ro", "rw", nil) + require.NoError(t, err) + assert.Empty(t, skipped) + assert.Equal(t, []string{"codex", "cursor"}, moved) + pin, _, _, _ := fx.sm.CurrentClientBinding("cursor") + assert.Equal(t, "rw", pin) +} + +func TestMintingAnAPIKeyForAnOAuthOnlyClientKeepsOneBinding(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "", ApprovalChoice{Client: ClientChoice{New: &NewClientChoice{ID: "acme"}}, Profile: oauthStrp("ro")}) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + require.Nil(t, terr) + + _, secret, err := fx.clients.Add(fx.ctx(), fx.actor(), AddRequest{ID: "acme", Profile: "rw"}) + require.NoError(t, err) + assert.NotEmpty(t, secret) + pin, _, _, err := fx.sm.CurrentClientBinding("acme") + require.NoError(t, err) + assert.Equal(t, "rw", pin) + b, err := fx.sm.GetOAuthClientBinding("acme") + require.NoError(t, err) + assert.Equal(t, "rw", b.ProfilePin, "both copies carry the binding the caller asked for") +} + +// --- forget, revoke --------------------------------------------------------------------------------------- + +func TestForgetClient_DeletesTheLoginsAndTheBinding(t *testing.T) { + fx := newOAuthFx(t) + fx.loginNew("cursor", "ro") + _, err := fx.clients.Forget(fx.ctx(), fx.actor(), "cursor", false) + require.NoError(t, err) + assert.Empty(t, fx.grants()) + b, _ := fx.sm.GetOAuthClientBinding("cursor") + assert.Nil(t, b) + got, _ := fx.clients.Get("cursor") + assert.Nil(t, got) + assert.Len(t, fx.changeRows("forget"), 1) + // Forgetting something that has nothing is still the old refusal. + _, err = fx.clients.Forget(fx.ctx(), fx.actor(), "cursor", false) + var nc *NoClientCredentialError + require.True(t, errors.As(err, &nc)) +} + +func TestRevokeClient_RevokesTheKeyAndEveryLoginAndKeepsThemForDisplay(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + res, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + + r, err := fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Client: "codex"}, false) + require.NoError(t, err) + assert.True(t, r.Changed) + tok, _ := fx.sm.GetAgentTokenByName("client-codex") + assert.True(t, tok.Revoked) + gs := fx.grants() + require.Len(t, gs, 1) + assert.True(t, gs[0].Revoked) + assert.Equal(t, storage.OAuthRevokeClientRevoked, gs[0].RevokeReason) + _, _, aerr := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/codex", fx.clock.Now()) + assert.ErrorIs(t, aerr, ErrOAuthUnauthorized, "a live session's next request is refused") + assert.Len(t, fx.changeRows("revoke"), 1) + + // An API key that is already revoked with a live login still revokes the login. + fx.mintClient("zed", "ro", auth.ProfileModeLocked) + regZ := fx.register() + idZ := fx.authorize(regZ, "zed") + revZ, _ := fx.sm.ClientBindingRevision("zed") + redirectZ, err := fx.svc.Approve(fx.ctx(), idZ, ApprovalChoice{BindingRevision: revZ}) + require.NoError(t, err) + _, terr = fx.svc.Exchange(fx.tokenInput(regZ, oauthCodeOf(t, redirectZ))) + require.Nil(t, terr) + _, err = fx.clients.RevokeAPIKey(fx.ctx(), fx.actor(), "zed") + require.NoError(t, err) + r, err = fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Client: "zed"}, false) + require.NoError(t, err) + assert.True(t, r.Changed, "the revoked key does not hide a live login") + for _, g := range fx.grants() { + assert.True(t, g.Revoked, g.Client) + } +} + +func TestRevokeClient_OAuthOnlyClient(t *testing.T) { + fx := newOAuthFx(t) + fx.loginNew("cursor", "ro") + r, err := fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Client: "cursor"}, false) + require.NoError(t, err) + assert.True(t, r.Changed) + assert.Equal(t, CredentialStateRevoked, r.View.State) + require.Len(t, fx.grants(), 1) + assert.True(t, fx.grants()[0].Revoked) + b, _ := fx.sm.GetOAuthClientBinding("cursor") + assert.NotNil(t, b, "kept for display") + evs := fx.eventsOf(EventTypeCredentialsChanged) + assert.Equal(t, "revoke", evs[len(evs)-1].Payload["change"]) +} + +func TestRevokeAPIKey_LeavesTheLoginsAndTheBinding(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + res, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + + v, err := fx.clients.RevokeAPIKey(fx.ctx(), fx.actor(), "codex") + require.NoError(t, err) + assert.Equal(t, profile.CredentialStateRevoked, v.CredentialState) + _, _, aerr := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/codex", fx.clock.Now()) + assert.NoError(t, aerr, "the login keeps working") + pin, _, _, _ := fx.sm.CurrentClientBinding("codex") + assert.Equal(t, "ro", pin) + assert.False(t, fx.grants()[0].Revoked) + + _, err = fx.clients.RevokeAPIKey(fx.ctx(), fx.actor(), "codex") + var nc *NoClientCredentialError + require.True(t, errors.As(err, &nc), "no API key left") + _, err = fx.clients.RevokeAPIKey(fx.ctx(), fx.actor(), "ghost") + require.True(t, errors.As(err, &nc)) +} + +func TestCredentialsRevoke_OneGrant(t *testing.T) { + fx := newOAuthFx(t) + _, res := fx.loginNew("cursor", "ro") + gid := fx.grants()[0].GrantID + r, err := fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Client: "cursor", Grant: gid}, false) + require.NoError(t, err) + assert.True(t, r.Changed) + assert.Equal(t, "browser_login", r.View.Kind) + assert.Equal(t, "revoked", r.View.State) + _, _, aerr := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", fx.clock.Now()) + assert.ErrorIs(t, aerr, ErrOAuthUnauthorized) + + _, err = fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Client: "cursor", Grant: "nope"}, false) + var ce *CredentialError + require.True(t, errors.As(err, &ce)) + assert.Equal(t, 404, ce.Status) + _, err = fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Token: "x", Grant: gid}, false) + require.Error(t, err) +} + +// --- profiles and the funnel --------------------------------------------------------------------------------- + +func TestProfilesService_OAuthOnlyClientIsAUserOfItsProfile(t *testing.T) { + h := newProfilesHarness(t) + ctx := context.Background() + commitOAuthOnlyClient(t, h.rt.StorageManager(), "reg1", "grantAAAAAAAAAAAAAAAAAA", "acme", "ro", auth.ProfileModeLocked) + + u, err := h.svc.UsedBy("ro") + require.NoError(t, err) + require.Len(t, u.Clients, 1) + assert.Equal(t, "acme", u.Clients[0].ID) + + // Delete is refused while it points at the profile. + _, err = h.svc.Delete(ctx, h.actor(), "ro", "", false) + var inUse *ProfileInUseError + require.True(t, errors.As(err, &inUse)) + require.Len(t, inUse.UsedBy.Clients, 1) + + // A revoked login no longer counts. + _, err = h.rt.StorageManager().RevokeOAuthGrant("grantAAAAAAAAAAAAAAAAAA", storage.OAuthRevokeAdmin, time.Now()) + require.NoError(t, err) + u, err = h.svc.UsedBy("ro") + require.NoError(t, err) + assert.Empty(t, u.Clients) +} + +func TestProfilesService_ReassignAndRenameMoveTheOAuthOnlyClient(t *testing.T) { + h := newProfilesHarness(t) + ctx := context.Background() + sm := h.rt.StorageManager() + commitOAuthOnlyClient(t, sm, "reg1", "grantAAAAAAAAAAAAAAAAAA", "acme", "ro", auth.ProfileModeLocked) + + _, err := h.svc.Rename(ctx, h.actor(), "ro", "ro2") + require.NoError(t, err) + pin, _, _, _ := sm.CurrentClientBinding("acme") + assert.Equal(t, "ro2", pin, "rename moves its pin") + + _, err = h.svc.Delete(ctx, h.actor(), "ro2", "full", false) + require.NoError(t, err) + pin, _, _, _ = sm.CurrentClientBinding("acme") + assert.Equal(t, "full", pin, "reassign_to moves it") +} + +func TestMutateConfig_FailedApplyRestoresAnOAuthOnlyClient(t *testing.T) { + rt := newFunnelRuntime(t) + sm := rt.StorageManager() + commitOAuthOnlyClient(t, sm, "reg1", "grantAAAAAAAAAAAAAAAAAA", "acme", "ro", auth.ProfileModeLocked) + + blocker := filepath.Join(t.TempDir(), "blocker") + require.NoError(t, os.WriteFile(blocker, []byte("x"), 0o600)) + rt.configSvc.UpdatePath(filepath.Join(blocker, "mcp_config.json")) + + _, _, err := rt.MutateConfig(context.Background(), funnelActor(), func(d *config.Config) (ChangeHint, error) { + d.Profiles[0].Name = "ro2" + return ChangeHint{Kind: profile.ChangeRename, Profile: "ro2", PreviousProfile: "ro"}, nil + }, TokenRewrite{From: "ro", To: "ro2"}) + require.Error(t, err) + pin, _, _, _ := sm.CurrentClientBinding("acme") + assert.Equal(t, "ro", pin, "the failed commit restores the browser-login client") + b, _ := sm.GetOAuthClientBinding("acme") + assert.Equal(t, "ro", b.ProfilePin) +} + +// The funnel judges the whole candidate, browser logins included: a config +// that turns auth off while a live login holds a named binding is refused. +func TestMutateConfig_GuardSeesAnOAuthOnlyBinding(t *testing.T) { + rt := newFunnelRuntime(t) + sm := rt.StorageManager() + commitOAuthOnlyClient(t, sm, "reg1", "grantAAAAAAAAAAAAAAAAAA", "acme", "ro", auth.ProfileModeLocked) + rt.SetBindingGuard(ConservativeBindingGuard{}) + + _, _, err := rt.MutateConfig(context.Background(), funnelActor(), func(d *config.Config) (ChangeHint, error) { + d.RequireMCPAuth = false + return ChangeHint{}, nil + }, TokenRewrite{}) + var ge *BindingGuardError + require.ErrorAs(t, err, &ge) + require.NotEmpty(t, ge.Bindings) + assert.Equal(t, "acme", ge.Bindings[0].ClientID) + + // Once the login is revoked nothing is bound. + _, err = sm.RevokeOAuthGrant("grantAAAAAAAAAAAAAAAAAA", storage.OAuthRevokeAdmin, time.Now()) + require.NoError(t, err) + _, _, err = rt.MutateConfig(context.Background(), funnelActor(), func(d *config.Config) (ChangeHint, error) { + d.RequireMCPAuth = false + return ChangeHint{}, nil + }, TokenRewrite{}) + require.NoError(t, err) +} + +// --- the switch --------------------------------------------------------------------------------------------------- + +// Applying a config in which the switch goes off cancels every pending and +// approved request BEFORE the new config is visible, on the commit path both +// the API update and the file reload end in, with no event delivered. +func TestCommit_TurningTheSwitchOffCancelsSignInRequests(t *testing.T) { + rt := newFunnelRuntime(t) + _, err := rt.Commit("test_on", func(tx *CommitTx) error { + return tx.MutateGlobal(func(c *config.Config) error { c.MCPOAuthEnabled = true; return nil }) + }) + require.NoError(t, err) + svc := rt.OAuthLoginService() + require.True(t, svc.Enabled()) + + reg, rerr, err := svc.Register(mcpRegistration()) + require.NoError(t, err) + require.Nil(t, rerr) + regID := reg["client_id"].(string) + id, aerr := svc.BeginAuthorization(AuthorizeInput{ + Origin: oauthTestOrigin, ClientID: regID, RedirectURI: oauthTestRedirect, State: "s", + CodeChallenge: oauthTestChallenge(), Method: "S256", Resource: oauthTestOrigin + "/mcp/oauth/cursor", ResponseType: "code", + }) + require.Nil(t, aerr) + redirect, err := svc.Approve(context.Background(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + require.NoError(t, err) + code := oauthCodeOf(t, redirect) + pendingID, aerr := svc.BeginAuthorization(AuthorizeInput{ + Origin: oauthTestOrigin, ClientID: regID, RedirectURI: oauthTestRedirect, State: "s", + CodeChallenge: oauthTestChallenge(), Method: "S256", Resource: oauthTestOrigin + "/mcp/oauth", ResponseType: "code", + }) + require.Nil(t, aerr) + + _, err = rt.Commit("test_off", func(tx *CommitTx) error { + return tx.MutateGlobal(func(c *config.Config) error { c.MCPOAuthEnabled = false; return nil }) + }) + require.NoError(t, err) + _, err = rt.Commit("test_on_again", func(tx *CommitTx) error { + return tx.MutateGlobal(func(c *config.Config) error { c.MCPOAuthEnabled = true; return nil }) + }) + require.NoError(t, err) + + _, terr := svc.Exchange(TokenInput{Origin: oauthTestOrigin, Code: code, RedirectURI: oauthTestRedirect, ClientID: regID, CodeVerifier: oauthTestVerifier}) + requireInvalidGrant(t, terr) + _, err = svc.Approve(context.Background(), pendingID, ApprovalChoice{Client: ClientChoice{ID: "x"}}) + assert.ErrorIs(t, err, ErrOAuthRequestNotFound) + used, _ := rt.StorageManager().OAuthLoginEverUsed() + assert.False(t, used) +} + +func mcpRegistration() mcplogin.RegistrationRequest { + return mcplogin.RegistrationRequest{RedirectURIs: []string{oauthTestRedirect}, ClientName: "Cursor"} +} + +// --- startup ------------------------------------------------------------------------------------------------------ + +// RepairOAuthClientBindings runs once at startup; on a database that never +// used browser login it opens no write transaction (the runtime is built in +// every funnel test: a never-used database stays free of the OAuth buckets). +func TestStartup_RepairIsANoOpWithoutBrowserLogin(t *testing.T) { + rt := newFunnelRuntime(t) + rt.repairOAuthBindings() // a second run changes nothing and does not panic + b, err := rt.StorageManager().ListOAuthClientBindings() + require.NoError(t, err) + assert.Empty(t, b) + used, _ := rt.StorageManager().OAuthLoginEverUsed() + assert.False(t, used) +} diff --git a/internal/runtime/oauth_login_consent.go b/internal/runtime/oauth_login_consent.go new file mode 100644 index 000000000..e3427a312 --- /dev/null +++ b/internal/runtime/oauth_login_consent.go @@ -0,0 +1,822 @@ +package runtime + +import ( + "context" + "errors" + "fmt" + "net/http" + "sort" + "strings" + "time" + "unicode/utf8" + + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/connect" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// --- GET /oauth/authorize ---------------------------------------------------------- + +// AuthorizeInput is the query of GET /oauth/authorize. Origin is the origin of +// this request (mcplogin.Origin). +type AuthorizeInput struct { + Origin, ClientID, RedirectURI, State, CodeChallenge, Method, Resource, ResponseType string +} + +// AuthorizeErrorKind says what the HTTP layer does with a refusal. +type AuthorizeErrorKind int + +const ( + // AuthorizeNoRedirect: an HTML error page (400), never a redirect: the + // client id or redirect URI cannot be trusted. + AuthorizeNoRedirect AuthorizeErrorKind = iota + // AuthorizeNotFound: an HTML 404 page, no redirect (the per-client resource + // names a client that does not exist). + AuthorizeNotFound + // AuthorizeRedirect: redirect to the registered redirect URI with error. + AuthorizeRedirect +) + +// AuthorizeError is a refusal of BeginAuthorization. +type AuthorizeError struct { + Kind AuthorizeErrorKind + Code string // OAuth error code (redirect kind) + Description string + // RedirectURI and State are set for AuthorizeRedirect. + RedirectURI string + State string +} + +func (e *AuthorizeError) Error() string { return e.Code + ": " + e.Description } + +// RedirectURL builds the error redirect from the registered redirect URI, +// keeping its query and appending percent-encoded parameters; state only when +// the client sent one. +func (e *AuthorizeError) RedirectURL() (string, error) { + params := map[string]string{"error": e.Code, "error_description": e.Description} + if e.State != "" { + params["state"] = e.State + } + return mcplogin.BuildRedirect(e.RedirectURI, params) +} + +func authzNoRedirect(desc string) *AuthorizeError { + return &AuthorizeError{Kind: AuthorizeNoRedirect, Code: "invalid_request", Description: desc} +} + +// BeginAuthorization validates an authorization request in the order of +// contracts/oauth-endpoints.md, stores it (10 minutes), marks the registration +// authorized and publishes oauth.authorization_pending. It returns the request +// id the consent URL carries. +func (s *OAuthLoginService) BeginAuthorization(in AuthorizeInput) (string, *AuthorizeError) { + if !s.Enabled() { + return "", &AuthorizeError{Kind: AuthorizeNotFound, Code: "not_found", Description: "not found"} + } + // 1. Unknown client_id, or a redirect URI the registration does not hold: + // no redirect, because neither can be trusted. + reg, err := s.store.GetOAuthRegistration(in.ClientID) + if err != nil || reg == nil { + return "", authzNoRedirect("unknown client_id") + } + redirect, ok := mcplogin.MatchRedirect(reg.RedirectURIs, in.RedirectURI) + if !ok { + return "", authzNoRedirect("redirect_uri is not registered") + } + fail := func(code, desc string) *AuthorizeError { + return &AuthorizeError{Kind: AuthorizeRedirect, Code: code, Description: desc, RedirectURI: redirect, State: in.State} + } + // 2. A per-client resource naming a client that does not exist: 404, no + // redirect, checked before the general resource rule (FR-015). + pathClient, generic, resourceOK := mcplogin.ParseResource(in.Origin, in.Resource) + if resourceOK && !generic && !s.clientExists(pathClient) { + return "", &AuthorizeError{Kind: AuthorizeNotFound, Code: "not_found", Description: "unknown client"} + } + // 3. The rest are redirectable. + if in.ResponseType != "code" { + return "", fail("unsupported_response_type", "only response_type=code is supported") + } + if in.Method != "S256" || !mcplogin.ValidChallenge(in.CodeChallenge) { + return "", fail("invalid_request", "a PKCE S256 code_challenge is required") + } + if !resourceOK { + return "", fail("invalid_target", "resource must be an MCPProxy browser-login address on this origin") + } + reqs, err := s.requests() + if err != nil { + s.logger.Error("browser login: cannot build the request store", zap.Error(err)) + return "", fail("temporarily_unavailable", "try again") + } + req, err := reqs.Create(mcplogin.Request{ + RegistrationID: reg.ClientID, RedirectURI: redirect, State: in.State, CodeChallenge: in.CodeChallenge, + Resource: in.Resource, Issuer: in.Origin, PathClient: pathClient, + }) + if err != nil { + if errors.Is(err, mcplogin.ErrTooManyPending) { + return "", fail("temporarily_unavailable", "too many sign-in requests are waiting") + } + s.logger.Error("browser login: cannot store the request", zap.Error(err)) + return "", fail("temporarily_unavailable", "try again") + } + if err := s.store.MarkOAuthRegistrationAuthorized(reg.ClientID, s.now()); err != nil { + s.logger.Warn("browser login: cannot mark the registration authorized", zap.Error(err)) + } + if s.publish != nil { + s.publish(newEvent(EventTypeOAuthAuthorizationPending, map[string]any{ + "request_id": req.ID, "client_id": pathClient, "client_label": clientLabel(reg.ReportedName), + })) + } + return req.ID, nil +} + +func clientLabel(reported string) string { + if strings.TrimSpace(reported) == "" { + return "an application" + } + return reported +} + +// --- client lookups ------------------------------------------------------------------ + +// clientExists: a connect-registry id (supported or not), or an existing client +// record (API key in any state) or browser-login binding. +func (s *OAuthLoginService) clientExists(clientID string) bool { + if connect.FindClient(clientID) != nil { + return true + } + return s.hasClientRecords(clientID) +} + +// hasClientRecords: the client has an API-key record or a browser-login entry +// (a registry id alone does not count). +func (s *OAuthLoginService) hasClientRecords(clientID string) bool { + rec, err := s.store.GetAgentTokenByName(auth.ClientTokenName(clientID)) + if err == nil && rec != nil { + return true + } + b, err := s.store.GetOAuthClientBinding(clientID) + return err == nil && b != nil +} + +// --- views --------------------------------------------------------------------------- + +// BindingView is a client's binding and its revision. +type BindingView struct { + Profile string `json:"profile"` + Mode string `json:"mode"` + Revision string `json:"revision"` +} + +// AuthorizationClientView is the fixed client of a per-client address. +type AuthorizationClientView struct { + ID string `json:"id"` + DisplayName string `json:"display_name"` + Exists bool `json:"exists"` + HasAPIKey bool `json:"has_api_key"` + Logins int `json:"logins"` + Binding *BindingView `json:"binding,omitempty"` +} + +// ExistingClientView is one choice of the generic address. +type ExistingClientView struct { + ID string `json:"id"` + DisplayName string `json:"display_name"` + Binding *BindingView `json:"binding,omitempty"` +} + +// SuggestedClient is the new-client suggestion derived from the reported name. +type SuggestedClient struct { + ID string `json:"id"` + DisplayName string `json:"display_name"` +} + +// ProfileChoice names a profile the page may offer. +type ProfileChoice struct { + Name string `json:"name"` +} + +// PreviousLogin is a live login of THIS registration. +type PreviousLogin struct { + GrantID string `json:"grant_id"` + ApprovedAt time.Time `json:"approved_at"` +} + +// GuardVerdict is the binding guard's refusal as the page shows it. +type GuardVerdict struct { + Code string `json:"code"` + Bindings []BindingRef `json:"bindings"` + Fixes []GuardFix `json:"fixes"` +} + +// AuthorizationSummary is one row of the pending list. +type AuthorizationSummary struct { + ID string `json:"id"` + ClientLabel string `json:"client_label"` + CreatedAt time.Time `json:"created_at"` + ExpiresAt time.Time `json:"expires_at"` +} + +// AuthorizationView is GET /oauth/authorizations/{id} (contracts/rest-admin.md). +type AuthorizationView struct { + ID string `json:"id"` + Status string `json:"status"` + ExpiresAt time.Time `json:"expires_at"` + ReportedName string `json:"reported_name"` + RedirectURI string `json:"redirect_uri"` + Resource string `json:"resource"` + AddressKind string `json:"address_kind"` + Client *AuthorizationClientView `json:"client,omitempty"` + ExistingClients []ExistingClientView `json:"existing_clients,omitempty"` + SuggestedNewClient *SuggestedClient `json:"suggested_new_client,omitempty"` + Profiles []ProfileChoice `json:"profiles"` + ProfileRequired bool `json:"profile_required"` + PreviousLogin *PreviousLogin `json:"previous_login,omitempty"` + Guard *GuardVerdict `json:"guard"` +} + +// PreviewAccess is the access sentence of a proposed choice. +type PreviewAccess struct { + Client string `json:"client"` + Profile string `json:"profile"` + Mode string `json:"mode"` + SameAccessAsExistingClient bool `json:"same_access_as_existing_client"` +} + +// PreviewView is POST /oauth/authorizations/{id}/preview. +type PreviewView struct { + Complete bool `json:"complete"` + Access *PreviewAccess `json:"access,omitempty"` + Guard *GuardVerdict `json:"guard"` +} + +// ListPending returns the pending requests, newest first. +func (s *OAuthLoginService) ListPending() []AuthorizationSummary { + reqs := s.existingRequests() + out := []AuthorizationSummary{} + if reqs == nil || !s.Enabled() { + return out + } + for _, r := range reqs.ListPending() { + label := "an application" + if reg, err := s.store.GetOAuthRegistration(r.RegistrationID); err == nil && reg != nil { + label = clientLabel(reg.ReportedName) + } + out = append(out, AuthorizationSummary{ID: r.ID, ClientLabel: label, CreatedAt: r.CreatedAt, ExpiresAt: r.ExpiresAt}) + } + sort.Slice(out, func(i, j int) bool { return out[i].CreatedAt.After(out[j].CreatedAt) }) + return out +} + +// pendingRequest returns the request when it is still pending. +func (s *OAuthLoginService) pendingRequest(id string) (mcplogin.Request, *mcplogin.Store, error) { + reqs := s.existingRequests() + if reqs == nil || !s.Enabled() { + return mcplogin.Request{}, nil, ErrOAuthRequestNotFound + } + req, ok := reqs.Get(id) + if !ok || req.Status != mcplogin.StatusPending { + return mcplogin.Request{}, nil, ErrOAuthRequestNotFound + } + return req, reqs, nil +} + +// Describe returns the consent page's view of a pending request. The reported +// name is shown and NEVER selects anything. +func (s *OAuthLoginService) Describe(ctx context.Context, requestID string) (*AuthorizationView, error) { + req, _, err := s.pendingRequest(requestID) + if err != nil { + return nil, err + } + reg, err := s.store.GetOAuthRegistration(req.RegistrationID) + if err != nil || reg == nil { + return nil, ErrOAuthRequestNotFound + } + cfg := s.cfg() + all, err := s.store.ListAgentTokens() + if err != nil { + return nil, fmt.Errorf("cannot read client credentials: %w", err) + } + grants, err := s.store.ListOAuthGrants() + if err != nil { + return nil, fmt.Errorf("cannot read browser logins: %w", err) + } + bindings, err := s.store.ListOAuthClientBindings() + if err != nil { + return nil, fmt.Errorf("cannot read browser-login bindings: %w", err) + } + now := s.now() + v := &AuthorizationView{ + ID: req.ID, Status: string(req.Status), ExpiresAt: req.ExpiresAt, ReportedName: reg.ReportedName, + RedirectURI: req.RedirectURI, Resource: req.Resource, Profiles: profileChoices(cfg), + } + liveByClient := map[string]int{} + for i := range grants { + g := &grants[i] + if !g.Revoked && g.RefreshExpiresAt.After(now) { + liveByClient[g.Client]++ + if g.RegistrationID == reg.ClientID && (req.PathClient == "" || g.Client == req.PathClient) && + (v.PreviousLogin == nil || g.ApprovedAt.After(v.PreviousLogin.ApprovedAt)) { + v.PreviousLogin = &PreviousLogin{GrantID: g.GrantID, ApprovedAt: g.ApprovedAt} + } + } + } + bindingOf := func(id string) (*BindingView, bool) { + pin, mode, found, err := s.store.CurrentClientBinding(id) + if err != nil || !found { + return nil, false + } + rev, err := s.store.ClientBindingRevision(id) + if err != nil { + return nil, false + } + return &BindingView{Profile: pin, Mode: mode, Revision: rev}, true + } + + if req.PathClient != "" { + v.AddressKind = "client" + cv := &AuthorizationClientView{ID: req.PathClient, DisplayName: s.displayNameOf(req.PathClient, all, bindings), + Logins: liveByClient[req.PathClient]} + rec := clientRecord(all, req.PathClient) + cv.HasAPIKey = rec != nil && rec.Kind == auth.KindClient + _, hasEntry := bindings[req.PathClient] + cv.Exists = cv.HasAPIKey || hasEntry + if b, ok := bindingOf(req.PathClient); ok && cv.Exists { + cv.Binding = b + } + v.Client = cv + v.ProfileRequired = len(v.Profiles) > 0 && cv.Binding == nil + if cv.Binding != nil { + if perr := s.checkCandidateGuard(cv.ID, cv.Binding.Profile, cv.Binding.Mode); perr != nil { + var ge *BindingGuardError + if errors.As(perr, &ge) { + v.Guard = verdictOf(ge) + } + } + } + } else { + v.AddressKind = "generic" + ids := map[string]bool{} + for i := range all { + if all[i].Kind == auth.KindClient && all[i].UserID == "" { + ids[all[i].ClientID] = true + } + } + for id := range bindings { + ids[id] = true + } + sorted := make([]string, 0, len(ids)) + for id := range ids { + sorted = append(sorted, id) + } + sort.Strings(sorted) + v.ExistingClients = []ExistingClientView{} + for _, id := range sorted { + ev := ExistingClientView{ID: id, DisplayName: s.displayNameOf(id, all, bindings)} + if b, ok := bindingOf(id); ok { + ev.Binding = b + } + v.ExistingClients = append(v.ExistingClients, ev) + } + v.ProfileRequired = len(v.Profiles) > 0 + v.SuggestedNewClient = s.suggestNewClient(reg.ReportedName, ids) + } + return v, nil +} + +func profileChoices(cfg *config.Config) []ProfileChoice { + out := []ProfileChoice{} + if cfg != nil { + for i := range cfg.Profiles { + out = append(out, ProfileChoice{Name: cfg.Profiles[i].Name}) + } + } + return out +} + +func verdictOf(ge *BindingGuardError) *GuardVerdict { + return &GuardVerdict{Code: ge.Code(), Bindings: ge.Bindings, Fixes: ge.Fixes} +} + +// displayNameOf is the registry name, else the record's display name, else the id. +func (s *OAuthLoginService) displayNameOf(id string, all []auth.AgentToken, bindings map[string]storage.OAuthClientBinding) string { + if def := connect.FindClient(id); def != nil && def.Name != "" { + return def.Name + } + if rec := clientRecord(all, id); rec != nil && rec.DisplayName != "" { + return rec.DisplayName + } + if b, ok := bindings[id]; ok && b.DisplayName != "" { + return b.DisplayName + } + return id +} + +// suggestNewClient derives an id from the reported name: lower-case slug of +// letters, digits, '-' and '_', at most 56 characters, made unique against the +// registry and the existing clients ("-2", "-3", ...). It only SUGGESTS: the +// page shows it in an editable field and the administrator submits what they +// want. The suggested display name is the reported name. +func (s *OAuthLoginService) suggestNewClient(reported string, existing map[string]bool) *SuggestedClient { + var b strings.Builder + dash := false + for _, r := range strings.ToLower(reported) { + switch { + case r >= 'a' && r <= 'z', r >= '0' && r <= '9': + b.WriteRune(r) + dash = false + case r == '_' || r == '-': + if b.Len() > 0 && !dash { + b.WriteRune('-') + dash = true + } + default: + if b.Len() > 0 && !dash { + b.WriteRune('-') + dash = true + } + } + } + base := strings.Trim(b.String(), "-_") + if base == "" { + base = "client" + } + if len(base) > 50 { + base = strings.Trim(base[:50], "-_") + } + taken := func(id string) bool { + return existing[id] || connect.FindClient(id) != nil || s.hasClientRecords(id) + } + id := base + for n := 2; taken(id); n++ { + id = fmt.Sprintf("%s-%d", base, n) + } + name := strings.TrimSpace(reported) + if name == "" { + name = id + } + if utf8.RuneCountInString(name) > auth.MaxClientDisplayName { + name = string([]rune(name)[:auth.MaxClientDisplayName]) + } + return &SuggestedClient{ID: id, DisplayName: name} +} + +// --- choice ------------------------------------------------------------------------------ + +// NewClientChoice is a client the approval creates. +type NewClientChoice struct { + ID string `json:"id"` + DisplayName string `json:"display_name,omitempty"` +} + +// ClientChoice is the client of an approval: an existing id, or a new one. +type ClientChoice struct { + ID string `json:"id,omitempty"` + New *NewClientChoice `json:"new,omitempty"` +} + +// ApprovalChoice is the body of preview and approve. Profile nil means "not +// chosen" (an empty string is the explicit choice All servers). +type ApprovalChoice struct { + Client ClientChoice `json:"client"` + Profile *string `json:"profile,omitempty"` + Mode string `json:"mode,omitempty"` + BindingRevision string `json:"binding_revision,omitempty"` + ReplaceGrant string `json:"replace_grant,omitempty"` +} + +// Typed refusals of Preview, Approve and Deny. The REST layer maps them with +// OAuthErrorStatus. +var ( + ErrOAuthRequestNotFound = errors.New("authorization request not found") + ErrOAuthAlreadyDecided = errors.New("authorization request already decided") + ErrOAuthBindingChanged = errors.New("the client's binding changed since it was displayed") + ErrOAuthClientFixed = errors.New("this address fixes the client") + ErrOAuthClientRequired = errors.New("choose a client") + ErrOAuthClientUnknown = errors.New("unknown client") + ErrOAuthProfileRequired = errors.New("choose a profile") + ErrOAuthProfileNotFound = errors.New("unknown profile") + ErrOAuthIdentityExists = errors.New("a client with this id already exists") + ErrOAuthReservedIdentity = errors.New("this id belongs to a supported client") +) + +// OAuthErrorStatus maps a refusal to its wire code and HTTP status +// (contracts/rest-admin.md). ok is false for an error that is not one of them. +func OAuthErrorStatus(err error) (code string, status int, ok bool) { + var ge *BindingGuardError + var ve *ValidationError + switch { + case errors.Is(err, ErrOAuthRequestNotFound): + return "request_not_found", http.StatusNotFound, true + case errors.Is(err, ErrOAuthAlreadyDecided): + return "already_decided", http.StatusConflict, true + case errors.Is(err, ErrOAuthBindingChanged): + return "binding_changed", http.StatusConflict, true + case errors.As(err, &ge): + return ge.Code(), http.StatusConflict, true + case errors.Is(err, ErrOAuthClientFixed): + return "client_fixed", http.StatusUnprocessableEntity, true + case errors.Is(err, ErrOAuthClientRequired): + return "client_required", http.StatusUnprocessableEntity, true + case errors.Is(err, ErrOAuthClientUnknown): + return "client_not_found", http.StatusNotFound, true + case errors.Is(err, ErrOAuthProfileRequired): + return "profile_required", http.StatusUnprocessableEntity, true + case errors.Is(err, ErrOAuthProfileNotFound): + return "profile_not_found", http.StatusNotFound, true + case errors.Is(err, ErrOAuthIdentityExists): + return "identity_exists", http.StatusUnprocessableEntity, true + case errors.Is(err, ErrOAuthReservedIdentity): + return "reserved_identity", http.StatusUnprocessableEntity, true + case errors.As(err, &ve): + return "invalid_" + ve.Field, http.StatusUnprocessableEntity, true + } + return "", 0, false +} + +// resolvedChoice is a validated choice. +type resolvedChoice struct { + clientID string + newClient bool + display string + pin, mode string + revision string // expected binding revision at commit + hasBinding bool + replace string + complete bool +} + +// resolveChoice validates a choice against the request and the stored state. +// An incomplete choice (a required selection is missing) is not an error: it is +// reported as complete=false so a preview can say so. Invalid values are +// errors in both cases. +func (s *OAuthLoginService) resolveChoice(req mcplogin.Request, c ApprovalChoice) (*resolvedChoice, error) { + cfg := s.cfg() + rc := &resolvedChoice{complete: true} + + // 1. Which client. + switch { + case req.PathClient != "": + if c.Client.New != nil || (c.Client.ID != "" && c.Client.ID != req.PathClient) { + return nil, ErrOAuthClientFixed + } + rc.clientID = req.PathClient + if !s.hasClientRecords(rc.clientID) { + def := connect.FindClient(rc.clientID) + if def == nil { + return nil, ErrOAuthClientUnknown // the client vanished since authorize + } + rc.newClient, rc.display = true, def.Name + } + case c.Client.New != nil: + if c.Client.ID != "" { + return nil, &ValidationError{Field: "client", Message: "choose an existing client or a new one, not both"} + } + n := c.Client.New + if !auth.ValidClientID(n.ID) { + return nil, &ValidationError{Field: "client_new_id", Message: fmt.Sprintf( + "invalid client id %q: must be lower-case letters, digits, '-' or '_', start with a letter or digit, and be at most 56 characters", n.ID)} + } + if connect.FindClient(n.ID) != nil { + return nil, ErrOAuthReservedIdentity + } + if s.hasClientRecords(n.ID) { + return nil, ErrOAuthIdentityExists + } + if utf8.RuneCountInString(n.DisplayName) > auth.MaxClientDisplayName { + return nil, &ValidationError{Field: "client_new_display_name", Message: "display name is too long"} + } + rc.clientID, rc.newClient, rc.display = n.ID, true, n.DisplayName + case c.Client.ID != "": + if !s.hasClientRecords(c.Client.ID) { + return nil, ErrOAuthClientUnknown + } + rc.clientID = c.Client.ID + default: + rc.complete = false + } + if !rc.complete { + return rc, nil + } + + // 2. The binding: kept for a client that has one, chosen for a new one. + if !rc.newClient { + pin, mode, found, err := s.store.CurrentClientBinding(rc.clientID) + if err != nil { + return nil, err + } + if !found { + return nil, ErrOAuthClientUnknown + } + rev, err := s.store.ClientBindingRevision(rc.clientID) + if err != nil { + return nil, err + } + if c.BindingRevision != rev { + return nil, ErrOAuthBindingChanged + } + rc.pin, rc.mode, rc.revision, rc.hasBinding = pin, mode, rev, true + } else { + rc.revision = storage.OAuthBindingAbsent + if c.Profile == nil { + if cfg != nil && len(cfg.Profiles) > 0 { + rc.complete = false // profiles exist: nothing is pre-selected + return rc, nil + } + c.Profile = new(string) + } + pin := *c.Profile + if pin != "" && !profileConfigured(cfg, pin) { + return nil, ErrOAuthProfileNotFound + } + var modeArg *string + if c.Mode != "" { + m := c.Mode + modeArg = &m + } + mode, err := resolveMode(pin, modeArg, "") + if err != nil { + return nil, err + } + rc.pin, rc.mode = pin, mode + } + + // 3. Replace the previous login: only a live login of THIS registration + // and of this client; anything else is ignored, never revoked. + if c.ReplaceGrant != "" { + if g, err := s.store.GetOAuthGrant(c.ReplaceGrant); err == nil && g != nil && g.Client == rc.clientID && + !g.Revoked && g.RefreshExpiresAt.After(s.now()) && g.RegistrationID == req.RegistrationID { + rc.replace = g.GrantID + } + } + return rc, nil +} + +func profileConfigured(cfg *config.Config, name string) bool { + if cfg == nil { + return false + } + for i := range cfg.Profiles { + if cfg.Profiles[i].Name == name { + return true + } + } + return false +} + +// checkCandidateGuard runs the binding guard over the state this client's login +// would create (its entry added or replaced with Live true). +func (s *OAuthLoginService) checkCandidateGuard(clientID, pin, mode string) error { + cur, cand, err := s.guardStatesFor(clientID, pin, mode) + if err != nil { + return err + } + return CheckBindingGuard(s.guard(), cur, cand) +} + +// Preview is the read-only verdict of a proposed choice. It writes nothing. +// A guard refusal is part of the answer, not an error. +func (s *OAuthLoginService) Preview(ctx context.Context, requestID string, c ApprovalChoice) (*PreviewView, error) { + req, _, err := s.pendingRequest(requestID) + if err != nil { + return nil, err + } + rc, err := s.resolveChoice(req, c) + if err != nil { + return nil, err + } + out := &PreviewView{Complete: rc.complete} + if !rc.complete { + return out, nil + } + out.Access = &PreviewAccess{Client: rc.clientID, Profile: rc.pin, Mode: rc.mode, SameAccessAsExistingClient: rc.hasBinding} + if gerr := s.checkCandidateGuard(rc.clientID, rc.pin, rc.mode); gerr != nil { + var ge *BindingGuardError + if errors.As(gerr, &ge) { + out.Guard = verdictOf(ge) + return out, nil + } + return nil, gerr + } + return out, nil +} + +// --- approve and deny ---------------------------------------------------------------------- + +// Approve records the administrator's decision on the in-memory request and +// returns the redirect carrying the single-use code. It stores NO registration, +// login, binding or marker: the login is stored by the token exchange. It +// writes the `approve` activity row (the one thing it persists), naming the +// request's actor with the request id, and publishes +// oauth.authorization_decided. It runs under bindingWriteMu, so no binding +// write interleaves between the revision check and the decision. +func (s *OAuthLoginService) Approve(ctx context.Context, requestID string, c ApprovalChoice) (string, error) { + s.mu.Lock() + defer s.mu.Unlock() + req, reqs, err := s.pendingRequestForDecision(requestID) + if err != nil { + return "", err + } + rc, err := s.resolveChoice(req, c) + if err != nil { + return "", err + } + if !rc.complete { + if rc.clientID == "" { + return "", ErrOAuthClientRequired + } + return "", ErrOAuthProfileRequired + } + if gerr := s.checkCandidateGuard(rc.clientID, rc.pin, rc.mode); gerr != nil { + return "", gerr + } + actor, _ := RequestActor(ctx) + if actor.Surface == "" { + actor.Surface = profile.SurfaceAPI + } + code, err := reqs.Approve(requestID, mcplogin.Decision{ + ClientID: rc.clientID, NewClient: rc.newClient, DisplayName: rc.display, Profile: rc.pin, Mode: rc.mode, + BindingRevision: rc.revision, ReplaceGrantID: rc.replace, ActorKind: actor.Kind, ActorName: actor.Name, + }) + if err != nil { + return "", mapRequestStoreError(err) + } + writeChangeRecord(ctx, s.activity, s.logger, s.now(), actor, changeRecord{ + change: profile.ChangeApprove, profile: rc.pin, clientID: rc.clientID, tokenName: auth.ClientTokenName(rc.clientID), + meta: map[string]interface{}{"request_id": requestID}, + }) + s.publishDecided(requestID, string(mcplogin.StatusApproved)) + params := map[string]string{"code": code} + if req.State != "" { + params["state"] = req.State + } + return mcplogin.BuildRedirect(req.RedirectURI, params) +} + +// Deny refuses the request: the redirect carries error=access_denied. +func (s *OAuthLoginService) Deny(ctx context.Context, requestID string) (string, error) { + s.mu.Lock() + defer s.mu.Unlock() + req, reqs, err := s.pendingRequestForDecision(requestID) + if err != nil { + return "", err + } + if err := reqs.Deny(requestID); err != nil { + return "", mapRequestStoreError(err) + } + actor, _ := RequestActor(ctx) + if actor.Surface == "" { + actor.Surface = profile.SurfaceAPI + } + writeChangeRecord(ctx, s.activity, s.logger, s.now(), actor, changeRecord{ + change: profile.ChangeDeny, clientID: req.PathClient, tokenName: authTokenNameOrEmpty(req.PathClient), + meta: map[string]interface{}{"request_id": requestID}, + }) + s.publishDecided(requestID, string(mcplogin.StatusDenied)) + params := map[string]string{"error": "access_denied", "error_description": "the administrator denied the request"} + if req.State != "" { + params["state"] = req.State + } + return mcplogin.BuildRedirect(req.RedirectURI, params) +} + +func authTokenNameOrEmpty(clientID string) string { + if clientID == "" { + return "" + } + return auth.ClientTokenName(clientID) +} + +// pendingRequestForDecision is pendingRequest, but a request that was decided +// already answers ErrOAuthAlreadyDecided instead of not-found. +func (s *OAuthLoginService) pendingRequestForDecision(id string) (mcplogin.Request, *mcplogin.Store, error) { + reqs := s.existingRequests() + if reqs == nil || !s.Enabled() { + return mcplogin.Request{}, nil, ErrOAuthRequestNotFound + } + req, ok := reqs.Get(id) + if !ok { + return mcplogin.Request{}, nil, ErrOAuthRequestNotFound + } + switch req.Status { + case mcplogin.StatusPending: + return req, reqs, nil + case mcplogin.StatusCancelled: + return mcplogin.Request{}, nil, ErrOAuthRequestNotFound + default: + return mcplogin.Request{}, nil, ErrOAuthAlreadyDecided + } +} + +func mapRequestStoreError(err error) error { + switch { + case errors.Is(err, mcplogin.ErrAlreadyDecided): + return ErrOAuthAlreadyDecided + case errors.Is(err, mcplogin.ErrRequestNotFound): + return ErrOAuthRequestNotFound + } + return err +} diff --git a/internal/runtime/oauth_login_exchange_test.go b/internal/runtime/oauth_login_exchange_test.go new file mode 100644 index 000000000..31879d714 --- /dev/null +++ b/internal/runtime/oauth_login_exchange_test.go @@ -0,0 +1,649 @@ +package runtime + +import ( + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// approvedCode runs authorize + approve for a fixed client and returns the code. +func (fx *oauthFx) approvedCode(reg, client string, choice ApprovalChoice) string { + fx.t.Helper() + id := fx.authorize(reg, client) + redirect, err := fx.svc.Approve(fx.ctx(), id, choice) + require.NoError(fx.t, err) + return oauthCodeOf(fx.t, redirect) +} + +func requireInvalidGrant(t *testing.T, terr *TokenError) { + t.Helper() + require.NotNil(t, terr) + assert.Equal(t, TokenErrInvalidGrant, terr.Code) +} + +// --- the exchange is the commit --------------------------------------------------------- + +func TestExchange_StoresTheLoginAndWritesTheIssueRow(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + fx.nothingStored() + + res, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + require.Nil(t, terr) + assert.True(t, strings.HasPrefix(res.AccessToken, mcplogin.AccessTokenPrefix)) + assert.True(t, strings.HasPrefix(res.RefreshToken, mcplogin.RefreshTokenPrefix)) + assert.Equal(t, "Bearer", res.TokenType) + assert.Equal(t, 3600, res.ExpiresIn) + + gs := fx.grants() + require.Len(t, gs, 1) + g := gs[0] + assert.Equal(t, "cursor", g.Client) + assert.Equal(t, reg, g.RegistrationID) + assert.Equal(t, oauthTestOrigin+"/mcp/oauth/cursor", g.Resource) + assert.Equal(t, oauthTestOrigin, g.Issuer) + assert.Equal(t, oauthTestRedirect, g.RedirectURI) + assert.Equal(t, "admin", g.ApprovedBy.Name) + assert.NotContains(t, g.AccessHash, res.AccessToken, "only hashes are stored") + pin, mode, found, err := fx.sm.CurrentClientBinding("cursor") + require.NoError(t, err) + require.True(t, found) + assert.Equal(t, "ro", pin) + assert.Equal(t, auth.ProfileModeLocked, mode) + used, _ := fx.sm.OAuthLoginEverUsed() + assert.True(t, used) + + rows := fx.changeRows("issue") + require.Len(t, rows, 1) + assert.Equal(t, g.GrantID, rows[0]["grant_id"]) + assert.Equal(t, "client", rows[0]["trigger"]) + assert.Equal(t, "admin", rows[0]["actor_name"], "the approving administrator, not the client") + assert.Equal(t, map[string]interface{}{"kind": "api_key", "name": "admin"}, rows[0]["approved_by"]) + ev := fx.eventsOf(EventTypeCredentialsChanged) + require.NotEmpty(t, ev) + last := ev[len(ev)-1].Payload + assert.Equal(t, "browser_login", last["kind"]) + assert.Equal(t, "issue", last["change"]) + assert.Equal(t, g.GrantID, last["id"]) + + // The access token authenticates exactly where it was approved. + ac, grant, aerr := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", fx.clock.Now()) + require.NoError(t, aerr) + assert.Equal(t, g.GrantID, grant.GrantID) + assert.Equal(t, auth.CredentialKindOAuth, ac.CredentialKind) + assert.Equal(t, g.GrantID, ac.GrantID) + assert.Equal(t, g.GrantID, ac.TokenGeneration) + assert.Equal(t, "cursor", ac.ClientID) + assert.Equal(t, "client-cursor", ac.AgentName) + assert.Equal(t, "ro", ac.ProfilePin) + assert.Equal(t, auth.ProfileModeLocked, ac.ProfileMode) + assert.True(t, ac.IsClientCredential()) +} + +func TestExchange_ExistingAPIKeyClientGetsItsFirstLoginFromItsCurrentBinding(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + b, err := fx.sm.GetOAuthClientBinding("codex") + require.NoError(t, err) + require.NotNil(t, b) + assert.Equal(t, "ro", b.ProfilePin) +} + +func TestExchange_FirstApprovalIsJudgedByTheGuardAtExchange(t *testing.T) { + fx := newOAuthFx(t) + fx.guard = ConservativeBindingGuard{} + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) // auth on: allowed + fx.cfg.RequireMCPAuth = false // ...then auth goes off + + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + fx.nothingStored() + rows := fx.changeRows("deny") + require.Len(t, rows, 1) + assert.Equal(t, "guard", rows[0]["reason"]) + assert.Equal(t, "client", rows[0]["trigger"]) + assert.Equal(t, "admin", rows[0]["actor_name"], "the approving administrator") +} + +func TestExchange_RefusalsAreInvalidGrantAndBurnTheCode(t *testing.T) { + cases := map[string]func(in *TokenInput){ + "wrong verifier": func(in *TokenInput) { in.CodeVerifier = strings.Repeat("w", 43) }, + "wrong client": func(in *TokenInput) { in.ClientID = "someoneelse" }, + "wrong redirect uri": func(in *TokenInput) { in.RedirectURI = "http://127.0.0.1:5556/cb" }, + } + for name, mut := range cases { + t.Run(name, func(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + in := fx.tokenInput(reg, code) + mut(&in) + _, terr := fx.svc.Exchange(in) + requireInvalidGrant(t, terr) + fx.nothingStored() + // Single use: even the right request now fails. + _, terr = fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + fx.nothingStored() + }) + } +} + +func TestExchange_ResourceMustEqualTheApprovedOne(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + in := fx.tokenInput(reg, code) + in.Resource = oauthTestOrigin + "/mcp/oauth/codex" + _, terr := fx.svc.Exchange(in) + require.NotNil(t, terr) + assert.Equal(t, TokenErrInvalidTarget, terr.Code) + fx.nothingStored() + + // The same resource, and an absent one, are fine. + code = fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + in = fx.tokenInput(reg, code) + in.Resource = oauthTestOrigin + "/mcp/oauth/cursor" + _, terr = fx.svc.Exchange(in) + require.Nil(t, terr) +} + +func TestExchange_OriginMismatchIsRefusedFirstAndConsumesNothing(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + in := fx.tokenInput(reg, code) + in.Origin = "http://localhost:8080" + _, terr := fx.svc.Exchange(in) + requireInvalidGrant(t, terr) + fx.nothingStored() + _, terr = fx.svc.Exchange(fx.tokenInput(reg, code)) + require.Nil(t, terr, "the code is still usable on the right origin") +} + +func TestExchange_CodeExpiryAndReuse(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + fx.clock.Advance(mcplogin.CodeLifetime) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + fx.nothingStored() + + // Reuse inside the tombstone window revokes the login it produced. + code = fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + res, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + require.Nil(t, terr) + _, terr = fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + gs := fx.grants() + require.Len(t, gs, 1) + assert.True(t, gs[0].Revoked) + assert.Equal(t, storage.OAuthRevokeReplay, gs[0].RevokeReason) + rows := fx.changeRows("replay_revoke") + require.Len(t, rows, 1) + assert.Equal(t, gs[0].GrantID, rows[0]["grant_id"]) + assert.Equal(t, "client", rows[0]["trigger"]) + assert.Equal(t, "admin", rows[0]["actor_name"]) + _, _, aerr := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", fx.clock.Now()) + assert.ErrorIs(t, aerr, ErrOAuthUnauthorized, "a revoked login stops authenticating") + + // After the window the code is simply unknown: nothing more is revoked. + fx.clock.Advance(mcplogin.TombstoneLifetime + time.Second) + _, terr = fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + assert.Len(t, fx.changeRows("replay_revoke"), 1) +} + +func TestExchange_ReuseOfACodeWhoseCommitFailedRevokesNothing(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + code := oauthCodeOf(t, redirect) + _, _, err = fx.clients.SetBindingForTest(fx, "rw") + require.NoError(t, err) + + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + _, terr = fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + assert.Empty(t, fx.changeRows("replay_revoke"), "an empty grant id means there is nothing to revoke") +} + +// SetBindingForTest changes codex's binding through the real clients service. +func (s *ClientsService) SetBindingForTest(fx *oauthFx, pin string) (*ClientCredentialView, struct{}, error) { + v, err := s.SetBinding(fx.ctx(), fx.actor(), "codex", pin, nil) + return v, struct{}{}, err +} + +func TestExchange_BindingChangedAfterApprovalStoresNothing(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + _, _, err = fx.clients.SetBindingForTest(fx, "rw") + require.NoError(t, err) + + _, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + requireInvalidGrant(t, terr) + assert.Empty(t, fx.grants()) + rows := fx.changeRows("deny") + require.Len(t, rows, 1) + assert.Equal(t, "binding_changed", rows[0]["reason"]) + assert.Equal(t, "client", rows[0]["trigger"]) + assert.Equal(t, "admin", rows[0]["actor_name"]) +} + +func TestExchange_ReplaceGrantRevokesTheOldLogin(t *testing.T) { + fx := newOAuthFx(t) + reg, first := fx.loginNew("cursor", "ro") + old := fx.grants()[0] + + id := fx.authorize(reg, "cursor") + rev, _ := fx.sm.ClientBindingRevision("cursor") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev, ReplaceGrant: old.GrantID}) + require.NoError(t, err) + second, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + + _, _, aerr := fx.svc.Authenticate(first.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", fx.clock.Now()) + assert.ErrorIs(t, aerr, ErrOAuthUnauthorized) + _, _, aerr = fx.svc.Authenticate(second.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", fx.clock.Now()) + assert.NoError(t, aerr) + for _, g := range fx.grants() { + if g.GrantID == old.GrantID { + assert.True(t, g.Revoked) + assert.Equal(t, storage.OAuthRevokeReplaced, g.RevokeReason) + } + } + + // A replace_grant of someone else's login is ignored, never revoked. + other := fx.register() + id = fx.authorize(other, "cursor") + rev, _ = fx.sm.ClientBindingRevision("cursor") + live := "" + for _, g := range fx.grants() { + if !g.Revoked { + live = g.GrantID + } + } + redirect, err = fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev, ReplaceGrant: live}) + require.NoError(t, err) + _, terr = fx.svc.Exchange(fx.tokenInput(other, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + _, _, aerr = fx.svc.Authenticate(second.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", fx.clock.Now()) + assert.NoError(t, aerr, "another registration's login is not replaced") +} + +// --- cancellation after approval ------------------------------------------------------------ + +func TestExchange_AfterApprovalRevokeClientFails(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + + _, err = fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Client: "codex"}, false) + require.NoError(t, err) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + requireInvalidGrant(t, terr) + assert.Empty(t, fx.grants(), "a revoke changes neither pin nor mode: only the cancellation catches it") +} + +func TestExchange_AfterApprovalForgetAndRecreateFails(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + + _, err = fx.clients.Forget(fx.ctx(), fx.actor(), "codex", false) + require.NoError(t, err) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) // recreated with the very same binding + _, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + requireInvalidGrant(t, terr) + assert.Empty(t, fx.grants()) +} + +func TestExchange_AfterApprovalFeatureOffThenOnFailsEvenWithoutAnEvent(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + pendingID := fx.authorize(reg, "cursor") + + // The synchronous step of applying a config in which the switch goes off. + assert.Equal(t, 2, fx.svc.CancelAll("feature_disabled")) + fx.cfg.MCPOAuthEnabled = false + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + fx.cfg.MCPOAuthEnabled = true // on again: the code is still dead + _, terr = fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + fx.nothingStored() + _, err := fx.svc.Approve(fx.ctx(), pendingID, ApprovalChoice{Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthRequestNotFound, "a cancelled pending request cannot be approved") + assert.NotEmpty(t, fx.eventsOf(EventTypeOAuthAuthorizationDecided)) +} + +func TestExchange_TwoApprovedNewClientRequestsWithTheSameID(t *testing.T) { + fx := newOAuthFx(t) + choice := ApprovalChoice{Client: ClientChoice{New: &NewClientChoice{ID: "acme"}}, Profile: oauthStrp("ro")} + regA, regB := fx.register(), fx.register() + codeA := fx.approvedCode(regA, "", choice) + codeB := fx.approvedCode(regB, "", choice) + + _, terr := fx.svc.Exchange(fx.tokenInput(regA, codeA)) + require.Nil(t, terr) + _, terr = fx.svc.Exchange(fx.tokenInput(regB, codeB)) + requireInvalidGrant(t, terr) + gs := fx.grants() + require.Len(t, gs, 1, "the second is not turned into an existing-client login") + assert.Equal(t, regA, gs[0].RegistrationID) + rows := fx.changeRows("deny") + require.Len(t, rows, 1) + assert.Equal(t, "client_exists", rows[0]["reason"]) +} + +func TestExchange_RegistrationEvictedAfterApproval(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + n, err := fx.sm.SweepOAuthRegistrations(fx.clock.Now().Add(48 * time.Hour)) + require.NoError(t, err) + require.Equal(t, 1, n) + + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + fx.nothingStored() + _, err = fx.sm.GetOAuthRegistration(reg) + assert.ErrorIs(t, err, storage.ErrOAuthRegistrationGone, "it is never recreated from the code") +} + +func TestExchange_FeatureOffRefusesEverything(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + fx.cfg.MCPOAuthEnabled = false + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + _, terr = fx.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: "x", ClientID: reg}) + requireInvalidGrant(t, terr) + _, _, aerr := fx.svc.Authenticate("mcp_oat_x", oauthTestOrigin, "/mcp/oauth", fx.clock.Now()) + assert.ErrorIs(t, aerr, ErrOAuthUnauthorized) +} + +// --- authentication ------------------------------------------------------------------------------ + +func TestAuthenticate_AudienceBinding(t *testing.T) { + fx := newOAuthFx(t) + _, res := fx.loginNew("cursor", "ro") + now := fx.clock.Now() + + _, _, err := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", now) + assert.NoError(t, err) + _, _, err = fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor/", now) + assert.NoError(t, err, "a trailing slash names the same resource path") + for name, c := range map[string]struct{ origin, path string }{ + "another client's address": {oauthTestOrigin, "/mcp/oauth/codex"}, + "the generic address": {oauthTestOrigin, "/mcp/oauth"}, + "another origin": {"http://localhost:8080", "/mcp/oauth/cursor"}, + "the plain MCP endpoint": {oauthTestOrigin, "/mcp"}, + } { + _, _, err := fx.svc.Authenticate(res.AccessToken, c.origin, c.path, now) + assert.ErrorIs(t, err, ErrOAuthUnauthorized, name) + } + _, _, err = fx.svc.Authenticate("mcp_oat_notatoken", oauthTestOrigin, "/mcp/oauth/cursor", now) + assert.ErrorIs(t, err, ErrOAuthUnauthorized) + _, _, err = fx.svc.Authenticate("mcp_cli_something", oauthTestOrigin, "/mcp/oauth/cursor", now) + assert.ErrorIs(t, err, ErrOAuthUnauthorized) + _, _, err = fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", now.Add(time.Hour)) + assert.ErrorIs(t, err, ErrOAuthUnauthorized, "the access token lives one hour") +} + +func TestAuthenticate_GenericResourceGrantOnlyOnTheGenericAddress(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "", ApprovalChoice{Client: ClientChoice{New: &NewClientChoice{ID: "acme"}}, Profile: oauthStrp("ro")}) + res, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + require.Nil(t, terr) + _, _, err := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth", fx.clock.Now()) + assert.NoError(t, err) + _, _, err = fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/acme", fx.clock.Now()) + assert.ErrorIs(t, err, ErrOAuthUnauthorized) +} + +func TestAuthenticate_BindingIsReadThroughTheAPIKeyRecord(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + res, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + + ac, _, aerr := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/codex", fx.clock.Now()) + require.NoError(t, aerr) + assert.Equal(t, "ro", ac.ProfilePin) + // An older binary moved the API-key record only; the entry is stale. + _, _, uerr := fx.sm.UpdateClientCredentialBinding("codex", "rw", auth.ProfileModeLocked) + require.NoError(t, uerr) + ac, _, aerr = fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/codex", fx.clock.Now()) + require.NoError(t, aerr) + assert.Equal(t, "rw", ac.ProfilePin) +} + +// --- refresh ------------------------------------------------------------------------------------------ + +func (fx *oauthFx) refresh(reg, token string) (TokenResult, *TokenError) { + return fx.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: token, ClientID: reg}) +} + +func TestRefresh_RotatesAndNeverExtendsAnExpiredLogin(t *testing.T) { + fx := newOAuthFx(t) + reg, first := fx.loginNew("cursor", "ro") + gid := fx.grants()[0].GrantID + + fx.clock.Advance(10 * 24 * time.Hour) + second, terr := fx.refresh(reg, first.RefreshToken) + require.Nil(t, terr) + assert.NotEqual(t, first.RefreshToken, second.RefreshToken) + assert.NotEqual(t, first.AccessToken, second.AccessToken) + g, _ := fx.sm.GetOAuthGrant(gid) + assert.True(t, g.RefreshExpiresAt.Equal(fx.clock.Now().Add(OAuthRefreshTokenTTL)), "30 days from the last rotation") + _, _, aerr := fx.svc.Authenticate(first.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", fx.clock.Now()) + assert.ErrorIs(t, aerr, ErrOAuthUnauthorized, "the previous access token is replaced") + _, _, aerr = fx.svc.Authenticate(second.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", fx.clock.Now()) + assert.NoError(t, aerr) + + // Expiry: 31 days of silence. Refused, not extended, nothing written. + before, _ := fx.sm.GetOAuthGrant(gid) + fx.clock.Advance(31 * 24 * time.Hour) + _, terr = fx.refresh(reg, second.RefreshToken) + requireInvalidGrant(t, terr) + after, _ := fx.sm.GetOAuthGrant(gid) + assert.Equal(t, before.RefreshExpiresAt, after.RefreshExpiresAt) + assert.False(t, after.Revoked) +} + +func TestRefresh_AuthenticReplayRevokesAndForgeryDoesNot(t *testing.T) { + fx := newOAuthFx(t) + reg, first := fx.loginNew("cursor", "ro") + gid := fx.grants()[0].GrantID + second, terr := fx.refresh(reg, first.RefreshToken) + require.Nil(t, terr) + + // A made-up token for a real grant id: bad MAC, nothing written. + forged := first.RefreshToken[:len(first.RefreshToken)-3] + "AAA" + _, terr = fx.refresh(reg, forged) + requireInvalidGrant(t, terr) + g, _ := fx.sm.GetOAuthGrant(gid) + assert.False(t, g.Revoked, "knowing a grant id is not enough to disturb a grant") + _, terr = fx.refresh(reg, "mcp_ort_"+gid+"_"+strings.Repeat("A", 43)+"_"+strings.Repeat("B", 22)) + requireInvalidGrant(t, terr) + g, _ = fx.sm.GetOAuthGrant(gid) + assert.False(t, g.Revoked) + + // The authentic, already-spent token comes back: the login is revoked. + _, terr = fx.refresh(reg, first.RefreshToken) + requireInvalidGrant(t, terr) + g, _ = fx.sm.GetOAuthGrant(gid) + assert.True(t, g.Revoked) + assert.Equal(t, storage.OAuthRevokeReplay, g.RevokeReason) + rows := fx.changeRows("replay_revoke") + require.Len(t, rows, 1) + assert.Equal(t, gid, rows[0]["grant_id"]) + assert.Equal(t, "client", rows[0]["trigger"]) + evs := fx.eventsOf(EventTypeCredentialsChanged) + assert.Equal(t, "replay_revoke", evs[len(evs)-1].Payload["change"]) + // The current token is dead too now. + _, terr = fx.refresh(reg, second.RefreshToken) + requireInvalidGrant(t, terr) +} + +func TestRefresh_ClientOriginAndResourceChecks(t *testing.T) { + fx := newOAuthFx(t) + reg, first := fx.loginNew("cursor", "ro") + gid := fx.grants()[0].GrantID + + _, terr := fx.refresh("someoneelse", first.RefreshToken) + requireInvalidGrant(t, terr) + _, terr = fx.svc.Refresh(TokenInput{Origin: "http://localhost:8080", RefreshToken: first.RefreshToken, ClientID: reg}) + requireInvalidGrant(t, terr) + _, terr = fx.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: first.RefreshToken, ClientID: reg, Resource: oauthTestOrigin + "/mcp/oauth"}) + require.NotNil(t, terr) + assert.Equal(t, TokenErrInvalidTarget, terr.Code) + g, _ := fx.sm.GetOAuthGrant(gid) + assert.False(t, g.Revoked, "none of these wrote anything") + + _, terr = fx.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: first.RefreshToken, ClientID: reg, Resource: oauthTestOrigin + "/mcp/oauth/cursor"}) + require.Nil(t, terr, "the same resource is accepted") +} + +// --- admin revoke ------------------------------------------------------------------------------------------ + +func TestRevokeGrant_NamesTheRequestActorAndStopsTheToken(t *testing.T) { + fx := newOAuthFx(t) + _, res := fx.loginNew("cursor", "ro") + gid := fx.grants()[0].GrantID + n := &countingNotifier{} + fx.svc.SetNotifier(n) + + changed, err := fx.svc.RevokeGrant(fx.ctx(), "cursor", gid) + require.NoError(t, err) + assert.True(t, changed) + rows := fx.changeRows("revoke") + require.Len(t, rows, 1) + assert.Equal(t, gid, rows[0]["grant_id"]) + assert.Equal(t, "admin", rows[0]["actor_name"]) + assert.NotContains(t, rows[0], "trigger", "an administrator's action, not the client's") + assert.Equal(t, 1, int(n.calls.Load())) + evs := fx.eventsOf(EventTypeCredentialsChanged) + assert.Equal(t, "revoke", evs[len(evs)-1].Payload["change"]) + _, _, aerr := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", fx.clock.Now()) + assert.ErrorIs(t, aerr, ErrOAuthUnauthorized, "the next request is refused") + + changed, err = fx.svc.RevokeGrant(fx.ctx(), "cursor", gid) + require.NoError(t, err) + assert.False(t, changed, "already revoked") + _, err = fx.svc.RevokeGrant(fx.ctx(), "codex", gid) + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) + _, err = fx.svc.RevokeGrant(fx.ctx(), "cursor", "nope") + assert.ErrorIs(t, err, ErrOAuthGrantNotFound) +} + +type countingNotifier struct{ calls atomic.Int32 } + +func (c *countingNotifier) NotifyBindingChanged(string) { c.calls.Add(1) } + +// --- the lock order -------------------------------------------------------------------------------------------- + +// Exchange takes bindingWriteMu before the request store, and revoke/forget take +// it before CancelForClient: one order, so hammering both finishes. Run under +// -race. +func TestExchangeAgainstRevokeClientDoesNotDeadlockOrRace(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + const n = 12 + type pending struct{ reg, code string } + var ps []pending + for i := 0; i < n; i++ { + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + ps = append(ps, pending{reg, oauthCodeOf(t, redirect)}) + } + + done := make(chan struct{}) + go func() { + defer close(done) + var wg sync.WaitGroup + for _, p := range ps { + p := p + wg.Add(1) + go func() { + defer wg.Done() + _, _ = fx.svc.Exchange(fx.tokenInput(p.reg, p.code)) + }() + } + for i := 0; i < 4; i++ { + wg.Add(2) + go func() { + defer wg.Done() + _, _ = fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Client: "codex"}, false) + }() + go func() { + defer wg.Done() + fx.svc.CancelForClient("codex") + fx.svc.CancelAll("race") + }() + } + wg.Wait() + }() + select { + case <-done: + case <-time.After(60 * time.Second): + t.Fatal("deadlock: Exchange and revoke/cancel never finished") + } + // Whatever won, no login is left live for a revoked client. + for _, g := range fx.grants() { + assert.True(t, g.Revoked, "a login that slipped in before the revoke is revoked by it") + } +} + +var _ = profile.ChangeApprove diff --git a/internal/runtime/oauth_login_failclosed_test.go b/internal/runtime/oauth_login_failclosed_test.go new file mode 100644 index 000000000..6cf792d0d --- /dev/null +++ b/internal/runtime/oauth_login_failclosed_test.go @@ -0,0 +1,77 @@ +package runtime + +import ( + "errors" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// brokenOAuthStore is a real store whose browser-login bindings cannot be read. +type brokenOAuthStore struct{ *storage.Manager } + +func (brokenOAuthStore) ListOAuthClientBindings() (map[string]storage.OAuthClientBinding, error) { + return nil, errors.New("disk on fire") +} + +// A storage read error REFUSES the change instead of being read as "no +// bindings" (research R5): the producers of a guard state fail closed. +func TestGuardProducersFailClosedOnAnOAuthStoreReadError(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + broken := brokenOAuthStore{fx.sm} + var shared = fx.clients.mu + clients := NewClientsService(ClientsServiceDeps{ + Store: broken, HMACKey: func() ([]byte, error) { return oauthTestKey, nil }, + Config: func() *config.Config { return fx.cfg }, Guard: func() BindingGuard { return stubGuard{} }, + Now: fx.clock.Now, Mu: shared, + }) + + _, err := clients.SetBinding(fx.ctx(), fx.actor(), "codex", "rw", nil) + require.Error(t, err) + assert.Contains(t, err.Error(), "browser-login") + pin, _, _, _ := fx.sm.CurrentClientBinding("codex") + assert.Equal(t, "ro", pin, "nothing was written") + + // The views refuse too, rather than silently dropping the logins. + _, err = clients.List() + require.Error(t, err) +} + +func TestOAuthNameMismatch(t *testing.T) { + cases := []struct { + observed, reported, client string + want bool + }{ + {"", "anything", "cursor", false}, + {"cursor", "other", "cursor", false}, // a registry id + {"Cursor", "other", "cursor", false}, // the registry display name + {"totally-other", "cursor ide", "cursor", true}, // neither + {"cursor ide", "cursor ide", "acme", false}, // the registered name + {"cursor ide", "something else", "acme", true}, // a custom client knows only its registered name + {"claude-code (via mcp-remote 0.1.2)", "x", "claude-code", false}, + } + for _, c := range cases { + assert.Equal(t, c.want, OAuthNameMismatch(c.observed, c.reported, c.client), "%+v", c) + } +} + +func TestTouch_StampsLastUseAndObservedNameOffTheRequestPath(t *testing.T) { + fx := newOAuthFx(t) + fx.loginNew("cursor", "ro") + gid := fx.grants()[0].GrantID + fx.svc.Touch(gid, "Cursor-VSCode") + require.Eventually(t, func() bool { + g, _ := fx.sm.GetOAuthGrant(gid) + return g != nil && g.LastUsedAt != nil && g.ObservedClientName != "" + }, 2*time.Second, 10*time.Millisecond) + g, _ := fx.sm.GetOAuthGrant(gid) + assert.Equal(t, "cursor-vscode", g.ObservedClientName, "sanitised before it is stored") + fx.svc.Touch("", "x") // no grant: nothing happens +} diff --git a/internal/runtime/oauth_login_fixture_test.go b/internal/runtime/oauth_login_fixture_test.go new file mode 100644 index 000000000..52e5ec57c --- /dev/null +++ b/internal/runtime/oauth_login_fixture_test.go @@ -0,0 +1,230 @@ +package runtime + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "net/url" + "os" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/require" + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +const ( + oauthTestOrigin = "http://127.0.0.1:8080" + oauthTestRedirect = "http://127.0.0.1:5555/cb" +) + +var oauthTestKey = []byte("oauth-login-test-key-0123456789ab") + +type oauthTestClock struct { + mu sync.Mutex + t time.Time +} + +func (c *oauthTestClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.t +} + +func (c *oauthTestClock) Advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.t = c.t.Add(d) +} + +// oauthFx is the browser-login services over a real storage manager. +type oauthFx struct { + t *testing.T + sm *storage.Manager + cfg *config.Config + clock *oauthTestClock + svc *OAuthLoginService + clients *ClientsService + creds *CredentialsService + reqs *mcplogin.Store + guard BindingGuard + + mu sync.Mutex + rows []*storage.ActivityRecord + events []Event +} + +func newOAuthFx(t *testing.T) *oauthFx { + t.Helper() + dir, err := os.MkdirTemp("", "oauth-login-svc-*") + require.NoError(t, err) + sm, err := storage.NewManager(dir, zap.NewNop().Sugar()) + require.NoError(t, err) + t.Cleanup(func() { _ = sm.Close(); _ = os.RemoveAll(dir) }) + + fx := &oauthFx{t: t, sm: sm, clock: &oauthTestClock{t: time.Date(2026, 11, 22, 12, 0, 0, 0, time.UTC)}, guard: stubGuard{}} + fx.cfg = &config.Config{ + MCPOAuthEnabled: true, RequireMCPAuth: true, + Profiles: []config.ProfileConfig{{Name: "ro", Servers: []string{"a"}}, {Name: "rw", Servers: []string{"a"}}}, + } + fx.reqs = mcplogin.NewStore(oauthTestKey, fx.clock.Now) + var shared sync.Mutex + keyf := func() ([]byte, error) { return oauthTestKey, nil } + cfgf := func() *config.Config { return fx.cfg } + guardf := func() BindingGuard { return fx.guard } + act := func(r *storage.ActivityRecord) error { + fx.mu.Lock() + defer fx.mu.Unlock() + fx.rows = append(fx.rows, r) + return nil + } + pub := func(e Event) { + fx.mu.Lock() + defer fx.mu.Unlock() + fx.events = append(fx.events, e) + } + fx.svc = NewOAuthLoginService(OAuthLoginDeps{ + Store: sm, HMACKey: keyf, Config: cfgf, Guard: guardf, Activity: act, Publish: pub, + Now: fx.clock.Now, Mu: &shared, Requests: fx.reqs, + }) + fx.clients = NewClientsService(ClientsServiceDeps{ + Store: sm, HMACKey: keyf, Config: cfgf, Guard: guardf, Activity: act, Publish: pub, + Now: fx.clock.Now, Mu: &shared, + }) + fx.clients.SetLoginCanceler(func(id string) { fx.svc.CancelForClient(id) }) + fx.creds = fx.clients.CredentialsServiceOver(sm) + fx.creds.SetOAuthLogin(fx.svc) + return fx +} + +// stubGuard never refuses (the same shape config_funnel_test uses); tests that +// need the real conservative evaluator set fx.guard. +func (fx *oauthFx) ctx() context.Context { + return ContextWithActor(context.Background(), Actor{Kind: "api_key", Name: "admin", Surface: profile.SurfaceAPI}) +} + +func (fx *oauthFx) actor() Actor { + return Actor{Kind: "api_key", Name: "admin", Surface: profile.SurfaceAPI} +} + +// mintClient creates an API-key client with a binding. +func (fx *oauthFx) mintClient(id, pin, mode string) { + fx.t.Helper() + _, err := fx.sm.MintClientCredential(id, "mcp_cli_"+id+"_oauth_test_secret_000000", oauthTestKey, mode, pin, fx.clock.Now().Add(24*time.Hour)) + require.NoError(fx.t, err) +} + +func (fx *oauthFx) register() string { + fx.t.Helper() + resp, rerr, err := fx.svc.Register(mcplogin.RegistrationRequest{ + RedirectURIs: []string{oauthTestRedirect}, ClientName: "Cursor IDE", + }) + require.NoError(fx.t, err) + require.Nil(fx.t, rerr) + return resp["client_id"].(string) +} + +var oauthTestVerifier = strings.Repeat("v", 43) + +func oauthTestChallenge() string { + sum := sha256.Sum256([]byte(oauthTestVerifier)) + return base64.RawURLEncoding.EncodeToString(sum[:]) +} + +func (fx *oauthFx) authInput(reg, resource string) AuthorizeInput { + return AuthorizeInput{ + Origin: oauthTestOrigin, ClientID: reg, RedirectURI: oauthTestRedirect, State: "st-1", + CodeChallenge: oauthTestChallenge(), Method: "S256", Resource: resource, ResponseType: "code", + } +} + +// authorize registers nothing: it begins an authorization for reg at the +// per-client resource of client ("" = the generic address). +func (fx *oauthFx) authorize(reg, client string) string { + fx.t.Helper() + id, aerr := fx.svc.BeginAuthorization(fx.authInput(reg, oauthTestOrigin+mcplogin.ResourcePath(client))) + require.Nil(fx.t, aerr) + require.NotEmpty(fx.t, id) + return id +} + +func oauthCodeOf(t *testing.T, redirect string) string { + t.Helper() + u, err := url.Parse(redirect) + require.NoError(t, err) + code := u.Query().Get("code") + require.NotEmpty(t, code, redirect) + return code +} + +func (fx *oauthFx) tokenInput(reg, code string) TokenInput { + return TokenInput{Origin: oauthTestOrigin, Code: code, RedirectURI: oauthTestRedirect, ClientID: reg, CodeVerifier: oauthTestVerifier} +} + +func oauthStrp(s string) *string { return &s } + +// login runs register -> authorize -> approve -> exchange for a new client. +func (fx *oauthFx) loginNew(client, profileName string) (reg string, res TokenResult) { + fx.t.Helper() + reg = fx.register() + id := fx.authorize(reg, client) + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Client: ClientChoice{ID: client}, Profile: oauthStrp(profileName)}) + require.NoError(fx.t, err) + var terr *TokenError + res, terr = fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(fx.t, redirect))) + require.Nil(fx.t, terr) + return reg, res +} + +func (fx *oauthFx) changeRows(change string) []map[string]interface{} { + fx.mu.Lock() + defer fx.mu.Unlock() + var out []map[string]interface{} + for _, r := range fx.rows { + if r.Type == storage.ActivityTypeProfileChange && r.Metadata["change"] == change { + out = append(out, r.Metadata) + } + } + return out +} + +func (fx *oauthFx) eventsOf(typ EventType) []Event { + fx.mu.Lock() + defer fx.mu.Unlock() + var out []Event + for _, e := range fx.events { + if e.Type == typ { + out = append(out, e) + } + } + return out +} + +func (fx *oauthFx) grants() []storage.OAuthGrant { + fx.t.Helper() + gs, err := fx.sm.ListOAuthGrants() + require.NoError(fx.t, err) + return gs +} + +// nothingStored asserts that no login, binding or marker exists. +func (fx *oauthFx) nothingStored() { + fx.t.Helper() + require.Empty(fx.t, fx.grants()) + b, err := fx.sm.ListOAuthClientBindings() + require.NoError(fx.t, err) + require.Empty(fx.t, b) + used, err := fx.sm.OAuthLoginEverUsed() + require.NoError(fx.t, err) + require.False(fx.t, used) +} + +var _ = auth.KindClient diff --git a/internal/runtime/oauth_login_service.go b/internal/runtime/oauth_login_service.go new file mode 100644 index 000000000..7023f2ed4 --- /dev/null +++ b/internal/runtime/oauth_login_service.go @@ -0,0 +1,468 @@ +package runtime + +import ( + "errors" + "sync" + "time" + + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// OAuthLoginService is the runtime half of the browser login for MCP clients +// (Spec 132): registration, the authorization request and its consent +// decision, the token endpoint's exchange and refresh, access-token +// authentication, and the admin revoke of one login. +// +// LOCK ORDER (one rule, no cycles). Every path that pairs a storage write with +// the in-memory request store takes the runtime's bindingWriteMu FIRST and the +// request store's own mutex second: +// +// bindingWriteMu -> mcplogin.Store.mu -> storage.Manager.mu +// +// - Exchange takes bindingWriteMu BEFORE calling Store.Consume, and its commit +// callback (which Consume runs under Store.mu) does NOT take bindingWriteMu +// again. That is why the callback may do the guard check and the storage +// commit: the lock above it is already held. +// - Revoke-client, forget-client and RevokeGrant hold bindingWriteMu (their +// own services take it) and then call Store.CancelForClient, the same order. +// - Approve holds bindingWriteMu while it validates the choice and calls +// Store.Approve, the same order. +// - The turn-off cancellation (CancelAll from the config commit) takes Store.mu +// alone. It needs no bindingWriteMu: it is one in-memory step, atomic with +// Consume through Store.mu, and may run while the caller already holds +// bindingWriteMu (MutateConfig) or does not (file reload). +// - Nothing holding Store.mu ever acquires bindingWriteMu (the commit callback +// never does), so the two cannot be taken in opposite orders. +type OAuthLoginService struct { + store OAuthLoginStore + hmacKey func() ([]byte, error) + cfg func() *config.Config + guard func() BindingGuard + // activity writes a profile_change row; publish emits an SSE event. + activity func(*storage.ActivityRecord) error + publish func(Event) + now func() time.Time + mu *sync.Mutex + logger *zap.Logger + + notifier BindingNotifier + + // reqs is built on first use, because building it needs the token key and + // creating that key writes a file: a default-off install must not. + reqMu sync.Mutex + reqs *mcplogin.Store + + everUsed bool // positive results only + everMu sync.Mutex + touchMu sync.Mutex + lastTouch map[string]time.Time +} + +// OAuthLoginStore is the storage surface the service needs; *storage.Manager +// implements it. +type OAuthLoginStore interface { + ListAgentTokens() ([]auth.AgentToken, error) + GetAgentTokenByName(name string) (*auth.AgentToken, error) + CreateOAuthRegistration(reg storage.OAuthRegistration) error + GetOAuthRegistration(id string) (*storage.OAuthRegistration, error) + MarkOAuthRegistrationAuthorized(id string, at time.Time) error + CommitOAuthLogin(in storage.CommitLoginInput) (storage.OAuthGrant, error) + GetOAuthGrant(id string) (*storage.OAuthGrant, error) + ListOAuthGrants() ([]storage.OAuthGrant, error) + ListOAuthGrantsForClient(clientID string) ([]storage.OAuthGrant, error) + AuthenticateOAuthAccess(accessHash string, now time.Time) (*storage.OAuthGrant, error) + RotateOAuthRefresh(grantID, presentedSecretHash, newRefreshHash, newRefreshPrefix, newAccessHash string, now time.Time, accessTTL, refreshTTL time.Duration) (storage.RefreshOutcome, storage.OAuthGrant, error) + RevokeOAuthGrant(id, reason string, now time.Time) (bool, error) + TouchOAuthGrant(id string, lastUsedAt time.Time, observedName string) error + GetOAuthClientBinding(clientID string) (*storage.OAuthClientBinding, error) + ListOAuthClientBindings() (map[string]storage.OAuthClientBinding, error) + CurrentClientBinding(clientID string) (pin, mode string, found bool, err error) + ClientBindingRevision(clientID string) (string, error) + OAuthLoginEverUsed() (bool, error) +} + +// Token lifetimes of a browser login (research R6). +const ( + OAuthAccessTokenTTL = time.Hour + OAuthRefreshTokenTTL = 30 * 24 * time.Hour +) + +// OAuthLoginDeps wires an OAuthLoginService. Zero values are safe in tests: +// Now defaults to time.Now, Mu to a private mutex, Guard to the conservative +// evaluator, Logger to a no-op, Requests to a store built on first use. +type OAuthLoginDeps struct { + Store OAuthLoginStore + HMACKey func() ([]byte, error) + Config func() *config.Config + Guard func() BindingGuard + Activity func(*storage.ActivityRecord) error + Publish func(Event) + Now func() time.Time + Mu *sync.Mutex + Logger *zap.Logger + // Requests is the in-memory request and code store (tests inject one with + // a fake clock). + Requests *mcplogin.Store +} + +// NewOAuthLoginService builds the service. +func NewOAuthLoginService(d OAuthLoginDeps) *OAuthLoginService { + s := &OAuthLoginService{ + store: d.Store, hmacKey: d.HMACKey, cfg: d.Config, guard: d.Guard, activity: d.Activity, + publish: d.Publish, now: d.Now, mu: d.Mu, logger: d.Logger, reqs: d.Requests, + lastTouch: map[string]time.Time{}, + } + if s.now == nil { + s.now = time.Now + } + if s.mu == nil { + s.mu = &sync.Mutex{} + } + if s.guard == nil { + s.guard = func() BindingGuard { return ConservativeBindingGuard{} } + } + if s.logger == nil { + s.logger = zap.NewNop() + } + if s.cfg == nil { + s.cfg = func() *config.Config { return nil } + } + return s +} + +// OAuthLoginService returns the runtime's browser-login service (Spec 132). +func (r *Runtime) OAuthLoginService() *OAuthLoginService { return r.oauthLoginService } + +// SetNotifier installs the live-session notifier (the server). +func (s *OAuthLoginService) SetNotifier(n BindingNotifier) { s.notifier = n } + +// Enabled reports whether the feature is on in the live configuration. +func (s *OAuthLoginService) Enabled() bool { + c := s.cfg() + return c != nil && c.MCPOAuthEnabled +} + +// EverUsed reports whether a browser login was ever stored. Only a positive +// answer is cached: the marker is never cleared, a negative one can change. +func (s *OAuthLoginService) EverUsed() bool { + s.everMu.Lock() + defer s.everMu.Unlock() + if s.everUsed { + return true + } + used, err := s.store.OAuthLoginEverUsed() + if err != nil { + s.logger.Warn("cannot read the browser-login marker", zap.Error(err)) + return false + } + s.everUsed = used + return used +} + +// requests returns the request store, building it on first use. +func (s *OAuthLoginService) requests() (*mcplogin.Store, error) { + s.reqMu.Lock() + defer s.reqMu.Unlock() + if s.reqs != nil { + return s.reqs, nil + } + key, err := s.hmacKey() + if err != nil { + return nil, err + } + s.reqs = mcplogin.NewStore(key, s.now) + return s.reqs, nil +} + +// existingRequests returns the request store when one was ever built. +func (s *OAuthLoginService) existingRequests() *mcplogin.Store { + s.reqMu.Lock() + defer s.reqMu.Unlock() + return s.reqs +} + +// --- cancellation ------------------------------------------------------------ + +// CancelAll cancels every pending and approved-but-unconsumed request (the +// feature is being turned off). It takes the request store's mutex only (see +// the lock-order note): it may run under bindingWriteMu or without it. +func (s *OAuthLoginService) CancelAll(reason string) int { + reqs := s.existingRequests() + if reqs == nil { + return 0 + } + pending := reqs.ListPending() + n := reqs.CancelAll() + for _, p := range pending { + s.publishDecided(p.ID, string(mcplogin.StatusCancelled)) + } + if n > 0 { + s.logger.Info("cancelled browser sign-in requests", zap.Int("count", n), zap.String("reason", reason)) + } + return n +} + +// CancelForClient cancels the pending and approved requests that target the +// client, by address or by decision. Callers hold bindingWriteMu (revoke and +// forget run under it), so an exchange either completed before them or finds +// its request cancelled. +func (s *OAuthLoginService) CancelForClient(clientID string) int { + reqs := s.existingRequests() + if reqs == nil { + return 0 + } + var ids []string + for _, p := range reqs.ListPending() { + if p.PathClient == clientID { + ids = append(ids, p.ID) + } + } + n := reqs.CancelForClient(clientID) + for _, id := range ids { + s.publishDecided(id, string(mcplogin.StatusCancelled)) + } + return n +} + +func (s *OAuthLoginService) publishDecided(requestID, status string) { + if s.publish != nil { + s.publish(newEvent(EventTypeOAuthAuthorizationDecided, map[string]any{"request_id": requestID, "status": status})) + } +} + +// --- registration -------------------------------------------------------------- + +// Register validates an RFC 7591 request and stores a pending registration. +// The first return is the 201 body; the second a refusal shaped for the +// client; the third an internal failure. +func (s *OAuthLoginService) Register(req mcplogin.RegistrationRequest) (map[string]any, *mcplogin.RegError, error) { + reg, regErr := mcplogin.ValidateRegistration(req) + if regErr != nil { + return nil, regErr, nil + } + id, err := mcplogin.NewClientID() + if err != nil { + return nil, nil, err + } + reg.ClientID = id + now := s.now().UTC() + if err := s.store.CreateOAuthRegistration(storage.OAuthRegistration{ + ClientID: id, ReportedName: reg.ClientName, RedirectURIs: reg.RedirectURIs, + SoftwareID: reg.SoftwareID, SoftwareVersion: reg.SoftwareVersion, + TokenEndpointAuthMethod: reg.TokenEndpointAuthMethod, GrantTypes: reg.GrantTypes, CreatedAt: now, + }); err != nil { + return nil, nil, err + } + return reg.Response(now), nil, nil +} + +// --- tokens ---------------------------------------------------------------------- + +// TokenInput is a token request, after the HTTP layer parsed the form. Origin +// is the origin of THIS request (mcplogin.Origin). +type TokenInput struct { + Origin string + Code string + RedirectURI string + ClientID string // the registration's client_id + CodeVerifier string + RefreshToken string + Resource string +} + +// TokenResult is a successful token answer. +type TokenResult struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type"` + ExpiresIn int `json:"expires_in"` + RefreshToken string `json:"refresh_token"` +} + +// Token error codes (contracts/oauth-endpoints.md). +const ( + TokenErrInvalidGrant = "invalid_grant" + TokenErrInvalidTarget = "invalid_target" + TokenErrServer = "server_error" +) + +// TokenError is a refusal of the token endpoint: always 400 except +// server_error. Descriptions are deliberately uniform: they never tell which +// check failed. +type TokenError struct { + Code string + Description string +} + +func (e *TokenError) Error() string { return e.Code + ": " + e.Description } + +var ( + errInvalidGrant = &TokenError{Code: TokenErrInvalidGrant, Description: "the grant is invalid, expired or revoked"} + errInvalidTarget = &TokenError{Code: TokenErrInvalidTarget, Description: "the resource does not match the approved one"} + errTokenServer = &TokenError{Code: TokenErrServer, Description: "the server could not complete the request"} +) + +// errExchangeRefused is how an exchange re-check says "invalid_grant". +var errExchangeRefused = errors.New("oauth exchange refused") + +// newTokenSet mints the access and refresh tokens of a grant. +type tokenSet struct { + access, refresh string + accessHash, refreshHash, refreshPrefix string + displayPrefix string +} + +func newTokenSet(key []byte, grantID string) (*tokenSet, error) { + access, err := mcplogin.NewAccessToken() + if err != nil { + return nil, err + } + refresh, secret, err := mcplogin.NewRefreshToken(key, grantID) + if err != nil { + return nil, err + } + return &tokenSet{ + access: access, refresh: refresh, + accessHash: mcplogin.HashSecret(key, mcplogin.KindAccess, access), + refreshHash: mcplogin.HashSecret(key, mcplogin.KindRefresh, secret), + refreshPrefix: mcplogin.DisplayPrefix(refresh), + displayPrefix: mcplogin.DisplayPrefix(access), + }, nil +} + +func (t *tokenSet) result() TokenResult { + return TokenResult{ + AccessToken: t.access, TokenType: "Bearer", ExpiresIn: int(OAuthAccessTokenTTL / time.Second), + RefreshToken: t.refresh, + } +} + +// Exchange is the authorization-code grant. It is where the login is STORED +// (research R15): the request's origin is compared with the stored issuer +// first (a mismatch consumes nothing), then, under bindingWriteMu and the +// request store's single-use boundary, the PKCE verifier, client, redirect URI +// and resource are checked, the guard is re-run over the decided candidate and +// storage.CommitOAuthLogin re-checks the registration, the new-client id and +// the binding revision in one transaction. Any failed check answers +// invalid_grant (invalid_target for a resource mismatch) with nothing stored. +func (s *OAuthLoginService) Exchange(in TokenInput) (TokenResult, *TokenError) { + if !s.Enabled() { + return TokenResult{}, errInvalidGrant + } + reqs, err := s.requests() + if err != nil { + s.logger.Error("browser login: cannot build the request store", zap.Error(err)) + return TokenResult{}, errTokenServer + } + key, err := s.hmacKey() + if err != nil { + s.logger.Error("browser login: cannot read the token key", zap.Error(err)) + return TokenResult{}, errTokenServer + } + // The origin check comes first and consumes nothing. + peek, ok := reqs.PeekCode(in.Code) + if ok && peek.Issuer != in.Origin { + return TokenResult{}, errInvalidGrant + } + + // Lock order: bindingWriteMu BEFORE the request store (see the type doc). + s.mu.Lock() + defer s.mu.Unlock() + + var ( + tokens *tokenSet + grant storage.OAuthGrant + decided mcplogin.Decision + target bool + ) + commit := func(req mcplogin.Request) (string, error) { + decided = req.Decision + if req.Issuer != in.Origin { + return "", errExchangeRefused // the code was re-issued between peek and consume: refuse, burn + } + if !mcplogin.VerifyS256(in.CodeVerifier, req.CodeChallenge) || + in.ClientID != req.RegistrationID || in.RedirectURI != req.RedirectURI { + return "", errExchangeRefused + } + if in.Resource != "" && in.Resource != req.Resource { + target = true + return "", errExchangeRefused + } + now := s.now().UTC() + if err := s.recheckGuard(req.Decision); err != nil { + s.writeDecisionRow(profile.ChangeDeny, req, "guard", now) + return "", errExchangeRefused + } + grantID, err := mcplogin.NewGrantID() + if err != nil { + return "", err + } + ts, err := newTokenSet(key, grantID) + if err != nil { + return "", err + } + stored, err := s.store.CommitOAuthLogin(storage.CommitLoginInput{ + Grant: storage.OAuthGrant{ + GrantID: grantID, RegistrationID: req.RegistrationID, Client: req.Decision.ClientID, + RedirectURI: req.RedirectURI, Resource: req.Resource, Issuer: req.Issuer, + RefreshHash: ts.refreshHash, RefreshPrefix: ts.refreshPrefix, AccessHash: ts.accessHash, + AccessExpiresAt: now.Add(OAuthAccessTokenTTL), RefreshExpiresAt: now.Add(OAuthRefreshTokenTTL), + ApprovedAt: now, ApprovedBy: storage.OAuthActor{Kind: req.Decision.ActorKind, Name: req.Decision.ActorName}, + DisplayPrefix: ts.displayPrefix, + }, + Client: req.Decision.ClientID, NewClient: req.Decision.NewClient, + Pin: req.Decision.Profile, Mode: req.Decision.Mode, DisplayName: req.Decision.DisplayName, + ExpectedBindingRevision: req.Decision.BindingRevision, ReplaceGrantID: req.Decision.ReplaceGrantID, Now: now, + }) + if err != nil { + reason := "" + switch { + case errors.Is(err, storage.ErrOAuthBindingChanged): + reason = "binding_changed" + case errors.Is(err, storage.ErrOAuthClientExists): + reason = "client_exists" + case errors.Is(err, storage.ErrOAuthRegistrationGone): + reason = "registration_gone" + } + if reason == "" { + return "", err // a storage failure: not a refusal + } + s.writeDecisionRow(profile.ChangeDeny, req, reason, now) + return "", errExchangeRefused + } + tokens, grant = ts, stored + return grantID, nil + } + + req, replayedGrant, err := reqs.Consume(in.Code, commit) + switch { + case err == nil: + case errors.Is(err, mcplogin.ErrCodeReused): + // A code presented again inside the tombstone window revokes the login + // it produced. An empty grant id means the first presentation stored + // nothing: there is nothing to revoke. + s.revokeReplayedCode(replayedGrant) + return TokenResult{}, errInvalidGrant + default: + if target { + return TokenResult{}, errInvalidTarget + } + if errors.Is(err, errExchangeRefused) || errors.Is(err, mcplogin.ErrCodeUnknown) { + return TokenResult{}, errInvalidGrant + } + s.logger.Error("browser login: token exchange failed", zap.Error(err)) + return TokenResult{}, errTokenServer + } + + s.writeGrantRow(profile.ChangeIssue, grant, decided, "") + s.publishGrantChanged(grant, profile.ChangeIssue, req.Decision.Profile) + if s.notifier != nil && decided.ReplaceGrantID != "" { + s.notifier.NotifyBindingChanged(auth.ClientTokenName(grant.Client)) + } + return tokens.result(), nil +} diff --git a/internal/runtime/oauth_login_service_test.go b/internal/runtime/oauth_login_service_test.go new file mode 100644 index 000000000..7c3c3229d --- /dev/null +++ b/internal/runtime/oauth_login_service_test.go @@ -0,0 +1,456 @@ +package runtime + +import ( + "net/url" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" +) + +// --- BeginAuthorization --------------------------------------------------------- + +func TestBeginAuthorization_OrderOfChecks(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + + in := func(mut func(*AuthorizeInput)) *AuthorizeError { + a := fx.authInput(reg, oauthTestOrigin+"/mcp/oauth/codex") + mut(&a) + _, err := fx.svc.BeginAuthorization(a) + return err + } + // 1. unknown client or unregistered redirect: no redirect, whatever else is wrong. + e := in(func(a *AuthorizeInput) { a.ClientID = "nope"; a.ResponseType = "token" }) + require.NotNil(t, e) + assert.Equal(t, AuthorizeNoRedirect, e.Kind) + e = in(func(a *AuthorizeInput) { a.RedirectURI = "http://127.0.0.1:5555/other" }) + require.NotNil(t, e) + assert.Equal(t, AuthorizeNoRedirect, e.Kind) + // 2. a per-client resource of a client that does not exist: 404, no redirect, before the rest. + e = in(func(a *AuthorizeInput) { a.Resource = oauthTestOrigin + "/mcp/oauth/ghost"; a.ResponseType = "token" }) + require.NotNil(t, e) + assert.Equal(t, AuthorizeNotFound, e.Kind) + // A registry id without a record exists. + e = in(func(a *AuthorizeInput) { a.Resource = oauthTestOrigin + "/mcp/oauth/cursor" }) + assert.Nil(t, e) + // 3. redirectable errors. + e = in(func(a *AuthorizeInput) { a.ResponseType = "token" }) + require.NotNil(t, e) + assert.Equal(t, AuthorizeRedirect, e.Kind) + assert.Equal(t, "unsupported_response_type", e.Code) + e = in(func(a *AuthorizeInput) { a.Method = "plain" }) + assert.Equal(t, "invalid_request", e.Code) + e = in(func(a *AuthorizeInput) { a.CodeChallenge = "short" }) + assert.Equal(t, "invalid_request", e.Code) + e = in(func(a *AuthorizeInput) { a.Resource = oauthTestOrigin + "/mcp" }) + assert.Equal(t, "invalid_target", e.Code) + e = in(func(a *AuthorizeInput) { a.Resource = "http://localhost:8080/mcp/oauth/codex" }) + assert.Equal(t, "invalid_target", e.Code, "another origin is another resource") + + u, err := e.RedirectURL() + require.NoError(t, err) + pu, _ := url.Parse(u) + assert.Equal(t, "invalid_target", pu.Query().Get("error")) + assert.Equal(t, "st-1", pu.Query().Get("state")) +} + +func TestBeginAuthorization_PublishesPendingAndMarksAuthorized(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + id := fx.authorize(reg, "cursor") + ev := fx.eventsOf(EventTypeOAuthAuthorizationPending) + require.Len(t, ev, 1) + assert.Equal(t, map[string]any{"request_id": id, "client_id": "cursor", "client_label": "cursor ide"}, ev[0].Payload) + got, err := fx.sm.GetOAuthRegistration(reg) + require.NoError(t, err) + assert.Equal(t, "authorized", got.State) + pend := fx.svc.ListPending() + require.Len(t, pend, 1) + assert.Equal(t, id, pend[0].ID) + assert.Equal(t, "cursor ide", pend[0].ClientLabel) + + // The generic address names no client in the event. + id2 := fx.authorize(reg, "") + ev = fx.eventsOf(EventTypeOAuthAuthorizationPending) + require.Len(t, ev, 2) + assert.Equal(t, id2, ev[1].Payload["request_id"]) + assert.Equal(t, "", ev[1].Payload["client_id"]) +} + +// --- Describe ----------------------------------------------------------------------- + +func TestDescribe_FixedClientOnPerClientAddress(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + + v, err := fx.svc.Describe(fx.ctx(), id) + require.NoError(t, err) + assert.Equal(t, "client", v.AddressKind) + require.NotNil(t, v.Client) + assert.Equal(t, "codex", v.Client.ID) + assert.True(t, v.Client.Exists) + assert.True(t, v.Client.HasAPIKey) + require.NotNil(t, v.Client.Binding) + assert.Equal(t, "ro", v.Client.Binding.Profile) + rev, err := fx.sm.ClientBindingRevision("codex") + require.NoError(t, err) + assert.Equal(t, rev, v.Client.Binding.Revision) + assert.False(t, v.ProfileRequired, "the client already has a binding") + assert.Empty(t, v.ExistingClients) + assert.Nil(t, v.PreviousLogin) + assert.Nil(t, v.Guard, "auth is on: nothing to refuse") + assert.Equal(t, "cursor ide", v.ReportedName, "shown, unverified") + assert.Len(t, v.Profiles, 2) +} + +func TestDescribe_GenericAddressListsClientsNothingPreselected(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + fx.mintClient("zed", "rw", auth.ProfileModeSwitchable) + reg := fx.register() // reports itself as "Cursor IDE" + id := fx.authorize(reg, "") + + v, err := fx.svc.Describe(fx.ctx(), id) + require.NoError(t, err) + assert.Equal(t, "generic", v.AddressKind) + assert.Nil(t, v.Client, "the generic address fixes nothing") + require.Len(t, v.ExistingClients, 2) + assert.Equal(t, "codex", v.ExistingClients[0].ID) + assert.Equal(t, "zed", v.ExistingClients[1].ID) + assert.True(t, v.ProfileRequired) + require.NotNil(t, v.SuggestedNewClient) + assert.Equal(t, "cursor-ide", v.SuggestedNewClient.ID) + + // The reported name never selects: an empty choice stays incomplete even + // though the app calls itself after an existing client. + pv, err := fx.svc.Preview(fx.ctx(), id, ApprovalChoice{}) + require.NoError(t, err) + assert.False(t, pv.Complete) + assert.Nil(t, pv.Access) +} + +func TestDescribe_SuggestedIDIsUniqueAndNeverARegistryID(t *testing.T) { + fx := newOAuthFx(t) + resp, _, err := fx.svc.Register(mcplogin.RegistrationRequest{RedirectURIs: []string{oauthTestRedirect}, ClientName: "Cursor"}) + require.NoError(t, err) + id := fx.authorize(resp["client_id"].(string), "") + v, err := fx.svc.Describe(fx.ctx(), id) + require.NoError(t, err) + assert.Equal(t, "cursor-2", v.SuggestedNewClient.ID, "cursor is a supported client's id") + assert.Equal(t, "cursor", v.SuggestedNewClient.DisplayName) +} + +func TestDescribe_ProfileRequiredOnlyWhenProfilesExistAndNoBinding(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + id := fx.authorize(reg, "cursor") // a registry client with no record yet + v, err := fx.svc.Describe(fx.ctx(), id) + require.NoError(t, err) + require.NotNil(t, v.Client) + assert.False(t, v.Client.Exists) + assert.Nil(t, v.Client.Binding) + assert.True(t, v.ProfileRequired) + + fx.cfg.Profiles = nil + v, err = fx.svc.Describe(fx.ctx(), id) + require.NoError(t, err) + assert.False(t, v.ProfileRequired, "no profiles are configured: All servers") +} + +func TestDescribe_PreviousLoginOnlyForTheSameRegistration(t *testing.T) { + fx := newOAuthFx(t) + reg, _ := fx.loginNew("cursor", "ro") + grants := fx.grants() + require.Len(t, grants, 1) + + id := fx.authorize(reg, "cursor") + v, err := fx.svc.Describe(fx.ctx(), id) + require.NoError(t, err) + require.NotNil(t, v.PreviousLogin) + assert.Equal(t, grants[0].GrantID, v.PreviousLogin.GrantID) + assert.Equal(t, 1, v.Client.Logins) + + // Another registration of the same client: signed in before? No: this + // registration never was. + other := fx.register() + id2 := fx.authorize(other, "cursor") + v2, err := fx.svc.Describe(fx.ctx(), id2) + require.NoError(t, err) + assert.Nil(t, v2.PreviousLogin) + + // A revoked login is not a previous login. + _, err = fx.svc.RevokeGrant(fx.ctx(), "cursor", grants[0].GrantID) + require.NoError(t, err) + v, err = fx.svc.Describe(fx.ctx(), id) + require.NoError(t, err) + assert.Nil(t, v.PreviousLogin) +} + +func TestDescribe_GuardVerdictForAFixedClientThatHasABinding(t *testing.T) { + fx := newOAuthFx(t) + fx.guard = ConservativeBindingGuard{} + reg, _ := fx.loginNew("cursor", "ro") // auth on: allowed + gs := fx.grants() + _, err := fx.svc.RevokeGrant(fx.ctx(), "cursor", gs[0].GrantID) + require.NoError(t, err) + fx.cfg.RequireMCPAuth = false + + id := fx.authorize(reg, "cursor") + v, err := fx.svc.Describe(fx.ctx(), id) + require.NoError(t, err) + require.NotNil(t, v.Guard, "a new live login on a named binding with auth off is refused") + assert.Equal(t, profile.ErrorCodeBindingBypassable, v.Guard.Code) + require.NotEmpty(t, v.Guard.Fixes) + assert.Equal(t, profile.GuardFixRequireMCPAuth, v.Guard.Fixes[0].Kind) +} + +func TestDescribe_DecidedOrUnknownRequestIsNotFound(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + id := fx.authorize(reg, "cursor") + _, err := fx.svc.Describe(fx.ctx(), "nope") + assert.ErrorIs(t, err, ErrOAuthRequestNotFound) + _, err = fx.svc.Deny(fx.ctx(), id) + require.NoError(t, err) + _, err = fx.svc.Describe(fx.ctx(), id) + assert.ErrorIs(t, err, ErrOAuthRequestNotFound, "decided: one uniform answer") +} + +// --- Preview ---------------------------------------------------------------------------- + +func TestPreview_CompleteVerdictAndWritesNothing(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + id := fx.authorize(reg, "cursor") + + // Profiles exist and none is chosen: incomplete, no verdict. + pv, err := fx.svc.Preview(fx.ctx(), id, ApprovalChoice{}) + require.NoError(t, err) + assert.False(t, pv.Complete) + assert.Nil(t, pv.Guard) + + pv, err = fx.svc.Preview(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + require.NoError(t, err) + assert.True(t, pv.Complete) + require.NotNil(t, pv.Access) + assert.Equal(t, PreviewAccess{Client: "cursor", Profile: "ro", Mode: auth.ProfileModeLocked, SameAccessAsExistingClient: false}, *pv.Access) + assert.Nil(t, pv.Guard) + + // auth off: the guard's verdict is part of the answer, not an error. + fx.guard = ConservativeBindingGuard{} + fx.cfg.RequireMCPAuth = false + pv, err = fx.svc.Preview(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + require.NoError(t, err) + require.NotNil(t, pv.Guard) + assert.Equal(t, profile.ErrorCodeBindingBypassable, pv.Guard.Code) + + // Invalid choices are the same errors approve answers. + _, err = fx.svc.Preview(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ghost")}) + assert.ErrorIs(t, err, ErrOAuthProfileNotFound) + + fx.nothingStored() + toks, lerr := fx.sm.ListAgentTokens() + require.NoError(t, lerr) + assert.Empty(t, toks, "a preview mints and writes nothing") + assert.Empty(t, fx.changeRows("approve")) + _, ok := fx.reqs.Get(id) + assert.True(t, ok) + r, _ := fx.reqs.Get(id) + assert.Equal(t, mcplogin.StatusPending, r.Status) +} + +func TestPreview_ExistingClientIsTheSameAccess(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "") + rev, err := fx.sm.ClientBindingRevision("codex") + require.NoError(t, err) + pv, err := fx.svc.Preview(fx.ctx(), id, ApprovalChoice{Client: ClientChoice{ID: "codex"}, BindingRevision: rev}) + require.NoError(t, err) + require.True(t, pv.Complete) + assert.True(t, pv.Access.SameAccessAsExistingClient) + assert.Equal(t, "ro", pv.Access.Profile) +} + +// --- Approve and Deny ---------------------------------------------------------------------- + +func TestApprove_StoresNothingAndRecordsTheDecision(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + id := fx.authorize(reg, "cursor") + + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + require.NoError(t, err) + u, err := url.Parse(redirect) + require.NoError(t, err) + assert.NotEmpty(t, u.Query().Get("code")) + assert.Equal(t, "st-1", u.Query().Get("state")) + assert.Equal(t, "127.0.0.1:5555", u.Host) + + fx.nothingStored() + toks, lerr := fx.sm.ListAgentTokens() + require.NoError(t, lerr) + assert.Empty(t, toks) + r, ok := fx.reqs.Get(id) + require.True(t, ok) + assert.Equal(t, mcplogin.StatusApproved, r.Status) + assert.Equal(t, "cursor", r.Decision.ClientID) + assert.True(t, r.Decision.NewClient) + assert.Equal(t, "ro", r.Decision.Profile) + assert.Equal(t, auth.ProfileModeLocked, r.Decision.Mode) + assert.Equal(t, "admin", r.Decision.ActorName) + + rows := fx.changeRows("approve") + require.Len(t, rows, 1) + assert.Equal(t, id, rows[0]["request_id"]) + assert.Equal(t, "api_key", rows[0]["actor_kind"]) + assert.Equal(t, "admin", rows[0]["actor_name"]) + assert.Equal(t, "cursor", rows[0]["client_id"]) + decided := fx.eventsOf(EventTypeOAuthAuthorizationDecided) + require.Len(t, decided, 1) + assert.Equal(t, "approved", decided[0].Payload["status"]) +} + +func TestApprove_NoStateInTheRedirectWhenTheClientSentNone(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + in := fx.authInput(reg, oauthTestOrigin+"/mcp/oauth/cursor") + in.State = "" + id, aerr := fx.svc.BeginAuthorization(in) + require.Nil(t, aerr) + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + require.NoError(t, err) + u, _ := url.Parse(redirect) + assert.False(t, u.Query().Has("state")) +} + +func TestDeny_RedirectsWithAccessDeniedAndWritesARow(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + id := fx.authorize(reg, "cursor") + redirect, err := fx.svc.Deny(fx.ctx(), id) + require.NoError(t, err) + u, _ := url.Parse(redirect) + assert.Equal(t, "access_denied", u.Query().Get("error")) + assert.Equal(t, "st-1", u.Query().Get("state")) + assert.Empty(t, u.Query().Get("code")) + rows := fx.changeRows("deny") + require.Len(t, rows, 1) + assert.Equal(t, id, rows[0]["request_id"]) + assert.Equal(t, "admin", rows[0]["actor_name"]) + fx.nothingStored() + _, err = fx.svc.Deny(fx.ctx(), id) + assert.ErrorIs(t, err, ErrOAuthAlreadyDecided) +} + +func TestApprove_Refusals(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + fx.mintClient("acme", "ro", auth.ProfileModeLocked) + reg := fx.register() + + t.Run("already decided", func(t *testing.T) { + id := fx.authorize(reg, "cursor") + _, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + require.NoError(t, err) + _, err = fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthAlreadyDecided) + code, status, ok := OAuthErrorStatus(err) + assert.True(t, ok) + assert.Equal(t, "already_decided", code) + assert.Equal(t, 409, status) + }) + t.Run("client_fixed", func(t *testing.T) { + id := fx.authorize(reg, "cursor") + _, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Client: ClientChoice{ID: "codex"}, Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthClientFixed) + _, err = fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Client: ClientChoice{New: &NewClientChoice{ID: "x"}}, Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthClientFixed) + }) + t.Run("profile_required", func(t *testing.T) { + id := fx.authorize(reg, "cursor") + _, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{}) + assert.ErrorIs(t, err, ErrOAuthProfileRequired) + }) + t.Run("client_required on the generic address", func(t *testing.T) { + id := fx.authorize(reg, "") + _, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthClientRequired) + }) + t.Run("profile_not_found", func(t *testing.T) { + id := fx.authorize(reg, "cursor") + _, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ghost")}) + assert.ErrorIs(t, err, ErrOAuthProfileNotFound) + }) + t.Run("identity_exists", func(t *testing.T) { + id := fx.authorize(reg, "") + _, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Client: ClientChoice{New: &NewClientChoice{ID: "acme"}}, Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthIdentityExists) + }) + t.Run("reserved_identity", func(t *testing.T) { + id := fx.authorize(reg, "") + _, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Client: ClientChoice{New: &NewClientChoice{ID: "cursor"}}, Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthReservedIdentity) + _, err = fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Client: ClientChoice{New: &NewClientChoice{ID: "Bad Id"}}, Profile: oauthStrp("ro")}) + var ve *ValidationError + assert.ErrorAs(t, err, &ve) + }) + t.Run("binding_changed on a stale or missing revision", func(t *testing.T) { + id := fx.authorize(reg, "codex") + _, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: "stale"}) + assert.ErrorIs(t, err, ErrOAuthBindingChanged) + _, err = fx.svc.Approve(fx.ctx(), id, ApprovalChoice{}) + assert.ErrorIs(t, err, ErrOAuthBindingChanged, "an existing client needs the revision the page displayed") + rev, _ := fx.sm.ClientBindingRevision("codex") + _, err = fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev, Profile: oauthStrp("rw")}) + assert.NoError(t, err, "the profile of an existing client is ignored") + }) + fx.nothingStored() +} + +func TestApprove_GuardRefusalCarriesTheFixesAndLeavesTheRequestPending(t *testing.T) { + fx := newOAuthFx(t) + fx.guard = ConservativeBindingGuard{} + fx.cfg.RequireMCPAuth = false + reg := fx.register() + id := fx.authorize(reg, "cursor") + _, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + var ge *BindingGuardError + require.ErrorAs(t, err, &ge, "a first approval is judged through its candidate entry") + require.NotEmpty(t, ge.Fixes) + assert.Equal(t, profile.GuardFixRequireMCPAuth, ge.Fixes[0].Kind) + code, status, _ := OAuthErrorStatus(err) + assert.Equal(t, profile.ErrorCodeBindingBypassable, code) + assert.Equal(t, 409, status) + r, _ := fx.reqs.Get(id) + assert.Equal(t, mcplogin.StatusPending, r.Status) + + // All servers (no pin) is not a named binding. + fx.cfg.Profiles = nil + _, err = fx.svc.Approve(fx.ctx(), id, ApprovalChoice{}) + assert.NoError(t, err) +} + +func TestApprove_NewCustomClientOnTheGenericAddress(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + id := fx.authorize(reg, "") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{ + Client: ClientChoice{New: &NewClientChoice{ID: "acme-agent", DisplayName: "Acme Agent"}}, Profile: oauthStrp("rw"), Mode: auth.ProfileModeSwitchable, + }) + require.NoError(t, err) + r, _ := fx.reqs.Get(id) + assert.Equal(t, "acme-agent", r.Decision.ClientID) + assert.Equal(t, "Acme Agent", r.Decision.DisplayName) + assert.Equal(t, auth.ProfileModeSwitchable, r.Decision.Mode) + assert.NotEmpty(t, oauthCodeOf(t, redirect)) +} diff --git a/internal/runtime/oauth_login_tokens.go b/internal/runtime/oauth_login_tokens.go new file mode 100644 index 000000000..52d6214f8 --- /dev/null +++ b/internal/runtime/oauth_login_tokens.go @@ -0,0 +1,357 @@ +package runtime + +import ( + "context" + "errors" + "fmt" + "net/url" + "strings" + "time" + + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/clientidentity" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/connect" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// --- refresh ---------------------------------------------------------------------- + +// Refresh is the refresh-token grant. Every refusal is the one indistinguishable +// invalid_grant, and none of them writes anything or extends a lifetime, except +// an authentic refresh token that is not the current one: that revokes the +// login (reason replay) and writes a replay_revoke row. +// +// Check order (FR-009, FR-032): origin, then parse and MAC, then the grant, +// then client and resource, then storage.RotateOAuthRefresh. +func (s *OAuthLoginService) Refresh(in TokenInput) (TokenResult, *TokenError) { + if !s.Enabled() { + return TokenResult{}, errInvalidGrant + } + key, err := s.hmacKey() + if err != nil { + s.logger.Error("browser login: cannot read the token key", zap.Error(err)) + return TokenResult{}, errTokenServer + } + grantID, secret, ok := mcplogin.ParseRefreshToken(key, in.RefreshToken) + if !ok { + return TokenResult{}, errInvalidGrant + } + grant, err := s.store.GetOAuthGrant(grantID) + if err != nil || grant == nil { + if err != nil && !errors.Is(err, storage.ErrOAuthGrantNotFound) { + s.logger.Warn("browser login: cannot read a grant", zap.Error(err)) + } + return TokenResult{}, errInvalidGrant + } + if grant.Issuer != in.Origin || grant.RegistrationID != in.ClientID { + return TokenResult{}, errInvalidGrant + } + if in.Resource != "" && in.Resource != grant.Resource { + return TokenResult{}, errInvalidTarget + } + ts, err := newTokenSet(key, grantID) + if err != nil { + s.logger.Error("browser login: cannot mint tokens", zap.Error(err)) + return TokenResult{}, errTokenServer + } + now := s.now().UTC() + outcome, after, err := s.store.RotateOAuthRefresh(grantID, mcplogin.HashSecret(key, mcplogin.KindRefresh, secret), + ts.refreshHash, ts.refreshPrefix, ts.accessHash, now, OAuthAccessTokenTTL, OAuthRefreshTokenTTL) + if err != nil { + s.logger.Error("browser login: refresh rotation failed", zap.Error(err)) + return TokenResult{}, errTokenServer + } + switch outcome { + case storage.RefreshRotated: + return ts.result(), nil + case storage.RefreshReplay: + s.writeGrantRow(profile.ChangeReplayRevoke, after, mcplogin.Decision{}, "refresh_replay") + s.publishGrantChanged(after, profile.ChangeReplayRevoke, "") + s.notifyGrantRevoked(after) + } + return TokenResult{}, errInvalidGrant +} + +// revokeReplayedCode revokes the login an authorization code produced when the +// code is presented again inside the tombstone window. +func (s *OAuthLoginService) revokeReplayedCode(grantID string) { + if grantID == "" { + return + } + now := s.now().UTC() + changed, err := s.store.RevokeOAuthGrant(grantID, storage.OAuthRevokeReplay, now) + if err != nil { + if !errors.Is(err, storage.ErrOAuthGrantNotFound) { + s.logger.Error("browser login: cannot revoke a replayed login", zap.Error(err)) + } + return + } + if !changed { + return + } + g, err := s.store.GetOAuthGrant(grantID) + if err != nil || g == nil { + return + } + s.writeGrantRow(profile.ChangeReplayRevoke, *g, mcplogin.Decision{}, "code_replay") + s.publishGrantChanged(*g, profile.ChangeReplayRevoke, "") + s.notifyGrantRevoked(*g) +} + +// --- authentication ------------------------------------------------------------------ + +// ErrOAuthUnauthorized is the one answer for every failed access-token check. +var ErrOAuthUnauthorized = errors.New("oauth access token not accepted") + +// Authenticate resolves an mcp_oat_ access token presented at origin+path. The +// grant must be live, its resource must be exactly this origin and path, and +// (on a per-client address) its client must be the path's client. The binding +// is read through storage.CurrentClientBinding, so the API-key record wins. The +// context comes from auth.ClientAuthContext, the builder the mcp_cli_ path +// uses. Every failure is the same ErrOAuthUnauthorized. +func (s *OAuthLoginService) Authenticate(accessToken, origin, path string, now time.Time) (*auth.AuthContext, *storage.OAuthGrant, error) { + if !s.Enabled() || !mcplogin.IsAccessToken(accessToken) { + return nil, nil, ErrOAuthUnauthorized + } + clientID, _, ok := mcplogin.ParseResourcePath(path) + if !ok { + return nil, nil, ErrOAuthUnauthorized + } + key, err := s.hmacKey() + if err != nil { + return nil, nil, ErrOAuthUnauthorized + } + grant, err := s.store.AuthenticateOAuthAccess(mcplogin.HashSecret(key, mcplogin.KindAccess, accessToken), now) + if err != nil { + if !errors.Is(err, storage.ErrOAuthGrantNotFound) { + s.logger.Warn("browser login: access-token lookup failed", zap.Error(err)) + } + return nil, nil, ErrOAuthUnauthorized + } + if grant.Issuer != origin || grant.Resource != origin+mcplogin.ResourcePath(clientID) || + (clientID != "" && grant.Client != clientID) { + return nil, nil, ErrOAuthUnauthorized + } + pin, mode, found, err := s.store.CurrentClientBinding(grant.Client) + if err != nil || !found { + return nil, nil, ErrOAuthUnauthorized + } + ac := auth.ClientAuthContext(auth.ClientIdentity{ + ClientID: grant.Client, ProfilePin: pin, ProfileMode: mode, + CredentialKind: auth.CredentialKindOAuth, GrantID: grant.GrantID, + TokenPrefix: grant.DisplayPrefix, TokenGeneration: grant.GrantID, + }) + return ac, grant, nil +} + +// touchInterval bounds how often a grant's last-used stamp is rewritten. +const touchInterval = time.Minute + +// Touch stamps the grant's last use and, when non-empty, the name the client +// sent at initialize. It is best effort and off the request path, like the +// agent-token stamp: one write per grant per minute, a new observed name +// always. +func (s *OAuthLoginService) Touch(grantID, observedName string) { + if grantID == "" { + return + } + observed := clientidentity.SanitizeDisplay(observedName) + now := s.now() + s.touchMu.Lock() + last, seen := s.lastTouch[grantID] + if seen && observed == "" && now.Sub(last) < touchInterval { + s.touchMu.Unlock() + return + } + if len(s.lastTouch) > 4096 { + s.lastTouch = map[string]time.Time{} + } + s.lastTouch[grantID] = now + s.touchMu.Unlock() + go func() { + if err := s.store.TouchOAuthGrant(grantID, now, observed); err != nil && !errors.Is(err, storage.ErrOAuthGrantNotFound) { + s.logger.Debug("browser login: cannot stamp last use", zap.Error(err)) + } + }() +} + +// --- admin: list and revoke ------------------------------------------------------------ + +// ListGrants returns the client's browser logins, newest approval first. +func (s *OAuthLoginService) ListGrants(clientID string) ([]storage.OAuthGrant, error) { + return s.store.ListOAuthGrantsForClient(clientID) +} + +// ErrOAuthGrantNotFound is RevokeGrant's answer for a grant that is not the +// client's. +var ErrOAuthGrantNotFound = errors.New("browser login not found") + +// RevokeGrant revokes one login of a client (reason admin) under +// bindingWriteMu, writes a `revoke` row naming the request's actor, emits +// credentials.changed and tells live sessions so they drop on their next +// request. It reports whether the login changed (an already revoked login is +// not an error). +func (s *OAuthLoginService) RevokeGrant(ctx context.Context, clientID, grantID string) (bool, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.revokeGrantLocked(ctx, clientID, grantID) +} + +func (s *OAuthLoginService) revokeGrantLocked(ctx context.Context, clientID, grantID string) (bool, error) { + g, err := s.store.GetOAuthGrant(grantID) + if err != nil || g == nil || g.Client != clientID { + if err != nil && !errors.Is(err, storage.ErrOAuthGrantNotFound) { + return false, err + } + return false, ErrOAuthGrantNotFound + } + changed, err := s.store.RevokeOAuthGrant(grantID, storage.OAuthRevokeAdmin, s.now().UTC()) + if err != nil { + if errors.Is(err, storage.ErrOAuthGrantNotFound) { + return false, ErrOAuthGrantNotFound + } + return false, err + } + if !changed { + return false, nil + } + actor, _ := RequestActor(ctx) + if actor.Surface == "" { + actor.Surface = profile.SurfaceAPI + } + pin, _, _, _ := s.store.CurrentClientBinding(clientID) + writeChangeRecord(ctx, s.activity, s.logger, s.now(), actor, changeRecord{ + change: profile.ChangeRevoke, profile: pin, previousProfile: pin, + clientID: clientID, tokenName: auth.ClientTokenName(clientID), + meta: map[string]interface{}{"grant_id": grantID, "credential_kind": CredentialKindBrowserLogin}, + }) + s.publishGrantChanged(*g, profile.ChangeRevoke, pin) + s.notifyGrantRevoked(*g) + return true, nil +} + +// notifyGrantRevoked tells the sessions of the client's name that their +// binding state changed so they re-list. A revoked access token already stops +// authenticating on the next request (storage refuses it). +func (s *OAuthLoginService) notifyGrantRevoked(g storage.OAuthGrant) { + if s.notifier != nil { + s.notifier.NotifyBindingChanged(auth.ClientTokenName(g.Client)) + } +} + +// --- rows and events --------------------------------------------------------------------- + +// CredentialKindBrowserLogin is the credentials vocabulary's name for a grant. +const CredentialKindBrowserLogin = "browser_login" + +func (s *OAuthLoginService) publishGrantChanged(g storage.OAuthGrant, change profile.ChangeKind, pin string) { + if s.publish == nil { + return + } + s.publish(newEvent(EventTypeCredentialsChanged, map[string]any{ + "kind": CredentialKindBrowserLogin, "id": g.GrantID, "client": g.Client, + "token_name": auth.ClientTokenName(g.Client), "change": string(change), "profile": pin, + })) +} + +// writeGrantRow writes a row about a STORED login on the public token endpoint +// (issue, replay_revoke): it names the administrator who approved the login and +// says the trigger was the client. +func (s *OAuthLoginService) writeGrantRow(change profile.ChangeKind, g storage.OAuthGrant, d mcplogin.Decision, reason string) { + actor := Actor{Kind: g.ApprovedBy.Kind, Name: g.ApprovedBy.Name, Surface: profile.SurfaceAPI} + pin, _, _, _ := s.store.CurrentClientBinding(g.Client) + meta := map[string]interface{}{ + "grant_id": g.GrantID, "trigger": "client", "credential_kind": CredentialKindBrowserLogin, + "approved_by": map[string]interface{}{"kind": g.ApprovedBy.Kind, "name": g.ApprovedBy.Name}, + } + if reason != "" { + meta["reason"] = reason + } + if d.ReplaceGrantID != "" { + meta["replaced_grant"] = d.ReplaceGrantID + } + writeChangeRecord(context.Background(), s.activity, s.logger, s.now(), actor, changeRecord{ + change: change, profile: pin, previousProfile: pin, + clientID: g.Client, tokenName: auth.ClientTokenName(g.Client), meta: meta, + }) +} + +// writeDecisionRow writes the `deny` row of an exchange that was refused after +// approval: it names the approving administrator with trigger client. +func (s *OAuthLoginService) writeDecisionRow(change profile.ChangeKind, req mcplogin.Request, reason string, now time.Time) { + actor := Actor{Kind: req.Decision.ActorKind, Name: req.Decision.ActorName, Surface: profile.SurfaceAPI} + writeChangeRecord(context.Background(), s.activity, s.logger, now, actor, changeRecord{ + change: change, profile: req.Decision.Profile, + clientID: req.Decision.ClientID, tokenName: auth.ClientTokenName(req.Decision.ClientID), + meta: map[string]interface{}{"request_id": req.ID, "trigger": "client", "reason": reason}, + }) +} + +// --- guard ------------------------------------------------------------------------------- + +// guardStatesFor builds the current state and the candidate state a login of +// clientID with (pin, mode) would create: the candidate adds or replaces the +// client's own browser-login entry with Live true, before anything is stored. +// A storage read error is returned and the caller must refuse (fail closed). +func (s *OAuthLoginService) guardStatesFor(clientID, pin, mode string) (current, candidate GuardState, err error) { + all, err := s.store.ListAgentTokens() + if err != nil { + return current, candidate, fmt.Errorf("cannot inspect client bindings: %w", err) + } + oauth, err := LoadOAuthBindings(s.store, s.now()) + if err != nil { + return current, candidate, err + } + cfg := s.cfg() + tokens := guardedOnly(all) + current = GuardState{Config: cfg, Tokens: tokens, OAuthBindings: oauth} + candidate = GuardState{Config: cfg, Tokens: tokens, + OAuthBindings: withOAuthClient(oauth, OAuthBinding{ClientID: clientID, Pin: pin, Mode: mode, Live: true})} + return current, candidate, nil +} + +func (s *OAuthLoginService) recheckGuard(d mcplogin.Decision) error { + cur, cand, err := s.guardStatesFor(d.ClientID, d.Profile, d.Mode) + if err != nil { + return err + } + return CheckBindingGuard(s.guard(), cur, cand) +} + +// --- name mismatch (research R14) ------------------------------------------------------- + +// OAuthNameMismatch derives the advisory warning of a login: the name the +// client sent at initialize is neither the name it registered with nor, for a +// registry client, one of its id, display name or ClientInfoNames. An empty +// observed name never mismatches. It takes no part in selection or +// authorization. +func OAuthNameMismatch(observed, reportedName, clientID string) bool { + norm := clientidentity.NormalizeRaw(observed) + if norm == "" { + return false + } + known := []string{reportedName} + if def := connect.FindClient(clientID); def != nil { + known = append(known, def.ID, def.Name) + known = append(known, def.ClientInfoNames...) + } + for _, k := range known { + if k != "" && (norm == clientidentity.NormalizeRaw(k) || clientidentity.AliasCandidate(observed) == clientidentity.NormalizeRaw(k)) { + return false + } + } + return true +} + +// redirectHost is the host part of a stored redirect URI, for listings. +func redirectHost(raw string) string { + u, err := url.Parse(raw) + if err != nil { + return "" + } + return strings.ToLower(u.Hostname()) +} diff --git a/internal/runtime/profiles_service.go b/internal/runtime/profiles_service.go index 5ca4784fb..0fbd6a0ec 100644 --- a/internal/runtime/profiles_service.go +++ b/internal/runtime/profiles_service.go @@ -240,6 +240,9 @@ func (s *ProfilesService) usedByAll(cfg *config.Config) (map[string]*UsedBy, err u.Tokens = append(u.Tokens, t.Name) } } + if err := s.addOAuthUsers(tokens, func(pin string) *UsedBy { return out[pin] }); err != nil { + return nil, err + } for _, u := range out { sortUsedBy(u) } @@ -281,6 +284,14 @@ func (s *ProfilesService) UsedBy(name string) (UsedBy, error) { u.Tokens = append(u.Tokens, t.Name) } } + if err := s.addOAuthUsers(tokens, func(pin string) *UsedBy { + if pin == name { + return &u + } + return nil + }); err != nil { + return u, err + } sortUsedBy(&u) if cfg := s.rt.Config(); cfg != nil { u.AnonymousProfile = cfg.AnonymousProfile == name diff --git a/internal/runtime/profiles_service_oauth.go b/internal/runtime/profiles_service_oauth.go new file mode 100644 index 000000000..59c6e8bfe --- /dev/null +++ b/internal/runtime/profiles_service_oauth.go @@ -0,0 +1,47 @@ +package runtime + +import ( + "fmt" + "time" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// addOAuthUsers adds the clients that are bound to a profile only through +// browser logins (Spec 132): a client with a live login and a named pin is a +// user of that profile exactly like one with an API key, so a profile delete +// reports it in profile_in_use and a reassign moves it. A client that has an +// active API-key record is already listed through the record and is not +// counted twice. target returns the used-by list for a pin, or nil when the +// pin is not one the caller collects. A read error fails the call (fail +// closed): an unreadable store must not look like "nobody uses it". +func (s *ProfilesService) addOAuthUsers(tokens []auth.AgentToken, target func(pin string) *UsedBy) error { + sm := s.rt.StorageManager() + if sm == nil { + return nil + } + now := time.Now() + bindings, err := LoadOAuthBindings(sm, now) + if err != nil { + return fmt.Errorf("cannot read browser-login bindings: %w", err) + } + if len(bindings) == 0 { + return nil + } + active := map[string]bool{} + for i := range tokens { + t := &tokens[i] + if t.Kind == auth.KindClient && t.UserID == "" && !t.Revoked && t.ExpiresAt.After(now) { + active[t.ClientID] = true + } + } + for _, b := range bindings { + if !b.Live || b.Pin == "" || active[b.ClientID] { + continue + } + if u := target(b.Pin); u != nil { + u.Clients = append(u.Clients, UsedByClient{ID: b.ClientID, Mode: b.Mode}) + } + } + return nil +} diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index 5416bc339..2030b2fe2 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -448,6 +448,9 @@ type Runtime struct { // credentialsService is Spec 115's issuance/revocation facade over both // credential kinds; it shares bindingWriteMu with clientsService. credentialsService *CredentialsService + // oauthLoginService is Spec 132's browser-login service; it shares + // bindingWriteMu with the two services above. + oauthLoginService *OAuthLoginService // profilesService is Spec 108-f's single profiles service; the evaluator // and session hook are installed by the server. profilesService *ProfilesService @@ -776,6 +779,26 @@ func New(cfg *config.Config, cfgPath string, logger *zap.Logger) (*Runtime, erro Logger: logger, }) + // Spec 132: the browser-login service. Same mutex as the two services + // above (the one lock order is documented on OAuthLoginService); revoking + // or forgetting a client cancels that client's pending sign-in requests + // through it. + rt.oauthLoginService = NewOAuthLoginService(OAuthLoginDeps{ + Store: storageManager, + HMACKey: func() ([]byte, error) { + return auth.GetOrCreateHMACKey(rt.Config().DataDir) + }, + Config: rt.Config, + Guard: rt.BindingGuard, + Activity: storageManager.SaveActivity, + Publish: rt.publishEvent, + Mu: &rt.bindingWriteMu, + Logger: logger, + }) + rt.clientsService.SetLoginCanceler(func(clientID string) { rt.oauthLoginService.CancelForClient(clientID) }) + rt.credentialsService.SetOAuthLogin(rt.oauthLoginService) + rt.repairOAuthBindings() + rt.profilesService = newProfilesService(rt) // Spec 047: drainer goroutine that publishes coalesced servers.changed diff --git a/internal/server/mcp.go b/internal/server/mcp.go index 447afebed..263764aa2 100644 --- a/internal/server/mcp.go +++ b/internal/server/mcp.go @@ -817,6 +817,9 @@ func NewMCPProxyServer( if ac := auth.AuthContextFromContext(ctx); ac != nil && ac.AgentName != "" { sessionStore.SetSessionIdentity(sessionID, ac.AgentName, ac.ClientID) sessionStore.SetSessionTokenPrefix(sessionID, ac.TokenPrefix) + if ac.GrantID != "" { + sessionStore.SetSessionGrantID(sessionID, ac.GrantID) + } } sessionStore.SetSessionServer(sessionID, mcpserver.ServerFromContext(ctx)) // Spec 108-f F10: a session that presented no credential has diff --git a/internal/server/mcp_activity_attribution.go b/internal/server/mcp_activity_attribution.go index 09e3da93e..ec9e59841 100644 --- a/internal/server/mcp_activity_attribution.go +++ b/internal/server/mcp_activity_attribution.go @@ -69,6 +69,9 @@ func (p *MCPProxyServer) activityAttribution(ctx context.Context, sessionID stri if attr.ClientID == "" && ac.IsClientCredential() { attr.ClientID = ac.ClientID } + if attr.GrantID == "" { + attr.GrantID = ac.GrantID + } } if sessionID == "" { @@ -99,6 +102,9 @@ func (p *MCPProxyServer) activityAttribution(ctx context.Context, sessionID stri if attr.ClientID == "" && sessionCredential { attr.ClientID = info.ClientID } + if attr.GrantID == "" && sessionCredential { + attr.GrantID = info.GrantID + } if attr.ProfileSource == "" { attr.Profile = info.Profile attr.ProfileSource = info.ProfileSource diff --git a/internal/server/oauth_login_attribution_test.go b/internal/server/oauth_login_attribution_test.go new file mode 100644 index 000000000..30cc62848 --- /dev/null +++ b/internal/server/oauth_login_attribution_test.go @@ -0,0 +1,42 @@ +package server + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +func browserLoginContext(grant string) context.Context { + return auth.WithAuthContext(context.Background(), auth.ClientAuthContext(auth.ClientIdentity{ + ClientID: "cursor", ProfilePin: "dev", ProfileMode: auth.ProfileModeLocked, + CredentialKind: auth.CredentialKindOAuth, GrantID: grant, TokenPrefix: "mcp_oat_" + grant[:4], TokenGeneration: grant, + })) +} + +// Spec 132 R3: two logins of one client are two work sessions (the grant id is +// the credential generation), and a revoked login never merges with a new one. +func TestPrincipalFromContext_BrowserLoginsOfOneClientAreSeparate(t *testing.T) { + a, b := browserLoginContext("grantAAAAAAAAAAAAAAAAAA"), browserLoginContext("grantBBBBBBBBBBBBBBBBBB") + assert.NotEqual(t, principalFromContext(a), principalFromContext(b)) + assert.Contains(t, principalFromContext(a), "agent:client-cursor:") +} + +// Session-backed and request-backed activity both carry the grant id. +func TestActivityAttribution_BrowserLoginCarriesGrantID(t *testing.T) { + f := newProfilesV3RESTFixture(t, nil) + ctx := browserLoginContext("grantAAAAAAAAAAAAAAAAAA") + attr := f.proxy.activityAttribution(ctx, "") + assert.Equal(t, "grantAAAAAAAAAAAAAAAAAA", attr.GrantID) + assert.Equal(t, "cursor", attr.ClientID, "attributed to the client exactly like its mcp_cli_ credential") + assert.Equal(t, "client-cursor", attr.TokenName) + + // A ctx-less internal emitter reads the grant back from the session. + f.proxy.sessionStore.SetSession("s-oauth", "Cursor", "1.0", false, false, nil) + f.proxy.sessionStore.SetSessionIdentity("s-oauth", "client-cursor", "cursor") + f.proxy.sessionStore.SetSessionGrantID("s-oauth", "grantAAAAAAAAAAAAAAAAAA") + attr = f.proxy.activityAttribution(context.Background(), "s-oauth") + assert.Equal(t, "grantAAAAAAAAAAAAAAAAAA", attr.GrantID) +} diff --git a/internal/server/profile_binding_guard.go b/internal/server/profile_binding_guard.go index 529b9fa11..56990c033 100644 --- a/internal/server/profile_binding_guard.go +++ b/internal/server/profile_binding_guard.go @@ -41,6 +41,14 @@ func (p *MCPProxyServer) bindingGuardActive(idx *profileIndex) bool { } return true } + oauthBindings, err := runtime.LoadOAuthBindings(p.storage, time.Now()) + if err != nil { + if p.logger != nil { + p.logger.Error("cannot inspect browser-login bindings for anonymous profile guard", zap.Error(err)) + } + return true + } + tokens = runtime.GuardState{Tokens: tokens, OAuthBindings: oauthBindings}.EffectiveTokens(time.Now()) if cfg == nil || idx == nil || idx.cfg == nil { // During a publication gap the guard cannot compare reachability. Any // live named client binding therefore denies anonymous access until a @@ -123,15 +131,17 @@ func (p *MCPProxyServer) BindingGuardDelta(current, candidate runtime.GuardState curIdx := newProfileIndex(current.Config) candIdx := newProfileIndex(candidate.Config) already := make(map[string]bool) - for i := range current.Tokens { - t := ¤t.Tokens[i] + currentTokens := current.EffectiveTokens(e.now) + for i := range currentTokens { + t := ¤tTokens[i] if e.bypassable(current.Config, curIdx, t) { already[t.Name] = true } } var out []runtime.BindingRef - for i := range candidate.Tokens { - t := &candidate.Tokens[i] + candidateTokens := candidate.EffectiveTokens(e.now) + for i := range candidateTokens { + t := &candidateTokens[i] if !already[t.Name] && e.bypassable(candidate.Config, candIdx, t) { out = append(out, runtime.BindingRefOf(t)) } @@ -167,8 +177,9 @@ func (p *MCPProxyServer) BindingGuardFixes(candidate runtime.GuardState, delta [ altIdx := newProfileIndex(&alt) e := p.newGuardEvaluation() qualifies := true - for i := range candidate.Tokens { - t := &candidate.Tokens[i] + fixTokens := candidate.EffectiveTokens(e.now) + for i := range fixTokens { + t := &fixTokens[i] if e.bypassable(&alt, altIdx, t) { qualifies = false break @@ -195,8 +206,16 @@ func (p *MCPProxyServer) BindingGuardActiveBindings() []runtime.BindingRef { } return nil } + oauthBindings, err := runtime.LoadOAuthBindings(p.storage, time.Now()) + if err != nil { + if p.logger != nil { + p.logger.Error("cannot inspect browser-login bindings for the binding guard", zap.Error(err)) + } + return nil + } idx := p.profileIndexFor(cfg) e := p.newGuardEvaluation() + tokens = runtime.GuardState{Tokens: tokens, OAuthBindings: oauthBindings}.EffectiveTokens(e.now) var out []runtime.BindingRef for i := range tokens { if e.bypassable(cfg, idx, &tokens[i]) { diff --git a/internal/server/profile_binding_guard_oauth_test.go b/internal/server/profile_binding_guard_oauth_test.go new file mode 100644 index 000000000..b8732a085 --- /dev/null +++ b/internal/server/profile_binding_guard_oauth_test.go @@ -0,0 +1,86 @@ +package server + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// oauthOnlyGuardProxy builds a proxy whose only binding is a browser login: +// client "cursor", no API key, a live grant, bound to profile P (locked). +func oauthOnlyGuardProxy(t *testing.T, anonymousProfile string) (*MCPProxyServer, *profileIndex) { + t.Helper() + proxy, rt := createTestProxyWithRuntimeCfg(t, []*config.ServerConfig{{Name: "a", Enabled: true}}, func(cfg *config.Config) { + cfg.RequireMCPAuth = false + cfg.AnonymousProfile = anonymousProfile + cfg.Profiles = []config.ProfileConfig{{Name: "P", Servers: []string{"a"}}} + }) + sm := rt.StorageManager() + now := time.Now() + require.NoError(t, sm.CreateOAuthRegistration(storage.OAuthRegistration{ + ClientID: "reg1", ReportedName: "Cursor IDE", RedirectURIs: []string{"http://127.0.0.1:9/cb"}, + TokenEndpointAuthMethod: "none", GrantTypes: []string{"authorization_code", "refresh_token"}, CreatedAt: now, + })) + _, err := sm.CommitOAuthLogin(storage.CommitLoginInput{ + Grant: storage.OAuthGrant{ + GrantID: "grantAAAAAAAAAAAAAAAAAA", RegistrationID: "reg1", Client: "cursor", + RedirectURI: "http://127.0.0.1:9/cb", Resource: "http://127.0.0.1:8080/mcp/oauth/cursor", Issuer: "http://127.0.0.1:8080", + RefreshHash: "rh", AccessHash: "ah", AccessExpiresAt: now.Add(time.Hour), RefreshExpiresAt: now.Add(24 * time.Hour), + ApprovedAt: now, DisplayPrefix: "mcp_oat_abcd", + }, + Client: "cursor", NewClient: true, Pin: "P", Mode: auth.ProfileModeLocked, + ExpectedBindingRevision: storage.OAuthBindingAbsent, Now: now, + }) + require.NoError(t, err) + return proxy, proxy.profileIndexFor(proxy.currentConfig()) +} + +// Spec 132 R5: an OAuth-only client with a named pin and a live grant is an +// active binding, so an anonymous caller that could escape it is denied. +func TestBindingGuard_OAuthOnlyClientGuardsAnonymous(t *testing.T) { + proxy, idx := oauthOnlyGuardProxy(t, "") + got := proxy.ResolveProfileV3(context.Background(), idx) + require.Equal(t, string(profile.SourceAnonymous), got.Source) + require.True(t, got.BindingGuarded, "a live browser login bound to P is a binding anonymous could escape") + + active := proxy.BindingGuardActiveBindings() + require.Len(t, active, 1) + require.Equal(t, "cursor", active[0].ClientID) + require.Equal(t, "P", active[0].Profile) + + // Revoking the login ends the binding. + _, err := proxy.storage.RevokeOAuthGrant("grantAAAAAAAAAAAAAAAAAA", storage.OAuthRevokeAdmin, time.Now()) + require.NoError(t, err) + got = proxy.ResolveProfileV3(context.Background(), idx) + require.False(t, got.BindingGuarded, "a revoked login binds nothing") + require.Empty(t, proxy.BindingGuardActiveBindings()) +} + +func TestBindingGuard_OAuthEntryIsEvaluatedThroughItsCandidate(t *testing.T) { + proxy, _ := bindingGuardTestProxy(t, "", []config.ProfileConfig{{Name: "P", Servers: []string{"a"}}}, auth.ProfileModeLocked, "P") + cfg := proxy.currentConfig() + cur := runtime.GuardState{Config: cfg} + cand := runtime.GuardState{Config: cfg, OAuthBindings: []runtime.OAuthBinding{ + {ClientID: "cursor2", Pin: "P", Mode: auth.ProfileModeLocked, Live: true}, + }} + delta := proxy.BindingGuardDelta(cur, cand) + require.Len(t, delta, 1, "a first approval is judged through its candidate entry before anything is stored") + require.Equal(t, "cursor2", delta[0].ClientID) + fixes := proxy.BindingGuardFixes(cand, delta) + require.NotEmpty(t, fixes) + require.Equal(t, profile.GuardFixRequireMCPAuth, fixes[0].Kind) + + // Not live: no binding. Unchanged: nothing new. + cand.OAuthBindings[0].Live = false + require.Empty(t, proxy.BindingGuardDelta(cur, cand)) + cand.OAuthBindings[0].Live = true + require.Empty(t, proxy.BindingGuardDelta(cand, cand)) +} diff --git a/internal/server/session_store.go b/internal/server/session_store.go index 807be5854..d4eabe321 100644 --- a/internal/server/session_store.go +++ b/internal/server/session_store.go @@ -90,6 +90,10 @@ type SessionInfo struct { // no request context read it back so an event carries the same ownership // proof the SSE renderer checks (name AND prefix). TokenPrefix string + // GrantID is the browser-login grant that authenticated the session (Spec + // 132), set once at initialize like TokenName; empty for every other + // credential. INTERNAL: it only feeds activity attribution. + GrantID string // Anonymous marks a session that presented no credential (Spec 108-f F10): // its base is the snapshot's anonymous_profile, read at notify time. Memory diff --git a/internal/server/session_store_grant.go b/internal/server/session_store_grant.go new file mode 100644 index 000000000..0a55e87f7 --- /dev/null +++ b/internal/server/session_store_grant.go @@ -0,0 +1,15 @@ +package server + +// SetSessionGrantID records the browser-login grant that authenticated a +// session (Spec 132 R3), next to SetSessionTokenPrefix, so session-backed +// activity emitted without a request context still carries it. +func (s *SessionStore) SetSessionGrantID(sessionID, grantID string) { + if sessionID == "" { + return + } + s.mu.Lock() + defer s.mu.Unlock() + if info, ok := s.sessions[sessionID]; ok { + info.GrantID = grantID + } +} diff --git a/internal/storage/client_binding_update.go b/internal/storage/client_binding_update.go new file mode 100644 index 000000000..ceafb1530 --- /dev/null +++ b/internal/storage/client_binding_update.go @@ -0,0 +1,46 @@ +package storage + +import ( + "fmt" + + "go.etcd.io/bbolt" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// UpdateOAuthClientBinding rewrites the binding of a client that has a +// browser-login entry, whether or not its API-key record is active (an +// UpdateClientCredentialBinding of a revoked or absent API key refuses). It +// goes through the one binding writer, so an API-key record that exists is kept +// equal. It returns the binding the client held before (the API-key record +// wins, as everywhere on the request path). ErrClientCredentialNotFound means +// the client has no browser-login entry. +func (m *Manager) UpdateOAuthClientBinding(clientID, pin, mode string) (beforePin, beforeMode string, err error) { + if !auth.ValidClientID(clientID) { + return "", "", fmt.Errorf("invalid client id %q", clientID) + } + if err := validateClientBinding(pin, mode); err != nil { + return "", "", err + } + m.mu.Lock() + defer m.mu.Unlock() + err = m.db.db.Update(func(tx *bbolt.Tx) error { + b, err := getOAuthBindingTx(tx, clientID) + if err != nil { + return err + } + if b == nil { + return ErrClientCredentialNotFound + } + var exists bool + beforePin, beforeMode, exists, err = currentClientBindingTx(tx, clientID) + if err != nil { + return err + } + if !exists { + return ErrClientCredentialNotFound + } + return writeClientBindingOptsTx(tx, clientID, pin, mode, true) + }) + return beforePin, beforeMode, err +} diff --git a/internal/storage/client_binding_update_test.go b/internal/storage/client_binding_update_test.go new file mode 100644 index 000000000..4911521cb --- /dev/null +++ b/internal/storage/client_binding_update_test.go @@ -0,0 +1,49 @@ +package storage + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +func TestUpdateOAuthClientBinding_OAuthOnlyClient(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + commitNew(t, m, "r", "g1", "webonly", "ro", auth.ProfileModeLocked, time.Now().UTC()) + + pin, mode, err := m.UpdateOAuthClientBinding("webonly", "", auth.ProfileModeSwitchable) + require.NoError(t, err) + assert.Equal(t, "ro", pin) + assert.Equal(t, auth.ProfileModeLocked, mode) + p, md, found, err := m.CurrentClientBinding("webonly") + require.NoError(t, err) + require.True(t, found) + assert.Equal(t, "", p) + assert.Equal(t, auth.ProfileModeSwitchable, md) + + // Invalid: locked needs a pin; nothing changes. + _, _, err = m.UpdateOAuthClientBinding("webonly", "", auth.ProfileModeLocked) + require.Error(t, err) + _, md, _, _ = m.CurrentClientBinding("webonly") + assert.Equal(t, auth.ProfileModeSwitchable, md) + + // A client with no browser-login entry is NotFound. + _, _, err = m.UpdateOAuthClientBinding("ghost", "ro", auth.ProfileModeLocked) + assert.ErrorIs(t, err, ErrClientCredentialNotFound) +} + +func TestUpdateOAuthClientBinding_KeepsBothCopiesEqualEvenWhenKeyIsRevoked(t *testing.T) { + m, cleanup := setupTestStorageForAgentTokens(t) + defer cleanup() + twoLoginClient(t, m) + _, err := m.RevokeClientAPIKey("cursor") + require.NoError(t, err) + + _, _, err = m.UpdateOAuthClientBinding("cursor", "rw", auth.ProfileModeSwitchable) + require.NoError(t, err, "a revoked API key does not block a binding change of a client with live logins") + assertEqualBindings(t, m, "cursor", "rw", auth.ProfileModeSwitchable) +} From a59231581b10b181bf16a30738becd57dd44083e Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 21:22:11 +0200 Subject: [PATCH 12/42] fix(oauth): close cancellation, token-endpoint and client-view gaps (Spec 132 PR-1d) Related #1971 --- internal/mcplogin/cancel_report.go | 19 + internal/mcplogin/origin_test.go | 46 ++ internal/mcplogin/requests.go | 24 +- internal/runtime/clients_service.go | 25 +- internal/runtime/clients_service_connect.go | 29 +- internal/runtime/clients_service_oauth.go | 9 +- internal/runtime/commit.go | 8 +- internal/runtime/credential_input_screen.go | 4 +- internal/runtime/credentials_service.go | 58 ++- internal/runtime/credentials_service_oauth.go | 19 +- internal/runtime/oauth_login_consent.go | 24 +- internal/runtime/oauth_login_review_test.go | 437 ++++++++++++++++++ internal/runtime/oauth_login_service.go | 96 +++- internal/runtime/oauth_login_tokens.go | 11 +- internal/runtime/profiles_service_oauth.go | 23 +- 15 files changed, 771 insertions(+), 61 deletions(-) create mode 100644 internal/mcplogin/cancel_report.go create mode 100644 internal/mcplogin/origin_test.go create mode 100644 internal/runtime/oauth_login_review_test.go diff --git a/internal/mcplogin/cancel_report.go b/internal/mcplogin/cancel_report.go new file mode 100644 index 000000000..7619d5328 --- /dev/null +++ b/internal/mcplogin/cancel_report.go @@ -0,0 +1,19 @@ +package mcplogin + +import "sort" + +// CancelAllReport cancels every pending and approved-but-unconsumed request in +// ONE critical section and returns the ids of the requests that were still +// pending, so a caller can announce them without a race between listing and +// cancelling. +func (s *Store) CancelAllReport() (pendingIDs []string, cancelled int) { + s.mu.Lock() + defer s.mu.Unlock() + for id := range s.reqs { + if r := s.live(id); r != nil && r.Status == StatusPending { + pendingIDs = append(pendingIDs, id) + } + } + sort.Strings(pendingIDs) + return pendingIDs, s.cancelWhere(func(*Request) bool { return true }) +} diff --git a/internal/mcplogin/origin_test.go b/internal/mcplogin/origin_test.go new file mode 100644 index 000000000..b93bd8c4b --- /dev/null +++ b/internal/mcplogin/origin_test.go @@ -0,0 +1,46 @@ +package mcplogin + +import ( + "errors" + "testing" +) + +// The issuer rides on the code for its whole life: a replay on another origin +// is refused before replay handling (no grant id comes back to revoke). +func TestConsumeAt_OriginIsCheckedBeforeConsumptionAndReplay(t *testing.T) { + s, _ := newTestStore() + r := mustCreate(t, s, "cursor") + code, err := s.Approve(r.ID, Decision{ClientID: "cursor"}) + if err != nil { + t.Fatal(err) + } + if _, _, err := s.ConsumeAt(code, "http://localhost:8080", func(Request) (string, error) { return "g", nil }); !errors.Is(err, ErrCodeOriginMismatch) { + t.Fatalf("wrong origin on a live code: %v", err) + } + if _, g, err := s.ConsumeAt(code, r.Issuer, func(Request) (string, error) { return "g1", nil }); err != nil || g != "g1" { + t.Fatalf("the code is still usable on its own origin: %v %q", err, g) + } + // Replay: the right origin reports the grant, another origin learns nothing. + if _, g, err := s.ConsumeAt(code, "http://localhost:8080", nil); !errors.Is(err, ErrCodeOriginMismatch) || g != "" { + t.Fatalf("replay on another origin: %v %q", err, g) + } + if _, g, err := s.ConsumeAt(code, r.Issuer, nil); !errors.Is(err, ErrCodeReused) || g != "g1" { + t.Fatalf("replay on the same origin: %v %q", err, g) + } +} + +func TestCancelAllReport(t *testing.T) { + s, _ := newTestStore() + a := mustCreate(t, s, "") + b := mustCreate(t, s, "") + if _, err := s.Approve(b.ID, Decision{ClientID: "c"}); err != nil { + t.Fatal(err) + } + ids, n := s.CancelAllReport() + if n != 2 || len(ids) != 1 || ids[0] != a.ID { + t.Fatalf("ids=%v n=%d", ids, n) + } + if ids, n = s.CancelAllReport(); n != 0 || len(ids) != 0 { + t.Fatal("second call finds nothing") + } +} diff --git a/internal/mcplogin/requests.go b/internal/mcplogin/requests.go index 5c4768035..2fe687ff1 100644 --- a/internal/mcplogin/requests.go +++ b/internal/mcplogin/requests.go @@ -31,6 +31,9 @@ var ( // ErrCodeReused means a consumed code was presented again inside the // tombstone window. Consume returns the grant id it produced. ErrCodeReused = errors.New("mcplogin: authorization code already used") + // ErrCodeOriginMismatch means the code was presented on another origin than + // the one it was issued for. Nothing is consumed and nothing is revoked. + ErrCodeOriginMismatch = errors.New("mcplogin: authorization code presented on another origin") ) // Status is the state of an authorization request. @@ -99,6 +102,10 @@ type codeEntry struct { consumed bool consumedAt time.Time grantID string // empty when the commit failed + // issuer is the origin the request was made on. It stays on the entry (and + // so on the tombstone) for its whole life, so a replay on another origin is + // refused before replay handling. + issuer string } // Store holds authorization requests and their codes. It is safe for @@ -223,7 +230,7 @@ func (s *Store) Approve(id string, d Decision) (string, error) { // Pending expiry and approved-code expiry are separate: an approved // request lives exactly as long as its code. r.ExpiresAt = now.Add(CodeLifetime) - s.codes[HashSecret(s.key, KindCode, code)] = &codeEntry{requestID: id, expiresAt: now.Add(CodeLifetime)} + s.codes[HashSecret(s.key, KindCode, code)] = &codeEntry{requestID: id, expiresAt: now.Add(CodeLifetime), issuer: r.Issuer} return code, nil } @@ -284,6 +291,18 @@ func (s *Store) CancelAll() int { // unknown. This holds for a code whose commit failed as well, with an empty // grant id: callers must treat an empty grant id as "nothing to revoke". func (s *Store) Consume(code string, commit func(Request) (grantID string, err error)) (Request, string, error) { + return s.consume(code, "", false, commit) +} + +// ConsumeAt is Consume that first requires the code to have been issued for +// origin. The comparison happens inside the store, BEFORE consumption and +// BEFORE replay handling, and also for an already consumed code: a mismatch is +// ErrCodeOriginMismatch with nothing consumed and no grant id returned. +func (s *Store) ConsumeAt(code, origin string, commit func(Request) (grantID string, err error)) (Request, string, error) { + return s.consume(code, origin, true, commit) +} + +func (s *Store) consume(code, origin string, checkOrigin bool, commit func(Request) (string, error)) (Request, string, error) { h := HashSecret(s.key, KindCode, code) s.mu.Lock() defer s.mu.Unlock() @@ -293,6 +312,9 @@ func (s *Store) Consume(code string, commit func(Request) (grantID string, err e if e == nil { return Request{}, "", ErrCodeUnknown } + if checkOrigin && e.issuer != origin { + return Request{}, "", ErrCodeOriginMismatch + } if e.consumed { if now.Before(e.consumedAt.Add(TombstoneLifetime)) { return Request{}, e.grantID, ErrCodeReused diff --git a/internal/runtime/clients_service.go b/internal/runtime/clients_service.go index d79039feb..c58508926 100644 --- a/internal/runtime/clients_service.go +++ b/internal/runtime/clients_service.go @@ -765,13 +765,24 @@ func (s *ClientsService) forgetLockedChange(ctx context.Context, a Actor, client // forgetRecordLocked is forgetLockedChange returning the committed revoked // record, so the credentials service projects its view without a re-read. func (s *ClientsService) forgetRecordLocked(ctx context.Context, a Actor, clientID string, diff map[string]interface{}, restorePrior bool, change profile.ChangeKind) (*auth.AgentToken, error) { + // Cancel the client's pending and approved sign-in requests FIRST, under the + // mutex the token exchange commits under, and whatever the storage call + // below answers: a client with nothing stored yet (no_client_credential) + // must not keep an approved first login alive (Spec 132 R15). + s.cancelLoginRequests(clientID) forget := s.store.ForgetClientCredential if restorePrior { forget = s.store.ForgetClientCredentialRestoringPrior - } else if o := s.oauthStore(); s.hasLoginRecords(o, clientID) { - // Spec 132: forget deletes the client's browser logins, revoke marks - // them revoked; both cover the API key exactly as before. - forget = s.oauthForgetFunc(o, change) + } else if o := s.oauthStore(); o != nil { + hasLogins, herr := s.hasLoginRecords(o, clientID) + if herr != nil { + return nil, herr // fail closed: never leave live logins behind + } + if hasLogins { + // Spec 132: forget deletes the client's browser logins, revoke + // marks them revoked; both cover the API key exactly as before. + forget = s.oauthForgetFunc(o, change) + } } // The restore path rewrites the revoked record's binding, so capture the // binding it held when revoked for the audit record. @@ -793,14 +804,12 @@ func (s *ClientsService) forgetRecordLocked(ctx context.Context, a Actor, client if !restorePrior { heldPin = revoked.ProfilePin } - // Revoking or forgetting a client also cancels its pending and approved - // sign-in requests, under the same mutex the token exchange commits under - // (Spec 132 R15). - s.cancelLoginRequests(clientID) s.writeChange(ctx, a, changeRecord{ change: change, profile: heldPin, previousProfile: heldPin, clientID: clientID, tokenName: revoked.Name, diff: diff, }) + // Live MCP sessions and streams are not terminated here: a revoked login is + // refused on its next request, which the HTTP layer enforces per request. if s.publish != nil { s.publish(newEvent(EventTypeCredentialsChanged, map[string]any{ "kind": CredentialKindClient, "id": clientID, "token_name": revoked.Name, diff --git a/internal/runtime/clients_service_connect.go b/internal/runtime/clients_service_connect.go index e0ca39ab5..8dfe795ca 100644 --- a/internal/runtime/clients_service_connect.go +++ b/internal/runtime/clients_service_connect.go @@ -116,7 +116,30 @@ func (s *ClientsService) releaseConnect(clientID, token string) { // instead of silently widening a profile-locked client to All servers. A // tombstone with no binding (or no record) starts from the defaults, and an // explicit profile always wins. -func (s *ClientsService) resolveBindingLocked(rec *auth.AgentToken, profilePtr, modePtr *string) (pin, mode string, err error) { +func (s *ClientsService) resolveBindingLocked(clientID string, rec *auth.AgentToken, profilePtr, modePtr *string) (pin, mode string, err error) { + // Spec 132: a client with browser logins and no API-key record keeps the + // binding of its logins when the connect names no profile, exactly as a + // reconnect keeps a record's. A read error refuses (fail closed); explicit + // arguments override and still go through the guard. + if rec == nil && profilePtr == nil { + if o := s.oauthStore(); o != nil { + entry, gerr := o.GetOAuthClientBinding(clientID) + if gerr != nil { + return "", "", fmt.Errorf("cannot read browser-login bindings: %w", gerr) + } + if entry != nil { + pin = entry.ProfilePin + mode, err = resolveMode(pin, modePtr, entry.ProfileMode) + if err != nil { + return "", "", err + } + if pin != "" && !s.profileExists(s.cfg(), pin) { + return "", "", &ValidationError{Field: "profile", Message: fmt.Sprintf("unknown profile %q", pin)} + } + return pin, mode, nil + } + } + } keepBinding := rec != nil && profilePtr == nil && (s.stateOf(rec) == profile.CredentialStateClient || s.stateOf(rec) == profile.CredentialStateExpired || s.stateOf(rec) == profile.CredentialStateRevoked) @@ -161,7 +184,7 @@ func (s *ClientsService) issueLockedRecord(clientID string, profilePtr, modePtr return nil, nil, &ValidationError{Field: "id", Message: fmt.Sprintf("client %s already has an active credential; rotate it instead", clientID)} } - pin, mode, err := s.resolveBindingLocked(rec, profilePtr, modePtr) + pin, mode, err := s.resolveBindingLocked(clientID, rec, profilePtr, modePtr) if err != nil { return nil, nil, err } @@ -254,7 +277,7 @@ func (m connectMinter) PreviewBinding(clientID string, intent connect.Credential if rec != nil && rec.Kind != auth.KindClient { return "", "", storage.ErrClientCredentialConflict } - return s.resolveBindingLocked(rec, intent.Profile, intent.Mode) + return s.resolveBindingLocked(clientID, rec, intent.Profile, intent.Mode) } // Release implements connect.CredentialMinter: it ends the in-flight claim diff --git a/internal/runtime/clients_service_oauth.go b/internal/runtime/clients_service_oauth.go index 15cd1e1aa..a0b14c37d 100644 --- a/internal/runtime/clients_service_oauth.go +++ b/internal/runtime/clients_service_oauth.go @@ -58,12 +58,15 @@ func (s *ClientsService) cancelLoginRequests(clientID string) { } // hasLoginRecords reports whether the client has browser-login storage. -func (s *ClientsService) hasLoginRecords(o oauthClientStore, clientID string) bool { +func (s *ClientsService) hasLoginRecords(o oauthClientStore, clientID string) (bool, error) { if o == nil { - return false + return false, nil } b, err := o.GetOAuthClientBinding(clientID) - return err == nil && b != nil + if err != nil { + return false, fmt.Errorf("cannot read browser-login bindings: %w", err) + } + return b != nil, nil } // loadOAuthBindings reads the OAuth side of a guard state (fail closed: an error diff --git a/internal/runtime/commit.go b/internal/runtime/commit.go index 09c3f73b6..6877b4070 100644 --- a/internal/runtime/commit.go +++ b/internal/runtime/commit.go @@ -960,10 +960,12 @@ func (r *Runtime) commitLocked(reason string, fn func(tx *CommitTx) error) (*Com // every pending and approved sign-in request BEFORE the new configuration // becomes visible, on the API update path and the file-reload path alike // (both end here). It does not depend on config.reloaded, which is - // asynchronous and may be dropped. It takes the request store's mutex only: - // see the lock-order note on OAuthLoginService. + // asynchronous and may be dropped. The lifecycle lock taken here is held until + // the function returns, that is, past the publish below and the r.cfg swap, so + // a BeginAuthorization either created its request before this ran or sees the + // switch off. See the lock-order note on OAuthLoginService. if base.Config != nil && base.Config.MCPOAuthEnabled && !tx.next.MCPOAuthEnabled && r.oauthLoginService != nil { - r.oauthLoginService.CancelAll("feature_disabled") + defer r.oauthLoginService.beginDisable("feature_disabled")() } // Step 8: publish. diff --git a/internal/runtime/credential_input_screen.go b/internal/runtime/credential_input_screen.go index 29d6911bb..00001e754 100644 --- a/internal/runtime/credential_input_screen.go +++ b/internal/runtime/credential_input_screen.go @@ -10,6 +10,7 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" "github.com/smart-mcp-proxy/mcpproxy-go/internal/security" ) @@ -117,7 +118,8 @@ func (c *CredentialScreen) SecretShaped(s string) bool { return false } lower := strings.ToLower(s) - if strings.Contains(lower, auth.TokenPrefixStr) || strings.Contains(lower, auth.ClientTokenPrefixStr) { + if strings.Contains(lower, auth.TokenPrefixStr) || strings.Contains(lower, auth.ClientTokenPrefixStr) || + strings.Contains(lower, mcplogin.AccessTokenPrefix) || strings.Contains(lower, mcplogin.RefreshTokenPrefix) { return true } // Every nonempty configured key is compared, whatever its length (A24): diff --git a/internal/runtime/credentials_service.go b/internal/runtime/credentials_service.go index 3649fe1d2..66ac242c0 100644 --- a/internal/runtime/credentials_service.go +++ b/internal/runtime/credentials_service.go @@ -958,6 +958,16 @@ func (s *CredentialsService) issueClientMCP(ctx context.Context, a Actor, req Is Msg: fmt.Sprintf("client %s already exists (%s); choose a new id", req.ID, state)} } } + // 8. A client that has browser logins but no record exists too: create_client + // must not "create" it and rebind it (Spec 132). + hasLogins, herr := s.clients.hasLoginRecords(s.clients.oauthStore(), req.ID) + if herr != nil { + return nil, herr + } + if hasLogins { + return nil, &CredentialError{ErrCode: profile.CredentialErrorCodeIdentityExists, Field: "client", State: "browser_login", Status: 409, + Msg: fmt.Sprintf("client %s already exists (browser_login); choose a new id", req.ID)} + } profileArg := req.Profile return s.mintClientLocked(ctx, a, req, &profileArg, &mode, expiresAt) } @@ -1012,7 +1022,9 @@ func (s *CredentialsService) Revoke(ctx context.Context, a Actor, ref Credential return nil, err } if ref.Grant != "" { - return s.revokeGrantLocked(ctx, ref.Client, ref.Grant) + // The login service reads the actor from the context: stamp the one this + // call was given, as every other branch uses it. + return s.revokeGrantLocked(ContextWithActor(ctx, a), ref.Client, ref.Grant) } if ref.Client != "" { return s.revokeClientLocked(ctx, a, ref.Client) @@ -1034,6 +1046,21 @@ func (s *CredentialsService) Revoke(ctx context.Context, a Actor, ref Credential return nil, credErr(profile.CredentialErrorCodeReservedIdentity, "token", fmt.Sprintf("token %s is a client credential; revoke it with client=%s", ref.Token, before.ClientID), 400) } + if before.Kind == auth.KindClient { + // The legacy token-name door (DELETE /tokens/client-) used to cut a client + // off completely. It still does: a client that has browser logins goes + // through the client revoke (key, every login, request cancellation). One + // without logins keeps exactly the old result, row and events; its pending + // requests are cancelled either way. + s.clients.cancelLoginRequests(before.ClientID) + hasLogins, herr := s.clients.hasLoginRecords(s.clients.oauthStore(), before.ClientID) + if herr != nil { + return nil, herr + } + if hasLogins { + return s.revokeClientLocked(ctx, a, before.ClientID) + } + } cfg := s.cfg() if before.Revoked { return &RevokeResult{View: ViewOf(before, cfg, s.now())}, nil @@ -1135,6 +1162,10 @@ func (s *CredentialsService) revokeClientLocked(ctx context.Context, a Actor, cl return nil, credErr(profile.CredentialErrorCodeInvalidArgument, "client", `invalid argument "client": must be lower-case letters, digits, '-' or '_', at most 56 characters`, 400) } + // Cancel the client's pending AND approved sign-in requests before any + // idempotent early return: a revoke that changes nothing stored must still + // kill a login that was approved but not yet exchanged (Spec 132 R15). + s.clients.cancelLoginRequests(clientID) all, err := s.clients.records() if err != nil { return nil, err @@ -1143,13 +1174,24 @@ func (s *CredentialsService) revokeClientLocked(ctx context.Context, a Actor, cl hasKey := rec != nil && rec.Kind == auth.KindClient // Spec 132: a client with browser logins is a client even without an API // key, and revoking it revokes every login too. - hasLogins := s.clients.hasLoginRecords(s.clients.oauthStore(), clientID) + hasLogins, err := s.clients.hasLoginRecords(s.clients.oauthStore(), clientID) + if err != nil { + return nil, err + } if !hasKey && !hasLogins { return nil, s.notFound("client", clientID) } cfg := s.cfg() - if hasKey && rec.Revoked && (!hasLogins || !s.hasLiveGrant(clientID, s.now())) { - return &RevokeResult{View: ViewOf(rec, cfg, s.now()), ClientConfigUntouched: true}, nil + if hasKey && rec.Revoked { + live := false + if hasLogins { + if live, err = s.hasLiveGrant(clientID, s.now()); err != nil { + return nil, err // fail closed: an unreadable list is not "nothing live" + } + } + if !live { + return &RevokeResult{View: ViewOf(rec, cfg, s.now()), ClientConfigUntouched: true}, nil + } } var view CredentialView if hasKey { @@ -1207,7 +1249,13 @@ func (s *CredentialsService) List(f CredentialFilter) ([]CredentialView, error) } out = append(out, v) } - out, err = s.listOAuth(f, out) + haveClient := map[string]bool{} // from the UNFILTERED records + for _, t := range ownerlessTokens(all) { + if t.Kind == auth.KindClient { + haveClient[t.ClientID] = true + } + } + out, err = s.listOAuth(f, out, haveClient) if err != nil { return nil, err } diff --git a/internal/runtime/credentials_service_oauth.go b/internal/runtime/credentials_service_oauth.go index f30906a42..dc380eb0e 100644 --- a/internal/runtime/credentials_service_oauth.go +++ b/internal/runtime/credentials_service_oauth.go @@ -3,6 +3,7 @@ package runtime import ( "context" "errors" + "fmt" "sort" "time" @@ -75,7 +76,7 @@ func (s *CredentialsService) oauthOnlyCredentialView(id string, b storage.OAuthC // listOAuth adds the browser logins (and the clients that have only logins) to // a List result. It adds nothing while the feature was never used. -func (s *CredentialsService) listOAuth(f CredentialFilter, out []CredentialView) ([]CredentialView, error) { +func (s *CredentialsService) listOAuth(f CredentialFilter, out []CredentialView, have map[string]bool) ([]CredentialView, error) { if s.clients == nil { return out, nil } @@ -86,12 +87,6 @@ func (s *CredentialsService) listOAuth(f CredentialFilter, out []CredentialView) if !st.active { return out, nil } - have := map[string]bool{} - for _, v := range out { - if v.Kind == CredentialKindClient { - have[v.ID] = true - } - } add := func(v CredentialView) { if f.Kind != "" && f.Kind != "all" && f.Kind != v.Kind { return @@ -176,19 +171,19 @@ func (s *CredentialsService) revokeGrantLocked(ctx context.Context, clientID, gr // hasLiveGrant reports whether the client has a browser login that is neither // revoked nor lapsed. -func (s *CredentialsService) hasLiveGrant(clientID string, now time.Time) bool { +func (s *CredentialsService) hasLiveGrant(clientID string, now time.Time) (bool, error) { o := s.clients.oauthStore() if o == nil { - return false + return false, nil } gs, err := o.ListOAuthGrants() if err != nil { - return false + return false, fmt.Errorf("cannot read browser logins: %w", err) // fail closed } for i := range gs { if gs[i].Client == clientID && GrantStateOf(&gs[i], now) == GrantStateActive { - return true + return true, nil } } - return false + return false, nil } diff --git a/internal/runtime/oauth_login_consent.go b/internal/runtime/oauth_login_consent.go index e3427a312..31b3ef730 100644 --- a/internal/runtime/oauth_login_consent.go +++ b/internal/runtime/oauth_login_consent.go @@ -111,10 +111,23 @@ func (s *OAuthLoginService) BeginAuthorization(in AuthorizeInput) (string, *Auth s.logger.Error("browser login: cannot build the request store", zap.Error(err)) return "", fail("temporarily_unavailable", "try again") } + // "enabled check -> Create" is one boundary shared with the switch-off + // (lifecycleMu): a request admitted here is either created before CancelAll + // runs, and cancelled by it, or refused because the switch is already off. + // Nothing but those two steps happens under the lock. + s.lifecycleMu.Lock() + if !s.Enabled() { + s.lifecycleMu.Unlock() + return "", &AuthorizeError{Kind: AuthorizeNotFound, Code: "not_found", Description: "not found"} + } + if h := s.testHookBeginAfterEnabled; h != nil { + h() + } req, err := reqs.Create(mcplogin.Request{ RegistrationID: reg.ClientID, RedirectURI: redirect, State: in.State, CodeChallenge: in.CodeChallenge, - Resource: in.Resource, Issuer: in.Origin, PathClient: pathClient, + Resource: in.Origin + mcplogin.ResourcePath(pathClient), Issuer: in.Origin, PathClient: pathClient, }) + s.lifecycleMu.Unlock() if err != nil { if errors.Is(err, mcplogin.ErrTooManyPending) { return "", fail("temporarily_unavailable", "too many sign-in requests are waiting") @@ -744,6 +757,15 @@ func (s *OAuthLoginService) Approve(ctx context.Context, requestID string, c App if err != nil { return "", mapRequestStoreError(err) } + if h := s.testHookApproveAfterStore; h != nil { + h() + } + // A switch-off cancels without bindingWriteMu, so the approval may have lost + // a race after Store.Approve: re-read the request and write nothing, publish + // nothing and hand out no redirect if it is no longer approved. + if cur, ok := reqs.Get(requestID); !ok || cur.Status != mcplogin.StatusApproved { + return "", ErrOAuthRequestNotFound + } writeChangeRecord(ctx, s.activity, s.logger, s.now(), actor, changeRecord{ change: profile.ChangeApprove, profile: rc.pin, clientID: rc.clientID, tokenName: auth.ClientTokenName(rc.clientID), meta: map[string]interface{}{"request_id": requestID}, diff --git a/internal/runtime/oauth_login_review_test.go b/internal/runtime/oauth_login_review_test.go new file mode 100644 index 000000000..116f4cb47 --- /dev/null +++ b/internal/runtime/oauth_login_review_test.go @@ -0,0 +1,437 @@ +package runtime + +import ( + "errors" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/connect" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// --- A1: cancellation before any idempotent early return ----------------------------------- + +func TestRevokeClient_AlreadyRevokedKeyStillCancelsApprovedRequests(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + _, err := fx.clients.RevokeAPIKey(fx.ctx(), fx.actor(), "codex") + require.NoError(t, err) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + + r, err := fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Client: "codex"}, false) + require.NoError(t, err) + assert.False(t, r.Changed, "nothing live: the revoke itself is a no-op") + _, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + requireInvalidGrant(t, terr) + assert.Empty(t, fx.grants()) +} + +func TestForgetClient_WithNothingStoredStillCancelsApprovedRequests(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + pending := fx.authorize(reg, "cursor") + + _, err := fx.clients.Forget(fx.ctx(), fx.actor(), "cursor", false) + var nc *NoClientCredentialError + require.True(t, errors.As(err, &nc), "the returned error is unchanged") + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + _, err = fx.svc.Approve(fx.ctx(), pending, ApprovalChoice{Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthRequestNotFound) + fx.nothingStored() +} + +// --- A2: hasLiveGrant fails closed -------------------------------------------------------------- + +type failingGrantsStore struct{ *storage.Manager } + +func (failingGrantsStore) ListOAuthGrants() ([]storage.OAuthGrant, error) { + return nil, errors.New("disk on fire") +} + +func TestRevokeClient_UnreadableGrantsRefuseInsteadOfSkipping(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + _, err = fx.clients.RevokeAPIKey(fx.ctx(), fx.actor(), "codex") + require.NoError(t, err) + + broken := failingGrantsStore{fx.sm} + cs := NewClientsService(ClientsServiceDeps{ + Store: broken, HMACKey: func() ([]byte, error) { return oauthTestKey, nil }, + Config: func() *config.Config { return fx.cfg }, Guard: func() BindingGuard { return stubGuard{} }, + Now: fx.clock.Now, Mu: fx.clients.mu, + }) + _, err = cs.CredentialsServiceOver(broken).Revoke(fx.ctx(), fx.actor(), CredentialRef{Client: "codex"}, false) + require.Error(t, err, "an unreadable grant list must not look like 'nothing live'") + assert.False(t, fx.grants()[0].Revoked) +} + +// --- A3: the legacy token-name door cascades ------------------------------------------------- + +func TestRevokeByTokenName_ClientWithLoginsCascades(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + code := oauthCodeOf(t, redirect) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + require.Nil(t, terr) + pending := fx.approvedCode(fx.register(), "codex", ApprovalChoice{BindingRevision: rev}) + + _, err = fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Token: "client-codex"}, true) + require.NoError(t, err) + tok, _ := fx.sm.GetAgentTokenByName("client-codex") + assert.True(t, tok.Revoked) + for _, g := range fx.grants() { + assert.True(t, g.Revoked, "the door cut a client off completely before, and still does") + } + _, terr = fx.svc.Exchange(fx.tokenInput(reg, pending)) + requireInvalidGrant(t, terr) +} + +func TestRevokeByTokenName_ClientWithoutLoginsIsExactlyTheOldDoor(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + r, err := fx.creds.Revoke(fx.ctx(), fx.actor(), CredentialRef{Token: "client-codex"}, true) + require.NoError(t, err) + assert.True(t, r.Changed) + assert.False(t, r.ClientConfigUntouched, "the token door never said this") + rows := fx.changeRows("revoke") + require.Len(t, rows, 1) + diff, _ := rows[0]["diff"].(map[string]interface{}) + assert.Equal(t, true, diff["changed"]) + assert.NotContains(t, diff, "client_config_untouched", "the client-revoke diff is not used") + evs := fx.eventsOf(EventTypeCredentialsChanged) + require.Len(t, evs, 1) + assert.Equal(t, CredentialKindClient, evs[0].Payload["kind"]) +} + +// --- A4: the switch-off boundary ----------------------------------------------------------------- + +func TestBeginAuthorization_RequestAdmittedBeforeSwitchOffIsCancelledByIt(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + done := make(chan struct{}) + var once sync.Once + fx.svc.testHookBeginAfterEnabled = func() { + once.Do(func() { + go func() { + release := fx.svc.beginDisable("test") // blocks until Begin leaves the lifecycle section + fx.cfg.MCPOAuthEnabled = false + release() + close(done) + }() + time.Sleep(50 * time.Millisecond) // let it queue on the lifecycle lock + }) + } + id, aerr := fx.svc.BeginAuthorization(fx.authInput(reg, oauthTestOrigin+"/mcp/oauth/cursor")) + require.Nil(t, aerr, "admitted: the enabled check and the create share one boundary") + <-done + _, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthRequestNotFound, "the switch-off cancelled it") + + // During the off window nothing is admitted, and after off -> on nothing from + // the window is approvable. + _, aerr = fx.svc.BeginAuthorization(fx.authInput(reg, oauthTestOrigin+"/mcp/oauth/cursor")) + require.NotNil(t, aerr) + fx.cfg.MCPOAuthEnabled = true + _, err = fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthRequestNotFound) + assert.Empty(t, fx.svc.ListPending()) +} + +func TestApprove_LosingToACancelWritesNoRowAndNoRedirect(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + id := fx.authorize(reg, "cursor") + fx.svc.testHookApproveAfterStore = func() { fx.svc.CancelAll("race") } + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthRequestNotFound) + assert.Empty(t, redirect) + assert.Empty(t, fx.changeRows("approve")) + for _, e := range fx.eventsOf(EventTypeOAuthAuthorizationDecided) { + assert.NotEqual(t, "approved", e.Payload["status"]) + } +} + +// --- B5: wrong-origin replay ----------------------------------------------------------------------- + +func TestExchange_ReplayOnAnotherOriginDoesNotRevokeTheLogin(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + require.Nil(t, terr) + + in := fx.tokenInput(reg, code) + in.Origin = "http://localhost:8080" + _, terr = fx.svc.Exchange(in) + requireInvalidGrant(t, terr) + gs := fx.grants() + require.Len(t, gs, 1) + assert.False(t, gs[0].Revoked, "a foreign-origin replay revokes nothing") + assert.Empty(t, fx.changeRows("replay_revoke")) + // The same-origin replay still does. + _, terr = fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + assert.True(t, fx.grants()[0].Revoked) +} + +// --- B6: a dead grant never answers invalid_target --------------------------------------------------- + +func TestRefresh_DeadGrantAnswersInvalidGrantEvenWithAWrongResource(t *testing.T) { + fx := newOAuthFx(t) + reg, first := fx.loginNew("cursor", "ro") + gid := fx.grants()[0].GrantID + wrong := func(tok string) *TokenError { + _, terr := fx.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: tok, ClientID: reg, Resource: oauthTestOrigin + "/mcp/oauth/other"}) + return terr + } + live := wrong(first.RefreshToken) + require.NotNil(t, live) + assert.Equal(t, TokenErrInvalidTarget, live.Code, "a live grant: the resource check applies") + + key := oauthTestKey + unknownTok, _, err := mcplogin.NewRefreshToken(key, strings.Repeat("A", mcplogin.GrantIDLen)) + require.NoError(t, err) + unknown := wrong(unknownTok) + + _, err = fx.sm.RevokeOAuthGrant(gid, storage.OAuthRevokeAdmin, fx.clock.Now()) + require.NoError(t, err) + revoked := wrong(first.RefreshToken) + + fx2 := newOAuthFx(t) + reg2, first2 := fx2.loginNew("cursor", "ro") + fx2.clock.Advance(OAuthRefreshTokenTTL + time.Hour) + _, expired := fx2.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: first2.RefreshToken, ClientID: reg2, Resource: oauthTestOrigin + "/mcp/oauth/other"}) + + for name, e := range map[string]*TokenError{"unknown": unknown, "revoked": revoked, "expired": expired} { + require.NotNil(t, e, name) + assert.Equal(t, errInvalidGrant, e, name+": the one uniform answer") + } +} + +// --- B7: one resource identity -------------------------------------------------------------------------- + +func TestResource_SlashFormIsCanonicalisedEndToEnd(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + id, aerr := fx.svc.BeginAuthorization(fx.authInput(reg, oauthTestOrigin+"/mcp/oauth/cursor/")) + require.Nil(t, aerr) + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + require.NoError(t, err) + in := fx.tokenInput(reg, oauthCodeOf(t, redirect)) + in.Resource = oauthTestOrigin + "/mcp/oauth/cursor/" // the form the client sent + res, terr := fx.svc.Exchange(in) + require.Nil(t, terr) + assert.Equal(t, oauthTestOrigin+"/mcp/oauth/cursor", fx.grants()[0].Resource, "stored canonical") + + now := fx.clock.Now() + for _, p := range []string{"/mcp/oauth/cursor", "/mcp/oauth/cursor/"} { + _, _, aerr := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, p, now) + assert.NoError(t, aerr, p) + } + _, terr = fx.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: res.RefreshToken, ClientID: reg, Resource: oauthTestOrigin + "/mcp/oauth/cursor/"}) + require.Nil(t, terr, "the slash form the client sent still refreshes") +} + +func TestResource_RefreshAcceptsEitherFormAndGenericAddress(t *testing.T) { + fx := newOAuthFx(t) + reg, res := fx.loginNew("cursor", "ro") + r1, terr := fx.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: res.RefreshToken, ClientID: reg, Resource: oauthTestOrigin + "/mcp/oauth/cursor/"}) + require.Nil(t, terr) + _, terr = fx.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: r1.RefreshToken, ClientID: reg, Resource: oauthTestOrigin + "/mcp/oauth/cursor"}) + require.Nil(t, terr) + _, terr = fx.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: "x", ClientID: reg, Resource: oauthTestOrigin + "/mcp/oauth/codex/"}) + require.NotNil(t, terr) + + // the generic address, with and without the slash + reg2 := fx.register() + id, aerr := fx.svc.BeginAuthorization(fx.authInput(reg2, oauthTestOrigin+"/mcp/oauth/")) + require.Nil(t, aerr) + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Client: ClientChoice{New: &NewClientChoice{ID: "acme"}}, Profile: oauthStrp("ro")}) + require.NoError(t, err) + res2, terr := fx.svc.Exchange(fx.tokenInput(reg2, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + _, _, aerr2 := fx.svc.Authenticate(res2.AccessToken, oauthTestOrigin, "/mcp/oauth", fx.clock.Now()) + assert.NoError(t, aerr2) + _, _, aerr2 = fx.svc.Authenticate(res2.AccessToken, oauthTestOrigin, "/mcp/oauth/", fx.clock.Now()) + assert.NoError(t, aerr2) +} + +// --- B8: the profile must still exist --------------------------------------------------------------------- + +func TestExchange_NewClientProfileGoneAtExchange(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + fx.cfg.Profiles = fx.cfg.Profiles[1:] // "ro" deleted + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + fx.nothingStored() + rows := fx.changeRows("deny") + require.Len(t, rows, 1) + assert.Equal(t, "profile_gone", rows[0]["reason"]) +} + +// --- B9: Register is gated -------------------------------------------------------------------------------- + +func TestRegister_DisabledRefusesAndWritesNothing(t *testing.T) { + fx := newOAuthFx(t) + fx.cfg.MCPOAuthEnabled = false + _, rerr, err := fx.svc.Register(mcplogin.RegistrationRequest{RedirectURIs: []string{oauthTestRedirect}, ClientName: "x"}) + assert.ErrorIs(t, err, ErrOAuthFeatureDisabled) + assert.Nil(t, rerr) + regs, lerr := fx.sm.ListOAuthRegistrations() + require.NoError(t, lerr) + assert.Empty(t, regs) +} + +// --- C10: connect on a browser-only client ---------------------------------------------------------------- + +func TestConnect_BrowserOnlyClientKeepsItsBindingWhenNoProfileIsGiven(t *testing.T) { + fx := newOAuthFx(t) + fx.loginNew("cursor", "ro") + m := fx.clients.ConnectMinter() + + pin, mode, err := m.PreviewBinding("cursor", connect.CredentialIntent{}) + require.NoError(t, err) + assert.Equal(t, "ro", pin) + assert.Equal(t, auth.ProfileModeLocked, mode) + + issued, err := m.Issue("cursor", connect.CredentialIntent{}) + require.NoError(t, err) + assert.Equal(t, "ro", issued.Profile) + assert.Equal(t, auth.ProfileModeLocked, issued.Mode) + tok, _ := fx.sm.GetAgentTokenByName("client-cursor") + assert.Equal(t, "ro", tok.ProfilePin) + b, _ := fx.sm.GetOAuthClientBinding("cursor") + assert.Equal(t, "ro", b.ProfilePin) + assert.False(t, fx.grants()[0].Revoked, "logins unchanged") + require.NoError(t, m.Abort("cursor", connect.CredentialIntent{}, issued)) + + // An explicit profile still wins. + rw := "rw" + pin, _, err = m.PreviewBinding("cursor", connect.CredentialIntent{Profile: &rw}) + require.NoError(t, err) + assert.Equal(t, "rw", pin) +} + +// --- C11: create_client must not rebind an OAuth-only client ----------------------------------------------- + +func TestIssueClientMCP_RefusesAClientThatHasBrowserLogins(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "", ApprovalChoice{Client: ClientChoice{New: &NewClientChoice{ID: "acme"}}, Profile: oauthStrp("ro")}) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + require.Nil(t, terr) + + _, err := fx.creds.IssueClient(fx.ctx(), fx.actor(), IssueClientRequest{ + ID: "acme", Profile: "rw", ProfilePresent: true, ExpiresIn: "7d", RequireProfile: true, RefuseExistingRecord: true, + }) + var ce *CredentialError + require.True(t, errors.As(err, &ce)) + assert.Equal(t, "identity_exists", ce.Code()) + pin, _, _, _ := fx.sm.CurrentClientBinding("acme") + assert.Equal(t, "ro", pin, "nothing was rebound") +} + +// --- C12: list filters apply after the unfiltered record check ------------------------------------------------ + +func TestCredentialsList_ActiveFilterDoesNotFabricateAnOAuthOnlyRow(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + _, err = fx.clients.RevokeAPIKey(fx.ctx(), fx.actor(), "codex") + require.NoError(t, err) + + got, err := fx.creds.List(CredentialFilter{State: "active", Kind: "client"}) + require.NoError(t, err) + assert.Empty(t, got, "the client has an API-key record (revoked): no OAuth-only stand-in under an active filter") + got, err = fx.creds.List(CredentialFilter{State: "active"}) + require.NoError(t, err) + require.Len(t, got, 1) + assert.Equal(t, "browser_login", got[0].Kind) +} + +// --- C13: the explicit actor reaches the single-grant revoke ----------------------------------------------------- + +func TestCredentialsRevoke_OneGrantUsesTheSuppliedActor(t *testing.T) { + fx := newOAuthFx(t) + fx.loginNew("cursor", "ro") + gid := fx.grants()[0].GrantID + other := Actor{Kind: "agent_token", Name: "ops-bot", Surface: "mcp"} + _, err := fx.creds.Revoke(fx.ctx(), other, CredentialRef{Client: "cursor", Grant: gid}, false) + require.NoError(t, err) + rows := fx.changeRows("revoke") + require.Len(t, rows, 1) + assert.Equal(t, "ops-bot", rows[0]["actor_name"]) + assert.Equal(t, "agent_token", rows[0]["actor_kind"]) + assert.Equal(t, "mcp", rows[0]["surface"]) +} + +// --- C14: profile users take the pin from the API-key record --------------------------------------------------------- + +// A binary that knew nothing of browser logins moved only the API-key record: +// the record is the truth (storage.CurrentClientBinding), the entry is stale. +func TestProfilesService_UsedByTakesTheAPIKeyRecordPinOverADivergentEntry(t *testing.T) { + h := newProfilesHarness(t) + commitOAuthOnlyClient(t, h.rt.StorageManager(), "reg1", "grantAAAAAAAAAAAAAAAAAA", "acme", "ro", auth.ProfileModeLocked) + tokens := []auth.AgentToken{{ + Name: auth.ClientTokenName("acme"), Kind: auth.KindClient, ClientID: "acme", + ProfilePin: "full", ProfileMode: auth.ProfileModeSwitchable, Revoked: true, + }} + collect := func(pin string) *UsedBy { + u := &UsedBy{} + require.NoError(t, h.svc.addOAuthUsers(tokens, func(p string) *UsedBy { + if p == pin { + return u + } + return nil + })) + return u + } + assert.Empty(t, collect("ro").Clients, "the stale entry pin does not decide") + full := collect("full") + require.Len(t, full.Clients, 1) + assert.Equal(t, "acme", full.Clients[0].ID) + assert.Equal(t, auth.ProfileModeSwitchable, full.Clients[0].Mode) +} + +// --- C15: issued-credential prefixes ------------------------------------------------------------------------------------- + +func TestSecretShaped_RecognisesBrowserLoginTokens(t *testing.T) { + c := NewCredentialScreen(nil) + assert.True(t, c.SecretShaped("here: mcp_oat_abcdef")) + assert.True(t, c.SecretShaped("MCP_ORT_whatever")) + assert.False(t, c.SecretShaped("an ordinary sentence")) +} diff --git a/internal/runtime/oauth_login_service.go b/internal/runtime/oauth_login_service.go index 7023f2ed4..32aba090c 100644 --- a/internal/runtime/oauth_login_service.go +++ b/internal/runtime/oauth_login_service.go @@ -33,12 +33,25 @@ import ( // own services take it) and then call Store.CancelForClient, the same order. // - Approve holds bindingWriteMu while it validates the choice and calls // Store.Approve, the same order. -// - The turn-off cancellation (CancelAll from the config commit) takes Store.mu -// alone. It needs no bindingWriteMu: it is one in-memory step, atomic with -// Consume through Store.mu, and may run while the caller already holds -// bindingWriteMu (MutateConfig) or does not (file reload). +// - The turn-off cancellation (beginDisable from the config commit) takes +// lifecycleMu and then Store.mu. It needs no bindingWriteMu: it is one +// in-memory step, atomic with Consume through Store.mu, and may run while the +// caller already holds bindingWriteMu (MutateConfig) or does not (reload). // - Nothing holding Store.mu ever acquires bindingWriteMu (the commit callback // never does), so the two cannot be taken in opposite orders. +// +// The switch-off boundary adds one lock, lifecycleMu, with the full order +// +// bindingWriteMu -> configCommitMu -> lifecycleMu -> {Runtime.mu | Store.mu} +// +// BeginAuthorization holds lifecycleMu only across "Enabled() -> Store.Create" +// (Enabled reads Runtime.mu, Create takes Store.mu: both are leaves below it) +// and never takes bindingWriteMu, configCommitMu, storage or any disk I/O under +// it. The commit holds it from CancelAll until the new config is published, so +// a request admitted before the switch-off is created before CancelAll runs +// (and cancelled by it), and one admitted after sees the switch off. Exchange's +// commit callback holds Store.mu and reads Runtime.mu through the guard, but no +// path holds Runtime.mu and then waits for Store.mu or lifecycleMu. type OAuthLoginService struct { store OAuthLoginStore hmacKey func() ([]byte, error) @@ -58,6 +71,14 @@ type OAuthLoginService struct { reqMu sync.Mutex reqs *mcplogin.Store + // lifecycleMu is the switch-off boundary (see the lock-order note): held + // across "enabled check -> Store.Create" in BeginAuthorization and across + // "CancelAll -> config published" in the commit. + lifecycleMu sync.Mutex + // test hooks, nil in production. + testHookBeginAfterEnabled func() + testHookApproveAfterStore func() + everUsed bool // positive results only everMu sync.Mutex touchMu sync.Mutex @@ -193,14 +214,31 @@ func (s *OAuthLoginService) existingRequests() *mcplogin.Store { // feature is being turned off). It takes the request store's mutex only (see // the lock-order note): it may run under bindingWriteMu or without it. func (s *OAuthLoginService) CancelAll(reason string) int { + s.lifecycleMu.Lock() + defer s.lifecycleMu.Unlock() + return s.cancelAllLocked(reason) +} + +// beginDisable is the switch-off boundary: it takes the lifecycle lock, cancels +// every request and returns the release the caller runs AFTER the new config +// is visible. A BeginAuthorization either created its request before this ran +// (and it is cancelled here) or waits and then sees the switch off. +func (s *OAuthLoginService) beginDisable(reason string) (release func()) { + s.lifecycleMu.Lock() + s.cancelAllLocked(reason) + return s.lifecycleMu.Unlock +} + +// cancelAllLocked snapshots the pending ids and cancels everything in one +// request-store critical section (s.lifecycleMu held). +func (s *OAuthLoginService) cancelAllLocked(reason string) int { reqs := s.existingRequests() if reqs == nil { return 0 } - pending := reqs.ListPending() - n := reqs.CancelAll() - for _, p := range pending { - s.publishDecided(p.ID, string(mcplogin.StatusCancelled)) + pending, n := reqs.CancelAllReport() + for _, id := range pending { + s.publishDecided(id, string(mcplogin.StatusCancelled)) } if n > 0 { s.logger.Info("cancelled browser sign-in requests", zap.Int("count", n), zap.String("reason", reason)) @@ -238,10 +276,28 @@ func (s *OAuthLoginService) publishDecided(requestID, status string) { // --- registration -------------------------------------------------------------- +// ErrOAuthFeatureDisabled is the refusal of a public entry point while browser +// login is off. The HTTP layer maps it to 404. +var ErrOAuthFeatureDisabled = errors.New("browser login is disabled") + +// canonicalResource is THE resource identity: a resource that parses as an +// OAuth address on origin becomes origin + mcplogin.ResourcePath(client) (no +// trailing slash); anything else is returned unchanged, so it matches nothing. +// Stored and compared in this form everywhere. +func canonicalResource(origin, resource string) string { + if clientID, _, ok := mcplogin.ParseResource(origin, resource); ok { + return origin + mcplogin.ResourcePath(clientID) + } + return resource +} + // Register validates an RFC 7591 request and stores a pending registration. // The first return is the 201 body; the second a refusal shaped for the // client; the third an internal failure. func (s *OAuthLoginService) Register(req mcplogin.RegistrationRequest) (map[string]any, *mcplogin.RegError, error) { + if !s.Enabled() { + return nil, nil, ErrOAuthFeatureDisabled // the HTTP layer answers 404; nothing is written + } reg, regErr := mcplogin.ValidateRegistration(req) if regErr != nil { return nil, regErr, nil @@ -364,12 +420,6 @@ func (s *OAuthLoginService) Exchange(in TokenInput) (TokenResult, *TokenError) { s.logger.Error("browser login: cannot read the token key", zap.Error(err)) return TokenResult{}, errTokenServer } - // The origin check comes first and consumes nothing. - peek, ok := reqs.PeekCode(in.Code) - if ok && peek.Issuer != in.Origin { - return TokenResult{}, errInvalidGrant - } - // Lock order: bindingWriteMu BEFORE the request store (see the type doc). s.mu.Lock() defer s.mu.Unlock() @@ -382,18 +432,22 @@ func (s *OAuthLoginService) Exchange(in TokenInput) (TokenResult, *TokenError) { ) commit := func(req mcplogin.Request) (string, error) { decided = req.Decision - if req.Issuer != in.Origin { - return "", errExchangeRefused // the code was re-issued between peek and consume: refuse, burn - } + // (the origin was already compared inside the store, before consumption) if !mcplogin.VerifyS256(in.CodeVerifier, req.CodeChallenge) || in.ClientID != req.RegistrationID || in.RedirectURI != req.RedirectURI { return "", errExchangeRefused } - if in.Resource != "" && in.Resource != req.Resource { + if in.Resource != "" && canonicalResource(in.Origin, in.Resource) != req.Resource { target = true return "", errExchangeRefused } now := s.now().UTC() + // A new client's profile must still exist: a later profile of the same + // name must never apply silently to a decision made about another one. + if req.Decision.NewClient && req.Decision.Profile != "" && !profileConfigured(s.cfg(), req.Decision.Profile) { + s.writeDecisionRow(profile.ChangeDeny, req, "profile_gone", now) + return "", errExchangeRefused + } if err := s.recheckGuard(req.Decision); err != nil { s.writeDecisionRow(profile.ChangeDeny, req, "guard", now) return "", errExchangeRefused @@ -439,9 +493,13 @@ func (s *OAuthLoginService) Exchange(in TokenInput) (TokenResult, *TokenError) { return grantID, nil } - req, replayedGrant, err := reqs.Consume(in.Code, commit) + // The store compares the origin with the issuer kept on the code (also on + // its tombstone) BEFORE consumption and replay handling. + req, replayedGrant, err := reqs.ConsumeAt(in.Code, in.Origin, commit) switch { case err == nil: + case errors.Is(err, mcplogin.ErrCodeOriginMismatch): + return TokenResult{}, errInvalidGrant case errors.Is(err, mcplogin.ErrCodeReused): // A code presented again inside the tombstone window revokes the login // it produced. An empty grant id means the first presentation stored diff --git a/internal/runtime/oauth_login_tokens.go b/internal/runtime/oauth_login_tokens.go index 52d6214f8..e23372e8a 100644 --- a/internal/runtime/oauth_login_tokens.go +++ b/internal/runtime/oauth_login_tokens.go @@ -50,7 +50,13 @@ func (s *OAuthLoginService) Refresh(in TokenInput) (TokenResult, *TokenError) { if grant.Issuer != in.Origin || grant.RegistrationID != in.ClientID { return TokenResult{}, errInvalidGrant } - if in.Resource != "" && in.Resource != grant.Resource { + // A dead grant answers the uniform invalid_grant BEFORE the resource check, + // so it never reveals its resource. (The rotation re-checks liveness inside + // its own transaction.) + if grant.Revoked || !grant.RefreshExpiresAt.After(s.now()) { + return TokenResult{}, errInvalidGrant + } + if in.Resource != "" && canonicalResource(in.Origin, in.Resource) != grant.Resource { return TokenResult{}, errInvalidTarget } ts, err := newTokenSet(key, grantID) @@ -229,6 +235,9 @@ func (s *OAuthLoginService) revokeGrantLocked(ctx context.Context, clientID, gra clientID: clientID, tokenName: auth.ClientTokenName(clientID), meta: map[string]interface{}{"grant_id": grantID, "credential_kind": CredentialKindBrowserLogin}, }) + // Terminating live MCP sessions or streams is NOT done here: a revoked login is + // refused on its NEXT request (storage no longer authenticates it), which the + // HTTP layer enforces per request. s.publishGrantChanged(*g, profile.ChangeRevoke, pin) s.notifyGrantRevoked(*g) return true, nil diff --git a/internal/runtime/profiles_service_oauth.go b/internal/runtime/profiles_service_oauth.go index 59c6e8bfe..0036aedf8 100644 --- a/internal/runtime/profiles_service_oauth.go +++ b/internal/runtime/profiles_service_oauth.go @@ -29,18 +29,33 @@ func (s *ProfilesService) addOAuthUsers(tokens []auth.AgentToken, target func(pi return nil } active := map[string]bool{} + recs := map[string]*auth.AgentToken{} for i := range tokens { t := &tokens[i] - if t.Kind == auth.KindClient && t.UserID == "" && !t.Revoked && t.ExpiresAt.After(now) { + if t.Kind != auth.KindClient || t.UserID != "" { + continue + } + recs[t.ClientID] = t + if !t.Revoked && t.ExpiresAt.After(now) { active[t.ClientID] = true } } for _, b := range bindings { - if !b.Live || b.Pin == "" || active[b.ClientID] { + if !b.Live || active[b.ClientID] { + continue + } + // The API-key record, in any state, decides the binding (as + // EffectiveTokens and CurrentClientBinding do); the entry only when there + // is no record. + pin, mode := b.Pin, b.Mode + if rec := recs[b.ClientID]; rec != nil { + pin, mode = rec.ProfilePin, rec.ProfileMode + } + if pin == "" { continue } - if u := target(b.Pin); u != nil { - u.Clients = append(u.Clients, UsedByClient{ID: b.ClientID, Mode: b.Mode}) + if u := target(pin); u != nil { + u.Clients = append(u.Clients, UsedByClient{ID: b.ClientID, Mode: mode}) } } return nil From 4981623bd284f7411515cb73ff0f66ae8141ee7f Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 22:20:47 +0200 Subject: [PATCH 13/42] fix(oauth): close exchange/approve races and rollback guard gap (Spec 132 PR-1d) Related #1971 --- internal/runtime/clients_service.go | 14 + internal/runtime/clients_service_connect.go | 18 +- internal/runtime/clients_service_rollback.go | 68 +++++ internal/runtime/credentials_service.go | 13 +- .../runtime/credentials_service_nilsafe.go | 22 ++ internal/runtime/oauth_login_consent.go | 11 + internal/runtime/oauth_login_postcommit.go | 70 +++++ internal/runtime/oauth_login_round2_test.go | 246 ++++++++++++++++++ internal/runtime/oauth_login_service.go | 45 +++- 9 files changed, 499 insertions(+), 8 deletions(-) create mode 100644 internal/runtime/clients_service_rollback.go create mode 100644 internal/runtime/credentials_service_nilsafe.go create mode 100644 internal/runtime/oauth_login_postcommit.go create mode 100644 internal/runtime/oauth_login_round2_test.go diff --git a/internal/runtime/clients_service.go b/internal/runtime/clients_service.go index c58508926..d41dbdb8a 100644 --- a/internal/runtime/clients_service.go +++ b/internal/runtime/clients_service.go @@ -773,6 +773,20 @@ func (s *ClientsService) forgetRecordLocked(ctx context.Context, a Actor, client forget := s.store.ForgetClientCredential if restorePrior { forget = s.store.ForgetClientCredentialRestoringPrior + // A connect undone for a client with live logins must not restore a + // binding the guard now refuses: revoke the key only and say so. + skip, serr := s.restoreRefusedLocked(clientID) + if serr != nil { + return nil, serr + } + if skip { + forget = s.revokeKeyKeepingBinding + nd := map[string]interface{}{"restore_skipped": "guard"} + for k, v := range diff { + nd[k] = v + } + diff = nd + } } else if o := s.oauthStore(); o != nil { hasLogins, herr := s.hasLoginRecords(o, clientID) if herr != nil { diff --git a/internal/runtime/clients_service_connect.go b/internal/runtime/clients_service_connect.go index 8dfe795ca..451f02128 100644 --- a/internal/runtime/clients_service_connect.go +++ b/internal/runtime/clients_service_connect.go @@ -418,7 +418,23 @@ func (m connectMinter) Abort(clientID string, intent connect.CredentialIntent, i } // A fresh mint whose config write failed: revoke it and write no record // (from the operator's view nothing happened, plan D13). - _, err := s.store.ForgetClientCredentialRestoringPrior(clientID) + skip, err := s.restoreRefusedLocked(clientID) + if err != nil { + return err + } + if skip { + revoked, rerr := s.revokeKeyKeepingBinding(clientID) + if rerr != nil { + return rerr + } + s.writeChange(context.Background(), actorOf(intent), changeRecord{ + change: profile.ChangeForget, profile: revoked.ProfilePin, previousProfile: revoked.ProfilePin, + clientID: clientID, tokenName: revoked.Name, + diff: map[string]interface{}{"reason": "rollback", "restore_skipped": "guard"}, + }) + return nil + } + _, err = s.store.ForgetClientCredentialRestoringPrior(clientID) return err } diff --git a/internal/runtime/clients_service_rollback.go b/internal/runtime/clients_service_rollback.go new file mode 100644 index 000000000..f79c12bec --- /dev/null +++ b/internal/runtime/clients_service_rollback.go @@ -0,0 +1,68 @@ +package runtime + +import ( + "errors" + "fmt" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// restoreRefusedLocked reports whether undoing a connect (restoring the binding +// the revoked record replaced) would create a binding the guard now refuses +// (s.mu held). It only matters for a client that has LIVE browser logins: the +// restore also rewrites their binding, and the configuration may have changed +// since the connect. The candidate is the API key revoked with the prior +// binding plus the surviving live logins bound to it. A client without live +// logins, or without a prior binding to restore, answers false: the rollback +// behaves exactly as before. A read error is returned (fail closed). +func (s *ClientsService) restoreRefusedLocked(clientID string) (bool, error) { + o := s.oauthStore() + has, err := s.hasLoginRecords(o, clientID) + if err != nil || !has { + return false, err + } + grants, err := o.ListOAuthGrants() + if err != nil { + return false, fmt.Errorf("cannot read browser logins: %w", err) + } + live := false + for i := range grants { + if grants[i].Client == clientID && GrantStateOf(&grants[i], s.now()) == GrantStateActive { + live = true + } + } + if !live { + return false, nil + } + all, err := s.records() + if err != nil { + return false, err + } + rec := clientRecord(all, clientID) + if rec == nil || rec.Kind != auth.KindClient || rec.PriorProfileMode == "" { + return false, nil + } + oauth, err := s.loadOAuthBindings() + if err != nil { + return false, err + } + next := *rec + next.Revoked = true + next.ProfilePin, next.ProfileMode = rec.PriorProfilePin, rec.PriorProfileMode + cfg := s.cfg() + gerr := CheckBindingGuard(s.guard(), + GuardState{Config: cfg, Tokens: guardedOnly(all), OAuthBindings: oauth}, + GuardState{Config: cfg, Tokens: candidateTokens(all, clientID, &next), + OAuthBindings: repinOAuthClient(oauth, clientID, next.ProfilePin, next.ProfileMode)}) + var ge *BindingGuardError + if errors.As(gerr, &ge) { + return true, nil + } + return false, gerr +} + +// revokeKeyKeepingBinding revokes the API key alone and leaves the binding of +// the client's logins as it is (storage.RevokeClientAPIKey, the one writer). +func (s *ClientsService) revokeKeyKeepingBinding(clientID string) (*auth.AgentToken, error) { + return s.oauthStore().RevokeClientAPIKey(clientID) +} diff --git a/internal/runtime/credentials_service.go b/internal/runtime/credentials_service.go index 66ac242c0..632ecd9d6 100644 --- a/internal/runtime/credentials_service.go +++ b/internal/runtime/credentials_service.go @@ -1052,12 +1052,21 @@ func (s *CredentialsService) Revoke(ctx context.Context, a Actor, ref Credential // through the client revoke (key, every login, request cancellation). One // without logins keeps exactly the old result, row and events; its pending // requests are cancelled either way. - s.clients.cancelLoginRequests(before.ClientID) - hasLogins, herr := s.clients.hasLoginRecords(s.clients.oauthStore(), before.ClientID) + // + // A service built without a clients service (a supported construction, + // also the HTTP token-service fallback) has nothing to cancel; whether the + // client has logins is read through the storage interface it does have. + if s.clients != nil { + s.clients.cancelLoginRequests(before.ClientID) + } + hasLogins, herr := s.hasLoginRecordsFor(before.ClientID) if herr != nil { return nil, herr } if hasLogins { + if s.clients == nil { + return nil, ErrCredentialsUnavailable // cannot cascade: refuse, nothing half-done + } return s.revokeClientLocked(ctx, a, before.ClientID) } } diff --git a/internal/runtime/credentials_service_nilsafe.go b/internal/runtime/credentials_service_nilsafe.go new file mode 100644 index 000000000..b864c3ddd --- /dev/null +++ b/internal/runtime/credentials_service_nilsafe.go @@ -0,0 +1,22 @@ +package runtime + +// hasLoginRecordsFor reports whether the client has browser-login storage, +// through whichever storage interface this service has: the clients service's +// store when there is one, else the token store itself. A store without +// browser-login storage answers false. A read error is returned (fail closed). +func (s *CredentialsService) hasLoginRecordsFor(clientID string) (bool, error) { + var o oauthClientStore + if s.clients != nil { + o = s.clients.oauthStore() + } else if st, ok := s.tokens.(oauthClientStore); ok { + o = st + } + if o == nil { + return false, nil + } + b, err := o.GetOAuthClientBinding(clientID) + if err != nil { + return false, err + } + return b != nil, nil +} diff --git a/internal/runtime/oauth_login_consent.go b/internal/runtime/oauth_login_consent.go index 31b3ef730..1041b6f63 100644 --- a/internal/runtime/oauth_login_consent.go +++ b/internal/runtime/oauth_login_consent.go @@ -763,6 +763,17 @@ func (s *OAuthLoginService) Approve(ctx context.Context, requestID string, c App // A switch-off cancels without bindingWriteMu, so the approval may have lost // a race after Store.Approve: re-read the request and write nothing, publish // nothing and hand out no redirect if it is no longer approved. + // + // The rest runs under lifecycleMu (after bindingWriteMu, the documented + // order), released by the defer at return: final status check, activity row, + // event and redirect are one step, so a switch-off either ran before it + // (refusal, no row) or runs after it (the code is cancelled and the client's + // exchange fails, which is expected). + s.lifecycleMu.Lock() + defer s.lifecycleMu.Unlock() + if h := s.testHookApproveFinalising; h != nil { + h() + } if cur, ok := reqs.Get(requestID); !ok || cur.Status != mcplogin.StatusApproved { return "", ErrOAuthRequestNotFound } diff --git a/internal/runtime/oauth_login_postcommit.go b/internal/runtime/oauth_login_postcommit.go new file mode 100644 index 000000000..6ce8472d4 --- /dev/null +++ b/internal/runtime/oauth_login_postcommit.go @@ -0,0 +1,70 @@ +package runtime + +import ( + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// A file reload commits the configuration without bindingWriteMu, so the +// profile and the guard verdict the exchange checked can change between those +// checks and storage.CommitOAuthLogin. The exchange therefore re-reads the live +// configuration once more AFTER the commit and before any token is returned +// (Spec 132 R15), and undoes what it stored when the stored state is no longer +// acceptable. The reload locking itself is untouched. + +// postCommitRefusal returns "" when the stored login is still acceptable, else +// the deny reason: profile_gone, or guard (also for anything it cannot read: +// fail closed). +func (s *OAuthLoginService) postCommitRefusal(d mcplogin.Decision, g storage.OAuthGrant) string { + pin, mode, found, err := s.store.CurrentClientBinding(g.Client) + if err != nil || !found { + return "guard" + } + if pin != "" && !profileConfigured(s.cfg(), pin) { + return "profile_gone" + } + all, err := s.store.ListAgentTokens() + if err != nil { + return "guard" + } + oauth, err := LoadOAuthBindings(s.store, s.now()) + if err != nil { + return "guard" + } + grants, err := s.store.ListOAuthGrantsForClient(g.Client) + if err != nil { + return "guard" + } + otherLive := false + for i := range grants { + if grants[i].GrantID != g.GrantID && GrantStateOf(&grants[i], s.now()) == GrantStateActive { + otherLive = true + } + } + cfg := s.cfg() + tokens := guardedOnly(all) + // Before this login the client's entry was live only through its other logins. + current := GuardState{Config: cfg, Tokens: tokens, + OAuthBindings: withOAuthClient(oauth, OAuthBinding{ClientID: g.Client, Pin: pin, Mode: mode, Live: otherLive})} + candidate := GuardState{Config: cfg, Tokens: tokens, OAuthBindings: oauth} + if CheckBindingGuard(s.guard(), current, candidate) != nil { + return "guard" + } + return "" +} + +// undoCommit revokes the grant this exchange created and, for a brand-new +// client, removes what it created (grants, binding entry, registrations left +// without a grant). An existing client only loses the grant. +func (s *OAuthLoginService) undoCommit(d mcplogin.Decision, g storage.OAuthGrant) { + if _, err := s.store.RevokeOAuthGrant(g.GrantID, storage.OAuthRevokeAdmin, s.now().UTC()); err != nil { + s.logger.Error("browser login: cannot revoke a login that failed its post-commit check", zap.Error(err)) + } + if d.NewClient { + if _, err := s.store.ForgetClientLogins(g.Client); err != nil { + s.logger.Error("browser login: cannot remove a new client that failed its post-commit check", zap.Error(err)) + } + } +} diff --git a/internal/runtime/oauth_login_round2_test.go b/internal/runtime/oauth_login_round2_test.go new file mode 100644 index 000000000..ae18d629b --- /dev/null +++ b/internal/runtime/oauth_login_round2_test.go @@ -0,0 +1,246 @@ +package runtime + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/connect" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// --- 1: a reload between the pre-check and the commit ------------------------------------- + +func issuedEvents(fx *oauthFx) int { + n := 0 + for _, e := range fx.eventsOf(EventTypeCredentialsChanged) { + if e.Payload["change"] == "issue" { + n++ + } + } + return n +} + +func TestExchange_ProfileDeletedByAReloadBetweenCheckAndCommitUndoesTheNewClient(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + fx.svc.testHookBeforeCommit = func() { fx.cfg.Profiles = fx.cfg.Profiles[1:] } // "ro" vanishes + + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + assert.Empty(t, fx.grants(), "the new client's logins are removed") + bs, _ := fx.sm.ListOAuthClientBindings() + assert.Empty(t, bs, "and its binding (the ever-used marker is never cleared)") + rows := fx.changeRows("deny") + require.Len(t, rows, 1) + assert.Equal(t, "profile_gone", rows[0]["reason"]) + assert.Empty(t, fx.changeRows("issue")) + assert.Zero(t, issuedEvents(fx), "nothing announces an issued login") +} + +func TestExchange_ProfileDeletedByAReloadRevokesOnlyTheGrantOfAnExistingClient(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + fx.svc.testHookBeforeCommit = func() { fx.cfg.Profiles = fx.cfg.Profiles[1:] } + + _, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + requireInvalidGrant(t, terr) + gs := fx.grants() + require.Len(t, gs, 1) + assert.True(t, gs[0].Revoked, "the grant just created is revoked") + tok, _ := fx.sm.GetAgentTokenByName("client-codex") + assert.False(t, tok.Revoked, "the API key is not touched") + assert.Equal(t, "profile_gone", fx.changeRows("deny")[0]["reason"]) + assert.Zero(t, issuedEvents(fx)) +} + +func TestExchange_GuardRefusalAfterTheCommitUndoesTheLogin(t *testing.T) { + fx := newOAuthFx(t) + fx.guard = ConservativeBindingGuard{} + reg := fx.register() + code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) + fx.svc.testHookBeforeCommit = func() { fx.cfg.RequireMCPAuth = false } // a reload turns auth off + + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) + assert.Empty(t, fx.grants()) + rows := fx.changeRows("deny") + require.Len(t, rows, 1) + assert.Equal(t, "guard", rows[0]["reason"]) + assert.Zero(t, issuedEvents(fx)) +} + +// --- 2: Approve finalisation cannot interleave with a cancel --------------------------------- + +func TestApprove_FinalisationIsAtomicAgainstASwitchOff(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + id := fx.authorize(reg, "cursor") + cancelDone := make(chan struct{}) + var once sync.Once + fx.svc.testHookApproveFinalising = func() { + once.Do(func() { + go func() { fx.svc.CancelAll("race"); close(cancelDone) }() + select { + case <-cancelDone: + t.Error("a cancel completed while Approve was finalising") + case <-time.After(100 * time.Millisecond): // it is blocked on lifecycleMu + } + }) + } + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Profile: oauthStrp("ro")}) + require.NoError(t, err, "the cancel came after finalisation") + code := oauthCodeOf(t, redirect) + <-cancelDone + require.Len(t, fx.changeRows("approve"), 1) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) + requireInvalidGrant(t, terr) // the code was cancelled: fine and expected + fx.nothingStored() +} + +// --- 3: key I/O never blocks the switch-off ------------------------------------------------------ + +func TestSwitchOffDoesNotWaitOnLazyKeyInitialisation(t *testing.T) { + fx := newOAuthFx(t) + reg := fx.register() + release := make(chan struct{}) + entered := make(chan struct{}, 1) + svc := NewOAuthLoginService(OAuthLoginDeps{ + Store: fx.sm, Config: func() *config.Config { return fx.cfg }, Now: fx.clock.Now, + HMACKey: func() ([]byte, error) { + select { + case entered <- struct{}{}: + default: + } + <-release + return oauthTestKey, nil + }, + }) + go func() { _, _ = svc.BeginAuthorization(fx.authInput(reg, oauthTestOrigin+"/mcp/oauth/cursor")) }() + <-entered // key initialisation is now stalled + + done := make(chan struct{}) + go func() { + svc.CancelAll("switch_off") + unlock := svc.beginDisable("switch_off") + unlock() + close(done) + }() + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("the switch-off waited on key I/O") + } + close(release) +} + +// --- 4: connect rollback never restores a binding the guard refuses --------------------------------- + +func rollbackFixture(t *testing.T) (*oauthFx, connect.CredentialMinter, *connect.IssuedCredential) { + fx := newOAuthFx(t) + fx.loginNew("cursor", "ro") // browser-only client bound to ro (locked) + m := fx.clients.ConnectMinter() + rw := "rw" + issued, err := m.Issue("cursor", connect.CredentialIntent{Profile: &rw}) + require.NoError(t, err) + b, _ := fx.sm.GetOAuthClientBinding("cursor") + require.Equal(t, "rw", b.ProfilePin, "the connect moved both copies") + return fx, m, issued +} + +func TestConnectRollback_RestoresThePriorBindingWhenTheGuardAllowsIt(t *testing.T) { + fx, m, issued := rollbackFixture(t) + require.NoError(t, m.Abort("cursor", connect.CredentialIntent{}, issued)) + b, _ := fx.sm.GetOAuthClientBinding("cursor") + assert.Equal(t, "ro", b.ProfilePin, "as before: the aborted connect is undone") + tok, _ := fx.sm.GetAgentTokenByName("client-cursor") + assert.True(t, tok.Revoked) +} + +func TestConnectRollback_SkipsTheRestoreWhenTheGuardNowRefusesIt(t *testing.T) { + fx, m, issued := rollbackFixture(t) + fx.guard = StrictOfflineBindingGuard{} + fx.cfg.RequireMCPAuth = false // the config changed since the connect + + require.NoError(t, m.Abort("cursor", connect.CredentialIntent{}, issued)) + tok, _ := fx.sm.GetAgentTokenByName("client-cursor") + assert.True(t, tok.Revoked, "the API key is still revoked") + b, _ := fx.sm.GetOAuthClientBinding("cursor") + assert.Equal(t, "rw", b.ProfilePin, "the logins keep the binding the guard already accepts") + assert.False(t, fx.grants()[0].Revoked) + rows := fx.changeRows("forget") + require.Len(t, rows, 1) + diff, _ := rows[0]["diff"].(map[string]interface{}) + assert.Equal(t, "guard", diff["restore_skipped"]) +} + +func TestConnectRollback_APIKeyOnlyClientIsUnchanged(t *testing.T) { + fx := newOAuthFx(t) + m := fx.clients.ConnectMinter() + rw := "rw" + issued, err := m.Issue("cursor", connect.CredentialIntent{Profile: &rw}) + require.NoError(t, err) + fx.guard = StrictOfflineBindingGuard{} + fx.cfg.RequireMCPAuth = false + require.NoError(t, m.Abort("cursor", connect.CredentialIntent{}, issued)) + assert.Empty(t, fx.changeRows("forget"), "no row, exactly as before") +} + +// --- 5: a CredentialsService without a clients service ----------------------------------------------- + +func newClientlessCreds(fx *oauthFx) *CredentialsService { + return NewCredentialsService(CredentialsServiceDeps{ + Tokens: fx.sm, HMACKey: func() ([]byte, error) { return oauthTestKey, nil }, + Config: func() *config.Config { return fx.cfg }, Activity: func(*storage.ActivityRecord) error { return nil }, + Now: fx.clock.Now, + }) +} + +func TestRevokeByTokenName_WithoutAClientsService(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + cs := newClientlessCreds(fx) + + r, err := cs.Revoke(context.Background(), fx.actor(), CredentialRef{Token: "client-codex"}, true) + require.NoError(t, err, "no panic, the original token-revoke path") + assert.True(t, r.Changed) + r, err = cs.Revoke(context.Background(), fx.actor(), CredentialRef{Token: "client-codex"}, true) + require.NoError(t, err) + assert.False(t, r.Changed, "already revoked") +} + +func TestRevokeByTokenName_WithoutAClientsServiceButWithLogins(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + reg := fx.register() + id := fx.authorize(reg, "codex") + rev, _ := fx.sm.ClientBindingRevision("codex") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) + require.NoError(t, err) + _, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + + cs := newClientlessCreds(fx) + _, err = cs.Revoke(context.Background(), fx.actor(), CredentialRef{Token: "client-codex"}, true) + var ce *CredentialError + require.True(t, errors.As(err, &ce), "a controlled error, not a panic") + tok, _ := fx.sm.GetAgentTokenByName("client-codex") + assert.False(t, tok.Revoked, "nothing half-done") + assert.False(t, fx.grants()[0].Revoked) +} + +var _ = mcplogin.AccessTokenPrefix diff --git a/internal/runtime/oauth_login_service.go b/internal/runtime/oauth_login_service.go index 32aba090c..3c916a7b3 100644 --- a/internal/runtime/oauth_login_service.go +++ b/internal/runtime/oauth_login_service.go @@ -52,6 +52,16 @@ import ( // (and cancelled by it), and one admitted after sees the switch off. Exchange's // commit callback holds Store.mu and reads Runtime.mu through the guard, but no // path holds Runtime.mu and then waits for Store.mu or lifecycleMu. +// +// Approve's finalisation (final status check, activity row, event, redirect) +// runs under lifecycleMu taken AFTER bindingWriteMu, so a switch-off cannot +// interleave with it; it does one storage write (the activity row) under it, and +// the switch-off commit only waits for that. The lazy token key is created under +// keyInitMu, a leaf lock held across key I/O that nothing else waits behind: +// reqMu is never held across I/O, so existingRequests (and the switch-off) never +// wait on it. A file reload does not take bindingWriteMu, so Exchange re-checks +// the live config after CommitOAuthLogin and undoes the login when it no longer +// holds (postCommitRefusal). type OAuthLoginService struct { store OAuthLoginStore hmacKey func() ([]byte, error) @@ -78,6 +88,9 @@ type OAuthLoginService struct { // test hooks, nil in production. testHookBeginAfterEnabled func() testHookApproveAfterStore func() + testHookApproveFinalising func() + testHookBeforeCommit func() + keyInitMu sync.Mutex everUsed bool // positive results only everMu sync.Mutex @@ -106,6 +119,7 @@ type OAuthLoginStore interface { CurrentClientBinding(clientID string) (pin, mode string, found bool, err error) ClientBindingRevision(clientID string) (string, error) OAuthLoginEverUsed() (bool, error) + ForgetClientLogins(clientID string) (int, error) } // Token lifetimes of a browser login (research R6). @@ -188,16 +202,26 @@ func (s *OAuthLoginService) EverUsed() bool { // requests returns the request store, building it on first use. func (s *OAuthLoginService) requests() (*mcplogin.Store, error) { - s.reqMu.Lock() - defer s.reqMu.Unlock() - if s.reqs != nil { - return s.reqs, nil + if st := s.existingRequests(); st != nil { + return st, nil + } + // The key may be created on disk: do that OUTSIDE reqMu (serialised by its + // own mutex), so existingRequests, and with it the switch-off path, never + // waits on key I/O. Then install the store under reqMu, double-checked. + s.keyInitMu.Lock() + defer s.keyInitMu.Unlock() + if st := s.existingRequests(); st != nil { + return st, nil } key, err := s.hmacKey() if err != nil { return nil, err } - s.reqs = mcplogin.NewStore(key, s.now) + s.reqMu.Lock() + defer s.reqMu.Unlock() + if s.reqs == nil { + s.reqs = mcplogin.NewStore(key, s.now) + } return s.reqs, nil } @@ -460,6 +484,9 @@ func (s *OAuthLoginService) Exchange(in TokenInput) (TokenResult, *TokenError) { if err != nil { return "", err } + if h := s.testHookBeforeCommit; h != nil { + h() + } stored, err := s.store.CommitOAuthLogin(storage.CommitLoginInput{ Grant: storage.OAuthGrant{ GrantID: grantID, RegistrationID: req.RegistrationID, Client: req.Decision.ClientID, @@ -489,6 +516,14 @@ func (s *OAuthLoginService) Exchange(in TokenInput) (TokenResult, *TokenError) { s.writeDecisionRow(profile.ChangeDeny, req, reason, now) return "", errExchangeRefused } + // A file reload does not take bindingWriteMu, so the config may have + // changed between the checks above and the commit. Re-read it now, before + // any token leaves: undo what this exchange stored and refuse. + if reason := s.postCommitRefusal(req.Decision, stored); reason != "" { + s.undoCommit(req.Decision, stored) + s.writeDecisionRow(profile.ChangeDeny, req, reason, now) + return "", errExchangeRefused + } tokens, grant = ts, stored return grantID, nil } From 17c939784ebe30838146b0fee99e0381ea1c490a Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sun, 22 Nov 2026 23:24:04 +0200 Subject: [PATCH 14/42] fix(oauth): fence the exchange with config commits, atomic key creation (Spec 132 PR-1d) Related #1971 --- internal/auth/agent_token.go | 33 -- internal/auth/hmac_key.go | 109 +++++++ internal/auth/hmac_key_atomic_test.go | 83 +++++ internal/runtime/clients_service.go | 8 +- internal/runtime/clients_service_connect.go | 10 +- .../runtime/clients_service_restore_reason.go | 27 ++ internal/runtime/clients_service_rollback.go | 4 +- internal/runtime/oauth_login_consent.go | 2 +- internal/runtime/oauth_login_postcommit.go | 70 ----- internal/runtime/oauth_login_round2_test.go | 67 ---- internal/runtime/oauth_login_round3_test.go | 296 ++++++++++++++++++ internal/runtime/oauth_login_service.go | 121 ++++--- internal/runtime/oauth_login_tokens.go | 28 +- internal/runtime/runtime.go | 13 +- 14 files changed, 622 insertions(+), 249 deletions(-) create mode 100644 internal/auth/hmac_key.go create mode 100644 internal/auth/hmac_key_atomic_test.go create mode 100644 internal/runtime/clients_service_restore_reason.go delete mode 100644 internal/runtime/oauth_login_postcommit.go create mode 100644 internal/runtime/oauth_login_round3_test.go diff --git a/internal/auth/agent_token.go b/internal/auth/agent_token.go index a09820ec3..9bb9b8f00 100644 --- a/internal/auth/agent_token.go +++ b/internal/auth/agent_token.go @@ -7,8 +7,6 @@ import ( "encoding/hex" "errors" "fmt" - "os" - "path/filepath" "regexp" "strconv" "strings" @@ -641,37 +639,6 @@ func TokenPrefix(token string) string { // hmacKeyFile is the filename for the persisted HMAC key. const hmacKeyFile = ".token_key" -// GetOrCreateHMACKey reads the HMAC key from /.token_key. -// If the file does not exist, it generates a 32-byte random key, -// writes it with 0600 permissions, and returns it. -func GetOrCreateHMACKey(dataDir string) ([]byte, error) { - keyPath := filepath.Join(dataDir, hmacKeyFile) - - // Try to read existing key - data, err := os.ReadFile(keyPath) - if err == nil && len(data) == 32 { - return data, nil - } - - // Generate new key - key := make([]byte, 32) - if _, err := rand.Read(key); err != nil { - return nil, fmt.Errorf("failed to generate HMAC key: %w", err) - } - - // Ensure directory exists - if err := os.MkdirAll(dataDir, 0700); err != nil { - return nil, fmt.Errorf("failed to create data directory: %w", err) - } - - // Write key file with restrictive permissions - if err := os.WriteFile(keyPath, key, 0600); err != nil { - return nil, fmt.Errorf("failed to write HMAC key file: %w", err) - } - - return key, nil -} - // ValidatePermissions checks that the given permissions list is valid. // It must contain "read" and only contain valid permission values. func ValidatePermissions(perms []string) error { diff --git a/internal/auth/hmac_key.go b/internal/auth/hmac_key.go new file mode 100644 index 000000000..1af77e5c6 --- /dev/null +++ b/internal/auth/hmac_key.go @@ -0,0 +1,109 @@ +package auth + +import ( + "crypto/rand" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "sync" +) + +// hmacKeyMu serialises in-process creators. Disk exclusivity (below) covers +// other processes and every caller that bypasses this package-level lock. +var hmacKeyMu sync.Mutex + +// readValidHMACKey returns the key at path when it is a 32-byte file. +func readValidHMACKey(path string) ([]byte, bool) { + data, err := os.ReadFile(path) + if err == nil && len(data) == 32 { + return data, true + } + return nil, false +} + +// GetOrCreateHMACKey reads the HMAC key from /.token_key. +// If the file does not exist, it generates a 32-byte random key, +// writes it with 0600 permissions, and returns it. +// +// Creation is atomic for every caller: in-process callers are serialised by a +// package-level mutex, and the key reaches the final name only through a hard +// link (or O_EXCL) of a fully written 0600 temporary file in the same +// directory, so two first-time callers can never each generate a key and +// overwrite the other's. A caller that loses the race reads and returns the +// winner's key. A file of the wrong size is replaced, as it always was. +func GetOrCreateHMACKey(dataDir string) ([]byte, error) { + keyPath := filepath.Join(dataDir, hmacKeyFile) + + hmacKeyMu.Lock() + defer hmacKeyMu.Unlock() + + // Try to read existing key + if key, ok := readValidHMACKey(keyPath); ok { + return key, nil + } + + // Generate new key + key := make([]byte, 32) + if _, err := rand.Read(key); err != nil { + return nil, fmt.Errorf("failed to generate HMAC key: %w", err) + } + + // Ensure directory exists + if err := os.MkdirAll(dataDir, 0700); err != nil { + return nil, fmt.Errorf("failed to create data directory: %w", err) + } + + tmp, err := os.CreateTemp(dataDir, ".token_key.tmp-*") // created 0600 + if err != nil { + return nil, fmt.Errorf("failed to write HMAC key file: %w", err) + } + tmpPath := tmp.Name() + defer func() { _ = os.Remove(tmpPath) }() + if err := tmp.Chmod(0600); err != nil { + _ = tmp.Close() + return nil, fmt.Errorf("failed to write HMAC key file: %w", err) + } + if _, err := tmp.Write(key); err != nil { + _ = tmp.Close() + return nil, fmt.Errorf("failed to write HMAC key file: %w", err) + } + if err := tmp.Close(); err != nil { + return nil, fmt.Errorf("failed to write HMAC key file: %w", err) + } + + linkErr := os.Link(tmpPath, keyPath) + switch { + case linkErr == nil: + return key, nil + case errors.Is(linkErr, fs.ErrExist): + // Someone else created it first: theirs wins when it is valid. + if existing, ok := readValidHMACKey(keyPath); ok { + return existing, nil + } + // A corrupt file of the wrong size: replace it atomically. + if err := os.Rename(tmpPath, keyPath); err != nil { + return nil, fmt.Errorf("failed to write HMAC key file: %w", err) + } + return key, nil + default: + // No hard links on this filesystem: exclusive create instead. + f, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + if err != nil { + if errors.Is(err, fs.ErrExist) { + if existing, ok := readValidHMACKey(keyPath); ok { + return existing, nil + } + } + return nil, fmt.Errorf("failed to write HMAC key file: %w", err) + } + _, werr := f.Write(key) + cerr := f.Close() + if werr != nil || cerr != nil { + _ = os.Remove(keyPath) + return nil, fmt.Errorf("failed to write HMAC key file: %w", errors.Join(werr, cerr)) + } + return key, nil + } +} diff --git a/internal/auth/hmac_key_atomic_test.go b/internal/auth/hmac_key_atomic_test.go new file mode 100644 index 000000000..93f7c8570 --- /dev/null +++ b/internal/auth/hmac_key_atomic_test.go @@ -0,0 +1,83 @@ +package auth + +import ( + "bytes" + "os" + "path/filepath" + "sync" + "testing" +) + +// Two first-time callers must never end up with different keys: every caller of +// GetOrCreateHMACKey on an empty directory gets the one key the file holds. +func TestGetOrCreateHMACKey_ConcurrentFirstCallersAgree(t *testing.T) { + dir := t.TempDir() + const n = 32 + keys := make([][]byte, n) + errs := make([]error, n) + var wg sync.WaitGroup + start := make(chan struct{}) + for i := 0; i < n; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + <-start + keys[i], errs[i] = GetOrCreateHMACKey(dir) + }(i) + } + close(start) + wg.Wait() + + onDisk, err := os.ReadFile(filepath.Join(dir, hmacKeyFile)) + if err != nil || len(onDisk) != 32 { + t.Fatalf("key file: %v len=%d", err, len(onDisk)) + } + for i := range keys { + if errs[i] != nil { + t.Fatalf("caller %d: %v", i, errs[i]) + } + if !bytes.Equal(keys[i], onDisk) { + t.Fatalf("caller %d got a key that is not the one on disk", i) + } + } + info, _ := os.Stat(filepath.Join(dir, hmacKeyFile)) + if info.Mode().Perm() != 0o600 { + t.Fatalf("permissions %v", info.Mode().Perm()) + } + entries, _ := os.ReadDir(dir) + if len(entries) != 1 { + t.Fatalf("temporary files were left behind: %v", entries) + } +} + +func TestGetOrCreateHMACKey_ExistingKeyIsReturnedUnchanged(t *testing.T) { + dir := t.TempDir() + want := bytes.Repeat([]byte{7}, 32) + if err := os.WriteFile(filepath.Join(dir, hmacKeyFile), want, 0o600); err != nil { + t.Fatal(err) + } + got, err := GetOrCreateHMACKey(dir) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("got %x err %v", got, err) + } + onDisk, _ := os.ReadFile(filepath.Join(dir, hmacKeyFile)) + if !bytes.Equal(onDisk, want) { + t.Fatal("an existing key file was rewritten") + } +} + +// A file of the wrong size is replaced, as it always was. +func TestGetOrCreateHMACKey_WrongSizeFileIsReplaced(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, hmacKeyFile), []byte("short"), 0o600); err != nil { + t.Fatal(err) + } + got, err := GetOrCreateHMACKey(dir) + if err != nil || len(got) != 32 { + t.Fatalf("got %d bytes, err %v", len(got), err) + } + onDisk, _ := os.ReadFile(filepath.Join(dir, hmacKeyFile)) + if !bytes.Equal(onDisk, got) { + t.Fatal("the replacement is not on disk") + } +} diff --git a/internal/runtime/clients_service.go b/internal/runtime/clients_service.go index d41dbdb8a..69483588e 100644 --- a/internal/runtime/clients_service.go +++ b/internal/runtime/clients_service.go @@ -775,13 +775,9 @@ func (s *ClientsService) forgetRecordLocked(ctx context.Context, a Actor, client forget = s.store.ForgetClientCredentialRestoringPrior // A connect undone for a client with live logins must not restore a // binding the guard now refuses: revoke the key only and say so. - skip, serr := s.restoreRefusedLocked(clientID) - if serr != nil { - return nil, serr - } - if skip { + if reason := s.restoreSkipReason(clientID); reason != "" { forget = s.revokeKeyKeepingBinding - nd := map[string]interface{}{"restore_skipped": "guard"} + nd := map[string]interface{}{"restore_skipped": reason} for k, v := range diff { nd[k] = v } diff --git a/internal/runtime/clients_service_connect.go b/internal/runtime/clients_service_connect.go index 451f02128..447b7fd28 100644 --- a/internal/runtime/clients_service_connect.go +++ b/internal/runtime/clients_service_connect.go @@ -418,11 +418,7 @@ func (m connectMinter) Abort(clientID string, intent connect.CredentialIntent, i } // A fresh mint whose config write failed: revoke it and write no record // (from the operator's view nothing happened, plan D13). - skip, err := s.restoreRefusedLocked(clientID) - if err != nil { - return err - } - if skip { + if reason := s.restoreSkipReason(clientID); reason != "" { revoked, rerr := s.revokeKeyKeepingBinding(clientID) if rerr != nil { return rerr @@ -430,11 +426,11 @@ func (m connectMinter) Abort(clientID string, intent connect.CredentialIntent, i s.writeChange(context.Background(), actorOf(intent), changeRecord{ change: profile.ChangeForget, profile: revoked.ProfilePin, previousProfile: revoked.ProfilePin, clientID: clientID, tokenName: revoked.Name, - diff: map[string]interface{}{"reason": "rollback", "restore_skipped": "guard"}, + diff: map[string]interface{}{"reason": "rollback", "restore_skipped": reason}, }) return nil } - _, err = s.store.ForgetClientCredentialRestoringPrior(clientID) + _, err := s.store.ForgetClientCredentialRestoringPrior(clientID) return err } diff --git a/internal/runtime/clients_service_restore_reason.go b/internal/runtime/clients_service_restore_reason.go new file mode 100644 index 000000000..fa2f616d4 --- /dev/null +++ b/internal/runtime/clients_service_restore_reason.go @@ -0,0 +1,27 @@ +package runtime + +import "go.uber.org/zap" + +// Reasons a connect rollback does not restore the prior binding. +const ( + restoreSkippedGuard = "guard" + restoreSkippedInspectError = "inspect_error" +) + +// restoreSkipReason answers whether the rollback of a connect for clientID must +// skip restoring the prior binding: "" restores as before, "guard" when the +// guard now refuses the restored state, "inspect_error" when that could not be +// evaluated. The revocation of the fresh API key never depends on this: an +// inspection failure only costs the optional restore, and is logged (s.mu held). +func (s *ClientsService) restoreSkipReason(clientID string) string { + refused, err := s.restoreRefusedInner(clientID) + switch { + case err != nil: + s.logger.Warn("connect rollback: cannot evaluate the binding restore; revoking the key without restoring", + zap.String("client_id", clientID), zap.Error(err)) + return restoreSkippedInspectError + case refused: + return restoreSkippedGuard + } + return "" +} diff --git a/internal/runtime/clients_service_rollback.go b/internal/runtime/clients_service_rollback.go index f79c12bec..20b4288ed 100644 --- a/internal/runtime/clients_service_rollback.go +++ b/internal/runtime/clients_service_rollback.go @@ -7,7 +7,7 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" ) -// restoreRefusedLocked reports whether undoing a connect (restoring the binding +// restoreRefusedInner reports whether undoing a connect (restoring the binding // the revoked record replaced) would create a binding the guard now refuses // (s.mu held). It only matters for a client that has LIVE browser logins: the // restore also rewrites their binding, and the configuration may have changed @@ -15,7 +15,7 @@ import ( // binding plus the surviving live logins bound to it. A client without live // logins, or without a prior binding to restore, answers false: the rollback // behaves exactly as before. A read error is returned (fail closed). -func (s *ClientsService) restoreRefusedLocked(clientID string) (bool, error) { +func (s *ClientsService) restoreRefusedInner(clientID string) (bool, error) { o := s.oauthStore() has, err := s.hasLoginRecords(o, clientID) if err != nil || !has { diff --git a/internal/runtime/oauth_login_consent.go b/internal/runtime/oauth_login_consent.go index 1041b6f63..1a7e81c5e 100644 --- a/internal/runtime/oauth_login_consent.go +++ b/internal/runtime/oauth_login_consent.go @@ -683,7 +683,7 @@ func profileConfigured(cfg *config.Config, name string) bool { // checkCandidateGuard runs the binding guard over the state this client's login // would create (its entry added or replaced with Live true). func (s *OAuthLoginService) checkCandidateGuard(clientID, pin, mode string) error { - cur, cand, err := s.guardStatesFor(clientID, pin, mode) + cur, cand, err := s.guardStatesFor(s.cfg(), clientID, pin, mode) if err != nil { return err } diff --git a/internal/runtime/oauth_login_postcommit.go b/internal/runtime/oauth_login_postcommit.go deleted file mode 100644 index 6ce8472d4..000000000 --- a/internal/runtime/oauth_login_postcommit.go +++ /dev/null @@ -1,70 +0,0 @@ -package runtime - -import ( - "go.uber.org/zap" - - "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" - "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" -) - -// A file reload commits the configuration without bindingWriteMu, so the -// profile and the guard verdict the exchange checked can change between those -// checks and storage.CommitOAuthLogin. The exchange therefore re-reads the live -// configuration once more AFTER the commit and before any token is returned -// (Spec 132 R15), and undoes what it stored when the stored state is no longer -// acceptable. The reload locking itself is untouched. - -// postCommitRefusal returns "" when the stored login is still acceptable, else -// the deny reason: profile_gone, or guard (also for anything it cannot read: -// fail closed). -func (s *OAuthLoginService) postCommitRefusal(d mcplogin.Decision, g storage.OAuthGrant) string { - pin, mode, found, err := s.store.CurrentClientBinding(g.Client) - if err != nil || !found { - return "guard" - } - if pin != "" && !profileConfigured(s.cfg(), pin) { - return "profile_gone" - } - all, err := s.store.ListAgentTokens() - if err != nil { - return "guard" - } - oauth, err := LoadOAuthBindings(s.store, s.now()) - if err != nil { - return "guard" - } - grants, err := s.store.ListOAuthGrantsForClient(g.Client) - if err != nil { - return "guard" - } - otherLive := false - for i := range grants { - if grants[i].GrantID != g.GrantID && GrantStateOf(&grants[i], s.now()) == GrantStateActive { - otherLive = true - } - } - cfg := s.cfg() - tokens := guardedOnly(all) - // Before this login the client's entry was live only through its other logins. - current := GuardState{Config: cfg, Tokens: tokens, - OAuthBindings: withOAuthClient(oauth, OAuthBinding{ClientID: g.Client, Pin: pin, Mode: mode, Live: otherLive})} - candidate := GuardState{Config: cfg, Tokens: tokens, OAuthBindings: oauth} - if CheckBindingGuard(s.guard(), current, candidate) != nil { - return "guard" - } - return "" -} - -// undoCommit revokes the grant this exchange created and, for a brand-new -// client, removes what it created (grants, binding entry, registrations left -// without a grant). An existing client only loses the grant. -func (s *OAuthLoginService) undoCommit(d mcplogin.Decision, g storage.OAuthGrant) { - if _, err := s.store.RevokeOAuthGrant(g.GrantID, storage.OAuthRevokeAdmin, s.now().UTC()); err != nil { - s.logger.Error("browser login: cannot revoke a login that failed its post-commit check", zap.Error(err)) - } - if d.NewClient { - if _, err := s.store.ForgetClientLogins(g.Client); err != nil { - s.logger.Error("browser login: cannot remove a new client that failed its post-commit check", zap.Error(err)) - } - } -} diff --git a/internal/runtime/oauth_login_round2_test.go b/internal/runtime/oauth_login_round2_test.go index ae18d629b..6ab8a6d10 100644 --- a/internal/runtime/oauth_login_round2_test.go +++ b/internal/runtime/oauth_login_round2_test.go @@ -17,73 +17,6 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" ) -// --- 1: a reload between the pre-check and the commit ------------------------------------- - -func issuedEvents(fx *oauthFx) int { - n := 0 - for _, e := range fx.eventsOf(EventTypeCredentialsChanged) { - if e.Payload["change"] == "issue" { - n++ - } - } - return n -} - -func TestExchange_ProfileDeletedByAReloadBetweenCheckAndCommitUndoesTheNewClient(t *testing.T) { - fx := newOAuthFx(t) - reg := fx.register() - code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) - fx.svc.testHookBeforeCommit = func() { fx.cfg.Profiles = fx.cfg.Profiles[1:] } // "ro" vanishes - - _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) - requireInvalidGrant(t, terr) - assert.Empty(t, fx.grants(), "the new client's logins are removed") - bs, _ := fx.sm.ListOAuthClientBindings() - assert.Empty(t, bs, "and its binding (the ever-used marker is never cleared)") - rows := fx.changeRows("deny") - require.Len(t, rows, 1) - assert.Equal(t, "profile_gone", rows[0]["reason"]) - assert.Empty(t, fx.changeRows("issue")) - assert.Zero(t, issuedEvents(fx), "nothing announces an issued login") -} - -func TestExchange_ProfileDeletedByAReloadRevokesOnlyTheGrantOfAnExistingClient(t *testing.T) { - fx := newOAuthFx(t) - fx.mintClient("codex", "ro", auth.ProfileModeLocked) - reg := fx.register() - id := fx.authorize(reg, "codex") - rev, _ := fx.sm.ClientBindingRevision("codex") - redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev}) - require.NoError(t, err) - fx.svc.testHookBeforeCommit = func() { fx.cfg.Profiles = fx.cfg.Profiles[1:] } - - _, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) - requireInvalidGrant(t, terr) - gs := fx.grants() - require.Len(t, gs, 1) - assert.True(t, gs[0].Revoked, "the grant just created is revoked") - tok, _ := fx.sm.GetAgentTokenByName("client-codex") - assert.False(t, tok.Revoked, "the API key is not touched") - assert.Equal(t, "profile_gone", fx.changeRows("deny")[0]["reason"]) - assert.Zero(t, issuedEvents(fx)) -} - -func TestExchange_GuardRefusalAfterTheCommitUndoesTheLogin(t *testing.T) { - fx := newOAuthFx(t) - fx.guard = ConservativeBindingGuard{} - reg := fx.register() - code := fx.approvedCode(reg, "cursor", ApprovalChoice{Profile: oauthStrp("ro")}) - fx.svc.testHookBeforeCommit = func() { fx.cfg.RequireMCPAuth = false } // a reload turns auth off - - _, terr := fx.svc.Exchange(fx.tokenInput(reg, code)) - requireInvalidGrant(t, terr) - assert.Empty(t, fx.grants()) - rows := fx.changeRows("deny") - require.Len(t, rows, 1) - assert.Equal(t, "guard", rows[0]["reason"]) - assert.Zero(t, issuedEvents(fx)) -} - // --- 2: Approve finalisation cannot interleave with a cancel --------------------------------- func TestApprove_FinalisationIsAtomicAgainstASwitchOff(t *testing.T) { diff --git a/internal/runtime/oauth_login_round3_test.go b/internal/runtime/oauth_login_round3_test.go new file mode 100644 index 000000000..334ec5107 --- /dev/null +++ b/internal/runtime/oauth_login_round3_test.go @@ -0,0 +1,296 @@ +package runtime + +import ( + "context" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/connect" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// --- the exchange is fenced against config publication (real runtime) ----------------------------- + +func enabledFunnelRuntime(t *testing.T) *Runtime { + t.Helper() + rt := newFunnelRuntime(t) + _, err := rt.Commit("test_on", func(tx *CommitTx) error { + return tx.MutateGlobal(func(c *config.Config) error { c.MCPOAuthEnabled = true; return nil }) + }) + require.NoError(t, err) + return rt +} + +func rtActor() context.Context { + return ContextWithActor(context.Background(), Actor{Kind: "api_key", Name: "admin", Surface: "api"}) +} + +// rtApprovedNewClient registers, authorizes at the generic address and approves a +// NEW client bound to profile pin; it returns the registration and the code. +func rtApprovedNewClient(t *testing.T, rt *Runtime, client, pin string) (reg, code string) { + t.Helper() + svc := rt.OAuthLoginService() + resp, rerr, err := svc.Register(mcplogin.RegistrationRequest{RedirectURIs: []string{oauthTestRedirect}, ClientName: "App"}) + require.NoError(t, err) + require.Nil(t, rerr) + reg = resp["client_id"].(string) + id, aerr := svc.BeginAuthorization(AuthorizeInput{ + Origin: oauthTestOrigin, ClientID: reg, RedirectURI: oauthTestRedirect, State: "s", + CodeChallenge: oauthTestChallenge(), Method: "S256", Resource: oauthTestOrigin + "/mcp/oauth", ResponseType: "code", + }) + require.Nil(t, aerr) + redirect, err := svc.Approve(rtActor(), id, ApprovalChoice{Client: ClientChoice{New: &NewClientChoice{ID: client}}, Profile: oauthStrp(pin)}) + require.NoError(t, err) + return reg, oauthCodeOf(t, redirect) +} + +func rtToken(reg, code string) TokenInput { + return TokenInput{Origin: oauthTestOrigin, Code: code, RedirectURI: oauthTestRedirect, ClientID: reg, CodeVerifier: oauthTestVerifier} +} + +func deleteProfileRO(c *config.Config) error { + kept := c.Profiles[:0:0] + for _, p := range c.Profiles { + if p.Name != "ro" { + kept = append(kept, p) + } + } + c.Profiles = kept + return nil +} + +// A config publication attempted DURING the exchange (the file-reload entry point +// and the API funnel) waits for it, then succeeds over the stored login. +func TestExchange_ConfigPublicationWaitsForTheExchange(t *testing.T) { + rt := enabledFunnelRuntime(t) + reg, code := rtApprovedNewClient(t, rt, "acme", "ro") + svc := rt.OAuthLoginService() + + reloadDone := make(chan error, 1) + funnelDone := make(chan error, 1) + var reloadFinished, funnelFinished atomic.Bool + var once sync.Once + svc.testHookBeforeCommit = func() { + once.Do(func() { + go func() { + _, err := rt.Commit(commitReasonFileReload, func(tx *CommitTx) error { return tx.MutateGlobal(deleteProfileRO) }) + reloadFinished.Store(true) + reloadDone <- err + }() + go func() { + _, _, err := rt.MutateConfig(context.Background(), funnelActor(), func(d *config.Config) (ChangeHint, error) { + d.AnonymousProfile = "" + return ChangeHint{}, nil + }, TokenRewrite{}) + funnelFinished.Store(true) + funnelDone <- err + }() + time.Sleep(150 * time.Millisecond) + if reloadFinished.Load() { + t.Error("a config publication completed while the exchange held the fence") + } + if funnelFinished.Load() { + t.Error("a funnel write completed while the exchange held the fence") + } + }) + } + + res, terr := svc.Exchange(rtToken(reg, code)) + require.Nil(t, terr, "the exchange saw the config as it was when it started") + require.NotEmpty(t, res.AccessToken) + require.NoError(t, <-reloadDone) + require.NoError(t, <-funnelDone) + + gs, err := rt.StorageManager().ListOAuthGrants() + require.NoError(t, err) + require.Len(t, gs, 1) + assert.False(t, gs[0].Revoked, "the login is handled by the ordinary config path afterwards") + pin, _, found, _ := rt.StorageManager().CurrentClientBinding("acme") + require.True(t, found) + assert.Equal(t, "ro", pin, "a now-dangling pin is deny-all, never wider") +} + +// A reload that completed just before: the exchange sees it and refuses. +func TestExchange_ReloadCompletedBeforeIsSeenAndRefused(t *testing.T) { + rt := enabledFunnelRuntime(t) + reg, code := rtApprovedNewClient(t, rt, "acme", "ro") + _, err := rt.Commit(commitReasonFileReload, func(tx *CommitTx) error { return tx.MutateGlobal(deleteProfileRO) }) + require.NoError(t, err) + + _, terr := rt.OAuthLoginService().Exchange(rtToken(reg, code)) + requireInvalidGrant(t, terr) + gs, _ := rt.StorageManager().ListOAuthGrants() + assert.Empty(t, gs) + reasons := []interface{}{} + for _, m := range profileChanges(t, rt) { + if m["change"] == "deny" { + reasons = append(reasons, m["reason"]) + } + } + assert.Equal(t, []interface{}{"profile_gone"}, reasons) +} + +// The replacement scenario: the reload that turned auth off came earlier, the +// binding was already bypassable. The pre-commit guard decides, once: the +// replacement succeeds and the client is never left with no live login. +func TestExchange_ReplacementOfAnAlreadyBypassableBindingSucceeds(t *testing.T) { + fx := newOAuthFx(t) + fx.guard = ConservativeBindingGuard{} + reg, _ := fx.loginNew("cursor", "ro") // auth on at the time + old := fx.grants()[0] + fx.cfg.RequireMCPAuth = false // a reload turned auth off earlier + + id := fx.authorize(reg, "cursor") + rev, _ := fx.sm.ClientBindingRevision("cursor") + redirect, err := fx.svc.Approve(fx.ctx(), id, ApprovalChoice{BindingRevision: rev, ReplaceGrant: old.GrantID}) + require.NoError(t, err, "no new bypassable binding: the guard has nothing to add") + res, terr := fx.svc.Exchange(fx.tokenInput(reg, oauthCodeOf(t, redirect))) + require.Nil(t, terr) + + live := 0 + for _, g := range fx.grants() { + if !g.Revoked { + live++ + } + } + assert.Equal(t, 1, live, "exactly the replacement is live") + _, _, aerr := fx.svc.Authenticate(res.AccessToken, oauthTestOrigin, "/mcp/oauth/cursor", fx.clock.Now()) + assert.NoError(t, aerr) +} + +// --- the lock-order hammer, with config commits ------------------------------------------------------------ + +func TestExchangeAgainstConfigCommitsRevokeAndReloadDoesNotDeadlockOrRace(t *testing.T) { + rt := enabledFunnelRuntime(t) + const n = 8 + type pending struct{ reg, code string } + var ps []pending + for i := 0; i < n; i++ { + reg, code := rtApprovedNewClient(t, rt, "app"+string(rune('a'+i)), "ro") + ps = append(ps, pending{reg, code}) + } + svc := rt.OAuthLoginService() + + done := make(chan struct{}) + go func() { + defer close(done) + var wg sync.WaitGroup + for _, p := range ps { + p := p + wg.Add(1) + go func() { defer wg.Done(); _, _ = svc.Exchange(rtToken(p.reg, p.code)) }() + } + for i := 0; i < 4; i++ { + wg.Add(4) + go func() { // the API commit path + defer wg.Done() + _, _ = rt.Commit("test", func(tx *CommitTx) error { + return tx.MutateGlobal(func(c *config.Config) error { c.ToolsLimit++; return nil }) + }) + }() + go func() { // the file-reload entry point + defer wg.Done() + _ = rt.ReloadConfiguration() + }() + go func() { // the funnel + defer wg.Done() + _, _, _ = rt.MutateConfig(context.Background(), funnelActor(), func(d *config.Config) (ChangeHint, error) { + return ChangeHint{}, nil + }, TokenRewrite{}) + }() + go func() { + defer wg.Done() + _, _ = rt.CredentialsService().Revoke(rtActor(), funnelActor(), CredentialRef{Client: "appa"}, false) + svc.CancelForClient("appb") + }() + } + wg.Wait() + }() + select { + case <-done: + case <-time.After(120 * time.Second): + t.Fatal("deadlock between the exchange and config commits") + } +} + +// --- connect rollback when the guard inspection itself fails --------------------------------------------- + +type armedFailStore struct { + *storage.Manager + armed *atomic.Bool +} + +func (a armedFailStore) ListOAuthGrants() ([]storage.OAuthGrant, error) { + if a.armed.Load() { + return nil, assert.AnError + } + return a.Manager.ListOAuthGrants() +} + +func failingRollbackFixture(t *testing.T) (*oauthFx, *ClientsService, *atomic.Bool) { + fx := newOAuthFx(t) + fx.loginNew("cursor", "ro") + armed := &atomic.Bool{} + cs := NewClientsService(ClientsServiceDeps{ + Store: armedFailStore{fx.sm, armed}, HMACKey: func() ([]byte, error) { return oauthTestKey, nil }, + Config: func() *config.Config { return fx.cfg }, Guard: func() BindingGuard { return stubGuard{} }, + Activity: func(r *storage.ActivityRecord) error { + fx.mu.Lock() + defer fx.mu.Unlock() + fx.rows = append(fx.rows, r) + return nil + }, + Now: fx.clock.Now, Mu: fx.clients.mu, + }) + return fx, cs, armed +} + +func TestConnectAbort_InspectionFailureStillRevokesTheFreshKey(t *testing.T) { + fx, cs, armed := failingRollbackFixture(t) + m := cs.ConnectMinter() + rw := "rw" + issued, err := m.Issue("cursor", connect.CredentialIntent{Profile: &rw}) + require.NoError(t, err) + armed.Store(true) + + require.NoError(t, m.Abort("cursor", connect.CredentialIntent{}, issued)) + tok, _ := fx.sm.GetAgentTokenByName("client-cursor") + assert.True(t, tok.Revoked, "the aborted connect's key is revoked whatever the inspection said") + b, _ := fx.sm.GetOAuthClientBinding("cursor") + assert.Equal(t, "rw", b.ProfilePin, "the prior binding is not restored") + rows := fx.changeRows("forget") + require.Len(t, rows, 1) + diff, _ := rows[0]["diff"].(map[string]interface{}) + assert.Equal(t, "inspect_error", diff["restore_skipped"]) +} + +func TestConnectUndo_InspectionFailureStillRevokesTheFreshKey(t *testing.T) { + fx, cs, armed := failingRollbackFixture(t) + m := cs.ConnectMinter() + rw := "rw" + _, err := m.Issue("cursor", connect.CredentialIntent{Profile: &rw}) + require.NoError(t, err) + armed.Store(true) + + name, err := m.ForgetUnheld("cursor", "", connect.CredentialIntent{}) + require.NoError(t, err) + assert.Equal(t, "client-cursor", name) + tok, _ := fx.sm.GetAgentTokenByName("client-cursor") + assert.True(t, tok.Revoked) + b, _ := fx.sm.GetOAuthClientBinding("cursor") + assert.Equal(t, "rw", b.ProfilePin) + rows := fx.changeRows("forget") + require.Len(t, rows, 1) + diff, _ := rows[0]["diff"].(map[string]interface{}) + assert.Equal(t, "inspect_error", diff["restore_skipped"]) +} + +var _ = auth.KindClient diff --git a/internal/runtime/oauth_login_service.go b/internal/runtime/oauth_login_service.go index 3c916a7b3..0216b8bff 100644 --- a/internal/runtime/oauth_login_service.go +++ b/internal/runtime/oauth_login_service.go @@ -23,7 +23,7 @@ import ( // the in-memory request store takes the runtime's bindingWriteMu FIRST and the // request store's own mutex second: // -// bindingWriteMu -> mcplogin.Store.mu -> storage.Manager.mu +// bindingWriteMu -> configCommitMu (Exchange only) -> mcplogin.Store.mu -> storage.Manager.mu // // - Exchange takes bindingWriteMu BEFORE calling Store.Consume, and its commit // callback (which Consume runs under Store.mu) does NOT take bindingWriteMu @@ -56,12 +56,21 @@ import ( // Approve's finalisation (final status check, activity row, event, redirect) // runs under lifecycleMu taken AFTER bindingWriteMu, so a switch-off cannot // interleave with it; it does one storage write (the activity row) under it, and -// the switch-off commit only waits for that. The lazy token key is created under -// keyInitMu, a leaf lock held across key I/O that nothing else waits behind: -// reqMu is never held across I/O, so existingRequests (and the switch-off) never -// wait on it. A file reload does not take bindingWriteMu, so Exchange re-checks -// the live config after CommitOAuthLogin and undoes the login when it no longer -// holds (postCommitRefusal). +// the switch-off commit only waits for that. The lazy token key is created before +// reqMu is taken (auth.GetOrCreateHMACKey is atomic): reqMu is never held across +// I/O, so existingRequests (and the switch-off) never wait on it. +// +// THE EXCHANGE FENCE. A file reload commits without bindingWriteMu, so Exchange +// takes bindingWriteMu, then configCommitMu (the lock every config publication +// holds), then Store.mu and storage, reads ONE config snapshot inside that +// section and uses it for every check. Publication is thereby fenced: a config +// change completes before the exchange starts (its checks refuse) or starts after +// the grant is stored (an ordinary change over an existing login). It is safe +// because no path holding configCommitMu waits for bindingWriteMu (MutateConfig +// and GuardedApplyConfig take bindingWriteMu BEFORE the commit; no commit hook, +// publish hook or callback calls a service that takes it), and the commit path +// never calls Exchange or Store.Consume. Key creation, token minting, events and +// notifier callbacks stay outside the fence. type OAuthLoginService struct { store OAuthLoginStore hmacKey func() ([]byte, error) @@ -73,6 +82,9 @@ type OAuthLoginService struct { now func() time.Time mu *sync.Mutex logger *zap.Logger + // commitLock is the lock every config publication holds (the runtime's + // configCommitMu); nil in tests that build the service without a runtime. + commitLock sync.Locker notifier BindingNotifier @@ -90,7 +102,6 @@ type OAuthLoginService struct { testHookApproveAfterStore func() testHookApproveFinalising func() testHookBeforeCommit func() - keyInitMu sync.Mutex everUsed bool // positive results only everMu sync.Mutex @@ -119,7 +130,6 @@ type OAuthLoginStore interface { CurrentClientBinding(clientID string) (pin, mode string, found bool, err error) ClientBindingRevision(clientID string) (string, error) OAuthLoginEverUsed() (bool, error) - ForgetClientLogins(clientID string) (int, error) } // Token lifetimes of a browser login (research R6). @@ -144,13 +154,16 @@ type OAuthLoginDeps struct { // Requests is the in-memory request and code store (tests inject one with // a fake clock). Requests *mcplogin.Store + // ConfigCommitLock fences the token exchange against config publication + // (see exchangeFenced). Nil is allowed. + ConfigCommitLock sync.Locker } // NewOAuthLoginService builds the service. func NewOAuthLoginService(d OAuthLoginDeps) *OAuthLoginService { s := &OAuthLoginService{ store: d.Store, hmacKey: d.HMACKey, cfg: d.Config, guard: d.Guard, activity: d.Activity, - publish: d.Publish, now: d.Now, mu: d.Mu, logger: d.Logger, reqs: d.Requests, + publish: d.Publish, now: d.Now, mu: d.Mu, logger: d.Logger, reqs: d.Requests, commitLock: d.ConfigCommitLock, lastTouch: map[string]time.Time{}, } if s.now == nil { @@ -205,14 +218,10 @@ func (s *OAuthLoginService) requests() (*mcplogin.Store, error) { if st := s.existingRequests(); st != nil { return st, nil } - // The key may be created on disk: do that OUTSIDE reqMu (serialised by its - // own mutex), so existingRequests, and with it the switch-off path, never - // waits on key I/O. Then install the store under reqMu, double-checked. - s.keyInitMu.Lock() - defer s.keyInitMu.Unlock() - if st := s.existingRequests(); st != nil { - return st, nil - } + // The key may be created on disk (atomically, see auth.GetOrCreateHMACKey): + // do that OUTSIDE reqMu, so existingRequests, and with it the switch-off + // path, never waits on key I/O. Then install the store under reqMu, + // double-checked: two racing builders hold the same key. key, err := s.hmacKey() if err != nil { return nil, err @@ -431,9 +440,13 @@ func (t *tokenSet) result() TokenResult { // the binding revision in one transaction. Any failed check answers // invalid_grant (invalid_target for a resource mismatch) with nothing stored. func (s *OAuthLoginService) Exchange(in TokenInput) (TokenResult, *TokenError) { + // Advisory early exit: a disabled install must not create a key file. The + // authoritative check is made on the one config snapshot taken below. if !s.Enabled() { return TokenResult{}, errInvalidGrant } + // Everything that may touch the key file or mint secrets happens BEFORE the + // config-commit lock is taken. reqs, err := s.requests() if err != nil { s.logger.Error("browser login: cannot build the request store", zap.Error(err)) @@ -444,12 +457,44 @@ func (s *OAuthLoginService) Exchange(in TokenInput) (TokenResult, *TokenError) { s.logger.Error("browser login: cannot read the token key", zap.Error(err)) return TokenResult{}, errTokenServer } - // Lock order: bindingWriteMu BEFORE the request store (see the type doc). + grantID, err := mcplogin.NewGrantID() + if err != nil { + return TokenResult{}, errTokenServer + } + ts, err := newTokenSet(key, grantID) + if err != nil { + return TokenResult{}, errTokenServer + } + // Events and notifier callbacks run after every lock is released. + var after []func() + res, terr := s.exchangeFenced(in, reqs, ts, grantID, &after) + for _, f := range after { + f() + } + return res, terr +} + +// exchangeFenced is the part of Exchange that runs inside the fence: +// bindingWriteMu, then configCommitMu (the lock every config publication, +// including a file reload, holds), then the request store and storage. With +// publication fenced a config change either completed before the exchange +// started (its checks see it and refuse) or starts after the grant is stored (an +// ordinary config change over an existing login, covered by the funnel's guard +// and repin logic). ONE config snapshot is read inside the fence and used for +// every check of this exchange. +func (s *OAuthLoginService) exchangeFenced(in TokenInput, reqs *mcplogin.Store, ts *tokenSet, grantID string, after *[]func()) (TokenResult, *TokenError) { s.mu.Lock() defer s.mu.Unlock() + if s.commitLock != nil { + s.commitLock.Lock() + defer s.commitLock.Unlock() + } + cfg := s.cfg() + if cfg == nil || !cfg.MCPOAuthEnabled { + return TokenResult{}, errInvalidGrant + } var ( - tokens *tokenSet grant storage.OAuthGrant decided mcplogin.Decision target bool @@ -468,22 +513,14 @@ func (s *OAuthLoginService) Exchange(in TokenInput) (TokenResult, *TokenError) { now := s.now().UTC() // A new client's profile must still exist: a later profile of the same // name must never apply silently to a decision made about another one. - if req.Decision.NewClient && req.Decision.Profile != "" && !profileConfigured(s.cfg(), req.Decision.Profile) { + if req.Decision.NewClient && req.Decision.Profile != "" && !profileConfigured(cfg, req.Decision.Profile) { s.writeDecisionRow(profile.ChangeDeny, req, "profile_gone", now) return "", errExchangeRefused } - if err := s.recheckGuard(req.Decision); err != nil { + if err := s.recheckGuard(cfg, req.Decision); err != nil { s.writeDecisionRow(profile.ChangeDeny, req, "guard", now) return "", errExchangeRefused } - grantID, err := mcplogin.NewGrantID() - if err != nil { - return "", err - } - ts, err := newTokenSet(key, grantID) - if err != nil { - return "", err - } if h := s.testHookBeforeCommit; h != nil { h() } @@ -516,15 +553,7 @@ func (s *OAuthLoginService) Exchange(in TokenInput) (TokenResult, *TokenError) { s.writeDecisionRow(profile.ChangeDeny, req, reason, now) return "", errExchangeRefused } - // A file reload does not take bindingWriteMu, so the config may have - // changed between the checks above and the commit. Re-read it now, before - // any token leaves: undo what this exchange stored and refuse. - if reason := s.postCommitRefusal(req.Decision, stored); reason != "" { - s.undoCommit(req.Decision, stored) - s.writeDecisionRow(profile.ChangeDeny, req, reason, now) - return "", errExchangeRefused - } - tokens, grant = ts, stored + grant = stored return grantID, nil } @@ -539,7 +568,7 @@ func (s *OAuthLoginService) Exchange(in TokenInput) (TokenResult, *TokenError) { // A code presented again inside the tombstone window revokes the login // it produced. An empty grant id means the first presentation stored // nothing: there is nothing to revoke. - s.revokeReplayedCode(replayedGrant) + *after = append(*after, s.revokeReplayedCode(replayedGrant)...) return TokenResult{}, errInvalidGrant default: if target { @@ -553,9 +582,11 @@ func (s *OAuthLoginService) Exchange(in TokenInput) (TokenResult, *TokenError) { } s.writeGrantRow(profile.ChangeIssue, grant, decided, "") - s.publishGrantChanged(grant, profile.ChangeIssue, req.Decision.Profile) - if s.notifier != nil && decided.ReplaceGrantID != "" { - s.notifier.NotifyBindingChanged(auth.ClientTokenName(grant.Client)) - } - return tokens.result(), nil + *after = append(*after, func() { + s.publishGrantChanged(grant, profile.ChangeIssue, req.Decision.Profile) + if s.notifier != nil && decided.ReplaceGrantID != "" { + s.notifier.NotifyBindingChanged(auth.ClientTokenName(grant.Client)) + } + }) + return ts.result(), nil } diff --git a/internal/runtime/oauth_login_tokens.go b/internal/runtime/oauth_login_tokens.go index e23372e8a..89bdd0fdb 100644 --- a/internal/runtime/oauth_login_tokens.go +++ b/internal/runtime/oauth_login_tokens.go @@ -12,6 +12,7 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" "github.com/smart-mcp-proxy/mcpproxy-go/internal/clientidentity" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" "github.com/smart-mcp-proxy/mcpproxy-go/internal/connect" "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" @@ -83,10 +84,12 @@ func (s *OAuthLoginService) Refresh(in TokenInput) (TokenResult, *TokenError) { } // revokeReplayedCode revokes the login an authorization code produced when the -// code is presented again inside the tombstone window. -func (s *OAuthLoginService) revokeReplayedCode(grantID string) { +// code is presented again inside the tombstone window. The revoke and its +// activity row happen now (under the caller's locks); the event and the +// notifier callback are returned to run after they are released. +func (s *OAuthLoginService) revokeReplayedCode(grantID string) []func() { if grantID == "" { - return + return nil } now := s.now().UTC() changed, err := s.store.RevokeOAuthGrant(grantID, storage.OAuthRevokeReplay, now) @@ -94,18 +97,20 @@ func (s *OAuthLoginService) revokeReplayedCode(grantID string) { if !errors.Is(err, storage.ErrOAuthGrantNotFound) { s.logger.Error("browser login: cannot revoke a replayed login", zap.Error(err)) } - return + return nil } if !changed { - return + return nil } g, err := s.store.GetOAuthGrant(grantID) if err != nil || g == nil { - return + return nil } s.writeGrantRow(profile.ChangeReplayRevoke, *g, mcplogin.Decision{}, "code_replay") - s.publishGrantChanged(*g, profile.ChangeReplayRevoke, "") - s.notifyGrantRevoked(*g) + return []func(){func() { + s.publishGrantChanged(*g, profile.ChangeReplayRevoke, "") + s.notifyGrantRevoked(*g) + }} } // --- authentication ------------------------------------------------------------------ @@ -306,7 +311,7 @@ func (s *OAuthLoginService) writeDecisionRow(change profile.ChangeKind, req mcpl // clientID with (pin, mode) would create: the candidate adds or replaces the // client's own browser-login entry with Live true, before anything is stored. // A storage read error is returned and the caller must refuse (fail closed). -func (s *OAuthLoginService) guardStatesFor(clientID, pin, mode string) (current, candidate GuardState, err error) { +func (s *OAuthLoginService) guardStatesFor(cfg *config.Config, clientID, pin, mode string) (current, candidate GuardState, err error) { all, err := s.store.ListAgentTokens() if err != nil { return current, candidate, fmt.Errorf("cannot inspect client bindings: %w", err) @@ -315,7 +320,6 @@ func (s *OAuthLoginService) guardStatesFor(clientID, pin, mode string) (current, if err != nil { return current, candidate, err } - cfg := s.cfg() tokens := guardedOnly(all) current = GuardState{Config: cfg, Tokens: tokens, OAuthBindings: oauth} candidate = GuardState{Config: cfg, Tokens: tokens, @@ -323,8 +327,8 @@ func (s *OAuthLoginService) guardStatesFor(clientID, pin, mode string) (current, return current, candidate, nil } -func (s *OAuthLoginService) recheckGuard(d mcplogin.Decision) error { - cur, cand, err := s.guardStatesFor(d.ClientID, d.Profile, d.Mode) +func (s *OAuthLoginService) recheckGuard(cfg *config.Config, d mcplogin.Decision) error { + cur, cand, err := s.guardStatesFor(cfg, d.ClientID, d.Profile, d.Mode) if err != nil { return err } diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index 2030b2fe2..297ea6d31 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -788,12 +788,13 @@ func New(cfg *config.Config, cfgPath string, logger *zap.Logger) (*Runtime, erro HMACKey: func() ([]byte, error) { return auth.GetOrCreateHMACKey(rt.Config().DataDir) }, - Config: rt.Config, - Guard: rt.BindingGuard, - Activity: storageManager.SaveActivity, - Publish: rt.publishEvent, - Mu: &rt.bindingWriteMu, - Logger: logger, + Config: rt.Config, + Guard: rt.BindingGuard, + Activity: storageManager.SaveActivity, + Publish: rt.publishEvent, + Mu: &rt.bindingWriteMu, + Logger: logger, + ConfigCommitLock: &rt.configCommitMu, }) rt.clientsService.SetLoginCanceler(func(clientID string) { rt.oauthLoginService.CancelForClient(clientID) }) rt.credentialsService.SetOAuthLogin(rt.oauthLoginService) From 07613288a4e848042e7fa550481bf19f4146c5c6 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 00:19:32 +0200 Subject: [PATCH 15/42] fix(oauth): fence refresh with config commits, complete key-file fallback (Spec 132 PR-1d) Related #1971 --- internal/auth/hmac_key.go | 57 ++++----- internal/auth/hmac_key_fallback_test.go | 66 ++++++++++ internal/runtime/oauth_login_refresh_fence.go | 42 +++++++ internal/runtime/oauth_login_round4_test.go | 119 ++++++++++++++++++ internal/runtime/oauth_login_service.go | 2 + internal/runtime/oauth_login_tokens.go | 9 +- 6 files changed, 258 insertions(+), 37 deletions(-) create mode 100644 internal/auth/hmac_key_fallback_test.go create mode 100644 internal/runtime/oauth_login_refresh_fence.go create mode 100644 internal/runtime/oauth_login_round4_test.go diff --git a/internal/auth/hmac_key.go b/internal/auth/hmac_key.go index 1af77e5c6..92d8d173c 100644 --- a/internal/auth/hmac_key.go +++ b/internal/auth/hmac_key.go @@ -4,7 +4,6 @@ import ( "crypto/rand" "errors" "fmt" - "io/fs" "os" "path/filepath" "sync" @@ -14,6 +13,10 @@ import ( // other processes and every caller that bypasses this package-level lock. var hmacKeyMu sync.Mutex +// linkFile publishes the temp file without replacing a target; a variable so a +// test can simulate a filesystem without hard links. +var linkFile = os.Link + // readValidHMACKey returns the key at path when it is a 32-byte file. func readValidHMACKey(path string) ([]byte, bool) { data, err := os.ReadFile(path) @@ -29,10 +32,17 @@ func readValidHMACKey(path string) ([]byte, bool) { // // Creation is atomic for every caller: in-process callers are serialised by a // package-level mutex, and the key reaches the final name only through a hard -// link (or O_EXCL) of a fully written 0600 temporary file in the same -// directory, so two first-time callers can never each generate a key and -// overwrite the other's. A caller that loses the race reads and returns the -// winner's key. A file of the wrong size is replaced, as it always was. +// link (or, where links are unsupported, an atomic rename) of a fully written +// 0600 temporary file in the same directory, so a crash never leaves a partial +// key and two first-time callers can never each generate a key and overwrite +// the other's. A caller that loses the race returns the winner's key; after any +// write the on-disk bytes are re-read and returned. A file of the wrong size +// (empty included) is replaced, as it always was. +// +// Single-process assumption: replacing an INVALID file is not guarded across +// processes. That is safe because one data dir has one core process (the bbolt +// lock on config.db, exit code 3) and every caller runs only after its process +// holds that lock. func GetOrCreateHMACKey(dataDir string) ([]byte, error) { keyPath := filepath.Join(dataDir, hmacKeyFile) @@ -73,37 +83,22 @@ func GetOrCreateHMACKey(dataDir string) ([]byte, error) { return nil, fmt.Errorf("failed to write HMAC key file: %w", err) } - linkErr := os.Link(tmpPath, keyPath) - switch { - case linkErr == nil: - return key, nil - case errors.Is(linkErr, fs.ErrExist): - // Someone else created it first: theirs wins when it is valid. + // Publish the complete temp file. A hard link never replaces an existing + // target; when it fails (the target exists, or the filesystem has no hard + // links) a valid existing key wins, and otherwise the complete temp file is + // renamed into place, which is atomic and works on every filesystem and also + // recovers an empty or wrong-size target. + if err := linkFile(tmpPath, keyPath); err != nil { if existing, ok := readValidHMACKey(keyPath); ok { return existing, nil } - // A corrupt file of the wrong size: replace it atomically. if err := os.Rename(tmpPath, keyPath); err != nil { return nil, fmt.Errorf("failed to write HMAC key file: %w", err) } - return key, nil - default: - // No hard links on this filesystem: exclusive create instead. - f, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) - if err != nil { - if errors.Is(err, fs.ErrExist) { - if existing, ok := readValidHMACKey(keyPath); ok { - return existing, nil - } - } - return nil, fmt.Errorf("failed to write HMAC key file: %w", err) - } - _, werr := f.Write(key) - cerr := f.Close() - if werr != nil || cerr != nil { - _ = os.Remove(keyPath) - return nil, fmt.Errorf("failed to write HMAC key file: %w", errors.Join(werr, cerr)) - } - return key, nil } + // Whatever happened above, return what is on disk now. + if onDisk, ok := readValidHMACKey(keyPath); ok { + return onDisk, nil + } + return nil, errors.New("failed to write HMAC key file: the key file is unreadable after writing") } diff --git a/internal/auth/hmac_key_fallback_test.go b/internal/auth/hmac_key_fallback_test.go new file mode 100644 index 000000000..17f528c8c --- /dev/null +++ b/internal/auth/hmac_key_fallback_test.go @@ -0,0 +1,66 @@ +package auth + +import ( + "bytes" + "errors" + "os" + "path/filepath" + "testing" +) + +func noLinks(t *testing.T) { + t.Helper() + orig := linkFile + linkFile = func(string, string) error { return errors.New("hard links are not supported") } + t.Cleanup(func() { linkFile = orig }) +} + +// Without hard links the fallback publishes the COMPLETE temp file by rename: the +// key file is never visible empty, and the bytes on disk are what is returned. +func TestGetOrCreateHMACKey_NoHardLinkFallbackPublishesACompleteFile(t *testing.T) { + noLinks(t) + dir := t.TempDir() + got, err := GetOrCreateHMACKey(dir) + if err != nil || len(got) != 32 { + t.Fatalf("got %d bytes err %v", len(got), err) + } + onDisk, _ := os.ReadFile(filepath.Join(dir, hmacKeyFile)) + if !bytes.Equal(onDisk, got) { + t.Fatal("the returned key is not the one on disk") + } + info, _ := os.Stat(filepath.Join(dir, hmacKeyFile)) + if info.Mode().Perm() != 0o600 { + t.Fatalf("permissions %v", info.Mode().Perm()) + } + if entries, _ := os.ReadDir(dir); len(entries) != 1 { + t.Fatalf("temp files left behind: %v", entries) + } + // A second call reads the same key. + again, _ := GetOrCreateHMACKey(dir) + if !bytes.Equal(again, got) { + t.Fatal("second call returned another key") + } +} + +// An empty or wrong-size target is recovered on every filesystem. +func TestGetOrCreateHMACKey_EmptyTargetIsRecovered(t *testing.T) { + for name, withLinks := range map[string]bool{"links": true, "no links": false} { + t.Run(name, func(t *testing.T) { + if !withLinks { + noLinks(t) + } + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, hmacKeyFile), nil, 0o600); err != nil { + t.Fatal(err) + } + got, err := GetOrCreateHMACKey(dir) + if err != nil || len(got) != 32 { + t.Fatalf("got %d bytes err %v", len(got), err) + } + onDisk, _ := os.ReadFile(filepath.Join(dir, hmacKeyFile)) + if !bytes.Equal(onDisk, got) { + t.Fatal("not repaired on disk") + } + }) + } +} diff --git a/internal/runtime/oauth_login_refresh_fence.go b/internal/runtime/oauth_login_refresh_fence.go new file mode 100644 index 000000000..240f97294 --- /dev/null +++ b/internal/runtime/oauth_login_refresh_fence.go @@ -0,0 +1,42 @@ +package runtime + +import ( + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// rotateFenced runs storage.RotateOAuthRefresh inside the config fence: it takes +// the same ConfigCommitLock as the exchange (the lock every config publication +// holds, including the one that switches browser login off), reads ONE config +// snapshot, re-checks MCPOAuthEnabled on it and holds the lock through the +// rotation. A refresh that passed the early Enabled() check therefore cannot +// rotate secrets or extend an expiry after a commit disabled the feature: the +// commit either completed first (uniform refusal, nothing written) or starts +// after the rotation. Refresh does not take bindingWriteMu, so the order is +// configCommitMu -> storage. Key I/O and token generation happened before; the +// replay row, event and notifier run after the lock is released (by the caller). +func (s *OAuthLoginService) rotateFenced(grantID, presentedHash string, ts *tokenSet) (storage.RefreshOutcome, storage.OAuthGrant, *TokenError) { + if h := s.testHookBeforeRotateLock; h != nil { + h() + } + if s.commitLock != nil { + s.commitLock.Lock() + defer s.commitLock.Unlock() + } + cfg := s.cfg() + if cfg == nil || !cfg.MCPOAuthEnabled { + return storage.RefreshInvalid, storage.OAuthGrant{}, errInvalidGrant + } + if h := s.testHookInRotate; h != nil { + h() + } + now := s.now().UTC() + outcome, after, err := s.store.RotateOAuthRefresh(grantID, presentedHash, + ts.refreshHash, ts.refreshPrefix, ts.accessHash, now, OAuthAccessTokenTTL, OAuthRefreshTokenTTL) + if err != nil { + s.logger.Error("browser login: refresh rotation failed", zap.Error(err)) + return storage.RefreshInvalid, storage.OAuthGrant{}, errTokenServer + } + return outcome, after, nil +} diff --git a/internal/runtime/oauth_login_round4_test.go b/internal/runtime/oauth_login_round4_test.go new file mode 100644 index 000000000..177600104 --- /dev/null +++ b/internal/runtime/oauth_login_round4_test.go @@ -0,0 +1,119 @@ +package runtime + +import ( + "context" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" +) + +func switchBrowserLogin(rt *Runtime, on bool) error { + _, err := rt.Commit("test_switch", func(tx *CommitTx) error { + return tx.MutateGlobal(func(c *config.Config) error { c.MCPOAuthEnabled = on; return nil }) + }) + return err +} + +func rtLogin(t *testing.T, rt *Runtime, client string) (reg string, res TokenResult) { + t.Helper() + reg, code := rtApprovedNewClient(t, rt, client, "ro") + res, terr := rt.OAuthLoginService().Exchange(rtToken(reg, code)) + require.Nil(t, terr) + return reg, res +} + +// A switch-off commit started during a refresh waits for the rotation. +func TestRefresh_SwitchOffCommitWaitsForTheRotation(t *testing.T) { + rt := enabledFunnelRuntime(t) + reg, res := rtLogin(t, rt, "acme") + svc := rt.OAuthLoginService() + + var finished atomic.Bool + done := make(chan error, 1) + var once sync.Once + svc.testHookInRotate = func() { + once.Do(func() { + go func() { + err := switchBrowserLogin(rt, false) + finished.Store(true) + done <- err + }() + time.Sleep(150 * time.Millisecond) + if finished.Load() { + t.Error("the switch-off completed while the refresh held the fence") + } + }) + } + _, terr := svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: res.RefreshToken, ClientID: reg}) + require.Nil(t, terr, "the refresh started before the switch-off") + require.NoError(t, <-done) + assert.False(t, svc.Enabled()) +} + +// A refresh that passed the early check but meets the switch-off at the fence is +// refused uniformly and the stored grant is byte-for-byte unchanged. +func TestRefresh_AfterSwitchOffLeavesTheGrantUntouched(t *testing.T) { + fx := newOAuthFx(t) + reg, res := fx.loginNew("cursor", "ro") + before, _ := fx.sm.GetOAuthGrant(fx.grants()[0].GrantID) + fx.svc.testHookBeforeRotateLock = func() { fx.cfg.MCPOAuthEnabled = false } + + fx.clock.Advance(time.Hour) + _, terr := fx.svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: res.RefreshToken, ClientID: reg}) + requireInvalidGrant(t, terr) + after, _ := fx.sm.GetOAuthGrant(before.GrantID) + assert.Equal(t, before.RefreshHash, after.RefreshHash, "secrets not rotated") + assert.Equal(t, before.AccessHash, after.AccessHash) + assert.True(t, before.RefreshExpiresAt.Equal(after.RefreshExpiresAt), "expiry not extended") + assert.False(t, after.Revoked) +} + +// Concurrent refreshes, exchanges, switch-offs and other config commits finish. +func TestRefreshExchangeAndSwitchOffHammerDoesNotDeadlockOrRace(t *testing.T) { + rt := enabledFunnelRuntime(t) + svc := rt.OAuthLoginService() + type login struct{ reg, refresh string } + var logins []login + for _, c := range []string{"appa", "appb", "appc", "appd"} { + reg, res := rtLogin(t, rt, c) + logins = append(logins, login{reg, res.RefreshToken}) + } + done := make(chan struct{}) + go func() { + defer close(done) + var wg sync.WaitGroup + for _, l := range logins { + l := l + for i := 0; i < 3; i++ { + wg.Add(1) + go func() { + defer wg.Done() + _, _ = svc.Refresh(TokenInput{Origin: oauthTestOrigin, RefreshToken: l.refresh, ClientID: l.reg}) + }() + } + } + for i := 0; i < 4; i++ { + wg.Add(3) + go func() { defer wg.Done(); _ = switchBrowserLogin(rt, false); _ = switchBrowserLogin(rt, true) }() + go func() { defer wg.Done(); _ = rt.ReloadConfiguration() }() + go func() { + defer wg.Done() + _, _, _ = rt.MutateConfig(context.Background(), funnelActor(), func(d *config.Config) (ChangeHint, error) { + return ChangeHint{}, nil + }, TokenRewrite{}) + }() + } + wg.Wait() + }() + select { + case <-done: + case <-time.After(120 * time.Second): + t.Fatal("deadlock between refresh and config commits") + } +} diff --git a/internal/runtime/oauth_login_service.go b/internal/runtime/oauth_login_service.go index 0216b8bff..6115d6cab 100644 --- a/internal/runtime/oauth_login_service.go +++ b/internal/runtime/oauth_login_service.go @@ -102,6 +102,8 @@ type OAuthLoginService struct { testHookApproveAfterStore func() testHookApproveFinalising func() testHookBeforeCommit func() + testHookBeforeRotateLock func() + testHookInRotate func() everUsed bool // positive results only everMu sync.Mutex diff --git a/internal/runtime/oauth_login_tokens.go b/internal/runtime/oauth_login_tokens.go index 89bdd0fdb..50857cf1f 100644 --- a/internal/runtime/oauth_login_tokens.go +++ b/internal/runtime/oauth_login_tokens.go @@ -65,12 +65,9 @@ func (s *OAuthLoginService) Refresh(in TokenInput) (TokenResult, *TokenError) { s.logger.Error("browser login: cannot mint tokens", zap.Error(err)) return TokenResult{}, errTokenServer } - now := s.now().UTC() - outcome, after, err := s.store.RotateOAuthRefresh(grantID, mcplogin.HashSecret(key, mcplogin.KindRefresh, secret), - ts.refreshHash, ts.refreshPrefix, ts.accessHash, now, OAuthAccessTokenTTL, OAuthRefreshTokenTTL) - if err != nil { - s.logger.Error("browser login: refresh rotation failed", zap.Error(err)) - return TokenResult{}, errTokenServer + outcome, after, rerr := s.rotateFenced(grantID, mcplogin.HashSecret(key, mcplogin.KindRefresh, secret), ts) + if rerr != nil { + return TokenResult{}, rerr } switch outcome { case storage.RefreshRotated: From dc01d1a564794eb6b008bdc245a2c3179de43085 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 00:44:28 +0200 Subject: [PATCH 16/42] feat(oauth): browser-login endpoints and access-token auth (Spec 132 PR-1e) Public OAuth endpoints behind the three-state gate (metadata, register, authorize, token), the /mcp/oauth[/] resource chain that authenticates mcp_oat_ tokens on every request, the mcp_oat_ refusal on the classic MCP routes, admin REST for sign-in requests, per-login and API-key revoke, credentials[] on client payloads, and the oauth credential kind on activity rows. Related #1971 --- docs/api/rest-api.md | 28 ++ .../httpapi/binding_guard_coverage_test.go | 18 +- internal/httpapi/clients.go | 10 + internal/httpapi/clients_logins.go | 155 +++++++ internal/httpapi/clients_routes.go | 5 + internal/httpapi/oauth_login.go | 325 +++++++++++++ internal/httpapi/oauth_login_test.go | 355 ++++++++++++++ .../scope_route_clients_personal_test.go | 12 +- .../scope_route_clients_server_test.go | 6 +- internal/httpapi/server.go | 8 + internal/runtime/activity_attribution.go | 10 +- .../activity_attribution_grant_test.go | 18 + internal/runtime/oauth_login_consent.go | 6 + internal/server/mcp.go | 7 + internal/server/oauth_login_auth_test.go | 179 ++++++++ .../server/oauth_login_default_off_test.go | 17 +- .../server/oauth_login_flow_helpers_test.go | 173 +++++++ internal/server/oauth_login_flow_test.go | 171 +++++++ internal/server/oauth_login_gate_on_test.go | 37 +- internal/server/oauth_login_http.go | 344 ++++++++++++++ internal/server/oauth_login_http_test.go | 299 ++++++++++++ internal/server/oauth_login_routes.go | 33 +- internal/server/oauth_login_toggle_test.go | 110 +++++ internal/server/server.go | 39 +- oas/docs.go | 4 +- oas/swagger.yaml | 432 ++++++++++++++++++ 26 files changed, 2736 insertions(+), 65 deletions(-) create mode 100644 internal/httpapi/clients_logins.go create mode 100644 internal/httpapi/oauth_login.go create mode 100644 internal/httpapi/oauth_login_test.go create mode 100644 internal/server/oauth_login_auth_test.go create mode 100644 internal/server/oauth_login_flow_helpers_test.go create mode 100644 internal/server/oauth_login_flow_test.go create mode 100644 internal/server/oauth_login_http.go create mode 100644 internal/server/oauth_login_http_test.go create mode 100644 internal/server/oauth_login_toggle_test.go diff --git a/docs/api/rest-api.md b/docs/api/rest-api.md index aad948a33..6c8f59c20 100644 --- a/docs/api/rest-api.md +++ b/docs/api/rest-api.md @@ -1687,6 +1687,34 @@ profile, anonymous is required`, `400 use client= for a client credential` (a `client-` token name), `400 access/explain covers upstream tools (server:tool) only`, `404` for an unknown client, token or profile. +### Browser login for MCP clients (personal edition, opt-in) + +Off by default (`mcp_oauth_enabled`). With it off and never used none of this +exists and every payload is unchanged. All routes are administrator-only (an +agent token or a client credential gets `403`); with the feature off the +sign-in request routes answer `404` with `code: feature_disabled`. Full +reference: the Spec 132 contracts. + +- `GET /api/v1/oauth/authorizations`, `GET /api/v1/oauth/authorizations/{id}`: + pending sign-in requests and the data the consent view needs. One uniform `404` + for an unknown, expired, decided or cancelled id. +- `POST /api/v1/oauth/authorizations/{id}/preview`: read-only verdict for a + proposed client, profile and mode. `POST .../approve` and `POST .../deny` answer + `{redirect_url}`; approve refuses with `409 already_decided`, `409 binding_changed`, + `409 binding_bypassable_without_auth`, `422 profile_required`, `client_fixed`, + `identity_exists`, `reserved_identity` and `404 profile_not_found`. +- `GET /api/v1/clients` and `GET /api/v1/clients/{client}` gain `credentials[]` + (the API key and each browser login: `kind`, `prefix`, `grant_id`, `state`, + times, `reported_name`, `redirect_host`, `observed_name`, `name_mismatch`) and + `browser_login_disabled` once browser login was used. +- `DELETE /api/v1/clients/{client}/logins/{grant_id}` revokes one login (also + while the feature is off after use); `DELETE /api/v1/clients/{client}/api-key` + revokes the API key alone. + +The public OAuth endpoints (`/oauth/register`, `/oauth/authorize`, +`/oauth/token`, `/.well-known/oauth-*`, `/mcp/oauth[/]`) are loopback-only +and are not part of the `/api/v1` API. + ### Tokens `GET /api/v1/tokens` rows add `kind` (`agent` or `client`), `client_id`, diff --git a/internal/httpapi/binding_guard_coverage_test.go b/internal/httpapi/binding_guard_coverage_test.go index 855de781c..ce88f9b0a 100644 --- a/internal/httpapi/binding_guard_coverage_test.go +++ b/internal/httpapi/binding_guard_coverage_test.go @@ -51,14 +51,16 @@ var guardedRoutes = map[string]string{ // exemptRoutes: why each cannot change a binding's reach. var exemptRoutes = map[string]string{ - "POST /api/v1/clients/{client}/rotate": "keeps the binding; only swaps the secret", - "POST /api/v1/clients/{client}/rotate/finalize": "promotes a pending secret; the binding is untouched", - "DELETE /api/v1/clients/{client}": "revokes a credential: a binding can only disappear", - "DELETE /api/v1/connect/{client}": "removes a config entry; never grants", - "POST /api/v1/connect/{client}/undo": "restores the previous entry and only revokes a credential the restored config no longer holds", - "POST /api/v1/profiles/try": "nothing is written: a draft is searched, not stored", - "PUT /api/v1/profiles/active": "a UI default only; never enforcement (a live session's selection and every credential's binding are separate)", - "POST /api/v1/config/validate": "validation only; nothing is written", + "POST /api/v1/clients/{client}/rotate": "keeps the binding; only swaps the secret", + "POST /api/v1/clients/{client}/rotate/finalize": "promotes a pending secret; the binding is untouched", + "DELETE /api/v1/clients/{client}": "revokes a credential: a binding can only disappear", + "DELETE /api/v1/clients/{client}/api-key": "revokes the API key alone: the browser logins and the binding stay (Spec 132)", + "DELETE /api/v1/clients/{client}/logins/{grant_id}": "revokes one browser login: a login can only disappear (Spec 132)", + "DELETE /api/v1/connect/{client}": "removes a config entry; never grants", + "POST /api/v1/connect/{client}/undo": "restores the previous entry and only revokes a credential the restored config no longer holds", + "POST /api/v1/profiles/try": "nothing is written: a draft is searched, not stored", + "PUT /api/v1/profiles/active": "a UI default only; never enforcement (a live session's selection and every credential's binding are separate)", + "POST /api/v1/config/validate": "validation only; nothing is written", } func inGuardedFamily(route string) bool { diff --git a/internal/httpapi/clients.go b/internal/httpapi/clients.go index d1c42566c..74fa92e9d 100644 --- a/internal/httpapi/clients.go +++ b/internal/httpapi/clients.go @@ -69,6 +69,12 @@ type clientPresence struct { Lease bool `json:"lease,omitempty"` ProfileState string `json:"profile_state,omitempty"` + // Spec 132: the client's credentials (API key and browser logins) and + // whether browser login is off right now. Both exist only once browser + // login was used on this install; until then a row is exactly what it was. + Credentials []ClientCredential `json:"credentials,omitempty"` + BrowserLoginDisabled *bool `json:"browser_login_disabled,omitempty"` + // resolvedCredential is the classification of the on-demand config read of a // detail request; never serialised. resolvedCredential profile.CredentialState @@ -271,6 +277,10 @@ func (s *Server) clientRows(ctx context.Context, withSessions bool, detailID str } rows = s.decorateClientRows(rows, records, pctx, stats, cfg, now, withSessions, detailID) + rows, err = s.decorateBrowserLogins(rows, cfg) + if err != nil { + return nil, nil, err + } var warnings []internalRuntime.Warning if s.clientsService != nil { diff --git a/internal/httpapi/clients_logins.go b/internal/httpapi/clients_logins.go new file mode 100644 index 000000000..626fe5d29 --- /dev/null +++ b/internal/httpapi/clients_logins.go @@ -0,0 +1,155 @@ +//go:build !server + +package httpapi + +import ( + "sort" + "time" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "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/profile" + internalRuntime "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" +) + +// ClientCredential is one credential of a client in the Clients payloads +// (Spec 132, contracts/rest-admin.md): its API key or one browser login. A +// secret, a hash or a token never appears here, only the display prefix. +type ClientCredential struct { + // Kind is api_key or browser_login. + Kind string `json:"kind"` + Prefix string `json:"prefix,omitempty"` + // GrantID names a browser login. + GrantID string `json:"grant_id,omitempty"` + // State is active|expired|revoked for an API key and active|lapsed|revoked + // for a login. + State string `json:"state"` + ExpiresAt *time.Time `json:"expires_at,omitempty"` + ApprovedAt *time.Time `json:"approved_at,omitempty"` + LastUsedAt *time.Time `json:"last_used_at,omitempty"` + ReportedName string `json:"reported_name,omitempty"` + RedirectHost string `json:"redirect_host,omitempty"` + // ObservedName is the name the client sent at initialize (advisory). + ObservedName string `json:"observed_name,omitempty"` + NameMismatch *bool `json:"name_mismatch,omitempty"` +} + +func clientCredentials(in []internalRuntime.ClientCredentialEntry) []ClientCredential { + if in == nil { + return nil + } + out := make([]ClientCredential, 0, len(in)) + for i := range in { + e := &in[i] + out = append(out, ClientCredential{ + Kind: e.Kind, Prefix: e.Prefix, GrantID: e.GrantID, State: e.State, ExpiresAt: e.ExpiresAt, + ApprovedAt: e.ApprovedAt, LastUsedAt: e.LastUsedAt, ReportedName: e.ReportedName, + RedirectHost: e.RedirectHost, ObservedName: e.ObservedName, NameMismatch: e.NameMismatch, + }) + } + return out +} + +// decorateBrowserLogins adds the Spec 132 credentials list and +// browser_login_disabled to the client rows, and one row for every client that +// has browser logins but neither a registry entry nor an API-key record. It is +// a no-op until browser login was used on this install (the service returns +// views without credentials then), so a never-used install keeps exactly its +// previous payload. +func (s *Server) decorateBrowserLogins(rows []clientPresence, cfg *config.Config) ([]clientPresence, error) { + if s.clientsService == nil { + return rows, nil + } + views, err := s.clientsService.List() + if err != nil { + return nil, err + } + used := false + for i := range views { + if views[i].Credentials != nil { + used = true + break + } + } + if !used { + return rows, nil + } + titleOf := func(name string) string { + if cfg != nil { + for i := range cfg.Profiles { + if cfg.Profiles[i].Name == name { + return cfg.Profiles[i].Title + } + } + } + return "" + } + profileMissing := func(name string) bool { + if name == "" || cfg == nil { + return false + } + for i := range cfg.Profiles { + if cfg.Profiles[i].Name == name { + return false + } + } + return true + } + source := func(mode string) string { + if mode == auth.ProfileModeLocked { + return string(profile.SourcePin) + } + return string(profile.SourceBinding) + } + + seen := map[string]bool{} + for i := range rows { + seen[rows[i].ID] = true + } + ids := make([]string, 0, len(views)) + byID := map[string]int{} + for i := range views { + if views[i].Credentials == nil { + continue + } + byID[views[i].ID] = i + ids = append(ids, views[i].ID) + } + sort.Strings(ids) + + for i := range rows { + vi, ok := byID[rows[i].ID] + if !ok { + continue + } + v := &views[vi] + rows[i].Credentials = clientCredentials(v.Credentials) + rows[i].BrowserLoginDisabled = v.BrowserLoginDisabled + if rows[i].TokenName == "" { + // No API-key record: the binding the row shows is the browser login's. + rows[i].Profile, rows[i].ProfileMode = v.Profile, v.Mode + rows[i].ProfileTitle = titleOf(v.Profile) + rows[i].ProfileMissing = profileMissing(v.Profile) + rows[i].ProfileSource = source(v.Mode) + } + } + for _, id := range ids { + if seen[id] { + continue + } + v := &views[byID[id]] + name := v.DisplayName + if name == "" { + name = id + } + rows = append(rows, clientPresence{ + ID: id, DisplayName: name, Kind: "custom", State: contracts.ClientPresenceOther, + CredentialState: profile.CredentialStateNone, + Profile: v.Profile, ProfileMode: v.Mode, ProfileTitle: titleOf(v.Profile), + ProfileMissing: profileMissing(v.Profile), ProfileSource: source(v.Mode), + Credentials: clientCredentials(v.Credentials), BrowserLoginDisabled: v.BrowserLoginDisabled, + }) + } + return rows, nil +} diff --git a/internal/httpapi/clients_routes.go b/internal/httpapi/clients_routes.go index 86a99411a..45fc0536e 100644 --- a/internal/httpapi/clients_routes.go +++ b/internal/httpapi/clients_routes.go @@ -33,4 +33,9 @@ func (s *Server) registerClientRoutes(r chi.Router) { r.Post("/clients/{client}/rotate", admin(s.handleRotateClient)) r.Post("/clients/{client}/rotate/finalize", admin(s.handleFinalizeClientRotation)) r.Delete("/clients/{client}", admin(s.handleForgetClient)) + // exempt: a revoke only removes access (Spec 132); both work while browser + // login is on and while it is off after use. + r.Delete("/clients/{client}/logins/{grant_id}", admin(s.handleRevokeClientLogin)) + r.Delete("/clients/{client}/api-key", admin(s.handleRevokeClientAPIKey)) + s.registerOAuthLoginAdminRoutes(r) } diff --git a/internal/httpapi/oauth_login.go b/internal/httpapi/oauth_login.go new file mode 100644 index 000000000..0a2454252 --- /dev/null +++ b/internal/httpapi/oauth_login.go @@ -0,0 +1,325 @@ +//go:build !server + +package httpapi + +import ( + "encoding/json" + "errors" + "net/http" + + "github.com/go-chi/chi/v5" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" + internalRuntime "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" +) + +// Spec 132: the administrator surface of the browser login for MCP clients +// (contracts/rest-admin.md). Every route is administrator-only: an agent token +// or a client credential is refused with 403 before anything reaches the +// runtime service. The decisions (what a choice means, what the guard says, +// what the redirect carries) are the service's; the handlers decode, call it +// and map its typed refusals. + +// maxOAuthApprovalBody bounds an approve / preview body. +const maxOAuthApprovalBody = 16 << 10 + +// registerOAuthLoginAdminRoutes mounts the sign-in request routes. +func (s *Server) registerOAuthLoginAdminRoutes(r chi.Router) { + adminRead := s.requireAdminReadMiddleware("Admin credentials required to read sign-in requests") + admin := func(h http.HandlerFunc) http.HandlerFunc { return s.requireServerOp(auth.ServerOpConfigWrite, h) } + r.With(adminRead).Get("/oauth/authorizations", s.handleListOAuthAuthorizations) + r.With(adminRead).Get("/oauth/authorizations/{id}", s.handleGetOAuthAuthorization) + // exempt: a preview is read-only and writes nothing; approve runs the + // FR-008a guard (OAuthLoginService.Approve) before it records the decision. + r.Post("/oauth/authorizations/{id}/preview", admin(s.handlePreviewOAuthAuthorization)) + r.Post("/oauth/authorizations/{id}/approve", admin(s.handleApproveOAuthAuthorization)) // guarded: OAuthLoginService.Approve + r.Post("/oauth/authorizations/{id}/deny", admin(s.handleDenyOAuthAuthorization)) +} + +// writeOAuthLoginError answers 404 feature_disabled (and ok=false) while +// browser login is off or no service is configured. +func (s *Server) oauthLoginEnabledOrWrite(w http.ResponseWriter, r *http.Request) (*internalRuntime.OAuthLoginService, bool) { + svc := s.oauthLoginService + if svc == nil { + s.writeError(w, r, http.StatusServiceUnavailable, "browser login service not available") + return nil, false + } + if !svc.Enabled() { + s.writeClientBindingError(w, r, http.StatusNotFound, "feature_disabled", "", "browser login is turned off") + return nil, false + } + return svc, true +} + +// writeOAuthLoginFailure maps a service refusal to its wire shape: the guard +// refusal keeps its body (bindings and fixes), the typed refusals their code +// and status, everything else a generic 500. +func (s *Server) writeOAuthLoginFailure(w http.ResponseWriter, r *http.Request, err error) { + var guard *internalRuntime.BindingGuardError + if errors.As(err, &guard) { + if s.writeProfilesError(w, r, err) { + return + } + } + if code, status, ok := internalRuntime.OAuthErrorStatus(err); ok { + s.writeClientBindingError(w, r, status, code, "", err.Error()) + return + } + s.logger.Errorw("browser login operation failed", "error", err) + s.writeError(w, r, http.StatusInternalServerError, "the sign-in operation failed") +} + +// handleListOAuthAuthorizations godoc +// @Summary List pending sign-in requests +// @Description Pending browser-login requests, newest first: id, a sanitised client label and the times. Used by the tray and Home. 404 feature_disabled while browser login is off. Administrator only. +// @Tags clients +// @Produce json +// @Security ApiKeyAuth +// @Security ApiKeyQuery +// @Success 200 {object} contracts.APIResponse "Pending requests" +// @Failure 403 {object} contracts.ErrorResponse "Administrator credentials required" +// @Failure 404 {object} ClientBindingErrorResponse "feature_disabled" +// @Router /api/v1/oauth/authorizations [get] +func (s *Server) handleListOAuthAuthorizations(w http.ResponseWriter, r *http.Request) { + svc, ok := s.oauthLoginEnabledOrWrite(w, r) + if !ok { + return + } + s.writeSuccess(w, svc.ListPending()) +} + +// handleGetOAuthAuthorization godoc +// @Summary Read one sign-in request +// @Description Everything the consent view needs: the reported (unverified) name, the redirect URI, the resource, how the address fixes the client, the profiles, whether a profile must be chosen, the previous login of the same registration and, for a fixed client that has a binding, the guard verdict. One uniform 404 for an unknown, expired, decided or cancelled id. Administrator only. +// @Tags clients +// @Produce json +// @Security ApiKeyAuth +// @Security ApiKeyQuery +// @Param id path string true "Request id" +// @Success 200 {object} contracts.APIResponse "The request" +// @Failure 403 {object} contracts.ErrorResponse "Administrator credentials required" +// @Failure 404 {object} ClientBindingErrorResponse "request_not_found or feature_disabled" +// @Router /api/v1/oauth/authorizations/{id} [get] +func (s *Server) handleGetOAuthAuthorization(w http.ResponseWriter, r *http.Request) { + svc, ok := s.oauthLoginEnabledOrWrite(w, r) + if !ok { + return + } + view, err := svc.Describe(r.Context(), chi.URLParam(r, "id")) + if err != nil { + s.writeOAuthLoginFailure(w, r, err) + return + } + s.writeSuccess(w, view) +} + +// OAuthNewClient is a client an approval creates (generic address). +type OAuthNewClient struct { + ID string `json:"id"` + DisplayName string `json:"display_name,omitempty"` +} + +// OAuthClientChoice is the client of an approval: an existing id, or a new one. +type OAuthClientChoice struct { + ID string `json:"id,omitempty"` + New *OAuthNewClient `json:"new,omitempty"` +} + +// OAuthApprovalBody documents the body of preview and approve (it is decoded +// into runtime.ApprovalChoice, which has the same wire shape). profile "" means +// All servers; it is ignored when the client already has a binding, which the +// request then names with binding_revision. +type OAuthApprovalBody struct { + Client OAuthClientChoice `json:"client"` + Profile *string `json:"profile,omitempty"` + Mode string `json:"mode,omitempty"` + BindingRevision string `json:"binding_revision,omitempty"` + ReplaceGrant string `json:"replace_grant,omitempty"` +} + +func (s *Server) decodeOAuthApproval(w http.ResponseWriter, r *http.Request) (internalRuntime.ApprovalChoice, bool) { + var choice internalRuntime.ApprovalChoice + r.Body = http.MaxBytesReader(w, r.Body, maxOAuthApprovalBody) + if err := json.NewDecoder(r.Body).Decode(&choice); err != nil { + s.writeClientBindingError(w, r, http.StatusBadRequest, "", "body", "the body must be a JSON object") + return choice, false + } + return choice, true +} + +// handlePreviewOAuthAuthorization godoc +// @Summary Preview a sign-in decision +// @Description Read-only: for a proposed client (existing or new), profile and mode, returns whether the choice is complete, the access sentence and the binding guard's verdict with its fixes. Writes nothing. The same 422 codes as approve for an invalid choice. Administrator only. +// @Tags clients +// @Accept json +// @Produce json +// @Security ApiKeyAuth +// @Security ApiKeyQuery +// @Param id path string true "Request id" +// @Param body body OAuthApprovalBody true "client, profile, mode" +// @Success 200 {object} contracts.APIResponse "The preview" +// @Failure 403 {object} contracts.ErrorResponse "Administrator credentials required" +// @Failure 404 {object} ClientBindingErrorResponse "request_not_found, profile_not_found or feature_disabled" +// @Failure 422 {object} ClientBindingErrorResponse "client_fixed, identity_exists, reserved_identity" +// @Router /api/v1/oauth/authorizations/{id}/preview [post] +func (s *Server) handlePreviewOAuthAuthorization(w http.ResponseWriter, r *http.Request) { + svc, ok := s.oauthLoginEnabledOrWrite(w, r) + if !ok { + return + } + choice, ok := s.decodeOAuthApproval(w, r) + if !ok { + return + } + view, err := svc.Preview(r.Context(), chi.URLParam(r, "id"), choice) + if err != nil { + s.writeOAuthLoginFailure(w, r, err) + return + } + s.writeSuccess(w, view) +} + +// OAuthDecisionResponse is the data of approve and deny: where the browser goes +// next (the stored redirect URI with the code, or with error=access_denied). +type OAuthDecisionResponse struct { + RedirectURL string `json:"redirect_url"` +} + +// handleApproveOAuthAuthorization godoc +// @Summary Approve a sign-in request +// @Description Records the decision and issues the code; the login itself is stored when the client exchanges the code. 409 already_decided, 409 binding_changed (the binding differs from binding_revision), 409 binding_bypassable_without_auth (with the guard's fixes), 422 profile_required, client_fixed, identity_exists, reserved_identity, 404 profile_not_found. Writes an approve record naming the administrator. Administrator only. +// @Tags clients +// @Accept json +// @Produce json +// @Security ApiKeyAuth +// @Security ApiKeyQuery +// @Param id path string true "Request id" +// @Param body body OAuthApprovalBody true "client, profile, mode, binding_revision, replace_grant" +// @Success 200 {object} contracts.APIResponse{data=OAuthDecisionResponse} "Where the page navigates" +// @Failure 403 {object} contracts.ErrorResponse "Administrator credentials required" +// @Failure 404 {object} ClientBindingErrorResponse "request_not_found, profile_not_found or feature_disabled" +// @Failure 409 {object} ClientBindingErrorResponse "already_decided, binding_changed or binding_bypassable_without_auth" +// @Failure 422 {object} ClientBindingErrorResponse "profile_required, client_fixed, identity_exists, reserved_identity" +// @Router /api/v1/oauth/authorizations/{id}/approve [post] +func (s *Server) handleApproveOAuthAuthorization(w http.ResponseWriter, r *http.Request) { + svc, ok := s.oauthLoginEnabledOrWrite(w, r) + if !ok { + return + } + choice, ok := s.decodeOAuthApproval(w, r) + if !ok { + return + } + redirect, err := svc.Approve(r.Context(), chi.URLParam(r, "id"), choice) + if err != nil { + s.writeOAuthLoginFailure(w, r, err) + return + } + s.writeSuccess(w, OAuthDecisionResponse{RedirectURL: redirect}) +} + +// handleDenyOAuthAuthorization godoc +// @Summary Deny a sign-in request +// @Description The redirect carries error=access_denied. 409 already_decided. Writes a deny record naming the administrator. Administrator only. +// @Tags clients +// @Produce json +// @Security ApiKeyAuth +// @Security ApiKeyQuery +// @Param id path string true "Request id" +// @Success 200 {object} contracts.APIResponse{data=OAuthDecisionResponse} "Where the page navigates" +// @Failure 403 {object} contracts.ErrorResponse "Administrator credentials required" +// @Failure 404 {object} ClientBindingErrorResponse "request_not_found or feature_disabled" +// @Failure 409 {object} ClientBindingErrorResponse "already_decided" +// @Router /api/v1/oauth/authorizations/{id}/deny [post] +func (s *Server) handleDenyOAuthAuthorization(w http.ResponseWriter, r *http.Request) { + svc, ok := s.oauthLoginEnabledOrWrite(w, r) + if !ok { + return + } + redirect, err := svc.Deny(r.Context(), chi.URLParam(r, "id")) + if err != nil { + s.writeOAuthLoginFailure(w, r, err) + return + } + s.writeSuccess(w, OAuthDecisionResponse{RedirectURL: redirect}) +} + +// --- logins on clients (T042) ---------------------------------------------------- + +// RevokeCredentialResponse is the data of the per-credential revokes. +type RevokeCredentialResponse struct { + Changed bool `json:"changed"` +} + +// handleRevokeClientLogin godoc +// @Summary Revoke one browser login of a client +// @Description Revokes the login (reason admin): its access token stops authenticating on the next request, live sessions are told to re-list, and a revoke record names the administrator. Works while browser login is on and while it is off after use. An already revoked login answers changed:false; an unknown login (or one of another client) is 404. Administrator only. +// @Tags clients +// @Produce json +// @Security ApiKeyAuth +// @Security ApiKeyQuery +// @Param client path string true "Client id" +// @Param grant_id path string true "Login id" +// @Success 200 {object} contracts.APIResponse{data=RevokeCredentialResponse} "Whether the login changed" +// @Failure 403 {object} contracts.ErrorResponse "Administrator credentials required" +// @Failure 404 {object} contracts.ErrorResponse "login not found" +// @Router /api/v1/clients/{client}/logins/{grant_id} [delete] +func (s *Server) handleRevokeClientLogin(w http.ResponseWriter, r *http.Request) { + svc := s.oauthLoginService + if svc == nil { + s.writeError(w, r, http.StatusServiceUnavailable, "browser login service not available") + return + } + changed, err := svc.RevokeGrant(r.Context(), chi.URLParam(r, "client"), chi.URLParam(r, "grant_id")) + switch { + case errors.Is(err, internalRuntime.ErrOAuthGrantNotFound): + s.writeError(w, r, http.StatusNotFound, "login not found") + case err != nil: + s.logger.Errorw("revoking a browser login failed", "error", err) + s.writeError(w, r, http.StatusInternalServerError, "the revoke failed") + default: + s.writeSuccess(w, RevokeCredentialResponse{Changed: changed}) + } +} + +// handleRevokeClientAPIKey godoc +// @Summary Revoke a client's API key only +// @Description Revokes the client's mcp_cli_ credential alone: its browser logins and its binding stay. 404 no_client_credential when the client has no active API key. Writes a revoke record. Administrator only. +// @Tags clients +// @Produce json +// @Security ApiKeyAuth +// @Security ApiKeyQuery +// @Param client path string true "Client id" +// @Success 200 {object} contracts.APIResponse{data=RevokeCredentialResponse} "The key was revoked" +// @Failure 400 {object} ClientBindingErrorResponse "Invalid client id" +// @Failure 403 {object} contracts.ErrorResponse "Administrator credentials required" +// @Failure 404 {object} ClientBindingErrorResponse "no_client_credential" +// @Router /api/v1/clients/{client}/api-key [delete] +func (s *Server) handleRevokeClientAPIKey(w http.ResponseWriter, r *http.Request) { + svc := s.clientsService + if svc == nil { + s.writeError(w, r, http.StatusServiceUnavailable, "client service not available") + return + } + clientID := chi.URLParam(r, "client") + if !auth.ValidClientID(clientID) { + s.writeClientBindingError(w, r, http.StatusBadRequest, "", "id", "invalid client id") + return + } + if _, err := svc.RevokeAPIKey(r.Context(), actorFromRequest(r), clientID); err != nil { + var none *internalRuntime.NoClientCredentialError + if errors.As(err, &none) { + s.writeClientBindingError(w, r, http.StatusNotFound, profile.ErrorCodeNoClientCredential, "", "the client has no API key") + return + } + s.writeClientBindingFailure(w, r, err) + return + } + s.writeSuccess(w, RevokeCredentialResponse{Changed: true}) +} + +// contracts is referenced by the swagger annotations above (swag resolves the +// type through this file's imports). +var _ contracts.APIResponse diff --git a/internal/httpapi/oauth_login_test.go b/internal/httpapi/oauth_login_test.go new file mode 100644 index 000000000..7fc7f88b5 --- /dev/null +++ b/internal/httpapi/oauth_login_test.go @@ -0,0 +1,355 @@ +//go:build !server + +package httpapi + +import ( + "bytes" + "crypto/sha256" + "encoding/base64" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + internalRuntime "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" +) + +const oauthTestOrigin = "http://127.0.0.1:8080" +const oauthTestRedirect = "http://127.0.0.1:54321/callback" + +type oauthHarness struct { + *bindingHarness + svc *internalRuntime.OAuthLoginService +} + +func newOAuthHarness(t *testing.T, on bool) *oauthHarness { + t.Helper() + h := newBindingHarness(t, internalRuntime.ConservativeBindingGuard{}) + h.cfg.MCPOAuthEnabled = on + svc := internalRuntime.NewOAuthLoginService(internalRuntime.OAuthLoginDeps{ + Store: h.sm, + HMACKey: func() ([]byte, error) { return h.key, nil }, + Config: func() *config.Config { return h.cfg }, + Guard: func() internalRuntime.BindingGuard { return internalRuntime.ConservativeBindingGuard{} }, + Activity: h.sm.SaveActivity, + }) + h.srv.SetOAuthLoginService(svc) + h.svc.SetLoginCanceler(func(id string) { svc.CancelForClient(id) }) + return &oauthHarness{bindingHarness: h, svc: svc} +} + +func (h *oauthHarness) call(method, path, body, key string) *httptest.ResponseRecorder { + h.t.Helper() + var rdr *bytes.Buffer + if body != "" { + rdr = bytes.NewBufferString(body) + } else { + rdr = &bytes.Buffer{} + } + req := httptest.NewRequest(method, path, rdr) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-API-Key", key) + w := httptest.NewRecorder() + h.srv.ServeHTTP(w, req) + return w +} + +// pending registers a client and starts an authorization for the per-client +// address of client ("" = the generic address); it returns the request id plus +// what the token exchange needs. +func (h *oauthHarness) pending(client string) (id, regID, verifier, resource string) { + h.t.Helper() + reg, rerr, err := h.svc.Register(mcplogin.RegistrationRequest{RedirectURIs: []string{oauthTestRedirect}, ClientName: "Cursor IDE"}) + require.NoError(h.t, err) + require.Nil(h.t, rerr) + regID, _ = reg["client_id"].(string) + verifier = strings.Repeat("v", 43) + sum := sha256.Sum256([]byte(verifier)) + resource = oauthTestOrigin + mcplogin.ResourcePath(client) + id, aerr := h.svc.BeginAuthorization(internalRuntime.AuthorizeInput{ + Origin: oauthTestOrigin, ClientID: regID, RedirectURI: oauthTestRedirect, State: "st", + CodeChallenge: base64.RawURLEncoding.EncodeToString(sum[:]), Method: "S256", Resource: resource, ResponseType: "code", + }) + require.Nil(h.t, aerr) + return id, regID, verifier, resource +} + +func dataOf(t *testing.T, w *httptest.ResponseRecorder) map[string]interface{} { + t.Helper() + d, _ := decodeBody(t, w)["data"].(map[string]interface{}) + return d +} + +func codeOf(t *testing.T, w *httptest.ResponseRecorder) string { + t.Helper() + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + u, err := url.Parse(dataOf(t, w)["redirect_url"].(string)) + require.NoError(t, err) + require.NotEmpty(t, u.Query().Get("code")) + return u.Query().Get("code") +} + +// T040: administrators only; agent tokens and client credentials are 403 before +// anything reaches the service. +func TestOAuthLoginREST_AdministratorOnly(t *testing.T) { + h := newOAuthHarness(t, true) + secret := h.mint("cursor", "ro") + id, _, _, _ := h.pending("cursor") + for _, rt := range []struct{ method, path, body string }{ + {http.MethodGet, "/api/v1/oauth/authorizations", ""}, + {http.MethodGet, "/api/v1/oauth/authorizations/" + id, ""}, + {http.MethodPost, "/api/v1/oauth/authorizations/" + id + "/preview", `{"client":{"id":"cursor"}}`}, + {http.MethodPost, "/api/v1/oauth/authorizations/" + id + "/approve", `{"client":{"id":"cursor"}}`}, + {http.MethodPost, "/api/v1/oauth/authorizations/" + id + "/deny", ``}, + {http.MethodDelete, "/api/v1/clients/cursor/logins/whatever", ``}, + {http.MethodDelete, "/api/v1/clients/cursor/api-key", ``}, + } { + w := h.call(rt.method, rt.path, rt.body, secret) + assert.Equal(t, http.StatusForbidden, w.Code, rt.method+" "+rt.path) + } + // Nothing was decided. + assert.Len(t, h.svc.ListPending(), 1) +} + +func TestOAuthLoginREST_FeatureDisabled404(t *testing.T) { + h := newOAuthHarness(t, false) + for _, rt := range []struct{ method, path, body string }{ + {http.MethodGet, "/api/v1/oauth/authorizations", ""}, + {http.MethodGet, "/api/v1/oauth/authorizations/x", ""}, + {http.MethodPost, "/api/v1/oauth/authorizations/x/preview", `{}`}, + {http.MethodPost, "/api/v1/oauth/authorizations/x/approve", `{}`}, + {http.MethodPost, "/api/v1/oauth/authorizations/x/deny", ``}, + } { + w := h.call(rt.method, rt.path, rt.body, bindingAdminKey) + assert.Equal(t, http.StatusNotFound, w.Code, rt.path) + assert.Equal(t, "feature_disabled", decodeBody(t, w)["code"], rt.path) + } +} + +// T040: list, read, preview, approve, deny with the contract's payloads and codes. +func TestOAuthLoginREST_RequestLifecycle(t *testing.T) { + h := newOAuthHarness(t, true) + id, regID, verifier, resource := h.pending("cursor") + + // list + w := h.call(http.MethodGet, "/api/v1/oauth/authorizations", "", bindingAdminKey) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + list := decodeBody(t, w)["data"].([]interface{}) + require.Len(t, list, 1) + row := list[0].(map[string]interface{}) + assert.Equal(t, id, row["id"]) + assert.NotEmpty(t, row["client_label"]) + assert.NotEmpty(t, row["expires_at"]) + + // read + w = h.call(http.MethodGet, "/api/v1/oauth/authorizations/"+id, "", bindingAdminKey) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + d := dataOf(t, w) + assert.Equal(t, "client", d["address_kind"]) + assert.Equal(t, resource, d["resource"]) + assert.Equal(t, oauthTestRedirect, d["redirect_uri"]) + assert.Equal(t, true, d["profile_required"], "profiles exist and cursor has no binding") + assert.Equal(t, "cursor", d["client"].(map[string]interface{})["id"]) + + // uniform 404 + w = h.call(http.MethodGet, "/api/v1/oauth/authorizations/nope", "", bindingAdminKey) + assert.Equal(t, http.StatusNotFound, w.Code) + + // preview: incomplete without a profile, complete with one; writes nothing + w = h.call(http.MethodPost, "/api/v1/oauth/authorizations/"+id+"/preview", `{"client":{"id":"cursor"}}`, bindingAdminKey) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + assert.Equal(t, false, dataOf(t, w)["complete"]) + w = h.call(http.MethodPost, "/api/v1/oauth/authorizations/"+id+"/preview", `{"client":{"id":"cursor"},"profile":"ro","mode":"locked"}`, bindingAdminKey) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + assert.Equal(t, true, dataOf(t, w)["complete"]) + assert.Len(t, h.svc.ListPending(), 1, "a preview decides nothing") + + // approve refusals + w = h.call(http.MethodPost, "/api/v1/oauth/authorizations/"+id+"/approve", `{"client":{"id":"cursor"}}`, bindingAdminKey) + assert.Equal(t, http.StatusUnprocessableEntity, w.Code) + assert.Equal(t, "profile_required", decodeBody(t, w)["code"]) + w = h.call(http.MethodPost, "/api/v1/oauth/authorizations/"+id+"/approve", `{"client":{"id":"windsurf"},"profile":"ro"}`, bindingAdminKey) + assert.Equal(t, http.StatusUnprocessableEntity, w.Code) + assert.Equal(t, "client_fixed", decodeBody(t, w)["code"]) + w = h.call(http.MethodPost, "/api/v1/oauth/authorizations/"+id+"/approve", `{"client":{"id":"cursor"},"profile":"nope"}`, bindingAdminKey) + assert.Equal(t, http.StatusNotFound, w.Code) + assert.Equal(t, "profile_not_found", decodeBody(t, w)["code"]) + w = h.call(http.MethodPost, "/api/v1/oauth/authorizations/"+id+"/approve", `not json`, bindingAdminKey) + assert.Equal(t, http.StatusBadRequest, w.Code) + + // approve + w = h.call(http.MethodPost, "/api/v1/oauth/authorizations/"+id+"/approve", `{"client":{"id":"cursor"},"profile":"ro","mode":"locked"}`, bindingAdminKey) + code := codeOf(t, w) + u, _ := url.Parse(dataOf(t, w)["redirect_url"].(string)) + assert.Equal(t, "st", u.Query().Get("state")) + assert.True(t, strings.HasPrefix(u.String(), oauthTestRedirect)) + + // decided once + w = h.call(http.MethodPost, "/api/v1/oauth/authorizations/"+id+"/approve", `{"client":{"id":"cursor"},"profile":"ro"}`, bindingAdminKey) + assert.Equal(t, http.StatusConflict, w.Code) + assert.Equal(t, "already_decided", decodeBody(t, w)["code"]) + w = h.call(http.MethodPost, "/api/v1/oauth/authorizations/"+id+"/deny", ``, bindingAdminKey) + assert.Equal(t, http.StatusConflict, w.Code) + + // the approval stores nothing until the exchange: the login does not exist yet + grants, err := h.svc.ListGrants("cursor") + require.NoError(t, err) + assert.Empty(t, grants) + _, terr := h.svc.Exchange(internalRuntime.TokenInput{Origin: oauthTestOrigin, Code: code, RedirectURI: oauthTestRedirect, ClientID: regID, CodeVerifier: verifier}) + require.Nil(t, terr) + + // deny a second request + id2, _, _, _ := h.pending("cursor") + w = h.call(http.MethodPost, "/api/v1/oauth/authorizations/"+id2+"/deny", ``, bindingAdminKey) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + u, _ = url.Parse(dataOf(t, w)["redirect_url"].(string)) + assert.Equal(t, "access_denied", u.Query().Get("error")) + assert.Equal(t, "st", u.Query().Get("state")) + assert.Empty(t, h.svc.ListPending()) +} + +// T040: a named pin with require_mcp_auth off is refused with the guard's body. +func TestOAuthLoginREST_ApproveGuardRefusal(t *testing.T) { + h := newOAuthHarness(t, true) + h.cfg.RequireMCPAuth = false + id, _, _, _ := h.pending("cursor") + w := h.call(http.MethodPost, "/api/v1/oauth/authorizations/"+id+"/approve", `{"client":{"id":"cursor"},"profile":"ro","mode":"locked"}`, bindingAdminKey) + require.Equal(t, http.StatusConflict, w.Code, w.Body.String()) + body := decodeBody(t, w) + assert.Equal(t, "binding_bypassable_without_auth", body["code"]) + assert.NotEmpty(t, body["fixes"]) + // Still pending: a refused approval decides nothing. + assert.Len(t, h.svc.ListPending(), 1) +} + +// T040: the generic address lets the administrator choose (existing or new). +func TestOAuthLoginREST_GenericAddress(t *testing.T) { + h := newOAuthHarness(t, true) + id, _, _, _ := h.pending("") + w := h.call(http.MethodGet, "/api/v1/oauth/authorizations/"+id, "", bindingAdminKey) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + d := dataOf(t, w) + assert.Equal(t, "generic", d["address_kind"]) + assert.NotContains(t, d, "client", "nothing is pre-selected") + assert.NotNil(t, d["suggested_new_client"]) + + w = h.call(http.MethodPost, "/api/v1/oauth/authorizations/"+id+"/approve", `{}`, bindingAdminKey) + assert.Equal(t, http.StatusUnprocessableEntity, w.Code) + assert.Equal(t, "client_required", decodeBody(t, w)["code"]) + w = h.call(http.MethodPost, "/api/v1/oauth/authorizations/"+id+"/approve", `{"client":{"new":{"id":"cursor"}},"profile":"ro"}`, bindingAdminKey) + assert.Equal(t, http.StatusUnprocessableEntity, w.Code) + assert.Equal(t, "reserved_identity", decodeBody(t, w)["code"], "a supported client's id cannot be taken by a new client") + w = h.call(http.MethodPost, "/api/v1/oauth/authorizations/"+id+"/approve", `{"client":{"new":{"id":"acme-agent","display_name":"Acme Agent"}},"profile":"ro","mode":"locked"}`, bindingAdminKey) + assert.Equal(t, http.StatusOK, w.Code, w.Body.String()) +} + +// T042: client payloads and the per-credential revokes. +func TestOAuthLoginREST_ClientCredentialsPayloadAndRevokes(t *testing.T) { + h := newOAuthHarness(t, true) + h.mint("cursor", "ro") + + // Never used: the payload is exactly today's, no new fields. + w := h.call(http.MethodGet, "/api/v1/clients?client=cursor", "", bindingAdminKey) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + raw := w.Body.String() + assert.NotContains(t, raw, "browser_login_disabled") + assert.NotContains(t, raw, `"credentials"`) + + // A login. + id, regID, verifier, _ := h.pending("cursor") + // cursor already has an API-key binding: the approval carries its revision. + w = h.call(http.MethodGet, "/api/v1/oauth/authorizations/"+id, "", bindingAdminKey) + rev := dataOf(t, w)["client"].(map[string]interface{})["binding"].(map[string]interface{})["revision"].(string) + w = h.call(http.MethodPost, "/api/v1/oauth/authorizations/"+id+"/approve", `{"client":{"id":"cursor"},"binding_revision":"`+rev+`"}`, bindingAdminKey) + code := codeOf(t, w) + _, terr := h.svc.Exchange(internalRuntime.TokenInput{Origin: oauthTestOrigin, Code: code, RedirectURI: oauthTestRedirect, ClientID: regID, CodeVerifier: verifier}) + require.Nil(t, terr) + + findRow := func(w *httptest.ResponseRecorder) map[string]interface{} { + for _, c := range dataOf(t, w)["clients"].([]interface{}) { + if m := c.(map[string]interface{}); m["id"] == "cursor" { + return m + } + } + t.Fatal("cursor row missing") + return nil + } + w = h.call(http.MethodGet, "/api/v1/clients", "", bindingAdminKey) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + row := findRow(w) + creds := row["credentials"].([]interface{}) + require.Len(t, creds, 2) + kinds := map[string]map[string]interface{}{} + for _, c := range creds { + m := c.(map[string]interface{}) + kinds[m["kind"].(string)] = m + } + require.Contains(t, kinds, "api_key") + login := kinds["browser_login"] + require.NotNil(t, login) + assert.Equal(t, "active", login["state"]) + assert.Equal(t, "127.0.0.1", login["redirect_host"]) + assert.Equal(t, "cursor ide", login["reported_name"]) + assert.Contains(t, login, "name_mismatch") + assert.Equal(t, false, row["browser_login_disabled"]) + assert.Len(t, login["prefix"], 12, "only the display prefix of a token appears in a client payload") + grantID := login["grant_id"].(string) + + // Off after use: logins are still listed, disabled is true, and a login can still be revoked. + h.cfg.MCPOAuthEnabled = false + w = h.call(http.MethodGet, "/api/v1/clients", "", bindingAdminKey) + row = findRow(w) + assert.Equal(t, true, row["browser_login_disabled"]) + assert.Len(t, row["credentials"].([]interface{}), 2) + + w = h.call(http.MethodDelete, "/api/v1/clients/cursor/logins/"+grantID, "", bindingAdminKey) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + assert.Equal(t, true, dataOf(t, w)["changed"]) + w = h.call(http.MethodDelete, "/api/v1/clients/cursor/logins/"+grantID, "", bindingAdminKey) + require.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, false, dataOf(t, w)["changed"], "already revoked") + w = h.call(http.MethodDelete, "/api/v1/clients/cursor/logins/unknown", "", bindingAdminKey) + assert.Equal(t, http.StatusNotFound, w.Code) + w = h.call(http.MethodDelete, "/api/v1/clients/windsurf/logins/"+grantID, "", bindingAdminKey) + assert.Equal(t, http.StatusNotFound, w.Code, "a login is addressed through its own client") + + // The API key alone: the binding and the (revoked) login records stay. + w = h.call(http.MethodDelete, "/api/v1/clients/cursor/api-key", "", bindingAdminKey) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + w = h.call(http.MethodDelete, "/api/v1/clients/cursor/api-key", "", bindingAdminKey) + assert.Equal(t, http.StatusNotFound, w.Code) + assert.Equal(t, "no_client_credential", decodeBody(t, w)["code"]) + w = h.call(http.MethodDelete, "/api/v1/clients/Bad!Id/api-key", "", bindingAdminKey) + assert.Equal(t, http.StatusBadRequest, w.Code) +} + +// T042: a client that has only browser logins gets a row. +func TestOAuthLoginREST_OAuthOnlyClientRow(t *testing.T) { + h := newOAuthHarness(t, true) + id, regID, verifier, _ := h.pending("") + w := h.call(http.MethodPost, "/api/v1/oauth/authorizations/"+id+"/approve", + `{"client":{"new":{"id":"acme-agent","display_name":"Acme Agent"}},"profile":"ro","mode":"locked"}`, bindingAdminKey) + code := codeOf(t, w) + _, terr := h.svc.Exchange(internalRuntime.TokenInput{Origin: oauthTestOrigin, Code: code, RedirectURI: oauthTestRedirect, ClientID: regID, CodeVerifier: verifier}) + require.Nil(t, terr) + + w = h.call(http.MethodGet, "/api/v1/clients", "", bindingAdminKey) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + var found map[string]interface{} + for _, c := range dataOf(t, w)["clients"].([]interface{}) { + if m := c.(map[string]interface{}); m["id"] == "acme-agent" { + found = m + } + } + require.NotNil(t, found, "an OAuth-only client appears in the Clients list") + assert.Equal(t, "Acme Agent", found["display_name"]) + assert.Equal(t, "ro", found["profile"]) + assert.Equal(t, "locked", found["profile_mode"]) + assert.Len(t, found["credentials"].([]interface{}), 1) +} diff --git a/internal/httpapi/scope_route_clients_personal_test.go b/internal/httpapi/scope_route_clients_personal_test.go index 6f8fc55c7..439b4d9ef 100644 --- a/internal/httpapi/scope_route_clients_personal_test.go +++ b/internal/httpapi/scope_route_clients_personal_test.go @@ -4,15 +4,19 @@ package httpapi func editionGetRouteScopes() map[string]routeScope { return map[string]routeScope{ - "/api/v1/clients": {scopeRefused, "MCP client/session presence; TestClientsPresence_AdministratorOnly"}, - "/api/v1/clients/{client}": {scopeRefused, "MCP client/session presence detail; TestClientsPresence_AdministratorOnly"}, + "/api/v1/clients": {scopeRefused, "MCP client/session presence; TestClientsPresence_AdministratorOnly"}, + "/api/v1/clients/{client}": {scopeRefused, "MCP client/session presence detail; TestClientsPresence_AdministratorOnly"}, + "/api/v1/oauth/authorizations": {scopeRefused, "pending browser sign-in requests; TestOAuthLoginREST_AdministratorOnly"}, + "/api/v1/oauth/authorizations/{id}": {scopeRefused, "one browser sign-in request; TestOAuthLoginREST_AdministratorOnly"}, } } func editionRouteDenialMarkers() map[string]string { return map[string]string{ - "/api/v1/clients": "Admin credentials required to read clients", - "/api/v1/clients/{client}": "Admin credentials required to read clients", + "/api/v1/clients": "Admin credentials required to read clients", + "/api/v1/clients/{client}": "Admin credentials required to read clients", + "/api/v1/oauth/authorizations": "Admin credentials required to read sign-in requests", + "/api/v1/oauth/authorizations/{id}": "Admin credentials required to read sign-in requests", } } diff --git a/internal/httpapi/scope_route_clients_server_test.go b/internal/httpapi/scope_route_clients_server_test.go index 8a987fa4f..bc4790eab 100644 --- a/internal/httpapi/scope_route_clients_server_test.go +++ b/internal/httpapi/scope_route_clients_server_test.go @@ -8,7 +8,9 @@ func editionRouteDenialMarkers() map[string]string { return nil } func editionAbsentGetRoutes() map[string]string { return map[string]string{ - "/api/v1/clients": "server edition does not expose fleet-wide local client presence", - "/api/v1/clients/{client}": "server edition does not expose fleet-wide local client presence", + "/api/v1/clients": "server edition does not expose fleet-wide local client presence", + "/api/v1/clients/{client}": "server edition does not expose fleet-wide local client presence", + "/api/v1/oauth/authorizations": "server edition does not serve browser login", + "/api/v1/oauth/authorizations/{id}": "server edition does not serve browser login", } } diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index d85e89c92..de495cc3e 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -342,6 +342,8 @@ type Server struct { feedbackSubmitter FeedbackSubmitter // Feedback submission (Spec 036) connectService *connect.Service // Client connect/disconnect operations clientsService *internalRuntime.ClientsService // Client credentials and bindings (Spec 108 FR-026) + // oauthLoginService is the Spec 132 browser-login service (admin REST). + oauthLoginService *internalRuntime.OAuthLoginService // credentialsService is the Spec 115 issue/revoke path shared with the // MCP `credentials` tool (tokens and custom clients). credentialsService *internalRuntime.CredentialsService @@ -528,6 +530,12 @@ func (s *Server) SetClientsService(svc *internalRuntime.ClientsService) { s.wireClientsService() } +// SetOAuthLoginService configures the Spec 132 browser-login service behind the +// /oauth/authorizations routes and the per-login revoke (personal edition). +func (s *Server) SetOAuthLoginService(svc *internalRuntime.OAuthLoginService) { + s.oauthLoginService = svc +} + // wireClientsService connects the clients service to the REST server's // on-demand credential observations and, when the connect service is set, to // the connect port behind the admin-key upgrade (Spec 108-f F11, F22). Either diff --git a/internal/runtime/activity_attribution.go b/internal/runtime/activity_attribution.go index 0409c9364..d2a923936 100644 --- a/internal/runtime/activity_attribution.go +++ b/internal/runtime/activity_attribution.go @@ -1,6 +1,9 @@ package runtime -import "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +import ( + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) // attributionPayloadKey is the event-payload key that carries an // ActivityAttribution. It is a NESTED object on purpose: the legacy flat @@ -182,6 +185,11 @@ func applyAttribution(rec *storage.ActivityRecord, a ActivityAttribution) { setMetadataIfAbsent("client_name", a.ClientName) setMetadataIfAbsent("client_version", a.ClientVersion) setMetadataIfAbsent("grant_id", a.GrantID) + // A browser login (Spec 132) is labelled as such: a row with a grant id was + // authenticated by an OAuth access token, never by an agent token. + if a.GrantID != "" { + setMetadataIfAbsent("credential_kind", string(auth.CredentialKindOAuth)) + } } // NewUsageAggregate returns an empty aggregate at the current admission diff --git a/internal/runtime/activity_attribution_grant_test.go b/internal/runtime/activity_attribution_grant_test.go index 5f0765588..b04f46c4e 100644 --- a/internal/runtime/activity_attribution_grant_test.go +++ b/internal/runtime/activity_attribution_grant_test.go @@ -30,4 +30,22 @@ func TestActivityAttribution_GrantIDRoundTripsToMetadata(t *testing.T) { }) rec := onlyRecord(t, store) require.Equal(t, "grantAAAAAAAAAAAAAAAAAA", rec.Metadata["grant_id"]) + // A row with a grant id was authenticated by a browser login, never by an + // agent token: it is labelled as the OAuth credential kind. + require.Equal(t, "oauth", rec.Metadata["credential_kind"]) +} + +func TestActivityAttribution_NoGrantNoCredentialKind(t *testing.T) { + store, cleanup := setupTestStorage(t) + defer cleanup() + svc := NewActivityService(store, zap.NewNop()) + svc.handleEvent(Event{ + Type: EventTypeActivityToolCallCompleted, Timestamp: time.Now().UTC(), + Payload: map[string]any{ + "server_name": "github", "tool_name": "list_issues", "session_id": "s1", "request_id": "r1", + "source": "mcp", "status": "success", "duration_ms": int64(5), "attribution": testAttribution().payload(), + }, + }) + rec := onlyRecord(t, store) + require.NotContains(t, rec.Metadata, "credential_kind", "an API-key row is unchanged") } diff --git a/internal/runtime/oauth_login_consent.go b/internal/runtime/oauth_login_consent.go index 1a7e81c5e..93e9f10f8 100644 --- a/internal/runtime/oauth_login_consent.go +++ b/internal/runtime/oauth_login_consent.go @@ -164,6 +164,12 @@ func (s *OAuthLoginService) clientExists(clientID string) bool { return s.hasClientRecords(clientID) } +// ClientExists reports whether clientID names a client a browser-login address +// may fix: a connect-registry id (supported or not), or a client with an +// API-key record or a browser-login binding. The HTTP layer answers 404 for +// any other per-client address (Spec 132 FR-015). +func (s *OAuthLoginService) ClientExists(clientID string) bool { return s.clientExists(clientID) } + // hasClientRecords: the client has an API-key record or a browser-login entry // (a registry id alone does not count). func (s *OAuthLoginService) hasClientRecords(clientID string) bool { diff --git a/internal/server/mcp.go b/internal/server/mcp.go index 263764aa2..fae618282 100644 --- a/internal/server/mcp.go +++ b/internal/server/mcp.go @@ -819,6 +819,13 @@ func NewMCPProxyServer( sessionStore.SetSessionTokenPrefix(sessionID, ac.TokenPrefix) if ac.GrantID != "" { sessionStore.SetSessionGrantID(sessionID, ac.GrantID) + // Spec 132 R14: the name the client sends here is stored on its + // login, off the request path, to flag a mismatch advisorily. + if mainServer != nil && mainServer.runtime != nil { + if svc := mainServer.runtime.OAuthLoginService(); svc != nil { + svc.Touch(ac.GrantID, clientName) + } + } } } sessionStore.SetSessionServer(sessionID, mcpserver.ServerFromContext(ctx)) diff --git a/internal/server/oauth_login_auth_test.go b/internal/server/oauth_login_auth_test.go new file mode 100644 index 000000000..c10b7163f --- /dev/null +++ b/internal/server/oauth_login_auth_test.go @@ -0,0 +1,179 @@ +//go:build !server + +package server + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" +) + +// T036: mcp_oat_ is accepted only on its own resource and origin. +func TestOAuthLoginAuth_OnlyOnItsOwnResourceAndOrigin(t *testing.T) { + f := newOAuthFlow(t, nil) + _, tok := f.login("cursor") + + rec := f.get("/mcp/oauth/cursor", bearer(tok.access)) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + got := decodeBody(t, rec) + assert.Equal(t, "cursor", got["client"]) + assert.Equal(t, "oauth", got["kind"]) + assert.NotEmpty(t, got["grant"]) + assert.Equal(t, "client-cursor", got["agent"], "labelled like the client's API key") + // A trailing slash is the same address. + assert.Equal(t, http.StatusOK, f.get("/mcp/oauth/cursor/", bearer(tok.access)).Code) + // The scheme name is case-insensitive. + assert.Equal(t, http.StatusOK, f.get("/mcp/oauth/cursor", map[string]string{"Authorization": "bearer " + tok.access}).Code) + + // another client's address, the generic address, another origin: 401 with the challenge + for name, c := range map[string]struct { + path, host string + }{ + "other client": {"/mcp/oauth/windsurf", oauthTestHost}, + "generic": {"/mcp/oauth", oauthTestHost}, + "other origin": {"/mcp/oauth/cursor", "localhost:8080"}, + } { + other := *f + other.host = c.host + rec := other.get(c.path, bearer(tok.access)) + assert.Equal(t, http.StatusUnauthorized, rec.Code, name) + assert.Contains(t, rec.Header().Get("WWW-Authenticate"), "resource_metadata=", name) + } + assert.Equal(t, http.StatusNotFound, f.get("/mcp/oauth/no-such-client", bearer(tok.access)).Code) +} + +// T036: every other credential is 401 on an OAuth address, with +// require_mcp_auth off, and never falls to the anonymous context. +func TestOAuthLoginAuth_OtherCredentialsRefused(t *testing.T) { + for _, requireAuth := range []bool{false, true} { + f := newOAuthFlow(t, func(c *config.Config) { c.RequireMCPAuth = requireAuth }) + hdrs := map[string]map[string]string{ + "none": nil, + "x-api-key": {"X-API-Key": oauthLoginTestAPIKey}, + "bearer api key": {"Authorization": "Bearer " + oauthLoginTestAPIKey}, + "mcp_cli_": {"Authorization": "Bearer mcp_cli_0123456789abcdef"}, + "mcp_agt_": {"Authorization": "Bearer mcp_agt_0123456789abcdef"}, + "garbage": {"Authorization": "Bearer garbage"}, + "basic": {"Authorization": "Basic Zm9vOmJhcg=="}, + "oat in x-api-key": {"X-API-Key": "mcp_oat_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}, + } + for name, h := range hdrs { + for _, path := range []string{"/mcp/oauth", "/mcp/oauth/cursor"} { + rec := f.get(path, h) + assert.Equal(t, http.StatusUnauthorized, rec.Code, "require=%v %s %s", requireAuth, name, path) + assert.NotEmpty(t, rec.Header().Get("WWW-Authenticate"), name) + } + } + rec := f.get("/mcp/oauth/cursor?apikey="+oauthLoginTestAPIKey, nil) + assert.Equal(t, http.StatusUnauthorized, rec.Code, "?apikey=") + } +} + +// T036: mcp_oat_ on /mcp: 401 while the feature is on or was used, the +// previous (anonymous) behaviour while it is off and never used. +func TestOAuthLoginAuth_OatOnClassicMCP(t *testing.T) { + const oat = "mcp_oat_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + hdr := bearer(oat) + + on := newOAuthFlow(t, nil) + assert.Equal(t, http.StatusUnauthorized, on.get("/mcp", hdr).Code, "on") + assert.Equal(t, http.StatusUnauthorized, on.get("/mcp/", hdr).Code, "on") + + off := newOAuthFlow(t, func(c *config.Config) { c.MCPOAuthEnabled = false }) + assert.Equal(t, http.StatusOK, off.get("/mcp", hdr).Code, "off and never used: unchanged anonymous behaviour") + + used := newOAuthFlow(t, func(c *config.Config) { c.MCPOAuthEnabled = false }) + used.srv.oauthLoginEverUsed = func() bool { return true } + assert.Equal(t, http.StatusUnauthorized, used.get("/mcp", hdr).Code, "off after use") + + // require_mcp_auth off does not turn the refusal into an anonymous pass. + require.False(t, on.srv.liveConfig().RequireMCPAuth) +} + +// T036: a revoked login is refused on the next request, also for a client that +// kept the access token (and the refresh token no longer works). +func TestOAuthLoginAuth_RevokedLoginRefusedNextRequest(t *testing.T) { + f := newOAuthFlow(t, nil) + regID, tok := f.login("cursor") + require.Equal(t, http.StatusOK, f.get("/mcp/oauth/cursor", bearer(tok.access)).Code) + + svc := f.srv.oauthLoginSvc() + grants, err := svc.ListGrants("cursor") + require.NoError(t, err) + require.Len(t, grants, 1) + changed, err := svc.RevokeGrant(adminCtx(), "cursor", grants[0].GrantID) + require.NoError(t, err) + require.True(t, changed) + + assert.Equal(t, http.StatusUnauthorized, f.get("/mcp/oauth/cursor", bearer(tok.access)).Code) + assert.Equal(t, http.StatusBadRequest, f.refreshWith(regID, tok.refresh).Code) +} + +// T036: switching the feature off refuses a live access token at once, and +// switching it back on restores the login (nothing was deleted). +func TestOAuthLoginAuth_SwitchOffRefusesAtOnce(t *testing.T) { + f := newOAuthFlow(t, nil) + _, tok := f.login("cursor") + require.Equal(t, http.StatusOK, f.get("/mcp/oauth/cursor", bearer(tok.access)).Code) + + f.setEnabled(false) + assert.Equal(t, http.StatusNotFound, f.get("/mcp/oauth/cursor", bearer(tok.access)).Code, "off after use: 404") + f.setEnabled(true) + assert.Equal(t, http.StatusOK, f.get("/mcp/oauth/cursor", bearer(tok.access)).Code, "off -> on restores the login") +} + +// T036: profile scope equals what the client's API key would carry. +func TestOAuthLoginAuth_ProfileScopeFollowsClientBinding(t *testing.T) { + f := newOAuthFlow(t, func(c *config.Config) { + c.RequireMCPAuth = true // a named pin is only allowed with MCP auth required (FR-008a) + c.Profiles = []config.ProfileConfig{{Name: "dev", Servers: []string{}}} + }) + regID := f.register(oauthTestRedirect) + verifier, challenge := pkce() + resource := f.origin() + "/mcp/oauth/cursor" + id := f.authorize(regID, oauthTestRedirect, challenge, resource) + pin := "dev" + redirect, err := f.srv.oauthLoginSvc().Approve(adminCtx(), id, runtime.ApprovalChoice{ + Client: runtime.ClientChoice{ID: "cursor"}, Profile: &pin, Mode: auth.ProfileModeLocked, + }) + require.NoError(t, err) + code := redirectParam(t, redirect, "code") + rec := f.exchange(code, regID, verifier, resource) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + access, _ := decodeBody(t, rec)["access_token"].(string) + + got := decodeBody(t, f.get("/mcp/oauth/cursor", bearer(access))) + want := auth.ClientAuthContext(auth.ClientIdentity{ClientID: "cursor", ProfilePin: "dev", ProfileMode: auth.ProfileModeLocked, + CredentialKind: auth.CredentialKindOAuth}) + assert.Equal(t, "dev", got["pin"]) + assert.Equal(t, auth.ProfileModeLocked, got["mode"]) + assert.Equal(t, want.AgentName, got["agent"]) +} + +// newOAuthFlow's mux has no Touch on the sentinel: the "initialize name stored on +// the grant" behaviour is exercised against the real daemon in the in-process +// flow test (TestOAuthLogin_FullFlow_InProcess). + +func redirectParam(t *testing.T, redirect, key string) string { + t.Helper() + req := httptest.NewRequest(http.MethodGet, redirect, http.NoBody) + v := req.URL.Query().Get(key) + require.NotEmpty(t, v, redirect) + return v +} + +func (f *oauthFlow) setEnabled(on bool) { + f.t.Helper() + cfg := f.srv.runtime.Config() + require.NotNil(f.t, cfg) + next := *cfg + next.MCPOAuthEnabled = on + f.srv.runtime.UpdateConfig(&next, "") +} diff --git a/internal/server/oauth_login_default_off_test.go b/internal/server/oauth_login_default_off_test.go index f18449d5d..5e3fdb14d 100644 --- a/internal/server/oauth_login_default_off_test.go +++ b/internal/server/oauth_login_default_off_test.go @@ -1,6 +1,7 @@ package server import ( + "encoding/json" "fmt" "net/http" "net/http/httptest" @@ -13,6 +14,7 @@ import ( "go.etcd.io/bbolt" "go.uber.org/zap" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" ) @@ -56,7 +58,17 @@ func oauthLoginTestMux(s *Server, withRoutes bool) *http.ServeMux { mux.Handle("/mcp/", mcpHandler) mux.Handle("/", rootHandler) if withRoutes { - s.registerOAuthLoginRoutes(mux, mcpHandler, rootHandler) + // The OAuth address runs the REAL resource authentication around a + // sentinel that reports the identity it was handed. + oauthMCP := s.oauthResourceAuth(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ac := auth.AuthContextFromContext(r.Context()) + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "client": ac.ClientID, "kind": ac.CredentialKind, "grant": ac.GrantID, + "pin": ac.ProfilePin, "mode": ac.ProfileMode, "agent": ac.AgentName, "path": r.URL.Path, + }) + })) + s.registerOAuthLoginRoutes(mux, mcpHandler, rootHandler, s.hostValidationMiddleware(oauthMCP)) } return mux } @@ -100,6 +112,9 @@ func TestOAuthLogin_DefaultOff_RoutesUnchanged(t *testing.T) { "none": nil, "admin": {"X-API-Key": oauthLoginTestAPIKey}, "garbage": {"Authorization": "Bearer garbage-token"}, + // An access-token-shaped credential is just an unknown token while the + // feature is off and never used (Spec 132 FR-002). + "oat": {"Authorization": "Bearer mcp_oat_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}, } for _, requireAuth := range []bool{false, true} { srv := newOAuthLoginTestServer(t, func(c *config.Config) { c.RequireMCPAuth = requireAuth }) diff --git a/internal/server/oauth_login_flow_helpers_test.go b/internal/server/oauth_login_flow_helpers_test.go new file mode 100644 index 000000000..fa35881b2 --- /dev/null +++ b/internal/server/oauth_login_flow_helpers_test.go @@ -0,0 +1,173 @@ +//go:build !server + +package server + +import ( + "crypto/sha256" + "encoding/base64" + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" +) + +const ( + oauthTestHost = "127.0.0.1:8080" + oauthTestOrigin = "http://127.0.0.1:8080" + oauthTestRedirect = "http://127.0.0.1:54321/callback" +) + +// oauthFlow drives the public OAuth endpoints of an in-process server through +// the same mux shape startCustomHTTPServer builds. +type oauthFlow struct { + t *testing.T + srv *Server + mux http.Handler + host string + // limited keeps the endpoint rate limits between requests; by default every + // request starts with a fresh budget so table tests do not trip them. + limited bool +} + +func newOAuthFlow(t *testing.T, mutate func(*config.Config)) *oauthFlow { + t.Helper() + srv := newOAuthLoginTestServer(t, func(c *config.Config) { + c.MCPOAuthEnabled = true + if mutate != nil { + mutate(c) + } + }) + return &oauthFlow{t: t, srv: srv, mux: oauthLoginTestMux(srv, true), host: oauthTestHost} +} + +func (f *oauthFlow) origin() string { return "http://" + f.host } + +func (f *oauthFlow) do(req *http.Request) *httptest.ResponseRecorder { + req.RemoteAddr = "127.0.0.1:4000" + req.Host = f.host + if !f.limited { + f.srv.oauthLimiterOnce.Do(func() {}) + f.srv.oauthLimiter = mcplogin.NewLimiter(nil) + } + rec := httptest.NewRecorder() + f.mux.ServeHTTP(rec, req) + return rec +} + +func (f *oauthFlow) get(path string, hdr map[string]string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, path, http.NoBody) + for k, v := range hdr { + req.Header.Set(k, v) + } + return f.do(req) +} + +func (f *oauthFlow) postJSON(path, body string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + return f.do(req) +} + +func (f *oauthFlow) postForm(path string, form url.Values) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(form.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + return f.do(req) +} + +func decodeBody(t *testing.T, rec *httptest.ResponseRecorder) map[string]any { + t.Helper() + var out map[string]any + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &out), rec.Body.String()) + return out +} + +func (f *oauthFlow) register(redirect string) string { + f.t.Helper() + rec := f.postJSON("/oauth/register", `{"redirect_uris":["`+redirect+`"],"client_name":"Test Client"}`) + require.Equal(f.t, http.StatusCreated, rec.Code, rec.Body.String()) + id, _ := decodeBody(f.t, rec)["client_id"].(string) + require.NotEmpty(f.t, id) + return id +} + +// pkce returns a verifier and its S256 challenge. +func pkce() (verifier, challenge string) { + verifier = strings.Repeat("v", 43) + sum := sha256.Sum256([]byte(verifier)) + return verifier, base64.RawURLEncoding.EncodeToString(sum[:]) +} + +func (f *oauthFlow) authorizeQuery(clientID, redirect, challenge, resource, state string) string { + q := url.Values{ + "response_type": {"code"}, "client_id": {clientID}, "redirect_uri": {redirect}, + "code_challenge": {challenge}, "code_challenge_method": {"S256"}, "resource": {resource}, + } + if state != "" { + q.Set("state", state) + } + return "/oauth/authorize?" + q.Encode() +} + +// authorize returns the request id the consent URL carries. +func (f *oauthFlow) authorize(clientID, redirect, challenge, resource string) string { + f.t.Helper() + rec := f.get(f.authorizeQuery(clientID, redirect, challenge, resource, "st"), nil) + require.Equal(f.t, http.StatusFound, rec.Code, rec.Body.String()) + loc, err := url.Parse(rec.Header().Get("Location")) + require.NoError(f.t, err) + require.Equal(f.t, "/ui/authorize", loc.Path) + return loc.Query().Get("request") +} + +// approve approves request id for client and returns the code from the redirect. +func (f *oauthFlow) approve(id, clientID string) string { + f.t.Helper() + redirect, err := f.srv.oauthLoginSvc().Approve(adminCtx(), id, runtime.ApprovalChoice{Client: runtime.ClientChoice{ID: clientID}}) + require.NoError(f.t, err) + u, err := url.Parse(redirect) + require.NoError(f.t, err) + code := u.Query().Get("code") + require.NotEmpty(f.t, code, redirect) + return code +} + +type oauthTokens struct{ access, refresh string } + +func (f *oauthFlow) exchange(code, clientID, verifier, resource string) *httptest.ResponseRecorder { + return f.postForm("/oauth/token", url.Values{ + "grant_type": {"authorization_code"}, "code": {code}, "redirect_uri": {oauthTestRedirect}, + "client_id": {clientID}, "code_verifier": {verifier}, "resource": {resource}, + }) +} + +// login runs register -> authorize -> approve -> token for a per-client address. +func (f *oauthFlow) login(client string) (regID string, tok oauthTokens) { + f.t.Helper() + regID = f.register(oauthTestRedirect) + verifier, challenge := pkce() + resource := f.origin() + "/mcp/oauth/" + client + id := f.authorize(regID, oauthTestRedirect, challenge, resource) + code := f.approve(id, client) + rec := f.exchange(code, regID, verifier, resource) + require.Equal(f.t, http.StatusOK, rec.Code, rec.Body.String()) + body := decodeBody(f.t, rec) + tok.access, _ = body["access_token"].(string) + tok.refresh, _ = body["refresh_token"].(string) + require.True(f.t, strings.HasPrefix(tok.access, "mcp_oat_")) + require.True(f.t, strings.HasPrefix(tok.refresh, "mcp_ort_")) + return regID, tok +} + +func (f *oauthFlow) refreshWith(regID, refresh string) *httptest.ResponseRecorder { + return f.postForm("/oauth/token", url.Values{"grant_type": {"refresh_token"}, "refresh_token": {refresh}, "client_id": {regID}}) +} + +func bearer(tok string) map[string]string { return map[string]string{"Authorization": "Bearer " + tok} } diff --git a/internal/server/oauth_login_flow_test.go b/internal/server/oauth_login_flow_test.go new file mode 100644 index 000000000..a953412e2 --- /dev/null +++ b/internal/server/oauth_login_flow_test.go @@ -0,0 +1,171 @@ +//go:build !server + +package server + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "io" + "net/http" + "net/url" + "strings" + "testing" + "time" + + "github.com/mark3labs/mcp-go/client" + "github.com/mark3labs/mcp-go/client/transport" + "github.com/mark3labs/mcp-go/mcp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" +) + +// The whole browser login against a real in-process daemon over real HTTP: +// discovery, register, authorize, the administrator's approval over the admin +// REST, token, an MCP session on the OAuth address, refresh, revoke, and the +// refusal of the next request of the still-open session. +func TestOAuthLogin_FullFlow_InProcess(t *testing.T) { + env := NewTestEnvironmentWithOptions(t, TestEnvironmentOptions{ + Mutate: func(cfg *config.Config, _ string) { cfg.MCPOAuthEnabled = true }, + }) + t.Cleanup(env.Cleanup) + base := strings.TrimSuffix(env.proxyAddr, "/mcp") + const apiKey = "test-api-key-e2e" + httpc := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, Timeout: 20 * time.Second} + + do := func(method, path, ctype, body string, hdr map[string]string) (*http.Response, []byte) { + req, err := http.NewRequest(method, base+path, bytes.NewBufferString(body)) + require.NoError(t, err) + if ctype != "" { + req.Header.Set("Content-Type", ctype) + } + for k, v := range hdr { + req.Header.Set(k, v) + } + resp, err := httpc.Do(req) + require.NoError(t, err) + defer resp.Body.Close() + raw, _ := io.ReadAll(resp.Body) + return resp, raw + } + asJSON := func(raw []byte) map[string]any { + var m map[string]any + require.NoError(t, json.Unmarshal(raw, &m), string(raw)) + return m + } + + // 1. The address challenges, discovery documents point at this origin. + resp, _ := do(http.MethodPost, "/mcp/oauth/cursor", "application/json", `{}`, nil) + require.Equal(t, http.StatusUnauthorized, resp.StatusCode) + assert.Contains(t, resp.Header.Get("WWW-Authenticate"), base+"/.well-known/oauth-protected-resource/mcp/oauth/cursor") + resp, raw := do(http.MethodGet, "/.well-known/oauth-protected-resource/mcp/oauth/cursor", "", "", nil) + require.Equal(t, http.StatusOK, resp.StatusCode) + assert.Equal(t, base+"/mcp/oauth/cursor", asJSON(raw)["resource"]) + resp, raw = do(http.MethodGet, "/.well-known/oauth-authorization-server", "", "", nil) + require.Equal(t, http.StatusOK, resp.StatusCode) + assert.Equal(t, base, asJSON(raw)["issuer"]) + + // 2. Register, authorize. + redirect := "http://127.0.0.1:50999/callback" + resp, raw = do(http.MethodPost, "/oauth/register", "application/json", `{"redirect_uris":["`+redirect+`"],"client_name":"Cursor IDE"}`, nil) + require.Equal(t, http.StatusCreated, resp.StatusCode, string(raw)) + regID, _ := asJSON(raw)["client_id"].(string) + verifier := strings.Repeat("z", 64) + sum := sha256.Sum256([]byte(verifier)) + challenge := base64.RawURLEncoding.EncodeToString(sum[:]) + resource := base + "/mcp/oauth/cursor" + q := url.Values{"response_type": {"code"}, "client_id": {regID}, "redirect_uri": {redirect}, "code_challenge": {challenge}, + "code_challenge_method": {"S256"}, "resource": {resource}, "state": {"xyz"}} + resp, _ = do(http.MethodGet, "/oauth/authorize?"+q.Encode(), "", "", nil) + require.Equal(t, http.StatusFound, resp.StatusCode) + loc, err := url.Parse(resp.Header.Get("Location")) + require.NoError(t, err) + require.Equal(t, "/ui/authorize", loc.Path) + requestID := loc.Query().Get("request") + require.NotEmpty(t, requestID) + + // 3. The administrator sees the request and approves it (admin REST, API key). + admin := map[string]string{"X-API-Key": apiKey} + resp, raw = do(http.MethodGet, "/api/v1/oauth/authorizations", "", "", admin) + require.Equal(t, http.StatusOK, resp.StatusCode, string(raw)) + assert.Contains(t, string(raw), requestID) + resp, raw = do(http.MethodGet, "/api/v1/oauth/authorizations/"+requestID, "", "", admin) + require.Equal(t, http.StatusOK, resp.StatusCode, string(raw)) + resp, raw = do(http.MethodPost, "/api/v1/oauth/authorizations/"+requestID+"/approve", "application/json", `{"client":{"id":"cursor"}}`, admin) + require.Equal(t, http.StatusOK, resp.StatusCode, string(raw)) + redirectURL, _ := asJSON(raw)["data"].(map[string]any)["redirect_url"].(string) + ru, err := url.Parse(redirectURL) + require.NoError(t, err) + assert.Equal(t, "xyz", ru.Query().Get("state")) + code := ru.Query().Get("code") + require.NotEmpty(t, code) + + // 4. Token. + form := url.Values{"grant_type": {"authorization_code"}, "code": {code}, "redirect_uri": {redirect}, "client_id": {regID}, + "code_verifier": {verifier}, "resource": {resource}} + resp, raw = do(http.MethodPost, "/oauth/token", "application/x-www-form-urlencoded", form.Encode(), nil) + require.Equal(t, http.StatusOK, resp.StatusCode, string(raw)) + tok := asJSON(raw) + access, _ := tok["access_token"].(string) + refresh, _ := tok["refresh_token"].(string) + require.True(t, strings.HasPrefix(access, "mcp_oat_")) + + // 5. An MCP session on the OAuth address with the access token. The API key + // is refused there. + resp, _ = do(http.MethodPost, "/mcp/oauth/cursor", "application/json", `{}`, admin) + assert.Equal(t, http.StatusUnauthorized, resp.StatusCode, "the API key does not work on an OAuth address") + + newSession := func(token string) *client.Client { + tr, terr := transport.NewStreamableHTTP(base+"/mcp/oauth/cursor", transport.WithHTTPHeaders(map[string]string{"Authorization": "Bearer " + token})) + require.NoError(t, terr) + c := client.NewClient(tr) + require.NoError(t, c.Start(context.Background())) + initReq := mcp.InitializeRequest{} + initReq.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION + initReq.Params.ClientInfo = mcp.Implementation{Name: "cursor-vscode", Version: "1.0"} + _, ierr := c.Initialize(context.Background(), initReq) + require.NoError(t, ierr) + t.Cleanup(func() { _ = c.Close() }) + return c + } + session := newSession(access) + list, err := session.ListTools(context.Background(), mcp.ListToolsRequest{}) + require.NoError(t, err) + assert.NotEmpty(t, list.Tools, "tools/list works on the OAuth address") + + // The name sent at initialize is stored on the login (advisory). + svc := env.proxyServer.oauthLoginSvc() + require.Eventually(t, func() bool { + grants, gerr := svc.ListGrants("cursor") + return gerr == nil && len(grants) == 1 && grants[0].ObservedClientName == "cursor-vscode" + }, 5*time.Second, 50*time.Millisecond, "the name sent at initialize lands on the grant") + + // 6. Refresh rotates both tokens; the old refresh token is dead. + form = url.Values{"grant_type": {"refresh_token"}, "refresh_token": {refresh}, "client_id": {regID}} + resp, raw = do(http.MethodPost, "/oauth/token", "application/x-www-form-urlencoded", form.Encode(), nil) + require.Equal(t, http.StatusOK, resp.StatusCode, string(raw)) + access2, _ := asJSON(raw)["access_token"].(string) + assert.NotEqual(t, access, access2) + // The previous access token no longer authenticates, so the open session + // (still holding it) is refused on its next request. + _, err = session.ListTools(context.Background(), mcp.ListToolsRequest{}) + assert.Error(t, err, "rotation replaced the access token; the old one is refused on the next request") + session2 := newSession(access2) + _, err = session2.ListTools(context.Background(), mcp.ListToolsRequest{}) + require.NoError(t, err) + + // 7. Revoke the login (admin REST): the next request of the live session is refused. + grants, err := svc.ListGrants("cursor") + require.NoError(t, err) + require.Len(t, grants, 1) + resp, raw = do(http.MethodDelete, "/api/v1/clients/cursor/logins/"+grants[0].GrantID, "", "", admin) + require.Equal(t, http.StatusOK, resp.StatusCode, string(raw)) + _, err = session2.ListTools(context.Background(), mcp.ListToolsRequest{}) + assert.Error(t, err, "revoked login: refused on the next request of an open session") + resp, _ = do(http.MethodPost, "/mcp/oauth/cursor", "application/json", `{}`, map[string]string{"Authorization": "Bearer " + access2}) + assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) +} diff --git a/internal/server/oauth_login_gate_on_test.go b/internal/server/oauth_login_gate_on_test.go index fbdea267c..0414162cc 100644 --- a/internal/server/oauth_login_gate_on_test.go +++ b/internal/server/oauth_login_gate_on_test.go @@ -19,26 +19,27 @@ func TestOAuthLogin_Gate_On(t *testing.T) { srv := newOAuthLoginTestServer(t, func(c *config.Config) { c.MCPOAuthEnabled = true }) mux := oauthLoginTestMux(srv, true) + // A path every handler answers for a loopback peer without any credential: + // the discovery documents and the OAuth MCP address (401 challenge). + for _, path := range []string{"/.well-known/oauth-authorization-server", "/.well-known/oauth-protected-resource/mcp/oauth", "/mcp/oauth"} { + for _, hostPeer := range [][2]string{{"127.0.0.1:4000", "127.0.0.1:8080"}, {"[::1]:4000", "localhost:8080"}} { + req := httptest.NewRequest(http.MethodGet, path, http.NoBody) + req.RemoteAddr, req.Host = hostPeer[0], hostPeer[1] + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + want := http.StatusOK + if path == "/mcp/oauth" { + want = http.StatusUnauthorized + } + assert.Equal(t, want, rec.Code, "loopback "+path+" "+hostPeer[0]) + } + } + for _, path := range oauthLoginGatedPaths { req := httptest.NewRequest(http.MethodGet, path, http.NoBody) - req.RemoteAddr = "127.0.0.1:4000" - req.Host = "127.0.0.1:8080" - rec := httptest.NewRecorder() - mux.ServeHTTP(rec, req) - assert.Equal(t, http.StatusNotImplemented, rec.Code, "loopback peer+host "+path) - assert.Contains(t, rec.Header().Get("Content-Type"), "application/json", path) - - req = httptest.NewRequest(http.MethodGet, path, http.NoBody) - req.RemoteAddr = "[::1]:4000" - req.Host = "localhost:8080" - rec = httptest.NewRecorder() - mux.ServeHTTP(rec, req) - assert.Equal(t, http.StatusNotImplemented, rec.Code, "ipv6 loopback peer "+path) - - req = httptest.NewRequest(http.MethodGet, path, http.NoBody) req.RemoteAddr = "192.0.2.1:4000" req.Host = "127.0.0.1:8080" - rec = httptest.NewRecorder() + rec := httptest.NewRecorder() mux.ServeHTTP(rec, req) assert.Equal(t, http.StatusNotFound, rec.Code, "non-loopback peer "+path) @@ -57,7 +58,7 @@ func TestOAuthLogin_Gate_FollowsLiveConfig(t *testing.T) { srv := newOAuthLoginTestServer(t, nil) mux := oauthLoginTestMux(srv, true) get := func() int { - req := httptest.NewRequest(http.MethodGet, "/oauth/token", http.NoBody) + req := httptest.NewRequest(http.MethodGet, "/.well-known/oauth-authorization-server", http.NoBody) req.RemoteAddr = "127.0.0.1:4000" req.Host = "127.0.0.1:8080" rec := httptest.NewRecorder() @@ -71,5 +72,5 @@ func TestOAuthLogin_Gate_FollowsLiveConfig(t *testing.T) { on := *cfg on.MCPOAuthEnabled = true srv.runtime.UpdateConfig(&on, "") - assert.Equal(t, http.StatusNotImplemented, get(), "on") + assert.Equal(t, http.StatusOK, get(), "on") } diff --git a/internal/server/oauth_login_http.go b/internal/server/oauth_login_http.go new file mode 100644 index 000000000..b7c735477 --- /dev/null +++ b/internal/server/oauth_login_http.go @@ -0,0 +1,344 @@ +package server + +import ( + "encoding/json" + "errors" + "html" + "net" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" +) + +// Spec 132: the public OAuth endpoints of the browser login for MCP clients +// (contracts/oauth-endpoints.md). Everything here runs behind oauthLoginGate, +// so it answers only when the feature is on, the peer and the Host are +// loopback and the build is the personal edition. The handlers parse the wire +// format and map outcomes to status codes; every decision is the service's +// (runtime.OAuthLoginService). + +// oauthLoginSvc returns the runtime's browser-login service, or nil. +func (s *Server) oauthLoginSvc() *runtime.OAuthLoginService { + if s == nil || s.runtime == nil { + return nil + } + return s.runtime.OAuthLoginService() +} + +// oauthLoginLive reports whether browser login is on now or was ever used: +// the two states in which an mcp_oat_ token is refused outside its own +// address. Off and never used it is false, so nothing changes. +func (s *Server) oauthLoginLive() bool { + if cfg := s.liveConfig(); cfg != nil && cfg.MCPOAuthEnabled { + return true + } + return s.oauthLoginEverUsedNow() +} + +func (s *Server) oauthRateLimiter() *mcplogin.Limiter { + s.oauthLimiterOnce.Do(func() { s.oauthLimiter = mcplogin.NewLimiter(nil) }) + return s.oauthLimiter +} + +// oauthLoginPublicHandler dispatches /oauth/* and /.well-known/oauth-* once the +// gate admitted the request. +func (s *Server) oauthLoginPublicHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc := s.oauthLoginSvc() + if svc == nil { + http.NotFound(w, r) + return + } + path := r.URL.Path + switch { + case path == "/oauth/register": + s.oauthRegister(w, r, svc) + case path == "/oauth/authorize": + s.oauthAuthorize(w, r, svc) + case path == "/oauth/token": + s.oauthToken(w, r, svc) + case path == "/.well-known/oauth-authorization-server": + s.oauthASMetadata(w, r) + case strings.HasPrefix(path, oauthProtectedResourceWellKnown): + s.oauthResourceMetadata(w, r, svc) + default: + http.NotFound(w, r) + } + }) +} + +const oauthProtectedResourceWellKnown = "/.well-known/oauth-protected-resource" + +// --- helpers ------------------------------------------------------------------- + +func oauthNoStore(w http.ResponseWriter) { + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Pragma", "no-cache") +} + +func oauthWriteJSON(w http.ResponseWriter, status int, v any) { + oauthNoStore(w) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) +} + +func oauthJSONError(w http.ResponseWriter, status int, code, desc string) { + oauthWriteJSON(w, status, map[string]string{"error": code, "error_description": desc}) +} + +func oauthMethodNotAllowed(w http.ResponseWriter, allow string) { + w.Header().Set("Allow", allow) + oauthJSONError(w, http.StatusMethodNotAllowed, "invalid_request", "method not allowed") +} + +// oauthRemoteIP is the rate-limit key of the peer. +func oauthRemoteIP(r *http.Request) string { + if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil { + return host + } + return r.RemoteAddr +} + +// oauthAllow charges the endpoint's budget and answers 429 when it is spent. +func (s *Server) oauthAllow(w http.ResponseWriter, r *http.Request, endpoint string, asHTML bool) bool { + ok, retry := s.oauthRateLimiter().Allow(endpoint, oauthRemoteIP(r)) + if ok { + return true + } + w.Header().Set("Retry-After", strconv.Itoa(retry)) + if asHTML { + oauthErrorPage(w, http.StatusTooManyRequests, "Too many requests", "Try again in a little while.") + } else { + oauthJSONError(w, http.StatusTooManyRequests, "temporarily_unavailable", "too many requests") + } + return false +} + +// oauthErrorPage is the HTML answer of the authorize endpoint when the request +// cannot be redirected back to the client. No external assets, no script. +func oauthErrorPage(w http.ResponseWriter, status int, title, detail string) { + oauthNoStore(w) + w.Header().Set("Referrer-Policy", "no-referrer") + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'") + w.WriteHeader(status) + _, _ = w.Write([]byte("" + html.EscapeString(title) + + "

" + + html.EscapeString(title) + "

" + html.EscapeString(detail) + "

")) +} + +// --- metadata -------------------------------------------------------------------- + +func (s *Server) oauthASMetadata(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet && r.Method != http.MethodHead { + oauthMethodNotAllowed(w, "GET, HEAD") + return + } + oauthWriteJSON(w, http.StatusOK, mcplogin.AuthorizationServerMetadata(mcplogin.Origin(r))) +} + +// oauthResourceMetadata serves /.well-known/oauth-protected-resource/mcp/oauth +// and /…/mcp/oauth/{client} (RFC 9728). An unknown client id is 404, like the +// address itself. +func (s *Server) oauthResourceMetadata(w http.ResponseWriter, r *http.Request, svc *runtime.OAuthLoginService) { + if r.Method != http.MethodGet && r.Method != http.MethodHead { + oauthMethodNotAllowed(w, "GET, HEAD") + return + } + suffix := strings.TrimPrefix(r.URL.Path, oauthProtectedResourceWellKnown) + clientID, generic, ok := mcplogin.ParseResourcePath(suffix) + if !ok || (!generic && !svc.ClientExists(clientID)) { + http.NotFound(w, r) + return + } + oauthWriteJSON(w, http.StatusOK, mcplogin.ProtectedResourceMetadata(mcplogin.Origin(r), clientID)) +} + +// --- register -------------------------------------------------------------------- + +func (s *Server) oauthRegister(w http.ResponseWriter, r *http.Request, svc *runtime.OAuthLoginService) { + if r.Method != http.MethodPost { + oauthMethodNotAllowed(w, "POST") + return + } + if !s.oauthAllow(w, r, mcplogin.EndpointRegister, false) { + return + } + var req mcplogin.RegistrationRequest + body := http.MaxBytesReader(w, r.Body, mcplogin.MaxBodyBytes) + dec := json.NewDecoder(body) + if err := dec.Decode(&req); err != nil { + var tooBig *http.MaxBytesError + if errors.As(err, &tooBig) { + oauthJSONError(w, http.StatusRequestEntityTooLarge, mcplogin.ErrCodeInvalidClientMetadata, "the request is too large") + return + } + oauthJSONError(w, http.StatusBadRequest, mcplogin.ErrCodeInvalidClientMetadata, "the body must be a JSON object") + return + } + resp, regErr, err := svc.Register(req) + switch { + case errors.Is(err, runtime.ErrOAuthFeatureDisabled): + http.NotFound(w, r) + case err != nil: + s.logger.Error("browser login: registration failed", zap.Error(err)) + oauthJSONError(w, http.StatusInternalServerError, "server_error", "the server could not complete the request") + case regErr != nil: + oauthJSONError(w, http.StatusBadRequest, regErr.Code, regErr.Description) + default: + oauthWriteJSON(w, http.StatusCreated, resp) + } +} + +// --- authorize --------------------------------------------------------------------- + +func (s *Server) oauthAuthorize(w http.ResponseWriter, r *http.Request, svc *runtime.OAuthLoginService) { + w.Header().Set("Referrer-Policy", "no-referrer") + if r.Method != http.MethodGet { + w.Header().Set("Allow", "GET") + oauthErrorPage(w, http.StatusMethodNotAllowed, "Method not allowed", "Use GET.") + return + } + if !s.oauthAllow(w, r, mcplogin.EndpointAuthorize, true) { + return + } + q := r.URL.Query() + origin := mcplogin.Origin(r) + id, aerr := svc.BeginAuthorization(runtime.AuthorizeInput{ + Origin: origin, ClientID: q.Get("client_id"), RedirectURI: q.Get("redirect_uri"), State: q.Get("state"), + CodeChallenge: q.Get("code_challenge"), Method: q.Get("code_challenge_method"), + Resource: q.Get("resource"), ResponseType: q.Get("response_type"), + }) + if aerr != nil { + switch aerr.Kind { + case runtime.AuthorizeNotFound: + oauthErrorPage(w, http.StatusNotFound, "Not found", "This sign-in address is not known.") + case runtime.AuthorizeRedirect: + target, err := aerr.RedirectURL() + if err != nil { + oauthErrorPage(w, http.StatusBadRequest, "Sign-in request refused", "The request could not be completed.") + return + } + oauthNoStore(w) + http.Redirect(w, r, target, http.StatusFound) + default: + oauthErrorPage(w, http.StatusBadRequest, "Sign-in request refused", aerr.Description) + } + return + } + oauthNoStore(w) + http.Redirect(w, r, origin+"/ui/authorize?request="+url.QueryEscape(id), http.StatusFound) +} + +// --- token --------------------------------------------------------------------------- + +func (s *Server) oauthToken(w http.ResponseWriter, r *http.Request, svc *runtime.OAuthLoginService) { + if r.Method != http.MethodPost { + oauthMethodNotAllowed(w, "POST") + return + } + if !s.oauthAllow(w, r, mcplogin.EndpointToken, false) { + return + } + if ct := r.Header.Get("Content-Type"); !strings.HasPrefix(strings.ToLower(ct), "application/x-www-form-urlencoded") { + oauthJSONError(w, http.StatusBadRequest, "invalid_request", "the body must be application/x-www-form-urlencoded") + return + } + r.Body = http.MaxBytesReader(w, r.Body, mcplogin.MaxBodyBytes) + if err := r.ParseForm(); err != nil { + var tooBig *http.MaxBytesError + if errors.As(err, &tooBig) { + oauthJSONError(w, http.StatusRequestEntityTooLarge, "invalid_request", "the request is too large") + return + } + oauthJSONError(w, http.StatusBadRequest, "invalid_request", "the body could not be read") + return + } + f := r.PostForm + in := runtime.TokenInput{ + Origin: mcplogin.Origin(r), Code: f.Get("code"), RedirectURI: f.Get("redirect_uri"), ClientID: f.Get("client_id"), + CodeVerifier: f.Get("code_verifier"), RefreshToken: f.Get("refresh_token"), Resource: f.Get("resource"), + } + var ( + res runtime.TokenResult + terr *runtime.TokenError + ) + switch f.Get("grant_type") { + case "authorization_code": + res, terr = svc.Exchange(in) + case "refresh_token": + res, terr = svc.Refresh(in) + default: + oauthJSONError(w, http.StatusBadRequest, "unsupported_grant_type", "only authorization_code and refresh_token are supported") + return + } + if terr != nil { + status := http.StatusBadRequest + if terr.Code == runtime.TokenErrServer { + status = http.StatusInternalServerError + } + oauthJSONError(w, status, terr.Code, terr.Description) + return + } + oauthWriteJSON(w, http.StatusOK, res) +} + +// --- the MCP resource ------------------------------------------------------------------ + +// oauthBearer returns the credential of an Authorization header that uses the +// Bearer scheme (case-insensitive), else "". Only this header counts on an +// OAuth address: X-API-Key and ?apikey= are never read there. +func oauthBearer(h string) string { + const scheme = "Bearer " + if len(h) < len(scheme) || !strings.EqualFold(h[:len(scheme)], scheme) { + return "" + } + return strings.TrimSpace(h[len(scheme):]) +} + +// oauthResourceAuth is the authentication of /mcp/oauth and /mcp/oauth/{client} +// (research R2). It accepts only a live mcp_oat_ access token for exactly this +// origin and address, asks the service on EVERY request (so revoke, forget, +// switch-off and expiry take effect on the next request of an open session) and +// never falls back to the anonymous context: any other credential, or none, is +// 401 with the protected-resource challenge. An unknown client id is 404. +func (s *Server) oauthResourceAuth(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc := s.oauthLoginSvc() + clientID, generic, ok := mcplogin.ParseResourcePath(r.URL.Path) + if svc == nil || !ok || (!generic && !svc.ClientExists(clientID)) { + http.NotFound(w, r) + return + } + origin := mcplogin.Origin(r) + unauthorized := func() { + w.Header().Set("WWW-Authenticate", mcplogin.Challenge(origin, clientID)) + oauthNoStore(w) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusUnauthorized) + _, _ = w.Write([]byte(`{"error":"Sign in required. Authenticate with an OAuth access token for this address."}`)) + } + token := oauthBearer(r.Header.Get("Authorization")) + if token == "" { + unauthorized() + return + } + ac, grant, err := svc.Authenticate(token, origin, r.URL.Path, time.Now()) + if err != nil { + unauthorized() + return + } + svc.Touch(grant.GrantID, "") + mcpRequestMiddlewares(next).ServeHTTP(w, r.WithContext(auth.WithAuthContext(r.Context(), ac))) + }) +} diff --git a/internal/server/oauth_login_http_test.go b/internal/server/oauth_login_http_test.go new file mode 100644 index 000000000..dfbf04718 --- /dev/null +++ b/internal/server/oauth_login_http_test.go @@ -0,0 +1,299 @@ +//go:build !server + +package server + +import ( + "net/http" + "net/url" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// T033: metadata and the 401 challenge, unknown client id -> 404 everywhere. +func TestOAuthLoginHTTP_MetadataAndChallenge(t *testing.T) { + f := newOAuthFlow(t, nil) + + as := f.get("/.well-known/oauth-authorization-server", nil) + require.Equal(t, http.StatusOK, as.Code) + body := decodeBody(t, as) + assert.Equal(t, oauthTestOrigin, body["issuer"]) + assert.Equal(t, oauthTestOrigin+"/oauth/token", body["token_endpoint"]) + assert.Equal(t, oauthTestOrigin+"/oauth/register", body["registration_endpoint"]) + assert.Equal(t, []any{"S256"}, body["code_challenge_methods_supported"]) + assert.Equal(t, []any{"none"}, body["token_endpoint_auth_methods_supported"]) + assert.Equal(t, "no-store", as.Header().Get("Cache-Control")) + + for _, c := range []struct{ meta, resource string }{ + {"/.well-known/oauth-protected-resource/mcp/oauth", "/mcp/oauth"}, + {"/.well-known/oauth-protected-resource/mcp/oauth/", "/mcp/oauth"}, + {"/.well-known/oauth-protected-resource/mcp/oauth/cursor", "/mcp/oauth/cursor"}, + } { + rec := f.get(c.meta, nil) + require.Equal(t, http.StatusOK, rec.Code, c.meta) + pr := decodeBody(t, rec) + assert.Equal(t, oauthTestOrigin+c.resource, pr["resource"], c.meta) + assert.Equal(t, []any{oauthTestOrigin}, pr["authorization_servers"], c.meta) + assert.Equal(t, []any{"header"}, pr["bearer_methods_supported"], c.meta) + } + + for _, path := range []string{"/mcp/oauth", "/mcp/oauth/", "/mcp/oauth/cursor"} { + rec := f.get(path, nil) + assert.Equal(t, http.StatusUnauthorized, rec.Code, path) + clientPart := strings.TrimSuffix(strings.TrimPrefix(path, "/mcp/oauth"), "/") + assert.Equal(t, `Bearer resource_metadata="`+oauthTestOrigin+`/.well-known/oauth-protected-resource/mcp/oauth`+clientPart+`"`, + rec.Header().Get("WWW-Authenticate"), path) + } + + // An unknown client id is 404 on the address and on its metadata. So is an + // address nested deeper than a client id. + for _, path := range []string{ + "/mcp/oauth/no-such-client", "/.well-known/oauth-protected-resource/mcp/oauth/no-such-client", + "/mcp/oauth/cursor/extra", "/.well-known/oauth-protected-resource/mcp/oauth/cursor/extra", + "/mcp/oauth/Bad_ID!", + } { + assert.Equal(t, http.StatusNotFound, f.get(path, nil).Code, path) + } +} + +// T034: register. +func TestOAuthLoginHTTP_Register(t *testing.T) { + f := newOAuthFlow(t, nil) + rec := f.postJSON("/oauth/register", `{"redirect_uris":["http://127.0.0.1:1/cb"],"client_name":"Cursor IDE","software_id":"x","software_version":"1"}`) + require.Equal(t, http.StatusCreated, rec.Code, rec.Body.String()) + body := decodeBody(t, rec) + assert.NotEmpty(t, body["client_id"]) + assert.NotContains(t, body, "client_secret") + assert.Equal(t, "none", body["token_endpoint_auth_method"]) + assert.Equal(t, []any{"authorization_code", "refresh_token"}, body["grant_types"]) + assert.Equal(t, []any{"code"}, body["response_types"]) + assert.Equal(t, "cursor ide", body["client_name"], "the reported name is sanitised") + assert.Equal(t, "no-store", rec.Header().Get("Cache-Control")) + + cases := map[string]struct{ body, code string }{ + "plain http non-loopback": {`{"redirect_uris":["http://example.com/cb"]}`, "invalid_redirect_uri"}, + "fragment": {`{"redirect_uris":["https://example.com/cb#x"]}`, "invalid_redirect_uri"}, + "custom scheme": {`{"redirect_uris":["cursor://callback"]}`, "invalid_redirect_uri"}, + "none": {`{}`, "invalid_redirect_uri"}, + "six": {`{"redirect_uris":["https://a.example/1","https://a.example/2","https://a.example/3","https://a.example/4","https://a.example/5","https://a.example/6"]}`, "invalid_redirect_uri"}, + "secret method": {`{"redirect_uris":["https://a.example/1"],"token_endpoint_auth_method":"client_secret_basic"}`, "invalid_client_metadata"}, + "grant type": {`{"redirect_uris":["https://a.example/1"],"grant_types":["client_credentials"]}`, "invalid_client_metadata"}, + "response type": {`{"redirect_uris":["https://a.example/1"],"response_types":["token"]}`, "invalid_client_metadata"}, + "not json": {`nope`, "invalid_client_metadata"}, + } + for name, c := range cases { + rec := f.postJSON("/oauth/register", c.body) + assert.Equal(t, http.StatusBadRequest, rec.Code, name) + assert.Equal(t, c.code, decodeBody(t, rec)["error"], name) + } + + // Method and size. + assert.Equal(t, http.StatusMethodNotAllowed, f.get("/oauth/register", nil).Code) + big := `{"redirect_uris":["https://a.example/1"],"client_name":"` + strings.Repeat("a", 17<<10) + `"}` + assert.Equal(t, http.StatusRequestEntityTooLarge, f.postJSON("/oauth/register", big).Code) +} + +func TestOAuthLoginHTTP_Register_RateLimited(t *testing.T) { + f := newOAuthFlow(t, nil) + f.limited = true + var limited bool + for i := 0; i < 20; i++ { + rec := f.postJSON("/oauth/register", `{"redirect_uris":["https://a.example/1"]}`) + if rec.Code == http.StatusTooManyRequests { + limited = true + assert.NotEmpty(t, rec.Header().Get("Retry-After")) + assert.Equal(t, "temporarily_unavailable", decodeBody(t, rec)["error"]) + break + } + } + assert.True(t, limited, "a burst past the register budget must answer 429 with Retry-After") +} + +// T034: authorize. +func TestOAuthLoginHTTP_Authorize(t *testing.T) { + f := newOAuthFlow(t, nil) + cb := "http://127.0.0.1:54321/callback?x=1" + regID := f.register(cb) + _, challenge := pkce() + resource := oauthTestOrigin + "/mcp/oauth/cursor" + check := func(h http.Header) { + t.Helper() + assert.Equal(t, "no-store", h.Get("Cache-Control")) + assert.Equal(t, "no-referrer", h.Get("Referrer-Policy")) + } + + // Success: 302 to the consent page. + rec := f.get(f.authorizeQuery(regID, cb, challenge, resource, "s"), nil) + require.Equal(t, http.StatusFound, rec.Code) + assert.True(t, strings.HasPrefix(rec.Header().Get("Location"), oauthTestOrigin+"/ui/authorize?request="), rec.Header().Get("Location")) + check(rec.Header()) + + // The loopback port is ignored at match time. + rec = f.get(f.authorizeQuery(regID, "http://127.0.0.1:9999/callback?x=1", challenge, resource, "s"), nil) + assert.Equal(t, http.StatusFound, rec.Code) + + // No redirect for an unknown client or an unregistered redirect URI. + for name, q := range map[string]string{ + "unknown client": f.authorizeQuery("nope", cb, challenge, resource, ""), + "other redirect": f.authorizeQuery(regID, "http://127.0.0.1:54321/other", challenge, resource, ""), + "remote redirect": f.authorizeQuery(regID, "https://evil.example/cb", challenge, resource, ""), + } { + rec := f.get(q, nil) + assert.Equal(t, http.StatusBadRequest, rec.Code, name) + assert.Empty(t, rec.Header().Get("Location"), name) + assert.Contains(t, rec.Header().Get("Content-Type"), "text/html", name) + check(rec.Header()) + } + + // An unknown per-client resource is a 404 page, never a redirect. + rec = f.get(f.authorizeQuery(regID, cb, challenge, oauthTestOrigin+"/mcp/oauth/no-such-client", "s"), nil) + assert.Equal(t, http.StatusNotFound, rec.Code) + assert.Empty(t, rec.Header().Get("Location")) + check(rec.Header()) + + // Redirectable errors keep the callback query and return state unchanged. + state := "a b&c=d/é?#" + rec = f.get(f.authorizeQuery(regID, cb, challenge, "https://other.example/mcp", state), nil) + require.Equal(t, http.StatusFound, rec.Code) + loc, err := url.Parse(rec.Header().Get("Location")) + require.NoError(t, err) + assert.Equal(t, "/callback", loc.Path) + assert.Equal(t, "1", loc.Query().Get("x"), "the existing callback query is kept") + assert.Equal(t, "invalid_target", loc.Query().Get("error")) + assert.Equal(t, state, loc.Query().Get("state"), "state comes back exactly as sent") + check(rec.Header()) + + // No state sent -> none returned. + rec = f.get(f.authorizeQuery(regID, cb, challenge, "https://other.example/mcp", ""), nil) + loc, _ = url.Parse(rec.Header().Get("Location")) + assert.False(t, loc.Query().Has("state")) + + // Wrong response_type and a missing challenge are redirectable too. + rec = f.get("/oauth/authorize?response_type=token&client_id="+regID+"&redirect_uri="+url.QueryEscape(cb)+"&resource="+url.QueryEscape(resource), nil) + loc, _ = url.Parse(rec.Header().Get("Location")) + assert.Equal(t, "unsupported_response_type", loc.Query().Get("error")) + rec = f.get("/oauth/authorize?response_type=code&client_id="+regID+"&redirect_uri="+url.QueryEscape(cb)+"&resource="+url.QueryEscape(resource), nil) + loc, _ = url.Parse(rec.Header().Get("Location")) + assert.Equal(t, "invalid_request", loc.Query().Get("error")) + + // POST is not an authorize method. + req, _ := http.NewRequest(http.MethodPost, "/oauth/authorize", http.NoBody) + assert.Equal(t, http.StatusMethodNotAllowed, f.do(req).Code) +} + +// T034: token, every row of the contract's error table. +func TestOAuthLoginHTTP_Token_Errors(t *testing.T) { + f := newOAuthFlow(t, nil) + regID := f.register(oauthTestRedirect) + verifier, challenge := pkce() + resource := oauthTestOrigin + "/mcp/oauth/cursor" + mint := func() string { + id := f.authorize(regID, oauthTestRedirect, challenge, resource) + return f.approve(id, "cursor") + } + + // unknown code + rec := f.exchange("mcp_code_unknown", regID, verifier, resource) + assert.Equal(t, 400, rec.Code) + assert.Equal(t, "no-store", rec.Header().Get("Cache-Control")) + assert.Equal(t, "invalid_grant", decodeBody(t, rec)["error"]) + + // wrong verifier, wrong client, wrong redirect: invalid_grant + rec = f.exchange(mint(), regID, strings.Repeat("w", 43), resource) + assert.Equal(t, "invalid_grant", decodeBody(t, rec)["error"], "wrong verifier") + rec = f.exchange(mint(), "other-client", verifier, resource) + assert.Equal(t, "invalid_grant", decodeBody(t, rec)["error"], "wrong client") + rec = f.postForm("/oauth/token", url.Values{ + "grant_type": {"authorization_code"}, "code": {mint()}, "redirect_uri": {"http://127.0.0.1:54321/elsewhere"}, + "client_id": {regID}, "code_verifier": {verifier}, + }) + assert.Equal(t, "invalid_grant", decodeBody(t, rec)["error"], "wrong redirect uri") + + // resource substitution -> invalid_target + code := mint() + rec = f.exchange(code, regID, verifier, oauthTestOrigin+"/mcp/oauth/windsurf") + assert.Equal(t, 400, rec.Code) + assert.Equal(t, "invalid_target", decodeBody(t, rec)["error"]) + + // origin mismatch: invalid_grant and the code is NOT consumed + code = mint() + other := *f + other.host = "localhost:8080" + rec = other.exchange(code, regID, verifier, resource) + assert.Equal(t, "invalid_grant", decodeBody(t, rec)["error"], "origin mismatch") + rec = f.exchange(code, regID, verifier, resource) + require.Equal(t, 200, rec.Code, "the code survives a request from another origin: %s", rec.Body.String()) + + // a reused code revokes the login it produced + access, _ := decodeBody(t, rec)["access_token"].(string) + assert.Equal(t, http.StatusOK, f.get("/mcp/oauth/cursor", bearer(access)).Code) + rec = f.exchange(code, regID, verifier, resource) + assert.Equal(t, "invalid_grant", decodeBody(t, rec)["error"], "reuse") + assert.Equal(t, http.StatusUnauthorized, f.get("/mcp/oauth/cursor", bearer(access)).Code, "reuse revokes the login") + + // grant types + rec = f.postForm("/oauth/token", url.Values{"grant_type": {"password"}}) + assert.Equal(t, 400, rec.Code) + assert.Equal(t, "unsupported_grant_type", decodeBody(t, rec)["error"]) + rec = f.postForm("/oauth/token", url.Values{}) + assert.Equal(t, "unsupported_grant_type", decodeBody(t, rec)["error"]) + + // content type, size and method + req, _ := http.NewRequest(http.MethodPost, "/oauth/token", strings.NewReader(`{}`)) + req.Header.Set("Content-Type", "application/json") + assert.Equal(t, 400, f.do(req).Code) + big := url.Values{"grant_type": {"authorization_code"}, "code": {strings.Repeat("a", 17<<10)}} + assert.Equal(t, http.StatusRequestEntityTooLarge, f.postForm("/oauth/token", big).Code) + assert.Equal(t, http.StatusMethodNotAllowed, f.get("/oauth/token", nil).Code) +} + +func TestOAuthLoginHTTP_Token_RefreshRules(t *testing.T) { + f := newOAuthFlow(t, nil) + regID, tok := f.login("cursor") + + // malformed, bad MAC, unknown, wrong client: one indistinguishable answer + forged := tok.refresh[:len(tok.refresh)-4] + "AAAA" + for name, r := range map[string]string{"malformed": "nonsense", "bad mac": forged, "empty": ""} { + rec := f.refreshWith(regID, r) + assert.Equal(t, 400, rec.Code, name) + assert.Equal(t, "invalid_grant", decodeBody(t, rec)["error"], name) + } + rec := f.refreshWith("some-other-client", tok.refresh) + assert.Equal(t, "invalid_grant", decodeBody(t, rec)["error"], "wrong client") + + // resource substitution + rec = f.postForm("/oauth/token", url.Values{ + "grant_type": {"refresh_token"}, "refresh_token": {tok.refresh}, "client_id": {regID}, + "resource": {oauthTestOrigin + "/mcp/oauth/windsurf"}, + }) + assert.Equal(t, "invalid_target", decodeBody(t, rec)["error"]) + + // rotation: the new pair works, the old refresh token is an authentic replay + // that revokes the login. + rec = f.refreshWith(regID, tok.refresh) + require.Equal(t, 200, rec.Code, rec.Body.String()) + next := decodeBody(t, rec) + assert.NotEqual(t, tok.refresh, next["refresh_token"]) + newAccess, _ := next["access_token"].(string) + assert.Equal(t, http.StatusOK, f.get("/mcp/oauth/cursor", bearer(newAccess)).Code) + rec = f.refreshWith(regID, tok.refresh) + assert.Equal(t, "invalid_grant", decodeBody(t, rec)["error"], "replay") + assert.Equal(t, http.StatusUnauthorized, f.get("/mcp/oauth/cursor", bearer(newAccess)).Code, "a replay revokes the login") +} + +func TestOAuthLoginHTTP_Token_RateLimited(t *testing.T) { + f := newOAuthFlow(t, nil) + f.limited = true + var limited bool + for i := 0; i < 40; i++ { + rec := f.postForm("/oauth/token", url.Values{"grant_type": {"authorization_code"}}) + if rec.Code == http.StatusTooManyRequests { + limited = true + assert.NotEmpty(t, rec.Header().Get("Retry-After")) + break + } + } + assert.True(t, limited) +} diff --git a/internal/server/oauth_login_routes.go b/internal/server/oauth_login_routes.go index 582dec735..dc6655f4a 100644 --- a/internal/server/oauth_login_routes.go +++ b/internal/server/oauth_login_routes.go @@ -1,7 +1,6 @@ package server import ( - "encoding/json" "net/http" "net/netip" @@ -43,13 +42,16 @@ func peerIsLoopback(r *http.Request) bool { } // oauthLoginEverUsedNow reports whether browser login has ever been used on -// this install. It is injectable for tests. -// TODO(Spec 132): read the storage marker `oauth_login_ever_used` once the -// storage slice lands; until then the feature can never have been used. +// this install: the storage marker `oauth_login_ever_used`, read through the +// service (only a positive answer is cached; a read never writes). It is +// injectable for tests. func (s *Server) oauthLoginEverUsedNow() bool { if s.oauthLoginEverUsed != nil { return s.oauthLoginEverUsed() } + if svc := s.oauthLoginSvc(); svc != nil { + return svc.EverUsed() + } return false } @@ -79,28 +81,17 @@ func (s *Server) oauthLoginGate(prev, served http.Handler) http.Handler { }) } -// oauthLoginNotImplemented is the `served` stub of this slice. -func oauthLoginNotImplemented() http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusNotImplemented) - _ = json.NewEncoder(w).Encode(map[string]string{ - "error": "not_implemented", - "error_description": "browser login (mcp_oauth_enabled) is not functional in this release", - }) - }) -} - // registerOAuthLoginRoutes registers the browser-login patterns on mux. // mcpHandler is the existing /mcp/ catch-all chain, rootHandler the existing -// "/" handler; each is the off-state fallback of its patterns. -func (s *Server) registerOAuthLoginRoutes(mux *http.ServeMux, mcpHandler, rootHandler http.Handler) { - served := oauthLoginNotImplemented() - mcpGate := s.oauthLoginGate(mcpHandler, served) +// "/" handler; each is the off-state fallback of its patterns. oauthMCP is the +// MCP chain served on /mcp/oauth* while the feature is on (it authenticates +// mcp_oat_ access tokens itself, see oauthResourceAuth). +func (s *Server) registerOAuthLoginRoutes(mux *http.ServeMux, mcpHandler, rootHandler, oauthMCP http.Handler) { + mcpGate := s.oauthLoginGate(mcpHandler, oauthMCP) for _, p := range oauthLoginMCPPatterns { mux.Handle(p, mcpGate) } - rootGate := s.oauthLoginGate(rootHandler, served) + rootGate := s.oauthLoginGate(rootHandler, s.oauthLoginPublicHandler()) for _, p := range oauthLoginRootPatterns { mux.Handle(p, rootGate) } diff --git a/internal/server/oauth_login_toggle_test.go b/internal/server/oauth_login_toggle_test.go new file mode 100644 index 000000000..b635ba4db --- /dev/null +++ b/internal/server/oauth_login_toggle_test.go @@ -0,0 +1,110 @@ +//go:build !server + +package server + +import ( + "encoding/json" + "net/http" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" +) + +// T038: on -> off after use answers 404 on every OAuth path; off -> on brings +// the logins back; the switch needs no restart. +func TestOAuthLoginToggle_OffAfterUse404_OnRestores(t *testing.T) { + f := newOAuthFlow(t, nil) + _, tok := f.login("cursor") + + f.setEnabled(false) + for _, path := range oauthLoginGatedPaths { + for _, method := range []string{http.MethodGet, http.MethodPost} { + req, _ := http.NewRequest(method, path, http.NoBody) + assert.Equal(t, http.StatusNotFound, f.do(req).Code, method+" "+path) + } + } + assert.Equal(t, http.StatusNotFound, f.get("/mcp/oauth/cursor", bearer(tok.access)).Code) + + f.setEnabled(true) + assert.Equal(t, http.StatusOK, f.get("/mcp/oauth/cursor", bearer(tok.access)).Code) + assert.Equal(t, http.StatusOK, f.get("/.well-known/oauth-authorization-server", nil).Code) +} + +// T038: switching off cancels pending AND approved requests with their +// unconsumed codes, synchronously with the config apply, and a quick off -> on +// leaves no approved request usable. +func TestOAuthLoginToggle_OffCancelsPendingAndApproved(t *testing.T) { + f := newOAuthFlow(t, nil) + regID := f.register(oauthTestRedirect) + verifier, challenge := pkce() + resource := f.origin() + "/mcp/oauth/cursor" + pending := f.authorize(regID, oauthTestRedirect, challenge, resource) + approvedID := f.authorize(regID, oauthTestRedirect, challenge, resource) + code := f.approve(approvedID, "cursor") + + svc := f.srv.oauthLoginSvc() + require.Len(t, svc.ListPending(), 1) + + // A quick off -> on, back to back, with no pause for any event. + f.setEnabled(false) + f.setEnabled(true) + + assert.Empty(t, svc.ListPending(), "pending requests are cancelled") + _, err := svc.Approve(adminCtx(), pending, runtime.ApprovalChoice{Client: runtime.ClientChoice{ID: "cursor"}}) + assert.Error(t, err, "a cancelled pending request cannot be approved") + rec := f.exchange(code, regID, verifier, resource) + assert.Equal(t, http.StatusBadRequest, rec.Code, "an approved code does not survive off -> on") + assert.Equal(t, "invalid_grant", decodeBody(t, rec)["error"]) + // Nothing was stored. + grants, err := svc.ListGrants("cursor") + require.NoError(t, err) + assert.Empty(t, grants) +} + +// T038: the same cancellation holds on the file-reload path. +func TestOAuthLoginToggle_FileReloadCancels(t *testing.T) { + f := newOAuthFlow(t, nil) + regID := f.register(oauthTestRedirect) + verifier, challenge := pkce() + resource := f.origin() + "/mcp/oauth/cursor" + id := f.authorize(regID, oauthTestRedirect, challenge, resource) + code := f.approve(id, "cursor") + + cfg := f.srv.runtime.Config() + require.NotNil(t, cfg) + off := *cfg + off.MCPOAuthEnabled = false + raw, err := json.Marshal(&off) + require.NoError(t, err) + path := filepath.Join(t.TempDir(), "mcp_config.json") + f.srv.runtime.UpdateConfig(cfg, path) // point the runtime at the file (still on); this writes the file + require.NoError(t, os.WriteFile(path, raw, 0o600)) + require.NoError(t, f.srv.runtime.ReloadConfiguration()) + + require.False(t, f.srv.runtime.Config().MCPOAuthEnabled, "the reload switched the feature off") + f.setEnabled(true) + rec := f.exchange(code, regID, verifier, resource) + assert.Equal(t, "invalid_grant", decodeBody(t, rec)["error"], "the code was cancelled by the reload itself") +} + +// T038: forgetting the last client keeps the 404 of an off-after-use install. +func TestOAuthLoginToggle_ForgettingLastClientKeepsOff404(t *testing.T) { + f := newOAuthFlow(t, nil) + f.login("cursor") + + clients := f.srv.runtime.ClientsService() + require.NotNil(t, clients) + _, err := clients.Forget(adminCtx(), runtime.Actor{}, "cursor", false) + require.NoError(t, err) + + f.setEnabled(false) + for _, path := range oauthLoginGatedPaths { + assert.Equal(t, http.StatusNotFound, f.get(path, nil).Code, path) + } + assert.True(t, f.srv.oauthLoginEverUsedNow(), "the marker is never cleared") +} diff --git a/internal/server/server.go b/internal/server/server.go index 15f9184a1..d9edc704b 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -31,6 +31,7 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/httpapi" "github.com/smart-mcp-proxy/mcpproxy-go/internal/logs" "github.com/smart-mcp-proxy/mcpproxy-go/internal/management" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" "github.com/smart-mcp-proxy/mcpproxy-go/internal/oauth" "github.com/smart-mcp-proxy/mcpproxy-go/internal/observability" "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" @@ -125,6 +126,10 @@ type Server struct { // oauthLoginEverUsed reports whether browser login was ever used on this // install (Spec 132). nil means never; tests inject it. oauthLoginEverUsed func() bool + // oauthLimiter rate limits the public browser-login endpoints (Spec 132); + // built on first use so a default-off install never allocates it. + oauthLimiterOnce sync.Once + oauthLimiter *mcplogin.Limiter // createAfterConfigRead is a Spec 116 test seam (nil in production): it // runs in the create path after the runtime configuration was read and // before the new server is published. @@ -591,6 +596,19 @@ func (s *Server) logQueryAPIKeyRejection(r *http.Request) { zap.String("path", r.URL.Path)) } +// mcpRequestMiddlewares wraps next in the per-request middlewares every MCP +// route shares, whichever way the request authenticated (mcpAuthMiddleware and +// the browser-login resource chain, Spec 132, both use it). +func mcpRequestMiddlewares(next http.Handler) http.Handler { + next = directRequestKindMiddleware(next) + // Spec 124 FR-003: the run name header, for MCP over HTTP. + next = runNameMiddleware(next) + // Spec 058 US3 (R1): drop a modern client's separately posted + // notifications/cancelled before mcp-go can match it against another + // client's in-flight request — every modern request shares session id "". + return modernCancellationGuard(next) +} + // mcpAuthMiddleware wraps the MCP endpoint handler to inject AuthContext into the // request context. The MCP endpoint is not behind the REST API key middleware, so // this middleware extracts tokens from the request and creates the appropriate @@ -618,13 +636,7 @@ func (s *Server) mcpAuthMiddleware(next http.Handler) http.Handler { // automatically, on top of whatever AuthContext that branch attaches. // Harmless on every endpoint but /mcp/all, whose filters are the only // consumers. - next = directRequestKindMiddleware(next) - // Spec 124 FR-003: the run name header, for MCP over HTTP. - next = runNameMiddleware(next) - // Spec 058 US3 (R1): drop a modern client's separately posted - // notifications/cancelled before mcp-go can match it against another - // client's in-flight request — every modern request shares session id "". - next = modernCancellationGuard(next) + next = mcpRequestMiddlewares(next) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // mcp_reject_query_apikey: refuse a URL-borne credential outright. It // must be a 401 and not "no token": with require_mcp_auth off a request @@ -673,6 +685,15 @@ func (s *Server) mcpAuthMiddleware(next http.Handler) http.Handler { return } + // Spec 132: a browser-login access token is valid only on its own + // /mcp/oauth address (audience binding). Anywhere else it is refused, + // also with require_mcp_auth off, but only while the feature is on or + // was used: with it off and never used every answer is the previous one. + if mcplogin.IsAccessToken(token) && s.oauthLoginLive() { + http.Error(w, `{"error":"This token is not valid for this endpoint."}`, http.StatusUnauthorized) + return + } + // Check if this is an agent token OR a Spec 108-c client credential // (mcp_cli_): both authenticate on MCP through the same validator // (storage.ValidateAgentToken), which enforces the FR-021 fail-closed @@ -3575,6 +3596,7 @@ func (s *Server) startCustomHTTPServer(ctx context.Context, streamableServer *se connectSvc.WithCredentialMinter(clients.ConnectMinter()) clients.SetConfigReader(connectSvc) httpAPIServer.SetClientsService(clients) + httpAPIServer.SetOAuthLoginService(s.runtime.OAuthLoginService()) go func() { if err := clients.Reconcile(s.runtime.AppContext()); err != nil { s.logger.Warn("client rotation reconcile failed", zap.Error(err)) @@ -3771,7 +3793,8 @@ func (s *Server) startCustomHTTPServer(ctx context.Context, streamableServer *se mux.Handle("/", rootHandler) // Spec 132: opt-in browser login. Behaves exactly like the handlers above // until mcp_oauth_enabled is switched on (or the feature has been used). - s.registerOAuthLoginRoutes(mux, mcpHandler, rootHandler) + oauthMCPHandler := s.streamingNoDeadline(s.hostValidationMiddleware(tagMCP(s.oauthResourceAuth(loggingHandler(streamableServer))))) + s.registerOAuthLoginRoutes(mux, mcpHandler, rootHandler, oauthMCPHandler) s.logger.Info("Registered Web UI endpoints", zap.Strings("ui_endpoints", []string{"/ui/", "/"})) // Determine actual TCP address for logging diff --git a/oas/docs.go b/oas/docs.go index 7fc4734a5..bfb1dde23 100644 --- a/oas/docs.go +++ b/oas/docs.go @@ -6,10 +6,10 @@ import "github.com/swaggo/swag/v2" const docTemplate = `{ "schemes": {{ marshal .Schemes }}, - "components": {"schemas":{"auth.CredentialIssuer":{"properties":{"actor_kind":{"type":"string"},"actor_name":{"type":"string"},"surface":{"type":"string"}},"type":"object"},"config.AgentTokenRateLimit":{"description":"AgentTokenRateLimit caps how many upstream tool calls ONE agent token may\nmake: PerMinute on average, Burst at once (issue #1699). Every token is\ncounted separately, and a token's own rate_limit (set when it is created)\nreplaces this default for that token. Only agent-token callers are\nlimited; the admin API key, the unix socket and an unauthenticated /mcp\ncaller are not. Absent or per_minute 0 = no limit (default, zero behavior\nchange). The counters are in memory: a restart gives every token a full\nallowance again. Hot-reloadable. File/API-configured only, no env scheme.","properties":{"burst":{"description":"Burst is how many calls a token may make at once after a quiet spell.\n0 = the PerMinute value.","type":"integer"},"per_minute":{"description":"PerMinute is the sustained rate. 0 = no limit.","type":"integer"}},"type":"object"},"config.AuditLogConfig":{"description":"AuditLog configures the Spec 107 edition-neutral audit sink\n(internal/audit). nil means \"use the per-edition/per-transport\ndefault\" (EffectiveAuditLog); restart-pinned (bound at sink\nconstruction). See audit_log.go.","properties":{"compress":{"type":"boolean"},"enabled":{"type":"boolean"},"max_age_days":{"type":"integer"},"max_backups":{"type":"integer"},"max_size_mb":{"type":"integer"},"path":{"type":"string"},"stdout":{"type":"boolean"}},"type":"object"},"config.ConcurrencyDefaults":{"description":"ServerConcurrencyDefaults is scope (b) of FR-020: the blanket per-server\ndefault set inherited by every server that does not override a setting.\nAbsent (the default) = no per-server limiting unless a server configures\nit explicitly. File/API-configured only — no env scheme (FR-022).","properties":{"max_concurrent_requests":{"type":"integer"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"}},"type":"object"},"config.Config":{"properties":{"activity_cleanup_interval_min":{"description":"Background cleanup interval in minutes (default: 60)","type":"integer"},"activity_max_records":{"description":"Max records before pruning (default: 400000)","type":"integer"},"activity_max_response_size":{"description":"Response truncation limit in bytes (default: 65536)","type":"integer"},"activity_max_size_mb":{"description":"ActivityMaxSizeMB caps the total activity-log size in MB before the\noldest records are pruned. Omit the key for the 256MB default; set it to\n0 to disable the size cap.","type":"integer"},"activity_retention_days":{"description":"Activity logging settings (RFC-003)","type":"integer"},"advertise_upstream_servers":{"description":"AdvertiseUpstreamServers controls whether MCP clients are told the\nnames of the upstream servers they can reach — in the initialize\ninstructions and the retrieve_tools description — so agents use the\nproxied tools instead of falling back to shell CLIs. Names are always\nfiltered to the caller's profile and agent-token scope. Default true;\nset false to keep server names out of client context. Read live.","type":"boolean"},"agent_token_rate_limit":{"$ref":"#/components/schemas/config.AgentTokenRateLimit"},"aggregate_upstream_prompts":{"description":"AggregateUpstreamPrompts, when true, aggregates every connected upstream\nserver's advertised MCP prompts into mcpproxy's own prompts/list\n(exposed as \"\u003cserver\u003e__\u003cprompt\u003e\"). OFF by default: users are safe by\ndefault and opt in deliberately. EnablePrompts still governs the built-in\nprompts + the prompts capability; this flag gates ONLY the upstream\naggregation performed by RefreshPrompts. Hot-reloadable.","type":"boolean"},"allow_private_registry_fetch":{"description":"AllowPrivateRegistryFetch opts out of the registry SSRF guard (MCP-1076,\nCWE-918). By default (false) registry fetches refuse any host that is — or\nresolves to — a non-routable address (loopback, RFC1918/CGNAT private,\nlink-local incl. the 169.254.169.254 cloud-metadata endpoint), so a\nmalicious or typo'd registry source cannot turn the daemon into a\nrequest-forgery vector against internal services.\n\nThis opt-out is BLANKET (all-or-nothing): setting it true disables the\nguard for EVERY non-routable range at once — loopback, RFC1918/CGNAT\nprivate, link-local AND the 169.254.169.254 cloud-metadata endpoint. There\nis no way to allow only loopback; enabling it for a localhost dev registry\nalso re-opens the cloud-metadata SSRF vector. Set true ONLY when you\nintentionally run a trusted registry mirror on an internal/private address,\nideally on a host with no cloud-metadata exposure. The change takes effect\nonly on daemon (re)start or config reload.","type":"boolean"},"allow_server_add":{"type":"boolean"},"allow_server_remove":{"type":"boolean"},"anonymous_profile":{"description":"AnonymousProfile confines every caller whose request authenticates as\ncredential kind \"anonymous\" (no credential, or an unrecognised\nnon-agent token accepted by the require_mcp_auth:false back-compat\nbranch) to the named profile (Spec 108 FR-008). Empty (default) means\nunconfined, legacy anonymous behaviour. A name that does not match any\nconfigured profile resolves anonymous callers to deny-all and is\nreported as a validation warning (data-model.md §1).","type":"string"},"api_key":{"description":"Security settings","type":"string"},"audit_log":{"$ref":"#/components/schemas/config.AuditLogConfig"},"call_tool_timeout":{"type":"string"},"check_server_repo":{"description":"Repository detection settings","type":"boolean"},"code_execution_max_parallel":{"description":"Default concurrency for call_tools() batches (1-32, default: 8)","type":"integer"},"code_execution_max_tool_calls":{"description":"Max tool calls per execution (0 = unlimited, default: 0)","type":"integer"},"code_execution_pool_size":{"description":"JavaScript runtime pool size (default: 10)","type":"integer"},"code_execution_timeout_ms":{"description":"Timeout in milliseconds (default: 120000, max: 600000)","type":"integer"},"data_dir":{"type":"string"},"debug_search":{"type":"boolean"},"direct_tool_response_mode":{"description":"DirectToolResponseMode selects the serialization of the DIRECT\nenumeration surface (Spec 102). Valid values: \"\" (= full), \"full\"\n(default: today's schema-bearing entries), \"deferred\" (description +\ncompact signature, with a minimal permissive input schema; upstream\ninputSchema and outputSchema are stripped and recovered on demand via\ndescribe_tool).\n\nDeliberately NOT an extension of tool_response_mode: reusing that axis\nwould silently change /mcp/all output for every deployment already\nrunning compact, which FR-015 forbids. Serialization-only — it never\nchanges WHICH tools are listed, only how (FR-008). Hot-reloadable.","type":"string"},"disable_management":{"type":"boolean"},"docker_isolation":{"$ref":"#/components/schemas/config.DockerIsolationConfig"},"docker_recovery":{"$ref":"#/components/schemas/config.DockerRecoveryConfig"},"enable_code_execution":{"description":"Code execution settings","type":"boolean"},"enable_prompts":{"description":"Prompts settings","type":"boolean"},"enable_skills":{"description":"EnableSkills, when true, makes mcpproxy read the skills that upstream\nservers expose through the MCP skills extension. OFF by default. Unlike\nEnablePrompts this is hot-reloadable. No CLI flag, no environment\nvariable.","type":"boolean"},"enable_socket":{"description":"Enable Unix socket/named pipe for local IPC (default: true)","type":"boolean"},"enable_tray":{"description":"Deprecated: EnableTray is unused and has no runtime effect. Kept for backward compatibility.","type":"boolean"},"environment":{"$ref":"#/components/schemas/secureenv.EnvConfig"},"features":{"$ref":"#/components/schemas/config.FeatureFlags"},"forward_client_headers":{"description":"ForwardClientHeaders is the global switch for client header forwarding\n(Spec 112): copying allowlisted headers from the inbound /mcp request into\nthe upstream tools/call request. nil (absent) means enabled; because every\nper-server forward_headers allowlist is empty by default, the default\nforwards nothing. false disables forwarding for every server. Read via\nIsClientHeaderForwardingEnabled(); MCPPROXY_FORWARD_CLIENT_HEADERS\noverrides it for the process. Distinct from ForwardedHeaders/trusted_proxies\n(Spec 107), which trusts inbound X-Forwarded-*.","type":"boolean"},"forward_proxy_env":{"description":"ForwardProxyEnv opts in to forwarding the ambient HTTP(S)/ALL/NO/FTP proxy\nenvironment variables to spawned stdio upstream servers (MCP-2769). OFF by\ndefault: proxy URLs commonly embed credentials (http://user:pass@proxy), so\nforwarding them to every upstream is a credential-leak risk. When enabled,\nvalues are forwarded with their userinfo (credentials) redacted.","type":"boolean"},"health_check_interval":{"description":"Discovery \u0026 health-check cadence (spec 074, #608). Both are *Duration\ntri-state pointers: nil = inherit the built-in default; a pointer to 0s =\nthe loop is disabled; a positive value = that interval. Defaults live only\nin the resolvers (ResolveHealthCheckInterval / ResolveToolDiscoveryInterval)\nso an unset key behaves exactly as before this feature (SC-005). Validated\nin Validate(): health-check ∈ {0} ∪ [5s,1h]; tool-discovery ∈ {0} ∪ [30s,24h].","type":"string"},"http_idle_timeout":{"description":"HTTPIdleTimeout caps how long an idle keep-alive connection is kept open.\nUnset = 180s. \"0s\" removes the dedicated idle deadline, but net/http then\nfalls back to ReadTimeout — idle is fully unbounded only when\nhttp_read_timeout is also \"0s\". Requires a restart.","type":"string"},"http_read_timeout":{"description":"HTTPReadTimeout caps how long reading a whole request (headers + body)\nmay take. Unset = 120s; \"0s\" disables it. Requires a restart.","type":"string"},"http_write_timeout":{"description":"HTTPWriteTimeout caps how long producing a whole response may take on\nnon-streaming endpoints (REST, Web UI, health). Unset = 120s; \"0s\"\ndisables it globally. MCP and SSE /events routes are exempt by design.","type":"string"},"init_timeout":{"description":"InitTimeout is the global default deadline for an upstream's MCP\n` + "`" + `initialize` + "`" + ` handshake (MCP-3322 / GH #760). *Duration tri-state: nil =\ninherit the built-in 30s default; a positive value = that deadline. A\nper-server InitTimeout overrides this. Resolved by ResolveInitTimeout;\nvalidated to {0} ∪ [1s, 30m] in Validate(). Servers doing legitimate\nfirst-run warmup (cache/index build) before answering ` + "`" + `initialize` + "`" + ` can\nraise this so they are not killed mid-startup.","type":"string"},"instructions":{"description":"Instructions text returned in the MCP initialize response to guide AI agents.\nWhen empty, a built-in default is used that explains retrieve_tools workflow.","type":"string"},"intent_declaration":{"$ref":"#/components/schemas/config.IntentDeclarationConfig"},"listen":{"type":"string"},"logging":{"$ref":"#/components/schemas/config.LogConfig"},"max_concurrent_requests":{"description":"Concurrency limits (spec 093, GH #955). Scope (a) of FR-020: the GLOBAL\nAGGREGATE limiter — one proxy-wide cap on concurrently running upstream\ntool calls, with its own bounded wait queue. Tri-state pointers: absent =\nthe limiter does not exist (default, zero behavior change); an explicit 0\nmax also disables it; positive = that cap. This scope is NEVER a\nper-server inheritance source — per-server values come from\nServerConcurrencyDefaults / the per-server overrides — but a server's\neffective concurrency is bounded by BOTH its own limiter and this one.\nResolved by ResolveGlobalConcurrency; hot-reloadable; overridable via\nMCPPROXY_MAX_CONCURRENT_REQUESTS / _QUEUE_SIZE / _QUEUE_TIMEOUT (FR-022).","type":"integer"},"max_result_size_chars":{"description":"MaxResultSizeChars is advertised on every tool as\n` + "`" + `_meta.anthropic/maxResultSizeChars` + "`" + `; it raises Claude Code's\ninline-response ceiling from 50k to up to 500k chars. Omit the key for\nthe 500000 default; set it to 0 to disable the annotation.","type":"integer"},"mcpServers":{"items":{"$ref":"#/components/schemas/config.ServerConfig"},"type":"array","uniqueItems":false},"mcp_oauth_enabled":{"description":"MCPOAuthEnabled turns on browser login (OAuth 2.1 + PKCE) for MCP\nclients on the loopback listener (Spec 132). Experimental, default false:\nwith it off nothing changes. Env override MCPPROXY_MCP_OAUTH_ENABLED is\nprocess-only and never persisted. Live, no restart needed.","type":"boolean"},"mcp_reject_query_apikey":{"description":"MCPRejectQueryAPIKey makes every MCP endpoint (/mcp*) refuse a request that\ncarries a ?apikey= query parameter, with a 401, instead of honouring it. A credential in a URL ends up in access logs,\nproxy logs and browser history; MCP clients can send Authorization:\nBearer or X-API-Key instead. Default false (the query form keeps\nworking, for clients that can only configure a URL). It covers only the\nMCP endpoints: the Web UI and its SSE stream (/events) still use the\nquery form. Live, no restart needed.","type":"boolean"},"oauth_expiry_warning_hours":{"description":"Health status settings","type":"number"},"oauth_token_encryption_key":{"description":"OAuthTokenEncryptionKey seals the upstream OAuth tokens stored in\nconfig.db (Spec 123). Empty (the default) leaves them as plain JSON. It\ntakes a secret reference (${file:/abs/path}, ${env:NAME},\n${keyring:NAME}) or a literal standard-base64 32-byte key; the\nMCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY[_FILE] variables override it. The key\nis resolved only where config.db is opened (ResolveOAuthTokenKey), never\nstored on Config, and is restart-gated, so every save writes the field\nas configured.","type":"string"},"observability":{"$ref":"#/components/schemas/config.ObservabilityConfig"},"output_sanitisation":{"$ref":"#/components/schemas/config.OutputSanitisationConfig"},"output_validation":{"$ref":"#/components/schemas/config.OutputValidationConfig"},"profiles":{"description":"Profiles are optional named, server-scoped views exposed at /mcp/p/\u003cname\u003e\n(Spec 057). Absent/empty is fully supported — /mcp is unchanged and configs\nwithout this key serialize byte-identically (SC-004).","items":{"$ref":"#/components/schemas/config.ProfileConfig"},"type":"array","uniqueItems":false},"quarantine_enabled":{"description":"QuarantineEnabled controls whether quarantine is active. It gates two\nthings together:\n 1. Server-level auto-quarantine for newly added servers (issue #370).\n When true, servers added via the upstream_servers MCP tool or the\n REST API default to quarantined=true; when false, they default to\n quarantined=false. Explicit per-request values always win.\n 2. Tool-level quarantine (Spec 032): per-tool SHA-256 approval of\n tool descriptions/schemas.\nWhen nil (default), quarantine is enabled (secure by default). Set to\nexplicit false to opt out of both. Per-server SkipQuarantine still\napplies for the tool-level check on individual servers.","type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"read_only_mode":{"type":"boolean"},"registries":{"description":"Registries configuration for MCP server discovery","items":{"$ref":"#/components/schemas/config.RegistryEntry"},"type":"array","uniqueItems":false},"registries_locked":{"description":"RegistriesLocked is an enterprise stub knob (MCP-866): when true, runtime\nadditions of custom registries (e.g. ` + "`" + `registry add-source` + "`" + `, the REST/MCP\nadd-source surface) are rejected so an administrator can pin the discovery\nsources. Built-in defaults are unaffected. Documented but otherwise inert\nbeyond the add-source rejection.","type":"boolean"},"require_mcp_auth":{"description":"Require authentication on /mcp endpoint (default: false)","type":"boolean"},"reveal_secret_headers":{"description":"RevealSecretHeaders, when true, disables the redaction of the\nsecret-bearing server fields — sensitive header values (Authorization,\nX-API-Key, Cookie, …), env-var secrets, and URL query credentials — in\nresponses from the ` + "`" + `upstream_servers` + "`" + ` MCP tool, the ` + "`" + `/api/v1/servers` + "`" + `\nREST API, and the SSE event stream. It also lets URL secrets echoed\ninto last_error / health.detail through unscrubbed.\n\nDefault false — sensitive values are surfaced masked as\n` + "`" + `••••\u003clast2\u003e (\u003cN\u003e chars)` + "`" + ` (error strings use ` + "`" + `***REDACTED***` + "`" + `) so an\nMCP agent cannot read Bearer tokens / API keys / URL secrets out of\nanother upstream's config (PR #425, issue #872). ${env:…}/${keyring:…}\nreferences are labels, not secrets, and pass through unchanged.\n\nThe Web UI / macOS tray edit forms work without seeing the real\nvalues: PATCH /api/v1/servers/{id} deep-merges (omitted keys are\npreserved, see ` + "`" + `headers_remove` + "`" + ` / ` + "`" + `env_remove` + "`" + ` for explicit\ndeletes), so clients compute a diff and only send the keys that\nactually changed. Redacted-but-unchanged values never round-trip\n— the backend keeps the real string. Set this to true if a\ndownstream tool genuinely needs raw values in the response.","type":"boolean"},"routing_mode":{"description":"Routing mode (Spec 031): how MCP tools are exposed to clients\nValid values: \"retrieve_tools\" (default), \"direct\", \"code_execution\"","type":"string"},"security":{"$ref":"#/components/schemas/config.SecurityConfig"},"sensitive_data_detection":{"$ref":"#/components/schemas/config.SensitiveDataDetectionConfig"},"server_concurrency_defaults":{"$ref":"#/components/schemas/config.ConcurrencyDefaults"},"session_retention_days":{"description":"SessionRetentionDays is how long a work session is listed and kept whole\nin the activity log (Spec 124, default 7). Read at start.","type":"integer"},"telemetry":{"$ref":"#/components/schemas/config.TelemetryConfig"},"tls":{"$ref":"#/components/schemas/config.TLSConfig"},"tokenizer":{"$ref":"#/components/schemas/config.TokenizerConfig"},"tool_call_max_records_per_server":{"description":"Calls retained per server (default: 1000)","type":"integer"},"tool_call_max_response_size":{"description":"Bounds for the per-server tool-call history behind GET /api/v1/tool-calls\n(#1176). It is a recent-debugging window, not an audit log — the activity\nlog is the durable record — and it kept every upstream response whole,\nper server, forever. A non-positive value means \"use the default\", not\n\"disable\": this store must never be unbounded again, so there is\ndeliberately no off switch.","type":"integer"},"tool_discovery_interval":{"type":"string"},"tool_response_limit":{"type":"integer"},"tool_response_mode":{"description":"Tool response mode (Spec 085): how retrieve_tools serializes results.\nValid values: \"\" (= full), \"full\" (default: today's schema-bearing\nentries), \"compact\" (signature + first-sentence entries). Orthogonal to\nrouting_mode — routing_mode selects the tool SURFACE, this selects the\nSERIALIZATION within the retrieve_tools surface. Serialization-only: it\nnever affects the query, ranking, or result set. Hot-reloadable.","type":"string"},"tool_response_session_risk_warning":{"description":"ToolResponseSessionRiskWarning controls whether the prose ` + "`" + `warning` + "`" + ` field\nis included in the ` + "`" + `session_risk` + "`" + ` object returned by ` + "`" + `retrieve_tools` + "`" + `.\nThe structured fields (level, lethal_trifecta, has_open_world_tools, etc.)\nare always included. Default: false (quiet for LLM clients) — see issue #406.\nMost tools lack annotations, so the MCP-spec defaults treat them as fully\npermissive across all three risk axes, which makes the prose warning fire\non almost every call and wastes tokens.","type":"boolean"},"tools_limit":{"type":"integer"},"toon_min_savings_pct":{"description":"ToonMinSavingsPct is the minimum byte-savings percentage (validated\n1-90; 0/unset → 15) the complete TOON emission (marker + hint + body)\nmust achieve over the exact passthrough emission for adaptive mode to\nencode a block. Byte savings approximate token savings for the tabular\npayload class; the spec-083 profiler reports true token deltas.\nGlobal-only (no per-server override, FR-001).","type":"integer"},"toon_output":{"description":"ToonOutput selects the TOON encoding mode for call_tool_* result text\nblocks (spec 084): \"off\" (default — responses byte-identical to\npre-feature behavior), \"adaptive\" (encode only tabular-uniform payloads\nthat beat compact JSON by ToonMinSavingsPct), or \"always\"\n(benchmark/debug only — encodes every JSON-parseable block and can\nINCREASE token cost). Per-server override: ServerConfig.ToonOutput.\nResolved by ResolveToonOutput; hot-reloadable.","type":"string"},"top_k":{"description":"Deprecated: TopK is superseded by ToolsLimit and has no runtime effect. Kept for backward compatibility.","type":"integer"},"tray_endpoint":{"description":"Tray endpoint override (unix:// or npipe://)","type":"string"},"trusted_hosts":{"description":"TrustedHosts lists non-loopback Host header values accepted on loopback\nlisteners (GH #898). DNS-rebinding protection rejects requests whose Host\nheader is not a loopback address when mcpproxy listens on loopback; a\nreverse proxy (nginx → 127.0.0.1) forwarding the public domain in Host\ntrips it. Entries are hostnames, case-insensitive; an entry without a\nport matches any port, with a port it must match exactly; a leading dot\n(\".example.com\") is a subdomain wildcard. The single entry \"*\" disables\nHost and Origin validation entirely. The same list also validates the\nOrigin header when present (MCP spec DNS-rebinding defense). Empty\n(default) keeps full protection. Env override: MCPPROXY_TRUSTED_HOSTS\n(comma-separated).","items":{"type":"string"},"type":"array","uniqueItems":false},"trusted_proxies":{"description":"TrustedProxies lists the CIDRs or IP addresses whose X-Forwarded-For /\nX-Real-IP / X-Forwarded-Proto / X-Forwarded-Host headers are believed\n(Spec 107 FR-027). Empty (default) trusts nobody. Edition-neutral, live\n(hot-reloadable). Env override: MCPPROXY_TRUSTED_PROXIES (comma-separated).\nThe one reader is ForwardedHeaders; validation is validateTrustedProxies.","items":{"type":"string"},"type":"array","uniqueItems":false},"update_check":{"$ref":"#/components/schemas/config.UpdateCheckConfig"}},"type":"object"},"config.CustomPattern":{"properties":{"category":{"description":"Category (defaults to \"custom\")","type":"string"},"keywords":{"description":"Keywords to match (mutually exclusive with Regex)","items":{"type":"string"},"type":"array","uniqueItems":false},"name":{"description":"Unique identifier for this pattern","type":"string"},"regex":{"description":"Regex pattern (mutually exclusive with Keywords)","type":"string"},"severity":{"description":"Risk level: critical, high, medium, low","type":"string"}},"type":"object"},"config.DeepScanConfig":{"description":"DeepScan is the opt-in \"deep scan\" layer (Spec 077 US3). It subsumes the\ndeprecated top-level scanner_fetch_package_source / scanner_disable_no_new_privileges\nkeys (migrated on load) and gates the heavy Docker-based scanners + source\nextraction. Disabled by default (FR-006): only the deterministic in-process\nbaseline scanner runs. A deep-scan failure NEVER changes the baseline verdict\n(FR-007/FR-008).","properties":{"disable_no_new_privileges":{"description":"DisableNoNewPrivileges, when true, omits the ` + "`" + `--security-opt\nno-new-privileges` + "`" + ` flag from scanner container runs (snap-docker/AppArmor\nescape hatch). Absorbs the deprecated top-level\nscanner_disable_no_new_privileges. Default false.","type":"boolean"},"enabled":{"description":"Enabled is the master opt-in for the heavy layer (FR-006). Default false.","type":"boolean"},"fetch_package_source":{"description":"FetchPackageSource controls whether the scanner fetches the PUBLISHED\nsource of package-runner servers (npx/uvx) — without executing it — when\nno local source is available. Absorbs the deprecated top-level\nscanner_fetch_package_source. Default (nil) is ENABLED within deep scan.","type":"boolean"},"scanners":{"description":"Scanners optionally restricts which deep scanners may run under the\numbrella (by scanner id). Empty ⇒ all enabled deep scanners are eligible.","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"config.DockerIsolationConfig":{"description":"Docker isolation settings","properties":{"cpu_limit":{"description":"CPU limit for containers","type":"string"},"default_images":{"additionalProperties":{"type":"string"},"description":"Map of runtime type to Docker image","type":"object"},"enable_cache_volume":{"description":"Mount shared cache volumes for faster restarts (default: true)","type":"boolean"},"enabled":{"description":"Global enable/disable for Docker isolation (legacy; superseded by Mode)","type":"boolean"},"extra_args":{"description":"Additional docker run arguments","items":{"type":"string"},"type":"array","uniqueItems":false},"log_driver":{"description":"Docker log driver (default: json-file)","type":"string"},"log_max_files":{"description":"Maximum number of log files (default: 3)","type":"string"},"log_max_size":{"description":"Maximum size of log files (default: 100m)","type":"string"},"memory_limit":{"description":"Memory limit for containers","type":"string"},"mode":{"description":"Isolation mode: \"docker\" | \"sandbox\" | \"none\" (MCP-34.2). Unset per-server inherits the global mode; unset globally falls back to the legacy \"enabled\" flag (true ⇒ docker, false ⇒ none)","type":"string","x-enum-varnames":["IsolationModeDocker","IsolationModeSandbox","IsolationModeNone"]},"network_mode":{"description":"Docker network mode (default: bridge)","type":"string"},"registry":{"description":"Custom registry (defaults to docker.io)","type":"string"},"timeout":{"description":"Container startup timeout","type":"string"}},"type":"object"},"config.DockerRecoveryConfig":{"description":"Docker recovery settings","properties":{"enabled":{"description":"Enable Docker recovery monitoring (default: true)","type":"boolean"},"max_retries":{"description":"Maximum retry attempts (0 = unlimited)","type":"integer"},"notify_on_failure":{"description":"Show notification on recovery failure (default: true)","type":"boolean"},"notify_on_retry":{"description":"Show notification on each retry (default: false)","type":"boolean"},"notify_on_start":{"description":"Show notification when recovery starts (default: true)","type":"boolean"},"notify_on_success":{"description":"Show notification on successful recovery (default: true)","type":"boolean"},"persistent_state":{"description":"Save recovery state across restarts (default: true)","type":"boolean"}},"type":"object"},"config.FeatureFlags":{"description":"Deprecated: Features flags are unused and have no runtime effect. Kept for backward compatibility.","properties":{"enable_async_storage":{"type":"boolean"},"enable_caching":{"type":"boolean"},"enable_contract_tests":{"type":"boolean"},"enable_debug_logging":{"description":"Development features","type":"boolean"},"enable_docker_isolation":{"type":"boolean"},"enable_event_bus":{"type":"boolean"},"enable_health_checks":{"type":"boolean"},"enable_metrics":{"type":"boolean"},"enable_oauth":{"description":"Security features","type":"boolean"},"enable_observability":{"description":"Observability features","type":"boolean"},"enable_quarantine":{"type":"boolean"},"enable_runtime":{"description":"Runtime features","type":"boolean"},"enable_search":{"description":"Storage features","type":"boolean"},"enable_sse":{"type":"boolean"},"enable_tracing":{"type":"boolean"},"enable_tray":{"type":"boolean"},"enable_web_ui":{"description":"UI features","type":"boolean"}},"type":"object"},"config.IntentDeclarationConfig":{"description":"Intent declaration settings (Spec 018)","properties":{"strict_server_validation":{"description":"StrictServerValidation controls whether server annotation mismatches\ncause rejection (true) or just warnings (false).\nDefault: true (reject mismatches)","type":"boolean"}},"type":"object"},"config.IsolationConfig":{"description":"Per-server isolation settings","properties":{"enabled":{"description":"Enable Docker isolation for this server (nil = inherit global; legacy, superseded by Mode)","type":"boolean"},"extra_args":{"description":"Additional docker run arguments for this server","items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"description":"Custom Docker image (overrides default)","type":"string"},"log_driver":{"description":"Docker log driver override for this server","type":"string"},"log_max_files":{"description":"Maximum number of log files override","type":"string"},"log_max_size":{"description":"Maximum size of log files override","type":"string"},"mode":{"$ref":"#/components/schemas/config.IsolationMode"},"network_mode":{"description":"Custom network mode for this server","type":"string"},"working_dir":{"description":"Custom working directory in container","type":"string"}},"type":"object"},"config.IsolationMode":{"description":"Isolation mode: \"docker\" | \"sandbox\" | \"none\" (MCP-34.2). Unset per-server inherits the global mode; unset globally falls back to the legacy \"enabled\" flag (true ⇒ docker, false ⇒ none)","type":"string","x-enum-varnames":["IsolationModeDocker","IsolationModeSandbox","IsolationModeNone"]},"config.LogConfig":{"description":"Logging configuration","properties":{"compress":{"type":"boolean"},"enable_console":{"type":"boolean"},"enable_file":{"type":"boolean"},"filename":{"type":"string"},"json_format":{"type":"boolean"},"level":{"type":"string"},"log_dir":{"description":"Custom log directory","type":"string"},"max_age":{"description":"days","type":"integer"},"max_backups":{"description":"number of backup files","type":"integer"},"max_size":{"description":"MB","type":"integer"}},"type":"object"},"config.MetricsExporterConfig":{"description":"Metrics gates the Prometheus /metrics scrape endpoint (MCP-32). Disabled\nby default — operators opt in for k8s/enterprise deployments.","properties":{"enabled":{"description":"Enabled exposes /metrics on the existing HTTP listener when true.\nThe endpoint is admin-authenticated (SEC-07): scrapers must present the\nglobal API key, via X-API-Key or an Authorization: Bearer header.","type":"boolean"}},"type":"object"},"config.OAuthConfig":{"description":"OAuth configuration (keep even when empty to signal OAuth requirement)","properties":{"auth_server_metadata_url":{"type":"string"},"authorization_endpoint":{"description":"Spec 113-b: optional per-server discovery overrides. Each is an absolute\nhttps URL (http only on a loopback host) with no query, fragment or\nuserinfo; validated at write time only (ValidateOAuthEndpointOverrides).\nThe endpoint overrides rewrite the matching fields of the authorization\nserver metadata mcp-go reads; AuthServerMetadataURL replaces discovery.","type":"string"},"callback_base_url":{"type":"string"},"client_id":{"type":"string"},"client_secret":{"type":"string"},"extra_params":{"additionalProperties":{"type":"string"},"description":"Additional OAuth parameters (e.g., RFC 8707 resource)","type":"object"},"pkce_enabled":{"type":"boolean"},"redirect_uri":{"type":"string"},"refresh_replay_enabled":{"description":"Opt in only when token_endpoint supports idempotent refresh replay for at least 30 seconds.","type":"boolean"},"registration_endpoint":{"type":"string"},"scopes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"token_endpoint":{"type":"string"}},"type":"object"},"config.ObservabilityConfig":{"description":"Observability settings (Spec 069): usage aggregate cache/persistence cadence.","properties":{"metrics":{"$ref":"#/components/schemas/config.MetricsExporterConfig"},"tracing":{"$ref":"#/components/schemas/config.TracingExporterConfig"},"usage_cache_ttl":{"description":"UsageCacheTTL bounds the freshness of the usage endpoint's read cache for\nwide windows (FR-005). Default 5s.","type":"string"},"usage_persist_interval":{"description":"UsagePersistInterval is how often the actor-owned usage aggregate snapshot\nis flushed to storage. Default 30s.","type":"string"}},"type":"object"},"config.OutputSanitisationConfig":{"description":"Output sanitisation settings (Spec 054 Track B)","properties":{"max_redactions":{"description":"cap on redactions per response; default 100","type":"integer"},"response_action":{"description":"\"spotlight\" | \"redact\" | \"block\"; default \"spotlight\"","type":"string"},"spotlight_untrusted":{"description":"wrap untrusted output in spotlight markers; default true","type":"boolean"},"strip_classes":{"description":"classes to strip: ansi/c0c1/bidi/zero_width","items":{"type":"string"},"type":"array","uniqueItems":false},"strip_control_chars":{"description":"strip control-character classes; default false","type":"boolean"}},"type":"object"},"config.OutputValidationConfig":{"description":"Output-schema validation settings (Spec 056)","properties":{"max_bytes":{"description":"structured payload byte cap; default 5\u003c\u003c20","type":"integer"},"max_depth":{"description":"nesting depth cap; default 64","type":"integer"},"missing_structured_content":{"description":"\"allow\" | \"block\"; default \"allow\"","type":"string"},"mode":{"description":"\"off\" | \"warn\" | \"strict\"; default \"warn\"","type":"string"}},"type":"object"},"config.ProfileConfig":{"properties":{"code_execution":{"description":"CodeExecution: nil = inherit the global enable_code_execution gate;\nnon-nil narrows it (a profile can only narrow, never widen, FR-006).","type":"boolean"},"description":{"description":"\u003c= 500 chars (FR-001)","type":"string"},"management_tools":{"description":"ManagementTools: nil = legacy/inherit (FR-016); non-nil sets the\nprofile-level visibility of upstream_servers/quarantine_security.","type":"boolean"},"max_tier":{"description":"MaxTier caps the tier a tool may run at under this profile: \"\" (no\ncap) | \"read\" | \"write\" | \"destructive\" (FR-001).","type":"string"},"name":{"description":"slug (Spec 057 rules unchanged)","type":"string"},"servers":{"description":"references to mcpServers[].name","items":{"type":"string"},"type":"array","uniqueItems":false},"switchable_to":{"description":"SwitchableTo is the list of profile names a session under this\nprofile may ` + "`" + `set_profile` + "`" + ` into (FR-022). nil = legacy/none (research\nD6); a non-nil EMPTY list is an explicit \"none\" and must round-trip as\n` + "`" + `[]` + "`" + `, never be dropped by omitempty — hence the pointer (see the\nMarshalJSON note below, and profiles_v3_test.go's switchable_to round\ntrip case).","items":{"type":"string"},"type":"array","uniqueItems":false},"title":{"description":"display only, \u003c= 80 chars (FR-001)","type":"string"},"tools":{"$ref":"#/components/schemas/config.ProfileToolRules"},"unannotated":{"description":"Unannotated is this profile's handling of a tool whose effective\nannotations carry no tier hint: \"\" (unset, see EffectiveUnannotated) |\n\"deny\" | \"as_write\" | \"as_read\" (FR-001, FR-003).","type":"string"}},"type":"object"},"config.ProfileToolRules":{"description":"Tools holds the allow/deny/classify rule set (FR-001, FR-004, FR-005).","properties":{"allow":{"items":{"type":"string"},"type":"array","uniqueItems":false},"classify":{"additionalProperties":{"type":"string"},"type":"object"},"deny":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"config.RegistryEntry":{"properties":{"count":{"description":"number or string","type":"string"},"description":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"},"protocol":{"type":"string"},"provenance":{"description":"Provenance is the trust tag for this registry (MCP-866):\nRegistryProvenanceOfficial for built-in defaults, RegistryProvenanceCustom\nfor user-added registries. It is authoritatively (re)computed by the\nregistries merge from whether the ID is a shipped default — a user cannot\nclaim \"official\" by writing it into their config.","type":"string"},"requires_key":{"description":"RequiresKey marks a registry that needs an API key to be queried. When\ntrue and no key is configured, the registry is skipped/marked unavailable\nrather than failing the whole search (FR-008).","type":"boolean"},"servers_url":{"type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"url":{"type":"string"}},"type":"object"},"config.SecurityConfig":{"description":"Security scanner settings (Spec 039)","properties":{"auto_baseline_scan":{"description":"AutoBaselineScan is the kill-switch for the AUTOMATIC, informational\nPass-1 baseline scan: the free in-process TPA scan mcpproxy runs for every\nnewly admitted server (any trust mode) and, once per installation, over\npre-existing servers that have never been scanned.\n\nInformational ONLY: the resulting verdict populates the security badge and\nthe scan summary, and NEVER gates quarantine or approval. The\ntrust_mode:\"scan\" admission gate is a separate path and is unaffected by\nthis flag.\n\nDefault (nil) is ENABLED. Set to false to suppress every automatic scan\n(manual scans keep working). Env override: MCPPROXY_AUTO_BASELINE_SCAN,\nwhich wins over this field on every path.","type":"boolean"},"auto_rescan_on_change":{"description":"AutoRescanOnChange is the finer switch for the automatic, informational\nrescan that follows a tool-definition hash change: the in-process TPA scan\nof the changed (or newly pending) tool, recorded as hold evidence, and a\ndebounced informational server rescan that brings the review screen's scan\ncoverage back to \"current\".\n\nEvidence and freshness ONLY: this switch approves nothing. Under \"manual\"\nevery change is held for review whatever the verdict (RT-02); under\n\"scan\" the gate's own synchronous scan approves a clean change that\npasses the spec 120 structural gate (spec 119 FR-004), and this switch\ndoes not affect that path. Runs in every trust mode except \"auto\".\n\nDefault (nil) is ENABLED. It only takes effect while auto_baseline_scan is\nalso enabled, so a user can keep the admission scan and turn off per-change\nrescans with this key alone. Env override: MCPPROXY_AUTO_RESCAN_ON_CHANGE,\nwhich wins over this field on every path.","type":"boolean"},"deep_scan":{"$ref":"#/components/schemas/config.DeepScanConfig"},"integrity_check_interval":{"type":"string"},"integrity_check_on_restart":{"type":"boolean"},"require_signed_bundle":{"description":"RequireSignedBundle makes the detached signature sidecar mandatory for\nfile-dropped bundles (FR-007). Default false (maintainer decision D2):\nexisting unsigned drops keep working, but an unsigned external bundle\nalways runs with DEGRADED coverage (scan-mode auto-approval suspended).","type":"boolean"},"runtime_read_only":{"type":"boolean"},"runtime_tmpfs_size":{"type":"string"},"scan_timeout_default":{"type":"string"},"scanner_disable_no_new_privileges":{"description":"Deprecated (Spec 077 US3): migrated on load into DeepScan.DisableNoNewPrivileges\n(see migrateDeepScanConfig). Retained only so existing configs that still carry\nthe top-level key parse; consumers MUST read the effective value via\nSecurityConfig.IsDisableNoNewPrivileges. Cleared after migration.\n\nScannerDisableNoNewPrivileges, when true, omits the\n` + "`" + `--security-opt no-new-privileges` + "`" + ` flag from scanner container runs.\n\nBackground: snap-installed Docker on Ubuntu confines dockerd under the\n` + "`" + `snap.docker.dockerd` + "`" + ` AppArmor profile. When runc tries to transition\nthe container into the inner ` + "`" + `docker-default` + "`" + ` profile to exec the\nentrypoint, AppArmor refuses the transition because NO_NEW_PRIVS\nforbids privilege/profile changes on exec — the result is EPERM\n(\"operation not permitted\") and every scanner fails immediately.\n\nSet this to true ONLY on hosts hitting that incompatibility. Scanner\ncontainers still run with read-only rootfs, tmpfs /tmp, no-network by\ndefault, and read-only source mounts, so the marginal isolation loss\nis small. The preferred fix remains replacing snap docker with a\ndistro-packaged docker.","type":"boolean"},"scanner_fetch_package_source":{"description":"Deprecated (Spec 077 US3): migrated on load into DeepScan.FetchPackageSource\n(see migrateDeepScanConfig). Retained only so existing configs that still carry\nthe top-level key parse; consumers MUST read the effective value via\nSecurityConfig.EffectiveFetchPackageSource. Cleared after migration.\n\nScannerFetchPackageSource controls whether the scanner fetches the\nPUBLISHED source of package-runner servers (npx/uvx) — without executing\nit — when no local source is available (no Docker container, no local\npackage cache, no working_dir). This is the primary quarantine/scan\ntarget: a quarantined-on-add server is never run locally, so without this\nthe scan degrades to tool-definitions-only (no real source-level\nanalysis). See MCP-2206.\n\nFetching uses ` + "`" + `npm pack --ignore-scripts` + "`" + ` (npm) and ` + "`" + `uv pip download` + "`" + ` /\n` + "`" + `pip download` + "`" + ` with ` + "`" + `--only-binary=:all:` + "`" + ` (Python), which only download +\nunpack archives and NEVER run install, build, or setup.py — a scanner must\nnot execute the untrusted code it is scanning. The Python\n` + "`" + `--only-binary=:all:` + "`" + ` flag is required because downloading an sdist would\ninvoke its build backend (setup.py); packages with no wheel fall back to\ntool-definitions-only instead. Extraction is hardened against path\ntraversal and decompression bombs.\n\nDefault (nil) is ENABLED. Set to false on air-gapped deployments to\nforbid the scanner's network egress; such servers then fall back to the\ntool-definitions-only scan with no regression.","type":"boolean"},"scanner_registry_url":{"type":"string"},"tpa_active_root":{"description":"TPAActiveRoot declares which signing authority's bundles may activate\n(FR-004b): \"publisher\" (default, the keys embedded in this binary) or\n\"operator\" (TPAOperatorSigners). A bundle verified by the other root is\nrefused as authority_not_active, so whoever can write the bundle path\ncannot choose the authority.","type":"string"},"tpa_bundle_path":{"description":"TPABundlePath is the filesystem path to the tpa-db scanner-bundle.json\nthe offline TPA scanner runs (spec 086 FR-019: the signature-DB location\nMUST be configuration-driven, not hardcoded). Empty (the default) runs the\ncorpus embedded in this build.\n\nEnv override: MCPPROXY_TPA_BUNDLE_PATH. Hot-reloadable — the path is\nre-read on every config.reloaded event via\nscanner.Service.ApplySecurityConfig, so a corpus refresh needs no restart.\nA configured bundle that fails to read/parse/version-check/compile is\nREFUSED and the previously active corpus stays live (fail-closed, never\nfail-empty); the reason is logged and surfaced in the security overview's\nsignature_bundle.load_error.","type":"string"},"tpa_fetch_enabled":{"description":"TPAFetchEnabled opts in to the network fetch leg. Default false; the\nenvironment override is MCPPROXY_TPA_FETCH_ENABLED (EnvTPAFetchEnabled).","type":"boolean"},"tpa_fetch_url":{"description":"TPAFetchURL is the channel URL: a GitHub Releases \"latest\" API URL or a\ndirect bundle URL. Empty (the default) means the fetch leg is off; no URL\nis compiled into the binary.","type":"string"},"tpa_operator_baseline":{"description":"TPAOperatorBaseline seeds the operator authority's anti-downgrade\nwatermark (FR-009b): an operator-signed bundle must carry a sequence\nABOVE it (a rollback target may sit at it). It survives a data-directory\nwipe because it lives here. Absent means the operator authority has no\nanti-downgrade floor and an active operator bundle runs DEGRADED.","type":"integer"},"tpa_operator_epoch":{"description":"TPAOperatorEpoch is the operator authority's trust epoch (FR-005a).\nBumping it (after an operator key compromise) re-baselines the operator\nwatermark and retires prior-epoch pins. Absent means 0.","type":"integer"},"tpa_operator_signers":{"description":"TPAOperatorSigners lists operator Ed25519 public keys, each the standard\nbase64 encoding of the 32 raw key bytes (FR-004). Their key ids are the\nlowercase-hex SHA-256 of those bytes. Malformed or duplicate entries are\nrejected on write and dropped (with a log) on load.","items":{"type":"string"},"type":"array","uniqueItems":false},"tpa_refresh_interval":{"description":"TPARefreshInterval is the cadence of the refresh cycle (the network-free\nfile leg, then the optional fetch leg). Absent or 0 means 24h; the runtime\nclamps to at least 1h. There is no refresh-enable key: the file leg is\nidempotent and always on.","type":"string"},"tpa_stale_after_days":{"description":"TPAStaleAfterDays is the age in days after which the active bundle reads\nas stale. Absent means 30; an explicit 0 disables the stale flag and the\ndoctor stale warning.","type":"integer"}},"type":"object"},"config.SensitiveDataDetectionConfig":{"description":"Sensitive data detection settings (Spec 026)","properties":{"categories":{"additionalProperties":{"type":"boolean"},"description":"Enable/disable specific detection categories","type":"object"},"custom_patterns":{"description":"User-defined detection patterns","items":{"$ref":"#/components/schemas/config.CustomPattern"},"type":"array","uniqueItems":false},"enabled":{"description":"Enable sensitive data detection (default: true)","type":"boolean"},"entropy_threshold":{"description":"Shannon entropy threshold for high-entropy detection (default: 4.5)","type":"number"},"max_payload_size_kb":{"description":"Max size to scan before truncating (default: 1024)","type":"integer"},"scan_requests":{"description":"Scan tool call arguments (default: true)","type":"boolean"},"scan_responses":{"description":"Scan tool responses (default: true)","type":"boolean"},"sensitive_keywords":{"description":"Keywords to flag","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"config.ServerConfig":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges is the per-server intent to auto-approve tool\nchanges/additions (disabling per-server rug-pull protection). Supersedes\nskip_quarantine. MCP-2930 only ACCEPTS, persists, and migrates this flag — it\nis NOT yet consulted at runtime; auto-approval is still governed by\nSkipQuarantine until the trust-baseline behavior change (MCP-2931) migrates the\nruntime consumers onto it.\nTri-state pointer (mirrors QuarantineEnabled): nil = unset (inherit/migrate\nfrom legacy skip_quarantine), explicit true/false = honored as-is so an\nexplicit auto_approve_tool_changes:false overrides a legacy skip_quarantine:true.\nRead via IsAutoApproveToolChanges().","type":"boolean"},"command":{"type":"string"},"created":{"type":"string"},"disabled_tools":{"description":"Denylist: these tools are hidden; mutually exclusive with enabled_tools","items":{"type":"string"},"type":"array","uniqueItems":false},"enabled":{"type":"boolean"},"enabled_tools":{"description":"Allowlist: only these tools are exposed; mutually exclusive with disabled_tools","items":{"type":"string"},"type":"array","uniqueItems":false},"env":{"additionalProperties":{"type":"string"},"type":"object"},"expose_prompts":{"description":"ExposePrompts overrides whether this server's advertised MCP prompts are\naggregated into mcpproxy's prompts/list. nil (default) inherits the\ndefault-aggregate behavior (included if the server advertises\nCapabilities.Prompts); false excludes it regardless of capability.","type":"boolean"},"expose_skills":{"description":"ExposeSkills overrides whether this server's skills (MCP skills\nextension) are read when Config.EnableSkills is on. nil (default)\ninherits (included if the server supports skills); false excludes it.","type":"boolean"},"forward_headers":{"description":"ForwardHeaders lists inbound MCP-client header NAMES (never values) that\nare copied into this server's upstream tools/call requests (Spec 112).\nExact names, case-insensitive, at most 32, no wildcards. Empty forwards\nnothing. Only HTTP-based transports (http, streamable-http) forward; the\ndeny list (Authorization, Host, hop-by-hop, ...) is enforced at runtime\nregardless of what is configured here.","items":{"type":"string"},"type":"array","uniqueItems":false},"headers":{"additionalProperties":{"type":"string"},"description":"For HTTP servers","type":"object"},"health_check_interval":{"description":"Per-server discovery \u0026 health-check overrides (spec 074). Same *Duration\ntri-state as the global keys: nil = inherit the global value (or default),\npointer to 0s = disabled for this server, positive = that interval.\nHealthCheckInterval is fully wired into the per-server health loop;\nToolDiscoveryInterval is accepted/validated and round-trips for\nforward-compat, but the periodic index sweep is governed by the global\ncadence in this iteration (see spec 074 plan §C).","type":"string"},"init_timeout":{"description":"InitTimeout overrides the global init_timeout for this server's MCP\n` + "`" + `initialize` + "`" + ` handshake deadline (MCP-3322 / GH #760). *Duration tri-state:\nnil = inherit the global value (or 30s default), positive = that deadline.\nResolved by Config.ResolveInitTimeout; validated to {0} ∪ [1s, 30m]. Raise\nthis for upstreams that do legitimate first-run warmup (e.g. caching many\nchannels/users) before responding to ` + "`" + `initialize` + "`" + `.","type":"string"},"isolation":{"$ref":"#/components/schemas/config.IsolationConfig"},"launcher_wait_timeout":{"description":"LauncherWaitTimeout caps how long mcpproxy will wait for a locally-launched\nHTTP/SSE upstream's URL to become reachable after Spawn(). Only consulted\nwhen the server is configured with both Command and an HTTP/SSE URL — i.e.,\nmcpproxy starts the process AND connects via network. Stdio servers ignore\nthis field. Zero or unset → 30s default.","type":"string"},"max_concurrent_requests":{"description":"Per-server concurrency overrides — scope (c) of FR-020 (spec 093, #955).\nTri-state per setting, exactly like HealthCheckInterval: absent = inherit\nthe per-server default set (server_concurrency_defaults), explicit 0 =\ndisable that setting for this server (0 max = no per-server limiter at\nall; 0 queue_size = no pending capacity, shed immediately at the cap),\npositive = override. The global aggregate limiter is never inherited from\nhere — it applies on top, so effective concurrency is min(per-server,\nglobal). Resolved by Config.ResolveServerConcurrency.","type":"integer"},"name":{"type":"string"},"oauth":{"$ref":"#/components/schemas/config.OAuthConfig"},"protocol":{"description":"stdio, http, sse, streamable-http, auto","type":"string"},"quarantined":{"description":"Security quarantine status","type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_on_use":{"description":"Attempt reconnection when a tool call targets a disconnected server","type":"boolean"},"shared":{"description":"Server edition: shared with all users","type":"boolean"},"skip_quarantine":{"description":"SkipQuarantine is DEPRECATED (MCP-2930): use AutoApproveToolChanges instead.\nKept for back-compat parsing; on config load a legacy skip_quarantine:true is\nmigrated to auto_approve_tool_changes:true only when the new field is unset\n(see normalizeServerQuarantineFlags).","type":"boolean"},"source_registry_id":{"description":"SourceRegistryID records which registry this server was added from (empty\nfor manually-configured servers). MCP-866: surfaced in the approval /\nquarantine view so a reviewer can see a server's origin.","type":"string"},"source_registry_provenance":{"description":"SourceRegistryProvenance records the source registry's provenance at add\ntime (RegistryProvenanceOfficial / RegistryProvenanceCustom). It is purely\ninformational (MCP-1072) — surfaced so a reviewer can see a server's origin\n— and no longer gates quarantine or skip_quarantine.","type":"string"},"tool_argument_error_mode":{"description":"ToolArgumentErrorMode stores the per-upstream argument-error policy.\nEmpty and detailed retain detailed errors; redacted opts into redaction.\nUpdates omit/keep an empty value; detailed explicitly resets the policy.","type":"string"},"tool_discovery_interval":{"type":"string"},"toon_output":{"description":"ToonOutput overrides the global toon_output mode for this server's\ntools (spec 084, FR-001). Plain string, not a pointer: \"\"/absent =\ninherit the global value; \"off\"|\"adaptive\"|\"always\" = override (\"off\"\nis the explicit force-off). Resolved by Config.ResolveToonOutput.","type":"string"},"trust_mode":{"description":"TrustMode is the per-server trust tier: auto|scan|manual. Supersedes\nauto_approve_tool_changes (spec 086). An empty value is derived from the\nlegacy fields at load via normalizeServerQuarantineFlags; the single\nresolution point is EffectiveTrustMode(), which treats an empty value as\nscan (DefaultTrustMode, spec 119) and an unrecognized value as manual\n(fail closed). Read via\nEffectiveTrustMode(), never the raw string.","type":"string"},"updated":{"type":"string"},"url":{"type":"string"},"working_dir":{"description":"Working directory for stdio servers","type":"string"}},"type":"object"},"config.TLSConfig":{"description":"TLS configuration","properties":{"cert_file":{"description":"CertFile is the absolute path of an operator-provided server certificate\n(PEM, leaf first), served instead of a generated one. Needs KeyFile.","type":"string"},"certs_dir":{"description":"Directory for certificates","type":"string"},"enabled":{"description":"Enable HTTPS","type":"boolean"},"extra_sans":{"description":"ExtraSANs are DNS names and IP addresses added to the generated server\ncertificate, which is signed by the same local CA. Not used with CertFile.","items":{"type":"string"},"type":"array","uniqueItems":false},"hsts":{"description":"Enable HTTP Strict Transport Security","type":"boolean"},"key_file":{"description":"KeyFile is the absolute path of the private key for CertFile (PEM).","type":"string"},"require_client_cert":{"description":"Enable mTLS","type":"boolean"}},"type":"object"},"config.TelemetryConfig":{"description":"Telemetry settings (Spec 036)","properties":{"anonymous_id":{"description":"Auto-generated UUIDv4","type":"string"},"anonymous_id_created_at":{"description":"Spec 042 (Tier 2) additions — all default-zero, all backwards-compatible.","type":"string"},"enabled":{"description":"Default: true (opt-out)","type":"boolean"},"endpoint":{"description":"Override for testing","type":"string"},"last_reported_version":{"description":"Upgrade funnel","type":"string"},"last_startup_outcome":{"description":"success|port_conflict|db_locked|...","type":"string"},"notice_shown":{"description":"First-run notice flag","type":"boolean"}},"type":"object"},"config.TokenizerConfig":{"description":"Tokenizer configuration for token counting","properties":{"default_model":{"description":"Default model for tokenization (e.g., \"gpt-4\")","type":"string"},"enabled":{"description":"Enable token counting","type":"boolean"},"encoding":{"description":"Default encoding (e.g., \"cl100k_base\")","type":"string"}},"type":"object"},"config.TracingExporterConfig":{"description":"Tracing gates the OpenTelemetry OTLP trace exporter (MCP-32). Disabled by\ndefault.","properties":{"enabled":{"description":"Enabled turns on OTLP trace export for tool calls and upstream hops.","type":"boolean"},"endpoint":{"description":"Endpoint is the collector address as host:port (no scheme), e.g.\n\"localhost:4318\" for http or \"localhost:4317\" for grpc.","type":"string"},"protocol":{"description":"Protocol selects the OTLP transport: \"http\" or \"grpc\".","type":"string"},"sample_rate":{"description":"SampleRate is the head-based trace sampling ratio in [0,1]. Default 0.1.\nOmit the key for the 0.1 default; set it to 0 to sample nothing.","type":"number"}},"type":"object"},"config.UpdateCheckConfig":{"description":"Update-check settings (Spec 079 FR-012): config-file control of the\nbackground upgrade-awareness checker (internal/updatecheck). nil =\nenabled on the stable channel (existing default behavior). The existing\nenvironment switches keep working and WIN over these keys (FR-014):\nMCPPROXY_DISABLE_AUTO_UPDATE=true force-disables even when\nenabled=true, and MCPPROXY_ALLOW_PRERELEASE_UPDATES=true force-selects\nthe rc channel even when channel=stable.","properties":{"channel":{"description":"Channel selects which releases are offered as updates: \"stable\"\n(default; prereleases never offered) or \"rc\" (prereleases included).\nEmpty resolves to stable. Validated in ValidateDetailed.\n\nNOTE: for a RELEASED build the running binary's own version is\nauthoritative and overrides this field — a stable build is never\noffered an RC (even with channel=rc), and an RC build always tracks the\nrc channel. This field only takes effect on dev/unstamped builds. See\ninternal/updatecheck.Checker.IncludePrereleases.","type":"string"},"enabled":{"description":"Enabled gates all update checking. Tri-state: nil/absent = enabled\n(default true, matching pre-079 behavior). When false, no network\ncheck is performed and no upgrade nudge appears on any surface\n(FR-015) — /api/v1/info omits the update object entirely.","type":"boolean"}},"type":"object"},"configimport.FailedServer":{"properties":{"details":{"type":"string"},"error":{"type":"string"},"name":{"type":"string"}},"type":"object"},"configimport.ImportSummary":{"properties":{"failed":{"type":"integer"},"imported":{"type":"integer"},"skipped":{"type":"integer"},"total":{"type":"integer"}},"type":"object"},"configimport.SkippedServer":{"properties":{"name":{"type":"string"},"reason":{"description":"\"already_exists\", \"filtered_out\", \"invalid_name\", \"self_reference\"","type":"string"}},"type":"object"},"connect.ConnectResult":{"description":"The full result; its action mirrors the top-level one","properties":{"action":{"description":"\"created\", \"updated\", \"already_exists\", \"removed\", \"not_found\"","type":"string"},"backup_path":{"type":"string"},"client":{"type":"string"},"config_path":{"type":"string"},"credential":{"description":"Credential is the masked client credential the write embedded\n(` + "`" + `mcp_cli_••••` + "`" + `); the real secret is never returned (FR-024). Empty for a\nkeyless entry, a disconnect and every refusal.","type":"string"},"credential_revoke_error":{"description":"CredentialRevokeError is set when a disconnect removed the entry but\nrevoking the client credential failed. The disconnect still succeeded;\nthe credential is still active and ` + "`" + `mcpproxy client forget \u003cid\u003e` + "`" + `\nretries the revoke.","type":"string"},"credential_revoked":{"description":"CredentialRevoked names the credential that was revoked: by an undo,\nbecause the restored config no longer holds it (plan D16), or by a\ndisconnect, which cuts the client off (a later undo of that disconnect\ndoes not bring the credential back).","type":"string"},"display_path":{"description":"DisplayPath is ConfigPath with the home directory shortened to \"~\"\n(FR-037). Populated for every result whose ConfigPath is known.","type":"string"},"keyless":{"description":"Keyless is true when the entry was written with no credential.","type":"boolean"},"message":{"type":"string"},"mode":{"type":"string"},"profile":{"description":"Profile and Mode are the binding of the credential this write minted or\nkept. Profile \"\" means the built-in All servers scope.","type":"string"},"reload_hint":{"description":"ReloadHint is this client's instruction for making the write take\neffect (FR-037/FR-042), e.g. \"Restart Cursor to load MCPProxy\". Empty\nfor an unknown client.","type":"string"},"rotation":{"description":"Rotation is \"finalized\" when the write replaced an active credential's\nsecret (staged rotation, FR-021a), empty otherwise.","type":"string"},"server_name":{"type":"string"},"success":{"type":"boolean"},"token_name":{"description":"TokenName is the client credential's token name (` + "`" + `client-\u003cid\u003e` + "`" + `).","type":"string"}},"type":"object"},"contracts.APIResponse":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.ActivityDetailResponse":{"properties":{"activity":{"$ref":"#/components/schemas/contracts.ActivityRecord"}},"type":"object"},"contracts.ActivityListResponse":{"properties":{"activities":{"items":{"$ref":"#/components/schemas/contracts.ActivityRecord"},"type":"array","uniqueItems":false},"limit":{"type":"integer"},"offset":{"type":"integer"},"total":{"type":"integer"}},"type":"object"},"contracts.ActivityPerServer":{"properties":{"calls":{"description":"Calls counted per storage.CountsAsCall","type":"integer"},"errors":{"description":"Of those calls, how many failed","type":"integer"},"last_call_at":{"description":"LastCallAt is RFC3339, or \"\" if the server had no call in the period\n(PerServer only lists servers that did, so this is always set).","type":"string"},"name":{"description":"Server name","type":"string"}},"type":"object"},"contracts.ActivityRecord":{"description":"Activity is the stored row; absent on a session_start or session_end\nrow.","properties":{"agent_name":{"description":"Agent token name when auth_type is \"agent\"","type":"string"},"arguments":{"description":"Tool call arguments","type":"object"},"auth_type":{"description":"\"admin\", \"agent\", \"user\" or \"admin_user\"; empty without an auth context or on another caller's row for a scoped caller","type":"string"},"block_reason":{"description":"Typed cause of a profile policy refusal","type":"string"},"client_id":{"description":"Client id from the client-credential binding","type":"string"},"client_name":{"description":"Self-reported clientInfo.name (advisory)","type":"string"},"detection_types":{"description":"List of detection types found","items":{"type":"string"},"type":"array","uniqueItems":false},"duration_ms":{"description":"Execution duration in milliseconds","type":"integer"},"error_class":{"description":"Call-error taxonomy (Spec 113-c FR-045): what failed and whose fault it\nis. Absent on success and on records written before Spec 113.","type":"string"},"error_message":{"description":"Error details if status is \"error\"","type":"string"},"fault_domain":{"description":"upstream|proxy|client","type":"string"},"has_sensitive_data":{"description":"Sensitive data detection fields (Spec 026)","type":"boolean"},"id":{"description":"Unique identifier (ULID format)","type":"string"},"max_severity":{"description":"Highest severity level detected (critical, high, medium, low)","type":"string"},"metadata":{"description":"Additional context-specific data","type":"object"},"parent_id":{"description":"Correlation id of the parent call (the code_execution whose sandbox issued this sub-call)","type":"string"},"profile":{"description":"Scope attribution (Spec 108 FR-029): the profile, client and token in\neffect when the call ran. Stamped at write time, never rewritten. For a\nscoped (non-admin) caller the profile/profile_source/client_id/token_name\nof a row it did not make are blanked (binding disclosure is admin-only);\nclient_name is self-reported and stays. Absent on records written before\nSpec 108 and on records with no MCP/REST request context.","type":"string"},"profile_source":{"description":"pin|binding|url|session|anonymous|none","type":"string"},"request_bytes":{"description":"Byte sizes measured pre-truncation, mirroring storage.ActivityRecord\n(Spec 069 A1). They are the only cost signal a bodies-off export carries:\nwith payloads suppressed there is no text left to measure, so a consumer\naccounting for a record it cannot read has nothing else to go on. They are\nbyte LENGTHS, not token counts — the basis for an explicit estimate, never\na measured figure (spec 103, contracts/replay-input.md).\n\nZero means UNKNOWN, not free: legacy records predate the measurement and\ncode-execution sub-calls record both as zero. Hence omitempty — an absent\nkey tells a consumer to fall to exclusion accounting, whereas a present\nzero would read as a costless call and silently understate the workload.","type":"integer"},"request_id":{"description":"HTTP request ID for correlation","type":"string"},"response":{"description":"Tool response (potentially truncated)","type":"string"},"response_bytes":{"description":"Raw upstream response size in bytes before truncation","type":"integer"},"response_truncated":{"description":"True if response was truncated","type":"boolean"},"server_name":{"description":"Name of upstream MCP server","type":"string"},"session_id":{"description":"MCP transport session ID (regenerated on every reconnect)","type":"string"},"source":{"$ref":"#/components/schemas/contracts.ActivitySource"},"status":{"description":"Result status: \"success\", \"error\", \"blocked\", \"rejected\"","type":"string"},"timestamp":{"description":"When activity occurred","type":"string"},"token_name":{"description":"Agent/client token name","type":"string"},"tool_name":{"description":"Name of tool called","type":"string"},"type":{"$ref":"#/components/schemas/contracts.ActivityType"},"upstream_http_status":{"description":"Upstream HTTP status when known","type":"integer"},"work_session_id":{"description":"Spec 082: one client, one project, across reconnects","type":"string"}},"type":"object"},"contracts.ActivityRetentionReport":{"description":"ActivityRetention (Spec 124 FR-035) reports whether the activity caps\nhold the whole work-session retention window. Administrators only.","properties":{"cause":{"description":"Cause is age_cap, record_cap or size_cap.","type":"string"},"observed_at":{"description":"ObservedAt is when the shortfall was last observed.","type":"string"},"oldest_complete_session_at":{"description":"OldestCompleteSessionAt is the start of the oldest session that still\nhas all of its rows: complete history reaches back to here.","type":"string"},"raise":{"description":"Raise names the settings to raise for the cause.","items":{"type":"string"},"type":"array","uniqueItems":false},"shortfall":{"description":"Shortfall is true when a work session inside the window lost rows\nbecause a cap was reached, and a full window has not passed since.","type":"boolean"},"window_days":{"description":"WindowDays is the work-session retention window.","type":"integer"}},"type":"object"},"contracts.ActivitySource":{"description":"How activity was triggered: \"mcp\", \"cli\", \"api\"","type":"string","x-enum-varnames":["ActivitySourceMCP","ActivitySourceCLI","ActivitySourceAPI"]},"contracts.ActivitySummaryResponse":{"properties":{"blocked_count":{"description":"Count of blocked activities","type":"integer"},"call_count":{"description":"CallCount is how many of those records are CALLS THE USER MADE, as\ndefined once in storage.CountsAsCall and shared with the usage aggregate\nbehind the Usage tab (audit finding F1, #1046). TotalCount answers \"how\nmany rows does the Activity Log have\"; CallCount answers \"how many calls\nwere there\". They are different questions — quarantine auto-approvals,\nsystem start, security scans and management chatter are events, not calls\n— and printing either one under the other's label is how the same instance\ncame to report 51 calls on one screen and 19 on another.","type":"integer"},"call_error_count":{"description":"CallErrorCount is the failures within CallCount, so an error RATE computed\nfrom this response has one denominator. It is not ErrorCount: a policy\nblock is a failed call but carries status \"blocked\", and a shed call is an\nerror in neither sense because it never ran.","type":"integer"},"end_time":{"description":"End of the period (RFC3339)","type":"string"},"error_count":{"description":"Count of error activities","type":"integer"},"other_count":{"description":"OtherCount is every record whose status is outside the four-value\nvocabulary above, so that\n\n\tsuccess + error + blocked + rejected + other == total\n\nholds by construction. The status field is a CLOSED vocabulary for tool\ncalls, but the activity log is wider than tool calls: a quarantine change\nstores its ACTION there (\"approved\", \"auto_approved\"), a policy decision\nstores its DECISION (\"allow\"). Those rows were counted in the total and in\nnone of the four buckets, so the Activity Log's own status tiles summed to\nless than the denominator printed beside them — 15+4+0+0 under a \"42\"\n(audit finding F2, #1046). The residual now has a name and a tile.","type":"integer"},"per_server":{"description":"PerServer covers EVERY server with at least one call in the period\n(unlike TopServers, which is capped at 5 and carries no error counts).\nSpec 109 FR-013: the server-card stats line and the macOS Servers rows\nread this — one ` + "`" + `GET /activity/summary` + "`" + ` response per page load — rather\nthan issuing a per-server activity query each. Computed in the same\ncounting pass as the totals above, from the same CountsAsCall/\nIsManagementBuiltin definitions TopServers already uses.","items":{"$ref":"#/components/schemas/contracts.ActivityPerServer"},"type":"array","uniqueItems":false},"period":{"description":"Time period (1h, 24h, 7d, 30d)","type":"string"},"rejected_count":{"description":"RejectedCount is the number of calls shed by a concurrency limiter, or\nrefused because an agent token was over its call budget, before they\nreached an upstream (spec 093, issue #1699). Counted separately from\nerrors: it is proxy backpressure, not an upstream fault, and it is the\nsignal an operator right-sizes max_concurrent_requests and the rate\nlimits against.","type":"integer"},"start_time":{"description":"Start of the period (RFC3339)","type":"string"},"success_count":{"description":"Count of successful activities","type":"integer"},"top_servers":{"description":"Top servers by activity count","items":{"$ref":"#/components/schemas/contracts.ActivityTopServer"},"type":"array","uniqueItems":false},"top_tools":{"description":"Top tools by activity count","items":{"$ref":"#/components/schemas/contracts.ActivityTopTool"},"type":"array","uniqueItems":false},"total_count":{"description":"Total activity count","type":"integer"}},"type":"object"},"contracts.ActivityTopServer":{"properties":{"count":{"description":"Activity count","type":"integer"},"name":{"description":"Server name","type":"string"}},"type":"object"},"contracts.ActivityTopTool":{"properties":{"count":{"description":"Activity count","type":"integer"},"server":{"description":"Server name","type":"string"},"tool":{"description":"Tool name","type":"string"}},"type":"object"},"contracts.ActivityType":{"description":"Type of activity","type":"string","x-enum-varnames":["ActivityTypeToolCall","ActivityTypePolicyDecision","ActivityTypeQuarantineChange","ActivityTypeServerChange"]},"contracts.AddFromRegistryRequest":{"properties":{"enabled":{"description":"defaults to true when nil","type":"boolean"},"env":{"additionalProperties":{"type":"string"},"description":"overrides + required-input values","type":"object"},"name":{"description":"optional name override","type":"string"}},"type":"object"},"contracts.AddRegistrySourceRequest":{"properties":{"id":{"description":"derived from the host when empty","type":"string"},"name":{"description":"defaults to the id","type":"string"},"protocol":{"description":"defaults to modelcontextprotocol/registry","type":"string"},"url":{"description":"required https registry URL","type":"string"}},"type":"object"},"contracts.AttentionFix":{"properties":{"label":{"type":"string"},"target":{"type":"string"},"verb":{"type":"string"}},"type":"object"},"contracts.AttentionItem":{"properties":{"detail":{"type":"string"},"fix":{"$ref":"#/components/schemas/contracts.AttentionFix"},"id":{"description":"kind:type:subject[:state]","type":"string"},"kind":{"type":"string"},"rank":{"type":"integer"},"since":{"type":"string"},"subject":{"$ref":"#/components/schemas/contracts.AttentionSubject"},"summary":{"type":"string"}},"type":"object"},"contracts.AttentionSubject":{"properties":{"id":{"type":"string"},"name":{"type":"string"},"type":{"description":"server|tool|client|setting","type":"string"}},"type":"object"},"contracts.ConfigApplyResult":{"properties":{"applied_immediately":{"type":"boolean"},"changed_fields":{"items":{"type":"string"},"type":"array","uniqueItems":false},"requires_restart":{"type":"boolean"},"restart_reason":{"type":"string"},"success":{"type":"boolean"},"validation_errors":{"items":{"$ref":"#/components/schemas/contracts.ValidationError"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.DCRStatus":{"properties":{"attempted":{"type":"boolean"},"error":{"type":"string"},"status_code":{"type":"integer"},"success":{"type":"boolean"}},"type":"object"},"contracts.DeepScanDescriptor":{"description":"DeepScan reports the opt-in \"deep scan\" layer status (Spec 077 US3),\nSEPARATELY from the baseline verdict above. Always emitted on a computed\nsummary — when deep scan is off (the default) it reports enabled=false\nplus any enabled-but-skipped Docker scanners. It never influences Status.","properties":{"available":{"type":"boolean"},"enabled":{"type":"boolean"},"ran":{"type":"boolean"},"scanners_failed":{"items":{"$ref":"#/components/schemas/contracts.DeepScanScannerFailure"},"type":"array","uniqueItems":false},"skipped_scanners":{"description":"SkippedScanners lists Docker scanners the user enabled that are skipped\nbecause security.deep_scan.enabled is false (informational).","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.DeepScanScannerFailure":{"properties":{"id":{"type":"string"},"reason":{"type":"string"}},"type":"object"},"contracts.DeprecatedConfigWarning":{"properties":{"field":{"type":"string"},"message":{"type":"string"},"replacement":{"type":"string"}},"type":"object"},"contracts.Diagnostic":{"description":"Spec 044 — structured diagnostic error and stable error code. Both\nare populated when the server is in a failed state and the error\nhas been classified by internal/diagnostics. Healthy servers omit\nthese fields.","properties":{"cause":{"type":"string"},"code":{"type":"string"},"detected_at":{"type":"string"},"docs_url":{"type":"string"},"fix_steps":{"items":{"$ref":"#/components/schemas/contracts.DiagnosticFixStep"},"type":"array","uniqueItems":false},"severity":{"type":"string"},"user_message":{"type":"string"}},"type":"object"},"contracts.DiagnosticFixStep":{"properties":{"command":{"type":"string"},"destructive":{"type":"boolean"},"fixer_key":{"type":"string"},"label":{"type":"string"},"type":{"type":"string"},"url":{"type":"string"}},"type":"object"},"contracts.Diagnostics":{"properties":{"activity_retention":{"$ref":"#/components/schemas/contracts.ActivityRetentionReport"},"deprecated_configs":{"description":"Deprecated config fields found","items":{"$ref":"#/components/schemas/contracts.DeprecatedConfigWarning"},"type":"array","uniqueItems":false},"docker_status":{"$ref":"#/components/schemas/contracts.DockerStatus"},"missing_secrets":{"description":"Renamed to avoid conflict","items":{"$ref":"#/components/schemas/contracts.MissingSecretInfo"},"type":"array","uniqueItems":false},"oauth_issues":{"description":"OAuth parameter mismatches","items":{"$ref":"#/components/schemas/contracts.OAuthIssue"},"type":"array","uniqueItems":false},"oauth_required":{"items":{"$ref":"#/components/schemas/contracts.OAuthRequirement"},"type":"array","uniqueItems":false},"oauth_token_storage":{"$ref":"#/components/schemas/contracts.OAuthTokenStorageReport"},"runtime_warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false},"timestamp":{"type":"string"},"total_issues":{"type":"integer"},"upstream_errors":{"items":{"$ref":"#/components/schemas/contracts.UpstreamError"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.DockerStatus":{"properties":{"available":{"type":"boolean"},"error":{"type":"string"},"version":{"type":"string"}},"type":"object"},"contracts.EditRegistrySourceRequest":{"properties":{"name":{"description":"new display name","type":"string"},"servers_url":{"description":"explicit servers-collection URL","type":"string"},"url":{"description":"new base/servers https URL","type":"string"}},"type":"object"},"contracts.ErrorResponse":{"properties":{"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.FindingCounts":{"properties":{"dangerous":{"description":"Tool poisoning, active prompt injection","type":"integer"},"info":{"description":"Low-severity CVEs, informational","type":"integer"},"total":{"type":"integer"},"warning":{"description":"Rug pull, supply chain CVEs with exploits","type":"integer"}},"type":"object"},"contracts.GetConfigResponse":{"properties":{"config":{"description":"The configuration object","type":"object"},"config_path":{"description":"Path to config file","type":"string"}},"type":"object"},"contracts.GetRegistriesResponse":{"properties":{"registries":{"items":{"$ref":"#/components/schemas/contracts.Registry"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GetServerLogsResponse":{"properties":{"count":{"type":"integer"},"logs":{"items":{"$ref":"#/components/schemas/contracts.LogEntry"},"type":"array","uniqueItems":false},"server_name":{"type":"string"}},"type":"object"},"contracts.GetServerToolCallsResponse":{"properties":{"server_name":{"type":"string"},"tool_calls":{"items":{"$ref":"#/components/schemas/contracts.ToolCallRecord"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GetServerToolsResponse":{"properties":{"count":{"type":"integer"},"incarnation":{"description":"Incarnation is the committed incarnation of the server the tools were\nread for (Spec 116 FR-017), captured before they were fetched; omitted\nwhen unknown.","type":"integer"},"server_name":{"type":"string"},"tools":{"items":{"$ref":"#/components/schemas/contracts.Tool"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.GetServersResponse":{"properties":{"servers":{"items":{"$ref":"#/components/schemas/contracts.Server"},"type":"array","uniqueItems":false},"stats":{"$ref":"#/components/schemas/contracts.ServerStats"}},"type":"object"},"contracts.GetSessionDetailResponse":{"properties":{"session":{"$ref":"#/components/schemas/contracts.MCPSession"}},"type":"object"},"contracts.GetSessionsResponse":{"properties":{"limit":{"type":"integer"},"offset":{"type":"integer"},"sessions":{"items":{"$ref":"#/components/schemas/contracts.MCPSession"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GetToolCallDetailResponse":{"properties":{"tool_call":{"$ref":"#/components/schemas/contracts.ToolCallRecord"}},"type":"object"},"contracts.GetToolCallsResponse":{"properties":{"limit":{"type":"integer"},"offset":{"type":"integer"},"tool_calls":{"items":{"$ref":"#/components/schemas/contracts.ToolCallRecord"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GlobalToolsResponse":{"properties":{"counts":{"$ref":"#/components/schemas/contracts.ViewAsCounts"},"failed_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"partial":{"type":"boolean"},"stats":{"$ref":"#/components/schemas/contracts.GlobalToolsStats"},"tools":{"items":{"$ref":"#/components/schemas/contracts.Tool"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.GlobalToolsStats":{"properties":{"disabled":{"type":"integer"},"enabled":{"type":"integer"},"pending_approval":{"type":"integer"},"total":{"type":"integer"}},"type":"object"},"contracts.HealthStatus":{"description":"Unified health status calculated by the backend","properties":{"action":{"description":"Action is the suggested fix action: \"login\", \"restart\", \"enable\", \"approve\", \"view_logs\", \"set_secret\", \"configure\", \"edit_url\", or \"\" (none)\nInvariant: Action always equals Actions[0], or \"\" when Actions is empty.","type":"string"},"actions":{"description":"Actions lists every applicable next step in priority order (FR-012):\nlogin \u003e set_secret \u003e configure \u003e edit_url \u003e approve \u003e restart \u003e\nview_logs \u003e enable. Always non-nil (empty slice, never null).","items":{"type":"string"},"type":"array","uniqueItems":false},"admin_state":{"description":"AdminState indicates the admin state: \"enabled\", \"disabled\", or \"quarantined\"","type":"string"},"detail":{"description":"Detail is an optional longer explanation of the status","type":"string"},"level":{"description":"Level indicates the health level: \"healthy\", \"degraded\", or \"unhealthy\"","type":"string"},"status":{"description":"Status is the ONE status vocabulary rendered as text on every surface\n(Web UI, macOS, tray, CLI) — Spec 109 FR-010/FR-011. Values: \"ready\",\n\"connecting\", \"sign_in_required\", \"needs_review\", \"needs_secret\",\n\"needs_config\", \"error\", \"disabled\". Unlike Level (a severity signal for\nbadge/tray coloring only), no renderer may print Level as text.","type":"string"},"summary":{"description":"Summary is a human-readable status message (e.g., \"Connected (5 tools)\")","type":"string"},"usable":{"description":"Usable reports whether the server can currently serve tool calls. True\nonly when Status == \"ready\".","type":"boolean"}},"type":"object"},"contracts.InfoEndpoints":{"description":"Available API endpoints","properties":{"http":{"description":"HTTP endpoint address (e.g., \"127.0.0.1:8080\")","type":"string"},"socket":{"description":"Unix socket path (empty if disabled)","type":"string"}},"type":"object"},"contracts.InfoResponse":{"properties":{"endpoints":{"$ref":"#/components/schemas/contracts.InfoEndpoints"},"launched_by":{"description":"LaunchedBy is the durable launch provenance of the running core (Spec\n092 FR-001a): \"tray\" when a tray spawned it, \"installer\" when the macOS\nPKG postinstall did, \"\" when user-launched or unknown. Always present\n(possibly empty) so a tray can distinguish \"old core, not mine\" from\n\"old core I may supersede\".","type":"string"},"listen_addr":{"description":"Listen address (e.g., \"127.0.0.1:8080\")","type":"string"},"pid":{"description":"PID is the operating-system process id of the running core (Spec 092\nFR-002). A tray that merely ATTACHED to a core holds no Process handle\nfor it, so without this there is no mechanism at all to stop a stale\ncore — the consent action would have nothing to act on and could only\nprint instructions. Paired with LaunchedBy it is what lets a newer tray\nsupersede a core an older tray started.","type":"integer"},"update":{"$ref":"#/components/schemas/contracts.UpdateInfo"},"update_policy":{"$ref":"#/components/schemas/contracts.UpdatePolicy"},"version":{"description":"Current MCPProxy version","type":"string"},"web_ui_url":{"description":"URL to access the web control panel","type":"string"}},"type":"object"},"contracts.IsolationConfig":{"properties":{"cpu_limit":{"type":"string"},"enabled":{"description":"Enabled is the EFFECTIVE isolation state for this server: whether its\nprocess is actually CONFINED, after the global setting, the per-server\noverride, the structural gates and the host's capabilities. It is NOT the\nraw per-server override — read EnabledOverride for that (GH #1142).\n\nREAD-ONLY. The write surfaces reject an ` + "`" + `enabled` + "`" + ` key precisely because\nit is derived: echoing it back would convert \"inherits the global\nsetting\" into a permanent explicit override. Write EnabledOverride.\n\nIt stays a non-pointer bool that is always present on the wire: the macOS\ntray decodes it as a non-optional Swift Bool, so omitting or nulling the\nkey would fail Codable for the whole server payload. Older clients that\nread this field now simply get a true answer.","type":"boolean"},"enabled_override":{"description":"EnabledOverride is the RAW per-server ` + "`" + `isolation.enabled` + "`" + ` override, as\npersisted. Absent means \"inherit the global setting\" — which is a\ndistinct state from an explicit false, and the distinction the reporting\nbug used to destroy.","type":"boolean"},"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"memory_limit":{"type":"string"},"mode_override":{"description":"ModeOverride is the RAW per-server ` + "`" + `isolation.mode` + "`" + ` override\n(\"docker\" | \"sandbox\" | \"none\"). Absent means \"inherit\".","type":"string"},"network_mode":{"type":"string"},"timeout":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"contracts.IsolationDefaults":{"description":"IsolationDefaults exposes the resolved baseline values that\nwould apply when no per-server override is set. Populated on\nlist/get responses; never consumed on PATCH requests.","properties":{"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"network_mode":{"type":"string"},"runtime_type":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"contracts.IsolationEffective":{"description":"IsolationEffective exposes the resolved isolation state (and the rule\nthat decided it) so clients can distinguish \"inherits global\" from an\nexplicit per-server choice. Read-only; never consumed on PATCH.","properties":{"global_mode":{"description":"GlobalMode is what \"inherit\" resolves to right now.","type":"string"},"inherited":{"description":"Inherited is true when the server sets neither ` + "`" + `isolation.enabled` + "`" + ` nor\n` + "`" + `isolation.mode` + "`" + `, so its state tracks the global setting.","type":"boolean"},"isolated":{"description":"Isolated reports whether the process is actually CONFINED. It is NOT\nsimply Mode != \"none\": \"sandbox\" on a host that cannot enforce Landlock\n(any non-Linux OS, or a kernel without the LSM) runs the server\nunconfined, and Source then says \"sandbox-unavailable\" (GH #1142).","type":"boolean"},"mode":{"description":"Mode is the effective isolation mode: \"docker\" | \"sandbox\" | \"none\" —\nexactly what the spawn path branches on.","type":"string"},"source":{"description":"Source names the deciding rule: \"global\", \"server-mode\",\n\"server-opt-out\", \"server-opt-in-ignored\", \"not-stdio\",\n\"already-docker\", \"sandbox-unavailable\" or \"unsupported-mode\".\nTreat an unrecognized value as \"global\".","type":"string"}},"type":"object"},"contracts.LogEntry":{"properties":{"fields":{"type":"object"},"level":{"type":"string"},"message":{"type":"string"},"server":{"type":"string"},"timestamp":{"type":"string"}},"type":"object"},"contracts.MCPSession":{"properties":{"client_id":{"description":"Scope attribution (Spec 108 FR-033). ClientID and TokenName are the\ncredential the session initialized with; Profile and ProfileSource are\nthe session's latest effective resolution. Empty on legacy sessions.","type":"string"},"client_name":{"type":"string"},"client_version":{"type":"string"},"end_time":{"type":"string"},"experimental":{"items":{"type":"string"},"type":"array","uniqueItems":false},"has_roots":{"description":"MCP Client Capabilities","type":"boolean"},"has_sampling":{"type":"boolean"},"id":{"type":"string"},"last_activity":{"type":"string"},"profile":{"type":"string"},"profile_source":{"type":"string"},"start_time":{"type":"string"},"status":{"type":"string"},"token_name":{"type":"string"},"tool_call_count":{"type":"integer"},"total_tokens":{"type":"integer"},"work_session_id":{"type":"string"},"workspace_name":{"description":"Workspace / work session (Spec 082). WorkspaceName is the project's\nbasename — the full local path is never exposed. WorkSessionID groups the\nreconnects that make up one stretch of user work.","type":"string"}},"type":"object"},"contracts.MetadataStatus":{"properties":{"authorization_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"error":{"type":"string"},"found":{"type":"boolean"},"url_checked":{"type":"string"}},"type":"object"},"contracts.MissingSecretInfo":{"properties":{"secret_name":{"type":"string"},"used_by":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.NPMPackageInfo":{"properties":{"exists":{"type":"boolean"},"install_cmd":{"type":"string"}},"type":"object"},"contracts.OAuthConfig":{"properties":{"auth_server_metadata_url":{"type":"string"},"auth_url":{"type":"string"},"authorization_endpoint":{"description":"Spec 113-b operator overrides of OAuth discovery (https-or-loopback URLs,\nnever credentials). Empty means \"use discovery\".","type":"string"},"client_id":{"type":"string"},"extra_params":{"additionalProperties":{"type":"string"},"type":"object"},"pkce_enabled":{"type":"boolean"},"redirect_port":{"type":"integer"},"refresh_replay_enabled":{"type":"boolean"},"registration_endpoint":{"type":"string"},"scopes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"token_endpoint":{"type":"string"},"token_expires_at":{"description":"When the OAuth token expires","type":"string"},"token_url":{"type":"string"},"token_valid":{"description":"Whether token is currently valid","type":"boolean"}},"type":"object"},"contracts.OAuthErrorDetails":{"description":"Structured discovery/failure details","properties":{"authorization_server_metadata":{"$ref":"#/components/schemas/contracts.MetadataStatus"},"dcr_status":{"$ref":"#/components/schemas/contracts.DCRStatus"},"protected_resource_metadata":{"$ref":"#/components/schemas/contracts.MetadataStatus"},"server_url":{"type":"string"}},"type":"object"},"contracts.OAuthFlowError":{"properties":{"correlation_id":{"description":"Flow tracking ID for log correlation","type":"string"},"debug_hint":{"description":"CLI command for log lookup","type":"string"},"details":{"$ref":"#/components/schemas/contracts.OAuthErrorDetails"},"error_code":{"description":"Machine-readable error code (e.g., OAUTH_NO_METADATA)","type":"string"},"error_type":{"description":"Category of OAuth runtime failure","type":"string"},"message":{"description":"Human-readable error description","type":"string"},"request_id":{"description":"HTTP request ID (from PR #237)","type":"string"},"server_name":{"description":"Server that failed OAuth","type":"string"},"success":{"description":"Always false","type":"boolean"},"suggestion":{"description":"Actionable remediation hint","type":"string"}},"type":"object"},"contracts.OAuthIssue":{"properties":{"documentation_url":{"type":"string"},"error":{"type":"string"},"issue":{"type":"string"},"missing_params":{"items":{"type":"string"},"type":"array","uniqueItems":false},"resolution":{"type":"string"},"server_name":{"type":"string"}},"type":"object"},"contracts.OAuthRequirement":{"properties":{"expires_at":{"type":"string"},"message":{"type":"string"},"server_name":{"type":"string"},"state":{"type":"string"}},"type":"object"},"contracts.OAuthStartResponse":{"properties":{"auth_url":{"description":"Authorization URL (always included for manual use)","type":"string"},"browser_error":{"description":"Error message if browser launch failed","type":"string"},"browser_opened":{"description":"Whether browser launch succeeded","type":"boolean"},"correlation_id":{"description":"UUID for tracking this flow","type":"string"},"message":{"description":"Human-readable status message","type":"string"},"server_name":{"description":"Name of the server being authenticated","type":"string"},"success":{"description":"Always true for successful start","type":"boolean"}},"type":"object"},"contracts.OAuthTokenStorageReport":{"description":"OAuthTokenStorage (Spec 123 FR-030) reports the state of the stored\nupstream OAuth rows: encryption on or off, the public key id, the row\ncounts by state, the undecryptable servers and the compaction advice.\nIt never carries key material or the key reference.","properties":{"compaction_advised":{"description":"CompactionAdvised mirrors the compaction marker: freed pages may still\nhold old plaintext until ` + "`" + `mcpproxy db compact --keep-backup=false` + "`" + `.","type":"boolean"},"encryption_enabled":{"description":"EncryptionEnabled is true when an encryption key is configured.","type":"boolean"},"key_id":{"description":"KeyID is the public, non-secret id of the configured key (administrator only).","type":"string"},"key_source_in_data_dir":{"description":"KeySourceInDataDir is true when the key file lies inside the data directory.","type":"boolean"},"key_source_kind":{"description":"KeySourceKind is how the key was obtained: literal, env, env_file,\nref_file, ref_env or ref_keyring (administrator only).","type":"string"},"plaintext":{"description":"Plaintext counts valid JSON rows; Sealed counts envelopes the configured\nkey opens; Undecryptable counts everything else.","type":"integer"},"sealed":{"type":"integer"},"servers":{"description":"Servers lists the undecryptable rows by server.","items":{"$ref":"#/components/schemas/contracts.OAuthTokenStorageServer"},"type":"array","uniqueItems":false},"undecryptable":{"type":"integer"},"undecryptable_by_reason":{"$ref":"#/components/schemas/contracts.OAuthTokenUndecryptableByReason"},"warnings":{"description":"Warnings are stable codes: literal_key, key_file_in_data_dir,\nplaintext_rows_with_key, compaction_advised, backup_file_present\n(administrator only).","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.OAuthTokenStorageServer":{"properties":{"bucket_key":{"type":"string"},"reason":{"type":"string"},"row_key_id":{"description":"RowKeyID is the key id in the row's envelope (administrator only).","type":"string"},"server":{"type":"string"}},"type":"object"},"contracts.OAuthTokenUndecryptableByReason":{"description":"UndecryptableByReason breaks Undecryptable down by reason.","properties":{"auth_failed":{"type":"integer"},"key_mismatch":{"type":"integer"},"malformed":{"type":"integer"},"no_key":{"type":"integer"},"unsupported_version":{"type":"integer"}},"type":"object"},"contracts.PreflightPolicy":{"properties":{"exclude_destructive":{"type":"boolean"},"exclude_open_world":{"type":"boolean"},"read_only_only":{"type":"boolean"}},"type":"object"},"contracts.PreflightReason":{"type":"string","x-enum-varnames":["PreflightReasonServerInitializing","PreflightReasonServerUnhealthy","PreflightReasonServerDisabled","PreflightReasonServerQuarantined","PreflightReasonToolPendingApproval","PreflightReasonToolChanged","PreflightReasonToolBlockedByUser","PreflightReasonOAuthRequired","PreflightReasonHashMismatch","PreflightReasonServerNotInScope","PreflightReasonToolDeniedByConfig","PreflightReasonMissingAnnotation","PreflightReasonPolicyFiltered","PreflightReasonNotFound","PreflightReasonServerNotConfigured","PreflightReasonToolBlockedByProfile","PreflightReasonTokenPermissionDenied"]},"contracts.PreflightRequest":{"properties":{"policy":{"$ref":"#/components/schemas/contracts.PreflightPolicy"},"profile":{"description":"Profile evaluates under a named profile's server scope and tool policy;\nit can only narrow a credential's own pin. Unknown: 400.","type":"string"},"tools":{"description":"Tools is 1..100 entries BEFORE dedup; duplicates are collapsed, and\nduplicate ids carrying different pins are a validation error.","items":{"$ref":"#/components/schemas/contracts.PreflightToolRef"},"type":"array","uniqueItems":false},"wait_ms":{"description":"WaitMS polls local state for up to this many milliseconds (cap 10000)\nwhile every failure is retryable-class.","type":"integer"}},"type":"object"},"contracts.PreflightResponse":{"properties":{"checked_at":{"type":"string"},"tools":{"description":"Tools are ordered by first occurrence of each unique id in the request.","items":{"$ref":"#/components/schemas/contracts.PreflightToolResult"},"type":"array","uniqueItems":false},"verdict":{"$ref":"#/components/schemas/contracts.PreflightVerdict"},"waited_ms":{"description":"WaitedMS is present when wait_ms was requested (0 when the wait\nsemaphore was exhausted and the request resolved immediately).","type":"integer"}},"type":"object"},"contracts.PreflightStatus":{"type":"string","x-enum-varnames":["PreflightStatusReady","PreflightStatusUnavailable"]},"contracts.PreflightToolRef":{"properties":{"id":{"description":"ID is a canonical \"\u003cserver\u003e:\u003ctool\u003e\" id. A malformed id is answered with a\nper-ID not_found carrying a format hint, never a request-level error.","type":"string"},"pin_hash":{"description":"PinHash is \"sha256/v{N}:{hex}\" — the schema version is embedded so a\nproxy-side hash-algorithm bump is distinguishable from upstream drift.","type":"string"}},"type":"object"},"contracts.PreflightToolResult":{"properties":{"action":{"type":"string"},"detail":{"type":"string"},"did_you_mean":{"description":"DidYouMean carries up to 3 nearest caller-visible ids on not_found. It\nnever crosses a scope boundary and never names a quarantined server's\ntools.","items":{"type":"string"},"type":"array","uniqueItems":false},"hash":{"description":"Hash is the tool's current pin (\"sha256/v{N}:{hex}\") — operator tier,\nready results only. Never disclosed to an agent token.","type":"string"},"id":{"type":"string"},"reason":{"$ref":"#/components/schemas/contracts.PreflightReason"},"remediation":{"type":"string"},"retryable":{"type":"boolean"},"status":{"$ref":"#/components/schemas/contracts.PreflightStatus"}},"type":"object"},"contracts.PreflightVerdict":{"type":"string","x-enum-varnames":["PreflightVerdictReady","PreflightVerdictDegradedRetryable","PreflightVerdictBlocked","PreflightVerdictUnknownIDs"]},"contracts.QuarantineStats":{"description":"Tool quarantine metrics for this server","properties":{"blocked_count":{"description":"Number of disabled (blocked) tools","type":"integer"},"changed_count":{"description":"Number of tools whose description/schema changed since approval","type":"integer"},"pending_count":{"description":"Number of newly discovered tools awaiting approval","type":"integer"}},"type":"object"},"contracts.RefreshRegistryResponse":{"properties":{"cleared":{"description":"number of cached entries dropped","type":"integer"},"registry_id":{"type":"string"}},"type":"object"},"contracts.Registry":{"properties":{"count":{"description":"number or string","type":"string"},"description":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"},"protocol":{"type":"string"},"provenance":{"description":"Provenance is the trust tag (MCP-866): \"official/trusted\" for built-in\ndefaults, \"custom/unverified\" for user-added registries.","type":"string"},"servers_url":{"type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"trusted":{"description":"Trusted indicates whether this is an official, shipped-by-default\nregistry. Trust is derived from membership in the default set, never\nfrom self-assertion in config.","type":"boolean"},"url":{"type":"string"}},"type":"object"},"contracts.RegistryCacheInfo":{"properties":{"age_seconds":{"type":"number"},"stale":{"type":"boolean"}},"type":"object"},"contracts.RegistryUnavailable":{"properties":{"reason":{"type":"string"}},"type":"object"},"contracts.ReplayToolCallRequest":{"properties":{"arguments":{"description":"Modified arguments for replay","type":"object"}},"type":"object"},"contracts.ReplayToolCallResponse":{"properties":{"error":{"description":"Error if replay failed","type":"string"},"new_call_id":{"description":"ID of the newly created call","type":"string"},"new_tool_call":{"$ref":"#/components/schemas/contracts.ToolCallRecord"},"replayed_from":{"description":"Original call ID","type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.RepositoryInfo":{"description":"Detected package info","properties":{"npm":{"$ref":"#/components/schemas/contracts.NPMPackageInfo"}},"type":"object"},"contracts.RepositoryServer":{"properties":{"connect_url":{"description":"Alternative connection URL","type":"string"},"created_at":{"type":"string"},"description":{"type":"string"},"id":{"type":"string"},"install_cmd":{"description":"Installation command","type":"string"},"name":{"type":"string"},"registry":{"description":"Which registry this came from","type":"string"},"repository_info":{"$ref":"#/components/schemas/contracts.RepositoryInfo"},"source_code_url":{"description":"Source repository URL","type":"string"},"updated_at":{"type":"string"},"url":{"description":"MCP endpoint for remote servers only","type":"string"}},"type":"object"},"contracts.SearchRegistryServersResponse":{"properties":{"cache":{"$ref":"#/components/schemas/contracts.RegistryCacheInfo"},"query":{"type":"string"},"registry_id":{"type":"string"},"servers":{"items":{"$ref":"#/components/schemas/contracts.RepositoryServer"},"type":"array","uniqueItems":false},"tag":{"type":"string"},"total":{"type":"integer"},"unavailable":{"$ref":"#/components/schemas/contracts.RegistryUnavailable"}},"type":"object"},"contracts.SearchResult":{"properties":{"matches":{"type":"integer"},"score":{"type":"number"},"snippet":{"type":"string"},"tool":{"$ref":"#/components/schemas/contracts.Tool"}},"type":"object"},"contracts.SearchToolsResponse":{"properties":{"query":{"type":"string"},"results":{"items":{"$ref":"#/components/schemas/contracts.SearchResult"},"type":"array","uniqueItems":false},"took":{"type":"string"},"total":{"type":"integer"}},"type":"object"},"contracts.SecurityScanSummary":{"description":"Latest security scan results summary","properties":{"deep_scan":{"$ref":"#/components/schemas/contracts.DeepScanDescriptor"},"finding_counts":{"$ref":"#/components/schemas/contracts.FindingCounts"},"last_scan_at":{"type":"string"},"risk_score":{"description":"0-100","type":"integer"},"scanners_failed":{"type":"integer"},"scanners_run":{"description":"Scanner coverage for the primary (baseline) scan pass — informational only.\nSpec 077 US3 (FR-008/FR-014): Status is derived SOLELY from the\ndeterministic baseline findings; a failed Docker deep scanner no longer\ndowngrades a clean verdict. That failure is surfaced via DeepScan instead.","type":"integer"},"scanners_total":{"type":"integer"},"status":{"description":"\"clean\", \"warnings\", \"dangerous\", \"failed\", \"not_scanned\", \"scanning\"","type":"string"}},"type":"object"},"contracts.Server":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"authenticated":{"description":"OAuth authentication status","type":"boolean"},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges mirrors config.ServerConfig.AutoApproveToolChanges\n(MCP-2930): the per-server intent to auto-approve new/changed tools past\nthe trust baseline. Tri-state *bool — nil means \"never set\" (omitted from\nthe payload), so the Web UI toggle (MCP-2932) can distinguish unset from\nan explicit false. Read-only on the GET path; PATCH/POST accept it via\nAddServerRequest.","type":"boolean"},"command":{"type":"string"},"connected":{"type":"boolean"},"connected_at":{"type":"string"},"connecting":{"type":"boolean"},"created":{"type":"string"},"diagnostic":{"$ref":"#/components/schemas/contracts.Diagnostic"},"enabled":{"type":"boolean"},"env":{"additionalProperties":{"type":"string"},"type":"object"},"error_code":{"type":"string"},"expose_prompts":{"description":"ExposePrompts mirrors config.ServerConfig.ExposePrompts (F9): the per-server\nprompt-aggregation override. Tri-state *bool — nil/omitted means \"inherit\ndefault aggregation\". Surfaced on GET so a caller that PATCHed the override\ncan read it back; PATCH/POST accept it via AddServerRequest.","type":"boolean"},"expose_skills":{"description":"ExposeSkills mirrors config.ServerConfig.ExposeSkills: the per-server\nskills override. Tri-state *bool; nil/omitted means \"inherit\".","type":"boolean"},"forward_headers":{"description":"ForwardHeaders mirrors config.ServerConfig.ForwardHeaders (Spec 112): the\nallowlist of inbound MCP client header NAMES forwarded to this server on\ntools/call. Names only, never values. Omitted when empty.","items":{"type":"string"},"type":"array","uniqueItems":false},"generation":{"description":"Generation is the server's committed config generation (Spec 116\nFR-017): it changes whenever the server's configuration changes.","type":"integer"},"headers":{"additionalProperties":{"type":"string"},"type":"object"},"health":{"$ref":"#/components/schemas/contracts.HealthStatus"},"id":{"type":"string"},"incarnation":{"description":"Incarnation changes only when the name is removed and created again\n(Spec 116 FR-017). Approval endpoints accept it back as\nexpected_incarnation and answer 409 server_replaced on a mismatch.","type":"integer"},"init_timeout":{"description":"InitTimeout mirrors config.ServerConfig.InitTimeout (MCP-3322 / GH #760):\nthe per-server MCP ` + "`" + `initialize` + "`" + ` handshake deadline override. Serialized as\na duration string (e.g. \"120s\"); nil/omitted means \"inherit the global\ndefault\". Surfaced on the GET path so clients can read back a configured\noverride; PATCH/POST accept it via AddServerRequest.","type":"string"},"isolation":{"$ref":"#/components/schemas/contracts.IsolationConfig"},"isolation_defaults":{"$ref":"#/components/schemas/contracts.IsolationDefaults"},"isolation_effective":{"$ref":"#/components/schemas/contracts.IsolationEffective"},"last_error":{"type":"string"},"last_reconnect_at":{"type":"string"},"last_retry_time":{"type":"string"},"max_concurrent_requests":{"description":"Spec 093 (GH #955) — per-server concurrency overrides, scope (c) of\nFR-020. Each setting is tri-state: nil (omitted) means \"inherit\nserver_concurrency_defaults\", 0 disables that setting for this server,\npositive overrides it. Surfaced on the GET path so a caller can read back\nwhat it set; PATCH/POST accept them via AddServerRequest. The effective\nconcurrency for a server is additionally bounded by the global aggregate\nlimiter, which is NOT an inheritance source for these fields.","type":"integer"},"name":{"type":"string"},"oauth":{"$ref":"#/components/schemas/contracts.OAuthConfig"},"oauth_status":{"description":"OAuth status: \"authenticated\", \"expired\", \"error\", \"none\"","type":"string"},"protocol":{"type":"string"},"quarantine":{"$ref":"#/components/schemas/contracts.QuarantineStats"},"quarantined":{"type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_count":{"type":"integer"},"reconnect_on_use":{"description":"Attempt reconnection when a tool call targets this disconnected server","type":"boolean"},"retry_count":{"type":"integer"},"retry_stopped":{"description":"RetryStopped reports that automatic reconnection has been given up for\ngood because the failure is deterministic and unrecoverable — a missing\nbinary, an image without the interpreter, an unparseable config (GH\n#1145). It is NOT ordinary exponential backoff, which keeps retrying;\nnothing will happen until the user fixes the config or restarts the\nserver. RetryStoppedCode is the stable MCPX_* code that proved it and\nRetryStoppedReason the catalog message explaining how to fix it. All three\nare omitted for servers that are healthy or still retrying.","type":"boolean"},"retry_stopped_code":{"type":"string"},"retry_stopped_reason":{"type":"string"},"security_scan":{"$ref":"#/components/schemas/contracts.SecurityScanSummary"},"should_retry":{"type":"boolean"},"source_registry_id":{"description":"MCP-901 — registry provenance of an upstream that was added from a\nregistry. SourceRegistryID names the source registry (empty for\nmanually-configured servers); SourceRegistryProvenance is the trust tag\nrecorded at add time (\"official/trusted\" or \"custom/unverified\"). Both\nare projected from config.ServerConfig so the approval/quarantine view\ncan render an \"added from \u003cregistry\u003e · unverified\" origin badge. Optional\nand omitted when empty — clients that pre-date this treat them as absent.","type":"string"},"source_registry_provenance":{"type":"string"},"status":{"type":"string"},"token_expires_at":{"description":"When the OAuth token expires (ISO 8601)","type":"string"},"tool_argument_error_mode":{"type":"string"},"tool_count":{"type":"integer"},"tool_list_token_size":{"description":"Token size for this server's tools","type":"integer"},"trust_mode":{"description":"TrustMode mirrors config.ServerConfig.TrustMode (spec 086): the per-server\ntrust tier (\"auto\"/\"scan\"/\"manual\"). Surfaced on the GET path so clients can\nread back the persisted mode; PATCH/POST accept it via AddServerRequest.\nOmitted when empty (server predates the field / relies on legacy flags).","type":"string"},"updated":{"type":"string"},"url":{"type":"string"},"user_logged_out":{"description":"True if user explicitly logged out (prevents auto-reconnection)","type":"boolean"},"working_dir":{"type":"string"}},"type":"object"},"contracts.ServerActionResponse":{"properties":{"action":{"type":"string"},"async":{"type":"boolean"},"server":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.ServerStats":{"properties":{"connected_servers":{"type":"integer"},"docker_containers":{"type":"integer"},"quarantined_servers":{"type":"integer"},"token_metrics":{"$ref":"#/components/schemas/contracts.ServerTokenMetrics"},"total_servers":{"type":"integer"},"total_tools":{"type":"integer"}},"type":"object"},"contracts.ServerTokenMetrics":{"properties":{"average_query_result_size":{"description":"Typical retrieve_tools output (tokens)","type":"integer"},"estimated":{"description":"Estimated (Spec 109-k FR-070-ish, url-filter-contract.md / audit F-Token):\ntrue while AverageQueryResultSize is a synthetic simulation (a sample of\nthe first ` + "`" + `tools_limit` + "`" + ` tools' schemas — no real retrieve_tools call has\ncompleted yet in this runtime's usage aggregate); false once at least one\nreal retrieve_tools call has, at which point AverageQueryResultSize is\nderived from the real observed average response size instead. The Web\nUI and macOS render an \"estimate\" label while this is true.","type":"boolean"},"per_server_tool_list_sizes":{"additionalProperties":{"type":"integer"},"description":"Token size per server","type":"object"},"saved_tokens":{"description":"Difference","type":"integer"},"saved_tokens_percentage":{"description":"Percentage saved","type":"number"},"total_server_tool_list_size":{"description":"All upstream tools combined (tokens)","type":"integer"}},"type":"object"},"contracts.SkillContentResponse":{"properties":{"digest":{"type":"string"},"next_offset":{"description":"NextOffset is the byte offset of the next chunk; absent at the end.","type":"integer"},"offset":{"type":"integer"},"size":{"type":"integer"},"text":{"type":"string"}},"type":"object"},"contracts.SkillEntry":{"properties":{"approved_at":{"description":"ApprovedAt is omitted when the skill was never approved.","type":"string"},"approved_by":{"type":"string"},"approved_files":{"description":"ApprovedFiles is the file set of the approved copy; omitted when the\nskill has no approved copy. ` + "`" + `skills show --diff` + "`" + ` compares it with Files.","items":{"$ref":"#/components/schemas/contracts.SkillFileInfo"},"type":"array","uniqueItems":false},"approved_hash":{"type":"string"},"available":{"type":"boolean"},"blocked":{"type":"boolean"},"current_hash":{"type":"string"},"description":{"type":"string"},"files":{"items":{"$ref":"#/components/schemas/contracts.SkillFileInfo"},"type":"array","uniqueItems":false},"id":{"type":"string"},"listed":{"type":"boolean"},"name":{"type":"string"},"path":{"type":"string"},"scan":{"$ref":"#/components/schemas/contracts.SkillScanInfo"},"status":{"type":"string"},"total_size":{"type":"integer"},"unusable_reason":{"type":"string"},"uri":{"type":"string"}},"type":"object"},"contracts.SkillFileInfo":{"properties":{"digest":{"type":"string"},"path":{"type":"string"},"size":{"type":"integer"},"text":{"type":"boolean"}},"type":"object"},"contracts.SkillScanFinding":{"properties":{"evidence":{"type":"string"},"file":{"type":"string"},"offset":{"type":"integer"},"rule":{"type":"string"},"severity":{"type":"string"}},"type":"object"},"contracts.SkillScanInfo":{"properties":{"complete":{"type":"boolean"},"findings":{"items":{"$ref":"#/components/schemas/contracts.SkillScanFinding"},"type":"array","uniqueItems":false},"findings_truncated":{"description":"FindingsTruncated is true when more findings existed than are listed.","type":"boolean"},"incomplete":{"description":"Incomplete says why Complete is false: size_cap, time_limit, coverage or\ninterrupted; empty when the scan is complete.","type":"string"},"scanned_at":{"description":"ScannedAt is omitted when no scan of the current content exists.","type":"string"},"verdict":{"type":"string"}},"type":"object"},"contracts.SkillsApproveRequest":{"properties":{"expected_hashes":{"additionalProperties":{"type":"string"},"description":"ExpectedHashes maps each skill path to the current_hash the reviewer\nsaw. A skill without an entry is refused as unreviewed.","type":"object"},"expected_incarnation":{"description":"ExpectedIncarnation binds the approval to the server the reviewer saw;\n0 (or absent) binds to the incarnation current when the request starts.","type":"integer"},"skills":{"description":"Skills are skill paths (the part of the id after \"\u003cserver\u003e:\"), 1 to 200.","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.SkillsApproveResponse":{"properties":{"approved":{"description":"Approved counts the skills newly approved; a skill already approved for\nits current content is not counted.","type":"integer"}},"type":"object"},"contracts.SkillsBlockRequest":{"properties":{"expected_incarnation":{"type":"integer"},"skills":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.SkillsBlockResponse":{"properties":{"changed":{"description":"Changed counts the skills whose blocked mark changed.","type":"integer"}},"type":"object"},"contracts.SkillsErrorResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.SkillsListResponse":{"properties":{"enabled":{"type":"boolean"},"error":{"type":"string"},"expose_skills":{"type":"boolean"},"incarnation":{"description":"Incarnation is the server's approval incarnation: send it back as\nexpected_incarnation on approve, block and unblock.","type":"integer"},"last_refresh":{"type":"string"},"server":{"type":"string"},"skills":{"items":{"$ref":"#/components/schemas/contracts.SkillEntry"},"type":"array","uniqueItems":false},"supported":{"type":"boolean"},"truncated":{"type":"boolean"}},"type":"object"},"contracts.SkillsStaleReviewResponse":{"properties":{"changed":{"items":{"type":"string"},"type":"array","uniqueItems":false},"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"},"unreviewed":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.SkillsUnusableResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"skills":{"items":{"type":"string"},"type":"array","uniqueItems":false},"success":{"type":"boolean"}},"type":"object"},"contracts.SuccessResponse":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"success":{"type":"boolean"}},"type":"object"},"contracts.Tier":{"description":"Tier is computed by AnnotationTier (Spec 109 FR-028/X11) from\nAnnotations — read|write|destructive|unannotated. Set by every producer\nof a Tool (enrichServerTools, the global tools handler); never left for\na consuming surface to compute.","type":"string","x-enum-varnames":["TierRead","TierWrite","TierDestructive","TierUnannotated","TierUnknown"]},"contracts.TokenMetrics":{"description":"Token usage metrics (nil for older records)","properties":{"encoding":{"description":"Encoding used (e.g., cl100k_base)","type":"string"},"estimated_cost":{"description":"Optional cost estimate","type":"number"},"input_tokens":{"description":"Tokens in the request","type":"integer"},"model":{"description":"Model used for tokenization","type":"string"},"output_tokens":{"description":"Tokens in the response","type":"integer"},"total_tokens":{"description":"Total tokens (input + output)","type":"integer"},"truncated_tokens":{"description":"Tokens removed by truncation","type":"integer"},"was_truncated":{"description":"Whether response was truncated","type":"boolean"}},"type":"object"},"contracts.Tool":{"properties":{"access":{"$ref":"#/components/schemas/contracts.ToolAccess"},"annotations":{"$ref":"#/components/schemas/contracts.ToolAnnotation"},"approval_status":{"type":"string"},"config_denied":{"description":"ConfigDenied is true when the tool is denied by the server's static\nenabled_tools / disabled_tools config. The user cannot override this toggle.","type":"boolean"},"description":{"type":"string"},"disabled":{"description":"Disabled mirrors ToolApprovalRecord.Disabled so per-tool enable state is\navailable without a second round-trip to the approvals endpoint. Absent\nin the JSON when false (default) to keep responses compact.","type":"boolean"},"hash":{"description":"Hash is the tool's current stored hash rendered in the preflight pin\nformat \"sha256/v{N}:{hex}\" (Spec 098 FR-011), where N is the approval\nrecord's HashSchemaVersion. It is the authoring surface for\n` + "`" + `POST /api/v1/preflight` + "`" + ` pins and ` + "`" + `mcpproxy tools preflight --pin` + "`" + `:\ncopy the value straight into a pin.\n\nDisclosure is OPERATOR TIER ONLY — same rule as the preflight per-tool\nresult. The field is omitted for agent-token callers and for tools with\nno stored hash (no approval record yet, or a record written before\nhashes existed).","type":"string"},"held_reason":{"description":"HeldReason, HeldVerdict and HeldSignals mirror the same-named fields on\nstorage.ToolApprovalRecord: the offline-scan evidence that made\ntrust_mode: scan hold this tool for review (spec 086 FR-018). HeldSignals\nnames the matched deterministic check ids, e.g.\n\"tpa.TPA-2026-0001.hidden_instruction\", so a reviewer can see WHY the tool\nis held. All three are omitted for tools that are not held by the scan gate\n(including every record written before the field existed).","type":"string"},"held_signals":{"items":{"type":"string"},"type":"array","uniqueItems":false},"held_verdict":{"type":"string"},"last_used":{"type":"string"},"name":{"type":"string"},"profile_tier":{"description":"ProfileTier and Access are present only in a view-as listing (a tools\nlisting with ?client= or ?profile=, Spec 108 FR-032). ProfileTier is the\ntool's tier under the viewed subject's profile (Tier above stays the\nintrinsic tier); Access is the subject's verdict for the tool. Absent\notherwise, so an ordinary listing is byte-identical to before.","type":"string","x-enum-varnames":["TierRead","TierWrite","TierDestructive","TierUnannotated","TierUnknown"]},"schema":{"type":"object"},"server_incarnation":{"description":"ServerIncarnation is the committed incarnation of the server this row\nwas read for (Spec 116 FR-017), captured before the tools were fetched.\nA client echoes it as expected_incarnation on a per-tool decision, so a\nstale row is refused (409 server_replaced) after a same-name re-add.\nOmitted when the server has no committed incarnation.","type":"integer"},"server_name":{"type":"string"},"tier":{"$ref":"#/components/schemas/contracts.Tier"},"usage":{"type":"integer"}},"type":"object"},"contracts.ToolAccess":{"properties":{"callable":{"type":"boolean"},"reason":{"type":"string"},"visible":{"type":"boolean"}},"type":"object"},"contracts.ToolAnnotation":{"description":"Tool behavior hints snapshot","properties":{"destructiveHint":{"type":"boolean"},"idempotentHint":{"type":"boolean"},"openWorldHint":{"type":"boolean"},"readOnlyHint":{"type":"boolean"},"title":{"type":"string"}},"type":"object"},"contracts.ToolCallRecord":{"description":"The new tool call record","properties":{"annotations":{"$ref":"#/components/schemas/contracts.ToolAnnotation"},"arguments":{"description":"Tool arguments","type":"object"},"arguments_truncated":{"description":"ArgumentsTruncated marks Arguments as a placeholder rather than the\narguments the tool was called with. Replaying such a record without\nsupplying arguments explicitly is refused.","type":"boolean"},"config_path":{"description":"Active config file path","type":"string"},"duration":{"description":"Duration in nanoseconds","type":"integer"},"error":{"description":"Error message (failure only)","type":"string"},"execution_type":{"description":"\"direct\" or \"code_execution\"","type":"string"},"id":{"description":"Unique identifier","type":"string"},"mcp_client_name":{"description":"MCP client name from InitializeRequest","type":"string"},"mcp_client_version":{"description":"MCP client version","type":"string"},"mcp_session_id":{"description":"MCP session identifier","type":"string"},"metrics":{"$ref":"#/components/schemas/contracts.TokenMetrics"},"parent_call_id":{"description":"Links nested calls to parent code_execution","type":"string"},"request_id":{"description":"Request correlation ID","type":"string"},"response":{"description":"Tool response (success only)","type":"object"},"response_bytes":{"description":"Marshalled response size before truncation","type":"integer"},"response_truncated":{"description":"ResponseTruncated and ResponseBytes describe a STORAGE-side cut (#1176):\nthe caller received the response whole, and only the persisted copy was\nshortened to tool_call_max_response_size. When ResponseTruncated is true\nthe Response object carries {truncated, original_bytes, preview, note}\ninstead of the upstream result, and ResponseBytes is its size before the\ncut.","type":"boolean"},"server_id":{"description":"Server identity hash","type":"string"},"server_name":{"description":"Human-readable server name","type":"string"},"timestamp":{"description":"When the call was made","type":"string"},"tool_name":{"description":"Tool name (without server prefix)","type":"string"}},"type":"object"},"contracts.UpdateInfo":{"description":"Update information (if available)","properties":{"available":{"description":"Whether an update is available","type":"boolean"},"behind_summary":{"description":"Spec 079 FR-002 — how far behind the running build is. All four are\nadditive (FR-021) and absent when the delta could not be resolved, in\nwhich case every surface renders its pre-delta wording.","type":"string"},"check_error":{"description":"Error message if update check failed","type":"string"},"checked_at":{"description":"When the update check was performed","type":"string"},"install_channel":{"description":"Detected install channel (homebrew, dmg, deb, rpm, docker, go-install, windows-installer, tarball, unknown) — Spec 079 FR-008","type":"string"},"is_prerelease":{"description":"Whether the latest version is a prerelease","type":"boolean"},"latest_version":{"description":"Latest version available (e.g., \"v1.2.3\")","type":"string"},"nudges_suppressed":{"description":"UI surfaces must stay quiet (CI / non-interactive context); machine-readable fields still report the facts — Spec 079 FR-019","type":"boolean"},"release_url":{"description":"URL to the release page","type":"string"},"releases_behind":{"description":"Releases on the offered channel between the running and offered versions","type":"integer"},"releases_behind_saturated":{"description":"ReleasesBehind is a lower bound: the running build predates the scanned release window","type":"boolean"},"update_command":{"description":"One-line update command for the channel; only set when an update is available and the channel has one — Spec 079 FR-009","type":"string"},"weeks_behind":{"description":"Whole weeks between the two releases' publish dates; 0 is a real value, absent means unknown","type":"integer"}},"type":"object"},"contracts.UpdatePolicy":{"description":"UpdatePolicy is the effective, hot-reloadable update policy (Spec 092\nFR-015). Always present: the ` + "`" + `update` + "`" + ` object above is omitted both when\nupdate checking is disabled AND when no check has produced a result\nyet, so its absence cannot tell a client whether it is allowed to run\nits own (e.g. Sparkle feed) check. This field states the answer.","properties":{"channel":{"description":"Channel is the tracked release channel: \"stable\" or \"rc\".","type":"string"},"enabled":{"description":"Enabled is the effective automatic-check kill switch: update_check.enabled\nwith MCPPROXY_DISABLE_AUTO_UPDATE=true winning over it. A user-initiated\n\"Check for Updates\" stays available regardless.","type":"boolean"},"nudges_suppressed":{"description":"NudgesSuppressed asks UI surfaces to stay quiet (CI / non-interactive)\nwhile machine-readable fields keep reporting the facts.","type":"boolean"}},"type":"object"},"contracts.UpstreamError":{"properties":{"error_message":{"type":"string"},"server_name":{"type":"string"},"timestamp":{"type":"string"}},"type":"object"},"contracts.UsageAggregateResponse":{"properties":{"freshness_ms":{"description":"age of the underlying snapshot in ms","type":"integer"},"generated_at":{"type":"string"},"other":{"$ref":"#/components/schemas/contracts.UsageOtherBucket"},"timeline":{"items":{"$ref":"#/components/schemas/contracts.UsageTimeBucket"},"type":"array","uniqueItems":false},"token_source":{"description":"\"bytes\" (size-based proxy, FR-006)","type":"string"},"tokens_saved":{"description":"echoed from ServerTokenMetrics (FR-007)","type":"integer"},"tokens_saved_estimated":{"description":"TokensSavedEstimated echoes ServerTokenMetrics.Estimated (Spec 109-k):\ntrue while TokensSaved is a synthetic simulation rather than derived\nfrom a real retrieve_tools call. Dropped (false, the zero value) for a\nscoped caller along with TokensSaved itself, above.","type":"boolean"},"tokens_saved_percentage":{"type":"number"},"tools":{"items":{"$ref":"#/components/schemas/contracts.UsageToolStat"},"type":"array","uniqueItems":false},"total_calls":{"description":"TotalCalls and TotalErrors are the headline counts for the window: the sum\nof the timeline this same response carries, so the tiles and the histogram\nunder them cannot disagree. They are NOT the sum of Tools — that list is\nlifetime-cumulative, upstream-only and truncated to top-N, and summing it\nclient-side is what made the Usage tab print a third number for the same\n24 hours (audit finding F1, #1046). The population is\nstorage.CountsAsCall, shared with ActivitySummaryResponse.CallCount.\n\nTwo bounds on how exactly this matches the Activity Log's own count.\nBoth are bounded and disclosed, unlike the population mismatch they\nreplace, which was unbounded and silent:\n\n - Window granularity is the timeline's: whole hour buckets, so the span\n is the requested window rounded up to a bucket edge.\n - This response is served from a snapshot behind a short read cache\n (observability.usage_cache_ttl, 5s by default) so the endpoint never\n scans the activity log per request, while the summary endpoint counts\n live. Calls that land inside that window appear on the Activity Log\n first. FreshnessMs and GeneratedAt say how old the figures are, and\n the Usage tab prints it (\"Updated 3s ago\").","type":"integer"},"total_errors":{"type":"integer"},"window":{"type":"string"}},"type":"object"},"contracts.UsageOtherBucket":{"description":"present only when the list was truncated to top-N","properties":{"calls":{"type":"integer"},"tools_folded":{"type":"integer"},"total_resp_bytes":{"type":"integer"}},"type":"object"},"contracts.UsageTimeBucket":{"properties":{"calls":{"type":"integer"},"errors":{"type":"integer"},"start":{"type":"string"},"total_resp_bytes":{"type":"integer"}},"type":"object"},"contracts.UsageToolStat":{"properties":{"avg_req_bytes":{"description":"null when no sized request calls","type":"integer"},"avg_resp_bytes":{"description":"null when sized_calls == 0 (only legacy 0-byte calls)","type":"integer"},"blocked":{"type":"integer"},"calls":{"type":"integer"},"error_rate":{"type":"number"},"errors":{"type":"integer"},"last_used":{"type":"string"},"p50_exceeds":{"type":"boolean"},"p50_ms":{"description":"P50Ms and P95Ms are read off a fixed latency histogram, so they are BUCKET\nBOUNDS, not measured durations: the true percentile is at or below the\nvalue, and a client must render it as a bound (\"≤ 5 ms\"). P50Exceeds /\nP95Exceeds flip that reading for the unbounded overflow bucket, where the\nvalue is the last bound and the truth is above it (\"\u003e 10 s\").","type":"integer"},"p95_exceeds":{"type":"boolean"},"p95_ms":{"type":"integer"},"rejected":{"description":"spec 093: shed by a concurrency limit; never executed, so excluded from calls/latency","type":"integer"},"server":{"type":"string"},"sized_calls":{"description":"calls with known response size (basis for avg_resp_bytes)","type":"integer"},"tool":{"type":"string"},"total_req_bytes":{"type":"integer"},"total_resp_bytes":{"type":"integer"}},"type":"object"},"contracts.ValidateConfigResponse":{"properties":{"errors":{"items":{"$ref":"#/components/schemas/contracts.ValidationError"},"type":"array","uniqueItems":false},"valid":{"type":"boolean"}},"type":"object"},"contracts.ValidationError":{"properties":{"field":{"type":"string"},"message":{"type":"string"}},"type":"object"},"contracts.ViewAsCounts":{"description":"Counts is present only for a NON-administrator profile view-as (Spec 108\nFR-032): the response then lists only the visible rows, and this is the\nonly trace of the rest, with no per-server, per-tier or per-reason\nbreakdown.","properties":{"hidden":{"type":"integer"},"visible":{"type":"integer"}},"type":"object"},"contracts.WorkSession":{"properties":{"attempts":{"description":"Attempts, Failures and PolicyBlocks are lifetime counts of the session.\nPolicyBlocks are included in Failures.","type":"integer"},"client_id":{"type":"string"},"client_name":{"type":"string"},"connection_count":{"description":"Administrators only.","type":"integer"},"duration_ms":{"type":"integer"},"ended_at":{"type":"string"},"failures":{"type":"integer"},"first_failure_at":{"type":"string"},"id":{"type":"string"},"last_activity_at":{"type":"string"},"last_failure":{"$ref":"#/components/schemas/contracts.WorkSessionFailure"},"ownerless":{"type":"boolean"},"policy_blocks":{"type":"integer"},"profile":{"description":"Profile is returned to administrators only.","type":"string"},"profile_source":{"type":"string"},"project_name":{"description":"ProjectName is the basename of the client's workspace, when it\ndisclosed one.","type":"string"},"rebuilt":{"type":"boolean"},"run_name":{"type":"string"},"started_at":{"type":"string"},"status":{"description":"Status is \"active\" or \"ended\".","type":"string"},"stored_failures":{"description":"StoredFailures counts the failures whose rows are still in the log;\nit is what the timeline can navigate.","type":"integer"},"surface":{"type":"string"},"token_name":{"type":"string"},"truncated_start_at":{"type":"string"}},"type":"object"},"contracts.WorkSessionEnvelope":{"properties":{"data":{"$ref":"#/components/schemas/contracts.WorkSession"},"success":{"type":"boolean"}},"type":"object"},"contracts.WorkSessionFailure":{"properties":{"at":{"type":"string"},"error_class":{"type":"string"},"error_code":{"type":"string"},"policy_block":{"description":"PolicyBlock is true when the failure was a refusal by MCPProxy itself.","type":"boolean"},"reason":{"description":"Reason is at most 200 characters and never contains argument or\nresponse bodies.","type":"string"},"server":{"type":"string"},"tool":{"type":"string"}},"type":"object"},"contracts.WorkSessionListEnvelope":{"properties":{"data":{"$ref":"#/components/schemas/contracts.WorkSessionListResponse"},"success":{"type":"boolean"}},"type":"object"},"contracts.WorkSessionListResponse":{"properties":{"limit":{"type":"integer"},"offset":{"type":"integer"},"sessions":{"items":{"$ref":"#/components/schemas/contracts.WorkSession"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.WorkSessionTimelineEnvelope":{"properties":{"data":{"$ref":"#/components/schemas/contracts.WorkSessionTimelineResponse"},"success":{"type":"boolean"}},"type":"object"},"contracts.WorkSessionTimelineResponse":{"properties":{"earlier_failures_not_stored":{"type":"boolean"},"failure_index":{"description":"FailureIndex is the 1-based number of the failure at or before the\nposition among the stored failures in reach (0 when none), and\nFailureTotal their count.","type":"integer"},"failure_total":{"type":"integer"},"has_after":{"type":"boolean"},"has_before":{"type":"boolean"},"lifetime_failures":{"description":"LifetimeFailures is the session's lifetime failure count in reach.\nEarlierFailuresNotStored says some of them are no longer in the log.","type":"integer"},"position":{"description":"Position is the index of the row the page is positioned at; TotalRows\nis the number of rows in the caller's view.","type":"integer"},"rows":{"items":{"$ref":"#/components/schemas/contracts.WorkSessionTimelineRow"},"type":"array","uniqueItems":false},"session":{"$ref":"#/components/schemas/contracts.WorkSession"},"total_rows":{"type":"integer"}},"type":"object"},"contracts.WorkSessionTimelineRow":{"properties":{"activity":{"$ref":"#/components/schemas/contracts.ActivityRecord"},"at":{"description":"At is the time of the row.","type":"string"},"bodies_removed":{"description":"BodiesRemoved is true when retention removed the row's argument and\nresponse bodies to keep the row.","type":"boolean"},"failed":{"description":"Failed marks the counted row of a failed attempt; PolicyBlock marks a\nrefusal by MCPProxy itself.","type":"boolean"},"index":{"description":"Index is the row's position in the caller's view of the timeline.","type":"integer"},"kind":{"type":"string"},"policy_block":{"type":"boolean"},"precedes_session":{"description":"PrecedesSession marks an upstream event from before the session\nstarted: the latest event of a server the session then failed on,\nstill unresolved when the session began (release QA F2, SC-005).","type":"boolean"}},"type":"object"},"data":{"properties":{"data":{"$ref":"#/components/schemas/contracts.InfoResponse"}},"type":"object"},"httpapi.AccessExplanationData":{"properties":{"first_failure":{"type":"string","x-enum-varnames":["StepCredential","StepProfile","StepServerInScope","StepToolRule","StepTierCap","StepTokenPermission","StepGlobalGate","StepServerState","StepToolApproval"]},"fixes":{"items":{"$ref":"#/components/schemas/runtime.Fix"},"type":"array","uniqueItems":false},"profile":{"$ref":"#/components/schemas/runtime.ExplainProfileView"},"steps":{"items":{"$ref":"#/components/schemas/runtime.ExplainStepView"},"type":"array","uniqueItems":false},"subject":{"$ref":"#/components/schemas/runtime.ExplainSubjectView"},"tool":{"type":"string"},"verdict":{"$ref":"#/components/schemas/profile.ExplainVerdict"}},"type":"object"},"httpapi.AccessSuggestionsData":{"properties":{"already_fixed":{"description":"AlreadyFixed counts groups the explainer now allows (they drop out).","type":"integer"},"blocked_calls":{"description":"BlockedCalls counts every profile-refused call in the window.","type":"integer"},"non_profile_blocked":{"description":"NonProfileBlocked counts blocked calls with a cause outside profiles.","type":"integer"},"patches":{"items":{"$ref":"#/components/schemas/runtime.ProfilePatch"},"type":"array","uniqueItems":false},"profile_removed":{"description":"ProfileRemoved counts groups whose profile no longer exists (they drop out).","type":"integer"},"since":{"type":"string"},"suggestions":{"items":{"$ref":"#/components/schemas/runtime.AccessSuggestion"},"type":"array","uniqueItems":false},"unattributed":{"description":"Unattributed counts profile refusals whose record names no profile.","type":"integer"},"until":{"type":"string"},"window":{"type":"string"}},"type":"object"},"httpapi.AddServerRequest":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges is the per-server intent to auto-approve\nnew/changed tools past the trust baseline (MCP-2930). Tri-state *bool:\na nil pointer means \"leave unchanged\" on PATCH; a present value\n(including false) is applied. Mirrors config.ServerConfig's *bool\nsemantics — do NOT collapse to a plain bool, or an omitted field would\nsilently reset a previously-set value.","type":"boolean"},"command":{"type":"string"},"enabled":{"type":"boolean"},"env":{"additionalProperties":{"type":"string"},"type":"object"},"expose_prompts":{"description":"ExposePrompts is the per-server override for prompt aggregation (F9):\nwhether this server's advertised MCP prompts are merged into mcpproxy's\nprompts/list. Tri-state *bool mirroring config.ServerConfig.ExposePrompts —\na nil pointer means \"leave unchanged\" on PATCH (and \"inherit the default\naggregate behavior\" on create); a present value (including false) is applied.","type":"boolean"},"expose_skills":{"description":"ExposeSkills is the per-server skills override (MCP skills extension).\nTri-state *bool mirroring config.ServerConfig.ExposeSkills: nil means\n\"leave unchanged\" on PATCH and \"inherit\" on create.","type":"boolean"},"forward_headers":{"description":"ForwardHeaders is the per-server allowlist of inbound MCP client header\nNAMES forwarded to this server on tools/call (Spec 112). Names only, never\nvalues. On PATCH a nil slice (field omitted) leaves the stored allowlist\nunchanged and an empty array ([]) clears it. Invalid, denied, duplicate\nand static-header-colliding names are rejected with 400.","items":{"type":"string"},"type":"array","uniqueItems":false},"headers":{"additionalProperties":{"type":"string"},"type":"object"},"init_timeout":{"description":"InitTimeout is the per-server MCP ` + "`" + `initialize` + "`" + ` handshake deadline override\n(MCP-3322 / GH #760), serialized as a duration string (e.g. \"120s\"). A nil\npointer means \"leave unchanged\" on PATCH; a present value is applied.\nMirrors config.ServerConfig.InitTimeout's *Duration tri-state.","type":"string"},"isolation":{"$ref":"#/components/schemas/httpapi.IsolationRequest"},"max_concurrent_requests":{"description":"MaxConcurrentRequests / QueueSize / QueueTimeout are the per-server\nconcurrency overrides (spec 093 / GH #955, FR-020 scope (c)). Each is\ntri-state: a nil pointer means \"leave unchanged\" on PATCH and \"inherit\nserver_concurrency_defaults\" on create; an explicit 0 disables that\nsetting for this server; a positive value overrides it. Do NOT collapse\nthem to plain values — an omitted field would then silently reset a\nconfigured limit.","type":"integer"},"name":{"type":"string"},"protocol":{"type":"string"},"quarantined":{"type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_on_use":{"type":"boolean"},"tool_argument_error_mode":{"description":"Empty preserves an update; detailed explicitly resets a redacted policy.","type":"string"},"trust_mode":{"description":"TrustMode is the per-server trust tier (spec 086): \"auto\", \"scan\", or\n\"manual\". Empty means \"leave unchanged\" on PATCH (and inherit the migrated\ndefault on create). A non-empty value is applied to ServerConfig.TrustMode\nand resolved by EffectiveTrustMode (an unrecognized value fails closed to\nmanual). This is the REST seam for changing the trust tier via\nPOST/PATCH /api/v1/servers.","type":"string"},"url":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"httpapi.BindingGuardResponse":{"properties":{"bindings":{"items":{"$ref":"#/components/schemas/httpapi.GuardBinding"},"type":"array","uniqueItems":false},"code":{"description":"binding_bypassable_without_auth","type":"string"},"error":{"description":"Human-readable, byte-stable refusal text","type":"string"},"fixes":{"items":{"$ref":"#/components/schemas/httpapi.GuardFixOption"},"type":"array","uniqueItems":false},"request_id":{"type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.BulkAssignRequest":{"properties":{"from_profile":{"type":"string"},"mode":{"type":"string"},"to_profile":{"type":"string"}},"type":"object"},"httpapi.BulkAssignResponse":{"properties":{"moved":{"items":{"type":"string"},"type":"array","uniqueItems":false},"skipped":{"items":{"$ref":"#/components/schemas/httpapi.BulkAssignSkipped"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.BulkAssignSkipped":{"properties":{"client_id":{"type":"string"},"code":{"type":"string"},"error":{"type":"string"}},"type":"object"},"httpapi.BundleRollbackRefusedResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"rejection":{"$ref":"#/components/schemas/scanner.BundleRejection"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"httpapi.CanonicalConfigPath":{"properties":{"description":{"description":"Brief description","type":"string"},"exists":{"description":"Whether the file exists","type":"boolean"},"format":{"description":"Format identifier (e.g., \"claude_desktop\")","type":"string"},"name":{"description":"Display name (e.g., \"Claude Desktop\")","type":"string"},"os":{"description":"Operating system (darwin, windows, linux)","type":"string"},"path":{"description":"Full path to the config file","type":"string"}},"type":"object"},"httpapi.CanonicalConfigPathsResponse":{"properties":{"os":{"description":"Current operating system","type":"string"},"paths":{"description":"List of canonical config paths","items":{"$ref":"#/components/schemas/httpapi.CanonicalConfigPath"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ClientBindingErrorResponse":{"properties":{"code":{"type":"string"},"error":{"type":"string"},"field":{"type":"string"},"request_id":{"type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.ClientBindingResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"warnings":{"items":{"$ref":"#/components/schemas/httpapi.ClientWarning"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ClientSnippet":{"properties":{"generic_http":{"type":"string"},"header_name":{"type":"string"}},"type":"object"},"httpapi.ClientWarning":{"properties":{"action":{"$ref":"#/components/schemas/runtime.WarningAction"},"bindings":{"items":{"$ref":"#/components/schemas/runtime.BindingRef"},"type":"array","uniqueItems":false},"client_id":{"type":"string"},"code":{"$ref":"#/components/schemas/profile.WarningCode"},"fixes":{"items":{"$ref":"#/components/schemas/runtime.GuardFix"},"type":"array","uniqueItems":false},"message":{"type":"string"},"severity":{"$ref":"#/components/schemas/profile.WarningSeverity"}},"type":"object"},"httpapi.ConnectConflictResponse":{"properties":{"action":{"description":"already_exists | precondition_failed","type":"string"},"data":{"$ref":"#/components/schemas/connect.ConnectResult"},"error":{"description":"Human-readable message","type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.ConnectRequest":{"properties":{"force":{"description":"Overwrite existing entry","type":"boolean"},"keyless":{"type":"boolean"},"mode":{"type":"string"},"precondition_token":{"description":"PreconditionToken is the opaque token from the preview this write was\nconfirmed against (Spec 091 FR-005). When present, the core rechecks it\nat write time and responds 409 with action \"precondition_failed\" —\nwriting nothing — if the config or the entry MCPProxy would write has\ndrifted since; the caller then re-previews instead of retrying. Absent\nmeans exactly the pre-091 behavior. A replace-classified flow sends this\nTOGETHER with force=true: the token, not the absence of force, is the\noverwrite safety.","type":"string"},"profile":{"description":"Profile, Mode and Keyless are the client-credential intent (Spec 108\nFR-024). Profile names the profile the client's credential binds to;\n\"\" is the built-in All servers scope. Omitted means \"not specified\": a\nfresh credential defaults to All servers and a reconnect keeps the\nclient's existing binding (a reconnect never silently widens a locked\nclient). Mode is locked|switchable (default locked for a named profile,\nswitchable for All servers). Keyless writes a credential-less entry and\nis only possible while require_mcp_auth is off; it cannot carry a\nprofile or mode.","type":"string"},"server_name":{"description":"Defaults to \"mcpproxy\"","type":"string"}},"type":"object"},"httpapi.CreateClientRequest":{"properties":{"display_name":{"type":"string"},"expires_in":{"description":"ExpiresIn is a duration like 30d or 720h; default and cap are 365 days.","type":"string"},"id":{"type":"string"},"mode":{"type":"string"},"profile":{"type":"string"},"purpose":{"description":"Purpose is the stated, unenforced task brief (Spec 115), at most 500\ncharacters; screened for secrets before anything is stored.","type":"string"}},"type":"object"},"httpapi.CreateClientResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"credential":{"type":"string"},"snippet":{"$ref":"#/components/schemas/httpapi.ClientSnippet"}},"type":"object"},"httpapi.EffectiveToolsData":{"properties":{"counts":{"$ref":"#/components/schemas/runtime.EffectiveCounts"},"profile":{"type":"string"},"stale_classification_reasons":{"additionalProperties":{"type":"string"},"description":"StaleClassificationReasons maps each stale classify entry to why it no\nlonger applies: profile.StaleClassificationAnnotated or\nprofile.StaleClassificationMissing. It is computed over the UNFILTERED\ntool set, so a server or reason filter never changes it. Administrators\nonly.","type":"object"},"stale_classifications":{"description":"StaleClassifications lists classify entries for tools that are now\nannotated or no longer exist (FR-005). Administrators only.","items":{"type":"string"},"type":"array","uniqueItems":false},"tools":{"items":{"$ref":"#/components/schemas/runtime.EffectiveTool"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.EnvFieldPreview":{"properties":{"empty_or_placeholder":{"type":"boolean"},"name":{"type":"string"},"secret_like":{"type":"boolean"},"value_present":{"type":"boolean"}},"type":"object"},"httpapi.FinalizeClientResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"rotation":{"$ref":"#/components/schemas/httpapi.RotationState"}},"type":"object"},"httpapi.ForgetClientResponse":{"properties":{"disconnect_error":{"type":"string"},"disconnected":{"type":"boolean"},"revoked":{"type":"string"}},"type":"object"},"httpapi.GuardBinding":{"properties":{"client_id":{"type":"string"},"mode":{"type":"string"},"profile":{"type":"string"},"token_name":{"type":"string"}},"type":"object"},"httpapi.GuardFixOption":{"properties":{"kind":{"type":"string"},"target":{"type":"string"}},"type":"object"},"httpapi.HeaderFieldPreview":{"properties":{"empty_or_placeholder":{"type":"boolean"},"name":{"type":"string"},"secret_like":{"type":"boolean"},"value_present":{"type":"boolean"}},"type":"object"},"httpapi.ImportFromPathRequest":{"properties":{"format":{"description":"Optional format hint","type":"string"},"path":{"description":"File path to import from","type":"string"},"rename":{"additionalProperties":{"type":"string"},"description":"Rename maps a server name → new name. Applied after parsing so the\ncaller can disambiguate cross-source name collisions (Spec 046 v2 —\ne.g. \"mcpproxy\" → \"mcpproxy_claude_code\"). Keys are matched against\neither the raw source name (OriginalName) or the sanitized name shown\nin the preview (Server.Name); these differ for names that need\nsanitizing (e.g. \"Figma Desktop\" → \"Figma_Desktop\"). Keys not present\nin the imported set are ignored.","type":"object"},"server_names":{"description":"Optional: import only these servers","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportRequest":{"properties":{"allow_paste_fallback":{"description":"AllowPasteFallback opts into detecting a bare URL or a single command\nline (FR-064) when Format/format detection would otherwise fail — see\nconfigimport.ImportOptions.AllowPasteFallback for why this must stay\nopt-in (review round 4 F-E). Only the interactive Paste tab sets this;\nevery other caller of this endpoint (the general \"Import config\"\npanel, or a direct API call) leaves it false and gets a clear\n\"unable to detect configuration format\" error for a plain one-liner\ninstead of it being silently guessed at and, on apply, added as a\nreal server with no confirmation step.","type":"boolean"},"content":{"description":"Raw JSON or TOML content","type":"string"},"env_override":{"additionalProperties":{"type":"string"},"description":"EnvOverride/HeaderOverride (Spec 109 FR-064/065, PR review round 4\nF-A/F-D fix): the Paste tab's per-field Value/Secret edits — a plain\nvalue the user typed, or a keyring ref path if they chose Secret —\nkeyed by field name. Applied to the matching imported server's\nEnv/Headers ONLY when preview=false, directly on the server this\nrequest's own raw Content parses to server-side. This is what lets\nthe apply call carry the user's edited env/header values without\never round-tripping the redacted preview: url/command/args on apply\nalways come from re-parsing Content here, never from a client-held\npreview response, so a credential embedded in a URL query param or\nargv flag (which the preview necessarily redacted for display) is\nnever overwritten with the masked placeholder.","type":"object"},"format":{"description":"Optional format hint","type":"string"},"header_override":{"additionalProperties":{"type":"string"},"type":"object"},"server_names":{"description":"Optional: import only these servers","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportResponse":{"properties":{"failed":{"items":{"$ref":"#/components/schemas/configimport.FailedServer"},"type":"array","uniqueItems":false},"format":{"type":"string"},"format_name":{"type":"string"},"imported":{"items":{"$ref":"#/components/schemas/httpapi.ImportedServerResponse"},"type":"array","uniqueItems":false},"skipped":{"items":{"$ref":"#/components/schemas/configimport.SkippedServer"},"type":"array","uniqueItems":false},"summary":{"$ref":"#/components/schemas/configimport.ImportSummary"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportedServerResponse":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"command":{"type":"string"},"env":{"items":{"$ref":"#/components/schemas/httpapi.EnvFieldPreview"},"type":"array","uniqueItems":false},"fields_skipped":{"items":{"type":"string"},"type":"array","uniqueItems":false},"headers":{"items":{"$ref":"#/components/schemas/httpapi.HeaderFieldPreview"},"type":"array","uniqueItems":false},"name":{"type":"string"},"original_name":{"type":"string"},"protocol":{"type":"string"},"source_format":{"type":"string"},"summary":{"description":"Summary, Tags, Env and Headers are the Spec 109 FR-064 preview\nenrichment (contracts/rest-api.md \"Import preview\"). Summary and Tags\nare built from the already-redacted URL/Command/Args above, so a\nsecret embedded in argv or a URL query never reaches Summary either.\nEnv/Headers never carry the raw value — only its presence and two\nbooleans a surface uses to default the Value/Secret toggle (FR-065).","type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"url":{"type":"string"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.IsolationRequest":{"description":"Isolation carries per-server Docker isolation overrides (enabled,\nmode_override, image, network_mode, extra_args, working_dir). A nil\npointer means \"do not touch isolation config\". A present object is\napplied field-by-field ON TOP of the persisted overrides, so omitting a\nfield leaves it alone; clear an individual override by sending it\nexplicitly (` + "`" + `\"enabled\": null` + "`" + `, ` + "`" + `\"image\": \"\"` + "`" + `).","properties":{"enabled":{"description":"Enabled exists ONLY to detect and reject an echoed-back read. It is the\neffective state on the read surface and is never writable; see validate().","type":"boolean"},"enabled_override":{"description":"EnabledOverride is the tri-state per-server override — the RAW value, the\nsame one reads return as ` + "`" + `enabled_override` + "`" + `. It has THREE meaningful wire\nstates, and collapsing them is what silently un-isolated servers\n(GH #1142):\n - absent → leave the persisted override untouched\n - null → clear the override, back to inheriting the global\n - true / false → set an explicit opt-in / opt-out","type":"boolean"},"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"mode_override":{"description":"ModeOverride sets ` + "`" + `isolation.mode` + "`" + ` (\"docker\" | \"sandbox\" | \"none\").\nnil leaves the persisted value alone; an empty string clears it. An\nunrecognized value is rejected with a 400 rather than persisted.","type":"string"},"network_mode":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"httpapi.OnboardingMarkRequest":{"properties":{"connect_step_status":{"description":"ConnectStepStatus is one of: \"\", \"completed\", \"skipped\". Empty\npreserves the existing value. The stored enum is wider (Spec 080\nFR-001): a \"skipped\" request for a previously untouched connect step\nis upgraded server-side to \"completed_external\" when the install\nshows positive evidence of an external connection (Spec 080 FR-002).\n\"completed_external\" is NOT accepted from clients — it must never be\npersisted without that server-verified evidence (edge case: \"never\nguess completed_external without positive evidence\").","type":"string"},"connected_client_id":{"description":"ConnectedClientID records a successful connect write for this client id\n(Spec 109-b FR-042, review round 6). The REST connect endpoint\n(POST /api/v1/connect/{client}) already records this itself on success;\nthis field exists so ` + "`" + `mcpproxy connect` + "`" + ` — which writes the client's\nconfig file directly, without going through that endpoint, so the\ncommand still works when no daemon is running — can relay the same\nevent to a daemon that IS running, keeping ClientConnectedAt in sync\nacross both surfaces. Must be a known id from the fixed connect client\nregistry (internal/connect.GetAllClients); any other value is rejected,\nmatching the field's \"bounded by the registry\" invariant\n(data-model.md §7).","type":"string"},"disconnected_client_id":{"description":"DisconnectedClientID relays a successful local CLI disconnect to a running\ndaemon, which cannot observe the CLI's direct config-file edit itself.\nLike ConnectedClientID, it is bounded to the fixed client registry.","type":"string"},"engaged":{"description":"Engaged marks the wizard as engaged (completed or explicitly skipped).\nOnce true, the wizard does not auto-show again.","type":"boolean"},"mark_shown":{"description":"MarkShown records the wizard's first display time if not already set.","type":"boolean"},"server_step_status":{"description":"ServerStepStatus is one of: \"\", \"completed\", \"skipped\". Empty\npreserves the existing value.","type":"string"}},"type":"object"},"httpapi.OnboardingStateResponse":{"properties":{"configured_server_count":{"description":"ConfiguredServerCount is the number of upstream MCP servers configured\nin mcpproxy (counts both enabled and disabled).","type":"integer"},"connected_client_count":{"description":"ConnectedClientCount is the number of supported clients currently\npointing at mcpproxy.","type":"integer"},"connected_client_ids":{"description":"ConnectedClientIDs are the identifiers of supported clients currently\npointing at mcpproxy. Drawn exclusively from the fixed adapter table —\nuser-entered values never appear here.","items":{"type":"string"},"type":"array","uniqueItems":false},"first_mcp_client_ever":{"description":"FirstMCPClientEver is true once any MCP client has successfully completed\nan ` + "`" + `initialize` + "`" + ` round-trip with this mcpproxy. Sourced from the Spec 044\nactivation bucket. Drives the Verify tab's \"green check\" state.","type":"boolean"},"has_configured_server":{"description":"HasConfiguredServer is true if at least one upstream MCP server is\nconfigured (regardless of current connection health).","type":"boolean"},"has_connected_client":{"description":"HasConnectedClient is true if at least one supported AI client currently\nhas mcpproxy registered in its config.","type":"boolean"},"has_usable_server":{"description":"HasUsableServer is true once at least one enabled, non-quarantined\nserver has usable health and at least one approved (non-disabled) tool.\nThis is the real \"the wizard has something to try\" signal:\nHasConfiguredServer only means a server entry exists, even while every\none of them sits quarantined, requires sign-in, or has zero approved\ntools. The Servers step and Setup badge use this instead of\nHasConfiguredServer, which is kept above for compatibility.\nHealthStatus.Usable is the shared\nreadiness contract used by every UI surface (Spec 109-c, tasks.md T051).","type":"boolean"},"incomplete_tab_count":{"description":"IncompleteTabCount is the number of wizard tabs whose state is incomplete.\nDrives the sidebar Setup entry's badge. Formula:\n +1 if HasConnectedClient == false\n +1 if HasUsableServer == false\n +1 if FirstMCPClientEver == false","type":"integer"},"mcp_clients_seen_ever":{"description":"MCPClientsSeenEver is the capped list of recognized client names that\nhave ever called this mcpproxy. Names come from the MCP ` + "`" + `initialize` + "`" + `\npayload's ` + "`" + `clientInfo.name` + "`" + ` field, sanitized. Surfaces on the Verify tab\nso the user can see whether their real IDE — not a test client — has\nconnected.","items":{"type":"string"},"type":"array","uniqueItems":false},"should_show_wizard":{"description":"ShouldShowWizard is the derived flag the frontend uses to decide\nwhether to auto-show. True when not engaged and IncompleteTabCount \u003e 0\n(Spec 046 v2 — semantics widened to also count the Verify tab).","type":"boolean"},"state":{"$ref":"#/components/schemas/storage.OnboardingState"},"usable_servers":{"description":"UsableServers lists the names behind HasUsableServer, for the Verify\nstep's suggested-prompt generator (FR-042): prompts are only built from\ntools of servers in this list, never from a quarantined or toolless one.","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileConflictResponse":{"properties":{"code":{"type":"string"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"description":"Always false","type":"boolean"},"used_by":{"$ref":"#/components/schemas/httpapi.ProfileUsedByData"}},"type":"object"},"httpapi.ProfileDeleteData":{"properties":{"anonymous_profile_moved_to":{"type":"string"},"deleted":{"type":"string"},"moved":{"$ref":"#/components/schemas/runtime.MovedRefs"}},"type":"object"},"httpapi.ProfileListData":{"properties":{"anonymous_profile":{"type":"string"},"profiles":{"items":{"$ref":"#/components/schemas/runtime.ProfileView"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileRenameData":{"properties":{"moved":{"$ref":"#/components/schemas/runtime.MovedRefs"},"profile":{"$ref":"#/components/schemas/runtime.ProfileView"}},"type":"object"},"httpapi.ProfileTryData":{"properties":{"hidden":{"items":{"$ref":"#/components/schemas/runtime.TryHidden"},"type":"array","uniqueItems":false},"hidden_by_profile":{"type":"integer"},"hidden_truncated":{"type":"boolean"},"results":{"items":{"additionalProperties":{},"type":"object"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileUsedByData":{"properties":{"anonymous_profile":{"type":"boolean"},"clients":{"items":{"$ref":"#/components/schemas/runtime.UsedByClient"},"type":"array","uniqueItems":false},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileViewData":{"properties":{"blocked_24h":{"type":"integer"},"calls_24h":{"type":"integer"},"code_execution":{"type":"boolean"},"description":{"type":"string"},"effective_code_execution":{"type":"boolean"},"effective_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"effective_unannotated":{"type":"string"},"is_legacy":{"type":"boolean"},"management_tools":{"type":"boolean"},"max_tier":{"type":"string"},"name":{"type":"string"},"servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"switchable_to":{"items":{"type":"string"},"type":"array","uniqueItems":false},"title":{"type":"string"},"tool_count":{"description":"ToolCount is the v2 field: indexed tools on the effective servers.\nDeprecated: use tool_counts.","type":"integer"},"tool_counts":{"$ref":"#/components/schemas/runtime.ToolCounts"},"tools":{"$ref":"#/components/schemas/config.ProfileToolRules"},"unannotated":{"type":"string"},"used_by":{"$ref":"#/components/schemas/runtime.UsedBy"}},"type":"object"},"httpapi.ProfileWriteData":{"properties":{"profile":{"$ref":"#/components/schemas/runtime.ProfileView"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.PutClientBindingRequest":{"properties":{"mode":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.RenameProfileRequest":{"properties":{"new_name":{"type":"string"}},"type":"object"},"httpapi.RotateClientRequest":{"properties":{"precondition_token":{"description":"PreconditionToken is the token of GET /connect/{client}/preview; it\nbinds a supported client's rotation to what the preview showed.","type":"string"}},"type":"object"},"httpapi.RotateClientResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"connect":{"$ref":"#/components/schemas/connect.ConnectResult"},"credential":{"type":"string"},"rotation":{"$ref":"#/components/schemas/httpapi.RotationState"},"snippet":{"$ref":"#/components/schemas/httpapi.ClientSnippet"}},"type":"object"},"httpapi.RotationState":{"properties":{"state":{"type":"string"}},"type":"object"},"httpapi.SetActiveProfileRequest":{"properties":{"active_profile":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.StaleReviewErrorResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"stale_tools":{"$ref":"#/components/schemas/httpapi.StaleToolsDetail"},"success":{"type":"boolean"}},"type":"object"},"httpapi.StaleToolsDetail":{"properties":{"changed":{"items":{"type":"string"},"type":"array","uniqueItems":false},"missing_blocks":{"items":{"type":"string"},"type":"array","uniqueItems":false},"unreviewed":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.TryProfileRequest":{"properties":{"limit":{"type":"integer"},"profile":{"$ref":"#/components/schemas/config.ProfileConfig"},"query":{"type":"string"}},"type":"object"},"httpapi.UndoConnectRequest":{"properties":{"backup_name":{"description":"BackupName is the bare filename (filepath.Base) of the backup returned as\nbackup_path by the preceding connect — a name, never a path. Undo resolves\nthe full path server-side by joining it with the client's own config\ndirectory, so a client-supplied value can never contribute a directory\ncomponent (traversal is impossible by construction). Empty means the\nconnect created the file (no prior file existed), so undo removes it.","type":"string"},"server_name":{"description":"Defaults to \"mcpproxy\"","type":"string"}},"type":"object"},"httpapi.UpdateFailureRequest":{"properties":{"stage":{"description":"Stage is the failure stage of the update session.","enum":["appcast","download","install","other"],"type":"string"}},"type":"object"},"httpapi.UpgradeAdminKeyHoldersRequest":{"properties":{"apply":{"type":"boolean"},"mode":{"type":"string"},"precondition_token":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.approveToolsRequest":{"properties":{"approve_all":{"type":"boolean"},"expected_hashes":{"additionalProperties":{"type":"string"},"description":"ExpectedHashes binds the approval to the reviewed definitions (Spec\n117 PR-2, #1566): tool name -\u003e the review's current_hash. Absent or\nnull is an unbound (legacy) request; {} is bound.","type":["object","null"]},"expected_incarnation":{"description":"ExpectedIncarnation binds the approval to the server the client\nreviewed (Spec 116 FR-017); 409 server_replaced on a mismatch. It is\nindependent of ExpectedHashes and the two may be sent together.","type":"integer"},"tools":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.attentionResponse":{"properties":{"count":{"type":"integer"},"generated_at":{"type":"string"},"items":{"items":{"$ref":"#/components/schemas/contracts.AttentionItem"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.bundleRollbackRequest":{"properties":{"digest":{"description":"Digest is the full 64-character lowercase hex SHA-256 of the target.","type":"string"},"embedded":{"description":"Embedded rolls back to the corpus compiled into this binary.","type":"boolean"},"path":{"description":"Path is where to find the target bundle (a hint only).","type":"string"}},"type":"object"},"httpapi.clientPresence":{"properties":{"active_sessions":{"type":"integer"},"blocked_24h":{"type":"integer"},"calls_24h":{"type":"integer"},"config_path":{"type":"string"},"connected":{"type":"boolean"},"connection_unverified":{"type":"boolean"},"credential_checked_at":{"type":"string"},"credential_state":{"$ref":"#/components/schemas/profile.CredentialState"},"display_name":{"type":"string"},"display_path":{"type":"string"},"expires_at":{"type":"string"},"icon":{"type":"string"},"id":{"type":"string"},"installed":{"type":"boolean"},"issuer":{"$ref":"#/components/schemas/auth.CredentialIssuer"},"kind":{"type":"string"},"last_seen":{"type":"string"},"lease":{"type":"boolean"},"profile":{"type":"string"},"profile_missing":{"type":"boolean"},"profile_mode":{"type":"string"},"profile_source":{"description":"profile_source is pin (locked) or binding (switchable) and is empty when\ncredential_state is not client.","type":"string"},"profile_state":{"type":"string"},"profile_title":{"type":"string"},"purpose":{"type":"string"},"reload_hint":{"type":"string"},"revoked_at":{"description":"Spec 115 lifecycle fields of the client's credential record (additive):\nwhen it was revoked, who issued it, its stated (unenforced) purpose,\nwhether it is a task lease (lifetime at issue \u003c= 24h) and whether its\nprofile still exists (ok | dangling | none).","type":"string"},"rotation_pending":{"type":"boolean"},"sessions":{"items":{"$ref":"#/components/schemas/httpapi.clientSession"},"type":"array","uniqueItems":false},"state":{"type":"string"},"token_name":{"type":"string"}},"type":"object"},"httpapi.clientSession":{"properties":{"id":{"type":"string"},"last_activity":{"type":"string"},"profile":{"description":"Profile and ProfileSource are the session's latest effective resolution\n(Spec 108-e FR-033); empty on legacy sessions.","type":"string"},"profile_source":{"type":"string"},"started_at":{"type":"string"},"work_session_id":{"type":"string"}},"type":"object"},"httpapi.clientsResponse":{"properties":{"clients":{"items":{"$ref":"#/components/schemas/httpapi.clientPresence"},"type":"array","uniqueItems":false},"routing":{},"warnings":{"items":{"$ref":"#/components/schemas/httpapi.ClientWarning"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.expectedIncarnationBody":{"properties":{"expected_incarnation":{"type":"integer"}},"type":"object"},"httpapi.securityApproveRequest":{"properties":{"block":{"items":{"type":"string"},"type":"array","uniqueItems":false},"expected_hashes":{"additionalProperties":{"type":"string"},"description":"ExpectedHashes binds the approval to the reviewed definitions (Spec\n117 PR-2, #1566): tool name -\u003e the review's current_hash. Absent or\nnull is an unbound (legacy) request; {} binds to the empty snapshot.\nIndependent of ExpectedIncarnation: a request may carry both, and the\ntwo refusals stay distinct (review_out_of_date vs server_replaced).","type":["object","null"]},"expected_incarnation":{"description":"ExpectedIncarnation binds the approval to the server the client\nreviewed (Spec 116 FR-017): a remove and re-add since then is refused\nwith 409 server_replaced and the replacement stays quarantined.","type":"integer"},"force":{"type":"boolean"}},"type":"object"},"management.BulkOperationResult":{"properties":{"errors":{"additionalProperties":{"type":"string"},"description":"Map of server name to error message","type":"object"},"failed":{"description":"Number of failed operations","type":"integer"},"successful":{"description":"Number of successful operations","type":"integer"},"total":{"description":"Total servers processed","type":"integer"}},"type":"object"},"observability.HealthResponse":{"properties":{"components":{"items":{"$ref":"#/components/schemas/observability.HealthStatus"},"type":"array","uniqueItems":false},"status":{"description":"\"healthy\" or \"unhealthy\"","type":"string"},"timestamp":{"type":"string"}},"type":"object"},"observability.HealthStatus":{"properties":{"error":{"type":"string"},"latency":{"type":"string"},"name":{"type":"string"},"status":{"description":"\"healthy\" or \"unhealthy\"","type":"string"}},"type":"object"},"observability.ReadinessResponse":{"properties":{"components":{"items":{"$ref":"#/components/schemas/observability.HealthStatus"},"type":"array","uniqueItems":false},"status":{"description":"\"ready\" or \"not_ready\"","type":"string"},"timestamp":{"type":"string"}},"type":"object"},"profile.AccessStepStatus":{"type":"string","x-enum-varnames":["AccessStepPass","AccessStepFail","AccessStepSkip"]},"profile.AccessSubjectKind":{"type":"string","x-enum-varnames":["AccessSubjectClient","AccessSubjectProfile","AccessSubjectToken","AccessSubjectAnonymous"]},"profile.BlockReason":{"type":"string","x-enum-varnames":["BlockReasonTier","BlockReasonRule","BlockReasonUnannotated","BlockReasonCodeExecution","BlockReasonManagement","BlockReasonServerScope"]},"profile.CredentialState":{"description":"Spec 108-f ClientView additions (data-model §7). The Spec 109 fields above\nare unchanged; everything below is additive.\n\ncredential_state is what the client's connection carries (client |\nadmin_key | none | revoked | expired | unknown). The stat-only list never\nreads a config: it reports the token store, else the last on-demand\nobservation (credential_checked_at says when), else unknown.","type":"string","x-enum-varnames":["CredentialStateClient","CredentialStateAdminKey","CredentialStateNone","CredentialStateRevoked","CredentialStateExpired","CredentialStateUnknown"]},"profile.ExplainStep":{"type":"string","x-enum-varnames":["StepCredential","StepProfile","StepServerInScope","StepToolRule","StepTierCap","StepTokenPermission","StepGlobalGate","StepServerState","StepToolApproval"]},"profile.ExplainVerdict":{"type":"string","x-enum-varnames":["ExplainVerdictAllowed","ExplainVerdictBlocked","ExplainVerdictHidden"]},"profile.FixAction":{"type":"string","x-enum-varnames":["FixAllowInProfile","FixClassifyInProfile","FixAddServerToProfile","FixMoveClient","FixEditToken","FixEnableServer","FixApproveTool","FixChangeSetting","FixReconnectClient"]},"profile.WarningCode":{"type":"string","x-enum-varnames":["WarningAnonymousDeniedByBindingGuard","WarningClientHoldsAdminKey","WarningClientCredentialExpiring","WarningClientRotationPending","WarningProfileMissing","WarningClientTokenNameConflict"]},"profile.WarningSeverity":{"type":"string","x-enum-varnames":["WarningSeverityWarn","WarningSeverityInfo"]},"runtime.AccessSuggestion":{"properties":{"block_reason":{"$ref":"#/components/schemas/profile.BlockReason"},"clients":{"items":{"type":"string"},"type":"array","uniqueItems":false},"count":{"type":"integer"},"first_seen":{"type":"string"},"fixes":{"description":"Fixes are the access explainer's remediations of the first failing step,\nin preference order. Empty for a deny rule and for the built-in tools.","items":{"$ref":"#/components/schemas/runtime.Fix"},"type":"array","uniqueItems":false},"last_seen":{"type":"string"},"needs_input":{"description":"NeedsInput names what a person must supply before a change is\napply-ready (classify: \"tier\").","items":{"type":"string"},"type":"array","uniqueItems":false},"note":{"type":"string"},"profile":{"type":"string"},"server":{"type":"string"},"suggestion":{"$ref":"#/components/schemas/runtime.SuggestionKind"},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false},"tool":{"description":"\"server:tool\", or the built-in name","type":"string"},"warning":{"description":"Warning is set for profile_code_execution and profile_management: both\nchange what a profile can do beyond tool access.","type":"string"}},"type":"object"},"runtime.BindingRef":{"properties":{"client_id":{"type":"string"},"mode":{"type":"string"},"profile":{"type":"string"},"token_name":{"type":"string"}},"type":"object"},"runtime.EffectiveCounts":{"properties":{"by_reason":{"additionalProperties":{"type":"integer"},"type":"object"},"callable":{"type":"integer"},"hidden":{"type":"integer"},"visible":{"type":"integer"}},"type":"object"},"runtime.EffectiveTool":{"properties":{"access":{"$ref":"#/components/schemas/runtime.ToolAccessView"},"classification_stale":{"type":"boolean"},"intrinsic_tier":{"type":"string"},"profile_tier":{"type":"string"},"server":{"type":"string"},"tool":{"type":"string"}},"type":"object"},"runtime.ExplainProfileView":{"properties":{"name":{"type":"string"},"source":{"type":"string"}},"type":"object"},"runtime.ExplainStepView":{"properties":{"detail":{"type":"string"},"status":{"$ref":"#/components/schemas/profile.AccessStepStatus"},"step":{"$ref":"#/components/schemas/profile.ExplainStep"}},"type":"object"},"runtime.ExplainSubjectView":{"properties":{"kind":{"$ref":"#/components/schemas/profile.AccessSubjectKind"},"name":{"type":"string"}},"type":"object"},"runtime.Fix":{"properties":{"action":{"$ref":"#/components/schemas/profile.FixAction"},"label":{"type":"string"},"profile":{"description":"Profile is set for move_client only: the destination profile slug the fix\nmoves the client to. Target stays the client id (UIs navigate by it) and\nLabel carries the title, so neither can name the slug.","type":"string"},"step":{"type":"string","x-enum-varnames":["StepCredential","StepProfile","StepServerInScope","StepToolRule","StepTierCap","StepTokenPermission","StepGlobalGate","StepServerState","StepToolApproval"]},"target":{"type":"string"}},"type":"object"},"runtime.GuardFix":{"properties":{"kind":{"type":"string"},"target":{"type":"string"}},"type":"object"},"runtime.MovedRefs":{"properties":{"clients":{"items":{"type":"string"},"type":"array","uniqueItems":false},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"runtime.ProfilePatch":{"properties":{"changes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"profile":{"type":"string"},"proposed":{"$ref":"#/components/schemas/config.ProfileConfig"}},"type":"object"},"runtime.ProfileView":{"properties":{"blocked_24h":{"type":"integer"},"calls_24h":{"type":"integer"},"code_execution":{"type":"boolean"},"description":{"type":"string"},"effective_code_execution":{"type":"boolean"},"effective_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"effective_unannotated":{"type":"string"},"is_legacy":{"type":"boolean"},"management_tools":{"type":"boolean"},"max_tier":{"type":"string"},"name":{"type":"string"},"servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"switchable_to":{"items":{"type":"string"},"type":"array","uniqueItems":false},"title":{"type":"string"},"tool_count":{"description":"ToolCount is the v2 field: indexed tools on the effective servers.\nDeprecated: use tool_counts.","type":"integer"},"tool_counts":{"$ref":"#/components/schemas/runtime.ToolCounts"},"tools":{"$ref":"#/components/schemas/config.ProfileToolRules"},"unannotated":{"type":"string"},"used_by":{"$ref":"#/components/schemas/runtime.UsedBy"}},"type":"object"},"runtime.SuggestionKind":{"type":"string","x-enum-varnames":["SuggestAllow","SuggestAddServer","SuggestClassify","SuggestNone"]},"runtime.ToolAccessView":{"properties":{"callable":{"type":"boolean"},"reason":{"type":"string"},"visible":{"type":"boolean"}},"type":"object"},"runtime.ToolCounts":{"properties":{"destructive":{"type":"integer"},"read":{"type":"integer"},"unannotated_hidden":{"type":"integer"},"write":{"type":"integer"}},"type":"object"},"runtime.TryHidden":{"properties":{"reason":{"type":"string"},"server":{"type":"string"},"tool":{"type":"string"}},"type":"object"},"runtime.UsedBy":{"properties":{"anonymous_profile":{"type":"boolean"},"clients":{"items":{"$ref":"#/components/schemas/runtime.UsedByClient"},"type":"array","uniqueItems":false},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"runtime.UsedByClient":{"properties":{"id":{"type":"string"},"mode":{"type":"string"}},"type":"object"},"runtime.WarningAction":{"properties":{"kind":{"type":"string"},"target":{"type":"string"}},"type":"object"},"scanner.BundleInfo":{"properties":{"authority":{"description":"Authority is the signing root serving this bundle: \"publisher\" (the\nembedded default, or verified against a publisher key), \"operator\", or \"\"\nfor an unsigned external bundle.","type":"string"},"bundle_version":{"description":"BundleVersion / SchemaVersion are the corpus's own declared versions.","type":"string"},"coverage_degraded":{"description":"CoverageDegraded suspends scan-mode auto-approval; DegradedReason says\nwhy (one of the Degraded* constants).","type":"boolean"},"declared_skipped":{"type":"integer"},"degraded_reason":{"type":"string"},"fingerprint":{"description":"Fingerprint is the first 12 hex chars of the SHA-256 of the corpus bytes:\na stable identity an operator (or automation) can compare across hosts\nwithout shipping the whole file around.","type":"string"},"full_digest":{"description":"FullDigest is the complete lowercase-hex SHA-256 of the bundle bytes —\nthe ONLY value rollback accepts (FR-010). Fingerprint stays the 12-hex\nhuman label beside it.","type":"string"},"generated_at":{"description":"GeneratedAt is the corpus freshness stamp. It is the bundle's own\n` + "`" + `generated_at` + "`" + ` key when present; for a file-sourced bundle without one it\nfalls back to the file's modification time, so a years-stale corpus is\ndistinguishable from a fresh export.","type":"string"},"last_activated_at":{"description":"LastActivatedAt is when the serving external bundle was activated; nil\nfor the embedded default.","type":"string"},"last_checked_at":{"description":"LastCheckedAt is the end of the most recent pipeline run, including\nno-op runs the idempotence short-circuit skipped.","type":"string"},"last_rejection":{"$ref":"#/components/schemas/scanner.BundleRejection"},"load_error":{"description":"LoadError is the reason the LAST configured-path load failed, if any. The\npreviously active (or embedded) corpus stays live — a bundle problem must\nnever leave the scanner with no signatures — but the failure is surfaced\nhere rather than swallowed.","type":"string"},"loaded_at":{"description":"LoadedAt is when this corpus became active in this process.","type":"string"},"path":{"description":"Path is the configured filesystem path, when Source is \"file\".","type":"string"},"pinned":{"description":"Pinned is true while an operator rollback pin governs activation.","type":"boolean"},"refresh":{"$ref":"#/components/schemas/scanner.BundleRefreshStatus"},"reprotect":{"$ref":"#/components/schemas/scanner.BundleReprotectStatus"},"rollback":{"description":"Rollback is true when the active bundle was activated by an explicit\nrollback.","type":"boolean"},"runnable_rules":{"description":"RunnableRules is how many rules are LIVE in the offline tier; SkippedRules\nand DeclaredSkipped are the not-runnable / bundle-declared-skipped\nremainder (FR-006/FR-007) — un-evaluated coverage, never clean coverage.","type":"integer"},"schema_version":{"type":"string"},"sequence":{"description":"Sequence is the manifest sequence as published (decimal string), \"\" when\nthe bundle carries none.","type":"string"},"signature_count":{"description":"SignatureCount is the bundle's self-declared signature count.","type":"integer"},"signature_verified":{"description":"SignatureVerified reports whether the active bundle's detached signature\nverified. Always false for the embedded default (it is binary-trusted).","type":"boolean"},"skipped_rules":{"type":"integer"},"source":{"description":"Source is BundleSourceEmbedded, BundleSourceFile or BundleSourceFetch.","type":"string"},"stale":{"description":"Stale and StaleAfterDays are computed at read time next to\nStalenessDays; a future generated_at is never stale. StaleAfterDays nil\nmeans the flag is not evaluated.","type":"boolean"},"stale_after_days":{"type":"integer"},"staleness_days":{"description":"StalenessDays is the whole days since GeneratedAt (nil when unknown).","type":"integer"},"trust_epoch":{"description":"TrustEpoch is the epoch the bundle was published under.","type":"integer"}},"type":"object"},"scanner.BundleRefreshStatus":{"description":"Refresh is the refresh-cycle status (nil before any cycle or setting is\nknown). Reprotect is the post-activation re-protection sweep status,\nset from the server through SetReprotectStatus.","properties":{"consecutive_failures":{"type":"integer"},"fetch_enabled":{"type":"boolean"},"fetch_host":{"description":"FetchHost is the host of the configured fetch URL (\"\" when none).","type":"string"},"fetch_reason":{"type":"string"},"fetch_state":{"description":"FetchState and FetchReason are the fetch leg's own last answer (one of the\nRefreshOutcome* values and its reason), kept apart from LastOutcome: a file\nactivation owns the merged cycle outcome but must not hide a fetch leg that\ncannot run (B16 warning 3).","type":"string"},"interval_seconds":{"type":"integer"},"last_attempt_at":{"type":"string"},"last_outcome":{"type":"string"},"last_reason":{"type":"string"},"last_trigger":{"description":"LastTrigger, LastOutcome and LastReason use the closed vocabularies above.","type":"string"},"next_check_at":{"type":"string"}},"type":"object"},"scanner.BundleRejection":{"description":"LastRejection is the most recent refused candidate. It is retained\nacross a later successful load so \"what did it refuse, and when\"\nsurvives.","properties":{"at":{"type":"string"},"detail":{"description":"Detail is a short human string (which ceiling, which key id, which\nepoch, the bundlesig contract code). Never parsed.","type":"string"},"reason":{"description":"Reason is one of the Reject* constants; the only field to branch on.","type":"string"}},"type":"object"},"scanner.BundleReprotectStatus":{"properties":{"last_completed_at":{"type":"string"},"reason":{"description":"Reason qualifies suspended and failed (for example\nReprotectReasonAutoBaselineScanOff).","type":"string"},"servers_scanned":{"type":"integer"},"servers_with_hits":{"type":"integer"},"state":{"description":"State is one of the ReprotectState* constants.","type":"string"}},"type":"object"},"secureenv.EnvConfig":{"description":"Environment configuration for secure variable filtering","properties":{"allowed_system_vars":{"items":{"type":"string"},"type":"array","uniqueItems":false},"custom_vars":{"additionalProperties":{"type":"string"},"type":"object"},"enhance_path":{"description":"Enable PATH enhancement for Launchd scenarios","type":"boolean"},"forward_proxy_env":{"description":"ForwardProxyEnv opts in to forwarding the ambient HTTP(S)/ALL/NO/FTP proxy\nenvironment variables to spawned upstream servers (MCP-2769). It is OFF by\ndefault and deliberately kept out of the AllowedSystemVars default list:\nproxy URLs frequently carry credentials (http://user:pass@proxy), so\nforwarding them to every stdio upstream is a credential-leak risk. When\nenabled, values are forwarded with their userinfo (credentials) redacted.","type":"boolean"},"inherit_system_safe":{"type":"boolean"}},"type":"object"},"storage.ClientCredentialObservation":{"properties":{"at":{"type":"string"},"state":{"type":"string"}},"type":"object"},"storage.OnboardingState":{"description":"State is the persisted wizard engagement record. Engaged is true once\nthe wizard was shown and the user completed or skipped it.","properties":{"client_connected_at":{"additionalProperties":{"type":"string"},"description":"ClientConnectedAt records, per client id from the fixed connect client\nregistry (internal/connect.GetAllClients — never user input), the last\ntime a connect write succeeded for that client (Spec 109-b FR-042).\nWritten by the connect success path through UpdateOnboardingState so a\nconcurrent onboarding/mark write can never drop it. Consumed by the\nVerify step / presence layer to tell \"connected, never seen\" apart from\n\"connected seconds ago, hasn't reconnected yet\".","type":"object"},"client_credential_observed":{"additionalProperties":{"$ref":"#/components/schemas/storage.ClientCredentialObservation"},"description":"ClientCredentialObserved records, per client id, the LAST credential\nclassification an on-demand read produced (Spec 108-f FR-025, F11): what\nthe client's config held (client | admin_key | none | revoked | expired)\nand when it was read. The stat-only GET /clients listing never reads a\nconfig (Spec 075: no macOS App-Data prompt from a list), so this is how\nit still reports a client that holds the admin key across restarts. It is\nwritten only when the classification CHANGES, by every on-demand read\n(GET /clients/{id}, GET /connect/{client}, the admin-key upgrade preview,\na connect write) and deleted on disconnect. Additive: an older binary\nignores it, and a record without it reads as \"unknown\".","type":"object"},"client_disconnected_at":{"additionalProperties":{"type":"string"},"type":"object"},"client_last_seen":{"additionalProperties":{"type":"string"},"description":"ClientLastSeen records the latest MCP initialize for a recognised client\nalias. It is intentionally kept with onboarding state: presence is a\nlocal UI concern and must still work when telemetry is disabled.","type":"object"},"connect_step_status":{"description":"ConnectStepStatus is one of: \"\", \"completed\", \"completed_external\",\n\"skipped\" (Spec 080 FR-001). \"completed_external\" records a dismissal\nwhere the connect step was untouched but the install was already\nconnected outside the wizard (CLI, ConnectModal, manual config).","type":"string"},"engaged":{"description":"Engaged is true once the wizard was shown and the user completed or\nskipped it. Once true, the wizard does not auto-show again, even if\nstate regresses (e.g. user disconnects all clients).","type":"boolean"},"engaged_at":{"description":"EngagedAt is the timestamp of completion or explicit skip.","type":"string"},"first_shown_at":{"description":"FirstShownAt is the timestamp of first wizard render.","type":"string"},"server_step_status":{"description":"ServerStepStatus is one of: \"\", \"completed\", \"skipped\".","type":"string"}},"type":"object"},"telemetry.DiagnosticsCounters":{"properties":{"current_error_codes":{"additionalProperties":{"type":"integer"},"description":"CurrentErrorCodes is the STANDING state at heartbeat time: stable MCPX_\ncode -\u003e number of configured servers currently in that state. It is not\na counter and is never persisted — it is recomputed each heartbeat from\nthe supervisor's live stateview.\n\nSchema v11 (MCP-2967). It exists because error_code_counts_24h became\nedge-triggered in the same change: previously the supervisor re-counted\nevery standing failure on its 30s reconcile ticker, so a parked install\ninflated the counter by ~2880/day/server. Edge-triggering alone would\nhave swung the error to the other side — the 24h window decays, this\nstruct is omitempty via isZero(), so a permanently broken install would\nemit once and then disappear from the payload entirely, and absent reads\nas zero. The two fields answer different questions and are only correct\ntogether: \"how often did something newly break\" and \"how many servers\nare broken right now\".\n\nSafe: only MCPX_* enum constants as keys, never server names, URLs,\ncommands, or free text; values are non-negative server counts.","type":"object"},"error_code_counts_24h":{"additionalProperties":{"type":"integer"},"description":"ErrorCodeCounts24h maps stable MCPX_ code strings to 24h occurrence counts.\nSafe: only MCPX_* enum constants are stored here, never free text, paths,\nserver names, or user-entered values.","type":"object"},"fix_attempted_24h":{"description":"FixAttempted24h counts POST /api/v1/diagnostics/fix calls in the last 24h.","type":"integer"},"fix_succeeded_24h":{"description":"FixSucceeded24h counts fix invocations with outcome=\"success\" in the last 24h.","type":"integer"},"unique_codes_ever":{"description":"UniqueCodesEver is the cardinality of the all-time error code set.\nBounded by the MCPX_ catalog size (~30 codes), never approaches PII risk.","type":"integer"}},"type":"object"},"telemetry.FeedbackContext":{"properties":{"anonymous_id":{"description":"AnonymousID is the install's telemetry anonymous ID (heartbeat value).","type":"string"},"arch":{"type":"string"},"connected_server_count":{"type":"integer"},"diagnostics":{"$ref":"#/components/schemas/telemetry.DiagnosticsCounters"},"edition":{"type":"string"},"go_version":{"type":"string"},"last_error_code":{"description":"LastErrorCode is the most recent MCPX_* error code.","type":"string"},"last_startup_outcome":{"description":"LastStartupOutcome is the previous startup's outcome word.","type":"string"},"machine_id":{"description":"MachineID is the hashed machine identifier (heartbeat value).","type":"string"},"os":{"type":"string"},"previous_shutdown":{"description":"PreviousShutdown is how the previous run ended (clean, crash, ...).","type":"string"},"routing_mode":{"type":"string"},"server_count":{"type":"integer"},"tool_count":{"type":"integer"},"uptime_minutes":{"description":"UptimeMinutes is the daemon's uptime. Omitted from short-lived CLI\nsubmissions, where the process uptime says nothing about the daemon.","type":"integer"},"version":{"type":"string"}},"type":"object"},"telemetry.FeedbackRequest":{"properties":{"category":{"description":"bug, feature, other","type":"string"},"context":{"$ref":"#/components/schemas/telemetry.FeedbackContext"},"email":{"type":"string"},"message":{"type":"string"}},"type":"object"},"telemetry.FeedbackResponse":{"properties":{"error":{"type":"string"},"issue_url":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}},"securitySchemes":{"ApiKeyAuth":{"description":"API key authentication via query parameter. Use ?apikey=your-key","in":"query","name":"apikey","type":"apiKey"}}}, + "components": {"schemas":{"auth.CredentialIssuer":{"properties":{"actor_kind":{"type":"string"},"actor_name":{"type":"string"},"surface":{"type":"string"}},"type":"object"},"config.AgentTokenRateLimit":{"description":"AgentTokenRateLimit caps how many upstream tool calls ONE agent token may\nmake: PerMinute on average, Burst at once (issue #1699). Every token is\ncounted separately, and a token's own rate_limit (set when it is created)\nreplaces this default for that token. Only agent-token callers are\nlimited; the admin API key, the unix socket and an unauthenticated /mcp\ncaller are not. Absent or per_minute 0 = no limit (default, zero behavior\nchange). The counters are in memory: a restart gives every token a full\nallowance again. Hot-reloadable. File/API-configured only, no env scheme.","properties":{"burst":{"description":"Burst is how many calls a token may make at once after a quiet spell.\n0 = the PerMinute value.","type":"integer"},"per_minute":{"description":"PerMinute is the sustained rate. 0 = no limit.","type":"integer"}},"type":"object"},"config.AuditLogConfig":{"description":"AuditLog configures the Spec 107 edition-neutral audit sink\n(internal/audit). nil means \"use the per-edition/per-transport\ndefault\" (EffectiveAuditLog); restart-pinned (bound at sink\nconstruction). See audit_log.go.","properties":{"compress":{"type":"boolean"},"enabled":{"type":"boolean"},"max_age_days":{"type":"integer"},"max_backups":{"type":"integer"},"max_size_mb":{"type":"integer"},"path":{"type":"string"},"stdout":{"type":"boolean"}},"type":"object"},"config.ConcurrencyDefaults":{"description":"ServerConcurrencyDefaults is scope (b) of FR-020: the blanket per-server\ndefault set inherited by every server that does not override a setting.\nAbsent (the default) = no per-server limiting unless a server configures\nit explicitly. File/API-configured only — no env scheme (FR-022).","properties":{"max_concurrent_requests":{"type":"integer"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"}},"type":"object"},"config.Config":{"properties":{"activity_cleanup_interval_min":{"description":"Background cleanup interval in minutes (default: 60)","type":"integer"},"activity_max_records":{"description":"Max records before pruning (default: 400000)","type":"integer"},"activity_max_response_size":{"description":"Response truncation limit in bytes (default: 65536)","type":"integer"},"activity_max_size_mb":{"description":"ActivityMaxSizeMB caps the total activity-log size in MB before the\noldest records are pruned. Omit the key for the 256MB default; set it to\n0 to disable the size cap.","type":"integer"},"activity_retention_days":{"description":"Activity logging settings (RFC-003)","type":"integer"},"advertise_upstream_servers":{"description":"AdvertiseUpstreamServers controls whether MCP clients are told the\nnames of the upstream servers they can reach — in the initialize\ninstructions and the retrieve_tools description — so agents use the\nproxied tools instead of falling back to shell CLIs. Names are always\nfiltered to the caller's profile and agent-token scope. Default true;\nset false to keep server names out of client context. Read live.","type":"boolean"},"agent_token_rate_limit":{"$ref":"#/components/schemas/config.AgentTokenRateLimit"},"aggregate_upstream_prompts":{"description":"AggregateUpstreamPrompts, when true, aggregates every connected upstream\nserver's advertised MCP prompts into mcpproxy's own prompts/list\n(exposed as \"\u003cserver\u003e__\u003cprompt\u003e\"). OFF by default: users are safe by\ndefault and opt in deliberately. EnablePrompts still governs the built-in\nprompts + the prompts capability; this flag gates ONLY the upstream\naggregation performed by RefreshPrompts. Hot-reloadable.","type":"boolean"},"allow_private_registry_fetch":{"description":"AllowPrivateRegistryFetch opts out of the registry SSRF guard (MCP-1076,\nCWE-918). By default (false) registry fetches refuse any host that is — or\nresolves to — a non-routable address (loopback, RFC1918/CGNAT private,\nlink-local incl. the 169.254.169.254 cloud-metadata endpoint), so a\nmalicious or typo'd registry source cannot turn the daemon into a\nrequest-forgery vector against internal services.\n\nThis opt-out is BLANKET (all-or-nothing): setting it true disables the\nguard for EVERY non-routable range at once — loopback, RFC1918/CGNAT\nprivate, link-local AND the 169.254.169.254 cloud-metadata endpoint. There\nis no way to allow only loopback; enabling it for a localhost dev registry\nalso re-opens the cloud-metadata SSRF vector. Set true ONLY when you\nintentionally run a trusted registry mirror on an internal/private address,\nideally on a host with no cloud-metadata exposure. The change takes effect\nonly on daemon (re)start or config reload.","type":"boolean"},"allow_server_add":{"type":"boolean"},"allow_server_remove":{"type":"boolean"},"anonymous_profile":{"description":"AnonymousProfile confines every caller whose request authenticates as\ncredential kind \"anonymous\" (no credential, or an unrecognised\nnon-agent token accepted by the require_mcp_auth:false back-compat\nbranch) to the named profile (Spec 108 FR-008). Empty (default) means\nunconfined, legacy anonymous behaviour. A name that does not match any\nconfigured profile resolves anonymous callers to deny-all and is\nreported as a validation warning (data-model.md §1).","type":"string"},"api_key":{"description":"Security settings","type":"string"},"audit_log":{"$ref":"#/components/schemas/config.AuditLogConfig"},"call_tool_timeout":{"type":"string"},"check_server_repo":{"description":"Repository detection settings","type":"boolean"},"code_execution_max_parallel":{"description":"Default concurrency for call_tools() batches (1-32, default: 8)","type":"integer"},"code_execution_max_tool_calls":{"description":"Max tool calls per execution (0 = unlimited, default: 0)","type":"integer"},"code_execution_pool_size":{"description":"JavaScript runtime pool size (default: 10)","type":"integer"},"code_execution_timeout_ms":{"description":"Timeout in milliseconds (default: 120000, max: 600000)","type":"integer"},"data_dir":{"type":"string"},"debug_search":{"type":"boolean"},"direct_tool_response_mode":{"description":"DirectToolResponseMode selects the serialization of the DIRECT\nenumeration surface (Spec 102). Valid values: \"\" (= full), \"full\"\n(default: today's schema-bearing entries), \"deferred\" (description +\ncompact signature, with a minimal permissive input schema; upstream\ninputSchema and outputSchema are stripped and recovered on demand via\ndescribe_tool).\n\nDeliberately NOT an extension of tool_response_mode: reusing that axis\nwould silently change /mcp/all output for every deployment already\nrunning compact, which FR-015 forbids. Serialization-only — it never\nchanges WHICH tools are listed, only how (FR-008). Hot-reloadable.","type":"string"},"disable_management":{"type":"boolean"},"docker_isolation":{"$ref":"#/components/schemas/config.DockerIsolationConfig"},"docker_recovery":{"$ref":"#/components/schemas/config.DockerRecoveryConfig"},"enable_code_execution":{"description":"Code execution settings","type":"boolean"},"enable_prompts":{"description":"Prompts settings","type":"boolean"},"enable_skills":{"description":"EnableSkills, when true, makes mcpproxy read the skills that upstream\nservers expose through the MCP skills extension. OFF by default. Unlike\nEnablePrompts this is hot-reloadable. No CLI flag, no environment\nvariable.","type":"boolean"},"enable_socket":{"description":"Enable Unix socket/named pipe for local IPC (default: true)","type":"boolean"},"enable_tray":{"description":"Deprecated: EnableTray is unused and has no runtime effect. Kept for backward compatibility.","type":"boolean"},"environment":{"$ref":"#/components/schemas/secureenv.EnvConfig"},"features":{"$ref":"#/components/schemas/config.FeatureFlags"},"forward_client_headers":{"description":"ForwardClientHeaders is the global switch for client header forwarding\n(Spec 112): copying allowlisted headers from the inbound /mcp request into\nthe upstream tools/call request. nil (absent) means enabled; because every\nper-server forward_headers allowlist is empty by default, the default\nforwards nothing. false disables forwarding for every server. Read via\nIsClientHeaderForwardingEnabled(); MCPPROXY_FORWARD_CLIENT_HEADERS\noverrides it for the process. Distinct from ForwardedHeaders/trusted_proxies\n(Spec 107), which trusts inbound X-Forwarded-*.","type":"boolean"},"forward_proxy_env":{"description":"ForwardProxyEnv opts in to forwarding the ambient HTTP(S)/ALL/NO/FTP proxy\nenvironment variables to spawned stdio upstream servers (MCP-2769). OFF by\ndefault: proxy URLs commonly embed credentials (http://user:pass@proxy), so\nforwarding them to every upstream is a credential-leak risk. When enabled,\nvalues are forwarded with their userinfo (credentials) redacted.","type":"boolean"},"health_check_interval":{"description":"Discovery \u0026 health-check cadence (spec 074, #608). Both are *Duration\ntri-state pointers: nil = inherit the built-in default; a pointer to 0s =\nthe loop is disabled; a positive value = that interval. Defaults live only\nin the resolvers (ResolveHealthCheckInterval / ResolveToolDiscoveryInterval)\nso an unset key behaves exactly as before this feature (SC-005). Validated\nin Validate(): health-check ∈ {0} ∪ [5s,1h]; tool-discovery ∈ {0} ∪ [30s,24h].","type":"string"},"http_idle_timeout":{"description":"HTTPIdleTimeout caps how long an idle keep-alive connection is kept open.\nUnset = 180s. \"0s\" removes the dedicated idle deadline, but net/http then\nfalls back to ReadTimeout — idle is fully unbounded only when\nhttp_read_timeout is also \"0s\". Requires a restart.","type":"string"},"http_read_timeout":{"description":"HTTPReadTimeout caps how long reading a whole request (headers + body)\nmay take. Unset = 120s; \"0s\" disables it. Requires a restart.","type":"string"},"http_write_timeout":{"description":"HTTPWriteTimeout caps how long producing a whole response may take on\nnon-streaming endpoints (REST, Web UI, health). Unset = 120s; \"0s\"\ndisables it globally. MCP and SSE /events routes are exempt by design.","type":"string"},"init_timeout":{"description":"InitTimeout is the global default deadline for an upstream's MCP\n` + "`" + `initialize` + "`" + ` handshake (MCP-3322 / GH #760). *Duration tri-state: nil =\ninherit the built-in 30s default; a positive value = that deadline. A\nper-server InitTimeout overrides this. Resolved by ResolveInitTimeout;\nvalidated to {0} ∪ [1s, 30m] in Validate(). Servers doing legitimate\nfirst-run warmup (cache/index build) before answering ` + "`" + `initialize` + "`" + ` can\nraise this so they are not killed mid-startup.","type":"string"},"instructions":{"description":"Instructions text returned in the MCP initialize response to guide AI agents.\nWhen empty, a built-in default is used that explains retrieve_tools workflow.","type":"string"},"intent_declaration":{"$ref":"#/components/schemas/config.IntentDeclarationConfig"},"listen":{"type":"string"},"logging":{"$ref":"#/components/schemas/config.LogConfig"},"max_concurrent_requests":{"description":"Concurrency limits (spec 093, GH #955). Scope (a) of FR-020: the GLOBAL\nAGGREGATE limiter — one proxy-wide cap on concurrently running upstream\ntool calls, with its own bounded wait queue. Tri-state pointers: absent =\nthe limiter does not exist (default, zero behavior change); an explicit 0\nmax also disables it; positive = that cap. This scope is NEVER a\nper-server inheritance source — per-server values come from\nServerConcurrencyDefaults / the per-server overrides — but a server's\neffective concurrency is bounded by BOTH its own limiter and this one.\nResolved by ResolveGlobalConcurrency; hot-reloadable; overridable via\nMCPPROXY_MAX_CONCURRENT_REQUESTS / _QUEUE_SIZE / _QUEUE_TIMEOUT (FR-022).","type":"integer"},"max_result_size_chars":{"description":"MaxResultSizeChars is advertised on every tool as\n` + "`" + `_meta.anthropic/maxResultSizeChars` + "`" + `; it raises Claude Code's\ninline-response ceiling from 50k to up to 500k chars. Omit the key for\nthe 500000 default; set it to 0 to disable the annotation.","type":"integer"},"mcpServers":{"items":{"$ref":"#/components/schemas/config.ServerConfig"},"type":"array","uniqueItems":false},"mcp_oauth_enabled":{"description":"MCPOAuthEnabled turns on browser login (OAuth 2.1 + PKCE) for MCP\nclients on the loopback listener (Spec 132). Experimental, default false:\nwith it off nothing changes. Env override MCPPROXY_MCP_OAUTH_ENABLED is\nprocess-only and never persisted. Live, no restart needed.","type":"boolean"},"mcp_reject_query_apikey":{"description":"MCPRejectQueryAPIKey makes every MCP endpoint (/mcp*) refuse a request that\ncarries a ?apikey= query parameter, with a 401, instead of honouring it. A credential in a URL ends up in access logs,\nproxy logs and browser history; MCP clients can send Authorization:\nBearer or X-API-Key instead. Default false (the query form keeps\nworking, for clients that can only configure a URL). It covers only the\nMCP endpoints: the Web UI and its SSE stream (/events) still use the\nquery form. Live, no restart needed.","type":"boolean"},"oauth_expiry_warning_hours":{"description":"Health status settings","type":"number"},"oauth_token_encryption_key":{"description":"OAuthTokenEncryptionKey seals the upstream OAuth tokens stored in\nconfig.db (Spec 123). Empty (the default) leaves them as plain JSON. It\ntakes a secret reference (${file:/abs/path}, ${env:NAME},\n${keyring:NAME}) or a literal standard-base64 32-byte key; the\nMCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY[_FILE] variables override it. The key\nis resolved only where config.db is opened (ResolveOAuthTokenKey), never\nstored on Config, and is restart-gated, so every save writes the field\nas configured.","type":"string"},"observability":{"$ref":"#/components/schemas/config.ObservabilityConfig"},"output_sanitisation":{"$ref":"#/components/schemas/config.OutputSanitisationConfig"},"output_validation":{"$ref":"#/components/schemas/config.OutputValidationConfig"},"profiles":{"description":"Profiles are optional named, server-scoped views exposed at /mcp/p/\u003cname\u003e\n(Spec 057). Absent/empty is fully supported — /mcp is unchanged and configs\nwithout this key serialize byte-identically (SC-004).","items":{"$ref":"#/components/schemas/config.ProfileConfig"},"type":"array","uniqueItems":false},"quarantine_enabled":{"description":"QuarantineEnabled controls whether quarantine is active. It gates two\nthings together:\n 1. Server-level auto-quarantine for newly added servers (issue #370).\n When true, servers added via the upstream_servers MCP tool or the\n REST API default to quarantined=true; when false, they default to\n quarantined=false. Explicit per-request values always win.\n 2. Tool-level quarantine (Spec 032): per-tool SHA-256 approval of\n tool descriptions/schemas.\nWhen nil (default), quarantine is enabled (secure by default). Set to\nexplicit false to opt out of both. Per-server SkipQuarantine still\napplies for the tool-level check on individual servers.","type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"read_only_mode":{"type":"boolean"},"registries":{"description":"Registries configuration for MCP server discovery","items":{"$ref":"#/components/schemas/config.RegistryEntry"},"type":"array","uniqueItems":false},"registries_locked":{"description":"RegistriesLocked is an enterprise stub knob (MCP-866): when true, runtime\nadditions of custom registries (e.g. ` + "`" + `registry add-source` + "`" + `, the REST/MCP\nadd-source surface) are rejected so an administrator can pin the discovery\nsources. Built-in defaults are unaffected. Documented but otherwise inert\nbeyond the add-source rejection.","type":"boolean"},"require_mcp_auth":{"description":"Require authentication on /mcp endpoint (default: false)","type":"boolean"},"reveal_secret_headers":{"description":"RevealSecretHeaders, when true, disables the redaction of the\nsecret-bearing server fields — sensitive header values (Authorization,\nX-API-Key, Cookie, …), env-var secrets, and URL query credentials — in\nresponses from the ` + "`" + `upstream_servers` + "`" + ` MCP tool, the ` + "`" + `/api/v1/servers` + "`" + `\nREST API, and the SSE event stream. It also lets URL secrets echoed\ninto last_error / health.detail through unscrubbed.\n\nDefault false — sensitive values are surfaced masked as\n` + "`" + `••••\u003clast2\u003e (\u003cN\u003e chars)` + "`" + ` (error strings use ` + "`" + `***REDACTED***` + "`" + `) so an\nMCP agent cannot read Bearer tokens / API keys / URL secrets out of\nanother upstream's config (PR #425, issue #872). ${env:…}/${keyring:…}\nreferences are labels, not secrets, and pass through unchanged.\n\nThe Web UI / macOS tray edit forms work without seeing the real\nvalues: PATCH /api/v1/servers/{id} deep-merges (omitted keys are\npreserved, see ` + "`" + `headers_remove` + "`" + ` / ` + "`" + `env_remove` + "`" + ` for explicit\ndeletes), so clients compute a diff and only send the keys that\nactually changed. Redacted-but-unchanged values never round-trip\n— the backend keeps the real string. Set this to true if a\ndownstream tool genuinely needs raw values in the response.","type":"boolean"},"routing_mode":{"description":"Routing mode (Spec 031): how MCP tools are exposed to clients\nValid values: \"retrieve_tools\" (default), \"direct\", \"code_execution\"","type":"string"},"security":{"$ref":"#/components/schemas/config.SecurityConfig"},"sensitive_data_detection":{"$ref":"#/components/schemas/config.SensitiveDataDetectionConfig"},"server_concurrency_defaults":{"$ref":"#/components/schemas/config.ConcurrencyDefaults"},"session_retention_days":{"description":"SessionRetentionDays is how long a work session is listed and kept whole\nin the activity log (Spec 124, default 7). Read at start.","type":"integer"},"telemetry":{"$ref":"#/components/schemas/config.TelemetryConfig"},"tls":{"$ref":"#/components/schemas/config.TLSConfig"},"tokenizer":{"$ref":"#/components/schemas/config.TokenizerConfig"},"tool_call_max_records_per_server":{"description":"Calls retained per server (default: 1000)","type":"integer"},"tool_call_max_response_size":{"description":"Bounds for the per-server tool-call history behind GET /api/v1/tool-calls\n(#1176). It is a recent-debugging window, not an audit log — the activity\nlog is the durable record — and it kept every upstream response whole,\nper server, forever. A non-positive value means \"use the default\", not\n\"disable\": this store must never be unbounded again, so there is\ndeliberately no off switch.","type":"integer"},"tool_discovery_interval":{"type":"string"},"tool_response_limit":{"type":"integer"},"tool_response_mode":{"description":"Tool response mode (Spec 085): how retrieve_tools serializes results.\nValid values: \"\" (= full), \"full\" (default: today's schema-bearing\nentries), \"compact\" (signature + first-sentence entries). Orthogonal to\nrouting_mode — routing_mode selects the tool SURFACE, this selects the\nSERIALIZATION within the retrieve_tools surface. Serialization-only: it\nnever affects the query, ranking, or result set. Hot-reloadable.","type":"string"},"tool_response_session_risk_warning":{"description":"ToolResponseSessionRiskWarning controls whether the prose ` + "`" + `warning` + "`" + ` field\nis included in the ` + "`" + `session_risk` + "`" + ` object returned by ` + "`" + `retrieve_tools` + "`" + `.\nThe structured fields (level, lethal_trifecta, has_open_world_tools, etc.)\nare always included. Default: false (quiet for LLM clients) — see issue #406.\nMost tools lack annotations, so the MCP-spec defaults treat them as fully\npermissive across all three risk axes, which makes the prose warning fire\non almost every call and wastes tokens.","type":"boolean"},"tools_limit":{"type":"integer"},"toon_min_savings_pct":{"description":"ToonMinSavingsPct is the minimum byte-savings percentage (validated\n1-90; 0/unset → 15) the complete TOON emission (marker + hint + body)\nmust achieve over the exact passthrough emission for adaptive mode to\nencode a block. Byte savings approximate token savings for the tabular\npayload class; the spec-083 profiler reports true token deltas.\nGlobal-only (no per-server override, FR-001).","type":"integer"},"toon_output":{"description":"ToonOutput selects the TOON encoding mode for call_tool_* result text\nblocks (spec 084): \"off\" (default — responses byte-identical to\npre-feature behavior), \"adaptive\" (encode only tabular-uniform payloads\nthat beat compact JSON by ToonMinSavingsPct), or \"always\"\n(benchmark/debug only — encodes every JSON-parseable block and can\nINCREASE token cost). Per-server override: ServerConfig.ToonOutput.\nResolved by ResolveToonOutput; hot-reloadable.","type":"string"},"top_k":{"description":"Deprecated: TopK is superseded by ToolsLimit and has no runtime effect. Kept for backward compatibility.","type":"integer"},"tray_endpoint":{"description":"Tray endpoint override (unix:// or npipe://)","type":"string"},"trusted_hosts":{"description":"TrustedHosts lists non-loopback Host header values accepted on loopback\nlisteners (GH #898). DNS-rebinding protection rejects requests whose Host\nheader is not a loopback address when mcpproxy listens on loopback; a\nreverse proxy (nginx → 127.0.0.1) forwarding the public domain in Host\ntrips it. Entries are hostnames, case-insensitive; an entry without a\nport matches any port, with a port it must match exactly; a leading dot\n(\".example.com\") is a subdomain wildcard. The single entry \"*\" disables\nHost and Origin validation entirely. The same list also validates the\nOrigin header when present (MCP spec DNS-rebinding defense). Empty\n(default) keeps full protection. Env override: MCPPROXY_TRUSTED_HOSTS\n(comma-separated).","items":{"type":"string"},"type":"array","uniqueItems":false},"trusted_proxies":{"description":"TrustedProxies lists the CIDRs or IP addresses whose X-Forwarded-For /\nX-Real-IP / X-Forwarded-Proto / X-Forwarded-Host headers are believed\n(Spec 107 FR-027). Empty (default) trusts nobody. Edition-neutral, live\n(hot-reloadable). Env override: MCPPROXY_TRUSTED_PROXIES (comma-separated).\nThe one reader is ForwardedHeaders; validation is validateTrustedProxies.","items":{"type":"string"},"type":"array","uniqueItems":false},"update_check":{"$ref":"#/components/schemas/config.UpdateCheckConfig"}},"type":"object"},"config.CustomPattern":{"properties":{"category":{"description":"Category (defaults to \"custom\")","type":"string"},"keywords":{"description":"Keywords to match (mutually exclusive with Regex)","items":{"type":"string"},"type":"array","uniqueItems":false},"name":{"description":"Unique identifier for this pattern","type":"string"},"regex":{"description":"Regex pattern (mutually exclusive with Keywords)","type":"string"},"severity":{"description":"Risk level: critical, high, medium, low","type":"string"}},"type":"object"},"config.DeepScanConfig":{"description":"DeepScan is the opt-in \"deep scan\" layer (Spec 077 US3). It subsumes the\ndeprecated top-level scanner_fetch_package_source / scanner_disable_no_new_privileges\nkeys (migrated on load) and gates the heavy Docker-based scanners + source\nextraction. Disabled by default (FR-006): only the deterministic in-process\nbaseline scanner runs. A deep-scan failure NEVER changes the baseline verdict\n(FR-007/FR-008).","properties":{"disable_no_new_privileges":{"description":"DisableNoNewPrivileges, when true, omits the ` + "`" + `--security-opt\nno-new-privileges` + "`" + ` flag from scanner container runs (snap-docker/AppArmor\nescape hatch). Absorbs the deprecated top-level\nscanner_disable_no_new_privileges. Default false.","type":"boolean"},"enabled":{"description":"Enabled is the master opt-in for the heavy layer (FR-006). Default false.","type":"boolean"},"fetch_package_source":{"description":"FetchPackageSource controls whether the scanner fetches the PUBLISHED\nsource of package-runner servers (npx/uvx) — without executing it — when\nno local source is available. Absorbs the deprecated top-level\nscanner_fetch_package_source. Default (nil) is ENABLED within deep scan.","type":"boolean"},"scanners":{"description":"Scanners optionally restricts which deep scanners may run under the\numbrella (by scanner id). Empty ⇒ all enabled deep scanners are eligible.","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"config.DockerIsolationConfig":{"description":"Docker isolation settings","properties":{"cpu_limit":{"description":"CPU limit for containers","type":"string"},"default_images":{"additionalProperties":{"type":"string"},"description":"Map of runtime type to Docker image","type":"object"},"enable_cache_volume":{"description":"Mount shared cache volumes for faster restarts (default: true)","type":"boolean"},"enabled":{"description":"Global enable/disable for Docker isolation (legacy; superseded by Mode)","type":"boolean"},"extra_args":{"description":"Additional docker run arguments","items":{"type":"string"},"type":"array","uniqueItems":false},"log_driver":{"description":"Docker log driver (default: json-file)","type":"string"},"log_max_files":{"description":"Maximum number of log files (default: 3)","type":"string"},"log_max_size":{"description":"Maximum size of log files (default: 100m)","type":"string"},"memory_limit":{"description":"Memory limit for containers","type":"string"},"mode":{"description":"Isolation mode: \"docker\" | \"sandbox\" | \"none\" (MCP-34.2). Unset per-server inherits the global mode; unset globally falls back to the legacy \"enabled\" flag (true ⇒ docker, false ⇒ none)","type":"string","x-enum-varnames":["IsolationModeDocker","IsolationModeSandbox","IsolationModeNone"]},"network_mode":{"description":"Docker network mode (default: bridge)","type":"string"},"registry":{"description":"Custom registry (defaults to docker.io)","type":"string"},"timeout":{"description":"Container startup timeout","type":"string"}},"type":"object"},"config.DockerRecoveryConfig":{"description":"Docker recovery settings","properties":{"enabled":{"description":"Enable Docker recovery monitoring (default: true)","type":"boolean"},"max_retries":{"description":"Maximum retry attempts (0 = unlimited)","type":"integer"},"notify_on_failure":{"description":"Show notification on recovery failure (default: true)","type":"boolean"},"notify_on_retry":{"description":"Show notification on each retry (default: false)","type":"boolean"},"notify_on_start":{"description":"Show notification when recovery starts (default: true)","type":"boolean"},"notify_on_success":{"description":"Show notification on successful recovery (default: true)","type":"boolean"},"persistent_state":{"description":"Save recovery state across restarts (default: true)","type":"boolean"}},"type":"object"},"config.FeatureFlags":{"description":"Deprecated: Features flags are unused and have no runtime effect. Kept for backward compatibility.","properties":{"enable_async_storage":{"type":"boolean"},"enable_caching":{"type":"boolean"},"enable_contract_tests":{"type":"boolean"},"enable_debug_logging":{"description":"Development features","type":"boolean"},"enable_docker_isolation":{"type":"boolean"},"enable_event_bus":{"type":"boolean"},"enable_health_checks":{"type":"boolean"},"enable_metrics":{"type":"boolean"},"enable_oauth":{"description":"Security features","type":"boolean"},"enable_observability":{"description":"Observability features","type":"boolean"},"enable_quarantine":{"type":"boolean"},"enable_runtime":{"description":"Runtime features","type":"boolean"},"enable_search":{"description":"Storage features","type":"boolean"},"enable_sse":{"type":"boolean"},"enable_tracing":{"type":"boolean"},"enable_tray":{"type":"boolean"},"enable_web_ui":{"description":"UI features","type":"boolean"}},"type":"object"},"config.IntentDeclarationConfig":{"description":"Intent declaration settings (Spec 018)","properties":{"strict_server_validation":{"description":"StrictServerValidation controls whether server annotation mismatches\ncause rejection (true) or just warnings (false).\nDefault: true (reject mismatches)","type":"boolean"}},"type":"object"},"config.IsolationConfig":{"description":"Per-server isolation settings","properties":{"enabled":{"description":"Enable Docker isolation for this server (nil = inherit global; legacy, superseded by Mode)","type":"boolean"},"extra_args":{"description":"Additional docker run arguments for this server","items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"description":"Custom Docker image (overrides default)","type":"string"},"log_driver":{"description":"Docker log driver override for this server","type":"string"},"log_max_files":{"description":"Maximum number of log files override","type":"string"},"log_max_size":{"description":"Maximum size of log files override","type":"string"},"mode":{"$ref":"#/components/schemas/config.IsolationMode"},"network_mode":{"description":"Custom network mode for this server","type":"string"},"working_dir":{"description":"Custom working directory in container","type":"string"}},"type":"object"},"config.IsolationMode":{"description":"Isolation mode: \"docker\" | \"sandbox\" | \"none\" (MCP-34.2). Unset per-server inherits the global mode; unset globally falls back to the legacy \"enabled\" flag (true ⇒ docker, false ⇒ none)","type":"string","x-enum-varnames":["IsolationModeDocker","IsolationModeSandbox","IsolationModeNone"]},"config.LogConfig":{"description":"Logging configuration","properties":{"compress":{"type":"boolean"},"enable_console":{"type":"boolean"},"enable_file":{"type":"boolean"},"filename":{"type":"string"},"json_format":{"type":"boolean"},"level":{"type":"string"},"log_dir":{"description":"Custom log directory","type":"string"},"max_age":{"description":"days","type":"integer"},"max_backups":{"description":"number of backup files","type":"integer"},"max_size":{"description":"MB","type":"integer"}},"type":"object"},"config.MetricsExporterConfig":{"description":"Metrics gates the Prometheus /metrics scrape endpoint (MCP-32). Disabled\nby default — operators opt in for k8s/enterprise deployments.","properties":{"enabled":{"description":"Enabled exposes /metrics on the existing HTTP listener when true.\nThe endpoint is admin-authenticated (SEC-07): scrapers must present the\nglobal API key, via X-API-Key or an Authorization: Bearer header.","type":"boolean"}},"type":"object"},"config.OAuthConfig":{"description":"OAuth configuration (keep even when empty to signal OAuth requirement)","properties":{"auth_server_metadata_url":{"type":"string"},"authorization_endpoint":{"description":"Spec 113-b: optional per-server discovery overrides. Each is an absolute\nhttps URL (http only on a loopback host) with no query, fragment or\nuserinfo; validated at write time only (ValidateOAuthEndpointOverrides).\nThe endpoint overrides rewrite the matching fields of the authorization\nserver metadata mcp-go reads; AuthServerMetadataURL replaces discovery.","type":"string"},"callback_base_url":{"type":"string"},"client_id":{"type":"string"},"client_secret":{"type":"string"},"extra_params":{"additionalProperties":{"type":"string"},"description":"Additional OAuth parameters (e.g., RFC 8707 resource)","type":"object"},"pkce_enabled":{"type":"boolean"},"redirect_uri":{"type":"string"},"refresh_replay_enabled":{"description":"Opt in only when token_endpoint supports idempotent refresh replay for at least 30 seconds.","type":"boolean"},"registration_endpoint":{"type":"string"},"scopes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"token_endpoint":{"type":"string"}},"type":"object"},"config.ObservabilityConfig":{"description":"Observability settings (Spec 069): usage aggregate cache/persistence cadence.","properties":{"metrics":{"$ref":"#/components/schemas/config.MetricsExporterConfig"},"tracing":{"$ref":"#/components/schemas/config.TracingExporterConfig"},"usage_cache_ttl":{"description":"UsageCacheTTL bounds the freshness of the usage endpoint's read cache for\nwide windows (FR-005). Default 5s.","type":"string"},"usage_persist_interval":{"description":"UsagePersistInterval is how often the actor-owned usage aggregate snapshot\nis flushed to storage. Default 30s.","type":"string"}},"type":"object"},"config.OutputSanitisationConfig":{"description":"Output sanitisation settings (Spec 054 Track B)","properties":{"max_redactions":{"description":"cap on redactions per response; default 100","type":"integer"},"response_action":{"description":"\"spotlight\" | \"redact\" | \"block\"; default \"spotlight\"","type":"string"},"spotlight_untrusted":{"description":"wrap untrusted output in spotlight markers; default true","type":"boolean"},"strip_classes":{"description":"classes to strip: ansi/c0c1/bidi/zero_width","items":{"type":"string"},"type":"array","uniqueItems":false},"strip_control_chars":{"description":"strip control-character classes; default false","type":"boolean"}},"type":"object"},"config.OutputValidationConfig":{"description":"Output-schema validation settings (Spec 056)","properties":{"max_bytes":{"description":"structured payload byte cap; default 5\u003c\u003c20","type":"integer"},"max_depth":{"description":"nesting depth cap; default 64","type":"integer"},"missing_structured_content":{"description":"\"allow\" | \"block\"; default \"allow\"","type":"string"},"mode":{"description":"\"off\" | \"warn\" | \"strict\"; default \"warn\"","type":"string"}},"type":"object"},"config.ProfileConfig":{"properties":{"code_execution":{"description":"CodeExecution: nil = inherit the global enable_code_execution gate;\nnon-nil narrows it (a profile can only narrow, never widen, FR-006).","type":"boolean"},"description":{"description":"\u003c= 500 chars (FR-001)","type":"string"},"management_tools":{"description":"ManagementTools: nil = legacy/inherit (FR-016); non-nil sets the\nprofile-level visibility of upstream_servers/quarantine_security.","type":"boolean"},"max_tier":{"description":"MaxTier caps the tier a tool may run at under this profile: \"\" (no\ncap) | \"read\" | \"write\" | \"destructive\" (FR-001).","type":"string"},"name":{"description":"slug (Spec 057 rules unchanged)","type":"string"},"servers":{"description":"references to mcpServers[].name","items":{"type":"string"},"type":"array","uniqueItems":false},"switchable_to":{"description":"SwitchableTo is the list of profile names a session under this\nprofile may ` + "`" + `set_profile` + "`" + ` into (FR-022). nil = legacy/none (research\nD6); a non-nil EMPTY list is an explicit \"none\" and must round-trip as\n` + "`" + `[]` + "`" + `, never be dropped by omitempty — hence the pointer (see the\nMarshalJSON note below, and profiles_v3_test.go's switchable_to round\ntrip case).","items":{"type":"string"},"type":"array","uniqueItems":false},"title":{"description":"display only, \u003c= 80 chars (FR-001)","type":"string"},"tools":{"$ref":"#/components/schemas/config.ProfileToolRules"},"unannotated":{"description":"Unannotated is this profile's handling of a tool whose effective\nannotations carry no tier hint: \"\" (unset, see EffectiveUnannotated) |\n\"deny\" | \"as_write\" | \"as_read\" (FR-001, FR-003).","type":"string"}},"type":"object"},"config.ProfileToolRules":{"description":"Tools holds the allow/deny/classify rule set (FR-001, FR-004, FR-005).","properties":{"allow":{"items":{"type":"string"},"type":"array","uniqueItems":false},"classify":{"additionalProperties":{"type":"string"},"type":"object"},"deny":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"config.RegistryEntry":{"properties":{"count":{"description":"number or string","type":"string"},"description":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"},"protocol":{"type":"string"},"provenance":{"description":"Provenance is the trust tag for this registry (MCP-866):\nRegistryProvenanceOfficial for built-in defaults, RegistryProvenanceCustom\nfor user-added registries. It is authoritatively (re)computed by the\nregistries merge from whether the ID is a shipped default — a user cannot\nclaim \"official\" by writing it into their config.","type":"string"},"requires_key":{"description":"RequiresKey marks a registry that needs an API key to be queried. When\ntrue and no key is configured, the registry is skipped/marked unavailable\nrather than failing the whole search (FR-008).","type":"boolean"},"servers_url":{"type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"url":{"type":"string"}},"type":"object"},"config.SecurityConfig":{"description":"Security scanner settings (Spec 039)","properties":{"auto_baseline_scan":{"description":"AutoBaselineScan is the kill-switch for the AUTOMATIC, informational\nPass-1 baseline scan: the free in-process TPA scan mcpproxy runs for every\nnewly admitted server (any trust mode) and, once per installation, over\npre-existing servers that have never been scanned.\n\nInformational ONLY: the resulting verdict populates the security badge and\nthe scan summary, and NEVER gates quarantine or approval. The\ntrust_mode:\"scan\" admission gate is a separate path and is unaffected by\nthis flag.\n\nDefault (nil) is ENABLED. Set to false to suppress every automatic scan\n(manual scans keep working). Env override: MCPPROXY_AUTO_BASELINE_SCAN,\nwhich wins over this field on every path.","type":"boolean"},"auto_rescan_on_change":{"description":"AutoRescanOnChange is the finer switch for the automatic, informational\nrescan that follows a tool-definition hash change: the in-process TPA scan\nof the changed (or newly pending) tool, recorded as hold evidence, and a\ndebounced informational server rescan that brings the review screen's scan\ncoverage back to \"current\".\n\nEvidence and freshness ONLY: this switch approves nothing. Under \"manual\"\nevery change is held for review whatever the verdict (RT-02); under\n\"scan\" the gate's own synchronous scan approves a clean change that\npasses the spec 120 structural gate (spec 119 FR-004), and this switch\ndoes not affect that path. Runs in every trust mode except \"auto\".\n\nDefault (nil) is ENABLED. It only takes effect while auto_baseline_scan is\nalso enabled, so a user can keep the admission scan and turn off per-change\nrescans with this key alone. Env override: MCPPROXY_AUTO_RESCAN_ON_CHANGE,\nwhich wins over this field on every path.","type":"boolean"},"deep_scan":{"$ref":"#/components/schemas/config.DeepScanConfig"},"integrity_check_interval":{"type":"string"},"integrity_check_on_restart":{"type":"boolean"},"require_signed_bundle":{"description":"RequireSignedBundle makes the detached signature sidecar mandatory for\nfile-dropped bundles (FR-007). Default false (maintainer decision D2):\nexisting unsigned drops keep working, but an unsigned external bundle\nalways runs with DEGRADED coverage (scan-mode auto-approval suspended).","type":"boolean"},"runtime_read_only":{"type":"boolean"},"runtime_tmpfs_size":{"type":"string"},"scan_timeout_default":{"type":"string"},"scanner_disable_no_new_privileges":{"description":"Deprecated (Spec 077 US3): migrated on load into DeepScan.DisableNoNewPrivileges\n(see migrateDeepScanConfig). Retained only so existing configs that still carry\nthe top-level key parse; consumers MUST read the effective value via\nSecurityConfig.IsDisableNoNewPrivileges. Cleared after migration.\n\nScannerDisableNoNewPrivileges, when true, omits the\n` + "`" + `--security-opt no-new-privileges` + "`" + ` flag from scanner container runs.\n\nBackground: snap-installed Docker on Ubuntu confines dockerd under the\n` + "`" + `snap.docker.dockerd` + "`" + ` AppArmor profile. When runc tries to transition\nthe container into the inner ` + "`" + `docker-default` + "`" + ` profile to exec the\nentrypoint, AppArmor refuses the transition because NO_NEW_PRIVS\nforbids privilege/profile changes on exec — the result is EPERM\n(\"operation not permitted\") and every scanner fails immediately.\n\nSet this to true ONLY on hosts hitting that incompatibility. Scanner\ncontainers still run with read-only rootfs, tmpfs /tmp, no-network by\ndefault, and read-only source mounts, so the marginal isolation loss\nis small. The preferred fix remains replacing snap docker with a\ndistro-packaged docker.","type":"boolean"},"scanner_fetch_package_source":{"description":"Deprecated (Spec 077 US3): migrated on load into DeepScan.FetchPackageSource\n(see migrateDeepScanConfig). Retained only so existing configs that still carry\nthe top-level key parse; consumers MUST read the effective value via\nSecurityConfig.EffectiveFetchPackageSource. Cleared after migration.\n\nScannerFetchPackageSource controls whether the scanner fetches the\nPUBLISHED source of package-runner servers (npx/uvx) — without executing\nit — when no local source is available (no Docker container, no local\npackage cache, no working_dir). This is the primary quarantine/scan\ntarget: a quarantined-on-add server is never run locally, so without this\nthe scan degrades to tool-definitions-only (no real source-level\nanalysis). See MCP-2206.\n\nFetching uses ` + "`" + `npm pack --ignore-scripts` + "`" + ` (npm) and ` + "`" + `uv pip download` + "`" + ` /\n` + "`" + `pip download` + "`" + ` with ` + "`" + `--only-binary=:all:` + "`" + ` (Python), which only download +\nunpack archives and NEVER run install, build, or setup.py — a scanner must\nnot execute the untrusted code it is scanning. The Python\n` + "`" + `--only-binary=:all:` + "`" + ` flag is required because downloading an sdist would\ninvoke its build backend (setup.py); packages with no wheel fall back to\ntool-definitions-only instead. Extraction is hardened against path\ntraversal and decompression bombs.\n\nDefault (nil) is ENABLED. Set to false on air-gapped deployments to\nforbid the scanner's network egress; such servers then fall back to the\ntool-definitions-only scan with no regression.","type":"boolean"},"scanner_registry_url":{"type":"string"},"tpa_active_root":{"description":"TPAActiveRoot declares which signing authority's bundles may activate\n(FR-004b): \"publisher\" (default, the keys embedded in this binary) or\n\"operator\" (TPAOperatorSigners). A bundle verified by the other root is\nrefused as authority_not_active, so whoever can write the bundle path\ncannot choose the authority.","type":"string"},"tpa_bundle_path":{"description":"TPABundlePath is the filesystem path to the tpa-db scanner-bundle.json\nthe offline TPA scanner runs (spec 086 FR-019: the signature-DB location\nMUST be configuration-driven, not hardcoded). Empty (the default) runs the\ncorpus embedded in this build.\n\nEnv override: MCPPROXY_TPA_BUNDLE_PATH. Hot-reloadable — the path is\nre-read on every config.reloaded event via\nscanner.Service.ApplySecurityConfig, so a corpus refresh needs no restart.\nA configured bundle that fails to read/parse/version-check/compile is\nREFUSED and the previously active corpus stays live (fail-closed, never\nfail-empty); the reason is logged and surfaced in the security overview's\nsignature_bundle.load_error.","type":"string"},"tpa_fetch_enabled":{"description":"TPAFetchEnabled opts in to the network fetch leg. Default false; the\nenvironment override is MCPPROXY_TPA_FETCH_ENABLED (EnvTPAFetchEnabled).","type":"boolean"},"tpa_fetch_url":{"description":"TPAFetchURL is the channel URL: a GitHub Releases \"latest\" API URL or a\ndirect bundle URL. Empty (the default) means the fetch leg is off; no URL\nis compiled into the binary.","type":"string"},"tpa_operator_baseline":{"description":"TPAOperatorBaseline seeds the operator authority's anti-downgrade\nwatermark (FR-009b): an operator-signed bundle must carry a sequence\nABOVE it (a rollback target may sit at it). It survives a data-directory\nwipe because it lives here. Absent means the operator authority has no\nanti-downgrade floor and an active operator bundle runs DEGRADED.","type":"integer"},"tpa_operator_epoch":{"description":"TPAOperatorEpoch is the operator authority's trust epoch (FR-005a).\nBumping it (after an operator key compromise) re-baselines the operator\nwatermark and retires prior-epoch pins. Absent means 0.","type":"integer"},"tpa_operator_signers":{"description":"TPAOperatorSigners lists operator Ed25519 public keys, each the standard\nbase64 encoding of the 32 raw key bytes (FR-004). Their key ids are the\nlowercase-hex SHA-256 of those bytes. Malformed or duplicate entries are\nrejected on write and dropped (with a log) on load.","items":{"type":"string"},"type":"array","uniqueItems":false},"tpa_refresh_interval":{"description":"TPARefreshInterval is the cadence of the refresh cycle (the network-free\nfile leg, then the optional fetch leg). Absent or 0 means 24h; the runtime\nclamps to at least 1h. There is no refresh-enable key: the file leg is\nidempotent and always on.","type":"string"},"tpa_stale_after_days":{"description":"TPAStaleAfterDays is the age in days after which the active bundle reads\nas stale. Absent means 30; an explicit 0 disables the stale flag and the\ndoctor stale warning.","type":"integer"}},"type":"object"},"config.SensitiveDataDetectionConfig":{"description":"Sensitive data detection settings (Spec 026)","properties":{"categories":{"additionalProperties":{"type":"boolean"},"description":"Enable/disable specific detection categories","type":"object"},"custom_patterns":{"description":"User-defined detection patterns","items":{"$ref":"#/components/schemas/config.CustomPattern"},"type":"array","uniqueItems":false},"enabled":{"description":"Enable sensitive data detection (default: true)","type":"boolean"},"entropy_threshold":{"description":"Shannon entropy threshold for high-entropy detection (default: 4.5)","type":"number"},"max_payload_size_kb":{"description":"Max size to scan before truncating (default: 1024)","type":"integer"},"scan_requests":{"description":"Scan tool call arguments (default: true)","type":"boolean"},"scan_responses":{"description":"Scan tool responses (default: true)","type":"boolean"},"sensitive_keywords":{"description":"Keywords to flag","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"config.ServerConfig":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges is the per-server intent to auto-approve tool\nchanges/additions (disabling per-server rug-pull protection). Supersedes\nskip_quarantine. MCP-2930 only ACCEPTS, persists, and migrates this flag — it\nis NOT yet consulted at runtime; auto-approval is still governed by\nSkipQuarantine until the trust-baseline behavior change (MCP-2931) migrates the\nruntime consumers onto it.\nTri-state pointer (mirrors QuarantineEnabled): nil = unset (inherit/migrate\nfrom legacy skip_quarantine), explicit true/false = honored as-is so an\nexplicit auto_approve_tool_changes:false overrides a legacy skip_quarantine:true.\nRead via IsAutoApproveToolChanges().","type":"boolean"},"command":{"type":"string"},"created":{"type":"string"},"disabled_tools":{"description":"Denylist: these tools are hidden; mutually exclusive with enabled_tools","items":{"type":"string"},"type":"array","uniqueItems":false},"enabled":{"type":"boolean"},"enabled_tools":{"description":"Allowlist: only these tools are exposed; mutually exclusive with disabled_tools","items":{"type":"string"},"type":"array","uniqueItems":false},"env":{"additionalProperties":{"type":"string"},"type":"object"},"expose_prompts":{"description":"ExposePrompts overrides whether this server's advertised MCP prompts are\naggregated into mcpproxy's prompts/list. nil (default) inherits the\ndefault-aggregate behavior (included if the server advertises\nCapabilities.Prompts); false excludes it regardless of capability.","type":"boolean"},"expose_skills":{"description":"ExposeSkills overrides whether this server's skills (MCP skills\nextension) are read when Config.EnableSkills is on. nil (default)\ninherits (included if the server supports skills); false excludes it.","type":"boolean"},"forward_headers":{"description":"ForwardHeaders lists inbound MCP-client header NAMES (never values) that\nare copied into this server's upstream tools/call requests (Spec 112).\nExact names, case-insensitive, at most 32, no wildcards. Empty forwards\nnothing. Only HTTP-based transports (http, streamable-http) forward; the\ndeny list (Authorization, Host, hop-by-hop, ...) is enforced at runtime\nregardless of what is configured here.","items":{"type":"string"},"type":"array","uniqueItems":false},"headers":{"additionalProperties":{"type":"string"},"description":"For HTTP servers","type":"object"},"health_check_interval":{"description":"Per-server discovery \u0026 health-check overrides (spec 074). Same *Duration\ntri-state as the global keys: nil = inherit the global value (or default),\npointer to 0s = disabled for this server, positive = that interval.\nHealthCheckInterval is fully wired into the per-server health loop;\nToolDiscoveryInterval is accepted/validated and round-trips for\nforward-compat, but the periodic index sweep is governed by the global\ncadence in this iteration (see spec 074 plan §C).","type":"string"},"init_timeout":{"description":"InitTimeout overrides the global init_timeout for this server's MCP\n` + "`" + `initialize` + "`" + ` handshake deadline (MCP-3322 / GH #760). *Duration tri-state:\nnil = inherit the global value (or 30s default), positive = that deadline.\nResolved by Config.ResolveInitTimeout; validated to {0} ∪ [1s, 30m]. Raise\nthis for upstreams that do legitimate first-run warmup (e.g. caching many\nchannels/users) before responding to ` + "`" + `initialize` + "`" + `.","type":"string"},"isolation":{"$ref":"#/components/schemas/config.IsolationConfig"},"launcher_wait_timeout":{"description":"LauncherWaitTimeout caps how long mcpproxy will wait for a locally-launched\nHTTP/SSE upstream's URL to become reachable after Spawn(). Only consulted\nwhen the server is configured with both Command and an HTTP/SSE URL — i.e.,\nmcpproxy starts the process AND connects via network. Stdio servers ignore\nthis field. Zero or unset → 30s default.","type":"string"},"max_concurrent_requests":{"description":"Per-server concurrency overrides — scope (c) of FR-020 (spec 093, #955).\nTri-state per setting, exactly like HealthCheckInterval: absent = inherit\nthe per-server default set (server_concurrency_defaults), explicit 0 =\ndisable that setting for this server (0 max = no per-server limiter at\nall; 0 queue_size = no pending capacity, shed immediately at the cap),\npositive = override. The global aggregate limiter is never inherited from\nhere — it applies on top, so effective concurrency is min(per-server,\nglobal). Resolved by Config.ResolveServerConcurrency.","type":"integer"},"name":{"type":"string"},"oauth":{"$ref":"#/components/schemas/config.OAuthConfig"},"protocol":{"description":"stdio, http, sse, streamable-http, auto","type":"string"},"quarantined":{"description":"Security quarantine status","type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_on_use":{"description":"Attempt reconnection when a tool call targets a disconnected server","type":"boolean"},"shared":{"description":"Server edition: shared with all users","type":"boolean"},"skip_quarantine":{"description":"SkipQuarantine is DEPRECATED (MCP-2930): use AutoApproveToolChanges instead.\nKept for back-compat parsing; on config load a legacy skip_quarantine:true is\nmigrated to auto_approve_tool_changes:true only when the new field is unset\n(see normalizeServerQuarantineFlags).","type":"boolean"},"source_registry_id":{"description":"SourceRegistryID records which registry this server was added from (empty\nfor manually-configured servers). MCP-866: surfaced in the approval /\nquarantine view so a reviewer can see a server's origin.","type":"string"},"source_registry_provenance":{"description":"SourceRegistryProvenance records the source registry's provenance at add\ntime (RegistryProvenanceOfficial / RegistryProvenanceCustom). It is purely\ninformational (MCP-1072) — surfaced so a reviewer can see a server's origin\n— and no longer gates quarantine or skip_quarantine.","type":"string"},"tool_argument_error_mode":{"description":"ToolArgumentErrorMode stores the per-upstream argument-error policy.\nEmpty and detailed retain detailed errors; redacted opts into redaction.\nUpdates omit/keep an empty value; detailed explicitly resets the policy.","type":"string"},"tool_discovery_interval":{"type":"string"},"toon_output":{"description":"ToonOutput overrides the global toon_output mode for this server's\ntools (spec 084, FR-001). Plain string, not a pointer: \"\"/absent =\ninherit the global value; \"off\"|\"adaptive\"|\"always\" = override (\"off\"\nis the explicit force-off). Resolved by Config.ResolveToonOutput.","type":"string"},"trust_mode":{"description":"TrustMode is the per-server trust tier: auto|scan|manual. Supersedes\nauto_approve_tool_changes (spec 086). An empty value is derived from the\nlegacy fields at load via normalizeServerQuarantineFlags; the single\nresolution point is EffectiveTrustMode(), which treats an empty value as\nscan (DefaultTrustMode, spec 119) and an unrecognized value as manual\n(fail closed). Read via\nEffectiveTrustMode(), never the raw string.","type":"string"},"updated":{"type":"string"},"url":{"type":"string"},"working_dir":{"description":"Working directory for stdio servers","type":"string"}},"type":"object"},"config.TLSConfig":{"description":"TLS configuration","properties":{"cert_file":{"description":"CertFile is the absolute path of an operator-provided server certificate\n(PEM, leaf first), served instead of a generated one. Needs KeyFile.","type":"string"},"certs_dir":{"description":"Directory for certificates","type":"string"},"enabled":{"description":"Enable HTTPS","type":"boolean"},"extra_sans":{"description":"ExtraSANs are DNS names and IP addresses added to the generated server\ncertificate, which is signed by the same local CA. Not used with CertFile.","items":{"type":"string"},"type":"array","uniqueItems":false},"hsts":{"description":"Enable HTTP Strict Transport Security","type":"boolean"},"key_file":{"description":"KeyFile is the absolute path of the private key for CertFile (PEM).","type":"string"},"require_client_cert":{"description":"Enable mTLS","type":"boolean"}},"type":"object"},"config.TelemetryConfig":{"description":"Telemetry settings (Spec 036)","properties":{"anonymous_id":{"description":"Auto-generated UUIDv4","type":"string"},"anonymous_id_created_at":{"description":"Spec 042 (Tier 2) additions — all default-zero, all backwards-compatible.","type":"string"},"enabled":{"description":"Default: true (opt-out)","type":"boolean"},"endpoint":{"description":"Override for testing","type":"string"},"last_reported_version":{"description":"Upgrade funnel","type":"string"},"last_startup_outcome":{"description":"success|port_conflict|db_locked|...","type":"string"},"notice_shown":{"description":"First-run notice flag","type":"boolean"}},"type":"object"},"config.TokenizerConfig":{"description":"Tokenizer configuration for token counting","properties":{"default_model":{"description":"Default model for tokenization (e.g., \"gpt-4\")","type":"string"},"enabled":{"description":"Enable token counting","type":"boolean"},"encoding":{"description":"Default encoding (e.g., \"cl100k_base\")","type":"string"}},"type":"object"},"config.TracingExporterConfig":{"description":"Tracing gates the OpenTelemetry OTLP trace exporter (MCP-32). Disabled by\ndefault.","properties":{"enabled":{"description":"Enabled turns on OTLP trace export for tool calls and upstream hops.","type":"boolean"},"endpoint":{"description":"Endpoint is the collector address as host:port (no scheme), e.g.\n\"localhost:4318\" for http or \"localhost:4317\" for grpc.","type":"string"},"protocol":{"description":"Protocol selects the OTLP transport: \"http\" or \"grpc\".","type":"string"},"sample_rate":{"description":"SampleRate is the head-based trace sampling ratio in [0,1]. Default 0.1.\nOmit the key for the 0.1 default; set it to 0 to sample nothing.","type":"number"}},"type":"object"},"config.UpdateCheckConfig":{"description":"Update-check settings (Spec 079 FR-012): config-file control of the\nbackground upgrade-awareness checker (internal/updatecheck). nil =\nenabled on the stable channel (existing default behavior). The existing\nenvironment switches keep working and WIN over these keys (FR-014):\nMCPPROXY_DISABLE_AUTO_UPDATE=true force-disables even when\nenabled=true, and MCPPROXY_ALLOW_PRERELEASE_UPDATES=true force-selects\nthe rc channel even when channel=stable.","properties":{"channel":{"description":"Channel selects which releases are offered as updates: \"stable\"\n(default; prereleases never offered) or \"rc\" (prereleases included).\nEmpty resolves to stable. Validated in ValidateDetailed.\n\nNOTE: for a RELEASED build the running binary's own version is\nauthoritative and overrides this field — a stable build is never\noffered an RC (even with channel=rc), and an RC build always tracks the\nrc channel. This field only takes effect on dev/unstamped builds. See\ninternal/updatecheck.Checker.IncludePrereleases.","type":"string"},"enabled":{"description":"Enabled gates all update checking. Tri-state: nil/absent = enabled\n(default true, matching pre-079 behavior). When false, no network\ncheck is performed and no upgrade nudge appears on any surface\n(FR-015) — /api/v1/info omits the update object entirely.","type":"boolean"}},"type":"object"},"configimport.FailedServer":{"properties":{"details":{"type":"string"},"error":{"type":"string"},"name":{"type":"string"}},"type":"object"},"configimport.ImportSummary":{"properties":{"failed":{"type":"integer"},"imported":{"type":"integer"},"skipped":{"type":"integer"},"total":{"type":"integer"}},"type":"object"},"configimport.SkippedServer":{"properties":{"name":{"type":"string"},"reason":{"description":"\"already_exists\", \"filtered_out\", \"invalid_name\", \"self_reference\"","type":"string"}},"type":"object"},"connect.ConnectResult":{"description":"The full result; its action mirrors the top-level one","properties":{"action":{"description":"\"created\", \"updated\", \"already_exists\", \"removed\", \"not_found\"","type":"string"},"backup_path":{"type":"string"},"client":{"type":"string"},"config_path":{"type":"string"},"credential":{"description":"Credential is the masked client credential the write embedded\n(` + "`" + `mcp_cli_••••` + "`" + `); the real secret is never returned (FR-024). Empty for a\nkeyless entry, a disconnect and every refusal.","type":"string"},"credential_revoke_error":{"description":"CredentialRevokeError is set when a disconnect removed the entry but\nrevoking the client credential failed. The disconnect still succeeded;\nthe credential is still active and ` + "`" + `mcpproxy client forget \u003cid\u003e` + "`" + `\nretries the revoke.","type":"string"},"credential_revoked":{"description":"CredentialRevoked names the credential that was revoked: by an undo,\nbecause the restored config no longer holds it (plan D16), or by a\ndisconnect, which cuts the client off (a later undo of that disconnect\ndoes not bring the credential back).","type":"string"},"display_path":{"description":"DisplayPath is ConfigPath with the home directory shortened to \"~\"\n(FR-037). Populated for every result whose ConfigPath is known.","type":"string"},"keyless":{"description":"Keyless is true when the entry was written with no credential.","type":"boolean"},"message":{"type":"string"},"mode":{"type":"string"},"profile":{"description":"Profile and Mode are the binding of the credential this write minted or\nkept. Profile \"\" means the built-in All servers scope.","type":"string"},"reload_hint":{"description":"ReloadHint is this client's instruction for making the write take\neffect (FR-037/FR-042), e.g. \"Restart Cursor to load MCPProxy\". Empty\nfor an unknown client.","type":"string"},"rotation":{"description":"Rotation is \"finalized\" when the write replaced an active credential's\nsecret (staged rotation, FR-021a), empty otherwise.","type":"string"},"server_name":{"type":"string"},"success":{"type":"boolean"},"token_name":{"description":"TokenName is the client credential's token name (` + "`" + `client-\u003cid\u003e` + "`" + `).","type":"string"}},"type":"object"},"contracts.APIResponse":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.ActivityDetailResponse":{"properties":{"activity":{"$ref":"#/components/schemas/contracts.ActivityRecord"}},"type":"object"},"contracts.ActivityListResponse":{"properties":{"activities":{"items":{"$ref":"#/components/schemas/contracts.ActivityRecord"},"type":"array","uniqueItems":false},"limit":{"type":"integer"},"offset":{"type":"integer"},"total":{"type":"integer"}},"type":"object"},"contracts.ActivityPerServer":{"properties":{"calls":{"description":"Calls counted per storage.CountsAsCall","type":"integer"},"errors":{"description":"Of those calls, how many failed","type":"integer"},"last_call_at":{"description":"LastCallAt is RFC3339, or \"\" if the server had no call in the period\n(PerServer only lists servers that did, so this is always set).","type":"string"},"name":{"description":"Server name","type":"string"}},"type":"object"},"contracts.ActivityRecord":{"description":"Activity is the stored row; absent on a session_start or session_end\nrow.","properties":{"agent_name":{"description":"Agent token name when auth_type is \"agent\"","type":"string"},"arguments":{"description":"Tool call arguments","type":"object"},"auth_type":{"description":"\"admin\", \"agent\", \"user\" or \"admin_user\"; empty without an auth context or on another caller's row for a scoped caller","type":"string"},"block_reason":{"description":"Typed cause of a profile policy refusal","type":"string"},"client_id":{"description":"Client id from the client-credential binding","type":"string"},"client_name":{"description":"Self-reported clientInfo.name (advisory)","type":"string"},"detection_types":{"description":"List of detection types found","items":{"type":"string"},"type":"array","uniqueItems":false},"duration_ms":{"description":"Execution duration in milliseconds","type":"integer"},"error_class":{"description":"Call-error taxonomy (Spec 113-c FR-045): what failed and whose fault it\nis. Absent on success and on records written before Spec 113.","type":"string"},"error_message":{"description":"Error details if status is \"error\"","type":"string"},"fault_domain":{"description":"upstream|proxy|client","type":"string"},"has_sensitive_data":{"description":"Sensitive data detection fields (Spec 026)","type":"boolean"},"id":{"description":"Unique identifier (ULID format)","type":"string"},"max_severity":{"description":"Highest severity level detected (critical, high, medium, low)","type":"string"},"metadata":{"description":"Additional context-specific data","type":"object"},"parent_id":{"description":"Correlation id of the parent call (the code_execution whose sandbox issued this sub-call)","type":"string"},"profile":{"description":"Scope attribution (Spec 108 FR-029): the profile, client and token in\neffect when the call ran. Stamped at write time, never rewritten. For a\nscoped (non-admin) caller the profile/profile_source/client_id/token_name\nof a row it did not make are blanked (binding disclosure is admin-only);\nclient_name is self-reported and stays. Absent on records written before\nSpec 108 and on records with no MCP/REST request context.","type":"string"},"profile_source":{"description":"pin|binding|url|session|anonymous|none","type":"string"},"request_bytes":{"description":"Byte sizes measured pre-truncation, mirroring storage.ActivityRecord\n(Spec 069 A1). They are the only cost signal a bodies-off export carries:\nwith payloads suppressed there is no text left to measure, so a consumer\naccounting for a record it cannot read has nothing else to go on. They are\nbyte LENGTHS, not token counts — the basis for an explicit estimate, never\na measured figure (spec 103, contracts/replay-input.md).\n\nZero means UNKNOWN, not free: legacy records predate the measurement and\ncode-execution sub-calls record both as zero. Hence omitempty — an absent\nkey tells a consumer to fall to exclusion accounting, whereas a present\nzero would read as a costless call and silently understate the workload.","type":"integer"},"request_id":{"description":"HTTP request ID for correlation","type":"string"},"response":{"description":"Tool response (potentially truncated)","type":"string"},"response_bytes":{"description":"Raw upstream response size in bytes before truncation","type":"integer"},"response_truncated":{"description":"True if response was truncated","type":"boolean"},"server_name":{"description":"Name of upstream MCP server","type":"string"},"session_id":{"description":"MCP transport session ID (regenerated on every reconnect)","type":"string"},"source":{"$ref":"#/components/schemas/contracts.ActivitySource"},"status":{"description":"Result status: \"success\", \"error\", \"blocked\", \"rejected\"","type":"string"},"timestamp":{"description":"When activity occurred","type":"string"},"token_name":{"description":"Agent/client token name","type":"string"},"tool_name":{"description":"Name of tool called","type":"string"},"type":{"$ref":"#/components/schemas/contracts.ActivityType"},"upstream_http_status":{"description":"Upstream HTTP status when known","type":"integer"},"work_session_id":{"description":"Spec 082: one client, one project, across reconnects","type":"string"}},"type":"object"},"contracts.ActivityRetentionReport":{"description":"ActivityRetention (Spec 124 FR-035) reports whether the activity caps\nhold the whole work-session retention window. Administrators only.","properties":{"cause":{"description":"Cause is age_cap, record_cap or size_cap.","type":"string"},"observed_at":{"description":"ObservedAt is when the shortfall was last observed.","type":"string"},"oldest_complete_session_at":{"description":"OldestCompleteSessionAt is the start of the oldest session that still\nhas all of its rows: complete history reaches back to here.","type":"string"},"raise":{"description":"Raise names the settings to raise for the cause.","items":{"type":"string"},"type":"array","uniqueItems":false},"shortfall":{"description":"Shortfall is true when a work session inside the window lost rows\nbecause a cap was reached, and a full window has not passed since.","type":"boolean"},"window_days":{"description":"WindowDays is the work-session retention window.","type":"integer"}},"type":"object"},"contracts.ActivitySource":{"description":"How activity was triggered: \"mcp\", \"cli\", \"api\"","type":"string","x-enum-varnames":["ActivitySourceMCP","ActivitySourceCLI","ActivitySourceAPI"]},"contracts.ActivitySummaryResponse":{"properties":{"blocked_count":{"description":"Count of blocked activities","type":"integer"},"call_count":{"description":"CallCount is how many of those records are CALLS THE USER MADE, as\ndefined once in storage.CountsAsCall and shared with the usage aggregate\nbehind the Usage tab (audit finding F1, #1046). TotalCount answers \"how\nmany rows does the Activity Log have\"; CallCount answers \"how many calls\nwere there\". They are different questions — quarantine auto-approvals,\nsystem start, security scans and management chatter are events, not calls\n— and printing either one under the other's label is how the same instance\ncame to report 51 calls on one screen and 19 on another.","type":"integer"},"call_error_count":{"description":"CallErrorCount is the failures within CallCount, so an error RATE computed\nfrom this response has one denominator. It is not ErrorCount: a policy\nblock is a failed call but carries status \"blocked\", and a shed call is an\nerror in neither sense because it never ran.","type":"integer"},"end_time":{"description":"End of the period (RFC3339)","type":"string"},"error_count":{"description":"Count of error activities","type":"integer"},"other_count":{"description":"OtherCount is every record whose status is outside the four-value\nvocabulary above, so that\n\n\tsuccess + error + blocked + rejected + other == total\n\nholds by construction. The status field is a CLOSED vocabulary for tool\ncalls, but the activity log is wider than tool calls: a quarantine change\nstores its ACTION there (\"approved\", \"auto_approved\"), a policy decision\nstores its DECISION (\"allow\"). Those rows were counted in the total and in\nnone of the four buckets, so the Activity Log's own status tiles summed to\nless than the denominator printed beside them — 15+4+0+0 under a \"42\"\n(audit finding F2, #1046). The residual now has a name and a tile.","type":"integer"},"per_server":{"description":"PerServer covers EVERY server with at least one call in the period\n(unlike TopServers, which is capped at 5 and carries no error counts).\nSpec 109 FR-013: the server-card stats line and the macOS Servers rows\nread this — one ` + "`" + `GET /activity/summary` + "`" + ` response per page load — rather\nthan issuing a per-server activity query each. Computed in the same\ncounting pass as the totals above, from the same CountsAsCall/\nIsManagementBuiltin definitions TopServers already uses.","items":{"$ref":"#/components/schemas/contracts.ActivityPerServer"},"type":"array","uniqueItems":false},"period":{"description":"Time period (1h, 24h, 7d, 30d)","type":"string"},"rejected_count":{"description":"RejectedCount is the number of calls shed by a concurrency limiter, or\nrefused because an agent token was over its call budget, before they\nreached an upstream (spec 093, issue #1699). Counted separately from\nerrors: it is proxy backpressure, not an upstream fault, and it is the\nsignal an operator right-sizes max_concurrent_requests and the rate\nlimits against.","type":"integer"},"start_time":{"description":"Start of the period (RFC3339)","type":"string"},"success_count":{"description":"Count of successful activities","type":"integer"},"top_servers":{"description":"Top servers by activity count","items":{"$ref":"#/components/schemas/contracts.ActivityTopServer"},"type":"array","uniqueItems":false},"top_tools":{"description":"Top tools by activity count","items":{"$ref":"#/components/schemas/contracts.ActivityTopTool"},"type":"array","uniqueItems":false},"total_count":{"description":"Total activity count","type":"integer"}},"type":"object"},"contracts.ActivityTopServer":{"properties":{"count":{"description":"Activity count","type":"integer"},"name":{"description":"Server name","type":"string"}},"type":"object"},"contracts.ActivityTopTool":{"properties":{"count":{"description":"Activity count","type":"integer"},"server":{"description":"Server name","type":"string"},"tool":{"description":"Tool name","type":"string"}},"type":"object"},"contracts.ActivityType":{"description":"Type of activity","type":"string","x-enum-varnames":["ActivityTypeToolCall","ActivityTypePolicyDecision","ActivityTypeQuarantineChange","ActivityTypeServerChange"]},"contracts.AddFromRegistryRequest":{"properties":{"enabled":{"description":"defaults to true when nil","type":"boolean"},"env":{"additionalProperties":{"type":"string"},"description":"overrides + required-input values","type":"object"},"name":{"description":"optional name override","type":"string"}},"type":"object"},"contracts.AddRegistrySourceRequest":{"properties":{"id":{"description":"derived from the host when empty","type":"string"},"name":{"description":"defaults to the id","type":"string"},"protocol":{"description":"defaults to modelcontextprotocol/registry","type":"string"},"url":{"description":"required https registry URL","type":"string"}},"type":"object"},"contracts.AttentionFix":{"properties":{"label":{"type":"string"},"target":{"type":"string"},"verb":{"type":"string"}},"type":"object"},"contracts.AttentionItem":{"properties":{"detail":{"type":"string"},"fix":{"$ref":"#/components/schemas/contracts.AttentionFix"},"id":{"description":"kind:type:subject[:state]","type":"string"},"kind":{"type":"string"},"rank":{"type":"integer"},"since":{"type":"string"},"subject":{"$ref":"#/components/schemas/contracts.AttentionSubject"},"summary":{"type":"string"}},"type":"object"},"contracts.AttentionSubject":{"properties":{"id":{"type":"string"},"name":{"type":"string"},"type":{"description":"server|tool|client|setting","type":"string"}},"type":"object"},"contracts.ConfigApplyResult":{"properties":{"applied_immediately":{"type":"boolean"},"changed_fields":{"items":{"type":"string"},"type":"array","uniqueItems":false},"requires_restart":{"type":"boolean"},"restart_reason":{"type":"string"},"success":{"type":"boolean"},"validation_errors":{"items":{"$ref":"#/components/schemas/contracts.ValidationError"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.DCRStatus":{"properties":{"attempted":{"type":"boolean"},"error":{"type":"string"},"status_code":{"type":"integer"},"success":{"type":"boolean"}},"type":"object"},"contracts.DeepScanDescriptor":{"description":"DeepScan reports the opt-in \"deep scan\" layer status (Spec 077 US3),\nSEPARATELY from the baseline verdict above. Always emitted on a computed\nsummary — when deep scan is off (the default) it reports enabled=false\nplus any enabled-but-skipped Docker scanners. It never influences Status.","properties":{"available":{"type":"boolean"},"enabled":{"type":"boolean"},"ran":{"type":"boolean"},"scanners_failed":{"items":{"$ref":"#/components/schemas/contracts.DeepScanScannerFailure"},"type":"array","uniqueItems":false},"skipped_scanners":{"description":"SkippedScanners lists Docker scanners the user enabled that are skipped\nbecause security.deep_scan.enabled is false (informational).","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.DeepScanScannerFailure":{"properties":{"id":{"type":"string"},"reason":{"type":"string"}},"type":"object"},"contracts.DeprecatedConfigWarning":{"properties":{"field":{"type":"string"},"message":{"type":"string"},"replacement":{"type":"string"}},"type":"object"},"contracts.Diagnostic":{"description":"Spec 044 — structured diagnostic error and stable error code. Both\nare populated when the server is in a failed state and the error\nhas been classified by internal/diagnostics. Healthy servers omit\nthese fields.","properties":{"cause":{"type":"string"},"code":{"type":"string"},"detected_at":{"type":"string"},"docs_url":{"type":"string"},"fix_steps":{"items":{"$ref":"#/components/schemas/contracts.DiagnosticFixStep"},"type":"array","uniqueItems":false},"severity":{"type":"string"},"user_message":{"type":"string"}},"type":"object"},"contracts.DiagnosticFixStep":{"properties":{"command":{"type":"string"},"destructive":{"type":"boolean"},"fixer_key":{"type":"string"},"label":{"type":"string"},"type":{"type":"string"},"url":{"type":"string"}},"type":"object"},"contracts.Diagnostics":{"properties":{"activity_retention":{"$ref":"#/components/schemas/contracts.ActivityRetentionReport"},"deprecated_configs":{"description":"Deprecated config fields found","items":{"$ref":"#/components/schemas/contracts.DeprecatedConfigWarning"},"type":"array","uniqueItems":false},"docker_status":{"$ref":"#/components/schemas/contracts.DockerStatus"},"missing_secrets":{"description":"Renamed to avoid conflict","items":{"$ref":"#/components/schemas/contracts.MissingSecretInfo"},"type":"array","uniqueItems":false},"oauth_issues":{"description":"OAuth parameter mismatches","items":{"$ref":"#/components/schemas/contracts.OAuthIssue"},"type":"array","uniqueItems":false},"oauth_required":{"items":{"$ref":"#/components/schemas/contracts.OAuthRequirement"},"type":"array","uniqueItems":false},"oauth_token_storage":{"$ref":"#/components/schemas/contracts.OAuthTokenStorageReport"},"runtime_warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false},"timestamp":{"type":"string"},"total_issues":{"type":"integer"},"upstream_errors":{"items":{"$ref":"#/components/schemas/contracts.UpstreamError"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.DockerStatus":{"properties":{"available":{"type":"boolean"},"error":{"type":"string"},"version":{"type":"string"}},"type":"object"},"contracts.EditRegistrySourceRequest":{"properties":{"name":{"description":"new display name","type":"string"},"servers_url":{"description":"explicit servers-collection URL","type":"string"},"url":{"description":"new base/servers https URL","type":"string"}},"type":"object"},"contracts.ErrorResponse":{"properties":{"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.FindingCounts":{"properties":{"dangerous":{"description":"Tool poisoning, active prompt injection","type":"integer"},"info":{"description":"Low-severity CVEs, informational","type":"integer"},"total":{"type":"integer"},"warning":{"description":"Rug pull, supply chain CVEs with exploits","type":"integer"}},"type":"object"},"contracts.GetConfigResponse":{"properties":{"config":{"description":"The configuration object","type":"object"},"config_path":{"description":"Path to config file","type":"string"}},"type":"object"},"contracts.GetRegistriesResponse":{"properties":{"registries":{"items":{"$ref":"#/components/schemas/contracts.Registry"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GetServerLogsResponse":{"properties":{"count":{"type":"integer"},"logs":{"items":{"$ref":"#/components/schemas/contracts.LogEntry"},"type":"array","uniqueItems":false},"server_name":{"type":"string"}},"type":"object"},"contracts.GetServerToolCallsResponse":{"properties":{"server_name":{"type":"string"},"tool_calls":{"items":{"$ref":"#/components/schemas/contracts.ToolCallRecord"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GetServerToolsResponse":{"properties":{"count":{"type":"integer"},"incarnation":{"description":"Incarnation is the committed incarnation of the server the tools were\nread for (Spec 116 FR-017), captured before they were fetched; omitted\nwhen unknown.","type":"integer"},"server_name":{"type":"string"},"tools":{"items":{"$ref":"#/components/schemas/contracts.Tool"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.GetServersResponse":{"properties":{"servers":{"items":{"$ref":"#/components/schemas/contracts.Server"},"type":"array","uniqueItems":false},"stats":{"$ref":"#/components/schemas/contracts.ServerStats"}},"type":"object"},"contracts.GetSessionDetailResponse":{"properties":{"session":{"$ref":"#/components/schemas/contracts.MCPSession"}},"type":"object"},"contracts.GetSessionsResponse":{"properties":{"limit":{"type":"integer"},"offset":{"type":"integer"},"sessions":{"items":{"$ref":"#/components/schemas/contracts.MCPSession"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GetToolCallDetailResponse":{"properties":{"tool_call":{"$ref":"#/components/schemas/contracts.ToolCallRecord"}},"type":"object"},"contracts.GetToolCallsResponse":{"properties":{"limit":{"type":"integer"},"offset":{"type":"integer"},"tool_calls":{"items":{"$ref":"#/components/schemas/contracts.ToolCallRecord"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GlobalToolsResponse":{"properties":{"counts":{"$ref":"#/components/schemas/contracts.ViewAsCounts"},"failed_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"partial":{"type":"boolean"},"stats":{"$ref":"#/components/schemas/contracts.GlobalToolsStats"},"tools":{"items":{"$ref":"#/components/schemas/contracts.Tool"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.GlobalToolsStats":{"properties":{"disabled":{"type":"integer"},"enabled":{"type":"integer"},"pending_approval":{"type":"integer"},"total":{"type":"integer"}},"type":"object"},"contracts.HealthStatus":{"description":"Unified health status calculated by the backend","properties":{"action":{"description":"Action is the suggested fix action: \"login\", \"restart\", \"enable\", \"approve\", \"view_logs\", \"set_secret\", \"configure\", \"edit_url\", or \"\" (none)\nInvariant: Action always equals Actions[0], or \"\" when Actions is empty.","type":"string"},"actions":{"description":"Actions lists every applicable next step in priority order (FR-012):\nlogin \u003e set_secret \u003e configure \u003e edit_url \u003e approve \u003e restart \u003e\nview_logs \u003e enable. Always non-nil (empty slice, never null).","items":{"type":"string"},"type":"array","uniqueItems":false},"admin_state":{"description":"AdminState indicates the admin state: \"enabled\", \"disabled\", or \"quarantined\"","type":"string"},"detail":{"description":"Detail is an optional longer explanation of the status","type":"string"},"level":{"description":"Level indicates the health level: \"healthy\", \"degraded\", or \"unhealthy\"","type":"string"},"status":{"description":"Status is the ONE status vocabulary rendered as text on every surface\n(Web UI, macOS, tray, CLI) — Spec 109 FR-010/FR-011. Values: \"ready\",\n\"connecting\", \"sign_in_required\", \"needs_review\", \"needs_secret\",\n\"needs_config\", \"error\", \"disabled\". Unlike Level (a severity signal for\nbadge/tray coloring only), no renderer may print Level as text.","type":"string"},"summary":{"description":"Summary is a human-readable status message (e.g., \"Connected (5 tools)\")","type":"string"},"usable":{"description":"Usable reports whether the server can currently serve tool calls. True\nonly when Status == \"ready\".","type":"boolean"}},"type":"object"},"contracts.InfoEndpoints":{"description":"Available API endpoints","properties":{"http":{"description":"HTTP endpoint address (e.g., \"127.0.0.1:8080\")","type":"string"},"socket":{"description":"Unix socket path (empty if disabled)","type":"string"}},"type":"object"},"contracts.InfoResponse":{"properties":{"endpoints":{"$ref":"#/components/schemas/contracts.InfoEndpoints"},"launched_by":{"description":"LaunchedBy is the durable launch provenance of the running core (Spec\n092 FR-001a): \"tray\" when a tray spawned it, \"installer\" when the macOS\nPKG postinstall did, \"\" when user-launched or unknown. Always present\n(possibly empty) so a tray can distinguish \"old core, not mine\" from\n\"old core I may supersede\".","type":"string"},"listen_addr":{"description":"Listen address (e.g., \"127.0.0.1:8080\")","type":"string"},"pid":{"description":"PID is the operating-system process id of the running core (Spec 092\nFR-002). A tray that merely ATTACHED to a core holds no Process handle\nfor it, so without this there is no mechanism at all to stop a stale\ncore — the consent action would have nothing to act on and could only\nprint instructions. Paired with LaunchedBy it is what lets a newer tray\nsupersede a core an older tray started.","type":"integer"},"update":{"$ref":"#/components/schemas/contracts.UpdateInfo"},"update_policy":{"$ref":"#/components/schemas/contracts.UpdatePolicy"},"version":{"description":"Current MCPProxy version","type":"string"},"web_ui_url":{"description":"URL to access the web control panel","type":"string"}},"type":"object"},"contracts.IsolationConfig":{"properties":{"cpu_limit":{"type":"string"},"enabled":{"description":"Enabled is the EFFECTIVE isolation state for this server: whether its\nprocess is actually CONFINED, after the global setting, the per-server\noverride, the structural gates and the host's capabilities. It is NOT the\nraw per-server override — read EnabledOverride for that (GH #1142).\n\nREAD-ONLY. The write surfaces reject an ` + "`" + `enabled` + "`" + ` key precisely because\nit is derived: echoing it back would convert \"inherits the global\nsetting\" into a permanent explicit override. Write EnabledOverride.\n\nIt stays a non-pointer bool that is always present on the wire: the macOS\ntray decodes it as a non-optional Swift Bool, so omitting or nulling the\nkey would fail Codable for the whole server payload. Older clients that\nread this field now simply get a true answer.","type":"boolean"},"enabled_override":{"description":"EnabledOverride is the RAW per-server ` + "`" + `isolation.enabled` + "`" + ` override, as\npersisted. Absent means \"inherit the global setting\" — which is a\ndistinct state from an explicit false, and the distinction the reporting\nbug used to destroy.","type":"boolean"},"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"memory_limit":{"type":"string"},"mode_override":{"description":"ModeOverride is the RAW per-server ` + "`" + `isolation.mode` + "`" + ` override\n(\"docker\" | \"sandbox\" | \"none\"). Absent means \"inherit\".","type":"string"},"network_mode":{"type":"string"},"timeout":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"contracts.IsolationDefaults":{"description":"IsolationDefaults exposes the resolved baseline values that\nwould apply when no per-server override is set. Populated on\nlist/get responses; never consumed on PATCH requests.","properties":{"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"network_mode":{"type":"string"},"runtime_type":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"contracts.IsolationEffective":{"description":"IsolationEffective exposes the resolved isolation state (and the rule\nthat decided it) so clients can distinguish \"inherits global\" from an\nexplicit per-server choice. Read-only; never consumed on PATCH.","properties":{"global_mode":{"description":"GlobalMode is what \"inherit\" resolves to right now.","type":"string"},"inherited":{"description":"Inherited is true when the server sets neither ` + "`" + `isolation.enabled` + "`" + ` nor\n` + "`" + `isolation.mode` + "`" + `, so its state tracks the global setting.","type":"boolean"},"isolated":{"description":"Isolated reports whether the process is actually CONFINED. It is NOT\nsimply Mode != \"none\": \"sandbox\" on a host that cannot enforce Landlock\n(any non-Linux OS, or a kernel without the LSM) runs the server\nunconfined, and Source then says \"sandbox-unavailable\" (GH #1142).","type":"boolean"},"mode":{"description":"Mode is the effective isolation mode: \"docker\" | \"sandbox\" | \"none\" —\nexactly what the spawn path branches on.","type":"string"},"source":{"description":"Source names the deciding rule: \"global\", \"server-mode\",\n\"server-opt-out\", \"server-opt-in-ignored\", \"not-stdio\",\n\"already-docker\", \"sandbox-unavailable\" or \"unsupported-mode\".\nTreat an unrecognized value as \"global\".","type":"string"}},"type":"object"},"contracts.LogEntry":{"properties":{"fields":{"type":"object"},"level":{"type":"string"},"message":{"type":"string"},"server":{"type":"string"},"timestamp":{"type":"string"}},"type":"object"},"contracts.MCPSession":{"properties":{"client_id":{"description":"Scope attribution (Spec 108 FR-033). ClientID and TokenName are the\ncredential the session initialized with; Profile and ProfileSource are\nthe session's latest effective resolution. Empty on legacy sessions.","type":"string"},"client_name":{"type":"string"},"client_version":{"type":"string"},"end_time":{"type":"string"},"experimental":{"items":{"type":"string"},"type":"array","uniqueItems":false},"has_roots":{"description":"MCP Client Capabilities","type":"boolean"},"has_sampling":{"type":"boolean"},"id":{"type":"string"},"last_activity":{"type":"string"},"profile":{"type":"string"},"profile_source":{"type":"string"},"start_time":{"type":"string"},"status":{"type":"string"},"token_name":{"type":"string"},"tool_call_count":{"type":"integer"},"total_tokens":{"type":"integer"},"work_session_id":{"type":"string"},"workspace_name":{"description":"Workspace / work session (Spec 082). WorkspaceName is the project's\nbasename — the full local path is never exposed. WorkSessionID groups the\nreconnects that make up one stretch of user work.","type":"string"}},"type":"object"},"contracts.MetadataStatus":{"properties":{"authorization_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"error":{"type":"string"},"found":{"type":"boolean"},"url_checked":{"type":"string"}},"type":"object"},"contracts.MissingSecretInfo":{"properties":{"secret_name":{"type":"string"},"used_by":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.NPMPackageInfo":{"properties":{"exists":{"type":"boolean"},"install_cmd":{"type":"string"}},"type":"object"},"contracts.OAuthConfig":{"properties":{"auth_server_metadata_url":{"type":"string"},"auth_url":{"type":"string"},"authorization_endpoint":{"description":"Spec 113-b operator overrides of OAuth discovery (https-or-loopback URLs,\nnever credentials). Empty means \"use discovery\".","type":"string"},"client_id":{"type":"string"},"extra_params":{"additionalProperties":{"type":"string"},"type":"object"},"pkce_enabled":{"type":"boolean"},"redirect_port":{"type":"integer"},"refresh_replay_enabled":{"type":"boolean"},"registration_endpoint":{"type":"string"},"scopes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"token_endpoint":{"type":"string"},"token_expires_at":{"description":"When the OAuth token expires","type":"string"},"token_url":{"type":"string"},"token_valid":{"description":"Whether token is currently valid","type":"boolean"}},"type":"object"},"contracts.OAuthErrorDetails":{"description":"Structured discovery/failure details","properties":{"authorization_server_metadata":{"$ref":"#/components/schemas/contracts.MetadataStatus"},"dcr_status":{"$ref":"#/components/schemas/contracts.DCRStatus"},"protected_resource_metadata":{"$ref":"#/components/schemas/contracts.MetadataStatus"},"server_url":{"type":"string"}},"type":"object"},"contracts.OAuthFlowError":{"properties":{"correlation_id":{"description":"Flow tracking ID for log correlation","type":"string"},"debug_hint":{"description":"CLI command for log lookup","type":"string"},"details":{"$ref":"#/components/schemas/contracts.OAuthErrorDetails"},"error_code":{"description":"Machine-readable error code (e.g., OAUTH_NO_METADATA)","type":"string"},"error_type":{"description":"Category of OAuth runtime failure","type":"string"},"message":{"description":"Human-readable error description","type":"string"},"request_id":{"description":"HTTP request ID (from PR #237)","type":"string"},"server_name":{"description":"Server that failed OAuth","type":"string"},"success":{"description":"Always false","type":"boolean"},"suggestion":{"description":"Actionable remediation hint","type":"string"}},"type":"object"},"contracts.OAuthIssue":{"properties":{"documentation_url":{"type":"string"},"error":{"type":"string"},"issue":{"type":"string"},"missing_params":{"items":{"type":"string"},"type":"array","uniqueItems":false},"resolution":{"type":"string"},"server_name":{"type":"string"}},"type":"object"},"contracts.OAuthRequirement":{"properties":{"expires_at":{"type":"string"},"message":{"type":"string"},"server_name":{"type":"string"},"state":{"type":"string"}},"type":"object"},"contracts.OAuthStartResponse":{"properties":{"auth_url":{"description":"Authorization URL (always included for manual use)","type":"string"},"browser_error":{"description":"Error message if browser launch failed","type":"string"},"browser_opened":{"description":"Whether browser launch succeeded","type":"boolean"},"correlation_id":{"description":"UUID for tracking this flow","type":"string"},"message":{"description":"Human-readable status message","type":"string"},"server_name":{"description":"Name of the server being authenticated","type":"string"},"success":{"description":"Always true for successful start","type":"boolean"}},"type":"object"},"contracts.OAuthTokenStorageReport":{"description":"OAuthTokenStorage (Spec 123 FR-030) reports the state of the stored\nupstream OAuth rows: encryption on or off, the public key id, the row\ncounts by state, the undecryptable servers and the compaction advice.\nIt never carries key material or the key reference.","properties":{"compaction_advised":{"description":"CompactionAdvised mirrors the compaction marker: freed pages may still\nhold old plaintext until ` + "`" + `mcpproxy db compact --keep-backup=false` + "`" + `.","type":"boolean"},"encryption_enabled":{"description":"EncryptionEnabled is true when an encryption key is configured.","type":"boolean"},"key_id":{"description":"KeyID is the public, non-secret id of the configured key (administrator only).","type":"string"},"key_source_in_data_dir":{"description":"KeySourceInDataDir is true when the key file lies inside the data directory.","type":"boolean"},"key_source_kind":{"description":"KeySourceKind is how the key was obtained: literal, env, env_file,\nref_file, ref_env or ref_keyring (administrator only).","type":"string"},"plaintext":{"description":"Plaintext counts valid JSON rows; Sealed counts envelopes the configured\nkey opens; Undecryptable counts everything else.","type":"integer"},"sealed":{"type":"integer"},"servers":{"description":"Servers lists the undecryptable rows by server.","items":{"$ref":"#/components/schemas/contracts.OAuthTokenStorageServer"},"type":"array","uniqueItems":false},"undecryptable":{"type":"integer"},"undecryptable_by_reason":{"$ref":"#/components/schemas/contracts.OAuthTokenUndecryptableByReason"},"warnings":{"description":"Warnings are stable codes: literal_key, key_file_in_data_dir,\nplaintext_rows_with_key, compaction_advised, backup_file_present\n(administrator only).","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.OAuthTokenStorageServer":{"properties":{"bucket_key":{"type":"string"},"reason":{"type":"string"},"row_key_id":{"description":"RowKeyID is the key id in the row's envelope (administrator only).","type":"string"},"server":{"type":"string"}},"type":"object"},"contracts.OAuthTokenUndecryptableByReason":{"description":"UndecryptableByReason breaks Undecryptable down by reason.","properties":{"auth_failed":{"type":"integer"},"key_mismatch":{"type":"integer"},"malformed":{"type":"integer"},"no_key":{"type":"integer"},"unsupported_version":{"type":"integer"}},"type":"object"},"contracts.PreflightPolicy":{"properties":{"exclude_destructive":{"type":"boolean"},"exclude_open_world":{"type":"boolean"},"read_only_only":{"type":"boolean"}},"type":"object"},"contracts.PreflightReason":{"type":"string","x-enum-varnames":["PreflightReasonServerInitializing","PreflightReasonServerUnhealthy","PreflightReasonServerDisabled","PreflightReasonServerQuarantined","PreflightReasonToolPendingApproval","PreflightReasonToolChanged","PreflightReasonToolBlockedByUser","PreflightReasonOAuthRequired","PreflightReasonHashMismatch","PreflightReasonServerNotInScope","PreflightReasonToolDeniedByConfig","PreflightReasonMissingAnnotation","PreflightReasonPolicyFiltered","PreflightReasonNotFound","PreflightReasonServerNotConfigured","PreflightReasonToolBlockedByProfile","PreflightReasonTokenPermissionDenied"]},"contracts.PreflightRequest":{"properties":{"policy":{"$ref":"#/components/schemas/contracts.PreflightPolicy"},"profile":{"description":"Profile evaluates under a named profile's server scope and tool policy;\nit can only narrow a credential's own pin. Unknown: 400.","type":"string"},"tools":{"description":"Tools is 1..100 entries BEFORE dedup; duplicates are collapsed, and\nduplicate ids carrying different pins are a validation error.","items":{"$ref":"#/components/schemas/contracts.PreflightToolRef"},"type":"array","uniqueItems":false},"wait_ms":{"description":"WaitMS polls local state for up to this many milliseconds (cap 10000)\nwhile every failure is retryable-class.","type":"integer"}},"type":"object"},"contracts.PreflightResponse":{"properties":{"checked_at":{"type":"string"},"tools":{"description":"Tools are ordered by first occurrence of each unique id in the request.","items":{"$ref":"#/components/schemas/contracts.PreflightToolResult"},"type":"array","uniqueItems":false},"verdict":{"$ref":"#/components/schemas/contracts.PreflightVerdict"},"waited_ms":{"description":"WaitedMS is present when wait_ms was requested (0 when the wait\nsemaphore was exhausted and the request resolved immediately).","type":"integer"}},"type":"object"},"contracts.PreflightStatus":{"type":"string","x-enum-varnames":["PreflightStatusReady","PreflightStatusUnavailable"]},"contracts.PreflightToolRef":{"properties":{"id":{"description":"ID is a canonical \"\u003cserver\u003e:\u003ctool\u003e\" id. A malformed id is answered with a\nper-ID not_found carrying a format hint, never a request-level error.","type":"string"},"pin_hash":{"description":"PinHash is \"sha256/v{N}:{hex}\" — the schema version is embedded so a\nproxy-side hash-algorithm bump is distinguishable from upstream drift.","type":"string"}},"type":"object"},"contracts.PreflightToolResult":{"properties":{"action":{"type":"string"},"detail":{"type":"string"},"did_you_mean":{"description":"DidYouMean carries up to 3 nearest caller-visible ids on not_found. It\nnever crosses a scope boundary and never names a quarantined server's\ntools.","items":{"type":"string"},"type":"array","uniqueItems":false},"hash":{"description":"Hash is the tool's current pin (\"sha256/v{N}:{hex}\") — operator tier,\nready results only. Never disclosed to an agent token.","type":"string"},"id":{"type":"string"},"reason":{"$ref":"#/components/schemas/contracts.PreflightReason"},"remediation":{"type":"string"},"retryable":{"type":"boolean"},"status":{"$ref":"#/components/schemas/contracts.PreflightStatus"}},"type":"object"},"contracts.PreflightVerdict":{"type":"string","x-enum-varnames":["PreflightVerdictReady","PreflightVerdictDegradedRetryable","PreflightVerdictBlocked","PreflightVerdictUnknownIDs"]},"contracts.QuarantineStats":{"description":"Tool quarantine metrics for this server","properties":{"blocked_count":{"description":"Number of disabled (blocked) tools","type":"integer"},"changed_count":{"description":"Number of tools whose description/schema changed since approval","type":"integer"},"pending_count":{"description":"Number of newly discovered tools awaiting approval","type":"integer"}},"type":"object"},"contracts.RefreshRegistryResponse":{"properties":{"cleared":{"description":"number of cached entries dropped","type":"integer"},"registry_id":{"type":"string"}},"type":"object"},"contracts.Registry":{"properties":{"count":{"description":"number or string","type":"string"},"description":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"},"protocol":{"type":"string"},"provenance":{"description":"Provenance is the trust tag (MCP-866): \"official/trusted\" for built-in\ndefaults, \"custom/unverified\" for user-added registries.","type":"string"},"servers_url":{"type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"trusted":{"description":"Trusted indicates whether this is an official, shipped-by-default\nregistry. Trust is derived from membership in the default set, never\nfrom self-assertion in config.","type":"boolean"},"url":{"type":"string"}},"type":"object"},"contracts.RegistryCacheInfo":{"properties":{"age_seconds":{"type":"number"},"stale":{"type":"boolean"}},"type":"object"},"contracts.RegistryUnavailable":{"properties":{"reason":{"type":"string"}},"type":"object"},"contracts.ReplayToolCallRequest":{"properties":{"arguments":{"description":"Modified arguments for replay","type":"object"}},"type":"object"},"contracts.ReplayToolCallResponse":{"properties":{"error":{"description":"Error if replay failed","type":"string"},"new_call_id":{"description":"ID of the newly created call","type":"string"},"new_tool_call":{"$ref":"#/components/schemas/contracts.ToolCallRecord"},"replayed_from":{"description":"Original call ID","type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.RepositoryInfo":{"description":"Detected package info","properties":{"npm":{"$ref":"#/components/schemas/contracts.NPMPackageInfo"}},"type":"object"},"contracts.RepositoryServer":{"properties":{"connect_url":{"description":"Alternative connection URL","type":"string"},"created_at":{"type":"string"},"description":{"type":"string"},"id":{"type":"string"},"install_cmd":{"description":"Installation command","type":"string"},"name":{"type":"string"},"registry":{"description":"Which registry this came from","type":"string"},"repository_info":{"$ref":"#/components/schemas/contracts.RepositoryInfo"},"source_code_url":{"description":"Source repository URL","type":"string"},"updated_at":{"type":"string"},"url":{"description":"MCP endpoint for remote servers only","type":"string"}},"type":"object"},"contracts.SearchRegistryServersResponse":{"properties":{"cache":{"$ref":"#/components/schemas/contracts.RegistryCacheInfo"},"query":{"type":"string"},"registry_id":{"type":"string"},"servers":{"items":{"$ref":"#/components/schemas/contracts.RepositoryServer"},"type":"array","uniqueItems":false},"tag":{"type":"string"},"total":{"type":"integer"},"unavailable":{"$ref":"#/components/schemas/contracts.RegistryUnavailable"}},"type":"object"},"contracts.SearchResult":{"properties":{"matches":{"type":"integer"},"score":{"type":"number"},"snippet":{"type":"string"},"tool":{"$ref":"#/components/schemas/contracts.Tool"}},"type":"object"},"contracts.SearchToolsResponse":{"properties":{"query":{"type":"string"},"results":{"items":{"$ref":"#/components/schemas/contracts.SearchResult"},"type":"array","uniqueItems":false},"took":{"type":"string"},"total":{"type":"integer"}},"type":"object"},"contracts.SecurityScanSummary":{"description":"Latest security scan results summary","properties":{"deep_scan":{"$ref":"#/components/schemas/contracts.DeepScanDescriptor"},"finding_counts":{"$ref":"#/components/schemas/contracts.FindingCounts"},"last_scan_at":{"type":"string"},"risk_score":{"description":"0-100","type":"integer"},"scanners_failed":{"type":"integer"},"scanners_run":{"description":"Scanner coverage for the primary (baseline) scan pass — informational only.\nSpec 077 US3 (FR-008/FR-014): Status is derived SOLELY from the\ndeterministic baseline findings; a failed Docker deep scanner no longer\ndowngrades a clean verdict. That failure is surfaced via DeepScan instead.","type":"integer"},"scanners_total":{"type":"integer"},"status":{"description":"\"clean\", \"warnings\", \"dangerous\", \"failed\", \"not_scanned\", \"scanning\"","type":"string"}},"type":"object"},"contracts.Server":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"authenticated":{"description":"OAuth authentication status","type":"boolean"},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges mirrors config.ServerConfig.AutoApproveToolChanges\n(MCP-2930): the per-server intent to auto-approve new/changed tools past\nthe trust baseline. Tri-state *bool — nil means \"never set\" (omitted from\nthe payload), so the Web UI toggle (MCP-2932) can distinguish unset from\nan explicit false. Read-only on the GET path; PATCH/POST accept it via\nAddServerRequest.","type":"boolean"},"command":{"type":"string"},"connected":{"type":"boolean"},"connected_at":{"type":"string"},"connecting":{"type":"boolean"},"created":{"type":"string"},"diagnostic":{"$ref":"#/components/schemas/contracts.Diagnostic"},"enabled":{"type":"boolean"},"env":{"additionalProperties":{"type":"string"},"type":"object"},"error_code":{"type":"string"},"expose_prompts":{"description":"ExposePrompts mirrors config.ServerConfig.ExposePrompts (F9): the per-server\nprompt-aggregation override. Tri-state *bool — nil/omitted means \"inherit\ndefault aggregation\". Surfaced on GET so a caller that PATCHed the override\ncan read it back; PATCH/POST accept it via AddServerRequest.","type":"boolean"},"expose_skills":{"description":"ExposeSkills mirrors config.ServerConfig.ExposeSkills: the per-server\nskills override. Tri-state *bool; nil/omitted means \"inherit\".","type":"boolean"},"forward_headers":{"description":"ForwardHeaders mirrors config.ServerConfig.ForwardHeaders (Spec 112): the\nallowlist of inbound MCP client header NAMES forwarded to this server on\ntools/call. Names only, never values. Omitted when empty.","items":{"type":"string"},"type":"array","uniqueItems":false},"generation":{"description":"Generation is the server's committed config generation (Spec 116\nFR-017): it changes whenever the server's configuration changes.","type":"integer"},"headers":{"additionalProperties":{"type":"string"},"type":"object"},"health":{"$ref":"#/components/schemas/contracts.HealthStatus"},"id":{"type":"string"},"incarnation":{"description":"Incarnation changes only when the name is removed and created again\n(Spec 116 FR-017). Approval endpoints accept it back as\nexpected_incarnation and answer 409 server_replaced on a mismatch.","type":"integer"},"init_timeout":{"description":"InitTimeout mirrors config.ServerConfig.InitTimeout (MCP-3322 / GH #760):\nthe per-server MCP ` + "`" + `initialize` + "`" + ` handshake deadline override. Serialized as\na duration string (e.g. \"120s\"); nil/omitted means \"inherit the global\ndefault\". Surfaced on the GET path so clients can read back a configured\noverride; PATCH/POST accept it via AddServerRequest.","type":"string"},"isolation":{"$ref":"#/components/schemas/contracts.IsolationConfig"},"isolation_defaults":{"$ref":"#/components/schemas/contracts.IsolationDefaults"},"isolation_effective":{"$ref":"#/components/schemas/contracts.IsolationEffective"},"last_error":{"type":"string"},"last_reconnect_at":{"type":"string"},"last_retry_time":{"type":"string"},"max_concurrent_requests":{"description":"Spec 093 (GH #955) — per-server concurrency overrides, scope (c) of\nFR-020. Each setting is tri-state: nil (omitted) means \"inherit\nserver_concurrency_defaults\", 0 disables that setting for this server,\npositive overrides it. Surfaced on the GET path so a caller can read back\nwhat it set; PATCH/POST accept them via AddServerRequest. The effective\nconcurrency for a server is additionally bounded by the global aggregate\nlimiter, which is NOT an inheritance source for these fields.","type":"integer"},"name":{"type":"string"},"oauth":{"$ref":"#/components/schemas/contracts.OAuthConfig"},"oauth_status":{"description":"OAuth status: \"authenticated\", \"expired\", \"error\", \"none\"","type":"string"},"protocol":{"type":"string"},"quarantine":{"$ref":"#/components/schemas/contracts.QuarantineStats"},"quarantined":{"type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_count":{"type":"integer"},"reconnect_on_use":{"description":"Attempt reconnection when a tool call targets this disconnected server","type":"boolean"},"retry_count":{"type":"integer"},"retry_stopped":{"description":"RetryStopped reports that automatic reconnection has been given up for\ngood because the failure is deterministic and unrecoverable — a missing\nbinary, an image without the interpreter, an unparseable config (GH\n#1145). It is NOT ordinary exponential backoff, which keeps retrying;\nnothing will happen until the user fixes the config or restarts the\nserver. RetryStoppedCode is the stable MCPX_* code that proved it and\nRetryStoppedReason the catalog message explaining how to fix it. All three\nare omitted for servers that are healthy or still retrying.","type":"boolean"},"retry_stopped_code":{"type":"string"},"retry_stopped_reason":{"type":"string"},"security_scan":{"$ref":"#/components/schemas/contracts.SecurityScanSummary"},"should_retry":{"type":"boolean"},"source_registry_id":{"description":"MCP-901 — registry provenance of an upstream that was added from a\nregistry. SourceRegistryID names the source registry (empty for\nmanually-configured servers); SourceRegistryProvenance is the trust tag\nrecorded at add time (\"official/trusted\" or \"custom/unverified\"). Both\nare projected from config.ServerConfig so the approval/quarantine view\ncan render an \"added from \u003cregistry\u003e · unverified\" origin badge. Optional\nand omitted when empty — clients that pre-date this treat them as absent.","type":"string"},"source_registry_provenance":{"type":"string"},"status":{"type":"string"},"token_expires_at":{"description":"When the OAuth token expires (ISO 8601)","type":"string"},"tool_argument_error_mode":{"type":"string"},"tool_count":{"type":"integer"},"tool_list_token_size":{"description":"Token size for this server's tools","type":"integer"},"trust_mode":{"description":"TrustMode mirrors config.ServerConfig.TrustMode (spec 086): the per-server\ntrust tier (\"auto\"/\"scan\"/\"manual\"). Surfaced on the GET path so clients can\nread back the persisted mode; PATCH/POST accept it via AddServerRequest.\nOmitted when empty (server predates the field / relies on legacy flags).","type":"string"},"updated":{"type":"string"},"url":{"type":"string"},"user_logged_out":{"description":"True if user explicitly logged out (prevents auto-reconnection)","type":"boolean"},"working_dir":{"type":"string"}},"type":"object"},"contracts.ServerActionResponse":{"properties":{"action":{"type":"string"},"async":{"type":"boolean"},"server":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.ServerStats":{"properties":{"connected_servers":{"type":"integer"},"docker_containers":{"type":"integer"},"quarantined_servers":{"type":"integer"},"token_metrics":{"$ref":"#/components/schemas/contracts.ServerTokenMetrics"},"total_servers":{"type":"integer"},"total_tools":{"type":"integer"}},"type":"object"},"contracts.ServerTokenMetrics":{"properties":{"average_query_result_size":{"description":"Typical retrieve_tools output (tokens)","type":"integer"},"estimated":{"description":"Estimated (Spec 109-k FR-070-ish, url-filter-contract.md / audit F-Token):\ntrue while AverageQueryResultSize is a synthetic simulation (a sample of\nthe first ` + "`" + `tools_limit` + "`" + ` tools' schemas — no real retrieve_tools call has\ncompleted yet in this runtime's usage aggregate); false once at least one\nreal retrieve_tools call has, at which point AverageQueryResultSize is\nderived from the real observed average response size instead. The Web\nUI and macOS render an \"estimate\" label while this is true.","type":"boolean"},"per_server_tool_list_sizes":{"additionalProperties":{"type":"integer"},"description":"Token size per server","type":"object"},"saved_tokens":{"description":"Difference","type":"integer"},"saved_tokens_percentage":{"description":"Percentage saved","type":"number"},"total_server_tool_list_size":{"description":"All upstream tools combined (tokens)","type":"integer"}},"type":"object"},"contracts.SkillContentResponse":{"properties":{"digest":{"type":"string"},"next_offset":{"description":"NextOffset is the byte offset of the next chunk; absent at the end.","type":"integer"},"offset":{"type":"integer"},"size":{"type":"integer"},"text":{"type":"string"}},"type":"object"},"contracts.SkillEntry":{"properties":{"approved_at":{"description":"ApprovedAt is omitted when the skill was never approved.","type":"string"},"approved_by":{"type":"string"},"approved_files":{"description":"ApprovedFiles is the file set of the approved copy; omitted when the\nskill has no approved copy. ` + "`" + `skills show --diff` + "`" + ` compares it with Files.","items":{"$ref":"#/components/schemas/contracts.SkillFileInfo"},"type":"array","uniqueItems":false},"approved_hash":{"type":"string"},"available":{"type":"boolean"},"blocked":{"type":"boolean"},"current_hash":{"type":"string"},"description":{"type":"string"},"files":{"items":{"$ref":"#/components/schemas/contracts.SkillFileInfo"},"type":"array","uniqueItems":false},"id":{"type":"string"},"listed":{"type":"boolean"},"name":{"type":"string"},"path":{"type":"string"},"scan":{"$ref":"#/components/schemas/contracts.SkillScanInfo"},"status":{"type":"string"},"total_size":{"type":"integer"},"unusable_reason":{"type":"string"},"uri":{"type":"string"}},"type":"object"},"contracts.SkillFileInfo":{"properties":{"digest":{"type":"string"},"path":{"type":"string"},"size":{"type":"integer"},"text":{"type":"boolean"}},"type":"object"},"contracts.SkillScanFinding":{"properties":{"evidence":{"type":"string"},"file":{"type":"string"},"offset":{"type":"integer"},"rule":{"type":"string"},"severity":{"type":"string"}},"type":"object"},"contracts.SkillScanInfo":{"properties":{"complete":{"type":"boolean"},"findings":{"items":{"$ref":"#/components/schemas/contracts.SkillScanFinding"},"type":"array","uniqueItems":false},"findings_truncated":{"description":"FindingsTruncated is true when more findings existed than are listed.","type":"boolean"},"incomplete":{"description":"Incomplete says why Complete is false: size_cap, time_limit, coverage or\ninterrupted; empty when the scan is complete.","type":"string"},"scanned_at":{"description":"ScannedAt is omitted when no scan of the current content exists.","type":"string"},"verdict":{"type":"string"}},"type":"object"},"contracts.SkillsApproveRequest":{"properties":{"expected_hashes":{"additionalProperties":{"type":"string"},"description":"ExpectedHashes maps each skill path to the current_hash the reviewer\nsaw. A skill without an entry is refused as unreviewed.","type":"object"},"expected_incarnation":{"description":"ExpectedIncarnation binds the approval to the server the reviewer saw;\n0 (or absent) binds to the incarnation current when the request starts.","type":"integer"},"skills":{"description":"Skills are skill paths (the part of the id after \"\u003cserver\u003e:\"), 1 to 200.","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.SkillsApproveResponse":{"properties":{"approved":{"description":"Approved counts the skills newly approved; a skill already approved for\nits current content is not counted.","type":"integer"}},"type":"object"},"contracts.SkillsBlockRequest":{"properties":{"expected_incarnation":{"type":"integer"},"skills":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.SkillsBlockResponse":{"properties":{"changed":{"description":"Changed counts the skills whose blocked mark changed.","type":"integer"}},"type":"object"},"contracts.SkillsErrorResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.SkillsListResponse":{"properties":{"enabled":{"type":"boolean"},"error":{"type":"string"},"expose_skills":{"type":"boolean"},"incarnation":{"description":"Incarnation is the server's approval incarnation: send it back as\nexpected_incarnation on approve, block and unblock.","type":"integer"},"last_refresh":{"type":"string"},"server":{"type":"string"},"skills":{"items":{"$ref":"#/components/schemas/contracts.SkillEntry"},"type":"array","uniqueItems":false},"supported":{"type":"boolean"},"truncated":{"type":"boolean"}},"type":"object"},"contracts.SkillsStaleReviewResponse":{"properties":{"changed":{"items":{"type":"string"},"type":"array","uniqueItems":false},"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"},"unreviewed":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.SkillsUnusableResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"skills":{"items":{"type":"string"},"type":"array","uniqueItems":false},"success":{"type":"boolean"}},"type":"object"},"contracts.SuccessResponse":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"success":{"type":"boolean"}},"type":"object"},"contracts.Tier":{"description":"Tier is computed by AnnotationTier (Spec 109 FR-028/X11) from\nAnnotations — read|write|destructive|unannotated. Set by every producer\nof a Tool (enrichServerTools, the global tools handler); never left for\na consuming surface to compute.","type":"string","x-enum-varnames":["TierRead","TierWrite","TierDestructive","TierUnannotated","TierUnknown"]},"contracts.TokenMetrics":{"description":"Token usage metrics (nil for older records)","properties":{"encoding":{"description":"Encoding used (e.g., cl100k_base)","type":"string"},"estimated_cost":{"description":"Optional cost estimate","type":"number"},"input_tokens":{"description":"Tokens in the request","type":"integer"},"model":{"description":"Model used for tokenization","type":"string"},"output_tokens":{"description":"Tokens in the response","type":"integer"},"total_tokens":{"description":"Total tokens (input + output)","type":"integer"},"truncated_tokens":{"description":"Tokens removed by truncation","type":"integer"},"was_truncated":{"description":"Whether response was truncated","type":"boolean"}},"type":"object"},"contracts.Tool":{"properties":{"access":{"$ref":"#/components/schemas/contracts.ToolAccess"},"annotations":{"$ref":"#/components/schemas/contracts.ToolAnnotation"},"approval_status":{"type":"string"},"config_denied":{"description":"ConfigDenied is true when the tool is denied by the server's static\nenabled_tools / disabled_tools config. The user cannot override this toggle.","type":"boolean"},"description":{"type":"string"},"disabled":{"description":"Disabled mirrors ToolApprovalRecord.Disabled so per-tool enable state is\navailable without a second round-trip to the approvals endpoint. Absent\nin the JSON when false (default) to keep responses compact.","type":"boolean"},"hash":{"description":"Hash is the tool's current stored hash rendered in the preflight pin\nformat \"sha256/v{N}:{hex}\" (Spec 098 FR-011), where N is the approval\nrecord's HashSchemaVersion. It is the authoring surface for\n` + "`" + `POST /api/v1/preflight` + "`" + ` pins and ` + "`" + `mcpproxy tools preflight --pin` + "`" + `:\ncopy the value straight into a pin.\n\nDisclosure is OPERATOR TIER ONLY — same rule as the preflight per-tool\nresult. The field is omitted for agent-token callers and for tools with\nno stored hash (no approval record yet, or a record written before\nhashes existed).","type":"string"},"held_reason":{"description":"HeldReason, HeldVerdict and HeldSignals mirror the same-named fields on\nstorage.ToolApprovalRecord: the offline-scan evidence that made\ntrust_mode: scan hold this tool for review (spec 086 FR-018). HeldSignals\nnames the matched deterministic check ids, e.g.\n\"tpa.TPA-2026-0001.hidden_instruction\", so a reviewer can see WHY the tool\nis held. All three are omitted for tools that are not held by the scan gate\n(including every record written before the field existed).","type":"string"},"held_signals":{"items":{"type":"string"},"type":"array","uniqueItems":false},"held_verdict":{"type":"string"},"last_used":{"type":"string"},"name":{"type":"string"},"profile_tier":{"description":"ProfileTier and Access are present only in a view-as listing (a tools\nlisting with ?client= or ?profile=, Spec 108 FR-032). ProfileTier is the\ntool's tier under the viewed subject's profile (Tier above stays the\nintrinsic tier); Access is the subject's verdict for the tool. Absent\notherwise, so an ordinary listing is byte-identical to before.","type":"string","x-enum-varnames":["TierRead","TierWrite","TierDestructive","TierUnannotated","TierUnknown"]},"schema":{"type":"object"},"server_incarnation":{"description":"ServerIncarnation is the committed incarnation of the server this row\nwas read for (Spec 116 FR-017), captured before the tools were fetched.\nA client echoes it as expected_incarnation on a per-tool decision, so a\nstale row is refused (409 server_replaced) after a same-name re-add.\nOmitted when the server has no committed incarnation.","type":"integer"},"server_name":{"type":"string"},"tier":{"$ref":"#/components/schemas/contracts.Tier"},"usage":{"type":"integer"}},"type":"object"},"contracts.ToolAccess":{"properties":{"callable":{"type":"boolean"},"reason":{"type":"string"},"visible":{"type":"boolean"}},"type":"object"},"contracts.ToolAnnotation":{"description":"Tool behavior hints snapshot","properties":{"destructiveHint":{"type":"boolean"},"idempotentHint":{"type":"boolean"},"openWorldHint":{"type":"boolean"},"readOnlyHint":{"type":"boolean"},"title":{"type":"string"}},"type":"object"},"contracts.ToolCallRecord":{"description":"The new tool call record","properties":{"annotations":{"$ref":"#/components/schemas/contracts.ToolAnnotation"},"arguments":{"description":"Tool arguments","type":"object"},"arguments_truncated":{"description":"ArgumentsTruncated marks Arguments as a placeholder rather than the\narguments the tool was called with. Replaying such a record without\nsupplying arguments explicitly is refused.","type":"boolean"},"config_path":{"description":"Active config file path","type":"string"},"duration":{"description":"Duration in nanoseconds","type":"integer"},"error":{"description":"Error message (failure only)","type":"string"},"execution_type":{"description":"\"direct\" or \"code_execution\"","type":"string"},"id":{"description":"Unique identifier","type":"string"},"mcp_client_name":{"description":"MCP client name from InitializeRequest","type":"string"},"mcp_client_version":{"description":"MCP client version","type":"string"},"mcp_session_id":{"description":"MCP session identifier","type":"string"},"metrics":{"$ref":"#/components/schemas/contracts.TokenMetrics"},"parent_call_id":{"description":"Links nested calls to parent code_execution","type":"string"},"request_id":{"description":"Request correlation ID","type":"string"},"response":{"description":"Tool response (success only)","type":"object"},"response_bytes":{"description":"Marshalled response size before truncation","type":"integer"},"response_truncated":{"description":"ResponseTruncated and ResponseBytes describe a STORAGE-side cut (#1176):\nthe caller received the response whole, and only the persisted copy was\nshortened to tool_call_max_response_size. When ResponseTruncated is true\nthe Response object carries {truncated, original_bytes, preview, note}\ninstead of the upstream result, and ResponseBytes is its size before the\ncut.","type":"boolean"},"server_id":{"description":"Server identity hash","type":"string"},"server_name":{"description":"Human-readable server name","type":"string"},"timestamp":{"description":"When the call was made","type":"string"},"tool_name":{"description":"Tool name (without server prefix)","type":"string"}},"type":"object"},"contracts.UpdateInfo":{"description":"Update information (if available)","properties":{"available":{"description":"Whether an update is available","type":"boolean"},"behind_summary":{"description":"Spec 079 FR-002 — how far behind the running build is. All four are\nadditive (FR-021) and absent when the delta could not be resolved, in\nwhich case every surface renders its pre-delta wording.","type":"string"},"check_error":{"description":"Error message if update check failed","type":"string"},"checked_at":{"description":"When the update check was performed","type":"string"},"install_channel":{"description":"Detected install channel (homebrew, dmg, deb, rpm, docker, go-install, windows-installer, tarball, unknown) — Spec 079 FR-008","type":"string"},"is_prerelease":{"description":"Whether the latest version is a prerelease","type":"boolean"},"latest_version":{"description":"Latest version available (e.g., \"v1.2.3\")","type":"string"},"nudges_suppressed":{"description":"UI surfaces must stay quiet (CI / non-interactive context); machine-readable fields still report the facts — Spec 079 FR-019","type":"boolean"},"release_url":{"description":"URL to the release page","type":"string"},"releases_behind":{"description":"Releases on the offered channel between the running and offered versions","type":"integer"},"releases_behind_saturated":{"description":"ReleasesBehind is a lower bound: the running build predates the scanned release window","type":"boolean"},"update_command":{"description":"One-line update command for the channel; only set when an update is available and the channel has one — Spec 079 FR-009","type":"string"},"weeks_behind":{"description":"Whole weeks between the two releases' publish dates; 0 is a real value, absent means unknown","type":"integer"}},"type":"object"},"contracts.UpdatePolicy":{"description":"UpdatePolicy is the effective, hot-reloadable update policy (Spec 092\nFR-015). Always present: the ` + "`" + `update` + "`" + ` object above is omitted both when\nupdate checking is disabled AND when no check has produced a result\nyet, so its absence cannot tell a client whether it is allowed to run\nits own (e.g. Sparkle feed) check. This field states the answer.","properties":{"channel":{"description":"Channel is the tracked release channel: \"stable\" or \"rc\".","type":"string"},"enabled":{"description":"Enabled is the effective automatic-check kill switch: update_check.enabled\nwith MCPPROXY_DISABLE_AUTO_UPDATE=true winning over it. A user-initiated\n\"Check for Updates\" stays available regardless.","type":"boolean"},"nudges_suppressed":{"description":"NudgesSuppressed asks UI surfaces to stay quiet (CI / non-interactive)\nwhile machine-readable fields keep reporting the facts.","type":"boolean"}},"type":"object"},"contracts.UpstreamError":{"properties":{"error_message":{"type":"string"},"server_name":{"type":"string"},"timestamp":{"type":"string"}},"type":"object"},"contracts.UsageAggregateResponse":{"properties":{"freshness_ms":{"description":"age of the underlying snapshot in ms","type":"integer"},"generated_at":{"type":"string"},"other":{"$ref":"#/components/schemas/contracts.UsageOtherBucket"},"timeline":{"items":{"$ref":"#/components/schemas/contracts.UsageTimeBucket"},"type":"array","uniqueItems":false},"token_source":{"description":"\"bytes\" (size-based proxy, FR-006)","type":"string"},"tokens_saved":{"description":"echoed from ServerTokenMetrics (FR-007)","type":"integer"},"tokens_saved_estimated":{"description":"TokensSavedEstimated echoes ServerTokenMetrics.Estimated (Spec 109-k):\ntrue while TokensSaved is a synthetic simulation rather than derived\nfrom a real retrieve_tools call. Dropped (false, the zero value) for a\nscoped caller along with TokensSaved itself, above.","type":"boolean"},"tokens_saved_percentage":{"type":"number"},"tools":{"items":{"$ref":"#/components/schemas/contracts.UsageToolStat"},"type":"array","uniqueItems":false},"total_calls":{"description":"TotalCalls and TotalErrors are the headline counts for the window: the sum\nof the timeline this same response carries, so the tiles and the histogram\nunder them cannot disagree. They are NOT the sum of Tools — that list is\nlifetime-cumulative, upstream-only and truncated to top-N, and summing it\nclient-side is what made the Usage tab print a third number for the same\n24 hours (audit finding F1, #1046). The population is\nstorage.CountsAsCall, shared with ActivitySummaryResponse.CallCount.\n\nTwo bounds on how exactly this matches the Activity Log's own count.\nBoth are bounded and disclosed, unlike the population mismatch they\nreplace, which was unbounded and silent:\n\n - Window granularity is the timeline's: whole hour buckets, so the span\n is the requested window rounded up to a bucket edge.\n - This response is served from a snapshot behind a short read cache\n (observability.usage_cache_ttl, 5s by default) so the endpoint never\n scans the activity log per request, while the summary endpoint counts\n live. Calls that land inside that window appear on the Activity Log\n first. FreshnessMs and GeneratedAt say how old the figures are, and\n the Usage tab prints it (\"Updated 3s ago\").","type":"integer"},"total_errors":{"type":"integer"},"window":{"type":"string"}},"type":"object"},"contracts.UsageOtherBucket":{"description":"present only when the list was truncated to top-N","properties":{"calls":{"type":"integer"},"tools_folded":{"type":"integer"},"total_resp_bytes":{"type":"integer"}},"type":"object"},"contracts.UsageTimeBucket":{"properties":{"calls":{"type":"integer"},"errors":{"type":"integer"},"start":{"type":"string"},"total_resp_bytes":{"type":"integer"}},"type":"object"},"contracts.UsageToolStat":{"properties":{"avg_req_bytes":{"description":"null when no sized request calls","type":"integer"},"avg_resp_bytes":{"description":"null when sized_calls == 0 (only legacy 0-byte calls)","type":"integer"},"blocked":{"type":"integer"},"calls":{"type":"integer"},"error_rate":{"type":"number"},"errors":{"type":"integer"},"last_used":{"type":"string"},"p50_exceeds":{"type":"boolean"},"p50_ms":{"description":"P50Ms and P95Ms are read off a fixed latency histogram, so they are BUCKET\nBOUNDS, not measured durations: the true percentile is at or below the\nvalue, and a client must render it as a bound (\"≤ 5 ms\"). P50Exceeds /\nP95Exceeds flip that reading for the unbounded overflow bucket, where the\nvalue is the last bound and the truth is above it (\"\u003e 10 s\").","type":"integer"},"p95_exceeds":{"type":"boolean"},"p95_ms":{"type":"integer"},"rejected":{"description":"spec 093: shed by a concurrency limit; never executed, so excluded from calls/latency","type":"integer"},"server":{"type":"string"},"sized_calls":{"description":"calls with known response size (basis for avg_resp_bytes)","type":"integer"},"tool":{"type":"string"},"total_req_bytes":{"type":"integer"},"total_resp_bytes":{"type":"integer"}},"type":"object"},"contracts.ValidateConfigResponse":{"properties":{"errors":{"items":{"$ref":"#/components/schemas/contracts.ValidationError"},"type":"array","uniqueItems":false},"valid":{"type":"boolean"}},"type":"object"},"contracts.ValidationError":{"properties":{"field":{"type":"string"},"message":{"type":"string"}},"type":"object"},"contracts.ViewAsCounts":{"description":"Counts is present only for a NON-administrator profile view-as (Spec 108\nFR-032): the response then lists only the visible rows, and this is the\nonly trace of the rest, with no per-server, per-tier or per-reason\nbreakdown.","properties":{"hidden":{"type":"integer"},"visible":{"type":"integer"}},"type":"object"},"contracts.WorkSession":{"properties":{"attempts":{"description":"Attempts, Failures and PolicyBlocks are lifetime counts of the session.\nPolicyBlocks are included in Failures.","type":"integer"},"client_id":{"type":"string"},"client_name":{"type":"string"},"connection_count":{"description":"Administrators only.","type":"integer"},"duration_ms":{"type":"integer"},"ended_at":{"type":"string"},"failures":{"type":"integer"},"first_failure_at":{"type":"string"},"id":{"type":"string"},"last_activity_at":{"type":"string"},"last_failure":{"$ref":"#/components/schemas/contracts.WorkSessionFailure"},"ownerless":{"type":"boolean"},"policy_blocks":{"type":"integer"},"profile":{"description":"Profile is returned to administrators only.","type":"string"},"profile_source":{"type":"string"},"project_name":{"description":"ProjectName is the basename of the client's workspace, when it\ndisclosed one.","type":"string"},"rebuilt":{"type":"boolean"},"run_name":{"type":"string"},"started_at":{"type":"string"},"status":{"description":"Status is \"active\" or \"ended\".","type":"string"},"stored_failures":{"description":"StoredFailures counts the failures whose rows are still in the log;\nit is what the timeline can navigate.","type":"integer"},"surface":{"type":"string"},"token_name":{"type":"string"},"truncated_start_at":{"type":"string"}},"type":"object"},"contracts.WorkSessionEnvelope":{"properties":{"data":{"$ref":"#/components/schemas/contracts.WorkSession"},"success":{"type":"boolean"}},"type":"object"},"contracts.WorkSessionFailure":{"properties":{"at":{"type":"string"},"error_class":{"type":"string"},"error_code":{"type":"string"},"policy_block":{"description":"PolicyBlock is true when the failure was a refusal by MCPProxy itself.","type":"boolean"},"reason":{"description":"Reason is at most 200 characters and never contains argument or\nresponse bodies.","type":"string"},"server":{"type":"string"},"tool":{"type":"string"}},"type":"object"},"contracts.WorkSessionListEnvelope":{"properties":{"data":{"$ref":"#/components/schemas/contracts.WorkSessionListResponse"},"success":{"type":"boolean"}},"type":"object"},"contracts.WorkSessionListResponse":{"properties":{"limit":{"type":"integer"},"offset":{"type":"integer"},"sessions":{"items":{"$ref":"#/components/schemas/contracts.WorkSession"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.WorkSessionTimelineEnvelope":{"properties":{"data":{"$ref":"#/components/schemas/contracts.WorkSessionTimelineResponse"},"success":{"type":"boolean"}},"type":"object"},"contracts.WorkSessionTimelineResponse":{"properties":{"earlier_failures_not_stored":{"type":"boolean"},"failure_index":{"description":"FailureIndex is the 1-based number of the failure at or before the\nposition among the stored failures in reach (0 when none), and\nFailureTotal their count.","type":"integer"},"failure_total":{"type":"integer"},"has_after":{"type":"boolean"},"has_before":{"type":"boolean"},"lifetime_failures":{"description":"LifetimeFailures is the session's lifetime failure count in reach.\nEarlierFailuresNotStored says some of them are no longer in the log.","type":"integer"},"position":{"description":"Position is the index of the row the page is positioned at; TotalRows\nis the number of rows in the caller's view.","type":"integer"},"rows":{"items":{"$ref":"#/components/schemas/contracts.WorkSessionTimelineRow"},"type":"array","uniqueItems":false},"session":{"$ref":"#/components/schemas/contracts.WorkSession"},"total_rows":{"type":"integer"}},"type":"object"},"contracts.WorkSessionTimelineRow":{"properties":{"activity":{"$ref":"#/components/schemas/contracts.ActivityRecord"},"at":{"description":"At is the time of the row.","type":"string"},"bodies_removed":{"description":"BodiesRemoved is true when retention removed the row's argument and\nresponse bodies to keep the row.","type":"boolean"},"failed":{"description":"Failed marks the counted row of a failed attempt; PolicyBlock marks a\nrefusal by MCPProxy itself.","type":"boolean"},"index":{"description":"Index is the row's position in the caller's view of the timeline.","type":"integer"},"kind":{"type":"string"},"policy_block":{"type":"boolean"},"precedes_session":{"description":"PrecedesSession marks an upstream event from before the session\nstarted: the latest event of a server the session then failed on,\nstill unresolved when the session began (release QA F2, SC-005).","type":"boolean"}},"type":"object"},"data":{"properties":{"data":{"$ref":"#/components/schemas/contracts.InfoResponse"}},"type":"object"},"httpapi.AccessExplanationData":{"properties":{"first_failure":{"type":"string","x-enum-varnames":["StepCredential","StepProfile","StepServerInScope","StepToolRule","StepTierCap","StepTokenPermission","StepGlobalGate","StepServerState","StepToolApproval"]},"fixes":{"items":{"$ref":"#/components/schemas/runtime.Fix"},"type":"array","uniqueItems":false},"profile":{"$ref":"#/components/schemas/runtime.ExplainProfileView"},"steps":{"items":{"$ref":"#/components/schemas/runtime.ExplainStepView"},"type":"array","uniqueItems":false},"subject":{"$ref":"#/components/schemas/runtime.ExplainSubjectView"},"tool":{"type":"string"},"verdict":{"$ref":"#/components/schemas/profile.ExplainVerdict"}},"type":"object"},"httpapi.AccessSuggestionsData":{"properties":{"already_fixed":{"description":"AlreadyFixed counts groups the explainer now allows (they drop out).","type":"integer"},"blocked_calls":{"description":"BlockedCalls counts every profile-refused call in the window.","type":"integer"},"non_profile_blocked":{"description":"NonProfileBlocked counts blocked calls with a cause outside profiles.","type":"integer"},"patches":{"items":{"$ref":"#/components/schemas/runtime.ProfilePatch"},"type":"array","uniqueItems":false},"profile_removed":{"description":"ProfileRemoved counts groups whose profile no longer exists (they drop out).","type":"integer"},"since":{"type":"string"},"suggestions":{"items":{"$ref":"#/components/schemas/runtime.AccessSuggestion"},"type":"array","uniqueItems":false},"unattributed":{"description":"Unattributed counts profile refusals whose record names no profile.","type":"integer"},"until":{"type":"string"},"window":{"type":"string"}},"type":"object"},"httpapi.AddServerRequest":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges is the per-server intent to auto-approve\nnew/changed tools past the trust baseline (MCP-2930). Tri-state *bool:\na nil pointer means \"leave unchanged\" on PATCH; a present value\n(including false) is applied. Mirrors config.ServerConfig's *bool\nsemantics — do NOT collapse to a plain bool, or an omitted field would\nsilently reset a previously-set value.","type":"boolean"},"command":{"type":"string"},"enabled":{"type":"boolean"},"env":{"additionalProperties":{"type":"string"},"type":"object"},"expose_prompts":{"description":"ExposePrompts is the per-server override for prompt aggregation (F9):\nwhether this server's advertised MCP prompts are merged into mcpproxy's\nprompts/list. Tri-state *bool mirroring config.ServerConfig.ExposePrompts —\na nil pointer means \"leave unchanged\" on PATCH (and \"inherit the default\naggregate behavior\" on create); a present value (including false) is applied.","type":"boolean"},"expose_skills":{"description":"ExposeSkills is the per-server skills override (MCP skills extension).\nTri-state *bool mirroring config.ServerConfig.ExposeSkills: nil means\n\"leave unchanged\" on PATCH and \"inherit\" on create.","type":"boolean"},"forward_headers":{"description":"ForwardHeaders is the per-server allowlist of inbound MCP client header\nNAMES forwarded to this server on tools/call (Spec 112). Names only, never\nvalues. On PATCH a nil slice (field omitted) leaves the stored allowlist\nunchanged and an empty array ([]) clears it. Invalid, denied, duplicate\nand static-header-colliding names are rejected with 400.","items":{"type":"string"},"type":"array","uniqueItems":false},"headers":{"additionalProperties":{"type":"string"},"type":"object"},"init_timeout":{"description":"InitTimeout is the per-server MCP ` + "`" + `initialize` + "`" + ` handshake deadline override\n(MCP-3322 / GH #760), serialized as a duration string (e.g. \"120s\"). A nil\npointer means \"leave unchanged\" on PATCH; a present value is applied.\nMirrors config.ServerConfig.InitTimeout's *Duration tri-state.","type":"string"},"isolation":{"$ref":"#/components/schemas/httpapi.IsolationRequest"},"max_concurrent_requests":{"description":"MaxConcurrentRequests / QueueSize / QueueTimeout are the per-server\nconcurrency overrides (spec 093 / GH #955, FR-020 scope (c)). Each is\ntri-state: a nil pointer means \"leave unchanged\" on PATCH and \"inherit\nserver_concurrency_defaults\" on create; an explicit 0 disables that\nsetting for this server; a positive value overrides it. Do NOT collapse\nthem to plain values — an omitted field would then silently reset a\nconfigured limit.","type":"integer"},"name":{"type":"string"},"protocol":{"type":"string"},"quarantined":{"type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_on_use":{"type":"boolean"},"tool_argument_error_mode":{"description":"Empty preserves an update; detailed explicitly resets a redacted policy.","type":"string"},"trust_mode":{"description":"TrustMode is the per-server trust tier (spec 086): \"auto\", \"scan\", or\n\"manual\". Empty means \"leave unchanged\" on PATCH (and inherit the migrated\ndefault on create). A non-empty value is applied to ServerConfig.TrustMode\nand resolved by EffectiveTrustMode (an unrecognized value fails closed to\nmanual). This is the REST seam for changing the trust tier via\nPOST/PATCH /api/v1/servers.","type":"string"},"url":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"httpapi.BindingGuardResponse":{"properties":{"bindings":{"items":{"$ref":"#/components/schemas/httpapi.GuardBinding"},"type":"array","uniqueItems":false},"code":{"description":"binding_bypassable_without_auth","type":"string"},"error":{"description":"Human-readable, byte-stable refusal text","type":"string"},"fixes":{"items":{"$ref":"#/components/schemas/httpapi.GuardFixOption"},"type":"array","uniqueItems":false},"request_id":{"type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.BulkAssignRequest":{"properties":{"from_profile":{"type":"string"},"mode":{"type":"string"},"to_profile":{"type":"string"}},"type":"object"},"httpapi.BulkAssignResponse":{"properties":{"moved":{"items":{"type":"string"},"type":"array","uniqueItems":false},"skipped":{"items":{"$ref":"#/components/schemas/httpapi.BulkAssignSkipped"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.BulkAssignSkipped":{"properties":{"client_id":{"type":"string"},"code":{"type":"string"},"error":{"type":"string"}},"type":"object"},"httpapi.BundleRollbackRefusedResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"rejection":{"$ref":"#/components/schemas/scanner.BundleRejection"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"httpapi.CanonicalConfigPath":{"properties":{"description":{"description":"Brief description","type":"string"},"exists":{"description":"Whether the file exists","type":"boolean"},"format":{"description":"Format identifier (e.g., \"claude_desktop\")","type":"string"},"name":{"description":"Display name (e.g., \"Claude Desktop\")","type":"string"},"os":{"description":"Operating system (darwin, windows, linux)","type":"string"},"path":{"description":"Full path to the config file","type":"string"}},"type":"object"},"httpapi.CanonicalConfigPathsResponse":{"properties":{"os":{"description":"Current operating system","type":"string"},"paths":{"description":"List of canonical config paths","items":{"$ref":"#/components/schemas/httpapi.CanonicalConfigPath"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ClientBindingErrorResponse":{"properties":{"code":{"type":"string"},"error":{"type":"string"},"field":{"type":"string"},"request_id":{"type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.ClientBindingResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"warnings":{"items":{"$ref":"#/components/schemas/httpapi.ClientWarning"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ClientCredential":{"properties":{"approved_at":{"type":"string"},"expires_at":{"type":"string"},"grant_id":{"description":"GrantID names a browser login.","type":"string"},"kind":{"description":"Kind is api_key or browser_login.","type":"string"},"last_used_at":{"type":"string"},"name_mismatch":{"type":"boolean"},"observed_name":{"description":"ObservedName is the name the client sent at initialize (advisory).","type":"string"},"prefix":{"type":"string"},"redirect_host":{"type":"string"},"reported_name":{"type":"string"},"state":{"description":"State is active|expired|revoked for an API key and active|lapsed|revoked\nfor a login.","type":"string"}},"type":"object"},"httpapi.ClientSnippet":{"properties":{"generic_http":{"type":"string"},"header_name":{"type":"string"}},"type":"object"},"httpapi.ClientWarning":{"properties":{"action":{"$ref":"#/components/schemas/runtime.WarningAction"},"bindings":{"items":{"$ref":"#/components/schemas/runtime.BindingRef"},"type":"array","uniqueItems":false},"client_id":{"type":"string"},"code":{"$ref":"#/components/schemas/profile.WarningCode"},"fixes":{"items":{"$ref":"#/components/schemas/runtime.GuardFix"},"type":"array","uniqueItems":false},"message":{"type":"string"},"severity":{"$ref":"#/components/schemas/profile.WarningSeverity"}},"type":"object"},"httpapi.ConnectConflictResponse":{"properties":{"action":{"description":"already_exists | precondition_failed","type":"string"},"data":{"$ref":"#/components/schemas/connect.ConnectResult"},"error":{"description":"Human-readable message","type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.ConnectRequest":{"properties":{"force":{"description":"Overwrite existing entry","type":"boolean"},"keyless":{"type":"boolean"},"mode":{"type":"string"},"precondition_token":{"description":"PreconditionToken is the opaque token from the preview this write was\nconfirmed against (Spec 091 FR-005). When present, the core rechecks it\nat write time and responds 409 with action \"precondition_failed\" —\nwriting nothing — if the config or the entry MCPProxy would write has\ndrifted since; the caller then re-previews instead of retrying. Absent\nmeans exactly the pre-091 behavior. A replace-classified flow sends this\nTOGETHER with force=true: the token, not the absence of force, is the\noverwrite safety.","type":"string"},"profile":{"description":"Profile, Mode and Keyless are the client-credential intent (Spec 108\nFR-024). Profile names the profile the client's credential binds to;\n\"\" is the built-in All servers scope. Omitted means \"not specified\": a\nfresh credential defaults to All servers and a reconnect keeps the\nclient's existing binding (a reconnect never silently widens a locked\nclient). Mode is locked|switchable (default locked for a named profile,\nswitchable for All servers). Keyless writes a credential-less entry and\nis only possible while require_mcp_auth is off; it cannot carry a\nprofile or mode.","type":"string"},"server_name":{"description":"Defaults to \"mcpproxy\"","type":"string"}},"type":"object"},"httpapi.CreateClientRequest":{"properties":{"display_name":{"type":"string"},"expires_in":{"description":"ExpiresIn is a duration like 30d or 720h; default and cap are 365 days.","type":"string"},"id":{"type":"string"},"mode":{"type":"string"},"profile":{"type":"string"},"purpose":{"description":"Purpose is the stated, unenforced task brief (Spec 115), at most 500\ncharacters; screened for secrets before anything is stored.","type":"string"}},"type":"object"},"httpapi.CreateClientResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"credential":{"type":"string"},"snippet":{"$ref":"#/components/schemas/httpapi.ClientSnippet"}},"type":"object"},"httpapi.EffectiveToolsData":{"properties":{"counts":{"$ref":"#/components/schemas/runtime.EffectiveCounts"},"profile":{"type":"string"},"stale_classification_reasons":{"additionalProperties":{"type":"string"},"description":"StaleClassificationReasons maps each stale classify entry to why it no\nlonger applies: profile.StaleClassificationAnnotated or\nprofile.StaleClassificationMissing. It is computed over the UNFILTERED\ntool set, so a server or reason filter never changes it. Administrators\nonly.","type":"object"},"stale_classifications":{"description":"StaleClassifications lists classify entries for tools that are now\nannotated or no longer exist (FR-005). Administrators only.","items":{"type":"string"},"type":"array","uniqueItems":false},"tools":{"items":{"$ref":"#/components/schemas/runtime.EffectiveTool"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.EnvFieldPreview":{"properties":{"empty_or_placeholder":{"type":"boolean"},"name":{"type":"string"},"secret_like":{"type":"boolean"},"value_present":{"type":"boolean"}},"type":"object"},"httpapi.FinalizeClientResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"rotation":{"$ref":"#/components/schemas/httpapi.RotationState"}},"type":"object"},"httpapi.ForgetClientResponse":{"properties":{"disconnect_error":{"type":"string"},"disconnected":{"type":"boolean"},"revoked":{"type":"string"}},"type":"object"},"httpapi.GuardBinding":{"properties":{"client_id":{"type":"string"},"mode":{"type":"string"},"profile":{"type":"string"},"token_name":{"type":"string"}},"type":"object"},"httpapi.GuardFixOption":{"properties":{"kind":{"type":"string"},"target":{"type":"string"}},"type":"object"},"httpapi.HeaderFieldPreview":{"properties":{"empty_or_placeholder":{"type":"boolean"},"name":{"type":"string"},"secret_like":{"type":"boolean"},"value_present":{"type":"boolean"}},"type":"object"},"httpapi.ImportFromPathRequest":{"properties":{"format":{"description":"Optional format hint","type":"string"},"path":{"description":"File path to import from","type":"string"},"rename":{"additionalProperties":{"type":"string"},"description":"Rename maps a server name → new name. Applied after parsing so the\ncaller can disambiguate cross-source name collisions (Spec 046 v2 —\ne.g. \"mcpproxy\" → \"mcpproxy_claude_code\"). Keys are matched against\neither the raw source name (OriginalName) or the sanitized name shown\nin the preview (Server.Name); these differ for names that need\nsanitizing (e.g. \"Figma Desktop\" → \"Figma_Desktop\"). Keys not present\nin the imported set are ignored.","type":"object"},"server_names":{"description":"Optional: import only these servers","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportRequest":{"properties":{"allow_paste_fallback":{"description":"AllowPasteFallback opts into detecting a bare URL or a single command\nline (FR-064) when Format/format detection would otherwise fail — see\nconfigimport.ImportOptions.AllowPasteFallback for why this must stay\nopt-in (review round 4 F-E). Only the interactive Paste tab sets this;\nevery other caller of this endpoint (the general \"Import config\"\npanel, or a direct API call) leaves it false and gets a clear\n\"unable to detect configuration format\" error for a plain one-liner\ninstead of it being silently guessed at and, on apply, added as a\nreal server with no confirmation step.","type":"boolean"},"content":{"description":"Raw JSON or TOML content","type":"string"},"env_override":{"additionalProperties":{"type":"string"},"description":"EnvOverride/HeaderOverride (Spec 109 FR-064/065, PR review round 4\nF-A/F-D fix): the Paste tab's per-field Value/Secret edits — a plain\nvalue the user typed, or a keyring ref path if they chose Secret —\nkeyed by field name. Applied to the matching imported server's\nEnv/Headers ONLY when preview=false, directly on the server this\nrequest's own raw Content parses to server-side. This is what lets\nthe apply call carry the user's edited env/header values without\never round-tripping the redacted preview: url/command/args on apply\nalways come from re-parsing Content here, never from a client-held\npreview response, so a credential embedded in a URL query param or\nargv flag (which the preview necessarily redacted for display) is\nnever overwritten with the masked placeholder.","type":"object"},"format":{"description":"Optional format hint","type":"string"},"header_override":{"additionalProperties":{"type":"string"},"type":"object"},"server_names":{"description":"Optional: import only these servers","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportResponse":{"properties":{"failed":{"items":{"$ref":"#/components/schemas/configimport.FailedServer"},"type":"array","uniqueItems":false},"format":{"type":"string"},"format_name":{"type":"string"},"imported":{"items":{"$ref":"#/components/schemas/httpapi.ImportedServerResponse"},"type":"array","uniqueItems":false},"skipped":{"items":{"$ref":"#/components/schemas/configimport.SkippedServer"},"type":"array","uniqueItems":false},"summary":{"$ref":"#/components/schemas/configimport.ImportSummary"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportedServerResponse":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"command":{"type":"string"},"env":{"items":{"$ref":"#/components/schemas/httpapi.EnvFieldPreview"},"type":"array","uniqueItems":false},"fields_skipped":{"items":{"type":"string"},"type":"array","uniqueItems":false},"headers":{"items":{"$ref":"#/components/schemas/httpapi.HeaderFieldPreview"},"type":"array","uniqueItems":false},"name":{"type":"string"},"original_name":{"type":"string"},"protocol":{"type":"string"},"source_format":{"type":"string"},"summary":{"description":"Summary, Tags, Env and Headers are the Spec 109 FR-064 preview\nenrichment (contracts/rest-api.md \"Import preview\"). Summary and Tags\nare built from the already-redacted URL/Command/Args above, so a\nsecret embedded in argv or a URL query never reaches Summary either.\nEnv/Headers never carry the raw value — only its presence and two\nbooleans a surface uses to default the Value/Secret toggle (FR-065).","type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"url":{"type":"string"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.IsolationRequest":{"description":"Isolation carries per-server Docker isolation overrides (enabled,\nmode_override, image, network_mode, extra_args, working_dir). A nil\npointer means \"do not touch isolation config\". A present object is\napplied field-by-field ON TOP of the persisted overrides, so omitting a\nfield leaves it alone; clear an individual override by sending it\nexplicitly (` + "`" + `\"enabled\": null` + "`" + `, ` + "`" + `\"image\": \"\"` + "`" + `).","properties":{"enabled":{"description":"Enabled exists ONLY to detect and reject an echoed-back read. It is the\neffective state on the read surface and is never writable; see validate().","type":"boolean"},"enabled_override":{"description":"EnabledOverride is the tri-state per-server override — the RAW value, the\nsame one reads return as ` + "`" + `enabled_override` + "`" + `. It has THREE meaningful wire\nstates, and collapsing them is what silently un-isolated servers\n(GH #1142):\n - absent → leave the persisted override untouched\n - null → clear the override, back to inheriting the global\n - true / false → set an explicit opt-in / opt-out","type":"boolean"},"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"mode_override":{"description":"ModeOverride sets ` + "`" + `isolation.mode` + "`" + ` (\"docker\" | \"sandbox\" | \"none\").\nnil leaves the persisted value alone; an empty string clears it. An\nunrecognized value is rejected with a 400 rather than persisted.","type":"string"},"network_mode":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"httpapi.OAuthApprovalBody":{"properties":{"binding_revision":{"type":"string"},"client":{"$ref":"#/components/schemas/httpapi.OAuthClientChoice"},"mode":{"type":"string"},"profile":{"type":"string"},"replace_grant":{"type":"string"}},"type":"object"},"httpapi.OAuthClientChoice":{"properties":{"id":{"type":"string"},"new":{"$ref":"#/components/schemas/httpapi.OAuthNewClient"}},"type":"object"},"httpapi.OAuthDecisionResponse":{"properties":{"redirect_url":{"type":"string"}},"type":"object"},"httpapi.OAuthNewClient":{"properties":{"display_name":{"type":"string"},"id":{"type":"string"}},"type":"object"},"httpapi.OnboardingMarkRequest":{"properties":{"connect_step_status":{"description":"ConnectStepStatus is one of: \"\", \"completed\", \"skipped\". Empty\npreserves the existing value. The stored enum is wider (Spec 080\nFR-001): a \"skipped\" request for a previously untouched connect step\nis upgraded server-side to \"completed_external\" when the install\nshows positive evidence of an external connection (Spec 080 FR-002).\n\"completed_external\" is NOT accepted from clients — it must never be\npersisted without that server-verified evidence (edge case: \"never\nguess completed_external without positive evidence\").","type":"string"},"connected_client_id":{"description":"ConnectedClientID records a successful connect write for this client id\n(Spec 109-b FR-042, review round 6). The REST connect endpoint\n(POST /api/v1/connect/{client}) already records this itself on success;\nthis field exists so ` + "`" + `mcpproxy connect` + "`" + ` — which writes the client's\nconfig file directly, without going through that endpoint, so the\ncommand still works when no daemon is running — can relay the same\nevent to a daemon that IS running, keeping ClientConnectedAt in sync\nacross both surfaces. Must be a known id from the fixed connect client\nregistry (internal/connect.GetAllClients); any other value is rejected,\nmatching the field's \"bounded by the registry\" invariant\n(data-model.md §7).","type":"string"},"disconnected_client_id":{"description":"DisconnectedClientID relays a successful local CLI disconnect to a running\ndaemon, which cannot observe the CLI's direct config-file edit itself.\nLike ConnectedClientID, it is bounded to the fixed client registry.","type":"string"},"engaged":{"description":"Engaged marks the wizard as engaged (completed or explicitly skipped).\nOnce true, the wizard does not auto-show again.","type":"boolean"},"mark_shown":{"description":"MarkShown records the wizard's first display time if not already set.","type":"boolean"},"server_step_status":{"description":"ServerStepStatus is one of: \"\", \"completed\", \"skipped\". Empty\npreserves the existing value.","type":"string"}},"type":"object"},"httpapi.OnboardingStateResponse":{"properties":{"configured_server_count":{"description":"ConfiguredServerCount is the number of upstream MCP servers configured\nin mcpproxy (counts both enabled and disabled).","type":"integer"},"connected_client_count":{"description":"ConnectedClientCount is the number of supported clients currently\npointing at mcpproxy.","type":"integer"},"connected_client_ids":{"description":"ConnectedClientIDs are the identifiers of supported clients currently\npointing at mcpproxy. Drawn exclusively from the fixed adapter table —\nuser-entered values never appear here.","items":{"type":"string"},"type":"array","uniqueItems":false},"first_mcp_client_ever":{"description":"FirstMCPClientEver is true once any MCP client has successfully completed\nan ` + "`" + `initialize` + "`" + ` round-trip with this mcpproxy. Sourced from the Spec 044\nactivation bucket. Drives the Verify tab's \"green check\" state.","type":"boolean"},"has_configured_server":{"description":"HasConfiguredServer is true if at least one upstream MCP server is\nconfigured (regardless of current connection health).","type":"boolean"},"has_connected_client":{"description":"HasConnectedClient is true if at least one supported AI client currently\nhas mcpproxy registered in its config.","type":"boolean"},"has_usable_server":{"description":"HasUsableServer is true once at least one enabled, non-quarantined\nserver has usable health and at least one approved (non-disabled) tool.\nThis is the real \"the wizard has something to try\" signal:\nHasConfiguredServer only means a server entry exists, even while every\none of them sits quarantined, requires sign-in, or has zero approved\ntools. The Servers step and Setup badge use this instead of\nHasConfiguredServer, which is kept above for compatibility.\nHealthStatus.Usable is the shared\nreadiness contract used by every UI surface (Spec 109-c, tasks.md T051).","type":"boolean"},"incomplete_tab_count":{"description":"IncompleteTabCount is the number of wizard tabs whose state is incomplete.\nDrives the sidebar Setup entry's badge. Formula:\n +1 if HasConnectedClient == false\n +1 if HasUsableServer == false\n +1 if FirstMCPClientEver == false","type":"integer"},"mcp_clients_seen_ever":{"description":"MCPClientsSeenEver is the capped list of recognized client names that\nhave ever called this mcpproxy. Names come from the MCP ` + "`" + `initialize` + "`" + `\npayload's ` + "`" + `clientInfo.name` + "`" + ` field, sanitized. Surfaces on the Verify tab\nso the user can see whether their real IDE — not a test client — has\nconnected.","items":{"type":"string"},"type":"array","uniqueItems":false},"should_show_wizard":{"description":"ShouldShowWizard is the derived flag the frontend uses to decide\nwhether to auto-show. True when not engaged and IncompleteTabCount \u003e 0\n(Spec 046 v2 — semantics widened to also count the Verify tab).","type":"boolean"},"state":{"$ref":"#/components/schemas/storage.OnboardingState"},"usable_servers":{"description":"UsableServers lists the names behind HasUsableServer, for the Verify\nstep's suggested-prompt generator (FR-042): prompts are only built from\ntools of servers in this list, never from a quarantined or toolless one.","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileConflictResponse":{"properties":{"code":{"type":"string"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"description":"Always false","type":"boolean"},"used_by":{"$ref":"#/components/schemas/httpapi.ProfileUsedByData"}},"type":"object"},"httpapi.ProfileDeleteData":{"properties":{"anonymous_profile_moved_to":{"type":"string"},"deleted":{"type":"string"},"moved":{"$ref":"#/components/schemas/runtime.MovedRefs"}},"type":"object"},"httpapi.ProfileListData":{"properties":{"anonymous_profile":{"type":"string"},"profiles":{"items":{"$ref":"#/components/schemas/runtime.ProfileView"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileRenameData":{"properties":{"moved":{"$ref":"#/components/schemas/runtime.MovedRefs"},"profile":{"$ref":"#/components/schemas/runtime.ProfileView"}},"type":"object"},"httpapi.ProfileTryData":{"properties":{"hidden":{"items":{"$ref":"#/components/schemas/runtime.TryHidden"},"type":"array","uniqueItems":false},"hidden_by_profile":{"type":"integer"},"hidden_truncated":{"type":"boolean"},"results":{"items":{"additionalProperties":{},"type":"object"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileUsedByData":{"properties":{"anonymous_profile":{"type":"boolean"},"clients":{"items":{"$ref":"#/components/schemas/runtime.UsedByClient"},"type":"array","uniqueItems":false},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileViewData":{"properties":{"blocked_24h":{"type":"integer"},"calls_24h":{"type":"integer"},"code_execution":{"type":"boolean"},"description":{"type":"string"},"effective_code_execution":{"type":"boolean"},"effective_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"effective_unannotated":{"type":"string"},"is_legacy":{"type":"boolean"},"management_tools":{"type":"boolean"},"max_tier":{"type":"string"},"name":{"type":"string"},"servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"switchable_to":{"items":{"type":"string"},"type":"array","uniqueItems":false},"title":{"type":"string"},"tool_count":{"description":"ToolCount is the v2 field: indexed tools on the effective servers.\nDeprecated: use tool_counts.","type":"integer"},"tool_counts":{"$ref":"#/components/schemas/runtime.ToolCounts"},"tools":{"$ref":"#/components/schemas/config.ProfileToolRules"},"unannotated":{"type":"string"},"used_by":{"$ref":"#/components/schemas/runtime.UsedBy"}},"type":"object"},"httpapi.ProfileWriteData":{"properties":{"profile":{"$ref":"#/components/schemas/runtime.ProfileView"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.PutClientBindingRequest":{"properties":{"mode":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.RenameProfileRequest":{"properties":{"new_name":{"type":"string"}},"type":"object"},"httpapi.RevokeCredentialResponse":{"properties":{"changed":{"type":"boolean"}},"type":"object"},"httpapi.RotateClientRequest":{"properties":{"precondition_token":{"description":"PreconditionToken is the token of GET /connect/{client}/preview; it\nbinds a supported client's rotation to what the preview showed.","type":"string"}},"type":"object"},"httpapi.RotateClientResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"connect":{"$ref":"#/components/schemas/connect.ConnectResult"},"credential":{"type":"string"},"rotation":{"$ref":"#/components/schemas/httpapi.RotationState"},"snippet":{"$ref":"#/components/schemas/httpapi.ClientSnippet"}},"type":"object"},"httpapi.RotationState":{"properties":{"state":{"type":"string"}},"type":"object"},"httpapi.SetActiveProfileRequest":{"properties":{"active_profile":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.StaleReviewErrorResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"stale_tools":{"$ref":"#/components/schemas/httpapi.StaleToolsDetail"},"success":{"type":"boolean"}},"type":"object"},"httpapi.StaleToolsDetail":{"properties":{"changed":{"items":{"type":"string"},"type":"array","uniqueItems":false},"missing_blocks":{"items":{"type":"string"},"type":"array","uniqueItems":false},"unreviewed":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.TryProfileRequest":{"properties":{"limit":{"type":"integer"},"profile":{"$ref":"#/components/schemas/config.ProfileConfig"},"query":{"type":"string"}},"type":"object"},"httpapi.UndoConnectRequest":{"properties":{"backup_name":{"description":"BackupName is the bare filename (filepath.Base) of the backup returned as\nbackup_path by the preceding connect — a name, never a path. Undo resolves\nthe full path server-side by joining it with the client's own config\ndirectory, so a client-supplied value can never contribute a directory\ncomponent (traversal is impossible by construction). Empty means the\nconnect created the file (no prior file existed), so undo removes it.","type":"string"},"server_name":{"description":"Defaults to \"mcpproxy\"","type":"string"}},"type":"object"},"httpapi.UpdateFailureRequest":{"properties":{"stage":{"description":"Stage is the failure stage of the update session.","enum":["appcast","download","install","other"],"type":"string"}},"type":"object"},"httpapi.UpgradeAdminKeyHoldersRequest":{"properties":{"apply":{"type":"boolean"},"mode":{"type":"string"},"precondition_token":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.approveToolsRequest":{"properties":{"approve_all":{"type":"boolean"},"expected_hashes":{"additionalProperties":{"type":"string"},"description":"ExpectedHashes binds the approval to the reviewed definitions (Spec\n117 PR-2, #1566): tool name -\u003e the review's current_hash. Absent or\nnull is an unbound (legacy) request; {} is bound.","type":["object","null"]},"expected_incarnation":{"description":"ExpectedIncarnation binds the approval to the server the client\nreviewed (Spec 116 FR-017); 409 server_replaced on a mismatch. It is\nindependent of ExpectedHashes and the two may be sent together.","type":"integer"},"tools":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.attentionResponse":{"properties":{"count":{"type":"integer"},"generated_at":{"type":"string"},"items":{"items":{"$ref":"#/components/schemas/contracts.AttentionItem"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.bundleRollbackRequest":{"properties":{"digest":{"description":"Digest is the full 64-character lowercase hex SHA-256 of the target.","type":"string"},"embedded":{"description":"Embedded rolls back to the corpus compiled into this binary.","type":"boolean"},"path":{"description":"Path is where to find the target bundle (a hint only).","type":"string"}},"type":"object"},"httpapi.clientPresence":{"properties":{"active_sessions":{"type":"integer"},"blocked_24h":{"type":"integer"},"browser_login_disabled":{"type":"boolean"},"calls_24h":{"type":"integer"},"config_path":{"type":"string"},"connected":{"type":"boolean"},"connection_unverified":{"type":"boolean"},"credential_checked_at":{"type":"string"},"credential_state":{"$ref":"#/components/schemas/profile.CredentialState"},"credentials":{"description":"Spec 132: the client's credentials (API key and browser logins) and\nwhether browser login is off right now. Both exist only once browser\nlogin was used on this install; until then a row is exactly what it was.","items":{"$ref":"#/components/schemas/httpapi.ClientCredential"},"type":"array","uniqueItems":false},"display_name":{"type":"string"},"display_path":{"type":"string"},"expires_at":{"type":"string"},"icon":{"type":"string"},"id":{"type":"string"},"installed":{"type":"boolean"},"issuer":{"$ref":"#/components/schemas/auth.CredentialIssuer"},"kind":{"type":"string"},"last_seen":{"type":"string"},"lease":{"type":"boolean"},"profile":{"type":"string"},"profile_missing":{"type":"boolean"},"profile_mode":{"type":"string"},"profile_source":{"description":"profile_source is pin (locked) or binding (switchable) and is empty when\ncredential_state is not client.","type":"string"},"profile_state":{"type":"string"},"profile_title":{"type":"string"},"purpose":{"type":"string"},"reload_hint":{"type":"string"},"revoked_at":{"description":"Spec 115 lifecycle fields of the client's credential record (additive):\nwhen it was revoked, who issued it, its stated (unenforced) purpose,\nwhether it is a task lease (lifetime at issue \u003c= 24h) and whether its\nprofile still exists (ok | dangling | none).","type":"string"},"rotation_pending":{"type":"boolean"},"sessions":{"items":{"$ref":"#/components/schemas/httpapi.clientSession"},"type":"array","uniqueItems":false},"state":{"type":"string"},"token_name":{"type":"string"}},"type":"object"},"httpapi.clientSession":{"properties":{"id":{"type":"string"},"last_activity":{"type":"string"},"profile":{"description":"Profile and ProfileSource are the session's latest effective resolution\n(Spec 108-e FR-033); empty on legacy sessions.","type":"string"},"profile_source":{"type":"string"},"started_at":{"type":"string"},"work_session_id":{"type":"string"}},"type":"object"},"httpapi.clientsResponse":{"properties":{"clients":{"items":{"$ref":"#/components/schemas/httpapi.clientPresence"},"type":"array","uniqueItems":false},"routing":{},"warnings":{"items":{"$ref":"#/components/schemas/httpapi.ClientWarning"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.expectedIncarnationBody":{"properties":{"expected_incarnation":{"type":"integer"}},"type":"object"},"httpapi.securityApproveRequest":{"properties":{"block":{"items":{"type":"string"},"type":"array","uniqueItems":false},"expected_hashes":{"additionalProperties":{"type":"string"},"description":"ExpectedHashes binds the approval to the reviewed definitions (Spec\n117 PR-2, #1566): tool name -\u003e the review's current_hash. Absent or\nnull is an unbound (legacy) request; {} binds to the empty snapshot.\nIndependent of ExpectedIncarnation: a request may carry both, and the\ntwo refusals stay distinct (review_out_of_date vs server_replaced).","type":["object","null"]},"expected_incarnation":{"description":"ExpectedIncarnation binds the approval to the server the client\nreviewed (Spec 116 FR-017): a remove and re-add since then is refused\nwith 409 server_replaced and the replacement stays quarantined.","type":"integer"},"force":{"type":"boolean"}},"type":"object"},"management.BulkOperationResult":{"properties":{"errors":{"additionalProperties":{"type":"string"},"description":"Map of server name to error message","type":"object"},"failed":{"description":"Number of failed operations","type":"integer"},"successful":{"description":"Number of successful operations","type":"integer"},"total":{"description":"Total servers processed","type":"integer"}},"type":"object"},"observability.HealthResponse":{"properties":{"components":{"items":{"$ref":"#/components/schemas/observability.HealthStatus"},"type":"array","uniqueItems":false},"status":{"description":"\"healthy\" or \"unhealthy\"","type":"string"},"timestamp":{"type":"string"}},"type":"object"},"observability.HealthStatus":{"properties":{"error":{"type":"string"},"latency":{"type":"string"},"name":{"type":"string"},"status":{"description":"\"healthy\" or \"unhealthy\"","type":"string"}},"type":"object"},"observability.ReadinessResponse":{"properties":{"components":{"items":{"$ref":"#/components/schemas/observability.HealthStatus"},"type":"array","uniqueItems":false},"status":{"description":"\"ready\" or \"not_ready\"","type":"string"},"timestamp":{"type":"string"}},"type":"object"},"profile.AccessStepStatus":{"type":"string","x-enum-varnames":["AccessStepPass","AccessStepFail","AccessStepSkip"]},"profile.AccessSubjectKind":{"type":"string","x-enum-varnames":["AccessSubjectClient","AccessSubjectProfile","AccessSubjectToken","AccessSubjectAnonymous"]},"profile.BlockReason":{"type":"string","x-enum-varnames":["BlockReasonTier","BlockReasonRule","BlockReasonUnannotated","BlockReasonCodeExecution","BlockReasonManagement","BlockReasonServerScope"]},"profile.CredentialState":{"description":"Spec 108-f ClientView additions (data-model §7). The Spec 109 fields above\nare unchanged; everything below is additive.\n\ncredential_state is what the client's connection carries (client |\nadmin_key | none | revoked | expired | unknown). The stat-only list never\nreads a config: it reports the token store, else the last on-demand\nobservation (credential_checked_at says when), else unknown.","type":"string","x-enum-varnames":["CredentialStateClient","CredentialStateAdminKey","CredentialStateNone","CredentialStateRevoked","CredentialStateExpired","CredentialStateUnknown"]},"profile.ExplainStep":{"type":"string","x-enum-varnames":["StepCredential","StepProfile","StepServerInScope","StepToolRule","StepTierCap","StepTokenPermission","StepGlobalGate","StepServerState","StepToolApproval"]},"profile.ExplainVerdict":{"type":"string","x-enum-varnames":["ExplainVerdictAllowed","ExplainVerdictBlocked","ExplainVerdictHidden"]},"profile.FixAction":{"type":"string","x-enum-varnames":["FixAllowInProfile","FixClassifyInProfile","FixAddServerToProfile","FixMoveClient","FixEditToken","FixEnableServer","FixApproveTool","FixChangeSetting","FixReconnectClient"]},"profile.WarningCode":{"type":"string","x-enum-varnames":["WarningAnonymousDeniedByBindingGuard","WarningClientHoldsAdminKey","WarningClientCredentialExpiring","WarningClientRotationPending","WarningProfileMissing","WarningClientTokenNameConflict"]},"profile.WarningSeverity":{"type":"string","x-enum-varnames":["WarningSeverityWarn","WarningSeverityInfo"]},"runtime.AccessSuggestion":{"properties":{"block_reason":{"$ref":"#/components/schemas/profile.BlockReason"},"clients":{"items":{"type":"string"},"type":"array","uniqueItems":false},"count":{"type":"integer"},"first_seen":{"type":"string"},"fixes":{"description":"Fixes are the access explainer's remediations of the first failing step,\nin preference order. Empty for a deny rule and for the built-in tools.","items":{"$ref":"#/components/schemas/runtime.Fix"},"type":"array","uniqueItems":false},"last_seen":{"type":"string"},"needs_input":{"description":"NeedsInput names what a person must supply before a change is\napply-ready (classify: \"tier\").","items":{"type":"string"},"type":"array","uniqueItems":false},"note":{"type":"string"},"profile":{"type":"string"},"server":{"type":"string"},"suggestion":{"$ref":"#/components/schemas/runtime.SuggestionKind"},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false},"tool":{"description":"\"server:tool\", or the built-in name","type":"string"},"warning":{"description":"Warning is set for profile_code_execution and profile_management: both\nchange what a profile can do beyond tool access.","type":"string"}},"type":"object"},"runtime.BindingRef":{"properties":{"client_id":{"type":"string"},"mode":{"type":"string"},"profile":{"type":"string"},"token_name":{"type":"string"}},"type":"object"},"runtime.EffectiveCounts":{"properties":{"by_reason":{"additionalProperties":{"type":"integer"},"type":"object"},"callable":{"type":"integer"},"hidden":{"type":"integer"},"visible":{"type":"integer"}},"type":"object"},"runtime.EffectiveTool":{"properties":{"access":{"$ref":"#/components/schemas/runtime.ToolAccessView"},"classification_stale":{"type":"boolean"},"intrinsic_tier":{"type":"string"},"profile_tier":{"type":"string"},"server":{"type":"string"},"tool":{"type":"string"}},"type":"object"},"runtime.ExplainProfileView":{"properties":{"name":{"type":"string"},"source":{"type":"string"}},"type":"object"},"runtime.ExplainStepView":{"properties":{"detail":{"type":"string"},"status":{"$ref":"#/components/schemas/profile.AccessStepStatus"},"step":{"$ref":"#/components/schemas/profile.ExplainStep"}},"type":"object"},"runtime.ExplainSubjectView":{"properties":{"kind":{"$ref":"#/components/schemas/profile.AccessSubjectKind"},"name":{"type":"string"}},"type":"object"},"runtime.Fix":{"properties":{"action":{"$ref":"#/components/schemas/profile.FixAction"},"label":{"type":"string"},"profile":{"description":"Profile is set for move_client only: the destination profile slug the fix\nmoves the client to. Target stays the client id (UIs navigate by it) and\nLabel carries the title, so neither can name the slug.","type":"string"},"step":{"type":"string","x-enum-varnames":["StepCredential","StepProfile","StepServerInScope","StepToolRule","StepTierCap","StepTokenPermission","StepGlobalGate","StepServerState","StepToolApproval"]},"target":{"type":"string"}},"type":"object"},"runtime.GuardFix":{"properties":{"kind":{"type":"string"},"target":{"type":"string"}},"type":"object"},"runtime.MovedRefs":{"properties":{"clients":{"items":{"type":"string"},"type":"array","uniqueItems":false},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"runtime.ProfilePatch":{"properties":{"changes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"profile":{"type":"string"},"proposed":{"$ref":"#/components/schemas/config.ProfileConfig"}},"type":"object"},"runtime.ProfileView":{"properties":{"blocked_24h":{"type":"integer"},"calls_24h":{"type":"integer"},"code_execution":{"type":"boolean"},"description":{"type":"string"},"effective_code_execution":{"type":"boolean"},"effective_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"effective_unannotated":{"type":"string"},"is_legacy":{"type":"boolean"},"management_tools":{"type":"boolean"},"max_tier":{"type":"string"},"name":{"type":"string"},"servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"switchable_to":{"items":{"type":"string"},"type":"array","uniqueItems":false},"title":{"type":"string"},"tool_count":{"description":"ToolCount is the v2 field: indexed tools on the effective servers.\nDeprecated: use tool_counts.","type":"integer"},"tool_counts":{"$ref":"#/components/schemas/runtime.ToolCounts"},"tools":{"$ref":"#/components/schemas/config.ProfileToolRules"},"unannotated":{"type":"string"},"used_by":{"$ref":"#/components/schemas/runtime.UsedBy"}},"type":"object"},"runtime.SuggestionKind":{"type":"string","x-enum-varnames":["SuggestAllow","SuggestAddServer","SuggestClassify","SuggestNone"]},"runtime.ToolAccessView":{"properties":{"callable":{"type":"boolean"},"reason":{"type":"string"},"visible":{"type":"boolean"}},"type":"object"},"runtime.ToolCounts":{"properties":{"destructive":{"type":"integer"},"read":{"type":"integer"},"unannotated_hidden":{"type":"integer"},"write":{"type":"integer"}},"type":"object"},"runtime.TryHidden":{"properties":{"reason":{"type":"string"},"server":{"type":"string"},"tool":{"type":"string"}},"type":"object"},"runtime.UsedBy":{"properties":{"anonymous_profile":{"type":"boolean"},"clients":{"items":{"$ref":"#/components/schemas/runtime.UsedByClient"},"type":"array","uniqueItems":false},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"runtime.UsedByClient":{"properties":{"id":{"type":"string"},"mode":{"type":"string"}},"type":"object"},"runtime.WarningAction":{"properties":{"kind":{"type":"string"},"target":{"type":"string"}},"type":"object"},"scanner.BundleInfo":{"properties":{"authority":{"description":"Authority is the signing root serving this bundle: \"publisher\" (the\nembedded default, or verified against a publisher key), \"operator\", or \"\"\nfor an unsigned external bundle.","type":"string"},"bundle_version":{"description":"BundleVersion / SchemaVersion are the corpus's own declared versions.","type":"string"},"coverage_degraded":{"description":"CoverageDegraded suspends scan-mode auto-approval; DegradedReason says\nwhy (one of the Degraded* constants).","type":"boolean"},"declared_skipped":{"type":"integer"},"degraded_reason":{"type":"string"},"fingerprint":{"description":"Fingerprint is the first 12 hex chars of the SHA-256 of the corpus bytes:\na stable identity an operator (or automation) can compare across hosts\nwithout shipping the whole file around.","type":"string"},"full_digest":{"description":"FullDigest is the complete lowercase-hex SHA-256 of the bundle bytes —\nthe ONLY value rollback accepts (FR-010). Fingerprint stays the 12-hex\nhuman label beside it.","type":"string"},"generated_at":{"description":"GeneratedAt is the corpus freshness stamp. It is the bundle's own\n` + "`" + `generated_at` + "`" + ` key when present; for a file-sourced bundle without one it\nfalls back to the file's modification time, so a years-stale corpus is\ndistinguishable from a fresh export.","type":"string"},"last_activated_at":{"description":"LastActivatedAt is when the serving external bundle was activated; nil\nfor the embedded default.","type":"string"},"last_checked_at":{"description":"LastCheckedAt is the end of the most recent pipeline run, including\nno-op runs the idempotence short-circuit skipped.","type":"string"},"last_rejection":{"$ref":"#/components/schemas/scanner.BundleRejection"},"load_error":{"description":"LoadError is the reason the LAST configured-path load failed, if any. The\npreviously active (or embedded) corpus stays live — a bundle problem must\nnever leave the scanner with no signatures — but the failure is surfaced\nhere rather than swallowed.","type":"string"},"loaded_at":{"description":"LoadedAt is when this corpus became active in this process.","type":"string"},"path":{"description":"Path is the configured filesystem path, when Source is \"file\".","type":"string"},"pinned":{"description":"Pinned is true while an operator rollback pin governs activation.","type":"boolean"},"refresh":{"$ref":"#/components/schemas/scanner.BundleRefreshStatus"},"reprotect":{"$ref":"#/components/schemas/scanner.BundleReprotectStatus"},"rollback":{"description":"Rollback is true when the active bundle was activated by an explicit\nrollback.","type":"boolean"},"runnable_rules":{"description":"RunnableRules is how many rules are LIVE in the offline tier; SkippedRules\nand DeclaredSkipped are the not-runnable / bundle-declared-skipped\nremainder (FR-006/FR-007) — un-evaluated coverage, never clean coverage.","type":"integer"},"schema_version":{"type":"string"},"sequence":{"description":"Sequence is the manifest sequence as published (decimal string), \"\" when\nthe bundle carries none.","type":"string"},"signature_count":{"description":"SignatureCount is the bundle's self-declared signature count.","type":"integer"},"signature_verified":{"description":"SignatureVerified reports whether the active bundle's detached signature\nverified. Always false for the embedded default (it is binary-trusted).","type":"boolean"},"skipped_rules":{"type":"integer"},"source":{"description":"Source is BundleSourceEmbedded, BundleSourceFile or BundleSourceFetch.","type":"string"},"stale":{"description":"Stale and StaleAfterDays are computed at read time next to\nStalenessDays; a future generated_at is never stale. StaleAfterDays nil\nmeans the flag is not evaluated.","type":"boolean"},"stale_after_days":{"type":"integer"},"staleness_days":{"description":"StalenessDays is the whole days since GeneratedAt (nil when unknown).","type":"integer"},"trust_epoch":{"description":"TrustEpoch is the epoch the bundle was published under.","type":"integer"}},"type":"object"},"scanner.BundleRefreshStatus":{"description":"Refresh is the refresh-cycle status (nil before any cycle or setting is\nknown). Reprotect is the post-activation re-protection sweep status,\nset from the server through SetReprotectStatus.","properties":{"consecutive_failures":{"type":"integer"},"fetch_enabled":{"type":"boolean"},"fetch_host":{"description":"FetchHost is the host of the configured fetch URL (\"\" when none).","type":"string"},"fetch_reason":{"type":"string"},"fetch_state":{"description":"FetchState and FetchReason are the fetch leg's own last answer (one of the\nRefreshOutcome* values and its reason), kept apart from LastOutcome: a file\nactivation owns the merged cycle outcome but must not hide a fetch leg that\ncannot run (B16 warning 3).","type":"string"},"interval_seconds":{"type":"integer"},"last_attempt_at":{"type":"string"},"last_outcome":{"type":"string"},"last_reason":{"type":"string"},"last_trigger":{"description":"LastTrigger, LastOutcome and LastReason use the closed vocabularies above.","type":"string"},"next_check_at":{"type":"string"}},"type":"object"},"scanner.BundleRejection":{"description":"LastRejection is the most recent refused candidate. It is retained\nacross a later successful load so \"what did it refuse, and when\"\nsurvives.","properties":{"at":{"type":"string"},"detail":{"description":"Detail is a short human string (which ceiling, which key id, which\nepoch, the bundlesig contract code). Never parsed.","type":"string"},"reason":{"description":"Reason is one of the Reject* constants; the only field to branch on.","type":"string"}},"type":"object"},"scanner.BundleReprotectStatus":{"properties":{"last_completed_at":{"type":"string"},"reason":{"description":"Reason qualifies suspended and failed (for example\nReprotectReasonAutoBaselineScanOff).","type":"string"},"servers_scanned":{"type":"integer"},"servers_with_hits":{"type":"integer"},"state":{"description":"State is one of the ReprotectState* constants.","type":"string"}},"type":"object"},"secureenv.EnvConfig":{"description":"Environment configuration for secure variable filtering","properties":{"allowed_system_vars":{"items":{"type":"string"},"type":"array","uniqueItems":false},"custom_vars":{"additionalProperties":{"type":"string"},"type":"object"},"enhance_path":{"description":"Enable PATH enhancement for Launchd scenarios","type":"boolean"},"forward_proxy_env":{"description":"ForwardProxyEnv opts in to forwarding the ambient HTTP(S)/ALL/NO/FTP proxy\nenvironment variables to spawned upstream servers (MCP-2769). It is OFF by\ndefault and deliberately kept out of the AllowedSystemVars default list:\nproxy URLs frequently carry credentials (http://user:pass@proxy), so\nforwarding them to every stdio upstream is a credential-leak risk. When\nenabled, values are forwarded with their userinfo (credentials) redacted.","type":"boolean"},"inherit_system_safe":{"type":"boolean"}},"type":"object"},"storage.ClientCredentialObservation":{"properties":{"at":{"type":"string"},"state":{"type":"string"}},"type":"object"},"storage.OnboardingState":{"description":"State is the persisted wizard engagement record. Engaged is true once\nthe wizard was shown and the user completed or skipped it.","properties":{"client_connected_at":{"additionalProperties":{"type":"string"},"description":"ClientConnectedAt records, per client id from the fixed connect client\nregistry (internal/connect.GetAllClients — never user input), the last\ntime a connect write succeeded for that client (Spec 109-b FR-042).\nWritten by the connect success path through UpdateOnboardingState so a\nconcurrent onboarding/mark write can never drop it. Consumed by the\nVerify step / presence layer to tell \"connected, never seen\" apart from\n\"connected seconds ago, hasn't reconnected yet\".","type":"object"},"client_credential_observed":{"additionalProperties":{"$ref":"#/components/schemas/storage.ClientCredentialObservation"},"description":"ClientCredentialObserved records, per client id, the LAST credential\nclassification an on-demand read produced (Spec 108-f FR-025, F11): what\nthe client's config held (client | admin_key | none | revoked | expired)\nand when it was read. The stat-only GET /clients listing never reads a\nconfig (Spec 075: no macOS App-Data prompt from a list), so this is how\nit still reports a client that holds the admin key across restarts. It is\nwritten only when the classification CHANGES, by every on-demand read\n(GET /clients/{id}, GET /connect/{client}, the admin-key upgrade preview,\na connect write) and deleted on disconnect. Additive: an older binary\nignores it, and a record without it reads as \"unknown\".","type":"object"},"client_disconnected_at":{"additionalProperties":{"type":"string"},"type":"object"},"client_last_seen":{"additionalProperties":{"type":"string"},"description":"ClientLastSeen records the latest MCP initialize for a recognised client\nalias. It is intentionally kept with onboarding state: presence is a\nlocal UI concern and must still work when telemetry is disabled.","type":"object"},"connect_step_status":{"description":"ConnectStepStatus is one of: \"\", \"completed\", \"completed_external\",\n\"skipped\" (Spec 080 FR-001). \"completed_external\" records a dismissal\nwhere the connect step was untouched but the install was already\nconnected outside the wizard (CLI, ConnectModal, manual config).","type":"string"},"engaged":{"description":"Engaged is true once the wizard was shown and the user completed or\nskipped it. Once true, the wizard does not auto-show again, even if\nstate regresses (e.g. user disconnects all clients).","type":"boolean"},"engaged_at":{"description":"EngagedAt is the timestamp of completion or explicit skip.","type":"string"},"first_shown_at":{"description":"FirstShownAt is the timestamp of first wizard render.","type":"string"},"server_step_status":{"description":"ServerStepStatus is one of: \"\", \"completed\", \"skipped\".","type":"string"}},"type":"object"},"telemetry.DiagnosticsCounters":{"properties":{"current_error_codes":{"additionalProperties":{"type":"integer"},"description":"CurrentErrorCodes is the STANDING state at heartbeat time: stable MCPX_\ncode -\u003e number of configured servers currently in that state. It is not\na counter and is never persisted — it is recomputed each heartbeat from\nthe supervisor's live stateview.\n\nSchema v11 (MCP-2967). It exists because error_code_counts_24h became\nedge-triggered in the same change: previously the supervisor re-counted\nevery standing failure on its 30s reconcile ticker, so a parked install\ninflated the counter by ~2880/day/server. Edge-triggering alone would\nhave swung the error to the other side — the 24h window decays, this\nstruct is omitempty via isZero(), so a permanently broken install would\nemit once and then disappear from the payload entirely, and absent reads\nas zero. The two fields answer different questions and are only correct\ntogether: \"how often did something newly break\" and \"how many servers\nare broken right now\".\n\nSafe: only MCPX_* enum constants as keys, never server names, URLs,\ncommands, or free text; values are non-negative server counts.","type":"object"},"error_code_counts_24h":{"additionalProperties":{"type":"integer"},"description":"ErrorCodeCounts24h maps stable MCPX_ code strings to 24h occurrence counts.\nSafe: only MCPX_* enum constants are stored here, never free text, paths,\nserver names, or user-entered values.","type":"object"},"fix_attempted_24h":{"description":"FixAttempted24h counts POST /api/v1/diagnostics/fix calls in the last 24h.","type":"integer"},"fix_succeeded_24h":{"description":"FixSucceeded24h counts fix invocations with outcome=\"success\" in the last 24h.","type":"integer"},"unique_codes_ever":{"description":"UniqueCodesEver is the cardinality of the all-time error code set.\nBounded by the MCPX_ catalog size (~30 codes), never approaches PII risk.","type":"integer"}},"type":"object"},"telemetry.FeedbackContext":{"properties":{"anonymous_id":{"description":"AnonymousID is the install's telemetry anonymous ID (heartbeat value).","type":"string"},"arch":{"type":"string"},"connected_server_count":{"type":"integer"},"diagnostics":{"$ref":"#/components/schemas/telemetry.DiagnosticsCounters"},"edition":{"type":"string"},"go_version":{"type":"string"},"last_error_code":{"description":"LastErrorCode is the most recent MCPX_* error code.","type":"string"},"last_startup_outcome":{"description":"LastStartupOutcome is the previous startup's outcome word.","type":"string"},"machine_id":{"description":"MachineID is the hashed machine identifier (heartbeat value).","type":"string"},"os":{"type":"string"},"previous_shutdown":{"description":"PreviousShutdown is how the previous run ended (clean, crash, ...).","type":"string"},"routing_mode":{"type":"string"},"server_count":{"type":"integer"},"tool_count":{"type":"integer"},"uptime_minutes":{"description":"UptimeMinutes is the daemon's uptime. Omitted from short-lived CLI\nsubmissions, where the process uptime says nothing about the daemon.","type":"integer"},"version":{"type":"string"}},"type":"object"},"telemetry.FeedbackRequest":{"properties":{"category":{"description":"bug, feature, other","type":"string"},"context":{"$ref":"#/components/schemas/telemetry.FeedbackContext"},"email":{"type":"string"},"message":{"type":"string"}},"type":"object"},"telemetry.FeedbackResponse":{"properties":{"error":{"type":"string"},"issue_url":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}},"securitySchemes":{"ApiKeyAuth":{"description":"API key authentication via query parameter. Use ?apikey=your-key","in":"query","name":"apikey","type":"apiKey"}}}, "info": {"contact":{"name":"MCPProxy Support","url":"https://github.com/smart-mcp-proxy/mcpproxy-go"},"description":"{{escape .Description}}","license":{"name":"MIT","url":"https://opensource.org/licenses/MIT"},"title":"{{.Title}}","version":"{{.Version}}"}, "externalDocs": {"description":"","url":""}, - "paths": {"/api/v1/access/explain":{"get":{"description":"For one subject (exactly one of client=\u003cid\u003e, token=\u003cname\u003e, profile=\u003cname\u003e or anonymous=true) and one upstream tool (server:tool), returns the ordered chain of gates a real call would meet - credential, profile, server_in_scope, tool_rule, tier_cap, token_permission, global_gate, server_state, tool_approval - the overall verdict (allowed, blocked, hidden), the first failing step and the fixes for it in preference order. The chain is the one every discovery and dispatch path walks, so ` + "`" + `allowed` + "`" + ` equals what a real call does. Built-in management tools are not explained (400). A client credential is explained with client=, never token=. Administrators only.","parameters":[{"description":"Upstream tool as server:tool","in":"query","name":"tool","required":true,"schema":{"type":"string"}},{"description":"Client id","in":"query","name":"client","schema":{"type":"string"}},{"description":"Regular agent token name","in":"query","name":"token","schema":{"type":"string"}},{"description":"Profile name","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Explain an anonymous (credential-less) caller","in":"query","name":"anonymous","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The explanation"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Not exactly one subject, a built-in tool, or token=client-\u003cid\u003e"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"client / token / profile not found"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Explain why a tool is or is not reachable","tags":["access"]}},"/api/v1/access/suggest":{"get":{"description":"Reads the profile refusals in the activity log over a look-back window and groups them by profile, tool and block reason. Each group is re-checked with the access explainer, so tools that are already reachable drop out, and carries the explainer's fixes. A deny-rule block is reported and never offered for widening; an unannotated tool is never given a tier. Nothing is applied. patch=true also returns the proposed profile document per profile (the body PUT /api/v1/profiles/{name} takes).","parameters":[{"description":"Look-back window: a duration such as 90m, 24h or 7d (default 24h; the audit-log retention is the only limit)","in":"query","name":"since","schema":{"type":"string"}},{"description":"Only refusals under this profile","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Only refusals of this token","in":"query","name":"token","schema":{"type":"string"}},{"description":"Also return the proposed profile document per profile","in":"query","name":"patch","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The suggestions"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid since"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Suggest profile changes from blocked calls","tags":["access"]}},"/api/v1/activity":{"get":{"description":"Returns paginated list of activity records with optional filtering","parameters":[{"description":"Filter by activity type(s), comma-separated for multiple (Spec 024)","in":"query","name":"type","schema":{"enum":["tool_call","policy_decision","quarantine_change","server_change","system_start","system_stop","internal_tool_call","config_change","preflight","prompt_get","profile_change","upstream_event"],"type":"string"}},{"description":"Filter by server name","in":"query","name":"server","schema":{"type":"string"}},{"description":"Filter by tool name","in":"query","name":"tool","schema":{"type":"string"}},{"description":"Filter by MCP transport session ID","in":"query","name":"session_id","schema":{"type":"string"}},{"description":"Filter by work session (one client, one project, across reconnects)","in":"query","name":"work_session_id","schema":{"type":"string"}},{"description":"Filter by status","in":"query","name":"status","schema":{"enum":["success","error","blocked","rejected"],"type":"string"}},{"description":"Filter by intent operation type (Spec 018)","in":"query","name":"intent_type","schema":{"enum":["read","write","destructive"],"type":"string"}},{"description":"Filter by HTTP request ID for log correlation (Spec 021)","in":"query","name":"request_id","schema":{"type":"string"}},{"description":"Filter by parent call id — returns the sub-calls one code_execution issued","in":"query","name":"parent_id","schema":{"type":"string"}},{"description":"Filter by call-error class (Spec 113-c)","in":"query","name":"error_class","schema":{"enum":["network","timeout","http","jsonrpc","tool_error","session_terminated","auth","proxy_policy","proxy_internal","cancelled"],"type":"string"}},{"description":"Filter by fault domain (Spec 113-c)","in":"query","name":"fault_domain","schema":{"enum":["upstream","proxy","client"],"type":"string"}},{"description":"Include successful call_tool_* internal tool calls (default: false, excluded to avoid duplicates)","in":"query","name":"include_call_tool","schema":{"type":"boolean"}},{"description":"Filter by sensitive data detection (true=has detections, false=no detections)","in":"query","name":"sensitive_data","schema":{"type":"boolean"}},{"description":"Filter by specific detection type (e.g., 'aws_access_key', 'credit_card')","in":"query","name":"detection_type","schema":{"type":"string"}},{"description":"Filter by severity level","in":"query","name":"severity","schema":{"enum":["critical","high","medium","low"],"type":"string"}},{"description":"Alias of token (Spec 028)","in":"query","name":"agent","schema":{"type":"string"}},{"description":"Filter by the token in effect for the call; - selects records with no token (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Filter by the profile in effect for the call; - selects records with no profile (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Filter by client id; - selects records with no client (Spec 108)","in":"query","name":"client","schema":{"type":"string"}},{"description":"Filter by the client's self-reported name (advisory; Spec 108)","in":"query","name":"client_name","schema":{"type":"string"}},{"description":"Filter by auth type (Spec 028)","in":"query","name":"auth_type","schema":{"enum":["admin","agent"],"type":"string"}},{"description":"Filter activities after this time (RFC3339)","in":"query","name":"start_time","schema":{"type":"string"}},{"description":"Filter activities before this time (RFC3339)","in":"query","name":"end_time","schema":{"type":"string"}},{"description":"Maximum records to return (1-100, default 50)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Pagination offset (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Omit arguments, response and metadata except a contextual whitelist (intent.reason, intent.operation_type, decision, reason, client_name, client_version) (default: false). For clients that render summary fields only; has_sensitive_data is still derived before metadata is dropped.","in":"query","name":"exclude_payloads","schema":{"type":"boolean"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"List activity records","tags":["Activity"]}},"/api/v1/activity/export":{"get":{"description":"Exports activity records in JSON Lines or CSV format for compliance","parameters":[{"description":"Export format: json (default) or csv","in":"query","name":"format","schema":{"type":"string"}},{"description":"Filter by activity type","in":"query","name":"type","schema":{"type":"string"}},{"description":"Filter by server name","in":"query","name":"server","schema":{"type":"string"}},{"description":"Filter by tool name","in":"query","name":"tool","schema":{"type":"string"}},{"description":"Filter by MCP transport session ID","in":"query","name":"session_id","schema":{"type":"string"}},{"description":"Filter by work session (one client, one project, across reconnects)","in":"query","name":"work_session_id","schema":{"type":"string"}},{"description":"Filter by status","in":"query","name":"status","schema":{"type":"string"}},{"description":"Filter by HTTP request ID for log correlation (Spec 021)","in":"query","name":"request_id","schema":{"type":"string"}},{"description":"Filter by parent call id — exports the sub-calls one code_execution issued","in":"query","name":"parent_id","schema":{"type":"string"}},{"description":"Filter by call-error class (Spec 113-c)","in":"query","name":"error_class","schema":{"enum":["network","timeout","http","jsonrpc","tool_error","session_terminated","auth","proxy_policy","proxy_internal","cancelled"],"type":"string"}},{"description":"Filter by fault domain (Spec 113-c)","in":"query","name":"fault_domain","schema":{"enum":["upstream","proxy","client"],"type":"string"}},{"description":"Alias of token (Spec 028)","in":"query","name":"agent","schema":{"type":"string"}},{"description":"Filter by the token in effect for the call; - selects records with no token (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Filter by the profile in effect for the call; - selects records with no profile (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Filter by client id; - selects records with no client (Spec 108)","in":"query","name":"client","schema":{"type":"string"}},{"description":"Filter by the client's self-reported name (advisory; Spec 108)","in":"query","name":"client_name","schema":{"type":"string"}},{"description":"Filter activities after this time (RFC3339)","in":"query","name":"start_time","schema":{"type":"string"}},{"description":"Filter activities before this time (RFC3339)","in":"query","name":"end_time","schema":{"type":"string"}},{"description":"Maximum records to export (1-50000, default 10000)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Pagination offset (default 0)","in":"query","name":"offset","schema":{"type":"integer"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"type":"string"}},"application/x-ndjson":{"schema":{"type":"string"}},"text/csv":{"schema":{"type":"string"}}},"description":"Streamed activity records"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Export activity records","tags":["Activity"]}},"/api/v1/activity/summary":{"get":{"description":"Returns aggregated activity statistics for a time period","parameters":[{"description":"Time period: 1h, 24h (default), 7d, 30d","in":"query","name":"period","schema":{"type":"string"}},{"description":"Group by: server, tool (optional)","in":"query","name":"group_by","schema":{"type":"string"}},{"description":"Alias of token (Spec 028)","in":"query","name":"agent","schema":{"type":"string"}},{"description":"Count only records made under this token; - selects records with no token (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Count only records made under this profile; - selects records with no profile (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Count only records made by this client id; - selects records with no client (Spec 108)","in":"query","name":"client","schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Get activity summary statistics","tags":["Activity"]}},"/api/v1/activity/usage":{"get":{"description":"Returns the actor-owned usage aggregate (per-tool rollup + timeline + tokens-saved headline) for the Web UI usage graphs (Spec 069). Served from an in-memory snapshot — never a per-request full-log scan. Per-tool metrics are lifetime-cumulative; ` + "`" + `window` + "`" + ` scopes the timeline and filters the tool list to tools active within the span.","parameters":[{"description":"Time window for timeline + tool-list membership","in":"query","name":"window","schema":{"enum":["24h","7d","all"],"type":"string"}},{"description":"Filter to one server","in":"query","name":"server","schema":{"type":"string"}},{"description":"Filter to one tool","in":"query","name":"tool","schema":{"type":"string"}},{"description":"Filter to tools with activity of this status","in":"query","name":"status","schema":{"enum":["success","error","blocked","rejected"],"type":"string"}},{"description":"Top-N tools by sort key; remainder folded into 'other' (default 20)","in":"query","name":"top","schema":{"type":"integer"}},{"description":"Ranking key for the per-tool list","in":"query","name":"sort","schema":{"enum":["calls","resp_bytes","error_rate","p95"],"type":"string"}},{"description":"Alias of token (Spec 028)","in":"query","name":"agent","schema":{"type":"string"}},{"description":"Restrict to calls made under this token; - selects records with no token. Computed from a window-bounded scan (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Restrict to calls made under this profile; - selects records with no profile. Computed from a window-bounded scan (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Restrict to calls made by this client id; - selects records with no client. Computed from a window-bounded scan (Spec 108)","in":"query","name":"client","schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Get usage statistics aggregate","tags":["Activity"]}},"/api/v1/activity/{id}":{"get":{"description":"Returns full details for a single activity record","parameters":[{"description":"Activity record ID (ULID)","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Not Found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Get activity record details","tags":["Activity"]}},"/api/v1/annotations/coverage":{"get":{"description":"Reports how many upstream tools have MCP annotations vs don't, broken down by server","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Annotation coverage report"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get annotation coverage report","tags":["annotations"]}},"/api/v1/attention":{"get":{"description":"One list, one count, every surface (Web UI, macOS tray/Home, CLI) reads from it. Filtered per caller: an administrator sees every item; a scoped caller (agent token, or a non-admin server-edition OAuth user session) sees only server items whose server it may enumerate (for a profile-pinned token: servers within its pin); every other subject type (client, setting) and the skill_review kind (Spec 125 held skills) are administrator-only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.attentionResponse"}}},"description":"The needs-attention list"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the needs-attention list","tags":["attention"]}},"/api/v1/catalog/search":{"get":{"description":"Fans out to every enabled catalog source (registry) in parallel, merges, de-duplicates and ranks the results (FR-060/061). An empty q returns official + popular sections instead of a flat list. Open to any authenticated caller — added is the only field filtered per caller scope (FR-007).","parameters":[{"description":"Free-text search","in":"query","name":"q","schema":{"type":"string"}},{"description":"Narrow to one catalog source id","in":"query","name":"source","schema":{"type":"string"}},{"description":"Not supported: catalog entries carry no tags; a non-empty value returns 400","in":"query","name":"tag","schema":{"type":"string"}},{"description":"Max results (default 20, max 50)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"tag filtering is not supported"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"configured servers could not be listed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Search the server catalog across every enabled source","tags":["catalog"]}},"/api/v1/clients":{"get":{"description":"Lists every client row (supported, other and custom) with its presence, its credential and its profile binding, plus response-level warnings. The list is content-read-free (Spec 075): credential_state comes from the token store, else the last on-demand observation (credential_checked_at), else unknown. It runs only the time-based half of the rotation reconciler. The profile and client filters match the CURRENT binding and are applied AFTER warnings are computed over the full set.","parameters":[{"description":"Rows whose active credential is bound to this profile; - = bound to All servers","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Exact client id","in":"query","name":"client","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Client rows, routing and warnings"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List clients","tags":["clients"]},"post":{"description":"Creates a per-client credential for a client that is NOT in the connect registry (a script, a CI job, an editor without a connect adapter). The secret (mcp_cli_...) is returned ONCE, with a paste-ready snippet that carries it in the X-API-Key header. The id follows the client-id rule (lower-case letters, digits, '-' or '_', at most 56 characters) and must not be a supported client's id. A named profile binds the credential locked unless mode says otherwise. Refused with 409 binding_bypassable_without_auth when the binding would be bypassable while require_mcp_auth is off (FR-008a), and 409 conflicting_token when a regular token holds client-\u003cid\u003e. Every value (id, display_name, profile, mode, expires_in, purpose) passes the shared secret-shaped input screen first: a credential, the API key or a detector-flagged secret answers 400 secret_in_argument naming the field, and nothing is minted. A malformed body answers a sanitized 400 that never echoes a caller key or value. Writes one profile_change record with change issue (Spec 115) and publishes credentials.changed. Personal edition only.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.CreateClientRequest"}}},"description":"id (required), optional display_name, profile, mode, expires_in and purpose","required":true},"responses":{"201":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The new client row, its credential (once) and a snippet"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"binding_bypassable_without_auth, or conflicting_token (ClientCredentialConflictResponse)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add a custom client","tags":["clients"]}},"/api/v1/clients/bulk-assign":{"post":{"description":"Moves every client credential bound to from_profile (\"\" = All servers) onto to_profile (\"\" = All servers). The guard and the credential precondition apply PER CLIENT: a refused client is reported in skipped[] with the code the single operation returns, the others move and each writes its own assign record and emits client.binding_changed. Personal edition only.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BulkAssignRequest"}}},"description":"from_profile and to_profile (both required; empty = All servers) and optional mode","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Moved client ids and the clients that were skipped"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Move every client of one profile to another","tags":["clients"]}},"/api/v1/clients/upgrade-admin-key-holders":{"post":{"description":"Without apply: classifies every supported client whose config still holds the instance admin API key (an on-demand read per client) and returns preview[] (display path, what would change, the masked credential mcp_cli_••••, the binding and a precondition_token per client), a combined precondition_token, and guard when the whole request would be refused by FR-008a; next_step is rotate_admin_api_key when nothing holds the key. Nothing is written or minted. With apply=true: recomputes the preview, refuses with 409 precondition_failed when a sent precondition_token no longer matches, runs the FR-008a guard over the WHOLE request (409 binding_bypassable_without_auth, nothing minted, no file written), then connects each client with force bound to its own token; one client's failure does not stop the others. Each mint writes its own assign record. The guard only applies when a named profile is given. Personal edition only.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.UpgradeAdminKeyHoldersRequest"}}},"description":"Optional profile and mode for every upgraded client; apply and precondition_token"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"UpgradePreview (no apply) or UpgradeResult (apply)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"precondition_failed, or binding_bypassable_without_auth"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Upgrade every client that holds the admin API key","tags":["clients"]}},"/api/v1/clients/{client}":{"delete":{"description":"Revokes the client's credential; it stops authenticating at once. With disconnect=true a SUPPORTED client's mcpproxy entry is removed from its config FIRST, but the credential is revoked either way: revocation never waits for a config write, so a failed write (for example a macOS App-Data denial) leaves the client cut off and is reported as disconnected:false with disconnect_error. A client with no credential record is 409 no_client_credential. disconnect=true on a custom client is ignored. Writes one forget record naming the revoked token. The FR-008a guard is not involved: revoking only removes a binding.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}},{"description":"Also remove the entry from the client's config (supported clients)","in":"query","name":"disconnect","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Revoked token name and what happened to the config entry"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"no_client_credential"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Forget a client (revoke its credential)","tags":["clients"]},"get":{"description":"Returns one client row with its sessions (newest 20, each with its latest effective profile). This is the only read that may open the client's config file: it runs the full rotation reconciler first, classifies the credential the config holds and records the observation. No scope filter is honoured on this route.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Client row"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"client not found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get one client","tags":["clients"]}},"/api/v1/clients/{client}/binding":{"put":{"description":"Changes the profile binding (and optionally the locked/switchable mode) of a\nclient that holds an active client credential. One service operation shared by\nevery surface: it updates the credential in the token store, clears the stored\nset_profile selection of every live session of that credential, sends\nnotifications/tools/list_changed to each, emits client.binding_changed and writes\none profile_change activity record. It never touches the client's config file.\nA client without an active client credential (none, admin key, revoked or expired)\nis refused with 409 no_client_credential and nothing is minted or written. A\nreassignment that would leave the binding bypassable while require_mcp_auth is off\nis refused with 409 binding_bypassable_without_auth (FR-008a). Personal edition only.","parameters":[{"description":"Client id (lower-case letters, digits, '-' or '_', at most 56 characters)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.PutClientBindingRequest"}}},"description":"profile (required; empty = All servers) and optional mode (locked|switchable)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The client row after the change, with its warnings"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"no_client_credential, connect_in_progress (a connect of this client is mid-write), or binding_bypassable_without_auth with bindings and fixes"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Reassign a client's profile and/or mode","tags":["clients"]}},"/api/v1/clients/{client}/rotate":{"post":{"description":"Replaces a client's secret without ever invalidating the old one mid-flight (FR-021a). A SUPPORTED client is rewritten through connect: staged rotation, binding kept, finalized when the config write succeeds, rolled back (the old secret keeps working) when it fails; a preview's precondition_token binds the call, a mismatch is the connect 409 precondition_failed. A CUSTOM client gets a new secret returned ONCE with a snippet; both secrets authenticate until POST /clients/{client}/rotate/finalize or 24 hours. A client with no active credential is 409 no_client_credential. The FR-008a guard is not involved: a rotation never changes a binding's reach. Writes one rotate record when it finalizes.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.RotateClientRequest"}}},"description":"Optional precondition_token of a connect preview"},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The client row and the rotation state"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required (or macOS App-Data block)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectConflictResponse"}}},"description":"no_client_credential, precondition_failed, connect_in_progress (another connect of this client is mid-write), or credential_superseded (the written credential was replaced or revoked before it could be finalized; reconnect)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Rotate a client's credential","tags":["clients"]}},"/api/v1/clients/{client}/rotate/finalize":{"post":{"description":"Promotes a client's pending secret: the old secret stops authenticating. Idempotent: with no rotation in progress it is a no-op success. A client with no client credential is 409 no_client_credential. Writes one rotate record when it promotes.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The client row; rotation.state is finalized"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"no_client_credential, or connect_in_progress (a connect of this client is mid-write)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Finalize a staged rotation","tags":["clients"]}},"/api/v1/code/scripts":{"get":{"description":"List the stored scripts available to the code_execution tool. Scripts are ` + "`" + `\u003cname\u003e.js` + "`" + ` / ` + "`" + `\u003cname\u003e.ts` + "`" + ` files in the ` + "`" + `scripts/` + "`" + ` directory next to the active configuration file. Entries are advisory: ` + "`" + `ok` + "`" + ` scripts are invocable, ` + "`" + `ambiguous` + "`" + ` names have both extensions, and ` + "`" + `invalid` + "`" + ` ones report why (empty, oversized, unreadable, non-regular). Read-only — there is no write surface for stored scripts. Administrator-only (Spec 105 FR-012): an agent token, whatever its server scope, is refused with 403 — the listing is the enumeration the missing-script error withholds from a scoped caller.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Stored scripts and the directory they were read from"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot list stored scripts"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List stored code-execution scripts","tags":["code"]}},"/api/v1/config":{"get":{"description":"Retrieves the current MCPProxy configuration including all server definitions, global settings, and runtime parameters","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetConfigResponse"}}},"description":"Configuration retrieved successfully"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read the configuration document"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get current configuration","tags":["config"]},"patch":{"description":"Deep-merges only the fields present in the request body onto the live in-memory configuration and routes the result through the existing apply pipeline (validation, change detection, disk persistence, hot-reload). Fields the client omits — including masked secrets such as ` + "`" + `api_key` + "`" + ` and secret request headers — are preserved verbatim. Nested objects are merged recursively; arrays and scalars replace wholesale.","requestBody":{"content":{"application/json":{"schema":{"type":"object"}}},"description":"Partial configuration with only the fields to change","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ConfigApplyResult"}}},"description":"Configuration patch applied (inspect validation_errors for rejected values)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload or empty patch"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate configuration)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"binding_bypassable_without_auth: the patch would let a client bound to a named profile escape it while require_mcp_auth is off (FR-008a); nothing was written"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"telemetry.enabled is locked while an environment variable (DO_NOT_TRACK, CI, MCPPROXY_TELEMETRY=false) disables telemetry; nothing was written (FR-044a)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to read or apply configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Partially update configuration","tags":["config"]}},"/api/v1/config/apply":{"post":{"description":"Applies a new MCPProxy configuration. Validates and persists the configuration to disk. Some changes apply immediately, while others may require a restart. Returns detailed information about applied changes and restart requirements.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.Config"}}},"description":"Configuration to apply","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ConfigApplyResult"}}},"description":"Configuration applied successfully with change details"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate configuration)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"binding_bypassable_without_auth: the write would let a client bound to a named profile escape it while require_mcp_auth is off (FR-008a); nothing was written"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"telemetry.enabled is locked while an environment variable (DO_NOT_TRACK, CI, MCPPROXY_TELEMETRY=false) disables telemetry; nothing was written (FR-044a)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to apply configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Apply configuration","tags":["config"]}},"/api/v1/config/docker-isolation":{"patch":{"description":"Convenience endpoint to flip ` + "`" + `docker_isolation.enabled` + "`" + ` without resending the full config. Persists to disk via the existing config writer — the file watcher then hot-reloads the change. Returns the new state and whether a restart is required for existing connections to pick it up.","requestBody":{"content":{"application/json":{"schema":{"properties":{"enabled":{"type":"boolean"}},"type":"object"}}},"description":"New isolation state","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ConfigApplyResult"}}},"description":"Isolation toggle applied"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate configuration)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"binding_bypassable_without_auth (FR-008a); nothing was written"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to apply configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Toggle global Docker isolation","tags":["config"]}},"/api/v1/config/validate":{"post":{"description":"Validates a provided MCPProxy configuration without applying it. Checks for syntax errors, invalid server definitions, conflicting settings, and other configuration issues.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.Config"}}},"description":"Configuration to validate","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ValidateConfigResponse"}}},"description":"Configuration validation result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Validation failed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Validate configuration","tags":["config"]}},"/api/v1/connect":{"get":{"description":"Returns the connection status for all known MCP client applications.\nEach entry indicates whether the client config file exists and whether\nMCPProxy is currently registered in it. This stat-only listing never reads\na client config (Spec 075), so a client whose config exists reports\ncredential_state \"unknown\"; GET /connect/{client} resolves it.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"List of ClientStatus objects"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List client connection status","tags":["connect"]}},"/api/v1/connect/{client}":{"delete":{"description":"Remove the MCPProxy entry from the specified client's configuration file.\nCreates a backup of the existing config before modifying.\nAlso revokes the client's credential (it stops authenticating at once); the result names it in credential_revoked, or reports credential_revoke_error when the revoke failed after the entry was removed. Undoing a disconnect does not restore the credential: a later connect mints a new one.","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectRequest"}}},"description":"Optional parameters (server_name)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectResult"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Permission denied (macOS App-Data block)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client or entry not found"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Disconnect MCPProxy from a client","tags":["connect"]},"get":{"description":"Resolves one client's status by reading its config file on demand.\nThis is the only Connect endpoint that opens a client config file, so\non macOS it is the sole place an App-Data privacy prompt may legitimately\nappear (scoped to this user action). Resolves access_state to\naccessible|absent|denied|malformed and populates remediation when denied.\nFor a connected client it also resolves credential_state (Spec 108 FR-025):\nclient (an active per-client credential), admin_key (the instance admin API\nkey), none, revoked (a rotated-away or revoked credential) or expired. The\ncredential value is classified and never echoed.","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ClientStatus"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get a single client's connection status (on-demand)","tags":["connect"]},"post":{"description":"Register MCPProxy as an MCP server in the specified client's configuration file.\nCreates a backup of the existing config before modifying.\nOptionally accepts precondition_token from a preview (Spec 091): when supplied,\nthe core rechecks the raw pre-write state and the entry it would write, and\nrefuses a drifted write with 409 before taking any backup. The 409 body's\naction discriminates the two conflict kinds: \"precondition_failed\" (stale\npreview — re-preview, do not retry) vs \"already_exists\" (entry present — pass\nforce=true). force=true never rescues a stale token.\n\nSpec 108 FR-024: the entry carries a per-client mcp_cli_ credential bound to the\nrequested profile (default: All servers, switchable; a reconnect keeps the client's\nexisting binding unless a profile is given), never the instance admin API key.\nReconnecting over an active credential is a staged rotation: the old secret keeps\nworking until the config write succeeds. keyless=true writes no credential and is\nonly possible while require_mcp_auth is off (400 otherwise, and with a profile).\nA write that would let the client escape its profile by omitting its credential\nwhile require_mcp_auth is off is refused with 409 binding_bypassable_without_auth\n(nothing minted or written); a token named client-\u003cid\u003e held by a regular agent\ntoken is refused with 409 conflicting_token.","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectRequest"}}},"description":"Optional connection parameters (server_name, force, precondition_token, profile, mode, keyless)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectResult (credential is the masked mcp_cli_ value, with token_name, profile, mode, keyless and rotation)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Bad request; field names the offending input (profile, mode, keyless)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Permission denied (macOS App-Data block)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectConflictResponse"}}},"description":"Conflict: action=already_exists (use force=true) or action=precondition_failed (preview is stale; re-preview); or binding_bypassable_without_auth (BindingGuardResponse); or conflicting_token (ClientCredentialConflictResponse); or connect_in_progress (another connect of this client is mid-write) or credential_superseded (the written credential was replaced or revoked before it could be finalized; reconnect)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable (or no credential store wired while require_mcp_auth is on)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Connect MCPProxy to a client","tags":["connect"]}},"/api/v1/connect/{client}/preview":{"get":{"description":"Returns the exact entry a subsequent connect would add to the client's\nconfig — target path, server key, entry name, and entry contents — WITHOUT\nmodifying the file or creating a backup (Spec 078 US1). The per-client credential\nis masked in the payload (credential, always starting mcp_cli_; contains_api_key is\nalways false since connect never writes the admin API key); profile, mode and\nkeyless echo the requested intent.\nentry_exists distinguishes a create from an overwrite of a same-named entry.\nReads the config on demand to classify create-vs-overwrite, so on macOS this\nmay raise an App-Data privacy prompt; a denial returns 403 + remediation.\nSpec 091 adds three fields: existing_entry_summary (present only when\nentry_exists — a sanitized, non-secret projection of the entry being replaced:\nits name, type, endpoint with query/userinfo stripped, command, and header and\nenv NAMES, never values); precondition_token (always present — an opaque keyed\ndigest of the raw pre-write state and the pending entry, echoed back on POST\nconnect to detect drift); and connect_refusal (present when the write would\nrefuse regardless of intent, e.g. a non-create-capable client with no config —\ntreat its presence as \"Connect unavailable\").","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}},{"description":"Entry name to preview (defaults to mcpproxy); mirror the value passed to POST connect","in":"query","name":"server_name","schema":{"type":"string"}},{"description":"Profile the client credential would bind to (empty = All servers); mirror POST connect","in":"query","name":"profile","schema":{"type":"string"}},{"description":"locked|switchable; mirror POST connect","in":"query","name":"mode","schema":{"enum":["locked","switchable"],"type":"string"}},{"description":"Preview a credential-less entry (only while require_mcp_auth is off)","in":"query","name":"keyless","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectPreview"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid intent (field names the input; keyless with auth on or with a profile)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required or access denied by macOS App Data"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Preview the change a connect would make (no write)","tags":["connect"]}},"/api/v1/connect/{client}/undo":{"post":{"description":"Reverts the connect that produced the named backup (Spec 078 US3):\nrestores the client config byte-for-byte from that backup, or — when\nbackup_name is empty because the connect created the file — deletes the\ncreated file. backup_name is the bare filename of the backup the connect\nreturned (never a path); undo resolves the full path server-side inside\nthe client's own config directory, so a client value cannot escape it.\nRefuses with 409 when the config changed since the connect (undo never\nclobbers later edits; use DELETE /connect/{client} for a surgical entry\nremoval instead). Takes its own safety backup first; its path is returned\nas backup_path in the result. Undo is \"as if the connect never happened\": a\nclient credential the connect minted or rotated is revoked unless the restored\nconfig still holds it, and the result names it in credential_revoked.","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.UndoConnectRequest"}}},"description":"Undo parameters (server_name, backup_name = the bare filename of the backup the preceding connect returned)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectResult (action restored|deleted)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (e.g. backup_name is a path, or not a backup of this client's config)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Permission denied (macOS App-Data block)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client or backup no longer exists"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Config changed since connect; undo refused"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Undo a connect, restoring the pre-connect config","tags":["connect"]}},"/api/v1/diagnostics":{"get":{"description":"Get comprehensive health diagnostics including upstream errors, OAuth requirements, missing secrets, and Docker status","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.Diagnostics"}}},"description":"Health diagnostics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get health diagnostics","tags":["diagnostics"]}},"/api/v1/docker/status":{"get":{"description":"Retrieve current Docker availability and recovery status","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Docker status information"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get Docker status","tags":["docker"]}},"/api/v1/doctor":{"get":{"description":"Get comprehensive health diagnostics including upstream errors, OAuth requirements, missing secrets, and Docker status","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.Diagnostics"}}},"description":"Health diagnostics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get health diagnostics","tags":["diagnostics"]}},"/api/v1/feedback":{"post":{"description":"Submit a bug report, feature request, or general feedback","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/telemetry.FeedbackRequest"}}},"description":"Feedback request","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/telemetry.FeedbackResponse"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"additionalProperties":{"type":"string"},"type":"object"}}},"description":"Bad Request"},"429":{"content":{"application/json":{"schema":{"additionalProperties":{"type":"string"},"type":"object"}}},"description":"Too Many Requests"},"500":{"content":{"application/json":{"schema":{"additionalProperties":{"type":"string"},"type":"object"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyAuth":[]}],"summary":"Submit feedback","tags":["feedback"]}},"/api/v1/index/search":{"get":{"description":"Search across all upstream MCP server tools using BM25 keyword search","parameters":[{"description":"Search query","in":"query","name":"q","required":true,"schema":{"type":"string"}},{"description":"Maximum number of results","in":"query","name":"limit","schema":{"default":10,"maximum":100,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SearchToolsResponse"}}},"description":"Search results"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing query parameter)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Search for tools","tags":["tools"]}},"/api/v1/info":{"get":{"description":"Get essential server metadata including version, web UI URL, endpoint addresses, and update availability\nweb_ui_url carries the ?apikey= credential ONLY for an authenticated admin; a scoped agent token receives the bare URL\nThis endpoint is designed for tray-core communication and version checking\nUse refresh=true query parameter to force an immediate update check against GitHub\nThe launched_by field reports durable launch provenance (\"tray\", \"installer\", or \"\" for user-launched/unknown)","parameters":[{"description":"Force immediate update check against GitHub","in":"query","name":"refresh","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Server information with optional update info"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server information","tags":["status"]}},"/api/v1/onboarding/mark":{"post":{"description":"Updates wizard engagement and per-step status. Once engaged is\ntrue, the wizard does not auto-show again, even if state regresses.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.OnboardingMarkRequest"}}},"description":"Mark request","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Updated OnboardingStateResponse"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read onboarding state"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Mark onboarding wizard state (Spec 046)","tags":["onboarding"]}},"/api/v1/onboarding/state":{"get":{"description":"Returns the wizard engagement record alongside live predicates\n(whether any client is connected, whether any server is configured),\nplus a derived ShouldShowWizard flag the frontend can rely on.","responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OnboardingStateResponse"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read onboarding state"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get onboarding wizard state and predicates (Spec 046)","tags":["onboarding"]}},"/api/v1/preflight":{"post":{"description":"Deterministic, side-effect-free availability check for a caller-supplied list of tool IDs (Spec 098). Performs zero upstream calls and mutates no runtime state. HTTP status reports whether the CHECK executed: a fully blocked set is still 200, with the availability verdict in the body. Every executed preflight writes an activity record before the response is returned.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.PreflightRequest"}}},"description":"Tool IDs (1-100 before dedup), optional profile, annotation policy filters and wait budget","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Preflight verdict and per-tool results"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Validation error (malformed, oversized, doubled or unknown-field body; empty or oversized tool list; conflicting duplicate pins; unknown profile; wait_ms out of range)"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Missing or invalid credentials"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Runtime unavailable, evaluator infrastructure read failure, or the activity record could not be persisted"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Preflight required tools","tags":["tools"]}},"/api/v1/profiles":{"get":{"description":"Lists every profile as a ProfileView: the config fields as stored, the derived effective values, visible tool counts by tier, 24 h calls and blocked calls, and (administrators only) used_by and the anonymous_profile. A caller that is not an administrator sees only the profiles its entitlement reaches, with servers, rules and switchable_to narrowed to what it may see; an unreachable profile is omitted, never shown empty.","responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Profile list"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Configuration unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List configured profiles","tags":["profiles"]},"post":{"description":"Adds a profile. The body is a ProfileConfig. A name that already exists is 409 profile_exists; ` + "`" + `active` + "`" + ` and ` + "`" + `try` + "`" + ` are reserved by the REST API; a fatal validation rule is 400 with the offending field and the unchanged FR-007 text. A write that would let a client bound to a named profile escape it while require_mcp_auth is off is refused 409 binding_bypassable_without_auth (FR-008a) and nothing is written. Writes one profile_change record.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.ProfileConfig"}}},"description":"The profile","required":true},"responses":{"201":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Created, with the validator's warnings"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ProfileConflictResponse"}}},"description":"profile_exists, or binding_bypassable_without_auth (BindingGuardResponse)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Create a profile","tags":["profiles"]}},"/api/v1/profiles/active":{"get":{"description":"Deprecated (Spec 108 FR-039; sends a Deprecation header, successor GET /api/v1/profiles). Get the server-level default active profile used by UI surfaces (Web UI / tray). Empty string means \"all servers\". Note: within a live MCP session, the set_profile tool selection takes precedence over this default.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Active profile"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the default active profile","tags":["profiles"]},"put":{"description":"Deprecated (Spec 108 FR-039; sends a Deprecation header, successor GET /api/v1/profiles). Set the server-level default active profile for UI surfaces. The slug must match a configured profile; pass an empty string to clear. This does not affect live MCP sessions, which use the set_profile tool.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.SetActiveProfileRequest"}}},"description":"Profile slug to activate (empty clears)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Active profile updated"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request body"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot change the active profile)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown profile"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Set the default active profile","tags":["profiles"]}},"/api/v1/profiles/try":{"post":{"description":"Evaluates a DRAFT profile against a query exactly as retrieve_tools would (policy is applied before the limit) and returns the hits plus what the draft hides (hidden_by_profile and up to 100 {server, tool, reason}). The draft is validated as if it replaced the same-named profile, or was appended under a placeholder name when it has none. Nothing is persisted, no record is written, no event is published and the FR-008a guard does not run. Administrators only.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.TryProfileRequest"}}},"description":"draft profile, query and optional limit (default 10, max 50)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Search result under the draft"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid draft; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Try a draft profile","tags":["profiles"]}},"/api/v1/profiles/{name}":{"delete":{"description":"Deletes a profile. 409 profile_in_use (with used_by) while clients or tokens point at it, unless reassign_to names another existing profile (every pin moves there) or force is set (pins are left dangling, which the resolver treats as deny-all). 409 profile_is_anonymous_profile whenever it is the anonymous_profile and reassign_to is absent, even with force. Both paths remove the name from every switchable_to. Guarded by FR-008a. Writes one ` + "`" + `delete` + "`" + ` record.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}},{"description":"Another existing profile that takes over the pins","in":"query","name":"reassign_to","schema":{"type":"string"}},{"description":"Delete although in use, leaving pins dangling","in":"query","name":"force","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Deleted"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"reassign_to does not name another existing profile"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ProfileConflictResponse"}}},"description":"profile_in_use, profile_is_anonymous_profile, or binding_bypassable_without_auth (BindingGuardResponse)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Delete a profile","tags":["profiles"]},"get":{"description":"Returns the ProfileView of the named profile. A caller that is not an administrator gets the same 404 for an unreachable profile as for an unknown one.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The profile"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get one profile","tags":["profiles"]},"put":{"description":"Replaces the named profile with the body (a ProfileConfig whose name, when sent non-empty, must equal the path; 409 name_mismatch otherwise - a rename has its own route; an omitted or empty name takes the path's). A write whose only change is tools.classify is recorded as ` + "`" + `classify` + "`" + `. Guarded by FR-008a like a create.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.ProfileConfig"}}},"description":"The profile","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Updated, with the validator's warnings"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ProfileConflictResponse"}}},"description":"name_mismatch, or binding_bypassable_without_auth (BindingGuardResponse)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Replace a profile","tags":["profiles"]}},"/api/v1/profiles/{name}/effective-tools":{"get":{"description":"One row per catalog tool with the verdict of the access chain (the same rendering GET /tools?profile= uses): server, tool, intrinsic_tier, profile_tier, access{visible, callable, reason} and classification_stale. With client=\u003cid\u003e the client's credential is evaluated UNDER this profile (\"what would Cursor get here\"). An administrator gets every row plus counts.callable, counts.by_reason and stale_classifications; every other caller gets only visible rows and counts{visible, hidden}, and client= and reason= are refused 403. An unreachable profile answers exactly like an unknown one.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}},{"description":"Evaluate this client's credential under the profile (administrators only)","in":"query","name":"client","schema":{"type":"string"}},{"description":"Keep only this server's rows","in":"query","name":"server","schema":{"type":"string"}},{"description":"Keep only rows with this access reason (administrators only)","in":"query","name":"reason","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Effective tools"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"operation requires admin access"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found / client not found"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Effective tools of a profile","tags":["profiles"]}},"/api/v1/profiles/{name}/rename":{"post":{"description":"Renames a profile and moves every reference to it - token pins, client bindings, other profiles' switchable_to and the anonymous_profile - in one write (D19). Tokens move first, so a failure part-way never widens a scope. Guarded by FR-008a. Writes one ` + "`" + `rename` + "`" + ` record.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.RenameProfileRequest"}}},"description":"new_name","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Renamed; moved lists the clients and tokens that followed"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ProfileConflictResponse"}}},"description":"profile_exists, or binding_bypassable_without_auth (BindingGuardResponse)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Rename a profile","tags":["profiles"]}},"/api/v1/registries":{"get":{"description":"Retrieves list of all MCP server registries that can be browsed for discovering and installing new upstream servers. Includes registry metadata, server counts, and API endpoints.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetRegistriesResponse"}}},"description":"Registries retrieved successfully"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to list registries"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List available MCP server registries","tags":["registries"]},"post":{"description":"Adds a generic modelcontextprotocol/registry v0.1 https endpoint as a custom registry (MCP-866). The source is always tagged custom/unverified, so every server discovered through it lands quarantined and can never skip quarantine.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.AddRegistrySourceRequest"}}},"description":"Registry source (https url + optional protocol/id/name)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Registry source added"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"invalid_registry_url"},"403":{"content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/contracts.ErrorResponse"},{"$ref":"#/components/schemas/contracts.ErrorResponse"}]}}},"description":"Forbidden (agent tokens cannot mutate registries)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_shadows_builtin | duplicate_registry"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add a user-supplied registry source","tags":["registries"]}},"/api/v1/registries/{id}":{"delete":{"description":"Removes a custom/unverified registry previously added via add-source (MCP-1057). Built-in registries are refused with registry_shadows_builtin; an unknown id yields registry_not_found. The change is persisted copy-on-write.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Registry source removed"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID is required"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registries_locked"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_not_found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_shadows_builtin"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Remove a user-added custom registry source","tags":["registries"]},"put":{"description":"Updates a custom registry previously added via add-source (MCP-1072): name, url, servers-url. Empty fields are left unchanged. Built-in registries are refused with registry_shadows_builtin; an unknown id yields registry_not_found; a non-https url yields invalid_registry_url. The change is persisted copy-on-write.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.EditRegistrySourceRequest"}}},"description":"Fields to update (name/url/servers_url; empty = unchanged)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Registry source updated"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID is required | invalid_registry_url"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registries_locked"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_not_found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_shadows_builtin"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Edit a user-added custom registry source","tags":["registries"]}},"/api/v1/registries/{id}/refresh":{"post":{"description":"Invalidates the cached server lists for a registry so the next search re-fetches fresh data from the source (spec 070 FR-007). Returns how many cache entries were dropped.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.RefreshRegistryResponse"}}},"description":"Registry cache refreshed"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID is required"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to refresh registry cache"}},"summary":"Refresh a registry's cached server list","tags":["registries"]}},"/api/v1/registries/{id}/servers":{"get":{"description":"Searches for MCP servers within a specific registry by keyword or tag. Returns server metadata including installation commands, source code URLs, and npm package information for easy discovery and installation.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Search query keyword","in":"query","name":"q","schema":{"type":"string"}},{"description":"Filter by tag","in":"query","name":"tag","schema":{"type":"string"}},{"description":"Maximum number of results (default 10)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SearchRegistryServersResponse"}}},"description":"Servers retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to search servers"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Search MCP servers in a registry","tags":["registries"]}},"/api/v1/registries/{id}/servers/{serverId}/add":{"post":{"description":"Resolves a registry server reference server-side, re-derives a validated config, and persists it quarantined (spec 070 keystone). The client never sends a config blob — command/args/url and the quarantine flag are derived from the registry entry, not the request.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Server ID within the registry","in":"path","name":"serverId","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.AddFromRegistryRequest"}}},"description":"Optional overrides (name, env, enabled)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server added (quarantined)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"no_install_info | missing_required_input | duplicate_name"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot add servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_not_found | server_not_found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add an upstream server from a registry reference","tags":["registries"]}},"/api/v1/review":{"get":{"description":"Returns one row per quarantined server, trusted server with pending or changed tools, or (Spec 125) server with held skills (kind skill_review; skills_pending / skills_changed counts). Scoped callers see only servers they may enumerate (for a profile-pinned token: servers within its pin), with count recomputed; held-skill counts and skill_review rows are administrator-only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Review queue"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to load review queue"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the server review queue","tags":["review"]}},"/api/v1/routing":{"get":{"description":"Get the current routing mode and available MCP endpoints.\nrouting_mode is what /mcp is actually serving; pending_routing_mode carries a\nrestart-pending value persisted on disk (empty when there is none).\ntool_response_mode and direct_tool_response_mode report the two serialization axes, resolved.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Routing mode information"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get routing mode information","tags":["status"]}},"/api/v1/secrets":{"post":{"description":"Stores a secret value in the operating system's secure keyring. The secret can then be referenced in configuration using ${keyring:secret-name} syntax. Automatically notifies runtime to restart affected servers.","requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{},"type":"object"}}},"description":"Secret stored successfully with reference syntax"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload, missing name/value, or unsupported type"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Secret resolver not available or failed to store secret"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Store a secret in OS keyring","tags":["secrets"]}},"/api/v1/secrets/{name}":{"delete":{"description":"Deletes a secret from the operating system's secure keyring. Automatically notifies runtime to restart affected servers. Only keyring type is supported for security.","parameters":[{"description":"Name of the secret to delete","in":"path","name":"name","required":true,"schema":{"type":"string"}},{"description":"Secret type (only 'keyring' supported, defaults to 'keyring')","in":"query","name":"type","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{},"type":"object"}}},"description":"Secret deleted successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Missing secret name or unsupported type"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Secret resolver not available or failed to delete secret"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Delete a secret from OS keyring","tags":["secrets"]}},"/api/v1/security/bundle":{"get":{"description":"Reports the offline TPA signature corpus this install is serving: full SHA-256 digest, sequence, authority, trust epoch, signature verification, staleness (with the stale flag and its threshold), degraded coverage with its reason, rollback pin, and the last refused candidate. Also carries the refresh status (last checked and activated times, last cycle outcome, next check, consecutive failures; the fetch host only, never the URL) and the post-activation re-protection sweep status. Admin only.","responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Bundle status"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the TPA signature bundle status","tags":["security"]}},"/api/v1/security/bundle/history":{"get":{"description":"Append-only list of bundle activations, oldest first, each with its full SHA-256 digest. It is the trustworthy source of the digest to name in a rollback. Admin only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Activation history (data is an array of TPABundleActivation)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"History could not be read"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the TPA signature bundle activation history","tags":["security"]}},"/api/v1/security/bundle/refresh":{"post":{"description":"Runs one refresh cycle immediately: the local file leg (always network-free) followed by the optional fetch leg when security.tpa_fetch_enabled is on and a trusted signer and URL are configured. A cycle already in flight is joined, so one download and at most one activation happen per distinct candidate. The response is the resulting bundle status; the cycle outcome is in its refresh block (activated, unchanged, not_modified, rejected, fetch_unavailable, channel_invalid, superseded, disabled). Network failures are reported as fetch_unavailable and never as a rejection; last-known-good keeps serving. Unlike reload, refresh may make an outbound request. Admin API key only.","responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Updated bundle status; the refresh block holds the cycle outcome"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Refresh the TPA signature bundle now","tags":["security"]}},"/api/v1/security/bundle/reload":{"post":{"description":"Re-runs the single-flight bundle pipeline against the configured source and current policy. A refused candidate leaves last-known-good serving and is reported as last_rejection in the returned status. Admin API key only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Updated bundle status"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Reload the TPA signature bundle","tags":["security"]}},"/api/v1/security/bundle/rollback":{"post":{"description":"The one operator override of the downgrade watermark. Exactly one of embedded or path must be given, and digest must be the FULL 64-character lowercase hex SHA-256 of the target (the 12-character fingerprint is refused). On success the target serves and is pinned. A refusal (for example rollback_target_mismatch) returns 409 with the rejection reason and last-known-good keeps serving. Admin API key only; agent tokens are refused.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.bundleRollbackRequest"}}},"description":"Rollback target","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Updated bundle status"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Usage error: both or neither of embedded/path, or digest is not 64 lowercase hex"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BundleRollbackRefusedResponse"}}},"description":"Rollback refused; the response carries the rejection reason"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal error"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Roll the TPA signature bundle back to a named artifact","tags":["security"]}},"/api/v1/security/bundle/unpin":{"post":{"description":"Clears the rollback pin and re-validates the serving bundle under the normal downgrade watermark, so a rolled-back target below the watermark no longer serves. A quiet no-op when nothing is pinned. Admin API key only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Updated bundle status"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"The unpin could not be recorded"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Clear the TPA signature bundle rollback pin","tags":["security"]}},"/api/v1/servers":{"get":{"description":"Get a list of all configured upstream MCP servers with their connection status and statistics","parameters":[{"description":"Restrict to the profile's effective servers; tool_count becomes the number of that server's tools visible under the profile (Spec 108 FR-032)","in":"query","name":"profile","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServersResponse"}}},"description":"Server list with statistics"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unsupported scope filter (client/token), or '-' on a server filter"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown or unreachable profile"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List all upstream MCP servers","tags":["servers"]},"post":{"description":"Add a new MCP upstream server to the configuration. New servers are quarantined by default for security. Isolation: ` + "`" + `isolation.enabled` + "`" + ` is READ-ONLY (it reports the effective state on reads) and is rejected with 400; set the per-server override via ` + "`" + `isolation.enabled_override` + "`" + ` (true | false | null to clear, omit to leave unchanged). An unrecognized ` + "`" + `isolation.mode_override` + "`" + ` is rejected with 400.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.AddServerRequest"}}},"description":"Server configuration","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server added successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid configuration"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Conflict - server with this name already exists"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add a new upstream server","tags":["servers"]}},"/api/v1/servers/disable_all":{"post":{"description":"Disable all configured upstream MCP servers with partial failure handling","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/management.BulkOperationResult"}}},"description":"Bulk disable results with success/failure counts"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Disable all servers","tags":["servers"]}},"/api/v1/servers/enable_all":{"post":{"description":"Enable all configured upstream MCP servers with partial failure handling","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/management.BulkOperationResult"}}},"description":"Bulk enable results with success/failure counts"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable all servers","tags":["servers"]}},"/api/v1/servers/import":{"post":{"description":"Import MCP server configurations from a Claude Desktop, Claude Code, Cursor IDE, Codex CLI, or Gemini CLI configuration file","parameters":[{"description":"If true, return preview without importing","in":"query","name":"preview","schema":{"type":"boolean"}},{"description":"Force format (claude-desktop, claude-code, cursor, codex, gemini)","in":"query","name":"format","schema":{"type":"string"}},{"description":"Comma-separated list of server names to import","in":"query","name":"server_names","schema":{"type":"string"}}],"requestBody":{"content":{"multipart/form-data":{"schema":{"type":"file"}}},"description":"Configuration file to import","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportResponse"}}},"description":"Import result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid file or format"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Import servers from uploaded configuration file","tags":["servers"]}},"/api/v1/servers/import/json":{"post":{"description":"Import MCP server configurations from raw JSON or TOML content (useful for pasting configurations)","parameters":[{"description":"If true, return preview without importing","in":"query","name":"preview","schema":{"type":"boolean"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportRequest"}}},"description":"Import request with content","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportResponse"}}},"description":"Import result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid content or format"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Import servers from JSON/TOML content","tags":["servers"]}},"/api/v1/servers/import/path":{"post":{"description":"Import MCP server configurations by reading a file from the server's filesystem. A preview (preview=true) of a file with no MCP servers (empty, {}, or no/empty server map) answers 200 with an empty imported list; an apply of such a file and a malformed file still answer 400.","parameters":[{"description":"If true, return preview without importing","in":"query","name":"preview","schema":{"type":"boolean"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportFromPathRequest"}}},"description":"Import request with file path","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportResponse"}}},"description":"Import result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid path or format"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"File not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Import servers from a file path","tags":["servers"]}},"/api/v1/servers/import/paths":{"get":{"description":"Returns well-known configuration file paths for supported formats with existence check","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.CanonicalConfigPathsResponse"}}},"description":"Canonical config paths"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get canonical config file paths","tags":["servers"]}},"/api/v1/servers/reconnect":{"post":{"description":"Force reconnection to all upstream MCP servers","parameters":[{"description":"Reason for reconnection","in":"query","name":"reason","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"All servers reconnected successfully"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Reconnect all servers","tags":["servers"]}},"/api/v1/servers/restart_all":{"post":{"description":"Restart all configured upstream MCP servers sequentially with partial failure handling","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/management.BulkOperationResult"}}},"description":"Bulk restart results with success/failure counts"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Restart all servers","tags":["servers"]}},"/api/v1/servers/{id}":{"delete":{"description":"Remove an MCP upstream server from the configuration. This stops the server if running and removes it from config.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server removed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Remove an upstream server","tags":["servers"]},"patch":{"description":"Update specific fields of an existing upstream MCP server configuration. Isolation: ` + "`" + `isolation.enabled` + "`" + ` is READ-ONLY (it reports the effective state on reads) and is rejected with 400; set the per-server override via ` + "`" + `isolation.enabled_override` + "`" + ` (true | false | null to clear, omit to leave unchanged). An unrecognized ` + "`" + `isolation.mode_override` + "`" + ` is rejected with 400.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.AddServerRequest"}}},"description":"Fields to update (all optional)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server updated successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - no fields or invalid body"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Partially update an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/config-to-secret":{"post":{"description":"Atomically reads the real value from the server config, stores it in the OS keyring, and rewrites the config field to ` + "`" + `${keyring:\u003cname\u003e}` + "`" + `. Unblocks the UI's Convert-to-secret affordance for values the API redacts on the read path.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{},"type":"object"}}},"description":"Secret stored, config updated with reference"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad scope/key/secret_name, or value is already a reference / empty"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or key not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Secret resolver or config update failed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Convert a header / env value to a keyring secret","tags":["servers"]}},"/api/v1/servers/{id}/disable":{"post":{"description":"Disable a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server disabled successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Disable an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/discover-tools":{"post":{"description":"Manually trigger tool discovery and indexing for a specific upstream MCP server. This forces an immediate refresh of the server's tool cache.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Tool discovery triggered successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot discover tools)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to discover tools"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Discover tools for a specific server","tags":["servers"]}},"/api/v1/servers/{id}/enable":{"post":{"description":"Enable a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server enabled successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/login":{"post":{"description":"Initiate OAuth authentication flow for a specific upstream MCP server. Returns structured OAuth start response with correlation ID for tracking.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.OAuthStartResponse"}}},"description":"OAuth login initiated successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.OAuthFlowError"}}},"description":"OAuth error (client_id required, DCR failed, etc.)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Trigger OAuth login for server","tags":["servers"]}},"/api/v1/servers/{id}/logout":{"post":{"description":"Clear OAuth authentication token and disconnect a specific upstream MCP server. The server will need to re-authenticate before tools can be used again.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"OAuth logout completed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled or read-only mode)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Clear OAuth token and disconnect server","tags":["servers"]}},"/api/v1/servers/{id}/logs":{"get":{"description":"Retrieve log entries for a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Number of log lines to retrieve","in":"query","name":"tail","schema":{"default":100,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServerLogsResponse"}}},"description":"Server logs retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server logs","tags":["servers"]}},"/api/v1/servers/{id}/quarantine":{"post":{"description":"Place a specific upstream MCP server in quarantine to prevent tool execution","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server quarantined successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Quarantine a server","tags":["servers"]}},"/api/v1/servers/{id}/refresh":{"post":{"description":"Re-discover and re-index a specific upstream MCP server's tools without changing any security state. Alias of discover-tools, named for the upstream_servers 'refresh' operation; use it to make just-approved tools searchable immediately.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Tool refresh triggered successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot refresh)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to refresh tools"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Refresh a server's tools","tags":["servers"]}},"/api/v1/servers/{id}/restart":{"post":{"description":"Restart the connection to a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server restarted successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Restart an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/review":{"get":{"description":"Returns redacted server configuration, captured tool definitions, annotations, scan verdicts, and diffs. Scoped callers receive the same 404 for invisible and missing servers.","parameters":[{"description":"Server name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server review"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to load server review"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get review details for a server","tags":["review"]}},"/api/v1/servers/{id}/security/approve":{"post":{"description":"Saves the integrity baseline and optionally blocks selected tools atomically before unquarantining the server. With expected_hashes (tool name -\u003e the review's current_hash; {} for an empty review) the approval is bound to the reviewed definitions: when a tool the approval would make reachable (pending, or approved and enabled, minus block) changed or appeared since the review, or a block target no longer exists, the response is 409 review_out_of_date, nothing is written and the server stays quarantined. Tools listed after the approval wait for review.","parameters":[{"description":"Server name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.securityApproveRequest"}}},"description":"Force approval and tool names to keep disabled"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server approved"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request or unknown tool block target"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not configured"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.StaleReviewErrorResponse"}}},"description":"Dangerous scan verdict requires force, approval failed, the review is out of date (error_code review_out_of_date), or server_replaced (the server was removed or re-added since expected_incarnation)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Approve a server after security review","tags":["security"]}},"/api/v1/servers/{id}/skills":{"get":{"description":"Lists the skills of one upstream server. An administrator sees every record: status, hashes, files, scan result and the availability an agent would see. A scoped agent token with the server in its reach sees only the available skills, as the approved copy (id, uri, path, name, description, status \"approved\", approved_hash, files, total_size; contracts.SkillsAgentListResponse) and nothing about any other skill; a server outside its reach is 404. With enable_skills off the answer is {\"enabled\": false, \"skills\": []} and no upstream is contacted.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsListResponse"}}},"description":"Skills of the server"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found, or outside the caller's reach"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List the skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/skills/approve":{"post":{"description":"Administrator only. Approves the named skills for exactly the content the reviewer saw: expected_hashes maps each skill path to the current_hash from the listing, and expected_incarnation (the listing's incarnation) binds the approval to the server that was reviewed. When a hash differs, or a named skill has no expected hash, the response is 409 review_out_of_date with the changed and unreviewed names and nothing is approved; 409 server_replaced when the server was removed or replaced since the review; 422 skill_unusable for a skill that cannot be approved (a failed check or a dynamic file list). A skill already approved for its current content is left as it is and not counted. The blocked mark is never touched. A scoped agent token is refused with 403.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsApproveRequest"}}},"description":"Skills to approve, with the review binding","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsApproveResponse"}}},"description":"Number of skills newly approved (inside the data envelope)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or skill not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsStaleReviewResponse"}}},"description":"review_out_of_date, server_replaced or skills_disabled"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsUnusableResponse"}}},"description":"skill_unusable"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Approve skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/skills/block":{"post":{"description":"Administrator only. Sets the blocked mark on the named skills: a blocked skill is never offered to an agent, and no refresh, content change or automatic approval clears the mark. expected_incarnation is optional (0 binds to the current server). 409 server_replaced when the server was removed or replaced since it was reviewed. A scoped agent token is refused with 403.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsBlockRequest"}}},"description":"Skills to block","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsBlockResponse"}}},"description":"Number of skills whose mark changed (inside the data envelope)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or skill not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"server_replaced or skills_disabled"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Block skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/skills/content":{"get":{"description":"Returns a chunk of one stored text file of a skill. An administrator reads the current copy by default; a scoped agent token with the server in its reach reads the approved copy of an available skill only (copy is forced to approved), and gets one 404 for every other skill or file. A server outside its reach is 404. Offsets are byte positions; a chunk never splits a UTF-8 character, so it can be a few bytes shorter than limit. next_offset is absent at the end of the file. 404 for an unknown skill or file (or with enable_skills off), 415 for a binary file, 409 stored_copy_damaged when the stored bytes no longer match their digest.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Skill path, e.g. hf-cli","in":"query","name":"skill","required":true,"schema":{"type":"string"}},{"description":"File path inside the skill (default SKILL.md)","in":"query","name":"file","schema":{"type":"string"}},{"description":"current (default) or approved","in":"query","name":"copy","schema":{"type":"string"}},{"description":"Byte offset to start at (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Maximum bytes (default and maximum 65536)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillContentResponse"}}},"description":"A chunk of the file"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad parameters"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"output_blocked: the output sanitisation policy withholds the text (scoped caller)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server, skill or file not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"stored_copy_damaged (administrator)"},"415":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"The file is binary"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Read one text file of a skill","tags":["servers"]}},"/api/v1/servers/{id}/skills/refresh":{"post":{"description":"Administrator only. Reads the server's skills from the upstream again, verifies every file and returns the listing once applied. A refresh that is already running is joined. 409 skills_disabled when enable_skills is off; 409 skills_not_supported when the server does not announce the skills extension.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsListResponse"}}},"description":"Skills of the server after the refresh"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"skills_disabled, skills_not_supported or refresh_superseded"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Refresh failed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Refresh the skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/skills/unblock":{"post":{"description":"Administrator only. Clears the blocked mark on the named skills. The skill's approval state is not changed: a skill that is not approved stays unavailable. expected_incarnation is optional (0 binds to the current server). 409 server_replaced when the server was removed or replaced since it was reviewed. A scoped agent token is refused with 403.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsBlockRequest"}}},"description":"Skills to unblock","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsBlockResponse"}}},"description":"Number of skills whose mark changed (inside the data envelope)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or skill not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"server_replaced or skills_disabled"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Unblock skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/tool-calls":{"get":{"description":"Retrieves tool call history filtered by upstream server ID. Returns recent tool executions for the specified server including timestamps, arguments, results, and errors. Useful for server-specific debugging and monitoring.","parameters":[{"description":"Upstream server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Maximum number of records to return (1-100, default 50)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServerToolCallsResponse"}}},"description":"Server tool calls retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get server tool calls"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call history for specific server","tags":["tool-calls"]}},"/api/v1/servers/{id}/tools":{"get":{"description":"Retrieve all available tools for a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServerToolsResponse"}}},"description":"Server tools retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server kept being removed or replaced while its tools were read"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/approve":{"post":{"description":"Approves the given pending/changed tools (or all of them with approve_all). With expected_hashes (tool name -\u003e the review's current_hash) the approval is bound to the reviewed definitions: when a requested tool (approve_all: any pending or changed tool) no longer matches, the response is 409 review_out_of_date and nothing is approved.","parameters":[{"description":"Server name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.approveToolsRequest"}}},"description":"Tools to approve, or approve_all, with an optional review binding","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Approval outcome"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.StaleReviewErrorResponse"}}},"description":"The review is out of date; nothing was approved"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Approve tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/block":{"post":{"description":"Atomically approves AND disables the given tools (or all pending/changed tools when block_all=true) for a server. The approve and disable land in a single write per tool, so a tool is never left in the approved+enabled state. The \"blocked\" field counts tools actually blocked. An optional expected_incarnation binds the write to the reviewed server (Spec 116): a remove and re-add since then answers 409 server_replaced and writes nothing.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Block result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server was removed or re-added since expected_incarnation"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Block (approve+disable) tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/disable_all":{"post":{"description":"Bulk-toggles every known tool of a server. The \"changed\" field","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.expectedIncarnationBody"}}},"description":"Optional incarnation of the reviewed server (Spec 116)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Operation result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server was removed or re-added since expected_incarnation"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable or disable all tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/enable_all":{"post":{"description":"Bulk-toggles every known tool of a server. The \"changed\" field","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.expectedIncarnationBody"}}},"description":"Optional incarnation of the reviewed server (Spec 116)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Operation result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server was removed or re-added since expected_incarnation"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable or disable all tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/unquarantine":{"post":{"description":"Remove a specific upstream MCP server from quarantine to allow tool execution","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.expectedIncarnationBody"}}},"description":"Optional incarnation of the reviewed server (Spec 116)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server unquarantined successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server was removed or re-added since expected_incarnation"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Unquarantine a server","tags":["servers"]}},"/api/v1/sessions":{"get":{"description":"Retrieves paginated list of active and recent MCP client sessions. Each session represents a connection from an MCP client to MCPProxy, tracking initialization time, tool calls, and connection status.","parameters":[{"description":"Maximum number of sessions to return (1-100, default 10)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Number of sessions to skip for pagination (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Filter by session status","in":"query","name":"status","schema":{"enum":["active","closed"],"type":"string"}},{"description":"Filter by the session's latest effective profile; - selects sessions with none (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Filter by the client id the session's credential is bound to; - selects sessions with none (Spec 108)","in":"query","name":"client","schema":{"type":"string"}},{"description":"Filter by the token name the session initialized with; - selects sessions with none (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Alias of token","in":"query","name":"agent","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetSessionsResponse"}}},"description":"Sessions retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid status filter, token and agent naming different tokens, or client_name (not supported here; filter by client)"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read MCP session history"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get sessions"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get active MCP sessions","tags":["sessions"]}},"/api/v1/sessions/{id}":{"get":{"description":"Retrieves detailed information about a specific MCP client session including initialization parameters, connection status, tool call count, and activity timestamps.","parameters":[{"description":"Session ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetSessionDetailResponse"}}},"description":"Session details retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Session ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read MCP session history"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Session not found"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get MCP session details by ID","tags":["sessions"]}},"/api/v1/stats/tokens":{"get":{"description":"Retrieve token savings statistics across all servers and sessions","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Token statistics"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read deployment-wide token statistics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get token savings statistics","tags":["stats"]}},"/api/v1/status":{"get":{"description":"Get comprehensive server status including running state, listen address, upstream statistics, and timestamp. For a scoped caller (an agent token; for a profile-pinned token, its allowed_servers intersected with the pin) upstream_stats lists only the servers it may enumerate and every counter is recomputed over them.\ntelemetry (admin only): effective telemetry state {enabled, source: env|config|default, disabled_by}","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server status information"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server status","tags":["status"]}},"/api/v1/telemetry/payload":{"get":{"description":"Render the exact JSON heartbeat payload that mcpproxy would next send to the telemetry endpoint, without making a network call. Counters in the payload reflect the current in-memory state. Spec 042.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Telemetry heartbeat payload"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read the deployment telemetry payload"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Telemetry service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Preview next telemetry heartbeat payload","tags":["telemetry"]}},"/api/v1/telemetry/update-failure":{"post":{"description":"Records one terminal update-session failure, identified only by its\nstage (appcast, download, install, other). The body carries no error\ntext, URL, or version — the stage is the only value transmitted.\nReturns 204 both when the occurrence was durably persisted and when\ntelemetry is inactive at event time (config opt-out, environment\nopt-out, CI, or dev build), in which case nothing is recorded.\nCallers cannot and need not distinguish the two.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.UpdateFailureRequest"}}},"description":"Update failure stage","required":true},"responses":{"204":{"description":"Accepted (recorded, or a deliberate no-op while telemetry is inactive)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Malformed body, unknown field, trailing value, or stage outside the closed set"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Persistence failure"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Record a desktop auto-update failure occurrence (Spec 095)","tags":["telemetry"]}},"/api/v1/tool-calls":{"get":{"description":"Retrieves paginated tool call history across all upstream servers or filtered by session ID. Includes execution timestamps, arguments, results, and error information for debugging and auditing.","parameters":[{"description":"Maximum number of records to return (1-100, default 50)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Number of records to skip for pagination (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Filter tool calls by MCP session ID","in":"query","name":"session_id","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetToolCallsResponse"}}},"description":"Tool calls retrieved successfully"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get tool calls"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call history","tags":["tool-calls"]}},"/api/v1/tool-calls/{id}":{"get":{"description":"Retrieves detailed information about a specific tool call execution including full request arguments, response data, execution time, and any errors encountered.","parameters":[{"description":"Tool call ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetToolCallDetailResponse"}}},"description":"Tool call details retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call not found"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call details by ID","tags":["tool-calls"]}},"/api/v1/tool-calls/{id}/replay":{"post":{"description":"Re-executes a previous tool call with optional modified arguments. Useful for debugging and testing tool behavior with different inputs. Creates a new tool call record linked to the original.","parameters":[{"description":"Original tool call ID to replay","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ReplayToolCallRequest"}}},"description":"Optional modified arguments for replay"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ReplayToolCallResponse"}}},"description":"Tool call replayed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call ID required or invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Replay refused: tool quarantined or not callable, server quarantined, outside the profile policy, or the token lacks the tool's permission tier"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"429":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Shed by a concurrency limit or an agent token call rate limit (Retry-After header carries the wait hint)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to replay tool call"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Replay a tool call","tags":["tool-calls"]}},"/api/v1/tools":{"get":{"description":"Consolidated, read-only listing of all tools from every configured server (including disabled servers and disabled/config-denied tools), enriched with approval state and 30-day usage. Backs the global Tools page and the CLI global ` + "`" + `tools list` + "`" + ` (spec 050, issue #437).","parameters":[{"description":"View-as (administrator only): the tools this client would see, each with its access verdict {visible, callable, reason} and profile_tier (Spec 108 FR-032)","in":"query","name":"client","schema":{"type":"string"}},{"description":"View-as: the tools this profile would expose. An administrator gets every row with a verdict; any other caller gets only the visible rows plus counts {visible, hidden} (Spec 108 FR-032)","in":"query","name":"profile","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GlobalToolsResponse"}}},"description":"All tools across all servers"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unsupported scope filter (token), both client and profile, or '-' on a tools filter"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"client= requires administrator credentials"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown or unreachable client / profile"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Could not enumerate servers"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List every tool across all servers","tags":["tools"]}},"/api/v1/tools/call":{"post":{"description":"Execute a tool on an upstream MCP server (wrapper around MCP tool calls)","requestBody":{"content":{"application/json":{"schema":{"properties":{"arguments":{"type":"object"},"tool_name":{"type":"string"}},"type":"object"}}},"description":"Tool call request with tool name and arguments","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Tool call result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (invalid payload or missing tool name)"},"429":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Shed by a concurrency limit or an agent token call rate limit (Retry-After header carries the wait hint)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error or tool execution failure"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Call a tool","tags":["tools"]}},"/api/v1/work-sessions":{"get":{"description":"Lists work sessions (one agent's run of work) with their failure facts. An agent token sees only its own sessions, and only the part of each that touched servers in its reach.","parameters":[{"description":"Only sessions with at least one failure","in":"query","name":"failed","schema":{"type":"boolean"}},{"description":"With failed: count policy blocks as failures (default true)","in":"query","name":"include_blocked","schema":{"type":"boolean"}},{"description":"Filter by agent token name","in":"query","name":"token","schema":{"type":"string"}},{"description":"Filter by client id","in":"query","name":"client","schema":{"type":"string"}},{"description":"Filter by profile (administrators only)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Filter by run name","in":"query","name":"run","schema":{"type":"string"}},{"description":"Filter by the error class of the last failure","in":"query","name":"error_class","schema":{"type":"string"}},{"description":"Only sessions active at or after this time (RFC3339)","in":"query","name":"since","schema":{"type":"string"}},{"description":"Only sessions active at or before this time (RFC3339)","in":"query","name":"until","schema":{"type":"string"}},{"description":"last_activity (default) or last_failure","in":"query","name":"sort","schema":{"enum":["last_activity","last_failure"],"type":"string"}},{"description":"Page size (default 25, max 100)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Page offset","in":"query","name":"offset","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.WorkSessionListEnvelope"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad Request"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List work sessions","tags":["activity"]}},"/api/v1/work-sessions/{id}":{"get":{"parameters":[{"description":"Work session id","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.WorkSessionEnvelope"}}},"description":"OK"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Not Found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get one work session","tags":["activity"]}},"/api/v1/work-sessions/{id}/timeline":{"get":{"description":"Returns the session's activity rows and the upstream events of the servers it called, in time order, positioned at a failure, a row or the end. Bodies are omitted unless include_bodies is set.","parameters":[{"description":"Work session id","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"first_failure (default), failure:\u003cn\u003e, row:\u003cactivity id\u003e or end","in":"query","name":"at","schema":{"type":"string"}},{"description":"Rows before the position (default 20, max 250)","in":"query","name":"before","schema":{"type":"integer"}},{"description":"Rows after the position (default 20, max 250)","in":"query","name":"after","schema":{"type":"integer"}},{"description":"Include argument and response bodies","in":"query","name":"include_bodies","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.WorkSessionTimelineEnvelope"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad Request"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Not Found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get a work session's timeline","tags":["activity"]}},"/healthz":{"get":{"description":"Get comprehensive health status including all component health (Kubernetes-compatible liveness probe)","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.HealthResponse"}}},"description":"Service is healthy"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.HealthResponse"}}},"description":"Service is unhealthy"}},"summary":"Get health status","tags":["health"]}},"/readyz":{"get":{"description":"Get readiness status including all component readiness checks (Kubernetes-compatible readiness probe)","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.ReadinessResponse"}}},"description":"Service is ready"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.ReadinessResponse"}}},"description":"Service is not ready"}},"summary":"Get readiness status","tags":["health"]}}}, + "paths": {"/api/v1/access/explain":{"get":{"description":"For one subject (exactly one of client=\u003cid\u003e, token=\u003cname\u003e, profile=\u003cname\u003e or anonymous=true) and one upstream tool (server:tool), returns the ordered chain of gates a real call would meet - credential, profile, server_in_scope, tool_rule, tier_cap, token_permission, global_gate, server_state, tool_approval - the overall verdict (allowed, blocked, hidden), the first failing step and the fixes for it in preference order. The chain is the one every discovery and dispatch path walks, so ` + "`" + `allowed` + "`" + ` equals what a real call does. Built-in management tools are not explained (400). A client credential is explained with client=, never token=. Administrators only.","parameters":[{"description":"Upstream tool as server:tool","in":"query","name":"tool","required":true,"schema":{"type":"string"}},{"description":"Client id","in":"query","name":"client","schema":{"type":"string"}},{"description":"Regular agent token name","in":"query","name":"token","schema":{"type":"string"}},{"description":"Profile name","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Explain an anonymous (credential-less) caller","in":"query","name":"anonymous","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The explanation"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Not exactly one subject, a built-in tool, or token=client-\u003cid\u003e"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"client / token / profile not found"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Explain why a tool is or is not reachable","tags":["access"]}},"/api/v1/access/suggest":{"get":{"description":"Reads the profile refusals in the activity log over a look-back window and groups them by profile, tool and block reason. Each group is re-checked with the access explainer, so tools that are already reachable drop out, and carries the explainer's fixes. A deny-rule block is reported and never offered for widening; an unannotated tool is never given a tier. Nothing is applied. patch=true also returns the proposed profile document per profile (the body PUT /api/v1/profiles/{name} takes).","parameters":[{"description":"Look-back window: a duration such as 90m, 24h or 7d (default 24h; the audit-log retention is the only limit)","in":"query","name":"since","schema":{"type":"string"}},{"description":"Only refusals under this profile","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Only refusals of this token","in":"query","name":"token","schema":{"type":"string"}},{"description":"Also return the proposed profile document per profile","in":"query","name":"patch","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The suggestions"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid since"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Suggest profile changes from blocked calls","tags":["access"]}},"/api/v1/activity":{"get":{"description":"Returns paginated list of activity records with optional filtering","parameters":[{"description":"Filter by activity type(s), comma-separated for multiple (Spec 024)","in":"query","name":"type","schema":{"enum":["tool_call","policy_decision","quarantine_change","server_change","system_start","system_stop","internal_tool_call","config_change","preflight","prompt_get","profile_change","upstream_event"],"type":"string"}},{"description":"Filter by server name","in":"query","name":"server","schema":{"type":"string"}},{"description":"Filter by tool name","in":"query","name":"tool","schema":{"type":"string"}},{"description":"Filter by MCP transport session ID","in":"query","name":"session_id","schema":{"type":"string"}},{"description":"Filter by work session (one client, one project, across reconnects)","in":"query","name":"work_session_id","schema":{"type":"string"}},{"description":"Filter by status","in":"query","name":"status","schema":{"enum":["success","error","blocked","rejected"],"type":"string"}},{"description":"Filter by intent operation type (Spec 018)","in":"query","name":"intent_type","schema":{"enum":["read","write","destructive"],"type":"string"}},{"description":"Filter by HTTP request ID for log correlation (Spec 021)","in":"query","name":"request_id","schema":{"type":"string"}},{"description":"Filter by parent call id — returns the sub-calls one code_execution issued","in":"query","name":"parent_id","schema":{"type":"string"}},{"description":"Filter by call-error class (Spec 113-c)","in":"query","name":"error_class","schema":{"enum":["network","timeout","http","jsonrpc","tool_error","session_terminated","auth","proxy_policy","proxy_internal","cancelled"],"type":"string"}},{"description":"Filter by fault domain (Spec 113-c)","in":"query","name":"fault_domain","schema":{"enum":["upstream","proxy","client"],"type":"string"}},{"description":"Include successful call_tool_* internal tool calls (default: false, excluded to avoid duplicates)","in":"query","name":"include_call_tool","schema":{"type":"boolean"}},{"description":"Filter by sensitive data detection (true=has detections, false=no detections)","in":"query","name":"sensitive_data","schema":{"type":"boolean"}},{"description":"Filter by specific detection type (e.g., 'aws_access_key', 'credit_card')","in":"query","name":"detection_type","schema":{"type":"string"}},{"description":"Filter by severity level","in":"query","name":"severity","schema":{"enum":["critical","high","medium","low"],"type":"string"}},{"description":"Alias of token (Spec 028)","in":"query","name":"agent","schema":{"type":"string"}},{"description":"Filter by the token in effect for the call; - selects records with no token (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Filter by the profile in effect for the call; - selects records with no profile (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Filter by client id; - selects records with no client (Spec 108)","in":"query","name":"client","schema":{"type":"string"}},{"description":"Filter by the client's self-reported name (advisory; Spec 108)","in":"query","name":"client_name","schema":{"type":"string"}},{"description":"Filter by auth type (Spec 028)","in":"query","name":"auth_type","schema":{"enum":["admin","agent"],"type":"string"}},{"description":"Filter activities after this time (RFC3339)","in":"query","name":"start_time","schema":{"type":"string"}},{"description":"Filter activities before this time (RFC3339)","in":"query","name":"end_time","schema":{"type":"string"}},{"description":"Maximum records to return (1-100, default 50)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Pagination offset (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Omit arguments, response and metadata except a contextual whitelist (intent.reason, intent.operation_type, decision, reason, client_name, client_version) (default: false). For clients that render summary fields only; has_sensitive_data is still derived before metadata is dropped.","in":"query","name":"exclude_payloads","schema":{"type":"boolean"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"List activity records","tags":["Activity"]}},"/api/v1/activity/export":{"get":{"description":"Exports activity records in JSON Lines or CSV format for compliance","parameters":[{"description":"Export format: json (default) or csv","in":"query","name":"format","schema":{"type":"string"}},{"description":"Filter by activity type","in":"query","name":"type","schema":{"type":"string"}},{"description":"Filter by server name","in":"query","name":"server","schema":{"type":"string"}},{"description":"Filter by tool name","in":"query","name":"tool","schema":{"type":"string"}},{"description":"Filter by MCP transport session ID","in":"query","name":"session_id","schema":{"type":"string"}},{"description":"Filter by work session (one client, one project, across reconnects)","in":"query","name":"work_session_id","schema":{"type":"string"}},{"description":"Filter by status","in":"query","name":"status","schema":{"type":"string"}},{"description":"Filter by HTTP request ID for log correlation (Spec 021)","in":"query","name":"request_id","schema":{"type":"string"}},{"description":"Filter by parent call id — exports the sub-calls one code_execution issued","in":"query","name":"parent_id","schema":{"type":"string"}},{"description":"Filter by call-error class (Spec 113-c)","in":"query","name":"error_class","schema":{"enum":["network","timeout","http","jsonrpc","tool_error","session_terminated","auth","proxy_policy","proxy_internal","cancelled"],"type":"string"}},{"description":"Filter by fault domain (Spec 113-c)","in":"query","name":"fault_domain","schema":{"enum":["upstream","proxy","client"],"type":"string"}},{"description":"Alias of token (Spec 028)","in":"query","name":"agent","schema":{"type":"string"}},{"description":"Filter by the token in effect for the call; - selects records with no token (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Filter by the profile in effect for the call; - selects records with no profile (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Filter by client id; - selects records with no client (Spec 108)","in":"query","name":"client","schema":{"type":"string"}},{"description":"Filter by the client's self-reported name (advisory; Spec 108)","in":"query","name":"client_name","schema":{"type":"string"}},{"description":"Filter activities after this time (RFC3339)","in":"query","name":"start_time","schema":{"type":"string"}},{"description":"Filter activities before this time (RFC3339)","in":"query","name":"end_time","schema":{"type":"string"}},{"description":"Maximum records to export (1-50000, default 10000)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Pagination offset (default 0)","in":"query","name":"offset","schema":{"type":"integer"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"type":"string"}},"application/x-ndjson":{"schema":{"type":"string"}},"text/csv":{"schema":{"type":"string"}}},"description":"Streamed activity records"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Export activity records","tags":["Activity"]}},"/api/v1/activity/summary":{"get":{"description":"Returns aggregated activity statistics for a time period","parameters":[{"description":"Time period: 1h, 24h (default), 7d, 30d","in":"query","name":"period","schema":{"type":"string"}},{"description":"Group by: server, tool (optional)","in":"query","name":"group_by","schema":{"type":"string"}},{"description":"Alias of token (Spec 028)","in":"query","name":"agent","schema":{"type":"string"}},{"description":"Count only records made under this token; - selects records with no token (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Count only records made under this profile; - selects records with no profile (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Count only records made by this client id; - selects records with no client (Spec 108)","in":"query","name":"client","schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Get activity summary statistics","tags":["Activity"]}},"/api/v1/activity/usage":{"get":{"description":"Returns the actor-owned usage aggregate (per-tool rollup + timeline + tokens-saved headline) for the Web UI usage graphs (Spec 069). Served from an in-memory snapshot — never a per-request full-log scan. Per-tool metrics are lifetime-cumulative; ` + "`" + `window` + "`" + ` scopes the timeline and filters the tool list to tools active within the span.","parameters":[{"description":"Time window for timeline + tool-list membership","in":"query","name":"window","schema":{"enum":["24h","7d","all"],"type":"string"}},{"description":"Filter to one server","in":"query","name":"server","schema":{"type":"string"}},{"description":"Filter to one tool","in":"query","name":"tool","schema":{"type":"string"}},{"description":"Filter to tools with activity of this status","in":"query","name":"status","schema":{"enum":["success","error","blocked","rejected"],"type":"string"}},{"description":"Top-N tools by sort key; remainder folded into 'other' (default 20)","in":"query","name":"top","schema":{"type":"integer"}},{"description":"Ranking key for the per-tool list","in":"query","name":"sort","schema":{"enum":["calls","resp_bytes","error_rate","p95"],"type":"string"}},{"description":"Alias of token (Spec 028)","in":"query","name":"agent","schema":{"type":"string"}},{"description":"Restrict to calls made under this token; - selects records with no token. Computed from a window-bounded scan (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Restrict to calls made under this profile; - selects records with no profile. Computed from a window-bounded scan (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Restrict to calls made by this client id; - selects records with no client. Computed from a window-bounded scan (Spec 108)","in":"query","name":"client","schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Get usage statistics aggregate","tags":["Activity"]}},"/api/v1/activity/{id}":{"get":{"description":"Returns full details for a single activity record","parameters":[{"description":"Activity record ID (ULID)","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Not Found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Get activity record details","tags":["Activity"]}},"/api/v1/annotations/coverage":{"get":{"description":"Reports how many upstream tools have MCP annotations vs don't, broken down by server","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Annotation coverage report"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get annotation coverage report","tags":["annotations"]}},"/api/v1/attention":{"get":{"description":"One list, one count, every surface (Web UI, macOS tray/Home, CLI) reads from it. Filtered per caller: an administrator sees every item; a scoped caller (agent token, or a non-admin server-edition OAuth user session) sees only server items whose server it may enumerate (for a profile-pinned token: servers within its pin); every other subject type (client, setting) and the skill_review kind (Spec 125 held skills) are administrator-only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.attentionResponse"}}},"description":"The needs-attention list"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the needs-attention list","tags":["attention"]}},"/api/v1/catalog/search":{"get":{"description":"Fans out to every enabled catalog source (registry) in parallel, merges, de-duplicates and ranks the results (FR-060/061). An empty q returns official + popular sections instead of a flat list. Open to any authenticated caller — added is the only field filtered per caller scope (FR-007).","parameters":[{"description":"Free-text search","in":"query","name":"q","schema":{"type":"string"}},{"description":"Narrow to one catalog source id","in":"query","name":"source","schema":{"type":"string"}},{"description":"Not supported: catalog entries carry no tags; a non-empty value returns 400","in":"query","name":"tag","schema":{"type":"string"}},{"description":"Max results (default 20, max 50)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"tag filtering is not supported"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"configured servers could not be listed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Search the server catalog across every enabled source","tags":["catalog"]}},"/api/v1/clients":{"get":{"description":"Lists every client row (supported, other and custom) with its presence, its credential and its profile binding, plus response-level warnings. The list is content-read-free (Spec 075): credential_state comes from the token store, else the last on-demand observation (credential_checked_at), else unknown. It runs only the time-based half of the rotation reconciler. The profile and client filters match the CURRENT binding and are applied AFTER warnings are computed over the full set.","parameters":[{"description":"Rows whose active credential is bound to this profile; - = bound to All servers","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Exact client id","in":"query","name":"client","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Client rows, routing and warnings"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List clients","tags":["clients"]},"post":{"description":"Creates a per-client credential for a client that is NOT in the connect registry (a script, a CI job, an editor without a connect adapter). The secret (mcp_cli_...) is returned ONCE, with a paste-ready snippet that carries it in the X-API-Key header. The id follows the client-id rule (lower-case letters, digits, '-' or '_', at most 56 characters) and must not be a supported client's id. A named profile binds the credential locked unless mode says otherwise. Refused with 409 binding_bypassable_without_auth when the binding would be bypassable while require_mcp_auth is off (FR-008a), and 409 conflicting_token when a regular token holds client-\u003cid\u003e. Every value (id, display_name, profile, mode, expires_in, purpose) passes the shared secret-shaped input screen first: a credential, the API key or a detector-flagged secret answers 400 secret_in_argument naming the field, and nothing is minted. A malformed body answers a sanitized 400 that never echoes a caller key or value. Writes one profile_change record with change issue (Spec 115) and publishes credentials.changed. Personal edition only.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.CreateClientRequest"}}},"description":"id (required), optional display_name, profile, mode, expires_in and purpose","required":true},"responses":{"201":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The new client row, its credential (once) and a snippet"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"binding_bypassable_without_auth, or conflicting_token (ClientCredentialConflictResponse)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add a custom client","tags":["clients"]}},"/api/v1/clients/bulk-assign":{"post":{"description":"Moves every client credential bound to from_profile (\"\" = All servers) onto to_profile (\"\" = All servers). The guard and the credential precondition apply PER CLIENT: a refused client is reported in skipped[] with the code the single operation returns, the others move and each writes its own assign record and emits client.binding_changed. Personal edition only.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BulkAssignRequest"}}},"description":"from_profile and to_profile (both required; empty = All servers) and optional mode","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Moved client ids and the clients that were skipped"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Move every client of one profile to another","tags":["clients"]}},"/api/v1/clients/upgrade-admin-key-holders":{"post":{"description":"Without apply: classifies every supported client whose config still holds the instance admin API key (an on-demand read per client) and returns preview[] (display path, what would change, the masked credential mcp_cli_••••, the binding and a precondition_token per client), a combined precondition_token, and guard when the whole request would be refused by FR-008a; next_step is rotate_admin_api_key when nothing holds the key. Nothing is written or minted. With apply=true: recomputes the preview, refuses with 409 precondition_failed when a sent precondition_token no longer matches, runs the FR-008a guard over the WHOLE request (409 binding_bypassable_without_auth, nothing minted, no file written), then connects each client with force bound to its own token; one client's failure does not stop the others. Each mint writes its own assign record. The guard only applies when a named profile is given. Personal edition only.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.UpgradeAdminKeyHoldersRequest"}}},"description":"Optional profile and mode for every upgraded client; apply and precondition_token"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"UpgradePreview (no apply) or UpgradeResult (apply)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"precondition_failed, or binding_bypassable_without_auth"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Upgrade every client that holds the admin API key","tags":["clients"]}},"/api/v1/clients/{client}":{"delete":{"description":"Revokes the client's credential; it stops authenticating at once. With disconnect=true a SUPPORTED client's mcpproxy entry is removed from its config FIRST, but the credential is revoked either way: revocation never waits for a config write, so a failed write (for example a macOS App-Data denial) leaves the client cut off and is reported as disconnected:false with disconnect_error. A client with no credential record is 409 no_client_credential. disconnect=true on a custom client is ignored. Writes one forget record naming the revoked token. The FR-008a guard is not involved: revoking only removes a binding.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}},{"description":"Also remove the entry from the client's config (supported clients)","in":"query","name":"disconnect","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Revoked token name and what happened to the config entry"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"no_client_credential"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Forget a client (revoke its credential)","tags":["clients"]},"get":{"description":"Returns one client row with its sessions (newest 20, each with its latest effective profile). This is the only read that may open the client's config file: it runs the full rotation reconciler first, classifies the credential the config holds and records the observation. No scope filter is honoured on this route.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Client row"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"client not found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get one client","tags":["clients"]}},"/api/v1/clients/{client}/api-key":{"delete":{"description":"Revokes the client's mcp_cli_ credential alone: its browser logins and its binding stay. 404 no_client_credential when the client has no active API key. Writes a revoke record. Administrator only.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The key was revoked"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid client id"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"no_client_credential"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Revoke a client's API key only","tags":["clients"]}},"/api/v1/clients/{client}/binding":{"put":{"description":"Changes the profile binding (and optionally the locked/switchable mode) of a\nclient that holds an active client credential. One service operation shared by\nevery surface: it updates the credential in the token store, clears the stored\nset_profile selection of every live session of that credential, sends\nnotifications/tools/list_changed to each, emits client.binding_changed and writes\none profile_change activity record. It never touches the client's config file.\nA client without an active client credential (none, admin key, revoked or expired)\nis refused with 409 no_client_credential and nothing is minted or written. A\nreassignment that would leave the binding bypassable while require_mcp_auth is off\nis refused with 409 binding_bypassable_without_auth (FR-008a). Personal edition only.","parameters":[{"description":"Client id (lower-case letters, digits, '-' or '_', at most 56 characters)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.PutClientBindingRequest"}}},"description":"profile (required; empty = All servers) and optional mode (locked|switchable)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The client row after the change, with its warnings"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"no_client_credential, connect_in_progress (a connect of this client is mid-write), or binding_bypassable_without_auth with bindings and fixes"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Reassign a client's profile and/or mode","tags":["clients"]}},"/api/v1/clients/{client}/logins/{grant_id}":{"delete":{"description":"Revokes the login (reason admin): its access token stops authenticating on the next request, live sessions are told to re-list, and a revoke record names the administrator. Works while browser login is on and while it is off after use. An already revoked login answers changed:false; an unknown login (or one of another client) is 404. Administrator only.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}},{"description":"Login id","in":"path","name":"grant_id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Whether the login changed"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"login not found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Revoke one browser login of a client","tags":["clients"]}},"/api/v1/clients/{client}/rotate":{"post":{"description":"Replaces a client's secret without ever invalidating the old one mid-flight (FR-021a). A SUPPORTED client is rewritten through connect: staged rotation, binding kept, finalized when the config write succeeds, rolled back (the old secret keeps working) when it fails; a preview's precondition_token binds the call, a mismatch is the connect 409 precondition_failed. A CUSTOM client gets a new secret returned ONCE with a snippet; both secrets authenticate until POST /clients/{client}/rotate/finalize or 24 hours. A client with no active credential is 409 no_client_credential. The FR-008a guard is not involved: a rotation never changes a binding's reach. Writes one rotate record when it finalizes.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.RotateClientRequest"}}},"description":"Optional precondition_token of a connect preview"},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The client row and the rotation state"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required (or macOS App-Data block)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectConflictResponse"}}},"description":"no_client_credential, precondition_failed, connect_in_progress (another connect of this client is mid-write), or credential_superseded (the written credential was replaced or revoked before it could be finalized; reconnect)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Rotate a client's credential","tags":["clients"]}},"/api/v1/clients/{client}/rotate/finalize":{"post":{"description":"Promotes a client's pending secret: the old secret stops authenticating. Idempotent: with no rotation in progress it is a no-op success. A client with no client credential is 409 no_client_credential. Writes one rotate record when it promotes.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The client row; rotation.state is finalized"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"no_client_credential, or connect_in_progress (a connect of this client is mid-write)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Finalize a staged rotation","tags":["clients"]}},"/api/v1/code/scripts":{"get":{"description":"List the stored scripts available to the code_execution tool. Scripts are ` + "`" + `\u003cname\u003e.js` + "`" + ` / ` + "`" + `\u003cname\u003e.ts` + "`" + ` files in the ` + "`" + `scripts/` + "`" + ` directory next to the active configuration file. Entries are advisory: ` + "`" + `ok` + "`" + ` scripts are invocable, ` + "`" + `ambiguous` + "`" + ` names have both extensions, and ` + "`" + `invalid` + "`" + ` ones report why (empty, oversized, unreadable, non-regular). Read-only — there is no write surface for stored scripts. Administrator-only (Spec 105 FR-012): an agent token, whatever its server scope, is refused with 403 — the listing is the enumeration the missing-script error withholds from a scoped caller.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Stored scripts and the directory they were read from"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot list stored scripts"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List stored code-execution scripts","tags":["code"]}},"/api/v1/config":{"get":{"description":"Retrieves the current MCPProxy configuration including all server definitions, global settings, and runtime parameters","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetConfigResponse"}}},"description":"Configuration retrieved successfully"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read the configuration document"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get current configuration","tags":["config"]},"patch":{"description":"Deep-merges only the fields present in the request body onto the live in-memory configuration and routes the result through the existing apply pipeline (validation, change detection, disk persistence, hot-reload). Fields the client omits — including masked secrets such as ` + "`" + `api_key` + "`" + ` and secret request headers — are preserved verbatim. Nested objects are merged recursively; arrays and scalars replace wholesale.","requestBody":{"content":{"application/json":{"schema":{"type":"object"}}},"description":"Partial configuration with only the fields to change","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ConfigApplyResult"}}},"description":"Configuration patch applied (inspect validation_errors for rejected values)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload or empty patch"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate configuration)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"binding_bypassable_without_auth: the patch would let a client bound to a named profile escape it while require_mcp_auth is off (FR-008a); nothing was written"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"telemetry.enabled is locked while an environment variable (DO_NOT_TRACK, CI, MCPPROXY_TELEMETRY=false) disables telemetry; nothing was written (FR-044a)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to read or apply configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Partially update configuration","tags":["config"]}},"/api/v1/config/apply":{"post":{"description":"Applies a new MCPProxy configuration. Validates and persists the configuration to disk. Some changes apply immediately, while others may require a restart. Returns detailed information about applied changes and restart requirements.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.Config"}}},"description":"Configuration to apply","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ConfigApplyResult"}}},"description":"Configuration applied successfully with change details"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate configuration)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"binding_bypassable_without_auth: the write would let a client bound to a named profile escape it while require_mcp_auth is off (FR-008a); nothing was written"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"telemetry.enabled is locked while an environment variable (DO_NOT_TRACK, CI, MCPPROXY_TELEMETRY=false) disables telemetry; nothing was written (FR-044a)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to apply configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Apply configuration","tags":["config"]}},"/api/v1/config/docker-isolation":{"patch":{"description":"Convenience endpoint to flip ` + "`" + `docker_isolation.enabled` + "`" + ` without resending the full config. Persists to disk via the existing config writer — the file watcher then hot-reloads the change. Returns the new state and whether a restart is required for existing connections to pick it up.","requestBody":{"content":{"application/json":{"schema":{"properties":{"enabled":{"type":"boolean"}},"type":"object"}}},"description":"New isolation state","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ConfigApplyResult"}}},"description":"Isolation toggle applied"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate configuration)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"binding_bypassable_without_auth (FR-008a); nothing was written"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to apply configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Toggle global Docker isolation","tags":["config"]}},"/api/v1/config/validate":{"post":{"description":"Validates a provided MCPProxy configuration without applying it. Checks for syntax errors, invalid server definitions, conflicting settings, and other configuration issues.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.Config"}}},"description":"Configuration to validate","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ValidateConfigResponse"}}},"description":"Configuration validation result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Validation failed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Validate configuration","tags":["config"]}},"/api/v1/connect":{"get":{"description":"Returns the connection status for all known MCP client applications.\nEach entry indicates whether the client config file exists and whether\nMCPProxy is currently registered in it. This stat-only listing never reads\na client config (Spec 075), so a client whose config exists reports\ncredential_state \"unknown\"; GET /connect/{client} resolves it.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"List of ClientStatus objects"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List client connection status","tags":["connect"]}},"/api/v1/connect/{client}":{"delete":{"description":"Remove the MCPProxy entry from the specified client's configuration file.\nCreates a backup of the existing config before modifying.\nAlso revokes the client's credential (it stops authenticating at once); the result names it in credential_revoked, or reports credential_revoke_error when the revoke failed after the entry was removed. Undoing a disconnect does not restore the credential: a later connect mints a new one.","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectRequest"}}},"description":"Optional parameters (server_name)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectResult"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Permission denied (macOS App-Data block)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client or entry not found"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Disconnect MCPProxy from a client","tags":["connect"]},"get":{"description":"Resolves one client's status by reading its config file on demand.\nThis is the only Connect endpoint that opens a client config file, so\non macOS it is the sole place an App-Data privacy prompt may legitimately\nappear (scoped to this user action). Resolves access_state to\naccessible|absent|denied|malformed and populates remediation when denied.\nFor a connected client it also resolves credential_state (Spec 108 FR-025):\nclient (an active per-client credential), admin_key (the instance admin API\nkey), none, revoked (a rotated-away or revoked credential) or expired. The\ncredential value is classified and never echoed.","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ClientStatus"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get a single client's connection status (on-demand)","tags":["connect"]},"post":{"description":"Register MCPProxy as an MCP server in the specified client's configuration file.\nCreates a backup of the existing config before modifying.\nOptionally accepts precondition_token from a preview (Spec 091): when supplied,\nthe core rechecks the raw pre-write state and the entry it would write, and\nrefuses a drifted write with 409 before taking any backup. The 409 body's\naction discriminates the two conflict kinds: \"precondition_failed\" (stale\npreview — re-preview, do not retry) vs \"already_exists\" (entry present — pass\nforce=true). force=true never rescues a stale token.\n\nSpec 108 FR-024: the entry carries a per-client mcp_cli_ credential bound to the\nrequested profile (default: All servers, switchable; a reconnect keeps the client's\nexisting binding unless a profile is given), never the instance admin API key.\nReconnecting over an active credential is a staged rotation: the old secret keeps\nworking until the config write succeeds. keyless=true writes no credential and is\nonly possible while require_mcp_auth is off (400 otherwise, and with a profile).\nA write that would let the client escape its profile by omitting its credential\nwhile require_mcp_auth is off is refused with 409 binding_bypassable_without_auth\n(nothing minted or written); a token named client-\u003cid\u003e held by a regular agent\ntoken is refused with 409 conflicting_token.","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectRequest"}}},"description":"Optional connection parameters (server_name, force, precondition_token, profile, mode, keyless)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectResult (credential is the masked mcp_cli_ value, with token_name, profile, mode, keyless and rotation)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Bad request; field names the offending input (profile, mode, keyless)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Permission denied (macOS App-Data block)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectConflictResponse"}}},"description":"Conflict: action=already_exists (use force=true) or action=precondition_failed (preview is stale; re-preview); or binding_bypassable_without_auth (BindingGuardResponse); or conflicting_token (ClientCredentialConflictResponse); or connect_in_progress (another connect of this client is mid-write) or credential_superseded (the written credential was replaced or revoked before it could be finalized; reconnect)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable (or no credential store wired while require_mcp_auth is on)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Connect MCPProxy to a client","tags":["connect"]}},"/api/v1/connect/{client}/preview":{"get":{"description":"Returns the exact entry a subsequent connect would add to the client's\nconfig — target path, server key, entry name, and entry contents — WITHOUT\nmodifying the file or creating a backup (Spec 078 US1). The per-client credential\nis masked in the payload (credential, always starting mcp_cli_; contains_api_key is\nalways false since connect never writes the admin API key); profile, mode and\nkeyless echo the requested intent.\nentry_exists distinguishes a create from an overwrite of a same-named entry.\nReads the config on demand to classify create-vs-overwrite, so on macOS this\nmay raise an App-Data privacy prompt; a denial returns 403 + remediation.\nSpec 091 adds three fields: existing_entry_summary (present only when\nentry_exists — a sanitized, non-secret projection of the entry being replaced:\nits name, type, endpoint with query/userinfo stripped, command, and header and\nenv NAMES, never values); precondition_token (always present — an opaque keyed\ndigest of the raw pre-write state and the pending entry, echoed back on POST\nconnect to detect drift); and connect_refusal (present when the write would\nrefuse regardless of intent, e.g. a non-create-capable client with no config —\ntreat its presence as \"Connect unavailable\").","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}},{"description":"Entry name to preview (defaults to mcpproxy); mirror the value passed to POST connect","in":"query","name":"server_name","schema":{"type":"string"}},{"description":"Profile the client credential would bind to (empty = All servers); mirror POST connect","in":"query","name":"profile","schema":{"type":"string"}},{"description":"locked|switchable; mirror POST connect","in":"query","name":"mode","schema":{"enum":["locked","switchable"],"type":"string"}},{"description":"Preview a credential-less entry (only while require_mcp_auth is off)","in":"query","name":"keyless","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectPreview"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid intent (field names the input; keyless with auth on or with a profile)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required or access denied by macOS App Data"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Preview the change a connect would make (no write)","tags":["connect"]}},"/api/v1/connect/{client}/undo":{"post":{"description":"Reverts the connect that produced the named backup (Spec 078 US3):\nrestores the client config byte-for-byte from that backup, or — when\nbackup_name is empty because the connect created the file — deletes the\ncreated file. backup_name is the bare filename of the backup the connect\nreturned (never a path); undo resolves the full path server-side inside\nthe client's own config directory, so a client value cannot escape it.\nRefuses with 409 when the config changed since the connect (undo never\nclobbers later edits; use DELETE /connect/{client} for a surgical entry\nremoval instead). Takes its own safety backup first; its path is returned\nas backup_path in the result. Undo is \"as if the connect never happened\": a\nclient credential the connect minted or rotated is revoked unless the restored\nconfig still holds it, and the result names it in credential_revoked.","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.UndoConnectRequest"}}},"description":"Undo parameters (server_name, backup_name = the bare filename of the backup the preceding connect returned)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectResult (action restored|deleted)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (e.g. backup_name is a path, or not a backup of this client's config)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Permission denied (macOS App-Data block)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client or backup no longer exists"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Config changed since connect; undo refused"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Undo a connect, restoring the pre-connect config","tags":["connect"]}},"/api/v1/diagnostics":{"get":{"description":"Get comprehensive health diagnostics including upstream errors, OAuth requirements, missing secrets, and Docker status","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.Diagnostics"}}},"description":"Health diagnostics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get health diagnostics","tags":["diagnostics"]}},"/api/v1/docker/status":{"get":{"description":"Retrieve current Docker availability and recovery status","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Docker status information"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get Docker status","tags":["docker"]}},"/api/v1/doctor":{"get":{"description":"Get comprehensive health diagnostics including upstream errors, OAuth requirements, missing secrets, and Docker status","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.Diagnostics"}}},"description":"Health diagnostics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get health diagnostics","tags":["diagnostics"]}},"/api/v1/feedback":{"post":{"description":"Submit a bug report, feature request, or general feedback","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/telemetry.FeedbackRequest"}}},"description":"Feedback request","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/telemetry.FeedbackResponse"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"additionalProperties":{"type":"string"},"type":"object"}}},"description":"Bad Request"},"429":{"content":{"application/json":{"schema":{"additionalProperties":{"type":"string"},"type":"object"}}},"description":"Too Many Requests"},"500":{"content":{"application/json":{"schema":{"additionalProperties":{"type":"string"},"type":"object"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyAuth":[]}],"summary":"Submit feedback","tags":["feedback"]}},"/api/v1/index/search":{"get":{"description":"Search across all upstream MCP server tools using BM25 keyword search","parameters":[{"description":"Search query","in":"query","name":"q","required":true,"schema":{"type":"string"}},{"description":"Maximum number of results","in":"query","name":"limit","schema":{"default":10,"maximum":100,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SearchToolsResponse"}}},"description":"Search results"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing query parameter)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Search for tools","tags":["tools"]}},"/api/v1/info":{"get":{"description":"Get essential server metadata including version, web UI URL, endpoint addresses, and update availability\nweb_ui_url carries the ?apikey= credential ONLY for an authenticated admin; a scoped agent token receives the bare URL\nThis endpoint is designed for tray-core communication and version checking\nUse refresh=true query parameter to force an immediate update check against GitHub\nThe launched_by field reports durable launch provenance (\"tray\", \"installer\", or \"\" for user-launched/unknown)","parameters":[{"description":"Force immediate update check against GitHub","in":"query","name":"refresh","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Server information with optional update info"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server information","tags":["status"]}},"/api/v1/oauth/authorizations":{"get":{"description":"Pending browser-login requests, newest first: id, a sanitised client label and the times. Used by the tray and Home. 404 feature_disabled while browser login is off. Administrator only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Pending requests"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"feature_disabled"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List pending sign-in requests","tags":["clients"]}},"/api/v1/oauth/authorizations/{id}":{"get":{"description":"Everything the consent view needs: the reported (unverified) name, the redirect URI, the resource, how the address fixes the client, the profiles, whether a profile must be chosen, the previous login of the same registration and, for a fixed client that has a binding, the guard verdict. One uniform 404 for an unknown, expired, decided or cancelled id. Administrator only.","parameters":[{"description":"Request id","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"The request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"request_not_found or feature_disabled"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Read one sign-in request","tags":["clients"]}},"/api/v1/oauth/authorizations/{id}/approve":{"post":{"description":"Records the decision and issues the code; the login itself is stored when the client exchanges the code. 409 already_decided, 409 binding_changed (the binding differs from binding_revision), 409 binding_bypassable_without_auth (with the guard's fixes), 422 profile_required, client_fixed, identity_exists, reserved_identity, 404 profile_not_found. Writes an approve record naming the administrator. Administrator only.","parameters":[{"description":"Request id","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.OAuthApprovalBody"}}},"description":"client, profile, mode, binding_revision, replace_grant","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Where the page navigates"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"request_not_found, profile_not_found or feature_disabled"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"already_decided, binding_changed or binding_bypassable_without_auth"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"profile_required, client_fixed, identity_exists, reserved_identity"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Approve a sign-in request","tags":["clients"]}},"/api/v1/oauth/authorizations/{id}/deny":{"post":{"description":"The redirect carries error=access_denied. 409 already_decided. Writes a deny record naming the administrator. Administrator only.","parameters":[{"description":"Request id","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Where the page navigates"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"request_not_found or feature_disabled"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"already_decided"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Deny a sign-in request","tags":["clients"]}},"/api/v1/oauth/authorizations/{id}/preview":{"post":{"description":"Read-only: for a proposed client (existing or new), profile and mode, returns whether the choice is complete, the access sentence and the binding guard's verdict with its fixes. Writes nothing. The same 422 codes as approve for an invalid choice. Administrator only.","parameters":[{"description":"Request id","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.OAuthApprovalBody"}}},"description":"client, profile, mode","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"The preview"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"request_not_found, profile_not_found or feature_disabled"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"client_fixed, identity_exists, reserved_identity"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Preview a sign-in decision","tags":["clients"]}},"/api/v1/onboarding/mark":{"post":{"description":"Updates wizard engagement and per-step status. Once engaged is\ntrue, the wizard does not auto-show again, even if state regresses.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.OnboardingMarkRequest"}}},"description":"Mark request","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Updated OnboardingStateResponse"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read onboarding state"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Mark onboarding wizard state (Spec 046)","tags":["onboarding"]}},"/api/v1/onboarding/state":{"get":{"description":"Returns the wizard engagement record alongside live predicates\n(whether any client is connected, whether any server is configured),\nplus a derived ShouldShowWizard flag the frontend can rely on.","responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OnboardingStateResponse"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read onboarding state"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get onboarding wizard state and predicates (Spec 046)","tags":["onboarding"]}},"/api/v1/preflight":{"post":{"description":"Deterministic, side-effect-free availability check for a caller-supplied list of tool IDs (Spec 098). Performs zero upstream calls and mutates no runtime state. HTTP status reports whether the CHECK executed: a fully blocked set is still 200, with the availability verdict in the body. Every executed preflight writes an activity record before the response is returned.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.PreflightRequest"}}},"description":"Tool IDs (1-100 before dedup), optional profile, annotation policy filters and wait budget","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Preflight verdict and per-tool results"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Validation error (malformed, oversized, doubled or unknown-field body; empty or oversized tool list; conflicting duplicate pins; unknown profile; wait_ms out of range)"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Missing or invalid credentials"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Runtime unavailable, evaluator infrastructure read failure, or the activity record could not be persisted"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Preflight required tools","tags":["tools"]}},"/api/v1/profiles":{"get":{"description":"Lists every profile as a ProfileView: the config fields as stored, the derived effective values, visible tool counts by tier, 24 h calls and blocked calls, and (administrators only) used_by and the anonymous_profile. A caller that is not an administrator sees only the profiles its entitlement reaches, with servers, rules and switchable_to narrowed to what it may see; an unreachable profile is omitted, never shown empty.","responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Profile list"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Configuration unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List configured profiles","tags":["profiles"]},"post":{"description":"Adds a profile. The body is a ProfileConfig. A name that already exists is 409 profile_exists; ` + "`" + `active` + "`" + ` and ` + "`" + `try` + "`" + ` are reserved by the REST API; a fatal validation rule is 400 with the offending field and the unchanged FR-007 text. A write that would let a client bound to a named profile escape it while require_mcp_auth is off is refused 409 binding_bypassable_without_auth (FR-008a) and nothing is written. Writes one profile_change record.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.ProfileConfig"}}},"description":"The profile","required":true},"responses":{"201":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Created, with the validator's warnings"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ProfileConflictResponse"}}},"description":"profile_exists, or binding_bypassable_without_auth (BindingGuardResponse)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Create a profile","tags":["profiles"]}},"/api/v1/profiles/active":{"get":{"description":"Deprecated (Spec 108 FR-039; sends a Deprecation header, successor GET /api/v1/profiles). Get the server-level default active profile used by UI surfaces (Web UI / tray). Empty string means \"all servers\". Note: within a live MCP session, the set_profile tool selection takes precedence over this default.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Active profile"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the default active profile","tags":["profiles"]},"put":{"description":"Deprecated (Spec 108 FR-039; sends a Deprecation header, successor GET /api/v1/profiles). Set the server-level default active profile for UI surfaces. The slug must match a configured profile; pass an empty string to clear. This does not affect live MCP sessions, which use the set_profile tool.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.SetActiveProfileRequest"}}},"description":"Profile slug to activate (empty clears)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Active profile updated"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request body"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot change the active profile)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown profile"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Set the default active profile","tags":["profiles"]}},"/api/v1/profiles/try":{"post":{"description":"Evaluates a DRAFT profile against a query exactly as retrieve_tools would (policy is applied before the limit) and returns the hits plus what the draft hides (hidden_by_profile and up to 100 {server, tool, reason}). The draft is validated as if it replaced the same-named profile, or was appended under a placeholder name when it has none. Nothing is persisted, no record is written, no event is published and the FR-008a guard does not run. Administrators only.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.TryProfileRequest"}}},"description":"draft profile, query and optional limit (default 10, max 50)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Search result under the draft"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid draft; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Try a draft profile","tags":["profiles"]}},"/api/v1/profiles/{name}":{"delete":{"description":"Deletes a profile. 409 profile_in_use (with used_by) while clients or tokens point at it, unless reassign_to names another existing profile (every pin moves there) or force is set (pins are left dangling, which the resolver treats as deny-all). 409 profile_is_anonymous_profile whenever it is the anonymous_profile and reassign_to is absent, even with force. Both paths remove the name from every switchable_to. Guarded by FR-008a. Writes one ` + "`" + `delete` + "`" + ` record.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}},{"description":"Another existing profile that takes over the pins","in":"query","name":"reassign_to","schema":{"type":"string"}},{"description":"Delete although in use, leaving pins dangling","in":"query","name":"force","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Deleted"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"reassign_to does not name another existing profile"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ProfileConflictResponse"}}},"description":"profile_in_use, profile_is_anonymous_profile, or binding_bypassable_without_auth (BindingGuardResponse)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Delete a profile","tags":["profiles"]},"get":{"description":"Returns the ProfileView of the named profile. A caller that is not an administrator gets the same 404 for an unreachable profile as for an unknown one.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The profile"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get one profile","tags":["profiles"]},"put":{"description":"Replaces the named profile with the body (a ProfileConfig whose name, when sent non-empty, must equal the path; 409 name_mismatch otherwise - a rename has its own route; an omitted or empty name takes the path's). A write whose only change is tools.classify is recorded as ` + "`" + `classify` + "`" + `. Guarded by FR-008a like a create.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.ProfileConfig"}}},"description":"The profile","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Updated, with the validator's warnings"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ProfileConflictResponse"}}},"description":"name_mismatch, or binding_bypassable_without_auth (BindingGuardResponse)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Replace a profile","tags":["profiles"]}},"/api/v1/profiles/{name}/effective-tools":{"get":{"description":"One row per catalog tool with the verdict of the access chain (the same rendering GET /tools?profile= uses): server, tool, intrinsic_tier, profile_tier, access{visible, callable, reason} and classification_stale. With client=\u003cid\u003e the client's credential is evaluated UNDER this profile (\"what would Cursor get here\"). An administrator gets every row plus counts.callable, counts.by_reason and stale_classifications; every other caller gets only visible rows and counts{visible, hidden}, and client= and reason= are refused 403. An unreachable profile answers exactly like an unknown one.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}},{"description":"Evaluate this client's credential under the profile (administrators only)","in":"query","name":"client","schema":{"type":"string"}},{"description":"Keep only this server's rows","in":"query","name":"server","schema":{"type":"string"}},{"description":"Keep only rows with this access reason (administrators only)","in":"query","name":"reason","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Effective tools"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"operation requires admin access"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found / client not found"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Effective tools of a profile","tags":["profiles"]}},"/api/v1/profiles/{name}/rename":{"post":{"description":"Renames a profile and moves every reference to it - token pins, client bindings, other profiles' switchable_to and the anonymous_profile - in one write (D19). Tokens move first, so a failure part-way never widens a scope. Guarded by FR-008a. Writes one ` + "`" + `rename` + "`" + ` record.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.RenameProfileRequest"}}},"description":"new_name","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Renamed; moved lists the clients and tokens that followed"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ProfileConflictResponse"}}},"description":"profile_exists, or binding_bypassable_without_auth (BindingGuardResponse)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Rename a profile","tags":["profiles"]}},"/api/v1/registries":{"get":{"description":"Retrieves list of all MCP server registries that can be browsed for discovering and installing new upstream servers. Includes registry metadata, server counts, and API endpoints.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetRegistriesResponse"}}},"description":"Registries retrieved successfully"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to list registries"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List available MCP server registries","tags":["registries"]},"post":{"description":"Adds a generic modelcontextprotocol/registry v0.1 https endpoint as a custom registry (MCP-866). The source is always tagged custom/unverified, so every server discovered through it lands quarantined and can never skip quarantine.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.AddRegistrySourceRequest"}}},"description":"Registry source (https url + optional protocol/id/name)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Registry source added"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"invalid_registry_url"},"403":{"content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/contracts.ErrorResponse"},{"$ref":"#/components/schemas/contracts.ErrorResponse"}]}}},"description":"Forbidden (agent tokens cannot mutate registries)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_shadows_builtin | duplicate_registry"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add a user-supplied registry source","tags":["registries"]}},"/api/v1/registries/{id}":{"delete":{"description":"Removes a custom/unverified registry previously added via add-source (MCP-1057). Built-in registries are refused with registry_shadows_builtin; an unknown id yields registry_not_found. The change is persisted copy-on-write.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Registry source removed"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID is required"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registries_locked"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_not_found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_shadows_builtin"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Remove a user-added custom registry source","tags":["registries"]},"put":{"description":"Updates a custom registry previously added via add-source (MCP-1072): name, url, servers-url. Empty fields are left unchanged. Built-in registries are refused with registry_shadows_builtin; an unknown id yields registry_not_found; a non-https url yields invalid_registry_url. The change is persisted copy-on-write.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.EditRegistrySourceRequest"}}},"description":"Fields to update (name/url/servers_url; empty = unchanged)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Registry source updated"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID is required | invalid_registry_url"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registries_locked"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_not_found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_shadows_builtin"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Edit a user-added custom registry source","tags":["registries"]}},"/api/v1/registries/{id}/refresh":{"post":{"description":"Invalidates the cached server lists for a registry so the next search re-fetches fresh data from the source (spec 070 FR-007). Returns how many cache entries were dropped.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.RefreshRegistryResponse"}}},"description":"Registry cache refreshed"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID is required"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to refresh registry cache"}},"summary":"Refresh a registry's cached server list","tags":["registries"]}},"/api/v1/registries/{id}/servers":{"get":{"description":"Searches for MCP servers within a specific registry by keyword or tag. Returns server metadata including installation commands, source code URLs, and npm package information for easy discovery and installation.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Search query keyword","in":"query","name":"q","schema":{"type":"string"}},{"description":"Filter by tag","in":"query","name":"tag","schema":{"type":"string"}},{"description":"Maximum number of results (default 10)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SearchRegistryServersResponse"}}},"description":"Servers retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to search servers"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Search MCP servers in a registry","tags":["registries"]}},"/api/v1/registries/{id}/servers/{serverId}/add":{"post":{"description":"Resolves a registry server reference server-side, re-derives a validated config, and persists it quarantined (spec 070 keystone). The client never sends a config blob — command/args/url and the quarantine flag are derived from the registry entry, not the request.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Server ID within the registry","in":"path","name":"serverId","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.AddFromRegistryRequest"}}},"description":"Optional overrides (name, env, enabled)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server added (quarantined)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"no_install_info | missing_required_input | duplicate_name"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot add servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_not_found | server_not_found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add an upstream server from a registry reference","tags":["registries"]}},"/api/v1/review":{"get":{"description":"Returns one row per quarantined server, trusted server with pending or changed tools, or (Spec 125) server with held skills (kind skill_review; skills_pending / skills_changed counts). Scoped callers see only servers they may enumerate (for a profile-pinned token: servers within its pin), with count recomputed; held-skill counts and skill_review rows are administrator-only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Review queue"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to load review queue"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the server review queue","tags":["review"]}},"/api/v1/routing":{"get":{"description":"Get the current routing mode and available MCP endpoints.\nrouting_mode is what /mcp is actually serving; pending_routing_mode carries a\nrestart-pending value persisted on disk (empty when there is none).\ntool_response_mode and direct_tool_response_mode report the two serialization axes, resolved.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Routing mode information"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get routing mode information","tags":["status"]}},"/api/v1/secrets":{"post":{"description":"Stores a secret value in the operating system's secure keyring. The secret can then be referenced in configuration using ${keyring:secret-name} syntax. Automatically notifies runtime to restart affected servers.","requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{},"type":"object"}}},"description":"Secret stored successfully with reference syntax"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload, missing name/value, or unsupported type"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Secret resolver not available or failed to store secret"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Store a secret in OS keyring","tags":["secrets"]}},"/api/v1/secrets/{name}":{"delete":{"description":"Deletes a secret from the operating system's secure keyring. Automatically notifies runtime to restart affected servers. Only keyring type is supported for security.","parameters":[{"description":"Name of the secret to delete","in":"path","name":"name","required":true,"schema":{"type":"string"}},{"description":"Secret type (only 'keyring' supported, defaults to 'keyring')","in":"query","name":"type","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{},"type":"object"}}},"description":"Secret deleted successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Missing secret name or unsupported type"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Secret resolver not available or failed to delete secret"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Delete a secret from OS keyring","tags":["secrets"]}},"/api/v1/security/bundle":{"get":{"description":"Reports the offline TPA signature corpus this install is serving: full SHA-256 digest, sequence, authority, trust epoch, signature verification, staleness (with the stale flag and its threshold), degraded coverage with its reason, rollback pin, and the last refused candidate. Also carries the refresh status (last checked and activated times, last cycle outcome, next check, consecutive failures; the fetch host only, never the URL) and the post-activation re-protection sweep status. Admin only.","responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Bundle status"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the TPA signature bundle status","tags":["security"]}},"/api/v1/security/bundle/history":{"get":{"description":"Append-only list of bundle activations, oldest first, each with its full SHA-256 digest. It is the trustworthy source of the digest to name in a rollback. Admin only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Activation history (data is an array of TPABundleActivation)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"History could not be read"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the TPA signature bundle activation history","tags":["security"]}},"/api/v1/security/bundle/refresh":{"post":{"description":"Runs one refresh cycle immediately: the local file leg (always network-free) followed by the optional fetch leg when security.tpa_fetch_enabled is on and a trusted signer and URL are configured. A cycle already in flight is joined, so one download and at most one activation happen per distinct candidate. The response is the resulting bundle status; the cycle outcome is in its refresh block (activated, unchanged, not_modified, rejected, fetch_unavailable, channel_invalid, superseded, disabled). Network failures are reported as fetch_unavailable and never as a rejection; last-known-good keeps serving. Unlike reload, refresh may make an outbound request. Admin API key only.","responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Updated bundle status; the refresh block holds the cycle outcome"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Refresh the TPA signature bundle now","tags":["security"]}},"/api/v1/security/bundle/reload":{"post":{"description":"Re-runs the single-flight bundle pipeline against the configured source and current policy. A refused candidate leaves last-known-good serving and is reported as last_rejection in the returned status. Admin API key only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Updated bundle status"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Reload the TPA signature bundle","tags":["security"]}},"/api/v1/security/bundle/rollback":{"post":{"description":"The one operator override of the downgrade watermark. Exactly one of embedded or path must be given, and digest must be the FULL 64-character lowercase hex SHA-256 of the target (the 12-character fingerprint is refused). On success the target serves and is pinned. A refusal (for example rollback_target_mismatch) returns 409 with the rejection reason and last-known-good keeps serving. Admin API key only; agent tokens are refused.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.bundleRollbackRequest"}}},"description":"Rollback target","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Updated bundle status"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Usage error: both or neither of embedded/path, or digest is not 64 lowercase hex"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BundleRollbackRefusedResponse"}}},"description":"Rollback refused; the response carries the rejection reason"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal error"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Roll the TPA signature bundle back to a named artifact","tags":["security"]}},"/api/v1/security/bundle/unpin":{"post":{"description":"Clears the rollback pin and re-validates the serving bundle under the normal downgrade watermark, so a rolled-back target below the watermark no longer serves. A quiet no-op when nothing is pinned. Admin API key only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Updated bundle status"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"The unpin could not be recorded"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Clear the TPA signature bundle rollback pin","tags":["security"]}},"/api/v1/servers":{"get":{"description":"Get a list of all configured upstream MCP servers with their connection status and statistics","parameters":[{"description":"Restrict to the profile's effective servers; tool_count becomes the number of that server's tools visible under the profile (Spec 108 FR-032)","in":"query","name":"profile","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServersResponse"}}},"description":"Server list with statistics"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unsupported scope filter (client/token), or '-' on a server filter"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown or unreachable profile"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List all upstream MCP servers","tags":["servers"]},"post":{"description":"Add a new MCP upstream server to the configuration. New servers are quarantined by default for security. Isolation: ` + "`" + `isolation.enabled` + "`" + ` is READ-ONLY (it reports the effective state on reads) and is rejected with 400; set the per-server override via ` + "`" + `isolation.enabled_override` + "`" + ` (true | false | null to clear, omit to leave unchanged). An unrecognized ` + "`" + `isolation.mode_override` + "`" + ` is rejected with 400.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.AddServerRequest"}}},"description":"Server configuration","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server added successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid configuration"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Conflict - server with this name already exists"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add a new upstream server","tags":["servers"]}},"/api/v1/servers/disable_all":{"post":{"description":"Disable all configured upstream MCP servers with partial failure handling","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/management.BulkOperationResult"}}},"description":"Bulk disable results with success/failure counts"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Disable all servers","tags":["servers"]}},"/api/v1/servers/enable_all":{"post":{"description":"Enable all configured upstream MCP servers with partial failure handling","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/management.BulkOperationResult"}}},"description":"Bulk enable results with success/failure counts"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable all servers","tags":["servers"]}},"/api/v1/servers/import":{"post":{"description":"Import MCP server configurations from a Claude Desktop, Claude Code, Cursor IDE, Codex CLI, or Gemini CLI configuration file","parameters":[{"description":"If true, return preview without importing","in":"query","name":"preview","schema":{"type":"boolean"}},{"description":"Force format (claude-desktop, claude-code, cursor, codex, gemini)","in":"query","name":"format","schema":{"type":"string"}},{"description":"Comma-separated list of server names to import","in":"query","name":"server_names","schema":{"type":"string"}}],"requestBody":{"content":{"multipart/form-data":{"schema":{"type":"file"}}},"description":"Configuration file to import","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportResponse"}}},"description":"Import result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid file or format"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Import servers from uploaded configuration file","tags":["servers"]}},"/api/v1/servers/import/json":{"post":{"description":"Import MCP server configurations from raw JSON or TOML content (useful for pasting configurations)","parameters":[{"description":"If true, return preview without importing","in":"query","name":"preview","schema":{"type":"boolean"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportRequest"}}},"description":"Import request with content","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportResponse"}}},"description":"Import result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid content or format"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Import servers from JSON/TOML content","tags":["servers"]}},"/api/v1/servers/import/path":{"post":{"description":"Import MCP server configurations by reading a file from the server's filesystem. A preview (preview=true) of a file with no MCP servers (empty, {}, or no/empty server map) answers 200 with an empty imported list; an apply of such a file and a malformed file still answer 400.","parameters":[{"description":"If true, return preview without importing","in":"query","name":"preview","schema":{"type":"boolean"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportFromPathRequest"}}},"description":"Import request with file path","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportResponse"}}},"description":"Import result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid path or format"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"File not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Import servers from a file path","tags":["servers"]}},"/api/v1/servers/import/paths":{"get":{"description":"Returns well-known configuration file paths for supported formats with existence check","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.CanonicalConfigPathsResponse"}}},"description":"Canonical config paths"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get canonical config file paths","tags":["servers"]}},"/api/v1/servers/reconnect":{"post":{"description":"Force reconnection to all upstream MCP servers","parameters":[{"description":"Reason for reconnection","in":"query","name":"reason","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"All servers reconnected successfully"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Reconnect all servers","tags":["servers"]}},"/api/v1/servers/restart_all":{"post":{"description":"Restart all configured upstream MCP servers sequentially with partial failure handling","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/management.BulkOperationResult"}}},"description":"Bulk restart results with success/failure counts"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Restart all servers","tags":["servers"]}},"/api/v1/servers/{id}":{"delete":{"description":"Remove an MCP upstream server from the configuration. This stops the server if running and removes it from config.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server removed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Remove an upstream server","tags":["servers"]},"patch":{"description":"Update specific fields of an existing upstream MCP server configuration. Isolation: ` + "`" + `isolation.enabled` + "`" + ` is READ-ONLY (it reports the effective state on reads) and is rejected with 400; set the per-server override via ` + "`" + `isolation.enabled_override` + "`" + ` (true | false | null to clear, omit to leave unchanged). An unrecognized ` + "`" + `isolation.mode_override` + "`" + ` is rejected with 400.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.AddServerRequest"}}},"description":"Fields to update (all optional)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server updated successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - no fields or invalid body"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Partially update an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/config-to-secret":{"post":{"description":"Atomically reads the real value from the server config, stores it in the OS keyring, and rewrites the config field to ` + "`" + `${keyring:\u003cname\u003e}` + "`" + `. Unblocks the UI's Convert-to-secret affordance for values the API redacts on the read path.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{},"type":"object"}}},"description":"Secret stored, config updated with reference"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad scope/key/secret_name, or value is already a reference / empty"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or key not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Secret resolver or config update failed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Convert a header / env value to a keyring secret","tags":["servers"]}},"/api/v1/servers/{id}/disable":{"post":{"description":"Disable a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server disabled successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Disable an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/discover-tools":{"post":{"description":"Manually trigger tool discovery and indexing for a specific upstream MCP server. This forces an immediate refresh of the server's tool cache.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Tool discovery triggered successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot discover tools)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to discover tools"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Discover tools for a specific server","tags":["servers"]}},"/api/v1/servers/{id}/enable":{"post":{"description":"Enable a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server enabled successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/login":{"post":{"description":"Initiate OAuth authentication flow for a specific upstream MCP server. Returns structured OAuth start response with correlation ID for tracking.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.OAuthStartResponse"}}},"description":"OAuth login initiated successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.OAuthFlowError"}}},"description":"OAuth error (client_id required, DCR failed, etc.)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Trigger OAuth login for server","tags":["servers"]}},"/api/v1/servers/{id}/logout":{"post":{"description":"Clear OAuth authentication token and disconnect a specific upstream MCP server. The server will need to re-authenticate before tools can be used again.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"OAuth logout completed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled or read-only mode)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Clear OAuth token and disconnect server","tags":["servers"]}},"/api/v1/servers/{id}/logs":{"get":{"description":"Retrieve log entries for a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Number of log lines to retrieve","in":"query","name":"tail","schema":{"default":100,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServerLogsResponse"}}},"description":"Server logs retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server logs","tags":["servers"]}},"/api/v1/servers/{id}/quarantine":{"post":{"description":"Place a specific upstream MCP server in quarantine to prevent tool execution","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server quarantined successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Quarantine a server","tags":["servers"]}},"/api/v1/servers/{id}/refresh":{"post":{"description":"Re-discover and re-index a specific upstream MCP server's tools without changing any security state. Alias of discover-tools, named for the upstream_servers 'refresh' operation; use it to make just-approved tools searchable immediately.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Tool refresh triggered successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot refresh)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to refresh tools"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Refresh a server's tools","tags":["servers"]}},"/api/v1/servers/{id}/restart":{"post":{"description":"Restart the connection to a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server restarted successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Restart an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/review":{"get":{"description":"Returns redacted server configuration, captured tool definitions, annotations, scan verdicts, and diffs. Scoped callers receive the same 404 for invisible and missing servers.","parameters":[{"description":"Server name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server review"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to load server review"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get review details for a server","tags":["review"]}},"/api/v1/servers/{id}/security/approve":{"post":{"description":"Saves the integrity baseline and optionally blocks selected tools atomically before unquarantining the server. With expected_hashes (tool name -\u003e the review's current_hash; {} for an empty review) the approval is bound to the reviewed definitions: when a tool the approval would make reachable (pending, or approved and enabled, minus block) changed or appeared since the review, or a block target no longer exists, the response is 409 review_out_of_date, nothing is written and the server stays quarantined. Tools listed after the approval wait for review.","parameters":[{"description":"Server name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.securityApproveRequest"}}},"description":"Force approval and tool names to keep disabled"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server approved"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request or unknown tool block target"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not configured"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.StaleReviewErrorResponse"}}},"description":"Dangerous scan verdict requires force, approval failed, the review is out of date (error_code review_out_of_date), or server_replaced (the server was removed or re-added since expected_incarnation)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Approve a server after security review","tags":["security"]}},"/api/v1/servers/{id}/skills":{"get":{"description":"Lists the skills of one upstream server. An administrator sees every record: status, hashes, files, scan result and the availability an agent would see. A scoped agent token with the server in its reach sees only the available skills, as the approved copy (id, uri, path, name, description, status \"approved\", approved_hash, files, total_size; contracts.SkillsAgentListResponse) and nothing about any other skill; a server outside its reach is 404. With enable_skills off the answer is {\"enabled\": false, \"skills\": []} and no upstream is contacted.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsListResponse"}}},"description":"Skills of the server"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found, or outside the caller's reach"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List the skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/skills/approve":{"post":{"description":"Administrator only. Approves the named skills for exactly the content the reviewer saw: expected_hashes maps each skill path to the current_hash from the listing, and expected_incarnation (the listing's incarnation) binds the approval to the server that was reviewed. When a hash differs, or a named skill has no expected hash, the response is 409 review_out_of_date with the changed and unreviewed names and nothing is approved; 409 server_replaced when the server was removed or replaced since the review; 422 skill_unusable for a skill that cannot be approved (a failed check or a dynamic file list). A skill already approved for its current content is left as it is and not counted. The blocked mark is never touched. A scoped agent token is refused with 403.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsApproveRequest"}}},"description":"Skills to approve, with the review binding","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsApproveResponse"}}},"description":"Number of skills newly approved (inside the data envelope)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or skill not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsStaleReviewResponse"}}},"description":"review_out_of_date, server_replaced or skills_disabled"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsUnusableResponse"}}},"description":"skill_unusable"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Approve skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/skills/block":{"post":{"description":"Administrator only. Sets the blocked mark on the named skills: a blocked skill is never offered to an agent, and no refresh, content change or automatic approval clears the mark. expected_incarnation is optional (0 binds to the current server). 409 server_replaced when the server was removed or replaced since it was reviewed. A scoped agent token is refused with 403.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsBlockRequest"}}},"description":"Skills to block","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsBlockResponse"}}},"description":"Number of skills whose mark changed (inside the data envelope)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or skill not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"server_replaced or skills_disabled"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Block skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/skills/content":{"get":{"description":"Returns a chunk of one stored text file of a skill. An administrator reads the current copy by default; a scoped agent token with the server in its reach reads the approved copy of an available skill only (copy is forced to approved), and gets one 404 for every other skill or file. A server outside its reach is 404. Offsets are byte positions; a chunk never splits a UTF-8 character, so it can be a few bytes shorter than limit. next_offset is absent at the end of the file. 404 for an unknown skill or file (or with enable_skills off), 415 for a binary file, 409 stored_copy_damaged when the stored bytes no longer match their digest.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Skill path, e.g. hf-cli","in":"query","name":"skill","required":true,"schema":{"type":"string"}},{"description":"File path inside the skill (default SKILL.md)","in":"query","name":"file","schema":{"type":"string"}},{"description":"current (default) or approved","in":"query","name":"copy","schema":{"type":"string"}},{"description":"Byte offset to start at (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Maximum bytes (default and maximum 65536)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillContentResponse"}}},"description":"A chunk of the file"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad parameters"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"output_blocked: the output sanitisation policy withholds the text (scoped caller)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server, skill or file not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"stored_copy_damaged (administrator)"},"415":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"The file is binary"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Read one text file of a skill","tags":["servers"]}},"/api/v1/servers/{id}/skills/refresh":{"post":{"description":"Administrator only. Reads the server's skills from the upstream again, verifies every file and returns the listing once applied. A refresh that is already running is joined. 409 skills_disabled when enable_skills is off; 409 skills_not_supported when the server does not announce the skills extension.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsListResponse"}}},"description":"Skills of the server after the refresh"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"skills_disabled, skills_not_supported or refresh_superseded"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Refresh failed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Refresh the skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/skills/unblock":{"post":{"description":"Administrator only. Clears the blocked mark on the named skills. The skill's approval state is not changed: a skill that is not approved stays unavailable. expected_incarnation is optional (0 binds to the current server). 409 server_replaced when the server was removed or replaced since it was reviewed. A scoped agent token is refused with 403.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsBlockRequest"}}},"description":"Skills to unblock","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsBlockResponse"}}},"description":"Number of skills whose mark changed (inside the data envelope)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or skill not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"server_replaced or skills_disabled"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Unblock skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/tool-calls":{"get":{"description":"Retrieves tool call history filtered by upstream server ID. Returns recent tool executions for the specified server including timestamps, arguments, results, and errors. Useful for server-specific debugging and monitoring.","parameters":[{"description":"Upstream server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Maximum number of records to return (1-100, default 50)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServerToolCallsResponse"}}},"description":"Server tool calls retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get server tool calls"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call history for specific server","tags":["tool-calls"]}},"/api/v1/servers/{id}/tools":{"get":{"description":"Retrieve all available tools for a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServerToolsResponse"}}},"description":"Server tools retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server kept being removed or replaced while its tools were read"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/approve":{"post":{"description":"Approves the given pending/changed tools (or all of them with approve_all). With expected_hashes (tool name -\u003e the review's current_hash) the approval is bound to the reviewed definitions: when a requested tool (approve_all: any pending or changed tool) no longer matches, the response is 409 review_out_of_date and nothing is approved.","parameters":[{"description":"Server name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.approveToolsRequest"}}},"description":"Tools to approve, or approve_all, with an optional review binding","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Approval outcome"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.StaleReviewErrorResponse"}}},"description":"The review is out of date; nothing was approved"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Approve tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/block":{"post":{"description":"Atomically approves AND disables the given tools (or all pending/changed tools when block_all=true) for a server. The approve and disable land in a single write per tool, so a tool is never left in the approved+enabled state. The \"blocked\" field counts tools actually blocked. An optional expected_incarnation binds the write to the reviewed server (Spec 116): a remove and re-add since then answers 409 server_replaced and writes nothing.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Block result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server was removed or re-added since expected_incarnation"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Block (approve+disable) tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/disable_all":{"post":{"description":"Bulk-toggles every known tool of a server. The \"changed\" field","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.expectedIncarnationBody"}}},"description":"Optional incarnation of the reviewed server (Spec 116)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Operation result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server was removed or re-added since expected_incarnation"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable or disable all tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/enable_all":{"post":{"description":"Bulk-toggles every known tool of a server. The \"changed\" field","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.expectedIncarnationBody"}}},"description":"Optional incarnation of the reviewed server (Spec 116)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Operation result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server was removed or re-added since expected_incarnation"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable or disable all tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/unquarantine":{"post":{"description":"Remove a specific upstream MCP server from quarantine to allow tool execution","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.expectedIncarnationBody"}}},"description":"Optional incarnation of the reviewed server (Spec 116)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server unquarantined successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server was removed or re-added since expected_incarnation"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Unquarantine a server","tags":["servers"]}},"/api/v1/sessions":{"get":{"description":"Retrieves paginated list of active and recent MCP client sessions. Each session represents a connection from an MCP client to MCPProxy, tracking initialization time, tool calls, and connection status.","parameters":[{"description":"Maximum number of sessions to return (1-100, default 10)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Number of sessions to skip for pagination (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Filter by session status","in":"query","name":"status","schema":{"enum":["active","closed"],"type":"string"}},{"description":"Filter by the session's latest effective profile; - selects sessions with none (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Filter by the client id the session's credential is bound to; - selects sessions with none (Spec 108)","in":"query","name":"client","schema":{"type":"string"}},{"description":"Filter by the token name the session initialized with; - selects sessions with none (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Alias of token","in":"query","name":"agent","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetSessionsResponse"}}},"description":"Sessions retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid status filter, token and agent naming different tokens, or client_name (not supported here; filter by client)"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read MCP session history"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get sessions"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get active MCP sessions","tags":["sessions"]}},"/api/v1/sessions/{id}":{"get":{"description":"Retrieves detailed information about a specific MCP client session including initialization parameters, connection status, tool call count, and activity timestamps.","parameters":[{"description":"Session ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetSessionDetailResponse"}}},"description":"Session details retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Session ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read MCP session history"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Session not found"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get MCP session details by ID","tags":["sessions"]}},"/api/v1/stats/tokens":{"get":{"description":"Retrieve token savings statistics across all servers and sessions","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Token statistics"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read deployment-wide token statistics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get token savings statistics","tags":["stats"]}},"/api/v1/status":{"get":{"description":"Get comprehensive server status including running state, listen address, upstream statistics, and timestamp. For a scoped caller (an agent token; for a profile-pinned token, its allowed_servers intersected with the pin) upstream_stats lists only the servers it may enumerate and every counter is recomputed over them.\ntelemetry (admin only): effective telemetry state {enabled, source: env|config|default, disabled_by}","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server status information"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server status","tags":["status"]}},"/api/v1/telemetry/payload":{"get":{"description":"Render the exact JSON heartbeat payload that mcpproxy would next send to the telemetry endpoint, without making a network call. Counters in the payload reflect the current in-memory state. Spec 042.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Telemetry heartbeat payload"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read the deployment telemetry payload"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Telemetry service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Preview next telemetry heartbeat payload","tags":["telemetry"]}},"/api/v1/telemetry/update-failure":{"post":{"description":"Records one terminal update-session failure, identified only by its\nstage (appcast, download, install, other). The body carries no error\ntext, URL, or version — the stage is the only value transmitted.\nReturns 204 both when the occurrence was durably persisted and when\ntelemetry is inactive at event time (config opt-out, environment\nopt-out, CI, or dev build), in which case nothing is recorded.\nCallers cannot and need not distinguish the two.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.UpdateFailureRequest"}}},"description":"Update failure stage","required":true},"responses":{"204":{"description":"Accepted (recorded, or a deliberate no-op while telemetry is inactive)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Malformed body, unknown field, trailing value, or stage outside the closed set"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Persistence failure"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Record a desktop auto-update failure occurrence (Spec 095)","tags":["telemetry"]}},"/api/v1/tool-calls":{"get":{"description":"Retrieves paginated tool call history across all upstream servers or filtered by session ID. Includes execution timestamps, arguments, results, and error information for debugging and auditing.","parameters":[{"description":"Maximum number of records to return (1-100, default 50)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Number of records to skip for pagination (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Filter tool calls by MCP session ID","in":"query","name":"session_id","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetToolCallsResponse"}}},"description":"Tool calls retrieved successfully"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get tool calls"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call history","tags":["tool-calls"]}},"/api/v1/tool-calls/{id}":{"get":{"description":"Retrieves detailed information about a specific tool call execution including full request arguments, response data, execution time, and any errors encountered.","parameters":[{"description":"Tool call ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetToolCallDetailResponse"}}},"description":"Tool call details retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call not found"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call details by ID","tags":["tool-calls"]}},"/api/v1/tool-calls/{id}/replay":{"post":{"description":"Re-executes a previous tool call with optional modified arguments. Useful for debugging and testing tool behavior with different inputs. Creates a new tool call record linked to the original.","parameters":[{"description":"Original tool call ID to replay","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ReplayToolCallRequest"}}},"description":"Optional modified arguments for replay"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ReplayToolCallResponse"}}},"description":"Tool call replayed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call ID required or invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Replay refused: tool quarantined or not callable, server quarantined, outside the profile policy, or the token lacks the tool's permission tier"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"429":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Shed by a concurrency limit or an agent token call rate limit (Retry-After header carries the wait hint)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to replay tool call"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Replay a tool call","tags":["tool-calls"]}},"/api/v1/tools":{"get":{"description":"Consolidated, read-only listing of all tools from every configured server (including disabled servers and disabled/config-denied tools), enriched with approval state and 30-day usage. Backs the global Tools page and the CLI global ` + "`" + `tools list` + "`" + ` (spec 050, issue #437).","parameters":[{"description":"View-as (administrator only): the tools this client would see, each with its access verdict {visible, callable, reason} and profile_tier (Spec 108 FR-032)","in":"query","name":"client","schema":{"type":"string"}},{"description":"View-as: the tools this profile would expose. An administrator gets every row with a verdict; any other caller gets only the visible rows plus counts {visible, hidden} (Spec 108 FR-032)","in":"query","name":"profile","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GlobalToolsResponse"}}},"description":"All tools across all servers"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unsupported scope filter (token), both client and profile, or '-' on a tools filter"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"client= requires administrator credentials"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown or unreachable client / profile"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Could not enumerate servers"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List every tool across all servers","tags":["tools"]}},"/api/v1/tools/call":{"post":{"description":"Execute a tool on an upstream MCP server (wrapper around MCP tool calls)","requestBody":{"content":{"application/json":{"schema":{"properties":{"arguments":{"type":"object"},"tool_name":{"type":"string"}},"type":"object"}}},"description":"Tool call request with tool name and arguments","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Tool call result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (invalid payload or missing tool name)"},"429":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Shed by a concurrency limit or an agent token call rate limit (Retry-After header carries the wait hint)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error or tool execution failure"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Call a tool","tags":["tools"]}},"/api/v1/work-sessions":{"get":{"description":"Lists work sessions (one agent's run of work) with their failure facts. An agent token sees only its own sessions, and only the part of each that touched servers in its reach.","parameters":[{"description":"Only sessions with at least one failure","in":"query","name":"failed","schema":{"type":"boolean"}},{"description":"With failed: count policy blocks as failures (default true)","in":"query","name":"include_blocked","schema":{"type":"boolean"}},{"description":"Filter by agent token name","in":"query","name":"token","schema":{"type":"string"}},{"description":"Filter by client id","in":"query","name":"client","schema":{"type":"string"}},{"description":"Filter by profile (administrators only)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Filter by run name","in":"query","name":"run","schema":{"type":"string"}},{"description":"Filter by the error class of the last failure","in":"query","name":"error_class","schema":{"type":"string"}},{"description":"Only sessions active at or after this time (RFC3339)","in":"query","name":"since","schema":{"type":"string"}},{"description":"Only sessions active at or before this time (RFC3339)","in":"query","name":"until","schema":{"type":"string"}},{"description":"last_activity (default) or last_failure","in":"query","name":"sort","schema":{"enum":["last_activity","last_failure"],"type":"string"}},{"description":"Page size (default 25, max 100)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Page offset","in":"query","name":"offset","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.WorkSessionListEnvelope"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad Request"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List work sessions","tags":["activity"]}},"/api/v1/work-sessions/{id}":{"get":{"parameters":[{"description":"Work session id","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.WorkSessionEnvelope"}}},"description":"OK"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Not Found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get one work session","tags":["activity"]}},"/api/v1/work-sessions/{id}/timeline":{"get":{"description":"Returns the session's activity rows and the upstream events of the servers it called, in time order, positioned at a failure, a row or the end. Bodies are omitted unless include_bodies is set.","parameters":[{"description":"Work session id","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"first_failure (default), failure:\u003cn\u003e, row:\u003cactivity id\u003e or end","in":"query","name":"at","schema":{"type":"string"}},{"description":"Rows before the position (default 20, max 250)","in":"query","name":"before","schema":{"type":"integer"}},{"description":"Rows after the position (default 20, max 250)","in":"query","name":"after","schema":{"type":"integer"}},{"description":"Include argument and response bodies","in":"query","name":"include_bodies","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.WorkSessionTimelineEnvelope"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad Request"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Not Found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get a work session's timeline","tags":["activity"]}},"/healthz":{"get":{"description":"Get comprehensive health status including all component health (Kubernetes-compatible liveness probe)","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.HealthResponse"}}},"description":"Service is healthy"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.HealthResponse"}}},"description":"Service is unhealthy"}},"summary":"Get health status","tags":["health"]}},"/readyz":{"get":{"description":"Get readiness status including all component readiness checks (Kubernetes-compatible readiness probe)","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.ReadinessResponse"}}},"description":"Service is ready"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.ReadinessResponse"}}},"description":"Service is not ready"}},"summary":"Get readiness status","tags":["health"]}}}, "openapi": "3.1.0" }` diff --git a/oas/swagger.yaml b/oas/swagger.yaml index e40653240..44ebfb747 100644 --- a/oas/swagger.yaml +++ b/oas/swagger.yaml @@ -4656,6 +4656,37 @@ components: type: array uniqueItems: false type: object + httpapi.ClientCredential: + properties: + approved_at: + type: string + expires_at: + type: string + grant_id: + description: GrantID names a browser login. + type: string + kind: + description: Kind is api_key or browser_login. + type: string + last_used_at: + type: string + name_mismatch: + type: boolean + observed_name: + description: ObservedName is the name the client sent at initialize (advisory). + type: string + prefix: + type: string + redirect_host: + type: string + reported_name: + type: string + state: + description: |- + State is active|expired|revoked for an API key and active|lapsed|revoked + for a login. + type: string + type: object httpapi.ClientSnippet: properties: generic_http: @@ -5051,6 +5082,38 @@ components: working_dir: type: string type: object + httpapi.OAuthApprovalBody: + properties: + binding_revision: + type: string + client: + $ref: '#/components/schemas/httpapi.OAuthClientChoice' + mode: + type: string + profile: + type: string + replace_grant: + type: string + type: object + httpapi.OAuthClientChoice: + properties: + id: + type: string + new: + $ref: '#/components/schemas/httpapi.OAuthNewClient' + type: object + httpapi.OAuthDecisionResponse: + properties: + redirect_url: + type: string + type: object + httpapi.OAuthNewClient: + properties: + display_name: + type: string + id: + type: string + type: object httpapi.OnboardingMarkRequest: properties: connect_step_status: @@ -5333,6 +5396,11 @@ components: new_name: type: string type: object + httpapi.RevokeCredentialResponse: + properties: + changed: + type: boolean + type: object httpapi.RotateClientRequest: properties: precondition_token: @@ -5500,6 +5568,8 @@ components: type: integer blocked_24h: type: integer + browser_login_disabled: + type: boolean calls_24h: type: integer config_path: @@ -5512,6 +5582,15 @@ components: type: string credential_state: $ref: '#/components/schemas/profile.CredentialState' + credentials: + description: |- + Spec 132: the client's credentials (API key and browser logins) and + whether browser login is off right now. Both exist only once browser + login was used on this install; until then a row is exactly what it was. + items: + $ref: '#/components/schemas/httpapi.ClientCredential' + type: array + uniqueItems: false display_name: type: string display_path: @@ -7628,6 +7707,60 @@ paths: summary: Get one client tags: - clients + /api/v1/clients/{client}/api-key: + delete: + description: 'Revokes the client''s mcp_cli_ credential alone: its browser logins + and its binding stay. 404 no_client_credential when the client has no active + API key. Writes a revoke record. Administrator only.' + parameters: + - description: Client id + in: path + name: client + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + allOf: + - $ref: '#/components/schemas/data' + properties: + data: + type: object + error: + type: string + request_id: + type: string + success: + type: boolean + type: object + description: The key was revoked + "400": + content: + application/json: + schema: + $ref: '#/components/schemas/httpapi.ClientBindingErrorResponse' + description: Invalid client id + "403": + content: + application/json: + schema: + $ref: '#/components/schemas/contracts.ErrorResponse' + description: Administrator credentials required + "404": + content: + application/json: + schema: + $ref: '#/components/schemas/httpapi.ClientBindingErrorResponse' + description: no_client_credential + security: + - ApiKeyAuth: [] + - ApiKeyQuery: [] + summary: Revoke a client's API key only + tags: + - clients /api/v1/clients/{client}/binding: put: description: |- @@ -7706,6 +7839,62 @@ paths: summary: Reassign a client's profile and/or mode tags: - clients + /api/v1/clients/{client}/logins/{grant_id}: + delete: + description: 'Revokes the login (reason admin): its access token stops authenticating + on the next request, live sessions are told to re-list, and a revoke record + names the administrator. Works while browser login is on and while it is off + after use. An already revoked login answers changed:false; an unknown login + (or one of another client) is 404. Administrator only.' + parameters: + - description: Client id + in: path + name: client + required: true + schema: + type: string + - description: Login id + in: path + name: grant_id + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + allOf: + - $ref: '#/components/schemas/data' + properties: + data: + type: object + error: + type: string + request_id: + type: string + success: + type: boolean + type: object + description: Whether the login changed + "403": + content: + application/json: + schema: + $ref: '#/components/schemas/contracts.ErrorResponse' + description: Administrator credentials required + "404": + content: + application/json: + schema: + $ref: '#/components/schemas/contracts.ErrorResponse' + description: login not found + security: + - ApiKeyAuth: [] + - ApiKeyQuery: [] + summary: Revoke one browser login of a client + tags: + - clients /api/v1/clients/{client}/rotate: post: description: 'Replaces a client''s secret without ever invalidating the old @@ -8837,6 +9026,249 @@ paths: summary: Get server information tags: - status + /api/v1/oauth/authorizations: + get: + description: 'Pending browser-login requests, newest first: id, a sanitised + client label and the times. Used by the tray and Home. 404 feature_disabled + while browser login is off. Administrator only.' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/contracts.APIResponse' + description: Pending requests + "403": + content: + application/json: + schema: + $ref: '#/components/schemas/contracts.ErrorResponse' + description: Administrator credentials required + "404": + content: + application/json: + schema: + $ref: '#/components/schemas/httpapi.ClientBindingErrorResponse' + description: feature_disabled + security: + - ApiKeyAuth: [] + - ApiKeyQuery: [] + summary: List pending sign-in requests + tags: + - clients + /api/v1/oauth/authorizations/{id}: + get: + description: 'Everything the consent view needs: the reported (unverified) name, + the redirect URI, the resource, how the address fixes the client, the profiles, + whether a profile must be chosen, the previous login of the same registration + and, for a fixed client that has a binding, the guard verdict. One uniform + 404 for an unknown, expired, decided or cancelled id. Administrator only.' + parameters: + - description: Request id + in: path + name: id + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/contracts.APIResponse' + description: The request + "403": + content: + application/json: + schema: + $ref: '#/components/schemas/contracts.ErrorResponse' + description: Administrator credentials required + "404": + content: + application/json: + schema: + $ref: '#/components/schemas/httpapi.ClientBindingErrorResponse' + description: request_not_found or feature_disabled + security: + - ApiKeyAuth: [] + - ApiKeyQuery: [] + summary: Read one sign-in request + tags: + - clients + /api/v1/oauth/authorizations/{id}/approve: + post: + description: Records the decision and issues the code; the login itself is stored + when the client exchanges the code. 409 already_decided, 409 binding_changed + (the binding differs from binding_revision), 409 binding_bypassable_without_auth + (with the guard's fixes), 422 profile_required, client_fixed, identity_exists, + reserved_identity, 404 profile_not_found. Writes an approve record naming + the administrator. Administrator only. + parameters: + - description: Request id + in: path + name: id + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/httpapi.OAuthApprovalBody' + description: client, profile, mode, binding_revision, replace_grant + required: true + responses: + "200": + content: + application/json: + schema: + allOf: + - $ref: '#/components/schemas/data' + properties: + data: + type: object + error: + type: string + request_id: + type: string + success: + type: boolean + type: object + description: Where the page navigates + "403": + content: + application/json: + schema: + $ref: '#/components/schemas/contracts.ErrorResponse' + description: Administrator credentials required + "404": + content: + application/json: + schema: + $ref: '#/components/schemas/httpapi.ClientBindingErrorResponse' + description: request_not_found, profile_not_found or feature_disabled + "409": + content: + application/json: + schema: + $ref: '#/components/schemas/httpapi.ClientBindingErrorResponse' + description: already_decided, binding_changed or binding_bypassable_without_auth + "422": + content: + application/json: + schema: + $ref: '#/components/schemas/httpapi.ClientBindingErrorResponse' + description: profile_required, client_fixed, identity_exists, reserved_identity + security: + - ApiKeyAuth: [] + - ApiKeyQuery: [] + summary: Approve a sign-in request + tags: + - clients + /api/v1/oauth/authorizations/{id}/deny: + post: + description: The redirect carries error=access_denied. 409 already_decided. + Writes a deny record naming the administrator. Administrator only. + parameters: + - description: Request id + in: path + name: id + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + allOf: + - $ref: '#/components/schemas/data' + properties: + data: + type: object + error: + type: string + request_id: + type: string + success: + type: boolean + type: object + description: Where the page navigates + "403": + content: + application/json: + schema: + $ref: '#/components/schemas/contracts.ErrorResponse' + description: Administrator credentials required + "404": + content: + application/json: + schema: + $ref: '#/components/schemas/httpapi.ClientBindingErrorResponse' + description: request_not_found or feature_disabled + "409": + content: + application/json: + schema: + $ref: '#/components/schemas/httpapi.ClientBindingErrorResponse' + description: already_decided + security: + - ApiKeyAuth: [] + - ApiKeyQuery: [] + summary: Deny a sign-in request + tags: + - clients + /api/v1/oauth/authorizations/{id}/preview: + post: + description: 'Read-only: for a proposed client (existing or new), profile and + mode, returns whether the choice is complete, the access sentence and the + binding guard''s verdict with its fixes. Writes nothing. The same 422 codes + as approve for an invalid choice. Administrator only.' + parameters: + - description: Request id + in: path + name: id + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/httpapi.OAuthApprovalBody' + description: client, profile, mode + required: true + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/contracts.APIResponse' + description: The preview + "403": + content: + application/json: + schema: + $ref: '#/components/schemas/contracts.ErrorResponse' + description: Administrator credentials required + "404": + content: + application/json: + schema: + $ref: '#/components/schemas/httpapi.ClientBindingErrorResponse' + description: request_not_found, profile_not_found or feature_disabled + "422": + content: + application/json: + schema: + $ref: '#/components/schemas/httpapi.ClientBindingErrorResponse' + description: client_fixed, identity_exists, reserved_identity + security: + - ApiKeyAuth: [] + - ApiKeyQuery: [] + summary: Preview a sign-in decision + tags: + - clients /api/v1/onboarding/mark: post: description: |- From 6c66382210d1ba8ea01da29cf315812c38affeb3 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 02:33:33 +0200 Subject: [PATCH 17/42] fix(oauth): close stream, cross-site and contract gaps after review (Spec 132 PR-1e) Register takes exactly one JSON object as application/json; mcp_oat_ is refused on classic MCP routes whatever the bearer whitespace and on the REST API with the client-credential 403; once used every client row carries credentials and browser_login_disabled (install-wide); open requests and SSE streams end with their login (revoke, forget, switch-off, rotation, expiry); cross-origin and cross-site posts to register and token are refused; an unreadable ever-used marker reads as used; OAuth routes answer 404 behind a proxy header. Related #1971 --- internal/httpapi/clients.go | 7 +- internal/httpapi/clients_logins.go | 33 ++- internal/httpapi/oauth_login_test.go | 41 +++ internal/httpapi/server.go | 21 ++ internal/runtime/clients_service_oauth.go | 2 +- internal/runtime/oauth_login_clients_test.go | 2 +- internal/runtime/oauth_login_everused_test.go | 24 ++ internal/runtime/oauth_login_service.go | 9 +- internal/runtime/oauth_login_tokens.go | 18 ++ .../server/oauth_login_default_off_test.go | 3 +- internal/server/oauth_login_hardening_test.go | 267 ++++++++++++++++++ internal/server/oauth_login_http.go | 57 +++- internal/server/oauth_login_routes.go | 14 +- internal/server/oauth_login_streams.go | 130 +++++++++ internal/server/profile_notify.go | 5 + internal/server/server.go | 6 +- oas/docs.go | 2 +- oas/swagger.yaml | 3 + 18 files changed, 621 insertions(+), 23 deletions(-) create mode 100644 internal/runtime/oauth_login_everused_test.go create mode 100644 internal/server/oauth_login_hardening_test.go create mode 100644 internal/server/oauth_login_streams.go diff --git a/internal/httpapi/clients.go b/internal/httpapi/clients.go index 74fa92e9d..28ac17972 100644 --- a/internal/httpapi/clients.go +++ b/internal/httpapi/clients.go @@ -72,8 +72,11 @@ type clientPresence struct { // Spec 132: the client's credentials (API key and browser logins) and // whether browser login is off right now. Both exist only once browser // login was used on this install; until then a row is exactly what it was. - Credentials []ClientCredential `json:"credentials,omitempty"` - BrowserLoginDisabled *bool `json:"browser_login_disabled,omitempty"` + // + // Credentials is a pointer so that once the feature was used a row with no + // credential serialises "credentials": [] instead of omitting the field. + Credentials *[]ClientCredential `json:"credentials,omitempty"` + BrowserLoginDisabled *bool `json:"browser_login_disabled,omitempty"` // resolvedCredential is the classification of the on-demand config read of a // detail request; never serialised. diff --git a/internal/httpapi/clients_logins.go b/internal/httpapi/clients_logins.go index 626fe5d29..398715d6a 100644 --- a/internal/httpapi/clients_logins.go +++ b/internal/httpapi/clients_logins.go @@ -65,15 +65,21 @@ func (s *Server) decorateBrowserLogins(rows []clientPresence, cfg *config.Config if err != nil { return nil, err } - used := false + // Used = the runtime decorated the views (it does so only once the feature + // was used); the flag is the same install-wide value on every view. + var disabled *bool for i := range views { - if views[i].Credentials != nil { - used = true + if views[i].BrowserLoginDisabled != nil { + disabled = views[i].BrowserLoginDisabled break } } - if !used { - return rows, nil + if disabled == nil { + if len(views) > 0 || !s.browserLoginUsed() { + return rows, nil + } + off := !s.oauthLoginService.Enabled() + disabled = &off } titleOf := func(name string) string { if cfg != nil { @@ -119,13 +125,17 @@ func (s *Server) decorateBrowserLogins(rows []clientPresence, cfg *config.Config sort.Strings(ids) for i := range rows { + // Every row carries both fields once the feature was used. + empty := []ClientCredential{} + rows[i].Credentials = &empty + rows[i].BrowserLoginDisabled = disabled vi, ok := byID[rows[i].ID] if !ok { continue } v := &views[vi] - rows[i].Credentials = clientCredentials(v.Credentials) - rows[i].BrowserLoginDisabled = v.BrowserLoginDisabled + creds := clientCredentials(v.Credentials) + rows[i].Credentials = &creds if rows[i].TokenName == "" { // No API-key record: the binding the row shows is the browser login's. rows[i].Profile, rows[i].ProfileMode = v.Profile, v.Mode @@ -139,6 +149,7 @@ func (s *Server) decorateBrowserLogins(rows []clientPresence, cfg *config.Config continue } v := &views[byID[id]] + creds := clientCredentials(v.Credentials) name := v.DisplayName if name == "" { name = id @@ -148,8 +159,14 @@ func (s *Server) decorateBrowserLogins(rows []clientPresence, cfg *config.Config CredentialState: profile.CredentialStateNone, Profile: v.Profile, ProfileMode: v.Mode, ProfileTitle: titleOf(v.Profile), ProfileMissing: profileMissing(v.Profile), ProfileSource: source(v.Mode), - Credentials: clientCredentials(v.Credentials), BrowserLoginDisabled: v.BrowserLoginDisabled, + Credentials: &creds, BrowserLoginDisabled: disabled, }) } return rows, nil } + +// browserLoginUsed reports whether browser login was ever used (fail closed on +// an unreadable marker). +func (s *Server) browserLoginUsed() bool { + return s.oauthLoginService != nil && s.oauthLoginService.EverUsed() +} diff --git a/internal/httpapi/oauth_login_test.go b/internal/httpapi/oauth_login_test.go index 7fc7f88b5..87028a502 100644 --- a/internal/httpapi/oauth_login_test.go +++ b/internal/httpapi/oauth_login_test.go @@ -298,6 +298,14 @@ func TestOAuthLoginREST_ClientCredentialsPayloadAndRevokes(t *testing.T) { assert.Equal(t, "cursor ide", login["reported_name"]) assert.Contains(t, login, "name_mismatch") assert.Equal(t, false, row["browser_login_disabled"]) + // Once the feature was used EVERY row carries both fields, an empty list as []. + for _, c := range dataOf(t, w)["clients"].([]interface{}) { + m := c.(map[string]interface{}) + _, has := m["credentials"] + assert.True(t, has, "row %v lacks credentials", m["id"]) + assert.Contains(t, m, "browser_login_disabled", "row %v", m["id"]) + } + assert.Equal(t, []interface{}{}, findRowByID(t, w, "windsurf")["credentials"]) assert.Len(t, login["prefix"], 12, "only the display prefix of a token appears in a client payload") grantID := login["grant_id"].(string) @@ -307,6 +315,7 @@ func TestOAuthLoginREST_ClientCredentialsPayloadAndRevokes(t *testing.T) { row = findRow(w) assert.Equal(t, true, row["browser_login_disabled"]) assert.Len(t, row["credentials"].([]interface{}), 2) + assert.Equal(t, true, findRowByID(t, w, "windsurf")["browser_login_disabled"], "the flag is install-wide") w = h.call(http.MethodDelete, "/api/v1/clients/cursor/logins/"+grantID, "", bindingAdminKey) require.Equal(t, http.StatusOK, w.Code, w.Body.String()) @@ -353,3 +362,35 @@ func TestOAuthLoginREST_OAuthOnlyClientRow(t *testing.T) { assert.Equal(t, "locked", found["profile_mode"]) assert.Len(t, found["credentials"].([]interface{}), 1) } + +func findRowByID(t *testing.T, w *httptest.ResponseRecorder, id string) map[string]interface{} { + t.Helper() + for _, c := range dataOf(t, w)["clients"].([]interface{}) { + if m := c.(map[string]interface{}); m["id"] == id { + return m + } + } + t.Fatalf("%s row missing", id) + return nil +} + +// An mcp_oat_ access token is valid on its MCP address only: on the REST API it +// gets the client-credential 403 once the feature is on or was used, and the +// previous answer (unknown token, 401) while it is off and never used. +func TestOAuthLoginREST_AccessTokenRefusedOnREST(t *testing.T) { + const oat = "mcp_oat_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + status := func(h *oauthHarness, hdr, val string) int { + req := httptest.NewRequest(http.MethodGet, "/api/v1/status", http.NoBody) + req.Header.Set(hdr, val) + w := httptest.NewRecorder() + h.srv.ServeHTTP(w, req) + return w.Code + } + on := newOAuthHarness(t, true) + assert.Equal(t, http.StatusForbidden, status(on, "Authorization", "Bearer "+oat)) + assert.Equal(t, http.StatusForbidden, status(on, "Authorization", "Bearer "+oat), "extra whitespace is the same token") + assert.Equal(t, http.StatusForbidden, status(on, "X-API-Key", oat)) + off := newOAuthHarness(t, false) + assert.Equal(t, http.StatusUnauthorized, status(off, "Authorization", "Bearer "+oat), "off and never used: unchanged") + assert.Equal(t, http.StatusUnauthorized, status(off, "X-API-Key", oat)) +} diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index de495cc3e..055ef0226 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -30,6 +30,7 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/launch" "github.com/smart-mcp-proxy/mcpproxy-go/internal/logs" "github.com/smart-mcp-proxy/mcpproxy-go/internal/management" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" "github.com/smart-mcp-proxy/mcpproxy-go/internal/oauth" "github.com/smart-mcp-proxy/mcpproxy-go/internal/observability" "github.com/smart-mcp-proxy/mcpproxy-go/internal/preflight" @@ -682,6 +683,10 @@ func (s *Server) authenticateWithPrecedence(w http.ResponseWriter, r *http.Reque // sources never resolve a session principal (only Authorization: Bearer and // the cookie do). func (s *Server) authenticateExplicitToken(w http.ResponseWriter, r *http.Request, next http.Handler, cfg *config.Config, token string) { + if token != "" && s.isLiveOAuthAccessToken(token) { + s.rejectClientCredentialOnREST(w, r) + return + } if token != "" && strings.HasPrefix(token, auth.ClientTokenPrefixStr) { s.rejectClientCredentialOnREST(w, r) return @@ -712,6 +717,10 @@ func (s *Server) authenticateExplicitToken(w http.ResponseWriter, r *http.Reques func (s *Server) authenticateBearer(w http.ResponseWriter, r *http.Request, next http.Handler, cfg *config.Config, authHeader string) { token := bearerToken(authHeader) + if token != "" && s.isLiveOAuthAccessToken(token) { + s.rejectClientCredentialOnREST(w, r) + return + } if token != "" && strings.HasPrefix(token, auth.ClientTokenPrefixStr) { s.rejectClientCredentialOnREST(w, r) return @@ -741,6 +750,18 @@ func (s *Server) authenticateBearer(w http.ResponseWriter, r *http.Request, next s.writeError(w, r, http.StatusUnauthorized, "Invalid or missing API key") } +// isLiveOAuthAccessToken reports whether token is a browser-login access token +// (mcp_oat_) while browser login is on or was used (Spec 132): like a client +// credential it is valid on MCP endpoints only. With the feature off and never +// used the prefix means nothing and the request is handled as before. +func (s *Server) isLiveOAuthAccessToken(token string) bool { + if !strings.HasPrefix(strings.TrimSpace(token), mcplogin.AccessTokenPrefix) { + return false + } + svc := s.oauthLoginService + return svc != nil && (svc.Enabled() || svc.EverUsed()) +} + // rejectClientCredentialOnREST is the FR-023 refusal: a Spec 108-c client // credential (kind=client, mcp_cli_ secret prefix) authenticates on MCP // endpoints only. Recognised by the prefix BEFORE any store lookup — a diff --git a/internal/runtime/clients_service_oauth.go b/internal/runtime/clients_service_oauth.go index a0b14c37d..de6a31ebf 100644 --- a/internal/runtime/clients_service_oauth.go +++ b/internal/runtime/clients_service_oauth.go @@ -224,7 +224,7 @@ func (st oauthClientsState) decorate(v *ClientCredentialView, rec *auth.AgentTok }) } v.Credentials = creds - disabled := st.disabled && len(grants) > 0 + disabled := st.disabled // install-wide: only whether the switch is off right now v.BrowserLoginDisabled = &disabled } diff --git a/internal/runtime/oauth_login_clients_test.go b/internal/runtime/oauth_login_clients_test.go index 0ee4d95c5..24ab7017d 100644 --- a/internal/runtime/oauth_login_clients_test.go +++ b/internal/runtime/oauth_login_clients_test.go @@ -131,7 +131,7 @@ func TestClientViews_ListCredentialsOnceUsed(t *testing.T) { require.NoError(t, err) assert.True(t, *got.BrowserLoginDisabled) codex2, _ := fx.clients.Get("codex") - assert.False(t, *codex2.BrowserLoginDisabled, "only a client that has logins is flagged") + assert.True(t, *codex2.BrowserLoginDisabled, "browser_login_disabled reflects the install-wide switch, not whether the client has logins") // A lapsed login says so. fx.clock.Advance(OAuthRefreshTokenTTL + time.Hour) diff --git a/internal/runtime/oauth_login_everused_test.go b/internal/runtime/oauth_login_everused_test.go new file mode 100644 index 000000000..8e70e9410 --- /dev/null +++ b/internal/runtime/oauth_login_everused_test.go @@ -0,0 +1,24 @@ +package runtime + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" +) + +// brokenMarkerStore cannot read the ever-used marker. +type brokenMarkerStore struct{ OAuthLoginStore } + +func (brokenMarkerStore) OAuthLoginEverUsed() (bool, error) { return false, errors.New("disk on fire") } + +// An unreadable marker is read as "used" (fail closed), and the answer is not +// cached: a later successful read wins. +func TestEverUsed_ReadErrorFailsClosed(t *testing.T) { + fx := newOAuthFx(t) + svc := NewOAuthLoginService(OAuthLoginDeps{Store: brokenMarkerStore{fx.sm}}) + assert.True(t, svc.EverUsed(), "a read error must not look like a never-used install") + + healthy := NewOAuthLoginService(OAuthLoginDeps{Store: fx.sm}) + assert.False(t, healthy.EverUsed(), "a successful read of an unused install is false") +} diff --git a/internal/runtime/oauth_login_service.go b/internal/runtime/oauth_login_service.go index 6115d6cab..08fd855ea 100644 --- a/internal/runtime/oauth_login_service.go +++ b/internal/runtime/oauth_login_service.go @@ -199,7 +199,8 @@ func (s *OAuthLoginService) Enabled() bool { } // EverUsed reports whether a browser login was ever stored. Only a positive -// answer is cached: the marker is never cleared, a negative one can change. +// answer is cached: the marker is never cleared, a negative one can change. A +// storage read error answers true (fail closed, never cached). func (s *OAuthLoginService) EverUsed() bool { s.everMu.Lock() defer s.everMu.Unlock() @@ -208,8 +209,10 @@ func (s *OAuthLoginService) EverUsed() bool { } used, err := s.store.OAuthLoginEverUsed() if err != nil { - s.logger.Warn("cannot read the browser-login marker", zap.Error(err)) - return false + // Fail closed: an unreadable marker is read as "used", so a used and + // switched-off install never falls back to the previous behaviour. + s.logger.Warn("cannot read the browser-login marker; treating the feature as used", zap.Error(err)) + return true } s.everUsed = used return used diff --git a/internal/runtime/oauth_login_tokens.go b/internal/runtime/oauth_login_tokens.go index 50857cf1f..bbd5f5747 100644 --- a/internal/runtime/oauth_login_tokens.go +++ b/internal/runtime/oauth_login_tokens.go @@ -156,6 +156,24 @@ func (s *OAuthLoginService) Authenticate(accessToken, origin, path string, now t return ac, grant, nil } +// GrantLive reports whether the login grantID still authenticates the access +// token that expires at accessExpiresAt: the feature is on, the grant exists +// (a forgotten client's grants are gone), is not revoked, its refresh lifetime +// has not run out and its access token is the one that was authenticated (a +// refresh rotates it). A plain storage read that takes no runtime lock; any +// read error answers false (fail closed). +func (s *OAuthLoginService) GrantLive(grantID string, accessExpiresAt time.Time) bool { + if !s.Enabled() { + return false + } + g, err := s.store.GetOAuthGrant(grantID) + if err != nil || g == nil || g.Revoked { + return false + } + now := s.now() + return g.AccessExpiresAt.Equal(accessExpiresAt) && g.AccessExpiresAt.After(now) && g.RefreshExpiresAt.After(now) +} + // touchInterval bounds how often a grant's last-used stamp is rewritten. const touchInterval = time.Minute diff --git a/internal/server/oauth_login_default_off_test.go b/internal/server/oauth_login_default_off_test.go index 5e3fdb14d..69cd15b2e 100644 --- a/internal/server/oauth_login_default_off_test.go +++ b/internal/server/oauth_login_default_off_test.go @@ -114,7 +114,8 @@ func TestOAuthLogin_DefaultOff_RoutesUnchanged(t *testing.T) { "garbage": {"Authorization": "Bearer garbage-token"}, // An access-token-shaped credential is just an unknown token while the // feature is off and never used (Spec 132 FR-002). - "oat": {"Authorization": "Bearer mcp_oat_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}, + "oat": {"Authorization": "Bearer mcp_oat_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}, + "oat-ws": {"Authorization": "Bearer mcp_oat_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}, } for _, requireAuth := range []bool{false, true} { srv := newOAuthLoginTestServer(t, func(c *config.Config) { c.RequireMCPAuth = requireAuth }) diff --git a/internal/server/oauth_login_hardening_test.go b/internal/server/oauth_login_hardening_test.go new file mode 100644 index 000000000..63a3ed060 --- /dev/null +++ b/internal/server/oauth_login_hardening_test.go @@ -0,0 +1,267 @@ +//go:build !server + +package server + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "io" + "net/http" + "net/url" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" +) + +// Item 1: register accepts exactly one JSON value within the size limit, and +// only as application/json. +func TestOAuthLoginHardening_RegisterBodyAndMediaType(t *testing.T) { + f := newOAuthFlow(t, nil) + obj := `{"redirect_uris":["https://a.example/1"]}` + + // padding past 16 KiB after a valid object is refused, not accepted + rec := f.postJSON("/oauth/register", obj+strings.Repeat(" ", 17<<10)) + assert.Equal(t, http.StatusRequestEntityTooLarge, rec.Code) + // a second JSON value + rec = f.postJSON("/oauth/register", obj+` {"x":1}`) + assert.Equal(t, http.StatusBadRequest, rec.Code) + assert.Equal(t, "invalid_client_metadata", decodeBody(t, rec)["error"]) + // trailing whitespace within the limit is fine + assert.Equal(t, http.StatusCreated, f.postJSON("/oauth/register", obj+"\n ").Code) + + // media type + for ct, want := range map[string]int{ + "application/json": http.StatusCreated, + "application/json; charset=utf-8": http.StatusCreated, + "text/plain": http.StatusUnsupportedMediaType, + "application/x-www-form-urlencoded": http.StatusUnsupportedMediaType, + "": http.StatusUnsupportedMediaType, + } { + req, _ := http.NewRequest(http.MethodPost, "/oauth/register", strings.NewReader(obj)) + if ct != "" { + req.Header.Set("Content-Type", ct) + } + assert.Equal(t, want, f.do(req).Code, "content type %q", ct) + } +} + +// Item 2: extra whitespace after "Bearer" is the same token on the classic routes. +func TestOAuthLoginHardening_BearerWhitespaceOnClassicMCP(t *testing.T) { + const oat = "mcp_oat_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + on := newOAuthFlow(t, nil) + assert.Equal(t, http.StatusUnauthorized, on.get("/mcp", map[string]string{"Authorization": "Bearer " + oat}).Code) + assert.Equal(t, http.StatusUnauthorized, on.get("/mcp", map[string]string{"Authorization": "Bearer \t" + oat}).Code) + off := newOAuthFlow(t, func(c *config.Config) { c.MCPOAuthEnabled = false }) + assert.Equal(t, http.StatusOK, off.get("/mcp", map[string]string{"Authorization": "Bearer " + oat}).Code, "off and never used: unchanged") +} + +// Item 7: a web page cannot drive the public state-changing endpoints. +func TestOAuthLoginHardening_CrossSiteRefused(t *testing.T) { + f := newOAuthFlow(t, nil) + body := `{"redirect_uris":["https://a.example/1"]}` + post := func(path, ctype, payload string, hdr map[string]string) int { + req, _ := http.NewRequest(http.MethodPost, path, strings.NewReader(payload)) + req.Header.Set("Content-Type", ctype) + for k, v := range hdr { + req.Header.Set(k, v) + } + return f.do(req).Code + } + form := url.Values{"grant_type": {"authorization_code"}}.Encode() + for name, hdr := range map[string]map[string]string{ + "foreign origin": {"Origin": "https://evil.example"}, + "null origin": {"Origin": "null"}, + "cross-site": {"Sec-Fetch-Site": "cross-site"}, + } { + assert.Equal(t, http.StatusForbidden, post("/oauth/register", "application/json", body, hdr), "register "+name) + assert.Equal(t, http.StatusForbidden, post("/oauth/token", "application/x-www-form-urlencoded", form, hdr), "token "+name) + } + // Nothing was stored and no budget was spent by the refused requests. + // Own origin, same-origin and absent headers are accepted. + assert.Equal(t, http.StatusCreated, post("/oauth/register", "application/json", body, map[string]string{"Origin": oauthTestOrigin})) + assert.Equal(t, http.StatusCreated, post("/oauth/register", "application/json", body, map[string]string{"Sec-Fetch-Site": "same-origin"})) + assert.Equal(t, http.StatusCreated, post("/oauth/register", "application/json", body, nil)) + + // The authorize GET is a top-level navigation and keeps working. + regID := f.register(oauthTestRedirect) + _, challenge := pkce() + rec := f.get(f.authorizeQuery(regID, oauthTestRedirect, challenge, oauthTestOrigin+"/mcp/oauth/cursor", "s"), map[string]string{"Sec-Fetch-Site": "cross-site"}) + assert.Equal(t, http.StatusFound, rec.Code) +} + +// Item 9: a request that went through a proxy is not a local one. +func TestOAuthLoginHardening_ProxyHeadersRefused(t *testing.T) { + f := newOAuthFlow(t, nil) + for _, h := range []string{"Forwarded", "X-Forwarded-For", "X-Forwarded-Host", "X-Real-IP"} { + for _, path := range oauthLoginGatedPaths { + assert.Equal(t, http.StatusNotFound, f.get(path, map[string]string{h: "203.0.113.9"}).Code, h+" "+path) + } + // Classic routes are untouched. + assert.Equal(t, http.StatusOK, f.get("/mcp", map[string]string{h: "203.0.113.9"}).Code, "classic /mcp with "+h) + } + assert.Equal(t, http.StatusOK, f.get("/.well-known/oauth-authorization-server", nil).Code) +} + +// Item 6: what is open on a login ends with the login. +func TestOAuthLogin_OpenStreamsEndWithTheLogin(t *testing.T) { + env := NewTestEnvironmentWithOptions(t, TestEnvironmentOptions{ + Mutate: func(cfg *config.Config, _ string) { cfg.MCPOAuthEnabled = true }, + }) + t.Cleanup(env.Cleanup) + base := strings.TrimSuffix(env.proxyAddr, "/mcp") + svc := env.proxyServer.oauthLoginSvc() + require.NotNil(t, svc) + require.Zero(t, env.proxyServer.oauthTrackedRequests(), "nothing tracked before the first OAuth request") + httpc := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + + login := func(client string) string { + redirect := "http://127.0.0.1:50999/callback" + resp, err := httpc.Post(base+"/oauth/register", "application/json", strings.NewReader(`{"redirect_uris":["`+redirect+`"]}`)) + require.NoError(t, err) + var reg map[string]any + require.NoError(t, json.NewDecoder(resp.Body).Decode(®)) + resp.Body.Close() + regID, _ := reg["client_id"].(string) + verifier := strings.Repeat("q", 50) + sum := sha256.Sum256([]byte(verifier)) + resource := base + "/mcp/oauth/" + client + q := url.Values{"response_type": {"code"}, "client_id": {regID}, "redirect_uri": {redirect}, + "code_challenge": {base64.RawURLEncoding.EncodeToString(sum[:])}, "code_challenge_method": {"S256"}, "resource": {resource}} + resp, err = httpc.Get(base + "/oauth/authorize?" + q.Encode()) + require.NoError(t, err) + resp.Body.Close() + loc, err := url.Parse(resp.Header.Get("Location")) + require.NoError(t, err) + redir, err := svc.Approve(context.Background(), loc.Query().Get("request"), runtime.ApprovalChoice{Client: runtime.ClientChoice{ID: client}}) + require.NoError(t, err) + ru, _ := url.Parse(redir) + form := url.Values{"grant_type": {"authorization_code"}, "code": {ru.Query().Get("code")}, "redirect_uri": {redirect}, + "client_id": {regID}, "code_verifier": {verifier}, "resource": {resource}} + resp, err = httpc.Post(base+"/oauth/token", "application/x-www-form-urlencoded", strings.NewReader(form.Encode())) + require.NoError(t, err) + defer resp.Body.Close() + var tok map[string]any + require.NoError(t, json.NewDecoder(resp.Body).Decode(&tok)) + access, _ := tok["access_token"].(string) + require.NotEmpty(t, access) + return access + } + + // openStream opens a session on the client's OAuth address and an SSE GET + // stream on it; done closes when the stream ends. + openStream := func(client, access string) (done chan struct{}) { + do := func(method, body, session string) *http.Response { + req, _ := http.NewRequest(method, base+"/mcp/oauth/"+client, bytes.NewBufferString(body)) + req.Header.Set("Authorization", "Bearer "+access) + req.Header.Set("Accept", "application/json, text/event-stream") + if method == http.MethodPost { + req.Header.Set("Content-Type", "application/json") + } + if session != "" { + req.Header.Set("Mcp-Session-Id", session) + } + resp, err := httpc.Do(req) + require.NoError(t, err) + return resp + } + resp := do(http.MethodPost, `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"t","version":"1"}}}`, "") + require.Equal(t, http.StatusOK, resp.StatusCode) + session := resp.Header.Get("Mcp-Session-Id") + _, _ = io.Copy(io.Discard, resp.Body) + resp.Body.Close() + resp = do(http.MethodPost, `{"jsonrpc":"2.0","method":"notifications/initialized"}`, session) + resp.Body.Close() + stream := do(http.MethodGet, "", session) + require.Equal(t, http.StatusOK, stream.StatusCode) + done = make(chan struct{}) + go func() { + _, _ = io.Copy(io.Discard, stream.Body) + stream.Body.Close() + close(done) + }() + return done + } + open := func(done chan struct{}, d time.Duration) bool { + select { + case <-done: + return false + case <-time.After(d): + return true + } + } + + accessA := login("cursor") + accessB := login("windsurf") + streamA := openStream("cursor", accessA) + streamB := openStream("windsurf", accessB) + require.True(t, open(streamA, time.Second), "an authenticated stream stays open") + require.True(t, open(streamB, 0)) + + // Revoking A's login ends A's stream promptly and leaves B's open. + grants, err := svc.ListGrants("cursor") + require.NoError(t, err) + require.Len(t, grants, 1) + _, err = svc.RevokeGrant(context.Background(), "cursor", grants[0].GrantID) + require.NoError(t, err) + select { + case <-streamA: + case <-time.After(5 * time.Second): + t.Fatal("the revoked login's stream is still open") + } + require.True(t, open(streamB, time.Second), "an unrelated login's stream stays open") + + // Switching the feature off ends the rest. + cfg := env.proxyServer.runtime.Config() + off := *cfg + off.MCPOAuthEnabled = false + env.proxyServer.runtime.UpdateConfig(&off, "") + select { + case <-streamB: + case <-time.After(5 * time.Second): + t.Fatal("the stream survived the switch-off") + } + require.Eventually(t, func() bool { return env.proxyServer.oauthTrackedRequests() == 0 }, 5*time.Second, 50*time.Millisecond, + "ended streams leave nothing behind") +} + +// A tracked request ends at its access token's expiry and leaves no entry. +func TestOAuthLoginHardening_RegistryExpiryAndRelease(t *testing.T) { + srv := newOAuthLoginTestServer(t, func(c *config.Config) { c.MCPOAuthEnabled = true }) + ctx, cancel := context.WithCancel(context.Background()) + release := srv.trackOAuthRequest("g1", time.Now().Add(150*time.Millisecond), cancel) + require.Equal(t, 1, srv.oauthTrackedRequests()) + select { + case <-ctx.Done(): + case <-time.After(3 * time.Second): + t.Fatal("the request outlived its access token") + } + release() + assert.Zero(t, srv.oauthTrackedRequests()) + + // A request that ends normally leaves nothing behind. + ctx2, cancel2 := context.WithCancel(context.Background()) + release2 := srv.trackOAuthRequest("g2", time.Now().Add(time.Hour), cancel2) + release2() + assert.Zero(t, srv.oauthTrackedRequests()) + assert.Error(t, ctx2.Err()) +} + +// oauthTrackedRequests is the number of requests currently tracked (tests). +func (s *Server) oauthTrackedRequests() int { + r := s.oauthStreams.Load() + if r == nil { + return 0 + } + r.mu.Lock() + defer r.mu.Unlock() + return len(r.entries) +} diff --git a/internal/server/oauth_login_http.go b/internal/server/oauth_login_http.go index b7c735477..405d5e201 100644 --- a/internal/server/oauth_login_http.go +++ b/internal/server/oauth_login_http.go @@ -1,9 +1,12 @@ package server import ( + "context" "encoding/json" "errors" "html" + "io" + "mime" "net" "net/http" "net/url" @@ -137,6 +140,30 @@ func oauthErrorPage(w http.ResponseWriter, status int, title, detail string) { html.EscapeString(title) + "

" + html.EscapeString(detail) + "

")) } +// oauthMediaType reports whether the request's Content-Type is want (a media +// type; parameters such as charset are allowed). +func oauthMediaType(r *http.Request, want string) bool { + mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + return err == nil && mt == want +} + +// oauthCrossSite refuses (403, and reports true) a state-changing public +// request that a web page in the administrator's browser sent to the loopback +// address: an Origin that is not this request's own origin, or +// Sec-Fetch-Site: cross-site. Native clients send neither header. It is not +// applied to the authorize GET, which is a top-level browser navigation. +func oauthCrossSite(w http.ResponseWriter, r *http.Request) bool { + if o := r.Header.Get("Origin"); o != "" && o != mcplogin.Origin(r) { + oauthJSONError(w, http.StatusForbidden, "access_denied", "cross-origin requests are not accepted") + return true + } + if r.Header.Get("Sec-Fetch-Site") == "cross-site" { + oauthJSONError(w, http.StatusForbidden, "access_denied", "cross-site requests are not accepted") + return true + } + return false +} + // --- metadata -------------------------------------------------------------------- func (s *Server) oauthASMetadata(w http.ResponseWriter, r *http.Request) { @@ -171,13 +198,29 @@ func (s *Server) oauthRegister(w http.ResponseWriter, r *http.Request, svc *runt oauthMethodNotAllowed(w, "POST") return } - if !s.oauthAllow(w, r, mcplogin.EndpointRegister, false) { + if oauthCrossSite(w, r) || !s.oauthAllow(w, r, mcplogin.EndpointRegister, false) { + return + } + if !oauthMediaType(r, "application/json") { + oauthJSONError(w, http.StatusUnsupportedMediaType, "invalid_request", "the body must be application/json") return } var req mcplogin.RegistrationRequest body := http.MaxBytesReader(w, r.Body, mcplogin.MaxBodyBytes) dec := json.NewDecoder(body) - if err := dec.Decode(&req); err != nil { + err := dec.Decode(&req) + if err == nil { + // Exactly one JSON value: whatever follows it (a second value, or + // padding that pushes the body past the limit) is refused. + var extra json.RawMessage + if err = dec.Decode(&extra); errors.Is(err, io.EOF) { + err = nil + } else if err == nil { + oauthJSONError(w, http.StatusBadRequest, mcplogin.ErrCodeInvalidClientMetadata, "the body must be a single JSON object") + return + } + } + if err != nil { var tooBig *http.MaxBytesError if errors.As(err, &tooBig) { oauthJSONError(w, http.StatusRequestEntityTooLarge, mcplogin.ErrCodeInvalidClientMetadata, "the request is too large") @@ -247,7 +290,7 @@ func (s *Server) oauthToken(w http.ResponseWriter, r *http.Request, svc *runtime oauthMethodNotAllowed(w, "POST") return } - if !s.oauthAllow(w, r, mcplogin.EndpointToken, false) { + if oauthCrossSite(w, r) || !s.oauthAllow(w, r, mcplogin.EndpointToken, false) { return } if ct := r.Header.Get("Content-Type"); !strings.HasPrefix(strings.ToLower(ct), "application/x-www-form-urlencoded") { @@ -339,6 +382,12 @@ func (s *Server) oauthResourceAuth(next http.Handler) http.Handler { return } svc.Touch(grant.GrantID, "") - mcpRequestMiddlewares(next).ServeHTTP(w, r.WithContext(auth.WithAuthContext(r.Context(), ac))) + // The request (an SSE stream can live for hours) ends when the login is + // revoked, its client forgotten, the feature switched off, its tokens + // rotated or its access token expires. + ctx, cancel := context.WithCancel(auth.WithAuthContext(r.Context(), ac)) + release := s.trackOAuthRequest(grant.GrantID, grant.AccessExpiresAt, cancel) + defer release() + mcpRequestMiddlewares(next).ServeHTTP(w, r.WithContext(ctx)) }) } diff --git a/internal/server/oauth_login_routes.go b/internal/server/oauth_login_routes.go index dc6655f4a..e248fd6ce 100644 --- a/internal/server/oauth_login_routes.go +++ b/internal/server/oauth_login_routes.go @@ -41,6 +41,18 @@ func peerIsLoopback(r *http.Request) bool { return ap.Addr().Unmap().IsLoopback() } +// hasProxyHeaders reports whether the request carries a header a reverse +// proxy or tunnel adds. A proxy on the same host presents as a loopback peer, +// so such a request is not a local one and the OAuth routes answer 404. +func hasProxyHeaders(r *http.Request) bool { + for _, h := range []string{"Forwarded", "X-Forwarded-For", "X-Forwarded-Host", "X-Real-IP"} { + if _, ok := r.Header[http.CanonicalHeaderKey(h)]; ok { + return true + } + } + return false +} + // oauthLoginEverUsedNow reports whether browser login has ever been used on // this install: the storage marker `oauth_login_ever_used`, read through the // service (only a positive answer is cached; a read never writes). It is @@ -73,7 +85,7 @@ func (s *Server) oauthLoginGate(prev, served http.Handler) http.Handler { prev.ServeHTTP(w, r) return } - if !peerIsLoopback(r) || !httpx.IsLoopbackHost(r.Host) || !oauthLoginEditionSupported { + if !peerIsLoopback(r) || !httpx.IsLoopbackHost(r.Host) || !oauthLoginEditionSupported || hasProxyHeaders(r) { http.NotFound(w, r) return } diff --git a/internal/server/oauth_login_streams.go b/internal/server/oauth_login_streams.go new file mode 100644 index 000000000..61b691266 --- /dev/null +++ b/internal/server/oauth_login_streams.go @@ -0,0 +1,130 @@ +package server + +import ( + "context" + "sync" + "time" +) + +// Spec 132 FR-031 / SC-006: revoking a login, forgetting its client, switching +// the feature off, rotating its tokens or the access token's expiry must also +// end what is already open on that login (a long-lived SSE stream, a slow +// request), not only the next request. oauthResourceAuth authenticates once +// per request, so every authenticated request is tracked here with the cancel +// of its context. +// +// The registry never calls into the runtime while a runtime lock is held and +// takes no runtime lock itself: a watcher goroutine re-reads each tracked grant +// from storage (OAuthLoginService.GrantLive, a plain read) every +// oauthStreamCheckInterval and whenever the binding notifier wakes it (grant +// revoke, replay revoke, client revoke or forget all call it), and an expiry +// timer bound to the access token's lifetime cancels the request when the token +// runs out. Nothing is allocated until the first OAuth request, and the watcher +// exits when the last tracked request ends. + +const oauthStreamCheckInterval = time.Second + +type oauthStream struct { + grantID string + expiresAt time.Time // the access token's expiry when it was authenticated + cancel context.CancelFunc + timer *time.Timer +} + +type oauthStreamRegistry struct { + mu sync.Mutex + next uint64 + entries map[uint64]*oauthStream + running bool + wake chan struct{} +} + +// oauthStreamsRegistry returns the registry, creating it on first use. +func (s *Server) oauthStreamsRegistry() *oauthStreamRegistry { + if r := s.oauthStreams.Load(); r != nil { + return r + } + s.oauthStreams.CompareAndSwap(nil, &oauthStreamRegistry{entries: map[uint64]*oauthStream{}, wake: make(chan struct{}, 1)}) + return s.oauthStreams.Load() +} + +// wakeOAuthStreams asks the watcher to re-check now. It allocates nothing and +// never blocks: with no registry (default-off installs) it does nothing. +func (s *Server) wakeOAuthStreams() { + if r := s.oauthStreams.Load(); r != nil { + select { + case r.wake <- struct{}{}: + default: + } + } +} + +// trackOAuthRequest registers an authenticated request of grantID. cancel ends +// its context. The returned release must be called when the request ends; it +// stops the expiry timer, forgets the entry and cancels the context. +func (s *Server) trackOAuthRequest(grantID string, expiresAt time.Time, cancel context.CancelFunc) (release func()) { + reg := s.oauthStreamsRegistry() + st := &oauthStream{grantID: grantID, expiresAt: expiresAt, cancel: cancel} + if d := time.Until(expiresAt); d > 0 { + st.timer = time.AfterFunc(d, cancel) + } else { + cancel() + } + reg.mu.Lock() + reg.next++ + id := reg.next + reg.entries[id] = st + start := !reg.running + reg.running = true + reg.mu.Unlock() + if start { + go s.watchOAuthStreams(reg) + } + return func() { + reg.mu.Lock() + delete(reg.entries, id) + reg.mu.Unlock() + if st.timer != nil { + st.timer.Stop() + } + cancel() + } +} + +// watchOAuthStreams re-validates the tracked grants until none is left. +func (s *Server) watchOAuthStreams(reg *oauthStreamRegistry) { + ticker := time.NewTicker(oauthStreamCheckInterval) + defer ticker.Stop() + for { + reg.mu.Lock() + if len(reg.entries) == 0 { + reg.running = false + reg.mu.Unlock() + return + } + type key struct { + grant string + exp time.Time + } + groups := map[key][]*oauthStream{} + for _, e := range reg.entries { + k := key{e.grantID, e.expiresAt} + groups[k] = append(groups[k], e) + } + reg.mu.Unlock() + + svc := s.oauthLoginSvc() + for k, list := range groups { + if svc != nil && svc.GrantLive(k.grant, k.exp) { + continue + } + for _, e := range list { + e.cancel() + } + } + select { + case <-ticker.C: + case <-reg.wake: + } + } +} diff --git a/internal/server/profile_notify.go b/internal/server/profile_notify.go index 58e0c3757..40a698a83 100644 --- a/internal/server/profile_notify.go +++ b/internal/server/profile_notify.go @@ -17,6 +17,11 @@ import ( // request re-resolves against the credential's current binding, FR-020), but // no stale selection window is left either. func (p *MCPProxyServer) NotifyBindingChanged(tokenName string) { + // Spec 132: a revoked or forgotten browser login ends what it has open. + // The wake is a non-blocking channel send; the check runs in the watcher. + if p.mainServer != nil { + p.mainServer.wakeOAuthStreams() + } if p.sessionStore == nil { return } diff --git a/internal/server/server.go b/internal/server/server.go index d9edc704b..d07c7978e 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -128,6 +128,10 @@ type Server struct { oauthLoginEverUsed func() bool // oauthLimiter rate limits the public browser-login endpoints (Spec 132); // built on first use so a default-off install never allocates it. + // oauthStreams tracks authenticated browser-login requests so a revoke or + // a switch-off ends what is already open (oauth_login_streams.go); nil + // until the first one. + oauthStreams atomic.Pointer[oauthStreamRegistry] oauthLimiterOnce sync.Once oauthLimiter *mcplogin.Limiter // createAfterConfigRead is a Spec 116 test seam (nil in production): it @@ -689,7 +693,7 @@ func (s *Server) mcpAuthMiddleware(next http.Handler) http.Handler { // /mcp/oauth address (audience binding). Anywhere else it is refused, // also with require_mcp_auth off, but only while the feature is on or // was used: with it off and never used every answer is the previous one. - if mcplogin.IsAccessToken(token) && s.oauthLoginLive() { + if mcplogin.IsAccessToken(strings.TrimSpace(token)) && s.oauthLoginLive() { http.Error(w, `{"error":"This token is not valid for this endpoint."}`, http.StatusUnauthorized) return } diff --git a/oas/docs.go b/oas/docs.go index bfb1dde23..f48e13dba 100644 --- a/oas/docs.go +++ b/oas/docs.go @@ -6,7 +6,7 @@ import "github.com/swaggo/swag/v2" const docTemplate = `{ "schemes": {{ marshal .Schemes }}, - "components": {"schemas":{"auth.CredentialIssuer":{"properties":{"actor_kind":{"type":"string"},"actor_name":{"type":"string"},"surface":{"type":"string"}},"type":"object"},"config.AgentTokenRateLimit":{"description":"AgentTokenRateLimit caps how many upstream tool calls ONE agent token may\nmake: PerMinute on average, Burst at once (issue #1699). Every token is\ncounted separately, and a token's own rate_limit (set when it is created)\nreplaces this default for that token. Only agent-token callers are\nlimited; the admin API key, the unix socket and an unauthenticated /mcp\ncaller are not. Absent or per_minute 0 = no limit (default, zero behavior\nchange). The counters are in memory: a restart gives every token a full\nallowance again. Hot-reloadable. File/API-configured only, no env scheme.","properties":{"burst":{"description":"Burst is how many calls a token may make at once after a quiet spell.\n0 = the PerMinute value.","type":"integer"},"per_minute":{"description":"PerMinute is the sustained rate. 0 = no limit.","type":"integer"}},"type":"object"},"config.AuditLogConfig":{"description":"AuditLog configures the Spec 107 edition-neutral audit sink\n(internal/audit). nil means \"use the per-edition/per-transport\ndefault\" (EffectiveAuditLog); restart-pinned (bound at sink\nconstruction). See audit_log.go.","properties":{"compress":{"type":"boolean"},"enabled":{"type":"boolean"},"max_age_days":{"type":"integer"},"max_backups":{"type":"integer"},"max_size_mb":{"type":"integer"},"path":{"type":"string"},"stdout":{"type":"boolean"}},"type":"object"},"config.ConcurrencyDefaults":{"description":"ServerConcurrencyDefaults is scope (b) of FR-020: the blanket per-server\ndefault set inherited by every server that does not override a setting.\nAbsent (the default) = no per-server limiting unless a server configures\nit explicitly. File/API-configured only — no env scheme (FR-022).","properties":{"max_concurrent_requests":{"type":"integer"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"}},"type":"object"},"config.Config":{"properties":{"activity_cleanup_interval_min":{"description":"Background cleanup interval in minutes (default: 60)","type":"integer"},"activity_max_records":{"description":"Max records before pruning (default: 400000)","type":"integer"},"activity_max_response_size":{"description":"Response truncation limit in bytes (default: 65536)","type":"integer"},"activity_max_size_mb":{"description":"ActivityMaxSizeMB caps the total activity-log size in MB before the\noldest records are pruned. Omit the key for the 256MB default; set it to\n0 to disable the size cap.","type":"integer"},"activity_retention_days":{"description":"Activity logging settings (RFC-003)","type":"integer"},"advertise_upstream_servers":{"description":"AdvertiseUpstreamServers controls whether MCP clients are told the\nnames of the upstream servers they can reach — in the initialize\ninstructions and the retrieve_tools description — so agents use the\nproxied tools instead of falling back to shell CLIs. Names are always\nfiltered to the caller's profile and agent-token scope. Default true;\nset false to keep server names out of client context. Read live.","type":"boolean"},"agent_token_rate_limit":{"$ref":"#/components/schemas/config.AgentTokenRateLimit"},"aggregate_upstream_prompts":{"description":"AggregateUpstreamPrompts, when true, aggregates every connected upstream\nserver's advertised MCP prompts into mcpproxy's own prompts/list\n(exposed as \"\u003cserver\u003e__\u003cprompt\u003e\"). OFF by default: users are safe by\ndefault and opt in deliberately. EnablePrompts still governs the built-in\nprompts + the prompts capability; this flag gates ONLY the upstream\naggregation performed by RefreshPrompts. Hot-reloadable.","type":"boolean"},"allow_private_registry_fetch":{"description":"AllowPrivateRegistryFetch opts out of the registry SSRF guard (MCP-1076,\nCWE-918). By default (false) registry fetches refuse any host that is — or\nresolves to — a non-routable address (loopback, RFC1918/CGNAT private,\nlink-local incl. the 169.254.169.254 cloud-metadata endpoint), so a\nmalicious or typo'd registry source cannot turn the daemon into a\nrequest-forgery vector against internal services.\n\nThis opt-out is BLANKET (all-or-nothing): setting it true disables the\nguard for EVERY non-routable range at once — loopback, RFC1918/CGNAT\nprivate, link-local AND the 169.254.169.254 cloud-metadata endpoint. There\nis no way to allow only loopback; enabling it for a localhost dev registry\nalso re-opens the cloud-metadata SSRF vector. Set true ONLY when you\nintentionally run a trusted registry mirror on an internal/private address,\nideally on a host with no cloud-metadata exposure. The change takes effect\nonly on daemon (re)start or config reload.","type":"boolean"},"allow_server_add":{"type":"boolean"},"allow_server_remove":{"type":"boolean"},"anonymous_profile":{"description":"AnonymousProfile confines every caller whose request authenticates as\ncredential kind \"anonymous\" (no credential, or an unrecognised\nnon-agent token accepted by the require_mcp_auth:false back-compat\nbranch) to the named profile (Spec 108 FR-008). Empty (default) means\nunconfined, legacy anonymous behaviour. A name that does not match any\nconfigured profile resolves anonymous callers to deny-all and is\nreported as a validation warning (data-model.md §1).","type":"string"},"api_key":{"description":"Security settings","type":"string"},"audit_log":{"$ref":"#/components/schemas/config.AuditLogConfig"},"call_tool_timeout":{"type":"string"},"check_server_repo":{"description":"Repository detection settings","type":"boolean"},"code_execution_max_parallel":{"description":"Default concurrency for call_tools() batches (1-32, default: 8)","type":"integer"},"code_execution_max_tool_calls":{"description":"Max tool calls per execution (0 = unlimited, default: 0)","type":"integer"},"code_execution_pool_size":{"description":"JavaScript runtime pool size (default: 10)","type":"integer"},"code_execution_timeout_ms":{"description":"Timeout in milliseconds (default: 120000, max: 600000)","type":"integer"},"data_dir":{"type":"string"},"debug_search":{"type":"boolean"},"direct_tool_response_mode":{"description":"DirectToolResponseMode selects the serialization of the DIRECT\nenumeration surface (Spec 102). Valid values: \"\" (= full), \"full\"\n(default: today's schema-bearing entries), \"deferred\" (description +\ncompact signature, with a minimal permissive input schema; upstream\ninputSchema and outputSchema are stripped and recovered on demand via\ndescribe_tool).\n\nDeliberately NOT an extension of tool_response_mode: reusing that axis\nwould silently change /mcp/all output for every deployment already\nrunning compact, which FR-015 forbids. Serialization-only — it never\nchanges WHICH tools are listed, only how (FR-008). Hot-reloadable.","type":"string"},"disable_management":{"type":"boolean"},"docker_isolation":{"$ref":"#/components/schemas/config.DockerIsolationConfig"},"docker_recovery":{"$ref":"#/components/schemas/config.DockerRecoveryConfig"},"enable_code_execution":{"description":"Code execution settings","type":"boolean"},"enable_prompts":{"description":"Prompts settings","type":"boolean"},"enable_skills":{"description":"EnableSkills, when true, makes mcpproxy read the skills that upstream\nservers expose through the MCP skills extension. OFF by default. Unlike\nEnablePrompts this is hot-reloadable. No CLI flag, no environment\nvariable.","type":"boolean"},"enable_socket":{"description":"Enable Unix socket/named pipe for local IPC (default: true)","type":"boolean"},"enable_tray":{"description":"Deprecated: EnableTray is unused and has no runtime effect. Kept for backward compatibility.","type":"boolean"},"environment":{"$ref":"#/components/schemas/secureenv.EnvConfig"},"features":{"$ref":"#/components/schemas/config.FeatureFlags"},"forward_client_headers":{"description":"ForwardClientHeaders is the global switch for client header forwarding\n(Spec 112): copying allowlisted headers from the inbound /mcp request into\nthe upstream tools/call request. nil (absent) means enabled; because every\nper-server forward_headers allowlist is empty by default, the default\nforwards nothing. false disables forwarding for every server. Read via\nIsClientHeaderForwardingEnabled(); MCPPROXY_FORWARD_CLIENT_HEADERS\noverrides it for the process. Distinct from ForwardedHeaders/trusted_proxies\n(Spec 107), which trusts inbound X-Forwarded-*.","type":"boolean"},"forward_proxy_env":{"description":"ForwardProxyEnv opts in to forwarding the ambient HTTP(S)/ALL/NO/FTP proxy\nenvironment variables to spawned stdio upstream servers (MCP-2769). OFF by\ndefault: proxy URLs commonly embed credentials (http://user:pass@proxy), so\nforwarding them to every upstream is a credential-leak risk. When enabled,\nvalues are forwarded with their userinfo (credentials) redacted.","type":"boolean"},"health_check_interval":{"description":"Discovery \u0026 health-check cadence (spec 074, #608). Both are *Duration\ntri-state pointers: nil = inherit the built-in default; a pointer to 0s =\nthe loop is disabled; a positive value = that interval. Defaults live only\nin the resolvers (ResolveHealthCheckInterval / ResolveToolDiscoveryInterval)\nso an unset key behaves exactly as before this feature (SC-005). Validated\nin Validate(): health-check ∈ {0} ∪ [5s,1h]; tool-discovery ∈ {0} ∪ [30s,24h].","type":"string"},"http_idle_timeout":{"description":"HTTPIdleTimeout caps how long an idle keep-alive connection is kept open.\nUnset = 180s. \"0s\" removes the dedicated idle deadline, but net/http then\nfalls back to ReadTimeout — idle is fully unbounded only when\nhttp_read_timeout is also \"0s\". Requires a restart.","type":"string"},"http_read_timeout":{"description":"HTTPReadTimeout caps how long reading a whole request (headers + body)\nmay take. Unset = 120s; \"0s\" disables it. Requires a restart.","type":"string"},"http_write_timeout":{"description":"HTTPWriteTimeout caps how long producing a whole response may take on\nnon-streaming endpoints (REST, Web UI, health). Unset = 120s; \"0s\"\ndisables it globally. MCP and SSE /events routes are exempt by design.","type":"string"},"init_timeout":{"description":"InitTimeout is the global default deadline for an upstream's MCP\n` + "`" + `initialize` + "`" + ` handshake (MCP-3322 / GH #760). *Duration tri-state: nil =\ninherit the built-in 30s default; a positive value = that deadline. A\nper-server InitTimeout overrides this. Resolved by ResolveInitTimeout;\nvalidated to {0} ∪ [1s, 30m] in Validate(). Servers doing legitimate\nfirst-run warmup (cache/index build) before answering ` + "`" + `initialize` + "`" + ` can\nraise this so they are not killed mid-startup.","type":"string"},"instructions":{"description":"Instructions text returned in the MCP initialize response to guide AI agents.\nWhen empty, a built-in default is used that explains retrieve_tools workflow.","type":"string"},"intent_declaration":{"$ref":"#/components/schemas/config.IntentDeclarationConfig"},"listen":{"type":"string"},"logging":{"$ref":"#/components/schemas/config.LogConfig"},"max_concurrent_requests":{"description":"Concurrency limits (spec 093, GH #955). Scope (a) of FR-020: the GLOBAL\nAGGREGATE limiter — one proxy-wide cap on concurrently running upstream\ntool calls, with its own bounded wait queue. Tri-state pointers: absent =\nthe limiter does not exist (default, zero behavior change); an explicit 0\nmax also disables it; positive = that cap. This scope is NEVER a\nper-server inheritance source — per-server values come from\nServerConcurrencyDefaults / the per-server overrides — but a server's\neffective concurrency is bounded by BOTH its own limiter and this one.\nResolved by ResolveGlobalConcurrency; hot-reloadable; overridable via\nMCPPROXY_MAX_CONCURRENT_REQUESTS / _QUEUE_SIZE / _QUEUE_TIMEOUT (FR-022).","type":"integer"},"max_result_size_chars":{"description":"MaxResultSizeChars is advertised on every tool as\n` + "`" + `_meta.anthropic/maxResultSizeChars` + "`" + `; it raises Claude Code's\ninline-response ceiling from 50k to up to 500k chars. Omit the key for\nthe 500000 default; set it to 0 to disable the annotation.","type":"integer"},"mcpServers":{"items":{"$ref":"#/components/schemas/config.ServerConfig"},"type":"array","uniqueItems":false},"mcp_oauth_enabled":{"description":"MCPOAuthEnabled turns on browser login (OAuth 2.1 + PKCE) for MCP\nclients on the loopback listener (Spec 132). Experimental, default false:\nwith it off nothing changes. Env override MCPPROXY_MCP_OAUTH_ENABLED is\nprocess-only and never persisted. Live, no restart needed.","type":"boolean"},"mcp_reject_query_apikey":{"description":"MCPRejectQueryAPIKey makes every MCP endpoint (/mcp*) refuse a request that\ncarries a ?apikey= query parameter, with a 401, instead of honouring it. A credential in a URL ends up in access logs,\nproxy logs and browser history; MCP clients can send Authorization:\nBearer or X-API-Key instead. Default false (the query form keeps\nworking, for clients that can only configure a URL). It covers only the\nMCP endpoints: the Web UI and its SSE stream (/events) still use the\nquery form. Live, no restart needed.","type":"boolean"},"oauth_expiry_warning_hours":{"description":"Health status settings","type":"number"},"oauth_token_encryption_key":{"description":"OAuthTokenEncryptionKey seals the upstream OAuth tokens stored in\nconfig.db (Spec 123). Empty (the default) leaves them as plain JSON. It\ntakes a secret reference (${file:/abs/path}, ${env:NAME},\n${keyring:NAME}) or a literal standard-base64 32-byte key; the\nMCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY[_FILE] variables override it. The key\nis resolved only where config.db is opened (ResolveOAuthTokenKey), never\nstored on Config, and is restart-gated, so every save writes the field\nas configured.","type":"string"},"observability":{"$ref":"#/components/schemas/config.ObservabilityConfig"},"output_sanitisation":{"$ref":"#/components/schemas/config.OutputSanitisationConfig"},"output_validation":{"$ref":"#/components/schemas/config.OutputValidationConfig"},"profiles":{"description":"Profiles are optional named, server-scoped views exposed at /mcp/p/\u003cname\u003e\n(Spec 057). Absent/empty is fully supported — /mcp is unchanged and configs\nwithout this key serialize byte-identically (SC-004).","items":{"$ref":"#/components/schemas/config.ProfileConfig"},"type":"array","uniqueItems":false},"quarantine_enabled":{"description":"QuarantineEnabled controls whether quarantine is active. It gates two\nthings together:\n 1. Server-level auto-quarantine for newly added servers (issue #370).\n When true, servers added via the upstream_servers MCP tool or the\n REST API default to quarantined=true; when false, they default to\n quarantined=false. Explicit per-request values always win.\n 2. Tool-level quarantine (Spec 032): per-tool SHA-256 approval of\n tool descriptions/schemas.\nWhen nil (default), quarantine is enabled (secure by default). Set to\nexplicit false to opt out of both. Per-server SkipQuarantine still\napplies for the tool-level check on individual servers.","type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"read_only_mode":{"type":"boolean"},"registries":{"description":"Registries configuration for MCP server discovery","items":{"$ref":"#/components/schemas/config.RegistryEntry"},"type":"array","uniqueItems":false},"registries_locked":{"description":"RegistriesLocked is an enterprise stub knob (MCP-866): when true, runtime\nadditions of custom registries (e.g. ` + "`" + `registry add-source` + "`" + `, the REST/MCP\nadd-source surface) are rejected so an administrator can pin the discovery\nsources. Built-in defaults are unaffected. Documented but otherwise inert\nbeyond the add-source rejection.","type":"boolean"},"require_mcp_auth":{"description":"Require authentication on /mcp endpoint (default: false)","type":"boolean"},"reveal_secret_headers":{"description":"RevealSecretHeaders, when true, disables the redaction of the\nsecret-bearing server fields — sensitive header values (Authorization,\nX-API-Key, Cookie, …), env-var secrets, and URL query credentials — in\nresponses from the ` + "`" + `upstream_servers` + "`" + ` MCP tool, the ` + "`" + `/api/v1/servers` + "`" + `\nREST API, and the SSE event stream. It also lets URL secrets echoed\ninto last_error / health.detail through unscrubbed.\n\nDefault false — sensitive values are surfaced masked as\n` + "`" + `••••\u003clast2\u003e (\u003cN\u003e chars)` + "`" + ` (error strings use ` + "`" + `***REDACTED***` + "`" + `) so an\nMCP agent cannot read Bearer tokens / API keys / URL secrets out of\nanother upstream's config (PR #425, issue #872). ${env:…}/${keyring:…}\nreferences are labels, not secrets, and pass through unchanged.\n\nThe Web UI / macOS tray edit forms work without seeing the real\nvalues: PATCH /api/v1/servers/{id} deep-merges (omitted keys are\npreserved, see ` + "`" + `headers_remove` + "`" + ` / ` + "`" + `env_remove` + "`" + ` for explicit\ndeletes), so clients compute a diff and only send the keys that\nactually changed. Redacted-but-unchanged values never round-trip\n— the backend keeps the real string. Set this to true if a\ndownstream tool genuinely needs raw values in the response.","type":"boolean"},"routing_mode":{"description":"Routing mode (Spec 031): how MCP tools are exposed to clients\nValid values: \"retrieve_tools\" (default), \"direct\", \"code_execution\"","type":"string"},"security":{"$ref":"#/components/schemas/config.SecurityConfig"},"sensitive_data_detection":{"$ref":"#/components/schemas/config.SensitiveDataDetectionConfig"},"server_concurrency_defaults":{"$ref":"#/components/schemas/config.ConcurrencyDefaults"},"session_retention_days":{"description":"SessionRetentionDays is how long a work session is listed and kept whole\nin the activity log (Spec 124, default 7). Read at start.","type":"integer"},"telemetry":{"$ref":"#/components/schemas/config.TelemetryConfig"},"tls":{"$ref":"#/components/schemas/config.TLSConfig"},"tokenizer":{"$ref":"#/components/schemas/config.TokenizerConfig"},"tool_call_max_records_per_server":{"description":"Calls retained per server (default: 1000)","type":"integer"},"tool_call_max_response_size":{"description":"Bounds for the per-server tool-call history behind GET /api/v1/tool-calls\n(#1176). It is a recent-debugging window, not an audit log — the activity\nlog is the durable record — and it kept every upstream response whole,\nper server, forever. A non-positive value means \"use the default\", not\n\"disable\": this store must never be unbounded again, so there is\ndeliberately no off switch.","type":"integer"},"tool_discovery_interval":{"type":"string"},"tool_response_limit":{"type":"integer"},"tool_response_mode":{"description":"Tool response mode (Spec 085): how retrieve_tools serializes results.\nValid values: \"\" (= full), \"full\" (default: today's schema-bearing\nentries), \"compact\" (signature + first-sentence entries). Orthogonal to\nrouting_mode — routing_mode selects the tool SURFACE, this selects the\nSERIALIZATION within the retrieve_tools surface. Serialization-only: it\nnever affects the query, ranking, or result set. Hot-reloadable.","type":"string"},"tool_response_session_risk_warning":{"description":"ToolResponseSessionRiskWarning controls whether the prose ` + "`" + `warning` + "`" + ` field\nis included in the ` + "`" + `session_risk` + "`" + ` object returned by ` + "`" + `retrieve_tools` + "`" + `.\nThe structured fields (level, lethal_trifecta, has_open_world_tools, etc.)\nare always included. Default: false (quiet for LLM clients) — see issue #406.\nMost tools lack annotations, so the MCP-spec defaults treat them as fully\npermissive across all three risk axes, which makes the prose warning fire\non almost every call and wastes tokens.","type":"boolean"},"tools_limit":{"type":"integer"},"toon_min_savings_pct":{"description":"ToonMinSavingsPct is the minimum byte-savings percentage (validated\n1-90; 0/unset → 15) the complete TOON emission (marker + hint + body)\nmust achieve over the exact passthrough emission for adaptive mode to\nencode a block. Byte savings approximate token savings for the tabular\npayload class; the spec-083 profiler reports true token deltas.\nGlobal-only (no per-server override, FR-001).","type":"integer"},"toon_output":{"description":"ToonOutput selects the TOON encoding mode for call_tool_* result text\nblocks (spec 084): \"off\" (default — responses byte-identical to\npre-feature behavior), \"adaptive\" (encode only tabular-uniform payloads\nthat beat compact JSON by ToonMinSavingsPct), or \"always\"\n(benchmark/debug only — encodes every JSON-parseable block and can\nINCREASE token cost). Per-server override: ServerConfig.ToonOutput.\nResolved by ResolveToonOutput; hot-reloadable.","type":"string"},"top_k":{"description":"Deprecated: TopK is superseded by ToolsLimit and has no runtime effect. Kept for backward compatibility.","type":"integer"},"tray_endpoint":{"description":"Tray endpoint override (unix:// or npipe://)","type":"string"},"trusted_hosts":{"description":"TrustedHosts lists non-loopback Host header values accepted on loopback\nlisteners (GH #898). DNS-rebinding protection rejects requests whose Host\nheader is not a loopback address when mcpproxy listens on loopback; a\nreverse proxy (nginx → 127.0.0.1) forwarding the public domain in Host\ntrips it. Entries are hostnames, case-insensitive; an entry without a\nport matches any port, with a port it must match exactly; a leading dot\n(\".example.com\") is a subdomain wildcard. The single entry \"*\" disables\nHost and Origin validation entirely. The same list also validates the\nOrigin header when present (MCP spec DNS-rebinding defense). Empty\n(default) keeps full protection. Env override: MCPPROXY_TRUSTED_HOSTS\n(comma-separated).","items":{"type":"string"},"type":"array","uniqueItems":false},"trusted_proxies":{"description":"TrustedProxies lists the CIDRs or IP addresses whose X-Forwarded-For /\nX-Real-IP / X-Forwarded-Proto / X-Forwarded-Host headers are believed\n(Spec 107 FR-027). Empty (default) trusts nobody. Edition-neutral, live\n(hot-reloadable). Env override: MCPPROXY_TRUSTED_PROXIES (comma-separated).\nThe one reader is ForwardedHeaders; validation is validateTrustedProxies.","items":{"type":"string"},"type":"array","uniqueItems":false},"update_check":{"$ref":"#/components/schemas/config.UpdateCheckConfig"}},"type":"object"},"config.CustomPattern":{"properties":{"category":{"description":"Category (defaults to \"custom\")","type":"string"},"keywords":{"description":"Keywords to match (mutually exclusive with Regex)","items":{"type":"string"},"type":"array","uniqueItems":false},"name":{"description":"Unique identifier for this pattern","type":"string"},"regex":{"description":"Regex pattern (mutually exclusive with Keywords)","type":"string"},"severity":{"description":"Risk level: critical, high, medium, low","type":"string"}},"type":"object"},"config.DeepScanConfig":{"description":"DeepScan is the opt-in \"deep scan\" layer (Spec 077 US3). It subsumes the\ndeprecated top-level scanner_fetch_package_source / scanner_disable_no_new_privileges\nkeys (migrated on load) and gates the heavy Docker-based scanners + source\nextraction. Disabled by default (FR-006): only the deterministic in-process\nbaseline scanner runs. A deep-scan failure NEVER changes the baseline verdict\n(FR-007/FR-008).","properties":{"disable_no_new_privileges":{"description":"DisableNoNewPrivileges, when true, omits the ` + "`" + `--security-opt\nno-new-privileges` + "`" + ` flag from scanner container runs (snap-docker/AppArmor\nescape hatch). Absorbs the deprecated top-level\nscanner_disable_no_new_privileges. Default false.","type":"boolean"},"enabled":{"description":"Enabled is the master opt-in for the heavy layer (FR-006). Default false.","type":"boolean"},"fetch_package_source":{"description":"FetchPackageSource controls whether the scanner fetches the PUBLISHED\nsource of package-runner servers (npx/uvx) — without executing it — when\nno local source is available. Absorbs the deprecated top-level\nscanner_fetch_package_source. Default (nil) is ENABLED within deep scan.","type":"boolean"},"scanners":{"description":"Scanners optionally restricts which deep scanners may run under the\numbrella (by scanner id). Empty ⇒ all enabled deep scanners are eligible.","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"config.DockerIsolationConfig":{"description":"Docker isolation settings","properties":{"cpu_limit":{"description":"CPU limit for containers","type":"string"},"default_images":{"additionalProperties":{"type":"string"},"description":"Map of runtime type to Docker image","type":"object"},"enable_cache_volume":{"description":"Mount shared cache volumes for faster restarts (default: true)","type":"boolean"},"enabled":{"description":"Global enable/disable for Docker isolation (legacy; superseded by Mode)","type":"boolean"},"extra_args":{"description":"Additional docker run arguments","items":{"type":"string"},"type":"array","uniqueItems":false},"log_driver":{"description":"Docker log driver (default: json-file)","type":"string"},"log_max_files":{"description":"Maximum number of log files (default: 3)","type":"string"},"log_max_size":{"description":"Maximum size of log files (default: 100m)","type":"string"},"memory_limit":{"description":"Memory limit for containers","type":"string"},"mode":{"description":"Isolation mode: \"docker\" | \"sandbox\" | \"none\" (MCP-34.2). Unset per-server inherits the global mode; unset globally falls back to the legacy \"enabled\" flag (true ⇒ docker, false ⇒ none)","type":"string","x-enum-varnames":["IsolationModeDocker","IsolationModeSandbox","IsolationModeNone"]},"network_mode":{"description":"Docker network mode (default: bridge)","type":"string"},"registry":{"description":"Custom registry (defaults to docker.io)","type":"string"},"timeout":{"description":"Container startup timeout","type":"string"}},"type":"object"},"config.DockerRecoveryConfig":{"description":"Docker recovery settings","properties":{"enabled":{"description":"Enable Docker recovery monitoring (default: true)","type":"boolean"},"max_retries":{"description":"Maximum retry attempts (0 = unlimited)","type":"integer"},"notify_on_failure":{"description":"Show notification on recovery failure (default: true)","type":"boolean"},"notify_on_retry":{"description":"Show notification on each retry (default: false)","type":"boolean"},"notify_on_start":{"description":"Show notification when recovery starts (default: true)","type":"boolean"},"notify_on_success":{"description":"Show notification on successful recovery (default: true)","type":"boolean"},"persistent_state":{"description":"Save recovery state across restarts (default: true)","type":"boolean"}},"type":"object"},"config.FeatureFlags":{"description":"Deprecated: Features flags are unused and have no runtime effect. Kept for backward compatibility.","properties":{"enable_async_storage":{"type":"boolean"},"enable_caching":{"type":"boolean"},"enable_contract_tests":{"type":"boolean"},"enable_debug_logging":{"description":"Development features","type":"boolean"},"enable_docker_isolation":{"type":"boolean"},"enable_event_bus":{"type":"boolean"},"enable_health_checks":{"type":"boolean"},"enable_metrics":{"type":"boolean"},"enable_oauth":{"description":"Security features","type":"boolean"},"enable_observability":{"description":"Observability features","type":"boolean"},"enable_quarantine":{"type":"boolean"},"enable_runtime":{"description":"Runtime features","type":"boolean"},"enable_search":{"description":"Storage features","type":"boolean"},"enable_sse":{"type":"boolean"},"enable_tracing":{"type":"boolean"},"enable_tray":{"type":"boolean"},"enable_web_ui":{"description":"UI features","type":"boolean"}},"type":"object"},"config.IntentDeclarationConfig":{"description":"Intent declaration settings (Spec 018)","properties":{"strict_server_validation":{"description":"StrictServerValidation controls whether server annotation mismatches\ncause rejection (true) or just warnings (false).\nDefault: true (reject mismatches)","type":"boolean"}},"type":"object"},"config.IsolationConfig":{"description":"Per-server isolation settings","properties":{"enabled":{"description":"Enable Docker isolation for this server (nil = inherit global; legacy, superseded by Mode)","type":"boolean"},"extra_args":{"description":"Additional docker run arguments for this server","items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"description":"Custom Docker image (overrides default)","type":"string"},"log_driver":{"description":"Docker log driver override for this server","type":"string"},"log_max_files":{"description":"Maximum number of log files override","type":"string"},"log_max_size":{"description":"Maximum size of log files override","type":"string"},"mode":{"$ref":"#/components/schemas/config.IsolationMode"},"network_mode":{"description":"Custom network mode for this server","type":"string"},"working_dir":{"description":"Custom working directory in container","type":"string"}},"type":"object"},"config.IsolationMode":{"description":"Isolation mode: \"docker\" | \"sandbox\" | \"none\" (MCP-34.2). Unset per-server inherits the global mode; unset globally falls back to the legacy \"enabled\" flag (true ⇒ docker, false ⇒ none)","type":"string","x-enum-varnames":["IsolationModeDocker","IsolationModeSandbox","IsolationModeNone"]},"config.LogConfig":{"description":"Logging configuration","properties":{"compress":{"type":"boolean"},"enable_console":{"type":"boolean"},"enable_file":{"type":"boolean"},"filename":{"type":"string"},"json_format":{"type":"boolean"},"level":{"type":"string"},"log_dir":{"description":"Custom log directory","type":"string"},"max_age":{"description":"days","type":"integer"},"max_backups":{"description":"number of backup files","type":"integer"},"max_size":{"description":"MB","type":"integer"}},"type":"object"},"config.MetricsExporterConfig":{"description":"Metrics gates the Prometheus /metrics scrape endpoint (MCP-32). Disabled\nby default — operators opt in for k8s/enterprise deployments.","properties":{"enabled":{"description":"Enabled exposes /metrics on the existing HTTP listener when true.\nThe endpoint is admin-authenticated (SEC-07): scrapers must present the\nglobal API key, via X-API-Key or an Authorization: Bearer header.","type":"boolean"}},"type":"object"},"config.OAuthConfig":{"description":"OAuth configuration (keep even when empty to signal OAuth requirement)","properties":{"auth_server_metadata_url":{"type":"string"},"authorization_endpoint":{"description":"Spec 113-b: optional per-server discovery overrides. Each is an absolute\nhttps URL (http only on a loopback host) with no query, fragment or\nuserinfo; validated at write time only (ValidateOAuthEndpointOverrides).\nThe endpoint overrides rewrite the matching fields of the authorization\nserver metadata mcp-go reads; AuthServerMetadataURL replaces discovery.","type":"string"},"callback_base_url":{"type":"string"},"client_id":{"type":"string"},"client_secret":{"type":"string"},"extra_params":{"additionalProperties":{"type":"string"},"description":"Additional OAuth parameters (e.g., RFC 8707 resource)","type":"object"},"pkce_enabled":{"type":"boolean"},"redirect_uri":{"type":"string"},"refresh_replay_enabled":{"description":"Opt in only when token_endpoint supports idempotent refresh replay for at least 30 seconds.","type":"boolean"},"registration_endpoint":{"type":"string"},"scopes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"token_endpoint":{"type":"string"}},"type":"object"},"config.ObservabilityConfig":{"description":"Observability settings (Spec 069): usage aggregate cache/persistence cadence.","properties":{"metrics":{"$ref":"#/components/schemas/config.MetricsExporterConfig"},"tracing":{"$ref":"#/components/schemas/config.TracingExporterConfig"},"usage_cache_ttl":{"description":"UsageCacheTTL bounds the freshness of the usage endpoint's read cache for\nwide windows (FR-005). Default 5s.","type":"string"},"usage_persist_interval":{"description":"UsagePersistInterval is how often the actor-owned usage aggregate snapshot\nis flushed to storage. Default 30s.","type":"string"}},"type":"object"},"config.OutputSanitisationConfig":{"description":"Output sanitisation settings (Spec 054 Track B)","properties":{"max_redactions":{"description":"cap on redactions per response; default 100","type":"integer"},"response_action":{"description":"\"spotlight\" | \"redact\" | \"block\"; default \"spotlight\"","type":"string"},"spotlight_untrusted":{"description":"wrap untrusted output in spotlight markers; default true","type":"boolean"},"strip_classes":{"description":"classes to strip: ansi/c0c1/bidi/zero_width","items":{"type":"string"},"type":"array","uniqueItems":false},"strip_control_chars":{"description":"strip control-character classes; default false","type":"boolean"}},"type":"object"},"config.OutputValidationConfig":{"description":"Output-schema validation settings (Spec 056)","properties":{"max_bytes":{"description":"structured payload byte cap; default 5\u003c\u003c20","type":"integer"},"max_depth":{"description":"nesting depth cap; default 64","type":"integer"},"missing_structured_content":{"description":"\"allow\" | \"block\"; default \"allow\"","type":"string"},"mode":{"description":"\"off\" | \"warn\" | \"strict\"; default \"warn\"","type":"string"}},"type":"object"},"config.ProfileConfig":{"properties":{"code_execution":{"description":"CodeExecution: nil = inherit the global enable_code_execution gate;\nnon-nil narrows it (a profile can only narrow, never widen, FR-006).","type":"boolean"},"description":{"description":"\u003c= 500 chars (FR-001)","type":"string"},"management_tools":{"description":"ManagementTools: nil = legacy/inherit (FR-016); non-nil sets the\nprofile-level visibility of upstream_servers/quarantine_security.","type":"boolean"},"max_tier":{"description":"MaxTier caps the tier a tool may run at under this profile: \"\" (no\ncap) | \"read\" | \"write\" | \"destructive\" (FR-001).","type":"string"},"name":{"description":"slug (Spec 057 rules unchanged)","type":"string"},"servers":{"description":"references to mcpServers[].name","items":{"type":"string"},"type":"array","uniqueItems":false},"switchable_to":{"description":"SwitchableTo is the list of profile names a session under this\nprofile may ` + "`" + `set_profile` + "`" + ` into (FR-022). nil = legacy/none (research\nD6); a non-nil EMPTY list is an explicit \"none\" and must round-trip as\n` + "`" + `[]` + "`" + `, never be dropped by omitempty — hence the pointer (see the\nMarshalJSON note below, and profiles_v3_test.go's switchable_to round\ntrip case).","items":{"type":"string"},"type":"array","uniqueItems":false},"title":{"description":"display only, \u003c= 80 chars (FR-001)","type":"string"},"tools":{"$ref":"#/components/schemas/config.ProfileToolRules"},"unannotated":{"description":"Unannotated is this profile's handling of a tool whose effective\nannotations carry no tier hint: \"\" (unset, see EffectiveUnannotated) |\n\"deny\" | \"as_write\" | \"as_read\" (FR-001, FR-003).","type":"string"}},"type":"object"},"config.ProfileToolRules":{"description":"Tools holds the allow/deny/classify rule set (FR-001, FR-004, FR-005).","properties":{"allow":{"items":{"type":"string"},"type":"array","uniqueItems":false},"classify":{"additionalProperties":{"type":"string"},"type":"object"},"deny":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"config.RegistryEntry":{"properties":{"count":{"description":"number or string","type":"string"},"description":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"},"protocol":{"type":"string"},"provenance":{"description":"Provenance is the trust tag for this registry (MCP-866):\nRegistryProvenanceOfficial for built-in defaults, RegistryProvenanceCustom\nfor user-added registries. It is authoritatively (re)computed by the\nregistries merge from whether the ID is a shipped default — a user cannot\nclaim \"official\" by writing it into their config.","type":"string"},"requires_key":{"description":"RequiresKey marks a registry that needs an API key to be queried. When\ntrue and no key is configured, the registry is skipped/marked unavailable\nrather than failing the whole search (FR-008).","type":"boolean"},"servers_url":{"type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"url":{"type":"string"}},"type":"object"},"config.SecurityConfig":{"description":"Security scanner settings (Spec 039)","properties":{"auto_baseline_scan":{"description":"AutoBaselineScan is the kill-switch for the AUTOMATIC, informational\nPass-1 baseline scan: the free in-process TPA scan mcpproxy runs for every\nnewly admitted server (any trust mode) and, once per installation, over\npre-existing servers that have never been scanned.\n\nInformational ONLY: the resulting verdict populates the security badge and\nthe scan summary, and NEVER gates quarantine or approval. The\ntrust_mode:\"scan\" admission gate is a separate path and is unaffected by\nthis flag.\n\nDefault (nil) is ENABLED. Set to false to suppress every automatic scan\n(manual scans keep working). Env override: MCPPROXY_AUTO_BASELINE_SCAN,\nwhich wins over this field on every path.","type":"boolean"},"auto_rescan_on_change":{"description":"AutoRescanOnChange is the finer switch for the automatic, informational\nrescan that follows a tool-definition hash change: the in-process TPA scan\nof the changed (or newly pending) tool, recorded as hold evidence, and a\ndebounced informational server rescan that brings the review screen's scan\ncoverage back to \"current\".\n\nEvidence and freshness ONLY: this switch approves nothing. Under \"manual\"\nevery change is held for review whatever the verdict (RT-02); under\n\"scan\" the gate's own synchronous scan approves a clean change that\npasses the spec 120 structural gate (spec 119 FR-004), and this switch\ndoes not affect that path. Runs in every trust mode except \"auto\".\n\nDefault (nil) is ENABLED. It only takes effect while auto_baseline_scan is\nalso enabled, so a user can keep the admission scan and turn off per-change\nrescans with this key alone. Env override: MCPPROXY_AUTO_RESCAN_ON_CHANGE,\nwhich wins over this field on every path.","type":"boolean"},"deep_scan":{"$ref":"#/components/schemas/config.DeepScanConfig"},"integrity_check_interval":{"type":"string"},"integrity_check_on_restart":{"type":"boolean"},"require_signed_bundle":{"description":"RequireSignedBundle makes the detached signature sidecar mandatory for\nfile-dropped bundles (FR-007). Default false (maintainer decision D2):\nexisting unsigned drops keep working, but an unsigned external bundle\nalways runs with DEGRADED coverage (scan-mode auto-approval suspended).","type":"boolean"},"runtime_read_only":{"type":"boolean"},"runtime_tmpfs_size":{"type":"string"},"scan_timeout_default":{"type":"string"},"scanner_disable_no_new_privileges":{"description":"Deprecated (Spec 077 US3): migrated on load into DeepScan.DisableNoNewPrivileges\n(see migrateDeepScanConfig). Retained only so existing configs that still carry\nthe top-level key parse; consumers MUST read the effective value via\nSecurityConfig.IsDisableNoNewPrivileges. Cleared after migration.\n\nScannerDisableNoNewPrivileges, when true, omits the\n` + "`" + `--security-opt no-new-privileges` + "`" + ` flag from scanner container runs.\n\nBackground: snap-installed Docker on Ubuntu confines dockerd under the\n` + "`" + `snap.docker.dockerd` + "`" + ` AppArmor profile. When runc tries to transition\nthe container into the inner ` + "`" + `docker-default` + "`" + ` profile to exec the\nentrypoint, AppArmor refuses the transition because NO_NEW_PRIVS\nforbids privilege/profile changes on exec — the result is EPERM\n(\"operation not permitted\") and every scanner fails immediately.\n\nSet this to true ONLY on hosts hitting that incompatibility. Scanner\ncontainers still run with read-only rootfs, tmpfs /tmp, no-network by\ndefault, and read-only source mounts, so the marginal isolation loss\nis small. The preferred fix remains replacing snap docker with a\ndistro-packaged docker.","type":"boolean"},"scanner_fetch_package_source":{"description":"Deprecated (Spec 077 US3): migrated on load into DeepScan.FetchPackageSource\n(see migrateDeepScanConfig). Retained only so existing configs that still carry\nthe top-level key parse; consumers MUST read the effective value via\nSecurityConfig.EffectiveFetchPackageSource. Cleared after migration.\n\nScannerFetchPackageSource controls whether the scanner fetches the\nPUBLISHED source of package-runner servers (npx/uvx) — without executing\nit — when no local source is available (no Docker container, no local\npackage cache, no working_dir). This is the primary quarantine/scan\ntarget: a quarantined-on-add server is never run locally, so without this\nthe scan degrades to tool-definitions-only (no real source-level\nanalysis). See MCP-2206.\n\nFetching uses ` + "`" + `npm pack --ignore-scripts` + "`" + ` (npm) and ` + "`" + `uv pip download` + "`" + ` /\n` + "`" + `pip download` + "`" + ` with ` + "`" + `--only-binary=:all:` + "`" + ` (Python), which only download +\nunpack archives and NEVER run install, build, or setup.py — a scanner must\nnot execute the untrusted code it is scanning. The Python\n` + "`" + `--only-binary=:all:` + "`" + ` flag is required because downloading an sdist would\ninvoke its build backend (setup.py); packages with no wheel fall back to\ntool-definitions-only instead. Extraction is hardened against path\ntraversal and decompression bombs.\n\nDefault (nil) is ENABLED. Set to false on air-gapped deployments to\nforbid the scanner's network egress; such servers then fall back to the\ntool-definitions-only scan with no regression.","type":"boolean"},"scanner_registry_url":{"type":"string"},"tpa_active_root":{"description":"TPAActiveRoot declares which signing authority's bundles may activate\n(FR-004b): \"publisher\" (default, the keys embedded in this binary) or\n\"operator\" (TPAOperatorSigners). A bundle verified by the other root is\nrefused as authority_not_active, so whoever can write the bundle path\ncannot choose the authority.","type":"string"},"tpa_bundle_path":{"description":"TPABundlePath is the filesystem path to the tpa-db scanner-bundle.json\nthe offline TPA scanner runs (spec 086 FR-019: the signature-DB location\nMUST be configuration-driven, not hardcoded). Empty (the default) runs the\ncorpus embedded in this build.\n\nEnv override: MCPPROXY_TPA_BUNDLE_PATH. Hot-reloadable — the path is\nre-read on every config.reloaded event via\nscanner.Service.ApplySecurityConfig, so a corpus refresh needs no restart.\nA configured bundle that fails to read/parse/version-check/compile is\nREFUSED and the previously active corpus stays live (fail-closed, never\nfail-empty); the reason is logged and surfaced in the security overview's\nsignature_bundle.load_error.","type":"string"},"tpa_fetch_enabled":{"description":"TPAFetchEnabled opts in to the network fetch leg. Default false; the\nenvironment override is MCPPROXY_TPA_FETCH_ENABLED (EnvTPAFetchEnabled).","type":"boolean"},"tpa_fetch_url":{"description":"TPAFetchURL is the channel URL: a GitHub Releases \"latest\" API URL or a\ndirect bundle URL. Empty (the default) means the fetch leg is off; no URL\nis compiled into the binary.","type":"string"},"tpa_operator_baseline":{"description":"TPAOperatorBaseline seeds the operator authority's anti-downgrade\nwatermark (FR-009b): an operator-signed bundle must carry a sequence\nABOVE it (a rollback target may sit at it). It survives a data-directory\nwipe because it lives here. Absent means the operator authority has no\nanti-downgrade floor and an active operator bundle runs DEGRADED.","type":"integer"},"tpa_operator_epoch":{"description":"TPAOperatorEpoch is the operator authority's trust epoch (FR-005a).\nBumping it (after an operator key compromise) re-baselines the operator\nwatermark and retires prior-epoch pins. Absent means 0.","type":"integer"},"tpa_operator_signers":{"description":"TPAOperatorSigners lists operator Ed25519 public keys, each the standard\nbase64 encoding of the 32 raw key bytes (FR-004). Their key ids are the\nlowercase-hex SHA-256 of those bytes. Malformed or duplicate entries are\nrejected on write and dropped (with a log) on load.","items":{"type":"string"},"type":"array","uniqueItems":false},"tpa_refresh_interval":{"description":"TPARefreshInterval is the cadence of the refresh cycle (the network-free\nfile leg, then the optional fetch leg). Absent or 0 means 24h; the runtime\nclamps to at least 1h. There is no refresh-enable key: the file leg is\nidempotent and always on.","type":"string"},"tpa_stale_after_days":{"description":"TPAStaleAfterDays is the age in days after which the active bundle reads\nas stale. Absent means 30; an explicit 0 disables the stale flag and the\ndoctor stale warning.","type":"integer"}},"type":"object"},"config.SensitiveDataDetectionConfig":{"description":"Sensitive data detection settings (Spec 026)","properties":{"categories":{"additionalProperties":{"type":"boolean"},"description":"Enable/disable specific detection categories","type":"object"},"custom_patterns":{"description":"User-defined detection patterns","items":{"$ref":"#/components/schemas/config.CustomPattern"},"type":"array","uniqueItems":false},"enabled":{"description":"Enable sensitive data detection (default: true)","type":"boolean"},"entropy_threshold":{"description":"Shannon entropy threshold for high-entropy detection (default: 4.5)","type":"number"},"max_payload_size_kb":{"description":"Max size to scan before truncating (default: 1024)","type":"integer"},"scan_requests":{"description":"Scan tool call arguments (default: true)","type":"boolean"},"scan_responses":{"description":"Scan tool responses (default: true)","type":"boolean"},"sensitive_keywords":{"description":"Keywords to flag","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"config.ServerConfig":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges is the per-server intent to auto-approve tool\nchanges/additions (disabling per-server rug-pull protection). Supersedes\nskip_quarantine. MCP-2930 only ACCEPTS, persists, and migrates this flag — it\nis NOT yet consulted at runtime; auto-approval is still governed by\nSkipQuarantine until the trust-baseline behavior change (MCP-2931) migrates the\nruntime consumers onto it.\nTri-state pointer (mirrors QuarantineEnabled): nil = unset (inherit/migrate\nfrom legacy skip_quarantine), explicit true/false = honored as-is so an\nexplicit auto_approve_tool_changes:false overrides a legacy skip_quarantine:true.\nRead via IsAutoApproveToolChanges().","type":"boolean"},"command":{"type":"string"},"created":{"type":"string"},"disabled_tools":{"description":"Denylist: these tools are hidden; mutually exclusive with enabled_tools","items":{"type":"string"},"type":"array","uniqueItems":false},"enabled":{"type":"boolean"},"enabled_tools":{"description":"Allowlist: only these tools are exposed; mutually exclusive with disabled_tools","items":{"type":"string"},"type":"array","uniqueItems":false},"env":{"additionalProperties":{"type":"string"},"type":"object"},"expose_prompts":{"description":"ExposePrompts overrides whether this server's advertised MCP prompts are\naggregated into mcpproxy's prompts/list. nil (default) inherits the\ndefault-aggregate behavior (included if the server advertises\nCapabilities.Prompts); false excludes it regardless of capability.","type":"boolean"},"expose_skills":{"description":"ExposeSkills overrides whether this server's skills (MCP skills\nextension) are read when Config.EnableSkills is on. nil (default)\ninherits (included if the server supports skills); false excludes it.","type":"boolean"},"forward_headers":{"description":"ForwardHeaders lists inbound MCP-client header NAMES (never values) that\nare copied into this server's upstream tools/call requests (Spec 112).\nExact names, case-insensitive, at most 32, no wildcards. Empty forwards\nnothing. Only HTTP-based transports (http, streamable-http) forward; the\ndeny list (Authorization, Host, hop-by-hop, ...) is enforced at runtime\nregardless of what is configured here.","items":{"type":"string"},"type":"array","uniqueItems":false},"headers":{"additionalProperties":{"type":"string"},"description":"For HTTP servers","type":"object"},"health_check_interval":{"description":"Per-server discovery \u0026 health-check overrides (spec 074). Same *Duration\ntri-state as the global keys: nil = inherit the global value (or default),\npointer to 0s = disabled for this server, positive = that interval.\nHealthCheckInterval is fully wired into the per-server health loop;\nToolDiscoveryInterval is accepted/validated and round-trips for\nforward-compat, but the periodic index sweep is governed by the global\ncadence in this iteration (see spec 074 plan §C).","type":"string"},"init_timeout":{"description":"InitTimeout overrides the global init_timeout for this server's MCP\n` + "`" + `initialize` + "`" + ` handshake deadline (MCP-3322 / GH #760). *Duration tri-state:\nnil = inherit the global value (or 30s default), positive = that deadline.\nResolved by Config.ResolveInitTimeout; validated to {0} ∪ [1s, 30m]. Raise\nthis for upstreams that do legitimate first-run warmup (e.g. caching many\nchannels/users) before responding to ` + "`" + `initialize` + "`" + `.","type":"string"},"isolation":{"$ref":"#/components/schemas/config.IsolationConfig"},"launcher_wait_timeout":{"description":"LauncherWaitTimeout caps how long mcpproxy will wait for a locally-launched\nHTTP/SSE upstream's URL to become reachable after Spawn(). Only consulted\nwhen the server is configured with both Command and an HTTP/SSE URL — i.e.,\nmcpproxy starts the process AND connects via network. Stdio servers ignore\nthis field. Zero or unset → 30s default.","type":"string"},"max_concurrent_requests":{"description":"Per-server concurrency overrides — scope (c) of FR-020 (spec 093, #955).\nTri-state per setting, exactly like HealthCheckInterval: absent = inherit\nthe per-server default set (server_concurrency_defaults), explicit 0 =\ndisable that setting for this server (0 max = no per-server limiter at\nall; 0 queue_size = no pending capacity, shed immediately at the cap),\npositive = override. The global aggregate limiter is never inherited from\nhere — it applies on top, so effective concurrency is min(per-server,\nglobal). Resolved by Config.ResolveServerConcurrency.","type":"integer"},"name":{"type":"string"},"oauth":{"$ref":"#/components/schemas/config.OAuthConfig"},"protocol":{"description":"stdio, http, sse, streamable-http, auto","type":"string"},"quarantined":{"description":"Security quarantine status","type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_on_use":{"description":"Attempt reconnection when a tool call targets a disconnected server","type":"boolean"},"shared":{"description":"Server edition: shared with all users","type":"boolean"},"skip_quarantine":{"description":"SkipQuarantine is DEPRECATED (MCP-2930): use AutoApproveToolChanges instead.\nKept for back-compat parsing; on config load a legacy skip_quarantine:true is\nmigrated to auto_approve_tool_changes:true only when the new field is unset\n(see normalizeServerQuarantineFlags).","type":"boolean"},"source_registry_id":{"description":"SourceRegistryID records which registry this server was added from (empty\nfor manually-configured servers). MCP-866: surfaced in the approval /\nquarantine view so a reviewer can see a server's origin.","type":"string"},"source_registry_provenance":{"description":"SourceRegistryProvenance records the source registry's provenance at add\ntime (RegistryProvenanceOfficial / RegistryProvenanceCustom). It is purely\ninformational (MCP-1072) — surfaced so a reviewer can see a server's origin\n— and no longer gates quarantine or skip_quarantine.","type":"string"},"tool_argument_error_mode":{"description":"ToolArgumentErrorMode stores the per-upstream argument-error policy.\nEmpty and detailed retain detailed errors; redacted opts into redaction.\nUpdates omit/keep an empty value; detailed explicitly resets the policy.","type":"string"},"tool_discovery_interval":{"type":"string"},"toon_output":{"description":"ToonOutput overrides the global toon_output mode for this server's\ntools (spec 084, FR-001). Plain string, not a pointer: \"\"/absent =\ninherit the global value; \"off\"|\"adaptive\"|\"always\" = override (\"off\"\nis the explicit force-off). Resolved by Config.ResolveToonOutput.","type":"string"},"trust_mode":{"description":"TrustMode is the per-server trust tier: auto|scan|manual. Supersedes\nauto_approve_tool_changes (spec 086). An empty value is derived from the\nlegacy fields at load via normalizeServerQuarantineFlags; the single\nresolution point is EffectiveTrustMode(), which treats an empty value as\nscan (DefaultTrustMode, spec 119) and an unrecognized value as manual\n(fail closed). Read via\nEffectiveTrustMode(), never the raw string.","type":"string"},"updated":{"type":"string"},"url":{"type":"string"},"working_dir":{"description":"Working directory for stdio servers","type":"string"}},"type":"object"},"config.TLSConfig":{"description":"TLS configuration","properties":{"cert_file":{"description":"CertFile is the absolute path of an operator-provided server certificate\n(PEM, leaf first), served instead of a generated one. Needs KeyFile.","type":"string"},"certs_dir":{"description":"Directory for certificates","type":"string"},"enabled":{"description":"Enable HTTPS","type":"boolean"},"extra_sans":{"description":"ExtraSANs are DNS names and IP addresses added to the generated server\ncertificate, which is signed by the same local CA. Not used with CertFile.","items":{"type":"string"},"type":"array","uniqueItems":false},"hsts":{"description":"Enable HTTP Strict Transport Security","type":"boolean"},"key_file":{"description":"KeyFile is the absolute path of the private key for CertFile (PEM).","type":"string"},"require_client_cert":{"description":"Enable mTLS","type":"boolean"}},"type":"object"},"config.TelemetryConfig":{"description":"Telemetry settings (Spec 036)","properties":{"anonymous_id":{"description":"Auto-generated UUIDv4","type":"string"},"anonymous_id_created_at":{"description":"Spec 042 (Tier 2) additions — all default-zero, all backwards-compatible.","type":"string"},"enabled":{"description":"Default: true (opt-out)","type":"boolean"},"endpoint":{"description":"Override for testing","type":"string"},"last_reported_version":{"description":"Upgrade funnel","type":"string"},"last_startup_outcome":{"description":"success|port_conflict|db_locked|...","type":"string"},"notice_shown":{"description":"First-run notice flag","type":"boolean"}},"type":"object"},"config.TokenizerConfig":{"description":"Tokenizer configuration for token counting","properties":{"default_model":{"description":"Default model for tokenization (e.g., \"gpt-4\")","type":"string"},"enabled":{"description":"Enable token counting","type":"boolean"},"encoding":{"description":"Default encoding (e.g., \"cl100k_base\")","type":"string"}},"type":"object"},"config.TracingExporterConfig":{"description":"Tracing gates the OpenTelemetry OTLP trace exporter (MCP-32). Disabled by\ndefault.","properties":{"enabled":{"description":"Enabled turns on OTLP trace export for tool calls and upstream hops.","type":"boolean"},"endpoint":{"description":"Endpoint is the collector address as host:port (no scheme), e.g.\n\"localhost:4318\" for http or \"localhost:4317\" for grpc.","type":"string"},"protocol":{"description":"Protocol selects the OTLP transport: \"http\" or \"grpc\".","type":"string"},"sample_rate":{"description":"SampleRate is the head-based trace sampling ratio in [0,1]. Default 0.1.\nOmit the key for the 0.1 default; set it to 0 to sample nothing.","type":"number"}},"type":"object"},"config.UpdateCheckConfig":{"description":"Update-check settings (Spec 079 FR-012): config-file control of the\nbackground upgrade-awareness checker (internal/updatecheck). nil =\nenabled on the stable channel (existing default behavior). The existing\nenvironment switches keep working and WIN over these keys (FR-014):\nMCPPROXY_DISABLE_AUTO_UPDATE=true force-disables even when\nenabled=true, and MCPPROXY_ALLOW_PRERELEASE_UPDATES=true force-selects\nthe rc channel even when channel=stable.","properties":{"channel":{"description":"Channel selects which releases are offered as updates: \"stable\"\n(default; prereleases never offered) or \"rc\" (prereleases included).\nEmpty resolves to stable. Validated in ValidateDetailed.\n\nNOTE: for a RELEASED build the running binary's own version is\nauthoritative and overrides this field — a stable build is never\noffered an RC (even with channel=rc), and an RC build always tracks the\nrc channel. This field only takes effect on dev/unstamped builds. See\ninternal/updatecheck.Checker.IncludePrereleases.","type":"string"},"enabled":{"description":"Enabled gates all update checking. Tri-state: nil/absent = enabled\n(default true, matching pre-079 behavior). When false, no network\ncheck is performed and no upgrade nudge appears on any surface\n(FR-015) — /api/v1/info omits the update object entirely.","type":"boolean"}},"type":"object"},"configimport.FailedServer":{"properties":{"details":{"type":"string"},"error":{"type":"string"},"name":{"type":"string"}},"type":"object"},"configimport.ImportSummary":{"properties":{"failed":{"type":"integer"},"imported":{"type":"integer"},"skipped":{"type":"integer"},"total":{"type":"integer"}},"type":"object"},"configimport.SkippedServer":{"properties":{"name":{"type":"string"},"reason":{"description":"\"already_exists\", \"filtered_out\", \"invalid_name\", \"self_reference\"","type":"string"}},"type":"object"},"connect.ConnectResult":{"description":"The full result; its action mirrors the top-level one","properties":{"action":{"description":"\"created\", \"updated\", \"already_exists\", \"removed\", \"not_found\"","type":"string"},"backup_path":{"type":"string"},"client":{"type":"string"},"config_path":{"type":"string"},"credential":{"description":"Credential is the masked client credential the write embedded\n(` + "`" + `mcp_cli_••••` + "`" + `); the real secret is never returned (FR-024). Empty for a\nkeyless entry, a disconnect and every refusal.","type":"string"},"credential_revoke_error":{"description":"CredentialRevokeError is set when a disconnect removed the entry but\nrevoking the client credential failed. The disconnect still succeeded;\nthe credential is still active and ` + "`" + `mcpproxy client forget \u003cid\u003e` + "`" + `\nretries the revoke.","type":"string"},"credential_revoked":{"description":"CredentialRevoked names the credential that was revoked: by an undo,\nbecause the restored config no longer holds it (plan D16), or by a\ndisconnect, which cuts the client off (a later undo of that disconnect\ndoes not bring the credential back).","type":"string"},"display_path":{"description":"DisplayPath is ConfigPath with the home directory shortened to \"~\"\n(FR-037). Populated for every result whose ConfigPath is known.","type":"string"},"keyless":{"description":"Keyless is true when the entry was written with no credential.","type":"boolean"},"message":{"type":"string"},"mode":{"type":"string"},"profile":{"description":"Profile and Mode are the binding of the credential this write minted or\nkept. Profile \"\" means the built-in All servers scope.","type":"string"},"reload_hint":{"description":"ReloadHint is this client's instruction for making the write take\neffect (FR-037/FR-042), e.g. \"Restart Cursor to load MCPProxy\". Empty\nfor an unknown client.","type":"string"},"rotation":{"description":"Rotation is \"finalized\" when the write replaced an active credential's\nsecret (staged rotation, FR-021a), empty otherwise.","type":"string"},"server_name":{"type":"string"},"success":{"type":"boolean"},"token_name":{"description":"TokenName is the client credential's token name (` + "`" + `client-\u003cid\u003e` + "`" + `).","type":"string"}},"type":"object"},"contracts.APIResponse":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.ActivityDetailResponse":{"properties":{"activity":{"$ref":"#/components/schemas/contracts.ActivityRecord"}},"type":"object"},"contracts.ActivityListResponse":{"properties":{"activities":{"items":{"$ref":"#/components/schemas/contracts.ActivityRecord"},"type":"array","uniqueItems":false},"limit":{"type":"integer"},"offset":{"type":"integer"},"total":{"type":"integer"}},"type":"object"},"contracts.ActivityPerServer":{"properties":{"calls":{"description":"Calls counted per storage.CountsAsCall","type":"integer"},"errors":{"description":"Of those calls, how many failed","type":"integer"},"last_call_at":{"description":"LastCallAt is RFC3339, or \"\" if the server had no call in the period\n(PerServer only lists servers that did, so this is always set).","type":"string"},"name":{"description":"Server name","type":"string"}},"type":"object"},"contracts.ActivityRecord":{"description":"Activity is the stored row; absent on a session_start or session_end\nrow.","properties":{"agent_name":{"description":"Agent token name when auth_type is \"agent\"","type":"string"},"arguments":{"description":"Tool call arguments","type":"object"},"auth_type":{"description":"\"admin\", \"agent\", \"user\" or \"admin_user\"; empty without an auth context or on another caller's row for a scoped caller","type":"string"},"block_reason":{"description":"Typed cause of a profile policy refusal","type":"string"},"client_id":{"description":"Client id from the client-credential binding","type":"string"},"client_name":{"description":"Self-reported clientInfo.name (advisory)","type":"string"},"detection_types":{"description":"List of detection types found","items":{"type":"string"},"type":"array","uniqueItems":false},"duration_ms":{"description":"Execution duration in milliseconds","type":"integer"},"error_class":{"description":"Call-error taxonomy (Spec 113-c FR-045): what failed and whose fault it\nis. Absent on success and on records written before Spec 113.","type":"string"},"error_message":{"description":"Error details if status is \"error\"","type":"string"},"fault_domain":{"description":"upstream|proxy|client","type":"string"},"has_sensitive_data":{"description":"Sensitive data detection fields (Spec 026)","type":"boolean"},"id":{"description":"Unique identifier (ULID format)","type":"string"},"max_severity":{"description":"Highest severity level detected (critical, high, medium, low)","type":"string"},"metadata":{"description":"Additional context-specific data","type":"object"},"parent_id":{"description":"Correlation id of the parent call (the code_execution whose sandbox issued this sub-call)","type":"string"},"profile":{"description":"Scope attribution (Spec 108 FR-029): the profile, client and token in\neffect when the call ran. Stamped at write time, never rewritten. For a\nscoped (non-admin) caller the profile/profile_source/client_id/token_name\nof a row it did not make are blanked (binding disclosure is admin-only);\nclient_name is self-reported and stays. Absent on records written before\nSpec 108 and on records with no MCP/REST request context.","type":"string"},"profile_source":{"description":"pin|binding|url|session|anonymous|none","type":"string"},"request_bytes":{"description":"Byte sizes measured pre-truncation, mirroring storage.ActivityRecord\n(Spec 069 A1). They are the only cost signal a bodies-off export carries:\nwith payloads suppressed there is no text left to measure, so a consumer\naccounting for a record it cannot read has nothing else to go on. They are\nbyte LENGTHS, not token counts — the basis for an explicit estimate, never\na measured figure (spec 103, contracts/replay-input.md).\n\nZero means UNKNOWN, not free: legacy records predate the measurement and\ncode-execution sub-calls record both as zero. Hence omitempty — an absent\nkey tells a consumer to fall to exclusion accounting, whereas a present\nzero would read as a costless call and silently understate the workload.","type":"integer"},"request_id":{"description":"HTTP request ID for correlation","type":"string"},"response":{"description":"Tool response (potentially truncated)","type":"string"},"response_bytes":{"description":"Raw upstream response size in bytes before truncation","type":"integer"},"response_truncated":{"description":"True if response was truncated","type":"boolean"},"server_name":{"description":"Name of upstream MCP server","type":"string"},"session_id":{"description":"MCP transport session ID (regenerated on every reconnect)","type":"string"},"source":{"$ref":"#/components/schemas/contracts.ActivitySource"},"status":{"description":"Result status: \"success\", \"error\", \"blocked\", \"rejected\"","type":"string"},"timestamp":{"description":"When activity occurred","type":"string"},"token_name":{"description":"Agent/client token name","type":"string"},"tool_name":{"description":"Name of tool called","type":"string"},"type":{"$ref":"#/components/schemas/contracts.ActivityType"},"upstream_http_status":{"description":"Upstream HTTP status when known","type":"integer"},"work_session_id":{"description":"Spec 082: one client, one project, across reconnects","type":"string"}},"type":"object"},"contracts.ActivityRetentionReport":{"description":"ActivityRetention (Spec 124 FR-035) reports whether the activity caps\nhold the whole work-session retention window. Administrators only.","properties":{"cause":{"description":"Cause is age_cap, record_cap or size_cap.","type":"string"},"observed_at":{"description":"ObservedAt is when the shortfall was last observed.","type":"string"},"oldest_complete_session_at":{"description":"OldestCompleteSessionAt is the start of the oldest session that still\nhas all of its rows: complete history reaches back to here.","type":"string"},"raise":{"description":"Raise names the settings to raise for the cause.","items":{"type":"string"},"type":"array","uniqueItems":false},"shortfall":{"description":"Shortfall is true when a work session inside the window lost rows\nbecause a cap was reached, and a full window has not passed since.","type":"boolean"},"window_days":{"description":"WindowDays is the work-session retention window.","type":"integer"}},"type":"object"},"contracts.ActivitySource":{"description":"How activity was triggered: \"mcp\", \"cli\", \"api\"","type":"string","x-enum-varnames":["ActivitySourceMCP","ActivitySourceCLI","ActivitySourceAPI"]},"contracts.ActivitySummaryResponse":{"properties":{"blocked_count":{"description":"Count of blocked activities","type":"integer"},"call_count":{"description":"CallCount is how many of those records are CALLS THE USER MADE, as\ndefined once in storage.CountsAsCall and shared with the usage aggregate\nbehind the Usage tab (audit finding F1, #1046). TotalCount answers \"how\nmany rows does the Activity Log have\"; CallCount answers \"how many calls\nwere there\". They are different questions — quarantine auto-approvals,\nsystem start, security scans and management chatter are events, not calls\n— and printing either one under the other's label is how the same instance\ncame to report 51 calls on one screen and 19 on another.","type":"integer"},"call_error_count":{"description":"CallErrorCount is the failures within CallCount, so an error RATE computed\nfrom this response has one denominator. It is not ErrorCount: a policy\nblock is a failed call but carries status \"blocked\", and a shed call is an\nerror in neither sense because it never ran.","type":"integer"},"end_time":{"description":"End of the period (RFC3339)","type":"string"},"error_count":{"description":"Count of error activities","type":"integer"},"other_count":{"description":"OtherCount is every record whose status is outside the four-value\nvocabulary above, so that\n\n\tsuccess + error + blocked + rejected + other == total\n\nholds by construction. The status field is a CLOSED vocabulary for tool\ncalls, but the activity log is wider than tool calls: a quarantine change\nstores its ACTION there (\"approved\", \"auto_approved\"), a policy decision\nstores its DECISION (\"allow\"). Those rows were counted in the total and in\nnone of the four buckets, so the Activity Log's own status tiles summed to\nless than the denominator printed beside them — 15+4+0+0 under a \"42\"\n(audit finding F2, #1046). The residual now has a name and a tile.","type":"integer"},"per_server":{"description":"PerServer covers EVERY server with at least one call in the period\n(unlike TopServers, which is capped at 5 and carries no error counts).\nSpec 109 FR-013: the server-card stats line and the macOS Servers rows\nread this — one ` + "`" + `GET /activity/summary` + "`" + ` response per page load — rather\nthan issuing a per-server activity query each. Computed in the same\ncounting pass as the totals above, from the same CountsAsCall/\nIsManagementBuiltin definitions TopServers already uses.","items":{"$ref":"#/components/schemas/contracts.ActivityPerServer"},"type":"array","uniqueItems":false},"period":{"description":"Time period (1h, 24h, 7d, 30d)","type":"string"},"rejected_count":{"description":"RejectedCount is the number of calls shed by a concurrency limiter, or\nrefused because an agent token was over its call budget, before they\nreached an upstream (spec 093, issue #1699). Counted separately from\nerrors: it is proxy backpressure, not an upstream fault, and it is the\nsignal an operator right-sizes max_concurrent_requests and the rate\nlimits against.","type":"integer"},"start_time":{"description":"Start of the period (RFC3339)","type":"string"},"success_count":{"description":"Count of successful activities","type":"integer"},"top_servers":{"description":"Top servers by activity count","items":{"$ref":"#/components/schemas/contracts.ActivityTopServer"},"type":"array","uniqueItems":false},"top_tools":{"description":"Top tools by activity count","items":{"$ref":"#/components/schemas/contracts.ActivityTopTool"},"type":"array","uniqueItems":false},"total_count":{"description":"Total activity count","type":"integer"}},"type":"object"},"contracts.ActivityTopServer":{"properties":{"count":{"description":"Activity count","type":"integer"},"name":{"description":"Server name","type":"string"}},"type":"object"},"contracts.ActivityTopTool":{"properties":{"count":{"description":"Activity count","type":"integer"},"server":{"description":"Server name","type":"string"},"tool":{"description":"Tool name","type":"string"}},"type":"object"},"contracts.ActivityType":{"description":"Type of activity","type":"string","x-enum-varnames":["ActivityTypeToolCall","ActivityTypePolicyDecision","ActivityTypeQuarantineChange","ActivityTypeServerChange"]},"contracts.AddFromRegistryRequest":{"properties":{"enabled":{"description":"defaults to true when nil","type":"boolean"},"env":{"additionalProperties":{"type":"string"},"description":"overrides + required-input values","type":"object"},"name":{"description":"optional name override","type":"string"}},"type":"object"},"contracts.AddRegistrySourceRequest":{"properties":{"id":{"description":"derived from the host when empty","type":"string"},"name":{"description":"defaults to the id","type":"string"},"protocol":{"description":"defaults to modelcontextprotocol/registry","type":"string"},"url":{"description":"required https registry URL","type":"string"}},"type":"object"},"contracts.AttentionFix":{"properties":{"label":{"type":"string"},"target":{"type":"string"},"verb":{"type":"string"}},"type":"object"},"contracts.AttentionItem":{"properties":{"detail":{"type":"string"},"fix":{"$ref":"#/components/schemas/contracts.AttentionFix"},"id":{"description":"kind:type:subject[:state]","type":"string"},"kind":{"type":"string"},"rank":{"type":"integer"},"since":{"type":"string"},"subject":{"$ref":"#/components/schemas/contracts.AttentionSubject"},"summary":{"type":"string"}},"type":"object"},"contracts.AttentionSubject":{"properties":{"id":{"type":"string"},"name":{"type":"string"},"type":{"description":"server|tool|client|setting","type":"string"}},"type":"object"},"contracts.ConfigApplyResult":{"properties":{"applied_immediately":{"type":"boolean"},"changed_fields":{"items":{"type":"string"},"type":"array","uniqueItems":false},"requires_restart":{"type":"boolean"},"restart_reason":{"type":"string"},"success":{"type":"boolean"},"validation_errors":{"items":{"$ref":"#/components/schemas/contracts.ValidationError"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.DCRStatus":{"properties":{"attempted":{"type":"boolean"},"error":{"type":"string"},"status_code":{"type":"integer"},"success":{"type":"boolean"}},"type":"object"},"contracts.DeepScanDescriptor":{"description":"DeepScan reports the opt-in \"deep scan\" layer status (Spec 077 US3),\nSEPARATELY from the baseline verdict above. Always emitted on a computed\nsummary — when deep scan is off (the default) it reports enabled=false\nplus any enabled-but-skipped Docker scanners. It never influences Status.","properties":{"available":{"type":"boolean"},"enabled":{"type":"boolean"},"ran":{"type":"boolean"},"scanners_failed":{"items":{"$ref":"#/components/schemas/contracts.DeepScanScannerFailure"},"type":"array","uniqueItems":false},"skipped_scanners":{"description":"SkippedScanners lists Docker scanners the user enabled that are skipped\nbecause security.deep_scan.enabled is false (informational).","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.DeepScanScannerFailure":{"properties":{"id":{"type":"string"},"reason":{"type":"string"}},"type":"object"},"contracts.DeprecatedConfigWarning":{"properties":{"field":{"type":"string"},"message":{"type":"string"},"replacement":{"type":"string"}},"type":"object"},"contracts.Diagnostic":{"description":"Spec 044 — structured diagnostic error and stable error code. Both\nare populated when the server is in a failed state and the error\nhas been classified by internal/diagnostics. Healthy servers omit\nthese fields.","properties":{"cause":{"type":"string"},"code":{"type":"string"},"detected_at":{"type":"string"},"docs_url":{"type":"string"},"fix_steps":{"items":{"$ref":"#/components/schemas/contracts.DiagnosticFixStep"},"type":"array","uniqueItems":false},"severity":{"type":"string"},"user_message":{"type":"string"}},"type":"object"},"contracts.DiagnosticFixStep":{"properties":{"command":{"type":"string"},"destructive":{"type":"boolean"},"fixer_key":{"type":"string"},"label":{"type":"string"},"type":{"type":"string"},"url":{"type":"string"}},"type":"object"},"contracts.Diagnostics":{"properties":{"activity_retention":{"$ref":"#/components/schemas/contracts.ActivityRetentionReport"},"deprecated_configs":{"description":"Deprecated config fields found","items":{"$ref":"#/components/schemas/contracts.DeprecatedConfigWarning"},"type":"array","uniqueItems":false},"docker_status":{"$ref":"#/components/schemas/contracts.DockerStatus"},"missing_secrets":{"description":"Renamed to avoid conflict","items":{"$ref":"#/components/schemas/contracts.MissingSecretInfo"},"type":"array","uniqueItems":false},"oauth_issues":{"description":"OAuth parameter mismatches","items":{"$ref":"#/components/schemas/contracts.OAuthIssue"},"type":"array","uniqueItems":false},"oauth_required":{"items":{"$ref":"#/components/schemas/contracts.OAuthRequirement"},"type":"array","uniqueItems":false},"oauth_token_storage":{"$ref":"#/components/schemas/contracts.OAuthTokenStorageReport"},"runtime_warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false},"timestamp":{"type":"string"},"total_issues":{"type":"integer"},"upstream_errors":{"items":{"$ref":"#/components/schemas/contracts.UpstreamError"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.DockerStatus":{"properties":{"available":{"type":"boolean"},"error":{"type":"string"},"version":{"type":"string"}},"type":"object"},"contracts.EditRegistrySourceRequest":{"properties":{"name":{"description":"new display name","type":"string"},"servers_url":{"description":"explicit servers-collection URL","type":"string"},"url":{"description":"new base/servers https URL","type":"string"}},"type":"object"},"contracts.ErrorResponse":{"properties":{"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.FindingCounts":{"properties":{"dangerous":{"description":"Tool poisoning, active prompt injection","type":"integer"},"info":{"description":"Low-severity CVEs, informational","type":"integer"},"total":{"type":"integer"},"warning":{"description":"Rug pull, supply chain CVEs with exploits","type":"integer"}},"type":"object"},"contracts.GetConfigResponse":{"properties":{"config":{"description":"The configuration object","type":"object"},"config_path":{"description":"Path to config file","type":"string"}},"type":"object"},"contracts.GetRegistriesResponse":{"properties":{"registries":{"items":{"$ref":"#/components/schemas/contracts.Registry"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GetServerLogsResponse":{"properties":{"count":{"type":"integer"},"logs":{"items":{"$ref":"#/components/schemas/contracts.LogEntry"},"type":"array","uniqueItems":false},"server_name":{"type":"string"}},"type":"object"},"contracts.GetServerToolCallsResponse":{"properties":{"server_name":{"type":"string"},"tool_calls":{"items":{"$ref":"#/components/schemas/contracts.ToolCallRecord"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GetServerToolsResponse":{"properties":{"count":{"type":"integer"},"incarnation":{"description":"Incarnation is the committed incarnation of the server the tools were\nread for (Spec 116 FR-017), captured before they were fetched; omitted\nwhen unknown.","type":"integer"},"server_name":{"type":"string"},"tools":{"items":{"$ref":"#/components/schemas/contracts.Tool"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.GetServersResponse":{"properties":{"servers":{"items":{"$ref":"#/components/schemas/contracts.Server"},"type":"array","uniqueItems":false},"stats":{"$ref":"#/components/schemas/contracts.ServerStats"}},"type":"object"},"contracts.GetSessionDetailResponse":{"properties":{"session":{"$ref":"#/components/schemas/contracts.MCPSession"}},"type":"object"},"contracts.GetSessionsResponse":{"properties":{"limit":{"type":"integer"},"offset":{"type":"integer"},"sessions":{"items":{"$ref":"#/components/schemas/contracts.MCPSession"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GetToolCallDetailResponse":{"properties":{"tool_call":{"$ref":"#/components/schemas/contracts.ToolCallRecord"}},"type":"object"},"contracts.GetToolCallsResponse":{"properties":{"limit":{"type":"integer"},"offset":{"type":"integer"},"tool_calls":{"items":{"$ref":"#/components/schemas/contracts.ToolCallRecord"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GlobalToolsResponse":{"properties":{"counts":{"$ref":"#/components/schemas/contracts.ViewAsCounts"},"failed_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"partial":{"type":"boolean"},"stats":{"$ref":"#/components/schemas/contracts.GlobalToolsStats"},"tools":{"items":{"$ref":"#/components/schemas/contracts.Tool"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.GlobalToolsStats":{"properties":{"disabled":{"type":"integer"},"enabled":{"type":"integer"},"pending_approval":{"type":"integer"},"total":{"type":"integer"}},"type":"object"},"contracts.HealthStatus":{"description":"Unified health status calculated by the backend","properties":{"action":{"description":"Action is the suggested fix action: \"login\", \"restart\", \"enable\", \"approve\", \"view_logs\", \"set_secret\", \"configure\", \"edit_url\", or \"\" (none)\nInvariant: Action always equals Actions[0], or \"\" when Actions is empty.","type":"string"},"actions":{"description":"Actions lists every applicable next step in priority order (FR-012):\nlogin \u003e set_secret \u003e configure \u003e edit_url \u003e approve \u003e restart \u003e\nview_logs \u003e enable. Always non-nil (empty slice, never null).","items":{"type":"string"},"type":"array","uniqueItems":false},"admin_state":{"description":"AdminState indicates the admin state: \"enabled\", \"disabled\", or \"quarantined\"","type":"string"},"detail":{"description":"Detail is an optional longer explanation of the status","type":"string"},"level":{"description":"Level indicates the health level: \"healthy\", \"degraded\", or \"unhealthy\"","type":"string"},"status":{"description":"Status is the ONE status vocabulary rendered as text on every surface\n(Web UI, macOS, tray, CLI) — Spec 109 FR-010/FR-011. Values: \"ready\",\n\"connecting\", \"sign_in_required\", \"needs_review\", \"needs_secret\",\n\"needs_config\", \"error\", \"disabled\". Unlike Level (a severity signal for\nbadge/tray coloring only), no renderer may print Level as text.","type":"string"},"summary":{"description":"Summary is a human-readable status message (e.g., \"Connected (5 tools)\")","type":"string"},"usable":{"description":"Usable reports whether the server can currently serve tool calls. True\nonly when Status == \"ready\".","type":"boolean"}},"type":"object"},"contracts.InfoEndpoints":{"description":"Available API endpoints","properties":{"http":{"description":"HTTP endpoint address (e.g., \"127.0.0.1:8080\")","type":"string"},"socket":{"description":"Unix socket path (empty if disabled)","type":"string"}},"type":"object"},"contracts.InfoResponse":{"properties":{"endpoints":{"$ref":"#/components/schemas/contracts.InfoEndpoints"},"launched_by":{"description":"LaunchedBy is the durable launch provenance of the running core (Spec\n092 FR-001a): \"tray\" when a tray spawned it, \"installer\" when the macOS\nPKG postinstall did, \"\" when user-launched or unknown. Always present\n(possibly empty) so a tray can distinguish \"old core, not mine\" from\n\"old core I may supersede\".","type":"string"},"listen_addr":{"description":"Listen address (e.g., \"127.0.0.1:8080\")","type":"string"},"pid":{"description":"PID is the operating-system process id of the running core (Spec 092\nFR-002). A tray that merely ATTACHED to a core holds no Process handle\nfor it, so without this there is no mechanism at all to stop a stale\ncore — the consent action would have nothing to act on and could only\nprint instructions. Paired with LaunchedBy it is what lets a newer tray\nsupersede a core an older tray started.","type":"integer"},"update":{"$ref":"#/components/schemas/contracts.UpdateInfo"},"update_policy":{"$ref":"#/components/schemas/contracts.UpdatePolicy"},"version":{"description":"Current MCPProxy version","type":"string"},"web_ui_url":{"description":"URL to access the web control panel","type":"string"}},"type":"object"},"contracts.IsolationConfig":{"properties":{"cpu_limit":{"type":"string"},"enabled":{"description":"Enabled is the EFFECTIVE isolation state for this server: whether its\nprocess is actually CONFINED, after the global setting, the per-server\noverride, the structural gates and the host's capabilities. It is NOT the\nraw per-server override — read EnabledOverride for that (GH #1142).\n\nREAD-ONLY. The write surfaces reject an ` + "`" + `enabled` + "`" + ` key precisely because\nit is derived: echoing it back would convert \"inherits the global\nsetting\" into a permanent explicit override. Write EnabledOverride.\n\nIt stays a non-pointer bool that is always present on the wire: the macOS\ntray decodes it as a non-optional Swift Bool, so omitting or nulling the\nkey would fail Codable for the whole server payload. Older clients that\nread this field now simply get a true answer.","type":"boolean"},"enabled_override":{"description":"EnabledOverride is the RAW per-server ` + "`" + `isolation.enabled` + "`" + ` override, as\npersisted. Absent means \"inherit the global setting\" — which is a\ndistinct state from an explicit false, and the distinction the reporting\nbug used to destroy.","type":"boolean"},"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"memory_limit":{"type":"string"},"mode_override":{"description":"ModeOverride is the RAW per-server ` + "`" + `isolation.mode` + "`" + ` override\n(\"docker\" | \"sandbox\" | \"none\"). Absent means \"inherit\".","type":"string"},"network_mode":{"type":"string"},"timeout":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"contracts.IsolationDefaults":{"description":"IsolationDefaults exposes the resolved baseline values that\nwould apply when no per-server override is set. Populated on\nlist/get responses; never consumed on PATCH requests.","properties":{"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"network_mode":{"type":"string"},"runtime_type":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"contracts.IsolationEffective":{"description":"IsolationEffective exposes the resolved isolation state (and the rule\nthat decided it) so clients can distinguish \"inherits global\" from an\nexplicit per-server choice. Read-only; never consumed on PATCH.","properties":{"global_mode":{"description":"GlobalMode is what \"inherit\" resolves to right now.","type":"string"},"inherited":{"description":"Inherited is true when the server sets neither ` + "`" + `isolation.enabled` + "`" + ` nor\n` + "`" + `isolation.mode` + "`" + `, so its state tracks the global setting.","type":"boolean"},"isolated":{"description":"Isolated reports whether the process is actually CONFINED. It is NOT\nsimply Mode != \"none\": \"sandbox\" on a host that cannot enforce Landlock\n(any non-Linux OS, or a kernel without the LSM) runs the server\nunconfined, and Source then says \"sandbox-unavailable\" (GH #1142).","type":"boolean"},"mode":{"description":"Mode is the effective isolation mode: \"docker\" | \"sandbox\" | \"none\" —\nexactly what the spawn path branches on.","type":"string"},"source":{"description":"Source names the deciding rule: \"global\", \"server-mode\",\n\"server-opt-out\", \"server-opt-in-ignored\", \"not-stdio\",\n\"already-docker\", \"sandbox-unavailable\" or \"unsupported-mode\".\nTreat an unrecognized value as \"global\".","type":"string"}},"type":"object"},"contracts.LogEntry":{"properties":{"fields":{"type":"object"},"level":{"type":"string"},"message":{"type":"string"},"server":{"type":"string"},"timestamp":{"type":"string"}},"type":"object"},"contracts.MCPSession":{"properties":{"client_id":{"description":"Scope attribution (Spec 108 FR-033). ClientID and TokenName are the\ncredential the session initialized with; Profile and ProfileSource are\nthe session's latest effective resolution. Empty on legacy sessions.","type":"string"},"client_name":{"type":"string"},"client_version":{"type":"string"},"end_time":{"type":"string"},"experimental":{"items":{"type":"string"},"type":"array","uniqueItems":false},"has_roots":{"description":"MCP Client Capabilities","type":"boolean"},"has_sampling":{"type":"boolean"},"id":{"type":"string"},"last_activity":{"type":"string"},"profile":{"type":"string"},"profile_source":{"type":"string"},"start_time":{"type":"string"},"status":{"type":"string"},"token_name":{"type":"string"},"tool_call_count":{"type":"integer"},"total_tokens":{"type":"integer"},"work_session_id":{"type":"string"},"workspace_name":{"description":"Workspace / work session (Spec 082). WorkspaceName is the project's\nbasename — the full local path is never exposed. WorkSessionID groups the\nreconnects that make up one stretch of user work.","type":"string"}},"type":"object"},"contracts.MetadataStatus":{"properties":{"authorization_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"error":{"type":"string"},"found":{"type":"boolean"},"url_checked":{"type":"string"}},"type":"object"},"contracts.MissingSecretInfo":{"properties":{"secret_name":{"type":"string"},"used_by":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.NPMPackageInfo":{"properties":{"exists":{"type":"boolean"},"install_cmd":{"type":"string"}},"type":"object"},"contracts.OAuthConfig":{"properties":{"auth_server_metadata_url":{"type":"string"},"auth_url":{"type":"string"},"authorization_endpoint":{"description":"Spec 113-b operator overrides of OAuth discovery (https-or-loopback URLs,\nnever credentials). Empty means \"use discovery\".","type":"string"},"client_id":{"type":"string"},"extra_params":{"additionalProperties":{"type":"string"},"type":"object"},"pkce_enabled":{"type":"boolean"},"redirect_port":{"type":"integer"},"refresh_replay_enabled":{"type":"boolean"},"registration_endpoint":{"type":"string"},"scopes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"token_endpoint":{"type":"string"},"token_expires_at":{"description":"When the OAuth token expires","type":"string"},"token_url":{"type":"string"},"token_valid":{"description":"Whether token is currently valid","type":"boolean"}},"type":"object"},"contracts.OAuthErrorDetails":{"description":"Structured discovery/failure details","properties":{"authorization_server_metadata":{"$ref":"#/components/schemas/contracts.MetadataStatus"},"dcr_status":{"$ref":"#/components/schemas/contracts.DCRStatus"},"protected_resource_metadata":{"$ref":"#/components/schemas/contracts.MetadataStatus"},"server_url":{"type":"string"}},"type":"object"},"contracts.OAuthFlowError":{"properties":{"correlation_id":{"description":"Flow tracking ID for log correlation","type":"string"},"debug_hint":{"description":"CLI command for log lookup","type":"string"},"details":{"$ref":"#/components/schemas/contracts.OAuthErrorDetails"},"error_code":{"description":"Machine-readable error code (e.g., OAUTH_NO_METADATA)","type":"string"},"error_type":{"description":"Category of OAuth runtime failure","type":"string"},"message":{"description":"Human-readable error description","type":"string"},"request_id":{"description":"HTTP request ID (from PR #237)","type":"string"},"server_name":{"description":"Server that failed OAuth","type":"string"},"success":{"description":"Always false","type":"boolean"},"suggestion":{"description":"Actionable remediation hint","type":"string"}},"type":"object"},"contracts.OAuthIssue":{"properties":{"documentation_url":{"type":"string"},"error":{"type":"string"},"issue":{"type":"string"},"missing_params":{"items":{"type":"string"},"type":"array","uniqueItems":false},"resolution":{"type":"string"},"server_name":{"type":"string"}},"type":"object"},"contracts.OAuthRequirement":{"properties":{"expires_at":{"type":"string"},"message":{"type":"string"},"server_name":{"type":"string"},"state":{"type":"string"}},"type":"object"},"contracts.OAuthStartResponse":{"properties":{"auth_url":{"description":"Authorization URL (always included for manual use)","type":"string"},"browser_error":{"description":"Error message if browser launch failed","type":"string"},"browser_opened":{"description":"Whether browser launch succeeded","type":"boolean"},"correlation_id":{"description":"UUID for tracking this flow","type":"string"},"message":{"description":"Human-readable status message","type":"string"},"server_name":{"description":"Name of the server being authenticated","type":"string"},"success":{"description":"Always true for successful start","type":"boolean"}},"type":"object"},"contracts.OAuthTokenStorageReport":{"description":"OAuthTokenStorage (Spec 123 FR-030) reports the state of the stored\nupstream OAuth rows: encryption on or off, the public key id, the row\ncounts by state, the undecryptable servers and the compaction advice.\nIt never carries key material or the key reference.","properties":{"compaction_advised":{"description":"CompactionAdvised mirrors the compaction marker: freed pages may still\nhold old plaintext until ` + "`" + `mcpproxy db compact --keep-backup=false` + "`" + `.","type":"boolean"},"encryption_enabled":{"description":"EncryptionEnabled is true when an encryption key is configured.","type":"boolean"},"key_id":{"description":"KeyID is the public, non-secret id of the configured key (administrator only).","type":"string"},"key_source_in_data_dir":{"description":"KeySourceInDataDir is true when the key file lies inside the data directory.","type":"boolean"},"key_source_kind":{"description":"KeySourceKind is how the key was obtained: literal, env, env_file,\nref_file, ref_env or ref_keyring (administrator only).","type":"string"},"plaintext":{"description":"Plaintext counts valid JSON rows; Sealed counts envelopes the configured\nkey opens; Undecryptable counts everything else.","type":"integer"},"sealed":{"type":"integer"},"servers":{"description":"Servers lists the undecryptable rows by server.","items":{"$ref":"#/components/schemas/contracts.OAuthTokenStorageServer"},"type":"array","uniqueItems":false},"undecryptable":{"type":"integer"},"undecryptable_by_reason":{"$ref":"#/components/schemas/contracts.OAuthTokenUndecryptableByReason"},"warnings":{"description":"Warnings are stable codes: literal_key, key_file_in_data_dir,\nplaintext_rows_with_key, compaction_advised, backup_file_present\n(administrator only).","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.OAuthTokenStorageServer":{"properties":{"bucket_key":{"type":"string"},"reason":{"type":"string"},"row_key_id":{"description":"RowKeyID is the key id in the row's envelope (administrator only).","type":"string"},"server":{"type":"string"}},"type":"object"},"contracts.OAuthTokenUndecryptableByReason":{"description":"UndecryptableByReason breaks Undecryptable down by reason.","properties":{"auth_failed":{"type":"integer"},"key_mismatch":{"type":"integer"},"malformed":{"type":"integer"},"no_key":{"type":"integer"},"unsupported_version":{"type":"integer"}},"type":"object"},"contracts.PreflightPolicy":{"properties":{"exclude_destructive":{"type":"boolean"},"exclude_open_world":{"type":"boolean"},"read_only_only":{"type":"boolean"}},"type":"object"},"contracts.PreflightReason":{"type":"string","x-enum-varnames":["PreflightReasonServerInitializing","PreflightReasonServerUnhealthy","PreflightReasonServerDisabled","PreflightReasonServerQuarantined","PreflightReasonToolPendingApproval","PreflightReasonToolChanged","PreflightReasonToolBlockedByUser","PreflightReasonOAuthRequired","PreflightReasonHashMismatch","PreflightReasonServerNotInScope","PreflightReasonToolDeniedByConfig","PreflightReasonMissingAnnotation","PreflightReasonPolicyFiltered","PreflightReasonNotFound","PreflightReasonServerNotConfigured","PreflightReasonToolBlockedByProfile","PreflightReasonTokenPermissionDenied"]},"contracts.PreflightRequest":{"properties":{"policy":{"$ref":"#/components/schemas/contracts.PreflightPolicy"},"profile":{"description":"Profile evaluates under a named profile's server scope and tool policy;\nit can only narrow a credential's own pin. Unknown: 400.","type":"string"},"tools":{"description":"Tools is 1..100 entries BEFORE dedup; duplicates are collapsed, and\nduplicate ids carrying different pins are a validation error.","items":{"$ref":"#/components/schemas/contracts.PreflightToolRef"},"type":"array","uniqueItems":false},"wait_ms":{"description":"WaitMS polls local state for up to this many milliseconds (cap 10000)\nwhile every failure is retryable-class.","type":"integer"}},"type":"object"},"contracts.PreflightResponse":{"properties":{"checked_at":{"type":"string"},"tools":{"description":"Tools are ordered by first occurrence of each unique id in the request.","items":{"$ref":"#/components/schemas/contracts.PreflightToolResult"},"type":"array","uniqueItems":false},"verdict":{"$ref":"#/components/schemas/contracts.PreflightVerdict"},"waited_ms":{"description":"WaitedMS is present when wait_ms was requested (0 when the wait\nsemaphore was exhausted and the request resolved immediately).","type":"integer"}},"type":"object"},"contracts.PreflightStatus":{"type":"string","x-enum-varnames":["PreflightStatusReady","PreflightStatusUnavailable"]},"contracts.PreflightToolRef":{"properties":{"id":{"description":"ID is a canonical \"\u003cserver\u003e:\u003ctool\u003e\" id. A malformed id is answered with a\nper-ID not_found carrying a format hint, never a request-level error.","type":"string"},"pin_hash":{"description":"PinHash is \"sha256/v{N}:{hex}\" — the schema version is embedded so a\nproxy-side hash-algorithm bump is distinguishable from upstream drift.","type":"string"}},"type":"object"},"contracts.PreflightToolResult":{"properties":{"action":{"type":"string"},"detail":{"type":"string"},"did_you_mean":{"description":"DidYouMean carries up to 3 nearest caller-visible ids on not_found. It\nnever crosses a scope boundary and never names a quarantined server's\ntools.","items":{"type":"string"},"type":"array","uniqueItems":false},"hash":{"description":"Hash is the tool's current pin (\"sha256/v{N}:{hex}\") — operator tier,\nready results only. Never disclosed to an agent token.","type":"string"},"id":{"type":"string"},"reason":{"$ref":"#/components/schemas/contracts.PreflightReason"},"remediation":{"type":"string"},"retryable":{"type":"boolean"},"status":{"$ref":"#/components/schemas/contracts.PreflightStatus"}},"type":"object"},"contracts.PreflightVerdict":{"type":"string","x-enum-varnames":["PreflightVerdictReady","PreflightVerdictDegradedRetryable","PreflightVerdictBlocked","PreflightVerdictUnknownIDs"]},"contracts.QuarantineStats":{"description":"Tool quarantine metrics for this server","properties":{"blocked_count":{"description":"Number of disabled (blocked) tools","type":"integer"},"changed_count":{"description":"Number of tools whose description/schema changed since approval","type":"integer"},"pending_count":{"description":"Number of newly discovered tools awaiting approval","type":"integer"}},"type":"object"},"contracts.RefreshRegistryResponse":{"properties":{"cleared":{"description":"number of cached entries dropped","type":"integer"},"registry_id":{"type":"string"}},"type":"object"},"contracts.Registry":{"properties":{"count":{"description":"number or string","type":"string"},"description":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"},"protocol":{"type":"string"},"provenance":{"description":"Provenance is the trust tag (MCP-866): \"official/trusted\" for built-in\ndefaults, \"custom/unverified\" for user-added registries.","type":"string"},"servers_url":{"type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"trusted":{"description":"Trusted indicates whether this is an official, shipped-by-default\nregistry. Trust is derived from membership in the default set, never\nfrom self-assertion in config.","type":"boolean"},"url":{"type":"string"}},"type":"object"},"contracts.RegistryCacheInfo":{"properties":{"age_seconds":{"type":"number"},"stale":{"type":"boolean"}},"type":"object"},"contracts.RegistryUnavailable":{"properties":{"reason":{"type":"string"}},"type":"object"},"contracts.ReplayToolCallRequest":{"properties":{"arguments":{"description":"Modified arguments for replay","type":"object"}},"type":"object"},"contracts.ReplayToolCallResponse":{"properties":{"error":{"description":"Error if replay failed","type":"string"},"new_call_id":{"description":"ID of the newly created call","type":"string"},"new_tool_call":{"$ref":"#/components/schemas/contracts.ToolCallRecord"},"replayed_from":{"description":"Original call ID","type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.RepositoryInfo":{"description":"Detected package info","properties":{"npm":{"$ref":"#/components/schemas/contracts.NPMPackageInfo"}},"type":"object"},"contracts.RepositoryServer":{"properties":{"connect_url":{"description":"Alternative connection URL","type":"string"},"created_at":{"type":"string"},"description":{"type":"string"},"id":{"type":"string"},"install_cmd":{"description":"Installation command","type":"string"},"name":{"type":"string"},"registry":{"description":"Which registry this came from","type":"string"},"repository_info":{"$ref":"#/components/schemas/contracts.RepositoryInfo"},"source_code_url":{"description":"Source repository URL","type":"string"},"updated_at":{"type":"string"},"url":{"description":"MCP endpoint for remote servers only","type":"string"}},"type":"object"},"contracts.SearchRegistryServersResponse":{"properties":{"cache":{"$ref":"#/components/schemas/contracts.RegistryCacheInfo"},"query":{"type":"string"},"registry_id":{"type":"string"},"servers":{"items":{"$ref":"#/components/schemas/contracts.RepositoryServer"},"type":"array","uniqueItems":false},"tag":{"type":"string"},"total":{"type":"integer"},"unavailable":{"$ref":"#/components/schemas/contracts.RegistryUnavailable"}},"type":"object"},"contracts.SearchResult":{"properties":{"matches":{"type":"integer"},"score":{"type":"number"},"snippet":{"type":"string"},"tool":{"$ref":"#/components/schemas/contracts.Tool"}},"type":"object"},"contracts.SearchToolsResponse":{"properties":{"query":{"type":"string"},"results":{"items":{"$ref":"#/components/schemas/contracts.SearchResult"},"type":"array","uniqueItems":false},"took":{"type":"string"},"total":{"type":"integer"}},"type":"object"},"contracts.SecurityScanSummary":{"description":"Latest security scan results summary","properties":{"deep_scan":{"$ref":"#/components/schemas/contracts.DeepScanDescriptor"},"finding_counts":{"$ref":"#/components/schemas/contracts.FindingCounts"},"last_scan_at":{"type":"string"},"risk_score":{"description":"0-100","type":"integer"},"scanners_failed":{"type":"integer"},"scanners_run":{"description":"Scanner coverage for the primary (baseline) scan pass — informational only.\nSpec 077 US3 (FR-008/FR-014): Status is derived SOLELY from the\ndeterministic baseline findings; a failed Docker deep scanner no longer\ndowngrades a clean verdict. That failure is surfaced via DeepScan instead.","type":"integer"},"scanners_total":{"type":"integer"},"status":{"description":"\"clean\", \"warnings\", \"dangerous\", \"failed\", \"not_scanned\", \"scanning\"","type":"string"}},"type":"object"},"contracts.Server":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"authenticated":{"description":"OAuth authentication status","type":"boolean"},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges mirrors config.ServerConfig.AutoApproveToolChanges\n(MCP-2930): the per-server intent to auto-approve new/changed tools past\nthe trust baseline. Tri-state *bool — nil means \"never set\" (omitted from\nthe payload), so the Web UI toggle (MCP-2932) can distinguish unset from\nan explicit false. Read-only on the GET path; PATCH/POST accept it via\nAddServerRequest.","type":"boolean"},"command":{"type":"string"},"connected":{"type":"boolean"},"connected_at":{"type":"string"},"connecting":{"type":"boolean"},"created":{"type":"string"},"diagnostic":{"$ref":"#/components/schemas/contracts.Diagnostic"},"enabled":{"type":"boolean"},"env":{"additionalProperties":{"type":"string"},"type":"object"},"error_code":{"type":"string"},"expose_prompts":{"description":"ExposePrompts mirrors config.ServerConfig.ExposePrompts (F9): the per-server\nprompt-aggregation override. Tri-state *bool — nil/omitted means \"inherit\ndefault aggregation\". Surfaced on GET so a caller that PATCHed the override\ncan read it back; PATCH/POST accept it via AddServerRequest.","type":"boolean"},"expose_skills":{"description":"ExposeSkills mirrors config.ServerConfig.ExposeSkills: the per-server\nskills override. Tri-state *bool; nil/omitted means \"inherit\".","type":"boolean"},"forward_headers":{"description":"ForwardHeaders mirrors config.ServerConfig.ForwardHeaders (Spec 112): the\nallowlist of inbound MCP client header NAMES forwarded to this server on\ntools/call. Names only, never values. Omitted when empty.","items":{"type":"string"},"type":"array","uniqueItems":false},"generation":{"description":"Generation is the server's committed config generation (Spec 116\nFR-017): it changes whenever the server's configuration changes.","type":"integer"},"headers":{"additionalProperties":{"type":"string"},"type":"object"},"health":{"$ref":"#/components/schemas/contracts.HealthStatus"},"id":{"type":"string"},"incarnation":{"description":"Incarnation changes only when the name is removed and created again\n(Spec 116 FR-017). Approval endpoints accept it back as\nexpected_incarnation and answer 409 server_replaced on a mismatch.","type":"integer"},"init_timeout":{"description":"InitTimeout mirrors config.ServerConfig.InitTimeout (MCP-3322 / GH #760):\nthe per-server MCP ` + "`" + `initialize` + "`" + ` handshake deadline override. Serialized as\na duration string (e.g. \"120s\"); nil/omitted means \"inherit the global\ndefault\". Surfaced on the GET path so clients can read back a configured\noverride; PATCH/POST accept it via AddServerRequest.","type":"string"},"isolation":{"$ref":"#/components/schemas/contracts.IsolationConfig"},"isolation_defaults":{"$ref":"#/components/schemas/contracts.IsolationDefaults"},"isolation_effective":{"$ref":"#/components/schemas/contracts.IsolationEffective"},"last_error":{"type":"string"},"last_reconnect_at":{"type":"string"},"last_retry_time":{"type":"string"},"max_concurrent_requests":{"description":"Spec 093 (GH #955) — per-server concurrency overrides, scope (c) of\nFR-020. Each setting is tri-state: nil (omitted) means \"inherit\nserver_concurrency_defaults\", 0 disables that setting for this server,\npositive overrides it. Surfaced on the GET path so a caller can read back\nwhat it set; PATCH/POST accept them via AddServerRequest. The effective\nconcurrency for a server is additionally bounded by the global aggregate\nlimiter, which is NOT an inheritance source for these fields.","type":"integer"},"name":{"type":"string"},"oauth":{"$ref":"#/components/schemas/contracts.OAuthConfig"},"oauth_status":{"description":"OAuth status: \"authenticated\", \"expired\", \"error\", \"none\"","type":"string"},"protocol":{"type":"string"},"quarantine":{"$ref":"#/components/schemas/contracts.QuarantineStats"},"quarantined":{"type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_count":{"type":"integer"},"reconnect_on_use":{"description":"Attempt reconnection when a tool call targets this disconnected server","type":"boolean"},"retry_count":{"type":"integer"},"retry_stopped":{"description":"RetryStopped reports that automatic reconnection has been given up for\ngood because the failure is deterministic and unrecoverable — a missing\nbinary, an image without the interpreter, an unparseable config (GH\n#1145). It is NOT ordinary exponential backoff, which keeps retrying;\nnothing will happen until the user fixes the config or restarts the\nserver. RetryStoppedCode is the stable MCPX_* code that proved it and\nRetryStoppedReason the catalog message explaining how to fix it. All three\nare omitted for servers that are healthy or still retrying.","type":"boolean"},"retry_stopped_code":{"type":"string"},"retry_stopped_reason":{"type":"string"},"security_scan":{"$ref":"#/components/schemas/contracts.SecurityScanSummary"},"should_retry":{"type":"boolean"},"source_registry_id":{"description":"MCP-901 — registry provenance of an upstream that was added from a\nregistry. SourceRegistryID names the source registry (empty for\nmanually-configured servers); SourceRegistryProvenance is the trust tag\nrecorded at add time (\"official/trusted\" or \"custom/unverified\"). Both\nare projected from config.ServerConfig so the approval/quarantine view\ncan render an \"added from \u003cregistry\u003e · unverified\" origin badge. Optional\nand omitted when empty — clients that pre-date this treat them as absent.","type":"string"},"source_registry_provenance":{"type":"string"},"status":{"type":"string"},"token_expires_at":{"description":"When the OAuth token expires (ISO 8601)","type":"string"},"tool_argument_error_mode":{"type":"string"},"tool_count":{"type":"integer"},"tool_list_token_size":{"description":"Token size for this server's tools","type":"integer"},"trust_mode":{"description":"TrustMode mirrors config.ServerConfig.TrustMode (spec 086): the per-server\ntrust tier (\"auto\"/\"scan\"/\"manual\"). Surfaced on the GET path so clients can\nread back the persisted mode; PATCH/POST accept it via AddServerRequest.\nOmitted when empty (server predates the field / relies on legacy flags).","type":"string"},"updated":{"type":"string"},"url":{"type":"string"},"user_logged_out":{"description":"True if user explicitly logged out (prevents auto-reconnection)","type":"boolean"},"working_dir":{"type":"string"}},"type":"object"},"contracts.ServerActionResponse":{"properties":{"action":{"type":"string"},"async":{"type":"boolean"},"server":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.ServerStats":{"properties":{"connected_servers":{"type":"integer"},"docker_containers":{"type":"integer"},"quarantined_servers":{"type":"integer"},"token_metrics":{"$ref":"#/components/schemas/contracts.ServerTokenMetrics"},"total_servers":{"type":"integer"},"total_tools":{"type":"integer"}},"type":"object"},"contracts.ServerTokenMetrics":{"properties":{"average_query_result_size":{"description":"Typical retrieve_tools output (tokens)","type":"integer"},"estimated":{"description":"Estimated (Spec 109-k FR-070-ish, url-filter-contract.md / audit F-Token):\ntrue while AverageQueryResultSize is a synthetic simulation (a sample of\nthe first ` + "`" + `tools_limit` + "`" + ` tools' schemas — no real retrieve_tools call has\ncompleted yet in this runtime's usage aggregate); false once at least one\nreal retrieve_tools call has, at which point AverageQueryResultSize is\nderived from the real observed average response size instead. The Web\nUI and macOS render an \"estimate\" label while this is true.","type":"boolean"},"per_server_tool_list_sizes":{"additionalProperties":{"type":"integer"},"description":"Token size per server","type":"object"},"saved_tokens":{"description":"Difference","type":"integer"},"saved_tokens_percentage":{"description":"Percentage saved","type":"number"},"total_server_tool_list_size":{"description":"All upstream tools combined (tokens)","type":"integer"}},"type":"object"},"contracts.SkillContentResponse":{"properties":{"digest":{"type":"string"},"next_offset":{"description":"NextOffset is the byte offset of the next chunk; absent at the end.","type":"integer"},"offset":{"type":"integer"},"size":{"type":"integer"},"text":{"type":"string"}},"type":"object"},"contracts.SkillEntry":{"properties":{"approved_at":{"description":"ApprovedAt is omitted when the skill was never approved.","type":"string"},"approved_by":{"type":"string"},"approved_files":{"description":"ApprovedFiles is the file set of the approved copy; omitted when the\nskill has no approved copy. ` + "`" + `skills show --diff` + "`" + ` compares it with Files.","items":{"$ref":"#/components/schemas/contracts.SkillFileInfo"},"type":"array","uniqueItems":false},"approved_hash":{"type":"string"},"available":{"type":"boolean"},"blocked":{"type":"boolean"},"current_hash":{"type":"string"},"description":{"type":"string"},"files":{"items":{"$ref":"#/components/schemas/contracts.SkillFileInfo"},"type":"array","uniqueItems":false},"id":{"type":"string"},"listed":{"type":"boolean"},"name":{"type":"string"},"path":{"type":"string"},"scan":{"$ref":"#/components/schemas/contracts.SkillScanInfo"},"status":{"type":"string"},"total_size":{"type":"integer"},"unusable_reason":{"type":"string"},"uri":{"type":"string"}},"type":"object"},"contracts.SkillFileInfo":{"properties":{"digest":{"type":"string"},"path":{"type":"string"},"size":{"type":"integer"},"text":{"type":"boolean"}},"type":"object"},"contracts.SkillScanFinding":{"properties":{"evidence":{"type":"string"},"file":{"type":"string"},"offset":{"type":"integer"},"rule":{"type":"string"},"severity":{"type":"string"}},"type":"object"},"contracts.SkillScanInfo":{"properties":{"complete":{"type":"boolean"},"findings":{"items":{"$ref":"#/components/schemas/contracts.SkillScanFinding"},"type":"array","uniqueItems":false},"findings_truncated":{"description":"FindingsTruncated is true when more findings existed than are listed.","type":"boolean"},"incomplete":{"description":"Incomplete says why Complete is false: size_cap, time_limit, coverage or\ninterrupted; empty when the scan is complete.","type":"string"},"scanned_at":{"description":"ScannedAt is omitted when no scan of the current content exists.","type":"string"},"verdict":{"type":"string"}},"type":"object"},"contracts.SkillsApproveRequest":{"properties":{"expected_hashes":{"additionalProperties":{"type":"string"},"description":"ExpectedHashes maps each skill path to the current_hash the reviewer\nsaw. A skill without an entry is refused as unreviewed.","type":"object"},"expected_incarnation":{"description":"ExpectedIncarnation binds the approval to the server the reviewer saw;\n0 (or absent) binds to the incarnation current when the request starts.","type":"integer"},"skills":{"description":"Skills are skill paths (the part of the id after \"\u003cserver\u003e:\"), 1 to 200.","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.SkillsApproveResponse":{"properties":{"approved":{"description":"Approved counts the skills newly approved; a skill already approved for\nits current content is not counted.","type":"integer"}},"type":"object"},"contracts.SkillsBlockRequest":{"properties":{"expected_incarnation":{"type":"integer"},"skills":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.SkillsBlockResponse":{"properties":{"changed":{"description":"Changed counts the skills whose blocked mark changed.","type":"integer"}},"type":"object"},"contracts.SkillsErrorResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.SkillsListResponse":{"properties":{"enabled":{"type":"boolean"},"error":{"type":"string"},"expose_skills":{"type":"boolean"},"incarnation":{"description":"Incarnation is the server's approval incarnation: send it back as\nexpected_incarnation on approve, block and unblock.","type":"integer"},"last_refresh":{"type":"string"},"server":{"type":"string"},"skills":{"items":{"$ref":"#/components/schemas/contracts.SkillEntry"},"type":"array","uniqueItems":false},"supported":{"type":"boolean"},"truncated":{"type":"boolean"}},"type":"object"},"contracts.SkillsStaleReviewResponse":{"properties":{"changed":{"items":{"type":"string"},"type":"array","uniqueItems":false},"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"},"unreviewed":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.SkillsUnusableResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"skills":{"items":{"type":"string"},"type":"array","uniqueItems":false},"success":{"type":"boolean"}},"type":"object"},"contracts.SuccessResponse":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"success":{"type":"boolean"}},"type":"object"},"contracts.Tier":{"description":"Tier is computed by AnnotationTier (Spec 109 FR-028/X11) from\nAnnotations — read|write|destructive|unannotated. Set by every producer\nof a Tool (enrichServerTools, the global tools handler); never left for\na consuming surface to compute.","type":"string","x-enum-varnames":["TierRead","TierWrite","TierDestructive","TierUnannotated","TierUnknown"]},"contracts.TokenMetrics":{"description":"Token usage metrics (nil for older records)","properties":{"encoding":{"description":"Encoding used (e.g., cl100k_base)","type":"string"},"estimated_cost":{"description":"Optional cost estimate","type":"number"},"input_tokens":{"description":"Tokens in the request","type":"integer"},"model":{"description":"Model used for tokenization","type":"string"},"output_tokens":{"description":"Tokens in the response","type":"integer"},"total_tokens":{"description":"Total tokens (input + output)","type":"integer"},"truncated_tokens":{"description":"Tokens removed by truncation","type":"integer"},"was_truncated":{"description":"Whether response was truncated","type":"boolean"}},"type":"object"},"contracts.Tool":{"properties":{"access":{"$ref":"#/components/schemas/contracts.ToolAccess"},"annotations":{"$ref":"#/components/schemas/contracts.ToolAnnotation"},"approval_status":{"type":"string"},"config_denied":{"description":"ConfigDenied is true when the tool is denied by the server's static\nenabled_tools / disabled_tools config. The user cannot override this toggle.","type":"boolean"},"description":{"type":"string"},"disabled":{"description":"Disabled mirrors ToolApprovalRecord.Disabled so per-tool enable state is\navailable without a second round-trip to the approvals endpoint. Absent\nin the JSON when false (default) to keep responses compact.","type":"boolean"},"hash":{"description":"Hash is the tool's current stored hash rendered in the preflight pin\nformat \"sha256/v{N}:{hex}\" (Spec 098 FR-011), where N is the approval\nrecord's HashSchemaVersion. It is the authoring surface for\n` + "`" + `POST /api/v1/preflight` + "`" + ` pins and ` + "`" + `mcpproxy tools preflight --pin` + "`" + `:\ncopy the value straight into a pin.\n\nDisclosure is OPERATOR TIER ONLY — same rule as the preflight per-tool\nresult. The field is omitted for agent-token callers and for tools with\nno stored hash (no approval record yet, or a record written before\nhashes existed).","type":"string"},"held_reason":{"description":"HeldReason, HeldVerdict and HeldSignals mirror the same-named fields on\nstorage.ToolApprovalRecord: the offline-scan evidence that made\ntrust_mode: scan hold this tool for review (spec 086 FR-018). HeldSignals\nnames the matched deterministic check ids, e.g.\n\"tpa.TPA-2026-0001.hidden_instruction\", so a reviewer can see WHY the tool\nis held. All three are omitted for tools that are not held by the scan gate\n(including every record written before the field existed).","type":"string"},"held_signals":{"items":{"type":"string"},"type":"array","uniqueItems":false},"held_verdict":{"type":"string"},"last_used":{"type":"string"},"name":{"type":"string"},"profile_tier":{"description":"ProfileTier and Access are present only in a view-as listing (a tools\nlisting with ?client= or ?profile=, Spec 108 FR-032). ProfileTier is the\ntool's tier under the viewed subject's profile (Tier above stays the\nintrinsic tier); Access is the subject's verdict for the tool. Absent\notherwise, so an ordinary listing is byte-identical to before.","type":"string","x-enum-varnames":["TierRead","TierWrite","TierDestructive","TierUnannotated","TierUnknown"]},"schema":{"type":"object"},"server_incarnation":{"description":"ServerIncarnation is the committed incarnation of the server this row\nwas read for (Spec 116 FR-017), captured before the tools were fetched.\nA client echoes it as expected_incarnation on a per-tool decision, so a\nstale row is refused (409 server_replaced) after a same-name re-add.\nOmitted when the server has no committed incarnation.","type":"integer"},"server_name":{"type":"string"},"tier":{"$ref":"#/components/schemas/contracts.Tier"},"usage":{"type":"integer"}},"type":"object"},"contracts.ToolAccess":{"properties":{"callable":{"type":"boolean"},"reason":{"type":"string"},"visible":{"type":"boolean"}},"type":"object"},"contracts.ToolAnnotation":{"description":"Tool behavior hints snapshot","properties":{"destructiveHint":{"type":"boolean"},"idempotentHint":{"type":"boolean"},"openWorldHint":{"type":"boolean"},"readOnlyHint":{"type":"boolean"},"title":{"type":"string"}},"type":"object"},"contracts.ToolCallRecord":{"description":"The new tool call record","properties":{"annotations":{"$ref":"#/components/schemas/contracts.ToolAnnotation"},"arguments":{"description":"Tool arguments","type":"object"},"arguments_truncated":{"description":"ArgumentsTruncated marks Arguments as a placeholder rather than the\narguments the tool was called with. Replaying such a record without\nsupplying arguments explicitly is refused.","type":"boolean"},"config_path":{"description":"Active config file path","type":"string"},"duration":{"description":"Duration in nanoseconds","type":"integer"},"error":{"description":"Error message (failure only)","type":"string"},"execution_type":{"description":"\"direct\" or \"code_execution\"","type":"string"},"id":{"description":"Unique identifier","type":"string"},"mcp_client_name":{"description":"MCP client name from InitializeRequest","type":"string"},"mcp_client_version":{"description":"MCP client version","type":"string"},"mcp_session_id":{"description":"MCP session identifier","type":"string"},"metrics":{"$ref":"#/components/schemas/contracts.TokenMetrics"},"parent_call_id":{"description":"Links nested calls to parent code_execution","type":"string"},"request_id":{"description":"Request correlation ID","type":"string"},"response":{"description":"Tool response (success only)","type":"object"},"response_bytes":{"description":"Marshalled response size before truncation","type":"integer"},"response_truncated":{"description":"ResponseTruncated and ResponseBytes describe a STORAGE-side cut (#1176):\nthe caller received the response whole, and only the persisted copy was\nshortened to tool_call_max_response_size. When ResponseTruncated is true\nthe Response object carries {truncated, original_bytes, preview, note}\ninstead of the upstream result, and ResponseBytes is its size before the\ncut.","type":"boolean"},"server_id":{"description":"Server identity hash","type":"string"},"server_name":{"description":"Human-readable server name","type":"string"},"timestamp":{"description":"When the call was made","type":"string"},"tool_name":{"description":"Tool name (without server prefix)","type":"string"}},"type":"object"},"contracts.UpdateInfo":{"description":"Update information (if available)","properties":{"available":{"description":"Whether an update is available","type":"boolean"},"behind_summary":{"description":"Spec 079 FR-002 — how far behind the running build is. All four are\nadditive (FR-021) and absent when the delta could not be resolved, in\nwhich case every surface renders its pre-delta wording.","type":"string"},"check_error":{"description":"Error message if update check failed","type":"string"},"checked_at":{"description":"When the update check was performed","type":"string"},"install_channel":{"description":"Detected install channel (homebrew, dmg, deb, rpm, docker, go-install, windows-installer, tarball, unknown) — Spec 079 FR-008","type":"string"},"is_prerelease":{"description":"Whether the latest version is a prerelease","type":"boolean"},"latest_version":{"description":"Latest version available (e.g., \"v1.2.3\")","type":"string"},"nudges_suppressed":{"description":"UI surfaces must stay quiet (CI / non-interactive context); machine-readable fields still report the facts — Spec 079 FR-019","type":"boolean"},"release_url":{"description":"URL to the release page","type":"string"},"releases_behind":{"description":"Releases on the offered channel between the running and offered versions","type":"integer"},"releases_behind_saturated":{"description":"ReleasesBehind is a lower bound: the running build predates the scanned release window","type":"boolean"},"update_command":{"description":"One-line update command for the channel; only set when an update is available and the channel has one — Spec 079 FR-009","type":"string"},"weeks_behind":{"description":"Whole weeks between the two releases' publish dates; 0 is a real value, absent means unknown","type":"integer"}},"type":"object"},"contracts.UpdatePolicy":{"description":"UpdatePolicy is the effective, hot-reloadable update policy (Spec 092\nFR-015). Always present: the ` + "`" + `update` + "`" + ` object above is omitted both when\nupdate checking is disabled AND when no check has produced a result\nyet, so its absence cannot tell a client whether it is allowed to run\nits own (e.g. Sparkle feed) check. This field states the answer.","properties":{"channel":{"description":"Channel is the tracked release channel: \"stable\" or \"rc\".","type":"string"},"enabled":{"description":"Enabled is the effective automatic-check kill switch: update_check.enabled\nwith MCPPROXY_DISABLE_AUTO_UPDATE=true winning over it. A user-initiated\n\"Check for Updates\" stays available regardless.","type":"boolean"},"nudges_suppressed":{"description":"NudgesSuppressed asks UI surfaces to stay quiet (CI / non-interactive)\nwhile machine-readable fields keep reporting the facts.","type":"boolean"}},"type":"object"},"contracts.UpstreamError":{"properties":{"error_message":{"type":"string"},"server_name":{"type":"string"},"timestamp":{"type":"string"}},"type":"object"},"contracts.UsageAggregateResponse":{"properties":{"freshness_ms":{"description":"age of the underlying snapshot in ms","type":"integer"},"generated_at":{"type":"string"},"other":{"$ref":"#/components/schemas/contracts.UsageOtherBucket"},"timeline":{"items":{"$ref":"#/components/schemas/contracts.UsageTimeBucket"},"type":"array","uniqueItems":false},"token_source":{"description":"\"bytes\" (size-based proxy, FR-006)","type":"string"},"tokens_saved":{"description":"echoed from ServerTokenMetrics (FR-007)","type":"integer"},"tokens_saved_estimated":{"description":"TokensSavedEstimated echoes ServerTokenMetrics.Estimated (Spec 109-k):\ntrue while TokensSaved is a synthetic simulation rather than derived\nfrom a real retrieve_tools call. Dropped (false, the zero value) for a\nscoped caller along with TokensSaved itself, above.","type":"boolean"},"tokens_saved_percentage":{"type":"number"},"tools":{"items":{"$ref":"#/components/schemas/contracts.UsageToolStat"},"type":"array","uniqueItems":false},"total_calls":{"description":"TotalCalls and TotalErrors are the headline counts for the window: the sum\nof the timeline this same response carries, so the tiles and the histogram\nunder them cannot disagree. They are NOT the sum of Tools — that list is\nlifetime-cumulative, upstream-only and truncated to top-N, and summing it\nclient-side is what made the Usage tab print a third number for the same\n24 hours (audit finding F1, #1046). The population is\nstorage.CountsAsCall, shared with ActivitySummaryResponse.CallCount.\n\nTwo bounds on how exactly this matches the Activity Log's own count.\nBoth are bounded and disclosed, unlike the population mismatch they\nreplace, which was unbounded and silent:\n\n - Window granularity is the timeline's: whole hour buckets, so the span\n is the requested window rounded up to a bucket edge.\n - This response is served from a snapshot behind a short read cache\n (observability.usage_cache_ttl, 5s by default) so the endpoint never\n scans the activity log per request, while the summary endpoint counts\n live. Calls that land inside that window appear on the Activity Log\n first. FreshnessMs and GeneratedAt say how old the figures are, and\n the Usage tab prints it (\"Updated 3s ago\").","type":"integer"},"total_errors":{"type":"integer"},"window":{"type":"string"}},"type":"object"},"contracts.UsageOtherBucket":{"description":"present only when the list was truncated to top-N","properties":{"calls":{"type":"integer"},"tools_folded":{"type":"integer"},"total_resp_bytes":{"type":"integer"}},"type":"object"},"contracts.UsageTimeBucket":{"properties":{"calls":{"type":"integer"},"errors":{"type":"integer"},"start":{"type":"string"},"total_resp_bytes":{"type":"integer"}},"type":"object"},"contracts.UsageToolStat":{"properties":{"avg_req_bytes":{"description":"null when no sized request calls","type":"integer"},"avg_resp_bytes":{"description":"null when sized_calls == 0 (only legacy 0-byte calls)","type":"integer"},"blocked":{"type":"integer"},"calls":{"type":"integer"},"error_rate":{"type":"number"},"errors":{"type":"integer"},"last_used":{"type":"string"},"p50_exceeds":{"type":"boolean"},"p50_ms":{"description":"P50Ms and P95Ms are read off a fixed latency histogram, so they are BUCKET\nBOUNDS, not measured durations: the true percentile is at or below the\nvalue, and a client must render it as a bound (\"≤ 5 ms\"). P50Exceeds /\nP95Exceeds flip that reading for the unbounded overflow bucket, where the\nvalue is the last bound and the truth is above it (\"\u003e 10 s\").","type":"integer"},"p95_exceeds":{"type":"boolean"},"p95_ms":{"type":"integer"},"rejected":{"description":"spec 093: shed by a concurrency limit; never executed, so excluded from calls/latency","type":"integer"},"server":{"type":"string"},"sized_calls":{"description":"calls with known response size (basis for avg_resp_bytes)","type":"integer"},"tool":{"type":"string"},"total_req_bytes":{"type":"integer"},"total_resp_bytes":{"type":"integer"}},"type":"object"},"contracts.ValidateConfigResponse":{"properties":{"errors":{"items":{"$ref":"#/components/schemas/contracts.ValidationError"},"type":"array","uniqueItems":false},"valid":{"type":"boolean"}},"type":"object"},"contracts.ValidationError":{"properties":{"field":{"type":"string"},"message":{"type":"string"}},"type":"object"},"contracts.ViewAsCounts":{"description":"Counts is present only for a NON-administrator profile view-as (Spec 108\nFR-032): the response then lists only the visible rows, and this is the\nonly trace of the rest, with no per-server, per-tier or per-reason\nbreakdown.","properties":{"hidden":{"type":"integer"},"visible":{"type":"integer"}},"type":"object"},"contracts.WorkSession":{"properties":{"attempts":{"description":"Attempts, Failures and PolicyBlocks are lifetime counts of the session.\nPolicyBlocks are included in Failures.","type":"integer"},"client_id":{"type":"string"},"client_name":{"type":"string"},"connection_count":{"description":"Administrators only.","type":"integer"},"duration_ms":{"type":"integer"},"ended_at":{"type":"string"},"failures":{"type":"integer"},"first_failure_at":{"type":"string"},"id":{"type":"string"},"last_activity_at":{"type":"string"},"last_failure":{"$ref":"#/components/schemas/contracts.WorkSessionFailure"},"ownerless":{"type":"boolean"},"policy_blocks":{"type":"integer"},"profile":{"description":"Profile is returned to administrators only.","type":"string"},"profile_source":{"type":"string"},"project_name":{"description":"ProjectName is the basename of the client's workspace, when it\ndisclosed one.","type":"string"},"rebuilt":{"type":"boolean"},"run_name":{"type":"string"},"started_at":{"type":"string"},"status":{"description":"Status is \"active\" or \"ended\".","type":"string"},"stored_failures":{"description":"StoredFailures counts the failures whose rows are still in the log;\nit is what the timeline can navigate.","type":"integer"},"surface":{"type":"string"},"token_name":{"type":"string"},"truncated_start_at":{"type":"string"}},"type":"object"},"contracts.WorkSessionEnvelope":{"properties":{"data":{"$ref":"#/components/schemas/contracts.WorkSession"},"success":{"type":"boolean"}},"type":"object"},"contracts.WorkSessionFailure":{"properties":{"at":{"type":"string"},"error_class":{"type":"string"},"error_code":{"type":"string"},"policy_block":{"description":"PolicyBlock is true when the failure was a refusal by MCPProxy itself.","type":"boolean"},"reason":{"description":"Reason is at most 200 characters and never contains argument or\nresponse bodies.","type":"string"},"server":{"type":"string"},"tool":{"type":"string"}},"type":"object"},"contracts.WorkSessionListEnvelope":{"properties":{"data":{"$ref":"#/components/schemas/contracts.WorkSessionListResponse"},"success":{"type":"boolean"}},"type":"object"},"contracts.WorkSessionListResponse":{"properties":{"limit":{"type":"integer"},"offset":{"type":"integer"},"sessions":{"items":{"$ref":"#/components/schemas/contracts.WorkSession"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.WorkSessionTimelineEnvelope":{"properties":{"data":{"$ref":"#/components/schemas/contracts.WorkSessionTimelineResponse"},"success":{"type":"boolean"}},"type":"object"},"contracts.WorkSessionTimelineResponse":{"properties":{"earlier_failures_not_stored":{"type":"boolean"},"failure_index":{"description":"FailureIndex is the 1-based number of the failure at or before the\nposition among the stored failures in reach (0 when none), and\nFailureTotal their count.","type":"integer"},"failure_total":{"type":"integer"},"has_after":{"type":"boolean"},"has_before":{"type":"boolean"},"lifetime_failures":{"description":"LifetimeFailures is the session's lifetime failure count in reach.\nEarlierFailuresNotStored says some of them are no longer in the log.","type":"integer"},"position":{"description":"Position is the index of the row the page is positioned at; TotalRows\nis the number of rows in the caller's view.","type":"integer"},"rows":{"items":{"$ref":"#/components/schemas/contracts.WorkSessionTimelineRow"},"type":"array","uniqueItems":false},"session":{"$ref":"#/components/schemas/contracts.WorkSession"},"total_rows":{"type":"integer"}},"type":"object"},"contracts.WorkSessionTimelineRow":{"properties":{"activity":{"$ref":"#/components/schemas/contracts.ActivityRecord"},"at":{"description":"At is the time of the row.","type":"string"},"bodies_removed":{"description":"BodiesRemoved is true when retention removed the row's argument and\nresponse bodies to keep the row.","type":"boolean"},"failed":{"description":"Failed marks the counted row of a failed attempt; PolicyBlock marks a\nrefusal by MCPProxy itself.","type":"boolean"},"index":{"description":"Index is the row's position in the caller's view of the timeline.","type":"integer"},"kind":{"type":"string"},"policy_block":{"type":"boolean"},"precedes_session":{"description":"PrecedesSession marks an upstream event from before the session\nstarted: the latest event of a server the session then failed on,\nstill unresolved when the session began (release QA F2, SC-005).","type":"boolean"}},"type":"object"},"data":{"properties":{"data":{"$ref":"#/components/schemas/contracts.InfoResponse"}},"type":"object"},"httpapi.AccessExplanationData":{"properties":{"first_failure":{"type":"string","x-enum-varnames":["StepCredential","StepProfile","StepServerInScope","StepToolRule","StepTierCap","StepTokenPermission","StepGlobalGate","StepServerState","StepToolApproval"]},"fixes":{"items":{"$ref":"#/components/schemas/runtime.Fix"},"type":"array","uniqueItems":false},"profile":{"$ref":"#/components/schemas/runtime.ExplainProfileView"},"steps":{"items":{"$ref":"#/components/schemas/runtime.ExplainStepView"},"type":"array","uniqueItems":false},"subject":{"$ref":"#/components/schemas/runtime.ExplainSubjectView"},"tool":{"type":"string"},"verdict":{"$ref":"#/components/schemas/profile.ExplainVerdict"}},"type":"object"},"httpapi.AccessSuggestionsData":{"properties":{"already_fixed":{"description":"AlreadyFixed counts groups the explainer now allows (they drop out).","type":"integer"},"blocked_calls":{"description":"BlockedCalls counts every profile-refused call in the window.","type":"integer"},"non_profile_blocked":{"description":"NonProfileBlocked counts blocked calls with a cause outside profiles.","type":"integer"},"patches":{"items":{"$ref":"#/components/schemas/runtime.ProfilePatch"},"type":"array","uniqueItems":false},"profile_removed":{"description":"ProfileRemoved counts groups whose profile no longer exists (they drop out).","type":"integer"},"since":{"type":"string"},"suggestions":{"items":{"$ref":"#/components/schemas/runtime.AccessSuggestion"},"type":"array","uniqueItems":false},"unattributed":{"description":"Unattributed counts profile refusals whose record names no profile.","type":"integer"},"until":{"type":"string"},"window":{"type":"string"}},"type":"object"},"httpapi.AddServerRequest":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges is the per-server intent to auto-approve\nnew/changed tools past the trust baseline (MCP-2930). Tri-state *bool:\na nil pointer means \"leave unchanged\" on PATCH; a present value\n(including false) is applied. Mirrors config.ServerConfig's *bool\nsemantics — do NOT collapse to a plain bool, or an omitted field would\nsilently reset a previously-set value.","type":"boolean"},"command":{"type":"string"},"enabled":{"type":"boolean"},"env":{"additionalProperties":{"type":"string"},"type":"object"},"expose_prompts":{"description":"ExposePrompts is the per-server override for prompt aggregation (F9):\nwhether this server's advertised MCP prompts are merged into mcpproxy's\nprompts/list. Tri-state *bool mirroring config.ServerConfig.ExposePrompts —\na nil pointer means \"leave unchanged\" on PATCH (and \"inherit the default\naggregate behavior\" on create); a present value (including false) is applied.","type":"boolean"},"expose_skills":{"description":"ExposeSkills is the per-server skills override (MCP skills extension).\nTri-state *bool mirroring config.ServerConfig.ExposeSkills: nil means\n\"leave unchanged\" on PATCH and \"inherit\" on create.","type":"boolean"},"forward_headers":{"description":"ForwardHeaders is the per-server allowlist of inbound MCP client header\nNAMES forwarded to this server on tools/call (Spec 112). Names only, never\nvalues. On PATCH a nil slice (field omitted) leaves the stored allowlist\nunchanged and an empty array ([]) clears it. Invalid, denied, duplicate\nand static-header-colliding names are rejected with 400.","items":{"type":"string"},"type":"array","uniqueItems":false},"headers":{"additionalProperties":{"type":"string"},"type":"object"},"init_timeout":{"description":"InitTimeout is the per-server MCP ` + "`" + `initialize` + "`" + ` handshake deadline override\n(MCP-3322 / GH #760), serialized as a duration string (e.g. \"120s\"). A nil\npointer means \"leave unchanged\" on PATCH; a present value is applied.\nMirrors config.ServerConfig.InitTimeout's *Duration tri-state.","type":"string"},"isolation":{"$ref":"#/components/schemas/httpapi.IsolationRequest"},"max_concurrent_requests":{"description":"MaxConcurrentRequests / QueueSize / QueueTimeout are the per-server\nconcurrency overrides (spec 093 / GH #955, FR-020 scope (c)). Each is\ntri-state: a nil pointer means \"leave unchanged\" on PATCH and \"inherit\nserver_concurrency_defaults\" on create; an explicit 0 disables that\nsetting for this server; a positive value overrides it. Do NOT collapse\nthem to plain values — an omitted field would then silently reset a\nconfigured limit.","type":"integer"},"name":{"type":"string"},"protocol":{"type":"string"},"quarantined":{"type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_on_use":{"type":"boolean"},"tool_argument_error_mode":{"description":"Empty preserves an update; detailed explicitly resets a redacted policy.","type":"string"},"trust_mode":{"description":"TrustMode is the per-server trust tier (spec 086): \"auto\", \"scan\", or\n\"manual\". Empty means \"leave unchanged\" on PATCH (and inherit the migrated\ndefault on create). A non-empty value is applied to ServerConfig.TrustMode\nand resolved by EffectiveTrustMode (an unrecognized value fails closed to\nmanual). This is the REST seam for changing the trust tier via\nPOST/PATCH /api/v1/servers.","type":"string"},"url":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"httpapi.BindingGuardResponse":{"properties":{"bindings":{"items":{"$ref":"#/components/schemas/httpapi.GuardBinding"},"type":"array","uniqueItems":false},"code":{"description":"binding_bypassable_without_auth","type":"string"},"error":{"description":"Human-readable, byte-stable refusal text","type":"string"},"fixes":{"items":{"$ref":"#/components/schemas/httpapi.GuardFixOption"},"type":"array","uniqueItems":false},"request_id":{"type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.BulkAssignRequest":{"properties":{"from_profile":{"type":"string"},"mode":{"type":"string"},"to_profile":{"type":"string"}},"type":"object"},"httpapi.BulkAssignResponse":{"properties":{"moved":{"items":{"type":"string"},"type":"array","uniqueItems":false},"skipped":{"items":{"$ref":"#/components/schemas/httpapi.BulkAssignSkipped"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.BulkAssignSkipped":{"properties":{"client_id":{"type":"string"},"code":{"type":"string"},"error":{"type":"string"}},"type":"object"},"httpapi.BundleRollbackRefusedResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"rejection":{"$ref":"#/components/schemas/scanner.BundleRejection"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"httpapi.CanonicalConfigPath":{"properties":{"description":{"description":"Brief description","type":"string"},"exists":{"description":"Whether the file exists","type":"boolean"},"format":{"description":"Format identifier (e.g., \"claude_desktop\")","type":"string"},"name":{"description":"Display name (e.g., \"Claude Desktop\")","type":"string"},"os":{"description":"Operating system (darwin, windows, linux)","type":"string"},"path":{"description":"Full path to the config file","type":"string"}},"type":"object"},"httpapi.CanonicalConfigPathsResponse":{"properties":{"os":{"description":"Current operating system","type":"string"},"paths":{"description":"List of canonical config paths","items":{"$ref":"#/components/schemas/httpapi.CanonicalConfigPath"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ClientBindingErrorResponse":{"properties":{"code":{"type":"string"},"error":{"type":"string"},"field":{"type":"string"},"request_id":{"type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.ClientBindingResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"warnings":{"items":{"$ref":"#/components/schemas/httpapi.ClientWarning"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ClientCredential":{"properties":{"approved_at":{"type":"string"},"expires_at":{"type":"string"},"grant_id":{"description":"GrantID names a browser login.","type":"string"},"kind":{"description":"Kind is api_key or browser_login.","type":"string"},"last_used_at":{"type":"string"},"name_mismatch":{"type":"boolean"},"observed_name":{"description":"ObservedName is the name the client sent at initialize (advisory).","type":"string"},"prefix":{"type":"string"},"redirect_host":{"type":"string"},"reported_name":{"type":"string"},"state":{"description":"State is active|expired|revoked for an API key and active|lapsed|revoked\nfor a login.","type":"string"}},"type":"object"},"httpapi.ClientSnippet":{"properties":{"generic_http":{"type":"string"},"header_name":{"type":"string"}},"type":"object"},"httpapi.ClientWarning":{"properties":{"action":{"$ref":"#/components/schemas/runtime.WarningAction"},"bindings":{"items":{"$ref":"#/components/schemas/runtime.BindingRef"},"type":"array","uniqueItems":false},"client_id":{"type":"string"},"code":{"$ref":"#/components/schemas/profile.WarningCode"},"fixes":{"items":{"$ref":"#/components/schemas/runtime.GuardFix"},"type":"array","uniqueItems":false},"message":{"type":"string"},"severity":{"$ref":"#/components/schemas/profile.WarningSeverity"}},"type":"object"},"httpapi.ConnectConflictResponse":{"properties":{"action":{"description":"already_exists | precondition_failed","type":"string"},"data":{"$ref":"#/components/schemas/connect.ConnectResult"},"error":{"description":"Human-readable message","type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.ConnectRequest":{"properties":{"force":{"description":"Overwrite existing entry","type":"boolean"},"keyless":{"type":"boolean"},"mode":{"type":"string"},"precondition_token":{"description":"PreconditionToken is the opaque token from the preview this write was\nconfirmed against (Spec 091 FR-005). When present, the core rechecks it\nat write time and responds 409 with action \"precondition_failed\" —\nwriting nothing — if the config or the entry MCPProxy would write has\ndrifted since; the caller then re-previews instead of retrying. Absent\nmeans exactly the pre-091 behavior. A replace-classified flow sends this\nTOGETHER with force=true: the token, not the absence of force, is the\noverwrite safety.","type":"string"},"profile":{"description":"Profile, Mode and Keyless are the client-credential intent (Spec 108\nFR-024). Profile names the profile the client's credential binds to;\n\"\" is the built-in All servers scope. Omitted means \"not specified\": a\nfresh credential defaults to All servers and a reconnect keeps the\nclient's existing binding (a reconnect never silently widens a locked\nclient). Mode is locked|switchable (default locked for a named profile,\nswitchable for All servers). Keyless writes a credential-less entry and\nis only possible while require_mcp_auth is off; it cannot carry a\nprofile or mode.","type":"string"},"server_name":{"description":"Defaults to \"mcpproxy\"","type":"string"}},"type":"object"},"httpapi.CreateClientRequest":{"properties":{"display_name":{"type":"string"},"expires_in":{"description":"ExpiresIn is a duration like 30d or 720h; default and cap are 365 days.","type":"string"},"id":{"type":"string"},"mode":{"type":"string"},"profile":{"type":"string"},"purpose":{"description":"Purpose is the stated, unenforced task brief (Spec 115), at most 500\ncharacters; screened for secrets before anything is stored.","type":"string"}},"type":"object"},"httpapi.CreateClientResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"credential":{"type":"string"},"snippet":{"$ref":"#/components/schemas/httpapi.ClientSnippet"}},"type":"object"},"httpapi.EffectiveToolsData":{"properties":{"counts":{"$ref":"#/components/schemas/runtime.EffectiveCounts"},"profile":{"type":"string"},"stale_classification_reasons":{"additionalProperties":{"type":"string"},"description":"StaleClassificationReasons maps each stale classify entry to why it no\nlonger applies: profile.StaleClassificationAnnotated or\nprofile.StaleClassificationMissing. It is computed over the UNFILTERED\ntool set, so a server or reason filter never changes it. Administrators\nonly.","type":"object"},"stale_classifications":{"description":"StaleClassifications lists classify entries for tools that are now\nannotated or no longer exist (FR-005). Administrators only.","items":{"type":"string"},"type":"array","uniqueItems":false},"tools":{"items":{"$ref":"#/components/schemas/runtime.EffectiveTool"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.EnvFieldPreview":{"properties":{"empty_or_placeholder":{"type":"boolean"},"name":{"type":"string"},"secret_like":{"type":"boolean"},"value_present":{"type":"boolean"}},"type":"object"},"httpapi.FinalizeClientResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"rotation":{"$ref":"#/components/schemas/httpapi.RotationState"}},"type":"object"},"httpapi.ForgetClientResponse":{"properties":{"disconnect_error":{"type":"string"},"disconnected":{"type":"boolean"},"revoked":{"type":"string"}},"type":"object"},"httpapi.GuardBinding":{"properties":{"client_id":{"type":"string"},"mode":{"type":"string"},"profile":{"type":"string"},"token_name":{"type":"string"}},"type":"object"},"httpapi.GuardFixOption":{"properties":{"kind":{"type":"string"},"target":{"type":"string"}},"type":"object"},"httpapi.HeaderFieldPreview":{"properties":{"empty_or_placeholder":{"type":"boolean"},"name":{"type":"string"},"secret_like":{"type":"boolean"},"value_present":{"type":"boolean"}},"type":"object"},"httpapi.ImportFromPathRequest":{"properties":{"format":{"description":"Optional format hint","type":"string"},"path":{"description":"File path to import from","type":"string"},"rename":{"additionalProperties":{"type":"string"},"description":"Rename maps a server name → new name. Applied after parsing so the\ncaller can disambiguate cross-source name collisions (Spec 046 v2 —\ne.g. \"mcpproxy\" → \"mcpproxy_claude_code\"). Keys are matched against\neither the raw source name (OriginalName) or the sanitized name shown\nin the preview (Server.Name); these differ for names that need\nsanitizing (e.g. \"Figma Desktop\" → \"Figma_Desktop\"). Keys not present\nin the imported set are ignored.","type":"object"},"server_names":{"description":"Optional: import only these servers","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportRequest":{"properties":{"allow_paste_fallback":{"description":"AllowPasteFallback opts into detecting a bare URL or a single command\nline (FR-064) when Format/format detection would otherwise fail — see\nconfigimport.ImportOptions.AllowPasteFallback for why this must stay\nopt-in (review round 4 F-E). Only the interactive Paste tab sets this;\nevery other caller of this endpoint (the general \"Import config\"\npanel, or a direct API call) leaves it false and gets a clear\n\"unable to detect configuration format\" error for a plain one-liner\ninstead of it being silently guessed at and, on apply, added as a\nreal server with no confirmation step.","type":"boolean"},"content":{"description":"Raw JSON or TOML content","type":"string"},"env_override":{"additionalProperties":{"type":"string"},"description":"EnvOverride/HeaderOverride (Spec 109 FR-064/065, PR review round 4\nF-A/F-D fix): the Paste tab's per-field Value/Secret edits — a plain\nvalue the user typed, or a keyring ref path if they chose Secret —\nkeyed by field name. Applied to the matching imported server's\nEnv/Headers ONLY when preview=false, directly on the server this\nrequest's own raw Content parses to server-side. This is what lets\nthe apply call carry the user's edited env/header values without\never round-tripping the redacted preview: url/command/args on apply\nalways come from re-parsing Content here, never from a client-held\npreview response, so a credential embedded in a URL query param or\nargv flag (which the preview necessarily redacted for display) is\nnever overwritten with the masked placeholder.","type":"object"},"format":{"description":"Optional format hint","type":"string"},"header_override":{"additionalProperties":{"type":"string"},"type":"object"},"server_names":{"description":"Optional: import only these servers","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportResponse":{"properties":{"failed":{"items":{"$ref":"#/components/schemas/configimport.FailedServer"},"type":"array","uniqueItems":false},"format":{"type":"string"},"format_name":{"type":"string"},"imported":{"items":{"$ref":"#/components/schemas/httpapi.ImportedServerResponse"},"type":"array","uniqueItems":false},"skipped":{"items":{"$ref":"#/components/schemas/configimport.SkippedServer"},"type":"array","uniqueItems":false},"summary":{"$ref":"#/components/schemas/configimport.ImportSummary"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportedServerResponse":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"command":{"type":"string"},"env":{"items":{"$ref":"#/components/schemas/httpapi.EnvFieldPreview"},"type":"array","uniqueItems":false},"fields_skipped":{"items":{"type":"string"},"type":"array","uniqueItems":false},"headers":{"items":{"$ref":"#/components/schemas/httpapi.HeaderFieldPreview"},"type":"array","uniqueItems":false},"name":{"type":"string"},"original_name":{"type":"string"},"protocol":{"type":"string"},"source_format":{"type":"string"},"summary":{"description":"Summary, Tags, Env and Headers are the Spec 109 FR-064 preview\nenrichment (contracts/rest-api.md \"Import preview\"). Summary and Tags\nare built from the already-redacted URL/Command/Args above, so a\nsecret embedded in argv or a URL query never reaches Summary either.\nEnv/Headers never carry the raw value — only its presence and two\nbooleans a surface uses to default the Value/Secret toggle (FR-065).","type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"url":{"type":"string"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.IsolationRequest":{"description":"Isolation carries per-server Docker isolation overrides (enabled,\nmode_override, image, network_mode, extra_args, working_dir). A nil\npointer means \"do not touch isolation config\". A present object is\napplied field-by-field ON TOP of the persisted overrides, so omitting a\nfield leaves it alone; clear an individual override by sending it\nexplicitly (` + "`" + `\"enabled\": null` + "`" + `, ` + "`" + `\"image\": \"\"` + "`" + `).","properties":{"enabled":{"description":"Enabled exists ONLY to detect and reject an echoed-back read. It is the\neffective state on the read surface and is never writable; see validate().","type":"boolean"},"enabled_override":{"description":"EnabledOverride is the tri-state per-server override — the RAW value, the\nsame one reads return as ` + "`" + `enabled_override` + "`" + `. It has THREE meaningful wire\nstates, and collapsing them is what silently un-isolated servers\n(GH #1142):\n - absent → leave the persisted override untouched\n - null → clear the override, back to inheriting the global\n - true / false → set an explicit opt-in / opt-out","type":"boolean"},"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"mode_override":{"description":"ModeOverride sets ` + "`" + `isolation.mode` + "`" + ` (\"docker\" | \"sandbox\" | \"none\").\nnil leaves the persisted value alone; an empty string clears it. An\nunrecognized value is rejected with a 400 rather than persisted.","type":"string"},"network_mode":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"httpapi.OAuthApprovalBody":{"properties":{"binding_revision":{"type":"string"},"client":{"$ref":"#/components/schemas/httpapi.OAuthClientChoice"},"mode":{"type":"string"},"profile":{"type":"string"},"replace_grant":{"type":"string"}},"type":"object"},"httpapi.OAuthClientChoice":{"properties":{"id":{"type":"string"},"new":{"$ref":"#/components/schemas/httpapi.OAuthNewClient"}},"type":"object"},"httpapi.OAuthDecisionResponse":{"properties":{"redirect_url":{"type":"string"}},"type":"object"},"httpapi.OAuthNewClient":{"properties":{"display_name":{"type":"string"},"id":{"type":"string"}},"type":"object"},"httpapi.OnboardingMarkRequest":{"properties":{"connect_step_status":{"description":"ConnectStepStatus is one of: \"\", \"completed\", \"skipped\". Empty\npreserves the existing value. The stored enum is wider (Spec 080\nFR-001): a \"skipped\" request for a previously untouched connect step\nis upgraded server-side to \"completed_external\" when the install\nshows positive evidence of an external connection (Spec 080 FR-002).\n\"completed_external\" is NOT accepted from clients — it must never be\npersisted without that server-verified evidence (edge case: \"never\nguess completed_external without positive evidence\").","type":"string"},"connected_client_id":{"description":"ConnectedClientID records a successful connect write for this client id\n(Spec 109-b FR-042, review round 6). The REST connect endpoint\n(POST /api/v1/connect/{client}) already records this itself on success;\nthis field exists so ` + "`" + `mcpproxy connect` + "`" + ` — which writes the client's\nconfig file directly, without going through that endpoint, so the\ncommand still works when no daemon is running — can relay the same\nevent to a daemon that IS running, keeping ClientConnectedAt in sync\nacross both surfaces. Must be a known id from the fixed connect client\nregistry (internal/connect.GetAllClients); any other value is rejected,\nmatching the field's \"bounded by the registry\" invariant\n(data-model.md §7).","type":"string"},"disconnected_client_id":{"description":"DisconnectedClientID relays a successful local CLI disconnect to a running\ndaemon, which cannot observe the CLI's direct config-file edit itself.\nLike ConnectedClientID, it is bounded to the fixed client registry.","type":"string"},"engaged":{"description":"Engaged marks the wizard as engaged (completed or explicitly skipped).\nOnce true, the wizard does not auto-show again.","type":"boolean"},"mark_shown":{"description":"MarkShown records the wizard's first display time if not already set.","type":"boolean"},"server_step_status":{"description":"ServerStepStatus is one of: \"\", \"completed\", \"skipped\". Empty\npreserves the existing value.","type":"string"}},"type":"object"},"httpapi.OnboardingStateResponse":{"properties":{"configured_server_count":{"description":"ConfiguredServerCount is the number of upstream MCP servers configured\nin mcpproxy (counts both enabled and disabled).","type":"integer"},"connected_client_count":{"description":"ConnectedClientCount is the number of supported clients currently\npointing at mcpproxy.","type":"integer"},"connected_client_ids":{"description":"ConnectedClientIDs are the identifiers of supported clients currently\npointing at mcpproxy. Drawn exclusively from the fixed adapter table —\nuser-entered values never appear here.","items":{"type":"string"},"type":"array","uniqueItems":false},"first_mcp_client_ever":{"description":"FirstMCPClientEver is true once any MCP client has successfully completed\nan ` + "`" + `initialize` + "`" + ` round-trip with this mcpproxy. Sourced from the Spec 044\nactivation bucket. Drives the Verify tab's \"green check\" state.","type":"boolean"},"has_configured_server":{"description":"HasConfiguredServer is true if at least one upstream MCP server is\nconfigured (regardless of current connection health).","type":"boolean"},"has_connected_client":{"description":"HasConnectedClient is true if at least one supported AI client currently\nhas mcpproxy registered in its config.","type":"boolean"},"has_usable_server":{"description":"HasUsableServer is true once at least one enabled, non-quarantined\nserver has usable health and at least one approved (non-disabled) tool.\nThis is the real \"the wizard has something to try\" signal:\nHasConfiguredServer only means a server entry exists, even while every\none of them sits quarantined, requires sign-in, or has zero approved\ntools. The Servers step and Setup badge use this instead of\nHasConfiguredServer, which is kept above for compatibility.\nHealthStatus.Usable is the shared\nreadiness contract used by every UI surface (Spec 109-c, tasks.md T051).","type":"boolean"},"incomplete_tab_count":{"description":"IncompleteTabCount is the number of wizard tabs whose state is incomplete.\nDrives the sidebar Setup entry's badge. Formula:\n +1 if HasConnectedClient == false\n +1 if HasUsableServer == false\n +1 if FirstMCPClientEver == false","type":"integer"},"mcp_clients_seen_ever":{"description":"MCPClientsSeenEver is the capped list of recognized client names that\nhave ever called this mcpproxy. Names come from the MCP ` + "`" + `initialize` + "`" + `\npayload's ` + "`" + `clientInfo.name` + "`" + ` field, sanitized. Surfaces on the Verify tab\nso the user can see whether their real IDE — not a test client — has\nconnected.","items":{"type":"string"},"type":"array","uniqueItems":false},"should_show_wizard":{"description":"ShouldShowWizard is the derived flag the frontend uses to decide\nwhether to auto-show. True when not engaged and IncompleteTabCount \u003e 0\n(Spec 046 v2 — semantics widened to also count the Verify tab).","type":"boolean"},"state":{"$ref":"#/components/schemas/storage.OnboardingState"},"usable_servers":{"description":"UsableServers lists the names behind HasUsableServer, for the Verify\nstep's suggested-prompt generator (FR-042): prompts are only built from\ntools of servers in this list, never from a quarantined or toolless one.","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileConflictResponse":{"properties":{"code":{"type":"string"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"description":"Always false","type":"boolean"},"used_by":{"$ref":"#/components/schemas/httpapi.ProfileUsedByData"}},"type":"object"},"httpapi.ProfileDeleteData":{"properties":{"anonymous_profile_moved_to":{"type":"string"},"deleted":{"type":"string"},"moved":{"$ref":"#/components/schemas/runtime.MovedRefs"}},"type":"object"},"httpapi.ProfileListData":{"properties":{"anonymous_profile":{"type":"string"},"profiles":{"items":{"$ref":"#/components/schemas/runtime.ProfileView"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileRenameData":{"properties":{"moved":{"$ref":"#/components/schemas/runtime.MovedRefs"},"profile":{"$ref":"#/components/schemas/runtime.ProfileView"}},"type":"object"},"httpapi.ProfileTryData":{"properties":{"hidden":{"items":{"$ref":"#/components/schemas/runtime.TryHidden"},"type":"array","uniqueItems":false},"hidden_by_profile":{"type":"integer"},"hidden_truncated":{"type":"boolean"},"results":{"items":{"additionalProperties":{},"type":"object"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileUsedByData":{"properties":{"anonymous_profile":{"type":"boolean"},"clients":{"items":{"$ref":"#/components/schemas/runtime.UsedByClient"},"type":"array","uniqueItems":false},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileViewData":{"properties":{"blocked_24h":{"type":"integer"},"calls_24h":{"type":"integer"},"code_execution":{"type":"boolean"},"description":{"type":"string"},"effective_code_execution":{"type":"boolean"},"effective_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"effective_unannotated":{"type":"string"},"is_legacy":{"type":"boolean"},"management_tools":{"type":"boolean"},"max_tier":{"type":"string"},"name":{"type":"string"},"servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"switchable_to":{"items":{"type":"string"},"type":"array","uniqueItems":false},"title":{"type":"string"},"tool_count":{"description":"ToolCount is the v2 field: indexed tools on the effective servers.\nDeprecated: use tool_counts.","type":"integer"},"tool_counts":{"$ref":"#/components/schemas/runtime.ToolCounts"},"tools":{"$ref":"#/components/schemas/config.ProfileToolRules"},"unannotated":{"type":"string"},"used_by":{"$ref":"#/components/schemas/runtime.UsedBy"}},"type":"object"},"httpapi.ProfileWriteData":{"properties":{"profile":{"$ref":"#/components/schemas/runtime.ProfileView"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.PutClientBindingRequest":{"properties":{"mode":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.RenameProfileRequest":{"properties":{"new_name":{"type":"string"}},"type":"object"},"httpapi.RevokeCredentialResponse":{"properties":{"changed":{"type":"boolean"}},"type":"object"},"httpapi.RotateClientRequest":{"properties":{"precondition_token":{"description":"PreconditionToken is the token of GET /connect/{client}/preview; it\nbinds a supported client's rotation to what the preview showed.","type":"string"}},"type":"object"},"httpapi.RotateClientResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"connect":{"$ref":"#/components/schemas/connect.ConnectResult"},"credential":{"type":"string"},"rotation":{"$ref":"#/components/schemas/httpapi.RotationState"},"snippet":{"$ref":"#/components/schemas/httpapi.ClientSnippet"}},"type":"object"},"httpapi.RotationState":{"properties":{"state":{"type":"string"}},"type":"object"},"httpapi.SetActiveProfileRequest":{"properties":{"active_profile":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.StaleReviewErrorResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"stale_tools":{"$ref":"#/components/schemas/httpapi.StaleToolsDetail"},"success":{"type":"boolean"}},"type":"object"},"httpapi.StaleToolsDetail":{"properties":{"changed":{"items":{"type":"string"},"type":"array","uniqueItems":false},"missing_blocks":{"items":{"type":"string"},"type":"array","uniqueItems":false},"unreviewed":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.TryProfileRequest":{"properties":{"limit":{"type":"integer"},"profile":{"$ref":"#/components/schemas/config.ProfileConfig"},"query":{"type":"string"}},"type":"object"},"httpapi.UndoConnectRequest":{"properties":{"backup_name":{"description":"BackupName is the bare filename (filepath.Base) of the backup returned as\nbackup_path by the preceding connect — a name, never a path. Undo resolves\nthe full path server-side by joining it with the client's own config\ndirectory, so a client-supplied value can never contribute a directory\ncomponent (traversal is impossible by construction). Empty means the\nconnect created the file (no prior file existed), so undo removes it.","type":"string"},"server_name":{"description":"Defaults to \"mcpproxy\"","type":"string"}},"type":"object"},"httpapi.UpdateFailureRequest":{"properties":{"stage":{"description":"Stage is the failure stage of the update session.","enum":["appcast","download","install","other"],"type":"string"}},"type":"object"},"httpapi.UpgradeAdminKeyHoldersRequest":{"properties":{"apply":{"type":"boolean"},"mode":{"type":"string"},"precondition_token":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.approveToolsRequest":{"properties":{"approve_all":{"type":"boolean"},"expected_hashes":{"additionalProperties":{"type":"string"},"description":"ExpectedHashes binds the approval to the reviewed definitions (Spec\n117 PR-2, #1566): tool name -\u003e the review's current_hash. Absent or\nnull is an unbound (legacy) request; {} is bound.","type":["object","null"]},"expected_incarnation":{"description":"ExpectedIncarnation binds the approval to the server the client\nreviewed (Spec 116 FR-017); 409 server_replaced on a mismatch. It is\nindependent of ExpectedHashes and the two may be sent together.","type":"integer"},"tools":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.attentionResponse":{"properties":{"count":{"type":"integer"},"generated_at":{"type":"string"},"items":{"items":{"$ref":"#/components/schemas/contracts.AttentionItem"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.bundleRollbackRequest":{"properties":{"digest":{"description":"Digest is the full 64-character lowercase hex SHA-256 of the target.","type":"string"},"embedded":{"description":"Embedded rolls back to the corpus compiled into this binary.","type":"boolean"},"path":{"description":"Path is where to find the target bundle (a hint only).","type":"string"}},"type":"object"},"httpapi.clientPresence":{"properties":{"active_sessions":{"type":"integer"},"blocked_24h":{"type":"integer"},"browser_login_disabled":{"type":"boolean"},"calls_24h":{"type":"integer"},"config_path":{"type":"string"},"connected":{"type":"boolean"},"connection_unverified":{"type":"boolean"},"credential_checked_at":{"type":"string"},"credential_state":{"$ref":"#/components/schemas/profile.CredentialState"},"credentials":{"description":"Spec 132: the client's credentials (API key and browser logins) and\nwhether browser login is off right now. Both exist only once browser\nlogin was used on this install; until then a row is exactly what it was.","items":{"$ref":"#/components/schemas/httpapi.ClientCredential"},"type":"array","uniqueItems":false},"display_name":{"type":"string"},"display_path":{"type":"string"},"expires_at":{"type":"string"},"icon":{"type":"string"},"id":{"type":"string"},"installed":{"type":"boolean"},"issuer":{"$ref":"#/components/schemas/auth.CredentialIssuer"},"kind":{"type":"string"},"last_seen":{"type":"string"},"lease":{"type":"boolean"},"profile":{"type":"string"},"profile_missing":{"type":"boolean"},"profile_mode":{"type":"string"},"profile_source":{"description":"profile_source is pin (locked) or binding (switchable) and is empty when\ncredential_state is not client.","type":"string"},"profile_state":{"type":"string"},"profile_title":{"type":"string"},"purpose":{"type":"string"},"reload_hint":{"type":"string"},"revoked_at":{"description":"Spec 115 lifecycle fields of the client's credential record (additive):\nwhen it was revoked, who issued it, its stated (unenforced) purpose,\nwhether it is a task lease (lifetime at issue \u003c= 24h) and whether its\nprofile still exists (ok | dangling | none).","type":"string"},"rotation_pending":{"type":"boolean"},"sessions":{"items":{"$ref":"#/components/schemas/httpapi.clientSession"},"type":"array","uniqueItems":false},"state":{"type":"string"},"token_name":{"type":"string"}},"type":"object"},"httpapi.clientSession":{"properties":{"id":{"type":"string"},"last_activity":{"type":"string"},"profile":{"description":"Profile and ProfileSource are the session's latest effective resolution\n(Spec 108-e FR-033); empty on legacy sessions.","type":"string"},"profile_source":{"type":"string"},"started_at":{"type":"string"},"work_session_id":{"type":"string"}},"type":"object"},"httpapi.clientsResponse":{"properties":{"clients":{"items":{"$ref":"#/components/schemas/httpapi.clientPresence"},"type":"array","uniqueItems":false},"routing":{},"warnings":{"items":{"$ref":"#/components/schemas/httpapi.ClientWarning"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.expectedIncarnationBody":{"properties":{"expected_incarnation":{"type":"integer"}},"type":"object"},"httpapi.securityApproveRequest":{"properties":{"block":{"items":{"type":"string"},"type":"array","uniqueItems":false},"expected_hashes":{"additionalProperties":{"type":"string"},"description":"ExpectedHashes binds the approval to the reviewed definitions (Spec\n117 PR-2, #1566): tool name -\u003e the review's current_hash. Absent or\nnull is an unbound (legacy) request; {} binds to the empty snapshot.\nIndependent of ExpectedIncarnation: a request may carry both, and the\ntwo refusals stay distinct (review_out_of_date vs server_replaced).","type":["object","null"]},"expected_incarnation":{"description":"ExpectedIncarnation binds the approval to the server the client\nreviewed (Spec 116 FR-017): a remove and re-add since then is refused\nwith 409 server_replaced and the replacement stays quarantined.","type":"integer"},"force":{"type":"boolean"}},"type":"object"},"management.BulkOperationResult":{"properties":{"errors":{"additionalProperties":{"type":"string"},"description":"Map of server name to error message","type":"object"},"failed":{"description":"Number of failed operations","type":"integer"},"successful":{"description":"Number of successful operations","type":"integer"},"total":{"description":"Total servers processed","type":"integer"}},"type":"object"},"observability.HealthResponse":{"properties":{"components":{"items":{"$ref":"#/components/schemas/observability.HealthStatus"},"type":"array","uniqueItems":false},"status":{"description":"\"healthy\" or \"unhealthy\"","type":"string"},"timestamp":{"type":"string"}},"type":"object"},"observability.HealthStatus":{"properties":{"error":{"type":"string"},"latency":{"type":"string"},"name":{"type":"string"},"status":{"description":"\"healthy\" or \"unhealthy\"","type":"string"}},"type":"object"},"observability.ReadinessResponse":{"properties":{"components":{"items":{"$ref":"#/components/schemas/observability.HealthStatus"},"type":"array","uniqueItems":false},"status":{"description":"\"ready\" or \"not_ready\"","type":"string"},"timestamp":{"type":"string"}},"type":"object"},"profile.AccessStepStatus":{"type":"string","x-enum-varnames":["AccessStepPass","AccessStepFail","AccessStepSkip"]},"profile.AccessSubjectKind":{"type":"string","x-enum-varnames":["AccessSubjectClient","AccessSubjectProfile","AccessSubjectToken","AccessSubjectAnonymous"]},"profile.BlockReason":{"type":"string","x-enum-varnames":["BlockReasonTier","BlockReasonRule","BlockReasonUnannotated","BlockReasonCodeExecution","BlockReasonManagement","BlockReasonServerScope"]},"profile.CredentialState":{"description":"Spec 108-f ClientView additions (data-model §7). The Spec 109 fields above\nare unchanged; everything below is additive.\n\ncredential_state is what the client's connection carries (client |\nadmin_key | none | revoked | expired | unknown). The stat-only list never\nreads a config: it reports the token store, else the last on-demand\nobservation (credential_checked_at says when), else unknown.","type":"string","x-enum-varnames":["CredentialStateClient","CredentialStateAdminKey","CredentialStateNone","CredentialStateRevoked","CredentialStateExpired","CredentialStateUnknown"]},"profile.ExplainStep":{"type":"string","x-enum-varnames":["StepCredential","StepProfile","StepServerInScope","StepToolRule","StepTierCap","StepTokenPermission","StepGlobalGate","StepServerState","StepToolApproval"]},"profile.ExplainVerdict":{"type":"string","x-enum-varnames":["ExplainVerdictAllowed","ExplainVerdictBlocked","ExplainVerdictHidden"]},"profile.FixAction":{"type":"string","x-enum-varnames":["FixAllowInProfile","FixClassifyInProfile","FixAddServerToProfile","FixMoveClient","FixEditToken","FixEnableServer","FixApproveTool","FixChangeSetting","FixReconnectClient"]},"profile.WarningCode":{"type":"string","x-enum-varnames":["WarningAnonymousDeniedByBindingGuard","WarningClientHoldsAdminKey","WarningClientCredentialExpiring","WarningClientRotationPending","WarningProfileMissing","WarningClientTokenNameConflict"]},"profile.WarningSeverity":{"type":"string","x-enum-varnames":["WarningSeverityWarn","WarningSeverityInfo"]},"runtime.AccessSuggestion":{"properties":{"block_reason":{"$ref":"#/components/schemas/profile.BlockReason"},"clients":{"items":{"type":"string"},"type":"array","uniqueItems":false},"count":{"type":"integer"},"first_seen":{"type":"string"},"fixes":{"description":"Fixes are the access explainer's remediations of the first failing step,\nin preference order. Empty for a deny rule and for the built-in tools.","items":{"$ref":"#/components/schemas/runtime.Fix"},"type":"array","uniqueItems":false},"last_seen":{"type":"string"},"needs_input":{"description":"NeedsInput names what a person must supply before a change is\napply-ready (classify: \"tier\").","items":{"type":"string"},"type":"array","uniqueItems":false},"note":{"type":"string"},"profile":{"type":"string"},"server":{"type":"string"},"suggestion":{"$ref":"#/components/schemas/runtime.SuggestionKind"},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false},"tool":{"description":"\"server:tool\", or the built-in name","type":"string"},"warning":{"description":"Warning is set for profile_code_execution and profile_management: both\nchange what a profile can do beyond tool access.","type":"string"}},"type":"object"},"runtime.BindingRef":{"properties":{"client_id":{"type":"string"},"mode":{"type":"string"},"profile":{"type":"string"},"token_name":{"type":"string"}},"type":"object"},"runtime.EffectiveCounts":{"properties":{"by_reason":{"additionalProperties":{"type":"integer"},"type":"object"},"callable":{"type":"integer"},"hidden":{"type":"integer"},"visible":{"type":"integer"}},"type":"object"},"runtime.EffectiveTool":{"properties":{"access":{"$ref":"#/components/schemas/runtime.ToolAccessView"},"classification_stale":{"type":"boolean"},"intrinsic_tier":{"type":"string"},"profile_tier":{"type":"string"},"server":{"type":"string"},"tool":{"type":"string"}},"type":"object"},"runtime.ExplainProfileView":{"properties":{"name":{"type":"string"},"source":{"type":"string"}},"type":"object"},"runtime.ExplainStepView":{"properties":{"detail":{"type":"string"},"status":{"$ref":"#/components/schemas/profile.AccessStepStatus"},"step":{"$ref":"#/components/schemas/profile.ExplainStep"}},"type":"object"},"runtime.ExplainSubjectView":{"properties":{"kind":{"$ref":"#/components/schemas/profile.AccessSubjectKind"},"name":{"type":"string"}},"type":"object"},"runtime.Fix":{"properties":{"action":{"$ref":"#/components/schemas/profile.FixAction"},"label":{"type":"string"},"profile":{"description":"Profile is set for move_client only: the destination profile slug the fix\nmoves the client to. Target stays the client id (UIs navigate by it) and\nLabel carries the title, so neither can name the slug.","type":"string"},"step":{"type":"string","x-enum-varnames":["StepCredential","StepProfile","StepServerInScope","StepToolRule","StepTierCap","StepTokenPermission","StepGlobalGate","StepServerState","StepToolApproval"]},"target":{"type":"string"}},"type":"object"},"runtime.GuardFix":{"properties":{"kind":{"type":"string"},"target":{"type":"string"}},"type":"object"},"runtime.MovedRefs":{"properties":{"clients":{"items":{"type":"string"},"type":"array","uniqueItems":false},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"runtime.ProfilePatch":{"properties":{"changes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"profile":{"type":"string"},"proposed":{"$ref":"#/components/schemas/config.ProfileConfig"}},"type":"object"},"runtime.ProfileView":{"properties":{"blocked_24h":{"type":"integer"},"calls_24h":{"type":"integer"},"code_execution":{"type":"boolean"},"description":{"type":"string"},"effective_code_execution":{"type":"boolean"},"effective_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"effective_unannotated":{"type":"string"},"is_legacy":{"type":"boolean"},"management_tools":{"type":"boolean"},"max_tier":{"type":"string"},"name":{"type":"string"},"servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"switchable_to":{"items":{"type":"string"},"type":"array","uniqueItems":false},"title":{"type":"string"},"tool_count":{"description":"ToolCount is the v2 field: indexed tools on the effective servers.\nDeprecated: use tool_counts.","type":"integer"},"tool_counts":{"$ref":"#/components/schemas/runtime.ToolCounts"},"tools":{"$ref":"#/components/schemas/config.ProfileToolRules"},"unannotated":{"type":"string"},"used_by":{"$ref":"#/components/schemas/runtime.UsedBy"}},"type":"object"},"runtime.SuggestionKind":{"type":"string","x-enum-varnames":["SuggestAllow","SuggestAddServer","SuggestClassify","SuggestNone"]},"runtime.ToolAccessView":{"properties":{"callable":{"type":"boolean"},"reason":{"type":"string"},"visible":{"type":"boolean"}},"type":"object"},"runtime.ToolCounts":{"properties":{"destructive":{"type":"integer"},"read":{"type":"integer"},"unannotated_hidden":{"type":"integer"},"write":{"type":"integer"}},"type":"object"},"runtime.TryHidden":{"properties":{"reason":{"type":"string"},"server":{"type":"string"},"tool":{"type":"string"}},"type":"object"},"runtime.UsedBy":{"properties":{"anonymous_profile":{"type":"boolean"},"clients":{"items":{"$ref":"#/components/schemas/runtime.UsedByClient"},"type":"array","uniqueItems":false},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"runtime.UsedByClient":{"properties":{"id":{"type":"string"},"mode":{"type":"string"}},"type":"object"},"runtime.WarningAction":{"properties":{"kind":{"type":"string"},"target":{"type":"string"}},"type":"object"},"scanner.BundleInfo":{"properties":{"authority":{"description":"Authority is the signing root serving this bundle: \"publisher\" (the\nembedded default, or verified against a publisher key), \"operator\", or \"\"\nfor an unsigned external bundle.","type":"string"},"bundle_version":{"description":"BundleVersion / SchemaVersion are the corpus's own declared versions.","type":"string"},"coverage_degraded":{"description":"CoverageDegraded suspends scan-mode auto-approval; DegradedReason says\nwhy (one of the Degraded* constants).","type":"boolean"},"declared_skipped":{"type":"integer"},"degraded_reason":{"type":"string"},"fingerprint":{"description":"Fingerprint is the first 12 hex chars of the SHA-256 of the corpus bytes:\na stable identity an operator (or automation) can compare across hosts\nwithout shipping the whole file around.","type":"string"},"full_digest":{"description":"FullDigest is the complete lowercase-hex SHA-256 of the bundle bytes —\nthe ONLY value rollback accepts (FR-010). Fingerprint stays the 12-hex\nhuman label beside it.","type":"string"},"generated_at":{"description":"GeneratedAt is the corpus freshness stamp. It is the bundle's own\n` + "`" + `generated_at` + "`" + ` key when present; for a file-sourced bundle without one it\nfalls back to the file's modification time, so a years-stale corpus is\ndistinguishable from a fresh export.","type":"string"},"last_activated_at":{"description":"LastActivatedAt is when the serving external bundle was activated; nil\nfor the embedded default.","type":"string"},"last_checked_at":{"description":"LastCheckedAt is the end of the most recent pipeline run, including\nno-op runs the idempotence short-circuit skipped.","type":"string"},"last_rejection":{"$ref":"#/components/schemas/scanner.BundleRejection"},"load_error":{"description":"LoadError is the reason the LAST configured-path load failed, if any. The\npreviously active (or embedded) corpus stays live — a bundle problem must\nnever leave the scanner with no signatures — but the failure is surfaced\nhere rather than swallowed.","type":"string"},"loaded_at":{"description":"LoadedAt is when this corpus became active in this process.","type":"string"},"path":{"description":"Path is the configured filesystem path, when Source is \"file\".","type":"string"},"pinned":{"description":"Pinned is true while an operator rollback pin governs activation.","type":"boolean"},"refresh":{"$ref":"#/components/schemas/scanner.BundleRefreshStatus"},"reprotect":{"$ref":"#/components/schemas/scanner.BundleReprotectStatus"},"rollback":{"description":"Rollback is true when the active bundle was activated by an explicit\nrollback.","type":"boolean"},"runnable_rules":{"description":"RunnableRules is how many rules are LIVE in the offline tier; SkippedRules\nand DeclaredSkipped are the not-runnable / bundle-declared-skipped\nremainder (FR-006/FR-007) — un-evaluated coverage, never clean coverage.","type":"integer"},"schema_version":{"type":"string"},"sequence":{"description":"Sequence is the manifest sequence as published (decimal string), \"\" when\nthe bundle carries none.","type":"string"},"signature_count":{"description":"SignatureCount is the bundle's self-declared signature count.","type":"integer"},"signature_verified":{"description":"SignatureVerified reports whether the active bundle's detached signature\nverified. Always false for the embedded default (it is binary-trusted).","type":"boolean"},"skipped_rules":{"type":"integer"},"source":{"description":"Source is BundleSourceEmbedded, BundleSourceFile or BundleSourceFetch.","type":"string"},"stale":{"description":"Stale and StaleAfterDays are computed at read time next to\nStalenessDays; a future generated_at is never stale. StaleAfterDays nil\nmeans the flag is not evaluated.","type":"boolean"},"stale_after_days":{"type":"integer"},"staleness_days":{"description":"StalenessDays is the whole days since GeneratedAt (nil when unknown).","type":"integer"},"trust_epoch":{"description":"TrustEpoch is the epoch the bundle was published under.","type":"integer"}},"type":"object"},"scanner.BundleRefreshStatus":{"description":"Refresh is the refresh-cycle status (nil before any cycle or setting is\nknown). Reprotect is the post-activation re-protection sweep status,\nset from the server through SetReprotectStatus.","properties":{"consecutive_failures":{"type":"integer"},"fetch_enabled":{"type":"boolean"},"fetch_host":{"description":"FetchHost is the host of the configured fetch URL (\"\" when none).","type":"string"},"fetch_reason":{"type":"string"},"fetch_state":{"description":"FetchState and FetchReason are the fetch leg's own last answer (one of the\nRefreshOutcome* values and its reason), kept apart from LastOutcome: a file\nactivation owns the merged cycle outcome but must not hide a fetch leg that\ncannot run (B16 warning 3).","type":"string"},"interval_seconds":{"type":"integer"},"last_attempt_at":{"type":"string"},"last_outcome":{"type":"string"},"last_reason":{"type":"string"},"last_trigger":{"description":"LastTrigger, LastOutcome and LastReason use the closed vocabularies above.","type":"string"},"next_check_at":{"type":"string"}},"type":"object"},"scanner.BundleRejection":{"description":"LastRejection is the most recent refused candidate. It is retained\nacross a later successful load so \"what did it refuse, and when\"\nsurvives.","properties":{"at":{"type":"string"},"detail":{"description":"Detail is a short human string (which ceiling, which key id, which\nepoch, the bundlesig contract code). Never parsed.","type":"string"},"reason":{"description":"Reason is one of the Reject* constants; the only field to branch on.","type":"string"}},"type":"object"},"scanner.BundleReprotectStatus":{"properties":{"last_completed_at":{"type":"string"},"reason":{"description":"Reason qualifies suspended and failed (for example\nReprotectReasonAutoBaselineScanOff).","type":"string"},"servers_scanned":{"type":"integer"},"servers_with_hits":{"type":"integer"},"state":{"description":"State is one of the ReprotectState* constants.","type":"string"}},"type":"object"},"secureenv.EnvConfig":{"description":"Environment configuration for secure variable filtering","properties":{"allowed_system_vars":{"items":{"type":"string"},"type":"array","uniqueItems":false},"custom_vars":{"additionalProperties":{"type":"string"},"type":"object"},"enhance_path":{"description":"Enable PATH enhancement for Launchd scenarios","type":"boolean"},"forward_proxy_env":{"description":"ForwardProxyEnv opts in to forwarding the ambient HTTP(S)/ALL/NO/FTP proxy\nenvironment variables to spawned upstream servers (MCP-2769). It is OFF by\ndefault and deliberately kept out of the AllowedSystemVars default list:\nproxy URLs frequently carry credentials (http://user:pass@proxy), so\nforwarding them to every stdio upstream is a credential-leak risk. When\nenabled, values are forwarded with their userinfo (credentials) redacted.","type":"boolean"},"inherit_system_safe":{"type":"boolean"}},"type":"object"},"storage.ClientCredentialObservation":{"properties":{"at":{"type":"string"},"state":{"type":"string"}},"type":"object"},"storage.OnboardingState":{"description":"State is the persisted wizard engagement record. Engaged is true once\nthe wizard was shown and the user completed or skipped it.","properties":{"client_connected_at":{"additionalProperties":{"type":"string"},"description":"ClientConnectedAt records, per client id from the fixed connect client\nregistry (internal/connect.GetAllClients — never user input), the last\ntime a connect write succeeded for that client (Spec 109-b FR-042).\nWritten by the connect success path through UpdateOnboardingState so a\nconcurrent onboarding/mark write can never drop it. Consumed by the\nVerify step / presence layer to tell \"connected, never seen\" apart from\n\"connected seconds ago, hasn't reconnected yet\".","type":"object"},"client_credential_observed":{"additionalProperties":{"$ref":"#/components/schemas/storage.ClientCredentialObservation"},"description":"ClientCredentialObserved records, per client id, the LAST credential\nclassification an on-demand read produced (Spec 108-f FR-025, F11): what\nthe client's config held (client | admin_key | none | revoked | expired)\nand when it was read. The stat-only GET /clients listing never reads a\nconfig (Spec 075: no macOS App-Data prompt from a list), so this is how\nit still reports a client that holds the admin key across restarts. It is\nwritten only when the classification CHANGES, by every on-demand read\n(GET /clients/{id}, GET /connect/{client}, the admin-key upgrade preview,\na connect write) and deleted on disconnect. Additive: an older binary\nignores it, and a record without it reads as \"unknown\".","type":"object"},"client_disconnected_at":{"additionalProperties":{"type":"string"},"type":"object"},"client_last_seen":{"additionalProperties":{"type":"string"},"description":"ClientLastSeen records the latest MCP initialize for a recognised client\nalias. It is intentionally kept with onboarding state: presence is a\nlocal UI concern and must still work when telemetry is disabled.","type":"object"},"connect_step_status":{"description":"ConnectStepStatus is one of: \"\", \"completed\", \"completed_external\",\n\"skipped\" (Spec 080 FR-001). \"completed_external\" records a dismissal\nwhere the connect step was untouched but the install was already\nconnected outside the wizard (CLI, ConnectModal, manual config).","type":"string"},"engaged":{"description":"Engaged is true once the wizard was shown and the user completed or\nskipped it. Once true, the wizard does not auto-show again, even if\nstate regresses (e.g. user disconnects all clients).","type":"boolean"},"engaged_at":{"description":"EngagedAt is the timestamp of completion or explicit skip.","type":"string"},"first_shown_at":{"description":"FirstShownAt is the timestamp of first wizard render.","type":"string"},"server_step_status":{"description":"ServerStepStatus is one of: \"\", \"completed\", \"skipped\".","type":"string"}},"type":"object"},"telemetry.DiagnosticsCounters":{"properties":{"current_error_codes":{"additionalProperties":{"type":"integer"},"description":"CurrentErrorCodes is the STANDING state at heartbeat time: stable MCPX_\ncode -\u003e number of configured servers currently in that state. It is not\na counter and is never persisted — it is recomputed each heartbeat from\nthe supervisor's live stateview.\n\nSchema v11 (MCP-2967). It exists because error_code_counts_24h became\nedge-triggered in the same change: previously the supervisor re-counted\nevery standing failure on its 30s reconcile ticker, so a parked install\ninflated the counter by ~2880/day/server. Edge-triggering alone would\nhave swung the error to the other side — the 24h window decays, this\nstruct is omitempty via isZero(), so a permanently broken install would\nemit once and then disappear from the payload entirely, and absent reads\nas zero. The two fields answer different questions and are only correct\ntogether: \"how often did something newly break\" and \"how many servers\nare broken right now\".\n\nSafe: only MCPX_* enum constants as keys, never server names, URLs,\ncommands, or free text; values are non-negative server counts.","type":"object"},"error_code_counts_24h":{"additionalProperties":{"type":"integer"},"description":"ErrorCodeCounts24h maps stable MCPX_ code strings to 24h occurrence counts.\nSafe: only MCPX_* enum constants are stored here, never free text, paths,\nserver names, or user-entered values.","type":"object"},"fix_attempted_24h":{"description":"FixAttempted24h counts POST /api/v1/diagnostics/fix calls in the last 24h.","type":"integer"},"fix_succeeded_24h":{"description":"FixSucceeded24h counts fix invocations with outcome=\"success\" in the last 24h.","type":"integer"},"unique_codes_ever":{"description":"UniqueCodesEver is the cardinality of the all-time error code set.\nBounded by the MCPX_ catalog size (~30 codes), never approaches PII risk.","type":"integer"}},"type":"object"},"telemetry.FeedbackContext":{"properties":{"anonymous_id":{"description":"AnonymousID is the install's telemetry anonymous ID (heartbeat value).","type":"string"},"arch":{"type":"string"},"connected_server_count":{"type":"integer"},"diagnostics":{"$ref":"#/components/schemas/telemetry.DiagnosticsCounters"},"edition":{"type":"string"},"go_version":{"type":"string"},"last_error_code":{"description":"LastErrorCode is the most recent MCPX_* error code.","type":"string"},"last_startup_outcome":{"description":"LastStartupOutcome is the previous startup's outcome word.","type":"string"},"machine_id":{"description":"MachineID is the hashed machine identifier (heartbeat value).","type":"string"},"os":{"type":"string"},"previous_shutdown":{"description":"PreviousShutdown is how the previous run ended (clean, crash, ...).","type":"string"},"routing_mode":{"type":"string"},"server_count":{"type":"integer"},"tool_count":{"type":"integer"},"uptime_minutes":{"description":"UptimeMinutes is the daemon's uptime. Omitted from short-lived CLI\nsubmissions, where the process uptime says nothing about the daemon.","type":"integer"},"version":{"type":"string"}},"type":"object"},"telemetry.FeedbackRequest":{"properties":{"category":{"description":"bug, feature, other","type":"string"},"context":{"$ref":"#/components/schemas/telemetry.FeedbackContext"},"email":{"type":"string"},"message":{"type":"string"}},"type":"object"},"telemetry.FeedbackResponse":{"properties":{"error":{"type":"string"},"issue_url":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}},"securitySchemes":{"ApiKeyAuth":{"description":"API key authentication via query parameter. Use ?apikey=your-key","in":"query","name":"apikey","type":"apiKey"}}}, + "components": {"schemas":{"auth.CredentialIssuer":{"properties":{"actor_kind":{"type":"string"},"actor_name":{"type":"string"},"surface":{"type":"string"}},"type":"object"},"config.AgentTokenRateLimit":{"description":"AgentTokenRateLimit caps how many upstream tool calls ONE agent token may\nmake: PerMinute on average, Burst at once (issue #1699). Every token is\ncounted separately, and a token's own rate_limit (set when it is created)\nreplaces this default for that token. Only agent-token callers are\nlimited; the admin API key, the unix socket and an unauthenticated /mcp\ncaller are not. Absent or per_minute 0 = no limit (default, zero behavior\nchange). The counters are in memory: a restart gives every token a full\nallowance again. Hot-reloadable. File/API-configured only, no env scheme.","properties":{"burst":{"description":"Burst is how many calls a token may make at once after a quiet spell.\n0 = the PerMinute value.","type":"integer"},"per_minute":{"description":"PerMinute is the sustained rate. 0 = no limit.","type":"integer"}},"type":"object"},"config.AuditLogConfig":{"description":"AuditLog configures the Spec 107 edition-neutral audit sink\n(internal/audit). nil means \"use the per-edition/per-transport\ndefault\" (EffectiveAuditLog); restart-pinned (bound at sink\nconstruction). See audit_log.go.","properties":{"compress":{"type":"boolean"},"enabled":{"type":"boolean"},"max_age_days":{"type":"integer"},"max_backups":{"type":"integer"},"max_size_mb":{"type":"integer"},"path":{"type":"string"},"stdout":{"type":"boolean"}},"type":"object"},"config.ConcurrencyDefaults":{"description":"ServerConcurrencyDefaults is scope (b) of FR-020: the blanket per-server\ndefault set inherited by every server that does not override a setting.\nAbsent (the default) = no per-server limiting unless a server configures\nit explicitly. File/API-configured only — no env scheme (FR-022).","properties":{"max_concurrent_requests":{"type":"integer"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"}},"type":"object"},"config.Config":{"properties":{"activity_cleanup_interval_min":{"description":"Background cleanup interval in minutes (default: 60)","type":"integer"},"activity_max_records":{"description":"Max records before pruning (default: 400000)","type":"integer"},"activity_max_response_size":{"description":"Response truncation limit in bytes (default: 65536)","type":"integer"},"activity_max_size_mb":{"description":"ActivityMaxSizeMB caps the total activity-log size in MB before the\noldest records are pruned. Omit the key for the 256MB default; set it to\n0 to disable the size cap.","type":"integer"},"activity_retention_days":{"description":"Activity logging settings (RFC-003)","type":"integer"},"advertise_upstream_servers":{"description":"AdvertiseUpstreamServers controls whether MCP clients are told the\nnames of the upstream servers they can reach — in the initialize\ninstructions and the retrieve_tools description — so agents use the\nproxied tools instead of falling back to shell CLIs. Names are always\nfiltered to the caller's profile and agent-token scope. Default true;\nset false to keep server names out of client context. Read live.","type":"boolean"},"agent_token_rate_limit":{"$ref":"#/components/schemas/config.AgentTokenRateLimit"},"aggregate_upstream_prompts":{"description":"AggregateUpstreamPrompts, when true, aggregates every connected upstream\nserver's advertised MCP prompts into mcpproxy's own prompts/list\n(exposed as \"\u003cserver\u003e__\u003cprompt\u003e\"). OFF by default: users are safe by\ndefault and opt in deliberately. EnablePrompts still governs the built-in\nprompts + the prompts capability; this flag gates ONLY the upstream\naggregation performed by RefreshPrompts. Hot-reloadable.","type":"boolean"},"allow_private_registry_fetch":{"description":"AllowPrivateRegistryFetch opts out of the registry SSRF guard (MCP-1076,\nCWE-918). By default (false) registry fetches refuse any host that is — or\nresolves to — a non-routable address (loopback, RFC1918/CGNAT private,\nlink-local incl. the 169.254.169.254 cloud-metadata endpoint), so a\nmalicious or typo'd registry source cannot turn the daemon into a\nrequest-forgery vector against internal services.\n\nThis opt-out is BLANKET (all-or-nothing): setting it true disables the\nguard for EVERY non-routable range at once — loopback, RFC1918/CGNAT\nprivate, link-local AND the 169.254.169.254 cloud-metadata endpoint. There\nis no way to allow only loopback; enabling it for a localhost dev registry\nalso re-opens the cloud-metadata SSRF vector. Set true ONLY when you\nintentionally run a trusted registry mirror on an internal/private address,\nideally on a host with no cloud-metadata exposure. The change takes effect\nonly on daemon (re)start or config reload.","type":"boolean"},"allow_server_add":{"type":"boolean"},"allow_server_remove":{"type":"boolean"},"anonymous_profile":{"description":"AnonymousProfile confines every caller whose request authenticates as\ncredential kind \"anonymous\" (no credential, or an unrecognised\nnon-agent token accepted by the require_mcp_auth:false back-compat\nbranch) to the named profile (Spec 108 FR-008). Empty (default) means\nunconfined, legacy anonymous behaviour. A name that does not match any\nconfigured profile resolves anonymous callers to deny-all and is\nreported as a validation warning (data-model.md §1).","type":"string"},"api_key":{"description":"Security settings","type":"string"},"audit_log":{"$ref":"#/components/schemas/config.AuditLogConfig"},"call_tool_timeout":{"type":"string"},"check_server_repo":{"description":"Repository detection settings","type":"boolean"},"code_execution_max_parallel":{"description":"Default concurrency for call_tools() batches (1-32, default: 8)","type":"integer"},"code_execution_max_tool_calls":{"description":"Max tool calls per execution (0 = unlimited, default: 0)","type":"integer"},"code_execution_pool_size":{"description":"JavaScript runtime pool size (default: 10)","type":"integer"},"code_execution_timeout_ms":{"description":"Timeout in milliseconds (default: 120000, max: 600000)","type":"integer"},"data_dir":{"type":"string"},"debug_search":{"type":"boolean"},"direct_tool_response_mode":{"description":"DirectToolResponseMode selects the serialization of the DIRECT\nenumeration surface (Spec 102). Valid values: \"\" (= full), \"full\"\n(default: today's schema-bearing entries), \"deferred\" (description +\ncompact signature, with a minimal permissive input schema; upstream\ninputSchema and outputSchema are stripped and recovered on demand via\ndescribe_tool).\n\nDeliberately NOT an extension of tool_response_mode: reusing that axis\nwould silently change /mcp/all output for every deployment already\nrunning compact, which FR-015 forbids. Serialization-only — it never\nchanges WHICH tools are listed, only how (FR-008). Hot-reloadable.","type":"string"},"disable_management":{"type":"boolean"},"docker_isolation":{"$ref":"#/components/schemas/config.DockerIsolationConfig"},"docker_recovery":{"$ref":"#/components/schemas/config.DockerRecoveryConfig"},"enable_code_execution":{"description":"Code execution settings","type":"boolean"},"enable_prompts":{"description":"Prompts settings","type":"boolean"},"enable_skills":{"description":"EnableSkills, when true, makes mcpproxy read the skills that upstream\nservers expose through the MCP skills extension. OFF by default. Unlike\nEnablePrompts this is hot-reloadable. No CLI flag, no environment\nvariable.","type":"boolean"},"enable_socket":{"description":"Enable Unix socket/named pipe for local IPC (default: true)","type":"boolean"},"enable_tray":{"description":"Deprecated: EnableTray is unused and has no runtime effect. Kept for backward compatibility.","type":"boolean"},"environment":{"$ref":"#/components/schemas/secureenv.EnvConfig"},"features":{"$ref":"#/components/schemas/config.FeatureFlags"},"forward_client_headers":{"description":"ForwardClientHeaders is the global switch for client header forwarding\n(Spec 112): copying allowlisted headers from the inbound /mcp request into\nthe upstream tools/call request. nil (absent) means enabled; because every\nper-server forward_headers allowlist is empty by default, the default\nforwards nothing. false disables forwarding for every server. Read via\nIsClientHeaderForwardingEnabled(); MCPPROXY_FORWARD_CLIENT_HEADERS\noverrides it for the process. Distinct from ForwardedHeaders/trusted_proxies\n(Spec 107), which trusts inbound X-Forwarded-*.","type":"boolean"},"forward_proxy_env":{"description":"ForwardProxyEnv opts in to forwarding the ambient HTTP(S)/ALL/NO/FTP proxy\nenvironment variables to spawned stdio upstream servers (MCP-2769). OFF by\ndefault: proxy URLs commonly embed credentials (http://user:pass@proxy), so\nforwarding them to every upstream is a credential-leak risk. When enabled,\nvalues are forwarded with their userinfo (credentials) redacted.","type":"boolean"},"health_check_interval":{"description":"Discovery \u0026 health-check cadence (spec 074, #608). Both are *Duration\ntri-state pointers: nil = inherit the built-in default; a pointer to 0s =\nthe loop is disabled; a positive value = that interval. Defaults live only\nin the resolvers (ResolveHealthCheckInterval / ResolveToolDiscoveryInterval)\nso an unset key behaves exactly as before this feature (SC-005). Validated\nin Validate(): health-check ∈ {0} ∪ [5s,1h]; tool-discovery ∈ {0} ∪ [30s,24h].","type":"string"},"http_idle_timeout":{"description":"HTTPIdleTimeout caps how long an idle keep-alive connection is kept open.\nUnset = 180s. \"0s\" removes the dedicated idle deadline, but net/http then\nfalls back to ReadTimeout — idle is fully unbounded only when\nhttp_read_timeout is also \"0s\". Requires a restart.","type":"string"},"http_read_timeout":{"description":"HTTPReadTimeout caps how long reading a whole request (headers + body)\nmay take. Unset = 120s; \"0s\" disables it. Requires a restart.","type":"string"},"http_write_timeout":{"description":"HTTPWriteTimeout caps how long producing a whole response may take on\nnon-streaming endpoints (REST, Web UI, health). Unset = 120s; \"0s\"\ndisables it globally. MCP and SSE /events routes are exempt by design.","type":"string"},"init_timeout":{"description":"InitTimeout is the global default deadline for an upstream's MCP\n` + "`" + `initialize` + "`" + ` handshake (MCP-3322 / GH #760). *Duration tri-state: nil =\ninherit the built-in 30s default; a positive value = that deadline. A\nper-server InitTimeout overrides this. Resolved by ResolveInitTimeout;\nvalidated to {0} ∪ [1s, 30m] in Validate(). Servers doing legitimate\nfirst-run warmup (cache/index build) before answering ` + "`" + `initialize` + "`" + ` can\nraise this so they are not killed mid-startup.","type":"string"},"instructions":{"description":"Instructions text returned in the MCP initialize response to guide AI agents.\nWhen empty, a built-in default is used that explains retrieve_tools workflow.","type":"string"},"intent_declaration":{"$ref":"#/components/schemas/config.IntentDeclarationConfig"},"listen":{"type":"string"},"logging":{"$ref":"#/components/schemas/config.LogConfig"},"max_concurrent_requests":{"description":"Concurrency limits (spec 093, GH #955). Scope (a) of FR-020: the GLOBAL\nAGGREGATE limiter — one proxy-wide cap on concurrently running upstream\ntool calls, with its own bounded wait queue. Tri-state pointers: absent =\nthe limiter does not exist (default, zero behavior change); an explicit 0\nmax also disables it; positive = that cap. This scope is NEVER a\nper-server inheritance source — per-server values come from\nServerConcurrencyDefaults / the per-server overrides — but a server's\neffective concurrency is bounded by BOTH its own limiter and this one.\nResolved by ResolveGlobalConcurrency; hot-reloadable; overridable via\nMCPPROXY_MAX_CONCURRENT_REQUESTS / _QUEUE_SIZE / _QUEUE_TIMEOUT (FR-022).","type":"integer"},"max_result_size_chars":{"description":"MaxResultSizeChars is advertised on every tool as\n` + "`" + `_meta.anthropic/maxResultSizeChars` + "`" + `; it raises Claude Code's\ninline-response ceiling from 50k to up to 500k chars. Omit the key for\nthe 500000 default; set it to 0 to disable the annotation.","type":"integer"},"mcpServers":{"items":{"$ref":"#/components/schemas/config.ServerConfig"},"type":"array","uniqueItems":false},"mcp_oauth_enabled":{"description":"MCPOAuthEnabled turns on browser login (OAuth 2.1 + PKCE) for MCP\nclients on the loopback listener (Spec 132). Experimental, default false:\nwith it off nothing changes. Env override MCPPROXY_MCP_OAUTH_ENABLED is\nprocess-only and never persisted. Live, no restart needed.","type":"boolean"},"mcp_reject_query_apikey":{"description":"MCPRejectQueryAPIKey makes every MCP endpoint (/mcp*) refuse a request that\ncarries a ?apikey= query parameter, with a 401, instead of honouring it. A credential in a URL ends up in access logs,\nproxy logs and browser history; MCP clients can send Authorization:\nBearer or X-API-Key instead. Default false (the query form keeps\nworking, for clients that can only configure a URL). It covers only the\nMCP endpoints: the Web UI and its SSE stream (/events) still use the\nquery form. Live, no restart needed.","type":"boolean"},"oauth_expiry_warning_hours":{"description":"Health status settings","type":"number"},"oauth_token_encryption_key":{"description":"OAuthTokenEncryptionKey seals the upstream OAuth tokens stored in\nconfig.db (Spec 123). Empty (the default) leaves them as plain JSON. It\ntakes a secret reference (${file:/abs/path}, ${env:NAME},\n${keyring:NAME}) or a literal standard-base64 32-byte key; the\nMCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY[_FILE] variables override it. The key\nis resolved only where config.db is opened (ResolveOAuthTokenKey), never\nstored on Config, and is restart-gated, so every save writes the field\nas configured.","type":"string"},"observability":{"$ref":"#/components/schemas/config.ObservabilityConfig"},"output_sanitisation":{"$ref":"#/components/schemas/config.OutputSanitisationConfig"},"output_validation":{"$ref":"#/components/schemas/config.OutputValidationConfig"},"profiles":{"description":"Profiles are optional named, server-scoped views exposed at /mcp/p/\u003cname\u003e\n(Spec 057). Absent/empty is fully supported — /mcp is unchanged and configs\nwithout this key serialize byte-identically (SC-004).","items":{"$ref":"#/components/schemas/config.ProfileConfig"},"type":"array","uniqueItems":false},"quarantine_enabled":{"description":"QuarantineEnabled controls whether quarantine is active. It gates two\nthings together:\n 1. Server-level auto-quarantine for newly added servers (issue #370).\n When true, servers added via the upstream_servers MCP tool or the\n REST API default to quarantined=true; when false, they default to\n quarantined=false. Explicit per-request values always win.\n 2. Tool-level quarantine (Spec 032): per-tool SHA-256 approval of\n tool descriptions/schemas.\nWhen nil (default), quarantine is enabled (secure by default). Set to\nexplicit false to opt out of both. Per-server SkipQuarantine still\napplies for the tool-level check on individual servers.","type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"read_only_mode":{"type":"boolean"},"registries":{"description":"Registries configuration for MCP server discovery","items":{"$ref":"#/components/schemas/config.RegistryEntry"},"type":"array","uniqueItems":false},"registries_locked":{"description":"RegistriesLocked is an enterprise stub knob (MCP-866): when true, runtime\nadditions of custom registries (e.g. ` + "`" + `registry add-source` + "`" + `, the REST/MCP\nadd-source surface) are rejected so an administrator can pin the discovery\nsources. Built-in defaults are unaffected. Documented but otherwise inert\nbeyond the add-source rejection.","type":"boolean"},"require_mcp_auth":{"description":"Require authentication on /mcp endpoint (default: false)","type":"boolean"},"reveal_secret_headers":{"description":"RevealSecretHeaders, when true, disables the redaction of the\nsecret-bearing server fields — sensitive header values (Authorization,\nX-API-Key, Cookie, …), env-var secrets, and URL query credentials — in\nresponses from the ` + "`" + `upstream_servers` + "`" + ` MCP tool, the ` + "`" + `/api/v1/servers` + "`" + `\nREST API, and the SSE event stream. It also lets URL secrets echoed\ninto last_error / health.detail through unscrubbed.\n\nDefault false — sensitive values are surfaced masked as\n` + "`" + `••••\u003clast2\u003e (\u003cN\u003e chars)` + "`" + ` (error strings use ` + "`" + `***REDACTED***` + "`" + `) so an\nMCP agent cannot read Bearer tokens / API keys / URL secrets out of\nanother upstream's config (PR #425, issue #872). ${env:…}/${keyring:…}\nreferences are labels, not secrets, and pass through unchanged.\n\nThe Web UI / macOS tray edit forms work without seeing the real\nvalues: PATCH /api/v1/servers/{id} deep-merges (omitted keys are\npreserved, see ` + "`" + `headers_remove` + "`" + ` / ` + "`" + `env_remove` + "`" + ` for explicit\ndeletes), so clients compute a diff and only send the keys that\nactually changed. Redacted-but-unchanged values never round-trip\n— the backend keeps the real string. Set this to true if a\ndownstream tool genuinely needs raw values in the response.","type":"boolean"},"routing_mode":{"description":"Routing mode (Spec 031): how MCP tools are exposed to clients\nValid values: \"retrieve_tools\" (default), \"direct\", \"code_execution\"","type":"string"},"security":{"$ref":"#/components/schemas/config.SecurityConfig"},"sensitive_data_detection":{"$ref":"#/components/schemas/config.SensitiveDataDetectionConfig"},"server_concurrency_defaults":{"$ref":"#/components/schemas/config.ConcurrencyDefaults"},"session_retention_days":{"description":"SessionRetentionDays is how long a work session is listed and kept whole\nin the activity log (Spec 124, default 7). Read at start.","type":"integer"},"telemetry":{"$ref":"#/components/schemas/config.TelemetryConfig"},"tls":{"$ref":"#/components/schemas/config.TLSConfig"},"tokenizer":{"$ref":"#/components/schemas/config.TokenizerConfig"},"tool_call_max_records_per_server":{"description":"Calls retained per server (default: 1000)","type":"integer"},"tool_call_max_response_size":{"description":"Bounds for the per-server tool-call history behind GET /api/v1/tool-calls\n(#1176). It is a recent-debugging window, not an audit log — the activity\nlog is the durable record — and it kept every upstream response whole,\nper server, forever. A non-positive value means \"use the default\", not\n\"disable\": this store must never be unbounded again, so there is\ndeliberately no off switch.","type":"integer"},"tool_discovery_interval":{"type":"string"},"tool_response_limit":{"type":"integer"},"tool_response_mode":{"description":"Tool response mode (Spec 085): how retrieve_tools serializes results.\nValid values: \"\" (= full), \"full\" (default: today's schema-bearing\nentries), \"compact\" (signature + first-sentence entries). Orthogonal to\nrouting_mode — routing_mode selects the tool SURFACE, this selects the\nSERIALIZATION within the retrieve_tools surface. Serialization-only: it\nnever affects the query, ranking, or result set. Hot-reloadable.","type":"string"},"tool_response_session_risk_warning":{"description":"ToolResponseSessionRiskWarning controls whether the prose ` + "`" + `warning` + "`" + ` field\nis included in the ` + "`" + `session_risk` + "`" + ` object returned by ` + "`" + `retrieve_tools` + "`" + `.\nThe structured fields (level, lethal_trifecta, has_open_world_tools, etc.)\nare always included. Default: false (quiet for LLM clients) — see issue #406.\nMost tools lack annotations, so the MCP-spec defaults treat them as fully\npermissive across all three risk axes, which makes the prose warning fire\non almost every call and wastes tokens.","type":"boolean"},"tools_limit":{"type":"integer"},"toon_min_savings_pct":{"description":"ToonMinSavingsPct is the minimum byte-savings percentage (validated\n1-90; 0/unset → 15) the complete TOON emission (marker + hint + body)\nmust achieve over the exact passthrough emission for adaptive mode to\nencode a block. Byte savings approximate token savings for the tabular\npayload class; the spec-083 profiler reports true token deltas.\nGlobal-only (no per-server override, FR-001).","type":"integer"},"toon_output":{"description":"ToonOutput selects the TOON encoding mode for call_tool_* result text\nblocks (spec 084): \"off\" (default — responses byte-identical to\npre-feature behavior), \"adaptive\" (encode only tabular-uniform payloads\nthat beat compact JSON by ToonMinSavingsPct), or \"always\"\n(benchmark/debug only — encodes every JSON-parseable block and can\nINCREASE token cost). Per-server override: ServerConfig.ToonOutput.\nResolved by ResolveToonOutput; hot-reloadable.","type":"string"},"top_k":{"description":"Deprecated: TopK is superseded by ToolsLimit and has no runtime effect. Kept for backward compatibility.","type":"integer"},"tray_endpoint":{"description":"Tray endpoint override (unix:// or npipe://)","type":"string"},"trusted_hosts":{"description":"TrustedHosts lists non-loopback Host header values accepted on loopback\nlisteners (GH #898). DNS-rebinding protection rejects requests whose Host\nheader is not a loopback address when mcpproxy listens on loopback; a\nreverse proxy (nginx → 127.0.0.1) forwarding the public domain in Host\ntrips it. Entries are hostnames, case-insensitive; an entry without a\nport matches any port, with a port it must match exactly; a leading dot\n(\".example.com\") is a subdomain wildcard. The single entry \"*\" disables\nHost and Origin validation entirely. The same list also validates the\nOrigin header when present (MCP spec DNS-rebinding defense). Empty\n(default) keeps full protection. Env override: MCPPROXY_TRUSTED_HOSTS\n(comma-separated).","items":{"type":"string"},"type":"array","uniqueItems":false},"trusted_proxies":{"description":"TrustedProxies lists the CIDRs or IP addresses whose X-Forwarded-For /\nX-Real-IP / X-Forwarded-Proto / X-Forwarded-Host headers are believed\n(Spec 107 FR-027). Empty (default) trusts nobody. Edition-neutral, live\n(hot-reloadable). Env override: MCPPROXY_TRUSTED_PROXIES (comma-separated).\nThe one reader is ForwardedHeaders; validation is validateTrustedProxies.","items":{"type":"string"},"type":"array","uniqueItems":false},"update_check":{"$ref":"#/components/schemas/config.UpdateCheckConfig"}},"type":"object"},"config.CustomPattern":{"properties":{"category":{"description":"Category (defaults to \"custom\")","type":"string"},"keywords":{"description":"Keywords to match (mutually exclusive with Regex)","items":{"type":"string"},"type":"array","uniqueItems":false},"name":{"description":"Unique identifier for this pattern","type":"string"},"regex":{"description":"Regex pattern (mutually exclusive with Keywords)","type":"string"},"severity":{"description":"Risk level: critical, high, medium, low","type":"string"}},"type":"object"},"config.DeepScanConfig":{"description":"DeepScan is the opt-in \"deep scan\" layer (Spec 077 US3). It subsumes the\ndeprecated top-level scanner_fetch_package_source / scanner_disable_no_new_privileges\nkeys (migrated on load) and gates the heavy Docker-based scanners + source\nextraction. Disabled by default (FR-006): only the deterministic in-process\nbaseline scanner runs. A deep-scan failure NEVER changes the baseline verdict\n(FR-007/FR-008).","properties":{"disable_no_new_privileges":{"description":"DisableNoNewPrivileges, when true, omits the ` + "`" + `--security-opt\nno-new-privileges` + "`" + ` flag from scanner container runs (snap-docker/AppArmor\nescape hatch). Absorbs the deprecated top-level\nscanner_disable_no_new_privileges. Default false.","type":"boolean"},"enabled":{"description":"Enabled is the master opt-in for the heavy layer (FR-006). Default false.","type":"boolean"},"fetch_package_source":{"description":"FetchPackageSource controls whether the scanner fetches the PUBLISHED\nsource of package-runner servers (npx/uvx) — without executing it — when\nno local source is available. Absorbs the deprecated top-level\nscanner_fetch_package_source. Default (nil) is ENABLED within deep scan.","type":"boolean"},"scanners":{"description":"Scanners optionally restricts which deep scanners may run under the\numbrella (by scanner id). Empty ⇒ all enabled deep scanners are eligible.","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"config.DockerIsolationConfig":{"description":"Docker isolation settings","properties":{"cpu_limit":{"description":"CPU limit for containers","type":"string"},"default_images":{"additionalProperties":{"type":"string"},"description":"Map of runtime type to Docker image","type":"object"},"enable_cache_volume":{"description":"Mount shared cache volumes for faster restarts (default: true)","type":"boolean"},"enabled":{"description":"Global enable/disable for Docker isolation (legacy; superseded by Mode)","type":"boolean"},"extra_args":{"description":"Additional docker run arguments","items":{"type":"string"},"type":"array","uniqueItems":false},"log_driver":{"description":"Docker log driver (default: json-file)","type":"string"},"log_max_files":{"description":"Maximum number of log files (default: 3)","type":"string"},"log_max_size":{"description":"Maximum size of log files (default: 100m)","type":"string"},"memory_limit":{"description":"Memory limit for containers","type":"string"},"mode":{"description":"Isolation mode: \"docker\" | \"sandbox\" | \"none\" (MCP-34.2). Unset per-server inherits the global mode; unset globally falls back to the legacy \"enabled\" flag (true ⇒ docker, false ⇒ none)","type":"string","x-enum-varnames":["IsolationModeDocker","IsolationModeSandbox","IsolationModeNone"]},"network_mode":{"description":"Docker network mode (default: bridge)","type":"string"},"registry":{"description":"Custom registry (defaults to docker.io)","type":"string"},"timeout":{"description":"Container startup timeout","type":"string"}},"type":"object"},"config.DockerRecoveryConfig":{"description":"Docker recovery settings","properties":{"enabled":{"description":"Enable Docker recovery monitoring (default: true)","type":"boolean"},"max_retries":{"description":"Maximum retry attempts (0 = unlimited)","type":"integer"},"notify_on_failure":{"description":"Show notification on recovery failure (default: true)","type":"boolean"},"notify_on_retry":{"description":"Show notification on each retry (default: false)","type":"boolean"},"notify_on_start":{"description":"Show notification when recovery starts (default: true)","type":"boolean"},"notify_on_success":{"description":"Show notification on successful recovery (default: true)","type":"boolean"},"persistent_state":{"description":"Save recovery state across restarts (default: true)","type":"boolean"}},"type":"object"},"config.FeatureFlags":{"description":"Deprecated: Features flags are unused and have no runtime effect. Kept for backward compatibility.","properties":{"enable_async_storage":{"type":"boolean"},"enable_caching":{"type":"boolean"},"enable_contract_tests":{"type":"boolean"},"enable_debug_logging":{"description":"Development features","type":"boolean"},"enable_docker_isolation":{"type":"boolean"},"enable_event_bus":{"type":"boolean"},"enable_health_checks":{"type":"boolean"},"enable_metrics":{"type":"boolean"},"enable_oauth":{"description":"Security features","type":"boolean"},"enable_observability":{"description":"Observability features","type":"boolean"},"enable_quarantine":{"type":"boolean"},"enable_runtime":{"description":"Runtime features","type":"boolean"},"enable_search":{"description":"Storage features","type":"boolean"},"enable_sse":{"type":"boolean"},"enable_tracing":{"type":"boolean"},"enable_tray":{"type":"boolean"},"enable_web_ui":{"description":"UI features","type":"boolean"}},"type":"object"},"config.IntentDeclarationConfig":{"description":"Intent declaration settings (Spec 018)","properties":{"strict_server_validation":{"description":"StrictServerValidation controls whether server annotation mismatches\ncause rejection (true) or just warnings (false).\nDefault: true (reject mismatches)","type":"boolean"}},"type":"object"},"config.IsolationConfig":{"description":"Per-server isolation settings","properties":{"enabled":{"description":"Enable Docker isolation for this server (nil = inherit global; legacy, superseded by Mode)","type":"boolean"},"extra_args":{"description":"Additional docker run arguments for this server","items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"description":"Custom Docker image (overrides default)","type":"string"},"log_driver":{"description":"Docker log driver override for this server","type":"string"},"log_max_files":{"description":"Maximum number of log files override","type":"string"},"log_max_size":{"description":"Maximum size of log files override","type":"string"},"mode":{"$ref":"#/components/schemas/config.IsolationMode"},"network_mode":{"description":"Custom network mode for this server","type":"string"},"working_dir":{"description":"Custom working directory in container","type":"string"}},"type":"object"},"config.IsolationMode":{"description":"Isolation mode: \"docker\" | \"sandbox\" | \"none\" (MCP-34.2). Unset per-server inherits the global mode; unset globally falls back to the legacy \"enabled\" flag (true ⇒ docker, false ⇒ none)","type":"string","x-enum-varnames":["IsolationModeDocker","IsolationModeSandbox","IsolationModeNone"]},"config.LogConfig":{"description":"Logging configuration","properties":{"compress":{"type":"boolean"},"enable_console":{"type":"boolean"},"enable_file":{"type":"boolean"},"filename":{"type":"string"},"json_format":{"type":"boolean"},"level":{"type":"string"},"log_dir":{"description":"Custom log directory","type":"string"},"max_age":{"description":"days","type":"integer"},"max_backups":{"description":"number of backup files","type":"integer"},"max_size":{"description":"MB","type":"integer"}},"type":"object"},"config.MetricsExporterConfig":{"description":"Metrics gates the Prometheus /metrics scrape endpoint (MCP-32). Disabled\nby default — operators opt in for k8s/enterprise deployments.","properties":{"enabled":{"description":"Enabled exposes /metrics on the existing HTTP listener when true.\nThe endpoint is admin-authenticated (SEC-07): scrapers must present the\nglobal API key, via X-API-Key or an Authorization: Bearer header.","type":"boolean"}},"type":"object"},"config.OAuthConfig":{"description":"OAuth configuration (keep even when empty to signal OAuth requirement)","properties":{"auth_server_metadata_url":{"type":"string"},"authorization_endpoint":{"description":"Spec 113-b: optional per-server discovery overrides. Each is an absolute\nhttps URL (http only on a loopback host) with no query, fragment or\nuserinfo; validated at write time only (ValidateOAuthEndpointOverrides).\nThe endpoint overrides rewrite the matching fields of the authorization\nserver metadata mcp-go reads; AuthServerMetadataURL replaces discovery.","type":"string"},"callback_base_url":{"type":"string"},"client_id":{"type":"string"},"client_secret":{"type":"string"},"extra_params":{"additionalProperties":{"type":"string"},"description":"Additional OAuth parameters (e.g., RFC 8707 resource)","type":"object"},"pkce_enabled":{"type":"boolean"},"redirect_uri":{"type":"string"},"refresh_replay_enabled":{"description":"Opt in only when token_endpoint supports idempotent refresh replay for at least 30 seconds.","type":"boolean"},"registration_endpoint":{"type":"string"},"scopes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"token_endpoint":{"type":"string"}},"type":"object"},"config.ObservabilityConfig":{"description":"Observability settings (Spec 069): usage aggregate cache/persistence cadence.","properties":{"metrics":{"$ref":"#/components/schemas/config.MetricsExporterConfig"},"tracing":{"$ref":"#/components/schemas/config.TracingExporterConfig"},"usage_cache_ttl":{"description":"UsageCacheTTL bounds the freshness of the usage endpoint's read cache for\nwide windows (FR-005). Default 5s.","type":"string"},"usage_persist_interval":{"description":"UsagePersistInterval is how often the actor-owned usage aggregate snapshot\nis flushed to storage. Default 30s.","type":"string"}},"type":"object"},"config.OutputSanitisationConfig":{"description":"Output sanitisation settings (Spec 054 Track B)","properties":{"max_redactions":{"description":"cap on redactions per response; default 100","type":"integer"},"response_action":{"description":"\"spotlight\" | \"redact\" | \"block\"; default \"spotlight\"","type":"string"},"spotlight_untrusted":{"description":"wrap untrusted output in spotlight markers; default true","type":"boolean"},"strip_classes":{"description":"classes to strip: ansi/c0c1/bidi/zero_width","items":{"type":"string"},"type":"array","uniqueItems":false},"strip_control_chars":{"description":"strip control-character classes; default false","type":"boolean"}},"type":"object"},"config.OutputValidationConfig":{"description":"Output-schema validation settings (Spec 056)","properties":{"max_bytes":{"description":"structured payload byte cap; default 5\u003c\u003c20","type":"integer"},"max_depth":{"description":"nesting depth cap; default 64","type":"integer"},"missing_structured_content":{"description":"\"allow\" | \"block\"; default \"allow\"","type":"string"},"mode":{"description":"\"off\" | \"warn\" | \"strict\"; default \"warn\"","type":"string"}},"type":"object"},"config.ProfileConfig":{"properties":{"code_execution":{"description":"CodeExecution: nil = inherit the global enable_code_execution gate;\nnon-nil narrows it (a profile can only narrow, never widen, FR-006).","type":"boolean"},"description":{"description":"\u003c= 500 chars (FR-001)","type":"string"},"management_tools":{"description":"ManagementTools: nil = legacy/inherit (FR-016); non-nil sets the\nprofile-level visibility of upstream_servers/quarantine_security.","type":"boolean"},"max_tier":{"description":"MaxTier caps the tier a tool may run at under this profile: \"\" (no\ncap) | \"read\" | \"write\" | \"destructive\" (FR-001).","type":"string"},"name":{"description":"slug (Spec 057 rules unchanged)","type":"string"},"servers":{"description":"references to mcpServers[].name","items":{"type":"string"},"type":"array","uniqueItems":false},"switchable_to":{"description":"SwitchableTo is the list of profile names a session under this\nprofile may ` + "`" + `set_profile` + "`" + ` into (FR-022). nil = legacy/none (research\nD6); a non-nil EMPTY list is an explicit \"none\" and must round-trip as\n` + "`" + `[]` + "`" + `, never be dropped by omitempty — hence the pointer (see the\nMarshalJSON note below, and profiles_v3_test.go's switchable_to round\ntrip case).","items":{"type":"string"},"type":"array","uniqueItems":false},"title":{"description":"display only, \u003c= 80 chars (FR-001)","type":"string"},"tools":{"$ref":"#/components/schemas/config.ProfileToolRules"},"unannotated":{"description":"Unannotated is this profile's handling of a tool whose effective\nannotations carry no tier hint: \"\" (unset, see EffectiveUnannotated) |\n\"deny\" | \"as_write\" | \"as_read\" (FR-001, FR-003).","type":"string"}},"type":"object"},"config.ProfileToolRules":{"description":"Tools holds the allow/deny/classify rule set (FR-001, FR-004, FR-005).","properties":{"allow":{"items":{"type":"string"},"type":"array","uniqueItems":false},"classify":{"additionalProperties":{"type":"string"},"type":"object"},"deny":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"config.RegistryEntry":{"properties":{"count":{"description":"number or string","type":"string"},"description":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"},"protocol":{"type":"string"},"provenance":{"description":"Provenance is the trust tag for this registry (MCP-866):\nRegistryProvenanceOfficial for built-in defaults, RegistryProvenanceCustom\nfor user-added registries. It is authoritatively (re)computed by the\nregistries merge from whether the ID is a shipped default — a user cannot\nclaim \"official\" by writing it into their config.","type":"string"},"requires_key":{"description":"RequiresKey marks a registry that needs an API key to be queried. When\ntrue and no key is configured, the registry is skipped/marked unavailable\nrather than failing the whole search (FR-008).","type":"boolean"},"servers_url":{"type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"url":{"type":"string"}},"type":"object"},"config.SecurityConfig":{"description":"Security scanner settings (Spec 039)","properties":{"auto_baseline_scan":{"description":"AutoBaselineScan is the kill-switch for the AUTOMATIC, informational\nPass-1 baseline scan: the free in-process TPA scan mcpproxy runs for every\nnewly admitted server (any trust mode) and, once per installation, over\npre-existing servers that have never been scanned.\n\nInformational ONLY: the resulting verdict populates the security badge and\nthe scan summary, and NEVER gates quarantine or approval. The\ntrust_mode:\"scan\" admission gate is a separate path and is unaffected by\nthis flag.\n\nDefault (nil) is ENABLED. Set to false to suppress every automatic scan\n(manual scans keep working). Env override: MCPPROXY_AUTO_BASELINE_SCAN,\nwhich wins over this field on every path.","type":"boolean"},"auto_rescan_on_change":{"description":"AutoRescanOnChange is the finer switch for the automatic, informational\nrescan that follows a tool-definition hash change: the in-process TPA scan\nof the changed (or newly pending) tool, recorded as hold evidence, and a\ndebounced informational server rescan that brings the review screen's scan\ncoverage back to \"current\".\n\nEvidence and freshness ONLY: this switch approves nothing. Under \"manual\"\nevery change is held for review whatever the verdict (RT-02); under\n\"scan\" the gate's own synchronous scan approves a clean change that\npasses the spec 120 structural gate (spec 119 FR-004), and this switch\ndoes not affect that path. Runs in every trust mode except \"auto\".\n\nDefault (nil) is ENABLED. It only takes effect while auto_baseline_scan is\nalso enabled, so a user can keep the admission scan and turn off per-change\nrescans with this key alone. Env override: MCPPROXY_AUTO_RESCAN_ON_CHANGE,\nwhich wins over this field on every path.","type":"boolean"},"deep_scan":{"$ref":"#/components/schemas/config.DeepScanConfig"},"integrity_check_interval":{"type":"string"},"integrity_check_on_restart":{"type":"boolean"},"require_signed_bundle":{"description":"RequireSignedBundle makes the detached signature sidecar mandatory for\nfile-dropped bundles (FR-007). Default false (maintainer decision D2):\nexisting unsigned drops keep working, but an unsigned external bundle\nalways runs with DEGRADED coverage (scan-mode auto-approval suspended).","type":"boolean"},"runtime_read_only":{"type":"boolean"},"runtime_tmpfs_size":{"type":"string"},"scan_timeout_default":{"type":"string"},"scanner_disable_no_new_privileges":{"description":"Deprecated (Spec 077 US3): migrated on load into DeepScan.DisableNoNewPrivileges\n(see migrateDeepScanConfig). Retained only so existing configs that still carry\nthe top-level key parse; consumers MUST read the effective value via\nSecurityConfig.IsDisableNoNewPrivileges. Cleared after migration.\n\nScannerDisableNoNewPrivileges, when true, omits the\n` + "`" + `--security-opt no-new-privileges` + "`" + ` flag from scanner container runs.\n\nBackground: snap-installed Docker on Ubuntu confines dockerd under the\n` + "`" + `snap.docker.dockerd` + "`" + ` AppArmor profile. When runc tries to transition\nthe container into the inner ` + "`" + `docker-default` + "`" + ` profile to exec the\nentrypoint, AppArmor refuses the transition because NO_NEW_PRIVS\nforbids privilege/profile changes on exec — the result is EPERM\n(\"operation not permitted\") and every scanner fails immediately.\n\nSet this to true ONLY on hosts hitting that incompatibility. Scanner\ncontainers still run with read-only rootfs, tmpfs /tmp, no-network by\ndefault, and read-only source mounts, so the marginal isolation loss\nis small. The preferred fix remains replacing snap docker with a\ndistro-packaged docker.","type":"boolean"},"scanner_fetch_package_source":{"description":"Deprecated (Spec 077 US3): migrated on load into DeepScan.FetchPackageSource\n(see migrateDeepScanConfig). Retained only so existing configs that still carry\nthe top-level key parse; consumers MUST read the effective value via\nSecurityConfig.EffectiveFetchPackageSource. Cleared after migration.\n\nScannerFetchPackageSource controls whether the scanner fetches the\nPUBLISHED source of package-runner servers (npx/uvx) — without executing\nit — when no local source is available (no Docker container, no local\npackage cache, no working_dir). This is the primary quarantine/scan\ntarget: a quarantined-on-add server is never run locally, so without this\nthe scan degrades to tool-definitions-only (no real source-level\nanalysis). See MCP-2206.\n\nFetching uses ` + "`" + `npm pack --ignore-scripts` + "`" + ` (npm) and ` + "`" + `uv pip download` + "`" + ` /\n` + "`" + `pip download` + "`" + ` with ` + "`" + `--only-binary=:all:` + "`" + ` (Python), which only download +\nunpack archives and NEVER run install, build, or setup.py — a scanner must\nnot execute the untrusted code it is scanning. The Python\n` + "`" + `--only-binary=:all:` + "`" + ` flag is required because downloading an sdist would\ninvoke its build backend (setup.py); packages with no wheel fall back to\ntool-definitions-only instead. Extraction is hardened against path\ntraversal and decompression bombs.\n\nDefault (nil) is ENABLED. Set to false on air-gapped deployments to\nforbid the scanner's network egress; such servers then fall back to the\ntool-definitions-only scan with no regression.","type":"boolean"},"scanner_registry_url":{"type":"string"},"tpa_active_root":{"description":"TPAActiveRoot declares which signing authority's bundles may activate\n(FR-004b): \"publisher\" (default, the keys embedded in this binary) or\n\"operator\" (TPAOperatorSigners). A bundle verified by the other root is\nrefused as authority_not_active, so whoever can write the bundle path\ncannot choose the authority.","type":"string"},"tpa_bundle_path":{"description":"TPABundlePath is the filesystem path to the tpa-db scanner-bundle.json\nthe offline TPA scanner runs (spec 086 FR-019: the signature-DB location\nMUST be configuration-driven, not hardcoded). Empty (the default) runs the\ncorpus embedded in this build.\n\nEnv override: MCPPROXY_TPA_BUNDLE_PATH. Hot-reloadable — the path is\nre-read on every config.reloaded event via\nscanner.Service.ApplySecurityConfig, so a corpus refresh needs no restart.\nA configured bundle that fails to read/parse/version-check/compile is\nREFUSED and the previously active corpus stays live (fail-closed, never\nfail-empty); the reason is logged and surfaced in the security overview's\nsignature_bundle.load_error.","type":"string"},"tpa_fetch_enabled":{"description":"TPAFetchEnabled opts in to the network fetch leg. Default false; the\nenvironment override is MCPPROXY_TPA_FETCH_ENABLED (EnvTPAFetchEnabled).","type":"boolean"},"tpa_fetch_url":{"description":"TPAFetchURL is the channel URL: a GitHub Releases \"latest\" API URL or a\ndirect bundle URL. Empty (the default) means the fetch leg is off; no URL\nis compiled into the binary.","type":"string"},"tpa_operator_baseline":{"description":"TPAOperatorBaseline seeds the operator authority's anti-downgrade\nwatermark (FR-009b): an operator-signed bundle must carry a sequence\nABOVE it (a rollback target may sit at it). It survives a data-directory\nwipe because it lives here. Absent means the operator authority has no\nanti-downgrade floor and an active operator bundle runs DEGRADED.","type":"integer"},"tpa_operator_epoch":{"description":"TPAOperatorEpoch is the operator authority's trust epoch (FR-005a).\nBumping it (after an operator key compromise) re-baselines the operator\nwatermark and retires prior-epoch pins. Absent means 0.","type":"integer"},"tpa_operator_signers":{"description":"TPAOperatorSigners lists operator Ed25519 public keys, each the standard\nbase64 encoding of the 32 raw key bytes (FR-004). Their key ids are the\nlowercase-hex SHA-256 of those bytes. Malformed or duplicate entries are\nrejected on write and dropped (with a log) on load.","items":{"type":"string"},"type":"array","uniqueItems":false},"tpa_refresh_interval":{"description":"TPARefreshInterval is the cadence of the refresh cycle (the network-free\nfile leg, then the optional fetch leg). Absent or 0 means 24h; the runtime\nclamps to at least 1h. There is no refresh-enable key: the file leg is\nidempotent and always on.","type":"string"},"tpa_stale_after_days":{"description":"TPAStaleAfterDays is the age in days after which the active bundle reads\nas stale. Absent means 30; an explicit 0 disables the stale flag and the\ndoctor stale warning.","type":"integer"}},"type":"object"},"config.SensitiveDataDetectionConfig":{"description":"Sensitive data detection settings (Spec 026)","properties":{"categories":{"additionalProperties":{"type":"boolean"},"description":"Enable/disable specific detection categories","type":"object"},"custom_patterns":{"description":"User-defined detection patterns","items":{"$ref":"#/components/schemas/config.CustomPattern"},"type":"array","uniqueItems":false},"enabled":{"description":"Enable sensitive data detection (default: true)","type":"boolean"},"entropy_threshold":{"description":"Shannon entropy threshold for high-entropy detection (default: 4.5)","type":"number"},"max_payload_size_kb":{"description":"Max size to scan before truncating (default: 1024)","type":"integer"},"scan_requests":{"description":"Scan tool call arguments (default: true)","type":"boolean"},"scan_responses":{"description":"Scan tool responses (default: true)","type":"boolean"},"sensitive_keywords":{"description":"Keywords to flag","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"config.ServerConfig":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges is the per-server intent to auto-approve tool\nchanges/additions (disabling per-server rug-pull protection). Supersedes\nskip_quarantine. MCP-2930 only ACCEPTS, persists, and migrates this flag — it\nis NOT yet consulted at runtime; auto-approval is still governed by\nSkipQuarantine until the trust-baseline behavior change (MCP-2931) migrates the\nruntime consumers onto it.\nTri-state pointer (mirrors QuarantineEnabled): nil = unset (inherit/migrate\nfrom legacy skip_quarantine), explicit true/false = honored as-is so an\nexplicit auto_approve_tool_changes:false overrides a legacy skip_quarantine:true.\nRead via IsAutoApproveToolChanges().","type":"boolean"},"command":{"type":"string"},"created":{"type":"string"},"disabled_tools":{"description":"Denylist: these tools are hidden; mutually exclusive with enabled_tools","items":{"type":"string"},"type":"array","uniqueItems":false},"enabled":{"type":"boolean"},"enabled_tools":{"description":"Allowlist: only these tools are exposed; mutually exclusive with disabled_tools","items":{"type":"string"},"type":"array","uniqueItems":false},"env":{"additionalProperties":{"type":"string"},"type":"object"},"expose_prompts":{"description":"ExposePrompts overrides whether this server's advertised MCP prompts are\naggregated into mcpproxy's prompts/list. nil (default) inherits the\ndefault-aggregate behavior (included if the server advertises\nCapabilities.Prompts); false excludes it regardless of capability.","type":"boolean"},"expose_skills":{"description":"ExposeSkills overrides whether this server's skills (MCP skills\nextension) are read when Config.EnableSkills is on. nil (default)\ninherits (included if the server supports skills); false excludes it.","type":"boolean"},"forward_headers":{"description":"ForwardHeaders lists inbound MCP-client header NAMES (never values) that\nare copied into this server's upstream tools/call requests (Spec 112).\nExact names, case-insensitive, at most 32, no wildcards. Empty forwards\nnothing. Only HTTP-based transports (http, streamable-http) forward; the\ndeny list (Authorization, Host, hop-by-hop, ...) is enforced at runtime\nregardless of what is configured here.","items":{"type":"string"},"type":"array","uniqueItems":false},"headers":{"additionalProperties":{"type":"string"},"description":"For HTTP servers","type":"object"},"health_check_interval":{"description":"Per-server discovery \u0026 health-check overrides (spec 074). Same *Duration\ntri-state as the global keys: nil = inherit the global value (or default),\npointer to 0s = disabled for this server, positive = that interval.\nHealthCheckInterval is fully wired into the per-server health loop;\nToolDiscoveryInterval is accepted/validated and round-trips for\nforward-compat, but the periodic index sweep is governed by the global\ncadence in this iteration (see spec 074 plan §C).","type":"string"},"init_timeout":{"description":"InitTimeout overrides the global init_timeout for this server's MCP\n` + "`" + `initialize` + "`" + ` handshake deadline (MCP-3322 / GH #760). *Duration tri-state:\nnil = inherit the global value (or 30s default), positive = that deadline.\nResolved by Config.ResolveInitTimeout; validated to {0} ∪ [1s, 30m]. Raise\nthis for upstreams that do legitimate first-run warmup (e.g. caching many\nchannels/users) before responding to ` + "`" + `initialize` + "`" + `.","type":"string"},"isolation":{"$ref":"#/components/schemas/config.IsolationConfig"},"launcher_wait_timeout":{"description":"LauncherWaitTimeout caps how long mcpproxy will wait for a locally-launched\nHTTP/SSE upstream's URL to become reachable after Spawn(). Only consulted\nwhen the server is configured with both Command and an HTTP/SSE URL — i.e.,\nmcpproxy starts the process AND connects via network. Stdio servers ignore\nthis field. Zero or unset → 30s default.","type":"string"},"max_concurrent_requests":{"description":"Per-server concurrency overrides — scope (c) of FR-020 (spec 093, #955).\nTri-state per setting, exactly like HealthCheckInterval: absent = inherit\nthe per-server default set (server_concurrency_defaults), explicit 0 =\ndisable that setting for this server (0 max = no per-server limiter at\nall; 0 queue_size = no pending capacity, shed immediately at the cap),\npositive = override. The global aggregate limiter is never inherited from\nhere — it applies on top, so effective concurrency is min(per-server,\nglobal). Resolved by Config.ResolveServerConcurrency.","type":"integer"},"name":{"type":"string"},"oauth":{"$ref":"#/components/schemas/config.OAuthConfig"},"protocol":{"description":"stdio, http, sse, streamable-http, auto","type":"string"},"quarantined":{"description":"Security quarantine status","type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_on_use":{"description":"Attempt reconnection when a tool call targets a disconnected server","type":"boolean"},"shared":{"description":"Server edition: shared with all users","type":"boolean"},"skip_quarantine":{"description":"SkipQuarantine is DEPRECATED (MCP-2930): use AutoApproveToolChanges instead.\nKept for back-compat parsing; on config load a legacy skip_quarantine:true is\nmigrated to auto_approve_tool_changes:true only when the new field is unset\n(see normalizeServerQuarantineFlags).","type":"boolean"},"source_registry_id":{"description":"SourceRegistryID records which registry this server was added from (empty\nfor manually-configured servers). MCP-866: surfaced in the approval /\nquarantine view so a reviewer can see a server's origin.","type":"string"},"source_registry_provenance":{"description":"SourceRegistryProvenance records the source registry's provenance at add\ntime (RegistryProvenanceOfficial / RegistryProvenanceCustom). It is purely\ninformational (MCP-1072) — surfaced so a reviewer can see a server's origin\n— and no longer gates quarantine or skip_quarantine.","type":"string"},"tool_argument_error_mode":{"description":"ToolArgumentErrorMode stores the per-upstream argument-error policy.\nEmpty and detailed retain detailed errors; redacted opts into redaction.\nUpdates omit/keep an empty value; detailed explicitly resets the policy.","type":"string"},"tool_discovery_interval":{"type":"string"},"toon_output":{"description":"ToonOutput overrides the global toon_output mode for this server's\ntools (spec 084, FR-001). Plain string, not a pointer: \"\"/absent =\ninherit the global value; \"off\"|\"adaptive\"|\"always\" = override (\"off\"\nis the explicit force-off). Resolved by Config.ResolveToonOutput.","type":"string"},"trust_mode":{"description":"TrustMode is the per-server trust tier: auto|scan|manual. Supersedes\nauto_approve_tool_changes (spec 086). An empty value is derived from the\nlegacy fields at load via normalizeServerQuarantineFlags; the single\nresolution point is EffectiveTrustMode(), which treats an empty value as\nscan (DefaultTrustMode, spec 119) and an unrecognized value as manual\n(fail closed). Read via\nEffectiveTrustMode(), never the raw string.","type":"string"},"updated":{"type":"string"},"url":{"type":"string"},"working_dir":{"description":"Working directory for stdio servers","type":"string"}},"type":"object"},"config.TLSConfig":{"description":"TLS configuration","properties":{"cert_file":{"description":"CertFile is the absolute path of an operator-provided server certificate\n(PEM, leaf first), served instead of a generated one. Needs KeyFile.","type":"string"},"certs_dir":{"description":"Directory for certificates","type":"string"},"enabled":{"description":"Enable HTTPS","type":"boolean"},"extra_sans":{"description":"ExtraSANs are DNS names and IP addresses added to the generated server\ncertificate, which is signed by the same local CA. Not used with CertFile.","items":{"type":"string"},"type":"array","uniqueItems":false},"hsts":{"description":"Enable HTTP Strict Transport Security","type":"boolean"},"key_file":{"description":"KeyFile is the absolute path of the private key for CertFile (PEM).","type":"string"},"require_client_cert":{"description":"Enable mTLS","type":"boolean"}},"type":"object"},"config.TelemetryConfig":{"description":"Telemetry settings (Spec 036)","properties":{"anonymous_id":{"description":"Auto-generated UUIDv4","type":"string"},"anonymous_id_created_at":{"description":"Spec 042 (Tier 2) additions — all default-zero, all backwards-compatible.","type":"string"},"enabled":{"description":"Default: true (opt-out)","type":"boolean"},"endpoint":{"description":"Override for testing","type":"string"},"last_reported_version":{"description":"Upgrade funnel","type":"string"},"last_startup_outcome":{"description":"success|port_conflict|db_locked|...","type":"string"},"notice_shown":{"description":"First-run notice flag","type":"boolean"}},"type":"object"},"config.TokenizerConfig":{"description":"Tokenizer configuration for token counting","properties":{"default_model":{"description":"Default model for tokenization (e.g., \"gpt-4\")","type":"string"},"enabled":{"description":"Enable token counting","type":"boolean"},"encoding":{"description":"Default encoding (e.g., \"cl100k_base\")","type":"string"}},"type":"object"},"config.TracingExporterConfig":{"description":"Tracing gates the OpenTelemetry OTLP trace exporter (MCP-32). Disabled by\ndefault.","properties":{"enabled":{"description":"Enabled turns on OTLP trace export for tool calls and upstream hops.","type":"boolean"},"endpoint":{"description":"Endpoint is the collector address as host:port (no scheme), e.g.\n\"localhost:4318\" for http or \"localhost:4317\" for grpc.","type":"string"},"protocol":{"description":"Protocol selects the OTLP transport: \"http\" or \"grpc\".","type":"string"},"sample_rate":{"description":"SampleRate is the head-based trace sampling ratio in [0,1]. Default 0.1.\nOmit the key for the 0.1 default; set it to 0 to sample nothing.","type":"number"}},"type":"object"},"config.UpdateCheckConfig":{"description":"Update-check settings (Spec 079 FR-012): config-file control of the\nbackground upgrade-awareness checker (internal/updatecheck). nil =\nenabled on the stable channel (existing default behavior). The existing\nenvironment switches keep working and WIN over these keys (FR-014):\nMCPPROXY_DISABLE_AUTO_UPDATE=true force-disables even when\nenabled=true, and MCPPROXY_ALLOW_PRERELEASE_UPDATES=true force-selects\nthe rc channel even when channel=stable.","properties":{"channel":{"description":"Channel selects which releases are offered as updates: \"stable\"\n(default; prereleases never offered) or \"rc\" (prereleases included).\nEmpty resolves to stable. Validated in ValidateDetailed.\n\nNOTE: for a RELEASED build the running binary's own version is\nauthoritative and overrides this field — a stable build is never\noffered an RC (even with channel=rc), and an RC build always tracks the\nrc channel. This field only takes effect on dev/unstamped builds. See\ninternal/updatecheck.Checker.IncludePrereleases.","type":"string"},"enabled":{"description":"Enabled gates all update checking. Tri-state: nil/absent = enabled\n(default true, matching pre-079 behavior). When false, no network\ncheck is performed and no upgrade nudge appears on any surface\n(FR-015) — /api/v1/info omits the update object entirely.","type":"boolean"}},"type":"object"},"configimport.FailedServer":{"properties":{"details":{"type":"string"},"error":{"type":"string"},"name":{"type":"string"}},"type":"object"},"configimport.ImportSummary":{"properties":{"failed":{"type":"integer"},"imported":{"type":"integer"},"skipped":{"type":"integer"},"total":{"type":"integer"}},"type":"object"},"configimport.SkippedServer":{"properties":{"name":{"type":"string"},"reason":{"description":"\"already_exists\", \"filtered_out\", \"invalid_name\", \"self_reference\"","type":"string"}},"type":"object"},"connect.ConnectResult":{"description":"The full result; its action mirrors the top-level one","properties":{"action":{"description":"\"created\", \"updated\", \"already_exists\", \"removed\", \"not_found\"","type":"string"},"backup_path":{"type":"string"},"client":{"type":"string"},"config_path":{"type":"string"},"credential":{"description":"Credential is the masked client credential the write embedded\n(` + "`" + `mcp_cli_••••` + "`" + `); the real secret is never returned (FR-024). Empty for a\nkeyless entry, a disconnect and every refusal.","type":"string"},"credential_revoke_error":{"description":"CredentialRevokeError is set when a disconnect removed the entry but\nrevoking the client credential failed. The disconnect still succeeded;\nthe credential is still active and ` + "`" + `mcpproxy client forget \u003cid\u003e` + "`" + `\nretries the revoke.","type":"string"},"credential_revoked":{"description":"CredentialRevoked names the credential that was revoked: by an undo,\nbecause the restored config no longer holds it (plan D16), or by a\ndisconnect, which cuts the client off (a later undo of that disconnect\ndoes not bring the credential back).","type":"string"},"display_path":{"description":"DisplayPath is ConfigPath with the home directory shortened to \"~\"\n(FR-037). Populated for every result whose ConfigPath is known.","type":"string"},"keyless":{"description":"Keyless is true when the entry was written with no credential.","type":"boolean"},"message":{"type":"string"},"mode":{"type":"string"},"profile":{"description":"Profile and Mode are the binding of the credential this write minted or\nkept. Profile \"\" means the built-in All servers scope.","type":"string"},"reload_hint":{"description":"ReloadHint is this client's instruction for making the write take\neffect (FR-037/FR-042), e.g. \"Restart Cursor to load MCPProxy\". Empty\nfor an unknown client.","type":"string"},"rotation":{"description":"Rotation is \"finalized\" when the write replaced an active credential's\nsecret (staged rotation, FR-021a), empty otherwise.","type":"string"},"server_name":{"type":"string"},"success":{"type":"boolean"},"token_name":{"description":"TokenName is the client credential's token name (` + "`" + `client-\u003cid\u003e` + "`" + `).","type":"string"}},"type":"object"},"contracts.APIResponse":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.ActivityDetailResponse":{"properties":{"activity":{"$ref":"#/components/schemas/contracts.ActivityRecord"}},"type":"object"},"contracts.ActivityListResponse":{"properties":{"activities":{"items":{"$ref":"#/components/schemas/contracts.ActivityRecord"},"type":"array","uniqueItems":false},"limit":{"type":"integer"},"offset":{"type":"integer"},"total":{"type":"integer"}},"type":"object"},"contracts.ActivityPerServer":{"properties":{"calls":{"description":"Calls counted per storage.CountsAsCall","type":"integer"},"errors":{"description":"Of those calls, how many failed","type":"integer"},"last_call_at":{"description":"LastCallAt is RFC3339, or \"\" if the server had no call in the period\n(PerServer only lists servers that did, so this is always set).","type":"string"},"name":{"description":"Server name","type":"string"}},"type":"object"},"contracts.ActivityRecord":{"description":"Activity is the stored row; absent on a session_start or session_end\nrow.","properties":{"agent_name":{"description":"Agent token name when auth_type is \"agent\"","type":"string"},"arguments":{"description":"Tool call arguments","type":"object"},"auth_type":{"description":"\"admin\", \"agent\", \"user\" or \"admin_user\"; empty without an auth context or on another caller's row for a scoped caller","type":"string"},"block_reason":{"description":"Typed cause of a profile policy refusal","type":"string"},"client_id":{"description":"Client id from the client-credential binding","type":"string"},"client_name":{"description":"Self-reported clientInfo.name (advisory)","type":"string"},"detection_types":{"description":"List of detection types found","items":{"type":"string"},"type":"array","uniqueItems":false},"duration_ms":{"description":"Execution duration in milliseconds","type":"integer"},"error_class":{"description":"Call-error taxonomy (Spec 113-c FR-045): what failed and whose fault it\nis. Absent on success and on records written before Spec 113.","type":"string"},"error_message":{"description":"Error details if status is \"error\"","type":"string"},"fault_domain":{"description":"upstream|proxy|client","type":"string"},"has_sensitive_data":{"description":"Sensitive data detection fields (Spec 026)","type":"boolean"},"id":{"description":"Unique identifier (ULID format)","type":"string"},"max_severity":{"description":"Highest severity level detected (critical, high, medium, low)","type":"string"},"metadata":{"description":"Additional context-specific data","type":"object"},"parent_id":{"description":"Correlation id of the parent call (the code_execution whose sandbox issued this sub-call)","type":"string"},"profile":{"description":"Scope attribution (Spec 108 FR-029): the profile, client and token in\neffect when the call ran. Stamped at write time, never rewritten. For a\nscoped (non-admin) caller the profile/profile_source/client_id/token_name\nof a row it did not make are blanked (binding disclosure is admin-only);\nclient_name is self-reported and stays. Absent on records written before\nSpec 108 and on records with no MCP/REST request context.","type":"string"},"profile_source":{"description":"pin|binding|url|session|anonymous|none","type":"string"},"request_bytes":{"description":"Byte sizes measured pre-truncation, mirroring storage.ActivityRecord\n(Spec 069 A1). They are the only cost signal a bodies-off export carries:\nwith payloads suppressed there is no text left to measure, so a consumer\naccounting for a record it cannot read has nothing else to go on. They are\nbyte LENGTHS, not token counts — the basis for an explicit estimate, never\na measured figure (spec 103, contracts/replay-input.md).\n\nZero means UNKNOWN, not free: legacy records predate the measurement and\ncode-execution sub-calls record both as zero. Hence omitempty — an absent\nkey tells a consumer to fall to exclusion accounting, whereas a present\nzero would read as a costless call and silently understate the workload.","type":"integer"},"request_id":{"description":"HTTP request ID for correlation","type":"string"},"response":{"description":"Tool response (potentially truncated)","type":"string"},"response_bytes":{"description":"Raw upstream response size in bytes before truncation","type":"integer"},"response_truncated":{"description":"True if response was truncated","type":"boolean"},"server_name":{"description":"Name of upstream MCP server","type":"string"},"session_id":{"description":"MCP transport session ID (regenerated on every reconnect)","type":"string"},"source":{"$ref":"#/components/schemas/contracts.ActivitySource"},"status":{"description":"Result status: \"success\", \"error\", \"blocked\", \"rejected\"","type":"string"},"timestamp":{"description":"When activity occurred","type":"string"},"token_name":{"description":"Agent/client token name","type":"string"},"tool_name":{"description":"Name of tool called","type":"string"},"type":{"$ref":"#/components/schemas/contracts.ActivityType"},"upstream_http_status":{"description":"Upstream HTTP status when known","type":"integer"},"work_session_id":{"description":"Spec 082: one client, one project, across reconnects","type":"string"}},"type":"object"},"contracts.ActivityRetentionReport":{"description":"ActivityRetention (Spec 124 FR-035) reports whether the activity caps\nhold the whole work-session retention window. Administrators only.","properties":{"cause":{"description":"Cause is age_cap, record_cap or size_cap.","type":"string"},"observed_at":{"description":"ObservedAt is when the shortfall was last observed.","type":"string"},"oldest_complete_session_at":{"description":"OldestCompleteSessionAt is the start of the oldest session that still\nhas all of its rows: complete history reaches back to here.","type":"string"},"raise":{"description":"Raise names the settings to raise for the cause.","items":{"type":"string"},"type":"array","uniqueItems":false},"shortfall":{"description":"Shortfall is true when a work session inside the window lost rows\nbecause a cap was reached, and a full window has not passed since.","type":"boolean"},"window_days":{"description":"WindowDays is the work-session retention window.","type":"integer"}},"type":"object"},"contracts.ActivitySource":{"description":"How activity was triggered: \"mcp\", \"cli\", \"api\"","type":"string","x-enum-varnames":["ActivitySourceMCP","ActivitySourceCLI","ActivitySourceAPI"]},"contracts.ActivitySummaryResponse":{"properties":{"blocked_count":{"description":"Count of blocked activities","type":"integer"},"call_count":{"description":"CallCount is how many of those records are CALLS THE USER MADE, as\ndefined once in storage.CountsAsCall and shared with the usage aggregate\nbehind the Usage tab (audit finding F1, #1046). TotalCount answers \"how\nmany rows does the Activity Log have\"; CallCount answers \"how many calls\nwere there\". They are different questions — quarantine auto-approvals,\nsystem start, security scans and management chatter are events, not calls\n— and printing either one under the other's label is how the same instance\ncame to report 51 calls on one screen and 19 on another.","type":"integer"},"call_error_count":{"description":"CallErrorCount is the failures within CallCount, so an error RATE computed\nfrom this response has one denominator. It is not ErrorCount: a policy\nblock is a failed call but carries status \"blocked\", and a shed call is an\nerror in neither sense because it never ran.","type":"integer"},"end_time":{"description":"End of the period (RFC3339)","type":"string"},"error_count":{"description":"Count of error activities","type":"integer"},"other_count":{"description":"OtherCount is every record whose status is outside the four-value\nvocabulary above, so that\n\n\tsuccess + error + blocked + rejected + other == total\n\nholds by construction. The status field is a CLOSED vocabulary for tool\ncalls, but the activity log is wider than tool calls: a quarantine change\nstores its ACTION there (\"approved\", \"auto_approved\"), a policy decision\nstores its DECISION (\"allow\"). Those rows were counted in the total and in\nnone of the four buckets, so the Activity Log's own status tiles summed to\nless than the denominator printed beside them — 15+4+0+0 under a \"42\"\n(audit finding F2, #1046). The residual now has a name and a tile.","type":"integer"},"per_server":{"description":"PerServer covers EVERY server with at least one call in the period\n(unlike TopServers, which is capped at 5 and carries no error counts).\nSpec 109 FR-013: the server-card stats line and the macOS Servers rows\nread this — one ` + "`" + `GET /activity/summary` + "`" + ` response per page load — rather\nthan issuing a per-server activity query each. Computed in the same\ncounting pass as the totals above, from the same CountsAsCall/\nIsManagementBuiltin definitions TopServers already uses.","items":{"$ref":"#/components/schemas/contracts.ActivityPerServer"},"type":"array","uniqueItems":false},"period":{"description":"Time period (1h, 24h, 7d, 30d)","type":"string"},"rejected_count":{"description":"RejectedCount is the number of calls shed by a concurrency limiter, or\nrefused because an agent token was over its call budget, before they\nreached an upstream (spec 093, issue #1699). Counted separately from\nerrors: it is proxy backpressure, not an upstream fault, and it is the\nsignal an operator right-sizes max_concurrent_requests and the rate\nlimits against.","type":"integer"},"start_time":{"description":"Start of the period (RFC3339)","type":"string"},"success_count":{"description":"Count of successful activities","type":"integer"},"top_servers":{"description":"Top servers by activity count","items":{"$ref":"#/components/schemas/contracts.ActivityTopServer"},"type":"array","uniqueItems":false},"top_tools":{"description":"Top tools by activity count","items":{"$ref":"#/components/schemas/contracts.ActivityTopTool"},"type":"array","uniqueItems":false},"total_count":{"description":"Total activity count","type":"integer"}},"type":"object"},"contracts.ActivityTopServer":{"properties":{"count":{"description":"Activity count","type":"integer"},"name":{"description":"Server name","type":"string"}},"type":"object"},"contracts.ActivityTopTool":{"properties":{"count":{"description":"Activity count","type":"integer"},"server":{"description":"Server name","type":"string"},"tool":{"description":"Tool name","type":"string"}},"type":"object"},"contracts.ActivityType":{"description":"Type of activity","type":"string","x-enum-varnames":["ActivityTypeToolCall","ActivityTypePolicyDecision","ActivityTypeQuarantineChange","ActivityTypeServerChange"]},"contracts.AddFromRegistryRequest":{"properties":{"enabled":{"description":"defaults to true when nil","type":"boolean"},"env":{"additionalProperties":{"type":"string"},"description":"overrides + required-input values","type":"object"},"name":{"description":"optional name override","type":"string"}},"type":"object"},"contracts.AddRegistrySourceRequest":{"properties":{"id":{"description":"derived from the host when empty","type":"string"},"name":{"description":"defaults to the id","type":"string"},"protocol":{"description":"defaults to modelcontextprotocol/registry","type":"string"},"url":{"description":"required https registry URL","type":"string"}},"type":"object"},"contracts.AttentionFix":{"properties":{"label":{"type":"string"},"target":{"type":"string"},"verb":{"type":"string"}},"type":"object"},"contracts.AttentionItem":{"properties":{"detail":{"type":"string"},"fix":{"$ref":"#/components/schemas/contracts.AttentionFix"},"id":{"description":"kind:type:subject[:state]","type":"string"},"kind":{"type":"string"},"rank":{"type":"integer"},"since":{"type":"string"},"subject":{"$ref":"#/components/schemas/contracts.AttentionSubject"},"summary":{"type":"string"}},"type":"object"},"contracts.AttentionSubject":{"properties":{"id":{"type":"string"},"name":{"type":"string"},"type":{"description":"server|tool|client|setting","type":"string"}},"type":"object"},"contracts.ConfigApplyResult":{"properties":{"applied_immediately":{"type":"boolean"},"changed_fields":{"items":{"type":"string"},"type":"array","uniqueItems":false},"requires_restart":{"type":"boolean"},"restart_reason":{"type":"string"},"success":{"type":"boolean"},"validation_errors":{"items":{"$ref":"#/components/schemas/contracts.ValidationError"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.DCRStatus":{"properties":{"attempted":{"type":"boolean"},"error":{"type":"string"},"status_code":{"type":"integer"},"success":{"type":"boolean"}},"type":"object"},"contracts.DeepScanDescriptor":{"description":"DeepScan reports the opt-in \"deep scan\" layer status (Spec 077 US3),\nSEPARATELY from the baseline verdict above. Always emitted on a computed\nsummary — when deep scan is off (the default) it reports enabled=false\nplus any enabled-but-skipped Docker scanners. It never influences Status.","properties":{"available":{"type":"boolean"},"enabled":{"type":"boolean"},"ran":{"type":"boolean"},"scanners_failed":{"items":{"$ref":"#/components/schemas/contracts.DeepScanScannerFailure"},"type":"array","uniqueItems":false},"skipped_scanners":{"description":"SkippedScanners lists Docker scanners the user enabled that are skipped\nbecause security.deep_scan.enabled is false (informational).","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.DeepScanScannerFailure":{"properties":{"id":{"type":"string"},"reason":{"type":"string"}},"type":"object"},"contracts.DeprecatedConfigWarning":{"properties":{"field":{"type":"string"},"message":{"type":"string"},"replacement":{"type":"string"}},"type":"object"},"contracts.Diagnostic":{"description":"Spec 044 — structured diagnostic error and stable error code. Both\nare populated when the server is in a failed state and the error\nhas been classified by internal/diagnostics. Healthy servers omit\nthese fields.","properties":{"cause":{"type":"string"},"code":{"type":"string"},"detected_at":{"type":"string"},"docs_url":{"type":"string"},"fix_steps":{"items":{"$ref":"#/components/schemas/contracts.DiagnosticFixStep"},"type":"array","uniqueItems":false},"severity":{"type":"string"},"user_message":{"type":"string"}},"type":"object"},"contracts.DiagnosticFixStep":{"properties":{"command":{"type":"string"},"destructive":{"type":"boolean"},"fixer_key":{"type":"string"},"label":{"type":"string"},"type":{"type":"string"},"url":{"type":"string"}},"type":"object"},"contracts.Diagnostics":{"properties":{"activity_retention":{"$ref":"#/components/schemas/contracts.ActivityRetentionReport"},"deprecated_configs":{"description":"Deprecated config fields found","items":{"$ref":"#/components/schemas/contracts.DeprecatedConfigWarning"},"type":"array","uniqueItems":false},"docker_status":{"$ref":"#/components/schemas/contracts.DockerStatus"},"missing_secrets":{"description":"Renamed to avoid conflict","items":{"$ref":"#/components/schemas/contracts.MissingSecretInfo"},"type":"array","uniqueItems":false},"oauth_issues":{"description":"OAuth parameter mismatches","items":{"$ref":"#/components/schemas/contracts.OAuthIssue"},"type":"array","uniqueItems":false},"oauth_required":{"items":{"$ref":"#/components/schemas/contracts.OAuthRequirement"},"type":"array","uniqueItems":false},"oauth_token_storage":{"$ref":"#/components/schemas/contracts.OAuthTokenStorageReport"},"runtime_warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false},"timestamp":{"type":"string"},"total_issues":{"type":"integer"},"upstream_errors":{"items":{"$ref":"#/components/schemas/contracts.UpstreamError"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.DockerStatus":{"properties":{"available":{"type":"boolean"},"error":{"type":"string"},"version":{"type":"string"}},"type":"object"},"contracts.EditRegistrySourceRequest":{"properties":{"name":{"description":"new display name","type":"string"},"servers_url":{"description":"explicit servers-collection URL","type":"string"},"url":{"description":"new base/servers https URL","type":"string"}},"type":"object"},"contracts.ErrorResponse":{"properties":{"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.FindingCounts":{"properties":{"dangerous":{"description":"Tool poisoning, active prompt injection","type":"integer"},"info":{"description":"Low-severity CVEs, informational","type":"integer"},"total":{"type":"integer"},"warning":{"description":"Rug pull, supply chain CVEs with exploits","type":"integer"}},"type":"object"},"contracts.GetConfigResponse":{"properties":{"config":{"description":"The configuration object","type":"object"},"config_path":{"description":"Path to config file","type":"string"}},"type":"object"},"contracts.GetRegistriesResponse":{"properties":{"registries":{"items":{"$ref":"#/components/schemas/contracts.Registry"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GetServerLogsResponse":{"properties":{"count":{"type":"integer"},"logs":{"items":{"$ref":"#/components/schemas/contracts.LogEntry"},"type":"array","uniqueItems":false},"server_name":{"type":"string"}},"type":"object"},"contracts.GetServerToolCallsResponse":{"properties":{"server_name":{"type":"string"},"tool_calls":{"items":{"$ref":"#/components/schemas/contracts.ToolCallRecord"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GetServerToolsResponse":{"properties":{"count":{"type":"integer"},"incarnation":{"description":"Incarnation is the committed incarnation of the server the tools were\nread for (Spec 116 FR-017), captured before they were fetched; omitted\nwhen unknown.","type":"integer"},"server_name":{"type":"string"},"tools":{"items":{"$ref":"#/components/schemas/contracts.Tool"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.GetServersResponse":{"properties":{"servers":{"items":{"$ref":"#/components/schemas/contracts.Server"},"type":"array","uniqueItems":false},"stats":{"$ref":"#/components/schemas/contracts.ServerStats"}},"type":"object"},"contracts.GetSessionDetailResponse":{"properties":{"session":{"$ref":"#/components/schemas/contracts.MCPSession"}},"type":"object"},"contracts.GetSessionsResponse":{"properties":{"limit":{"type":"integer"},"offset":{"type":"integer"},"sessions":{"items":{"$ref":"#/components/schemas/contracts.MCPSession"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GetToolCallDetailResponse":{"properties":{"tool_call":{"$ref":"#/components/schemas/contracts.ToolCallRecord"}},"type":"object"},"contracts.GetToolCallsResponse":{"properties":{"limit":{"type":"integer"},"offset":{"type":"integer"},"tool_calls":{"items":{"$ref":"#/components/schemas/contracts.ToolCallRecord"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.GlobalToolsResponse":{"properties":{"counts":{"$ref":"#/components/schemas/contracts.ViewAsCounts"},"failed_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"partial":{"type":"boolean"},"stats":{"$ref":"#/components/schemas/contracts.GlobalToolsStats"},"tools":{"items":{"$ref":"#/components/schemas/contracts.Tool"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.GlobalToolsStats":{"properties":{"disabled":{"type":"integer"},"enabled":{"type":"integer"},"pending_approval":{"type":"integer"},"total":{"type":"integer"}},"type":"object"},"contracts.HealthStatus":{"description":"Unified health status calculated by the backend","properties":{"action":{"description":"Action is the suggested fix action: \"login\", \"restart\", \"enable\", \"approve\", \"view_logs\", \"set_secret\", \"configure\", \"edit_url\", or \"\" (none)\nInvariant: Action always equals Actions[0], or \"\" when Actions is empty.","type":"string"},"actions":{"description":"Actions lists every applicable next step in priority order (FR-012):\nlogin \u003e set_secret \u003e configure \u003e edit_url \u003e approve \u003e restart \u003e\nview_logs \u003e enable. Always non-nil (empty slice, never null).","items":{"type":"string"},"type":"array","uniqueItems":false},"admin_state":{"description":"AdminState indicates the admin state: \"enabled\", \"disabled\", or \"quarantined\"","type":"string"},"detail":{"description":"Detail is an optional longer explanation of the status","type":"string"},"level":{"description":"Level indicates the health level: \"healthy\", \"degraded\", or \"unhealthy\"","type":"string"},"status":{"description":"Status is the ONE status vocabulary rendered as text on every surface\n(Web UI, macOS, tray, CLI) — Spec 109 FR-010/FR-011. Values: \"ready\",\n\"connecting\", \"sign_in_required\", \"needs_review\", \"needs_secret\",\n\"needs_config\", \"error\", \"disabled\". Unlike Level (a severity signal for\nbadge/tray coloring only), no renderer may print Level as text.","type":"string"},"summary":{"description":"Summary is a human-readable status message (e.g., \"Connected (5 tools)\")","type":"string"},"usable":{"description":"Usable reports whether the server can currently serve tool calls. True\nonly when Status == \"ready\".","type":"boolean"}},"type":"object"},"contracts.InfoEndpoints":{"description":"Available API endpoints","properties":{"http":{"description":"HTTP endpoint address (e.g., \"127.0.0.1:8080\")","type":"string"},"socket":{"description":"Unix socket path (empty if disabled)","type":"string"}},"type":"object"},"contracts.InfoResponse":{"properties":{"endpoints":{"$ref":"#/components/schemas/contracts.InfoEndpoints"},"launched_by":{"description":"LaunchedBy is the durable launch provenance of the running core (Spec\n092 FR-001a): \"tray\" when a tray spawned it, \"installer\" when the macOS\nPKG postinstall did, \"\" when user-launched or unknown. Always present\n(possibly empty) so a tray can distinguish \"old core, not mine\" from\n\"old core I may supersede\".","type":"string"},"listen_addr":{"description":"Listen address (e.g., \"127.0.0.1:8080\")","type":"string"},"pid":{"description":"PID is the operating-system process id of the running core (Spec 092\nFR-002). A tray that merely ATTACHED to a core holds no Process handle\nfor it, so without this there is no mechanism at all to stop a stale\ncore — the consent action would have nothing to act on and could only\nprint instructions. Paired with LaunchedBy it is what lets a newer tray\nsupersede a core an older tray started.","type":"integer"},"update":{"$ref":"#/components/schemas/contracts.UpdateInfo"},"update_policy":{"$ref":"#/components/schemas/contracts.UpdatePolicy"},"version":{"description":"Current MCPProxy version","type":"string"},"web_ui_url":{"description":"URL to access the web control panel","type":"string"}},"type":"object"},"contracts.IsolationConfig":{"properties":{"cpu_limit":{"type":"string"},"enabled":{"description":"Enabled is the EFFECTIVE isolation state for this server: whether its\nprocess is actually CONFINED, after the global setting, the per-server\noverride, the structural gates and the host's capabilities. It is NOT the\nraw per-server override — read EnabledOverride for that (GH #1142).\n\nREAD-ONLY. The write surfaces reject an ` + "`" + `enabled` + "`" + ` key precisely because\nit is derived: echoing it back would convert \"inherits the global\nsetting\" into a permanent explicit override. Write EnabledOverride.\n\nIt stays a non-pointer bool that is always present on the wire: the macOS\ntray decodes it as a non-optional Swift Bool, so omitting or nulling the\nkey would fail Codable for the whole server payload. Older clients that\nread this field now simply get a true answer.","type":"boolean"},"enabled_override":{"description":"EnabledOverride is the RAW per-server ` + "`" + `isolation.enabled` + "`" + ` override, as\npersisted. Absent means \"inherit the global setting\" — which is a\ndistinct state from an explicit false, and the distinction the reporting\nbug used to destroy.","type":"boolean"},"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"memory_limit":{"type":"string"},"mode_override":{"description":"ModeOverride is the RAW per-server ` + "`" + `isolation.mode` + "`" + ` override\n(\"docker\" | \"sandbox\" | \"none\"). Absent means \"inherit\".","type":"string"},"network_mode":{"type":"string"},"timeout":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"contracts.IsolationDefaults":{"description":"IsolationDefaults exposes the resolved baseline values that\nwould apply when no per-server override is set. Populated on\nlist/get responses; never consumed on PATCH requests.","properties":{"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"network_mode":{"type":"string"},"runtime_type":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"contracts.IsolationEffective":{"description":"IsolationEffective exposes the resolved isolation state (and the rule\nthat decided it) so clients can distinguish \"inherits global\" from an\nexplicit per-server choice. Read-only; never consumed on PATCH.","properties":{"global_mode":{"description":"GlobalMode is what \"inherit\" resolves to right now.","type":"string"},"inherited":{"description":"Inherited is true when the server sets neither ` + "`" + `isolation.enabled` + "`" + ` nor\n` + "`" + `isolation.mode` + "`" + `, so its state tracks the global setting.","type":"boolean"},"isolated":{"description":"Isolated reports whether the process is actually CONFINED. It is NOT\nsimply Mode != \"none\": \"sandbox\" on a host that cannot enforce Landlock\n(any non-Linux OS, or a kernel without the LSM) runs the server\nunconfined, and Source then says \"sandbox-unavailable\" (GH #1142).","type":"boolean"},"mode":{"description":"Mode is the effective isolation mode: \"docker\" | \"sandbox\" | \"none\" —\nexactly what the spawn path branches on.","type":"string"},"source":{"description":"Source names the deciding rule: \"global\", \"server-mode\",\n\"server-opt-out\", \"server-opt-in-ignored\", \"not-stdio\",\n\"already-docker\", \"sandbox-unavailable\" or \"unsupported-mode\".\nTreat an unrecognized value as \"global\".","type":"string"}},"type":"object"},"contracts.LogEntry":{"properties":{"fields":{"type":"object"},"level":{"type":"string"},"message":{"type":"string"},"server":{"type":"string"},"timestamp":{"type":"string"}},"type":"object"},"contracts.MCPSession":{"properties":{"client_id":{"description":"Scope attribution (Spec 108 FR-033). ClientID and TokenName are the\ncredential the session initialized with; Profile and ProfileSource are\nthe session's latest effective resolution. Empty on legacy sessions.","type":"string"},"client_name":{"type":"string"},"client_version":{"type":"string"},"end_time":{"type":"string"},"experimental":{"items":{"type":"string"},"type":"array","uniqueItems":false},"has_roots":{"description":"MCP Client Capabilities","type":"boolean"},"has_sampling":{"type":"boolean"},"id":{"type":"string"},"last_activity":{"type":"string"},"profile":{"type":"string"},"profile_source":{"type":"string"},"start_time":{"type":"string"},"status":{"type":"string"},"token_name":{"type":"string"},"tool_call_count":{"type":"integer"},"total_tokens":{"type":"integer"},"work_session_id":{"type":"string"},"workspace_name":{"description":"Workspace / work session (Spec 082). WorkspaceName is the project's\nbasename — the full local path is never exposed. WorkSessionID groups the\nreconnects that make up one stretch of user work.","type":"string"}},"type":"object"},"contracts.MetadataStatus":{"properties":{"authorization_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"error":{"type":"string"},"found":{"type":"boolean"},"url_checked":{"type":"string"}},"type":"object"},"contracts.MissingSecretInfo":{"properties":{"secret_name":{"type":"string"},"used_by":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.NPMPackageInfo":{"properties":{"exists":{"type":"boolean"},"install_cmd":{"type":"string"}},"type":"object"},"contracts.OAuthConfig":{"properties":{"auth_server_metadata_url":{"type":"string"},"auth_url":{"type":"string"},"authorization_endpoint":{"description":"Spec 113-b operator overrides of OAuth discovery (https-or-loopback URLs,\nnever credentials). Empty means \"use discovery\".","type":"string"},"client_id":{"type":"string"},"extra_params":{"additionalProperties":{"type":"string"},"type":"object"},"pkce_enabled":{"type":"boolean"},"redirect_port":{"type":"integer"},"refresh_replay_enabled":{"type":"boolean"},"registration_endpoint":{"type":"string"},"scopes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"token_endpoint":{"type":"string"},"token_expires_at":{"description":"When the OAuth token expires","type":"string"},"token_url":{"type":"string"},"token_valid":{"description":"Whether token is currently valid","type":"boolean"}},"type":"object"},"contracts.OAuthErrorDetails":{"description":"Structured discovery/failure details","properties":{"authorization_server_metadata":{"$ref":"#/components/schemas/contracts.MetadataStatus"},"dcr_status":{"$ref":"#/components/schemas/contracts.DCRStatus"},"protected_resource_metadata":{"$ref":"#/components/schemas/contracts.MetadataStatus"},"server_url":{"type":"string"}},"type":"object"},"contracts.OAuthFlowError":{"properties":{"correlation_id":{"description":"Flow tracking ID for log correlation","type":"string"},"debug_hint":{"description":"CLI command for log lookup","type":"string"},"details":{"$ref":"#/components/schemas/contracts.OAuthErrorDetails"},"error_code":{"description":"Machine-readable error code (e.g., OAUTH_NO_METADATA)","type":"string"},"error_type":{"description":"Category of OAuth runtime failure","type":"string"},"message":{"description":"Human-readable error description","type":"string"},"request_id":{"description":"HTTP request ID (from PR #237)","type":"string"},"server_name":{"description":"Server that failed OAuth","type":"string"},"success":{"description":"Always false","type":"boolean"},"suggestion":{"description":"Actionable remediation hint","type":"string"}},"type":"object"},"contracts.OAuthIssue":{"properties":{"documentation_url":{"type":"string"},"error":{"type":"string"},"issue":{"type":"string"},"missing_params":{"items":{"type":"string"},"type":"array","uniqueItems":false},"resolution":{"type":"string"},"server_name":{"type":"string"}},"type":"object"},"contracts.OAuthRequirement":{"properties":{"expires_at":{"type":"string"},"message":{"type":"string"},"server_name":{"type":"string"},"state":{"type":"string"}},"type":"object"},"contracts.OAuthStartResponse":{"properties":{"auth_url":{"description":"Authorization URL (always included for manual use)","type":"string"},"browser_error":{"description":"Error message if browser launch failed","type":"string"},"browser_opened":{"description":"Whether browser launch succeeded","type":"boolean"},"correlation_id":{"description":"UUID for tracking this flow","type":"string"},"message":{"description":"Human-readable status message","type":"string"},"server_name":{"description":"Name of the server being authenticated","type":"string"},"success":{"description":"Always true for successful start","type":"boolean"}},"type":"object"},"contracts.OAuthTokenStorageReport":{"description":"OAuthTokenStorage (Spec 123 FR-030) reports the state of the stored\nupstream OAuth rows: encryption on or off, the public key id, the row\ncounts by state, the undecryptable servers and the compaction advice.\nIt never carries key material or the key reference.","properties":{"compaction_advised":{"description":"CompactionAdvised mirrors the compaction marker: freed pages may still\nhold old plaintext until ` + "`" + `mcpproxy db compact --keep-backup=false` + "`" + `.","type":"boolean"},"encryption_enabled":{"description":"EncryptionEnabled is true when an encryption key is configured.","type":"boolean"},"key_id":{"description":"KeyID is the public, non-secret id of the configured key (administrator only).","type":"string"},"key_source_in_data_dir":{"description":"KeySourceInDataDir is true when the key file lies inside the data directory.","type":"boolean"},"key_source_kind":{"description":"KeySourceKind is how the key was obtained: literal, env, env_file,\nref_file, ref_env or ref_keyring (administrator only).","type":"string"},"plaintext":{"description":"Plaintext counts valid JSON rows; Sealed counts envelopes the configured\nkey opens; Undecryptable counts everything else.","type":"integer"},"sealed":{"type":"integer"},"servers":{"description":"Servers lists the undecryptable rows by server.","items":{"$ref":"#/components/schemas/contracts.OAuthTokenStorageServer"},"type":"array","uniqueItems":false},"undecryptable":{"type":"integer"},"undecryptable_by_reason":{"$ref":"#/components/schemas/contracts.OAuthTokenUndecryptableByReason"},"warnings":{"description":"Warnings are stable codes: literal_key, key_file_in_data_dir,\nplaintext_rows_with_key, compaction_advised, backup_file_present\n(administrator only).","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.OAuthTokenStorageServer":{"properties":{"bucket_key":{"type":"string"},"reason":{"type":"string"},"row_key_id":{"description":"RowKeyID is the key id in the row's envelope (administrator only).","type":"string"},"server":{"type":"string"}},"type":"object"},"contracts.OAuthTokenUndecryptableByReason":{"description":"UndecryptableByReason breaks Undecryptable down by reason.","properties":{"auth_failed":{"type":"integer"},"key_mismatch":{"type":"integer"},"malformed":{"type":"integer"},"no_key":{"type":"integer"},"unsupported_version":{"type":"integer"}},"type":"object"},"contracts.PreflightPolicy":{"properties":{"exclude_destructive":{"type":"boolean"},"exclude_open_world":{"type":"boolean"},"read_only_only":{"type":"boolean"}},"type":"object"},"contracts.PreflightReason":{"type":"string","x-enum-varnames":["PreflightReasonServerInitializing","PreflightReasonServerUnhealthy","PreflightReasonServerDisabled","PreflightReasonServerQuarantined","PreflightReasonToolPendingApproval","PreflightReasonToolChanged","PreflightReasonToolBlockedByUser","PreflightReasonOAuthRequired","PreflightReasonHashMismatch","PreflightReasonServerNotInScope","PreflightReasonToolDeniedByConfig","PreflightReasonMissingAnnotation","PreflightReasonPolicyFiltered","PreflightReasonNotFound","PreflightReasonServerNotConfigured","PreflightReasonToolBlockedByProfile","PreflightReasonTokenPermissionDenied"]},"contracts.PreflightRequest":{"properties":{"policy":{"$ref":"#/components/schemas/contracts.PreflightPolicy"},"profile":{"description":"Profile evaluates under a named profile's server scope and tool policy;\nit can only narrow a credential's own pin. Unknown: 400.","type":"string"},"tools":{"description":"Tools is 1..100 entries BEFORE dedup; duplicates are collapsed, and\nduplicate ids carrying different pins are a validation error.","items":{"$ref":"#/components/schemas/contracts.PreflightToolRef"},"type":"array","uniqueItems":false},"wait_ms":{"description":"WaitMS polls local state for up to this many milliseconds (cap 10000)\nwhile every failure is retryable-class.","type":"integer"}},"type":"object"},"contracts.PreflightResponse":{"properties":{"checked_at":{"type":"string"},"tools":{"description":"Tools are ordered by first occurrence of each unique id in the request.","items":{"$ref":"#/components/schemas/contracts.PreflightToolResult"},"type":"array","uniqueItems":false},"verdict":{"$ref":"#/components/schemas/contracts.PreflightVerdict"},"waited_ms":{"description":"WaitedMS is present when wait_ms was requested (0 when the wait\nsemaphore was exhausted and the request resolved immediately).","type":"integer"}},"type":"object"},"contracts.PreflightStatus":{"type":"string","x-enum-varnames":["PreflightStatusReady","PreflightStatusUnavailable"]},"contracts.PreflightToolRef":{"properties":{"id":{"description":"ID is a canonical \"\u003cserver\u003e:\u003ctool\u003e\" id. A malformed id is answered with a\nper-ID not_found carrying a format hint, never a request-level error.","type":"string"},"pin_hash":{"description":"PinHash is \"sha256/v{N}:{hex}\" — the schema version is embedded so a\nproxy-side hash-algorithm bump is distinguishable from upstream drift.","type":"string"}},"type":"object"},"contracts.PreflightToolResult":{"properties":{"action":{"type":"string"},"detail":{"type":"string"},"did_you_mean":{"description":"DidYouMean carries up to 3 nearest caller-visible ids on not_found. It\nnever crosses a scope boundary and never names a quarantined server's\ntools.","items":{"type":"string"},"type":"array","uniqueItems":false},"hash":{"description":"Hash is the tool's current pin (\"sha256/v{N}:{hex}\") — operator tier,\nready results only. Never disclosed to an agent token.","type":"string"},"id":{"type":"string"},"reason":{"$ref":"#/components/schemas/contracts.PreflightReason"},"remediation":{"type":"string"},"retryable":{"type":"boolean"},"status":{"$ref":"#/components/schemas/contracts.PreflightStatus"}},"type":"object"},"contracts.PreflightVerdict":{"type":"string","x-enum-varnames":["PreflightVerdictReady","PreflightVerdictDegradedRetryable","PreflightVerdictBlocked","PreflightVerdictUnknownIDs"]},"contracts.QuarantineStats":{"description":"Tool quarantine metrics for this server","properties":{"blocked_count":{"description":"Number of disabled (blocked) tools","type":"integer"},"changed_count":{"description":"Number of tools whose description/schema changed since approval","type":"integer"},"pending_count":{"description":"Number of newly discovered tools awaiting approval","type":"integer"}},"type":"object"},"contracts.RefreshRegistryResponse":{"properties":{"cleared":{"description":"number of cached entries dropped","type":"integer"},"registry_id":{"type":"string"}},"type":"object"},"contracts.Registry":{"properties":{"count":{"description":"number or string","type":"string"},"description":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"},"protocol":{"type":"string"},"provenance":{"description":"Provenance is the trust tag (MCP-866): \"official/trusted\" for built-in\ndefaults, \"custom/unverified\" for user-added registries.","type":"string"},"servers_url":{"type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"trusted":{"description":"Trusted indicates whether this is an official, shipped-by-default\nregistry. Trust is derived from membership in the default set, never\nfrom self-assertion in config.","type":"boolean"},"url":{"type":"string"}},"type":"object"},"contracts.RegistryCacheInfo":{"properties":{"age_seconds":{"type":"number"},"stale":{"type":"boolean"}},"type":"object"},"contracts.RegistryUnavailable":{"properties":{"reason":{"type":"string"}},"type":"object"},"contracts.ReplayToolCallRequest":{"properties":{"arguments":{"description":"Modified arguments for replay","type":"object"}},"type":"object"},"contracts.ReplayToolCallResponse":{"properties":{"error":{"description":"Error if replay failed","type":"string"},"new_call_id":{"description":"ID of the newly created call","type":"string"},"new_tool_call":{"$ref":"#/components/schemas/contracts.ToolCallRecord"},"replayed_from":{"description":"Original call ID","type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.RepositoryInfo":{"description":"Detected package info","properties":{"npm":{"$ref":"#/components/schemas/contracts.NPMPackageInfo"}},"type":"object"},"contracts.RepositoryServer":{"properties":{"connect_url":{"description":"Alternative connection URL","type":"string"},"created_at":{"type":"string"},"description":{"type":"string"},"id":{"type":"string"},"install_cmd":{"description":"Installation command","type":"string"},"name":{"type":"string"},"registry":{"description":"Which registry this came from","type":"string"},"repository_info":{"$ref":"#/components/schemas/contracts.RepositoryInfo"},"source_code_url":{"description":"Source repository URL","type":"string"},"updated_at":{"type":"string"},"url":{"description":"MCP endpoint for remote servers only","type":"string"}},"type":"object"},"contracts.SearchRegistryServersResponse":{"properties":{"cache":{"$ref":"#/components/schemas/contracts.RegistryCacheInfo"},"query":{"type":"string"},"registry_id":{"type":"string"},"servers":{"items":{"$ref":"#/components/schemas/contracts.RepositoryServer"},"type":"array","uniqueItems":false},"tag":{"type":"string"},"total":{"type":"integer"},"unavailable":{"$ref":"#/components/schemas/contracts.RegistryUnavailable"}},"type":"object"},"contracts.SearchResult":{"properties":{"matches":{"type":"integer"},"score":{"type":"number"},"snippet":{"type":"string"},"tool":{"$ref":"#/components/schemas/contracts.Tool"}},"type":"object"},"contracts.SearchToolsResponse":{"properties":{"query":{"type":"string"},"results":{"items":{"$ref":"#/components/schemas/contracts.SearchResult"},"type":"array","uniqueItems":false},"took":{"type":"string"},"total":{"type":"integer"}},"type":"object"},"contracts.SecurityScanSummary":{"description":"Latest security scan results summary","properties":{"deep_scan":{"$ref":"#/components/schemas/contracts.DeepScanDescriptor"},"finding_counts":{"$ref":"#/components/schemas/contracts.FindingCounts"},"last_scan_at":{"type":"string"},"risk_score":{"description":"0-100","type":"integer"},"scanners_failed":{"type":"integer"},"scanners_run":{"description":"Scanner coverage for the primary (baseline) scan pass — informational only.\nSpec 077 US3 (FR-008/FR-014): Status is derived SOLELY from the\ndeterministic baseline findings; a failed Docker deep scanner no longer\ndowngrades a clean verdict. That failure is surfaced via DeepScan instead.","type":"integer"},"scanners_total":{"type":"integer"},"status":{"description":"\"clean\", \"warnings\", \"dangerous\", \"failed\", \"not_scanned\", \"scanning\"","type":"string"}},"type":"object"},"contracts.Server":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"authenticated":{"description":"OAuth authentication status","type":"boolean"},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges mirrors config.ServerConfig.AutoApproveToolChanges\n(MCP-2930): the per-server intent to auto-approve new/changed tools past\nthe trust baseline. Tri-state *bool — nil means \"never set\" (omitted from\nthe payload), so the Web UI toggle (MCP-2932) can distinguish unset from\nan explicit false. Read-only on the GET path; PATCH/POST accept it via\nAddServerRequest.","type":"boolean"},"command":{"type":"string"},"connected":{"type":"boolean"},"connected_at":{"type":"string"},"connecting":{"type":"boolean"},"created":{"type":"string"},"diagnostic":{"$ref":"#/components/schemas/contracts.Diagnostic"},"enabled":{"type":"boolean"},"env":{"additionalProperties":{"type":"string"},"type":"object"},"error_code":{"type":"string"},"expose_prompts":{"description":"ExposePrompts mirrors config.ServerConfig.ExposePrompts (F9): the per-server\nprompt-aggregation override. Tri-state *bool — nil/omitted means \"inherit\ndefault aggregation\". Surfaced on GET so a caller that PATCHed the override\ncan read it back; PATCH/POST accept it via AddServerRequest.","type":"boolean"},"expose_skills":{"description":"ExposeSkills mirrors config.ServerConfig.ExposeSkills: the per-server\nskills override. Tri-state *bool; nil/omitted means \"inherit\".","type":"boolean"},"forward_headers":{"description":"ForwardHeaders mirrors config.ServerConfig.ForwardHeaders (Spec 112): the\nallowlist of inbound MCP client header NAMES forwarded to this server on\ntools/call. Names only, never values. Omitted when empty.","items":{"type":"string"},"type":"array","uniqueItems":false},"generation":{"description":"Generation is the server's committed config generation (Spec 116\nFR-017): it changes whenever the server's configuration changes.","type":"integer"},"headers":{"additionalProperties":{"type":"string"},"type":"object"},"health":{"$ref":"#/components/schemas/contracts.HealthStatus"},"id":{"type":"string"},"incarnation":{"description":"Incarnation changes only when the name is removed and created again\n(Spec 116 FR-017). Approval endpoints accept it back as\nexpected_incarnation and answer 409 server_replaced on a mismatch.","type":"integer"},"init_timeout":{"description":"InitTimeout mirrors config.ServerConfig.InitTimeout (MCP-3322 / GH #760):\nthe per-server MCP ` + "`" + `initialize` + "`" + ` handshake deadline override. Serialized as\na duration string (e.g. \"120s\"); nil/omitted means \"inherit the global\ndefault\". Surfaced on the GET path so clients can read back a configured\noverride; PATCH/POST accept it via AddServerRequest.","type":"string"},"isolation":{"$ref":"#/components/schemas/contracts.IsolationConfig"},"isolation_defaults":{"$ref":"#/components/schemas/contracts.IsolationDefaults"},"isolation_effective":{"$ref":"#/components/schemas/contracts.IsolationEffective"},"last_error":{"type":"string"},"last_reconnect_at":{"type":"string"},"last_retry_time":{"type":"string"},"max_concurrent_requests":{"description":"Spec 093 (GH #955) — per-server concurrency overrides, scope (c) of\nFR-020. Each setting is tri-state: nil (omitted) means \"inherit\nserver_concurrency_defaults\", 0 disables that setting for this server,\npositive overrides it. Surfaced on the GET path so a caller can read back\nwhat it set; PATCH/POST accept them via AddServerRequest. The effective\nconcurrency for a server is additionally bounded by the global aggregate\nlimiter, which is NOT an inheritance source for these fields.","type":"integer"},"name":{"type":"string"},"oauth":{"$ref":"#/components/schemas/contracts.OAuthConfig"},"oauth_status":{"description":"OAuth status: \"authenticated\", \"expired\", \"error\", \"none\"","type":"string"},"protocol":{"type":"string"},"quarantine":{"$ref":"#/components/schemas/contracts.QuarantineStats"},"quarantined":{"type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_count":{"type":"integer"},"reconnect_on_use":{"description":"Attempt reconnection when a tool call targets this disconnected server","type":"boolean"},"retry_count":{"type":"integer"},"retry_stopped":{"description":"RetryStopped reports that automatic reconnection has been given up for\ngood because the failure is deterministic and unrecoverable — a missing\nbinary, an image without the interpreter, an unparseable config (GH\n#1145). It is NOT ordinary exponential backoff, which keeps retrying;\nnothing will happen until the user fixes the config or restarts the\nserver. RetryStoppedCode is the stable MCPX_* code that proved it and\nRetryStoppedReason the catalog message explaining how to fix it. All three\nare omitted for servers that are healthy or still retrying.","type":"boolean"},"retry_stopped_code":{"type":"string"},"retry_stopped_reason":{"type":"string"},"security_scan":{"$ref":"#/components/schemas/contracts.SecurityScanSummary"},"should_retry":{"type":"boolean"},"source_registry_id":{"description":"MCP-901 — registry provenance of an upstream that was added from a\nregistry. SourceRegistryID names the source registry (empty for\nmanually-configured servers); SourceRegistryProvenance is the trust tag\nrecorded at add time (\"official/trusted\" or \"custom/unverified\"). Both\nare projected from config.ServerConfig so the approval/quarantine view\ncan render an \"added from \u003cregistry\u003e · unverified\" origin badge. Optional\nand omitted when empty — clients that pre-date this treat them as absent.","type":"string"},"source_registry_provenance":{"type":"string"},"status":{"type":"string"},"token_expires_at":{"description":"When the OAuth token expires (ISO 8601)","type":"string"},"tool_argument_error_mode":{"type":"string"},"tool_count":{"type":"integer"},"tool_list_token_size":{"description":"Token size for this server's tools","type":"integer"},"trust_mode":{"description":"TrustMode mirrors config.ServerConfig.TrustMode (spec 086): the per-server\ntrust tier (\"auto\"/\"scan\"/\"manual\"). Surfaced on the GET path so clients can\nread back the persisted mode; PATCH/POST accept it via AddServerRequest.\nOmitted when empty (server predates the field / relies on legacy flags).","type":"string"},"updated":{"type":"string"},"url":{"type":"string"},"user_logged_out":{"description":"True if user explicitly logged out (prevents auto-reconnection)","type":"boolean"},"working_dir":{"type":"string"}},"type":"object"},"contracts.ServerActionResponse":{"properties":{"action":{"type":"string"},"async":{"type":"boolean"},"server":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.ServerStats":{"properties":{"connected_servers":{"type":"integer"},"docker_containers":{"type":"integer"},"quarantined_servers":{"type":"integer"},"token_metrics":{"$ref":"#/components/schemas/contracts.ServerTokenMetrics"},"total_servers":{"type":"integer"},"total_tools":{"type":"integer"}},"type":"object"},"contracts.ServerTokenMetrics":{"properties":{"average_query_result_size":{"description":"Typical retrieve_tools output (tokens)","type":"integer"},"estimated":{"description":"Estimated (Spec 109-k FR-070-ish, url-filter-contract.md / audit F-Token):\ntrue while AverageQueryResultSize is a synthetic simulation (a sample of\nthe first ` + "`" + `tools_limit` + "`" + ` tools' schemas — no real retrieve_tools call has\ncompleted yet in this runtime's usage aggregate); false once at least one\nreal retrieve_tools call has, at which point AverageQueryResultSize is\nderived from the real observed average response size instead. The Web\nUI and macOS render an \"estimate\" label while this is true.","type":"boolean"},"per_server_tool_list_sizes":{"additionalProperties":{"type":"integer"},"description":"Token size per server","type":"object"},"saved_tokens":{"description":"Difference","type":"integer"},"saved_tokens_percentage":{"description":"Percentage saved","type":"number"},"total_server_tool_list_size":{"description":"All upstream tools combined (tokens)","type":"integer"}},"type":"object"},"contracts.SkillContentResponse":{"properties":{"digest":{"type":"string"},"next_offset":{"description":"NextOffset is the byte offset of the next chunk; absent at the end.","type":"integer"},"offset":{"type":"integer"},"size":{"type":"integer"},"text":{"type":"string"}},"type":"object"},"contracts.SkillEntry":{"properties":{"approved_at":{"description":"ApprovedAt is omitted when the skill was never approved.","type":"string"},"approved_by":{"type":"string"},"approved_files":{"description":"ApprovedFiles is the file set of the approved copy; omitted when the\nskill has no approved copy. ` + "`" + `skills show --diff` + "`" + ` compares it with Files.","items":{"$ref":"#/components/schemas/contracts.SkillFileInfo"},"type":"array","uniqueItems":false},"approved_hash":{"type":"string"},"available":{"type":"boolean"},"blocked":{"type":"boolean"},"current_hash":{"type":"string"},"description":{"type":"string"},"files":{"items":{"$ref":"#/components/schemas/contracts.SkillFileInfo"},"type":"array","uniqueItems":false},"id":{"type":"string"},"listed":{"type":"boolean"},"name":{"type":"string"},"path":{"type":"string"},"scan":{"$ref":"#/components/schemas/contracts.SkillScanInfo"},"status":{"type":"string"},"total_size":{"type":"integer"},"unusable_reason":{"type":"string"},"uri":{"type":"string"}},"type":"object"},"contracts.SkillFileInfo":{"properties":{"digest":{"type":"string"},"path":{"type":"string"},"size":{"type":"integer"},"text":{"type":"boolean"}},"type":"object"},"contracts.SkillScanFinding":{"properties":{"evidence":{"type":"string"},"file":{"type":"string"},"offset":{"type":"integer"},"rule":{"type":"string"},"severity":{"type":"string"}},"type":"object"},"contracts.SkillScanInfo":{"properties":{"complete":{"type":"boolean"},"findings":{"items":{"$ref":"#/components/schemas/contracts.SkillScanFinding"},"type":"array","uniqueItems":false},"findings_truncated":{"description":"FindingsTruncated is true when more findings existed than are listed.","type":"boolean"},"incomplete":{"description":"Incomplete says why Complete is false: size_cap, time_limit, coverage or\ninterrupted; empty when the scan is complete.","type":"string"},"scanned_at":{"description":"ScannedAt is omitted when no scan of the current content exists.","type":"string"},"verdict":{"type":"string"}},"type":"object"},"contracts.SkillsApproveRequest":{"properties":{"expected_hashes":{"additionalProperties":{"type":"string"},"description":"ExpectedHashes maps each skill path to the current_hash the reviewer\nsaw. A skill without an entry is refused as unreviewed.","type":"object"},"expected_incarnation":{"description":"ExpectedIncarnation binds the approval to the server the reviewer saw;\n0 (or absent) binds to the incarnation current when the request starts.","type":"integer"},"skills":{"description":"Skills are skill paths (the part of the id after \"\u003cserver\u003e:\"), 1 to 200.","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.SkillsApproveResponse":{"properties":{"approved":{"description":"Approved counts the skills newly approved; a skill already approved for\nits current content is not counted.","type":"integer"}},"type":"object"},"contracts.SkillsBlockRequest":{"properties":{"expected_incarnation":{"type":"integer"},"skills":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.SkillsBlockResponse":{"properties":{"changed":{"description":"Changed counts the skills whose blocked mark changed.","type":"integer"}},"type":"object"},"contracts.SkillsErrorResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.SkillsListResponse":{"properties":{"enabled":{"type":"boolean"},"error":{"type":"string"},"expose_skills":{"type":"boolean"},"incarnation":{"description":"Incarnation is the server's approval incarnation: send it back as\nexpected_incarnation on approve, block and unblock.","type":"integer"},"last_refresh":{"type":"string"},"server":{"type":"string"},"skills":{"items":{"$ref":"#/components/schemas/contracts.SkillEntry"},"type":"array","uniqueItems":false},"supported":{"type":"boolean"},"truncated":{"type":"boolean"}},"type":"object"},"contracts.SkillsStaleReviewResponse":{"properties":{"changed":{"items":{"type":"string"},"type":"array","uniqueItems":false},"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"},"unreviewed":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.SkillsUnusableResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"skills":{"items":{"type":"string"},"type":"array","uniqueItems":false},"success":{"type":"boolean"}},"type":"object"},"contracts.SuccessResponse":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"success":{"type":"boolean"}},"type":"object"},"contracts.Tier":{"description":"Tier is computed by AnnotationTier (Spec 109 FR-028/X11) from\nAnnotations — read|write|destructive|unannotated. Set by every producer\nof a Tool (enrichServerTools, the global tools handler); never left for\na consuming surface to compute.","type":"string","x-enum-varnames":["TierRead","TierWrite","TierDestructive","TierUnannotated","TierUnknown"]},"contracts.TokenMetrics":{"description":"Token usage metrics (nil for older records)","properties":{"encoding":{"description":"Encoding used (e.g., cl100k_base)","type":"string"},"estimated_cost":{"description":"Optional cost estimate","type":"number"},"input_tokens":{"description":"Tokens in the request","type":"integer"},"model":{"description":"Model used for tokenization","type":"string"},"output_tokens":{"description":"Tokens in the response","type":"integer"},"total_tokens":{"description":"Total tokens (input + output)","type":"integer"},"truncated_tokens":{"description":"Tokens removed by truncation","type":"integer"},"was_truncated":{"description":"Whether response was truncated","type":"boolean"}},"type":"object"},"contracts.Tool":{"properties":{"access":{"$ref":"#/components/schemas/contracts.ToolAccess"},"annotations":{"$ref":"#/components/schemas/contracts.ToolAnnotation"},"approval_status":{"type":"string"},"config_denied":{"description":"ConfigDenied is true when the tool is denied by the server's static\nenabled_tools / disabled_tools config. The user cannot override this toggle.","type":"boolean"},"description":{"type":"string"},"disabled":{"description":"Disabled mirrors ToolApprovalRecord.Disabled so per-tool enable state is\navailable without a second round-trip to the approvals endpoint. Absent\nin the JSON when false (default) to keep responses compact.","type":"boolean"},"hash":{"description":"Hash is the tool's current stored hash rendered in the preflight pin\nformat \"sha256/v{N}:{hex}\" (Spec 098 FR-011), where N is the approval\nrecord's HashSchemaVersion. It is the authoring surface for\n` + "`" + `POST /api/v1/preflight` + "`" + ` pins and ` + "`" + `mcpproxy tools preflight --pin` + "`" + `:\ncopy the value straight into a pin.\n\nDisclosure is OPERATOR TIER ONLY — same rule as the preflight per-tool\nresult. The field is omitted for agent-token callers and for tools with\nno stored hash (no approval record yet, or a record written before\nhashes existed).","type":"string"},"held_reason":{"description":"HeldReason, HeldVerdict and HeldSignals mirror the same-named fields on\nstorage.ToolApprovalRecord: the offline-scan evidence that made\ntrust_mode: scan hold this tool for review (spec 086 FR-018). HeldSignals\nnames the matched deterministic check ids, e.g.\n\"tpa.TPA-2026-0001.hidden_instruction\", so a reviewer can see WHY the tool\nis held. All three are omitted for tools that are not held by the scan gate\n(including every record written before the field existed).","type":"string"},"held_signals":{"items":{"type":"string"},"type":"array","uniqueItems":false},"held_verdict":{"type":"string"},"last_used":{"type":"string"},"name":{"type":"string"},"profile_tier":{"description":"ProfileTier and Access are present only in a view-as listing (a tools\nlisting with ?client= or ?profile=, Spec 108 FR-032). ProfileTier is the\ntool's tier under the viewed subject's profile (Tier above stays the\nintrinsic tier); Access is the subject's verdict for the tool. Absent\notherwise, so an ordinary listing is byte-identical to before.","type":"string","x-enum-varnames":["TierRead","TierWrite","TierDestructive","TierUnannotated","TierUnknown"]},"schema":{"type":"object"},"server_incarnation":{"description":"ServerIncarnation is the committed incarnation of the server this row\nwas read for (Spec 116 FR-017), captured before the tools were fetched.\nA client echoes it as expected_incarnation on a per-tool decision, so a\nstale row is refused (409 server_replaced) after a same-name re-add.\nOmitted when the server has no committed incarnation.","type":"integer"},"server_name":{"type":"string"},"tier":{"$ref":"#/components/schemas/contracts.Tier"},"usage":{"type":"integer"}},"type":"object"},"contracts.ToolAccess":{"properties":{"callable":{"type":"boolean"},"reason":{"type":"string"},"visible":{"type":"boolean"}},"type":"object"},"contracts.ToolAnnotation":{"description":"Tool behavior hints snapshot","properties":{"destructiveHint":{"type":"boolean"},"idempotentHint":{"type":"boolean"},"openWorldHint":{"type":"boolean"},"readOnlyHint":{"type":"boolean"},"title":{"type":"string"}},"type":"object"},"contracts.ToolCallRecord":{"description":"The new tool call record","properties":{"annotations":{"$ref":"#/components/schemas/contracts.ToolAnnotation"},"arguments":{"description":"Tool arguments","type":"object"},"arguments_truncated":{"description":"ArgumentsTruncated marks Arguments as a placeholder rather than the\narguments the tool was called with. Replaying such a record without\nsupplying arguments explicitly is refused.","type":"boolean"},"config_path":{"description":"Active config file path","type":"string"},"duration":{"description":"Duration in nanoseconds","type":"integer"},"error":{"description":"Error message (failure only)","type":"string"},"execution_type":{"description":"\"direct\" or \"code_execution\"","type":"string"},"id":{"description":"Unique identifier","type":"string"},"mcp_client_name":{"description":"MCP client name from InitializeRequest","type":"string"},"mcp_client_version":{"description":"MCP client version","type":"string"},"mcp_session_id":{"description":"MCP session identifier","type":"string"},"metrics":{"$ref":"#/components/schemas/contracts.TokenMetrics"},"parent_call_id":{"description":"Links nested calls to parent code_execution","type":"string"},"request_id":{"description":"Request correlation ID","type":"string"},"response":{"description":"Tool response (success only)","type":"object"},"response_bytes":{"description":"Marshalled response size before truncation","type":"integer"},"response_truncated":{"description":"ResponseTruncated and ResponseBytes describe a STORAGE-side cut (#1176):\nthe caller received the response whole, and only the persisted copy was\nshortened to tool_call_max_response_size. When ResponseTruncated is true\nthe Response object carries {truncated, original_bytes, preview, note}\ninstead of the upstream result, and ResponseBytes is its size before the\ncut.","type":"boolean"},"server_id":{"description":"Server identity hash","type":"string"},"server_name":{"description":"Human-readable server name","type":"string"},"timestamp":{"description":"When the call was made","type":"string"},"tool_name":{"description":"Tool name (without server prefix)","type":"string"}},"type":"object"},"contracts.UpdateInfo":{"description":"Update information (if available)","properties":{"available":{"description":"Whether an update is available","type":"boolean"},"behind_summary":{"description":"Spec 079 FR-002 — how far behind the running build is. All four are\nadditive (FR-021) and absent when the delta could not be resolved, in\nwhich case every surface renders its pre-delta wording.","type":"string"},"check_error":{"description":"Error message if update check failed","type":"string"},"checked_at":{"description":"When the update check was performed","type":"string"},"install_channel":{"description":"Detected install channel (homebrew, dmg, deb, rpm, docker, go-install, windows-installer, tarball, unknown) — Spec 079 FR-008","type":"string"},"is_prerelease":{"description":"Whether the latest version is a prerelease","type":"boolean"},"latest_version":{"description":"Latest version available (e.g., \"v1.2.3\")","type":"string"},"nudges_suppressed":{"description":"UI surfaces must stay quiet (CI / non-interactive context); machine-readable fields still report the facts — Spec 079 FR-019","type":"boolean"},"release_url":{"description":"URL to the release page","type":"string"},"releases_behind":{"description":"Releases on the offered channel between the running and offered versions","type":"integer"},"releases_behind_saturated":{"description":"ReleasesBehind is a lower bound: the running build predates the scanned release window","type":"boolean"},"update_command":{"description":"One-line update command for the channel; only set when an update is available and the channel has one — Spec 079 FR-009","type":"string"},"weeks_behind":{"description":"Whole weeks between the two releases' publish dates; 0 is a real value, absent means unknown","type":"integer"}},"type":"object"},"contracts.UpdatePolicy":{"description":"UpdatePolicy is the effective, hot-reloadable update policy (Spec 092\nFR-015). Always present: the ` + "`" + `update` + "`" + ` object above is omitted both when\nupdate checking is disabled AND when no check has produced a result\nyet, so its absence cannot tell a client whether it is allowed to run\nits own (e.g. Sparkle feed) check. This field states the answer.","properties":{"channel":{"description":"Channel is the tracked release channel: \"stable\" or \"rc\".","type":"string"},"enabled":{"description":"Enabled is the effective automatic-check kill switch: update_check.enabled\nwith MCPPROXY_DISABLE_AUTO_UPDATE=true winning over it. A user-initiated\n\"Check for Updates\" stays available regardless.","type":"boolean"},"nudges_suppressed":{"description":"NudgesSuppressed asks UI surfaces to stay quiet (CI / non-interactive)\nwhile machine-readable fields keep reporting the facts.","type":"boolean"}},"type":"object"},"contracts.UpstreamError":{"properties":{"error_message":{"type":"string"},"server_name":{"type":"string"},"timestamp":{"type":"string"}},"type":"object"},"contracts.UsageAggregateResponse":{"properties":{"freshness_ms":{"description":"age of the underlying snapshot in ms","type":"integer"},"generated_at":{"type":"string"},"other":{"$ref":"#/components/schemas/contracts.UsageOtherBucket"},"timeline":{"items":{"$ref":"#/components/schemas/contracts.UsageTimeBucket"},"type":"array","uniqueItems":false},"token_source":{"description":"\"bytes\" (size-based proxy, FR-006)","type":"string"},"tokens_saved":{"description":"echoed from ServerTokenMetrics (FR-007)","type":"integer"},"tokens_saved_estimated":{"description":"TokensSavedEstimated echoes ServerTokenMetrics.Estimated (Spec 109-k):\ntrue while TokensSaved is a synthetic simulation rather than derived\nfrom a real retrieve_tools call. Dropped (false, the zero value) for a\nscoped caller along with TokensSaved itself, above.","type":"boolean"},"tokens_saved_percentage":{"type":"number"},"tools":{"items":{"$ref":"#/components/schemas/contracts.UsageToolStat"},"type":"array","uniqueItems":false},"total_calls":{"description":"TotalCalls and TotalErrors are the headline counts for the window: the sum\nof the timeline this same response carries, so the tiles and the histogram\nunder them cannot disagree. They are NOT the sum of Tools — that list is\nlifetime-cumulative, upstream-only and truncated to top-N, and summing it\nclient-side is what made the Usage tab print a third number for the same\n24 hours (audit finding F1, #1046). The population is\nstorage.CountsAsCall, shared with ActivitySummaryResponse.CallCount.\n\nTwo bounds on how exactly this matches the Activity Log's own count.\nBoth are bounded and disclosed, unlike the population mismatch they\nreplace, which was unbounded and silent:\n\n - Window granularity is the timeline's: whole hour buckets, so the span\n is the requested window rounded up to a bucket edge.\n - This response is served from a snapshot behind a short read cache\n (observability.usage_cache_ttl, 5s by default) so the endpoint never\n scans the activity log per request, while the summary endpoint counts\n live. Calls that land inside that window appear on the Activity Log\n first. FreshnessMs and GeneratedAt say how old the figures are, and\n the Usage tab prints it (\"Updated 3s ago\").","type":"integer"},"total_errors":{"type":"integer"},"window":{"type":"string"}},"type":"object"},"contracts.UsageOtherBucket":{"description":"present only when the list was truncated to top-N","properties":{"calls":{"type":"integer"},"tools_folded":{"type":"integer"},"total_resp_bytes":{"type":"integer"}},"type":"object"},"contracts.UsageTimeBucket":{"properties":{"calls":{"type":"integer"},"errors":{"type":"integer"},"start":{"type":"string"},"total_resp_bytes":{"type":"integer"}},"type":"object"},"contracts.UsageToolStat":{"properties":{"avg_req_bytes":{"description":"null when no sized request calls","type":"integer"},"avg_resp_bytes":{"description":"null when sized_calls == 0 (only legacy 0-byte calls)","type":"integer"},"blocked":{"type":"integer"},"calls":{"type":"integer"},"error_rate":{"type":"number"},"errors":{"type":"integer"},"last_used":{"type":"string"},"p50_exceeds":{"type":"boolean"},"p50_ms":{"description":"P50Ms and P95Ms are read off a fixed latency histogram, so they are BUCKET\nBOUNDS, not measured durations: the true percentile is at or below the\nvalue, and a client must render it as a bound (\"≤ 5 ms\"). P50Exceeds /\nP95Exceeds flip that reading for the unbounded overflow bucket, where the\nvalue is the last bound and the truth is above it (\"\u003e 10 s\").","type":"integer"},"p95_exceeds":{"type":"boolean"},"p95_ms":{"type":"integer"},"rejected":{"description":"spec 093: shed by a concurrency limit; never executed, so excluded from calls/latency","type":"integer"},"server":{"type":"string"},"sized_calls":{"description":"calls with known response size (basis for avg_resp_bytes)","type":"integer"},"tool":{"type":"string"},"total_req_bytes":{"type":"integer"},"total_resp_bytes":{"type":"integer"}},"type":"object"},"contracts.ValidateConfigResponse":{"properties":{"errors":{"items":{"$ref":"#/components/schemas/contracts.ValidationError"},"type":"array","uniqueItems":false},"valid":{"type":"boolean"}},"type":"object"},"contracts.ValidationError":{"properties":{"field":{"type":"string"},"message":{"type":"string"}},"type":"object"},"contracts.ViewAsCounts":{"description":"Counts is present only for a NON-administrator profile view-as (Spec 108\nFR-032): the response then lists only the visible rows, and this is the\nonly trace of the rest, with no per-server, per-tier or per-reason\nbreakdown.","properties":{"hidden":{"type":"integer"},"visible":{"type":"integer"}},"type":"object"},"contracts.WorkSession":{"properties":{"attempts":{"description":"Attempts, Failures and PolicyBlocks are lifetime counts of the session.\nPolicyBlocks are included in Failures.","type":"integer"},"client_id":{"type":"string"},"client_name":{"type":"string"},"connection_count":{"description":"Administrators only.","type":"integer"},"duration_ms":{"type":"integer"},"ended_at":{"type":"string"},"failures":{"type":"integer"},"first_failure_at":{"type":"string"},"id":{"type":"string"},"last_activity_at":{"type":"string"},"last_failure":{"$ref":"#/components/schemas/contracts.WorkSessionFailure"},"ownerless":{"type":"boolean"},"policy_blocks":{"type":"integer"},"profile":{"description":"Profile is returned to administrators only.","type":"string"},"profile_source":{"type":"string"},"project_name":{"description":"ProjectName is the basename of the client's workspace, when it\ndisclosed one.","type":"string"},"rebuilt":{"type":"boolean"},"run_name":{"type":"string"},"started_at":{"type":"string"},"status":{"description":"Status is \"active\" or \"ended\".","type":"string"},"stored_failures":{"description":"StoredFailures counts the failures whose rows are still in the log;\nit is what the timeline can navigate.","type":"integer"},"surface":{"type":"string"},"token_name":{"type":"string"},"truncated_start_at":{"type":"string"}},"type":"object"},"contracts.WorkSessionEnvelope":{"properties":{"data":{"$ref":"#/components/schemas/contracts.WorkSession"},"success":{"type":"boolean"}},"type":"object"},"contracts.WorkSessionFailure":{"properties":{"at":{"type":"string"},"error_class":{"type":"string"},"error_code":{"type":"string"},"policy_block":{"description":"PolicyBlock is true when the failure was a refusal by MCPProxy itself.","type":"boolean"},"reason":{"description":"Reason is at most 200 characters and never contains argument or\nresponse bodies.","type":"string"},"server":{"type":"string"},"tool":{"type":"string"}},"type":"object"},"contracts.WorkSessionListEnvelope":{"properties":{"data":{"$ref":"#/components/schemas/contracts.WorkSessionListResponse"},"success":{"type":"boolean"}},"type":"object"},"contracts.WorkSessionListResponse":{"properties":{"limit":{"type":"integer"},"offset":{"type":"integer"},"sessions":{"items":{"$ref":"#/components/schemas/contracts.WorkSession"},"type":"array","uniqueItems":false},"total":{"type":"integer"}},"type":"object"},"contracts.WorkSessionTimelineEnvelope":{"properties":{"data":{"$ref":"#/components/schemas/contracts.WorkSessionTimelineResponse"},"success":{"type":"boolean"}},"type":"object"},"contracts.WorkSessionTimelineResponse":{"properties":{"earlier_failures_not_stored":{"type":"boolean"},"failure_index":{"description":"FailureIndex is the 1-based number of the failure at or before the\nposition among the stored failures in reach (0 when none), and\nFailureTotal their count.","type":"integer"},"failure_total":{"type":"integer"},"has_after":{"type":"boolean"},"has_before":{"type":"boolean"},"lifetime_failures":{"description":"LifetimeFailures is the session's lifetime failure count in reach.\nEarlierFailuresNotStored says some of them are no longer in the log.","type":"integer"},"position":{"description":"Position is the index of the row the page is positioned at; TotalRows\nis the number of rows in the caller's view.","type":"integer"},"rows":{"items":{"$ref":"#/components/schemas/contracts.WorkSessionTimelineRow"},"type":"array","uniqueItems":false},"session":{"$ref":"#/components/schemas/contracts.WorkSession"},"total_rows":{"type":"integer"}},"type":"object"},"contracts.WorkSessionTimelineRow":{"properties":{"activity":{"$ref":"#/components/schemas/contracts.ActivityRecord"},"at":{"description":"At is the time of the row.","type":"string"},"bodies_removed":{"description":"BodiesRemoved is true when retention removed the row's argument and\nresponse bodies to keep the row.","type":"boolean"},"failed":{"description":"Failed marks the counted row of a failed attempt; PolicyBlock marks a\nrefusal by MCPProxy itself.","type":"boolean"},"index":{"description":"Index is the row's position in the caller's view of the timeline.","type":"integer"},"kind":{"type":"string"},"policy_block":{"type":"boolean"},"precedes_session":{"description":"PrecedesSession marks an upstream event from before the session\nstarted: the latest event of a server the session then failed on,\nstill unresolved when the session began (release QA F2, SC-005).","type":"boolean"}},"type":"object"},"data":{"properties":{"data":{"$ref":"#/components/schemas/contracts.InfoResponse"}},"type":"object"},"httpapi.AccessExplanationData":{"properties":{"first_failure":{"type":"string","x-enum-varnames":["StepCredential","StepProfile","StepServerInScope","StepToolRule","StepTierCap","StepTokenPermission","StepGlobalGate","StepServerState","StepToolApproval"]},"fixes":{"items":{"$ref":"#/components/schemas/runtime.Fix"},"type":"array","uniqueItems":false},"profile":{"$ref":"#/components/schemas/runtime.ExplainProfileView"},"steps":{"items":{"$ref":"#/components/schemas/runtime.ExplainStepView"},"type":"array","uniqueItems":false},"subject":{"$ref":"#/components/schemas/runtime.ExplainSubjectView"},"tool":{"type":"string"},"verdict":{"$ref":"#/components/schemas/profile.ExplainVerdict"}},"type":"object"},"httpapi.AccessSuggestionsData":{"properties":{"already_fixed":{"description":"AlreadyFixed counts groups the explainer now allows (they drop out).","type":"integer"},"blocked_calls":{"description":"BlockedCalls counts every profile-refused call in the window.","type":"integer"},"non_profile_blocked":{"description":"NonProfileBlocked counts blocked calls with a cause outside profiles.","type":"integer"},"patches":{"items":{"$ref":"#/components/schemas/runtime.ProfilePatch"},"type":"array","uniqueItems":false},"profile_removed":{"description":"ProfileRemoved counts groups whose profile no longer exists (they drop out).","type":"integer"},"since":{"type":"string"},"suggestions":{"items":{"$ref":"#/components/schemas/runtime.AccessSuggestion"},"type":"array","uniqueItems":false},"unattributed":{"description":"Unattributed counts profile refusals whose record names no profile.","type":"integer"},"until":{"type":"string"},"window":{"type":"string"}},"type":"object"},"httpapi.AddServerRequest":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges is the per-server intent to auto-approve\nnew/changed tools past the trust baseline (MCP-2930). Tri-state *bool:\na nil pointer means \"leave unchanged\" on PATCH; a present value\n(including false) is applied. Mirrors config.ServerConfig's *bool\nsemantics — do NOT collapse to a plain bool, or an omitted field would\nsilently reset a previously-set value.","type":"boolean"},"command":{"type":"string"},"enabled":{"type":"boolean"},"env":{"additionalProperties":{"type":"string"},"type":"object"},"expose_prompts":{"description":"ExposePrompts is the per-server override for prompt aggregation (F9):\nwhether this server's advertised MCP prompts are merged into mcpproxy's\nprompts/list. Tri-state *bool mirroring config.ServerConfig.ExposePrompts —\na nil pointer means \"leave unchanged\" on PATCH (and \"inherit the default\naggregate behavior\" on create); a present value (including false) is applied.","type":"boolean"},"expose_skills":{"description":"ExposeSkills is the per-server skills override (MCP skills extension).\nTri-state *bool mirroring config.ServerConfig.ExposeSkills: nil means\n\"leave unchanged\" on PATCH and \"inherit\" on create.","type":"boolean"},"forward_headers":{"description":"ForwardHeaders is the per-server allowlist of inbound MCP client header\nNAMES forwarded to this server on tools/call (Spec 112). Names only, never\nvalues. On PATCH a nil slice (field omitted) leaves the stored allowlist\nunchanged and an empty array ([]) clears it. Invalid, denied, duplicate\nand static-header-colliding names are rejected with 400.","items":{"type":"string"},"type":"array","uniqueItems":false},"headers":{"additionalProperties":{"type":"string"},"type":"object"},"init_timeout":{"description":"InitTimeout is the per-server MCP ` + "`" + `initialize` + "`" + ` handshake deadline override\n(MCP-3322 / GH #760), serialized as a duration string (e.g. \"120s\"). A nil\npointer means \"leave unchanged\" on PATCH; a present value is applied.\nMirrors config.ServerConfig.InitTimeout's *Duration tri-state.","type":"string"},"isolation":{"$ref":"#/components/schemas/httpapi.IsolationRequest"},"max_concurrent_requests":{"description":"MaxConcurrentRequests / QueueSize / QueueTimeout are the per-server\nconcurrency overrides (spec 093 / GH #955, FR-020 scope (c)). Each is\ntri-state: a nil pointer means \"leave unchanged\" on PATCH and \"inherit\nserver_concurrency_defaults\" on create; an explicit 0 disables that\nsetting for this server; a positive value overrides it. Do NOT collapse\nthem to plain values — an omitted field would then silently reset a\nconfigured limit.","type":"integer"},"name":{"type":"string"},"protocol":{"type":"string"},"quarantined":{"type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_on_use":{"type":"boolean"},"tool_argument_error_mode":{"description":"Empty preserves an update; detailed explicitly resets a redacted policy.","type":"string"},"trust_mode":{"description":"TrustMode is the per-server trust tier (spec 086): \"auto\", \"scan\", or\n\"manual\". Empty means \"leave unchanged\" on PATCH (and inherit the migrated\ndefault on create). A non-empty value is applied to ServerConfig.TrustMode\nand resolved by EffectiveTrustMode (an unrecognized value fails closed to\nmanual). This is the REST seam for changing the trust tier via\nPOST/PATCH /api/v1/servers.","type":"string"},"url":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"httpapi.BindingGuardResponse":{"properties":{"bindings":{"items":{"$ref":"#/components/schemas/httpapi.GuardBinding"},"type":"array","uniqueItems":false},"code":{"description":"binding_bypassable_without_auth","type":"string"},"error":{"description":"Human-readable, byte-stable refusal text","type":"string"},"fixes":{"items":{"$ref":"#/components/schemas/httpapi.GuardFixOption"},"type":"array","uniqueItems":false},"request_id":{"type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.BulkAssignRequest":{"properties":{"from_profile":{"type":"string"},"mode":{"type":"string"},"to_profile":{"type":"string"}},"type":"object"},"httpapi.BulkAssignResponse":{"properties":{"moved":{"items":{"type":"string"},"type":"array","uniqueItems":false},"skipped":{"items":{"$ref":"#/components/schemas/httpapi.BulkAssignSkipped"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.BulkAssignSkipped":{"properties":{"client_id":{"type":"string"},"code":{"type":"string"},"error":{"type":"string"}},"type":"object"},"httpapi.BundleRollbackRefusedResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"rejection":{"$ref":"#/components/schemas/scanner.BundleRejection"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"httpapi.CanonicalConfigPath":{"properties":{"description":{"description":"Brief description","type":"string"},"exists":{"description":"Whether the file exists","type":"boolean"},"format":{"description":"Format identifier (e.g., \"claude_desktop\")","type":"string"},"name":{"description":"Display name (e.g., \"Claude Desktop\")","type":"string"},"os":{"description":"Operating system (darwin, windows, linux)","type":"string"},"path":{"description":"Full path to the config file","type":"string"}},"type":"object"},"httpapi.CanonicalConfigPathsResponse":{"properties":{"os":{"description":"Current operating system","type":"string"},"paths":{"description":"List of canonical config paths","items":{"$ref":"#/components/schemas/httpapi.CanonicalConfigPath"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ClientBindingErrorResponse":{"properties":{"code":{"type":"string"},"error":{"type":"string"},"field":{"type":"string"},"request_id":{"type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.ClientBindingResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"warnings":{"items":{"$ref":"#/components/schemas/httpapi.ClientWarning"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ClientCredential":{"properties":{"approved_at":{"type":"string"},"expires_at":{"type":"string"},"grant_id":{"description":"GrantID names a browser login.","type":"string"},"kind":{"description":"Kind is api_key or browser_login.","type":"string"},"last_used_at":{"type":"string"},"name_mismatch":{"type":"boolean"},"observed_name":{"description":"ObservedName is the name the client sent at initialize (advisory).","type":"string"},"prefix":{"type":"string"},"redirect_host":{"type":"string"},"reported_name":{"type":"string"},"state":{"description":"State is active|expired|revoked for an API key and active|lapsed|revoked\nfor a login.","type":"string"}},"type":"object"},"httpapi.ClientSnippet":{"properties":{"generic_http":{"type":"string"},"header_name":{"type":"string"}},"type":"object"},"httpapi.ClientWarning":{"properties":{"action":{"$ref":"#/components/schemas/runtime.WarningAction"},"bindings":{"items":{"$ref":"#/components/schemas/runtime.BindingRef"},"type":"array","uniqueItems":false},"client_id":{"type":"string"},"code":{"$ref":"#/components/schemas/profile.WarningCode"},"fixes":{"items":{"$ref":"#/components/schemas/runtime.GuardFix"},"type":"array","uniqueItems":false},"message":{"type":"string"},"severity":{"$ref":"#/components/schemas/profile.WarningSeverity"}},"type":"object"},"httpapi.ConnectConflictResponse":{"properties":{"action":{"description":"already_exists | precondition_failed","type":"string"},"data":{"$ref":"#/components/schemas/connect.ConnectResult"},"error":{"description":"Human-readable message","type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.ConnectRequest":{"properties":{"force":{"description":"Overwrite existing entry","type":"boolean"},"keyless":{"type":"boolean"},"mode":{"type":"string"},"precondition_token":{"description":"PreconditionToken is the opaque token from the preview this write was\nconfirmed against (Spec 091 FR-005). When present, the core rechecks it\nat write time and responds 409 with action \"precondition_failed\" —\nwriting nothing — if the config or the entry MCPProxy would write has\ndrifted since; the caller then re-previews instead of retrying. Absent\nmeans exactly the pre-091 behavior. A replace-classified flow sends this\nTOGETHER with force=true: the token, not the absence of force, is the\noverwrite safety.","type":"string"},"profile":{"description":"Profile, Mode and Keyless are the client-credential intent (Spec 108\nFR-024). Profile names the profile the client's credential binds to;\n\"\" is the built-in All servers scope. Omitted means \"not specified\": a\nfresh credential defaults to All servers and a reconnect keeps the\nclient's existing binding (a reconnect never silently widens a locked\nclient). Mode is locked|switchable (default locked for a named profile,\nswitchable for All servers). Keyless writes a credential-less entry and\nis only possible while require_mcp_auth is off; it cannot carry a\nprofile or mode.","type":"string"},"server_name":{"description":"Defaults to \"mcpproxy\"","type":"string"}},"type":"object"},"httpapi.CreateClientRequest":{"properties":{"display_name":{"type":"string"},"expires_in":{"description":"ExpiresIn is a duration like 30d or 720h; default and cap are 365 days.","type":"string"},"id":{"type":"string"},"mode":{"type":"string"},"profile":{"type":"string"},"purpose":{"description":"Purpose is the stated, unenforced task brief (Spec 115), at most 500\ncharacters; screened for secrets before anything is stored.","type":"string"}},"type":"object"},"httpapi.CreateClientResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"credential":{"type":"string"},"snippet":{"$ref":"#/components/schemas/httpapi.ClientSnippet"}},"type":"object"},"httpapi.EffectiveToolsData":{"properties":{"counts":{"$ref":"#/components/schemas/runtime.EffectiveCounts"},"profile":{"type":"string"},"stale_classification_reasons":{"additionalProperties":{"type":"string"},"description":"StaleClassificationReasons maps each stale classify entry to why it no\nlonger applies: profile.StaleClassificationAnnotated or\nprofile.StaleClassificationMissing. It is computed over the UNFILTERED\ntool set, so a server or reason filter never changes it. Administrators\nonly.","type":"object"},"stale_classifications":{"description":"StaleClassifications lists classify entries for tools that are now\nannotated or no longer exist (FR-005). Administrators only.","items":{"type":"string"},"type":"array","uniqueItems":false},"tools":{"items":{"$ref":"#/components/schemas/runtime.EffectiveTool"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.EnvFieldPreview":{"properties":{"empty_or_placeholder":{"type":"boolean"},"name":{"type":"string"},"secret_like":{"type":"boolean"},"value_present":{"type":"boolean"}},"type":"object"},"httpapi.FinalizeClientResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"rotation":{"$ref":"#/components/schemas/httpapi.RotationState"}},"type":"object"},"httpapi.ForgetClientResponse":{"properties":{"disconnect_error":{"type":"string"},"disconnected":{"type":"boolean"},"revoked":{"type":"string"}},"type":"object"},"httpapi.GuardBinding":{"properties":{"client_id":{"type":"string"},"mode":{"type":"string"},"profile":{"type":"string"},"token_name":{"type":"string"}},"type":"object"},"httpapi.GuardFixOption":{"properties":{"kind":{"type":"string"},"target":{"type":"string"}},"type":"object"},"httpapi.HeaderFieldPreview":{"properties":{"empty_or_placeholder":{"type":"boolean"},"name":{"type":"string"},"secret_like":{"type":"boolean"},"value_present":{"type":"boolean"}},"type":"object"},"httpapi.ImportFromPathRequest":{"properties":{"format":{"description":"Optional format hint","type":"string"},"path":{"description":"File path to import from","type":"string"},"rename":{"additionalProperties":{"type":"string"},"description":"Rename maps a server name → new name. Applied after parsing so the\ncaller can disambiguate cross-source name collisions (Spec 046 v2 —\ne.g. \"mcpproxy\" → \"mcpproxy_claude_code\"). Keys are matched against\neither the raw source name (OriginalName) or the sanitized name shown\nin the preview (Server.Name); these differ for names that need\nsanitizing (e.g. \"Figma Desktop\" → \"Figma_Desktop\"). Keys not present\nin the imported set are ignored.","type":"object"},"server_names":{"description":"Optional: import only these servers","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportRequest":{"properties":{"allow_paste_fallback":{"description":"AllowPasteFallback opts into detecting a bare URL or a single command\nline (FR-064) when Format/format detection would otherwise fail — see\nconfigimport.ImportOptions.AllowPasteFallback for why this must stay\nopt-in (review round 4 F-E). Only the interactive Paste tab sets this;\nevery other caller of this endpoint (the general \"Import config\"\npanel, or a direct API call) leaves it false and gets a clear\n\"unable to detect configuration format\" error for a plain one-liner\ninstead of it being silently guessed at and, on apply, added as a\nreal server with no confirmation step.","type":"boolean"},"content":{"description":"Raw JSON or TOML content","type":"string"},"env_override":{"additionalProperties":{"type":"string"},"description":"EnvOverride/HeaderOverride (Spec 109 FR-064/065, PR review round 4\nF-A/F-D fix): the Paste tab's per-field Value/Secret edits — a plain\nvalue the user typed, or a keyring ref path if they chose Secret —\nkeyed by field name. Applied to the matching imported server's\nEnv/Headers ONLY when preview=false, directly on the server this\nrequest's own raw Content parses to server-side. This is what lets\nthe apply call carry the user's edited env/header values without\never round-tripping the redacted preview: url/command/args on apply\nalways come from re-parsing Content here, never from a client-held\npreview response, so a credential embedded in a URL query param or\nargv flag (which the preview necessarily redacted for display) is\nnever overwritten with the masked placeholder.","type":"object"},"format":{"description":"Optional format hint","type":"string"},"header_override":{"additionalProperties":{"type":"string"},"type":"object"},"server_names":{"description":"Optional: import only these servers","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportResponse":{"properties":{"failed":{"items":{"$ref":"#/components/schemas/configimport.FailedServer"},"type":"array","uniqueItems":false},"format":{"type":"string"},"format_name":{"type":"string"},"imported":{"items":{"$ref":"#/components/schemas/httpapi.ImportedServerResponse"},"type":"array","uniqueItems":false},"skipped":{"items":{"$ref":"#/components/schemas/configimport.SkippedServer"},"type":"array","uniqueItems":false},"summary":{"$ref":"#/components/schemas/configimport.ImportSummary"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportedServerResponse":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"command":{"type":"string"},"env":{"items":{"$ref":"#/components/schemas/httpapi.EnvFieldPreview"},"type":"array","uniqueItems":false},"fields_skipped":{"items":{"type":"string"},"type":"array","uniqueItems":false},"headers":{"items":{"$ref":"#/components/schemas/httpapi.HeaderFieldPreview"},"type":"array","uniqueItems":false},"name":{"type":"string"},"original_name":{"type":"string"},"protocol":{"type":"string"},"source_format":{"type":"string"},"summary":{"description":"Summary, Tags, Env and Headers are the Spec 109 FR-064 preview\nenrichment (contracts/rest-api.md \"Import preview\"). Summary and Tags\nare built from the already-redacted URL/Command/Args above, so a\nsecret embedded in argv or a URL query never reaches Summary either.\nEnv/Headers never carry the raw value — only its presence and two\nbooleans a surface uses to default the Value/Secret toggle (FR-065).","type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"url":{"type":"string"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.IsolationRequest":{"description":"Isolation carries per-server Docker isolation overrides (enabled,\nmode_override, image, network_mode, extra_args, working_dir). A nil\npointer means \"do not touch isolation config\". A present object is\napplied field-by-field ON TOP of the persisted overrides, so omitting a\nfield leaves it alone; clear an individual override by sending it\nexplicitly (` + "`" + `\"enabled\": null` + "`" + `, ` + "`" + `\"image\": \"\"` + "`" + `).","properties":{"enabled":{"description":"Enabled exists ONLY to detect and reject an echoed-back read. It is the\neffective state on the read surface and is never writable; see validate().","type":"boolean"},"enabled_override":{"description":"EnabledOverride is the tri-state per-server override — the RAW value, the\nsame one reads return as ` + "`" + `enabled_override` + "`" + `. It has THREE meaningful wire\nstates, and collapsing them is what silently un-isolated servers\n(GH #1142):\n - absent → leave the persisted override untouched\n - null → clear the override, back to inheriting the global\n - true / false → set an explicit opt-in / opt-out","type":"boolean"},"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"mode_override":{"description":"ModeOverride sets ` + "`" + `isolation.mode` + "`" + ` (\"docker\" | \"sandbox\" | \"none\").\nnil leaves the persisted value alone; an empty string clears it. An\nunrecognized value is rejected with a 400 rather than persisted.","type":"string"},"network_mode":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"httpapi.OAuthApprovalBody":{"properties":{"binding_revision":{"type":"string"},"client":{"$ref":"#/components/schemas/httpapi.OAuthClientChoice"},"mode":{"type":"string"},"profile":{"type":"string"},"replace_grant":{"type":"string"}},"type":"object"},"httpapi.OAuthClientChoice":{"properties":{"id":{"type":"string"},"new":{"$ref":"#/components/schemas/httpapi.OAuthNewClient"}},"type":"object"},"httpapi.OAuthDecisionResponse":{"properties":{"redirect_url":{"type":"string"}},"type":"object"},"httpapi.OAuthNewClient":{"properties":{"display_name":{"type":"string"},"id":{"type":"string"}},"type":"object"},"httpapi.OnboardingMarkRequest":{"properties":{"connect_step_status":{"description":"ConnectStepStatus is one of: \"\", \"completed\", \"skipped\". Empty\npreserves the existing value. The stored enum is wider (Spec 080\nFR-001): a \"skipped\" request for a previously untouched connect step\nis upgraded server-side to \"completed_external\" when the install\nshows positive evidence of an external connection (Spec 080 FR-002).\n\"completed_external\" is NOT accepted from clients — it must never be\npersisted without that server-verified evidence (edge case: \"never\nguess completed_external without positive evidence\").","type":"string"},"connected_client_id":{"description":"ConnectedClientID records a successful connect write for this client id\n(Spec 109-b FR-042, review round 6). The REST connect endpoint\n(POST /api/v1/connect/{client}) already records this itself on success;\nthis field exists so ` + "`" + `mcpproxy connect` + "`" + ` — which writes the client's\nconfig file directly, without going through that endpoint, so the\ncommand still works when no daemon is running — can relay the same\nevent to a daemon that IS running, keeping ClientConnectedAt in sync\nacross both surfaces. Must be a known id from the fixed connect client\nregistry (internal/connect.GetAllClients); any other value is rejected,\nmatching the field's \"bounded by the registry\" invariant\n(data-model.md §7).","type":"string"},"disconnected_client_id":{"description":"DisconnectedClientID relays a successful local CLI disconnect to a running\ndaemon, which cannot observe the CLI's direct config-file edit itself.\nLike ConnectedClientID, it is bounded to the fixed client registry.","type":"string"},"engaged":{"description":"Engaged marks the wizard as engaged (completed or explicitly skipped).\nOnce true, the wizard does not auto-show again.","type":"boolean"},"mark_shown":{"description":"MarkShown records the wizard's first display time if not already set.","type":"boolean"},"server_step_status":{"description":"ServerStepStatus is one of: \"\", \"completed\", \"skipped\". Empty\npreserves the existing value.","type":"string"}},"type":"object"},"httpapi.OnboardingStateResponse":{"properties":{"configured_server_count":{"description":"ConfiguredServerCount is the number of upstream MCP servers configured\nin mcpproxy (counts both enabled and disabled).","type":"integer"},"connected_client_count":{"description":"ConnectedClientCount is the number of supported clients currently\npointing at mcpproxy.","type":"integer"},"connected_client_ids":{"description":"ConnectedClientIDs are the identifiers of supported clients currently\npointing at mcpproxy. Drawn exclusively from the fixed adapter table —\nuser-entered values never appear here.","items":{"type":"string"},"type":"array","uniqueItems":false},"first_mcp_client_ever":{"description":"FirstMCPClientEver is true once any MCP client has successfully completed\nan ` + "`" + `initialize` + "`" + ` round-trip with this mcpproxy. Sourced from the Spec 044\nactivation bucket. Drives the Verify tab's \"green check\" state.","type":"boolean"},"has_configured_server":{"description":"HasConfiguredServer is true if at least one upstream MCP server is\nconfigured (regardless of current connection health).","type":"boolean"},"has_connected_client":{"description":"HasConnectedClient is true if at least one supported AI client currently\nhas mcpproxy registered in its config.","type":"boolean"},"has_usable_server":{"description":"HasUsableServer is true once at least one enabled, non-quarantined\nserver has usable health and at least one approved (non-disabled) tool.\nThis is the real \"the wizard has something to try\" signal:\nHasConfiguredServer only means a server entry exists, even while every\none of them sits quarantined, requires sign-in, or has zero approved\ntools. The Servers step and Setup badge use this instead of\nHasConfiguredServer, which is kept above for compatibility.\nHealthStatus.Usable is the shared\nreadiness contract used by every UI surface (Spec 109-c, tasks.md T051).","type":"boolean"},"incomplete_tab_count":{"description":"IncompleteTabCount is the number of wizard tabs whose state is incomplete.\nDrives the sidebar Setup entry's badge. Formula:\n +1 if HasConnectedClient == false\n +1 if HasUsableServer == false\n +1 if FirstMCPClientEver == false","type":"integer"},"mcp_clients_seen_ever":{"description":"MCPClientsSeenEver is the capped list of recognized client names that\nhave ever called this mcpproxy. Names come from the MCP ` + "`" + `initialize` + "`" + `\npayload's ` + "`" + `clientInfo.name` + "`" + ` field, sanitized. Surfaces on the Verify tab\nso the user can see whether their real IDE — not a test client — has\nconnected.","items":{"type":"string"},"type":"array","uniqueItems":false},"should_show_wizard":{"description":"ShouldShowWizard is the derived flag the frontend uses to decide\nwhether to auto-show. True when not engaged and IncompleteTabCount \u003e 0\n(Spec 046 v2 — semantics widened to also count the Verify tab).","type":"boolean"},"state":{"$ref":"#/components/schemas/storage.OnboardingState"},"usable_servers":{"description":"UsableServers lists the names behind HasUsableServer, for the Verify\nstep's suggested-prompt generator (FR-042): prompts are only built from\ntools of servers in this list, never from a quarantined or toolless one.","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileConflictResponse":{"properties":{"code":{"type":"string"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"description":"Always false","type":"boolean"},"used_by":{"$ref":"#/components/schemas/httpapi.ProfileUsedByData"}},"type":"object"},"httpapi.ProfileDeleteData":{"properties":{"anonymous_profile_moved_to":{"type":"string"},"deleted":{"type":"string"},"moved":{"$ref":"#/components/schemas/runtime.MovedRefs"}},"type":"object"},"httpapi.ProfileListData":{"properties":{"anonymous_profile":{"type":"string"},"profiles":{"items":{"$ref":"#/components/schemas/runtime.ProfileView"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileRenameData":{"properties":{"moved":{"$ref":"#/components/schemas/runtime.MovedRefs"},"profile":{"$ref":"#/components/schemas/runtime.ProfileView"}},"type":"object"},"httpapi.ProfileTryData":{"properties":{"hidden":{"items":{"$ref":"#/components/schemas/runtime.TryHidden"},"type":"array","uniqueItems":false},"hidden_by_profile":{"type":"integer"},"hidden_truncated":{"type":"boolean"},"results":{"items":{"additionalProperties":{},"type":"object"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileUsedByData":{"properties":{"anonymous_profile":{"type":"boolean"},"clients":{"items":{"$ref":"#/components/schemas/runtime.UsedByClient"},"type":"array","uniqueItems":false},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileViewData":{"properties":{"blocked_24h":{"type":"integer"},"calls_24h":{"type":"integer"},"code_execution":{"type":"boolean"},"description":{"type":"string"},"effective_code_execution":{"type":"boolean"},"effective_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"effective_unannotated":{"type":"string"},"is_legacy":{"type":"boolean"},"management_tools":{"type":"boolean"},"max_tier":{"type":"string"},"name":{"type":"string"},"servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"switchable_to":{"items":{"type":"string"},"type":"array","uniqueItems":false},"title":{"type":"string"},"tool_count":{"description":"ToolCount is the v2 field: indexed tools on the effective servers.\nDeprecated: use tool_counts.","type":"integer"},"tool_counts":{"$ref":"#/components/schemas/runtime.ToolCounts"},"tools":{"$ref":"#/components/schemas/config.ProfileToolRules"},"unannotated":{"type":"string"},"used_by":{"$ref":"#/components/schemas/runtime.UsedBy"}},"type":"object"},"httpapi.ProfileWriteData":{"properties":{"profile":{"$ref":"#/components/schemas/runtime.ProfileView"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.PutClientBindingRequest":{"properties":{"mode":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.RenameProfileRequest":{"properties":{"new_name":{"type":"string"}},"type":"object"},"httpapi.RevokeCredentialResponse":{"properties":{"changed":{"type":"boolean"}},"type":"object"},"httpapi.RotateClientRequest":{"properties":{"precondition_token":{"description":"PreconditionToken is the token of GET /connect/{client}/preview; it\nbinds a supported client's rotation to what the preview showed.","type":"string"}},"type":"object"},"httpapi.RotateClientResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"connect":{"$ref":"#/components/schemas/connect.ConnectResult"},"credential":{"type":"string"},"rotation":{"$ref":"#/components/schemas/httpapi.RotationState"},"snippet":{"$ref":"#/components/schemas/httpapi.ClientSnippet"}},"type":"object"},"httpapi.RotationState":{"properties":{"state":{"type":"string"}},"type":"object"},"httpapi.SetActiveProfileRequest":{"properties":{"active_profile":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.StaleReviewErrorResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"stale_tools":{"$ref":"#/components/schemas/httpapi.StaleToolsDetail"},"success":{"type":"boolean"}},"type":"object"},"httpapi.StaleToolsDetail":{"properties":{"changed":{"items":{"type":"string"},"type":"array","uniqueItems":false},"missing_blocks":{"items":{"type":"string"},"type":"array","uniqueItems":false},"unreviewed":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.TryProfileRequest":{"properties":{"limit":{"type":"integer"},"profile":{"$ref":"#/components/schemas/config.ProfileConfig"},"query":{"type":"string"}},"type":"object"},"httpapi.UndoConnectRequest":{"properties":{"backup_name":{"description":"BackupName is the bare filename (filepath.Base) of the backup returned as\nbackup_path by the preceding connect — a name, never a path. Undo resolves\nthe full path server-side by joining it with the client's own config\ndirectory, so a client-supplied value can never contribute a directory\ncomponent (traversal is impossible by construction). Empty means the\nconnect created the file (no prior file existed), so undo removes it.","type":"string"},"server_name":{"description":"Defaults to \"mcpproxy\"","type":"string"}},"type":"object"},"httpapi.UpdateFailureRequest":{"properties":{"stage":{"description":"Stage is the failure stage of the update session.","enum":["appcast","download","install","other"],"type":"string"}},"type":"object"},"httpapi.UpgradeAdminKeyHoldersRequest":{"properties":{"apply":{"type":"boolean"},"mode":{"type":"string"},"precondition_token":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.approveToolsRequest":{"properties":{"approve_all":{"type":"boolean"},"expected_hashes":{"additionalProperties":{"type":"string"},"description":"ExpectedHashes binds the approval to the reviewed definitions (Spec\n117 PR-2, #1566): tool name -\u003e the review's current_hash. Absent or\nnull is an unbound (legacy) request; {} is bound.","type":["object","null"]},"expected_incarnation":{"description":"ExpectedIncarnation binds the approval to the server the client\nreviewed (Spec 116 FR-017); 409 server_replaced on a mismatch. It is\nindependent of ExpectedHashes and the two may be sent together.","type":"integer"},"tools":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.attentionResponse":{"properties":{"count":{"type":"integer"},"generated_at":{"type":"string"},"items":{"items":{"$ref":"#/components/schemas/contracts.AttentionItem"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.bundleRollbackRequest":{"properties":{"digest":{"description":"Digest is the full 64-character lowercase hex SHA-256 of the target.","type":"string"},"embedded":{"description":"Embedded rolls back to the corpus compiled into this binary.","type":"boolean"},"path":{"description":"Path is where to find the target bundle (a hint only).","type":"string"}},"type":"object"},"httpapi.clientPresence":{"properties":{"active_sessions":{"type":"integer"},"blocked_24h":{"type":"integer"},"browser_login_disabled":{"type":"boolean"},"calls_24h":{"type":"integer"},"config_path":{"type":"string"},"connected":{"type":"boolean"},"connection_unverified":{"type":"boolean"},"credential_checked_at":{"type":"string"},"credential_state":{"$ref":"#/components/schemas/profile.CredentialState"},"credentials":{"description":"Spec 132: the client's credentials (API key and browser logins) and\nwhether browser login is off right now. Both exist only once browser\nlogin was used on this install; until then a row is exactly what it was.\n\nCredentials is a pointer so that once the feature was used a row with no\ncredential serialises \"credentials\": [] instead of omitting the field.","items":{"$ref":"#/components/schemas/httpapi.ClientCredential"},"type":"array","uniqueItems":false},"display_name":{"type":"string"},"display_path":{"type":"string"},"expires_at":{"type":"string"},"icon":{"type":"string"},"id":{"type":"string"},"installed":{"type":"boolean"},"issuer":{"$ref":"#/components/schemas/auth.CredentialIssuer"},"kind":{"type":"string"},"last_seen":{"type":"string"},"lease":{"type":"boolean"},"profile":{"type":"string"},"profile_missing":{"type":"boolean"},"profile_mode":{"type":"string"},"profile_source":{"description":"profile_source is pin (locked) or binding (switchable) and is empty when\ncredential_state is not client.","type":"string"},"profile_state":{"type":"string"},"profile_title":{"type":"string"},"purpose":{"type":"string"},"reload_hint":{"type":"string"},"revoked_at":{"description":"Spec 115 lifecycle fields of the client's credential record (additive):\nwhen it was revoked, who issued it, its stated (unenforced) purpose,\nwhether it is a task lease (lifetime at issue \u003c= 24h) and whether its\nprofile still exists (ok | dangling | none).","type":"string"},"rotation_pending":{"type":"boolean"},"sessions":{"items":{"$ref":"#/components/schemas/httpapi.clientSession"},"type":"array","uniqueItems":false},"state":{"type":"string"},"token_name":{"type":"string"}},"type":"object"},"httpapi.clientSession":{"properties":{"id":{"type":"string"},"last_activity":{"type":"string"},"profile":{"description":"Profile and ProfileSource are the session's latest effective resolution\n(Spec 108-e FR-033); empty on legacy sessions.","type":"string"},"profile_source":{"type":"string"},"started_at":{"type":"string"},"work_session_id":{"type":"string"}},"type":"object"},"httpapi.clientsResponse":{"properties":{"clients":{"items":{"$ref":"#/components/schemas/httpapi.clientPresence"},"type":"array","uniqueItems":false},"routing":{},"warnings":{"items":{"$ref":"#/components/schemas/httpapi.ClientWarning"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.expectedIncarnationBody":{"properties":{"expected_incarnation":{"type":"integer"}},"type":"object"},"httpapi.securityApproveRequest":{"properties":{"block":{"items":{"type":"string"},"type":"array","uniqueItems":false},"expected_hashes":{"additionalProperties":{"type":"string"},"description":"ExpectedHashes binds the approval to the reviewed definitions (Spec\n117 PR-2, #1566): tool name -\u003e the review's current_hash. Absent or\nnull is an unbound (legacy) request; {} binds to the empty snapshot.\nIndependent of ExpectedIncarnation: a request may carry both, and the\ntwo refusals stay distinct (review_out_of_date vs server_replaced).","type":["object","null"]},"expected_incarnation":{"description":"ExpectedIncarnation binds the approval to the server the client\nreviewed (Spec 116 FR-017): a remove and re-add since then is refused\nwith 409 server_replaced and the replacement stays quarantined.","type":"integer"},"force":{"type":"boolean"}},"type":"object"},"management.BulkOperationResult":{"properties":{"errors":{"additionalProperties":{"type":"string"},"description":"Map of server name to error message","type":"object"},"failed":{"description":"Number of failed operations","type":"integer"},"successful":{"description":"Number of successful operations","type":"integer"},"total":{"description":"Total servers processed","type":"integer"}},"type":"object"},"observability.HealthResponse":{"properties":{"components":{"items":{"$ref":"#/components/schemas/observability.HealthStatus"},"type":"array","uniqueItems":false},"status":{"description":"\"healthy\" or \"unhealthy\"","type":"string"},"timestamp":{"type":"string"}},"type":"object"},"observability.HealthStatus":{"properties":{"error":{"type":"string"},"latency":{"type":"string"},"name":{"type":"string"},"status":{"description":"\"healthy\" or \"unhealthy\"","type":"string"}},"type":"object"},"observability.ReadinessResponse":{"properties":{"components":{"items":{"$ref":"#/components/schemas/observability.HealthStatus"},"type":"array","uniqueItems":false},"status":{"description":"\"ready\" or \"not_ready\"","type":"string"},"timestamp":{"type":"string"}},"type":"object"},"profile.AccessStepStatus":{"type":"string","x-enum-varnames":["AccessStepPass","AccessStepFail","AccessStepSkip"]},"profile.AccessSubjectKind":{"type":"string","x-enum-varnames":["AccessSubjectClient","AccessSubjectProfile","AccessSubjectToken","AccessSubjectAnonymous"]},"profile.BlockReason":{"type":"string","x-enum-varnames":["BlockReasonTier","BlockReasonRule","BlockReasonUnannotated","BlockReasonCodeExecution","BlockReasonManagement","BlockReasonServerScope"]},"profile.CredentialState":{"description":"Spec 108-f ClientView additions (data-model §7). The Spec 109 fields above\nare unchanged; everything below is additive.\n\ncredential_state is what the client's connection carries (client |\nadmin_key | none | revoked | expired | unknown). The stat-only list never\nreads a config: it reports the token store, else the last on-demand\nobservation (credential_checked_at says when), else unknown.","type":"string","x-enum-varnames":["CredentialStateClient","CredentialStateAdminKey","CredentialStateNone","CredentialStateRevoked","CredentialStateExpired","CredentialStateUnknown"]},"profile.ExplainStep":{"type":"string","x-enum-varnames":["StepCredential","StepProfile","StepServerInScope","StepToolRule","StepTierCap","StepTokenPermission","StepGlobalGate","StepServerState","StepToolApproval"]},"profile.ExplainVerdict":{"type":"string","x-enum-varnames":["ExplainVerdictAllowed","ExplainVerdictBlocked","ExplainVerdictHidden"]},"profile.FixAction":{"type":"string","x-enum-varnames":["FixAllowInProfile","FixClassifyInProfile","FixAddServerToProfile","FixMoveClient","FixEditToken","FixEnableServer","FixApproveTool","FixChangeSetting","FixReconnectClient"]},"profile.WarningCode":{"type":"string","x-enum-varnames":["WarningAnonymousDeniedByBindingGuard","WarningClientHoldsAdminKey","WarningClientCredentialExpiring","WarningClientRotationPending","WarningProfileMissing","WarningClientTokenNameConflict"]},"profile.WarningSeverity":{"type":"string","x-enum-varnames":["WarningSeverityWarn","WarningSeverityInfo"]},"runtime.AccessSuggestion":{"properties":{"block_reason":{"$ref":"#/components/schemas/profile.BlockReason"},"clients":{"items":{"type":"string"},"type":"array","uniqueItems":false},"count":{"type":"integer"},"first_seen":{"type":"string"},"fixes":{"description":"Fixes are the access explainer's remediations of the first failing step,\nin preference order. Empty for a deny rule and for the built-in tools.","items":{"$ref":"#/components/schemas/runtime.Fix"},"type":"array","uniqueItems":false},"last_seen":{"type":"string"},"needs_input":{"description":"NeedsInput names what a person must supply before a change is\napply-ready (classify: \"tier\").","items":{"type":"string"},"type":"array","uniqueItems":false},"note":{"type":"string"},"profile":{"type":"string"},"server":{"type":"string"},"suggestion":{"$ref":"#/components/schemas/runtime.SuggestionKind"},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false},"tool":{"description":"\"server:tool\", or the built-in name","type":"string"},"warning":{"description":"Warning is set for profile_code_execution and profile_management: both\nchange what a profile can do beyond tool access.","type":"string"}},"type":"object"},"runtime.BindingRef":{"properties":{"client_id":{"type":"string"},"mode":{"type":"string"},"profile":{"type":"string"},"token_name":{"type":"string"}},"type":"object"},"runtime.EffectiveCounts":{"properties":{"by_reason":{"additionalProperties":{"type":"integer"},"type":"object"},"callable":{"type":"integer"},"hidden":{"type":"integer"},"visible":{"type":"integer"}},"type":"object"},"runtime.EffectiveTool":{"properties":{"access":{"$ref":"#/components/schemas/runtime.ToolAccessView"},"classification_stale":{"type":"boolean"},"intrinsic_tier":{"type":"string"},"profile_tier":{"type":"string"},"server":{"type":"string"},"tool":{"type":"string"}},"type":"object"},"runtime.ExplainProfileView":{"properties":{"name":{"type":"string"},"source":{"type":"string"}},"type":"object"},"runtime.ExplainStepView":{"properties":{"detail":{"type":"string"},"status":{"$ref":"#/components/schemas/profile.AccessStepStatus"},"step":{"$ref":"#/components/schemas/profile.ExplainStep"}},"type":"object"},"runtime.ExplainSubjectView":{"properties":{"kind":{"$ref":"#/components/schemas/profile.AccessSubjectKind"},"name":{"type":"string"}},"type":"object"},"runtime.Fix":{"properties":{"action":{"$ref":"#/components/schemas/profile.FixAction"},"label":{"type":"string"},"profile":{"description":"Profile is set for move_client only: the destination profile slug the fix\nmoves the client to. Target stays the client id (UIs navigate by it) and\nLabel carries the title, so neither can name the slug.","type":"string"},"step":{"type":"string","x-enum-varnames":["StepCredential","StepProfile","StepServerInScope","StepToolRule","StepTierCap","StepTokenPermission","StepGlobalGate","StepServerState","StepToolApproval"]},"target":{"type":"string"}},"type":"object"},"runtime.GuardFix":{"properties":{"kind":{"type":"string"},"target":{"type":"string"}},"type":"object"},"runtime.MovedRefs":{"properties":{"clients":{"items":{"type":"string"},"type":"array","uniqueItems":false},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"runtime.ProfilePatch":{"properties":{"changes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"profile":{"type":"string"},"proposed":{"$ref":"#/components/schemas/config.ProfileConfig"}},"type":"object"},"runtime.ProfileView":{"properties":{"blocked_24h":{"type":"integer"},"calls_24h":{"type":"integer"},"code_execution":{"type":"boolean"},"description":{"type":"string"},"effective_code_execution":{"type":"boolean"},"effective_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"effective_unannotated":{"type":"string"},"is_legacy":{"type":"boolean"},"management_tools":{"type":"boolean"},"max_tier":{"type":"string"},"name":{"type":"string"},"servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"switchable_to":{"items":{"type":"string"},"type":"array","uniqueItems":false},"title":{"type":"string"},"tool_count":{"description":"ToolCount is the v2 field: indexed tools on the effective servers.\nDeprecated: use tool_counts.","type":"integer"},"tool_counts":{"$ref":"#/components/schemas/runtime.ToolCounts"},"tools":{"$ref":"#/components/schemas/config.ProfileToolRules"},"unannotated":{"type":"string"},"used_by":{"$ref":"#/components/schemas/runtime.UsedBy"}},"type":"object"},"runtime.SuggestionKind":{"type":"string","x-enum-varnames":["SuggestAllow","SuggestAddServer","SuggestClassify","SuggestNone"]},"runtime.ToolAccessView":{"properties":{"callable":{"type":"boolean"},"reason":{"type":"string"},"visible":{"type":"boolean"}},"type":"object"},"runtime.ToolCounts":{"properties":{"destructive":{"type":"integer"},"read":{"type":"integer"},"unannotated_hidden":{"type":"integer"},"write":{"type":"integer"}},"type":"object"},"runtime.TryHidden":{"properties":{"reason":{"type":"string"},"server":{"type":"string"},"tool":{"type":"string"}},"type":"object"},"runtime.UsedBy":{"properties":{"anonymous_profile":{"type":"boolean"},"clients":{"items":{"$ref":"#/components/schemas/runtime.UsedByClient"},"type":"array","uniqueItems":false},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"runtime.UsedByClient":{"properties":{"id":{"type":"string"},"mode":{"type":"string"}},"type":"object"},"runtime.WarningAction":{"properties":{"kind":{"type":"string"},"target":{"type":"string"}},"type":"object"},"scanner.BundleInfo":{"properties":{"authority":{"description":"Authority is the signing root serving this bundle: \"publisher\" (the\nembedded default, or verified against a publisher key), \"operator\", or \"\"\nfor an unsigned external bundle.","type":"string"},"bundle_version":{"description":"BundleVersion / SchemaVersion are the corpus's own declared versions.","type":"string"},"coverage_degraded":{"description":"CoverageDegraded suspends scan-mode auto-approval; DegradedReason says\nwhy (one of the Degraded* constants).","type":"boolean"},"declared_skipped":{"type":"integer"},"degraded_reason":{"type":"string"},"fingerprint":{"description":"Fingerprint is the first 12 hex chars of the SHA-256 of the corpus bytes:\na stable identity an operator (or automation) can compare across hosts\nwithout shipping the whole file around.","type":"string"},"full_digest":{"description":"FullDigest is the complete lowercase-hex SHA-256 of the bundle bytes —\nthe ONLY value rollback accepts (FR-010). Fingerprint stays the 12-hex\nhuman label beside it.","type":"string"},"generated_at":{"description":"GeneratedAt is the corpus freshness stamp. It is the bundle's own\n` + "`" + `generated_at` + "`" + ` key when present; for a file-sourced bundle without one it\nfalls back to the file's modification time, so a years-stale corpus is\ndistinguishable from a fresh export.","type":"string"},"last_activated_at":{"description":"LastActivatedAt is when the serving external bundle was activated; nil\nfor the embedded default.","type":"string"},"last_checked_at":{"description":"LastCheckedAt is the end of the most recent pipeline run, including\nno-op runs the idempotence short-circuit skipped.","type":"string"},"last_rejection":{"$ref":"#/components/schemas/scanner.BundleRejection"},"load_error":{"description":"LoadError is the reason the LAST configured-path load failed, if any. The\npreviously active (or embedded) corpus stays live — a bundle problem must\nnever leave the scanner with no signatures — but the failure is surfaced\nhere rather than swallowed.","type":"string"},"loaded_at":{"description":"LoadedAt is when this corpus became active in this process.","type":"string"},"path":{"description":"Path is the configured filesystem path, when Source is \"file\".","type":"string"},"pinned":{"description":"Pinned is true while an operator rollback pin governs activation.","type":"boolean"},"refresh":{"$ref":"#/components/schemas/scanner.BundleRefreshStatus"},"reprotect":{"$ref":"#/components/schemas/scanner.BundleReprotectStatus"},"rollback":{"description":"Rollback is true when the active bundle was activated by an explicit\nrollback.","type":"boolean"},"runnable_rules":{"description":"RunnableRules is how many rules are LIVE in the offline tier; SkippedRules\nand DeclaredSkipped are the not-runnable / bundle-declared-skipped\nremainder (FR-006/FR-007) — un-evaluated coverage, never clean coverage.","type":"integer"},"schema_version":{"type":"string"},"sequence":{"description":"Sequence is the manifest sequence as published (decimal string), \"\" when\nthe bundle carries none.","type":"string"},"signature_count":{"description":"SignatureCount is the bundle's self-declared signature count.","type":"integer"},"signature_verified":{"description":"SignatureVerified reports whether the active bundle's detached signature\nverified. Always false for the embedded default (it is binary-trusted).","type":"boolean"},"skipped_rules":{"type":"integer"},"source":{"description":"Source is BundleSourceEmbedded, BundleSourceFile or BundleSourceFetch.","type":"string"},"stale":{"description":"Stale and StaleAfterDays are computed at read time next to\nStalenessDays; a future generated_at is never stale. StaleAfterDays nil\nmeans the flag is not evaluated.","type":"boolean"},"stale_after_days":{"type":"integer"},"staleness_days":{"description":"StalenessDays is the whole days since GeneratedAt (nil when unknown).","type":"integer"},"trust_epoch":{"description":"TrustEpoch is the epoch the bundle was published under.","type":"integer"}},"type":"object"},"scanner.BundleRefreshStatus":{"description":"Refresh is the refresh-cycle status (nil before any cycle or setting is\nknown). Reprotect is the post-activation re-protection sweep status,\nset from the server through SetReprotectStatus.","properties":{"consecutive_failures":{"type":"integer"},"fetch_enabled":{"type":"boolean"},"fetch_host":{"description":"FetchHost is the host of the configured fetch URL (\"\" when none).","type":"string"},"fetch_reason":{"type":"string"},"fetch_state":{"description":"FetchState and FetchReason are the fetch leg's own last answer (one of the\nRefreshOutcome* values and its reason), kept apart from LastOutcome: a file\nactivation owns the merged cycle outcome but must not hide a fetch leg that\ncannot run (B16 warning 3).","type":"string"},"interval_seconds":{"type":"integer"},"last_attempt_at":{"type":"string"},"last_outcome":{"type":"string"},"last_reason":{"type":"string"},"last_trigger":{"description":"LastTrigger, LastOutcome and LastReason use the closed vocabularies above.","type":"string"},"next_check_at":{"type":"string"}},"type":"object"},"scanner.BundleRejection":{"description":"LastRejection is the most recent refused candidate. It is retained\nacross a later successful load so \"what did it refuse, and when\"\nsurvives.","properties":{"at":{"type":"string"},"detail":{"description":"Detail is a short human string (which ceiling, which key id, which\nepoch, the bundlesig contract code). Never parsed.","type":"string"},"reason":{"description":"Reason is one of the Reject* constants; the only field to branch on.","type":"string"}},"type":"object"},"scanner.BundleReprotectStatus":{"properties":{"last_completed_at":{"type":"string"},"reason":{"description":"Reason qualifies suspended and failed (for example\nReprotectReasonAutoBaselineScanOff).","type":"string"},"servers_scanned":{"type":"integer"},"servers_with_hits":{"type":"integer"},"state":{"description":"State is one of the ReprotectState* constants.","type":"string"}},"type":"object"},"secureenv.EnvConfig":{"description":"Environment configuration for secure variable filtering","properties":{"allowed_system_vars":{"items":{"type":"string"},"type":"array","uniqueItems":false},"custom_vars":{"additionalProperties":{"type":"string"},"type":"object"},"enhance_path":{"description":"Enable PATH enhancement for Launchd scenarios","type":"boolean"},"forward_proxy_env":{"description":"ForwardProxyEnv opts in to forwarding the ambient HTTP(S)/ALL/NO/FTP proxy\nenvironment variables to spawned upstream servers (MCP-2769). It is OFF by\ndefault and deliberately kept out of the AllowedSystemVars default list:\nproxy URLs frequently carry credentials (http://user:pass@proxy), so\nforwarding them to every stdio upstream is a credential-leak risk. When\nenabled, values are forwarded with their userinfo (credentials) redacted.","type":"boolean"},"inherit_system_safe":{"type":"boolean"}},"type":"object"},"storage.ClientCredentialObservation":{"properties":{"at":{"type":"string"},"state":{"type":"string"}},"type":"object"},"storage.OnboardingState":{"description":"State is the persisted wizard engagement record. Engaged is true once\nthe wizard was shown and the user completed or skipped it.","properties":{"client_connected_at":{"additionalProperties":{"type":"string"},"description":"ClientConnectedAt records, per client id from the fixed connect client\nregistry (internal/connect.GetAllClients — never user input), the last\ntime a connect write succeeded for that client (Spec 109-b FR-042).\nWritten by the connect success path through UpdateOnboardingState so a\nconcurrent onboarding/mark write can never drop it. Consumed by the\nVerify step / presence layer to tell \"connected, never seen\" apart from\n\"connected seconds ago, hasn't reconnected yet\".","type":"object"},"client_credential_observed":{"additionalProperties":{"$ref":"#/components/schemas/storage.ClientCredentialObservation"},"description":"ClientCredentialObserved records, per client id, the LAST credential\nclassification an on-demand read produced (Spec 108-f FR-025, F11): what\nthe client's config held (client | admin_key | none | revoked | expired)\nand when it was read. The stat-only GET /clients listing never reads a\nconfig (Spec 075: no macOS App-Data prompt from a list), so this is how\nit still reports a client that holds the admin key across restarts. It is\nwritten only when the classification CHANGES, by every on-demand read\n(GET /clients/{id}, GET /connect/{client}, the admin-key upgrade preview,\na connect write) and deleted on disconnect. Additive: an older binary\nignores it, and a record without it reads as \"unknown\".","type":"object"},"client_disconnected_at":{"additionalProperties":{"type":"string"},"type":"object"},"client_last_seen":{"additionalProperties":{"type":"string"},"description":"ClientLastSeen records the latest MCP initialize for a recognised client\nalias. It is intentionally kept with onboarding state: presence is a\nlocal UI concern and must still work when telemetry is disabled.","type":"object"},"connect_step_status":{"description":"ConnectStepStatus is one of: \"\", \"completed\", \"completed_external\",\n\"skipped\" (Spec 080 FR-001). \"completed_external\" records a dismissal\nwhere the connect step was untouched but the install was already\nconnected outside the wizard (CLI, ConnectModal, manual config).","type":"string"},"engaged":{"description":"Engaged is true once the wizard was shown and the user completed or\nskipped it. Once true, the wizard does not auto-show again, even if\nstate regresses (e.g. user disconnects all clients).","type":"boolean"},"engaged_at":{"description":"EngagedAt is the timestamp of completion or explicit skip.","type":"string"},"first_shown_at":{"description":"FirstShownAt is the timestamp of first wizard render.","type":"string"},"server_step_status":{"description":"ServerStepStatus is one of: \"\", \"completed\", \"skipped\".","type":"string"}},"type":"object"},"telemetry.DiagnosticsCounters":{"properties":{"current_error_codes":{"additionalProperties":{"type":"integer"},"description":"CurrentErrorCodes is the STANDING state at heartbeat time: stable MCPX_\ncode -\u003e number of configured servers currently in that state. It is not\na counter and is never persisted — it is recomputed each heartbeat from\nthe supervisor's live stateview.\n\nSchema v11 (MCP-2967). It exists because error_code_counts_24h became\nedge-triggered in the same change: previously the supervisor re-counted\nevery standing failure on its 30s reconcile ticker, so a parked install\ninflated the counter by ~2880/day/server. Edge-triggering alone would\nhave swung the error to the other side — the 24h window decays, this\nstruct is omitempty via isZero(), so a permanently broken install would\nemit once and then disappear from the payload entirely, and absent reads\nas zero. The two fields answer different questions and are only correct\ntogether: \"how often did something newly break\" and \"how many servers\nare broken right now\".\n\nSafe: only MCPX_* enum constants as keys, never server names, URLs,\ncommands, or free text; values are non-negative server counts.","type":"object"},"error_code_counts_24h":{"additionalProperties":{"type":"integer"},"description":"ErrorCodeCounts24h maps stable MCPX_ code strings to 24h occurrence counts.\nSafe: only MCPX_* enum constants are stored here, never free text, paths,\nserver names, or user-entered values.","type":"object"},"fix_attempted_24h":{"description":"FixAttempted24h counts POST /api/v1/diagnostics/fix calls in the last 24h.","type":"integer"},"fix_succeeded_24h":{"description":"FixSucceeded24h counts fix invocations with outcome=\"success\" in the last 24h.","type":"integer"},"unique_codes_ever":{"description":"UniqueCodesEver is the cardinality of the all-time error code set.\nBounded by the MCPX_ catalog size (~30 codes), never approaches PII risk.","type":"integer"}},"type":"object"},"telemetry.FeedbackContext":{"properties":{"anonymous_id":{"description":"AnonymousID is the install's telemetry anonymous ID (heartbeat value).","type":"string"},"arch":{"type":"string"},"connected_server_count":{"type":"integer"},"diagnostics":{"$ref":"#/components/schemas/telemetry.DiagnosticsCounters"},"edition":{"type":"string"},"go_version":{"type":"string"},"last_error_code":{"description":"LastErrorCode is the most recent MCPX_* error code.","type":"string"},"last_startup_outcome":{"description":"LastStartupOutcome is the previous startup's outcome word.","type":"string"},"machine_id":{"description":"MachineID is the hashed machine identifier (heartbeat value).","type":"string"},"os":{"type":"string"},"previous_shutdown":{"description":"PreviousShutdown is how the previous run ended (clean, crash, ...).","type":"string"},"routing_mode":{"type":"string"},"server_count":{"type":"integer"},"tool_count":{"type":"integer"},"uptime_minutes":{"description":"UptimeMinutes is the daemon's uptime. Omitted from short-lived CLI\nsubmissions, where the process uptime says nothing about the daemon.","type":"integer"},"version":{"type":"string"}},"type":"object"},"telemetry.FeedbackRequest":{"properties":{"category":{"description":"bug, feature, other","type":"string"},"context":{"$ref":"#/components/schemas/telemetry.FeedbackContext"},"email":{"type":"string"},"message":{"type":"string"}},"type":"object"},"telemetry.FeedbackResponse":{"properties":{"error":{"type":"string"},"issue_url":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}},"securitySchemes":{"ApiKeyAuth":{"description":"API key authentication via query parameter. Use ?apikey=your-key","in":"query","name":"apikey","type":"apiKey"}}}, "info": {"contact":{"name":"MCPProxy Support","url":"https://github.com/smart-mcp-proxy/mcpproxy-go"},"description":"{{escape .Description}}","license":{"name":"MIT","url":"https://opensource.org/licenses/MIT"},"title":"{{.Title}}","version":"{{.Version}}"}, "externalDocs": {"description":"","url":""}, "paths": {"/api/v1/access/explain":{"get":{"description":"For one subject (exactly one of client=\u003cid\u003e, token=\u003cname\u003e, profile=\u003cname\u003e or anonymous=true) and one upstream tool (server:tool), returns the ordered chain of gates a real call would meet - credential, profile, server_in_scope, tool_rule, tier_cap, token_permission, global_gate, server_state, tool_approval - the overall verdict (allowed, blocked, hidden), the first failing step and the fixes for it in preference order. The chain is the one every discovery and dispatch path walks, so ` + "`" + `allowed` + "`" + ` equals what a real call does. Built-in management tools are not explained (400). A client credential is explained with client=, never token=. Administrators only.","parameters":[{"description":"Upstream tool as server:tool","in":"query","name":"tool","required":true,"schema":{"type":"string"}},{"description":"Client id","in":"query","name":"client","schema":{"type":"string"}},{"description":"Regular agent token name","in":"query","name":"token","schema":{"type":"string"}},{"description":"Profile name","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Explain an anonymous (credential-less) caller","in":"query","name":"anonymous","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The explanation"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Not exactly one subject, a built-in tool, or token=client-\u003cid\u003e"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"client / token / profile not found"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Explain why a tool is or is not reachable","tags":["access"]}},"/api/v1/access/suggest":{"get":{"description":"Reads the profile refusals in the activity log over a look-back window and groups them by profile, tool and block reason. Each group is re-checked with the access explainer, so tools that are already reachable drop out, and carries the explainer's fixes. A deny-rule block is reported and never offered for widening; an unannotated tool is never given a tier. Nothing is applied. patch=true also returns the proposed profile document per profile (the body PUT /api/v1/profiles/{name} takes).","parameters":[{"description":"Look-back window: a duration such as 90m, 24h or 7d (default 24h; the audit-log retention is the only limit)","in":"query","name":"since","schema":{"type":"string"}},{"description":"Only refusals under this profile","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Only refusals of this token","in":"query","name":"token","schema":{"type":"string"}},{"description":"Also return the proposed profile document per profile","in":"query","name":"patch","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The suggestions"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid since"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Suggest profile changes from blocked calls","tags":["access"]}},"/api/v1/activity":{"get":{"description":"Returns paginated list of activity records with optional filtering","parameters":[{"description":"Filter by activity type(s), comma-separated for multiple (Spec 024)","in":"query","name":"type","schema":{"enum":["tool_call","policy_decision","quarantine_change","server_change","system_start","system_stop","internal_tool_call","config_change","preflight","prompt_get","profile_change","upstream_event"],"type":"string"}},{"description":"Filter by server name","in":"query","name":"server","schema":{"type":"string"}},{"description":"Filter by tool name","in":"query","name":"tool","schema":{"type":"string"}},{"description":"Filter by MCP transport session ID","in":"query","name":"session_id","schema":{"type":"string"}},{"description":"Filter by work session (one client, one project, across reconnects)","in":"query","name":"work_session_id","schema":{"type":"string"}},{"description":"Filter by status","in":"query","name":"status","schema":{"enum":["success","error","blocked","rejected"],"type":"string"}},{"description":"Filter by intent operation type (Spec 018)","in":"query","name":"intent_type","schema":{"enum":["read","write","destructive"],"type":"string"}},{"description":"Filter by HTTP request ID for log correlation (Spec 021)","in":"query","name":"request_id","schema":{"type":"string"}},{"description":"Filter by parent call id — returns the sub-calls one code_execution issued","in":"query","name":"parent_id","schema":{"type":"string"}},{"description":"Filter by call-error class (Spec 113-c)","in":"query","name":"error_class","schema":{"enum":["network","timeout","http","jsonrpc","tool_error","session_terminated","auth","proxy_policy","proxy_internal","cancelled"],"type":"string"}},{"description":"Filter by fault domain (Spec 113-c)","in":"query","name":"fault_domain","schema":{"enum":["upstream","proxy","client"],"type":"string"}},{"description":"Include successful call_tool_* internal tool calls (default: false, excluded to avoid duplicates)","in":"query","name":"include_call_tool","schema":{"type":"boolean"}},{"description":"Filter by sensitive data detection (true=has detections, false=no detections)","in":"query","name":"sensitive_data","schema":{"type":"boolean"}},{"description":"Filter by specific detection type (e.g., 'aws_access_key', 'credit_card')","in":"query","name":"detection_type","schema":{"type":"string"}},{"description":"Filter by severity level","in":"query","name":"severity","schema":{"enum":["critical","high","medium","low"],"type":"string"}},{"description":"Alias of token (Spec 028)","in":"query","name":"agent","schema":{"type":"string"}},{"description":"Filter by the token in effect for the call; - selects records with no token (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Filter by the profile in effect for the call; - selects records with no profile (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Filter by client id; - selects records with no client (Spec 108)","in":"query","name":"client","schema":{"type":"string"}},{"description":"Filter by the client's self-reported name (advisory; Spec 108)","in":"query","name":"client_name","schema":{"type":"string"}},{"description":"Filter by auth type (Spec 028)","in":"query","name":"auth_type","schema":{"enum":["admin","agent"],"type":"string"}},{"description":"Filter activities after this time (RFC3339)","in":"query","name":"start_time","schema":{"type":"string"}},{"description":"Filter activities before this time (RFC3339)","in":"query","name":"end_time","schema":{"type":"string"}},{"description":"Maximum records to return (1-100, default 50)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Pagination offset (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Omit arguments, response and metadata except a contextual whitelist (intent.reason, intent.operation_type, decision, reason, client_name, client_version) (default: false). For clients that render summary fields only; has_sensitive_data is still derived before metadata is dropped.","in":"query","name":"exclude_payloads","schema":{"type":"boolean"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"List activity records","tags":["Activity"]}},"/api/v1/activity/export":{"get":{"description":"Exports activity records in JSON Lines or CSV format for compliance","parameters":[{"description":"Export format: json (default) or csv","in":"query","name":"format","schema":{"type":"string"}},{"description":"Filter by activity type","in":"query","name":"type","schema":{"type":"string"}},{"description":"Filter by server name","in":"query","name":"server","schema":{"type":"string"}},{"description":"Filter by tool name","in":"query","name":"tool","schema":{"type":"string"}},{"description":"Filter by MCP transport session ID","in":"query","name":"session_id","schema":{"type":"string"}},{"description":"Filter by work session (one client, one project, across reconnects)","in":"query","name":"work_session_id","schema":{"type":"string"}},{"description":"Filter by status","in":"query","name":"status","schema":{"type":"string"}},{"description":"Filter by HTTP request ID for log correlation (Spec 021)","in":"query","name":"request_id","schema":{"type":"string"}},{"description":"Filter by parent call id — exports the sub-calls one code_execution issued","in":"query","name":"parent_id","schema":{"type":"string"}},{"description":"Filter by call-error class (Spec 113-c)","in":"query","name":"error_class","schema":{"enum":["network","timeout","http","jsonrpc","tool_error","session_terminated","auth","proxy_policy","proxy_internal","cancelled"],"type":"string"}},{"description":"Filter by fault domain (Spec 113-c)","in":"query","name":"fault_domain","schema":{"enum":["upstream","proxy","client"],"type":"string"}},{"description":"Alias of token (Spec 028)","in":"query","name":"agent","schema":{"type":"string"}},{"description":"Filter by the token in effect for the call; - selects records with no token (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Filter by the profile in effect for the call; - selects records with no profile (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Filter by client id; - selects records with no client (Spec 108)","in":"query","name":"client","schema":{"type":"string"}},{"description":"Filter by the client's self-reported name (advisory; Spec 108)","in":"query","name":"client_name","schema":{"type":"string"}},{"description":"Filter activities after this time (RFC3339)","in":"query","name":"start_time","schema":{"type":"string"}},{"description":"Filter activities before this time (RFC3339)","in":"query","name":"end_time","schema":{"type":"string"}},{"description":"Maximum records to export (1-50000, default 10000)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Pagination offset (default 0)","in":"query","name":"offset","schema":{"type":"integer"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"type":"string"}},"application/x-ndjson":{"schema":{"type":"string"}},"text/csv":{"schema":{"type":"string"}}},"description":"Streamed activity records"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Export activity records","tags":["Activity"]}},"/api/v1/activity/summary":{"get":{"description":"Returns aggregated activity statistics for a time period","parameters":[{"description":"Time period: 1h, 24h (default), 7d, 30d","in":"query","name":"period","schema":{"type":"string"}},{"description":"Group by: server, tool (optional)","in":"query","name":"group_by","schema":{"type":"string"}},{"description":"Alias of token (Spec 028)","in":"query","name":"agent","schema":{"type":"string"}},{"description":"Count only records made under this token; - selects records with no token (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Count only records made under this profile; - selects records with no profile (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Count only records made by this client id; - selects records with no client (Spec 108)","in":"query","name":"client","schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Get activity summary statistics","tags":["Activity"]}},"/api/v1/activity/usage":{"get":{"description":"Returns the actor-owned usage aggregate (per-tool rollup + timeline + tokens-saved headline) for the Web UI usage graphs (Spec 069). Served from an in-memory snapshot — never a per-request full-log scan. Per-tool metrics are lifetime-cumulative; ` + "`" + `window` + "`" + ` scopes the timeline and filters the tool list to tools active within the span.","parameters":[{"description":"Time window for timeline + tool-list membership","in":"query","name":"window","schema":{"enum":["24h","7d","all"],"type":"string"}},{"description":"Filter to one server","in":"query","name":"server","schema":{"type":"string"}},{"description":"Filter to one tool","in":"query","name":"tool","schema":{"type":"string"}},{"description":"Filter to tools with activity of this status","in":"query","name":"status","schema":{"enum":["success","error","blocked","rejected"],"type":"string"}},{"description":"Top-N tools by sort key; remainder folded into 'other' (default 20)","in":"query","name":"top","schema":{"type":"integer"}},{"description":"Ranking key for the per-tool list","in":"query","name":"sort","schema":{"enum":["calls","resp_bytes","error_rate","p95"],"type":"string"}},{"description":"Alias of token (Spec 028)","in":"query","name":"agent","schema":{"type":"string"}},{"description":"Restrict to calls made under this token; - selects records with no token. Computed from a window-bounded scan (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Restrict to calls made under this profile; - selects records with no profile. Computed from a window-bounded scan (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Restrict to calls made by this client id; - selects records with no client. Computed from a window-bounded scan (Spec 108)","in":"query","name":"client","schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Get usage statistics aggregate","tags":["Activity"]}},"/api/v1/activity/{id}":{"get":{"description":"Returns full details for a single activity record","parameters":[{"description":"Activity record ID (ULID)","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Not Found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Get activity record details","tags":["Activity"]}},"/api/v1/annotations/coverage":{"get":{"description":"Reports how many upstream tools have MCP annotations vs don't, broken down by server","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Annotation coverage report"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get annotation coverage report","tags":["annotations"]}},"/api/v1/attention":{"get":{"description":"One list, one count, every surface (Web UI, macOS tray/Home, CLI) reads from it. Filtered per caller: an administrator sees every item; a scoped caller (agent token, or a non-admin server-edition OAuth user session) sees only server items whose server it may enumerate (for a profile-pinned token: servers within its pin); every other subject type (client, setting) and the skill_review kind (Spec 125 held skills) are administrator-only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.attentionResponse"}}},"description":"The needs-attention list"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the needs-attention list","tags":["attention"]}},"/api/v1/catalog/search":{"get":{"description":"Fans out to every enabled catalog source (registry) in parallel, merges, de-duplicates and ranks the results (FR-060/061). An empty q returns official + popular sections instead of a flat list. Open to any authenticated caller — added is the only field filtered per caller scope (FR-007).","parameters":[{"description":"Free-text search","in":"query","name":"q","schema":{"type":"string"}},{"description":"Narrow to one catalog source id","in":"query","name":"source","schema":{"type":"string"}},{"description":"Not supported: catalog entries carry no tags; a non-empty value returns 400","in":"query","name":"tag","schema":{"type":"string"}},{"description":"Max results (default 20, max 50)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"tag filtering is not supported"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"configured servers could not be listed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Search the server catalog across every enabled source","tags":["catalog"]}},"/api/v1/clients":{"get":{"description":"Lists every client row (supported, other and custom) with its presence, its credential and its profile binding, plus response-level warnings. The list is content-read-free (Spec 075): credential_state comes from the token store, else the last on-demand observation (credential_checked_at), else unknown. It runs only the time-based half of the rotation reconciler. The profile and client filters match the CURRENT binding and are applied AFTER warnings are computed over the full set.","parameters":[{"description":"Rows whose active credential is bound to this profile; - = bound to All servers","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Exact client id","in":"query","name":"client","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Client rows, routing and warnings"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List clients","tags":["clients"]},"post":{"description":"Creates a per-client credential for a client that is NOT in the connect registry (a script, a CI job, an editor without a connect adapter). The secret (mcp_cli_...) is returned ONCE, with a paste-ready snippet that carries it in the X-API-Key header. The id follows the client-id rule (lower-case letters, digits, '-' or '_', at most 56 characters) and must not be a supported client's id. A named profile binds the credential locked unless mode says otherwise. Refused with 409 binding_bypassable_without_auth when the binding would be bypassable while require_mcp_auth is off (FR-008a), and 409 conflicting_token when a regular token holds client-\u003cid\u003e. Every value (id, display_name, profile, mode, expires_in, purpose) passes the shared secret-shaped input screen first: a credential, the API key or a detector-flagged secret answers 400 secret_in_argument naming the field, and nothing is minted. A malformed body answers a sanitized 400 that never echoes a caller key or value. Writes one profile_change record with change issue (Spec 115) and publishes credentials.changed. Personal edition only.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.CreateClientRequest"}}},"description":"id (required), optional display_name, profile, mode, expires_in and purpose","required":true},"responses":{"201":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The new client row, its credential (once) and a snippet"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"binding_bypassable_without_auth, or conflicting_token (ClientCredentialConflictResponse)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add a custom client","tags":["clients"]}},"/api/v1/clients/bulk-assign":{"post":{"description":"Moves every client credential bound to from_profile (\"\" = All servers) onto to_profile (\"\" = All servers). The guard and the credential precondition apply PER CLIENT: a refused client is reported in skipped[] with the code the single operation returns, the others move and each writes its own assign record and emits client.binding_changed. Personal edition only.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BulkAssignRequest"}}},"description":"from_profile and to_profile (both required; empty = All servers) and optional mode","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Moved client ids and the clients that were skipped"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Move every client of one profile to another","tags":["clients"]}},"/api/v1/clients/upgrade-admin-key-holders":{"post":{"description":"Without apply: classifies every supported client whose config still holds the instance admin API key (an on-demand read per client) and returns preview[] (display path, what would change, the masked credential mcp_cli_••••, the binding and a precondition_token per client), a combined precondition_token, and guard when the whole request would be refused by FR-008a; next_step is rotate_admin_api_key when nothing holds the key. Nothing is written or minted. With apply=true: recomputes the preview, refuses with 409 precondition_failed when a sent precondition_token no longer matches, runs the FR-008a guard over the WHOLE request (409 binding_bypassable_without_auth, nothing minted, no file written), then connects each client with force bound to its own token; one client's failure does not stop the others. Each mint writes its own assign record. The guard only applies when a named profile is given. Personal edition only.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.UpgradeAdminKeyHoldersRequest"}}},"description":"Optional profile and mode for every upgraded client; apply and precondition_token"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"UpgradePreview (no apply) or UpgradeResult (apply)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"precondition_failed, or binding_bypassable_without_auth"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Upgrade every client that holds the admin API key","tags":["clients"]}},"/api/v1/clients/{client}":{"delete":{"description":"Revokes the client's credential; it stops authenticating at once. With disconnect=true a SUPPORTED client's mcpproxy entry is removed from its config FIRST, but the credential is revoked either way: revocation never waits for a config write, so a failed write (for example a macOS App-Data denial) leaves the client cut off and is reported as disconnected:false with disconnect_error. A client with no credential record is 409 no_client_credential. disconnect=true on a custom client is ignored. Writes one forget record naming the revoked token. The FR-008a guard is not involved: revoking only removes a binding.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}},{"description":"Also remove the entry from the client's config (supported clients)","in":"query","name":"disconnect","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Revoked token name and what happened to the config entry"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"no_client_credential"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Forget a client (revoke its credential)","tags":["clients"]},"get":{"description":"Returns one client row with its sessions (newest 20, each with its latest effective profile). This is the only read that may open the client's config file: it runs the full rotation reconciler first, classifies the credential the config holds and records the observation. No scope filter is honoured on this route.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Client row"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"client not found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get one client","tags":["clients"]}},"/api/v1/clients/{client}/api-key":{"delete":{"description":"Revokes the client's mcp_cli_ credential alone: its browser logins and its binding stay. 404 no_client_credential when the client has no active API key. Writes a revoke record. Administrator only.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The key was revoked"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid client id"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"no_client_credential"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Revoke a client's API key only","tags":["clients"]}},"/api/v1/clients/{client}/binding":{"put":{"description":"Changes the profile binding (and optionally the locked/switchable mode) of a\nclient that holds an active client credential. One service operation shared by\nevery surface: it updates the credential in the token store, clears the stored\nset_profile selection of every live session of that credential, sends\nnotifications/tools/list_changed to each, emits client.binding_changed and writes\none profile_change activity record. It never touches the client's config file.\nA client without an active client credential (none, admin key, revoked or expired)\nis refused with 409 no_client_credential and nothing is minted or written. A\nreassignment that would leave the binding bypassable while require_mcp_auth is off\nis refused with 409 binding_bypassable_without_auth (FR-008a). Personal edition only.","parameters":[{"description":"Client id (lower-case letters, digits, '-' or '_', at most 56 characters)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.PutClientBindingRequest"}}},"description":"profile (required; empty = All servers) and optional mode (locked|switchable)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The client row after the change, with its warnings"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"no_client_credential, connect_in_progress (a connect of this client is mid-write), or binding_bypassable_without_auth with bindings and fixes"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Reassign a client's profile and/or mode","tags":["clients"]}},"/api/v1/clients/{client}/logins/{grant_id}":{"delete":{"description":"Revokes the login (reason admin): its access token stops authenticating on the next request, live sessions are told to re-list, and a revoke record names the administrator. Works while browser login is on and while it is off after use. An already revoked login answers changed:false; an unknown login (or one of another client) is 404. Administrator only.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}},{"description":"Login id","in":"path","name":"grant_id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Whether the login changed"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"login not found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Revoke one browser login of a client","tags":["clients"]}},"/api/v1/clients/{client}/rotate":{"post":{"description":"Replaces a client's secret without ever invalidating the old one mid-flight (FR-021a). A SUPPORTED client is rewritten through connect: staged rotation, binding kept, finalized when the config write succeeds, rolled back (the old secret keeps working) when it fails; a preview's precondition_token binds the call, a mismatch is the connect 409 precondition_failed. A CUSTOM client gets a new secret returned ONCE with a snippet; both secrets authenticate until POST /clients/{client}/rotate/finalize or 24 hours. A client with no active credential is 409 no_client_credential. The FR-008a guard is not involved: a rotation never changes a binding's reach. Writes one rotate record when it finalizes.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.RotateClientRequest"}}},"description":"Optional precondition_token of a connect preview"},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The client row and the rotation state"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required (or macOS App-Data block)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectConflictResponse"}}},"description":"no_client_credential, precondition_failed, connect_in_progress (another connect of this client is mid-write), or credential_superseded (the written credential was replaced or revoked before it could be finalized; reconnect)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Rotate a client's credential","tags":["clients"]}},"/api/v1/clients/{client}/rotate/finalize":{"post":{"description":"Promotes a client's pending secret: the old secret stops authenticating. Idempotent: with no rotation in progress it is a no-op success. A client with no client credential is 409 no_client_credential. Writes one rotate record when it promotes.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The client row; rotation.state is finalized"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"no_client_credential, or connect_in_progress (a connect of this client is mid-write)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Finalize a staged rotation","tags":["clients"]}},"/api/v1/code/scripts":{"get":{"description":"List the stored scripts available to the code_execution tool. Scripts are ` + "`" + `\u003cname\u003e.js` + "`" + ` / ` + "`" + `\u003cname\u003e.ts` + "`" + ` files in the ` + "`" + `scripts/` + "`" + ` directory next to the active configuration file. Entries are advisory: ` + "`" + `ok` + "`" + ` scripts are invocable, ` + "`" + `ambiguous` + "`" + ` names have both extensions, and ` + "`" + `invalid` + "`" + ` ones report why (empty, oversized, unreadable, non-regular). Read-only — there is no write surface for stored scripts. Administrator-only (Spec 105 FR-012): an agent token, whatever its server scope, is refused with 403 — the listing is the enumeration the missing-script error withholds from a scoped caller.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Stored scripts and the directory they were read from"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot list stored scripts"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List stored code-execution scripts","tags":["code"]}},"/api/v1/config":{"get":{"description":"Retrieves the current MCPProxy configuration including all server definitions, global settings, and runtime parameters","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetConfigResponse"}}},"description":"Configuration retrieved successfully"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read the configuration document"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get current configuration","tags":["config"]},"patch":{"description":"Deep-merges only the fields present in the request body onto the live in-memory configuration and routes the result through the existing apply pipeline (validation, change detection, disk persistence, hot-reload). Fields the client omits — including masked secrets such as ` + "`" + `api_key` + "`" + ` and secret request headers — are preserved verbatim. Nested objects are merged recursively; arrays and scalars replace wholesale.","requestBody":{"content":{"application/json":{"schema":{"type":"object"}}},"description":"Partial configuration with only the fields to change","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ConfigApplyResult"}}},"description":"Configuration patch applied (inspect validation_errors for rejected values)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload or empty patch"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate configuration)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"binding_bypassable_without_auth: the patch would let a client bound to a named profile escape it while require_mcp_auth is off (FR-008a); nothing was written"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"telemetry.enabled is locked while an environment variable (DO_NOT_TRACK, CI, MCPPROXY_TELEMETRY=false) disables telemetry; nothing was written (FR-044a)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to read or apply configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Partially update configuration","tags":["config"]}},"/api/v1/config/apply":{"post":{"description":"Applies a new MCPProxy configuration. Validates and persists the configuration to disk. Some changes apply immediately, while others may require a restart. Returns detailed information about applied changes and restart requirements.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.Config"}}},"description":"Configuration to apply","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ConfigApplyResult"}}},"description":"Configuration applied successfully with change details"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate configuration)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"binding_bypassable_without_auth: the write would let a client bound to a named profile escape it while require_mcp_auth is off (FR-008a); nothing was written"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"telemetry.enabled is locked while an environment variable (DO_NOT_TRACK, CI, MCPPROXY_TELEMETRY=false) disables telemetry; nothing was written (FR-044a)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to apply configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Apply configuration","tags":["config"]}},"/api/v1/config/docker-isolation":{"patch":{"description":"Convenience endpoint to flip ` + "`" + `docker_isolation.enabled` + "`" + ` without resending the full config. Persists to disk via the existing config writer — the file watcher then hot-reloads the change. Returns the new state and whether a restart is required for existing connections to pick it up.","requestBody":{"content":{"application/json":{"schema":{"properties":{"enabled":{"type":"boolean"}},"type":"object"}}},"description":"New isolation state","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ConfigApplyResult"}}},"description":"Isolation toggle applied"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate configuration)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"binding_bypassable_without_auth (FR-008a); nothing was written"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to apply configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Toggle global Docker isolation","tags":["config"]}},"/api/v1/config/validate":{"post":{"description":"Validates a provided MCPProxy configuration without applying it. Checks for syntax errors, invalid server definitions, conflicting settings, and other configuration issues.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.Config"}}},"description":"Configuration to validate","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ValidateConfigResponse"}}},"description":"Configuration validation result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Validation failed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Validate configuration","tags":["config"]}},"/api/v1/connect":{"get":{"description":"Returns the connection status for all known MCP client applications.\nEach entry indicates whether the client config file exists and whether\nMCPProxy is currently registered in it. This stat-only listing never reads\na client config (Spec 075), so a client whose config exists reports\ncredential_state \"unknown\"; GET /connect/{client} resolves it.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"List of ClientStatus objects"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List client connection status","tags":["connect"]}},"/api/v1/connect/{client}":{"delete":{"description":"Remove the MCPProxy entry from the specified client's configuration file.\nCreates a backup of the existing config before modifying.\nAlso revokes the client's credential (it stops authenticating at once); the result names it in credential_revoked, or reports credential_revoke_error when the revoke failed after the entry was removed. Undoing a disconnect does not restore the credential: a later connect mints a new one.","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectRequest"}}},"description":"Optional parameters (server_name)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectResult"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Permission denied (macOS App-Data block)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client or entry not found"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Disconnect MCPProxy from a client","tags":["connect"]},"get":{"description":"Resolves one client's status by reading its config file on demand.\nThis is the only Connect endpoint that opens a client config file, so\non macOS it is the sole place an App-Data privacy prompt may legitimately\nappear (scoped to this user action). Resolves access_state to\naccessible|absent|denied|malformed and populates remediation when denied.\nFor a connected client it also resolves credential_state (Spec 108 FR-025):\nclient (an active per-client credential), admin_key (the instance admin API\nkey), none, revoked (a rotated-away or revoked credential) or expired. The\ncredential value is classified and never echoed.","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ClientStatus"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get a single client's connection status (on-demand)","tags":["connect"]},"post":{"description":"Register MCPProxy as an MCP server in the specified client's configuration file.\nCreates a backup of the existing config before modifying.\nOptionally accepts precondition_token from a preview (Spec 091): when supplied,\nthe core rechecks the raw pre-write state and the entry it would write, and\nrefuses a drifted write with 409 before taking any backup. The 409 body's\naction discriminates the two conflict kinds: \"precondition_failed\" (stale\npreview — re-preview, do not retry) vs \"already_exists\" (entry present — pass\nforce=true). force=true never rescues a stale token.\n\nSpec 108 FR-024: the entry carries a per-client mcp_cli_ credential bound to the\nrequested profile (default: All servers, switchable; a reconnect keeps the client's\nexisting binding unless a profile is given), never the instance admin API key.\nReconnecting over an active credential is a staged rotation: the old secret keeps\nworking until the config write succeeds. keyless=true writes no credential and is\nonly possible while require_mcp_auth is off (400 otherwise, and with a profile).\nA write that would let the client escape its profile by omitting its credential\nwhile require_mcp_auth is off is refused with 409 binding_bypassable_without_auth\n(nothing minted or written); a token named client-\u003cid\u003e held by a regular agent\ntoken is refused with 409 conflicting_token.","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectRequest"}}},"description":"Optional connection parameters (server_name, force, precondition_token, profile, mode, keyless)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectResult (credential is the masked mcp_cli_ value, with token_name, profile, mode, keyless and rotation)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Bad request; field names the offending input (profile, mode, keyless)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Permission denied (macOS App-Data block)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectConflictResponse"}}},"description":"Conflict: action=already_exists (use force=true) or action=precondition_failed (preview is stale; re-preview); or binding_bypassable_without_auth (BindingGuardResponse); or conflicting_token (ClientCredentialConflictResponse); or connect_in_progress (another connect of this client is mid-write) or credential_superseded (the written credential was replaced or revoked before it could be finalized; reconnect)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable (or no credential store wired while require_mcp_auth is on)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Connect MCPProxy to a client","tags":["connect"]}},"/api/v1/connect/{client}/preview":{"get":{"description":"Returns the exact entry a subsequent connect would add to the client's\nconfig — target path, server key, entry name, and entry contents — WITHOUT\nmodifying the file or creating a backup (Spec 078 US1). The per-client credential\nis masked in the payload (credential, always starting mcp_cli_; contains_api_key is\nalways false since connect never writes the admin API key); profile, mode and\nkeyless echo the requested intent.\nentry_exists distinguishes a create from an overwrite of a same-named entry.\nReads the config on demand to classify create-vs-overwrite, so on macOS this\nmay raise an App-Data privacy prompt; a denial returns 403 + remediation.\nSpec 091 adds three fields: existing_entry_summary (present only when\nentry_exists — a sanitized, non-secret projection of the entry being replaced:\nits name, type, endpoint with query/userinfo stripped, command, and header and\nenv NAMES, never values); precondition_token (always present — an opaque keyed\ndigest of the raw pre-write state and the pending entry, echoed back on POST\nconnect to detect drift); and connect_refusal (present when the write would\nrefuse regardless of intent, e.g. a non-create-capable client with no config —\ntreat its presence as \"Connect unavailable\").","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}},{"description":"Entry name to preview (defaults to mcpproxy); mirror the value passed to POST connect","in":"query","name":"server_name","schema":{"type":"string"}},{"description":"Profile the client credential would bind to (empty = All servers); mirror POST connect","in":"query","name":"profile","schema":{"type":"string"}},{"description":"locked|switchable; mirror POST connect","in":"query","name":"mode","schema":{"enum":["locked","switchable"],"type":"string"}},{"description":"Preview a credential-less entry (only while require_mcp_auth is off)","in":"query","name":"keyless","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectPreview"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid intent (field names the input; keyless with auth on or with a profile)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required or access denied by macOS App Data"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Preview the change a connect would make (no write)","tags":["connect"]}},"/api/v1/connect/{client}/undo":{"post":{"description":"Reverts the connect that produced the named backup (Spec 078 US3):\nrestores the client config byte-for-byte from that backup, or — when\nbackup_name is empty because the connect created the file — deletes the\ncreated file. backup_name is the bare filename of the backup the connect\nreturned (never a path); undo resolves the full path server-side inside\nthe client's own config directory, so a client value cannot escape it.\nRefuses with 409 when the config changed since the connect (undo never\nclobbers later edits; use DELETE /connect/{client} for a surgical entry\nremoval instead). Takes its own safety backup first; its path is returned\nas backup_path in the result. Undo is \"as if the connect never happened\": a\nclient credential the connect minted or rotated is revoked unless the restored\nconfig still holds it, and the result names it in credential_revoked.","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.UndoConnectRequest"}}},"description":"Undo parameters (server_name, backup_name = the bare filename of the backup the preceding connect returned)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectResult (action restored|deleted)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (e.g. backup_name is a path, or not a backup of this client's config)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Permission denied (macOS App-Data block)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client or backup no longer exists"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Config changed since connect; undo refused"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Undo a connect, restoring the pre-connect config","tags":["connect"]}},"/api/v1/diagnostics":{"get":{"description":"Get comprehensive health diagnostics including upstream errors, OAuth requirements, missing secrets, and Docker status","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.Diagnostics"}}},"description":"Health diagnostics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get health diagnostics","tags":["diagnostics"]}},"/api/v1/docker/status":{"get":{"description":"Retrieve current Docker availability and recovery status","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Docker status information"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get Docker status","tags":["docker"]}},"/api/v1/doctor":{"get":{"description":"Get comprehensive health diagnostics including upstream errors, OAuth requirements, missing secrets, and Docker status","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.Diagnostics"}}},"description":"Health diagnostics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get health diagnostics","tags":["diagnostics"]}},"/api/v1/feedback":{"post":{"description":"Submit a bug report, feature request, or general feedback","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/telemetry.FeedbackRequest"}}},"description":"Feedback request","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/telemetry.FeedbackResponse"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"additionalProperties":{"type":"string"},"type":"object"}}},"description":"Bad Request"},"429":{"content":{"application/json":{"schema":{"additionalProperties":{"type":"string"},"type":"object"}}},"description":"Too Many Requests"},"500":{"content":{"application/json":{"schema":{"additionalProperties":{"type":"string"},"type":"object"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyAuth":[]}],"summary":"Submit feedback","tags":["feedback"]}},"/api/v1/index/search":{"get":{"description":"Search across all upstream MCP server tools using BM25 keyword search","parameters":[{"description":"Search query","in":"query","name":"q","required":true,"schema":{"type":"string"}},{"description":"Maximum number of results","in":"query","name":"limit","schema":{"default":10,"maximum":100,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SearchToolsResponse"}}},"description":"Search results"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing query parameter)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Search for tools","tags":["tools"]}},"/api/v1/info":{"get":{"description":"Get essential server metadata including version, web UI URL, endpoint addresses, and update availability\nweb_ui_url carries the ?apikey= credential ONLY for an authenticated admin; a scoped agent token receives the bare URL\nThis endpoint is designed for tray-core communication and version checking\nUse refresh=true query parameter to force an immediate update check against GitHub\nThe launched_by field reports durable launch provenance (\"tray\", \"installer\", or \"\" for user-launched/unknown)","parameters":[{"description":"Force immediate update check against GitHub","in":"query","name":"refresh","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Server information with optional update info"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server information","tags":["status"]}},"/api/v1/oauth/authorizations":{"get":{"description":"Pending browser-login requests, newest first: id, a sanitised client label and the times. Used by the tray and Home. 404 feature_disabled while browser login is off. Administrator only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Pending requests"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"feature_disabled"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List pending sign-in requests","tags":["clients"]}},"/api/v1/oauth/authorizations/{id}":{"get":{"description":"Everything the consent view needs: the reported (unverified) name, the redirect URI, the resource, how the address fixes the client, the profiles, whether a profile must be chosen, the previous login of the same registration and, for a fixed client that has a binding, the guard verdict. One uniform 404 for an unknown, expired, decided or cancelled id. Administrator only.","parameters":[{"description":"Request id","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"The request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"request_not_found or feature_disabled"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Read one sign-in request","tags":["clients"]}},"/api/v1/oauth/authorizations/{id}/approve":{"post":{"description":"Records the decision and issues the code; the login itself is stored when the client exchanges the code. 409 already_decided, 409 binding_changed (the binding differs from binding_revision), 409 binding_bypassable_without_auth (with the guard's fixes), 422 profile_required, client_fixed, identity_exists, reserved_identity, 404 profile_not_found. Writes an approve record naming the administrator. Administrator only.","parameters":[{"description":"Request id","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.OAuthApprovalBody"}}},"description":"client, profile, mode, binding_revision, replace_grant","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Where the page navigates"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"request_not_found, profile_not_found or feature_disabled"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"already_decided, binding_changed or binding_bypassable_without_auth"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"profile_required, client_fixed, identity_exists, reserved_identity"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Approve a sign-in request","tags":["clients"]}},"/api/v1/oauth/authorizations/{id}/deny":{"post":{"description":"The redirect carries error=access_denied. 409 already_decided. Writes a deny record naming the administrator. Administrator only.","parameters":[{"description":"Request id","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Where the page navigates"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"request_not_found or feature_disabled"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"already_decided"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Deny a sign-in request","tags":["clients"]}},"/api/v1/oauth/authorizations/{id}/preview":{"post":{"description":"Read-only: for a proposed client (existing or new), profile and mode, returns whether the choice is complete, the access sentence and the binding guard's verdict with its fixes. Writes nothing. The same 422 codes as approve for an invalid choice. Administrator only.","parameters":[{"description":"Request id","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.OAuthApprovalBody"}}},"description":"client, profile, mode","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"The preview"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"request_not_found, profile_not_found or feature_disabled"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"client_fixed, identity_exists, reserved_identity"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Preview a sign-in decision","tags":["clients"]}},"/api/v1/onboarding/mark":{"post":{"description":"Updates wizard engagement and per-step status. Once engaged is\ntrue, the wizard does not auto-show again, even if state regresses.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.OnboardingMarkRequest"}}},"description":"Mark request","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Updated OnboardingStateResponse"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read onboarding state"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Mark onboarding wizard state (Spec 046)","tags":["onboarding"]}},"/api/v1/onboarding/state":{"get":{"description":"Returns the wizard engagement record alongside live predicates\n(whether any client is connected, whether any server is configured),\nplus a derived ShouldShowWizard flag the frontend can rely on.","responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OnboardingStateResponse"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read onboarding state"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get onboarding wizard state and predicates (Spec 046)","tags":["onboarding"]}},"/api/v1/preflight":{"post":{"description":"Deterministic, side-effect-free availability check for a caller-supplied list of tool IDs (Spec 098). Performs zero upstream calls and mutates no runtime state. HTTP status reports whether the CHECK executed: a fully blocked set is still 200, with the availability verdict in the body. Every executed preflight writes an activity record before the response is returned.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.PreflightRequest"}}},"description":"Tool IDs (1-100 before dedup), optional profile, annotation policy filters and wait budget","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Preflight verdict and per-tool results"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Validation error (malformed, oversized, doubled or unknown-field body; empty or oversized tool list; conflicting duplicate pins; unknown profile; wait_ms out of range)"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Missing or invalid credentials"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Runtime unavailable, evaluator infrastructure read failure, or the activity record could not be persisted"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Preflight required tools","tags":["tools"]}},"/api/v1/profiles":{"get":{"description":"Lists every profile as a ProfileView: the config fields as stored, the derived effective values, visible tool counts by tier, 24 h calls and blocked calls, and (administrators only) used_by and the anonymous_profile. A caller that is not an administrator sees only the profiles its entitlement reaches, with servers, rules and switchable_to narrowed to what it may see; an unreachable profile is omitted, never shown empty.","responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Profile list"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Configuration unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List configured profiles","tags":["profiles"]},"post":{"description":"Adds a profile. The body is a ProfileConfig. A name that already exists is 409 profile_exists; ` + "`" + `active` + "`" + ` and ` + "`" + `try` + "`" + ` are reserved by the REST API; a fatal validation rule is 400 with the offending field and the unchanged FR-007 text. A write that would let a client bound to a named profile escape it while require_mcp_auth is off is refused 409 binding_bypassable_without_auth (FR-008a) and nothing is written. Writes one profile_change record.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.ProfileConfig"}}},"description":"The profile","required":true},"responses":{"201":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Created, with the validator's warnings"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ProfileConflictResponse"}}},"description":"profile_exists, or binding_bypassable_without_auth (BindingGuardResponse)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Create a profile","tags":["profiles"]}},"/api/v1/profiles/active":{"get":{"description":"Deprecated (Spec 108 FR-039; sends a Deprecation header, successor GET /api/v1/profiles). Get the server-level default active profile used by UI surfaces (Web UI / tray). Empty string means \"all servers\". Note: within a live MCP session, the set_profile tool selection takes precedence over this default.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Active profile"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the default active profile","tags":["profiles"]},"put":{"description":"Deprecated (Spec 108 FR-039; sends a Deprecation header, successor GET /api/v1/profiles). Set the server-level default active profile for UI surfaces. The slug must match a configured profile; pass an empty string to clear. This does not affect live MCP sessions, which use the set_profile tool.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.SetActiveProfileRequest"}}},"description":"Profile slug to activate (empty clears)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Active profile updated"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request body"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot change the active profile)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown profile"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Set the default active profile","tags":["profiles"]}},"/api/v1/profiles/try":{"post":{"description":"Evaluates a DRAFT profile against a query exactly as retrieve_tools would (policy is applied before the limit) and returns the hits plus what the draft hides (hidden_by_profile and up to 100 {server, tool, reason}). The draft is validated as if it replaced the same-named profile, or was appended under a placeholder name when it has none. Nothing is persisted, no record is written, no event is published and the FR-008a guard does not run. Administrators only.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.TryProfileRequest"}}},"description":"draft profile, query and optional limit (default 10, max 50)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Search result under the draft"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid draft; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Try a draft profile","tags":["profiles"]}},"/api/v1/profiles/{name}":{"delete":{"description":"Deletes a profile. 409 profile_in_use (with used_by) while clients or tokens point at it, unless reassign_to names another existing profile (every pin moves there) or force is set (pins are left dangling, which the resolver treats as deny-all). 409 profile_is_anonymous_profile whenever it is the anonymous_profile and reassign_to is absent, even with force. Both paths remove the name from every switchable_to. Guarded by FR-008a. Writes one ` + "`" + `delete` + "`" + ` record.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}},{"description":"Another existing profile that takes over the pins","in":"query","name":"reassign_to","schema":{"type":"string"}},{"description":"Delete although in use, leaving pins dangling","in":"query","name":"force","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Deleted"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"reassign_to does not name another existing profile"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ProfileConflictResponse"}}},"description":"profile_in_use, profile_is_anonymous_profile, or binding_bypassable_without_auth (BindingGuardResponse)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Delete a profile","tags":["profiles"]},"get":{"description":"Returns the ProfileView of the named profile. A caller that is not an administrator gets the same 404 for an unreachable profile as for an unknown one.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The profile"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get one profile","tags":["profiles"]},"put":{"description":"Replaces the named profile with the body (a ProfileConfig whose name, when sent non-empty, must equal the path; 409 name_mismatch otherwise - a rename has its own route; an omitted or empty name takes the path's). A write whose only change is tools.classify is recorded as ` + "`" + `classify` + "`" + `. Guarded by FR-008a like a create.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.ProfileConfig"}}},"description":"The profile","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Updated, with the validator's warnings"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ProfileConflictResponse"}}},"description":"name_mismatch, or binding_bypassable_without_auth (BindingGuardResponse)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Replace a profile","tags":["profiles"]}},"/api/v1/profiles/{name}/effective-tools":{"get":{"description":"One row per catalog tool with the verdict of the access chain (the same rendering GET /tools?profile= uses): server, tool, intrinsic_tier, profile_tier, access{visible, callable, reason} and classification_stale. With client=\u003cid\u003e the client's credential is evaluated UNDER this profile (\"what would Cursor get here\"). An administrator gets every row plus counts.callable, counts.by_reason and stale_classifications; every other caller gets only visible rows and counts{visible, hidden}, and client= and reason= are refused 403. An unreachable profile answers exactly like an unknown one.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}},{"description":"Evaluate this client's credential under the profile (administrators only)","in":"query","name":"client","schema":{"type":"string"}},{"description":"Keep only this server's rows","in":"query","name":"server","schema":{"type":"string"}},{"description":"Keep only rows with this access reason (administrators only)","in":"query","name":"reason","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Effective tools"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"operation requires admin access"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found / client not found"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Effective tools of a profile","tags":["profiles"]}},"/api/v1/profiles/{name}/rename":{"post":{"description":"Renames a profile and moves every reference to it - token pins, client bindings, other profiles' switchable_to and the anonymous_profile - in one write (D19). Tokens move first, so a failure part-way never widens a scope. Guarded by FR-008a. Writes one ` + "`" + `rename` + "`" + ` record.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.RenameProfileRequest"}}},"description":"new_name","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Renamed; moved lists the clients and tokens that followed"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ProfileConflictResponse"}}},"description":"profile_exists, or binding_bypassable_without_auth (BindingGuardResponse)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Rename a profile","tags":["profiles"]}},"/api/v1/registries":{"get":{"description":"Retrieves list of all MCP server registries that can be browsed for discovering and installing new upstream servers. Includes registry metadata, server counts, and API endpoints.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetRegistriesResponse"}}},"description":"Registries retrieved successfully"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to list registries"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List available MCP server registries","tags":["registries"]},"post":{"description":"Adds a generic modelcontextprotocol/registry v0.1 https endpoint as a custom registry (MCP-866). The source is always tagged custom/unverified, so every server discovered through it lands quarantined and can never skip quarantine.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.AddRegistrySourceRequest"}}},"description":"Registry source (https url + optional protocol/id/name)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Registry source added"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"invalid_registry_url"},"403":{"content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/contracts.ErrorResponse"},{"$ref":"#/components/schemas/contracts.ErrorResponse"}]}}},"description":"Forbidden (agent tokens cannot mutate registries)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_shadows_builtin | duplicate_registry"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add a user-supplied registry source","tags":["registries"]}},"/api/v1/registries/{id}":{"delete":{"description":"Removes a custom/unverified registry previously added via add-source (MCP-1057). Built-in registries are refused with registry_shadows_builtin; an unknown id yields registry_not_found. The change is persisted copy-on-write.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Registry source removed"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID is required"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registries_locked"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_not_found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_shadows_builtin"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Remove a user-added custom registry source","tags":["registries"]},"put":{"description":"Updates a custom registry previously added via add-source (MCP-1072): name, url, servers-url. Empty fields are left unchanged. Built-in registries are refused with registry_shadows_builtin; an unknown id yields registry_not_found; a non-https url yields invalid_registry_url. The change is persisted copy-on-write.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.EditRegistrySourceRequest"}}},"description":"Fields to update (name/url/servers_url; empty = unchanged)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Registry source updated"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID is required | invalid_registry_url"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registries_locked"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_not_found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_shadows_builtin"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Edit a user-added custom registry source","tags":["registries"]}},"/api/v1/registries/{id}/refresh":{"post":{"description":"Invalidates the cached server lists for a registry so the next search re-fetches fresh data from the source (spec 070 FR-007). Returns how many cache entries were dropped.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.RefreshRegistryResponse"}}},"description":"Registry cache refreshed"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID is required"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to refresh registry cache"}},"summary":"Refresh a registry's cached server list","tags":["registries"]}},"/api/v1/registries/{id}/servers":{"get":{"description":"Searches for MCP servers within a specific registry by keyword or tag. Returns server metadata including installation commands, source code URLs, and npm package information for easy discovery and installation.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Search query keyword","in":"query","name":"q","schema":{"type":"string"}},{"description":"Filter by tag","in":"query","name":"tag","schema":{"type":"string"}},{"description":"Maximum number of results (default 10)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SearchRegistryServersResponse"}}},"description":"Servers retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to search servers"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Search MCP servers in a registry","tags":["registries"]}},"/api/v1/registries/{id}/servers/{serverId}/add":{"post":{"description":"Resolves a registry server reference server-side, re-derives a validated config, and persists it quarantined (spec 070 keystone). The client never sends a config blob — command/args/url and the quarantine flag are derived from the registry entry, not the request.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Server ID within the registry","in":"path","name":"serverId","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.AddFromRegistryRequest"}}},"description":"Optional overrides (name, env, enabled)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server added (quarantined)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"no_install_info | missing_required_input | duplicate_name"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot add servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_not_found | server_not_found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add an upstream server from a registry reference","tags":["registries"]}},"/api/v1/review":{"get":{"description":"Returns one row per quarantined server, trusted server with pending or changed tools, or (Spec 125) server with held skills (kind skill_review; skills_pending / skills_changed counts). Scoped callers see only servers they may enumerate (for a profile-pinned token: servers within its pin), with count recomputed; held-skill counts and skill_review rows are administrator-only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Review queue"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to load review queue"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the server review queue","tags":["review"]}},"/api/v1/routing":{"get":{"description":"Get the current routing mode and available MCP endpoints.\nrouting_mode is what /mcp is actually serving; pending_routing_mode carries a\nrestart-pending value persisted on disk (empty when there is none).\ntool_response_mode and direct_tool_response_mode report the two serialization axes, resolved.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Routing mode information"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get routing mode information","tags":["status"]}},"/api/v1/secrets":{"post":{"description":"Stores a secret value in the operating system's secure keyring. The secret can then be referenced in configuration using ${keyring:secret-name} syntax. Automatically notifies runtime to restart affected servers.","requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{},"type":"object"}}},"description":"Secret stored successfully with reference syntax"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload, missing name/value, or unsupported type"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Secret resolver not available or failed to store secret"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Store a secret in OS keyring","tags":["secrets"]}},"/api/v1/secrets/{name}":{"delete":{"description":"Deletes a secret from the operating system's secure keyring. Automatically notifies runtime to restart affected servers. Only keyring type is supported for security.","parameters":[{"description":"Name of the secret to delete","in":"path","name":"name","required":true,"schema":{"type":"string"}},{"description":"Secret type (only 'keyring' supported, defaults to 'keyring')","in":"query","name":"type","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{},"type":"object"}}},"description":"Secret deleted successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Missing secret name or unsupported type"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Secret resolver not available or failed to delete secret"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Delete a secret from OS keyring","tags":["secrets"]}},"/api/v1/security/bundle":{"get":{"description":"Reports the offline TPA signature corpus this install is serving: full SHA-256 digest, sequence, authority, trust epoch, signature verification, staleness (with the stale flag and its threshold), degraded coverage with its reason, rollback pin, and the last refused candidate. Also carries the refresh status (last checked and activated times, last cycle outcome, next check, consecutive failures; the fetch host only, never the URL) and the post-activation re-protection sweep status. Admin only.","responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Bundle status"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the TPA signature bundle status","tags":["security"]}},"/api/v1/security/bundle/history":{"get":{"description":"Append-only list of bundle activations, oldest first, each with its full SHA-256 digest. It is the trustworthy source of the digest to name in a rollback. Admin only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Activation history (data is an array of TPABundleActivation)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"History could not be read"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the TPA signature bundle activation history","tags":["security"]}},"/api/v1/security/bundle/refresh":{"post":{"description":"Runs one refresh cycle immediately: the local file leg (always network-free) followed by the optional fetch leg when security.tpa_fetch_enabled is on and a trusted signer and URL are configured. A cycle already in flight is joined, so one download and at most one activation happen per distinct candidate. The response is the resulting bundle status; the cycle outcome is in its refresh block (activated, unchanged, not_modified, rejected, fetch_unavailable, channel_invalid, superseded, disabled). Network failures are reported as fetch_unavailable and never as a rejection; last-known-good keeps serving. Unlike reload, refresh may make an outbound request. Admin API key only.","responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Updated bundle status; the refresh block holds the cycle outcome"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Refresh the TPA signature bundle now","tags":["security"]}},"/api/v1/security/bundle/reload":{"post":{"description":"Re-runs the single-flight bundle pipeline against the configured source and current policy. A refused candidate leaves last-known-good serving and is reported as last_rejection in the returned status. Admin API key only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Updated bundle status"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Reload the TPA signature bundle","tags":["security"]}},"/api/v1/security/bundle/rollback":{"post":{"description":"The one operator override of the downgrade watermark. Exactly one of embedded or path must be given, and digest must be the FULL 64-character lowercase hex SHA-256 of the target (the 12-character fingerprint is refused). On success the target serves and is pinned. A refusal (for example rollback_target_mismatch) returns 409 with the rejection reason and last-known-good keeps serving. Admin API key only; agent tokens are refused.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.bundleRollbackRequest"}}},"description":"Rollback target","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Updated bundle status"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Usage error: both or neither of embedded/path, or digest is not 64 lowercase hex"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BundleRollbackRefusedResponse"}}},"description":"Rollback refused; the response carries the rejection reason"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal error"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Roll the TPA signature bundle back to a named artifact","tags":["security"]}},"/api/v1/security/bundle/unpin":{"post":{"description":"Clears the rollback pin and re-validates the serving bundle under the normal downgrade watermark, so a rolled-back target below the watermark no longer serves. A quiet no-op when nothing is pinned. Admin API key only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Updated bundle status"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"The unpin could not be recorded"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Clear the TPA signature bundle rollback pin","tags":["security"]}},"/api/v1/servers":{"get":{"description":"Get a list of all configured upstream MCP servers with their connection status and statistics","parameters":[{"description":"Restrict to the profile's effective servers; tool_count becomes the number of that server's tools visible under the profile (Spec 108 FR-032)","in":"query","name":"profile","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServersResponse"}}},"description":"Server list with statistics"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unsupported scope filter (client/token), or '-' on a server filter"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown or unreachable profile"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List all upstream MCP servers","tags":["servers"]},"post":{"description":"Add a new MCP upstream server to the configuration. New servers are quarantined by default for security. Isolation: ` + "`" + `isolation.enabled` + "`" + ` is READ-ONLY (it reports the effective state on reads) and is rejected with 400; set the per-server override via ` + "`" + `isolation.enabled_override` + "`" + ` (true | false | null to clear, omit to leave unchanged). An unrecognized ` + "`" + `isolation.mode_override` + "`" + ` is rejected with 400.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.AddServerRequest"}}},"description":"Server configuration","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server added successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid configuration"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Conflict - server with this name already exists"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add a new upstream server","tags":["servers"]}},"/api/v1/servers/disable_all":{"post":{"description":"Disable all configured upstream MCP servers with partial failure handling","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/management.BulkOperationResult"}}},"description":"Bulk disable results with success/failure counts"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Disable all servers","tags":["servers"]}},"/api/v1/servers/enable_all":{"post":{"description":"Enable all configured upstream MCP servers with partial failure handling","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/management.BulkOperationResult"}}},"description":"Bulk enable results with success/failure counts"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable all servers","tags":["servers"]}},"/api/v1/servers/import":{"post":{"description":"Import MCP server configurations from a Claude Desktop, Claude Code, Cursor IDE, Codex CLI, or Gemini CLI configuration file","parameters":[{"description":"If true, return preview without importing","in":"query","name":"preview","schema":{"type":"boolean"}},{"description":"Force format (claude-desktop, claude-code, cursor, codex, gemini)","in":"query","name":"format","schema":{"type":"string"}},{"description":"Comma-separated list of server names to import","in":"query","name":"server_names","schema":{"type":"string"}}],"requestBody":{"content":{"multipart/form-data":{"schema":{"type":"file"}}},"description":"Configuration file to import","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportResponse"}}},"description":"Import result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid file or format"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Import servers from uploaded configuration file","tags":["servers"]}},"/api/v1/servers/import/json":{"post":{"description":"Import MCP server configurations from raw JSON or TOML content (useful for pasting configurations)","parameters":[{"description":"If true, return preview without importing","in":"query","name":"preview","schema":{"type":"boolean"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportRequest"}}},"description":"Import request with content","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportResponse"}}},"description":"Import result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid content or format"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Import servers from JSON/TOML content","tags":["servers"]}},"/api/v1/servers/import/path":{"post":{"description":"Import MCP server configurations by reading a file from the server's filesystem. A preview (preview=true) of a file with no MCP servers (empty, {}, or no/empty server map) answers 200 with an empty imported list; an apply of such a file and a malformed file still answer 400.","parameters":[{"description":"If true, return preview without importing","in":"query","name":"preview","schema":{"type":"boolean"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportFromPathRequest"}}},"description":"Import request with file path","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportResponse"}}},"description":"Import result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid path or format"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"File not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Import servers from a file path","tags":["servers"]}},"/api/v1/servers/import/paths":{"get":{"description":"Returns well-known configuration file paths for supported formats with existence check","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.CanonicalConfigPathsResponse"}}},"description":"Canonical config paths"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get canonical config file paths","tags":["servers"]}},"/api/v1/servers/reconnect":{"post":{"description":"Force reconnection to all upstream MCP servers","parameters":[{"description":"Reason for reconnection","in":"query","name":"reason","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"All servers reconnected successfully"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Reconnect all servers","tags":["servers"]}},"/api/v1/servers/restart_all":{"post":{"description":"Restart all configured upstream MCP servers sequentially with partial failure handling","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/management.BulkOperationResult"}}},"description":"Bulk restart results with success/failure counts"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Restart all servers","tags":["servers"]}},"/api/v1/servers/{id}":{"delete":{"description":"Remove an MCP upstream server from the configuration. This stops the server if running and removes it from config.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server removed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Remove an upstream server","tags":["servers"]},"patch":{"description":"Update specific fields of an existing upstream MCP server configuration. Isolation: ` + "`" + `isolation.enabled` + "`" + ` is READ-ONLY (it reports the effective state on reads) and is rejected with 400; set the per-server override via ` + "`" + `isolation.enabled_override` + "`" + ` (true | false | null to clear, omit to leave unchanged). An unrecognized ` + "`" + `isolation.mode_override` + "`" + ` is rejected with 400.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.AddServerRequest"}}},"description":"Fields to update (all optional)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server updated successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - no fields or invalid body"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Partially update an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/config-to-secret":{"post":{"description":"Atomically reads the real value from the server config, stores it in the OS keyring, and rewrites the config field to ` + "`" + `${keyring:\u003cname\u003e}` + "`" + `. Unblocks the UI's Convert-to-secret affordance for values the API redacts on the read path.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{},"type":"object"}}},"description":"Secret stored, config updated with reference"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad scope/key/secret_name, or value is already a reference / empty"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or key not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Secret resolver or config update failed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Convert a header / env value to a keyring secret","tags":["servers"]}},"/api/v1/servers/{id}/disable":{"post":{"description":"Disable a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server disabled successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Disable an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/discover-tools":{"post":{"description":"Manually trigger tool discovery and indexing for a specific upstream MCP server. This forces an immediate refresh of the server's tool cache.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Tool discovery triggered successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot discover tools)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to discover tools"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Discover tools for a specific server","tags":["servers"]}},"/api/v1/servers/{id}/enable":{"post":{"description":"Enable a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server enabled successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/login":{"post":{"description":"Initiate OAuth authentication flow for a specific upstream MCP server. Returns structured OAuth start response with correlation ID for tracking.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.OAuthStartResponse"}}},"description":"OAuth login initiated successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.OAuthFlowError"}}},"description":"OAuth error (client_id required, DCR failed, etc.)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Trigger OAuth login for server","tags":["servers"]}},"/api/v1/servers/{id}/logout":{"post":{"description":"Clear OAuth authentication token and disconnect a specific upstream MCP server. The server will need to re-authenticate before tools can be used again.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"OAuth logout completed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled or read-only mode)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Clear OAuth token and disconnect server","tags":["servers"]}},"/api/v1/servers/{id}/logs":{"get":{"description":"Retrieve log entries for a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Number of log lines to retrieve","in":"query","name":"tail","schema":{"default":100,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServerLogsResponse"}}},"description":"Server logs retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server logs","tags":["servers"]}},"/api/v1/servers/{id}/quarantine":{"post":{"description":"Place a specific upstream MCP server in quarantine to prevent tool execution","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server quarantined successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Quarantine a server","tags":["servers"]}},"/api/v1/servers/{id}/refresh":{"post":{"description":"Re-discover and re-index a specific upstream MCP server's tools without changing any security state. Alias of discover-tools, named for the upstream_servers 'refresh' operation; use it to make just-approved tools searchable immediately.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Tool refresh triggered successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot refresh)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to refresh tools"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Refresh a server's tools","tags":["servers"]}},"/api/v1/servers/{id}/restart":{"post":{"description":"Restart the connection to a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server restarted successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Restart an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/review":{"get":{"description":"Returns redacted server configuration, captured tool definitions, annotations, scan verdicts, and diffs. Scoped callers receive the same 404 for invisible and missing servers.","parameters":[{"description":"Server name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server review"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to load server review"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get review details for a server","tags":["review"]}},"/api/v1/servers/{id}/security/approve":{"post":{"description":"Saves the integrity baseline and optionally blocks selected tools atomically before unquarantining the server. With expected_hashes (tool name -\u003e the review's current_hash; {} for an empty review) the approval is bound to the reviewed definitions: when a tool the approval would make reachable (pending, or approved and enabled, minus block) changed or appeared since the review, or a block target no longer exists, the response is 409 review_out_of_date, nothing is written and the server stays quarantined. Tools listed after the approval wait for review.","parameters":[{"description":"Server name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.securityApproveRequest"}}},"description":"Force approval and tool names to keep disabled"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server approved"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request or unknown tool block target"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not configured"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.StaleReviewErrorResponse"}}},"description":"Dangerous scan verdict requires force, approval failed, the review is out of date (error_code review_out_of_date), or server_replaced (the server was removed or re-added since expected_incarnation)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Approve a server after security review","tags":["security"]}},"/api/v1/servers/{id}/skills":{"get":{"description":"Lists the skills of one upstream server. An administrator sees every record: status, hashes, files, scan result and the availability an agent would see. A scoped agent token with the server in its reach sees only the available skills, as the approved copy (id, uri, path, name, description, status \"approved\", approved_hash, files, total_size; contracts.SkillsAgentListResponse) and nothing about any other skill; a server outside its reach is 404. With enable_skills off the answer is {\"enabled\": false, \"skills\": []} and no upstream is contacted.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsListResponse"}}},"description":"Skills of the server"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found, or outside the caller's reach"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List the skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/skills/approve":{"post":{"description":"Administrator only. Approves the named skills for exactly the content the reviewer saw: expected_hashes maps each skill path to the current_hash from the listing, and expected_incarnation (the listing's incarnation) binds the approval to the server that was reviewed. When a hash differs, or a named skill has no expected hash, the response is 409 review_out_of_date with the changed and unreviewed names and nothing is approved; 409 server_replaced when the server was removed or replaced since the review; 422 skill_unusable for a skill that cannot be approved (a failed check or a dynamic file list). A skill already approved for its current content is left as it is and not counted. The blocked mark is never touched. A scoped agent token is refused with 403.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsApproveRequest"}}},"description":"Skills to approve, with the review binding","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsApproveResponse"}}},"description":"Number of skills newly approved (inside the data envelope)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or skill not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsStaleReviewResponse"}}},"description":"review_out_of_date, server_replaced or skills_disabled"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsUnusableResponse"}}},"description":"skill_unusable"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Approve skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/skills/block":{"post":{"description":"Administrator only. Sets the blocked mark on the named skills: a blocked skill is never offered to an agent, and no refresh, content change or automatic approval clears the mark. expected_incarnation is optional (0 binds to the current server). 409 server_replaced when the server was removed or replaced since it was reviewed. A scoped agent token is refused with 403.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsBlockRequest"}}},"description":"Skills to block","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsBlockResponse"}}},"description":"Number of skills whose mark changed (inside the data envelope)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or skill not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"server_replaced or skills_disabled"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Block skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/skills/content":{"get":{"description":"Returns a chunk of one stored text file of a skill. An administrator reads the current copy by default; a scoped agent token with the server in its reach reads the approved copy of an available skill only (copy is forced to approved), and gets one 404 for every other skill or file. A server outside its reach is 404. Offsets are byte positions; a chunk never splits a UTF-8 character, so it can be a few bytes shorter than limit. next_offset is absent at the end of the file. 404 for an unknown skill or file (or with enable_skills off), 415 for a binary file, 409 stored_copy_damaged when the stored bytes no longer match their digest.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Skill path, e.g. hf-cli","in":"query","name":"skill","required":true,"schema":{"type":"string"}},{"description":"File path inside the skill (default SKILL.md)","in":"query","name":"file","schema":{"type":"string"}},{"description":"current (default) or approved","in":"query","name":"copy","schema":{"type":"string"}},{"description":"Byte offset to start at (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Maximum bytes (default and maximum 65536)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillContentResponse"}}},"description":"A chunk of the file"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad parameters"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"output_blocked: the output sanitisation policy withholds the text (scoped caller)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server, skill or file not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"stored_copy_damaged (administrator)"},"415":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"The file is binary"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Read one text file of a skill","tags":["servers"]}},"/api/v1/servers/{id}/skills/refresh":{"post":{"description":"Administrator only. Reads the server's skills from the upstream again, verifies every file and returns the listing once applied. A refresh that is already running is joined. 409 skills_disabled when enable_skills is off; 409 skills_not_supported when the server does not announce the skills extension.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsListResponse"}}},"description":"Skills of the server after the refresh"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"skills_disabled, skills_not_supported or refresh_superseded"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Refresh failed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Refresh the skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/skills/unblock":{"post":{"description":"Administrator only. Clears the blocked mark on the named skills. The skill's approval state is not changed: a skill that is not approved stays unavailable. expected_incarnation is optional (0 binds to the current server). 409 server_replaced when the server was removed or replaced since it was reviewed. A scoped agent token is refused with 403.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsBlockRequest"}}},"description":"Skills to unblock","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsBlockResponse"}}},"description":"Number of skills whose mark changed (inside the data envelope)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or skill not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"server_replaced or skills_disabled"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Unblock skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/tool-calls":{"get":{"description":"Retrieves tool call history filtered by upstream server ID. Returns recent tool executions for the specified server including timestamps, arguments, results, and errors. Useful for server-specific debugging and monitoring.","parameters":[{"description":"Upstream server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Maximum number of records to return (1-100, default 50)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServerToolCallsResponse"}}},"description":"Server tool calls retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get server tool calls"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call history for specific server","tags":["tool-calls"]}},"/api/v1/servers/{id}/tools":{"get":{"description":"Retrieve all available tools for a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServerToolsResponse"}}},"description":"Server tools retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server kept being removed or replaced while its tools were read"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/approve":{"post":{"description":"Approves the given pending/changed tools (or all of them with approve_all). With expected_hashes (tool name -\u003e the review's current_hash) the approval is bound to the reviewed definitions: when a requested tool (approve_all: any pending or changed tool) no longer matches, the response is 409 review_out_of_date and nothing is approved.","parameters":[{"description":"Server name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.approveToolsRequest"}}},"description":"Tools to approve, or approve_all, with an optional review binding","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Approval outcome"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.StaleReviewErrorResponse"}}},"description":"The review is out of date; nothing was approved"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Approve tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/block":{"post":{"description":"Atomically approves AND disables the given tools (or all pending/changed tools when block_all=true) for a server. The approve and disable land in a single write per tool, so a tool is never left in the approved+enabled state. The \"blocked\" field counts tools actually blocked. An optional expected_incarnation binds the write to the reviewed server (Spec 116): a remove and re-add since then answers 409 server_replaced and writes nothing.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Block result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server was removed or re-added since expected_incarnation"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Block (approve+disable) tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/disable_all":{"post":{"description":"Bulk-toggles every known tool of a server. The \"changed\" field","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.expectedIncarnationBody"}}},"description":"Optional incarnation of the reviewed server (Spec 116)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Operation result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server was removed or re-added since expected_incarnation"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable or disable all tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/enable_all":{"post":{"description":"Bulk-toggles every known tool of a server. The \"changed\" field","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.expectedIncarnationBody"}}},"description":"Optional incarnation of the reviewed server (Spec 116)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Operation result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server was removed or re-added since expected_incarnation"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable or disable all tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/unquarantine":{"post":{"description":"Remove a specific upstream MCP server from quarantine to allow tool execution","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.expectedIncarnationBody"}}},"description":"Optional incarnation of the reviewed server (Spec 116)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server unquarantined successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server was removed or re-added since expected_incarnation"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Unquarantine a server","tags":["servers"]}},"/api/v1/sessions":{"get":{"description":"Retrieves paginated list of active and recent MCP client sessions. Each session represents a connection from an MCP client to MCPProxy, tracking initialization time, tool calls, and connection status.","parameters":[{"description":"Maximum number of sessions to return (1-100, default 10)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Number of sessions to skip for pagination (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Filter by session status","in":"query","name":"status","schema":{"enum":["active","closed"],"type":"string"}},{"description":"Filter by the session's latest effective profile; - selects sessions with none (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Filter by the client id the session's credential is bound to; - selects sessions with none (Spec 108)","in":"query","name":"client","schema":{"type":"string"}},{"description":"Filter by the token name the session initialized with; - selects sessions with none (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Alias of token","in":"query","name":"agent","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetSessionsResponse"}}},"description":"Sessions retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid status filter, token and agent naming different tokens, or client_name (not supported here; filter by client)"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read MCP session history"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get sessions"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get active MCP sessions","tags":["sessions"]}},"/api/v1/sessions/{id}":{"get":{"description":"Retrieves detailed information about a specific MCP client session including initialization parameters, connection status, tool call count, and activity timestamps.","parameters":[{"description":"Session ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetSessionDetailResponse"}}},"description":"Session details retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Session ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read MCP session history"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Session not found"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get MCP session details by ID","tags":["sessions"]}},"/api/v1/stats/tokens":{"get":{"description":"Retrieve token savings statistics across all servers and sessions","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Token statistics"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read deployment-wide token statistics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get token savings statistics","tags":["stats"]}},"/api/v1/status":{"get":{"description":"Get comprehensive server status including running state, listen address, upstream statistics, and timestamp. For a scoped caller (an agent token; for a profile-pinned token, its allowed_servers intersected with the pin) upstream_stats lists only the servers it may enumerate and every counter is recomputed over them.\ntelemetry (admin only): effective telemetry state {enabled, source: env|config|default, disabled_by}","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server status information"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server status","tags":["status"]}},"/api/v1/telemetry/payload":{"get":{"description":"Render the exact JSON heartbeat payload that mcpproxy would next send to the telemetry endpoint, without making a network call. Counters in the payload reflect the current in-memory state. Spec 042.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Telemetry heartbeat payload"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read the deployment telemetry payload"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Telemetry service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Preview next telemetry heartbeat payload","tags":["telemetry"]}},"/api/v1/telemetry/update-failure":{"post":{"description":"Records one terminal update-session failure, identified only by its\nstage (appcast, download, install, other). The body carries no error\ntext, URL, or version — the stage is the only value transmitted.\nReturns 204 both when the occurrence was durably persisted and when\ntelemetry is inactive at event time (config opt-out, environment\nopt-out, CI, or dev build), in which case nothing is recorded.\nCallers cannot and need not distinguish the two.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.UpdateFailureRequest"}}},"description":"Update failure stage","required":true},"responses":{"204":{"description":"Accepted (recorded, or a deliberate no-op while telemetry is inactive)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Malformed body, unknown field, trailing value, or stage outside the closed set"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Persistence failure"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Record a desktop auto-update failure occurrence (Spec 095)","tags":["telemetry"]}},"/api/v1/tool-calls":{"get":{"description":"Retrieves paginated tool call history across all upstream servers or filtered by session ID. Includes execution timestamps, arguments, results, and error information for debugging and auditing.","parameters":[{"description":"Maximum number of records to return (1-100, default 50)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Number of records to skip for pagination (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Filter tool calls by MCP session ID","in":"query","name":"session_id","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetToolCallsResponse"}}},"description":"Tool calls retrieved successfully"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get tool calls"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call history","tags":["tool-calls"]}},"/api/v1/tool-calls/{id}":{"get":{"description":"Retrieves detailed information about a specific tool call execution including full request arguments, response data, execution time, and any errors encountered.","parameters":[{"description":"Tool call ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetToolCallDetailResponse"}}},"description":"Tool call details retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call not found"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call details by ID","tags":["tool-calls"]}},"/api/v1/tool-calls/{id}/replay":{"post":{"description":"Re-executes a previous tool call with optional modified arguments. Useful for debugging and testing tool behavior with different inputs. Creates a new tool call record linked to the original.","parameters":[{"description":"Original tool call ID to replay","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ReplayToolCallRequest"}}},"description":"Optional modified arguments for replay"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ReplayToolCallResponse"}}},"description":"Tool call replayed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call ID required or invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Replay refused: tool quarantined or not callable, server quarantined, outside the profile policy, or the token lacks the tool's permission tier"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"429":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Shed by a concurrency limit or an agent token call rate limit (Retry-After header carries the wait hint)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to replay tool call"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Replay a tool call","tags":["tool-calls"]}},"/api/v1/tools":{"get":{"description":"Consolidated, read-only listing of all tools from every configured server (including disabled servers and disabled/config-denied tools), enriched with approval state and 30-day usage. Backs the global Tools page and the CLI global ` + "`" + `tools list` + "`" + ` (spec 050, issue #437).","parameters":[{"description":"View-as (administrator only): the tools this client would see, each with its access verdict {visible, callable, reason} and profile_tier (Spec 108 FR-032)","in":"query","name":"client","schema":{"type":"string"}},{"description":"View-as: the tools this profile would expose. An administrator gets every row with a verdict; any other caller gets only the visible rows plus counts {visible, hidden} (Spec 108 FR-032)","in":"query","name":"profile","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GlobalToolsResponse"}}},"description":"All tools across all servers"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unsupported scope filter (token), both client and profile, or '-' on a tools filter"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"client= requires administrator credentials"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown or unreachable client / profile"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Could not enumerate servers"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List every tool across all servers","tags":["tools"]}},"/api/v1/tools/call":{"post":{"description":"Execute a tool on an upstream MCP server (wrapper around MCP tool calls)","requestBody":{"content":{"application/json":{"schema":{"properties":{"arguments":{"type":"object"},"tool_name":{"type":"string"}},"type":"object"}}},"description":"Tool call request with tool name and arguments","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Tool call result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (invalid payload or missing tool name)"},"429":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Shed by a concurrency limit or an agent token call rate limit (Retry-After header carries the wait hint)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error or tool execution failure"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Call a tool","tags":["tools"]}},"/api/v1/work-sessions":{"get":{"description":"Lists work sessions (one agent's run of work) with their failure facts. An agent token sees only its own sessions, and only the part of each that touched servers in its reach.","parameters":[{"description":"Only sessions with at least one failure","in":"query","name":"failed","schema":{"type":"boolean"}},{"description":"With failed: count policy blocks as failures (default true)","in":"query","name":"include_blocked","schema":{"type":"boolean"}},{"description":"Filter by agent token name","in":"query","name":"token","schema":{"type":"string"}},{"description":"Filter by client id","in":"query","name":"client","schema":{"type":"string"}},{"description":"Filter by profile (administrators only)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Filter by run name","in":"query","name":"run","schema":{"type":"string"}},{"description":"Filter by the error class of the last failure","in":"query","name":"error_class","schema":{"type":"string"}},{"description":"Only sessions active at or after this time (RFC3339)","in":"query","name":"since","schema":{"type":"string"}},{"description":"Only sessions active at or before this time (RFC3339)","in":"query","name":"until","schema":{"type":"string"}},{"description":"last_activity (default) or last_failure","in":"query","name":"sort","schema":{"enum":["last_activity","last_failure"],"type":"string"}},{"description":"Page size (default 25, max 100)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Page offset","in":"query","name":"offset","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.WorkSessionListEnvelope"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad Request"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List work sessions","tags":["activity"]}},"/api/v1/work-sessions/{id}":{"get":{"parameters":[{"description":"Work session id","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.WorkSessionEnvelope"}}},"description":"OK"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Not Found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get one work session","tags":["activity"]}},"/api/v1/work-sessions/{id}/timeline":{"get":{"description":"Returns the session's activity rows and the upstream events of the servers it called, in time order, positioned at a failure, a row or the end. Bodies are omitted unless include_bodies is set.","parameters":[{"description":"Work session id","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"first_failure (default), failure:\u003cn\u003e, row:\u003cactivity id\u003e or end","in":"query","name":"at","schema":{"type":"string"}},{"description":"Rows before the position (default 20, max 250)","in":"query","name":"before","schema":{"type":"integer"}},{"description":"Rows after the position (default 20, max 250)","in":"query","name":"after","schema":{"type":"integer"}},{"description":"Include argument and response bodies","in":"query","name":"include_bodies","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.WorkSessionTimelineEnvelope"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad Request"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Not Found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get a work session's timeline","tags":["activity"]}},"/healthz":{"get":{"description":"Get comprehensive health status including all component health (Kubernetes-compatible liveness probe)","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.HealthResponse"}}},"description":"Service is healthy"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.HealthResponse"}}},"description":"Service is unhealthy"}},"summary":"Get health status","tags":["health"]}},"/readyz":{"get":{"description":"Get readiness status including all component readiness checks (Kubernetes-compatible readiness probe)","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.ReadinessResponse"}}},"description":"Service is ready"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.ReadinessResponse"}}},"description":"Service is not ready"}},"summary":"Get readiness status","tags":["health"]}}}, diff --git a/oas/swagger.yaml b/oas/swagger.yaml index 44ebfb747..47115813d 100644 --- a/oas/swagger.yaml +++ b/oas/swagger.yaml @@ -5587,6 +5587,9 @@ components: Spec 132: the client's credentials (API key and browser logins) and whether browser login is off right now. Both exist only once browser login was used on this install; until then a row is exactly what it was. + + Credentials is a pointer so that once the feature was used a row with no + credential serialises "credentials": [] instead of omitting the field. items: $ref: '#/components/schemas/httpapi.ClientCredential' type: array From f08df210bcddf6b71277a846a612b3fc08fffe0d Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 03:32:43 +0200 Subject: [PATCH 18/42] fix(oauth): end blocked streams on revoke, cancel across quick off/on (Spec 132 PR-1e) Cancelling a tracked request also sets immediate read and write deadlines so a handler blocked in a write or a body read ends; the watcher is stopped and joined at shutdown (also in StopServer). A monotonic switch-off epoch makes a quick off then on still end requests authenticated before it. Tests cover blocked write, stalled upload, shutdown, quick off/on, and client revoke, client forget and refresh-token replay ending only the affected stream. Related #1971 --- internal/runtime/oauth_login_everused_test.go | 11 + internal/runtime/oauth_login_service.go | 12 + internal/server/oauth_login_hardening_test.go | 6 +- internal/server/oauth_login_http.go | 9 +- internal/server/oauth_login_streams.go | 152 +++++++-- internal/server/oauth_login_streams_test.go | 318 ++++++++++++++++++ internal/server/server.go | 8 + 7 files changed, 477 insertions(+), 39 deletions(-) create mode 100644 internal/server/oauth_login_streams_test.go diff --git a/internal/runtime/oauth_login_everused_test.go b/internal/runtime/oauth_login_everused_test.go index 8e70e9410..79cbc0ac9 100644 --- a/internal/runtime/oauth_login_everused_test.go +++ b/internal/runtime/oauth_login_everused_test.go @@ -22,3 +22,14 @@ func TestEverUsed_ReadErrorFailsClosed(t *testing.T) { healthy := NewOAuthLoginService(OAuthLoginDeps{Store: fx.sm}) assert.False(t, healthy.EverUsed(), "a successful read of an unused install is false") } + +// Every switch-off boundary bumps the epoch, so a request authenticated before +// an off -> on can be told apart from one authenticated after it. +func TestDisableEpoch_CountsSwitchOffs(t *testing.T) { + fx := newOAuthFx(t) + svc := NewOAuthLoginService(OAuthLoginDeps{Store: fx.sm}) + assert.Zero(t, svc.DisableEpoch()) + svc.beginDisable("test")() + svc.beginDisable("test")() + assert.Equal(t, uint64(2), svc.DisableEpoch()) +} diff --git a/internal/runtime/oauth_login_service.go b/internal/runtime/oauth_login_service.go index 08fd855ea..3d8f50ed3 100644 --- a/internal/runtime/oauth_login_service.go +++ b/internal/runtime/oauth_login_service.go @@ -3,6 +3,7 @@ package runtime import ( "errors" "sync" + "sync/atomic" "time" "go.uber.org/zap" @@ -105,6 +106,9 @@ type OAuthLoginService struct { testHookBeforeRotateLock func() testHookInRotate func() + // disableEpoch counts switch-offs (beginDisable); see DisableEpoch. + disableEpoch atomic.Uint64 + everUsed bool // positive results only everMu sync.Mutex touchMu sync.Mutex @@ -192,6 +196,11 @@ func (r *Runtime) OAuthLoginService() *OAuthLoginService { return r.oauthLoginSe // SetNotifier installs the live-session notifier (the server). func (s *OAuthLoginService) SetNotifier(n BindingNotifier) { s.notifier = n } +// DisableEpoch is the number of times the feature was switched off since the +// process started. A request authenticated at an older epoch predates a +// switch-off, even when the feature is on again. A lock-free read. +func (s *OAuthLoginService) DisableEpoch() uint64 { return s.disableEpoch.Load() } + // Enabled reports whether the feature is on in the live configuration. func (s *OAuthLoginService) Enabled() bool { c := s.cfg() @@ -263,6 +272,9 @@ func (s *OAuthLoginService) CancelAll(reason string) int { // (and it is cancelled here) or waits and then sees the switch off. func (s *OAuthLoginService) beginDisable(reason string) (release func()) { s.lifecycleMu.Lock() + // A quick off -> on must still end what was open before the switch-off, so + // the boundary counts itself (an atomic, read without any lock). + s.disableEpoch.Add(1) s.cancelAllLocked(reason) return s.lifecycleMu.Unlock } diff --git a/internal/server/oauth_login_hardening_test.go b/internal/server/oauth_login_hardening_test.go index 63a3ed060..e3cfb0dee 100644 --- a/internal/server/oauth_login_hardening_test.go +++ b/internal/server/oauth_login_hardening_test.go @@ -237,7 +237,7 @@ func TestOAuthLogin_OpenStreamsEndWithTheLogin(t *testing.T) { func TestOAuthLoginHardening_RegistryExpiryAndRelease(t *testing.T) { srv := newOAuthLoginTestServer(t, func(c *config.Config) { c.MCPOAuthEnabled = true }) ctx, cancel := context.WithCancel(context.Background()) - release := srv.trackOAuthRequest("g1", time.Now().Add(150*time.Millisecond), cancel) + release := srv.trackOAuthRequest("g1", time.Now().Add(150*time.Millisecond), 0, cancel) require.Equal(t, 1, srv.oauthTrackedRequests()) select { case <-ctx.Done(): @@ -248,11 +248,9 @@ func TestOAuthLoginHardening_RegistryExpiryAndRelease(t *testing.T) { assert.Zero(t, srv.oauthTrackedRequests()) // A request that ends normally leaves nothing behind. - ctx2, cancel2 := context.WithCancel(context.Background()) - release2 := srv.trackOAuthRequest("g2", time.Now().Add(time.Hour), cancel2) + release2 := srv.trackOAuthRequest("g2", time.Now().Add(time.Hour), 0, func() {}) release2() assert.Zero(t, srv.oauthTrackedRequests()) - assert.Error(t, ctx2.Err()) } // oauthTrackedRequests is the number of requests currently tracked (tests). diff --git a/internal/server/oauth_login_http.go b/internal/server/oauth_login_http.go index 405d5e201..c2b28d6d6 100644 --- a/internal/server/oauth_login_http.go +++ b/internal/server/oauth_login_http.go @@ -1,7 +1,6 @@ package server import ( - "context" "encoding/json" "errors" "html" @@ -376,6 +375,9 @@ func (s *Server) oauthResourceAuth(next http.Handler) http.Handler { unauthorized() return } + // The switch-off epoch is read BEFORE authenticating, so a switch-off + // that lands in between makes this request older than the epoch. + epoch := svc.DisableEpoch() ac, grant, err := svc.Authenticate(token, origin, r.URL.Path, time.Now()) if err != nil { unauthorized() @@ -385,9 +387,6 @@ func (s *Server) oauthResourceAuth(next http.Handler) http.Handler { // The request (an SSE stream can live for hours) ends when the login is // revoked, its client forgotten, the feature switched off, its tokens // rotated or its access token expires. - ctx, cancel := context.WithCancel(auth.WithAuthContext(r.Context(), ac)) - release := s.trackOAuthRequest(grant.GrantID, grant.AccessExpiresAt, cancel) - defer release() - mcpRequestMiddlewares(next).ServeHTTP(w, r.WithContext(ctx)) + s.serveTracked(w, r.WithContext(auth.WithAuthContext(r.Context(), ac)), mcpRequestMiddlewares(next), grant.GrantID, grant.AccessExpiresAt, epoch) }) } diff --git a/internal/server/oauth_login_streams.go b/internal/server/oauth_login_streams.go index 61b691266..6f823e5e3 100644 --- a/internal/server/oauth_login_streams.go +++ b/internal/server/oauth_login_streams.go @@ -2,33 +2,55 @@ package server import ( "context" + "net/http" "sync" "time" ) // Spec 132 FR-031 / SC-006: revoking a login, forgetting its client, switching -// the feature off, rotating its tokens or the access token's expiry must also -// end what is already open on that login (a long-lived SSE stream, a slow -// request), not only the next request. oauthResourceAuth authenticates once -// per request, so every authenticated request is tracked here with the cancel -// of its context. +// the feature off (even off and straight back on), rotating its tokens or the +// access token's expiry must also end what is already open on that login (a +// long-lived SSE stream, a slow request, a stalled upload), not only the next +// request. oauthResourceAuth authenticates once per request, so every +// authenticated request is tracked here. +// +// Ending a request is two steps: its context is cancelled AND its transport I/O +// is interrupted with immediate read and write deadlines, because a handler +// blocked in a write to a client that stopped reading (or a body read from one +// that stalled) never looks at its context, and these routes clear the server's +// deadlines. // // The registry never calls into the runtime while a runtime lock is held and // takes no runtime lock itself: a watcher goroutine re-reads each tracked grant // from storage (OAuthLoginService.GrantLive, a plain read) every -// oauthStreamCheckInterval and whenever the binding notifier wakes it (grant -// revoke, replay revoke, client revoke or forget all call it), and an expiry -// timer bound to the access token's lifetime cancels the request when the token -// runs out. Nothing is allocated until the first OAuth request, and the watcher -// exits when the last tracked request ends. +// oauthStreamCheckInterval and whenever the binding notifier wakes it, and +// compares the switch-off epoch (an atomic counter) captured at authentication +// with the current one. An expiry timer bound to the access token's lifetime +// interrupts the request when the token runs out. Nothing is allocated until the +// first OAuth request, the watcher exits when the last tracked request ends, and +// server shutdown stops and joins it. const oauthStreamCheckInterval = time.Second type oauthStream struct { grantID string expiresAt time.Time // the access token's expiry when it was authenticated - cancel context.CancelFunc + epoch uint64 // the switch-off epoch when it was authenticated timer *time.Timer + + mu sync.Mutex + finished bool + interrupt func() +} + +// end interrupts the request unless it already finished (a deadline set on a +// connection that moved on to its next request would break that request). +func (st *oauthStream) end() { + st.mu.Lock() + defer st.mu.Unlock() + if !st.finished { + st.interrupt() + } } type oauthStreamRegistry struct { @@ -36,7 +58,10 @@ type oauthStreamRegistry struct { next uint64 entries map[uint64]*oauthStream running bool + stopped bool wake chan struct{} + stop chan struct{} + wg sync.WaitGroup } // oauthStreamsRegistry returns the registry, creating it on first use. @@ -44,7 +69,9 @@ func (s *Server) oauthStreamsRegistry() *oauthStreamRegistry { if r := s.oauthStreams.Load(); r != nil { return r } - s.oauthStreams.CompareAndSwap(nil, &oauthStreamRegistry{entries: map[uint64]*oauthStream{}, wake: make(chan struct{}, 1)}) + s.oauthStreams.CompareAndSwap(nil, &oauthStreamRegistry{ + entries: map[uint64]*oauthStream{}, wake: make(chan struct{}, 1), stop: make(chan struct{}), + }) return s.oauthStreams.Load() } @@ -59,24 +86,32 @@ func (s *Server) wakeOAuthStreams() { } } -// trackOAuthRequest registers an authenticated request of grantID. cancel ends -// its context. The returned release must be called when the request ends; it -// stops the expiry timer, forgets the entry and cancels the context. -func (s *Server) trackOAuthRequest(grantID string, expiresAt time.Time, cancel context.CancelFunc) (release func()) { +// trackOAuthRequest registers an authenticated request of grantID, authenticated +// at switch-off epoch. interrupt ends it (context cancelled, transport I/O +// interrupted). The returned release must be called when the request ends. +func (s *Server) trackOAuthRequest(grantID string, expiresAt time.Time, epoch uint64, interrupt func()) (release func()) { reg := s.oauthStreamsRegistry() - st := &oauthStream{grantID: grantID, expiresAt: expiresAt, cancel: cancel} - if d := time.Until(expiresAt); d > 0 { - st.timer = time.AfterFunc(d, cancel) - } else { - cancel() - } + st := &oauthStream{grantID: grantID, expiresAt: expiresAt, epoch: epoch, interrupt: interrupt} reg.mu.Lock() + if reg.stopped { + reg.mu.Unlock() + st.end() + return func() {} + } reg.next++ id := reg.next reg.entries[id] = st start := !reg.running - reg.running = true + if start { + reg.running = true + reg.wg.Add(1) + } reg.mu.Unlock() + if d := time.Until(expiresAt); d > 0 { + st.timer = time.AfterFunc(d, st.end) + } else { + st.end() + } if start { go s.watchOAuthStreams(reg) } @@ -84,20 +119,24 @@ func (s *Server) trackOAuthRequest(grantID string, expiresAt time.Time, cancel c reg.mu.Lock() delete(reg.entries, id) reg.mu.Unlock() + st.mu.Lock() + st.finished = true if st.timer != nil { st.timer.Stop() } - cancel() + st.mu.Unlock() } } -// watchOAuthStreams re-validates the tracked grants until none is left. +// watchOAuthStreams re-validates the tracked requests until none is left or the +// server shuts down. func (s *Server) watchOAuthStreams(reg *oauthStreamRegistry) { + defer reg.wg.Done() ticker := time.NewTicker(oauthStreamCheckInterval) defer ticker.Stop() for { reg.mu.Lock() - if len(reg.entries) == 0 { + if len(reg.entries) == 0 || reg.stopped { reg.running = false reg.mu.Unlock() return @@ -114,17 +153,70 @@ func (s *Server) watchOAuthStreams(reg *oauthStreamRegistry) { reg.mu.Unlock() svc := s.oauthLoginSvc() + var epoch uint64 + if svc != nil { + epoch = svc.DisableEpoch() + } for k, list := range groups { - if svc != nil && svc.GrantLive(k.grant, k.exp) { - continue - } + live := svc != nil && svc.GrantLive(k.grant, k.exp) for _, e := range list { - e.cancel() + // A request authenticated before the latest switch-off is dead + // even when the feature is on again. + if !live || e.epoch < epoch { + e.end() + } } } select { case <-ticker.C: case <-reg.wake: + case <-reg.stop: } } } + +// stopOAuthStreams interrupts every tracked request, stops the watcher and +// waits for it. It runs at server shutdown, before the HTTP server waits for +// its active handlers. Nothing is tracked afterwards. +func (s *Server) stopOAuthStreams() { + reg := s.oauthStreams.Load() + if reg == nil { + return + } + reg.mu.Lock() + if reg.stopped { + reg.mu.Unlock() + reg.wg.Wait() + return + } + reg.stopped = true + close(reg.stop) + list := make([]*oauthStream, 0, len(reg.entries)) + for _, e := range reg.entries { + list = append(list, e) + } + reg.mu.Unlock() + for _, e := range list { + e.end() + } + reg.wg.Wait() +} + +// serveTracked serves next for an authenticated browser-login request and ends +// the request when its login stops being valid. grantID and expiresAt come from +// the authentication, epoch from BEFORE it (so a switch-off in between counts). +func (s *Server) serveTracked(w http.ResponseWriter, r *http.Request, next http.Handler, grantID string, expiresAt time.Time, epoch uint64) { + ctx, cancel := context.WithCancel(r.Context()) + defer cancel() + rc := http.NewResponseController(w) + release := s.trackOAuthRequest(grantID, expiresAt, epoch, func() { + cancel() + // Interrupt blocked transport I/O too; errors (a writer that cannot + // take deadlines) are ignored, the context cancel still applies. + now := time.Now() + _ = rc.SetReadDeadline(now) + _ = rc.SetWriteDeadline(now) + }) + defer release() + next.ServeHTTP(w, r.WithContext(ctx)) +} diff --git a/internal/server/oauth_login_streams_test.go b/internal/server/oauth_login_streams_test.go new file mode 100644 index 000000000..fc4dc5481 --- /dev/null +++ b/internal/server/oauth_login_streams_test.go @@ -0,0 +1,318 @@ +//go:build !server + +package server + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" +) + +// --- transport I/O is interrupted, not only the context ------------------------ + +// A handler that ignores its context and sits in a write to a client that +// stopped reading ends when the request is interrupted, and its registry entry +// is released. (The grant "g1" does not exist, so the watcher ends the request +// on its first pass.) +func TestOAuthStreams_BlockedWriteIsInterrupted(t *testing.T) { + srv := newOAuthLoginTestServer(t, func(c *config.Config) { c.MCPOAuthEnabled = true }) + done := make(chan struct{}) + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer close(done) + srv.serveTracked(w, r, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + chunk := bytes.Repeat([]byte("x"), 1<<20) + for { + if _, err := w.Write(chunk); err != nil { + return + } + if f, ok := w.(http.Flusher); ok { + f.Flush() + } + } + }), "g1", time.Now().Add(time.Hour), srv.oauthLoginSvc().DisableEpoch()) + })) + defer ts.Close() + + conn, err := net.Dial("tcp", strings.TrimPrefix(ts.URL, "http://")) + require.NoError(t, err) + defer conn.Close() + _, err = fmt.Fprintf(conn, "GET / HTTP/1.1\r\nHost: x\r\n\r\n") + require.NoError(t, err) + // never read: the handler fills the socket buffers and blocks in Write + select { + case <-done: + case <-time.After(10 * time.Second): + t.Fatal("a handler blocked in a write survived the end of its login") + } + require.Eventually(t, func() bool { return srv.oauthTrackedRequests() == 0 }, 3*time.Second, 20*time.Millisecond) +} + +// The same for a request body that stalls. +func TestOAuthStreams_StalledUploadIsInterrupted(t *testing.T) { + srv := newOAuthLoginTestServer(t, func(c *config.Config) { c.MCPOAuthEnabled = true }) + done := make(chan struct{}) + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer close(done) + srv.serveTracked(w, r, http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + }), "g1", time.Now().Add(time.Hour), srv.oauthLoginSvc().DisableEpoch()) + })) + defer ts.Close() + conn, err := net.Dial("tcp", strings.TrimPrefix(ts.URL, "http://")) + require.NoError(t, err) + defer conn.Close() + _, err = fmt.Fprintf(conn, "POST / HTTP/1.1\r\nHost: x\r\nContent-Length: 1000000\r\n\r\nabc") + require.NoError(t, err) + select { + case <-done: + case <-time.After(10 * time.Second): + t.Fatal("a stalled upload survived the end of its login") + } + require.Eventually(t, func() bool { return srv.oauthTrackedRequests() == 0 }, 3*time.Second, 20*time.Millisecond) +} + +// Shutdown interrupts what is open, joins the watcher and refuses new tracking. +func TestOAuthStreams_ShutdownJoinsWatcher(t *testing.T) { + srv := newOAuthLoginTestServer(t, func(c *config.Config) { c.MCPOAuthEnabled = true }) + interrupted := make(chan struct{}) + var once sync.Once + release := srv.trackOAuthRequest("g1", time.Now().Add(time.Hour), srv.oauthLoginSvc().DisableEpoch(), func() { once.Do(func() { close(interrupted) }) }) + defer release() + reg := srv.oauthStreams.Load() + require.NotNil(t, reg) + + stopped := make(chan struct{}) + go func() { srv.stopOAuthStreams(); close(stopped) }() + select { + case <-stopped: + case <-time.After(5 * time.Second): + t.Fatal("stopOAuthStreams did not return: the watcher was not joined") + } + select { + case <-interrupted: + default: + t.Fatal("the tracked request was not interrupted at shutdown") + } + reg.mu.Lock() + assert.False(t, reg.running, "no watcher goroutine is left") + reg.mu.Unlock() + + late := make(chan struct{}) + var onceLate sync.Once + srv.trackOAuthRequest("g2", time.Now().Add(time.Hour), 0, func() { onceLate.Do(func() { close(late) }) }) + select { + case <-late: + default: + t.Fatal("a request tracked after shutdown must be ended at once") + } + srv.stopOAuthStreams() // idempotent +} + +// --- real daemon: what ends an open stream ------------------------------------ + +type streamDaemon struct { + t *testing.T + env *TestEnvironment + base string + svc *runtime.OAuthLoginService + httpc *http.Client +} + +func newStreamDaemon(t *testing.T) *streamDaemon { + t.Helper() + env := NewTestEnvironmentWithOptions(t, TestEnvironmentOptions{ + Mutate: func(cfg *config.Config, _ string) { cfg.MCPOAuthEnabled = true }, + }) + t.Cleanup(env.Cleanup) + return &streamDaemon{ + t: t, env: env, base: strings.TrimSuffix(env.proxyAddr, "/mcp"), svc: env.proxyServer.oauthLoginSvc(), + httpc: &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, + } +} + +// login runs the whole flow for a per-client address and returns the tokens +// and the registration id. +func (d *streamDaemon) login(client string) (access, refresh, regID string) { + t := d.t + redirect := "http://127.0.0.1:50999/callback" + resp, err := d.httpc.Post(d.base+"/oauth/register", "application/json", strings.NewReader(`{"redirect_uris":["`+redirect+`"]}`)) + require.NoError(t, err) + var reg map[string]any + require.NoError(t, json.NewDecoder(resp.Body).Decode(®)) + resp.Body.Close() + regID, _ = reg["client_id"].(string) + verifier := strings.Repeat("q", 50) + sum := sha256.Sum256([]byte(verifier)) + resource := d.base + "/mcp/oauth/" + client + q := url.Values{"response_type": {"code"}, "client_id": {regID}, "redirect_uri": {redirect}, + "code_challenge": {base64.RawURLEncoding.EncodeToString(sum[:])}, "code_challenge_method": {"S256"}, "resource": {resource}} + resp, err = d.httpc.Get(d.base + "/oauth/authorize?" + q.Encode()) + require.NoError(t, err) + resp.Body.Close() + loc, err := url.Parse(resp.Header.Get("Location")) + require.NoError(t, err) + redir, err := d.svc.Approve(context.Background(), loc.Query().Get("request"), runtime.ApprovalChoice{Client: runtime.ClientChoice{ID: client}}) + require.NoError(t, err) + ru, _ := url.Parse(redir) + form := url.Values{"grant_type": {"authorization_code"}, "code": {ru.Query().Get("code")}, "redirect_uri": {redirect}, + "client_id": {regID}, "code_verifier": {verifier}, "resource": {resource}} + resp, err = d.httpc.Post(d.base+"/oauth/token", "application/x-www-form-urlencoded", strings.NewReader(form.Encode())) + require.NoError(t, err) + defer resp.Body.Close() + var tok map[string]any + require.NoError(t, json.NewDecoder(resp.Body).Decode(&tok)) + access, _ = tok["access_token"].(string) + refresh, _ = tok["refresh_token"].(string) + require.NotEmpty(t, access) + return access, refresh, regID +} + +func (d *streamDaemon) refresh(regID, refresh string) (access, newRefresh string, status int) { + form := url.Values{"grant_type": {"refresh_token"}, "refresh_token": {refresh}, "client_id": {regID}} + resp, err := d.httpc.Post(d.base+"/oauth/token", "application/x-www-form-urlencoded", strings.NewReader(form.Encode())) + require.NoError(d.t, err) + defer resp.Body.Close() + var tok map[string]any + _ = json.NewDecoder(resp.Body).Decode(&tok) + access, _ = tok["access_token"].(string) + newRefresh, _ = tok["refresh_token"].(string) + return access, newRefresh, resp.StatusCode +} + +// openStream opens a session on the client's OAuth address and an SSE GET +// stream on it; the channel closes when the stream ends. +func (d *streamDaemon) openStream(client, access string) chan struct{} { + t := d.t + do := func(method, body, session string) *http.Response { + req, _ := http.NewRequest(method, d.base+"/mcp/oauth/"+client, bytes.NewBufferString(body)) + req.Header.Set("Authorization", "Bearer "+access) + req.Header.Set("Accept", "application/json, text/event-stream") + if method == http.MethodPost { + req.Header.Set("Content-Type", "application/json") + } + if session != "" { + req.Header.Set("Mcp-Session-Id", session) + } + resp, err := d.httpc.Do(req) + require.NoError(t, err) + return resp + } + resp := do(http.MethodPost, `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"t","version":"1"}}}`, "") + require.Equal(t, http.StatusOK, resp.StatusCode) + session := resp.Header.Get("Mcp-Session-Id") + _, _ = io.Copy(io.Discard, resp.Body) + resp.Body.Close() + do(http.MethodPost, `{"jsonrpc":"2.0","method":"notifications/initialized"}`, session).Body.Close() + stream := do(http.MethodGet, "", session) + require.Equal(t, http.StatusOK, stream.StatusCode) + done := make(chan struct{}) + go func() { + _, _ = io.Copy(io.Discard, stream.Body) + stream.Body.Close() + close(done) + }() + return done +} + +func streamOpen(done chan struct{}, d time.Duration) bool { + select { + case <-done: + return false + case <-time.After(d): + return true + } +} + +func (d *streamDaemon) requireEnds(done chan struct{}, what string) { + d.t.Helper() + select { + case <-done: + case <-time.After(5 * time.Second): + d.t.Fatalf("the stream did not end after %s", what) + } +} + +func (d *streamDaemon) setEnabled(on bool) { + cfg := d.env.proxyServer.runtime.Config() + next := *cfg + next.MCPOAuthEnabled = on + d.env.proxyServer.runtime.UpdateConfig(&next, "") +} + +// A switch-off followed at once by a switch-on still ends what was open before +// it; a stream opened after the re-enable stays. +func TestOAuthStreams_QuickOffOnEndsPreDisableStreams(t *testing.T) { + d := newStreamDaemon(t) + access, _, _ := d.login("cursor") + before := d.openStream("cursor", access) + require.True(t, streamOpen(before, time.Second)) + + d.setEnabled(false) + d.setEnabled(true) + d.requireEnds(before, "off -> on") + + after := d.openStream("cursor", access) // the login itself survives off -> on + require.True(t, streamOpen(after, 2500*time.Millisecond), "a stream opened after the re-enable stays open") +} + +// Client revoke, client forget and replay-revoke each end the affected stream; +// an unrelated client's stream stays open. +func TestOAuthStreams_ClientRevokeForgetAndReplayEndStreams(t *testing.T) { + d := newStreamDaemon(t) + rt := d.env.proxyServer.runtime + bystander, _, _ := d.login("windsurf") + bystanderStream := d.openStream("windsurf", bystander) + + // replay-revoke: an authentic old refresh token presented again. + { + access1, refresh1, regID := d.login("codex") + access2, _, status := d.refresh(regID, refresh1) + require.Equal(t, http.StatusOK, status) + require.NotEqual(t, access1, access2) + stream := d.openStream("codex", access2) + require.True(t, streamOpen(stream, 500*time.Millisecond)) + _, _, status = d.refresh(regID, refresh1) // replay + require.Equal(t, http.StatusBadRequest, status) + d.requireEnds(stream, "a refresh-token replay") + } + + // client revoke + { + access, _, _ := d.login("gemini") + stream := d.openStream("gemini", access) + require.True(t, streamOpen(stream, 500*time.Millisecond)) + _, err := rt.CredentialsService().Revoke(context.Background(), runtime.Actor{}, runtime.CredentialRef{Client: "gemini"}, false) + require.NoError(t, err) + d.requireEnds(stream, "a client revoke") + } + + // client forget + { + access, _, _ := d.login("opencode") + stream := d.openStream("opencode", access) + require.True(t, streamOpen(stream, 500*time.Millisecond)) + _, err := rt.ClientsService().Forget(context.Background(), runtime.Actor{}, "opencode", false) + require.NoError(t, err) + d.requireEnds(stream, "a client forget") + } + + require.True(t, streamOpen(bystanderStream, time.Second), "an unrelated client's stream stays open") +} diff --git a/internal/server/server.go b/internal/server/server.go index d07c7978e..95ba5c214 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -1604,6 +1604,10 @@ func (s *Server) Shutdown() error { s.logger.Info("Shutting down MCP proxy server...") + // Spec 132: end every tracked browser-login request and join the watcher + // first, or the HTTP shutdown below would wait for open streams. + s.stopOAuthStreams() + // Gracefully shutdown HTTP server first to stop accepting new connections if httpServer != nil { s.logger.Info("Gracefully shutting down HTTP server...") @@ -2803,6 +2807,10 @@ func (s *Server) StopServer() error { s.updateStatus(runtime.PhaseStopping, "Server is stopping...") + // Spec 132: end tracked browser-login requests (open SSE streams) and join + // their watcher, or the graceful shutdown below waits for them. + s.stopOAuthStreams() + // STEP 1: Gracefully shutdown HTTP server FIRST to stop accepting new connections // This must happen before we disconnect upstream servers to prevent new requests if httpServer != nil { From b89b95d2a2d56b2ee7379a03ca93459cfe7018d3 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 04:28:21 +0200 Subject: [PATCH 19/42] fix(oauth): order the disable epoch, per-run stream tracking (Spec 132 PR-1e) The switch-off epoch is counted when the disabled configuration is published, so a request that authenticated under the enabled one is always older than it. Stream tracking has a stopping flag checked under the mutex that creates the registry, and a fresh lifecycle per server run; a refused request is answered 503 without invoking the MCP handler. Related #1971 --- internal/runtime/oauth_login_everused_test.go | 5 +- internal/runtime/oauth_login_service.go | 14 ++- internal/server/oauth_login_hardening_test.go | 6 +- internal/server/oauth_login_http.go | 3 + internal/server/oauth_login_streams.go | 56 ++++++---- internal/server/oauth_login_streams_test.go | 103 ++++++++++++++++-- internal/server/server.go | 13 ++- 7 files changed, 162 insertions(+), 38 deletions(-) diff --git a/internal/runtime/oauth_login_everused_test.go b/internal/runtime/oauth_login_everused_test.go index 79cbc0ac9..dc59d9133 100644 --- a/internal/runtime/oauth_login_everused_test.go +++ b/internal/runtime/oauth_login_everused_test.go @@ -29,7 +29,10 @@ func TestDisableEpoch_CountsSwitchOffs(t *testing.T) { fx := newOAuthFx(t) svc := NewOAuthLoginService(OAuthLoginDeps{Store: fx.sm}) assert.Zero(t, svc.DisableEpoch()) - svc.beginDisable("test")() + release := svc.beginDisable("test") + assert.Zero(t, svc.DisableEpoch(), "not counted before the disabled config is published") + release() + assert.Equal(t, uint64(1), svc.DisableEpoch()) svc.beginDisable("test")() assert.Equal(t, uint64(2), svc.DisableEpoch()) } diff --git a/internal/runtime/oauth_login_service.go b/internal/runtime/oauth_login_service.go index 3d8f50ed3..fd4ac2db9 100644 --- a/internal/runtime/oauth_login_service.go +++ b/internal/runtime/oauth_login_service.go @@ -272,11 +272,17 @@ func (s *OAuthLoginService) CancelAll(reason string) int { // (and it is cancelled here) or waits and then sees the switch off. func (s *OAuthLoginService) beginDisable(reason string) (release func()) { s.lifecycleMu.Lock() - // A quick off -> on must still end what was open before the switch-off, so - // the boundary counts itself (an atomic, read without any lock). - s.disableEpoch.Add(1) s.cancelAllLocked(reason) - return s.lifecycleMu.Unlock + return func() { + // The epoch counts the switch-off only once the disabled configuration + // is visible (the caller runs release after publishing it, inside the + // serialized config commit). A request that authenticated under the + // previous, enabled configuration therefore captured an epoch lower + // than the one read after this point, even across a quick off -> on. + // An atomic, read without any lock. + s.disableEpoch.Add(1) + s.lifecycleMu.Unlock() + } } // cancelAllLocked snapshots the pending ids and cancels everything in one diff --git a/internal/server/oauth_login_hardening_test.go b/internal/server/oauth_login_hardening_test.go index e3cfb0dee..2bf648afa 100644 --- a/internal/server/oauth_login_hardening_test.go +++ b/internal/server/oauth_login_hardening_test.go @@ -237,7 +237,8 @@ func TestOAuthLogin_OpenStreamsEndWithTheLogin(t *testing.T) { func TestOAuthLoginHardening_RegistryExpiryAndRelease(t *testing.T) { srv := newOAuthLoginTestServer(t, func(c *config.Config) { c.MCPOAuthEnabled = true }) ctx, cancel := context.WithCancel(context.Background()) - release := srv.trackOAuthRequest("g1", time.Now().Add(150*time.Millisecond), 0, cancel) + release, ok := srv.trackOAuthRequest("g1", time.Now().Add(150*time.Millisecond), 0, cancel) + require.True(t, ok) require.Equal(t, 1, srv.oauthTrackedRequests()) select { case <-ctx.Done(): @@ -248,7 +249,8 @@ func TestOAuthLoginHardening_RegistryExpiryAndRelease(t *testing.T) { assert.Zero(t, srv.oauthTrackedRequests()) // A request that ends normally leaves nothing behind. - release2 := srv.trackOAuthRequest("g2", time.Now().Add(time.Hour), 0, func() {}) + release2, ok := srv.trackOAuthRequest("g2", time.Now().Add(time.Hour), 0, func() {}) + require.True(t, ok) release2() assert.Zero(t, srv.oauthTrackedRequests()) } diff --git a/internal/server/oauth_login_http.go b/internal/server/oauth_login_http.go index c2b28d6d6..c5cce0902 100644 --- a/internal/server/oauth_login_http.go +++ b/internal/server/oauth_login_http.go @@ -378,6 +378,9 @@ func (s *Server) oauthResourceAuth(next http.Handler) http.Handler { // The switch-off epoch is read BEFORE authenticating, so a switch-off // that lands in between makes this request older than the epoch. epoch := svc.DisableEpoch() + if h := s.testHookAfterEpochCapture; h != nil { + h() + } ac, grant, err := svc.Authenticate(token, origin, r.URL.Path, time.Now()) if err != nil { unauthorized() diff --git a/internal/server/oauth_login_streams.go b/internal/server/oauth_login_streams.go index 6f823e5e3..3e9aa400d 100644 --- a/internal/server/oauth_login_streams.go +++ b/internal/server/oauth_login_streams.go @@ -64,15 +64,14 @@ type oauthStreamRegistry struct { wg sync.WaitGroup } -// oauthStreamsRegistry returns the registry, creating it on first use. -func (s *Server) oauthStreamsRegistry() *oauthStreamRegistry { - if r := s.oauthStreams.Load(); r != nil { - return r - } - s.oauthStreams.CompareAndSwap(nil, &oauthStreamRegistry{ - entries: map[uint64]*oauthStream{}, wake: make(chan struct{}, 1), stop: make(chan struct{}), - }) - return s.oauthStreams.Load() +// resetOAuthStreams starts a fresh tracking lifecycle for a new server run: the +// previous run's registry (already stopped and joined by stopOAuthStreams) is +// dropped, and tracking is accepted again. Allocation stays lazy. +func (s *Server) resetOAuthStreams() { + s.oauthStreamsMu.Lock() + s.oauthStreamsStopping = false + s.oauthStreams.Store(nil) + s.oauthStreamsMu.Unlock() } // wakeOAuthStreams asks the watcher to re-check now. It allocates nothing and @@ -88,16 +87,25 @@ func (s *Server) wakeOAuthStreams() { // trackOAuthRequest registers an authenticated request of grantID, authenticated // at switch-off epoch. interrupt ends it (context cancelled, transport I/O -// interrupted). The returned release must be called when the request ends. -func (s *Server) trackOAuthRequest(grantID string, expiresAt time.Time, epoch uint64, interrupt func()) (release func()) { - reg := s.oauthStreamsRegistry() +// interrupted). The returned release must be called when the request ends. ok is +// false when the server is stopping: nothing is tracked and no watcher starts, +// and the caller must not serve the request. +func (s *Server) trackOAuthRequest(grantID string, expiresAt time.Time, epoch uint64, interrupt func()) (release func(), ok bool) { st := &oauthStream{grantID: grantID, expiresAt: expiresAt, epoch: epoch, interrupt: interrupt} - reg.mu.Lock() - if reg.stopped { - reg.mu.Unlock() - st.end() - return func() {} + // The stopping flag, the registry's creation and the entry's insertion are + // one critical section: a track after stopOAuthStreams has marked the run + // stopped is refused, whether or not a registry ever existed. + s.oauthStreamsMu.Lock() + if s.oauthStreamsStopping { + s.oauthStreamsMu.Unlock() + return func() {}, false } + reg := s.oauthStreams.Load() + if reg == nil { + reg = &oauthStreamRegistry{entries: map[uint64]*oauthStream{}, wake: make(chan struct{}, 1), stop: make(chan struct{})} + s.oauthStreams.Store(reg) + } + reg.mu.Lock() reg.next++ id := reg.next reg.entries[id] = st @@ -107,6 +115,8 @@ func (s *Server) trackOAuthRequest(grantID string, expiresAt time.Time, epoch ui reg.wg.Add(1) } reg.mu.Unlock() + s.oauthStreamsMu.Unlock() + if d := time.Until(expiresAt); d > 0 { st.timer = time.AfterFunc(d, st.end) } else { @@ -125,7 +135,7 @@ func (s *Server) trackOAuthRequest(grantID string, expiresAt time.Time, epoch ui st.timer.Stop() } st.mu.Unlock() - } + }, true } // watchOAuthStreams re-validates the tracked requests until none is left or the @@ -179,7 +189,10 @@ func (s *Server) watchOAuthStreams(reg *oauthStreamRegistry) { // waits for it. It runs at server shutdown, before the HTTP server waits for // its active handlers. Nothing is tracked afterwards. func (s *Server) stopOAuthStreams() { + s.oauthStreamsMu.Lock() + s.oauthStreamsStopping = true // also with no registry: late tracking is refused reg := s.oauthStreams.Load() + s.oauthStreamsMu.Unlock() if reg == nil { return } @@ -209,7 +222,7 @@ func (s *Server) serveTracked(w http.ResponseWriter, r *http.Request, next http. ctx, cancel := context.WithCancel(r.Context()) defer cancel() rc := http.NewResponseController(w) - release := s.trackOAuthRequest(grantID, expiresAt, epoch, func() { + release, ok := s.trackOAuthRequest(grantID, expiresAt, epoch, func() { cancel() // Interrupt blocked transport I/O too; errors (a writer that cannot // take deadlines) are ignored, the context cancel still applies. @@ -217,6 +230,11 @@ func (s *Server) serveTracked(w http.ResponseWriter, r *http.Request, next http. _ = rc.SetReadDeadline(now) _ = rc.SetWriteDeadline(now) }) + if !ok { + // The server is stopping: the MCP handler is not invoked. + oauthJSONError(w, http.StatusServiceUnavailable, "temporarily_unavailable", "the server is shutting down") + return + } defer release() next.ServeHTTP(w, r.WithContext(ctx)) } diff --git a/internal/server/oauth_login_streams_test.go b/internal/server/oauth_login_streams_test.go index fc4dc5481..3198cfafd 100644 --- a/internal/server/oauth_login_streams_test.go +++ b/internal/server/oauth_login_streams_test.go @@ -94,7 +94,8 @@ func TestOAuthStreams_ShutdownJoinsWatcher(t *testing.T) { srv := newOAuthLoginTestServer(t, func(c *config.Config) { c.MCPOAuthEnabled = true }) interrupted := make(chan struct{}) var once sync.Once - release := srv.trackOAuthRequest("g1", time.Now().Add(time.Hour), srv.oauthLoginSvc().DisableEpoch(), func() { once.Do(func() { close(interrupted) }) }) + release, ok := srv.trackOAuthRequest("g1", time.Now().Add(time.Hour), srv.oauthLoginSvc().DisableEpoch(), func() { once.Do(func() { close(interrupted) }) }) + require.True(t, ok) defer release() reg := srv.oauthStreams.Load() require.NotNil(t, reg) @@ -115,14 +116,13 @@ func TestOAuthStreams_ShutdownJoinsWatcher(t *testing.T) { assert.False(t, reg.running, "no watcher goroutine is left") reg.mu.Unlock() - late := make(chan struct{}) - var onceLate sync.Once - srv.trackOAuthRequest("g2", time.Now().Add(time.Hour), 0, func() { onceLate.Do(func() { close(late) }) }) - select { - case <-late: - default: - t.Fatal("a request tracked after shutdown must be ended at once") - } + // Tracking after the stop is refused: nothing is registered, no watcher starts. + _, ok = srv.trackOAuthRequest("g2", time.Now().Add(time.Hour), 0, func() {}) + assert.False(t, ok, "a request tracked after shutdown is refused") + reg.mu.Lock() + assert.False(t, reg.running) + assert.Len(t, reg.entries, 1, "only the request tracked before the stop (released by its owner)") + reg.mu.Unlock() srv.stopOAuthStreams() // idempotent } @@ -316,3 +316,88 @@ func TestOAuthStreams_ClientRevokeForgetAndReplayEndStreams(t *testing.T) { require.True(t, streamOpen(bystanderStream, time.Second), "an unrelated client's stream stays open") } + +// Item 3: a stop with no registry still marks the run stopped; a late request is +// refused without allocating a registry or starting a watcher, and the MCP +// handler is not invoked. +func TestOAuthStreams_StopWithoutRegistryRefusesLateTracking(t *testing.T) { + srv := newOAuthLoginTestServer(t, func(c *config.Config) { c.MCPOAuthEnabled = true }) + require.Nil(t, srv.oauthStreams.Load(), "nothing is allocated before the first OAuth request") + srv.stopOAuthStreams() + require.Nil(t, srv.oauthStreams.Load(), "stopping allocates nothing") + + _, ok := srv.trackOAuthRequest("g", time.Now().Add(time.Hour), 0, func() {}) + assert.False(t, ok) + assert.Nil(t, srv.oauthStreams.Load(), "no registry, hence no watcher") + + called := false + rec := httptest.NewRecorder() + srv.serveTracked(rec, httptest.NewRequest(http.MethodGet, "/mcp/oauth/cursor", http.NoBody), + http.HandlerFunc(func(http.ResponseWriter, *http.Request) { called = true }), "g", time.Now().Add(time.Hour), 0) + assert.Equal(t, http.StatusServiceUnavailable, rec.Code) + assert.False(t, called, "the MCP handler is not invoked while stopping") +} + +// Item 2: a new server run gets a fresh tracking lifecycle. +func TestOAuthStreams_StopThenStartTracksAgain(t *testing.T) { + d := newStreamDaemon(t) + access, _, _ := d.login("cursor") + first := d.openStream("cursor", access) + require.True(t, streamOpen(first, 500*time.Millisecond)) + + require.NoError(t, d.env.proxyServer.StopServer()) + d.requireEnds(first, "the server stopping") + require.NoError(t, d.env.proxyServer.StartServer(context.Background())) + d.env.waitForServerReady() + + access2, _, _ := d.login("windsurf") + second := d.openStream("windsurf", access2) + require.True(t, streamOpen(second, 2500*time.Millisecond), "after stop and start an authenticated stream works normally") + _ = access +} + +// Item 1: a request that authenticated under the pre-disable configuration +// across a quick off -> on is older than the epoch and is ended. +func TestOAuthStreams_RequestPausedAcrossQuickOffOnIsEnded(t *testing.T) { + f := newOAuthFlow(t, nil) + srv := f.srv + ended := make(chan struct{}) + started := make(chan struct{}) + ts := httptest.NewServer(srv.oauthResourceAuth(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + close(started) + <-r.Context().Done() + close(ended) + }))) + defer ts.Close() + f.host = strings.TrimPrefix(ts.URL, "http://") + _, tok := f.login("cursor") + + paused, resume := make(chan struct{}), make(chan struct{}) + var once sync.Once + srv.testHookAfterEpochCapture = func() { + once.Do(func() { close(paused); <-resume }) + } + go func() { + req, _ := http.NewRequest(http.MethodGet, ts.URL+"/mcp/oauth/cursor", http.NoBody) + req.Header.Set("Authorization", "Bearer "+tok.access) + if resp, err := http.DefaultClient.Do(req); err == nil { + _, _ = io.Copy(io.Discard, resp.Body) + resp.Body.Close() + } + }() + <-paused + f.setEnabled(false) + f.setEnabled(true) + close(resume) + + select { + case <-started: + case <-time.After(5 * time.Second): + t.Fatal("the paused request never authenticated") + } + select { + case <-ended: + case <-time.After(5 * time.Second): + t.Fatal("a request authenticated before the switch-off survived the off -> on") + } +} diff --git a/internal/server/server.go b/internal/server/server.go index 95ba5c214..727371b8a 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -131,9 +131,14 @@ type Server struct { // oauthStreams tracks authenticated browser-login requests so a revoke or // a switch-off ends what is already open (oauth_login_streams.go); nil // until the first one. - oauthStreams atomic.Pointer[oauthStreamRegistry] - oauthLimiterOnce sync.Once - oauthLimiter *mcplogin.Limiter + oauthStreams atomic.Pointer[oauthStreamRegistry] + oauthStreamsMu sync.Mutex // guards oauthStreamsStopping and the registry's creation + oauthStreamsStopping bool // set by stopOAuthStreams, cleared by a new run + // testHookAfterEpochCapture pauses oauthResourceAuth between the switch-off + // epoch capture and the authentication (tests only; nil in production). + testHookAfterEpochCapture func() + oauthLimiterOnce sync.Once + oauthLimiter *mcplogin.Limiter // createAfterConfigRead is a Spec 116 test seam (nil in production): it // runs in the create path after the runtime configuration was read and // before the new server is published. @@ -2720,6 +2725,8 @@ func (s *Server) StartServer(ctx context.Context) error { } s.serverCtx, s.serverCancel = context.WithCancel(ctx) + // Spec 132: a fresh browser-login stream-tracking lifecycle for this run. + s.resetOAuthStreams() // MCP-32: project runtime events onto Prometheus metrics while running. if s.observability != nil && s.observability.Metrics() != nil { From 3f8eacbe77da491d452f3b18bb03a3ea7059634f Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 05:22:52 +0200 Subject: [PATCH 20/42] fix(oauth): bump the disable epoch only on publish, bind streams to a server run (Spec 132 PR-1e) A switch-off whose publish fails no longer ends live streams: the epoch is counted only after a successful publish while the lifecycle lock is always released. A request captures a server-run generation before authenticating and is refused (503, handler not invoked) if it registers in another run. Related #1971 --- internal/runtime/commit.go | 5 ++ internal/runtime/oauth_login_everused_test.go | 9 +- internal/runtime/oauth_login_publish_test.go | 41 ++++++++++ internal/runtime/oauth_login_service.go | 22 ++--- internal/server/oauth_login_hardening_test.go | 4 +- internal/server/oauth_login_http.go | 3 +- internal/server/oauth_login_streams.go | 23 ++++-- internal/server/oauth_login_streams_test.go | 82 +++++++++++++++++-- internal/server/server.go | 1 + 9 files changed, 160 insertions(+), 30 deletions(-) create mode 100644 internal/runtime/oauth_login_publish_test.go diff --git a/internal/runtime/commit.go b/internal/runtime/commit.go index 6877b4070..c5f5ea6a5 100644 --- a/internal/runtime/commit.go +++ b/internal/runtime/commit.go @@ -964,8 +964,12 @@ func (r *Runtime) commitLocked(reason string, fn func(tx *CommitTx) error) (*Com // the function returns, that is, past the publish below and the r.cfg swap, so // a BeginAuthorization either created its request before this ran or sees the // switch off. See the lock-order note on OAuthLoginService. + disablePublished := func() {} if base.Config != nil && base.Config.MCPOAuthEnabled && !tx.next.MCPOAuthEnabled && r.oauthLoginService != nil { defer r.oauthLoginService.beginDisable("feature_disabled")() + // The disable epoch counts the switch-off only after a successful + // publish (below); the lock above is released either way. + disablePublished = r.oauthLoginService.disablePublished } // Step 8: publish. @@ -990,6 +994,7 @@ func (r *Runtime) commitLocked(reason string, fn func(tx *CommitTx) error) (*Com fn(oldCfg, tx.next) } r.mu.Unlock() + disablePublished() if r.upstreamManager != nil { r.upstreamManager.SetGlobalConfig(tx.next) } diff --git a/internal/runtime/oauth_login_everused_test.go b/internal/runtime/oauth_login_everused_test.go index dc59d9133..16d840bc9 100644 --- a/internal/runtime/oauth_login_everused_test.go +++ b/internal/runtime/oauth_login_everused_test.go @@ -23,16 +23,15 @@ func TestEverUsed_ReadErrorFailsClosed(t *testing.T) { assert.False(t, healthy.EverUsed(), "a successful read of an unused install is false") } -// Every switch-off boundary bumps the epoch, so a request authenticated before -// an off -> on can be told apart from one authenticated after it. -func TestDisableEpoch_CountsSwitchOffs(t *testing.T) { +// The epoch counts a switch-off only when the commit reports a successful +// publish; the lifecycle lock is released either way. +func TestDisableEpoch_CountsOnlyPublishedSwitchOffs(t *testing.T) { fx := newOAuthFx(t) svc := NewOAuthLoginService(OAuthLoginDeps{Store: fx.sm}) assert.Zero(t, svc.DisableEpoch()) release := svc.beginDisable("test") assert.Zero(t, svc.DisableEpoch(), "not counted before the disabled config is published") + svc.disablePublished() release() assert.Equal(t, uint64(1), svc.DisableEpoch()) - svc.beginDisable("test")() - assert.Equal(t, uint64(2), svc.DisableEpoch()) } diff --git a/internal/runtime/oauth_login_publish_test.go b/internal/runtime/oauth_login_publish_test.go new file mode 100644 index 000000000..7b3084434 --- /dev/null +++ b/internal/runtime/oauth_login_publish_test.go @@ -0,0 +1,41 @@ +package runtime + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" +) + +// A switch-off whose publish fails leaves the feature on: the disable epoch is +// NOT counted (live streams must not end), the lifecycle lock is released, and +// a later successful switch-off counts once. +func TestDisableEpoch_NotCountedWhenPublishFails(t *testing.T) { + rt, _ := newSpec116Runtime(t, nil) + svc := rt.OAuthLoginService() + setEnabled := func(on bool) func(*CommitTx) error { + return func(tx *CommitTx) error { + return tx.MutateGlobal(func(c *config.Config) error { c.MCPOAuthEnabled = on; return nil }) + } + } + _, err := rt.Commit("on", setEnabled(true)) + require.NoError(t, err) + require.True(t, svc.Enabled()) + + // A concurrent publish moves the version between prepare and publish. + rt.testHooks.afterAdvance = func(string) { rt.configSvc.SeedVersion(rt.ConfigSnapshot().Version + 1000) } + _, err = rt.Commit("off", setEnabled(false)) + require.Error(t, err, "the publish fails") + assert.True(t, svc.Enabled(), "the feature stayed on") + assert.Zero(t, svc.DisableEpoch(), "a failed switch-off does not end live requests") + require.True(t, svc.lifecycleMu.TryLock(), "the lifecycle lock was released") + svc.lifecycleMu.Unlock() + + rt.testHooks.afterAdvance = nil + _, err = rt.Commit("off", setEnabled(false)) + require.NoError(t, err) + assert.False(t, svc.Enabled()) + assert.Equal(t, uint64(1), svc.DisableEpoch()) +} diff --git a/internal/runtime/oauth_login_service.go b/internal/runtime/oauth_login_service.go index fd4ac2db9..fc5819b13 100644 --- a/internal/runtime/oauth_login_service.go +++ b/internal/runtime/oauth_login_service.go @@ -272,19 +272,21 @@ func (s *OAuthLoginService) CancelAll(reason string) int { // (and it is cancelled here) or waits and then sees the switch off. func (s *OAuthLoginService) beginDisable(reason string) (release func()) { s.lifecycleMu.Lock() + // Pending and approved sign-in requests are cancelled here, before the new + // configuration is published. If the publish then FAILS the feature stays on + // and those requests stay cancelled: acceptable, the client starts again. s.cancelAllLocked(reason) - return func() { - // The epoch counts the switch-off only once the disabled configuration - // is visible (the caller runs release after publishing it, inside the - // serialized config commit). A request that authenticated under the - // previous, enabled configuration therefore captured an epoch lower - // than the one read after this point, even across a quick off -> on. - // An atomic, read without any lock. - s.disableEpoch.Add(1) - s.lifecycleMu.Unlock() - } + return s.lifecycleMu.Unlock } +// disablePublished counts a switch-off once the disabled configuration is +// visible. The commit calls it after a SUCCESSFUL publish only (a failed one +// leaves the feature on and must not end live streams). A request that +// authenticated under the previous, enabled configuration therefore captured an +// epoch lower than the one read after this point, even across a quick off -> on. +// An atomic, read without any lock. +func (s *OAuthLoginService) disablePublished() { s.disableEpoch.Add(1) } + // cancelAllLocked snapshots the pending ids and cancels everything in one // request-store critical section (s.lifecycleMu held). func (s *OAuthLoginService) cancelAllLocked(reason string) int { diff --git a/internal/server/oauth_login_hardening_test.go b/internal/server/oauth_login_hardening_test.go index 2bf648afa..b1ce1a335 100644 --- a/internal/server/oauth_login_hardening_test.go +++ b/internal/server/oauth_login_hardening_test.go @@ -237,7 +237,7 @@ func TestOAuthLogin_OpenStreamsEndWithTheLogin(t *testing.T) { func TestOAuthLoginHardening_RegistryExpiryAndRelease(t *testing.T) { srv := newOAuthLoginTestServer(t, func(c *config.Config) { c.MCPOAuthEnabled = true }) ctx, cancel := context.WithCancel(context.Background()) - release, ok := srv.trackOAuthRequest("g1", time.Now().Add(150*time.Millisecond), 0, cancel) + release, ok := srv.trackOAuthRequest("g1", time.Now().Add(150*time.Millisecond), 0, srv.oauthRunGen(), cancel) require.True(t, ok) require.Equal(t, 1, srv.oauthTrackedRequests()) select { @@ -249,7 +249,7 @@ func TestOAuthLoginHardening_RegistryExpiryAndRelease(t *testing.T) { assert.Zero(t, srv.oauthTrackedRequests()) // A request that ends normally leaves nothing behind. - release2, ok := srv.trackOAuthRequest("g2", time.Now().Add(time.Hour), 0, func() {}) + release2, ok := srv.trackOAuthRequest("g2", time.Now().Add(time.Hour), 0, srv.oauthRunGen(), func() {}) require.True(t, ok) release2() assert.Zero(t, srv.oauthTrackedRequests()) diff --git a/internal/server/oauth_login_http.go b/internal/server/oauth_login_http.go index c5cce0902..9f72bbc66 100644 --- a/internal/server/oauth_login_http.go +++ b/internal/server/oauth_login_http.go @@ -377,6 +377,7 @@ func (s *Server) oauthResourceAuth(next http.Handler) http.Handler { } // The switch-off epoch is read BEFORE authenticating, so a switch-off // that lands in between makes this request older than the epoch. + run := s.oauthRunGen() epoch := svc.DisableEpoch() if h := s.testHookAfterEpochCapture; h != nil { h() @@ -390,6 +391,6 @@ func (s *Server) oauthResourceAuth(next http.Handler) http.Handler { // The request (an SSE stream can live for hours) ends when the login is // revoked, its client forgotten, the feature switched off, its tokens // rotated or its access token expires. - s.serveTracked(w, r.WithContext(auth.WithAuthContext(r.Context(), ac)), mcpRequestMiddlewares(next), grant.GrantID, grant.AccessExpiresAt, epoch) + s.serveTracked(w, r.WithContext(auth.WithAuthContext(r.Context(), ac)), mcpRequestMiddlewares(next), grant.GrantID, grant.AccessExpiresAt, epoch, run) }) } diff --git a/internal/server/oauth_login_streams.go b/internal/server/oauth_login_streams.go index 3e9aa400d..7908ed2c1 100644 --- a/internal/server/oauth_login_streams.go +++ b/internal/server/oauth_login_streams.go @@ -69,6 +69,7 @@ type oauthStreamRegistry struct { // dropped, and tracking is accepted again. Allocation stays lazy. func (s *Server) resetOAuthStreams() { s.oauthStreamsMu.Lock() + s.oauthStreamsRun++ // requests of the previous run can no longer register s.oauthStreamsStopping = false s.oauthStreams.Store(nil) s.oauthStreamsMu.Unlock() @@ -85,18 +86,28 @@ func (s *Server) wakeOAuthStreams() { } } +// oauthRunGen is the server-run generation a request captures BEFORE it +// authenticates; trackOAuthRequest refuses a request of another generation, so +// a request of a stopped run that was still paused in authentication cannot +// register in the next run. +func (s *Server) oauthRunGen() uint64 { + s.oauthStreamsMu.Lock() + defer s.oauthStreamsMu.Unlock() + return s.oauthStreamsRun +} + // trackOAuthRequest registers an authenticated request of grantID, authenticated -// at switch-off epoch. interrupt ends it (context cancelled, transport I/O +// at switch-off epoch in server run run. interrupt ends it (context cancelled, transport I/O // interrupted). The returned release must be called when the request ends. ok is -// false when the server is stopping: nothing is tracked and no watcher starts, +// false when the server is stopping or the request belongs to another run: nothing is tracked and no watcher starts, // and the caller must not serve the request. -func (s *Server) trackOAuthRequest(grantID string, expiresAt time.Time, epoch uint64, interrupt func()) (release func(), ok bool) { +func (s *Server) trackOAuthRequest(grantID string, expiresAt time.Time, epoch, run uint64, interrupt func()) (release func(), ok bool) { st := &oauthStream{grantID: grantID, expiresAt: expiresAt, epoch: epoch, interrupt: interrupt} // The stopping flag, the registry's creation and the entry's insertion are // one critical section: a track after stopOAuthStreams has marked the run // stopped is refused, whether or not a registry ever existed. s.oauthStreamsMu.Lock() - if s.oauthStreamsStopping { + if s.oauthStreamsStopping || run != s.oauthStreamsRun { s.oauthStreamsMu.Unlock() return func() {}, false } @@ -218,11 +229,11 @@ func (s *Server) stopOAuthStreams() { // serveTracked serves next for an authenticated browser-login request and ends // the request when its login stops being valid. grantID and expiresAt come from // the authentication, epoch from BEFORE it (so a switch-off in between counts). -func (s *Server) serveTracked(w http.ResponseWriter, r *http.Request, next http.Handler, grantID string, expiresAt time.Time, epoch uint64) { +func (s *Server) serveTracked(w http.ResponseWriter, r *http.Request, next http.Handler, grantID string, expiresAt time.Time, epoch, run uint64) { ctx, cancel := context.WithCancel(r.Context()) defer cancel() rc := http.NewResponseController(w) - release, ok := s.trackOAuthRequest(grantID, expiresAt, epoch, func() { + release, ok := s.trackOAuthRequest(grantID, expiresAt, epoch, run, func() { cancel() // Interrupt blocked transport I/O too; errors (a writer that cannot // take deadlines) are ignored, the context cancel still applies. diff --git a/internal/server/oauth_login_streams_test.go b/internal/server/oauth_login_streams_test.go index 3198cfafd..92a451385 100644 --- a/internal/server/oauth_login_streams_test.go +++ b/internal/server/oauth_login_streams_test.go @@ -47,7 +47,7 @@ func TestOAuthStreams_BlockedWriteIsInterrupted(t *testing.T) { f.Flush() } } - }), "g1", time.Now().Add(time.Hour), srv.oauthLoginSvc().DisableEpoch()) + }), "g1", time.Now().Add(time.Hour), srv.oauthLoginSvc().DisableEpoch(), srv.oauthRunGen()) })) defer ts.Close() @@ -73,7 +73,7 @@ func TestOAuthStreams_StalledUploadIsInterrupted(t *testing.T) { defer close(done) srv.serveTracked(w, r, http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { _, _ = io.Copy(io.Discard, r.Body) - }), "g1", time.Now().Add(time.Hour), srv.oauthLoginSvc().DisableEpoch()) + }), "g1", time.Now().Add(time.Hour), srv.oauthLoginSvc().DisableEpoch(), srv.oauthRunGen()) })) defer ts.Close() conn, err := net.Dial("tcp", strings.TrimPrefix(ts.URL, "http://")) @@ -94,7 +94,7 @@ func TestOAuthStreams_ShutdownJoinsWatcher(t *testing.T) { srv := newOAuthLoginTestServer(t, func(c *config.Config) { c.MCPOAuthEnabled = true }) interrupted := make(chan struct{}) var once sync.Once - release, ok := srv.trackOAuthRequest("g1", time.Now().Add(time.Hour), srv.oauthLoginSvc().DisableEpoch(), func() { once.Do(func() { close(interrupted) }) }) + release, ok := srv.trackOAuthRequest("g1", time.Now().Add(time.Hour), srv.oauthLoginSvc().DisableEpoch(), srv.oauthRunGen(), func() { once.Do(func() { close(interrupted) }) }) require.True(t, ok) defer release() reg := srv.oauthStreams.Load() @@ -117,7 +117,7 @@ func TestOAuthStreams_ShutdownJoinsWatcher(t *testing.T) { reg.mu.Unlock() // Tracking after the stop is refused: nothing is registered, no watcher starts. - _, ok = srv.trackOAuthRequest("g2", time.Now().Add(time.Hour), 0, func() {}) + _, ok = srv.trackOAuthRequest("g2", time.Now().Add(time.Hour), 0, srv.oauthRunGen(), func() {}) assert.False(t, ok, "a request tracked after shutdown is refused") reg.mu.Lock() assert.False(t, reg.running) @@ -326,14 +326,14 @@ func TestOAuthStreams_StopWithoutRegistryRefusesLateTracking(t *testing.T) { srv.stopOAuthStreams() require.Nil(t, srv.oauthStreams.Load(), "stopping allocates nothing") - _, ok := srv.trackOAuthRequest("g", time.Now().Add(time.Hour), 0, func() {}) + _, ok := srv.trackOAuthRequest("g", time.Now().Add(time.Hour), 0, srv.oauthRunGen(), func() {}) assert.False(t, ok) assert.Nil(t, srv.oauthStreams.Load(), "no registry, hence no watcher") called := false rec := httptest.NewRecorder() srv.serveTracked(rec, httptest.NewRequest(http.MethodGet, "/mcp/oauth/cursor", http.NoBody), - http.HandlerFunc(func(http.ResponseWriter, *http.Request) { called = true }), "g", time.Now().Add(time.Hour), 0) + http.HandlerFunc(func(http.ResponseWriter, *http.Request) { called = true }), "g", time.Now().Add(time.Hour), 0, srv.oauthRunGen()) assert.Equal(t, http.StatusServiceUnavailable, rec.Code) assert.False(t, called, "the MCP handler is not invoked while stopping") } @@ -401,3 +401,73 @@ func TestOAuthStreams_RequestPausedAcrossQuickOffOnIsEnded(t *testing.T) { t.Fatal("a request authenticated before the switch-off survived the off -> on") } } + +// A request of a stopped run, still paused in authentication when the next run +// starts, is refused with 503 and not registered in the new run; a request of +// the new run works. +func TestOAuthStreams_LateRequestOfPreviousRunIsRefused(t *testing.T) { + f := newOAuthFlow(t, nil) + srv := f.srv + called := make(chan struct{}, 1) + ts := httptest.NewServer(srv.oauthResourceAuth(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + called <- struct{}{} + w.WriteHeader(http.StatusOK) + }))) + defer ts.Close() + f.host = strings.TrimPrefix(ts.URL, "http://") + _, tok := f.login("cursor") + + paused, resume := make(chan struct{}), make(chan struct{}) + var once sync.Once + srv.testHookAfterEpochCapture = func() { once.Do(func() { close(paused); <-resume }) } + status := make(chan int, 1) + go func() { + req, _ := http.NewRequest(http.MethodGet, ts.URL+"/mcp/oauth/cursor", http.NoBody) + req.Header.Set("Authorization", "Bearer "+tok.access) + resp, err := http.DefaultClient.Do(req) + if err != nil { + status <- -1 + return + } + resp.Body.Close() + status <- resp.StatusCode + }() + <-paused + srv.stopOAuthStreams() + srv.resetOAuthStreams() // the next run starts while the old request is paused + close(resume) + select { + case code := <-status: + assert.Equal(t, http.StatusServiceUnavailable, code) + case <-time.After(5 * time.Second): + t.Fatal("the old request never answered") + } + select { + case <-called: + t.Fatal("the MCP handler ran for a request of the previous run") + default: + } + assert.Zero(t, srv.oauthTrackedRequests(), "nothing of the old run registered in the new one") + + // a request of the new run works + req, _ := http.NewRequest(http.MethodGet, ts.URL+"/mcp/oauth/cursor", http.NoBody) + req.Header.Set("Authorization", "Bearer "+tok.access) + resp, err := http.DefaultClient.Do(req) + require.NoError(t, err) + resp.Body.Close() + assert.Equal(t, http.StatusOK, resp.StatusCode) +} + +// The generation itself: a captured generation is refused after stop and start. +func TestOAuthStreams_GenerationIsComparedAtRegistration(t *testing.T) { + srv := newOAuthLoginTestServer(t, func(c *config.Config) { c.MCPOAuthEnabled = true }) + old := srv.oauthRunGen() + srv.stopOAuthStreams() + srv.resetOAuthStreams() + _, ok := srv.trackOAuthRequest("g", time.Now().Add(time.Hour), 0, old, func() {}) + assert.False(t, ok) + assert.Nil(t, srv.oauthStreams.Load(), "refused without allocating a registry or watcher") + release, ok := srv.trackOAuthRequest("g", time.Now().Add(time.Hour), 0, srv.oauthRunGen(), func() {}) + assert.True(t, ok) + release() +} diff --git a/internal/server/server.go b/internal/server/server.go index 727371b8a..45ada135c 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -133,6 +133,7 @@ type Server struct { // until the first one. oauthStreams atomic.Pointer[oauthStreamRegistry] oauthStreamsMu sync.Mutex // guards oauthStreamsStopping and the registry's creation + oauthStreamsRun uint64 // server-run generation, bumped by resetOAuthStreams oauthStreamsStopping bool // set by stopOAuthStreams, cleared by a new run // testHookAfterEpochCapture pauses oauthResourceAuth between the switch-off // epoch capture and the authentication (tests only; nil in production). From ff2b6e7c3741d36b424c1cc7cac97aec10090109 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 05:40:12 +0200 Subject: [PATCH 21/42] test(oauth): end-to-end script, docs and real-client record for browser login (Spec 132 PR-1f) scripts/test-client-oauth-e2e.sh drives a real ./mcpproxy on a scratch data dir through default off, discovery, registration, authorize, admin approve, PKCE exchange, MCP over the login, wrong doors, refresh and replay, revoke/forget, guard refusal, rate limits, off after use and on again. Also adds docs/features/client-oauth-login.md, the CLAUDE.md entry, and specs/132-client-oauth-login/verification/real-clients.md (SDK client verified; Claude Code, Cursor, VS Code and Inspector not verified). Related #1971 --- CLAUDE.md | 1 + docs/configuration/config-file.md | 2 +- docs/features/client-oauth-login.md | 120 ++++ scripts/test-client-oauth-e2e.sh | 518 ++++++++++++++++++ .../verification/real-clients.md | 53 ++ .../verification/sdk-client.mjs | 90 +++ website/sidebars.js | 1 + 7 files changed, 784 insertions(+), 1 deletion(-) create mode 100644 docs/features/client-oauth-login.md create mode 100755 scripts/test-client-oauth-e2e.sh create mode 100644 specs/132-client-oauth-login/verification/real-clients.md create mode 100644 specs/132-client-oauth-login/verification/sdk-client.mjs diff --git a/CLAUDE.md b/CLAUDE.md index 4763e2096..0396e2b8a 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-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 (nothing is created until a login is stored). 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.** - 125-skills-over-mcp (PR-3): Go 1.26, backend + CLI + docs — approved skills reach agents through three read-only built-ins, registered only while `enable_skills` is on (`MCPProxyServer.RefreshSkillsAvailability`: default registry, call-tool, code-execution and direct surfaces; never `/mcp/s/`, never from `code_execution`): `retrieve_skills(query, limit)`, `load_skill(id, offset, limit, version)`, `read_skill_file(id, path, offset, limit, version)` (`internal/server/mcp_skills.go`). Everything comes from the approved copy through `Runtime.AvailableSkill` / `AvailableSkillFile` / `SearchAvailableSkills` (`internal/runtime/skills_agent.go`); one refusal `skill not found: ` for every unavailable reason; reach = `resolveActiveProfileWithSource` → `serverInScope`, tool policy not applied. Search: memory-only Bleve in `internal/skills/index`, one index per reach, every match re-checked against its record. Paging: parts of ≤60,000 bytes with `Version:` in the header. Output policy (`mcp_skills_output.go`): block/redact/strip on the whole file before paging, also on names, descriptions and file names; skills build a detector when a policy is switched on after start. Activity type `skill_access` (administrator-only, like `skill_quarantine_change`). Scoped REST: `GET /api/v1/servers/{id}/skills{,/content}` answer an agent token with available skills from the approved copy through the same policy. Records of skills a listing did not name are bounded (200 per server). Docs: `docs/features/skills.md` "Skills for agents". **No new dependencies.** diff --git a/docs/configuration/config-file.md b/docs/configuration/config-file.md index 9c981104d..b52cbe19c 100644 --- a/docs/configuration/config-file.md +++ b/docs/configuration/config-file.md @@ -64,7 +64,7 @@ MCPProxy uses a JSON configuration file located at `~/.mcpproxy/mcp_config.json` | `trusted_proxies` | string[] | `[]` (trust nobody) | CIDRs or IP addresses whose `X-Forwarded-For`, `X-Real-IP`, `X-Forwarded-Proto` and `X-Forwarded-Host` headers are believed. Headers from any other peer are ignored and the direct `RemoteAddr` is used. Env `MCPPROXY_TRUSTED_PROXIES` (comma list). Live (hot-reload, no restart). Validation: `trusted_proxies[N] "value" is not a valid CIDR or IP address` — refused identically at boot, `PATCH /api/v1/config` and `/config/apply`. See [Reverse Proxy Deployment](/operations/reverse-proxy#trusted_proxies-forwarded-headers) | | `require_mcp_auth` | boolean | `false` | Require an API key on the `/mcp` endpoint (off by default for client compatibility). Enable when exposing MCPProxy beyond localhost. **Server edition:** forced to `true` whenever `server_edition.enabled` is `true` — an explicit `false` is not an error, but boot logs `require_mcp_auth: false is overridden to true because server_edition.enabled is true` and `mcpproxy doctor` reports the same finding | | `mcp_reject_query_apikey` | boolean | `false` | Refuse a `?apikey=` query parameter on every MCP endpoint (`/mcp*` and the legacy `/v1/tool_code` aliases) with a 401, forcing clients onto `Authorization: Bearer ` or `X-API-Key` so tokens stop appearing in access logs, proxy logs and browser history (a URL already sent is still logged in transit; the option makes the client fail until it is migrated). MCP endpoints only: the REST API, the Web UI and `/events` keep accepting the query form. Entries written by an older Connect wizard with `?apikey=` in the URL (Codex, the generic fallback) must be reconnected first; current versions write an `X-API-Key` header. Live, no restart | -| `mcp_oauth_enabled` | boolean | `false` | Experimental. Opt-in browser login (OAuth 2.1 + PKCE) for MCP clients, served only to loopback peers and loopback `Host` values, personal edition only. With it off nothing changes: no new route behaves differently and nothing is stored. Env `MCPPROXY_MCP_OAUTH_ENABLED=true\|false` overrides it for the process (never persisted). Live, no restart. **Not functional yet in this release:** the endpoints (`/mcp/oauth`, `/oauth/register`, `/oauth/authorize`, `/oauth/token` and the two `/.well-known/oauth-*` documents) answer `501 Not Implemented` when enabled | +| `mcp_oauth_enabled` | boolean | `false` | Experimental. Opt-in browser login (OAuth 2.1 + PKCE) for MCP clients, served only to loopback peers and loopback `Host` values, personal edition only. With it off nothing changes: no new route behaves differently and nothing is stored. Env `MCPPROXY_MCP_OAUTH_ENABLED=true\|false` overrides it for the process (never persisted). Live, no restart. Backend and administrator REST only for now (no consent page): see [Browser Login for MCP Clients](../features/client-oauth-login.md) | | `enable_socket` | boolean | `true` | Enable the Unix socket/named pipe the tray uses. Socket connections are trusted **without the API key**, including stdio servers spawned under `none` or `sandbox` isolation, which can then mint agent tokens. Set `false` on headless installs and whenever untrusted stdio servers run outside `docker` isolation. | | `forward_client_headers` | boolean | `true` | Master switch for [client header forwarding](/configuration/upstream-servers#client-header-forwarding). Nothing is forwarded until a server lists names in `forward_headers`. Env `MCPPROXY_FORWARD_CLIENT_HEADERS=false` disables it for the process (never persisted). | diff --git a/docs/features/client-oauth-login.md b/docs/features/client-oauth-login.md new file mode 100644 index 000000000..f739c902a --- /dev/null +++ b/docs/features/client-oauth-login.md @@ -0,0 +1,120 @@ +--- +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. +keywords: [oauth, browser login, mcp client, pkce, dynamic client registration, rfc 9728, rfc 8414, rfc 8707, cursor, claude code, vscode] +--- + +# Browser Login for MCP Clients + +MCPProxy can act as a small OAuth 2.1 authorization server so that an MCP client +that supports OAuth can sign in instead of carrying an API key in its config file. +It is **off by default** and **experimental**: in this release only the backend and +the administrator REST exist. There is no consent page yet, so an administrator +approves each sign-in through the REST API (see [Approving a sign-in](#approving-a-sign-in)). + +What it gives you: + +- public clients only (no client secret), PKCE `S256`, dynamic client registration + (RFC 7591), protected-resource and authorization-server metadata (RFC 9728, RFC 8414) + and the `resource` parameter (RFC 8707); +- one sign-in address per client: `http://127.0.0.1:8080/mcp/oauth/` + (for example `/mcp/oauth/cursor`), or the generic `/mcp/oauth` where the administrator + chooses the client at approval; +- API keys keep working unchanged on `/mcp` and everywhere else. + +It is served to loopback peers and loopback `Host` values only, and only by the +personal edition (`mcpproxy`); the server edition answers `404` on all of these paths. + +## Enabling + +```json +{ "mcp_oauth_enabled": true } +``` + +or `MCPPROXY_MCP_OAUTH_ENABLED=true` for one process (never persisted). The setting is +read live, so a config change needs no restart; the environment variable is read at start. + +With the setting off and never used, nothing changes: the OAuth paths behave as they did +before, and no storage bucket is created. `scripts/test-client-oauth-e2e.sh` checks both. + +## Addresses + +| Path | Purpose | +|---|---| +| `/mcp/oauth`, `/mcp/oauth/` | The MCP endpoint, same tools as `/mcp`, bearer access token only | +| `/.well-known/oauth-protected-resource/mcp/oauth[/]` | Protected-resource metadata (RFC 9728) | +| `/.well-known/oauth-authorization-server` | Authorization-server metadata (RFC 8414) | +| `POST /oauth/register` | Dynamic client registration (RFC 7591) | +| `GET /oauth/authorize` | Starts a sign-in; redirects to `/ui/authorize?request=` | +| `POST /oauth/token` | Code exchange and refresh | + +An unknown client id in an address is `404`. Without a valid token the OAuth MCP address +answers `401` with a `WWW-Authenticate: Bearer resource_metadata="..."` challenge that +points at the metadata of that exact address, so a client discovers the per-client path +on its own. Registration, authorize and token are rate limited (`429` with `Retry-After`). + +## Tokens + +- Access token `mcp_oat_...`, valid for 1 hour, accepted only on the address it was issued for. +- Refresh token `mcp_ort_...`, valid for 30 days from the last rotation, rotated on every use. + Presenting an old (already rotated) refresh token revokes the whole login. +- An access token is refused on `/mcp`, on another client's address and on a different + origin (for example `localhost` instead of `127.0.0.1`). An API key, `?apikey=`, an agent + token or the admin key is refused on the OAuth addresses. + +A login belongs to a client and uses that client's profile binding, like its API key. +A binding that would let the client bypass its profile through `/mcp` without authentication +is refused the same way as for API keys (`binding_bypassable_without_auth`); set +`require_mcp_auth` or use an all-servers binding. + +## Approving a sign-in + +A sign-in is held until an administrator decides it. With the admin API key: + +```bash +# pending sign-ins +curl -s -H "X-API-Key: $KEY" http://127.0.0.1:8080/api/v1/oauth/authorizations +# one request, with the client, its binding and its revision +curl -s -H "X-API-Key: $KEY" http://127.0.0.1:8080/api/v1/oauth/authorizations/ +# approve (existing client: pass binding_revision when it has a binding) +curl -s -X POST -H "X-API-Key: $KEY" -H 'Content-Type: application/json' \ + http://127.0.0.1:8080/api/v1/oauth/authorizations//approve \ + -d '{"client":{"id":"cursor"},"mode":"switchable","profile":""}' +``` + +The answer is `{"data":{"redirect_url":"..."}}`; the client receives the code when its +browser is sent there. Approval stores nothing: the login is stored when the client +exchanges the code, after the binding and guard are checked again. `.../deny` ends the +request with `access_denied`; `.../preview` shows the guard verdict without writing. +Full contract: [REST API](../api/rest-api.md). + +## Seeing and revoking logins + +`GET /api/v1/clients` and `GET /api/v1/clients/` list each login under `credentials` +(`kind: browser_login`, state `active`, `lapsed` or `revoked`, never the token). Revoke one +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. + +## Turning it off + +Set `mcp_oauth_enabled` back to `false` (or the variable to `false`). After the feature has +been used, the OAuth paths answer `404`, pending sign-ins are cancelled and existing +logins stop working; they are kept, so turning it on again restores them while their +tokens are still valid. `browser_login_disabled` on the client payload is `true` while it +is off after use. API-key access is never affected. A login can still be revoked while off. + +## Downgrade + +Browser-login records live in their own storage buckets, created only when the first login +is stored. A binary that does not know the feature does not serve the OAuth paths, so the +logins simply stop being usable. + +## Plain HTTP + +The issuer is `http://127.0.0.1:`, not HTTPS. The specifications ask for HTTPS for +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`; only the MCP +TypeScript SDK client flow is verified so far. diff --git a/scripts/test-client-oauth-e2e.sh b/scripts/test-client-oauth-e2e.sh new file mode 100755 index 000000000..2fcb8cc4d --- /dev/null +++ b/scripts/test-client-oauth-e2e.sh @@ -0,0 +1,518 @@ +#!/usr/bin/env bash +# Spec 132 T043: end-to-end check of browser login for MCP clients against a +# real ./mcpproxy binary. A scratch data dir, a scratch HOME and a high port +# are used; nothing under ~/.mcpproxy or the real client configs is touched. +# There is no browser: the consent step is done through the admin REST +# (/api/v1/oauth/authorizations/{id}/approve), as PR-1 ships no consent page. +# +# 1. default off -> OAuth paths are not served, nothing is written to config.db +# 2. on: discovery -> 401 challenge + both metadata documents, unknown client 404 +# 3. register / authorize -> RFC 7591 registration, authorize redirect, bad requests +# 4. approve / token -> admin approve, deny, double approve, PKCE exchange, code reuse +# 5. MCP over the login -> initialize + tools/list on the OAuth address +# 6. wrong doors -> token on /mcp, on another client address, on localhost; +# API key on the OAuth address +# 7. refresh -> rotation, forged refresh token, replay revokes the login +# 8. revoke / forget -> revoking a login (and forgetting a client) ends access at once +# 9. guard refusal -> named profile with require_mcp_auth off is refused +# 10. off after use -> 404 on OAuth paths, API key /mcp still works +# 11. on again -> the surviving login works again +# +# Usage: ./scripts/test-client-oauth-e2e.sh (needs ./mcpproxy or go, curl, jq, openssl) +# PORT=19561 listen port of the scratch core +# MCPPROXY_BIN use this binary instead of building one + +set -uo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +WORK="$(mktemp -d)" +PORT="${PORT:-19561}" +API_KEY="e2e-client-oauth-key" +DATA="$WORK/data" +HOME_DIR="$WORK/home" +BIN="${MCPPROXY_BIN:-$WORK/mcpproxy}" +B="http://127.0.0.1:$PORT" +API="$B/api/v1" +RU="http://127.0.0.1:54321/callback" +PROXY_PID="" +NO_RETRY=0 +PASS=0 +FAIL=0 + +cleanup() { + [ -n "$PROXY_PID" ] && kill "$PROXY_PID" 2>/dev/null + wait 2>/dev/null + rm -rf "$WORK" +} +trap cleanup EXIT + +ok() { echo " PASS: $*"; PASS=$((PASS + 1)); } +bad() { echo " FAIL: $*"; FAIL=$((FAIL + 1)); } +step() { echo; echo "== $*"; } +need() { command -v "$1" >/dev/null || { echo "missing tool: $1"; exit 2; }; } +for t in curl jq openssl; do need "$t"; done + +# eq WHAT WANT GOT +eq() { if [ "$2" = "$3" ]; then ok "$1"; else bad "$1 (want '$2', got '$3')"; fi; } +# has WHAT HAYSTACK NEEDLE (fixed string) +has() { case "$2" in *"$3"*) ok "$1" ;; *) bad "$1 (no '$3' in '${2:0:200}')" ;; esac; } +hasnt() { case "$2" in *"$3"*) bad "$1 (found '$3')" ;; *) ok "$1" ;; esac; } +# mask hides token material in anything printed. +mask() { sed -E 's/mcp_o[ar]t_[A-Za-z0-9_-]+//g'; } + +mkdir -p "$DATA" "$HOME_DIR" +if [ -z "${MCPPROXY_BIN:-}" ]; then + echo "building mcpproxy" + (cd "$ROOT" && go build -o "$BIN" ./cmd/mcpproxy) || { echo "build failed"; exit 2; } +fi +if curl -s -o /dev/null "http://127.0.0.1:$PORT/"; then echo "port $PORT is in use"; exit 2; fi + +# write_config REQUIRE_MCP_AUTH +write_config() { + cat > "$WORK/config.json" <>"$WORK/proxy.log" 2>&1 & + PROXY_PID=$! + for _ in $(seq 1 100); do + curl -sf -H "X-API-Key: $API_KEY" "$API/status" >/dev/null && return 0 + kill -0 "$PROXY_PID" 2>/dev/null || return 1 + sleep 0.2 + done + return 1 +} + +stop_proxy() { + [ -n "$PROXY_PID" ] && kill "$PROXY_PID" 2>/dev/null + wait "$PROXY_PID" 2>/dev/null + PROXY_PID="" +} + +# --- HTTP helpers ----------------------------------------------------------- +# req METHOD URL [curl args...] -> sets CODE, HDRS, BODY +# A 429 from the public endpoints (burst 5 register / 10 authorize per address) is waited out +# once via Retry-After, so a fast script does not trip over the limiter it is not testing. +req() { + local m="$1" u="$2" + shift 2 + for _ in 1 2 3; do + CODE=$(curl -s -o "$WORK/body" -D "$WORK/hdrs" -w '%{http_code}' -X "$m" "$u" "$@") + BODY=$(cat "$WORK/body") + HDRS=$(tr -d '\r' < "$WORK/hdrs") + [ "$CODE" = 429 ] && [ "$NO_RETRY" != 1 ] || return 0 + sleep "$(hdr Retry-After | grep -E '^[0-9]+$' || echo 5)" + done +} +hdr() { printf '%s\n' "$HDRS" | awk -v k="$(printf %s "$1" | tr 'A-Z' 'a-z')" 'BEGIN{FS=": "} tolower($1)==k {sub(/^[^:]*: /,""); print; exit}'; } +admin() { req "$1" "$API$2" -H "X-API-Key: $API_KEY" -H 'Content-Type: application/json' "${@:3}"; } + +INIT='{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"e2e-client","version":"1"}}}' +# mcp_post URL TOKEN-HEADER... BODY: POST an MCP message (extra headers before body). +mcp_post() { + local u="$1" body="$2" + shift 2 + req POST "$u" -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' "$@" -d "$body" +} +# mcp_session URL BEARER -> prints session id of a successful initialize +mcp_init() { + mcp_post "$1" "$INIT" -H "Authorization: Bearer $2" + SID="" + [ "$CODE" = 200 ] && SID=$(hdr Mcp-Session-Id) +} + +# --- OAuth client helpers --------------------------------------------------- +pkce() { + VER=$(openssl rand -base64 48 | tr -d '=+/\n' | head -c 64) + CHAL=$(printf %s "$VER" | openssl dgst -sha256 -binary | openssl base64 -A | tr '+/' '-_' | tr -d '=') +} +register() { # NAME -> CID + req POST "$B/oauth/register" -H 'Content-Type: application/json' -d "{\"redirect_uris\":[\"$RU\"],\"client_name\":\"$1\"}" + CID=$(printf %s "$BODY" | jq -r '.client_id // empty') +} +authorize() { # CID RESOURCE-PATH -> sets RID (pkce first) + pkce + req GET "$B/oauth/authorize" -G --data-urlencode response_type=code --data-urlencode "client_id=$1" \ + --data-urlencode "redirect_uri=$RU" --data-urlencode "code_challenge=$CHAL" --data-urlencode code_challenge_method=S256 \ + --data-urlencode "resource=$B$2" --data-urlencode state=st-1 + RID=$(hdr Location | sed -n 's/.*[?&]request=\([^&]*\).*/\1/p') + [ -n "$RID" ] || [ -z "${E2E_DEBUG:-}" ] || echo " (authorize answered $CODE: $(printf %s "$BODY" | head -c 200))" +} +approve() { # RID JSON -> CODE_VAL (empty on refusal) + admin POST "/oauth/authorizations/$1/approve" -d "$2" + CODE_VAL=$(printf %s "$BODY" | jq -r '.data.redirect_url // empty' | sed -n 's/.*[?&]code=\([^&]*\).*/\1/p') + [ -n "$CODE_VAL" ] || [ -z "${E2E_DEBUG:-}" ] || echo " (approve answer $CODE: $(printf %s "$BODY" | head -c 300))" +} +# approve_fixed RID CLIENT: approve on a client address, binding revision taken from the request +# when the client already has a binding (a client that has had a login keeps one). +approve_fixed() { + admin GET "/oauth/authorizations/$1" + local rev + rev=$(printf %s "$BODY" | jq -r '.data.client.binding.revision // empty') + approve "$1" "$(jq -nc --arg c "$2" --arg r "$rev" '{client:{id:$c},mode:"switchable",profile:""} + (if $r != "" then {binding_revision:$r} else {} end)')" +} +exchange() { # CID CODE RESOURCE-PATH [verifier] + req POST "$B/oauth/token" -d grant_type=authorization_code --data-urlencode "code=$2" --data-urlencode "redirect_uri=$RU" \ + -d "client_id=$1" --data-urlencode "code_verifier=${4:-$VER}" --data-urlencode "resource=$B$3" + AT=$(printf %s "$BODY" | jq -r '.access_token // empty') + RT=$(printf %s "$BODY" | jq -r '.refresh_token // empty') + [ "$CODE" = 200 ] || [ -z "${E2E_DEBUG:-}" ] || echo " (token answer: $(printf %s "$BODY" | mask))" +} +refresh() { # CID RT RESOURCE-PATH + req POST "$B/oauth/token" -d grant_type=refresh_token --data-urlencode "refresh_token=$2" -d "client_id=$1" --data-urlencode "resource=$B$3" +} +# full_login NAME CLIENT-ID -> CID AT RT GRANT (client address /mcp/oauth/CLIENT-ID, switchable all-servers binding) +full_login() { + register "$1" + authorize "$CID" "/mcp/oauth/$2" + approve_fixed "$RID" "$2" + exchange "$CID" "$CODE_VAL" "/mcp/oauth/$2" + GRANT=$(admin GET "/clients/$2" && printf %s "$BODY" | jq -r '[.data.credentials[]? | select(.kind=="browser_login" and .state=="active")][0].grant_id // empty') +} + +############################################################################# +step "1. default off" +write_config false +start_proxy unset || { bad "core did not start"; tail -20 "$WORK/proxy.log"; exit 1; } +req POST "$B/mcp/oauth/cursor" -H 'Content-Type: application/json' -d "$INIT" +eq "OAuth MCP address gives no sign-in challenge" "" "$(hdr WWW-Authenticate)" +req GET "$B/.well-known/oauth-authorization-server" +hasnt "no authorization-server metadata" "$BODY" "token_endpoint" +req GET "$B/.well-known/oauth-protected-resource/mcp/oauth/cursor" +hasnt "no protected-resource metadata" "$BODY" "authorization_servers" +req POST "$B/oauth/register" -H 'Content-Type: application/json' -d "{\"redirect_uris\":[\"$RU\"]}" +[ "$CODE" != 201 ] && ok "registration not served (HTTP $CODE)" || bad "registration answered 201 while off" +req GET "$B/oauth/authorize?response_type=code&client_id=x" +[ "$CODE" != 302 ] && ok "authorize not served (HTTP $CODE)" || bad "authorize redirected while off" +admin GET "/oauth/authorizations" +eq "admin sign-in request list is 404 while off" 404 "$CODE" +has "feature_disabled code" "$BODY" "feature_disabled" +admin GET "/clients" +hasnt "client payload carries no browser-login field" "$BODY" "browser_login" +req POST "$B/mcp" -H "X-API-Key: $API_KEY" -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' -d "$INIT" +eq "API-key /mcp works" 200 "$CODE" +stop_proxy +for bucket in oauth_registrations oauth_grants oauth_grant_access_index oauth_client_bindings oauth_login_ever_used; do + if grep -a -q -F "$bucket" "$DATA/config.db"; then bad "config.db contains $bucket while the feature never ran"; else ok "no $bucket in config.db"; fi +done + +############################################################################# +step "2. on: discovery" +write_config true +start_proxy true || { bad "core did not start"; tail -20 "$WORK/proxy.log"; exit 1; } +req POST "$B/mcp/oauth/cursor" -H 'Content-Type: application/json' -d "$INIT" +eq "401 on the per-client address" 401 "$CODE" +CH=$(hdr WWW-Authenticate) +has "challenge names the per-client metadata" "$CH" "resource_metadata=\"$B/.well-known/oauth-protected-resource/mcp/oauth/cursor\"" +req GET "$B/.well-known/oauth-protected-resource/mcp/oauth/cursor" +eq "protected-resource document: resource" "$B/mcp/oauth/cursor" "$(printf %s "$BODY" | jq -r .resource)" +eq "protected-resource document: authorization server" "$B" "$(printf %s "$BODY" | jq -r '.authorization_servers[0]')" +req GET "$B/.well-known/oauth-authorization-server" +eq "AS metadata: issuer" "$B" "$(printf %s "$BODY" | jq -r .issuer)" +eq "AS metadata: S256 only" '["S256"]' "$(printf %s "$BODY" | jq -c .code_challenge_methods_supported)" +eq "AS metadata: public clients only" '["none"]' "$(printf %s "$BODY" | jq -c .token_endpoint_auth_methods_supported)" +eq "AS metadata: registration endpoint" "$B/oauth/register" "$(printf %s "$BODY" | jq -r .registration_endpoint)" +req POST "$B/mcp/oauth" -H 'Content-Type: application/json' -d "$INIT" +eq "401 on the generic address" 401 "$CODE" +has "generic challenge" "$(hdr WWW-Authenticate)" "oauth-protected-resource/mcp/oauth\"" +req POST "$B/mcp/oauth/no-such-client" -H 'Content-Type: application/json' -d "$INIT" +eq "unknown client address is 404" 404 "$CODE" +req GET "$B/.well-known/oauth-protected-resource/mcp/oauth/no-such-client" +eq "unknown client metadata is 404" 404 "$CODE" + +############################################################################# +step "3. register and authorize" +req POST "$B/oauth/register" -H 'Content-Type: application/json' -d '{"redirect_uris":["ftp://example.com/cb"]}' +eq "non-http redirect URI refused" 400 "$CODE" +has "invalid_redirect_uri" "$BODY" "invalid_redirect_uri" +req POST "$B/oauth/register" -H 'Content-Type: application/json' -d "{\"redirect_uris\":[\"$RU\"],\"token_endpoint_auth_method\":\"client_secret_post\"}" +eq "confidential client refused" 400 "$CODE" +register "Cursor IDE" +CID_A="$CID" +eq "registration answers 201" 201 "$CODE" +hasnt "no client_secret issued" "$BODY" "client_secret" +[ -n "$CID_A" ] && ok "client_id issued" || bad "no client_id" +authorize "$CID_A" /mcp/oauth/cursor +eq "authorize redirects" 302 "$CODE" +has "redirect goes to the consent page" "$(hdr Location)" "$B/ui/authorize?request=" +eq "no-store on authorize" "no-store" "$(hdr Cache-Control)" +[ -n "$RID" ] && ok "request id extracted" || bad "no request id" +req GET "$B/oauth/authorize" -G --data-urlencode response_type=code --data-urlencode "client_id=$CID_A" \ + --data-urlencode "redirect_uri=http://127.0.0.1:1/other" --data-urlencode "code_challenge=$CHAL" --data-urlencode code_challenge_method=S256 +eq "unregistered redirect URI is a 400 page, not a redirect" 400 "$CODE" +eq "...with no Location header" "" "$(hdr Location)" +authorize "$CID_A" /mcp/oauth/no-such-client +eq "resource of an unknown client is 404, no redirect" 404 "$CODE" +authorize "$CID_A" /somewhere/else +eq "foreign resource redirects" 302 "$CODE" +has "invalid_target error to the client" "$(hdr Location)" "error=invalid_target" +has "state echoed" "$(hdr Location)" "state=st-1" +req GET "$B/oauth/authorize" -G --data-urlencode response_type=code --data-urlencode "client_id=$CID_A" \ + --data-urlencode "redirect_uri=$RU" --data-urlencode "code_challenge=$CHAL" --data-urlencode code_challenge_method=plain --data-urlencode "resource=$B/mcp/oauth/cursor" +has "plain PKCE refused" "$(hdr Location)" "error=invalid_request" + +############################################################################# +step "4. approve and token exchange" +authorize "$CID_A" /mcp/oauth/cursor +admin GET "/oauth/authorizations/$RID" +eq "admin sees the request pending" pending "$(printf %s "$BODY" | jq -r .data.status)" +eq "address kind is client" client "$(printf %s "$BODY" | jq -r .data.address_kind)" +eq "fixed client id" cursor "$(printf %s "$BODY" | jq -r .data.client.id)" +admin GET "/oauth/authorizations" +has "pending list names the request" "$BODY" "$RID" +req GET "$B/api/v1/oauth/authorizations/$RID" +[ "$CODE" = 401 ] || [ "$CODE" = 403 ] && ok "admin REST refuses a call without the key (HTTP $CODE)" || bad "admin REST answered $CODE without the key" +approve "$RID" '{"client":{"id":"cursor"},"mode":"switchable","profile":""}' +eq "approve answers 200" 200 "$CODE" +[ -n "$CODE_VAL" ] && ok "approve returned a code" || bad "no code in redirect_url" +has "state carried in the redirect" "$BODY" "state=st-1" +admin POST "/oauth/authorizations/$RID/approve" -d '{"client":{"id":"cursor"},"mode":"switchable","profile":""}' +eq "double approve is 409" 409 "$CODE" +has "already_decided" "$BODY" "already_decided" +CODE_1="$CODE_VAL" +exchange "$CID_A" "$CODE_1" /mcp/oauth/cursor "wrong-verifier-wrong-verifier-wrong-verifier-wrong-verif" +eq "wrong PKCE verifier refused" 400 "$CODE" +has "invalid_grant" "$BODY" "invalid_grant" +authorize "$CID_A" /mcp/oauth/cursor +admin POST "/oauth/authorizations/$RID/deny" +eq "deny answers 200" 200 "$CODE" +has "access_denied redirect" "$BODY" "error=access_denied" +# the wrong-verifier attempt may have consumed the first code; get a fresh one +authorize "$CID_A" /mcp/oauth/cursor +approve "$RID" '{"client":{"id":"cursor"},"mode":"switchable","profile":""}' +exchange "$CID_A" "$CODE_VAL" /mcp/oauth/cursor +eq "token exchange answers 200" 200 "$CODE" +eq "no-store on the token answer" "no-store" "$(hdr Cache-Control)" +case "$AT" in mcp_oat_*) ok "access token has the mcp_oat_ prefix" ;; *) bad "access token shape" ;; esac +case "$RT" in mcp_ort_*) ok "refresh token has the mcp_ort_ prefix" ;; *) bad "refresh token shape" ;; esac +eq "expires_in is 3600" 3600 "$(printf %s "$BODY" | jq -r .expires_in)" +CODE_USED="$CODE_VAL" +req POST "$B/oauth/token" -d grant_type=authorization_code --data-urlencode "code=$CODE_USED" --data-urlencode "redirect_uri=$RU" \ + -d "client_id=$CID_A" --data-urlencode "code_verifier=$VER" --data-urlencode "resource=$B/mcp/oauth/cursor" +eq "reusing the code is refused" 400 "$CODE" +has "reuse is invalid_grant" "$BODY" "invalid_grant" +admin GET "/clients/cursor" +G=$(printf %s "$BODY" | jq -r '[.data.credentials[]? | select(.kind=="browser_login")][0].state // empty') +eq "code reuse revoked the login it produced" revoked "$G" +# the reuse revoked that login (and its registration); a fresh client is used from here on +register "Cursor IDE" +CID_A="$CID" +authorize "$CID_A" /mcp/oauth/cursor +approve_fixed "$RID" cursor +exchange "$CID_A" "$CODE_VAL" /mcp/oauth/cursor +eq "fresh login after the replay" 200 "$CODE" +AT_C="$AT"; RT_C="$RT" +admin GET "/clients/cursor" +GRANT_C=$(printf %s "$BODY" | jq -r '[.data.credentials[]? | select(.kind=="browser_login" and .state=="active")][0].grant_id // empty') +[ -n "$GRANT_C" ] && ok "active login listed on the client (kind browser_login)" || bad "no active login on the client" +eq "browser_login_disabled false while on" false "$(printf %s "$BODY" | jq -r .data.browser_login_disabled)" +if printf %s "$BODY" | grep -Eq 'mcp_o[ar]t_[A-Za-z0-9_-]{20}'; then bad "client payload carries token material"; else ok "client payload carries no token material"; fi + +############################################################################# +step "5. MCP over the login" +mcp_init "$B/mcp/oauth/cursor" "$AT_C" +[ -n "$SID" ] && ok "initialize accepted on the OAuth address" || bad "initialize refused (HTTP $CODE)" +eq "server name" mcpproxy-go "$(printf %s "$BODY" | jq -r '.result.serverInfo.name // empty')" +mcp_post "$B/mcp/oauth/cursor" '{"jsonrpc":"2.0","method":"notifications/initialized"}' -H "Authorization: Bearer $AT_C" -H "Mcp-Session-Id: $SID" +mcp_post "$B/mcp/oauth/cursor" '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' -H "Authorization: Bearer $AT_C" -H "Mcp-Session-Id: $SID" +eq "tools/list answers 200" 200 "$CODE" +NT=$(printf %s "$BODY" | jq -r '.result.tools | length' 2>/dev/null) +[ "${NT:-0}" -gt 0 ] 2>/dev/null && ok "tools/list returned $NT tools" || bad "tools/list had no tools: ${BODY:0:200}" +has "retrieve_tools is offered" "$BODY" "retrieve_tools" +admin GET "/clients/cursor" +eq "initialize name recorded as observed name" e2e-client "$(printf %s "$BODY" | jq -r '[.data.credentials[]? | select(.state=="active")][0].observed_name // empty')" + +############################################################################# +step "6. wrong doors" +# token for cursor on another client address, the classic endpoint and localhost +req POST "$B/mcp/oauth/claude-code" -H "Authorization: Bearer $AT_C" -H 'Content-Type: application/json' -d "$INIT" +eq "cursor token on /mcp/oauth/claude-code" 401 "$CODE" +req POST "$B/mcp/oauth" -H "Authorization: Bearer $AT_C" -H 'Content-Type: application/json' -d "$INIT" +eq "cursor token on the generic address" 401 "$CODE" +req POST "$B/mcp" -H "Authorization: Bearer $AT_C" -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' -d "$INIT" +eq "access token on classic /mcp (require_mcp_auth on)" 401 "$CODE" +req POST "http://localhost:$PORT/mcp/oauth/cursor" -H "Authorization: Bearer $AT_C" -H 'Content-Type: application/json' -d "$INIT" +[ "$CODE" = 401 ] || [ "$CODE" = 404 ] && ok "token replayed against localhost instead of 127.0.0.1 refused (HTTP $CODE)" || bad "localhost answered $CODE" +req POST "$B/mcp/oauth/cursor" -H "X-API-Key: $API_KEY" -H 'Content-Type: application/json' -d "$INIT" +eq "API key header on the OAuth address" 401 "$CODE" +req POST "$B/mcp/oauth/cursor?apikey=$API_KEY" -H 'Content-Type: application/json' -d "$INIT" +eq "?apikey= on the OAuth address" 401 "$CODE" +req POST "$B/mcp/oauth/cursor" -H "Authorization: Bearer $API_KEY" -H 'Content-Type: application/json' -d "$INIT" +eq "admin key as bearer on the OAuth address" 401 "$CODE" +req POST "$B/mcp/oauth/cursor" -H "Authorization: Bearer mcp_oat_0000000000000000000000000000000000000000000" -H 'Content-Type: application/json' -d "$INIT" +eq "forged access token" 401 "$CODE" +req POST "$B/mcp" -H "X-API-Key: $API_KEY" -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' -d "$INIT" +eq "API key on classic /mcp still works" 200 "$CODE" +req POST "$B/mcp" -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' -d "$INIT" +eq "classic /mcp without credentials refused (require_mcp_auth on)" 401 "$CODE" + +############################################################################# +step "7. refresh, forged refresh token, replay" +GID="${RT_C#mcp_ort_}"; GID="${GID%%_*}" +FORGED="mcp_ort_${GID}_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +refresh "$CID_A" "$FORGED" /mcp/oauth/cursor +eq "forged refresh token (real grant id) refused" 400 "$CODE" +has "forged is invalid_grant" "$BODY" "invalid_grant" +admin GET "/clients/cursor" +eq "forged token changed nothing: login still active" active "$(printf %s "$BODY" | jq -r --arg g "$GRANT_C" '[.data.credentials[]? | select(.grant_id==$g)][0].state // empty')" +refresh "$CID_A" "$RT_C" /mcp/oauth/cursor +eq "refresh answers 200" 200 "$CODE" +AT_2=$(printf %s "$BODY" | jq -r '.access_token // empty'); RT_2=$(printf %s "$BODY" | jq -r '.refresh_token // empty') +[ -n "$RT_2" ] && [ "$RT_2" != "$RT_C" ] && ok "refresh token rotated" || bad "refresh token not rotated" +[ -n "$AT_2" ] && [ "$AT_2" != "$AT_C" ] && ok "new access token issued" || bad "access token not renewed" +mcp_post "$B/mcp/oauth/cursor" "$INIT" -H "Authorization: Bearer $AT_2" +eq "new access token works" 200 "$CODE" +req POST "$B/oauth/token" -d grant_type=refresh_token --data-urlencode "refresh_token=$RT_C" -d "client_id=$CID_A" --data-urlencode "resource=$B/mcp/oauth/cursor" +eq "replaying the old refresh token is refused" 400 "$CODE" +mcp_post "$B/mcp/oauth/cursor" "$INIT" -H "Authorization: Bearer $AT_2" +eq "replay revoked the login: its access token stops" 401 "$CODE" +refresh "$CID_A" "$RT_2" /mcp/oauth/cursor +eq "the rotated refresh token is dead too" 400 "$CODE" +admin GET "/clients/cursor" +eq "grant listed as revoked" revoked "$(printf %s "$BODY" | jq -r --arg g "$GRANT_C" '[.data.credentials[]? | select(.grant_id==$g)][0].state // empty')" + +############################################################################# +step "8. revoke one login, forget a client" +full_login "Cursor again" cursor +eq "fresh cursor login" 200 "$CODE" +AT_R="$AT"; CID_R="$CID"; GRANT_R="$GRANT" +mcp_init "$B/mcp/oauth/cursor" "$AT_R" +[ -n "$SID" ] && ok "session open on the new login" || bad "could not open a session" +admin DELETE "/clients/cursor/logins/$GRANT_R" +eq "revoke login answers 200" 200 "$CODE" +mcp_post "$B/mcp/oauth/cursor" '{"jsonrpc":"2.0","id":3,"method":"tools/list"}' -H "Authorization: Bearer $AT_R" -H "Mcp-Session-Id: $SID" +eq "open session refused right after the revoke" 401 "$CODE" +mcp_post "$B/mcp/oauth/cursor" "$INIT" -H "Authorization: Bearer $AT_R" +eq "new session refused after the revoke" 401 "$CODE" +refresh "$CID_R" "none" /mcp/oauth/cursor +eq "refresh refused after the revoke" 400 "$CODE" +admin DELETE "/clients/cursor/logins/no-such-grant" +eq "revoking an unknown login is 404" 404 "$CODE" +full_login "Claude Code" claude-code +AT_F="$AT" +mcp_post "$B/mcp/oauth/claude-code" "$INIT" -H "Authorization: Bearer $AT_F" +eq "claude-code login works" 200 "$CODE" +admin DELETE "/clients/claude-code" +[ "$CODE" = 200 ] && ok "forget client answers 200" || bad "forget client answered $CODE: ${BODY:0:200}" +mcp_post "$B/mcp/oauth/claude-code" "$INIT" -H "Authorization: Bearer $AT_F" +eq "forgotten client's login refused" 401 "$CODE" + +############################################################################# +step "9. guard refusal and stale binding" +# a client with a binding: approve with a stale revision +full_login "VS Code" vscode +AT_Z="$AT" +authorize "$CID" /mcp/oauth/vscode +admin GET "/oauth/authorizations/$RID" +REV=$(printf %s "$BODY" | jq -r '.data.client.binding.revision // empty') +[ -n "$REV" ] && ok "existing client carries a binding revision" || bad "no binding revision in $(printf %s "$BODY" | head -c 200)" +admin POST "/oauth/authorizations/$RID/approve" -d '{"client":{"id":"vscode"},"binding_revision":"stale-revision"}' +eq "stale binding revision refused" 409 "$CODE" +has "binding_changed" "$BODY" "binding_changed" +admin POST "/oauth/authorizations/$RID/approve" -d '{"client":{"id":"other"}}' +eq "a client other than the address' client refused" 422 "$CODE" +has "client_fixed" "$BODY" "client_fixed" +admin POST "/oauth/authorizations/$RID/approve" -d "{\"client\":{\"id\":\"vscode\"},\"binding_revision\":\"$REV\"}" +eq "approve with the current revision" 200 "$CODE" +stop_proxy +# require_mcp_auth off: a named profile must be refused (the client could bypass it on /mcp) +write_config false +start_proxy true || { bad "core did not restart"; tail -20 "$WORK/proxy.log"; exit 1; } +register "Acme" +authorize "$CID" /mcp/oauth +admin GET "/oauth/authorizations/$RID" +eq "generic address kind" generic "$(printf %s "$BODY" | jq -r .data.address_kind)" +admin POST "/oauth/authorizations/$RID/preview" -d '{"client":{"new":{"id":"acme","display_name":"Acme"}},"profile":"dev","mode":"locked"}' +has "preview shows the guard verdict" "$BODY" "binding_bypassable_without_auth" +admin POST "/oauth/authorizations/$RID/approve" -d '{"client":{"new":{"id":"acme","display_name":"Acme"}},"profile":"dev","mode":"locked"}' +eq "named profile with require_mcp_auth off refused" 409 "$CODE" +has "guard code" "$BODY" "binding_bypassable_without_auth" +admin POST "/oauth/authorizations/$RID/approve" -d '{"client":{"new":{"id":"acme","display_name":"Acme"}},"profile":"nope","mode":"locked"}' +eq "unknown profile" 404 "$CODE" +approve "$RID" '{"client":{"new":{"id":"acme","display_name":"Acme"}},"profile":"","mode":"switchable"}' +eq "all-servers access is allowed" 200 "$CODE" +exchange "$CID" "$CODE_VAL" /mcp/oauth +eq "generic-address exchange" 200 "$CODE" +mcp_init "$B/mcp/oauth" "$AT" +[ -n "$SID" ] && ok "login on the generic address works" || bad "generic address refused the new login (HTTP $CODE)" +admin GET "/clients/acme" +eq "the new client exists with its login" browser_login "$(printf %s "$BODY" | jq -r '.data.credentials[0].kind // empty')" +mcp_post "$B/mcp/oauth/acme" "$INIT" -H "Authorization: Bearer $AT" +eq "generic-address token on the acme address" 401 "$CODE" + +step "9b. rate limits" +NO_RETRY=1 +GOT429="" +for _ in $(seq 1 25); do + req POST "$B/oauth/register" -H 'Content-Type: application/json' -d '{}' + if [ "$CODE" = 429 ]; then GOT429=1; break; fi +done +NO_RETRY=0 +[ -n "$GOT429" ] && ok "registration is rate limited (429)" || bad "no 429 after 25 registrations" +case "$(hdr Retry-After)" in '' | *[!0-9]*) bad "429 without a numeric Retry-After" ;; *) ok "429 carries Retry-After" ;; esac +stop_proxy + +############################################################################# +step "10. off after use" +write_config true +start_proxy false || { bad "core did not restart"; tail -20 "$WORK/proxy.log"; exit 1; } +req POST "$B/mcp/oauth/vscode" -H "Authorization: Bearer $AT_Z" -H 'Content-Type: application/json' -d "$INIT" +eq "OAuth MCP address is 404 after use" 404 "$CODE" +req GET "$B/.well-known/oauth-authorization-server" +eq "AS metadata 404" 404 "$CODE" +req GET "$B/.well-known/oauth-protected-resource/mcp/oauth/vscode" +eq "protected-resource metadata 404" 404 "$CODE" +req POST "$B/oauth/register" -H 'Content-Type: application/json' -d "{\"redirect_uris\":[\"$RU\"]}" +eq "registration 404" 404 "$CODE" +req GET "$B/oauth/authorize?response_type=code&client_id=x" +eq "authorize 404" 404 "$CODE" +req POST "$B/oauth/token" -d grant_type=refresh_token -d refresh_token=x -d client_id=x +eq "token endpoint 404" 404 "$CODE" +admin GET "/oauth/authorizations" +eq "admin request list 404 feature_disabled" 404 "$CODE" +req POST "$B/mcp" -H "X-API-Key: $API_KEY" -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' -d "$INIT" +eq "API-key /mcp still works" 200 "$CODE" +admin GET "/clients/vscode" +eq "browser_login_disabled true while off after use" true "$(printf %s "$BODY" | jq -r .data.browser_login_disabled)" +eq "the login is still listed" active "$(printf %s "$BODY" | jq -r '[.data.credentials[]? | select(.kind=="browser_login")][0].state // empty')" +stop_proxy + +############################################################################# +step "11. on again" +start_proxy true || { bad "core did not restart"; tail -20 "$WORK/proxy.log"; exit 1; } +mcp_post "$B/mcp/oauth/vscode" "$INIT" -H "Authorization: Bearer $AT_Z" +eq "the surviving login works again" 200 "$CODE" +req GET "$B/.well-known/oauth-authorization-server" +eq "AS metadata served again" 200 "$CODE" +admin GET "/clients/vscode" +eq "browser_login_disabled false again" false "$(printf %s "$BODY" | jq -r .data.browser_login_disabled)" +stop_proxy + +############################################################################# +echo +echo "passed: $PASS failed: $FAIL" +if [ "$FAIL" -ne 0 ]; then + echo "last core log lines:" + tail -15 "$WORK/proxy.log" | mask + exit 1 +fi +echo "OK" diff --git a/specs/132-client-oauth-login/verification/real-clients.md b/specs/132-client-oauth-login/verification/real-clients.md new file mode 100644 index 000000000..65efce7c5 --- /dev/null +++ b/specs/132-client-oauth-login/verification/real-clients.md @@ -0,0 +1,53 @@ +# Real-client check (Spec 132, T044, research R13) + +Date: 2026-11-23. Build: `feat/client-oauth-login-e2e` (slices 1a-1e), scratch core on `127.0.0.1:19551`, scratch data dir, `mcp_oauth_enabled` on, plain HTTP. + +**Constraint of this run:** no real client's configuration was touched and no human was present. The consent step was done through the admin REST (`approve`), not a browser page (there is none in PR-1). + +## Result summary + +| Client | Status | Evidence | +|---|---|---| +| MCP TypeScript SDK 1.32.2 (`@modelcontextprotocol/sdk`, the OAuth client code that MCP clients build on), driven by `sdk-client.mjs` | **VERIFIED** over plain HTTP | below | +| MCP Inspector CLI 2.13.0 | **NOT verified** | it needs a TTY and a browser for OAuth (`auth_required: Interactive OAuth requires a TTY ... or MCP_AUTO_OPEN_ENABLED=true`); a pty wrapper produced no request to the core within 20 s; not pursued further | +| Claude Code | **NOT verified** | needs `claude mcp add` / config edits and an interactive browser step | +| Cursor | **NOT verified** | needs its real config and a GUI | +| VS Code | **NOT verified** | needs its real settings and a GUI | + +`SupportsBrowserLogin` (PR-3) must stay unset for Claude Code, Cursor and VS Code until the manual checklist below is done for each. Note: the SDK result shows the server side works over plain HTTP for a standards-following client; it does not prove that any of the products above accepts an `http://127.0.0.1` issuer. + +## SDK client observations (`node sdk-client.mjs
`) + +Run against `/mcp/oauth/cursor` (redirect `http://127.0.0.1:54321/callback`), `/mcp/oauth` (redirect `http://localhost:54322/callback`) and `/mcp/oauth/claude-code` (redirect `http://localhost:54323/callback`). All three completed: discovery, registration, authorize, (admin) approve, exchange, `initialize` + `tools/list` (10 tools), and a refresh. + +Request order the SDK sent, identical for each address: + +1. `POST
` (`initialize`, no token) -> `401` with the `WWW-Authenticate` challenge. +2. `GET /.well-known/oauth-protected-resource/mcp/oauth[/]` -> `200` (it used the **per-address** metadata path, taken from the challenge). +3. `GET /.well-known/oauth-authorization-server` -> `200`. +4. `POST /oauth/register` -> `201`. Body: `client_name`, `redirect_uris`, `grant_types: [authorization_code, refresh_token]`, `response_types: [code]`, `token_endpoint_auth_method: none`. No `software_id`. +5. Authorize URL parameters: `response_type=code`, `client_id`, `code_challenge`, `code_challenge_method=S256`, `redirect_uri`, **`resource=/mcp/oauth[/]`**. It sent **no `state` and no `scope`**. +6. `POST /oauth/token` (`authorization_code`) with `code`, `code_verifier`, `redirect_uri`, **`resource`**, `client_id` -> `200`, `token_type: Bearer`, `expires_in: 3600`, refresh token present. +7. Session: `initialize` -> `200`, `notifications/initialized` -> `202`, `GET` SSE stream `200`, `tools/list` -> `200`. +8. With an invalid access token the SDK re-ran steps 1-3 (metadata fetched again), refreshed with `grant_type=refresh_token` + `resource` + `client_id` -> `200`, and continued. + +Findings that matter for the design: + +- The SDK **sends `resource`** on authorize, exchange and refresh, and the value equals the address it connected to (per-client path included). The per-client protected-resource metadata path is followed. +- Redirect URI shapes registered: `http://127.0.0.1:/callback` and `http://localhost:/callback`; both accepted. +- The sanitised reported name is lower-cased (`Cursor IDE` -> `cursor ide`); the consent request shows it as the unverified name. +- `initialize` `clientInfo.name` is recorded as `observed_name` on the login. +- Not exercised: a client that sends `state` (the script and the e2e script do), a client that omits `resource`. + +## Manual checklist (needs a human, not done) + +For each of Claude Code, Cursor, VS Code, MCP Inspector (web UI), with a scratch core (`MCPPROXY_MCP_OAUTH_ENABLED=true ./mcpproxy serve --listen 127.0.0.1:18080 --data-dir "$(mktemp -d)"`) and the client configured with `http://127.0.0.1:18080/mcp/oauth/` (back up the client config first): + +1. Start the client; does it show a sign-in step instead of failing on the 401? +2. In the core log or with `GET /api/v1/oauth/authorizations`, note: name it registered (`reported_name`), redirect URI shape, whether `resource` was sent, and the metadata URLs it fetched in order. +3. Approve with `POST /api/v1/oauth/authorizations//approve`; does the client finish and list tools? +4. Leave it past access-token expiry (1 h) or revoke the access token path by restarting the client; does it refresh without a new browser step? +5. Revoke the login (`DELETE /api/v1/clients//logins/`); does the client prompt to sign in again? +6. Record: accepts an `http://127.0.0.1` issuer (yes/no), follows per-client metadata (yes/no). + +If none of the four accepts a plain-HTTP loopback issuer, stop before PR-2 (research R13 fallback: serve the OAuth endpoints only when local TLS is on). diff --git a/specs/132-client-oauth-login/verification/sdk-client.mjs b/specs/132-client-oauth-login/verification/sdk-client.mjs new file mode 100644 index 000000000..38c1fab89 --- /dev/null +++ b/specs/132-client-oauth-login/verification/sdk-client.mjs @@ -0,0 +1,90 @@ +// Self-contained MCP SDK OAuth client for the Spec 132 T044 check. Not a real client's +// config: it only runs against the scratch core given by BASE/KEY. The browser step is +// replaced by the admin REST approve call (no human here). +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; +import { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js'; + +const BASE = process.env.BASE; +const KEY = process.env.KEY; +const ADDR = process.argv[2]; // e.g. /mcp/oauth/cursor +const REDIRECT = process.argv[3] || 'http://127.0.0.1:54321/callback'; +const NAME = process.argv[4] || 'sdk-client'; +const mask = (s) => String(s).replace(/mcp_o[ar]t_[A-Za-z0-9_-]+/g, '').replace(/(code_verifier|code|refresh_token)=[^&\s"]+/g, '$1='); + +let info, tokens, verifier, authCode; +const log = (...a) => console.log(...a); + +const loggedFetch = async (url, init = {}) => { + const u = String(url); + const body = init.body ? mask(init.body instanceof URLSearchParams ? init.body.toString() : init.body) : ''; + const res = await fetch(url, init); + log(` ${init.method || 'GET'} ${mask(u)} -> ${res.status}${body ? ' body: ' + body.slice(0, 300) : ''}`); + return res; +}; + +const provider = { + get redirectUrl() { return REDIRECT; }, + get clientMetadata() { + return { + client_name: NAME, + redirect_uris: [REDIRECT], + grant_types: ['authorization_code', 'refresh_token'], + response_types: ['code'], + token_endpoint_auth_method: 'none', + }; + }, + clientInformation: () => info, + saveClientInformation: (i) => { info = i; log(' saved client registration, client_id present:', !!i.client_id); }, + tokens: () => tokens, + saveTokens: (t) => { tokens = t; log(' saved tokens: token_type=%s expires_in=%s refresh=%s', t.token_type, t.expires_in, !!t.refresh_token); }, + saveCodeVerifier: (v) => { verifier = v; }, + codeVerifier: () => verifier, + redirectToAuthorization: async (authUrl) => { + log(' authorize URL params:', mask(JSON.stringify(Object.fromEntries(authUrl.searchParams)))); + const r = await fetch(authUrl, { redirect: 'manual' }); + const loc = r.headers.get('location'); + log(' authorize ->', r.status, mask(loc)); + const rid = new URL(loc).searchParams.get('request'); + const a = await fetch(`${BASE}/api/v1/oauth/authorizations/${rid}`, { headers: { 'X-API-Key': KEY } }); + const aj = await a.json(); + log(' consent request: reported_name=%s address_kind=%s resource=%s', aj.data.reported_name, aj.data.address_kind, aj.data.resource); + const body = aj.data.address_kind === 'generic' + ? { client: { new: { id: 'sdk-client', display_name: 'SDK client' } }, mode: 'switchable', profile: '' } + : { client: { id: aj.data.client.id }, mode: 'switchable', profile: '', ...(aj.data.client.binding ? { binding_revision: aj.data.client.binding.revision } : {}) }; + const p = await fetch(`${BASE}/api/v1/oauth/authorizations/${rid}/approve`, { method: 'POST', headers: { 'X-API-Key': KEY, 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); + const pj = await p.json(); + log(' approve (admin REST, no browser) ->', p.status); + authCode = new URL(pj.data.redirect_url).searchParams.get('code'); + }, +}; + +const mk = () => new StreamableHTTPClientTransport(new URL(BASE + ADDR), { authProvider: provider, fetch: loggedFetch }); +let transport = mk(); +let client = new Client({ name: NAME, version: '1.0.0' }); +try { + await client.connect(transport); + log('connected without auth?!'); +} catch (e) { + if (!(e instanceof UnauthorizedError)) { log('connect error:', e.message); process.exit(1); } + log('UnauthorizedError -> finishing auth with code'); +} +await transport.finishAuth(authCode); +transport = mk(); +client = new Client({ name: NAME, version: '1.0.0' }); +await client.connect(transport); +const tl = await client.listTools(); +log('tools/list OK:', tl.tools.map((t) => t.name).join(',')); +// refresh through the SDK path: expire the token locally and call again +tokens = { ...tokens, access_token: 'expired' }; +transport = mk(); +client = new Client({ name: NAME, version: '1.0.0' }); +try { + await client.connect(transport); + const tl2 = await client.listTools(); + log('after bad access token, SDK refreshed and tools/list OK:', tl2.tools.length, 'tools'); +} catch (e) { + log('after bad access token: error', e.constructor.name, e.message); +} +await client.close(); +process.exit(0); diff --git a/website/sidebars.js b/website/sidebars.js index 2c1dc5fa6..b3fc3d256 100644 --- a/website/sidebars.js +++ b/website/sidebars.js @@ -150,6 +150,7 @@ const sidebars = { items: [ 'features/oauth-authentication', 'features/oauth-token-encryption', + 'features/client-oauth-login', 'features/auth-broker', 'features/idp-token-storage', ], From b62f5080a8128ce62c0eac2979de5f9e015738e0 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 05:47:53 +0200 Subject: [PATCH 22/42] test(oauth): harden the browser-login e2e script, correct docs (Spec 132 PR-1f) Related #1971 --- CLAUDE.md | 2 +- docs/configuration/config-file.md | 2 +- docs/features/client-oauth-login.md | 17 ++- scripts/test-client-oauth-e2e.sh | 105 ++++++++++++++---- .../verification/real-clients.md | 2 +- .../verification/sdk-client.mjs | 17 ++- 6 files changed, 109 insertions(+), 36 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 0396e2b8a..297492d34 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -146,7 +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-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 (nothing is created until a login is stored). No consent page yet (PR-2). Gate: `scripts/test-client-oauth-e2e.sh`. Docs: `docs/features/client-oauth-login.md`. **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.** - 125-skills-over-mcp (PR-3): Go 1.26, backend + CLI + docs — approved skills reach agents through three read-only built-ins, registered only while `enable_skills` is on (`MCPProxyServer.RefreshSkillsAvailability`: default registry, call-tool, code-execution and direct surfaces; never `/mcp/s/`, never from `code_execution`): `retrieve_skills(query, limit)`, `load_skill(id, offset, limit, version)`, `read_skill_file(id, path, offset, limit, version)` (`internal/server/mcp_skills.go`). Everything comes from the approved copy through `Runtime.AvailableSkill` / `AvailableSkillFile` / `SearchAvailableSkills` (`internal/runtime/skills_agent.go`); one refusal `skill not found: ` for every unavailable reason; reach = `resolveActiveProfileWithSource` → `serverInScope`, tool policy not applied. Search: memory-only Bleve in `internal/skills/index`, one index per reach, every match re-checked against its record. Paging: parts of ≤60,000 bytes with `Version:` in the header. Output policy (`mcp_skills_output.go`): block/redact/strip on the whole file before paging, also on names, descriptions and file names; skills build a detector when a policy is switched on after start. Activity type `skill_access` (administrator-only, like `skill_quarantine_change`). Scoped REST: `GET /api/v1/servers/{id}/skills{,/content}` answer an agent token with available skills from the approved copy through the same policy. Records of skills a listing did not name are bounded (200 per server). Docs: `docs/features/skills.md` "Skills for agents". **No new dependencies.** diff --git a/docs/configuration/config-file.md b/docs/configuration/config-file.md index b52cbe19c..8b3df60ef 100644 --- a/docs/configuration/config-file.md +++ b/docs/configuration/config-file.md @@ -64,7 +64,7 @@ MCPProxy uses a JSON configuration file located at `~/.mcpproxy/mcp_config.json` | `trusted_proxies` | string[] | `[]` (trust nobody) | CIDRs or IP addresses whose `X-Forwarded-For`, `X-Real-IP`, `X-Forwarded-Proto` and `X-Forwarded-Host` headers are believed. Headers from any other peer are ignored and the direct `RemoteAddr` is used. Env `MCPPROXY_TRUSTED_PROXIES` (comma list). Live (hot-reload, no restart). Validation: `trusted_proxies[N] "value" is not a valid CIDR or IP address` — refused identically at boot, `PATCH /api/v1/config` and `/config/apply`. See [Reverse Proxy Deployment](/operations/reverse-proxy#trusted_proxies-forwarded-headers) | | `require_mcp_auth` | boolean | `false` | Require an API key on the `/mcp` endpoint (off by default for client compatibility). Enable when exposing MCPProxy beyond localhost. **Server edition:** forced to `true` whenever `server_edition.enabled` is `true` — an explicit `false` is not an error, but boot logs `require_mcp_auth: false is overridden to true because server_edition.enabled is true` and `mcpproxy doctor` reports the same finding | | `mcp_reject_query_apikey` | boolean | `false` | Refuse a `?apikey=` query parameter on every MCP endpoint (`/mcp*` and the legacy `/v1/tool_code` aliases) with a 401, forcing clients onto `Authorization: Bearer ` or `X-API-Key` so tokens stop appearing in access logs, proxy logs and browser history (a URL already sent is still logged in transit; the option makes the client fail until it is migrated). MCP endpoints only: the REST API, the Web UI and `/events` keep accepting the query form. Entries written by an older Connect wizard with `?apikey=` in the URL (Codex, the generic fallback) must be reconnected first; current versions write an `X-API-Key` header. Live, no restart | -| `mcp_oauth_enabled` | boolean | `false` | Experimental. Opt-in browser login (OAuth 2.1 + PKCE) for MCP clients, served only to loopback peers and loopback `Host` values, personal edition only. With it off nothing changes: no new route behaves differently and nothing is stored. Env `MCPPROXY_MCP_OAUTH_ENABLED=true\|false` overrides it for the process (never persisted). Live, no restart. Backend and administrator REST only for now (no consent page): see [Browser Login for MCP Clients](../features/client-oauth-login.md) | +| `mcp_oauth_enabled` | boolean | `false` | Experimental. Opt-in browser login (OAuth 2.1 + PKCE) for MCP clients, served only to loopback peers and loopback `Host` values, personal edition only. With it off and never used nothing changes: no new route behaves differently and nothing is stored. After a login was stored, off means the OAuth paths answer `404`, the stored records are kept and pending sign-in requests are cancelled. Env `MCPPROXY_MCP_OAUTH_ENABLED=true\|false` overrides it for the process (never persisted). Live, no restart. Backend and administrator REST only for now (no consent page): see [Browser Login for MCP Clients](../features/client-oauth-login.md) | | `enable_socket` | boolean | `true` | Enable the Unix socket/named pipe the tray uses. Socket connections are trusted **without the API key**, including stdio servers spawned under `none` or `sandbox` isolation, which can then mint agent tokens. Set `false` on headless installs and whenever untrusted stdio servers run outside `docker` isolation. | | `forward_client_headers` | boolean | `true` | Master switch for [client header forwarding](/configuration/upstream-servers#client-header-forwarding). Nothing is forwarded until a server lists names in `forward_headers`. Env `MCPPROXY_FORWARD_CLIENT_HEADERS=false` disables it for the process (never persisted). | diff --git a/docs/features/client-oauth-login.md b/docs/features/client-oauth-login.md index f739c902a..7bb497314 100644 --- a/docs/features/client-oauth-login.md +++ b/docs/features/client-oauth-login.md @@ -37,8 +37,12 @@ personal edition (`mcpproxy`); the server edition answers `404` on all of these or `MCPPROXY_MCP_OAUTH_ENABLED=true` for one process (never persisted). The setting is read live, so a config change needs no restart; the environment variable is read at start. -With the setting off and never used, nothing changes: the OAuth paths behave as they did -before, and no storage bucket is created. `scripts/test-client-oauth-e2e.sh` checks both. +With the setting off **and never used**, nothing changes: the OAuth paths behave as they did +before, and no storage bucket is created. Once the feature has been on, records exist (a +client registration is stored as soon as a client registers, before any login), so "off" then +means the OAuth paths answer `404` and the records are kept (see [Turning it off](#turning-it-off)). +`scripts/test-client-oauth-e2e.sh` checks the off-and-never-used case before it switches the +feature on. ## Addresses @@ -86,8 +90,9 @@ curl -s -X POST -H "X-API-Key: $KEY" -H 'Content-Type: application/json' \ ``` The answer is `{"data":{"redirect_url":"..."}}`; the client receives the code when its -browser is sent there. Approval stores nothing: the login is stored when the client -exchanges the code, after the binding and guard are checked again. `.../deny` ends the +browser is sent there. Approval writes an audit activity row but stores no login and no +binding: the login is stored when the client exchanges the code, after the binding and guard +are checked again. (The client's registration was already stored when it registered.) `.../deny` ends the request with `access_denied`; `.../preview` shows the guard verdict without writing. Full contract: [REST API](../api/rest-api.md). @@ -108,8 +113,8 @@ is off after use. API-key access is never affected. A login can still be revoked ## Downgrade -Browser-login records live in their own storage buckets, created only when the first login -is stored. A binary that does not know the feature does not serve the OAuth paths, so the +Browser-login records live in their own storage buckets, created lazily on the first write +(a client registration, then the first stored login). A binary that does not know the feature does not serve the OAuth paths, so the logins simply stop being usable. ## Plain HTTP diff --git a/scripts/test-client-oauth-e2e.sh b/scripts/test-client-oauth-e2e.sh index 2fcb8cc4d..be96b4d9e 100755 --- a/scripts/test-client-oauth-e2e.sh +++ b/scripts/test-client-oauth-e2e.sh @@ -5,7 +5,7 @@ # There is no browser: the consent step is done through the admin REST # (/api/v1/oauth/authorizations/{id}/approve), as PR-1 ships no consent page. # -# 1. default off -> OAuth paths are not served, nothing is written to config.db +# 1. off and never used -> OAuth paths are not served, no OAuth bucket in config.db (only for off AND never used) # 2. on: discovery -> 401 challenge + both metadata documents, unknown client 404 # 3. register / authorize -> RFC 7591 registration, authorize redirect, bad requests # 4. approve / token -> admin approve, deny, double approve, PKCE exchange, code reuse @@ -25,12 +25,17 @@ set -uo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +# The only MCPPROXY_* variable this script reads is MCPPROXY_BIN. Every other MCPPROXY_* / +# MCPP_* variable (data dir, listen, API key, TLS, ...) is an instance override the core would +# read, so drop them all: the scratch core must not be steered at a real installation. +BIN_OVERRIDE="${MCPPROXY_BIN:-}" +while IFS= read -r v; do unset "$v"; done < <(compgen -e | grep -E '^(MCPPROXY_|MCPP_)') WORK="$(mktemp -d)" PORT="${PORT:-19561}" API_KEY="e2e-client-oauth-key" DATA="$WORK/data" HOME_DIR="$WORK/home" -BIN="${MCPPROXY_BIN:-$WORK/mcpproxy}" +BIN="${BIN_OVERRIDE:-$WORK/mcpproxy}" B="http://127.0.0.1:$PORT" API="$B/api/v1" RU="http://127.0.0.1:54321/callback" @@ -61,11 +66,13 @@ hasnt() { case "$2" in *"$3"*) bad "$1 (found '$3')" ;; *) ok "$1" ;; esac; } mask() { sed -E 's/mcp_o[ar]t_[A-Za-z0-9_-]+//g'; } mkdir -p "$DATA" "$HOME_DIR" -if [ -z "${MCPPROXY_BIN:-}" ]; then +DATA_REAL="$(cd "$DATA" && pwd -P)" +case "$DATA" in "$WORK"/*) ;; *) echo "refusing to run: data dir $DATA is not under the scratch dir $WORK"; exit 2 ;; esac +if [ -z "$BIN_OVERRIDE" ]; then echo "building mcpproxy" (cd "$ROOT" && go build -o "$BIN" ./cmd/mcpproxy) || { echo "build failed"; exit 2; } fi -if curl -s -o /dev/null "http://127.0.0.1:$PORT/"; then echo "port $PORT is in use"; exit 2; fi +if curl -s --connect-timeout 2 --max-time 5 -o /dev/null "http://127.0.0.1:$PORT/"; then echo "port $PORT is in use"; exit 2; fi # write_config REQUIRE_MCP_AUTH write_config() { @@ -91,11 +98,25 @@ start_proxy() { case "$1" in true | false) envv=(MCPPROXY_MCP_OAUTH_ENABLED="$1") ;; esac - env -u MCPPROXY_MCP_OAUTH_ENABLED HOME="$HOME_DIR" MCPPROXY_TELEMETRY=false "${envv[@]+"${envv[@]}"}" \ - "$BIN" serve --config "$WORK/config.json" >>"$WORK/proxy.log" 2>&1 & + # Data dir and listen address are passed explicitly as well as in the config file. + env HOME="$HOME_DIR" MCPPROXY_TELEMETRY=false "${envv[@]+"${envv[@]}"}" \ + "$BIN" serve --config "$WORK/config.json" --data-dir "$DATA" --listen "127.0.0.1:$PORT" >>"$WORK/proxy.log" 2>&1 & PROXY_PID=$! for _ in $(seq 1 100); do - curl -sf -H "X-API-Key: $API_KEY" "$API/status" >/dev/null && return 0 + if curl -sf --connect-timeout 2 --max-time 5 -H "X-API-Key: $API_KEY" "$API/status" >/dev/null; then + # the core must be keeping its database in the scratch dir + [ -s "$DATA/config.db" ] || { echo "core is up but $DATA/config.db is missing: not using the scratch data dir"; return 1; } + # and the process we started must hold exactly that file open (a real instance may be running) + if command -v lsof >/dev/null; then + local held + held=$(lsof -nP -p "$PROXY_PID" 2>/dev/null | awk '/config\.db$/ {print $NF}' | head -1) + case "$held" in + "$DATA_REAL"/config.db) ;; + *) echo "core opened '$held', not $DATA_REAL/config.db: aborting"; return 1 ;; + esac + fi + return 0 + fi kill -0 "$PROXY_PID" 2>/dev/null || return 1 sleep 0.2 done @@ -116,9 +137,12 @@ req() { local m="$1" u="$2" shift 2 for _ in 1 2 3; do - CODE=$(curl -s -o "$WORK/body" -D "$WORK/hdrs" -w '%{http_code}' -X "$m" "$u" "$@") + : > "$WORK/body"; : > "$WORK/hdrs" + CODE=$(curl -s --connect-timeout 5 --max-time 30 -o "$WORK/body" -D "$WORK/hdrs" -w '%{http_code}' -X "$m" "$u" "$@") BODY=$(cat "$WORK/body") HDRS=$(tr -d '\r' < "$WORK/hdrs") + # A transport failure (HTTP 000) is a failure of its own, never a quiet pass of a negative check. + [ "$CODE" != 000 ] || { bad "transport failure: $m ${u%%\?*} (curl could not complete)"; return 0; } [ "$CODE" = 429 ] && [ "$NO_RETRY" != 1 ] || return 0 sleep "$(hdr Retry-After | grep -E '^[0-9]+$' || echo 5)" done @@ -193,27 +217,44 @@ full_login() { step "1. default off" write_config false start_proxy unset || { bad "core did not start"; tail -20 "$WORK/proxy.log"; exit 1; } -req POST "$B/mcp/oauth/cursor" -H 'Content-Type: application/json' -d "$INIT" -eq "OAuth MCP address gives no sign-in challenge" "" "$(hdr WWW-Authenticate)" +req POST "$B/mcp/oauth/cursor" -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' -d "$INIT" +eq "OAuth MCP address answers as the /mcp catch-all (HTTP)" 200 "$CODE" +eq "...with no sign-in challenge" "" "$(hdr WWW-Authenticate)" req GET "$B/.well-known/oauth-authorization-server" -hasnt "no authorization-server metadata" "$BODY" "token_endpoint" +eq "AS metadata not served" 404 "$CODE" +hasnt "...and no authorization-server document" "$BODY" "token_endpoint" req GET "$B/.well-known/oauth-protected-resource/mcp/oauth/cursor" -hasnt "no protected-resource metadata" "$BODY" "authorization_servers" +eq "protected-resource metadata not served" 404 "$CODE" +hasnt "...and no protected-resource document" "$BODY" "authorization_servers" req POST "$B/oauth/register" -H 'Content-Type: application/json' -d "{\"redirect_uris\":[\"$RU\"]}" -[ "$CODE" != 201 ] && ok "registration not served (HTTP $CODE)" || bad "registration answered 201 while off" +eq "registration not served" 404 "$CODE" req GET "$B/oauth/authorize?response_type=code&client_id=x" -[ "$CODE" != 302 ] && ok "authorize not served (HTTP $CODE)" || bad "authorize redirected while off" +eq "authorize not served" 404 "$CODE" +req POST "$B/oauth/token" -d grant_type=refresh_token -d refresh_token=x -d client_id=x +eq "token endpoint not served" 404 "$CODE" admin GET "/oauth/authorizations" eq "admin sign-in request list is 404 while off" 404 "$CODE" has "feature_disabled code" "$BODY" "feature_disabled" admin GET "/clients" +eq "client list answers" 200 "$CODE" hasnt "client payload carries no browser-login field" "$BODY" "browser_login" req POST "$B/mcp" -H "X-API-Key: $API_KEY" -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' -d "$INIT" eq "API-key /mcp works" 200 "$CODE" stop_proxy -for bucket in oauth_registrations oauth_grants oauth_grant_access_index oauth_client_bindings oauth_login_ever_used; do - if grep -a -q -F "$bucket" "$DATA/config.db"; then bad "config.db contains $bucket while the feature never ran"; else ok "no $bucket in config.db"; fi -done +# "Nothing stored" holds for off AND never used only: a registration alone persists a row. +if [ -r "$DATA/config.db" ] && [ -s "$DATA/config.db" ]; then + ok "config.db exists and is readable ($(wc -c < "$DATA/config.db" | tr -d ' ') bytes)" + for bucket in oauth_registrations oauth_grants oauth_grant_access_index oauth_client_bindings oauth_login_ever_used; do + grep -a -q -F "$bucket" "$DATA/config.db" + case $? in + 1) ok "no $bucket in config.db" ;; + 0) bad "config.db contains $bucket while the feature never ran" ;; + *) bad "could not scan config.db for $bucket" ;; + esac + done +else + bad "config.db missing or unreadable at $DATA/config.db: cannot check the buckets" +fi ############################################################################# step "2. on: discovery" @@ -280,7 +321,7 @@ eq "fixed client id" cursor "$(printf %s "$BODY" | jq -r .data.client.id)" admin GET "/oauth/authorizations" has "pending list names the request" "$BODY" "$RID" req GET "$B/api/v1/oauth/authorizations/$RID" -[ "$CODE" = 401 ] || [ "$CODE" = 403 ] && ok "admin REST refuses a call without the key (HTTP $CODE)" || bad "admin REST answered $CODE without the key" +eq "admin REST refuses a call without the key" 401 "$CODE" approve "$RID" '{"client":{"id":"cursor"},"mode":"switchable","profile":""}' eq "approve answers 200" 200 "$CODE" [ -n "$CODE_VAL" ] && ok "approve returned a code" || bad "no code in redirect_url" @@ -322,6 +363,7 @@ exchange "$CID_A" "$CODE_VAL" /mcp/oauth/cursor eq "fresh login after the replay" 200 "$CODE" AT_C="$AT"; RT_C="$RT" admin GET "/clients/cursor" +eq "client payload answers" 200 "$CODE" GRANT_C=$(printf %s "$BODY" | jq -r '[.data.credentials[]? | select(.kind=="browser_login" and .state=="active")][0].grant_id // empty') [ -n "$GRANT_C" ] && ok "active login listed on the client (kind browser_login)" || bad "no active login on the client" eq "browser_login_disabled false while on" false "$(printf %s "$BODY" | jq -r .data.browser_login_disabled)" @@ -338,8 +380,15 @@ eq "tools/list answers 200" 200 "$CODE" NT=$(printf %s "$BODY" | jq -r '.result.tools | length' 2>/dev/null) [ "${NT:-0}" -gt 0 ] 2>/dev/null && ok "tools/list returned $NT tools" || bad "tools/list had no tools: ${BODY:0:200}" has "retrieve_tools is offered" "$BODY" "retrieve_tools" -admin GET "/clients/cursor" -eq "initialize name recorded as observed name" e2e-client "$(printf %s "$BODY" | jq -r '[.data.credentials[]? | select(.state=="active")][0].observed_name // empty')" +# observed_name is written off the request path: poll with a bounded deadline. +OBS="" +for _ in $(seq 1 50); do + admin GET "/clients/cursor" + OBS=$(printf %s "$BODY" | jq -r '[.data.credentials[]? | select(.state=="active")][0].observed_name // empty') + [ "$OBS" = e2e-client ] && break + sleep 0.2 +done +eq "initialize name recorded as observed name (polled up to 10 s)" e2e-client "$OBS" ############################################################################# step "6. wrong doors" @@ -351,7 +400,7 @@ eq "cursor token on the generic address" 401 "$CODE" req POST "$B/mcp" -H "Authorization: Bearer $AT_C" -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' -d "$INIT" eq "access token on classic /mcp (require_mcp_auth on)" 401 "$CODE" req POST "http://localhost:$PORT/mcp/oauth/cursor" -H "Authorization: Bearer $AT_C" -H 'Content-Type: application/json' -d "$INIT" -[ "$CODE" = 401 ] || [ "$CODE" = 404 ] && ok "token replayed against localhost instead of 127.0.0.1 refused (HTTP $CODE)" || bad "localhost answered $CODE" +eq "token replayed against localhost instead of 127.0.0.1 refused" 401 "$CODE" req POST "$B/mcp/oauth/cursor" -H "X-API-Key: $API_KEY" -H 'Content-Type: application/json' -d "$INIT" eq "API key header on the OAuth address" 401 "$CODE" req POST "$B/mcp/oauth/cursor?apikey=$API_KEY" -H 'Content-Type: application/json' -d "$INIT" @@ -394,7 +443,8 @@ eq "grant listed as revoked" revoked "$(printf %s "$BODY" | jq -r --arg g "$GRAN step "8. revoke one login, forget a client" full_login "Cursor again" cursor eq "fresh cursor login" 200 "$CODE" -AT_R="$AT"; CID_R="$CID"; GRANT_R="$GRANT" +AT_R="$AT"; RT_R="$RT"; CID_R="$CID"; GRANT_R="$GRANT" +[ -n "$RT_R" ] && ok "the login's real refresh token is kept for the post-revoke check" || bad "no refresh token to test with" mcp_init "$B/mcp/oauth/cursor" "$AT_R" [ -n "$SID" ] && ok "session open on the new login" || bad "could not open a session" admin DELETE "/clients/cursor/logins/$GRANT_R" @@ -403,8 +453,9 @@ mcp_post "$B/mcp/oauth/cursor" '{"jsonrpc":"2.0","id":3,"method":"tools/list"}' eq "open session refused right after the revoke" 401 "$CODE" mcp_post "$B/mcp/oauth/cursor" "$INIT" -H "Authorization: Bearer $AT_R" eq "new session refused after the revoke" 401 "$CODE" -refresh "$CID_R" "none" /mcp/oauth/cursor -eq "refresh refused after the revoke" 400 "$CODE" +refresh "$CID_R" "$RT_R" /mcp/oauth/cursor +eq "the real refresh token is refused after the revoke" 400 "$CODE" +has "...as invalid_grant" "$BODY" "invalid_grant" admin DELETE "/clients/cursor/logins/no-such-grant" eq "revoking an unknown login is 404" 404 "$CODE" full_login "Claude Code" claude-code @@ -508,6 +559,12 @@ eq "browser_login_disabled false again" false "$(printf %s "$BODY" | jq -r .data stop_proxy ############################################################################# +step "12. isolation and control" +# control for the phase-1 scan: after real use the same scan must find the buckets +for bucket in oauth_registrations oauth_grants oauth_client_bindings oauth_login_ever_used; do + if grep -a -q -F "$bucket" "$DATA/config.db"; then ok "$bucket present after use (the phase-1 scan can see buckets)"; else bad "$bucket missing after use"; fi +done + echo echo "passed: $PASS failed: $FAIL" if [ "$FAIL" -ne 0 ]; then diff --git a/specs/132-client-oauth-login/verification/real-clients.md b/specs/132-client-oauth-login/verification/real-clients.md index 65efce7c5..31cd87b76 100644 --- a/specs/132-client-oauth-login/verification/real-clients.md +++ b/specs/132-client-oauth-login/verification/real-clients.md @@ -29,7 +29,7 @@ Request order the SDK sent, identical for each address: 5. Authorize URL parameters: `response_type=code`, `client_id`, `code_challenge`, `code_challenge_method=S256`, `redirect_uri`, **`resource=/mcp/oauth[/]`**. It sent **no `state` and no `scope`**. 6. `POST /oauth/token` (`authorization_code`) with `code`, `code_verifier`, `redirect_uri`, **`resource`**, `client_id` -> `200`, `token_type: Bearer`, `expires_in: 3600`, refresh token present. 7. Session: `initialize` -> `200`, `notifications/initialized` -> `202`, `GET` SSE stream `200`, `tools/list` -> `200`. -8. With an invalid access token the SDK re-ran steps 1-3 (metadata fetched again), refreshed with `grant_type=refresh_token` + `resource` + `client_id` -> `200`, and continued. +8. (Re-run 2026-11-23 with the hardened harness: it now exits non-zero unless a `refresh_token` grant answered 200, the access token changed and a following `tools/list` returned tools. All three addresses exited 0 with that proof.) With an invalid access token the SDK re-ran steps 1-3 (metadata fetched again), refreshed with `grant_type=refresh_token` + `resource` + `client_id` -> `200`, and continued. Findings that matter for the design: diff --git a/specs/132-client-oauth-login/verification/sdk-client.mjs b/specs/132-client-oauth-login/verification/sdk-client.mjs index 38c1fab89..0200bfadb 100644 --- a/specs/132-client-oauth-login/verification/sdk-client.mjs +++ b/specs/132-client-oauth-login/verification/sdk-client.mjs @@ -12,13 +12,14 @@ const REDIRECT = process.argv[3] || 'http://127.0.0.1:54321/callback'; const NAME = process.argv[4] || 'sdk-client'; const mask = (s) => String(s).replace(/mcp_o[ar]t_[A-Za-z0-9_-]+/g, '').replace(/(code_verifier|code|refresh_token)=[^&\s"]+/g, '$1='); -let info, tokens, verifier, authCode; +let info, tokens, verifier, authCode, refreshOK = false; const log = (...a) => console.log(...a); const loggedFetch = async (url, init = {}) => { const u = String(url); const body = init.body ? mask(init.body instanceof URLSearchParams ? init.body.toString() : init.body) : ''; const res = await fetch(url, init); + if (u.endsWith('/oauth/token') && body.includes('grant_type=refresh_token') && res.status === 200) refreshOK = true; log(` ${init.method || 'GET'} ${mask(u)} -> ${res.status}${body ? ' body: ' + body.slice(0, 300) : ''}`); return res; }; @@ -76,15 +77,25 @@ await client.connect(transport); const tl = await client.listTools(); log('tools/list OK:', tl.tools.map((t) => t.name).join(',')); // refresh through the SDK path: expire the token locally and call again +const before = tokens.access_token; tokens = { ...tokens, access_token: 'expired' }; +refreshOK = false; transport = mk(); client = new Client({ name: NAME, version: '1.0.0' }); +let failed = ''; try { await client.connect(transport); const tl2 = await client.listTools(); - log('after bad access token, SDK refreshed and tools/list OK:', tl2.tools.length, 'tools'); + if (!refreshOK) failed = 'no successful refresh_token response was seen'; + else if (!tokens.access_token || tokens.access_token === 'expired' || tokens.access_token === before) failed = 'refresh did not yield a new access token'; + else if (!tl2.tools.length) failed = 'tools/list after refresh returned no tools'; + else log('refresh OK (200 on refresh_token grant, new access token) and tools/list OK:', tl2.tools.length, 'tools'); } catch (e) { - log('after bad access token: error', e.constructor.name, e.message); + failed = `${e.constructor.name}: ${e.message}`; +} +if (failed) { + console.error('REFRESH FAILED:', failed); + process.exit(1); } await client.close(); process.exit(0); From 133210d3b8dc8b375573e46f9ef09cd91856527d Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 05:51:45 +0200 Subject: [PATCH 23/42] test(oauth): real-shaped forged tokens, isolate the manual check (Spec 132 PR-1f) Related #1971 --- docs/features/client-oauth-login.md | 10 +++--- scripts/test-client-oauth-e2e.sh | 36 +++++++++++++++++-- .../verification/real-clients.md | 18 ++++++++-- 3 files changed, 54 insertions(+), 10 deletions(-) diff --git a/docs/features/client-oauth-login.md b/docs/features/client-oauth-login.md index 7bb497314..d61ac870d 100644 --- a/docs/features/client-oauth-login.md +++ b/docs/features/client-oauth-login.md @@ -38,11 +38,11 @@ or `MCPPROXY_MCP_OAUTH_ENABLED=true` for one process (never persisted). The sett read live, so a config change needs no restart; the environment variable is read at start. With the setting off **and never used**, nothing changes: the OAuth paths behave as they did -before, and no storage bucket is created. Once the feature has been on, records exist (a -client registration is stored as soon as a client registers, before any login), so "off" then -means the OAuth paths answer `404` and the records are kept (see [Turning it off](#turning-it-off)). -`scripts/test-client-oauth-e2e.sh` checks the off-and-never-used case before it switches the -feature on. +before, and no storage bucket is created. A client registration is stored as soon as a client registers, but that does not change what +"off" means. The boundary is the first stored **login** (an authorization code exchanged for +tokens): from then on, off means the OAuth paths answer `404` and the records are kept (see +[Turning it off](#turning-it-off)). `scripts/test-client-oauth-e2e.sh` checks off-and-never-used +before it switches the feature on, and that "on, register only, off" still behaves as before. ## Addresses diff --git a/scripts/test-client-oauth-e2e.sh b/scripts/test-client-oauth-e2e.sh index be96b4d9e..b9126d696 100755 --- a/scripts/test-client-oauth-e2e.sh +++ b/scripts/test-client-oauth-e2e.sh @@ -256,6 +256,26 @@ else bad "config.db missing or unreadable at $DATA/config.db: cannot check the buckets" fi +############################################################################# +step "1b. on, register only, off again" +# A registration alone persists a row but is not a stored login: the ever-used marker is set at +# token exchange, so off must still behave as before (not 404). +write_config true +start_proxy true || { bad "core did not start"; tail -20 "$WORK/proxy.log"; exit 1; } +register "Register only" +eq "registration while on" 201 "$CODE" +stop_proxy +grep -a -q -F oauth_registrations "$DATA/config.db" && ok "registration row persisted" || bad "no registration row persisted" +grep -a -q -F oauth_login_ever_used "$DATA/config.db" && bad "ever-used marker set by a registration alone" || ok "no ever-used marker after registration only" +write_config false +start_proxy false || { bad "core did not start"; tail -20 "$WORK/proxy.log"; exit 1; } +req POST "$B/mcp/oauth/cursor" -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' -d "$INIT" +eq "off after registration only: OAuth MCP address keeps its previous behaviour (not 404)" 200 "$CODE" +eq "...with no sign-in challenge" "" "$(hdr WWW-Authenticate)" +req POST "$B/oauth/register" -H 'Content-Type: application/json' -d "{\"redirect_uris\":[\"$RU\"]}" +eq "registration not served while off" 404 "$CODE" +stop_proxy + ############################################################################# step "2. on: discovery" write_config true @@ -407,8 +427,14 @@ req POST "$B/mcp/oauth/cursor?apikey=$API_KEY" -H 'Content-Type: application/jso eq "?apikey= on the OAuth address" 401 "$CODE" req POST "$B/mcp/oauth/cursor" -H "Authorization: Bearer $API_KEY" -H 'Content-Type: application/json' -d "$INIT" eq "admin key as bearer on the OAuth address" 401 "$CODE" -req POST "$B/mcp/oauth/cursor" -H "Authorization: Bearer mcp_oat_0000000000000000000000000000000000000000000" -H 'Content-Type: application/json' -d "$INIT" -eq "forged access token" 401 "$CODE" +# Real shape (mcp_oat_ + 43 base64url characters), wrong secret: the genuine token with its last character changed. +case "$AT_C" in *A) FLIP=B ;; *) FLIP=A ;; esac +FORGED_AT="${AT_C%?}$FLIP" +eq "forged access token keeps the real shape (same length)" "${#AT_C}" "${#FORGED_AT}" +req POST "$B/mcp/oauth/cursor" -H "Authorization: Bearer $FORGED_AT" -H 'Content-Type: application/json' -d "$INIT" +eq "forged access token (right shape, wrong secret)" 401 "$CODE" +mcp_post "$B/mcp/oauth/cursor" "$INIT" -H "Authorization: Bearer $AT_C" +eq "the genuine access token still works after the forged one" 200 "$CODE" req POST "$B/mcp" -H "X-API-Key: $API_KEY" -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' -d "$INIT" eq "API key on classic /mcp still works" 200 "$CODE" req POST "$B/mcp" -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' -d "$INIT" @@ -417,7 +443,11 @@ eq "classic /mcp without credentials refused (require_mcp_auth on)" 401 "$CODE" ############################################################################# step "7. refresh, forged refresh token, replay" GID="${RT_C#mcp_ort_}"; GID="${GID%%_*}" -FORGED="mcp_ort_${GID}_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +# Real shape, wrong MAC: the genuine token with its last (MAC) character changed, same length, so +# it passes the shape check and is refused by MAC verification. +case "$RT_C" in *A) FLIP=B ;; *) FLIP=A ;; esac +FORGED="${RT_C%?}$FLIP" +eq "forged refresh token keeps the real shape (same length)" "${#RT_C}" "${#FORGED}" refresh "$CID_A" "$FORGED" /mcp/oauth/cursor eq "forged refresh token (real grant id) refused" 400 "$CODE" has "forged is invalid_grant" "$BODY" "invalid_grant" diff --git a/specs/132-client-oauth-login/verification/real-clients.md b/specs/132-client-oauth-login/verification/real-clients.md index 31cd87b76..9165c35c9 100644 --- a/specs/132-client-oauth-login/verification/real-clients.md +++ b/specs/132-client-oauth-login/verification/real-clients.md @@ -41,13 +41,27 @@ Findings that matter for the design: ## Manual checklist (needs a human, not done) -For each of Claude Code, Cursor, VS Code, MCP Inspector (web UI), with a scratch core (`MCPPROXY_MCP_OAUTH_ENABLED=true ./mcpproxy serve --listen 127.0.0.1:18080 --data-dir "$(mktemp -d)"`) and the client configured with `http://127.0.0.1:18080/mcp/oauth/` (back up the client config first): +For each of Claude Code, Cursor, VS Code, MCP Inspector (web UI), with an isolated scratch core (below) and the client configured with `http://127.0.0.1:18080/mcp/oauth/` (back up the client config first): 1. Start the client; does it show a sign-in step instead of failing on the 401? 2. In the core log or with `GET /api/v1/oauth/authorizations`, note: name it registered (`reported_name`), redirect URI shape, whether `resource` was sent, and the metadata URLs it fetched in order. 3. Approve with `POST /api/v1/oauth/authorizations//approve`; does the client finish and list tools? -4. Leave it past access-token expiry (1 h) or revoke the access token path by restarting the client; does it refresh without a new browser step? +4. Refresh: either leave the client past real access-token expiry (1 h), or invalidate only its cached access token (as `sdk-client.mjs` does) and keep the refresh token. Restarting the client proves nothing (it may reuse the stored access token). Pass only if the core log or a proxy shows a successful `POST /oauth/token` with `grant_type=refresh_token` (200), followed by a working request, with no new browser step. 5. Revoke the login (`DELETE /api/v1/clients//logins/`); does the client prompt to sign in again? 6. Record: accepts an `http://127.0.0.1` issuer (yes/no), follows per-client metadata (yes/no). +Isolated scratch core (the same isolation as `scripts/test-client-oauth-e2e.sh`; never omit `--config`, a bare `--data-dir` can pick up a legacy `~/.mcpproxy/mcp_config.json` and save to it): + +```bash +S="$(mktemp -d)"; mkdir -p "$S/data" "$S/home" +cat > "$S/config.json" < Date: Mon, 23 Nov 2026 05:53:42 +0200 Subject: [PATCH 24/42] docs(oauth): qualify the server-edition 404 (Spec 132 PR-1f) Related #1971 --- docs/features/client-oauth-login.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/features/client-oauth-login.md b/docs/features/client-oauth-login.md index d61ac870d..9fa6cb311 100644 --- a/docs/features/client-oauth-login.md +++ b/docs/features/client-oauth-login.md @@ -26,7 +26,7 @@ What it gives you: - API keys keep working unchanged on `/mcp` and everywhere else. It is served to loopback peers and loopback `Host` values only, and only by the -personal edition (`mcpproxy`); the server edition answers `404` on all of these paths. +personal edition (`mcpproxy`). In the server edition the feature is unavailable: with the switch on, the OAuth paths answer `404`; with it off and never used, nothing changes, as in the personal edition. ## Enabling From 5c0b698c3c0d14aec606ce78cfe655d4e57c6e64 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 06:50:18 +0200 Subject: [PATCH 25/42] docs(oauth): record the Claude Code real-client check (Spec 132 PR-1f) Related #1971 --- docs/features/client-oauth-login.md | 5 +++-- .../verification/real-clients.md | 20 ++++++++++++++++--- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/docs/features/client-oauth-login.md b/docs/features/client-oauth-login.md index 9fa6cb311..5d95a384b 100644 --- a/docs/features/client-oauth-login.md +++ b/docs/features/client-oauth-login.md @@ -121,5 +121,6 @@ logins simply stop being usable. The issuer is `http://127.0.0.1:`, not HTTPS. The specifications ask for HTTPS for 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`; only the MCP -TypeScript SDK client flow is verified so far. +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). diff --git a/specs/132-client-oauth-login/verification/real-clients.md b/specs/132-client-oauth-login/verification/real-clients.md index 9165c35c9..cde46f927 100644 --- a/specs/132-client-oauth-login/verification/real-clients.md +++ b/specs/132-client-oauth-login/verification/real-clients.md @@ -10,11 +10,25 @@ Date: 2026-11-23. Build: `feat/client-oauth-login-e2e` (slices 1a-1e), scratch c |---|---|---| | MCP TypeScript SDK 1.32.2 (`@modelcontextprotocol/sdk`, the OAuth client code that MCP clients build on), driven by `sdk-client.mjs` | **VERIFIED** over plain HTTP | below | | MCP Inspector CLI 2.13.0 | **NOT verified** | it needs a TTY and a browser for OAuth (`auth_required: Interactive OAuth requires a TTY ... or MCP_AUTO_OPEN_ENABLED=true`); a pty wrapper produced no request to the core within 20 s; not pursued further | -| Claude Code | **NOT verified** | needs `claude mcp add` / config edits and an interactive browser step | +| Claude Code CLI 2.1.318 | **VERIFIED** for the login flow over plain HTTP loopback (see "Claude Code observations"); refresh, metadata order, browser callback path and in-session tool calls NOT verified | below | | Cursor | **NOT verified** | needs its real config and a GUI | | VS Code | **NOT verified** | needs its real settings and a GUI | -`SupportsBrowserLogin` (PR-3) must stay unset for Claude Code, Cursor and VS Code until the manual checklist below is done for each. Note: the SDK result shows the server side works over plain HTTP for a standards-following client; it does not prove that any of the products above accepts an `http://127.0.0.1` issuer. +`SupportsBrowserLogin` (PR-3) may be set for `claude-code` only; it must stay unset for Cursor and VS Code (and Inspector) until the manual checklist below is done for each. The SDK result alone does not prove that a product accepts an `http://127.0.0.1` issuer; the Claude Code result below does for Claude Code. + +**R13 go/no-go:** the condition "at least one of the four completes the flow over plain HTTP loopback" is MET by Claude Code. Cursor, VS Code and MCP Inspector remain unverified; keep their checklist items. + +## Claude Code observations + +Run by the main session on 2026-11-23, Claude Code CLI 2.1.318, macOS, against an isolated scratch core built from 44ac406a7 (explicit `--config`, scratch HOME, `--data-dir`, `--listen 127.0.0.1:18431`, `MCPPROXY_*` cleared, `require_mcp_auth` true, web UI off, `mcp_oauth_enabled` via env). + +- Added with `claude mcp add --scope local --transport http mcpproxy-oauth-check http://127.0.0.1:18431/mcp/oauth/claude-code` from a scratch project dir; removed afterwards (`claude mcp logout`, `claude mcp remove -s local`). +- `claude mcp login --no-browser ` needs a TTY (without one it prints the authorize URL then exits 1: "stdin isn't a terminal"). It was run under a pseudo-terminal and the redirect URL was pasted back at its "Or paste the redirect URL here:" prompt. The browser/loopback-callback path (login without `--no-browser`) was NOT exercised. +- Observed: Claude Code accepted the plain-HTTP `http://127.0.0.1` issuer; it registered dynamically (same `client_id` reused across three login attempts). The authorize request carried `response_type=code`, `code_challenge_method=S256`, `state`, `resource=http://127.0.0.1:18431/mcp/oauth/claude-code` (exactly the per-client address), `redirect_uri` `http://localhost:/callback` (host `localhost`, fixed port across attempts in this run: 65306), and no `scope`. +- Server side: authorize -> 302 `/ui/authorize?request=`; the request showed `address_kind` "client", client id `claude-code`, `reported_name` "claude code (mcpproxy-oauth-check)" (i.e. "Claude Code ()" lower-cased); approved through the admin REST with profile "" / mode switchable; the client printed 'Authenticated with "mcpproxy-oauth-check". Its tools are now available in Claude Code.' and exited 0. +- After login `claude mcp get` showed "Status: Connected"; the client row had one `browser_login` credential, state active, `redirect_host` "localhost", `observed_name` "claude-code", `name_mismatch` false, `last_used_at` set; the server log shows POST and GET (stream) requests on `/mcp/oauth/claude-code`. +- NOT verified for Claude Code: token refresh (no expiry was waited for or forced), the order of metadata requests (those endpoints are not in the request log), the real browser + loopback callback path, behaviour inside an interactive Claude Code session (tool calls), the generic `/mcp/oauth` address, Windows/Linux. +- Note printed by the client, recorded verbatim without interpretation: "[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field." ## SDK client observations (`node sdk-client.mjs
`) @@ -41,7 +55,7 @@ Findings that matter for the design: ## Manual checklist (needs a human, not done) -For each of Claude Code, Cursor, VS Code, MCP Inspector (web UI), with an isolated scratch core (below) and the client configured with `http://127.0.0.1:18080/mcp/oauth/` (back up the client config first): +For each of Cursor, VS Code, MCP Inspector (web UI) (and, for the items marked NOT verified above, Claude Code), with an isolated scratch core (below) and the client configured with `http://127.0.0.1:18080/mcp/oauth/` (back up the client config first): 1. Start the client; does it show a sign-in step instead of failing on the 401? 2. In the core log or with `GET /api/v1/oauth/authorizations`, note: name it registered (`reported_name`), redirect URI shape, whether `resource` was sent, and the metadata URLs it fetched in order. From f1183059773493251bcaa6661ceb895f887c5494 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 13:11:26 +0200 Subject: [PATCH 26/42] feat(oauth): consent page for browser login (Spec 132 PR-2a) Web UI consent page at /ui/authorize for browser sign-in requests, with the generic-address name suggestion. - suggested_client on GET /api/v1/oauth/authorizations/{id} (generic address only): the sanitised reported name, trimmed and case-insensitive, compared with each existing client's id, display name and known client names (whole name, and the part before a trailing parenthesised suffix); exactly one distinct client -> {id, matched}, none or several -> absent. Computed on read, never stored, never applied by the server: preview without a client answers complete:false, approve answers client_required. - Content-Security-Policy frame-ancestors 'none' and X-Frame-Options DENY on /ui/authorize. - AuthorizeRequest.vue, /authorize route, API methods and types: fixed or chosen client, unverified-name label, access sentence, profile shown or asked, replace-login checkbox, guard verdict through preview with fixes, no-API-key mode, already_decided / binding_changed / 404 handling. - Docs: REST reference and docs/features/client-oauth-login.md. Related #1971 --- docs/api/rest-api.md | 11 +- docs/features/client-oauth-login.md | 23 ++ frontend/src/router/index.ts | 2 + frontend/src/services/api.ts | 20 +- frontend/src/types/api.ts | 55 +++ frontend/src/utils/navigate.ts | 5 + frontend/src/views/AuthorizeRequest.vue | 381 ++++++++++++++++++ .../unit/authorize-request-nokey.spec.ts | 69 ++++ frontend/tests/unit/authorize-request.spec.ts | 280 +++++++++++++ internal/httpapi/oauth_login_test.go | 47 +++ internal/runtime/oauth_login_consent.go | 73 ++++ internal/runtime/oauth_login_suggest_test.go | 96 +++++ internal/server/oauth_login_http_test.go | 25 ++ internal/server/server.go | 13 +- 14 files changed, 1094 insertions(+), 6 deletions(-) create mode 100644 frontend/src/utils/navigate.ts create mode 100644 frontend/src/views/AuthorizeRequest.vue create mode 100644 frontend/tests/unit/authorize-request-nokey.spec.ts create mode 100644 frontend/tests/unit/authorize-request.spec.ts create mode 100644 internal/runtime/oauth_login_suggest_test.go diff --git a/docs/api/rest-api.md b/docs/api/rest-api.md index 6c8f59c20..b106b90de 100644 --- a/docs/api/rest-api.md +++ b/docs/api/rest-api.md @@ -1697,11 +1697,18 @@ reference: the Spec 132 contracts. - `GET /api/v1/oauth/authorizations`, `GET /api/v1/oauth/authorizations/{id}`: pending sign-in requests and the data the consent view needs. One uniform `404` - for an unknown, expired, decided or cancelled id. + for an unknown, expired, decided or cancelled id. On the generic address the view + may carry `suggested_client` (`{id, matched}`, `matched` is `id`, `display_name` or + `known_name`): present only when the sanitised reported name (trimmed, any case; a + trailing parenthesised suffix is also tried without it) equals exactly one existing + client's id, display name or known client name, absent otherwise and never on a + per-client address. It is advice for the page, computed on read and never stored: preview + without a `client` answers `200 {"complete": false}` (no `access`, no `guard`) and + approve without one answers `422 client_required`. - `POST /api/v1/oauth/authorizations/{id}/preview`: read-only verdict for a proposed client, profile and mode. `POST .../approve` and `POST .../deny` answer `{redirect_url}`; approve refuses with `409 already_decided`, `409 binding_changed`, - `409 binding_bypassable_without_auth`, `422 profile_required`, `client_fixed`, + `409 binding_bypassable_without_auth`, `422 client_required`, `profile_required`, `client_fixed`, `identity_exists`, `reserved_identity` and `404 profile_not_found`. - `GET /api/v1/clients` and `GET /api/v1/clients/{client}` gain `credentials[]` (the API key and each browser login: `kind`, `prefix`, `grant_id`, `state`, diff --git a/docs/features/client-oauth-login.md b/docs/features/client-oauth-login.md index 5d95a384b..e7c37f3f2 100644 --- a/docs/features/client-oauth-login.md +++ b/docs/features/client-oauth-login.md @@ -96,6 +96,29 @@ are checked again. (The client's registration was already stored when it registe request with `access_denied`; `.../preview` shows the guard verdict without writing. Full contract: [REST API](../api/rest-api.md). +### The consent page + +The request opens in the Web UI at `/ui/authorize?request=` (the page is never framed: +`frame-ancestors 'none'` and `X-Frame-Options: DENY`). It shows the name the app reports, +labelled as unverified, where the browser returns to, and one sentence on whose access is being +handed over. Everything the app reports is shown as plain text. + +- **Per-client address**: the client is fixed. A client that has a profile binding shows it, + without asking; a client with none and configured profiles needs a profile chosen before + Approve is enabled. "Replace the previous browser login" appears only when this same + registration signed in before. +- **Generic address**: the page opens with a client selected and you can change it. When the + reported name equals exactly one existing client's id, display name or known client name + (`Claude Code (my-server)` is also tried as `Claude Code`), that client is pre-selected with + the note `Suggested because the app calls itself "". MCPProxy cannot verify that.` + Otherwise "New client" is selected, with an editable id and name filled from the reported name. + The suggestion decides nothing: approval carries the client the page sent, and a request with + no client is refused (`client_required`). +- The binding guard's verdict is fetched through the preview call whenever the choice is + complete or changes; a refusal is shown with its fixes and Approve stays disabled. +- Without the admin API key in this browser the page asks you to open the request from the + MCPProxy tray or paste the key, and makes no request until then. + ## Seeing and revoking logins `GET /api/v1/clients` and `GET /api/v1/clients/` list each login under `credentials` diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts index 2cfb7d855..bc885b3a5 100644 --- a/frontend/src/router/index.ts +++ b/frontend/src/router/index.ts @@ -35,6 +35,8 @@ const router = createRouter({ title: 'Usage Analytics', }, }, + // Spec 132: consent page for a browser sign-in request (`?request=`). + { path: '/authorize', name: 'authorize', component: () => import('@/views/AuthorizeRequest.vue'), meta: { title: 'Sign-in request' } }, { path: '/clients', name: 'clients', component: () => import('@/views/Clients.vue'), meta: { title: 'Clients' } }, // Spec 108-i I4: two SIBLING top-level routes. The Spec 109-i gate on the // sidebar item, the Add menu item and the palette action compares diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts index 3fb553725..5362b8c42 100644 --- a/frontend/src/services/api.ts +++ b/frontend/src/services/api.ts @@ -1,5 +1,5 @@ import type { APIResponse, Server, Tool, ToolApproval, SearchResult, StatusUpdate, StatusResponse, SecretRef, MigrationAnalysis, ConfigSecretsResponse, GetToolCallsResponse, GetToolCallDetailResponse, GetServerToolCallsResponse, GetConfigResponse, ValidateConfigResponse, ConfigApplyResult, ServerTokenMetrics, GetRegistriesResponse, SearchRegistryServersResponse, RegistrySummary, CatalogSearchResponse, GetSessionsResponse, GetSessionDetailResponse, InfoResponse, ActivityListResponse, ActivityDetailResponse, ActivityRecord, ActivitySummaryResponse, ImportResponse, AgentTokenInfo, CreateAgentTokenRequest, CreateAgentTokenResponse, RoutingInfo, ConnectStatusResponse, ClientStatus, ConnectResult, ConnectPreview, OnboardingStateResponse, OnboardingMarkRequest, DiagnosticFixResponse, GlobalToolsResponse, UsageAggregateResponse, UsageWindow, UsageSort, UsageStatus, AttentionResponse, ReviewQueueResponse, ServerReviewResponse } from '@/types' -import type { ProfileConfig, ProfileList, ProfileView, ProfileWriteResult, ProfileRenameResult, ProfileDeleteResult, EffectiveToolsResult, TryProfileResponse, AccessExplanation, ExplainSubjectQuery, ClientView, ClientsResponse, BulkAssignResponse, CustomClientResponse, RotateResponse, UpgradePreview, UpgradeApplyResult, ForgetClientResponse, ConnectOptions, SkillsListResponse, SkillContentResponse, SkillCopy, SkillsResponse } from '@/types/api' +import type { ProfileConfig, ProfileList, ProfileView, ProfileWriteResult, ProfileRenameResult, ProfileDeleteResult, EffectiveToolsResult, TryProfileResponse, AccessExplanation, ExplainSubjectQuery, ClientView, ClientsResponse, BulkAssignResponse, CustomClientResponse, RotateResponse, UpgradePreview, UpgradeApplyResult, ForgetClientResponse, ConnectOptions, OAuthAuthorization, OAuthApprovalBody, OAuthPreview, OAuthDecision, SkillsListResponse, SkillContentResponse, SkillCopy, SkillsResponse } from '@/types/api' import { joinHoldEvidence, type HoldEvidenceSource } from '@/utils/holdEvidence' @@ -1530,6 +1530,24 @@ class APIService { return this.data(`/api/v1/clients/${encodeURIComponent(id)}${queryString({ disconnect: opts.disconnect ? 'true' : undefined })}`, { method: 'DELETE' }) } + // Spec 132 sign-in requests (administrator only). All throw an ApiError whose + // `status` and `code` the consent page branches on. + getOAuthAuthorization(id: string): Promise { + return this.data(`/api/v1/oauth/authorizations/${encodeURIComponent(id)}`) + } + + previewOAuthAuthorization(id: string, body: OAuthApprovalBody): Promise { + return this.data(`/api/v1/oauth/authorizations/${encodeURIComponent(id)}/preview`, { method: 'POST', body: JSON.stringify(body) }) + } + + approveOAuthAuthorization(id: string, body: OAuthApprovalBody): Promise { + return this.data(`/api/v1/oauth/authorizations/${encodeURIComponent(id)}/approve`, { method: 'POST', body: JSON.stringify(body) }) + } + + denyOAuthAuthorization(id: string): Promise { + return this.data(`/api/v1/oauth/authorizations/${encodeURIComponent(id)}/deny`, { method: 'POST', body: '{}' }) + } + upgradeAdminKeyHolders(body: { profile?: string; mode?: 'locked' | 'switchable'; apply?: boolean; precondition_token?: string } = {}): Promise { return this.data('/api/v1/clients/upgrade-admin-key-holders', { method: 'POST', body: JSON.stringify(body) }) } diff --git a/frontend/src/types/api.ts b/frontend/src/types/api.ts index 2aa4c8a12..9b7189f24 100644 --- a/frontend/src/types/api.ts +++ b/frontend/src/types/api.ts @@ -1569,6 +1569,61 @@ export interface BindingRef { client_id: string; token_name: string; profile: st /** One fix of a binding-guard refusal (`require_mcp_auth` | `set_anonymous_profile`). */ export interface GuardFix { kind: string; target?: string } +// --- Spec 132: browser login for MCP clients (consent page) ---------------------- +// Everything named by the app (`reported_name`, `suggested_new_client`) is +// untrusted text: render it with mustaches, never as HTML. + +export interface OAuthBindingView { profile: string; mode: string; revision: string } + +export interface OAuthAuthorizationClient { + id: string + display_name: string + exists: boolean + has_api_key: boolean + logins: number + binding?: OAuthBindingView +} + +export interface OAuthExistingClient { id: string; display_name: string; binding?: OAuthBindingView } + +export interface OAuthGuardVerdict { code: string; bindings: BindingRef[]; fixes: GuardFix[] } + +export interface OAuthAuthorization { + id: string + status: string + expires_at: string + reported_name: string + redirect_uri: string + resource: string + address_kind: 'client' | 'generic' + client?: OAuthAuthorizationClient + existing_clients?: OAuthExistingClient[] + suggested_new_client?: { id: string; display_name: string } + /** Advice only; present on the generic address when the reported name equals exactly one existing client. */ + suggested_client?: { id: string; matched: 'id' | 'display_name' | 'known_name' } + profiles: Array<{ name: string }> + profile_required: boolean + previous_login?: { grant_id: string; approved_at: string } + guard: OAuthGuardVerdict | null +} + +export interface OAuthApprovalBody { + client?: { id?: string; new?: { id: string; display_name?: string } } + /** Omitted = not chosen; '' = All servers. */ + profile?: string + mode?: 'locked' | 'switchable' + binding_revision?: string + replace_grant?: string +} + +export interface OAuthPreview { + complete: boolean + access?: { client: string; profile: string; mode: string; same_access_as_existing_client: boolean } + guard: OAuthGuardVerdict | null +} + +export interface OAuthDecision { redirect_url: string } + export interface BulkAssignResponse { moved: string[] skipped: Array<{ client_id: string; code: string; error?: string }> diff --git a/frontend/src/utils/navigate.ts b/frontend/src/utils/navigate.ts new file mode 100644 index 000000000..c32eacd67 --- /dev/null +++ b/frontend/src/utils/navigate.ts @@ -0,0 +1,5 @@ +// A seam for leaving the app: the consent page hands the browser back to the +// client's redirect URI, which tests replace with a spy. +export function navigateTo(url: string): void { + window.location.assign(url) +} diff --git a/frontend/src/views/AuthorizeRequest.vue b/frontend/src/views/AuthorizeRequest.vue new file mode 100644 index 000000000..c8cc6b122 --- /dev/null +++ b/frontend/src/views/AuthorizeRequest.vue @@ -0,0 +1,381 @@ + + + diff --git a/frontend/tests/unit/authorize-request-nokey.spec.ts b/frontend/tests/unit/authorize-request-nokey.spec.ts new file mode 100644 index 000000000..5a20b9854 --- /dev/null +++ b/frontend/tests/unit/authorize-request-nokey.spec.ts @@ -0,0 +1,69 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import { createMemoryHistory, createRouter } from 'vue-router' +import AuthorizeRequest from '@/views/AuthorizeRequest.vue' +import api from '@/services/api' + +vi.mock('@/services/api', async (orig) => { + const actual = await orig() + return { + ...actual, + default: { + hasAPIKey: vi.fn(() => false), + setAPIKey: vi.fn(), + getOAuthAuthorization: vi.fn(), + previewOAuthAuthorization: vi.fn(), + approveOAuthAuthorization: vi.fn(), + denyOAuthAuthorization: vi.fn(), + }, + } +}) +vi.mock('@/utils/navigate', () => ({ navigateTo: vi.fn() })) + +const A = api as any + +describe('AuthorizeRequest without an API key in storage', () => { + beforeEach(() => { + vi.clearAllMocks() + A.hasAPIKey.mockReturnValue(false) + }) + + it('shows only the open-from-tray message, makes no request, and continues after a pasted key', async () => { + const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/authorize', component: AuthorizeRequest }] }) + await router.push('/authorize?request=r1') + const w = mount(AuthorizeRequest, { global: { plugins: [router] } }) + await flushPromises() + + expect(w.text()).toContain('Open this request from the MCPProxy tray, or paste the API key') + expect(w.find('[data-test="authorize-approve"]').exists()).toBe(false) + expect(w.find('[data-test="authorize-deny"]').exists()).toBe(false) + expect(A.getOAuthAuthorization).not.toHaveBeenCalled() + expect(A.previewOAuthAuthorization).not.toHaveBeenCalled() + + A.getOAuthAuthorization.mockResolvedValue({ + id: 'r1', status: 'pending', expires_at: '2026-11-23T12:10:00Z', reported_name: 'Cursor', + redirect_uri: 'http://127.0.0.1:1/cb', resource: 'http://127.0.0.1:8080/mcp/oauth/cursor', address_kind: 'client', + client: { id: 'cursor', display_name: 'Cursor', exists: true, has_api_key: false, logins: 0, binding: { profile: '', mode: 'switchable', revision: 'r' } }, + profiles: [], profile_required: false, guard: null, + }) + A.previewOAuthAuthorization.mockResolvedValue({ complete: true, access: { client: 'cursor', profile: '', mode: 'switchable', same_access_as_existing_client: true }, guard: null }) + + await w.find('[data-test="authorize-key-input"]').setValue(' the-admin-key ') + await w.find('[data-test="authorize-key-submit"]').trigger('click') + await flushPromises() + + expect(A.setAPIKey).toHaveBeenCalledWith('the-admin-key') + expect(A.getOAuthAuthorization).toHaveBeenCalledWith('r1') + expect(w.find('[data-test="authorize-approve"]').exists()).toBe(true) + }) + + it('does not call the API when the request id is missing', async () => { + A.hasAPIKey.mockReturnValue(true) + const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/authorize', component: AuthorizeRequest }] }) + await router.push('/authorize') + const w = mount(AuthorizeRequest, { global: { plugins: [router] } }) + await flushPromises() + expect(A.getOAuthAuthorization).not.toHaveBeenCalled() + expect(w.find('[data-test="authorize-gone"]').exists()).toBe(true) + }) +}) diff --git a/frontend/tests/unit/authorize-request.spec.ts b/frontend/tests/unit/authorize-request.spec.ts new file mode 100644 index 000000000..3e4741187 --- /dev/null +++ b/frontend/tests/unit/authorize-request.spec.ts @@ -0,0 +1,280 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import { createMemoryHistory, createRouter } from 'vue-router' +import AuthorizeRequest from '@/views/AuthorizeRequest.vue' +import api, { ApiError } from '@/services/api' +import { navigateTo } from '@/utils/navigate' + +vi.mock('@/services/api', async (orig) => { + const actual = await orig() + return { + ...actual, + default: { + hasAPIKey: vi.fn(() => true), + setAPIKey: vi.fn(), + getOAuthAuthorization: vi.fn(), + previewOAuthAuthorization: vi.fn(), + approveOAuthAuthorization: vi.fn(), + denyOAuthAuthorization: vi.fn(), + }, + } +}) +vi.mock('@/utils/navigate', () => ({ navigateTo: vi.fn() })) + +const A = api as any + +const bound = { profile: 'dev-readonly', mode: 'locked', revision: 'rev1' } + +function base(over: Record = {}) { + return { + id: 'r1', status: 'pending', expires_at: '2026-11-23T12:10:00Z', reported_name: 'Cursor IDE', + redirect_uri: 'http://127.0.0.1:54321/callback', resource: 'http://127.0.0.1:8080/mcp/oauth/cursor', + address_kind: 'client', + client: { id: 'cursor', display_name: 'Cursor', exists: true, has_api_key: true, logins: 1, binding: bound }, + profiles: [{ name: 'dev-readonly' }, { name: 'ops' }], profile_required: false, guard: null, + ...over, + } +} + +function generic(over: Record = {}) { + return base({ + address_kind: 'generic', client: undefined, resource: 'http://127.0.0.1:8080/mcp/oauth', + existing_clients: [ + { id: 'codex', display_name: 'Codex', binding: { profile: 'ops', mode: 'switchable', revision: 'rc' } }, + { id: 'cursor', display_name: 'Cursor', binding: bound }, + ], + suggested_new_client: { id: 'acme-agent', display_name: 'Acme Agent' }, + profile_required: true, + ...over, + }) +} + +async function mountPage(detail: any, query = '?request=r1') { + A.getOAuthAuthorization.mockResolvedValue(detail) + A.previewOAuthAuthorization.mockImplementation(async (_id: string, body: any) => { + const client = body.client?.id ?? body.client?.new?.id + if (!client) return { complete: false, guard: null } + const existing = !!body.binding_revision + return { + complete: true, + access: { client, profile: body.profile ?? 'dev-readonly', mode: body.mode ?? 'locked', same_access_as_existing_client: existing }, + guard: null, + } + }) + const router = createRouter({ + history: createMemoryHistory(), + routes: [ + { path: '/authorize', name: 'authorize', component: AuthorizeRequest }, + { path: '/settings', name: 'settings', component: { template: '
' } }, + ], + }) + await router.push('/authorize' + query) + await router.isReady() + const w = mount(AuthorizeRequest, { global: { plugins: [router] } }) + await flushPromises() + return w +} + +const t = (w: any, id: string) => w.find(`[data-test="${id}"]`) + +describe('AuthorizeRequest: per-client address', () => { + beforeEach(() => { + vi.clearAllMocks() + A.hasAPIKey.mockReturnValue(true) + }) + + it('fixes the client, labels the reported name as unverified and states the access', async () => { + const w = await mountPage(base()) + expect(t(w, 'authorize-reported').text()).toContain('The app calls itself "Cursor IDE". MCPProxy cannot verify that.') + expect(t(w, 'authorize-client-fixed').text()).toContain('Cursor') + expect(t(w, 'authorize-client-select').exists()).toBe(false) + expect(t(w, 'authorize-binding').text()).toContain('dev-readonly') + expect(t(w, 'authorize-binding').text()).toContain('locked') + expect(t(w, 'authorize-profile-select').exists()).toBe(false) + expect(t(w, 'authorize-access').text()).toContain('the same access as Cursor') + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + }) + + it('never renders reported text as HTML', async () => { + const w = await mountPage(base({ reported_name: '' })) + expect(w.find('img').exists()).toBe(false) + expect(t(w, 'authorize-reported').text()).toContain('') + }) + + it('disables Approve until a profile is chosen when profile_required', async () => { + const detail = base({ + profile_required: true, + client: { id: 'cursor', display_name: 'Cursor', exists: false, has_api_key: false, logins: 0 }, + }) + const w = await mountPage(detail) + expect(t(w, 'authorize-binding').exists()).toBe(false) + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + await t(w, 'authorize-profile-select').setValue('ops') + await flushPromises() + expect(A.previewOAuthAuthorization).toHaveBeenLastCalledWith('r1', expect.objectContaining({ client: { id: 'cursor' }, profile: 'ops', mode: 'locked' })) + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + }) + + it('offers the replace-login checkbox only with previous_login, pre-checked, and sends it', async () => { + const without = await mountPage(base()) + expect(t(without, 'authorize-replace').exists()).toBe(false) + + const w = await mountPage(base({ previous_login: { grant_id: 'g1', approved_at: '2026-11-03T10:00:00Z' } })) + const box = t(w, 'authorize-replace') + expect(box.exists()).toBe(true) + expect((box.element as HTMLInputElement).checked).toBe(true) + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:54321/callback?code=c&state=s' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization).toHaveBeenCalledWith('r1', expect.objectContaining({ + client: { id: 'cursor' }, binding_revision: 'rev1', replace_grant: 'g1', + })) + expect(navigateTo).toHaveBeenCalledWith('http://127.0.0.1:54321/callback?code=c&state=s') + + await box.setValue(false) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization.mock.calls.at(-1)![1].replace_grant).toBeUndefined() + }) + + it('fetches the guard verdict through preview, shows the refusal with its fixes and keeps Approve disabled', async () => { + const detail = base() + A.getOAuthAuthorization.mockResolvedValue(detail) + A.previewOAuthAuthorization.mockResolvedValue({ + complete: true, + access: { client: 'cursor', profile: 'dev-readonly', mode: 'locked', same_access_as_existing_client: true }, + guard: { code: 'binding_bypassable_without_auth', bindings: [{ client_id: 'cursor', token_name: 'client-cursor', profile: 'dev-readonly', mode: 'locked' }], fixes: [{ kind: 'require_mcp_auth' }] }, + }) + const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/authorize', component: AuthorizeRequest }, { path: '/settings', component: { template: '
' } }] }) + await router.push('/authorize?request=r1') + const w = mount(AuthorizeRequest, { global: { plugins: [router] } }) + await flushPromises() + expect(A.previewOAuthAuthorization).toHaveBeenCalled() + expect(w.find('[data-test="guard-refusal"]').exists()).toBe(true) + expect(w.find('[data-test="guard-fix-require_mcp_auth"]').exists()).toBe(true) + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + }) + + it('shows the refusal when approve itself answers binding_bypassable_without_auth', async () => { + const w = await mountPage(base()) + A.approveOAuthAuthorization.mockRejectedValue(new ApiError(409, { + code: 'binding_bypassable_without_auth', error: 'would leave a client reachable without authentication', + bindings: [], fixes: [{ kind: 'require_mcp_auth' }], + }, 'x')) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(w.find('[data-test="guard-refusal"]').exists()).toBe(true) + expect(navigateTo).not.toHaveBeenCalled() + }) + + it('handles already_decided, binding_changed and 404', async () => { + const w = await mountPage(base()) + A.approveOAuthAuthorization.mockRejectedValueOnce(new ApiError(409, { code: 'already_decided', error: 'decided' }, 'x')) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(t(w, 'authorize-decided').exists()).toBe(true) + expect(t(w, 'authorize-approve').exists()).toBe(false) + + const w2 = await mountPage(base()) + const calls = A.getOAuthAuthorization.mock.calls.length + A.approveOAuthAuthorization.mockRejectedValueOnce(new ApiError(409, { code: 'binding_changed', error: 'changed' }, 'x')) + await t(w2, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.getOAuthAuthorization.mock.calls.length).toBe(calls + 1) + expect(t(w2, 'authorize-changed').exists()).toBe(true) + expect(navigateTo).not.toHaveBeenCalled() + + A.getOAuthAuthorization.mockRejectedValueOnce(new ApiError(404, { error: 'not found' }, 'x')) + const w3 = await mountPage(base()) + expect(t(w3, 'authorize-gone').exists()).toBe(true) + expect(t(w3, 'authorize-approve').exists()).toBe(false) + }) + + it('deny navigates to the returned redirect', async () => { + const w = await mountPage(base()) + A.denyOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:54321/callback?error=access_denied' }) + await t(w, 'authorize-deny').trigger('click') + await flushPromises() + expect(A.denyOAuthAuthorization).toHaveBeenCalledWith('r1') + expect(navigateTo).toHaveBeenCalledWith('http://127.0.0.1:54321/callback?error=access_denied') + }) +}) + +describe('AuthorizeRequest: generic address', () => { + beforeEach(() => { + vi.clearAllMocks() + A.hasAPIKey.mockReturnValue(true) + }) + + it('selects "New client" with the id and name filled from the reported name when nothing is suggested', async () => { + const w = await mountPage(generic()) + expect((t(w, 'authorize-client-select').element as HTMLSelectElement).value).toBe('__new__') + expect((t(w, 'authorize-new-id').element as HTMLInputElement).value).toBe('acme-agent') + expect((t(w, 'authorize-new-name').element as HTMLInputElement).value).toBe('Acme Agent') + expect(t(w, 'authorize-suggestion-note').exists()).toBe(false) + // Profiles exist and the client is new: nothing pre-selected, Approve disabled. + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + }) + + it('opens with the suggested client selected and says why', async () => { + const w = await mountPage(generic({ reported_name: 'Cursor', suggested_client: { id: 'cursor', matched: 'display_name' } })) + expect((t(w, 'authorize-client-select').element as HTMLSelectElement).value).toBe('cursor') + expect(t(w, 'authorize-suggestion-note').text()).toBe('Suggested because the app calls itself "Cursor". MCPProxy cannot verify that.') + expect(t(w, 'authorize-new-id').exists()).toBe(false) + expect(t(w, 'authorize-access').text()).toContain('the same access as Cursor') + expect(A.previewOAuthAuthorization).toHaveBeenLastCalledWith('r1', expect.objectContaining({ client: { id: 'cursor' }, binding_revision: 'rev1' })) + }) + + it('sends the client the user changed to, not the suggestion', async () => { + const w = await mountPage(generic({ reported_name: 'Cursor', suggested_client: { id: 'cursor', matched: 'id' } })) + await t(w, 'authorize-client-select').setValue('codex') + await flushPromises() + expect(t(w, 'authorize-suggestion-note').exists()).toBe(false) + expect(A.previewOAuthAuthorization).toHaveBeenLastCalledWith('r1', expect.objectContaining({ client: { id: 'codex' }, binding_revision: 'rc' })) + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:54321/callback?code=c' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization).toHaveBeenCalledWith('r1', expect.objectContaining({ client: { id: 'codex' }, binding_revision: 'rc' })) + }) + + it('creates a new client with the edited id and name', async () => { + const w = await mountPage(generic()) + const id = t(w, 'authorize-new-id') + await id.setValue('my-agent') + await id.trigger('change') + const name = t(w, 'authorize-new-name') + await name.setValue('My Agent') + await name.trigger('change') + await t(w, 'authorize-profile-select').setValue('ops') + await flushPromises() + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:54321/callback?code=c' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization).toHaveBeenCalledWith('r1', expect.objectContaining({ + client: { new: { id: 'my-agent', display_name: 'My Agent' } }, profile: 'ops', mode: 'locked', + })) + }) + + it.each([ + ['identity_exists', 'A client with this id already exists'], + ['reserved_identity', 'This id belongs to a supported client'], + ])('shows %s next to the id and does not navigate', async (code, text) => { + const w = await mountPage(generic()) + await t(w, 'authorize-profile-select').setValue('ops') + await flushPromises() + A.approveOAuthAuthorization.mockRejectedValue(new ApiError(422, { code, error: text }, 'x')) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(t(w, 'authorize-error').text()).toContain(text) + expect(navigateTo).not.toHaveBeenCalled() + }) + + it('shows a profile-bound existing client without asking for a profile', async () => { + const w = await mountPage(generic()) + await t(w, 'authorize-client-select').setValue('codex') + await flushPromises() + expect(t(w, 'authorize-binding').text()).toContain('ops') + expect(t(w, 'authorize-profile-select').exists()).toBe(false) + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + }) +}) diff --git a/internal/httpapi/oauth_login_test.go b/internal/httpapi/oauth_login_test.go index 87028a502..718dc5648 100644 --- a/internal/httpapi/oauth_login_test.go +++ b/internal/httpapi/oauth_login_test.go @@ -249,6 +249,53 @@ func TestOAuthLoginREST_GenericAddress(t *testing.T) { assert.Equal(t, http.StatusOK, w.Code, w.Body.String()) } +// T049a: the generic address carries suggested_client when the reported name +// equals exactly one existing client; the server never applies it. +func TestOAuthLoginREST_SuggestedClient(t *testing.T) { + h := newOAuthHarness(t, true) + h.mint("cursor", "ro") + h.mint("codex", "ro") + begin := func(name, client string) string { + reg, rerr, err := h.svc.Register(mcplogin.RegistrationRequest{RedirectURIs: []string{oauthTestRedirect}, ClientName: name}) + require.NoError(t, err) + require.Nil(t, rerr) + regID, _ := reg["client_id"].(string) + sum := sha256.Sum256([]byte(strings.Repeat("v", 43))) + id, aerr := h.svc.BeginAuthorization(internalRuntime.AuthorizeInput{ + Origin: oauthTestOrigin, ClientID: regID, RedirectURI: oauthTestRedirect, State: "st", + CodeChallenge: base64.RawURLEncoding.EncodeToString(sum[:]), Method: "S256", + Resource: oauthTestOrigin + mcplogin.ResourcePath(client), ResponseType: "code", + }) + require.Nil(t, aerr) + return id + } + + id := begin("Cursor (my-server)", "") + w := h.call(http.MethodGet, "/api/v1/oauth/authorizations/"+id, "", bindingAdminKey) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + d := dataOf(t, w) + sc, _ := d["suggested_client"].(map[string]interface{}) + require.NotNil(t, sc, w.Body.String()) + assert.Equal(t, "cursor", sc["id"]) + assert.Equal(t, "id", sc["matched"]) + + w = h.call(http.MethodPost, "/api/v1/oauth/authorizations/"+id+"/preview", `{}`, bindingAdminKey) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + pv := dataOf(t, w) + assert.Equal(t, false, pv["complete"]) + assert.NotContains(t, pv, "access") + assert.Nil(t, pv["guard"]) + w = h.call(http.MethodPost, "/api/v1/oauth/authorizations/"+id+"/approve", `{"profile":"ro"}`, bindingAdminKey) + assert.Equal(t, http.StatusUnprocessableEntity, w.Code) + assert.Equal(t, "client_required", decodeBody(t, w)["code"]) + + // No match: absent. Per-client address: absent. + d = dataOf(t, h.call(http.MethodGet, "/api/v1/oauth/authorizations/"+begin("Something Else", ""), "", bindingAdminKey)) + assert.NotContains(t, d, "suggested_client") + d = dataOf(t, h.call(http.MethodGet, "/api/v1/oauth/authorizations/"+begin("codex", "cursor"), "", bindingAdminKey)) + assert.NotContains(t, d, "suggested_client") +} + // T042: client payloads and the per-credential revokes. func TestOAuthLoginREST_ClientCredentialsPayloadAndRevokes(t *testing.T) { h := newOAuthHarness(t, true) diff --git a/internal/runtime/oauth_login_consent.go b/internal/runtime/oauth_login_consent.go index 93e9f10f8..661584780 100644 --- a/internal/runtime/oauth_login_consent.go +++ b/internal/runtime/oauth_login_consent.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "net/http" + "regexp" "sort" "strings" "time" @@ -213,6 +214,15 @@ type SuggestedClient struct { DisplayName string `json:"display_name"` } +// SuggestedExisting is the page's advice for the generic address: the one +// existing client the reported name equals. Matched is the first field that +// matched: "id", "display_name" or "known_name". Advice only: the server never +// applies it (preview and approve take the client from their own body). +type SuggestedExisting struct { + ID string `json:"id"` + Matched string `json:"matched"` +} + // ProfileChoice names a profile the page may offer. type ProfileChoice struct { Name string `json:"name"` @@ -251,6 +261,7 @@ type AuthorizationView struct { Client *AuthorizationClientView `json:"client,omitempty"` ExistingClients []ExistingClientView `json:"existing_clients,omitempty"` SuggestedNewClient *SuggestedClient `json:"suggested_new_client,omitempty"` + SuggestedClient *SuggestedExisting `json:"suggested_client,omitempty"` Profiles []ProfileChoice `json:"profiles"` ProfileRequired bool `json:"profile_required"` PreviousLogin *PreviousLogin `json:"previous_login,omitempty"` @@ -402,6 +413,7 @@ func (s *OAuthLoginService) Describe(ctx context.Context, requestID string) (*Au } v.ProfileRequired = len(v.Profiles) > 0 v.SuggestedNewClient = s.suggestNewClient(reg.ReportedName, ids) + v.SuggestedClient = suggestExistingClient(reg.ReportedName, v.ExistingClients) } return v, nil } @@ -434,6 +446,67 @@ func (s *OAuthLoginService) displayNameOf(id string, all []auth.AgentToken, bind return id } +var parenSuffix = regexp.MustCompile(`^(.*\S)\s*\([^()]*\)$`) + +// suggestExistingClient compares the sanitised reported name, trimmed and +// without regard to case, with each offered client's id, display name and (for +// a connect-registry client) known client names. The whole name is tried and, +// when it ends with a parenthesised suffix, also the part before it. Matches +// are counted by distinct client id: exactly one client yields a suggestion, +// none or several yield nil. Pure advice, computed on read, never stored. +func suggestExistingClient(reported string, clients []ExistingClientView) *SuggestedExisting { + name := strings.ToLower(strings.TrimSpace(reported)) + if name == "" { + return nil + } + forms := []string{name} + if m := parenSuffix.FindStringSubmatch(name); m != nil { + if base := strings.TrimSpace(m[1]); base != "" && base != name { + forms = append(forms, base) + } + } + eq := func(candidate string) bool { + c := strings.ToLower(strings.TrimSpace(candidate)) + if c == "" { + return false + } + for _, f := range forms { + if f == c { + return true + } + } + return false + } + var found *SuggestedExisting + for i := range clients { + c := &clients[i] + matched := "" + switch { + case eq(c.ID): + matched = "id" + case eq(c.DisplayName): + matched = "display_name" + default: + if def := connect.FindClient(c.ID); def != nil { + for _, n := range def.ClientInfoNames { + if eq(n) { + matched = "known_name" + break + } + } + } + } + if matched == "" { + continue + } + if found != nil { + return nil // several distinct clients + } + found = &SuggestedExisting{ID: c.ID, Matched: matched} + } + return found +} + // suggestNewClient derives an id from the reported name: lower-case slug of // letters, digits, '-' and '_', at most 56 characters, made unique against the // registry and the existing clients ("-2", "-3", ...). It only SUGGESTS: the diff --git a/internal/runtime/oauth_login_suggest_test.go b/internal/runtime/oauth_login_suggest_test.go new file mode 100644 index 000000000..4dbc6273d --- /dev/null +++ b/internal/runtime/oauth_login_suggest_test.go @@ -0,0 +1,96 @@ +package runtime + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/mcplogin" +) + +// suggestFor registers a client reporting `name`, starts an authorization on the +// given address ("" = generic) and returns the described view. +func (fx *oauthFx) suggestFor(name, client string) *AuthorizationView { + fx.t.Helper() + resp, rerr, err := fx.svc.Register(mcplogin.RegistrationRequest{RedirectURIs: []string{oauthTestRedirect}, ClientName: name}) + require.NoError(fx.t, err) + require.Nil(fx.t, rerr) + id := fx.authorize(resp["client_id"].(string), client) + v, err := fx.svc.Describe(fx.ctx(), id) + require.NoError(fx.t, err) + return v +} + +func TestOAuthDescribe_SuggestedClient(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("cursor", "ro", auth.ProfileModeLocked) + fx.mintClient("codex", "rw", auth.ProfileModeSwitchable) + + t.Run("no match", func(t *testing.T) { + assert.Nil(t, fx.suggestFor("Totally Different", "").SuggestedClient) + }) + t.Run("id match, case and whitespace", func(t *testing.T) { + s := fx.suggestFor(" CODEX ", "").SuggestedClient + require.NotNil(t, s) + assert.Equal(t, "codex", s.ID) + assert.Equal(t, "id", s.Matched) + }) + t.Run("one client on several fields is one match, id wins", func(t *testing.T) { + // "cursor" is the id, the registry display name "Cursor" and a known name. + s := fx.suggestFor("cursor", "").SuggestedClient + require.NotNil(t, s) + assert.Equal(t, "cursor", s.ID) + assert.Equal(t, "id", s.Matched) + }) + t.Run("display name of a registry client", func(t *testing.T) { + // "Cursor" registry display name differs from the id only by case; use the + // alias path below for a distinct spelling. + s := fx.suggestFor("Cursor", "").SuggestedClient + require.NotNil(t, s) + assert.Equal(t, "cursor", s.ID) + }) + t.Run("registry alias", func(t *testing.T) { + s := fx.suggestFor("Cursor-VSCode", "").SuggestedClient + require.NotNil(t, s) + assert.Equal(t, "cursor", s.ID) + assert.Equal(t, "known_name", s.Matched) + }) + t.Run("parenthesised suffix", func(t *testing.T) { + s := fx.suggestFor("Codex (my-server)", "").SuggestedClient + require.NotNil(t, s) + assert.Equal(t, "codex", s.ID) + assert.Equal(t, "id", s.Matched) + }) + t.Run("name equal to one client's id and another's display name is ambiguous", func(t *testing.T) { + fx.mintClient("zed", "ro", auth.ProfileModeLocked) + _, _, err := fx.clients.Add(fx.ctx(), fx.actor(), AddRequest{ID: "acme", DisplayName: "Zed", Profile: "ro"}) + require.NoError(t, err) + assert.Nil(t, fx.suggestFor("zed", "").SuggestedClient) + // Either one alone is fine. + s := fx.suggestFor("Acme (x)", "").SuggestedClient + require.NotNil(t, s) + assert.Equal(t, "acme", s.ID) + }) + t.Run("never on a per-client address", func(t *testing.T) { + v := fx.suggestFor("codex", "cursor") + assert.Equal(t, "client", v.AddressKind) + assert.Nil(t, v.SuggestedClient) + }) + t.Run("the server never applies the suggestion", func(t *testing.T) { + v := fx.suggestFor("codex", "") + require.NotNil(t, v.SuggestedClient) + pv, err := fx.svc.Preview(fx.ctx(), v.ID, ApprovalChoice{}) + require.NoError(t, err) + assert.False(t, pv.Complete) + assert.Nil(t, pv.Access) + assert.Nil(t, pv.Guard) + _, err = fx.svc.Approve(fx.ctx(), v.ID, ApprovalChoice{Profile: oauthStrp("ro")}) + assert.ErrorIs(t, err, ErrOAuthClientRequired) + code, status, ok := OAuthErrorStatus(ErrOAuthClientRequired) + assert.True(t, ok) + assert.Equal(t, "client_required", code) + assert.Equal(t, 422, status) + }) +} diff --git a/internal/server/oauth_login_http_test.go b/internal/server/oauth_login_http_test.go index dfbf04718..e0f6be6d7 100644 --- a/internal/server/oauth_login_http_test.go +++ b/internal/server/oauth_login_http_test.go @@ -4,6 +4,7 @@ package server import ( "net/http" + "net/http/httptest" "net/url" "strings" "testing" @@ -58,6 +59,30 @@ func TestOAuthLoginHTTP_MetadataAndChallenge(t *testing.T) { } } +// T053: the consent page is never framed. The headers are set before the SPA +// handler runs, on the page and anything under it, and on no other UI path. +func TestOAuthLoginHTTP_AuthorizePageIsNeverFramed(t *testing.T) { + inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("spa")) }) + h := (&Server{}).createSelectiveWebUIProtectedHandler(inner) + for _, path := range []string{"/ui/authorize", "/ui/authorize?request=abc", "/ui/authorize/"} { + rec := httptestGet(h, path) + assert.Equal(t, "frame-ancestors 'none'", rec.Header().Get("Content-Security-Policy"), path) + assert.Equal(t, "DENY", rec.Header().Get("X-Frame-Options"), path) + assert.Equal(t, "spa", rec.Body.String(), path) + } + for _, path := range []string{"/ui/", "/ui/clients", "/ui/authorized"} { + rec := httptestGet(h, path) + assert.Empty(t, rec.Header().Get("Content-Security-Policy"), path) + assert.Empty(t, rec.Header().Get("X-Frame-Options"), path) + } +} + +func httptestGet(h http.Handler, target string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, target, nil)) + return rec +} + // T034: register. func TestOAuthLoginHTTP_Register(t *testing.T) { f := newOAuthFlow(t, nil) diff --git a/internal/server/server.go b/internal/server/server.go index 45ada135c..af56842d6 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -806,9 +806,16 @@ func credentialKindContext(ac *auth.AuthContext, kind auth.CredentialKind) *auth // that should be served without authentication to allow the SPA to work properly. // API endpoints are protected separately by the httpAPIServer middleware. func (s *Server) createSelectiveWebUIProtectedHandler(handler http.Handler) http.Handler { - // Simply pass through all requests without authentication - // The handler is only mounted on /ui/* so it won't receive API requests - return handler + // No authentication here; the handler is only mounted on /ui/* so it won't + // receive API requests. The one addition: the sign-in consent page (Spec 132) + // is never framed, so a hostile page cannot overlay its Approve button. + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if p := r.URL.Path; p == "/ui/authorize" || strings.HasPrefix(p, "/ui/authorize/") { + w.Header().Set("Content-Security-Policy", "frame-ancestors 'none'") + w.Header().Set("X-Frame-Options", "DENY") + } + handler.ServeHTTP(w, r) + }) } // GetStatus returns the current server status From 60723ab4b2bedcecaf1896a58a32f4f7fcc84f5d Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 13:16:41 +0200 Subject: [PATCH 27/42] fix(oauth): consent page review round 1, backend (Spec 132 PR-2a) - /ui/authorize frame headers: case-insensitive on the cleaned path (Vue Router matches case-insensitively and the SPA answers unknown paths). - suggested_client: compare with strings.EqualFold (Unicode folding), strip one balanced trailing parenthesised group (nested parentheses allowed); tests for display-name-only, display name over known name, sigma forms, nested suffix and whole-name vs stripped-name ambiguity. Related #1971 --- internal/runtime/oauth_login_consent.go | 38 ++++++-- .../oauth_login_suggest_round1_test.go | 86 +++++++++++++++++++ internal/server/oauth_login_http_test.go | 5 +- internal/server/server.go | 5 +- 4 files changed, 123 insertions(+), 11 deletions(-) create mode 100644 internal/runtime/oauth_login_suggest_round1_test.go diff --git a/internal/runtime/oauth_login_consent.go b/internal/runtime/oauth_login_consent.go index 661584780..7870ab6f0 100644 --- a/internal/runtime/oauth_login_consent.go +++ b/internal/runtime/oauth_login_consent.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "net/http" - "regexp" "sort" "strings" "time" @@ -446,7 +445,30 @@ func (s *OAuthLoginService) displayNameOf(id string, all []auth.AgentToken, bind return id } -var parenSuffix = regexp.MustCompile(`^(.*\S)\s*\([^()]*\)$`) +// stripTrailingGroup removes one balanced trailing parenthesised group +// ("Claude Code (my (dev) server)" -> "Claude Code") and returns the trimmed +// text before it. ok is false when the text does not end with a balanced group +// or nothing is left before it. +func stripTrailingGroup(s string) (string, bool) { + s = strings.TrimSpace(s) + if !strings.HasSuffix(s, ")") { + return "", false + } + depth := 0 + for i := len(s) - 1; i >= 0; i-- { + switch s[i] { + case ')': + depth++ + case '(': + depth-- + if depth == 0 { + base := strings.TrimSpace(s[:i]) + return base, base != "" + } + } + } + return "", false +} // suggestExistingClient compares the sanitised reported name, trimmed and // without regard to case, with each offered client's id, display name and (for @@ -455,23 +477,21 @@ var parenSuffix = regexp.MustCompile(`^(.*\S)\s*\([^()]*\)$`) // are counted by distinct client id: exactly one client yields a suggestion, // none or several yield nil. Pure advice, computed on read, never stored. func suggestExistingClient(reported string, clients []ExistingClientView) *SuggestedExisting { - name := strings.ToLower(strings.TrimSpace(reported)) + name := strings.TrimSpace(reported) if name == "" { return nil } forms := []string{name} - if m := parenSuffix.FindStringSubmatch(name); m != nil { - if base := strings.TrimSpace(m[1]); base != "" && base != name { - forms = append(forms, base) - } + if base, ok := stripTrailingGroup(name); ok { + forms = append(forms, base) } eq := func(candidate string) bool { - c := strings.ToLower(strings.TrimSpace(candidate)) + c := strings.TrimSpace(candidate) if c == "" { return false } for _, f := range forms { - if f == c { + if strings.EqualFold(f, c) { return true } } diff --git a/internal/runtime/oauth_login_suggest_round1_test.go b/internal/runtime/oauth_login_suggest_round1_test.go new file mode 100644 index 000000000..135731c61 --- /dev/null +++ b/internal/runtime/oauth_login_suggest_round1_test.go @@ -0,0 +1,86 @@ +package runtime + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +func (fx *oauthFx) addCustom(id, display string) { + fx.t.Helper() + _, _, err := fx.clients.Add(fx.ctx(), fx.actor(), AddRequest{ID: id, DisplayName: display, Profile: "ro"}) + require.NoError(fx.t, err) +} + +func TestOAuthDescribe_SuggestedClient_DisplayName(t *testing.T) { + fx := newOAuthFx(t) + fx.addCustom("acme", "Acme Agent") + for _, name := range []string{"Acme Agent", " acme agent "} { + s := fx.suggestFor(name, "").SuggestedClient + require.NotNil(t, s, name) + assert.Equal(t, "acme", s.ID) + assert.Equal(t, "display_name", s.Matched) + } +} + +func TestOAuthDescribe_SuggestedClient_DisplayNameBeatsKnownName(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("claude-desktop", "ro", auth.ProfileModeLocked) + // Registry display name "Claude Desktop"; "Claude" and "claude-ai" are known names. + s := fx.suggestFor("Claude Desktop", "").SuggestedClient + require.NotNil(t, s) + assert.Equal(t, "display_name", s.Matched) + s = fx.suggestFor("Claude", "").SuggestedClient + require.NotNil(t, s) + assert.Equal(t, "known_name", s.Matched) +} + +func TestOAuthDescribe_SuggestedClient_UnicodeFolding(t *testing.T) { + fx := newOAuthFx(t) + fx.addCustom("sig-a", "Σ") + s := fx.suggestFor("σ", "").SuggestedClient + require.NotNil(t, s) + assert.Equal(t, "sig-a", s.ID) + fx.addCustom("sig-b", "ς") + assert.Nil(t, fx.suggestFor("σ", "").SuggestedClient, "Σ and ς fold to the same letter as σ: two clients") +} + +func TestOAuthDescribe_SuggestedClient_Suffix(t *testing.T) { + fx := newOAuthFx(t) + fx.mintClient("codex", "ro", auth.ProfileModeLocked) + s := fx.suggestFor("Codex (my (dev) server)", "").SuggestedClient + require.NotNil(t, s, "one balanced trailing group is stripped, nested parentheses included") + assert.Equal(t, "codex", s.ID) + + fx.addCustom("acme", "Acme (prod)") + s = fx.suggestFor("Acme (prod)", "").SuggestedClient + require.NotNil(t, s, "whole-name match") + assert.Equal(t, "acme", s.ID) + + // Whole name matches one client, the stripped name another: no suggestion. + fx.addCustom("other", "Codex (x)") + assert.Nil(t, fx.suggestFor("Codex (x)", "").SuggestedClient) +} + +func TestSuggestExistingClient_StripTrailingGroup(t *testing.T) { + cases := map[string]struct { + in, base string + ok bool + }{ + "plain": {"a (b)", "a", true}, + "nested": {"a (b (c) d)", "a", true}, + "unbalanced": {"a (b", "", false}, + "only group": {"(b)", "", false}, + "no group": {"abc", "", false}, + "not trailing": {"a (b) c", "", false}, + "close first": {"a )b(", "", false}, + } + for name, c := range cases { + base, ok := stripTrailingGroup(c.in) + assert.Equal(t, c.ok, ok, name) + assert.Equal(t, c.base, base, name) + } +} diff --git a/internal/server/oauth_login_http_test.go b/internal/server/oauth_login_http_test.go index e0f6be6d7..ae7214d07 100644 --- a/internal/server/oauth_login_http_test.go +++ b/internal/server/oauth_login_http_test.go @@ -64,7 +64,10 @@ func TestOAuthLoginHTTP_MetadataAndChallenge(t *testing.T) { func TestOAuthLoginHTTP_AuthorizePageIsNeverFramed(t *testing.T) { inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("spa")) }) h := (&Server{}).createSelectiveWebUIProtectedHandler(inner) - for _, path := range []string{"/ui/authorize", "/ui/authorize?request=abc", "/ui/authorize/"} { + for _, path := range []string{ + "/ui/authorize", "/ui/authorize?request=abc", "/ui/authorize/", "/ui/authorize/x", + "/ui/Authorize?request=abc", "/ui/AUTHORIZE/", "/ui/Authorize/X", "/ui//authorize", "/ui/./authorize", "/ui/x/../authorize", + } { rec := httptestGet(h, path) assert.Equal(t, "frame-ancestors 'none'", rec.Header().Get("Content-Security-Policy"), path) assert.Equal(t, "DENY", rec.Header().Get("X-Frame-Options"), path) diff --git a/internal/server/server.go b/internal/server/server.go index af56842d6..c92b12d85 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -10,6 +10,7 @@ import ( "net/http" httppprof "net/http/pprof" "os" + "path" "path/filepath" gruntime "runtime" "strings" @@ -810,7 +811,9 @@ func (s *Server) createSelectiveWebUIProtectedHandler(handler http.Handler) http // receive API requests. The one addition: the sign-in consent page (Spec 132) // is never framed, so a hostile page cannot overlay its Approve button. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if p := r.URL.Path; p == "/ui/authorize" || strings.HasPrefix(p, "/ui/authorize/") { + // Vue Router matches case-insensitively and the SPA answers unknown + // paths, so compare the cleaned path without regard to case. + if p := strings.ToLower(path.Clean("/" + r.URL.Path)); p == "/ui/authorize" || strings.HasPrefix(p, "/ui/authorize/") { w.Header().Set("Content-Security-Policy", "frame-ancestors 'none'") w.Header().Set("X-Frame-Options", "DENY") } From 94fb487957a0b3560849ad7df5d31ba04c806a05 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 13:21:30 +0200 Subject: [PATCH 28/42] fix(oauth): consent page review round 1, page and replace ownership (Spec 132 PR-2a) - Page: a new ?request= id clears the page and reloads (generation check); decisions go to the loaded request. Approve needs a complete preview with access for the current choice and sends exactly the body it answered. The replace-login option is tied to the client that owns the previous login. The new-client draft is always filled from suggested_new_client. One decision per page: both buttons guarded, terminal after success. - Backend: previous_login carries client_id; a replace_grant that is a live login of this registration owned by another client is refused (422, field replace_grant). Related #1971 --- docs/api/rest-api.md | 6 +- frontend/src/types/api.ts | 2 +- frontend/src/views/AuthorizeRequest.vue | 157 ++++++---- .../tests/unit/authorize-request-race.spec.ts | 269 ++++++++++++++++++ frontend/tests/unit/authorize-request.spec.ts | 11 +- internal/runtime/oauth_login_consent.go | 12 +- .../runtime/oauth_login_replace_owner_test.go | 44 +++ 7 files changed, 431 insertions(+), 70 deletions(-) create mode 100644 frontend/tests/unit/authorize-request-race.spec.ts create mode 100644 internal/runtime/oauth_login_replace_owner_test.go diff --git a/docs/api/rest-api.md b/docs/api/rest-api.md index b106b90de..8dfa42366 100644 --- a/docs/api/rest-api.md +++ b/docs/api/rest-api.md @@ -1704,7 +1704,11 @@ reference: the Spec 132 contracts. client's id, display name or known client name, absent otherwise and never on a per-client address. It is advice for the page, computed on read and never stored: preview without a `client` answers `200 {"complete": false}` (no `access`, no `guard`) and - approve without one answers `422 client_required`. + approve without one answers `422 client_required`. `previous_login` is + `{grant_id, client_id, approved_at}`: `client_id` is the client that owns that + login. Preview and approve refuse (`422`, field `replace_grant`) a `replace_grant` + that is a live login of this registration owned by another client than the one + chosen; the page offers replacement only for the owning client. - `POST /api/v1/oauth/authorizations/{id}/preview`: read-only verdict for a proposed client, profile and mode. `POST .../approve` and `POST .../deny` answer `{redirect_url}`; approve refuses with `409 already_decided`, `409 binding_changed`, diff --git a/frontend/src/types/api.ts b/frontend/src/types/api.ts index 9b7189f24..b909d51c7 100644 --- a/frontend/src/types/api.ts +++ b/frontend/src/types/api.ts @@ -1603,7 +1603,7 @@ export interface OAuthAuthorization { suggested_client?: { id: string; matched: 'id' | 'display_name' | 'known_name' } profiles: Array<{ name: string }> profile_required: boolean - previous_login?: { grant_id: string; approved_at: string } + previous_login?: { grant_id: string; client_id: string; approved_at: string } guard: OAuthGuardVerdict | null } diff --git a/frontend/src/views/AuthorizeRequest.vue b/frontend/src/views/AuthorizeRequest.vue index c8cc6b122..d4a6fef01 100644 --- a/frontend/src/views/AuthorizeRequest.vue +++ b/frontend/src/views/AuthorizeRequest.vue @@ -97,9 +97,9 @@
-

{{ accessSentence }}

+

{{ accessSentence }}

-
@@ -125,12 +125,19 @@ // reports (name, redirect URI) is untrusted and is rendered as text only. The // reported name never decides anything: the page sends the client the user // sees selected, and the server never applies a suggestion. +// +// Three rules keep a decision tied to what is on screen: +// - the decision goes to the request that was LOADED and is displayed; a new +// `?request=` id clears the page at once and loads again; +// - Approve needs a complete preview, with access, for the CURRENT choice, and +// sends exactly the body that preview answered; +// - one decision per page: after success the buttons stay disabled. import { computed, onMounted, ref, watch } from 'vue' import { useRoute } from 'vue-router' import api, { ApiError } from '@/services/api' import { navigateTo } from '@/utils/navigate' import GuardRefusal from '@/components/GuardRefusal.vue' -import type { OAuthApprovalBody, OAuthAuthorization, OAuthGuardVerdict, OAuthPreview } from '@/types/api' +import type { OAuthApprovalBody, OAuthAuthorization, OAuthDecision, OAuthGuardVerdict, OAuthPreview } from '@/types/api' const UNSET = '__unset__' const ALL = '__all__' @@ -143,6 +150,7 @@ const requestId = computed(() => (typeof route.query.request === 'string' ? rout const phase = ref('loading') const view = ref(null) +const loadedId = ref('') const pastedKey = ref('') const selected = ref('') const newId = ref('') @@ -150,14 +158,17 @@ const newName = ref('') const profileSel = ref(UNSET) const lock = ref(true) const replace = ref(false) -const preview = ref(null) -const previewing = ref(false) +const accepted = ref<{ key: string; preview: OAuthPreview } | null>(null) +const previewFailed = ref(false) const guardOverride = ref(null) const errorText = ref('') const changedNote = ref(false) const submitting = ref(false) +const decided = ref(false) let previewSeq = 0 +let loadGen = 0 +const busy = computed(() => submitting.value || decided.value) const fixed = computed(() => (view.value?.address_kind === 'client' ? view.value.client ?? null : null)) const existingClients = computed(() => view.value?.existing_clients ?? []) const selectedExisting = computed(() => @@ -172,6 +183,14 @@ const showSuggestion = computed( () => !!view.value?.suggested_client && selected.value === view.value.suggested_client.id, ) +// A previous login is replaced only by signing in the client that owns it. +const showReplace = computed(() => { + const prev = view.value?.previous_login + if (!prev) return false + const owner = fixed.value?.id ?? selectedExisting.value?.id + return !!owner && owner === prev.client_id +}) + const title = computed(() => { const name = fixed.value?.display_name return name ? `Sign-in request for ${name}` : 'Sign-in request' @@ -210,15 +229,18 @@ function buildBody(): OAuthApprovalBody { body.profile = profileValue.value if (profileValue.value !== '') body.mode = lock.value ? 'locked' : 'switchable' } - if (view.value?.previous_login && replace.value && !isNewGeneric.value) body.replace_grant = view.value.previous_login.grant_id + if (view.value?.previous_login && showReplace.value && replace.value) body.replace_grant = view.value.previous_login.grant_id return body } const previewKey = computed(() => (phase.value === 'ready' && complete.value ? JSON.stringify(buildBody()) : null)) +// The accepted preview is current only for the exact body it answered. +const current = computed(() => (accepted.value && accepted.value.key === previewKey.value ? accepted.value.preview : null)) + const guard = computed(() => { if (guardOverride.value) return refusalOf(guardOverride.value) - if (preview.value) return preview.value.guard ? refusalOf(preview.value.guard) : null + if (current.value) return current.value.guard ? refusalOf(current.value.guard) : null return view.value?.guard ? refusalOf(view.value.guard) : null }) @@ -226,13 +248,13 @@ function refusalOf(g: OAuthGuardVerdict) { return { bindings: g.bindings, fixes: g.fixes } } -const approveDisabled = computed( - () => !complete.value || previewing.value || submitting.value || !!guard.value || !!previewFailed.value, +const approveReady = computed( + () => !!current.value && current.value.complete === true && !!current.value.access && !guard.value && !previewFailed.value, ) -const previewFailed = ref(false) +const approveDisabled = computed(() => !approveReady.value || busy.value) const accessSentence = computed(() => { - const a = preview.value?.access + const a = current.value?.access if (!a) return '' if (a.same_access_as_existing_client) return `Approving gives this app the same access as ${clientDisplayName.value}.` return `Approving gives this app access to ${a.profile || 'All servers'} as ${clientDisplayName.value}.` @@ -245,39 +267,49 @@ const approvedOn = computed(() => { return Number.isNaN(d.getTime()) ? '' : d.toLocaleDateString(undefined, { day: 'numeric', month: 'short' }) }) -function resetChoice(v: OAuthAuthorization) { - guardOverride.value = null - preview.value = null +function resetPage(keepNote = false) { + loadGen++ + previewSeq++ + view.value = null + loadedId.value = '' + accepted.value = null previewFailed.value = false + guardOverride.value = null + errorText.value = '' + submitting.value = false + decided.value = false + if (!keepNote) changedNote.value = false +} + +function resetChoice(v: OAuthAuthorization) { profileSel.value = UNSET + lock.value = true replace.value = !!v.previous_login - if (v.address_kind === 'generic') { - if (v.suggested_client) { - selected.value = v.suggested_client.id - } else { - selected.value = NEW - newId.value = v.suggested_new_client?.id ?? '' - newName.value = v.suggested_new_client?.display_name ?? '' - } - } else { - selected.value = '' - } + // The new-client draft is always ready, whatever is selected first. + newId.value = v.suggested_new_client?.id ?? '' + newName.value = v.suggested_new_client?.display_name ?? '' + if (v.address_kind === 'generic') selected.value = v.suggested_client ? v.suggested_client.id : NEW + else selected.value = '' } async function load(keepNote = false) { - if (!requestId.value) { + resetPage(keepNote) + const id = requestId.value + if (!id) { phase.value = 'gone' return } phase.value = 'loading' - errorText.value = '' - if (!keepNote) changedNote.value = false + const gen = loadGen try { - const v = await api.getOAuthAuthorization(requestId.value) + const v = await api.getOAuthAuthorization(id) + if (gen !== loadGen) return view.value = v + loadedId.value = id resetChoice(v) phase.value = 'ready' } catch (e) { + if (gen !== loadGen) return if (e instanceof ApiError && e.status === 404) phase.value = 'gone' else { errorText.value = e instanceof Error ? e.message : 'Could not load the request.' @@ -286,55 +318,69 @@ async function load(keepNote = false) { } } -async function runPreview(key: string) { +async function runPreview(id: string, key: string) { const seq = ++previewSeq - previewing.value = true errorText.value = '' try { - const p = await api.previewOAuthAuthorization(requestId.value, JSON.parse(key)) + const p = await api.previewOAuthAuthorization(id, JSON.parse(key)) if (seq !== previewSeq) return - preview.value = p + accepted.value = { key, preview: p } previewFailed.value = false guardOverride.value = null } catch (e) { if (seq !== previewSeq) return - preview.value = null + accepted.value = null if (e instanceof ApiError && e.status === 404 && e.code !== 'profile_not_found') { phase.value = 'gone' return } previewFailed.value = true errorText.value = e instanceof Error ? e.message : 'Could not check this choice.' - } finally { - if (seq === previewSeq) previewing.value = false } } -watch(previewKey, (key) => { - if (key === null) { +// Sync: the accepted preview is dropped in the same tick the choice changes. +watch( + previewKey, + (key) => { previewSeq++ - previewing.value = false - preview.value = null + accepted.value = null + guardOverride.value = null previewFailed.value = false - return - } - void runPreview(key) + if (key !== null && loadedId.value) void runPreview(loadedId.value, key) + }, + { flush: 'sync' }, +) + +watch(requestId, () => { + if (phase.value === 'nokey') return + void load() }) -async function approve() { - if (approveDisabled.value) return +async function decide(call: (id: string) => Promise) { + if (busy.value || !loadedId.value) return submitting.value = true errorText.value = '' try { - const res = await api.approveOAuthAuthorization(requestId.value, buildBody()) + const res = await call(loadedId.value) + decided.value = true // terminal: stays disabled while the browser leaves navigateTo(res.redirect_url) } catch (e) { - await handleDecisionError(e) - } finally { submitting.value = false + await handleDecisionError(e) } } +function approve() { + const a = accepted.value + if (!approveReady.value || !a) return + void decide((id) => api.approveOAuthAuthorization(id, JSON.parse(a.key))) +} + +function deny() { + void decide((id) => api.denyOAuthAuthorization(id)) +} + async function handleDecisionError(e: unknown) { if (!(e instanceof ApiError)) { errorText.value = e instanceof Error ? e.message : 'The request failed.' @@ -350,19 +396,6 @@ async function handleDecisionError(e: unknown) { else errorText.value = e.message } -async function deny() { - submitting.value = true - errorText.value = '' - try { - const res = await api.denyOAuthAuthorization(requestId.value) - navigateTo(res.redirect_url) - } catch (e) { - await handleDecisionError(e) - } finally { - submitting.value = false - } -} - function submitKey() { const key = pastedKey.value.trim() if (!key) return diff --git a/frontend/tests/unit/authorize-request-race.spec.ts b/frontend/tests/unit/authorize-request-race.spec.ts new file mode 100644 index 000000000..03fe82907 --- /dev/null +++ b/frontend/tests/unit/authorize-request-race.spec.ts @@ -0,0 +1,269 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import { createMemoryHistory, createRouter } from 'vue-router' +import AuthorizeRequest from '@/views/AuthorizeRequest.vue' +import api from '@/services/api' +import { navigateTo } from '@/utils/navigate' + +vi.mock('@/services/api', async (orig) => { + const actual = await orig() + return { + ...actual, + default: { + hasAPIKey: vi.fn(() => true), + setAPIKey: vi.fn(), + getOAuthAuthorization: vi.fn(), + previewOAuthAuthorization: vi.fn(), + approveOAuthAuthorization: vi.fn(), + denyOAuthAuthorization: vi.fn(), + }, + } +}) +vi.mock('@/utils/navigate', () => ({ navigateTo: vi.fn() })) + +const A = api as any +const bound = { profile: 'dev-readonly', mode: 'locked', revision: 'rev1' } +const t = (w: any, id: string) => w.find(`[data-test="${id}"]`) + +function detail(id: string, over: Record = {}) { + return { + id, status: 'pending', expires_at: '2026-11-23T12:10:00Z', reported_name: 'Cursor IDE', + redirect_uri: 'http://127.0.0.1:54321/callback', resource: 'http://127.0.0.1:8080/mcp/oauth/cursor', + address_kind: 'client', + client: { id: 'cursor', display_name: 'Cursor', exists: true, has_api_key: true, logins: 1, binding: bound }, + profiles: [{ name: 'dev-readonly' }, { name: 'ops' }], profile_required: false, guard: null, ...over, + } +} + +function generic(id: string, over: Record = {}) { + return detail(id, { + address_kind: 'generic', client: undefined, resource: 'http://127.0.0.1:8080/mcp/oauth', + existing_clients: [ + { id: 'codex', display_name: 'Codex', binding: { profile: 'ops', mode: 'switchable', revision: 'rc' } }, + { id: 'cursor', display_name: 'Cursor', binding: bound }, + ], + suggested_new_client: { id: 'acme-agent', display_name: 'Acme Agent' }, + profile_required: true, ...over, + }) +} + +const complete = (body: any) => ({ + complete: true, + access: { client: body.client?.id ?? body.client?.new?.id, profile: body.profile ?? 'dev-readonly', mode: body.mode ?? 'locked', same_access_as_existing_client: !!body.binding_revision }, + guard: null, +}) + +function deferred() { + let resolve!: (v: T) => void + let reject!: (e: unknown) => void + const promise = new Promise((res, rej) => { resolve = res; reject = rej }) + return { promise, resolve, reject } +} + +async function mountAt(details: Record, query = '?request=r1') { + A.getOAuthAuthorization.mockImplementation(async (id: string) => details[id]) + const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/authorize', component: AuthorizeRequest }, { path: '/settings', component: { template: '
' } }] }) + await router.push('/authorize' + query) + const w = mount(AuthorizeRequest, { global: { plugins: [router] } }) + await flushPromises() + return { w, router } +} + +beforeEach(() => { + vi.clearAllMocks() + A.hasAPIKey.mockReturnValue(true) + A.previewOAuthAuthorization.mockImplementation(async (_id: string, body: any) => complete(body)) +}) + +describe('AuthorizeRequest: request id changes in the same component', () => { + it('drops r1 at once, shows r2 and binds both decisions to the displayed request', async () => { + const slow = deferred() + const { w, router } = await mountAt({ r1: detail('r1', { reported_name: 'First App' }), r2: detail('r2', { reported_name: 'Second App' }) }) + expect(t(w, 'authorize-reported').text()).toContain('First App') + + A.getOAuthAuthorization.mockImplementation((id: string) => (id === 'r2' ? slow.promise : Promise.resolve(detail(id)))) + await router.push('/authorize?request=r2') + await flushPromises() + // r2 is still loading: r1 must not be on screen or decidable. + expect(w.text()).not.toContain('First App') + expect(t(w, 'authorize-approve').exists()).toBe(false) + expect(t(w, 'authorize-deny').exists()).toBe(false) + + slow.resolve(detail('r2', { reported_name: 'Second App' })) + await flushPromises() + expect(t(w, 'authorize-reported').text()).toContain('Second App') + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization).toHaveBeenCalledWith('r2', expect.anything()) + expect(A.approveOAuthAuthorization).not.toHaveBeenCalledWith('r1', expect.anything()) + }) + + it('ignores a late answer for the request that was left', async () => { + const late = deferred() + A.getOAuthAuthorization.mockImplementation((id: string) => (id === 'r1' ? late.promise : Promise.resolve(detail(id, { reported_name: 'Second App' })))) + const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/authorize', component: AuthorizeRequest }] }) + await router.push('/authorize?request=r1') + const w = mount(AuthorizeRequest, { global: { plugins: [router] } }) + await flushPromises() + await router.push('/authorize?request=r2') + await flushPromises() + late.resolve(detail('r1', { reported_name: 'First App' })) + await flushPromises() + expect(t(w, 'authorize-reported').text()).toContain('Second App') + A.denyOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?error=access_denied' }) + await t(w, 'authorize-deny').trigger('click') + await flushPromises() + expect(A.denyOAuthAuthorization).toHaveBeenCalledWith('r2') + }) +}) + +describe('AuthorizeRequest: Approve needs a complete, current preview', () => { + it('stays disabled on {complete:false} and while the preview is pending', async () => { + const first = deferred() + A.previewOAuthAuthorization.mockImplementation(() => first.promise) + const { w } = await mountAt({ r1: detail('r1') }) + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + first.resolve({ complete: false, guard: null }) + await flushPromises() + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + expect(t(w, 'authorize-access').exists()).toBe(false) + }) + + it('ignores an out-of-order preview and sends the body the accepted preview was for', async () => { + const p1 = deferred() + const p2 = deferred() + const pending: Array<[any, ReturnType>]> = [] + A.previewOAuthAuthorization.mockImplementation((_id: string, body: any) => { + const d = pending.length === 0 ? p1 : p2 + pending.push([body, d]) + return d.promise + }) + const { w } = await mountAt({ r1: generic('r1') }) + // First preview (new client acme-agent, no profile yet) is not even asked: incomplete. Choose ops. + await t(w, 'authorize-profile-select').setValue('ops') + await flushPromises() + expect(pending).toHaveLength(1) + await t(w, 'authorize-client-select').setValue('codex') + await flushPromises() + expect(pending).toHaveLength(2) + // The newer preview (codex) answers first; the stale one (acme-agent) arrives late. + p2.resolve(complete(pending[1][0])) + await flushPromises() + p1.resolve(complete(pending[0][0])) + await flushPromises() + expect(t(w, 'authorize-access').text()).toContain('Codex') + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization).toHaveBeenCalledWith('r1', pending[1][0]) + }) + + it('disables Approve again as soon as the choice changes, until its preview answers', async () => { + const { w } = await mountAt({ r1: generic('r1') }) + await t(w, 'authorize-profile-select').setValue('ops') + await flushPromises() + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + const next = deferred() + A.previewOAuthAuthorization.mockImplementation(() => next.promise) + await t(w, 'authorize-client-select').setValue('codex') + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + expect(t(w, 'authorize-access').exists()).toBe(false) + next.resolve(complete({ client: { id: 'codex' }, binding_revision: 'rc' })) + await flushPromises() + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + }) +}) + +describe('AuthorizeRequest: replacing the previous login', () => { + const prev = { grant_id: 'gc', client_id: 'cursor', approved_at: '2026-11-03T10:00:00Z' } + + it('offers it only for the client that owns it, and sends the exact body', async () => { + const { w } = await mountAt({ r1: generic('r1', { previous_login: prev, suggested_client: { id: 'cursor', matched: 'id' } }) }) + expect(t(w, 'authorize-replace').exists()).toBe(true) + + await t(w, 'authorize-client-select').setValue('codex') + await flushPromises() + expect(t(w, 'authorize-replace').exists()).toBe(false) + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization).toHaveBeenLastCalledWith('r1', { client: { id: 'codex' }, binding_revision: 'rc' }) + }) + + it('does not show or send it for a new client, and brings it back for the owner', async () => { + const { w } = await mountAt({ r1: generic('r1', { previous_login: prev, suggested_client: { id: 'cursor', matched: 'id' } }) }) + await t(w, 'authorize-client-select').setValue('__new__') + await flushPromises() + expect(t(w, 'authorize-replace').exists()).toBe(false) + await t(w, 'authorize-profile-select').setValue('ops') + await flushPromises() + expect(A.previewOAuthAuthorization.mock.calls.at(-1)![1].replace_grant).toBeUndefined() + await t(w, 'authorize-client-select').setValue('cursor') + await flushPromises() + expect(t(w, 'authorize-replace').exists()).toBe(true) + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization).toHaveBeenLastCalledWith('r1', { client: { id: 'cursor' }, binding_revision: 'rev1', replace_grant: 'gc' }) + }) +}) + +describe('AuthorizeRequest: new-client draft', () => { + it('is populated from suggested_new_client when the page opened on a suggested client', async () => { + const { w } = await mountAt({ r1: generic('r1', { suggested_client: { id: 'cursor', matched: 'id' } }) }) + expect(t(w, 'authorize-new-id').exists()).toBe(false) + await t(w, 'authorize-client-select').setValue('__new__') + await flushPromises() + expect((t(w, 'authorize-new-id').element as HTMLInputElement).value).toBe('acme-agent') + expect((t(w, 'authorize-new-name').element as HTMLInputElement).value).toBe('Acme Agent') + await t(w, 'authorize-profile-select').setValue('ops') + await flushPromises() + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization).toHaveBeenLastCalledWith('r1', { + client: { new: { id: 'acme-agent', display_name: 'Acme Agent' } }, profile: 'ops', mode: 'locked', + }) + }) +}) + +describe('AuthorizeRequest: one decision per request', () => { + it('ignores repeated and mixed clicks while a decision is in flight, and stays decided after success', async () => { + const d = deferred() + const { w } = await mountAt({ r1: detail('r1') }) + A.approveOAuthAuthorization.mockImplementation(() => d.promise) + await t(w, 'authorize-approve').trigger('click') + await t(w, 'authorize-approve').trigger('click') + await t(w, 'authorize-deny').trigger('click') + expect(A.approveOAuthAuthorization).toHaveBeenCalledTimes(1) + expect(A.denyOAuthAuthorization).not.toHaveBeenCalled() + d.resolve({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + await flushPromises() + expect(navigateTo).toHaveBeenCalledTimes(1) + // Terminal: the buttons stay disabled and no second decision is possible. + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + expect(t(w, 'authorize-deny').attributes('disabled')).toBeDefined() + await t(w, 'authorize-approve').trigger('click') + await t(w, 'authorize-deny').trigger('click') + expect(A.approveOAuthAuthorization).toHaveBeenCalledTimes(1) + expect(A.denyOAuthAuthorization).not.toHaveBeenCalled() + }) + + it('guards Deny too, and releases the buttons after a recoverable failure', async () => { + const d = deferred() + const { w } = await mountAt({ r1: detail('r1') }) + A.denyOAuthAuthorization.mockImplementation(() => d.promise) + await t(w, 'authorize-deny').trigger('click') + await t(w, 'authorize-deny').trigger('click') + await t(w, 'authorize-approve').trigger('click') + expect(A.denyOAuthAuthorization).toHaveBeenCalledTimes(1) + expect(A.approveOAuthAuthorization).not.toHaveBeenCalled() + d.reject(new Error('network down')) + await flushPromises() + expect(t(w, 'authorize-error').text()).toContain('network down') + expect(t(w, 'authorize-deny').attributes('disabled')).toBeUndefined() + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + expect(navigateTo).not.toHaveBeenCalled() + }) +}) diff --git a/frontend/tests/unit/authorize-request.spec.ts b/frontend/tests/unit/authorize-request.spec.ts index 3e4741187..ae32c32b4 100644 --- a/frontend/tests/unit/authorize-request.spec.ts +++ b/frontend/tests/unit/authorize-request.spec.ts @@ -119,7 +119,8 @@ describe('AuthorizeRequest: per-client address', () => { const without = await mountPage(base()) expect(t(without, 'authorize-replace').exists()).toBe(false) - const w = await mountPage(base({ previous_login: { grant_id: 'g1', approved_at: '2026-11-03T10:00:00Z' } })) + const prev = { grant_id: 'g1', client_id: 'cursor', approved_at: '2026-11-03T10:00:00Z' } + const w = await mountPage(base({ previous_login: prev })) const box = t(w, 'authorize-replace') expect(box.exists()).toBe(true) expect((box.element as HTMLInputElement).checked).toBe(true) @@ -131,8 +132,12 @@ describe('AuthorizeRequest: per-client address', () => { })) expect(navigateTo).toHaveBeenCalledWith('http://127.0.0.1:54321/callback?code=c&state=s') - await box.setValue(false) - await t(w, 'authorize-approve').trigger('click') + // A fresh page with the box unchecked sends no replace_grant. + const w2 = await mountPage(base({ previous_login: prev })) + await t(w2, 'authorize-replace').setValue(false) + await flushPromises() + A.approveOAuthAuthorization.mockClear() + await t(w2, 'authorize-approve').trigger('click') await flushPromises() expect(A.approveOAuthAuthorization.mock.calls.at(-1)![1].replace_grant).toBeUndefined() }) diff --git a/internal/runtime/oauth_login_consent.go b/internal/runtime/oauth_login_consent.go index 7870ab6f0..f5b688cfa 100644 --- a/internal/runtime/oauth_login_consent.go +++ b/internal/runtime/oauth_login_consent.go @@ -230,6 +230,7 @@ type ProfileChoice struct { // PreviousLogin is a live login of THIS registration. type PreviousLogin struct { GrantID string `json:"grant_id"` + ClientID string `json:"client_id"` // the client that owns the login ApprovedAt time.Time `json:"approved_at"` } @@ -349,7 +350,7 @@ func (s *OAuthLoginService) Describe(ctx context.Context, requestID string) (*Au liveByClient[g.Client]++ if g.RegistrationID == reg.ClientID && (req.PathClient == "" || g.Client == req.PathClient) && (v.PreviousLogin == nil || g.ApprovedAt.After(v.PreviousLogin.ApprovedAt)) { - v.PreviousLogin = &PreviousLogin{GrantID: g.GrantID, ApprovedAt: g.ApprovedAt} + v.PreviousLogin = &PreviousLogin{GrantID: g.GrantID, ClientID: g.Client, ApprovedAt: g.ApprovedAt} } } } @@ -757,10 +758,15 @@ func (s *OAuthLoginService) resolveChoice(req mcplogin.Request, c ApprovalChoice } // 3. Replace the previous login: only a live login of THIS registration - // and of this client; anything else is ignored, never revoked. + // and of this client; anything else is ignored, never revoked. A live login + // of this registration that belongs to ANOTHER client is refused: the page + // asked to replace a login of a client it is not signing in. if c.ReplaceGrant != "" { - if g, err := s.store.GetOAuthGrant(c.ReplaceGrant); err == nil && g != nil && g.Client == rc.clientID && + if g, err := s.store.GetOAuthGrant(c.ReplaceGrant); err == nil && g != nil && !g.Revoked && g.RefreshExpiresAt.After(s.now()) && g.RegistrationID == req.RegistrationID { + if g.Client != rc.clientID { + return nil, &ValidationError{Field: "replace_grant", Message: "that login belongs to another client"} + } rc.replace = g.GrantID } } diff --git a/internal/runtime/oauth_login_replace_owner_test.go b/internal/runtime/oauth_login_replace_owner_test.go new file mode 100644 index 000000000..a7155781f --- /dev/null +++ b/internal/runtime/oauth_login_replace_owner_test.go @@ -0,0 +1,44 @@ +package runtime + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// A login of this registration that belongs to ANOTHER client is never +// replaced by approving a different client: the choice is refused and the +// request stays pending. +func TestOAuthApprove_ReplaceGrantOfAnotherClientIsRefused(t *testing.T) { + fx := newOAuthFx(t) + reg, _ := fx.loginNew("cursor", "ro") + cursorGrant := fx.grants()[0] + fx.mintClient("codex", "rw", auth.ProfileModeSwitchable) + + id := fx.authorize(reg, "") + v, err := fx.svc.Describe(fx.ctx(), id) + require.NoError(t, err) + require.NotNil(t, v.PreviousLogin) + assert.Equal(t, "cursor", v.PreviousLogin.ClientID, "the view says which client owns the previous login") + + rev, _ := fx.sm.ClientBindingRevision("codex") + body := ApprovalChoice{Client: ClientChoice{ID: "codex"}, BindingRevision: rev, ReplaceGrant: cursorGrant.GrantID} + _, err = fx.svc.Approve(fx.ctx(), id, body) + var ve *ValidationError + require.ErrorAs(t, err, &ve) + assert.Equal(t, "replace_grant", ve.Field) + _, err = fx.svc.Preview(fx.ctx(), id, body) + assert.ErrorAs(t, err, &ve) + assert.Len(t, fx.svc.ListPending(), 1, "refused, still pending") + for _, g := range fx.grants() { + assert.False(t, g.Revoked) + } + + // The owner may replace it. + cursorRev, _ := fx.sm.ClientBindingRevision("cursor") + _, err = fx.svc.Approve(fx.ctx(), id, ApprovalChoice{Client: ClientChoice{ID: "cursor"}, BindingRevision: cursorRev, ReplaceGrant: cursorGrant.GrantID}) + assert.NoError(t, err) +} From db9a666cc7c16ed35aeda11149becc09b1f84f82 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 13:27:01 +0200 Subject: [PATCH 29/42] fix(oauth): consent page review round 2 (Spec 132 PR-2a) - Decision answers are ignored once the request was left (new id) or the page unmounted: no navigation, no state change, no release of a newer request's pending decision. - A preview refused with binding_changed reloads the request (keeping the user's choice when it still exists) and shows the review-again notice. - With no profiles configured an unbound client starts on "All servers", so the select shows what is submitted. Related #1971 --- frontend/src/views/AuthorizeRequest.vue | 32 +++- .../unit/authorize-request-round2.spec.ts | 169 ++++++++++++++++++ 2 files changed, 199 insertions(+), 2 deletions(-) create mode 100644 frontend/tests/unit/authorize-request-round2.spec.ts diff --git a/frontend/src/views/AuthorizeRequest.vue b/frontend/src/views/AuthorizeRequest.vue index d4a6fef01..fcec0a963 100644 --- a/frontend/src/views/AuthorizeRequest.vue +++ b/frontend/src/views/AuthorizeRequest.vue @@ -132,7 +132,7 @@ // - Approve needs a complete preview, with access, for the CURRENT choice, and // sends exactly the body that preview answered; // - one decision per page: after success the buttons stay disabled. -import { computed, onMounted, ref, watch } from 'vue' +import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue' import { useRoute } from 'vue-router' import api, { ApiError } from '@/services/api' import { navigateTo } from '@/utils/navigate' @@ -282,7 +282,8 @@ function resetPage(keepNote = false) { } function resetChoice(v: OAuthAuthorization) { - profileSel.value = UNSET + // With no profiles configured the select has no placeholder: All servers. + profileSel.value = v.profiles.length === 0 ? ALL : UNSET lock.value = true replace.value = !!v.previous_login // The new-client draft is always ready, whatever is selected first. @@ -293,6 +294,10 @@ function resetChoice(v: OAuthAuthorization) { } async function load(keepNote = false) { + // A review-again reload keeps what the user chose, when it still exists. + const kept = keepNote + ? { selected: selected.value, newId: newId.value, newName: newName.value, profileSel: profileSel.value, lock: lock.value, replace: replace.value } + : null resetPage(keepNote) const id = requestId.value if (!id) { @@ -307,6 +312,14 @@ async function load(keepNote = false) { view.value = v loadedId.value = id resetChoice(v) + if (kept && v.address_kind === 'generic' && (kept.selected === NEW || v.existing_clients?.some((c) => c.id === kept.selected))) { + selected.value = kept.selected + newId.value = kept.newId + newName.value = kept.newName + profileSel.value = kept.profileSel + lock.value = kept.lock + replace.value = kept.replace + } phase.value = 'ready' } catch (e) { if (gen !== loadGen) return @@ -334,6 +347,11 @@ async function runPreview(id: string, key: string) { phase.value = 'gone' return } + if (e instanceof ApiError && e.code === 'binding_changed') { + await load(true) + changedNote.value = true + return + } previewFailed.value = true errorText.value = e instanceof Error ? e.message : 'Could not check this choice.' } @@ -361,11 +379,16 @@ async function decide(call: (id: string) => Promise) { if (busy.value || !loadedId.value) return submitting.value = true errorText.value = '' + // An answer for a request that was left (new id, unmount) is obsolete: it + // must not navigate, hide, disable or release anything on the page now shown. + const gen = loadGen try { const res = await call(loadedId.value) + if (gen !== loadGen) return decided.value = true // terminal: stays disabled while the browser leaves navigateTo(res.redirect_url) } catch (e) { + if (gen !== loadGen) return submitting.value = false await handleDecisionError(e) } @@ -404,6 +427,11 @@ function submitKey() { void load() } +onBeforeUnmount(() => { + loadGen++ + previewSeq++ +}) + onMounted(() => { if (!api.hasAPIKey()) { phase.value = 'nokey' diff --git a/frontend/tests/unit/authorize-request-round2.spec.ts b/frontend/tests/unit/authorize-request-round2.spec.ts new file mode 100644 index 000000000..a26264cb5 --- /dev/null +++ b/frontend/tests/unit/authorize-request-round2.spec.ts @@ -0,0 +1,169 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import { createMemoryHistory, createRouter } from 'vue-router' +import AuthorizeRequest from '@/views/AuthorizeRequest.vue' +import api, { ApiError } from '@/services/api' +import { navigateTo } from '@/utils/navigate' + +vi.mock('@/services/api', async (orig) => { + const actual = await orig() + return { + ...actual, + default: { + hasAPIKey: vi.fn(() => true), + setAPIKey: vi.fn(), + getOAuthAuthorization: vi.fn(), + previewOAuthAuthorization: vi.fn(), + approveOAuthAuthorization: vi.fn(), + denyOAuthAuthorization: vi.fn(), + }, + } +}) +vi.mock('@/utils/navigate', () => ({ navigateTo: vi.fn() })) + +const A = api as any +const t = (w: any, id: string) => w.find(`[data-test="${id}"]`) + +function detail(id: string, over: Record = {}) { + return { + id, status: 'pending', expires_at: '2026-11-23T12:10:00Z', reported_name: `App ${id}`, + redirect_uri: 'http://127.0.0.1:54321/callback', resource: 'http://127.0.0.1:8080/mcp/oauth/cursor', + address_kind: 'client', + client: { id: 'cursor', display_name: 'Cursor', exists: true, has_api_key: true, logins: 1, binding: { profile: 'dev', mode: 'locked', revision: 'rev1' } }, + profiles: [{ name: 'dev' }], profile_required: false, guard: null, ...over, + } +} + +const complete = (body: any) => ({ + complete: true, + access: { client: body.client?.id ?? body.client?.new?.id, profile: body.profile ?? 'dev', mode: body.mode ?? 'locked', same_access_as_existing_client: !!body.binding_revision }, + guard: null, +}) + +function deferred() { + let resolve!: (v: T) => void + let reject!: (e: unknown) => void + const promise = new Promise((res, rej) => { resolve = res; reject = rej }) + return { promise, resolve, reject } +} + +async function mountAt(details: Record, query = '?request=r1') { + A.getOAuthAuthorization.mockImplementation(async (id: string) => details[id]) + const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/authorize', component: AuthorizeRequest }] }) + await router.push('/authorize' + query) + const w = mount(AuthorizeRequest, { global: { plugins: [router] } }) + await flushPromises() + return { w, router } +} + +beforeEach(() => { + vi.clearAllMocks() + A.hasAPIKey.mockReturnValue(true) + A.previewOAuthAuthorization.mockImplementation(async (_id: string, body: any) => complete(body)) +}) + +describe('obsolete decision responses are ignored', () => { + async function pendingApproveThenNavigate() { + const d = deferred() + const ctx = await mountAt({ r1: detail('r1'), r2: detail('r2') }) + A.approveOAuthAuthorization.mockImplementationOnce(() => d.promise) + await t(ctx.w, 'authorize-approve').trigger('click') + await ctx.router.push('/authorize?request=r2') + await flushPromises() + return { ...ctx, d } + } + + it('a successful r1 answer neither navigates nor disables r2', async () => { + const { w, d } = await pendingApproveThenNavigate() + d.resolve({ redirect_url: 'http://127.0.0.1:1/cb?code=r1' }) + await flushPromises() + expect(navigateTo).not.toHaveBeenCalled() + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + expect(t(w, 'authorize-deny').attributes('disabled')).toBeUndefined() + }) + + it('an already_decided / 404 answer for r1 does not hide r2', async () => { + const { w, d } = await pendingApproveThenNavigate() + d.reject(new ApiError(409, { code: 'already_decided', error: 'decided' }, 'x')) + await flushPromises() + expect(t(w, 'authorize-decided').exists()).toBe(false) + expect(t(w, 'authorize-gone').exists()).toBe(false) + expect(t(w, 'authorize-approve').exists()).toBe(true) + }) + + it("a failure of r1 does not release r2's own pending decision", async () => { + const { w, d } = await pendingApproveThenNavigate() + const d2 = deferred() + A.approveOAuthAuthorization.mockImplementationOnce(() => d2.promise) + await t(w, 'authorize-approve').trigger('click') + expect(A.approveOAuthAuthorization).toHaveBeenCalledTimes(2) + d.reject(new Error('network down')) + await flushPromises() + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + await t(w, 'authorize-approve').trigger('click') + expect(A.approveOAuthAuthorization).toHaveBeenCalledTimes(2) + expect(t(w, 'authorize-error').exists()).toBe(false) + }) + + it('a deny answer for r1 is ignored after navigating to r2', async () => { + const d = deferred() + const { w, router } = await mountAt({ r1: detail('r1'), r2: detail('r2') }) + A.denyOAuthAuthorization.mockImplementationOnce(() => d.promise) + await t(w, 'authorize-deny').trigger('click') + await router.push('/authorize?request=r2') + await flushPromises() + d.resolve({ redirect_url: 'http://127.0.0.1:1/cb?error=access_denied' }) + await flushPromises() + expect(navigateTo).not.toHaveBeenCalled() + expect(t(w, 'authorize-deny').attributes('disabled')).toBeUndefined() + }) + + it('an answer that arrives after the component is unmounted does nothing', async () => { + const d = deferred() + const { w } = await mountAt({ r1: detail('r1') }) + A.approveOAuthAuthorization.mockImplementationOnce(() => d.promise) + await t(w, 'authorize-approve').trigger('click') + w.unmount() + d.resolve({ redirect_url: 'http://127.0.0.1:1/cb?code=late' }) + await flushPromises() + expect(navigateTo).not.toHaveBeenCalled() + }) +}) + +describe('binding_changed from the preview call', () => { + it('on a generic page: a refused preview reloads with the new revision', async () => { + const generic = (rev: string) => detail('r1', { + address_kind: 'generic', client: undefined, + existing_clients: [{ id: 'codex', display_name: 'Codex', binding: { profile: 'ops', mode: 'switchable', revision: rev } }], + suggested_new_client: { id: 'acme', display_name: 'Acme' }, profile_required: true, + }) + const { w } = await mountAt({ r1: generic('rc1') }) + A.getOAuthAuthorization.mockImplementation(async () => generic('rc2')) + A.previewOAuthAuthorization.mockImplementation(async (_id: string, body: any) => { + if (body.binding_revision === 'rc1') throw new ApiError(409, { code: 'binding_changed', error: 'changed' }, 'x') + return complete(body) + }) + await t(w, 'authorize-client-select').setValue('codex') + await flushPromises() + expect(t(w, 'authorize-changed').exists()).toBe(true) + expect(A.previewOAuthAuthorization.mock.calls.at(-1)![1].binding_revision).toBe('rc2') + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + }) +}) + +describe('unbound client with no profiles configured', () => { + it('shows "All servers" selected and submits the empty profile', async () => { + const d = detail('r1', { + profiles: [], profile_required: false, + client: { id: 'cursor', display_name: 'Cursor', exists: false, has_api_key: false, logins: 0 }, + }) + const { w } = await mountAt({ r1: d }) + const select = t(w, 'authorize-profile-select') + expect((select.element as HTMLSelectElement).value).toBe('__all__') + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization).toHaveBeenCalledWith('r1', { client: { id: 'cursor' }, profile: '' }) + }) +}) From 313f261efac2ad521ebd4cd0e5eb523979c73f71 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 13:31:20 +0200 Subject: [PATCH 30/42] fix(oauth): consent page review round 3 (Spec 132 PR-2a) - A review-again reload validates every kept choice against the reloaded data: profile (All servers when none remain, unset when the named one is gone), client, lock and replace flags. - Every choice control is disabled while a decision is pending or done. - The review-again notice is set only when the reload's generation was applied, so it cannot appear on another request. Related #1971 --- frontend/src/views/AuthorizeRequest.vue | 39 ++-- .../unit/authorize-request-round3.spec.ts | 195 ++++++++++++++++++ 2 files changed, 219 insertions(+), 15 deletions(-) create mode 100644 frontend/tests/unit/authorize-request-round3.spec.ts diff --git a/frontend/src/views/AuthorizeRequest.vue b/frontend/src/views/AuthorizeRequest.vue index fcec0a963..02a0b0285 100644 --- a/frontend/src/views/AuthorizeRequest.vue +++ b/frontend/src/views/AuthorizeRequest.vue @@ -55,6 +55,7 @@ +
@@ -84,6 +85,7 @@ @@ -100,7 +102,7 @@

{{ accessSentence }}

@@ -293,41 +295,50 @@ function resetChoice(v: OAuthAuthorization) { else selected.value = '' } -async function load(keepNote = false) { +async function load(keepNote = false): Promise { // A review-again reload keeps what the user chose, when it still exists. const kept = keepNote - ? { selected: selected.value, newId: newId.value, newName: newName.value, profileSel: profileSel.value, lock: lock.value, replace: replace.value } + ? { + selected: selected.value, newId: newId.value, newName: newName.value, profileSel: profileSel.value, + lock: lock.value, replace: replace.value, grant: view.value?.previous_login?.grant_id ?? '', + } : null resetPage(keepNote) const id = requestId.value if (!id) { phase.value = 'gone' - return + return false } phase.value = 'loading' const gen = loadGen try { const v = await api.getOAuthAuthorization(id) - if (gen !== loadGen) return + if (gen !== loadGen) return false view.value = v loadedId.value = id resetChoice(v) if (kept && v.address_kind === 'generic' && (kept.selected === NEW || v.existing_clients?.some((c) => c.id === kept.selected))) { + // Every kept value is checked against the reloaded data. selected.value = kept.selected newId.value = kept.newId newName.value = kept.newName - profileSel.value = kept.profileSel + const names = v.profiles.map((p) => p.name) + if (names.length === 0) profileSel.value = ALL + else if (kept.profileSel === ALL || names.includes(kept.profileSel)) profileSel.value = kept.profileSel + else profileSel.value = UNSET lock.value = kept.lock - replace.value = kept.replace + replace.value = v.previous_login ? (v.previous_login.grant_id === kept.grant ? kept.replace : true) : false } phase.value = 'ready' + return true } catch (e) { - if (gen !== loadGen) return + if (gen !== loadGen) return false if (e instanceof ApiError && e.status === 404) phase.value = 'gone' else { errorText.value = e instanceof Error ? e.message : 'Could not load the request.' phase.value = 'error' } + return false } } @@ -348,8 +359,7 @@ async function runPreview(id: string, key: string) { return } if (e instanceof ApiError && e.code === 'binding_changed') { - await load(true) - changedNote.value = true + if (await load(true)) changedNote.value = true return } previewFailed.value = true @@ -411,8 +421,7 @@ async function handleDecisionError(e: unknown) { } if (e.code === 'already_decided') phase.value = 'decided' else if (e.code === 'binding_changed') { - await load(true) - changedNote.value = true + if (await load(true)) changedNote.value = true } else if (e.code === 'binding_bypassable_without_auth') { guardOverride.value = { code: e.code, bindings: e.bindings ?? [], fixes: e.fixes ?? [] } } else if (e.status === 404 && e.code !== 'profile_not_found') phase.value = 'gone' diff --git a/frontend/tests/unit/authorize-request-round3.spec.ts b/frontend/tests/unit/authorize-request-round3.spec.ts new file mode 100644 index 000000000..fd7d563b6 --- /dev/null +++ b/frontend/tests/unit/authorize-request-round3.spec.ts @@ -0,0 +1,195 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import { createMemoryHistory, createRouter } from 'vue-router' +import AuthorizeRequest from '@/views/AuthorizeRequest.vue' +import api, { ApiError } from '@/services/api' +import { navigateTo } from '@/utils/navigate' + +vi.mock('@/services/api', async (orig) => { + const actual = await orig() + return { + ...actual, + default: { + hasAPIKey: vi.fn(() => true), + setAPIKey: vi.fn(), + getOAuthAuthorization: vi.fn(), + previewOAuthAuthorization: vi.fn(), + approveOAuthAuthorization: vi.fn(), + denyOAuthAuthorization: vi.fn(), + }, + } +}) +vi.mock('@/utils/navigate', () => ({ navigateTo: vi.fn() })) + +const A = api as any +const t = (w: any, id: string) => w.find(`[data-test="${id}"]`) + +function generic(id: string, over: Record = {}) { + return { + id, status: 'pending', expires_at: '2026-11-23T12:10:00Z', reported_name: `App ${id}`, + redirect_uri: 'http://127.0.0.1:54321/callback', resource: 'http://127.0.0.1:8080/mcp/oauth', + address_kind: 'generic', + existing_clients: [ + { id: 'codex', display_name: 'Codex', binding: { profile: 'ops', mode: 'switchable', revision: 'rc' } }, + { id: 'cursor', display_name: 'Cursor', binding: { profile: 'dev', mode: 'locked', revision: 'rv' } }, + ], + suggested_new_client: { id: 'acme', display_name: 'Acme' }, + profiles: [{ name: 'ops' }, { name: 'dev' }], profile_required: true, guard: null, ...over, + } +} + +const complete = (body: any) => ({ + complete: true, + access: { client: body.client?.id ?? body.client?.new?.id, profile: body.profile ?? '', mode: body.mode ?? 'locked', same_access_as_existing_client: !!body.binding_revision }, + guard: null, +}) + +function deferred() { + let resolve!: (v: T) => void + let reject!: (e: unknown) => void + const promise = new Promise((res, rej) => { resolve = res; reject = rej }) + return { promise, resolve, reject } +} + +async function mountAt(details: Record) { + A.getOAuthAuthorization.mockImplementation(async (id: string) => details[id]) + const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/authorize', component: AuthorizeRequest }] }) + await router.push('/authorize?request=r1') + const w = mount(AuthorizeRequest, { global: { plugins: [router] } }) + await flushPromises() + return { w, router } +} + +const changed = () => new ApiError(409, { code: 'binding_changed', error: 'changed' }, 'x') + +beforeEach(() => { + vi.clearAllMocks() + A.hasAPIKey.mockReturnValue(true) + A.previewOAuthAuthorization.mockImplementation(async (_id: string, body: any) => complete(body)) +}) + +describe('review-again reload validates what it keeps', () => { + it('a kept named profile that no profiles remain for becomes All servers (select and body agree)', async () => { + const { w } = await mountAt({ r1: generic('r1') }) + await t(w, 'authorize-profile-select').setValue('ops') + await flushPromises() + // The next preview is refused; the reload finds that every profile was deleted. + A.previewOAuthAuthorization.mockImplementationOnce(async () => { throw changed() }) + A.getOAuthAuthorization.mockImplementation(async () => generic('r1', { profiles: [], profile_required: false })) + await t(w, 'authorize-new-id').setValue('acme2') + await t(w, 'authorize-new-id').trigger('change') + await flushPromises() + expect((t(w, 'authorize-profile-select').element as HTMLSelectElement).value).toBe('__all__') + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization.mock.calls.at(-1)![1].profile).toBe('') + }) + + it('a kept unset choice with no profiles left becomes All servers', async () => { + const { w } = await mountAt({ r1: generic('r1') }) + expect((t(w, 'authorize-profile-select').element as HTMLSelectElement).value).toBe('__unset__') + A.getOAuthAuthorization.mockImplementation(async () => generic('r1', { profiles: [], profile_required: false })) + A.previewOAuthAuthorization.mockImplementationOnce(async () => { throw changed() }) + await t(w, 'authorize-client-select').setValue('codex') + await flushPromises() + await t(w, 'authorize-client-select').setValue('__new__') + await flushPromises() + expect((t(w, 'authorize-profile-select').element as HTMLSelectElement).value).toBe('__all__') + }) + + it('a kept named profile that was deleted (others remain) goes back to unset and Approve stays disabled', async () => { + const { w } = await mountAt({ r1: generic('r1') }) + await t(w, 'authorize-profile-select').setValue('ops') + await flushPromises() + A.previewOAuthAuthorization.mockImplementationOnce(async () => { throw changed() }) + A.getOAuthAuthorization.mockImplementation(async () => generic('r1', { profiles: [{ name: 'dev' }] })) + await t(w, 'authorize-new-id').setValue('acme2') + await t(w, 'authorize-new-id').trigger('change') + await flushPromises() + expect((t(w, 'authorize-profile-select').element as HTMLSelectElement).value).toBe('__unset__') + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + }) + + it('a kept replace flag does not survive a previous login that is gone', async () => { + const prev = { grant_id: 'g1', client_id: 'cursor', approved_at: '2026-11-03T10:00:00Z' } + const { w } = await mountAt({ r1: generic('r1', { previous_login: prev, suggested_client: { id: 'cursor', matched: 'id' } }) }) + await t(w, 'authorize-replace').setValue(false) + A.previewOAuthAuthorization.mockImplementationOnce(async () => { throw changed() }) + A.getOAuthAuthorization.mockImplementation(async () => generic('r1', { previous_login: { ...prev, grant_id: 'g2' } })) + await t(w, 'authorize-client-select').setValue('cursor') + await t(w, 'authorize-client-select').trigger('change') + // Force a preview on the same client by switching away and back. + await t(w, 'authorize-client-select').setValue('codex') + await flushPromises() + await t(w, 'authorize-client-select').setValue('cursor') + await flushPromises() + const box = t(w, 'authorize-replace') + if (box.exists()) { + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + const sent = A.approveOAuthAuthorization.mock.calls.at(-1)![1] + expect(sent.replace_grant === undefined).toBe(!(box.element as HTMLInputElement).checked) + } + }) +}) + +describe('choice controls are frozen while a decision is pending or done', () => { + const controls = ['authorize-client-select', 'authorize-profile-select'] + + it('disables every choice control, and a late answer lands on the choice that was approved', async () => { + const prev = { grant_id: 'g1', client_id: 'cursor', approved_at: '2026-11-03T10:00:00Z' } + const { w } = await mountAt({ r1: generic('r1', { previous_login: prev, suggested_client: { id: 'cursor', matched: 'id' } }) }) + const d = deferred() + A.approveOAuthAuthorization.mockImplementationOnce(() => d.promise) + await t(w, 'authorize-approve').trigger('click') + for (const id of ['authorize-client-select', 'authorize-replace']) { + expect(t(w, id).attributes('disabled'), id).toBeDefined() + } + const calls = A.previewOAuthAuthorization.mock.calls.length + await t(w, 'authorize-client-select').setValue('codex') + await flushPromises() + expect(A.previewOAuthAuthorization.mock.calls.length).toBe(calls) + expect(t(w, 'authorize-access').text()).toContain('Cursor') + d.resolve({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + await flushPromises() + expect(navigateTo).toHaveBeenCalledTimes(1) + // Terminal: still frozen. + expect(t(w, 'authorize-client-select').attributes('disabled')).toBeDefined() + }) + + it('freezes the new-client fields, the profile and the lock', async () => { + const { w } = await mountAt({ r1: generic('r1') }) + await t(w, 'authorize-profile-select').setValue('ops') + await flushPromises() + const d = deferred() + A.approveOAuthAuthorization.mockImplementationOnce(() => d.promise) + await t(w, 'authorize-approve').trigger('click') + for (const id of [...controls, 'authorize-new-id', 'authorize-new-name', 'authorize-lock']) { + expect(t(w, id).attributes('disabled'), id).toBeDefined() + } + d.reject(new Error('network down')) + await flushPromises() + for (const id of controls) expect(t(w, id).attributes('disabled'), id).toBeUndefined() + }) +}) + +describe('the review-again notice belongs to the request that was reloaded', () => { + it('is not shown on r2 when the page navigated during the reload', async () => { + const { w, router } = await mountAt({ r1: generic('r1'), r2: generic('r2') }) + await t(w, 'authorize-client-select').setValue('codex') + await flushPromises() + const reload = deferred() + A.approveOAuthAuthorization.mockRejectedValueOnce(changed()) + A.getOAuthAuthorization.mockImplementation((id: string) => (id === 'r1' ? reload.promise : Promise.resolve(generic(id)))) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + await router.push('/authorize?request=r2') + await flushPromises() + reload.resolve(generic('r1')) + await flushPromises() + expect(t(w, 'authorize-changed').exists()).toBe(false) + expect(t(w, 'authorize-reported').text()).toContain('App r2') + }) +}) From fef8406d7b65be83bb4519b7817462a2395bc7da Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 13:38:14 +0200 Subject: [PATCH 31/42] fix(oauth): consent page review round 4 (Spec 132 PR-2a) - Starting a decision invalidates outstanding previews; preview handlers do nothing while a decision is pending or done, so a late binding_changed can no longer drop a Deny/Approve answer. After a recoverable decision failure the cut-off preview is run again. - A failed preview shows "Check again", which re-runs it for the current request and choice under the same guards. Related #1971 --- frontend/src/views/AuthorizeRequest.vue | 15 ++- .../unit/authorize-request-round4.spec.ts | 123 ++++++++++++++++++ 2 files changed, 136 insertions(+), 2 deletions(-) create mode 100644 frontend/tests/unit/authorize-request-round4.spec.ts diff --git a/frontend/src/views/AuthorizeRequest.vue b/frontend/src/views/AuthorizeRequest.vue index 02a0b0285..f9c3b57d6 100644 --- a/frontend/src/views/AuthorizeRequest.vue +++ b/frontend/src/views/AuthorizeRequest.vue @@ -112,6 +112,7 @@ The client's access changed while this page was open. It was reloaded: review it and approve again. +
@@ -347,12 +348,12 @@ async function runPreview(id: string, key: string) { errorText.value = '' try { const p = await api.previewOAuthAuthorization(id, JSON.parse(key)) - if (seq !== previewSeq) return + if (seq !== previewSeq || busy.value) return accepted.value = { key, preview: p } previewFailed.value = false guardOverride.value = null } catch (e) { - if (seq !== previewSeq) return + if (seq !== previewSeq || busy.value) return accepted.value = null if (e instanceof ApiError && e.status === 404 && e.code !== 'profile_not_found') { phase.value = 'gone' @@ -392,6 +393,7 @@ async function decide(call: (id: string) => Promise) { // An answer for a request that was left (new id, unmount) is obsolete: it // must not navigate, hide, disable or release anything on the page now shown. const gen = loadGen + previewSeq++ // a preview still in flight is obsolete once a decision starts try { const res = await call(loadedId.value) if (gen !== loadGen) return @@ -401,9 +403,18 @@ async function decide(call: (id: string) => Promise) { if (gen !== loadGen) return submitting.value = false await handleDecisionError(e) + // The preview that was cut off when the decision started is run again. + if (gen === loadGen && phase.value === 'ready' && !current.value) retryPreview() } } +// Runs the preview again for the current request and choice (also the +// "Check again" button after a failed preview). +function retryPreview() { + const key = previewKey.value + if (key !== null && loadedId.value && !busy.value) void runPreview(loadedId.value, key) +} + function approve() { const a = accepted.value if (!approveReady.value || !a) return diff --git a/frontend/tests/unit/authorize-request-round4.spec.ts b/frontend/tests/unit/authorize-request-round4.spec.ts new file mode 100644 index 000000000..1c740746e --- /dev/null +++ b/frontend/tests/unit/authorize-request-round4.spec.ts @@ -0,0 +1,123 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import { createMemoryHistory, createRouter } from 'vue-router' +import AuthorizeRequest from '@/views/AuthorizeRequest.vue' +import api, { ApiError } from '@/services/api' +import { navigateTo } from '@/utils/navigate' + +vi.mock('@/services/api', async (orig) => { + const actual = await orig() + return { + ...actual, + default: { + hasAPIKey: vi.fn(() => true), + setAPIKey: vi.fn(), + getOAuthAuthorization: vi.fn(), + previewOAuthAuthorization: vi.fn(), + approveOAuthAuthorization: vi.fn(), + denyOAuthAuthorization: vi.fn(), + }, + } +}) +vi.mock('@/utils/navigate', () => ({ navigateTo: vi.fn() })) + +const A = api as any +const t = (w: any, id: string) => w.find(`[data-test="${id}"]`) + +const detail = () => ({ + id: 'r1', status: 'pending', expires_at: '2026-11-23T12:10:00Z', reported_name: 'App', + redirect_uri: 'http://127.0.0.1:54321/callback', resource: 'http://127.0.0.1:8080/mcp/oauth/cursor', + address_kind: 'client', + client: { id: 'cursor', display_name: 'Cursor', exists: true, has_api_key: true, logins: 1, binding: { profile: 'dev', mode: 'locked', revision: 'rev1' } }, + profiles: [{ name: 'dev' }], profile_required: false, guard: null, +}) + +const complete = (body: any) => ({ + complete: true, + access: { client: body.client?.id, profile: 'dev', mode: 'locked', same_access_as_existing_client: true }, + guard: null, +}) + +function deferred() { + let resolve!: (v: T) => void + let reject!: (e: unknown) => void + const promise = new Promise((res, rej) => { resolve = res; reject = rej }) + return { promise, resolve, reject } +} + +async function mountPage() { + A.getOAuthAuthorization.mockImplementation(async () => detail()) + const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/authorize', component: AuthorizeRequest }] }) + await router.push('/authorize?request=r1') + const w = mount(AuthorizeRequest, { global: { plugins: [router] } }) + await flushPromises() + return w +} + +beforeEach(() => { + vi.clearAllMocks() + A.hasAPIKey.mockReturnValue(true) + A.previewOAuthAuthorization.mockImplementation(async (_id: string, body: any) => complete(body)) +}) + +describe('Deny does not depend on the preview', () => { + it('a pending preview that later answers binding_changed does not drop the Deny redirect', async () => { + const pv = deferred() + A.previewOAuthAuthorization.mockImplementationOnce(() => pv.promise) + const w = await mountPage() + const deny = deferred() + A.denyOAuthAuthorization.mockImplementationOnce(() => deny.promise) + await t(w, 'authorize-deny').trigger('click') + const loads = A.getOAuthAuthorization.mock.calls.length + pv.reject(new ApiError(409, { code: 'binding_changed', error: 'changed' }, 'x')) + await flushPromises() + expect(A.getOAuthAuthorization.mock.calls.length).toBe(loads) // no reload while deciding + expect(t(w, 'authorize-deny').attributes('disabled')).toBeDefined() + deny.resolve({ redirect_url: 'http://127.0.0.1:54321/callback?error=access_denied' }) + await flushPromises() + expect(navigateTo).toHaveBeenCalledWith('http://127.0.0.1:54321/callback?error=access_denied') + }) + + it.each([ + ['failed', async () => { throw new Error('boom') }], + ['incomplete', async () => ({ complete: false, guard: null })], + ])('works with a %s preview', async (_n, impl) => { + A.previewOAuthAuthorization.mockImplementation(impl) + const w = await mountPage() + A.denyOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?error=access_denied' }) + await t(w, 'authorize-deny').trigger('click') + await flushPromises() + expect(navigateTo).toHaveBeenCalledTimes(1) + }) + + it('restarts the preview after a recoverable decision failure', async () => { + const pv = deferred() + A.previewOAuthAuthorization.mockImplementationOnce(() => pv.promise) + const w = await mountPage() + const deny = deferred() + A.denyOAuthAuthorization.mockImplementationOnce(() => deny.promise) + await t(w, 'authorize-deny').trigger('click') + pv.resolve(complete({ client: { id: 'cursor' } })) // obsolete: a decision is pending + await flushPromises() + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + const calls = A.previewOAuthAuthorization.mock.calls.length + deny.reject(new Error('network down')) + await flushPromises() + expect(A.previewOAuthAuthorization.mock.calls.length).toBe(calls + 1) + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + }) +}) + +describe('a failed preview can be retried', () => { + it('shows Check again, and Approve enables after a successful retry without remount', async () => { + A.previewOAuthAuthorization.mockRejectedValueOnce(new Error('HTTP 503')) + const w = await mountPage() + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + expect(t(w, 'authorize-retry').exists()).toBe(true) + await t(w, 'authorize-retry').trigger('click') + await flushPromises() + expect(t(w, 'authorize-retry').exists()).toBe(false) + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + expect(t(w, 'authorize-access').exists()).toBe(true) + }) +}) From 0a0cd93d5d69da413b885a6f05f6e1e2e579f7cd Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 13:45:04 +0200 Subject: [PATCH 32/42] fix(oauth): consent page review round 5 (Spec 132 PR-2a) - A preview answering binding_changed reloads the request once on its own; after that the page stops, shows the review-again notice, keeps Deny and offers "Check again". A user edit, a new request or "Check again" earns one more reload. - A failed load (not a 404) shows "Try again", bound to the current request. - The replace-flag reload test asserts unconditionally (g1 -> g2). Related #1971 --- frontend/src/views/AuthorizeRequest.vue | 29 ++++- .../unit/authorize-request-round3.spec.ts | 26 ++--- .../unit/authorize-request-round5.spec.ts | 109 ++++++++++++++++++ 3 files changed, 145 insertions(+), 19 deletions(-) create mode 100644 frontend/tests/unit/authorize-request-round5.spec.ts diff --git a/frontend/src/views/AuthorizeRequest.vue b/frontend/src/views/AuthorizeRequest.vue index f9c3b57d6..c8a969578 100644 --- a/frontend/src/views/AuthorizeRequest.vue +++ b/frontend/src/views/AuthorizeRequest.vue @@ -32,7 +32,8 @@
@@ -112,7 +113,7 @@ The client's access changed while this page was open. It was reloaded: review it and approve again.
- +
@@ -170,6 +171,10 @@ const submitting = ref(false) const decided = ref(false) let previewSeq = 0 let loadGen = 0 +// A preview answering binding_changed reloads the request once on its own; a +// user-initiated change (or a new request) earns one more. +let reloadsLeft = 1 +let applyingReload = false const busy = computed(() => submitting.value || decided.value) const fixed = computed(() => (view.value?.address_kind === 'client' ? view.value.client ?? null : null)) @@ -305,6 +310,7 @@ async function load(keepNote = false): Promise { } : null resetPage(keepNote) + if (!keepNote) reloadsLeft = 1 const id = requestId.value if (!id) { phase.value = 'gone' @@ -315,6 +321,7 @@ async function load(keepNote = false): Promise { try { const v = await api.getOAuthAuthorization(id) if (gen !== loadGen) return false + applyingReload = keepNote // the watcher must not treat the reload's own changes as user edits view.value = v loadedId.value = id resetChoice(v) @@ -331,8 +338,10 @@ async function load(keepNote = false): Promise { replace.value = v.previous_login ? (v.previous_login.grant_id === kept.grant ? kept.replace : true) : false } phase.value = 'ready' + applyingReload = false return true } catch (e) { + applyingReload = false if (gen !== loadGen) return false if (e instanceof ApiError && e.status === 404) phase.value = 'gone' else { @@ -360,7 +369,15 @@ async function runPreview(id: string, key: string) { return } if (e instanceof ApiError && e.code === 'binding_changed') { - if (await load(true)) changedNote.value = true + if (reloadsLeft > 0) { + reloadsLeft-- + if (await load(true)) changedNote.value = true + return + } + // Reloaded once already: stop here. Deny stays available; Check again is the user's call. + previewFailed.value = true + changedNote.value = true + errorText.value = "The client's access keeps changing. Check again when it is stable." return } previewFailed.value = true @@ -372,6 +389,7 @@ async function runPreview(id: string, key: string) { watch( previewKey, (key) => { + if (key !== null && !applyingReload) reloadsLeft = 1 previewSeq++ accepted.value = null guardOverride.value = null @@ -408,6 +426,11 @@ async function decide(call: (id: string) => Promise) { } } +function checkAgain() { + reloadsLeft = 1 + retryPreview() +} + // Runs the preview again for the current request and choice (also the // "Check again" button after a failed preview). function retryPreview() { diff --git a/frontend/tests/unit/authorize-request-round3.spec.ts b/frontend/tests/unit/authorize-request-round3.spec.ts index fd7d563b6..4b8afcb28 100644 --- a/frontend/tests/unit/authorize-request-round3.spec.ts +++ b/frontend/tests/unit/authorize-request-round3.spec.ts @@ -111,27 +111,21 @@ describe('review-again reload validates what it keeps', () => { expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() }) - it('a kept replace flag does not survive a previous login that is gone', async () => { + it('re-checks replace for a previous login that changed (g1 -> g2) and sends the new grant', async () => { const prev = { grant_id: 'g1', client_id: 'cursor', approved_at: '2026-11-03T10:00:00Z' } const { w } = await mountAt({ r1: generic('r1', { previous_login: prev, suggested_client: { id: 'cursor', matched: 'id' } }) }) - await t(w, 'authorize-replace').setValue(false) + // Unchecking changes the choice; its preview is refused and the reload finds a newer login. A.previewOAuthAuthorization.mockImplementationOnce(async () => { throw changed() }) - A.getOAuthAuthorization.mockImplementation(async () => generic('r1', { previous_login: { ...prev, grant_id: 'g2' } })) - await t(w, 'authorize-client-select').setValue('cursor') - await t(w, 'authorize-client-select').trigger('change') - // Force a preview on the same client by switching away and back. - await t(w, 'authorize-client-select').setValue('codex') - await flushPromises() - await t(w, 'authorize-client-select').setValue('cursor') + A.getOAuthAuthorization.mockImplementation(async () => generic('r1', { previous_login: { ...prev, grant_id: 'g2' }, suggested_client: { id: 'cursor', matched: 'id' } })) + await t(w, 'authorize-replace').setValue(false) await flushPromises() const box = t(w, 'authorize-replace') - if (box.exists()) { - A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) - await t(w, 'authorize-approve').trigger('click') - await flushPromises() - const sent = A.approveOAuthAuthorization.mock.calls.at(-1)![1] - expect(sent.replace_grant === undefined).toBe(!(box.element as HTMLInputElement).checked) - } + expect(box.exists()).toBe(true) + expect((box.element as HTMLInputElement).checked).toBe(true) + A.approveOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:1/cb?code=c' }) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(A.approveOAuthAuthorization.mock.calls.at(-1)![1].replace_grant).toBe('g2') }) }) diff --git a/frontend/tests/unit/authorize-request-round5.spec.ts b/frontend/tests/unit/authorize-request-round5.spec.ts new file mode 100644 index 000000000..78333827a --- /dev/null +++ b/frontend/tests/unit/authorize-request-round5.spec.ts @@ -0,0 +1,109 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises, mount } from '@vue/test-utils' +import { createMemoryHistory, createRouter } from 'vue-router' +import AuthorizeRequest from '@/views/AuthorizeRequest.vue' +import api, { ApiError } from '@/services/api' +import { navigateTo } from '@/utils/navigate' + +vi.mock('@/services/api', async (orig) => { + const actual = await orig() + return { + ...actual, + default: { + hasAPIKey: vi.fn(() => true), + setAPIKey: vi.fn(), + getOAuthAuthorization: vi.fn(), + previewOAuthAuthorization: vi.fn(), + approveOAuthAuthorization: vi.fn(), + denyOAuthAuthorization: vi.fn(), + }, + } +}) +vi.mock('@/utils/navigate', () => ({ navigateTo: vi.fn() })) + +const A = api as any +const t = (w: any, id: string) => w.find(`[data-test="${id}"]`) + +const detail = () => ({ + id: 'r1', status: 'pending', expires_at: '2026-11-23T12:10:00Z', reported_name: 'App', + redirect_uri: 'http://127.0.0.1:54321/callback', resource: 'http://127.0.0.1:8080/mcp/oauth/cursor', + address_kind: 'client', + client: { id: 'cursor', display_name: 'Cursor', exists: true, has_api_key: true, logins: 1, binding: { profile: 'dev', mode: 'locked', revision: 'rev1' } }, + profiles: [{ name: 'dev' }], profile_required: false, guard: null, +}) + +const complete = (body: any) => ({ + complete: true, + access: { client: body.client?.id, profile: 'dev', mode: 'locked', same_access_as_existing_client: true }, + guard: null, +}) + +const changed = () => new ApiError(409, { code: 'binding_changed', error: 'changed' }, 'x') + +async function mountPage() { + const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/authorize', component: AuthorizeRequest }] }) + await router.push('/authorize?request=r1') + const w = mount(AuthorizeRequest, { global: { plugins: [router] } }) + await flushPromises() + return w +} + +beforeEach(() => { + vi.clearAllMocks() + A.hasAPIKey.mockReturnValue(true) + A.getOAuthAuthorization.mockImplementation(async () => detail()) + A.previewOAuthAuthorization.mockImplementation(async (_id: string, body: any) => complete(body)) +}) + +describe('binding_changed from preview reloads at most once', () => { + it('stops after one automatic reload, keeps Deny, shows the notice and offers Check again', async () => { + A.previewOAuthAuthorization.mockRejectedValue(changed()) + const w = await mountPage() + // initial GET + one automatic reload; initial preview + the reload's preview. + expect(A.getOAuthAuthorization).toHaveBeenCalledTimes(2) + expect(A.previewOAuthAuthorization).toHaveBeenCalledTimes(2) + expect(t(w, 'authorize-changed').exists()).toBe(true) + expect(t(w, 'authorize-retry').exists()).toBe(true) + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + expect(t(w, 'authorize-deny').attributes('disabled')).toBeUndefined() + + A.denyOAuthAuthorization.mockResolvedValue({ redirect_url: 'http://127.0.0.1:54321/callback?error=access_denied' }) + await t(w, 'authorize-deny').trigger('click') + await flushPromises() + expect(navigateTo).toHaveBeenCalledWith('http://127.0.0.1:54321/callback?error=access_denied') + expect(A.getOAuthAuthorization).toHaveBeenCalledTimes(2) + }) + + it('Check again is an explicit user action that can recover', async () => { + A.previewOAuthAuthorization.mockRejectedValueOnce(changed()).mockRejectedValueOnce(changed()) + const w = await mountPage() + expect(t(w, 'authorize-approve').attributes('disabled')).toBeDefined() + await t(w, 'authorize-retry').trigger('click') + await flushPromises() + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + }) +}) + +describe('a failed review-again reload can be retried', () => { + it('shows Try again for a transient failure (not for an expired request) and recovers', async () => { + const w = await mountPage() + A.approveOAuthAuthorization.mockRejectedValueOnce(changed()) + A.getOAuthAuthorization.mockRejectedValueOnce(new ApiError(503, { error: 'unavailable' }, 'x')) + await t(w, 'authorize-approve').trigger('click') + await flushPromises() + expect(t(w, 'authorize-load-error').exists()).toBe(true) + expect(t(w, 'authorize-load-retry').exists()).toBe(true) + await t(w, 'authorize-load-retry').trigger('click') + await flushPromises() + expect(t(w, 'authorize-load-error').exists()).toBe(false) + expect(t(w, 'authorize-approve').attributes('disabled')).toBeUndefined() + expect(t(w, 'authorize-deny').exists()).toBe(true) + }) + + it('an expired request (404) has no retry', async () => { + A.getOAuthAuthorization.mockRejectedValue(new ApiError(404, { error: 'not found' }, 'x')) + const w = await mountPage() + expect(t(w, 'authorize-gone').exists()).toBe(true) + expect(t(w, 'authorize-load-retry').exists()).toBe(false) + }) +}) From 09b828188f88bbc250e62cca78a534d7100deecc Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 13:51:37 +0200 Subject: [PATCH 33/42] test(oauth): Playwright spec for the consent page (Spec 132 PR-2a, T061) Drives /ui/authorize in a real browser against a core started with MCPPROXY_MCP_OAUTH_ENABLED=true: per-client and generic addresses, the name suggestion, new client, deny, no API key, markup-shaped names and the frame headers. Skips when browser login is not served. Related #1971 --- e2e/web-ui-sweep/client-oauth-consent.spec.ts | 270 ++++++++++++++++++ 1 file changed, 270 insertions(+) create mode 100644 e2e/web-ui-sweep/client-oauth-consent.spec.ts diff --git a/e2e/web-ui-sweep/client-oauth-consent.spec.ts b/e2e/web-ui-sweep/client-oauth-consent.spec.ts new file mode 100644 index 000000000..0eb2f51b5 --- /dev/null +++ b/e2e/web-ui-sweep/client-oauth-consent.spec.ts @@ -0,0 +1,270 @@ +import { test, expect, type Page } from '@playwright/test' +import { createHash, randomBytes } from 'node:crypto' +import { mkdirSync } from 'node:fs' +import { join } from 'node:path' + +// Spec 132 (issue #1971) consent page, driven in a real browser against a core +// started with MCPPROXY_MCP_OAUTH_ENABLED=true (no profiles configured, so a +// client's profile is "All servers"). A scripted public client does register -> +// authorize and follows the 302 to /ui/authorize?request=; the admin API key +// reaches the page through localStorage, never a URL. +// +// Environment (exported by the launcher / by hand): +// MCPPROXY_BASE_URL e.g. http://127.0.0.1:19700 (must be the 127.0.0.1 origin) +// MCPPROXY_API_KEY the admin API key +// SWEEP_SCREENSHOT_DIR optional: keep a PNG of every step there +const BASE = process.env.MCPPROXY_BASE_URL || '' +const KEY = process.env.MCPPROXY_API_KEY || '' +const REDIRECT = 'http://127.0.0.1:54321/callback' +const shotDir = process.env.SWEEP_SCREENSHOT_DIR || '' + +test.describe.configure({ mode: 'serial' }) +test.skip(!BASE || !KEY, 'MCPPROXY_BASE_URL and MCPPROXY_API_KEY are required (core with MCPPROXY_MCP_OAUTH_ENABLED=true)') + +// The standing sweep runs against a core with browser login off (the default): +// skip loudly there instead of failing. +let oauthServed = false +test.beforeAll(async () => { + try { + oauthServed = (await fetch(`${BASE}/.well-known/oauth-authorization-server`)).status === 200 + } catch { + oauthServed = false + } +}) +test.beforeEach(() => { + test.skip(!oauthServed, 'browser login is not served by this core (start it with MCPPROXY_MCP_OAUTH_ENABLED=true)') +}) + +const t = (page: Page, id: string) => page.locator(`[data-test="${id}"]`) + +async function shot(page: Page, name: string) { + if (!shotDir) return + mkdirSync(shotDir, { recursive: true }) + await page.screenshot({ path: join(shotDir, `${name}.png`), fullPage: true }) +} + +async function sleep(ms: number) { + await new Promise((r) => setTimeout(r, ms)) +} + +// fetch that waits out the public endpoints' 429 (the limiter is not under test). +async function fetchRetry(url: string, init: RequestInit = {}): Promise { + for (let i = 0; i < 5; i++) { + const res = await fetch(url, { ...init, redirect: 'manual' }) + if (res.status !== 429) return res + await sleep((Number(res.headers.get('retry-after')) || 3) * 1000) + } + throw new Error(`still rate limited: ${url}`) +} + +const admin = (path: string, init: RequestInit = {}) => + fetch(`${BASE}/api/v1${path}`, { ...init, headers: { 'X-API-Key': KEY, 'Content-Type': 'application/json', ...(init.headers || {}) } }) + +interface Pending { clientId: string; verifier: string; requestUrl: string; resource: string } + +async function startSignIn(clientName: string, clientPath: string, state: string): Promise { + const reg = await fetchRetry(`${BASE}/oauth/register`, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ redirect_uris: [REDIRECT], client_name: clientName }), + }) + expect(reg.status).toBe(201) + const clientId = (await reg.json()).client_id as string + const verifier = randomBytes(48).toString('base64url') + const challenge = createHash('sha256').update(verifier).digest('base64url') + const resource = `${BASE}${clientPath}` + const q = new URLSearchParams({ + response_type: 'code', client_id: clientId, redirect_uri: REDIRECT, code_challenge: challenge, + code_challenge_method: 'S256', resource, state, + }) + const auth = await fetchRetry(`${BASE}/oauth/authorize?${q}`) + expect(auth.status).toBe(302) + const location = auth.headers.get('location') || '' + expect(location).toContain('/ui/authorize?request=') + return { clientId, verifier, requestUrl: location, resource } +} + +async function exchange(p: Pending, code: string) { + const res = await fetchRetry(`${BASE}/oauth/token`, { + method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + grant_type: 'authorization_code', code, redirect_uri: REDIRECT, client_id: p.clientId, + code_verifier: p.verifier, resource: p.resource, + }), + }) + expect(res.status).toBe(200) + return (await res.json()) as { access_token: string } +} + +// The client's redirect URI has no listener: answer it so the navigation lands. +async function catchCallback(page: Page) { + await page.route('http://127.0.0.1:54321/**', (route) => route.fulfill({ status: 200, contentType: 'text/html', body: '

client callback

' })) +} + +async function withKey(page: Page) { + await page.addInitScript((k) => localStorage.setItem('mcpproxy-api-key', k), KEY) +} + +async function loginCount(client: string): Promise { + const res = await admin(`/clients/${client}`) + if (res.status !== 200) return 0 + const body = await res.json() + return ((body.data?.credentials as any[]) || []).filter((c) => c.kind === 'browser_login' && c.state === 'active').length +} + +test('a. per-client address: fixed client, All servers, approve, code + state, tools/list', async ({ page }) => { + await withKey(page) + await catchCallback(page) + const p = await startSignIn('Cursor IDE', '/mcp/oauth/cursor', 'state-a') + await page.goto(p.requestUrl) + await expect(t(page, 'authorize-client-fixed')).toContainText('Cursor') + await expect(t(page, 'authorize-reported')).toContainText('MCPProxy cannot verify that.') + await expect(t(page, 'authorize-client-select')).toHaveCount(0) + await expect(t(page, 'authorize-profile-select')).toHaveValue('__all__') + await expect(t(page, 'authorize-access')).toContainText('All servers') + await shot(page, 'a-per-client') + await t(page, 'authorize-approve').click() + await page.waitForURL(/127\.0\.0\.1:54321\/callback/) + const back = new URL(page.url()) + expect(back.searchParams.get('state')).toBe('state-a') + const code = back.searchParams.get('code') || '' + expect(code).not.toBe('') + const tok = await exchange(p, code) + + const headers = { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', Authorization: `Bearer ${tok.access_token}` } + const init = await fetch(`${BASE}/mcp/oauth/cursor`, { + method: 'POST', headers, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'cursor', version: '1' } } }), + }) + expect(init.status).toBe(200) + const sid = init.headers.get('mcp-session-id') || '' + const list = await fetch(`${BASE}/mcp/oauth/cursor`, { + method: 'POST', headers: { ...headers, ...(sid ? { 'Mcp-Session-Id': sid } : {}) }, + body: JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/list', params: {} }), + }) + expect(list.status).toBe(200) + expect(await list.text()).toContain('"tools"') +}) + +test('b. generic address: "Cursor" pre-selects the existing cursor client, approve unchanged', async ({ page }) => { + await withKey(page) + await catchCallback(page) + const before = await loginCount('cursor') + const p = await startSignIn('Cursor', '/mcp/oauth', 'state-b') + await page.goto(p.requestUrl) + await expect(t(page, 'authorize-client-select')).toHaveValue('cursor') + await expect(t(page, 'authorize-suggestion-note')).toHaveText('Suggested because the app calls itself "cursor". MCPProxy cannot verify that.') + await expect(t(page, 'authorize-access')).toContainText('the same access as') + await shot(page, 'b-suggested') + await t(page, 'authorize-approve').click() + await page.waitForURL(/127\.0\.0\.1:54321\/callback/) + const back = new URL(page.url()) + expect(back.searchParams.get('state')).toBe('state-b') + await exchange(p, back.searchParams.get('code') || '') + expect(await loginCount('cursor')).toBeGreaterThan(before) +}) + +test('c. generic address: switching to "New client" pre-fills id and name; cursor is unchanged', async ({ page }) => { + await withKey(page) + await catchCallback(page) + const before = await loginCount('cursor') + const p = await startSignIn('Cursor', '/mcp/oauth', 'state-c') + await page.goto(p.requestUrl) + await expect(t(page, 'authorize-client-select')).toHaveValue('cursor') + await t(page, 'authorize-client-select').selectOption('__new__') + await expect(t(page, 'authorize-suggestion-note')).toHaveCount(0) + const newId = await t(page, 'authorize-new-id').inputValue() + expect(newId).not.toBe('') + expect(newId).not.toBe('cursor') + expect(await t(page, 'authorize-new-name').inputValue()).not.toBe('') + await expect(t(page, 'authorize-approve')).toBeEnabled() + await shot(page, 'c-new-client') + await t(page, 'authorize-approve').click() + await page.waitForURL(/127\.0\.0\.1:54321\/callback/) + await exchange(p, new URL(page.url()).searchParams.get('code') || '') + expect((await admin(`/clients/${newId}`)).status).toBe(200) + expect(await loginCount(newId)).toBe(1) + expect(await loginCount('cursor')).toBe(before) +}) + +test('d. generic address, unknown name: "New client" is selected', async ({ page }) => { + await withKey(page) + const p = await startSignIn('Totally Unknown App', '/mcp/oauth', 'state-d') + await page.goto(p.requestUrl) + await expect(t(page, 'authorize-client-select')).toHaveValue('__new__') + await expect(t(page, 'authorize-suggestion-note')).toHaveCount(0) + expect(await t(page, 'authorize-new-id').inputValue()).toBe('totally-unknown-app') + await shot(page, 'd-unknown') +}) + +test('e. deny: access_denied and the original state', async ({ page }) => { + await withKey(page) + await catchCallback(page) + const p = await startSignIn('Cursor IDE', '/mcp/oauth/cursor', 'state-e') + await page.goto(p.requestUrl) + await t(page, 'authorize-deny').click() + await page.waitForURL(/127\.0\.0\.1:54321\/callback/) + const back = new URL(page.url()) + expect(back.searchParams.get('error')).toBe('access_denied') + expect(back.searchParams.get('state')).toBe('state-e') + expect(back.searchParams.get('code')).toBeNull() +}) + +// With no key the app shell also opens its own "Authentication Required" dialog +// (every page does). The consent page makes no request until a key is set, by +// either door: the dialog's field, or the page's own paste field once the dialog +// is dismissed. +test('f1. no API key: only the open-from-tray text and no detail request; the app dialog sets the key', async ({ page }) => { + const p = await startSignIn('Cursor IDE', '/mcp/oauth/cursor', 'state-f1') + const detailRequests: string[] = [] + page.on('request', (r) => { if (r.url().includes('/api/v1/oauth/authorizations')) detailRequests.push(r.url()) }) + await page.goto(p.requestUrl) + await expect(t(page, 'authorize-no-key')).toContainText('Open this request from the MCPProxy tray, or paste the API key') + await expect(t(page, 'authorize-approve')).toHaveCount(0) + await expect(t(page, 'authorize-deny')).toHaveCount(0) + await expect(page.getByText('Authentication Required')).toBeVisible() + await shot(page, 'f1-no-key') + expect(detailRequests).toEqual([]) + await page.getByPlaceholder('Enter your API key...').fill(KEY) + await page.getByRole('button', { name: 'Set Key' }).click() + await expect(t(page, 'authorize-client-fixed')).toContainText('Cursor') + expect(detailRequests.length).toBeGreaterThan(0) + await shot(page, 'f1-key-set') +}) + +test("f2. no API key: the page's own paste field works once the app dialog is dismissed", async ({ page }) => { + const p = await startSignIn('Cursor IDE', '/mcp/oauth/cursor', 'state-f2') + const detailRequests: string[] = [] + page.on('request', (r) => { if (r.url().includes('/api/v1/oauth/authorizations')) detailRequests.push(r.url()) }) + await page.goto(p.requestUrl) + await expect(t(page, 'authorize-no-key')).toBeVisible() + await page.getByText('Dismiss (pages stay empty)').click() + expect(detailRequests).toEqual([]) + await t(page, 'authorize-key-input').fill(KEY) + await t(page, 'authorize-key-submit').click() + await expect(t(page, 'authorize-client-fixed')).toContainText('Cursor') + expect(detailRequests.length).toBeGreaterThan(0) + await shot(page, 'f2-key-pasted') +}) + +test('g. a markup-shaped client name is shown as text: no element, no dialog', async ({ page }) => { + await withKey(page) + let dialog = '' + page.on('dialog', async (d) => { dialog = d.message(); await d.dismiss() }) + const p = await startSignIn('', '/mcp/oauth', 'state-g') + await page.goto(p.requestUrl) + await expect(t(page, 'authorize-reported')).toBeVisible() + await page.waitForTimeout(500) + expect(dialog).toBe('') + await expect(page.locator('img[src="x"]')).toHaveCount(0) + await expect(t(page, 'authorize-reported')).toContainText('cannot verify') + await shot(page, 'g-markup-name') +}) + +test('h. the consent page is never framed (any case)', async ({ request }) => { + for (const path of ['/ui/authorize?request=x', '/ui/Authorize?request=x']) { + const res = await request.get(`${BASE}${path}`) + expect(res.status(), path).toBe(200) + expect(res.headers()['content-security-policy'], path).toContain("frame-ancestors 'none'") + expect(res.headers()['x-frame-options'], path).toBe('DENY') + } +}) From a0a84a832c4e77a5d7a744c1ce6cf9a3e8279240 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Mon, 23 Nov 2026 13:59:52 +0200 Subject: [PATCH 34/42] fix(oauth): consent page security review fixes (Spec 132 PR-2a) - Names a client reports lose Unicode format characters (category Cf: bidi overrides and isolates, zero-width, BOM) at registration and in a new client's display name (mcplogin.StripFormat; the shared clientidentity sanitiser is unchanged). - The page renders every untrusted name (reported name in both sentences, the return address, the new-client name in the access sentence) in its own bdi element, with the page's own quotes and copy outside it. - previous_logins: the newest live login of the registration under each client; the page offers Replace for the selected client. - A 404 client_not_found is shown on the choice, not as an expired request. - Client options show the id next to the display name. Related #1971 --- docs/api/rest-api.md | 6 +- frontend/src/types/api.ts | 2 + frontend/src/views/AuthorizeRequest.vue | 47 +++--- .../unit/authorize-request-round7.spec.ts | 151 ++++++++++++++++++ internal/mcplogin/format_chars_test.go | 50 ++++++ internal/mcplogin/registration.go | 18 ++- internal/runtime/oauth_login_consent.go | 20 ++- .../runtime/oauth_login_round_sec_test.go | 93 +++++++++++ 8 files changed, 360 insertions(+), 27 deletions(-) create mode 100644 frontend/tests/unit/authorize-request-round7.spec.ts create mode 100644 internal/mcplogin/format_chars_test.go create mode 100644 internal/runtime/oauth_login_round_sec_test.go diff --git a/docs/api/rest-api.md b/docs/api/rest-api.md index 8dfa42366..35703bdb5 100644 --- a/docs/api/rest-api.md +++ b/docs/api/rest-api.md @@ -1706,7 +1706,11 @@ reference: the Spec 132 contracts. without a `client` answers `200 {"complete": false}` (no `access`, no `guard`) and approve without one answers `422 client_required`. `previous_login` is `{grant_id, client_id, approved_at}`: `client_id` is the client that owns that - login. Preview and approve refuse (`422`, field `replace_grant`) a `replace_grant` + login (the newest live login of this registration overall). `previous_logins` lists + the newest live login of this registration under each client, so the page can offer + replacement for whichever client is selected on the generic address. Names a client + reports are stripped of Unicode format characters (bidi controls, zero-width + characters) at registration and in a new client's display name. Preview and approve refuse (`422`, field `replace_grant`) a `replace_grant` that is a live login of this registration owned by another client than the one chosen; the page offers replacement only for the owning client. - `POST /api/v1/oauth/authorizations/{id}/preview`: read-only verdict for a diff --git a/frontend/src/types/api.ts b/frontend/src/types/api.ts index b909d51c7..a5557b781 100644 --- a/frontend/src/types/api.ts +++ b/frontend/src/types/api.ts @@ -1604,6 +1604,8 @@ export interface OAuthAuthorization { profiles: Array<{ name: string }> profile_required: boolean previous_login?: { grant_id: string; client_id: string; approved_at: string } + /** The newest live login of this registration under each client. */ + previous_logins?: Array<{ grant_id: string; client_id: string; approved_at: string }> guard: OAuthGuardVerdict | null } diff --git a/frontend/src/views/AuthorizeRequest.vue b/frontend/src/views/AuthorizeRequest.vue index c8a969578..a4aec555c 100644 --- a/frontend/src/views/AuthorizeRequest.vue +++ b/frontend/src/views/AuthorizeRequest.vue @@ -39,8 +39,8 @@
-

The app calls itself "{{ view.reported_name }}". MCPProxy cannot verify that.

-

Returns to: {{ view.redirect_uri }}

+

The app calls itself "{{ view.reported_name }}". MCPProxy cannot verify that.

+

Returns to: {{ view.redirect_uri }}

@@ -60,10 +60,10 @@ class="select select-bordered w-full" data-test="authorize-client-select" > - + -

Suggested because the app calls itself "{{ view.reported_name }}". MCPProxy cannot verify that.

+

Suggested because the app calls itself "{{ view.reported_name }}". MCPProxy cannot verify that.

-

{{ accessSentence }}

+