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..28ac17972 100644 --- a/internal/httpapi/clients.go +++ b/internal/httpapi/clients.go @@ -69,6 +69,15 @@ 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 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. resolvedCredential profile.CredentialState @@ -271,6 +280,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..398715d6a --- /dev/null +++ b/internal/httpapi/clients_logins.go @@ -0,0 +1,172 @@ +//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 = 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].BrowserLoginDisabled != nil { + disabled = views[i].BrowserLoginDisabled + break + } + } + 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 { + 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 { + // 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] + 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 + 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]] + creds := clientCredentials(v.Credentials) + 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: &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/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..87028a502 --- /dev/null +++ b/internal/httpapi/oauth_login_test.go @@ -0,0 +1,396 @@ +//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"]) + // 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) + + // 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) + 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()) + 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) +} + +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/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 9b1c670cf..51cb48488 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" @@ -342,6 +343,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 +531,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 @@ -674,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 @@ -704,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 @@ -733,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/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/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/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_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_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/runtime/oauth_login_everused_test.go b/internal/runtime/oauth_login_everused_test.go new file mode 100644 index 000000000..16d840bc9 --- /dev/null +++ b/internal/runtime/oauth_login_everused_test.go @@ -0,0 +1,37 @@ +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") +} + +// 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()) +} 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 6115d6cab..fc5819b13 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() @@ -199,7 +208,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 +218,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 @@ -260,10 +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 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/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/mcp.go b/internal/server/mcp.go index 5e4f997ee..40a62109b 100644 --- a/internal/server/mcp.go +++ b/internal/server/mcp.go @@ -820,6 +820,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..69cd15b2e 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,10 @@ 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"}, + "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_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_hardening_test.go b/internal/server/oauth_login_hardening_test.go new file mode 100644 index 000000000..b1ce1a335 --- /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, 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 { + 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. + release2, ok := srv.trackOAuthRequest("g2", time.Now().Add(time.Hour), 0, srv.oauthRunGen(), func() {}) + require.True(t, ok) + release2() + assert.Zero(t, srv.oauthTrackedRequests()) +} + +// 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 new file mode 100644 index 000000000..9f72bbc66 --- /dev/null +++ b/internal/server/oauth_login_http.go @@ -0,0 +1,396 @@ +package server + +import ( + "encoding/json" + "errors" + "html" + "io" + "mime" + "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) + "

")) +} + +// 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) { + 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 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) + 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") + 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 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") { + 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 + } + // 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() + } + ac, grant, err := svc.Authenticate(token, origin, r.URL.Path, time.Now()) + if err != nil { + unauthorized() + return + } + svc.Touch(grant.GrantID, "") + // 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, run) + }) +} 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..e248fd6ce 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" @@ -42,14 +41,29 @@ 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. 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 } @@ -71,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 } @@ -79,28 +93,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_streams.go b/internal/server/oauth_login_streams.go new file mode 100644 index 000000000..7908ed2c1 --- /dev/null +++ b/internal/server/oauth_login_streams.go @@ -0,0 +1,251 @@ +package server + +import ( + "context" + "net/http" + "sync" + "time" +) + +// Spec 132 FR-031 / SC-006: revoking a login, forgetting its client, switching +// 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, 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 + 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 { + mu sync.Mutex + next uint64 + entries map[uint64]*oauthStream + running bool + stopped bool + wake chan struct{} + stop chan struct{} + wg sync.WaitGroup +} + +// 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.oauthStreamsRun++ // requests of the previous run can no longer register + s.oauthStreamsStopping = false + s.oauthStreams.Store(nil) + s.oauthStreamsMu.Unlock() +} + +// 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: + } + } +} + +// 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 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 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, 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 || run != s.oauthStreamsRun { + 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 + start := !reg.running + if start { + reg.running = true + 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 { + st.end() + } + if start { + go s.watchOAuthStreams(reg) + } + return func() { + reg.mu.Lock() + delete(reg.entries, id) + reg.mu.Unlock() + st.mu.Lock() + st.finished = true + if st.timer != nil { + st.timer.Stop() + } + st.mu.Unlock() + }, true +} + +// 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 || reg.stopped { + 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() + var epoch uint64 + if svc != nil { + epoch = svc.DisableEpoch() + } + for k, list := range groups { + live := svc != nil && svc.GrantLive(k.grant, k.exp) + for _, e := range list { + // 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() { + 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 + } + 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, run uint64) { + ctx, cancel := context.WithCancel(r.Context()) + defer cancel() + rc := http.NewResponseController(w) + 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. + now := time.Now() + _ = 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 new file mode 100644 index 000000000..92a451385 --- /dev/null +++ b/internal/server/oauth_login_streams_test.go @@ -0,0 +1,473 @@ +//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(), srv.oauthRunGen()) + })) + 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(), srv.oauthRunGen()) + })) + 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, 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() + 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() + + // Tracking after the stop is refused: nothing is registered, no watcher starts. + _, 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) + assert.Len(t, reg.entries, 1, "only the request tracked before the stop (released by its owner)") + reg.mu.Unlock() + 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") +} + +// 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, 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, srv.oauthRunGen()) + 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") + } +} + +// 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/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/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 15f9184a1..73b629481 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,23 @@ 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. + // 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] + 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). + testHookAfterEpochCapture func() + // testHookRunWatcher pauses the context watcher of a server run right after + // its context was cancelled (tests only; nil in production). + testHookRunWatcher 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. @@ -591,6 +609,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 +649,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 +698,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(strings.TrimSpace(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 @@ -1363,9 +1397,14 @@ func (s *Server) Start(ctx context.Context) error { // Handle graceful shutdown when context is cancelled (for full application shutdown only) go func() { <-ctx.Done() + if h := s.testHookRunWatcher; h != nil { + h() + } s.logger.Info("Main context cancelled, shutting down server") - // First shutdown the HTTP server - if err := s.StopServer(); err != nil { + // First shutdown the HTTP server. Bound to this run: after StopServer + // and a new StartServer in the same process, "the server" is a newer + // run with its own context and its own watcher, and is left alone. + if err := s.stopServer(&serverRun{ctx: ctx}); err != nil { s.logger.Error("Error stopping server during context cancellation", zap.Error(err)) } // Then shutdown the rest (only for full application shutdown, not server restarts) @@ -1579,6 +1618,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...") @@ -2691,17 +2734,27 @@ 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 { go s.runMetricsBridge(s.serverCtx, s.observability.Metrics()) } + runCtx := s.serverCtx go func() { var serverError error defer func() { + // After StopServer and a new StartServer in the same process this + // run can finish after the next one has started. The state below + // then belongs to that newer run: leave it alone. s.mu.Lock() + if s.serverCtx != runCtx { + s.mu.Unlock() + return + } s.running = false s.listenAddr = "" s.mu.Unlock() @@ -2724,7 +2777,7 @@ func (s *Server) StartServer(ctx context.Context) error { // Notify about server start s.updateStatus(runtime.PhaseStarting, "Server is starting...") - serverError = s.Start(s.serverCtx) + serverError = s.Start(runCtx) if serverError != nil && !errors.Is(serverError, context.Canceled) { s.logger.Error("Server error during background start", zap.Error(serverError)) s.updateStatus(runtime.PhaseError, fmt.Sprintf("Server error: %v", serverError)) @@ -2751,6 +2804,15 @@ func (s *Server) ServeErr() <-chan error { // StopServer stops the server if it's running func (s *Server) StopServer() error { + return s.stopServer(nil) +} + +// serverRun names one StartServer run by the context it was started with. +type serverRun struct{ ctx context.Context } + +// stopServer stops the server. With a non-nil run it stops only that run and +// does nothing when a newer run is current. +func (s *Server) stopServer(run *serverRun) error { s.logger.Info("STOPSERVER CALLED - STARTING SHUTDOWN SEQUENCE") _ = s.logger.Sync() @@ -2761,6 +2823,11 @@ func (s *Server) StopServer() error { s.logger.Debug("Server shutdown already in progress via Shutdown(), skipping StopServer") return nil } + if run != nil && s.serverCtx != run.ctx { + s.mu.Unlock() + s.logger.Debug("Server stop requested for a previous run, a newer run is current") + return nil + } if !s.running { s.mu.Unlock() // Return nil instead of error to prevent race condition logs @@ -2768,8 +2835,11 @@ func (s *Server) StopServer() error { return nil } - // Capture httpServer reference while holding the lock + // Capture httpServer reference while holding the lock, and the run being + // stopped: a StartServer that lands while this stop is still cleaning up + // installs a new context, which the tail below must not cancel or unmark. httpServer := s.httpServer + stoppingCtx, stoppingCancel := s.serverCtx, s.serverCancel s.mu.Unlock() // Notify about server stopping @@ -2778,6 +2848,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 { @@ -2834,9 +2908,16 @@ func (s *Server) StopServer() error { // STEP 3: Cancel the server context to signal other components s.logger.Info("STOPSERVER - Cancelling server context") _ = s.logger.Sync() + if stoppingCancel != nil { + stoppingCancel() + } s.mu.Lock() - if s.serverCancel != nil { - s.serverCancel() + if s.serverCtx != stoppingCtx { + // A newer run started while this one was being stopped; its state is + // not this stop's to clear. + s.mu.Unlock() + s.logger.Info("STOPSERVER - A newer run started during the stop, leaving its state alone") + return nil } // Set running to false immediately after server is shut down @@ -3575,6 +3656,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 +3853,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/internal/server/server_restart_watcher_test.go b/internal/server/server_restart_watcher_test.go new file mode 100644 index 000000000..c5e9584ae --- /dev/null +++ b/internal/server/server_restart_watcher_test.go @@ -0,0 +1,44 @@ +//go:build !server + +package server + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// A stopped run leaves a watcher behind that reacts to its cancelled context. +// When it wakes after the next StartServer it must leave the new run alone. +func TestStartServer_WatcherOfAStoppedRunLeavesTheNextRunAlone(t *testing.T) { + env := NewTestEnvironment(t) + t.Cleanup(env.Cleanup) + srv := env.proxyServer + + reached := make(chan struct{}, 1) + release := make(chan struct{}) + srv.testHookRunWatcher = func() { + select { + case reached <- struct{}{}: + default: + } + <-release + } + + require.NoError(t, srv.StopServer()) + select { + case <-reached: + case <-time.After(10 * time.Second): + t.Fatal("the watcher of the stopped run never woke") + } + + require.NoError(t, srv.StartServer(context.Background())) + env.waitForServerReady() + + close(release) // the old watcher continues only now, with the new run up + time.Sleep(time.Second) + require.True(t, srv.IsRunning(), "the watcher of the previous run stopped the new run") + require.True(t, env.testServerConnection()) +} diff --git a/oas/docs.go b/oas/docs.go index 7fc4734a5..f48e13dba 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.\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}/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..47115813d 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,18 @@ 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. + + 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 + uniqueItems: false display_name: type: string display_path: @@ -7628,6 +7710,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 +7842,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 +9029,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: |-