diff --git a/CHANGELOG.md b/CHANGELOG.md index 3510dca44..3cfeb4d3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ Releases follow [Semantic Versioning](https://semver.org/). ### Breaking Changes +- **config: `secret_file_dirs` allow-list for `${file:}` and upstream guards (#1721).** Upstream server fields resolve `${file:}` only under `secret_file_dirs` (platform defaults, `CREDENTIALS_DIRECTORY`, `/secrets`; `[]` disables; `["*"]` warns). Before this release any absolute path resolved, so an existing upstream `${file:/abs/path}` outside the allow-list stops resolving after the upgrade and that server fails to connect (on macOS and Windows the default list is only `/secrets`); startup logs one warning naming every affected server. Upstream fields also refuse `${env:MCPPROXY_*}`, refuse proxy config/data/admin-key files by open-handle identity, any file with more than one hard link, and earlier config versions replaced on save, and use traversal-resistant opens (`os.Root`). `MCPPROXY_API_KEY_FILE`, `oauth_token_encryption_key` / `MCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY_FILE` are not gated; `api_key` `${file:}` is. `secret_file_dirs` is config-file-only (management APIs cannot change it, and an undecodable config file refuses the edit). Policy denials stop one upstream without stopping the daemon. **Migration:** add the file's directory to `secret_file_dirs` in the config file (an explicit list replaces the platform defaults), or move the file under `/secrets`; a hardlinked secret file must be copied instead (more than one link is refused); `["*"]` restores the old any-path behaviour. + - **trust mode / tool approvals (Spec 119):** `scan` is now the default per-server trust mode, and under `scan` a **changed** tool contract whose offline TPA scan is clean is approved automatically in the same discovery pass (reason `scan_approved`, activity event `tool_auto_approved`) instead of being held. A diff --git a/cmd/mcpproxy/call_cmd.go b/cmd/mcpproxy/call_cmd.go index f8aa03258..f49628850 100644 --- a/cmd/mcpproxy/call_cmd.go +++ b/cmd/mcpproxy/call_cmd.go @@ -14,7 +14,6 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/cliclient" "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" "github.com/smart-mcp-proxy/mcpproxy-go/internal/index" - "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" "github.com/smart-mcp-proxy/mcpproxy-go/internal/server" "github.com/smart-mcp-proxy/mcpproxy-go/internal/truncate" "github.com/smart-mcp-proxy/mcpproxy-go/internal/upstream" @@ -506,8 +505,7 @@ func runCallToolVariantStandalone(ctx context.Context, toolVariant string, args } defer indexManager.Close() - // Create secret resolver for command execution - secretResolver := secret.NewResolver() + secretResolver := cliUpstreamSecretResolver(globalConfig) // Create upstream manager upstreamManager := upstream.NewManager(logger, globalConfig, storageManager.GetBoltDB(), secretResolver, storageManager) diff --git a/cmd/mcpproxy/cli_config.go b/cmd/mcpproxy/cli_config.go index 05c1f4e69..7f1f03e29 100644 --- a/cmd/mcpproxy/cli_config.go +++ b/cmd/mcpproxy/cli_config.go @@ -7,8 +7,17 @@ import ( "path/filepath" "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" ) +// cliUpstreamSecretResolver matches the daemon's upstream ${file:}/env policy. +func cliUpstreamSecretResolver(cfg *config.Config) *secret.Resolver { + if cfg == nil { + return config.BuildSecretResolver(&config.Config{}, "", secret.ScopeUpstream) + } + return config.BuildSecretResolver(cfg, cfg.ConfigFilePathForPolicy(), secret.ScopeUpstream) +} + // cliDiagnosticsWriter receives the loader's removed-key / deprecated-key // findings (Spec 107 FR-032) for every CLI command that loads the config // through loadCLIConfig. It is stderr so structured stdout (`-o json`) stays diff --git a/cmd/mcpproxy/cli_upstream_secret_policy_test.go b/cmd/mcpproxy/cli_upstream_secret_policy_test.go new file mode 100644 index 000000000..e4c109b8c --- /dev/null +++ b/cmd/mcpproxy/cli_upstream_secret_policy_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "context" + "os" + "path/filepath" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" + "github.com/stretchr/testify/require" +) + +func TestCLIUpstreamSecretResolver_RefusesOutOfPolicyFileAndMCPProxyEnv(t *testing.T) { + dir := t.TempDir() + allowed := filepath.Join(dir, "allowed") + outside := filepath.Join(dir, "outside") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + require.NoError(t, os.MkdirAll(outside, 0o700)) + outsideFile := filepath.Join(outside, "secret") + require.NoError(t, os.WriteFile(outsideFile, []byte("leak\n"), 0o600)) + + w := config.SecretFileDirs{allowed} + cfg := &config.Config{DataDir: dir, Listen: "127.0.0.1:0", SecretFileDirs: &w} + path := filepath.Join(dir, config.ConfigFileName) + require.NoError(t, config.SaveConfig(cfg, path)) + cfg, err := config.LoadFromFile(path) + require.NoError(t, err) + + r := cliUpstreamSecretResolver(cfg) + srv := config.CopyServerConfig(&config.ServerConfig{ + Name: "s", + URL: "http://127.0.0.1:9/mcp", + Headers: map[string]string{"Authorization": "Bearer ${file:" + outsideFile + "}"}, + }) + errs := r.ExpandStructSecretsCollectErrors(context.Background(), srv) + require.NotEmpty(t, errs) + + srv2 := config.CopyServerConfig(&config.ServerConfig{ + Name: "s", + URL: "http://127.0.0.1:9/mcp", + Env: map[string]string{"K": "${env:MCPPROXY_API_KEY}"}, + }) + errs2 := r.ExpandStructSecretsCollectErrors(context.Background(), srv2) + require.NotEmpty(t, errs2) + require.ErrorIs(t, errs2[0].Err, secret.ErrReservedEnvVar) +} diff --git a/cmd/mcpproxy/code_cmd.go b/cmd/mcpproxy/code_cmd.go index edca604cf..e28796c17 100644 --- a/cmd/mcpproxy/code_cmd.go +++ b/cmd/mcpproxy/code_cmd.go @@ -15,7 +15,6 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/codescripts" "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" "github.com/smart-mcp-proxy/mcpproxy-go/internal/index" - "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" "github.com/smart-mcp-proxy/mcpproxy-go/internal/server" "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" "github.com/smart-mcp-proxy/mcpproxy-go/internal/truncate" @@ -323,8 +322,7 @@ func runCodeExecStandalone(globalConfig *config.Config, code string, input map[s } defer indexManager.Close() - // Create secret resolver - secretResolver := secret.NewResolver() + secretResolver := cliUpstreamSecretResolver(globalConfig) // Create upstream manager upstreamManager := upstream.NewManager(logger, globalConfig, storageManager.GetBoltDB(), secretResolver, storageManager) diff --git a/cmd/mcpproxy/doctor_upstream_secret_policy_test.go b/cmd/mcpproxy/doctor_upstream_secret_policy_test.go new file mode 100644 index 000000000..801b6f3f2 --- /dev/null +++ b/cmd/mcpproxy/doctor_upstream_secret_policy_test.go @@ -0,0 +1,61 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/health" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/upstream/core" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" +) + +func TestDoctorOutput_UpstreamSecretPolicyDenialPublicOnly(t *testing.T) { + dir := t.TempDir() + allowed := filepath.Join(dir, "allowed") + outside := filepath.Join(dir, "outside", "deep", "token.pem") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + require.NoError(t, os.MkdirAll(filepath.Dir(outside), 0o700)) + require.NoError(t, os.WriteFile(outside, []byte("x\n"), 0o600)) + w := config.SecretFileDirs{allowed} + cfg := &config.Config{DataDir: dir, SecretFileDirs: &w} + r := config.BuildSecretResolver(cfg, "", secret.ScopeUpstream) + srvCfg := &config.ServerConfig{ + Name: "denied", Command: "true", + Env: map[string]string{"TOKEN": "${file:" + outside + "}"}, + } + _, err := core.NewClientWithOptions("denied", srvCfg, zap.NewNop(), nil, cfg, nil, false, r) + require.Error(t, err) + var pe *core.UpstreamSecretPolicyError + require.ErrorAs(t, err, &pe) + + h := health.CalculateHealth(health.HealthCalculatorInput{ + Name: "denied", Enabled: true, State: "error", Connected: false, LastError: err.Error(), + }, nil) + diag := map[string]interface{}{ + "total_issues": 1, + "upstream_errors": []interface{}{ + map[string]interface{}{ + "server_name": "denied", + "error_message": h.Detail, + }, + }, + } + + oldFmt := doctorOutput + t.Cleanup(func() { doctorOutput = oldFmt }) + doctorOutput = "pretty" + var runErr error + out, _ := captureStd(func() { runErr = outputDiagnostics(diag, nil, nil, "", nil) }) + require.NoError(t, runErr) + assert.Contains(t, out, pe.Public) + for _, leak := range []string{outside, "${file:", "TOKEN"} { + assert.NotContains(t, out, leak) + } + assert.True(t, strings.Contains(out, "Upstream Server Connection Errors")) +} diff --git a/cmd/mcpproxy/secrets_cmd.go b/cmd/mcpproxy/secrets_cmd.go index 28bdcffe8..b5c5e0ab8 100644 --- a/cmd/mcpproxy/secrets_cmd.go +++ b/cmd/mcpproxy/secrets_cmd.go @@ -68,7 +68,7 @@ func getSecretsSetCommand() *cobra.Command { // The arguments parsed; from here a failure is about the keyring, // and the usage text would only bury the explanation. cmd.SilenceUsage = true - return runSecretsSet(secret.NewResolver(), os.Stdin, os.Stdout, args, opts) + return runSecretsSet(config.BuildSecretResolverForKeyringCLI(), os.Stdin, os.Stdout, args, opts) }, } @@ -188,7 +188,7 @@ func getSecretsGetCommand() *cobra.Command { RunE: func(_ *cobra.Command, args []string) error { name := args[0] - resolver := secret.NewResolver() + resolver := config.BuildSecretResolverForKeyringCLI() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() @@ -230,7 +230,7 @@ func getSecretsDeleteCommand() *cobra.Command { RunE: func(_ *cobra.Command, args []string) error { name := args[0] - resolver := secret.NewResolver() + resolver := config.BuildSecretResolverForKeyringCLI() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() @@ -264,7 +264,7 @@ func getSecretsListCommand() *cobra.Command { Short: "List all stored secrets", Long: "List all secrets stored in available providers. Secret values are never displayed.", RunE: func(_ *cobra.Command, _ []string) error { - resolver := secret.NewResolver() + resolver := config.BuildSecretResolverForKeyringCLI() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() @@ -369,8 +369,8 @@ func getSecretsMigrateCommand() *cobra.Command { return fmt.Errorf("failed to load config: %w", err) } - // Analyze configuration for potential secrets - resolver := secret.NewResolver() + // Analyze configuration for plaintext migration hints (no upstream file reads). + resolver := config.BuildSecretResolverForKeyringCLI() analysis := resolver.AnalyzeForMigration(cfg) if len(analysis.Candidates) == 0 { diff --git a/cmd/mcpproxy/tools_cmd.go b/cmd/mcpproxy/tools_cmd.go index 6736717b5..1f5e9da05 100644 --- a/cmd/mcpproxy/tools_cmd.go +++ b/cmd/mcpproxy/tools_cmd.go @@ -17,7 +17,6 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts" "github.com/smart-mcp-proxy/mcpproxy-go/internal/logs" "github.com/smart-mcp-proxy/mcpproxy-go/internal/preflight" - "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" "github.com/smart-mcp-proxy/mcpproxy-go/internal/security/detect" "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" "github.com/smart-mcp-proxy/mcpproxy-go/internal/transport" @@ -1110,8 +1109,7 @@ func runToolsListStandalone(ctx context.Context, serverName string, globalConfig } } - // Create secret resolver - secretResolver := secret.NewResolver() + secretResolver := cliUpstreamSecretResolver(globalConfig) // Create log config for managed client logConfig := &config.LogConfig{ diff --git a/cmd/mcpproxy/upstream_add_secret_test.go b/cmd/mcpproxy/upstream_add_secret_test.go index 572849a15..3b5db2f3e 100644 --- a/cmd/mcpproxy/upstream_add_secret_test.go +++ b/cmd/mcpproxy/upstream_add_secret_test.go @@ -6,6 +6,7 @@ import ( "strings" "testing" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" ) @@ -62,7 +63,7 @@ func (f *fakeKeyringProvider) List(_ context.Context) ([]secret.Ref, error) { func (f *fakeKeyringProvider) IsAvailable() bool { return f.available } func newTestSecretResolver(fake *fakeKeyringProvider) *secret.Resolver { - r := secret.NewResolver() + r := config.BuildSecretResolverForKeyringCLI() r.RegisterProvider("keyring", fake) return r } diff --git a/cmd/mcpproxy/upstream_cmd.go b/cmd/mcpproxy/upstream_cmd.go index 74cc16157..9029c2dfd 100644 --- a/cmd/mcpproxy/upstream_cmd.go +++ b/cmd/mcpproxy/upstream_cmd.go @@ -27,7 +27,6 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/logs" "github.com/smart-mcp-proxy/mcpproxy-go/internal/oauth" "github.com/smart-mcp-proxy/mcpproxy-go/internal/reqcontext" - "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" ) var ( @@ -1580,7 +1579,7 @@ func runUpstreamAdd(cmd *cobra.Command, args []string) error { // FR-065: --secret-env/--secret-header write to the OS keyring instead // of the config, under the shared per-kind ref name, and merge // ${keyring:} into the same env/headers maps above. - resolver := secret.NewResolver() + resolver := config.BuildSecretResolverForKeyringCLI() var writtenSecretRefs []string if len(upstreamAddSecretEnvs) > 0 || len(upstreamAddSecretHeaders) > 0 { var err error diff --git a/docs/configuration/config-file.md b/docs/configuration/config-file.md index 8b3df60ef..730a7aca7 100644 --- a/docs/configuration/config-file.md +++ b/docs/configuration/config-file.md @@ -58,6 +58,7 @@ MCPProxy uses a JSON configuration file located at `~/.mcpproxy/mcp_config.json` |--------|------|---------|-------------| | `listen` | string | `127.0.0.1:8080` | Address and port to listen on | | `data_dir` | string | `~/.mcpproxy` | Directory for data storage | +| `secret_file_dirs` | string[] | platform defaults | Where `${file:}` references may read on disk. See [Secret file directories](#secret-file-directories-secret_file_dirs). | | `api_key` | string | auto-generated | API key for REST API authentication | | `oauth_token_encryption_key` | string | `""` (off) | Key that encrypts the upstream OAuth tokens in `config.db` (AES-256-GCM): 32 random bytes, base64. A literal key or one reference: `${file:/abs/path}`, `${env:NAME}`, `${keyring:NAME}`. Env `MCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY` / `MCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY_FILE` override it. A key that cannot be resolved stops startup with exit code 4 before `config.db` is opened. Needs a restart. Masked in the REST API and the Web UI. See [OAuth Token Encryption](/features/oauth-token-encryption) | | `trusted_hosts` | string[] | `[]` | Non-loopback `Host` header values accepted on a loopback listener. Needed when running behind a reverse proxy — see [Reverse Proxy Deployment](/operations/reverse-proxy). This is DNS-rebinding protection only; it is **not** the control for forwarded headers (see `trusted_proxies`) | @@ -68,6 +69,39 @@ MCPProxy uses a JSON configuration file located at `~/.mcpproxy/mcp_config.json` | `enable_socket` | boolean | `true` | Enable the Unix socket/named pipe the tray uses. Socket connections are trusted **without the API key**, including stdio servers spawned under `none` or `sandbox` isolation, which can then mint agent tokens. Set `false` on headless installs and whenever untrusted stdio servers run outside `docker` isolation. | | `forward_client_headers` | boolean | `true` | Master switch for [client header forwarding](/configuration/upstream-servers#client-header-forwarding). Nothing is forwarded until a server lists names in `forward_headers`. Env `MCPPROXY_FORWARD_CLIENT_HEADERS=false` disables it for the process (never persisted). | +### Secret file directories (`secret_file_dirs`) {#secret-file-directories-secret_file_dirs} + +`secret_file_dirs` is the allow-list of absolute directories from which `${file:/absolute/path}` references may read a secret. It applies to proxy-owned fields (`api_key`, a `${file:}` in `data_dir`, and similar) and to every field on an upstream server entry (see [Upstream servers — Secret references](/configuration/upstream-servers#secret-references)). Upstream `${file:}` reads still refuse proxy state files even when a path lies under an allowed root. + +**Defaults when the key is omitted:** + +| Platform | Roots | +|----------|--------| +| Linux | `/run/secrets`, `/run/credentials`, and `/secrets` once `data_dir` is resolved | +| macOS | `/secrets` | +| Windows | `\secrets` | + +If `CREDENTIALS_DIRECTORY` is set to an absolute path (systemd user credentials, some container layouts), that directory is added to the effective list on every platform. + +| Value | Meaning | +|-------|---------| +| *(omitted)* | Platform defaults in the table above | +| `[]` | Every `${file:}` reference is refused | +| `["*"]` | Compatibility mode: any absolute regular file may be read (upstream deny rules still apply). Emits a startup **warning** | +| `["/var/lib/secrets", ...]` | Only files contained in the listed absolute directories | + +Validation rejects JSON `null`, relative paths, and a list that mixes `*` with other entries. A configured root that does not exist yet produces a startup warning; reads under that root fail until the directory appears. + +**Upgrading (breaking change):** releases before #1721 resolved any absolute `${file:}` path in an upstream server entry. After the upgrade, a reference outside the effective allow-list stops resolving and that server fails to connect; with the key omitted, macOS and Windows allow only `/secrets`. Startup logs one warning naming every affected server (`upstream ${file:} references are outside secret_file_dirs and will not resolve`). **Migration:** add the file's directory to `secret_file_dirs` in this file (an explicit list replaces the platform defaults, so include `/secrets` if you use it), or move the file under `/secrets`. A secret file with more than one hard link is refused, so copy a hardlinked secret instead of linking it. `["*"]` restores the old behaviour for every path; the upstream deny rules still apply, but it does not protect against a concurrent filesystem writer swapping a symlink between the check and the open. + +**OAuth token encryption key:** `oauth_token_encryption_key` and `MCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY_FILE` are proxy-owned operator keys, like `MCPPROXY_API_KEY_FILE`, and are **not** gated by `secret_file_dirs`: the recommended key location is outside `data_dir` (see [OAuth Token Encryption](/features/oauth-token-encryption)), and the key is never shown or sent anywhere, so an unreadable or wrong file only stops startup with exit code 4. + +**Operator policy, not management API (v1):** `secret_file_dirs` cannot be changed or widened through `PATCH /api/v1/config`, `POST /api/v1/config/apply`, or any management merge that would persist a different value than the on-disk file — each save restores the file’s setting (`PersistableConfig`). Hot reload: editing the key in `mcp_config.json` rebuilds the upstream secret resolver without a process restart. For v1, anyone who can replace the entire config file is trusted to set policy directly in that file. + +**Admin API key and `MCPPROXY_API_KEY_FILE`:** The environment variable `MCPPROXY_API_KEY_FILE` is operator-controlled and is **not** gated by `secret_file_dirs` (it uses the same absolute-path read rules as other admin key files). It is refused when it resolves to the active config file or to anything under `data_dir` except `/secrets`. A `${file:}` in the `api_key` field **is** gated by `secret_file_dirs`. Setting both `MCPPROXY_API_KEY` and `MCPPROXY_API_KEY_FILE` to non-empty values still fails startup; an unusable key file still fails startup with no generated-key fallback. + +See [Environment variables — API key from a file](/configuration/environment-variables#api-key-from-a-file) for `MCPPROXY_API_KEY_FILE` examples. + ### `audit_log` (edition-neutral JSONL audit record) One JSONL line per authorization decision and tool call. Personal edition defaults to diff --git a/docs/configuration/upstream-servers.md b/docs/configuration/upstream-servers.md index dcbd50899..e986cb184 100644 --- a/docs/configuration/upstream-servers.md +++ b/docs/configuration/upstream-servers.md @@ -313,21 +313,108 @@ full reference, including the [`/config-to-secret`](../api/rest-api.md#post-apiv1serversnameconfig-to-secret) endpoint that backs the "Convert to secret" affordance. -### Secret references +### Secret references {#secret-references} -`headers` and `env` values support three reference shapes that get resolved -at request time rather than stored in plaintext: +`headers`, `env`, `args`, `url`, `command`, `oauth`, and nested isolation fields +support secret references that are resolved when mcpproxy prepares that server’s +connection, not stored in plaintext on the wire after substitution: | Reference | Source | Lifetime | |---|---|---| | `${keyring:NAME}` | OS keyring entry called `NAME` | Persists across restarts; managed via the Secrets page or `mcpproxy secrets` CLI | | `${env:VAR}` | The `VAR` environment variable on the mcpproxy process | Tied to the shell/launcher that started mcpproxy | -| `${file:/absolute/path}` | The contents of a file (Docker/Kubernetes secret, systemd credential), one trailing newline removed | Read each time the server's connection is set up, so a rotated secret is picked up when the server is next restarted | - -When mcpproxy connects to an upstream it substitutes the reference with -the actual secret. The reference itself never reaches the upstream MCP -server. See [Keyring Integration](../features/keyring-integration.md) -for the full secret-storage story. +| `${file:/absolute/path}` | File contents (Compose/Kubernetes secret, systemd credential), one trailing newline removed | Read each time the server connection is built so a rotated file is picked up on the next connect or restart | + +#### `secret_file_dirs` and `${file:}` + +Every `${file:}` path must be absolute. For upstream servers, the file must lie +under one of the directories listed in [`secret_file_dirs`](/configuration/config-file#secret-file-directories-secret_file_dirs) +(or under platform defaults when the key is omitted). Set `secret_file_dirs` to +`[]` to disallow all file references; `["*"]` is compatibility mode (startup +warning) but upstream reads still enforce the deny rules below. + +`CREDENTIALS_DIRECTORY`, when set, is treated like an extra allow-list root on +load — useful for systemd user services that inject credentials beside the +process. + +The proxy’s own `api_key` and `data_dir` use the same `secret_file_dirs` policy +when they carry `${file:}` references. `MCPPROXY_API_KEY_FILE` is separate: it is +not limited by `secret_file_dirs` (see the config-file section above). + +**Upgrading from a release without `secret_file_dirs`:** before #1721 any +absolute `${file:}` path resolved. After the upgrade, a reference outside the +effective allow-list stops resolving, and that server fails to connect with +`secret file is missing, unreadable or outside secret_file_dirs`. With the key +omitted, macOS and Windows allow only `/secrets`, so a reference such +as `${file:/Users/me/.config/tokens/github}` is affected. At startup mcpproxy +logs one warning naming every such server +(`upstream ${file:} references are outside secret_file_dirs and will not resolve`). +To migrate, either add the file's directory to `secret_file_dirs` in the config +file (for example `"secret_file_dirs": ["/Users/me/.config/tokens"]`; the +platform defaults are then replaced by your list, so add `/secrets` +too if you use it), or move the file under `/secrets`. A secret file +with more than one hard link is refused (see below), so copy a hardlinked secret +rather than linking it. + +#### Reserved proxy namespace + +Upstream expansion refuses the whole `MCPPROXY_` environment namespace (including +`MCPPROXY_CRED_KEY`), using Windows case rules for the prefix. Proxy-owned +readers (`api_key`, `data_dir`, server-edition OAuth client fields) use a +proxy-scoped resolver and may still read those variables. + +#### Files an upstream must never read + +Even when a path is under an allowed root or `secret_file_dirs` is `["*"]`, an +upstream-scoped read refuses: + +- The active config file and the active admin API key source file(s) +- Regular files directly under `` (except under `/secrets`) +- Regular files one level below `/certs`, `/index.bleve`, or `/tpa-lkg` (not deeper subtrees) +- Any file with more than one hard link +- An earlier version of the config file that this process replaced on save, when a hardlink to it was made before the save + +Checks use the opened file’s identity (device and inode), so hardlinks, aliases, +and a config file replaced by rename are refused — not only a literal path match. +Secret files have no reason to be hard-linked: the link-count rule refuses a +hardlink to any live proxy file, wherever it is under ``. + +Hardlink protection is best-effort against a local user who can already create +links in an allowed directory. The list of replaced config versions lives in +memory, holds the last 4096 saves, and is filled only by saves this process +makes: a restart, a save by a separate process (a `mcpproxy` CLI command +editing the config while the daemon runs) or 4096 later saves forget an older +version, and a link to it then reads as an ordinary file with one link. The +same is true of a hardlink to a log file that has since been rotated or +deleted: once the original name is gone, the link is the file's only link. +Keep allowed directories writable only by the account that runs mcpproxy. + +`["*"]` resolves the path and then opens it by path, so it does not protect +against a concurrent filesystem writer that swaps a symlink in between; the +allow-list mode opens through the allowed root and does. + +#### Policy denials vs load failures + +A policy denial on one upstream server does **not** stop the daemon. That server +fails to connect or spawn; status, per-server logs, and `mcpproxy doctor` show a +fixed public message (no path or secret echoed), for example: + +- `secret file is missing, unreadable or outside secret_file_dirs` +- `secret reference refused: this environment variable is reserved` + +Non-policy resolution failures may still use an internal placeholder until the +reference is fixed. Failures in proxy-key or `data_dir` policy during **load** +still abort startup. + +Management surfaces (`mcpproxy tools`, `mcpproxy call`, the CLI upstream client, +and the daemon) all build the upstream resolver from the loaded config, so CLI +and runtime enforce one policy. Changing `secret_file_dirs` in the config file +hot-reloads the resolver; management APIs cannot widen the list. + +When mcpproxy connects successfully it substitutes references with the actual +secret; the reference itself never reaches the upstream MCP server. See +[Keyring Integration](../features/keyring-integration.md) for the full +secret-storage story. ## Client Header Forwarding {#client-header-forwarding} diff --git a/docs/features/keyring-integration.md b/docs/features/keyring-integration.md index 356677890..8f4ea234b 100644 --- a/docs/features/keyring-integration.md +++ b/docs/features/keyring-integration.md @@ -59,9 +59,11 @@ The same rules apply wherever it is used: - The path must be absolute. A symlink is followed (Kubernetes secret volumes are symlinks) but must point at a regular file. On Windows an absolute path has a drive letter (`C:\ProgramData\mcpproxy\key` - or `C:/ProgramData/mcpproxy/key`); a path that starts with `/` and has no drive is not absolute. In - `mcp_config.json` a backslash must be escaped (`"${file:C:\\ProgramData\\mcpproxy\\key}"`), so forward - slashes are easier. + or `C:/ProgramData/mcpproxy/key`); a path that starts with `/` and has no drive is not absolute. UNC + paths (`\\server\share\...`, `//server/share/...`) and device namespaces (`\\?\`, `\\.\`, and the + forward-slash or mixed spellings) are refused so a `${file:}` reference cannot trigger SMB or bypass + containment. In `mcp_config.json` a backslash must be escaped + (`"${file:C:\\ProgramData\\mcpproxy\\key}"`), so forward slashes are easier. - At most 64 KiB is read. A larger file is an error, never a truncated secret. - One trailing newline is removed, LF or CRLF, so a file written on Windows resolves to the same value as one written on Linux. Leading and inner whitespace are kept. diff --git a/internal/appctx/context.go b/internal/appctx/context.go index 1299f597b..49cdb8162 100644 --- a/internal/appctx/context.go +++ b/internal/appctx/context.go @@ -62,7 +62,7 @@ func NewApplicationContext(cfg *config.Config, logConfig *config.LogConfig, logg } // Initialize upstream manager - secretResolver := secret.NewResolver() + secretResolver := upstreamSecretResolver(cfg) baseUpstreamManager := upstream.NewManager(logger, cfg, storageManager.GetBoltDB(), secretResolver, storageManager) upstreamManager := &UpstreamManagerAdapter{Manager: baseUpstreamManager} @@ -191,3 +191,10 @@ func (ctx *ApplicationContext) GetLogManager() LogManager { func (ctx *ApplicationContext) GetCacheManager() CacheManager { return ctx.CacheManager } + +// upstreamSecretResolver builds the upstream-scoped resolver with the deny +// list naming the config file the process actually loaded (--config), not the +// default under data_dir. +func upstreamSecretResolver(cfg *config.Config) *secret.Resolver { + return config.BuildSecretResolver(cfg, cfg.ConfigFilePathForPolicy(), secret.ScopeUpstream) +} diff --git a/internal/appctx/secret_resolver_test.go b/internal/appctx/secret_resolver_test.go new file mode 100644 index 000000000..91e1fde50 --- /dev/null +++ b/internal/appctx/secret_resolver_test.go @@ -0,0 +1,37 @@ +package appctx + +import ( + "context" + "os" + "path/filepath" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" + "github.com/stretchr/testify/require" +) + +// Review #8 (PR #1884): with --config pointing outside data_dir, the upstream +// resolver's deny list must name that file, so an upstream ${file:} cannot +// read the loaded config even when it sits under an allowed root. +func TestUpstreamSecretResolver_DeniesLoadedConfigPath(t *testing.T) { + dir := t.TempDir() + allowed := filepath.Join(dir, "allowed") + dataDir := filepath.Join(dir, "data") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + require.NoError(t, os.MkdirAll(dataDir, 0o700)) + cfgPath := filepath.Join(allowed, "elsewhere.json") + + dirs := config.SecretFileDirs{allowed} + seed := config.DefaultConfig() + seed.DataDir = dataDir + seed.SecretFileDirs = &dirs + require.NoError(t, config.SaveConfig(seed, cfgPath)) + + cfg, err := config.LoadFromFile(cfgPath) + require.NoError(t, err) + + _, err = upstreamSecretResolver(cfg).ExpandSecretRefs(context.Background(), "${file:"+cfgPath+"}") + require.Error(t, err) + require.True(t, secret.IsPolicyDenial(err), "want a policy denial, got %v", err) +} diff --git a/internal/config/api_key_env.go b/internal/config/api_key_env.go index 2078be534..3318c8b74 100644 --- a/internal/config/api_key_env.go +++ b/internal/config/api_key_env.go @@ -119,7 +119,8 @@ func resolveAPIKeyRef(c *Config) error { if envKey.Set && envKey.Key != "" { return nil } - resolved, err := secret.NewResolver().ExpandSecretRefs(context.Background(), c.APIKey) + resolver := BuildSecretResolver(c, c.loadConfigPath, secret.ScopeProxy) + resolved, err := resolver.ExpandSecretRefs(context.Background(), c.APIKey) if err != nil { // The error is deliberately a fixed sentence: ExpandSecretRefs' own // text quotes the reference, and the api_key field is the one value diff --git a/internal/config/api_key_env_test.go b/internal/config/api_key_env_test.go index 3fb6aff18..0d268fa1d 100644 --- a/internal/config/api_key_env_test.go +++ b/internal/config/api_key_env_test.go @@ -27,9 +27,10 @@ func writeKeyFile(t *testing.T, content string) string { func writeAPIKeyConfig(t *testing.T, apiKey string) string { t.Helper() raw, err := json.Marshal(map[string]any{ - "listen": "127.0.0.1:8080", - "api_key": apiKey, - "mcpServers": []any{}, + "listen": "127.0.0.1:8080", + "api_key": apiKey, + "secret_file_dirs": []string{"*"}, + "mcpServers": []any{}, }) require.NoError(t, err) return writeOverrideTestFile(t, string(raw)) @@ -443,7 +444,7 @@ func TestServerConfig_FileReferencesExpandOnACopy(t *testing.T) { } resolved := CopyServerConfig(orig) - errs := secret.NewResolver().ExpandStructSecretsCollectErrors(context.Background(), resolved) + errs := secret.NewTestWildcardResolver().ExpandStructSecretsCollectErrors(context.Background(), resolved) require.Empty(t, errs) assert.Equal(t, "Bearer upstream-token", resolved.Headers["Authorization"]) diff --git a/internal/config/config.go b/internal/config/config.go index 5739f2e56..0b082e685 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -249,6 +249,13 @@ type Config struct { TrayEndpoint string `json:"tray_endpoint,omitempty" mapstructure:"tray-endpoint"` // Tray endpoint override (unix:// or npipe://) EnableSocket bool `json:"enable_socket" mapstructure:"enable-socket"` // Enable Unix socket/named pipe for local IPC (default: true) DataDir string `json:"data_dir" mapstructure:"data-dir"` + // SecretFileDirs lists absolute directories where ${file:} references may + // be resolved. Absent (nil) uses platform defaults; an explicit empty array + // disables file references; exactly ["*"] allows any path (compatibility mode). + SecretFileDirs *SecretFileDirs `json:"secret_file_dirs,omitempty" mapstructure:"secret-file-dirs"` + // loadConfigPath is the path LoadFromFile read; used for policy checks during + // validation (not serialized). + loadConfigPath string `json:"-"` // Deprecated: EnableTray is unused and has no runtime effect. Kept for backward compatibility. EnableTray bool `json:"enable_tray,omitempty" mapstructure:"tray"` DebugSearch bool `json:"debug_search" mapstructure:"debug-search"` @@ -3151,6 +3158,7 @@ func (c *Config) validateDetailedCore() []ValidationError { // Spec 107 FR-027/FR-039: every trusted_proxies entry must parse as a // CIDR or IP on every door (boot, PATCH, /config/apply). errors = append(errors, validateTrustedProxies(c)...) + errors = append(errors, validateSecretFileDirs(c)...) // Spec 107 FR-039: the server_edition block is validated (never mutated) // on every door — boot, PATCH and /config/apply. No-op in the personal @@ -3270,6 +3278,12 @@ func (c *Config) Validate() error { return err } + if path := os.Getenv(EnvAPIKeyFile); path != "" { + if err := validateAdminAPIKeyFilePath(c, c.loadConfigPath, path); err != nil { + return err + } + } + // api_key may itself be a secret reference (api_key: "${file:/run/secrets/k}"), // so the key can come from a Docker/Kubernetes secret or a systemd credential // without being written into this file. diff --git a/internal/config/deprecated.go b/internal/config/deprecated.go index 75d60bf64..fadc81296 100644 --- a/internal/config/deprecated.go +++ b/internal/config/deprecated.go @@ -113,6 +113,7 @@ func CleanDeprecatedFields(configPath string) ([]DeprecatedField, error) { if err := os.WriteFile(tmpPath, cleaned, perm); err != nil { return nil, fmt.Errorf("writing cleaned config: %w", err) } + noteSupersededConfig(configPath) if err := os.Rename(tmpPath, configPath); err != nil { os.Remove(tmpPath) // best-effort cleanup return nil, fmt.Errorf("replacing config: %w", err) diff --git a/internal/config/load_warnings.go b/internal/config/load_warnings.go new file mode 100644 index 000000000..41c55132d --- /dev/null +++ b/internal/config/load_warnings.go @@ -0,0 +1,53 @@ +package config + +import "sync" + +// LoadWarningRecorder receives non-fatal messages from config loading. +type LoadWarningRecorder func(message string, key string, value string) + +// LoadWarning is a deferred config load warning. +type LoadWarning struct { + Message string + Key string + Value string +} + +type pendingWarning struct { + message, key, value string +} + +var ( + loadWarnMu sync.RWMutex + loadWarnRecorder LoadWarningRecorder + pendingLoadWarnings []pendingWarning +) + +// SetLoadWarningRecorder installs a callback for config load warnings. When unset, +// warnings are discarded (CLI paths may log separately). +func SetLoadWarningRecorder(fn LoadWarningRecorder) { + loadWarnMu.Lock() + loadWarnRecorder = fn + loadWarnMu.Unlock() +} + +func emitLoadWarning(message, key, value string) { + loadWarnMu.Lock() + defer loadWarnMu.Unlock() + if loadWarnRecorder != nil { + loadWarnRecorder(message, key, value) + return + } + pendingLoadWarnings = append(pendingLoadWarnings, pendingWarning{message, key, value}) +} + +// DrainLoadWarnings returns warnings emitted before a recorder was installed. +func DrainLoadWarnings() []LoadWarning { + loadWarnMu.Lock() + defer loadWarnMu.Unlock() + out := make([]LoadWarning, len(pendingLoadWarnings)) + for i, w := range pendingLoadWarnings { + out[i] = LoadWarning{Message: w.message, Key: w.key, Value: w.value} + } + pendingLoadWarnings = nil + return out +} diff --git a/internal/config/loader.go b/internal/config/loader.go index d377de193..93cae5dd9 100644 --- a/internal/config/loader.go +++ b/internal/config/loader.go @@ -16,7 +16,6 @@ import ( "sync/atomic" "time" - "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" "github.com/spf13/viper" ) @@ -51,6 +50,7 @@ func LoadFromFile(configPath string) (*Config, error) { return nil, fmt.Errorf("failed to load config file %s: %w", configPath, err) } } + cfg.loadConfigPath = configPath // Set data directory if not specified if cfg.DataDir == "" { @@ -62,7 +62,13 @@ func LoadFromFile(configPath string) (*Config, error) { } // Expand secret/env refs in DataDir before creating it - expandDataDir(cfg) + expandDataDir(cfg, configPath) + for _, root := range WarnMissingSecretFileDirRoots(cfg) { + emitLoadWarning("secret_file_dirs root does not exist yet", "secret_file_dirs", root) + } + if cfg.SecretFileDirs != nil && SecretFileDirsWildcard([]string(*cfg.SecretFileDirs)) { + emitLoadWarning("secret_file_dirs is wildcard compatibility mode", "secret_file_dirs", "*") + } // server_edition.oauth.client_id/client_secret are deliberately NOT // expanded here (cross-review round 6, chunk 3 P2, superseding round 1's // in-place expansion): this cfg is what becomes r.cfg/r.desiredCfg and is @@ -202,6 +208,7 @@ func LoadWithPath() (*Config, string, error) { fmt.Fprintf(os.Stderr, "INFO: Created default configuration file at %s\n", defaultConfigPath) } } + cfg.loadConfigPath = configPath // Only use viper.Unmarshal if no config file was auto-loaded // When config file is auto-loaded, CLI flags are handled in main.go @@ -222,7 +229,7 @@ func LoadWithPath() (*Config, string, error) { } // Expand secret/env refs in DataDir before creating it - expandDataDir(cfg) + expandDataDir(cfg, configPath) // server_edition.oauth.client_id/client_secret are deliberately NOT // expanded here — see the matching comment in LoadFromFile (cross-review // round 6, chunk 3 P2). @@ -519,6 +526,10 @@ func atomicWriteFileMode(path string, data []byte, perm os.FileMode, exactMode b } tmpFile = nil // Prevent deferred cleanup + // The inode being replaced stays readable through any hardlink made to it + // earlier; upstream ${file:} reads refuse it from now on (#1721). + noteSupersededConfig(path) + // Atomic rename (POSIX guarantees atomicity, Windows is best-effort) if err := os.Rename(tmpPath, path); err != nil { os.Remove(tmpPath) // Clean up on rename failure @@ -555,7 +566,10 @@ func SaveConfigWithEdits(cfg, mergeBase *Config, path string) error { } saveConfigMu.Lock() defer saveConfigMu.Unlock() - persisted := PersistableConfigWithEdits(cfg, mergeBase, path) + persisted, err := persistableConfigWithEdits(cfg, mergeBase, path) + if err != nil { + return err + } if saveConfigTestHook != nil { saveConfigTestHook() } @@ -844,11 +858,12 @@ func SetRegistriesInitCallback(callback func(*Config)) { // expandDataDir expands secret/env refs in cfg.DataDir in place. // Failures are logged to stderr and the original value is kept. -func expandDataDir(cfg *Config) { +func expandDataDir(cfg *Config, configPath string) { if cfg.DataDir == "" { return } - resolver := secret.NewResolver() + _ = configPath + resolver := BuildSecretResolverForDataDirExpand(cfg) resolved, err := resolver.ExpandSecretRefs(context.Background(), cfg.DataDir) if err != nil { fmt.Fprintf(os.Stderr, "WARN: Failed to resolve secret ref in data_dir, using original value: reference=%s err=%v\n", cfg.DataDir, err) diff --git a/internal/config/loader_secret_warnings_test.go b/internal/config/loader_secret_warnings_test.go new file mode 100644 index 000000000..88bc18ada --- /dev/null +++ b/internal/config/loader_secret_warnings_test.go @@ -0,0 +1,58 @@ +package config + +import ( + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestLoad_WarnsMissingSecretFileDirRoot(t *testing.T) { + dir := t.TempDir() + missing := filepath.Join(dir, "no-such-root") + cfg := &Config{ + DataDir: dir, + Listen: "127.0.0.1:8080", + SecretFileDirs: &SecretFileDirs{missing}, + } + path := filepath.Join(dir, ConfigFileName) + require.NoError(t, SaveConfig(cfg, path)) + + var rec []LoadWarning + SetLoadWarningRecorder(func(message, key, value string) { + rec = append(rec, LoadWarning{Message: message, Key: key, Value: value}) + }) + t.Cleanup(func() { SetLoadWarningRecorder(nil) }) + + _, err := LoadFromFile(path) + require.NoError(t, err) + assert.True(t, hasLoadWarning(rec, "secret_file_dirs root does not exist yet", missing)) +} + +func TestLoad_WarnsWildcardSecretFileDirs(t *testing.T) { + dir := t.TempDir() + wild := SecretFileDirs{"*"} + cfg := &Config{DataDir: dir, Listen: "127.0.0.1:8080", SecretFileDirs: &wild} + path := filepath.Join(dir, ConfigFileName) + require.NoError(t, SaveConfig(cfg, path)) + + var rec []LoadWarning + SetLoadWarningRecorder(func(message, key, value string) { + rec = append(rec, LoadWarning{Message: message, Key: key, Value: value}) + }) + t.Cleanup(func() { SetLoadWarningRecorder(nil) }) + + _, err := LoadFromFile(path) + require.NoError(t, err) + assert.True(t, hasLoadWarning(rec, "secret_file_dirs is wildcard compatibility mode", "*")) +} + +func hasLoadWarning(rec []LoadWarning, message, value string) bool { + for _, w := range rec { + if w.Message == message && w.Value == value { + return true + } + } + return false +} diff --git a/internal/config/process_overrides.go b/internal/config/process_overrides.go index 20e8fefe0..3c64813c5 100644 --- a/internal/config/process_overrides.go +++ b/internal/config/process_overrides.go @@ -1,6 +1,8 @@ package config import ( + "errors" + "io/fs" "reflect" "sort" "sync" @@ -492,29 +494,59 @@ func PersistableConfig(effective *Config, path string) *Config { // indistinguishable from a round trip and is not persisted — unreachable // from the Web UI, which already shows the override as the current value. func PersistableConfigWithEdits(effective, mergeBase *Config, path string) *Config { + out, _ := persistableConfigWithEdits(effective, mergeBase, path) + return out +} + +// ErrSecretFileDirsUnverified is returned by a save when the config file +// exists but cannot be decoded while the config to be written sets +// secret_file_dirs: only the file can vouch for that value (management +// surfaces cannot change it), so nothing is written rather than persist a +// value the file never held. +var ErrSecretFileDirsUnverified = errors.New("config file cannot be decoded; refusing to save secret_file_dirs it does not hold") + +// persistableConfigWithEdits is PersistableConfigWithEdits for the save path: +// it fails closed (ErrSecretFileDirsUnverified) where the comparison helper +// would fall back to the in-memory value. A missing file is not an error (the +// save creates it). +func persistableConfigWithEdits(effective, mergeBase *Config, path string) (*Config, error) { if effective == nil { - return nil + return nil, nil } processOverridesMu.RLock() overrides := effectiveOverridesLocked() processOverridesMu.RUnlock() - if len(overrides) == 0 { - return effective - } var base *Config + var unverified bool if path != "" { - if onDisk, err := DecodeConfigFile(path); err == nil { + onDisk, err := DecodeConfigFile(path) + switch { + case err == nil: base = onDisk + case !errors.Is(err, fs.ErrNotExist): + unverified = effective.SecretFileDirs != nil } } + if unverified { + return effective, ErrSecretFileDirsUnverified + } out := *effective + if base != nil { + RestoreSecretFileDirsFromFile(&out, base) + } + if len(overrides) == 0 { + if base != nil && !SecretFileDirsEqual(effective.SecretFileDirs, out.SecretFileDirs) { + return &out, nil + } + return effective, nil + } for _, o := range overrides { if mergeBase != nil && o.movedBetween(mergeBase, effective) { continue // the caller's edit } o.restore(&out, base) } - return &out + return &out, nil } diff --git a/internal/config/secret_file_dirs.go b/internal/config/secret_file_dirs.go new file mode 100644 index 000000000..c2ef11a1a --- /dev/null +++ b/internal/config/secret_file_dirs.go @@ -0,0 +1,287 @@ +package config + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "runtime" + "strings" +) + +// SecretFileDirs is the configured ${file:} allow-list. Absent (nil) selects +// platform defaults; an explicit empty list disables file references; exactly +// ["*"] is wildcard compatibility mode. JSON null is rejected. +type SecretFileDirs []string + +// UnmarshalJSON rejects null and decodes a JSON array. +func (s *SecretFileDirs) UnmarshalJSON(data []byte) error { + if bytes.Equal(bytes.TrimSpace(data), []byte("null")) { + return errors.New("secret_file_dirs cannot be null") + } + var values []string + if err := json.Unmarshal(data, &values); err != nil { + return err + } + *s = SecretFileDirs(values) + return nil +} + +const ( + secretFileDirsWildcard = "*" + envCredentialsDir = "CREDENTIALS_DIRECTORY" +) + +// ErrAdminAPIKeyFilePath is returned when MCPPROXY_API_KEY_FILE names a forbidden path. +var ErrAdminAPIKeyFilePath = errors.New(EnvAPIKeyFile + ": path is not allowed") + +// ErrSecretFileDirsNotWritable is returned when a management surface tries to change secret_file_dirs. +var ErrSecretFileDirsNotWritable = errors.New("secret_file_dirs can only be set in the configuration file") + +// SecretFileDirsChanged reports whether a management merge attempted to change +// secret_file_dirs away from what is on disk. +func SecretFileDirsChanged(base, edited *Config) bool { + if base == nil || edited == nil { + return false + } + return !SecretFileDirsEqual(base.SecretFileDirs, edited.SecretFileDirs) +} + +// RestoreSecretFileDirsFromFile copies secret_file_dirs from the on-disk config into dst. +func RestoreSecretFileDirsFromFile(dst, onDisk *Config) { + if dst == nil || onDisk == nil { + return + } + dst.SecretFileDirs = onDisk.SecretFileDirs +} + +// SecretFileDirsManagementEditRefused reports whether incoming changes +// secret_file_dirs relative to the file at configPath. It fails closed: a file +// that exists but cannot be read or decoded refuses the edit, since nothing +// shows the edit leaves the operator's setting alone. A file that does not +// exist holds no setting, so only an edit that sets one is refused. +func SecretFileDirsManagementEditRefused(configPath string, incoming *Config) bool { + if incoming == nil || configPath == "" { + return false + } + if _, statErr := os.Stat(configPath); errors.Is(statErr, fs.ErrNotExist) { + return incoming.SecretFileDirs != nil + } + onDisk, err := DecodeConfigFile(configPath) + if err != nil { + return true + } + return SecretFileDirsChanged(onDisk, incoming) +} + +// DefaultSecretFileDirRoots returns the platform default allow-list roots before +// the data directory is known. The derived /secrets entry is added +// separately once data_dir is resolved. +func DefaultSecretFileDirRoots() []string { + return DefaultSecretFileDirRootsForGOOS(runtime.GOOS) +} + +// DefaultSecretFileDirRootsForGOOS returns platform default roots before data_dir is known. +func DefaultSecretFileDirRootsForGOOS(goos string) []string { + switch goos { + case "windows", "darwin": + return nil + default: + return []string{"/run/secrets", "/run/credentials"} + } +} + +// SecretFileDirsWildcard reports whether dirs is exactly ["*"]. +func SecretFileDirsWildcard(dirs []string) bool { + return len(dirs) == 1 && dirs[0] == secretFileDirsWildcard +} + +// SecretFileDirsEqual reports whether two secret_file_dirs settings are the same. +func SecretFileDirsEqual(a, b *SecretFileDirs) bool { + if a == nil && b == nil { + return true + } + if a == nil || b == nil { + return false + } + return stringSlicesEqual([]string(*a), []string(*b)) +} + +func stringSlicesEqual(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +// EffectiveSecretFileDirRoots resolves the configured allow-list for policy +// enforcement. When cfg.SecretFileDirs is nil the defaults apply; an empty +// non-nil slice disables ${file:}; ["*"] is wildcard mode. +func EffectiveSecretFileDirRoots(cfg *Config, includeDataDirDerived bool) (wildcard bool, roots []string, disabled bool) { + return EffectiveSecretFileDirRootsForGOOS(cfg, includeDataDirDerived, runtime.GOOS) +} + +// EffectiveSecretFileDirRootsForGOOS is EffectiveSecretFileDirRoots with an +// explicit GOOS so platform default roots can be tested on Linux CI. +func EffectiveSecretFileDirRootsForGOOS(cfg *Config, includeDataDirDerived bool, goos string) (wildcard bool, roots []string, disabled bool) { + if cfg != nil && cfg.SecretFileDirs != nil { + if len(*cfg.SecretFileDirs) == 0 { + return false, nil, true + } + if SecretFileDirsWildcard([]string(*cfg.SecretFileDirs)) { + return true, nil, false + } + roots = append(roots, ([]string)(*cfg.SecretFileDirs)...) + } else { + roots = append(roots, DefaultSecretFileDirRootsForGOOS(goos)...) + } + + if credDir := os.Getenv(envCredentialsDir); credDir != "" && filepath.IsAbs(credDir) { + roots = appendUniqueAbs(roots, credDir) + } + + if includeDataDirDerived && cfg != nil && cfg.DataDir != "" && !strings.Contains(cfg.DataDir, "${") { + roots = appendUniqueAbs(roots, filepath.Join(cfg.DataDir, "secrets")) + } + + return false, roots, false +} + +func appendUniqueAbs(roots []string, dir string) []string { + dir = filepath.Clean(dir) + for _, existing := range roots { + if existing == dir { + return roots + } + } + return append(roots, dir) +} + +// validateSecretFileDirs returns fatal validation errors for secret_file_dirs. +func validateSecretFileDirs(cfg *Config) []ValidationError { + if cfg == nil || cfg.SecretFileDirs == nil { + return nil + } + dirs := []string(*cfg.SecretFileDirs) + if len(dirs) == 0 { + return nil + } + if SecretFileDirsWildcard(dirs) { + return nil + } + var errs []ValidationError + for i, dir := range dirs { + if dir == secretFileDirsWildcard { + errs = append(errs, ValidationError{ + Field: fmt.Sprintf("secret_file_dirs[%d]", i), + Message: `wildcard "*" must be the only entry`, + }) + continue + } + if !filepath.IsAbs(dir) { + errs = append(errs, ValidationError{ + Field: fmt.Sprintf("secret_file_dirs[%d]", i), + Message: "each entry must be an absolute directory path", + }) + } + } + return errs +} + +// WarnMissingSecretFileDirRoots logs a warning for each configured root that +// does not exist yet. Missing defaults are expected on non-container hosts. +func WarnMissingSecretFileDirRoots(cfg *Config) []string { + if cfg == nil || cfg.SecretFileDirs == nil { + return nil + } + if SecretFileDirsWildcard([]string(*cfg.SecretFileDirs)) { + return nil + } + var missing []string + for _, root := range []string(*cfg.SecretFileDirs) { + if _, err := os.Stat(root); err != nil { + if os.IsNotExist(err) { + missing = append(missing, root) + } + } + } + return missing +} + +// ResolveConfigPath returns the effective on-disk config path. +func ResolveConfigPath(cfg *Config, configPath string) string { + if configPath != "" { + return configPath + } + if cfg == nil || cfg.DataDir == "" { + return "" + } + return filepath.Join(cfg.DataDir, ConfigFileName) +} + +// validateAdminAPIKeyFilePath refuses MCPPROXY_API_KEY_FILE paths that point at +// the active config file or at anything in the data directory except +// /secrets. +func validateAdminAPIKeyFilePath(cfg *Config, configPath, filePath string) error { + if filePath == "" { + return nil + } + resolved := resolvePathForPolicy(filePath) + cfgPath := ResolveConfigPath(cfg, configPath) + if cfgPath != "" { + if pathsEqual(resolved, resolvePathForPolicy(cfgPath)) { + return ErrAdminAPIKeyFilePath + } + } + if cfg != nil && cfg.DataDir != "" && !strings.Contains(cfg.DataDir, "${") { + secretsDir := filepath.Join(cfg.DataDir, "secrets") + if contained, _ := pathContainedInDir(secretsDir, resolved); contained { + return nil + } + if contained, _ := pathContainedInDir(cfg.DataDir, resolved); contained { + return ErrAdminAPIKeyFilePath + } + } + return nil +} + +// resolvePathForPolicy canonicalizes a path for policy comparisons. On Windows +// EvalSymlinks aligns long and 8.3 spellings so containment checks match. +func resolvePathForPolicy(path string) string { + if path == "" { + return "" + } + resolved, err := filepath.EvalSymlinks(path) + if err != nil { + return filepath.Clean(path) + } + return filepath.Clean(resolved) +} + +func pathsEqual(a, b string) bool { + if runtime.GOOS == "windows" { + return strings.EqualFold(filepath.Clean(a), filepath.Clean(b)) + } + return filepath.Clean(a) == filepath.Clean(b) +} + +func pathContainedInDir(dir, file string) (bool, error) { + dir = resolvePathForPolicy(dir) + file = resolvePathForPolicy(file) + rel, err := filepath.Rel(dir, file) + if err != nil { + return false, err + } + if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return false, nil + } + return true, nil +} diff --git a/internal/config/secret_file_dirs_policy_test.go b/internal/config/secret_file_dirs_policy_test.go new file mode 100644 index 000000000..407bbfdf3 --- /dev/null +++ b/internal/config/secret_file_dirs_policy_test.go @@ -0,0 +1,138 @@ +package config + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestPersistableConfig_SecretFileDirsRestoredFromDisk(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, ConfigFileName) + onDisk := &Config{DataDir: dir, Listen: "127.0.0.1:8080"} + wildcard := SecretFileDirs{"*"} + onDisk.SecretFileDirs = &wildcard + require.NoError(t, SaveConfig(onDisk, path)) + + effective := &Config{DataDir: dir, Listen: "127.0.0.1:8080"} + other := SecretFileDirs{"/tmp/nope"} + effective.SecretFileDirs = &other + effective.ToolsLimit = 9 + + persisted := PersistableConfig(effective, path) + assert.Equal(t, 9, persisted.ToolsLimit) + assert.True(t, SecretFileDirsWildcard([]string(*persisted.SecretFileDirs))) +} + +func TestSecretFileDirsChanged_detectsManagementEdit(t *testing.T) { + base := &Config{} + a := SecretFileDirs{"/run/secrets"} + b := SecretFileDirs{"*"} + base.SecretFileDirs = &a + edited := &Config{} + edited.SecretFileDirs = &b + assert.True(t, SecretFileDirsChanged(base, edited)) +} + +func TestSecretFileDirsManagementEditRefused(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, ConfigFileName) + base := &Config{DataDir: dir, Listen: ":8080"} + w := SecretFileDirs{"/run/secrets"} + base.SecretFileDirs = &w + require.NoError(t, SaveConfig(base, path)) + + wild := SecretFileDirs{"*"} + incoming := &Config{DataDir: dir, Listen: ":8080", SecretFileDirs: &wild} + assert.True(t, SecretFileDirsManagementEditRefused(path, incoming)) + + same := &Config{DataDir: dir, Listen: ":8080", SecretFileDirs: &w, ToolsLimit: 2} + assert.False(t, SecretFileDirsManagementEditRefused(path, same)) +} + +// Review #6 (PR #1884): an on-disk config that cannot be decoded must not +// let a management edit through; there is nothing to compare it with. +func TestSecretFileDirsManagementEditRefused_UndecodableFileFailsClosed(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, ConfigFileName) + require.NoError(t, os.WriteFile(path, []byte("{not json"), 0o600)) + + wild := SecretFileDirs{"*"} + incoming := &Config{DataDir: dir, Listen: ":8080", SecretFileDirs: &wild} + assert.True(t, SecretFileDirsManagementEditRefused(path, incoming)) + + // Even an incoming config that leaves the key unset is refused: the file's + // setting is unknown, so no edit can be shown not to change it. + assert.True(t, SecretFileDirsManagementEditRefused(path, &Config{DataDir: dir, Listen: ":8080"})) +} + +// A config file that does not exist yet holds no secret_file_dirs: an edit +// that sets one is refused, an edit that leaves it unset is not. +func TestSecretFileDirsManagementEditRefused_MissingFileComparesWithUnset(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, ConfigFileName) + + wild := SecretFileDirs{"*"} + assert.True(t, SecretFileDirsManagementEditRefused(path, &Config{DataDir: dir, SecretFileDirs: &wild})) + assert.False(t, SecretFileDirsManagementEditRefused(path, &Config{DataDir: dir})) +} + +// Cross-review R1 (PR #1884): the guard can decode the file and the save can +// then fail to (the file changed in between). The save must not fall back to +// the in-memory secret_file_dirs, which may carry an edit. +func TestSaveConfig_UndecodableFileRefusesSecretFileDirs(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, ConfigFileName) + garbage := []byte("{not json") + require.NoError(t, os.WriteFile(path, garbage, 0o600)) + + wild := SecretFileDirs{"*"} + err := SaveConfig(&Config{DataDir: dir, Listen: ":8080", SecretFileDirs: &wild}, path) + require.ErrorIs(t, err, ErrSecretFileDirsUnverified) + got, rerr := os.ReadFile(path) + require.NoError(t, rerr) + assert.Equal(t, garbage, got, "nothing written") + + // A config that leaves secret_file_dirs unset still saves (it writes the + // restrictive default, never a wider list). + require.NoError(t, SaveConfig(&Config{DataDir: dir, Listen: ":8080"}, path)) + + // A missing file is created as before. + other := filepath.Join(dir, "new.json") + require.NoError(t, SaveConfig(&Config{DataDir: dir, Listen: ":8080", SecretFileDirs: &wild}, other)) +} + +func TestApplyPatchMap_RejectsSecretFileDirs(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, ConfigFileName) + base := &Config{DataDir: dir, Listen: ":8080"} + w := SecretFileDirs{"/run/secrets"} + base.SecretFileDirs = &w + require.NoError(t, SaveConfig(base, path)) + + onDisk, err := DecodeConfigFile(path) + require.NoError(t, err) + + patch := map[string]interface{}{"secret_file_dirs": []interface{}{"*"}} + raw, err := json.Marshal(onDisk) + require.NoError(t, err) + var baseMap map[string]interface{} + require.NoError(t, json.Unmarshal(raw, &baseMap)) + deepMergeJSONMap(baseMap, patch) + mergedBytes, err := json.Marshal(baseMap) + require.NoError(t, err) + var merged Config + require.NoError(t, json.Unmarshal(mergedBytes, &merged)) + assert.True(t, SecretFileDirsChanged(onDisk, &merged)) +} + +// deepMergeJSONMap is the test-local merge helper (same semantics as httpapi deepMergeJSON). +func deepMergeJSONMap(base, patch map[string]interface{}) { + for k, v := range patch { + base[k] = v + } +} diff --git a/internal/config/secret_file_dirs_test.go b/internal/config/secret_file_dirs_test.go new file mode 100644 index 000000000..a503ff527 --- /dev/null +++ b/internal/config/secret_file_dirs_test.go @@ -0,0 +1,101 @@ +package config + +import ( + "os" + "path/filepath" + "runtime" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestDefaultSecretFileDirRootsForGOOS(t *testing.T) { + linux := DefaultSecretFileDirRootsForGOOS("linux") + assert.Contains(t, linux, "/run/secrets") + assert.NotContains(t, DefaultSecretFileDirRootsForGOOS("darwin"), "/run/secrets") + assert.Empty(t, DefaultSecretFileDirRootsForGOOS("windows")) +} + +func TestEffectiveSecretFileDirRootsForGOOS_DarwinAndWindowsDataDirOnly(t *testing.T) { + dataDir := filepath.Join(t.TempDir(), "data") + cfg := &Config{DataDir: dataDir} + want := filepath.Join(dataDir, "secrets") + for _, goos := range []string{"darwin", "windows"} { + t.Run(goos, func(t *testing.T) { + _, roots, disabled := EffectiveSecretFileDirRootsForGOOS(cfg, true, goos) + assert.False(t, disabled) + require.Len(t, roots, 1) + assert.Equal(t, want, roots[0]) + for _, stock := range []string{"/run/secrets", "/run/credentials"} { + assert.NotContains(t, roots, stock) + } + }) + } +} + +func TestEffectiveSecretFileDirRoots(t *testing.T) { + t.Run("absent uses defaults on linux", func(t *testing.T) { + if runtime.GOOS != "linux" { + t.Skip("linux-only defaults") + } + _, roots, disabled := EffectiveSecretFileDirRoots(&Config{}, true) + assert.False(t, disabled) + assert.Contains(t, roots, "/run/secrets") + }) + + t.Run("empty disables", func(t *testing.T) { + empty := SecretFileDirs{} + _, _, disabled := EffectiveSecretFileDirRoots(&Config{SecretFileDirs: &empty}, true) + assert.True(t, disabled) + }) + + t.Run("wildcard", func(t *testing.T) { + w := SecretFileDirs{"*"} + wildcard, _, disabled := EffectiveSecretFileDirRoots(&Config{SecretFileDirs: &w}, true) + assert.True(t, wildcard) + assert.False(t, disabled) + }) + + t.Run("credentials directory env", func(t *testing.T) { + dir := t.TempDir() + t.Setenv(envCredentialsDir, dir) + _, roots, _ := EffectiveSecretFileDirRoots(&Config{}, false) + assert.Contains(t, roots, dir) + }) +} + +func TestValidateSecretFileDirs(t *testing.T) { + rel := SecretFileDirs{"./secrets"} + errs := validateSecretFileDirs(&Config{SecretFileDirs: &rel}) + require.Len(t, errs, 1) + + mixed := SecretFileDirs{"/run/secrets", "*"} + errs = validateSecretFileDirs(&Config{SecretFileDirs: &mixed}) + require.NotEmpty(t, errs) +} + +func TestValidateAdminAPIKeyFilePath(t *testing.T) { + data := t.TempDir() + cfgPath := filepath.Join(data, ConfigFileName) + require.NoError(t, os.WriteFile(cfgPath, []byte(`{}`), 0o600)) + cfg := &Config{DataDir: data} + + require.Error(t, validateAdminAPIKeyFilePath(cfg, cfgPath, cfgPath)) + assert.ErrorIs(t, validateAdminAPIKeyFilePath(cfg, cfgPath, cfgPath), ErrAdminAPIKeyFilePath) + + db := filepath.Join(data, "config.db") + require.NoError(t, os.WriteFile(db, []byte("x"), 0o600)) + assert.ErrorIs(t, validateAdminAPIKeyFilePath(cfg, cfgPath, db), ErrAdminAPIKeyFilePath) + + secrets := filepath.Join(data, "secrets") + require.NoError(t, os.MkdirAll(secrets, 0o700)) + key := filepath.Join(secrets, "api_key") + require.NoError(t, validateAdminAPIKeyFilePath(cfg, cfgPath, key)) +} + +func TestSecretFileDirsNullRejected(t *testing.T) { + var s SecretFileDirs + err := s.UnmarshalJSON([]byte("null")) + require.Error(t, err) +} diff --git a/internal/config/secret_file_dirs_upgrade.go b/internal/config/secret_file_dirs_upgrade.go new file mode 100644 index 000000000..b8c6939ee --- /dev/null +++ b/internal/config/secret_file_dirs_upgrade.go @@ -0,0 +1,57 @@ +package config + +import ( + "sort" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" +) + +// MsgUpstreamFileRefsOutsideAllowList is the startup warning for upstream +// ${file:} references that secret_file_dirs no longer lets through. Before +// #1721 any absolute path resolved, so these servers stop resolving on +// upgrade; the warning names them so the fix is one step. +const MsgUpstreamFileRefsOutsideAllowList = "upstream ${file:} references are outside secret_file_dirs and will not resolve; " + + "add their directories to secret_file_dirs in the config file, or move the files under /secrets" + +// UpstreamFileRefsOutsideAllowList returns the names of the upstream servers +// with at least one ${file:} reference that the effective secret_file_dirs +// refuses by path. Only paths are checked: no secret file is opened and no +// other reference (env, keyring) is resolved. Wildcard mode reports nothing. +func UpstreamFileRefsOutsideAllowList(cfg *Config) []string { + if cfg == nil || len(cfg.Servers) == 0 { + return nil + } + wildcard, roots, disabled := EffectiveSecretFileDirRoots(cfg, true) + if wildcard { + return nil + } + policy := &secret.FilePolicy{Scope: secret.ScopeUpstream, Disabled: disabled} + if !disabled { + policy.AllowedRoots = append([]string(nil), roots...) + } + + var names []string + for _, sc := range cfg.Servers { + if sc == nil { + continue + } + if serverHasFileRefOutside(sc, policy) { + names = append(names, sc.Name) + } + } + sort.Strings(names) + return names +} + +// serverHasFileRefOutside checks the ${file:} references in exactly the +// fields the upstream resolver expands (secret.StructFileRefPaths walks what +// ExpandStructSecretsCollectErrors walks), so an opaque block it never reads +// does not produce a warning. +func serverHasFileRefOutside(sc *ServerConfig, policy *secret.FilePolicy) bool { + for _, path := range secret.StructFileRefPaths(CopyServerConfig(sc)) { + if !policy.PathWithinAllowList(path) { + return true + } + } + return false +} diff --git a/internal/config/secret_file_dirs_upgrade_test.go b/internal/config/secret_file_dirs_upgrade_test.go new file mode 100644 index 000000000..bd15d6326 --- /dev/null +++ b/internal/config/secret_file_dirs_upgrade_test.go @@ -0,0 +1,65 @@ +package config + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Review #1 (PR #1884): references that resolved before #1721 (any absolute +// path) and fall outside the allow-list now are named at startup. +func TestUpstreamFileRefsOutsideAllowList(t *testing.T) { + dir := t.TempDir() + allowed := filepath.Join(dir, "allowed") + outside := filepath.Join(dir, "outside") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + require.NoError(t, os.MkdirAll(outside, 0o700)) + inside := filepath.Join(allowed, "tok") + require.NoError(t, os.WriteFile(inside, []byte("v"), 0o600)) + + dirs := SecretFileDirs{allowed} + cfg := &Config{DataDir: filepath.Join(dir, "data"), SecretFileDirs: &dirs, Servers: []*ServerConfig{ + {Name: "ok", Env: map[string]string{"T": "${file:" + inside + "}"}}, + {Name: "env-outside", Env: map[string]string{"T": "${file:" + filepath.Join(outside, "tok") + "}"}}, + {Name: "header-outside", URL: "http://127.0.0.1:9/mcp", Headers: map[string]string{"Authorization": "Bearer ${file:" + filepath.Join(outside, "h") + "}"}}, + {Name: "args-outside", Args: []string{"--token", "${file:" + filepath.Join(outside, "a") + "}"}}, + {Name: "no-file-refs", Env: map[string]string{"T": "${env:HOME}", "K": "${keyring:x}"}}, + }} + + assert.Equal(t, []string{"args-outside", "env-outside", "header-outside"}, UpstreamFileRefsOutsideAllowList(cfg)) + + // Wildcard mode lets every path through: nothing to warn about. + wild := SecretFileDirs{"*"} + cfg.SecretFileDirs = &wild + assert.Empty(t, UpstreamFileRefsOutsideAllowList(cfg)) + + // [] disables ${file:}: every server with a file reference is named. + none := SecretFileDirs{} + cfg.SecretFileDirs = &none + assert.Equal(t, []string{"args-outside", "env-outside", "header-outside", "ok"}, UpstreamFileRefsOutsideAllowList(cfg)) +} + +// Cross-review R1 (PR #1884): only the fields the upstream resolver expands +// count. A ${file:} inside an opaque block it never walks (auth_broker in the +// personal build) must not warn on every start. +func TestUpstreamFileRefsOutsideAllowList_OnlyResolvedFields(t *testing.T) { + dir := t.TempDir() + allowed := filepath.Join(dir, "allowed") + dirs := SecretFileDirs{allowed} + + var sc ServerConfig + require.NoError(t, json.Unmarshal([]byte(`{"name":"broker","url":"http://127.0.0.1:9/mcp", + "auth_broker":{"mode":"oauth_connect","client_secret":"${file:/outside/secret}"}}`), &sc)) + cfg := &Config{DataDir: filepath.Join(dir, "data"), SecretFileDirs: &dirs, Servers: []*ServerConfig{&sc}} + + want := []string(nil) + if refs := secret.StructFileRefPaths(CopyServerConfig(&sc)); len(refs) > 0 { + want = []string{"broker"} // server build: auth_broker is a typed struct the resolver walks + } + assert.Equal(t, want, UpstreamFileRefsOutsideAllowList(cfg)) +} diff --git a/internal/config/secret_hardlink_save_unix_test.go b/internal/config/secret_hardlink_save_unix_test.go new file mode 100644 index 000000000..cf36a8767 --- /dev/null +++ b/internal/config/secret_hardlink_save_unix_test.go @@ -0,0 +1,42 @@ +//go:build unix + +package config + +import ( + "context" + "os" + "path/filepath" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" + "github.com/stretchr/testify/require" +) + +// Review #2 (PR #1884): a hardlink to mcp_config.json made before a save +// keeps the old inode, which still holds api_key, after SaveConfig renames a +// new file over the config. An upstream ${file:} read through that link must +// be refused. +func TestSaveConfig_HardlinkMadeBeforeSaveIsRefused(t *testing.T) { + dir := t.TempDir() + allowed := filepath.Join(dir, "allowed") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + cfgPath := filepath.Join(dir, ConfigFileName) + + dirs := SecretFileDirs{allowed} + cfg := DefaultConfig() + cfg.DataDir = dir + cfg.APIKey = "admin-key-before-save" + cfg.SecretFileDirs = &dirs + require.NoError(t, SaveConfig(cfg, cfgPath)) + + link := filepath.Join(allowed, "token") + require.NoError(t, os.Link(cfgPath, link)) + + cfg.APIKey = "admin-key-after-save" + require.NoError(t, SaveConfig(cfg, cfgPath)) + + r := BuildSecretResolver(cfg, cfgPath, secret.ScopeUpstream) + _, err := r.ExpandSecretRefs(context.Background(), "${file:"+link+"}") + require.Error(t, err) + require.True(t, secret.IsPolicyDenial(err), "want a policy denial, got %v", err) +} diff --git a/internal/config/secret_resolver.go b/internal/config/secret_resolver.go new file mode 100644 index 000000000..a2452ce48 --- /dev/null +++ b/internal/config/secret_resolver.go @@ -0,0 +1,93 @@ +package config + +import ( + "os" + "path/filepath" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" +) + +// NewResolverForConfig is an alias for BuildSecretResolver. +func NewResolverForConfig(cfg *Config, configPath string, scope secret.ResolveScope) *secret.Resolver { + return BuildSecretResolver(cfg, configPath, scope) +} + +// BuildSecretResolver constructs a secret resolver for the loaded configuration. +func BuildSecretResolver(cfg *Config, configPath string, scope secret.ResolveScope) *secret.Resolver { + wildcard, roots, disabled := EffectiveSecretFileDirRoots(cfg, true) + + policy := &secret.FilePolicy{Scope: scope} + if disabled { + policy.Disabled = true + } else if wildcard { + policy.Wildcard = true + } else { + policy.AllowedRoots = append([]string(nil), roots...) + } + + if scope == secret.ScopeUpstream { + cfgPath := ResolveConfigPath(cfg, configPath) + policy.Deny = secret.DenyPaths{ + ConfigFile: cfgPath, + DataDir: cfg.DataDir, + DataSecretsDir: filepath.Join(cfg.DataDir, "secrets"), + AdminKeyPaths: adminKeySourcePaths(cfg), + } + } + + return secret.NewResolverWithOptions(secret.ResolverOptions{ + Scope: scope, + FilePolicy: policy, + }) +} + +func adminKeySourcePaths(cfg *Config) []string { + var paths []string + if path := os.Getenv(EnvAPIKeyFile); path != "" { + paths = append(paths, path) + } + if cfg != nil && secret.IsSecretRef(cfg.APIKey) { + if ref, err := secret.ParseSecretRef(cfg.APIKey); err == nil && ref.Type == secret.SecretTypeFile { + paths = append(paths, ref.Name) + } + } + return paths +} + +// BuildSecretResolverForKeyringCLI is proxy-scoped with ${file:} disabled. +// CLI `secrets` keyring store/get/delete/list and upstream --secret-* flags only +// touch keyring (and optional operator env names), not server-entry file refs. +func BuildSecretResolverForKeyringCLI() *secret.Resolver { + return secret.NewResolverWithOptions(secret.ResolverOptions{ + Scope: secret.ScopeProxy, + FilePolicy: secret.NewDisabledFilePolicy(secret.ScopeProxy), + }) +} + +// ConfigFilePathForPolicy returns the path used for deny-list policy (load path +// when set, otherwise the default under data_dir). +func (c *Config) ConfigFilePathForPolicy() string { + if c != nil && c.loadConfigPath != "" { + return c.loadConfigPath + } + return ResolveConfigPath(c, "") +} + +// BuildSecretResolverForDataDirExpand builds a proxy-scoped resolver used only +// while resolving data_dir: allow-list entries are independent of data_dir, so +// a ${file:} data_dir cannot include its own derived secrets directory. +func BuildSecretResolverForDataDirExpand(cfg *Config) *secret.Resolver { + wildcard, roots, disabled := EffectiveSecretFileDirRoots(cfg, false) + policy := &secret.FilePolicy{Scope: secret.ScopeProxy} + if disabled { + policy.Disabled = true + } else if wildcard { + policy.Wildcard = true + } else { + policy.AllowedRoots = append([]string(nil), roots...) + } + return secret.NewResolverWithOptions(secret.ResolverOptions{ + Scope: secret.ScopeProxy, + FilePolicy: policy, + }) +} diff --git a/internal/config/server_edition_config.go b/internal/config/server_edition_config.go index 606e0fcdb..2b9dc3a85 100644 --- a/internal/config/server_edition_config.go +++ b/internal/config/server_edition_config.go @@ -285,11 +285,17 @@ func ValidatePublicURL(raw string) error { // private, never-persisted config clone to get the actual value for the // token endpoint. An empty input resolves to "" with no error (client_id and // client_secret share the same "is required" check for the empty case). -func resolveOAuthSecretRef(raw string) (string, error) { +// ResolveOAuthSecretRef resolves proxy-own OAuth fields with a proxy-scoped +// resolver (MCPPROXY_* env names are allowed). +func ResolveOAuthSecretRef(raw string) (string, error) { if raw == "" { return "", nil } - return secret.NewResolver().ExpandSecretRefs(context.Background(), raw) + r := secret.NewResolverWithOptions(secret.ResolverOptions{ + Scope: secret.ScopeProxy, + FilePolicy: secret.NewWildcardFilePolicy(secret.ScopeProxy), + }) + return r.ExpandSecretRefs(context.Background(), raw) } // PublicURLIsHTTPS reports whether the configured public_url uses https. @@ -445,10 +451,10 @@ func (c *ServerEditionConfig) Validate() error { // runtime resolution now happens once, at the one place that needs the // live secret for the token endpoint: auth.NewOAuthHandler, on its own // private, never-persisted config clone. - if _, err := resolveOAuthSecretRef(c.OAuth.ClientID); err != nil || c.OAuth.ClientID == "" { + if _, err := ResolveOAuthSecretRef(c.OAuth.ClientID); err != nil || c.OAuth.ClientID == "" { return fmt.Errorf("server_edition.oauth.client_id is required") } - if _, err := resolveOAuthSecretRef(c.OAuth.ClientSecret); err != nil || c.OAuth.ClientSecret == "" { + if _, err := ResolveOAuthSecretRef(c.OAuth.ClientSecret); err != nil || c.OAuth.ClientSecret == "" { return fmt.Errorf("server_edition.oauth.client_secret is required") } if err := c.OAuth.validateOIDC(); err != nil { diff --git a/internal/config/server_secret_policy.go b/internal/config/server_secret_policy.go new file mode 100644 index 000000000..647dd2a46 --- /dev/null +++ b/internal/config/server_secret_policy.go @@ -0,0 +1,47 @@ +package config + +import ( + "context" + "errors" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" +) + +// ServerSecretPolicyErrors reports upstream secret-policy failures suitable for +// write-time rejection. Messages use only the fixed public denial strings. +func ServerSecretPolicyErrors(cfg *Config, configPath string, sc *ServerConfig) []ValidationError { + if sc == nil { + return nil + } + r := BuildSecretResolver(cfg, ConfigFilePathForPolicyFrom(cfg, configPath), secret.ScopeUpstream) + cp := CopyServerConfig(sc) + errs := r.ExpandStructSecretsCollectErrors(context.Background(), cp) + if len(errs) == 0 { + return nil + } + var out []ValidationError + for _, e := range errs { + if !secret.IsPolicyDenial(e.Err) { + continue + } + out = append(out, ValidationError{ + Field: e.FieldPath, + Message: secret.PublicPolicyMessage(e.Err), + }) + } + return out +} + +// ConfigFilePathForPolicyFrom returns the config path used for policy deny lists. +func ConfigFilePathForPolicyFrom(cfg *Config, configPath string) string { + if configPath != "" { + return configPath + } + if cfg != nil { + return cfg.ConfigFilePathForPolicy() + } + return "" +} + +// ErrServerSecretPolicy is returned when a server entry violates secret policy. +var ErrServerSecretPolicy = errors.New("server secret reference refused by policy") diff --git a/internal/config/server_secret_policy_test.go b/internal/config/server_secret_policy_test.go new file mode 100644 index 000000000..1fb77af25 --- /dev/null +++ b/internal/config/server_secret_policy_test.go @@ -0,0 +1,59 @@ +package config + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestServerSecretPolicyErrors_RefusesReservedEnv(t *testing.T) { + dir := t.TempDir() + allowed := SecretFileDirs{filepath.Join(dir, "secrets")} + require.NoError(t, os.MkdirAll(string(allowed[0]), 0o700)) + cfg := &Config{DataDir: dir, Listen: "127.0.0.1:0", SecretFileDirs: &allowed} + sc := &ServerConfig{ + Name: "s", + URL: "http://127.0.0.1:9/mcp", + Env: map[string]string{"K": "${env:MCPPROXY_API_KEY}"}, + } + errs := ServerSecretPolicyErrors(cfg, filepath.Join(dir, ConfigFileName), sc) + require.NotEmpty(t, errs) + assert.Equal(t, secret.ErrReservedEnvVar.Error(), errs[0].Message) + assert.NotContains(t, errs[0].Message, "/") +} + +func TestLoad_APIKeyFileRefOutsideAllowListFailsLoad(t *testing.T) { + t.Cleanup(ResetProcessOverrides) + ResetProcessOverrides() + dir := t.TempDir() + allowed := filepath.Join(dir, "allowed") + outside := filepath.Join(dir, "outside") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + require.NoError(t, os.MkdirAll(outside, 0o700)) + key := filepath.Join(outside, "key") + require.NoError(t, os.WriteFile(key, []byte("secret\n"), 0o600)) + raw, err := jsonMarshalConfig(t, map[string]any{ + "listen": "127.0.0.1:8080", + "data_dir": dir, + "secret_file_dirs": []string{allowed}, + "api_key": "${file:" + key + "}", + }) + require.NoError(t, err) + path := filepath.Join(dir, ConfigFileName) + require.NoError(t, os.WriteFile(path, raw, 0o600)) + unsetEnv(t, EnvAPIKey) + t.Setenv(EnvAPIKeyFile, "") + _, err = LoadFromFile(path) + require.Error(t, err) + assert.Contains(t, err.Error(), "api_key") +} + +func jsonMarshalConfig(t *testing.T, m map[string]any) ([]byte, error) { + t.Helper() + return json.Marshal(m) +} diff --git a/internal/config/superseded_config.go b/internal/config/superseded_config.go new file mode 100644 index 000000000..9be3166c3 --- /dev/null +++ b/internal/config/superseded_config.go @@ -0,0 +1,22 @@ +package config + +import ( + "path/filepath" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" +) + +// MsgSupersededConfigNotRecorded is the warning when the identity of the +// config file about to be replaced cannot be read: a hardlink made to it +// earlier will not be refused by upstream ${file:} reads. +const MsgSupersededConfigNotRecorded = "could not record the identity of the config file being replaced; " + + "a hardlink made to it earlier is not refused by upstream ${file:} reads" + +// noteSupersededConfig records the config file's current identity before a +// rename replaces it (secret.NoteSupersededProxyFile) and warns, naming the +// file only, when that fails. +func noteSupersededConfig(path string) { + if err := secret.NoteSupersededProxyFile(path); err != nil { + emitLoadWarning(MsgSupersededConfigNotRecorded, "config_file", filepath.Base(path)) + } +} diff --git a/internal/config/superseded_config_test.go b/internal/config/superseded_config_test.go new file mode 100644 index 000000000..f283919ef --- /dev/null +++ b/internal/config/superseded_config_test.go @@ -0,0 +1,30 @@ +package config + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Cross-review R2 (PR #1884): when the identity of the config being replaced +// cannot be captured, the save warns (file name only) instead of going quiet. +func TestNoteSupersededConfig_WarnsOnCaptureFailure(t *testing.T) { + type warning struct{ msg, key, value string } + var got []warning + SetLoadWarningRecorder(func(m, k, v string) { got = append(got, warning{m, k, v}) }) + t.Cleanup(func() { SetLoadWarningRecorder(nil) }) + + dir := t.TempDir() + noteSupersededConfig(filepath.Join(dir, "missing.json")) // first save: silent + assert.Empty(t, got) + + blocked := filepath.Join(dir, "cfg-dir") + require.NoError(t, os.Mkdir(blocked, 0o700)) // no file identity to capture + noteSupersededConfig(blocked) + require.Len(t, got, 1) + assert.Equal(t, MsgSupersededConfigNotRecorded, got[0].msg) + assert.Equal(t, "cfg-dir", got[0].value, "file name only, never the full path or contents") +} diff --git a/internal/health/upstream_secret_policy_test.go b/internal/health/upstream_secret_policy_test.go new file mode 100644 index 000000000..f1504f5f2 --- /dev/null +++ b/internal/health/upstream_secret_policy_test.go @@ -0,0 +1,54 @@ +package health + +import ( + "os" + "path/filepath" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/upstream/core" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" +) + +func upstreamPolicyConnectError(t *testing.T) (lastError string, public string, leaks []string) { + t.Helper() + dir := t.TempDir() + allowed := filepath.Join(dir, "allowed") + outside := filepath.Join(dir, "outside", "deep", "token.pem") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + require.NoError(t, os.MkdirAll(filepath.Dir(outside), 0o700)) + require.NoError(t, os.WriteFile(outside, []byte("x\n"), 0o600)) + w := config.SecretFileDirs{allowed} + cfg := &config.Config{DataDir: dir, SecretFileDirs: &w} + r := config.BuildSecretResolver(cfg, "", secret.ScopeUpstream) + srv := &config.ServerConfig{ + Name: "denied", + Command: "true", + Env: map[string]string{"TOKEN": "${file:" + outside + "}"}, + } + _, err := core.NewClientWithOptions("denied", srv, zap.NewNop(), nil, cfg, nil, false, r) + require.Error(t, err) + var pe *core.UpstreamSecretPolicyError + require.ErrorAs(t, err, &pe) + return err.Error(), pe.Public, []string{outside, "${file:", "TOKEN"} +} + +func TestCalculateHealth_UpstreamSecretPolicyDenialPublicOnly(t *testing.T) { + lastError, public, leaks := upstreamPolicyConnectError(t) + got := CalculateHealth(HealthCalculatorInput{ + Name: "denied", + Enabled: true, + State: "error", + Connected: false, + LastError: lastError, + }, nil) + assert.Contains(t, got.Detail, public) + for _, leak := range leaks { + assert.NotContains(t, got.Detail, leak) + assert.NotContains(t, lastError, leak) + } + assert.Equal(t, secret.ErrSecretFileDenied.Error(), public) +} diff --git a/internal/httpapi/config_secret_file_dirs_test.go b/internal/httpapi/config_secret_file_dirs_test.go new file mode 100644 index 000000000..948d3e81a --- /dev/null +++ b/internal/httpapi/config_secret_file_dirs_test.go @@ -0,0 +1,80 @@ +package httpapi + +import ( + "encoding/json" + "net/http" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" +) + +type secretDirsFunnelController struct { + funnelController + cfgPath string +} + +func (c *secretDirsFunnelController) GetConfigPath() string { return c.cfgPath } + +func secretDirsHTTPServer(t *testing.T) (*Server, *secretDirsFunnelController, string) { + t.Helper() + dir := t.TempDir() + path := filepath.Join(dir, config.ConfigFileName) + w := config.SecretFileDirs{"/run/secrets"} + cfg := &config.Config{Listen: "127.0.0.1:8080", DataDir: dir, SecretFileDirs: &w} + require.NoError(t, config.SaveConfig(cfg, path)) + + ctrl := &secretDirsFunnelController{ + funnelController: funnelController{desired: cfg}, + cfgPath: path, + } + return NewServer(ctrl, zap.NewNop().Sugar(), nil), ctrl, path +} + +func TestApplyConfig_RefusesSecretFileDirsChange(t *testing.T) { + srv, ctrl, _ := secretDirsHTTPServer(t) + + w := funnelRequest(t, srv, http.MethodPost, "/api/v1/config/apply", + `{"listen":"127.0.0.1:8080","secret_file_dirs":["*"]}`) + assert.Equal(t, http.StatusBadRequest, w.Code, w.Body.String()) + assert.Contains(t, w.Body.String(), config.ErrSecretFileDirsNotWritable.Error()) + onDiskDirs := config.SecretFileDirs{"/run/secrets"} + assert.True(t, config.SecretFileDirsEqual(ctrl.desired.SecretFileDirs, &onDiskDirs)) +} + +func TestPatchConfig_RefusesSecretFileDirsChange(t *testing.T) { + srv, ctrl, _ := secretDirsHTTPServer(t) + + w := funnelRequest(t, srv, http.MethodPatch, "/api/v1/config", `{"secret_file_dirs":["*"]}`) + assert.Equal(t, http.StatusBadRequest, w.Code, w.Body.String()) + assert.Contains(t, w.Body.String(), config.ErrSecretFileDirsNotWritable.Error()) + onDiskDirs := config.SecretFileDirs{"/run/secrets"} + assert.True(t, config.SecretFileDirsEqual(ctrl.desired.SecretFileDirs, &onDiskDirs)) +} + +func TestPatchConfig_AllowsUnrelatedEdit(t *testing.T) { + srv, ctrl, path := secretDirsHTTPServer(t) + + w := funnelRequest(t, srv, http.MethodPatch, "/api/v1/config", `{"tools_limit":12}`) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + assert.Equal(t, 12, ctrl.desired.ToolsLimit) + + onDisk, err := config.DecodeConfigFile(path) + require.NoError(t, err) + assert.True(t, config.SecretFileDirsEqual(onDisk.SecretFileDirs, ctrl.desired.SecretFileDirs)) +} + +func TestApplyConfig_RoundTripPreservesSecretFileDirsFromDisk(t *testing.T) { + srv, _, path := secretDirsHTTPServer(t) + onDisk, err := config.DecodeConfigFile(path) + require.NoError(t, err) + raw, err := json.Marshal(onDisk) + require.NoError(t, err) + + w := funnelRequest(t, srv, http.MethodPost, "/api/v1/config/apply", string(raw)) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) +} diff --git a/internal/httpapi/get_servers_health_vocabulary_test.go b/internal/httpapi/get_servers_health_vocabulary_test.go index e696f2b84..086a16ba7 100644 --- a/internal/httpapi/get_servers_health_vocabulary_test.go +++ b/internal/httpapi/get_servers_health_vocabulary_test.go @@ -5,6 +5,8 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "os" + "path/filepath" "testing" "github.com/stretchr/testify/assert" @@ -15,6 +17,8 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts" "github.com/smart-mcp-proxy/mcpproxy-go/internal/health" "github.com/smart-mcp-proxy/mcpproxy-go/internal/management" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/upstream/core" ) // internal/server/upstream_servers_health_status_test.go already proves the @@ -161,3 +165,55 @@ func TestHandleGetServers_HealthCarriesMultiActionSlice(t *testing.T) { "the full ordered actions slice must survive the REST handler's JSON round-trip") assert.Equal(t, health.ActionLogin, got.Action) } + +func TestHandleGetServers_HealthSecretPolicyDenialPublicOnly(t *testing.T) { + dir := t.TempDir() + allowed := filepath.Join(dir, "allowed") + outside := filepath.Join(dir, "outside", "deep", "token.pem") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + require.NoError(t, os.MkdirAll(filepath.Dir(outside), 0o700)) + require.NoError(t, os.WriteFile(outside, []byte("x\n"), 0o600)) + secretDirs := config.SecretFileDirs{allowed} + cfg := &config.Config{DataDir: dir, SecretFileDirs: &secretDirs} + r := config.BuildSecretResolver(cfg, "", secret.ScopeUpstream) + srvCfg := &config.ServerConfig{ + Name: "denied", Command: "true", + Env: map[string]string{"TOKEN": "${file:" + outside + "}"}, + } + _, err := core.NewClientWithOptions("denied", srvCfg, zap.NewNop(), nil, cfg, nil, false, r) + require.Error(t, err) + var pe *core.UpstreamSecretPolicyError + require.ErrorAs(t, err, &pe) + + computed := health.CalculateHealth(health.HealthCalculatorInput{ + Name: "denied", Enabled: true, State: "error", Connected: false, LastError: err.Error(), + }, nil) + svc := &restHealthVocabService{server: &contracts.Server{ + ID: "denied", Name: "denied", Protocol: "stdio", Enabled: true, Health: computed, + LastError: err.Error(), + }} + srv := NewServer(&restHealthVocabController{svc: svc}, zap.NewNop().Sugar(), nil) + req := httptest.NewRequest(http.MethodGet, "/api/v1/servers", http.NoBody) + req.Header.Set("X-API-Key", restHealthVocabAPIKey) + w := httptest.NewRecorder() + srv.ServeHTTP(w, req) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + + var resp struct { + Data struct { + Servers []struct { + LastError string `json:"last_error"` + Health contracts.HealthStatus `json:"health"` + } `json:"servers"` + } `json:"data"` + } + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp)) + require.Len(t, resp.Data.Servers, 1) + leaks := []string{outside, "${file:", "TOKEN"} + for _, s := range []string{resp.Data.Servers[0].LastError, resp.Data.Servers[0].Health.Detail} { + assert.Contains(t, s, pe.Public) + for _, leak := range leaks { + assert.NotContains(t, s, leak) + } + } +} diff --git a/internal/httpapi/import_secret_policy_test.go b/internal/httpapi/import_secret_policy_test.go new file mode 100644 index 000000000..e023d8a1d --- /dev/null +++ b/internal/httpapi/import_secret_policy_test.go @@ -0,0 +1,74 @@ +package httpapi + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "sync" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" +) + +type policyImportController struct { + mockImportController + cfg *config.Config + cfgPath string + mu sync.Mutex + added []string +} + +func (m *policyImportController) GetCurrentConfig() *config.Config { return m.cfg } + +func (m *policyImportController) AddServer(_ context.Context, s *config.ServerConfig) error { + if errs := config.ServerSecretPolicyErrors(m.cfg, m.cfgPath, s); len(errs) > 0 { + return &config.InvalidServerUpdateError{Server: s.Name, Errors: errs} + } + m.mu.Lock() + defer m.mu.Unlock() + m.added = append(m.added, s.Name) + return nil +} + +func TestImportServersJSON_RefusesSecretPolicyBeforeSave(t *testing.T) { + dir := t.TempDir() + allowed := config.SecretFileDirs{dir + "/allowed"} + mock := &policyImportController{ + mockImportController: mockImportController{apiKey: "test-key"}, + cfg: &config.Config{ + APIKey: "test-key", + DataDir: dir, + SecretFileDirs: &allowed, + }, + cfgPath: dir + "/mcp_config.json", + } + srv := NewServer(mock, zap.NewNop().Sugar(), nil) + + body, _ := json.Marshal(ImportRequest{ + Content: `{"mcpServers": { + "bad": {"url": "https://example.com/mcp", "env": {"K": "${env:MCPPROXY_API_KEY}"}}, + "good": {"command": "echo", "args": ["ok"]} + }}`, + }) + req := httptest.NewRequest(http.MethodPost, "/api/v1/servers/import/json", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-API-Key", "test-key") + rr := httptest.NewRecorder() + srv.router.ServeHTTP(rr, req) + + require.Equal(t, http.StatusOK, rr.Code, rr.Body.String()) + var wrapped wrappedImportResponse + require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &wrapped)) + require.Len(t, wrapped.Data.Failed, 1) + assert.Equal(t, "bad", wrapped.Data.Failed[0].Name) + assert.Contains(t, wrapped.Data.Failed[0].Details, secret.ErrReservedEnvVar.Error()) + mock.mu.Lock() + assert.Equal(t, []string{"good"}, mock.added) + mock.mu.Unlock() +} diff --git a/internal/httpapi/secret_delete_name_decode_test.go b/internal/httpapi/secret_delete_name_decode_test.go index 2ba85acaf..486a71f8b 100644 --- a/internal/httpapi/secret_delete_name_decode_test.go +++ b/internal/httpapi/secret_delete_name_decode_test.go @@ -34,7 +34,7 @@ func (p *recordingKeyring) IsAvailable() bool { return // keyring delete, otherwise the wrong (nonexistent) entry is targeted. func TestDeleteSecret_DecodesNameParam(t *testing.T) { kr := &recordingKeyring{} - res := secret.NewResolver() + res := secret.NewTestWildcardResolver() res.RegisterProvider(secretTypeKeyring, kr) ctrl := &secretResolverController{MockServerController: &MockServerController{}, resolver: res} srv := NewServer(ctrl, zaptest.NewLogger(t).Sugar(), nil) @@ -64,7 +64,7 @@ func TestDeleteSecret_LiteralPercentNameNotDoubleDecoded(t *testing.T) { for path, want := range cases { t.Run(want, func(t *testing.T) { kr := &recordingKeyring{} - res := secret.NewResolver() + res := secret.NewTestWildcardResolver() res.RegisterProvider(secretTypeKeyring, kr) ctrl := &secretResolverController{MockServerController: &MockServerController{}, resolver: res} srv := NewServer(ctrl, zaptest.NewLogger(t).Sugar(), nil) diff --git a/internal/httpapi/secrets_keyring_available_test.go b/internal/httpapi/secrets_keyring_available_test.go index 36e92ebad..93b81fbb8 100644 --- a/internal/httpapi/secrets_keyring_available_test.go +++ b/internal/httpapi/secrets_keyring_available_test.go @@ -30,7 +30,7 @@ func newSecretResolverTestServer(t *testing.T) *Server { logger := zaptest.NewLogger(t).Sugar() controller := &secretResolverController{ MockServerController: &MockServerController{}, - resolver: secret.NewResolver(), + resolver: secret.NewTestWildcardResolver(), } return NewServer(controller, logger, nil) } diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 51cb48488..f238a968e 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -2733,6 +2733,11 @@ func (s *Server) handleAddServer(w http.ResponseWriter, r *http.Request) { // Add server via controller logger := s.getRequestLogger(r) // T019: Use request-scoped logger if err := s.controller.AddServer(r.Context(), serverConfig); err != nil { + var verr *config.InvalidServerUpdateError + if errors.As(err, &verr) { + s.writeError(w, r, http.StatusBadRequest, joinValidationMessages(verr.Errors)) + return + } // Check if it's a duplicate name error if strings.Contains(err.Error(), "already exists") { s.writeError(w, r, http.StatusConflict, err.Error()) @@ -6136,6 +6141,13 @@ func (s *Server) handleApplyConfig(w http.ResponseWriter, r *http.Request) { if err := refuseLockedTelemetryChange(stored, resolved); err != nil { return err } + cfgPath := s.controller.GetConfigPath() + if cfgPath != "" && config.SecretFileDirsManagementEditRefused(cfgPath, resolved) { + return &configMutationRefusal{ + status: http.StatusBadRequest, + msg: config.ErrSecretFileDirsNotWritable.Error(), + } + } *stored = *resolved return nil }) @@ -6352,6 +6364,12 @@ func (s *Server) mergeConfigPatch(base *config.Config, patchMap map[string]inter if err := json.Unmarshal(mergedBytes, &merged); err != nil { return nil, &configMutationRefusal{status: http.StatusBadRequest, msg: fmt.Sprintf("Invalid configuration patch: %v", err)} } + if config.SecretFileDirsChanged(base, &merged) { + return nil, &configMutationRefusal{ + status: http.StatusBadRequest, + msg: config.ErrSecretFileDirsNotWritable.Error(), + } + } return &merged, nil } diff --git a/internal/management/diagnostics_upstream_secret_policy_harness_test.go b/internal/management/diagnostics_upstream_secret_policy_harness_test.go new file mode 100644 index 000000000..36cf64726 --- /dev/null +++ b/internal/management/diagnostics_upstream_secret_policy_harness_test.go @@ -0,0 +1,36 @@ +package management + +import ( + "os" + "path/filepath" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/upstream/core" + "github.com/stretchr/testify/require" + "go.uber.org/zap" +) + +func upstreamPolicyDoctorInputs(t *testing.T) (lastError, public string, leaks []string) { + t.Helper() + dir := t.TempDir() + allowed := filepath.Join(dir, "allowed") + outside := filepath.Join(dir, "outside", "deep", "token.pem") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + require.NoError(t, os.MkdirAll(filepath.Dir(outside), 0o700)) + require.NoError(t, os.WriteFile(outside, []byte("x\n"), 0o600)) + w := config.SecretFileDirs{allowed} + cfg := &config.Config{DataDir: dir, SecretFileDirs: &w} + r := config.BuildSecretResolver(cfg, "", secret.ScopeUpstream) + srv := &config.ServerConfig{ + Name: "denied", + Command: "true", + Env: map[string]string{"TOKEN": "${file:" + outside + "}"}, + } + _, err := core.NewClientWithOptions("denied", srv, zap.NewNop(), nil, cfg, nil, false, r) + require.Error(t, err) + var pe *core.UpstreamSecretPolicyError + require.ErrorAs(t, err, &pe) + return err.Error(), pe.Public, []string{outside, "${file:", "TOKEN"} +} diff --git a/internal/management/diagnostics_upstream_secret_policy_test.go b/internal/management/diagnostics_upstream_secret_policy_test.go new file mode 100644 index 000000000..883225976 --- /dev/null +++ b/internal/management/diagnostics_upstream_secret_policy_test.go @@ -0,0 +1,43 @@ +package management + +import ( + "context" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/health" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap/zaptest" +) + +func TestDoctor_UpstreamSecretPolicyDenialPublicOnly(t *testing.T) { + logger := zaptest.NewLogger(t).Sugar() + lastError, public, leaks := upstreamPolicyDoctorInputs(t) + + h := health.CalculateHealth(health.HealthCalculatorInput{ + Name: "denied", Enabled: true, State: "error", Connected: false, LastError: lastError, + }, nil) + + runtime := newMockRuntime() + runtime.servers = []map[string]interface{}{ + { + "name": "denied", + "last_error": lastError, + "health": map[string]interface{}{ + "level": h.Level, + "action": h.Action, + "detail": h.Detail, + }, + }, + } + svc := NewService(runtime, &config.Config{}, "", &mockEventEmitter{}, nil, logger) + diag, err := svc.Doctor(context.Background()) + require.NoError(t, err) + require.Len(t, diag.UpstreamErrors, 1) + msg := diag.UpstreamErrors[0].ErrorMessage + assert.Contains(t, msg, public) + for _, leak := range leaks { + assert.NotContains(t, msg, leak) + } +} diff --git a/internal/runtime/commit.go b/internal/runtime/commit.go index c5f5ea6a5..cbf7adfdf 100644 --- a/internal/runtime/commit.go +++ b/internal/runtime/commit.go @@ -194,6 +194,26 @@ func (tx *CommitTx) Base() *config.Config { return tx.base.Config } // it only through the CommitTx operations (or MutateGlobal for global fields). func (tx *CommitTx) Config() *config.Config { return tx.next } +func (tx *CommitTx) commitConfigPath() string { + if tx.path != "" { + return tx.path + } + if tx.r != nil { + return tx.r.cfgPath + } + return "" +} + +func (tx *CommitTx) validateServerSecretPolicy(sc *config.ServerConfig) error { + if sc == nil { + return nil + } + if errs := config.ServerSecretPolicyErrors(tx.next, tx.commitConfigPath(), sc); len(errs) > 0 { + return &config.InvalidServerUpdateError{Server: sc.Name, Errors: errs} + } + return nil +} + func (tx *CommitTx) entry(name string) *config.ServerConfig { for _, sc := range tx.next.Servers { if sc != nil && sc.Name == name { @@ -247,6 +267,9 @@ func (tx *CommitTx) CreateServer(sc *config.ServerConfig) error { return &ServerExistsError{Name: sc.Name} } } + if err := tx.validateServerSecretPolicy(sc); err != nil { + return err + } tx.next.Servers = append(tx.next.Servers, config.CopyServerConfig(sc)) if tx.removed[sc.Name] { delete(tx.removed, sc.Name) @@ -271,6 +294,9 @@ func (tx *CommitTx) UpdateServer(name string, fn func(cur *config.ServerConfig) if cp.Name != name { return fmt.Errorf("%w: UpdateServer cannot rename %q to %q", ErrCommitInvariant, name, cp.Name) } + if err := tx.validateServerSecretPolicy(cp); err != nil { + return err + } if cp.Quarantined && cp.QuarantineExplicitlySet() { if tx.quarantineDecided == nil { tx.quarantineDecided = map[string]bool{} diff --git a/internal/runtime/config_hotreload.go b/internal/runtime/config_hotreload.go index 78f52dc2a..d04eea60e 100644 --- a/internal/runtime/config_hotreload.go +++ b/internal/runtime/config_hotreload.go @@ -189,6 +189,13 @@ func DetectConfigChanges(oldCfg, newCfg *config.Config) *ConfigApplyResult { // Track hot-reloadable changes + // secret_file_dirs (issue #1721 — hot-reloadable). Rebuilds the upstream + // secret resolver when the allow-list changes; an explicit [] disables + // ${file:} without a restart. + if !config.SecretFileDirsEqual(oldCfg.SecretFileDirs, newCfg.SecretFileDirs) { + result.ChangedFields = append(result.ChangedFields, "secret_file_dirs") + } + // Server configuration changes (can be hot-reloaded). // // Compared via jsonEqual, not reflect.DeepEqual, for the same reason as diff --git a/internal/runtime/config_hotreload_test.go b/internal/runtime/config_hotreload_test.go index 45acc8121..68cd5e9bd 100644 --- a/internal/runtime/config_hotreload_test.go +++ b/internal/runtime/config_hotreload_test.go @@ -15,6 +15,19 @@ import ( // the observability usage cadence must be detected as a hot-reloadable change so // ApplyConfig can push the new persist interval to the running ActivityService. // SetUsagePersistInterval advertises hot-reload; the detector must back it. +func TestDetectConfigChanges_SecretFileDirsHotReloadable(t *testing.T) { + a := config.SecretFileDirs{"/run/secrets"} + b := config.SecretFileDirs{"/etc/mcpproxy/secrets"} + old := &config.Config{DataDir: "/d", Listen: ":8080"} + old.SecretFileDirs = &a + changed := &config.Config{DataDir: "/d", Listen: ":8080"} + changed.SecretFileDirs = &b + result := DetectConfigChanges(old, changed) + require.True(t, result.Success) + assert.Contains(t, result.ChangedFields, "secret_file_dirs") + assert.False(t, result.RequiresRestart) +} + func TestDetectConfigChanges_Observability(t *testing.T) { base := &config.Config{ Listen: "127.0.0.1:8080", DataDir: "/d", TLS: &config.TLSConfig{}, diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index 297ea6d31..cf7c7fd12 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -191,8 +191,8 @@ type Runtime struct { // swap/read race-free (#861) and independent of r.mu, so the accessor stays // lock-free on the hot path and composes with the config commit serialization. truncator atomic.Pointer[truncate.Truncator] - sigCache *toolsig.Cache // Spec 085 FR-008: single process-wide signature cache (indexing warms, MCP reads) - secretResolver *secret.Resolver + sigCache *toolsig.Cache // Spec 085 FR-008: single process-wide signature cache (indexing warms, MCP reads) + secretResolver atomic.Pointer[secret.Resolver] // swapped on secret_file_dirs hot reload tokenizer tokens.Tokenizer // tokenSavingsCache holds the last tokenized savings estimate and @@ -493,6 +493,14 @@ func New(cfg *config.Config, cfgPath string, logger *zap.Logger) (*Runtime, erro return nil, fmt.Errorf("config cannot be nil") } + config.SetLoadWarningRecorder(func(message, key, value string) { + logger.Warn(message, zap.String("key", key), zap.String("value", value)) + }) + for _, w := range config.DrainLoadWarnings() { + logger.Warn(w.Message, zap.String("key", w.Key), zap.String("value", w.Value)) + } + warnUpstreamFileRefsOutsideAllowList(logger, cfg) + // Spec 123 FR-020/FR-022: resolve the OAuth token key once, before // config.db is opened. An unresolvable or malformed key stops here with a // *config.StartupError (exit 4) and no byte of the database written. @@ -572,8 +580,8 @@ func New(cfg *config.Config, cfgPath string, logger *zap.Logger) (*Runtime, erro return nil, fmt.Errorf("failed to initialize index manager: %w", err) } - // Initialize secret resolver - secretResolver := secret.NewResolver() + // Initialize secret resolver (upstream scope: server entries + guards). + secretResolver := config.BuildSecretResolver(cfg, cfgPath, secret.ScopeUpstream) if hook := runtimeNewStageHook; hook != nil { hook(runtimeStageUpstreamManager, storageManager) @@ -722,7 +730,6 @@ func New(cfg *config.Config, cfgPath string, logger *zap.Logger) (*Runtime, erro cacheManager: cacheManager, popularityProvider: popularityProvider, sigCache: toolsig.NewCache(), - secretResolver: secretResolver, tokenizer: tokenizer, refreshManager: refreshManager, activityService: activityService, @@ -744,6 +751,7 @@ func New(cfg *config.Config, cfgPath string, logger *zap.Logger) (*Runtime, erro lastGoodTools: make(map[string][]*config.ToolMetadata), profileMembership: make(map[string][]string), } + rt.secretResolver.Store(secretResolver) rt.truncator.Store(truncator) // Spec 108 FR-026: the one clients service behind every client-credential @@ -1525,7 +1533,7 @@ func extractToolCount(stats map[string]interface{}) int { // GetSecretResolver returns the secret resolver instance func (r *Runtime) GetSecretResolver() *secret.Resolver { - return r.secretResolver + return r.secretResolver.Load() } // NotifySecretsChanged notifies the runtime that secrets have changed and restarts affected servers. @@ -4181,6 +4189,14 @@ func (r *Runtime) applyComponentConfigLocked(oldCfg, newCfg *config.Config) { zap.Duration("new_interval", newCfg.Observability.UsagePersistInterval.Duration())) r.activityService.SetUsagePersistInterval(newCfg.Observability.UsagePersistInterval.Duration()) } + + if oldCfg.DataDir != newCfg.DataDir || !config.SecretFileDirsEqual(oldCfg.SecretFileDirs, newCfg.SecretFileDirs) { + resolver := config.BuildSecretResolver(newCfg, r.cfgPath, secret.ScopeUpstream) + r.secretResolver.Store(resolver) + if r.upstreamManager != nil { + r.upstreamManager.SetSecretResolver(resolver) + } + } } // GetVersionInfo returns the current version information from the update checker. diff --git a/internal/runtime/secret_file_dirs_hotreload_test.go b/internal/runtime/secret_file_dirs_hotreload_test.go new file mode 100644 index 000000000..a12752bf5 --- /dev/null +++ b/internal/runtime/secret_file_dirs_hotreload_test.go @@ -0,0 +1,65 @@ +package runtime + +import ( + "os" + "path/filepath" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestApplyConfig_SecretFileDirsRebuildsResolver(t *testing.T) { + dir := t.TempDir() + allowed := filepath.Join(dir, "allowed") + outside := filepath.Join(dir, "outside") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + require.NoError(t, os.MkdirAll(outside, 0o700)) + key := filepath.Join(outside, "token") + require.NoError(t, os.WriteFile(key, []byte("x\n"), 0o600)) + + narrow := config.SecretFileDirs{allowed} + rt, cfgPath := newSpec116Runtime(t, func(c *config.Config) { + c.DataDir = dir + c.SecretFileDirs = &narrow + }, &config.ServerConfig{Name: "s", URL: "http://127.0.0.1:9/mcp", Enabled: false}) + + ref := "Bearer ${file:" + key + "}" + _, err := rt.Commit("update_server", func(tx *CommitTx) error { + return tx.UpdateServer("s", func(cur *config.ServerConfig) error { + cur.Headers = map[string]string{"Authorization": ref} + return nil + }) + }) + var verr *config.InvalidServerUpdateError + require.ErrorAs(t, err, &verr) + assert.Equal(t, secret.ErrSecretFileDenied.Error(), verr.Errors[0].Message) + + wide := config.SecretFileDirs{allowed, outside} + next := cloneRuntimeConfig(t, rt.Config()) + next.SecretFileDirs = &wide + _, err = rt.ApplyConfig(next, cfgPath) + require.NoError(t, err) + + _, err = rt.Commit("update_server", func(tx *CommitTx) error { + return tx.UpdateServer("s", func(cur *config.ServerConfig) error { + cur.Headers = map[string]string{"Authorization": ref} + return nil + }) + }) + require.NoError(t, err) + got := liveServerConfig(rt, "s") + require.NotNil(t, got) + assert.Equal(t, ref, got.Headers["Authorization"]) +} + +func liveServerConfig(rt *Runtime, name string) *config.ServerConfig { + for _, sc := range rt.Config().Servers { + if sc != nil && sc.Name == name { + return sc + } + } + return nil +} diff --git a/internal/runtime/secret_file_dirs_warning.go b/internal/runtime/secret_file_dirs_warning.go new file mode 100644 index 000000000..055fab544 --- /dev/null +++ b/internal/runtime/secret_file_dirs_warning.go @@ -0,0 +1,25 @@ +package runtime + +import ( + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" +) + +// warnUpstreamFileRefsOutsideAllowList logs one startup WARN naming every +// upstream server whose ${file:} reference secret_file_dirs refuses by path +// (#1721 upgrade path: such references resolved before the allow-list +// existed). Paths are not logged; the server names are enough to find them in +// the config file. +func warnUpstreamFileRefsOutsideAllowList(logger *zap.Logger, cfg *config.Config) { + if logger == nil { + return + } + names := config.UpstreamFileRefsOutsideAllowList(cfg) + if len(names) == 0 { + return + } + logger.Warn(config.MsgUpstreamFileRefsOutsideAllowList, + zap.Strings("servers", names), + zap.String("key", "secret_file_dirs")) +} diff --git a/internal/runtime/secret_file_dirs_warning_test.go b/internal/runtime/secret_file_dirs_warning_test.go new file mode 100644 index 000000000..594c7f0c6 --- /dev/null +++ b/internal/runtime/secret_file_dirs_warning_test.go @@ -0,0 +1,41 @@ +package runtime + +import ( + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" + "go.uber.org/zap/zaptest/observer" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" +) + +func TestWarnUpstreamFileRefsOutsideAllowList(t *testing.T) { + dir := t.TempDir() + allowed := filepath.Join(dir, "allowed") + dirs := config.SecretFileDirs{allowed} + cfg := &config.Config{DataDir: filepath.Join(dir, "data"), SecretFileDirs: &dirs, Servers: []*config.ServerConfig{ + {Name: "b-outside", Env: map[string]string{"T": "${file:/elsewhere/tok}"}}, + {Name: "a-outside", Headers: map[string]string{"X": "${file:/other/tok}"}}, + {Name: "inside", Env: map[string]string{"T": "${file:" + filepath.Join(allowed, "tok") + "}"}}, + }} + + core, logs := observer.New(zapcore.WarnLevel) + warnUpstreamFileRefsOutsideAllowList(zap.New(core), cfg) + + entries := logs.FilterMessage(config.MsgUpstreamFileRefsOutsideAllowList).All() + require.Len(t, entries, 1, "one WARN line for all affected servers") + assert.Equal(t, []any{"a-outside", "b-outside"}, entries[0].ContextMap()["servers"]) + for _, f := range entries[0].Context { + assert.NotContains(t, f.String, "/elsewhere", "paths are not logged") + } + + // Nothing outside: no warning. + core2, logs2 := observer.New(zapcore.WarnLevel) + cfg.Servers = cfg.Servers[2:] + warnUpstreamFileRefsOutsideAllowList(zap.New(core2), cfg) + assert.Zero(t, logs2.Len()) +} diff --git a/internal/runtime/server_secret_policy_commit_test.go b/internal/runtime/server_secret_policy_commit_test.go new file mode 100644 index 000000000..4f1f73e00 --- /dev/null +++ b/internal/runtime/server_secret_policy_commit_test.go @@ -0,0 +1,57 @@ +package runtime + +import ( + "os" + "path/filepath" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCommit_CreateServer_RefusesSecretPolicyBeforeSave(t *testing.T) { + dir := t.TempDir() + allowed := filepath.Join(dir, "secrets") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + w := config.SecretFileDirs{allowed} + rt, _ := newSpec116Runtime(t, func(c *config.Config) { + c.DataDir = dir + c.SecretFileDirs = &w + }) + sc := &config.ServerConfig{ + Name: "bad", + URL: "http://127.0.0.1:9/mcp", + Env: map[string]string{"K": "${env:MCPPROXY_API_KEY}"}, + } + _, err := rt.Commit("create_server", func(tx *CommitTx) error { return tx.CreateServer(sc) }) + var verr *config.InvalidServerUpdateError + require.ErrorAs(t, err, &verr) + require.NotEmpty(t, verr.Errors) + assert.Equal(t, secret.ErrReservedEnvVar.Error(), verr.Errors[0].Message) +} + +func TestCommit_UpdateServer_RefusesOutOfPolicyFileBeforeSave(t *testing.T) { + dir := t.TempDir() + allowed := filepath.Join(dir, "allowed") + outside := filepath.Join(dir, "outside") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + require.NoError(t, os.MkdirAll(outside, 0o700)) + outFile := filepath.Join(outside, "k") + require.NoError(t, os.WriteFile(outFile, []byte("x\n"), 0o600)) + w := config.SecretFileDirs{allowed} + rt, _ := newSpec116Runtime(t, func(c *config.Config) { + c.DataDir = dir + c.SecretFileDirs = &w + }, &config.ServerConfig{Name: "s", URL: "http://127.0.0.1:9/mcp", Enabled: false}) + _, err := rt.Commit("update_server", func(tx *CommitTx) error { + return tx.UpdateServer("s", func(cur *config.ServerConfig) error { + cur.Headers = map[string]string{"Authorization": "Bearer ${file:" + outFile + "}"} + return nil + }) + }) + var verr *config.InvalidServerUpdateError + require.ErrorAs(t, err, &verr) + assert.Equal(t, secret.ErrSecretFileDenied.Error(), verr.Errors[0].Message) +} diff --git a/internal/runtime/unresolved_header_secret_test.go b/internal/runtime/unresolved_header_secret_test.go index 62d8065a8..033927e68 100644 --- a/internal/runtime/unresolved_header_secret_test.go +++ b/internal/runtime/unresolved_header_secret_test.go @@ -129,7 +129,7 @@ func testUnresolvedHeaderSecret(t *testing.T, restart func(*Runtime) error) { t.Cleanup(func() { _ = rt.Close() }) keyring := &fakeKeyring{values: map[string]string{"f9-present": presentValue}} - rt.secretResolver.RegisterProvider("keyring", keyring) + rt.secretResolver.Load().RegisterProvider("keyring", keyring) for _, c := range []*config.ServerConfig{secretCfg, otherCfg} { require.NoError(t, rt.storageManager.SaveUpstreamServer(c)) } diff --git a/internal/secret/deny_at_read.go b/internal/secret/deny_at_read.go new file mode 100644 index 000000000..8aa61f70b --- /dev/null +++ b/internal/secret/deny_at_read.go @@ -0,0 +1,100 @@ +package secret + +import ( + "os" + "path/filepath" +) + +// dataDirStateSubdirs are data-dir children that hold proxy state files. Files +// directly inside these directories are refused (not deeper nesting). The +// secrets/ subtree is always excluded. +var dataDirStateSubdirs = []string{ + "certs", + "index.bleve", + "tpa-lkg", +} + +// denyPathsAtRead returns filesystem paths to stat for handle identity checks. +// Paths are fresh on every read so renames and new inodes are caught. +func (p *FilePolicy) denyPathsAtRead() []string { + if p == nil || p.Scope != ScopeUpstream { + return nil + } + var paths []string + if p.Deny.ConfigFile != "" { + paths = append(paths, p.Deny.ConfigFile) + } + paths = append(paths, p.Deny.AdminKeyPaths...) + if p.Deny.DataDir == "" { + return uniqueAbsPaths(paths) + } + entries, err := os.ReadDir(p.Deny.DataDir) + if err != nil { + return uniqueAbsPaths(paths) + } + for _, e := range entries { + name := e.Name() + if name == "secrets" { + continue + } + full := filepath.Join(p.Deny.DataDir, name) + if !e.IsDir() { + paths = append(paths, full) + continue + } + for _, sub := range dataDirStateSubdirs { + if name != sub { + continue + } + subEntries, err := os.ReadDir(full) + if err != nil { + break + } + for _, se := range subEntries { + if !se.IsDir() { + paths = append(paths, filepath.Join(full, se.Name())) + } + } + break + } + } + return uniqueAbsPaths(paths) +} + +func uniqueAbsPaths(paths []string) []string { + seen := make(map[string]struct{}, len(paths)) + var out []string + for _, path := range paths { + if path == "" { + continue + } + path = filepath.Clean(path) + if _, ok := seen[path]; ok { + continue + } + seen[path] = struct{}{} + out = append(out, path) + } + return out +} + +func (p *FilePolicy) deniedByHandleAtRead(f *os.File, info os.FileInfo) bool { + if info == nil || p == nil || p.Scope != ScopeUpstream { + return false + } + // The opened file's identity, read from the handle (fail closed when it + // cannot be read). + id, ok := identityOfHandle(f, info) + if !ok { + return true + } + if matchesSupersededProxyFile(f, info) { + return true + } + for _, path := range p.denyPathsAtRead() { + if d, ok := StatDenyIdentity(path); ok && d.matches(id) { + return true + } + } + return false +} diff --git a/internal/secret/deny_identity.go b/internal/secret/deny_identity.go new file mode 100644 index 000000000..5b13d31e2 --- /dev/null +++ b/internal/secret/deny_identity.go @@ -0,0 +1,30 @@ +package secret + +// DenyIdentity is a reserved file identified by device and inode (volume +// serial and file index on Windows), captured when it is statted so a later +// rename cannot change which file it names. +type DenyIdentity struct { + id fileIdentity + ok bool +} + +// StatDenyIdentity records a file to refuse, following symlinks like a secret read. +func StatDenyIdentity(path string) (DenyIdentity, bool) { + if path == "" { + return DenyIdentity{}, false + } + resolved, err := resolveSymlinks(path) + if err != nil { + resolved = path + } + id, ok := identityOfPath(resolved) + if !ok { + return DenyIdentity{}, false + } + return DenyIdentity{id: id, ok: true}, true +} + +// matches reports whether the opened file's identity is this one. +func (d DenyIdentity) matches(id fileIdentity) bool { + return d.ok && d.id == id +} diff --git a/internal/secret/deny_superseded.go b/internal/secret/deny_superseded.go new file mode 100644 index 000000000..a4970a404 --- /dev/null +++ b/internal/secret/deny_superseded.go @@ -0,0 +1,100 @@ +package secret + +import ( + "errors" + "io/fs" + "os" + "sync" +) + +// maxSupersededProxyFiles bounds the process-lifetime list of replaced proxy +// file identities (16 bytes each). The oldest entry is dropped first. +const maxSupersededProxyFiles = 4096 + +// supersededStamp is a replaced proxy file: its identity plus its last +// modification time. Linux and Windows reuse a freed inode / file index, so +// the identity alone would, once the replaced file is gone, refuse an +// unrelated file that later got the same identity (for the life of the +// process). A hardlink to the replaced file keeps its modification time +// (unlinking and renaming change only ctime); a new file at a reused identity +// gets its own. +type supersededStamp struct { + id fileIdentity + mtime int64 // nanoseconds since the epoch +} + +var ( + supersededMu sync.Mutex + supersededFiles []supersededStamp + supersededSet = map[supersededStamp]struct{}{} +) + +// NoteSupersededProxyFile records the identity path has now, just before a +// writer renames a new file over it (SaveConfig and the deprecated-key +// cleanup do this for mcp_config.json). After the rename the old inode is no +// longer reachable through path, so the live deny list stops matching it, but +// a hardlink made to it earlier still reads the old content (api_key, server +// entries). Upstream reads refuse every identity recorded here for the life of +// the process. The identity is captured now (device and inode, or volume +// serial and file index read from a handle on Windows), never from a retained +// FileInfo, together with the file's modification time from the same stat +// (see supersededStamp). A path that does not exist records nothing and is +// not an error (the first save creates the file). +// +// A write to the replaced file through a hardlink, or setting its times, +// changes that time and ends the refusal; either needs ownership of or write +// access (FILE_WRITE_ATTRIBUTES on Windows) to the proxy's own 0600 config, +// which only its owner has, and the owner can read it anyway. On a filesystem +// with coarse timestamps a new file at a reused identity can still share the +// time and be refused: the rare residue of the false refusal this avoids, and +// it fails closed. +// +// Any other failure to read the identity is returned, and nothing is +// recorded: the caller should warn, since a hardlink to the replaced file will +// not be refused. The error names the path and the reason, never content. +// +// Best effort: the record is in memory only, so a restart, a save by another +// process (a separate CLI invocation) or more than maxSupersededProxyFiles +// later saves forget it. +func NoteSupersededProxyFile(path string) error { + if path == "" { + return nil + } + st, err := stampOfPathErr(path) + if err != nil { + if errors.Is(err, fs.ErrNotExist) { + return nil + } + return err + } + recordSupersededStamp(st) + return nil +} + +func recordSupersededStamp(st supersededStamp) { + supersededMu.Lock() + defer supersededMu.Unlock() + if _, known := supersededSet[st]; known { + return + } + if len(supersededFiles) >= maxSupersededProxyFiles { + delete(supersededSet, supersededFiles[0]) + supersededFiles = append(supersededFiles[:0:0], supersededFiles[1:]...) + } + supersededFiles = append(supersededFiles, st) + supersededSet[st] = struct{}{} +} + +// matchesSupersededProxyFile reports whether the opened file is one recorded +// by NoteSupersededProxyFile (same identity and modification time). An identity that cannot be read is treated as a +// match (fail closed). +func matchesSupersededProxyFile(f *os.File, info os.FileInfo) bool { + st, ok := stampOfHandle(f, info) + if !ok { + return true + } + supersededMu.Lock() + defer supersededMu.Unlock() + _, known := supersededSet[st] + return known +} diff --git a/internal/secret/deny_superseded_test.go b/internal/secret/deny_superseded_test.go new file mode 100644 index 000000000..3cc914c87 --- /dev/null +++ b/internal/secret/deny_superseded_test.go @@ -0,0 +1,76 @@ +package secret + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +// The noted identity must keep naming the replaced file after a new file is +// renamed over its path (on every platform; on Windows a retained os.Stat +// FileInfo would resolve to the new file instead). +func TestNoteSupersededProxyFile_KeepsReplacedIdentity(t *testing.T) { + dir := t.TempDir() + cfgPath := filepath.Join(dir, "mcp_config.json") + require.NoError(t, os.WriteFile(cfgPath, []byte(`{"api_key":"old"}`), 0o600)) + link := filepath.Join(dir, "link") + require.NoError(t, os.Link(cfgPath, link)) + + NoteSupersededProxyFile(cfgPath) + tmp := cfgPath + ".tmp" + require.NoError(t, os.WriteFile(tmp, []byte(`{"api_key":"new"}`), 0o600)) + require.NoError(t, os.Rename(tmp, cfgPath)) + + matches := func(path string) bool { + f, err := os.Open(path) + require.NoError(t, err) + defer f.Close() + info, err := f.Stat() + require.NoError(t, err) + return matchesSupersededProxyFile(f, info) + } + require.True(t, matches(link), "the replaced inode is remembered") + require.False(t, matches(cfgPath), "the new config is not the superseded one") +} + +// A missing file is the first save (nothing to record, no error); any other +// failure to capture the identity is reported so the caller can warn. +func TestNoteSupersededProxyFile_ReportsCaptureFailure(t *testing.T) { + dir := t.TempDir() + require.NoError(t, NoteSupersededProxyFile(filepath.Join(dir, "missing.json"))) + require.NoError(t, NoteSupersededProxyFile("")) + + err := NoteSupersededProxyFile(dir) // a directory: no file identity to record + require.Error(t, err) + require.NotContains(t, err.Error(), "api_key") +} + +// Linux and Windows reuse a freed inode / file index. A superseded record +// whose file was later deleted must not refuse an unrelated new file that got +// the same identity: the record also carries the replaced file's modification +// time, which a hardlink to it keeps and a new file does not share. +func TestNoteSupersededProxyFile_ReusedIdentityIsNotRefused(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "secret") + require.NoError(t, os.WriteFile(path, []byte("tok"), 0o600)) + f, err := os.Open(path) + require.NoError(t, err) + defer f.Close() + info, err := f.Stat() + require.NoError(t, err) + + live, ok := stampOfHandle(f, info) + require.True(t, ok) + + // The replaced config once had this file's identity, but a different + // modification time: the inode was freed and reused for this file. + reused := live + reused.mtime-- + recordSupersededStamp(reused) + require.False(t, matchesSupersededProxyFile(f, info), "a reused identity with another mtime is a different file") + + recordSupersededStamp(live) + require.True(t, matchesSupersededProxyFile(f, info), "identity and mtime both match: the replaced file") +} diff --git a/internal/secret/env_provider.go b/internal/secret/env_provider.go index 7735048a8..167aadb68 100644 --- a/internal/secret/env_provider.go +++ b/internal/secret/env_provider.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "os" + "runtime" "strings" ) @@ -12,11 +13,13 @@ const ( ) // EnvProvider resolves secrets from environment variables -type EnvProvider struct{} +type EnvProvider struct { + guardMCPProxy bool +} // NewEnvProvider creates a new environment variable provider -func NewEnvProvider() *EnvProvider { - return &EnvProvider{} +func NewEnvProvider(guardMCPProxy bool) *EnvProvider { + return &EnvProvider{guardMCPProxy: guardMCPProxy} } // CanResolve returns true if this provider can handle the given secret type @@ -30,6 +33,12 @@ func (p *EnvProvider) Resolve(_ context.Context, ref Ref) (string, error) { return "", fmt.Errorf("env provider cannot resolve secret type: %s", ref.Type) } + if p.guardMCPProxy { + if ReservedMCPProxyEnvName(ref.Name, runtime.GOOS) { + return "", ErrReservedEnvVar + } + } + value := os.Getenv(ref.Name) if value == "" { return "", fmt.Errorf("environment variable %s not found or empty", ref.Name) @@ -38,6 +47,18 @@ func (p *EnvProvider) Resolve(_ context.Context, ref Ref) (string, error) { return value, nil } +// ReservedMCPProxyEnvName reports whether name is in the reserved MCPPROXY_ namespace. +func ReservedMCPProxyEnvName(name, goos string) bool { + const prefix = "MCPPROXY_" + if len(name) < len(prefix) { + return false + } + if goos == "windows" { + return strings.EqualFold(name[:len(prefix)], prefix) + } + return strings.HasPrefix(name, prefix) +} + // Store is not supported for environment variables func (p *EnvProvider) Store(_ context.Context, _ Ref, _ string) error { return fmt.Errorf("env provider does not support storing secrets") @@ -61,7 +82,6 @@ func (p *EnvProvider) List(_ context.Context) ([]Ref, error) { name := pair[0] value := pair[1] - // Only include variables that look like secrets if isLikelySecretEnvVar(name, value) { refs = append(refs, Ref{ Type: "env", @@ -84,10 +104,6 @@ func isLikelySecretEnvVar(name, value string) bool { if value == "" { return false } - - // Check if the variable name suggests it's a secret isSecret, confidence := DetectPotentialSecret(value, name) - - // Lower threshold for env vars since they're commonly used for secrets return isSecret || confidence >= 0.3 } diff --git a/internal/secret/env_provider_reserved_test.go b/internal/secret/env_provider_reserved_test.go new file mode 100644 index 000000000..063b769e1 --- /dev/null +++ b/internal/secret/env_provider_reserved_test.go @@ -0,0 +1,15 @@ +package secret + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestReservedMCPProxyEnvName_WindowsCaseFold(t *testing.T) { + assert.True(t, ReservedMCPProxyEnvName("mcpproxy_api_key", "windows")) + assert.True(t, ReservedMCPProxyEnvName("McPpRoXy_API_KEY", "windows")) + assert.False(t, ReservedMCPProxyEnvName("MCPROXY_API_KEY", "windows")) + assert.True(t, ReservedMCPProxyEnvName("MCPPROXY_API_KEY", "linux")) + assert.False(t, ReservedMCPProxyEnvName("mcpproxy_api_key", "linux")) +} diff --git a/internal/secret/env_provider_test.go b/internal/secret/env_provider_test.go index 0c85611e9..befaf79da 100644 --- a/internal/secret/env_provider_test.go +++ b/internal/secret/env_provider_test.go @@ -2,159 +2,39 @@ package secret import ( "context" - "os" "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) -func TestEnvProvider_CanResolve(t *testing.T) { - provider := NewEnvProvider() - - assert.True(t, provider.CanResolve("env")) - assert.False(t, provider.CanResolve("keyring")) - assert.False(t, provider.CanResolve("unknown")) -} - -func TestEnvProvider_IsAvailable(t *testing.T) { - provider := NewEnvProvider() - assert.True(t, provider.IsAvailable()) -} - -func TestEnvProvider_Resolve(t *testing.T) { - provider := NewEnvProvider() - ctx := context.Background() - - t.Run("existing environment variable", func(t *testing.T) { - // Set a test environment variable - key := "TEST_SECRET_VAR" - value := "test-secret-value" - os.Setenv(key, value) - defer os.Unsetenv(key) - - ref := Ref{ - Type: "env", - Name: key, - } - - result, err := provider.Resolve(ctx, ref) - - assert.NoError(t, err) - assert.Equal(t, value, result) - }) - - t.Run("non-existing environment variable", func(t *testing.T) { - ref := Ref{ - Type: "env", - Name: "NON_EXISTING_VAR", - } - - _, err := provider.Resolve(ctx, ref) - - assert.Error(t, err) - assert.Contains(t, err.Error(), "not found or empty") - }) - - t.Run("empty environment variable", func(t *testing.T) { - key := "EMPTY_VAR" - os.Setenv(key, "") - defer os.Unsetenv(key) - - ref := Ref{ - Type: "env", - Name: key, - } - - _, err := provider.Resolve(ctx, ref) - - assert.Error(t, err) - assert.Contains(t, err.Error(), "not found or empty") - }) - - t.Run("wrong secret type", func(t *testing.T) { - ref := Ref{ - Type: "keyring", - Name: "test", - } - - _, err := provider.Resolve(ctx, ref) - - assert.Error(t, err) - assert.Contains(t, err.Error(), "cannot resolve secret type") - }) -} - -func TestEnvProvider_Store(t *testing.T) { - provider := NewEnvProvider() - ctx := context.Background() - - ref := Ref{ - Type: "env", - Name: "test", +func TestEnvProvider_ReservedMCPProxyNamespace(t *testing.T) { + p := NewEnvProvider(true) + refs := []string{ + "MCPPROXY_API_KEY", + "MCPPROXY_API_KEY_FILE", + "MCPPROXY_CRED_KEY", } - - err := provider.Store(ctx, ref, "value") - - assert.Error(t, err) - assert.Contains(t, err.Error(), "does not support storing") -} - -func TestEnvProvider_Delete(t *testing.T) { - provider := NewEnvProvider() - ctx := context.Background() - - ref := Ref{ - Type: "env", - Name: "test", + for _, name := range refs { + _, err := p.Resolve(context.Background(), Ref{Type: "env", Name: name}) + require.ErrorIs(t, err, ErrReservedEnvVar, name) } - err := provider.Delete(ctx, ref) + // Wrong spelling must not be guarded (regression: MCPROXY_ typo). + _, err := p.Resolve(context.Background(), Ref{Type: "env", Name: "MCPROXY_API_KEY"}) + require.Error(t, err) + require.NotErrorIs(t, err, ErrReservedEnvVar) - assert.Error(t, err) - assert.Contains(t, err.Error(), "does not support deleting") + t.Setenv("MCPROXY_X", "value") + val, err := p.Resolve(context.Background(), Ref{Type: "env", Name: "MCPROXY_X"}) + require.NoError(t, err) + assert.Equal(t, "value", val) } -func TestEnvProvider_List(t *testing.T) { - provider := NewEnvProvider() - ctx := context.Background() - - // Set some test environment variables - testVars := map[string]string{ - "TEST_API_KEY": "sk-1234567890abcdef", - "TEST_PASSWORD": "secretpassword123", - "TEST_REGULAR": "localhost", - "TEST_SHORT": "abc", - } - - // Set environment variables and collect keys for cleanup - var keysToCleanup []string - for key, value := range testVars { - os.Setenv(key, value) - keysToCleanup = append(keysToCleanup, key) - } - - // Clean up environment variables after test - defer func() { - for _, key := range keysToCleanup { - os.Unsetenv(key) - } - }() - - refs, err := provider.List(ctx) - - assert.NoError(t, err) - assert.NotNil(t, refs) - - // Should contain our test secret-like variables - foundSecrets := make(map[string]bool) - for _, ref := range refs { - assert.Equal(t, "env", ref.Type) - if _, exists := testVars[ref.Name]; exists { - foundSecrets[ref.Name] = true - } - } - - // Should detect API key and password as secrets - assert.True(t, foundSecrets["TEST_API_KEY"] || foundSecrets["TEST_PASSWORD"], - "Should detect at least one of the secret-like variables") +func TestEnvProvider_ProxyScopeDoesNotGuard(t *testing.T) { + t.Setenv("MCPPROXY_API_KEY", "from-env") + p := NewEnvProvider(false) + val, err := p.Resolve(context.Background(), Ref{Type: "env", Name: "MCPPROXY_API_KEY"}) + require.NoError(t, err) + assert.Equal(t, "from-env", val) } diff --git a/internal/secret/errors.go b/internal/secret/errors.go new file mode 100644 index 000000000..58b45e9d6 --- /dev/null +++ b/internal/secret/errors.go @@ -0,0 +1,12 @@ +package secret + +import "errors" + +// ErrSecretFileDenied is returned when a ${file:} reference is refused by +// secret_file_dirs, a deny path, or a disabled file provider. The message is +// fixed and must not echo the path or any file content. +var ErrSecretFileDenied = errors.New("secret file is missing, unreadable or outside secret_file_dirs") + +// ErrReservedEnvVar is returned when an upstream-scoped resolver refuses a +// ${env:MCPPROXY_* …} reference. The message is fixed and must not echo the name. +var ErrReservedEnvVar = errors.New("secret reference refused: this environment variable is reserved") diff --git a/internal/secret/extended_path.go b/internal/secret/extended_path.go new file mode 100644 index 000000000..340f816a1 --- /dev/null +++ b/internal/secret/extended_path.go @@ -0,0 +1,70 @@ +package secret + +import "strings" + +// windowsExtendedLengthPath returns the \\?\ form of an absolute Windows path +// so CreateFile accepts it past MAX_PATH (the os package does this itself; +// syscall.CreateFile does not). Because \\?\ turns off Win32 normalization, +// separators are converted to '\', repeated separators are collapsed and +// "." / ".." elements are resolved first (".." never climbs above the drive +// or the \\server\share root). Paths already in the \\?\ or \\.\ namespace, +// and paths that are neither drive-absolute nor UNC, are returned unchanged. +// +// Pure string logic with Windows rules, so it is tested on every platform. +func windowsExtendedLengthPath(p string) string { + if strings.HasPrefix(p, `\\?\`) || strings.HasPrefix(p, `\\.\`) { + return p + } + s := strings.ReplaceAll(p, "/", `\`) + if strings.HasPrefix(s, `\\?\`) || strings.HasPrefix(s, `\\.\`) { + return s + } + + switch { + case strings.HasPrefix(s, `\\`): + parts := splitClean(s[2:]) + if len(parts) < 2 { + return p // not \\server\share\... + } + root := parts[:2] + rest := resolveDots(parts[2:]) + return `\\?\UNC\` + strings.Join(append(root, rest...), `\`) + case len(s) >= 3 && s[1] == ':' && s[2] == '\\' && isDriveLetter(s[0]): + rest := resolveDots(splitClean(s[3:])) + return `\\?\` + s[:2] + `\` + strings.Join(rest, `\`) + default: + return p + } +} + +func isDriveLetter(c byte) bool { + return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') +} + +// splitClean splits on '\' and drops empty elements (repeated separators). +func splitClean(s string) []string { + var out []string + for _, e := range strings.Split(s, `\`) { + if e != "" { + out = append(out, e) + } + } + return out +} + +// resolveDots drops "." and applies ".." without climbing above the root. +func resolveDots(elems []string) []string { + out := make([]string, 0, len(elems)) + for _, e := range elems { + switch e { + case ".": + case "..": + if len(out) > 0 { + out = out[:len(out)-1] + } + default: + out = append(out, e) + } + } + return out +} diff --git a/internal/secret/extended_path_test.go b/internal/secret/extended_path_test.go new file mode 100644 index 000000000..5c25d564c --- /dev/null +++ b/internal/secret/extended_path_test.go @@ -0,0 +1,32 @@ +package secret + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestWindowsExtendedLengthPath(t *testing.T) { + long := `C:\` + strings.Repeat(`abcdefghij\`, 30) + `mcp_config.json` + cases := []struct{ in, want string }{ + {`C:\Users\me\.mcpproxy\mcp_config.json`, `\\?\C:\Users\me\.mcpproxy\mcp_config.json`}, + {`c:/Users/me/mcp_config.json`, `\\?\c:\Users\me\mcp_config.json`}, + {`C:\a\\b\.\c\..\mcp_config.json`, `\\?\C:\a\b\mcp_config.json`}, + {`C:\..\..\x`, `\\?\C:\x`}, + {`C:\`, `\\?\C:\`}, + {`\\server\share\dir\mcp_config.json`, `\\?\UNC\server\share\dir\mcp_config.json`}, + {`//server/share/dir/../cfg.json`, `\\?\UNC\server\share\cfg.json`}, + {`\\server\share\..\..\cfg.json`, `\\?\UNC\server\share\cfg.json`}, + {`\\?\C:\already\cfg.json`, `\\?\C:\already\cfg.json`}, + {`\\?\UNC\server\share\cfg.json`, `\\?\UNC\server\share\cfg.json`}, + {`\\.\pipe\mcpproxy`, `\\.\pipe\mcpproxy`}, + {`relative\cfg.json`, `relative\cfg.json`}, + {`\rooted\no-drive`, `\rooted\no-drive`}, + {`\\server`, `\\server`}, + {long, `\\?\` + long}, + } + for _, c := range cases { + assert.Equal(t, c.want, windowsExtendedLengthPath(c.in), c.in) + } +} diff --git a/internal/secret/file_identity_unix.go b/internal/secret/file_identity_unix.go new file mode 100644 index 000000000..d4d095435 --- /dev/null +++ b/internal/secret/file_identity_unix.go @@ -0,0 +1,86 @@ +//go:build unix + +package secret + +import ( + "errors" + "os" + "syscall" +) + +// fileIdentity is a file's device and inode, captured eagerly so it keeps +// naming the same file after the path is renamed over. +type fileIdentity struct { + dev, ino uint64 +} + +var errIdentityNotRegular = errors.New("not a regular file") + +func identityFromInfo(info os.FileInfo) (fileIdentity, bool) { + if info == nil { + return fileIdentity{}, false + } + st, ok := info.Sys().(*syscall.Stat_t) + if !ok || st == nil { + return fileIdentity{}, false + } + return fileIdentity{dev: uint64(st.Dev), ino: uint64(st.Ino)}, true //nolint:unconvert // widths differ by platform +} + +// identityOfPathErr stats path (following symlinks) and returns its identity. +// A missing file reports an error matching fs.ErrNotExist. +func identityOfPathErr(path string) (fileIdentity, error) { + fi, err := os.Stat(path) + if err != nil { + return fileIdentity{}, err + } + if !fi.Mode().IsRegular() { + return fileIdentity{}, errIdentityNotRegular + } + id, ok := identityFromInfo(fi) + if !ok { + return fileIdentity{}, errors.New("file identity unavailable") + } + return id, nil +} + +func identityOfPath(path string) (fileIdentity, bool) { + id, err := identityOfPathErr(path) + return id, err == nil +} + +// identityOfHandle returns the identity of an opened file from its fstat info. +func identityOfHandle(_ *os.File, info os.FileInfo) (fileIdentity, bool) { + return identityFromInfo(info) +} + +func stampFromInfo(info os.FileInfo) (supersededStamp, bool) { + id, ok := identityFromInfo(info) + if !ok { + return supersededStamp{}, false + } + return supersededStamp{id: id, mtime: info.ModTime().UnixNano()}, true +} + +// stampOfPathErr stats path once (following symlinks) and returns its +// identity and modification time from that one stat. +func stampOfPathErr(path string) (supersededStamp, error) { + fi, err := os.Stat(path) + if err != nil { + return supersededStamp{}, err + } + if !fi.Mode().IsRegular() { + return supersededStamp{}, errIdentityNotRegular + } + st, ok := stampFromInfo(fi) + if !ok { + return supersededStamp{}, errors.New("file identity unavailable") + } + return st, nil +} + +// stampOfHandle returns an opened file's identity and modification time from +// its fstat info. +func stampOfHandle(_ *os.File, info os.FileInfo) (supersededStamp, bool) { + return stampFromInfo(info) +} diff --git a/internal/secret/file_identity_windows.go b/internal/secret/file_identity_windows.go new file mode 100644 index 000000000..77b4648d9 --- /dev/null +++ b/internal/secret/file_identity_windows.go @@ -0,0 +1,103 @@ +//go:build windows + +package secret + +import ( + "errors" + "os" + "path/filepath" + "syscall" +) + +// fileIdentity is a file's volume serial number and file index, read from an +// open handle. os.Stat on Windows fills the file ID lazily, by path, on the +// first os.SameFile, so a retained FileInfo would name whatever file sits at +// the path by then (the new config after a rename); this is captured eagerly. +type fileIdentity struct { + vol uint32 + idx uint64 +} + +var errIdentityNotRegular = errors.New("not a regular file") + +// identityShareMode lets the identity open coexist with any other handle: +// os.Open omits FILE_SHARE_DELETE, so it fails with a sharing violation while +// another process holds the file open with DELETE access. +const identityShareMode = syscall.FILE_SHARE_READ | syscall.FILE_SHARE_WRITE | syscall.FILE_SHARE_DELETE + +// fileReadAttributes is FILE_READ_ATTRIBUTES, the only access +// GetFileInformationByHandle needs. +const fileReadAttributes = 0x0080 + +func identityFromHandle(h syscall.Handle) (fileIdentity, error) { + st, err := stampFromHandle(h) + return st.id, err +} + +// stampFromHandle reads the identity and last-write time from one +// GetFileInformationByHandle call. +func stampFromHandle(h syscall.Handle) (supersededStamp, error) { + var d syscall.ByHandleFileInformation + if err := syscall.GetFileInformationByHandle(h, &d); err != nil { + return supersededStamp{}, err + } + if d.FileAttributes&syscall.FILE_ATTRIBUTE_DIRECTORY != 0 { + return supersededStamp{}, errIdentityNotRegular + } + return supersededStamp{ + id: fileIdentity{vol: d.VolumeSerialNumber, idx: uint64(d.FileIndexHigh)<<32 | uint64(d.FileIndexLow)}, + mtime: d.LastWriteTime.Nanoseconds(), + }, nil +} + +// identityOfPathErr opens path (following links) with attribute-only access +// and every share flag, and reads its identity from the handle. A missing +// file reports an error matching fs.ErrNotExist. The path is made absolute +// and given the \\?\ prefix first: syscall.CreateFile, unlike the os package, +// does not do that itself, so a path longer than MAX_PATH would fail. +func identityOfPathErr(path string) (fileIdentity, error) { + st, err := stampOfPathErr(path) + return st.id, err +} + +// stampOfPathErr is identityOfPathErr plus the last-write time, both read +// from the one attribute handle. +func stampOfPathErr(path string) (supersededStamp, error) { + abs, err := filepath.Abs(path) + if err != nil { + return supersededStamp{}, &os.PathError{Op: "abs", Path: path, Err: err} + } + p, err := syscall.UTF16PtrFromString(windowsExtendedLengthPath(abs)) + if err != nil { + return supersededStamp{}, err + } + h, err := syscall.CreateFile(p, fileReadAttributes, identityShareMode, nil, syscall.OPEN_EXISTING, syscall.FILE_ATTRIBUTE_NORMAL, 0) + if err != nil { + return supersededStamp{}, &os.PathError{Op: "CreateFile", Path: path, Err: err} + } + defer syscall.CloseHandle(h) //nolint:errcheck // read-only attribute handle + return stampFromHandle(h) +} + +func identityOfPath(path string) (fileIdentity, bool) { + id, err := identityOfPathErr(path) + return id, err == nil +} + +// identityOfHandle returns the identity of an opened file. +func identityOfHandle(f *os.File, _ os.FileInfo) (fileIdentity, bool) { + if f == nil { + return fileIdentity{}, false + } + id, err := identityFromHandle(syscall.Handle(f.Fd())) + return id, err == nil +} + +// stampOfHandle returns an opened file's identity and last-write time. +func stampOfHandle(f *os.File, _ os.FileInfo) (supersededStamp, bool) { + if f == nil { + return supersededStamp{}, false + } + st, err := stampFromHandle(syscall.Handle(f.Fd())) + return st, err == nil +} diff --git a/internal/secret/file_identity_windows_test.go b/internal/secret/file_identity_windows_test.go new file mode 100644 index 000000000..615030f2b --- /dev/null +++ b/internal/secret/file_identity_windows_test.go @@ -0,0 +1,91 @@ +//go:build windows + +package secret + +import ( + "os" + "path/filepath" + "syscall" + "testing" + + "github.com/stretchr/testify/require" +) + +// Cross-review R1 (PR #1884): os.Stat on Windows loads the file ID lazily by +// path, so a FileInfo kept across a rename names the new file. The eager +// identity read from a handle must still name the old one. +func TestFileIdentity_WindowsEagerAcrossRename(t *testing.T) { + dir := t.TempDir() + cfgPath := filepath.Join(dir, "mcp_config.json") + require.NoError(t, os.WriteFile(cfgPath, []byte("old"), 0o600)) + link := filepath.Join(dir, "link") + require.NoError(t, os.Link(cfgPath, link)) + + before, ok := identityOfPath(cfgPath) + require.True(t, ok) + lazy, err := os.Stat(cfgPath) + require.NoError(t, err) + + tmp := cfgPath + ".tmp" + require.NoError(t, os.WriteFile(tmp, []byte("new"), 0o600)) + require.NoError(t, os.Rename(tmp, cfgPath)) + + after, ok := identityOfPath(cfgPath) + require.True(t, ok) + linked, ok := identityOfPath(link) + require.True(t, ok) + + require.NotEqual(t, before, after, "the rename gave the config a new file index") + require.Equal(t, before, linked, "the eager identity still names the replaced file") + + newInfo, err := os.Stat(cfgPath) + require.NoError(t, err) + if os.SameFile(lazy, newInfo) { + t.Log("os.Stat FileInfo resolved lazily to the new file, as the eager identity avoids") + } +} + +// Cross-review R3 (PR #1884): a config path longer than MAX_PATH must still +// be captured (CreateFile needs the \\?\ form for it). +func TestFileIdentity_WindowsLongPath(t *testing.T) { + dir := t.TempDir() + deep := dir + for len(deep) < 300 { + deep = filepath.Join(deep, "abcdefghijklmnopqrstuvwxyz") + } + require.NoError(t, os.MkdirAll(deep, 0o700)) + cfgPath := filepath.Join(deep, "mcp_config.json") + require.Greater(t, len(cfgPath), 260) + require.NoError(t, os.WriteFile(cfgPath, []byte("cfg"), 0o600)) + + _, err := identityOfPathErr(cfgPath) + require.NoError(t, err) + require.NoError(t, NoteSupersededProxyFile(cfgPath)) +} + +// Cross-review R2 (PR #1884): another process may hold the config open with +// DELETE access. os.Open does not share DELETE and fails with a sharing +// violation; the identity capture must share every mode and still succeed. +func TestFileIdentity_WindowsCaptureWhileHeldWithDeleteAccess(t *testing.T) { + dir := t.TempDir() + cfgPath := filepath.Join(dir, "mcp_config.json") + require.NoError(t, os.WriteFile(cfgPath, []byte("cfg"), 0o600)) + + p, err := syscall.UTF16PtrFromString(cfgPath) + require.NoError(t, err) + const deleteAccess = 0x00010000 // DELETE + held, err := syscall.CreateFile(p, syscall.GENERIC_READ|deleteAccess, + syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE, + nil, syscall.OPEN_EXISTING, syscall.FILE_ATTRIBUTE_NORMAL, 0) + require.NoError(t, err) + t.Cleanup(func() { _ = syscall.CloseHandle(held) }) + + if f, oerr := os.Open(cfgPath); oerr == nil { + _ = f.Close() + t.Log("os.Open succeeded here; the sharing violation it can hit is not reproduced on this runner") + } + + _, err = identityOfPathErr(cfgPath) + require.NoError(t, err, "identity capture shares DELETE") + require.NoError(t, NoteSupersededProxyFile(cfgPath)) +} diff --git a/internal/secret/file_policy.go b/internal/secret/file_policy.go new file mode 100644 index 000000000..61ee29bd5 --- /dev/null +++ b/internal/secret/file_policy.go @@ -0,0 +1,302 @@ +package secret + +import ( + "bytes" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "strings" +) + +// NewWildcardFilePolicy returns a policy that allows any absolute regular file. +// Used by NewTestWildcardResolver() so existing tests keep #1717 behaviour. +func NewWildcardFilePolicy(scope ResolveScope) *FilePolicy { + return &FilePolicy{Wildcard: true, Scope: scope} +} + +// NewDisabledFilePolicy refuses every ${file:} reference. +func NewDisabledFilePolicy(scope ResolveScope) *FilePolicy { + return &FilePolicy{Disabled: true, Scope: scope} +} + +// containsRawDotDot reports whether path has a .. path element before cleaning. +func containsRawDotDot(path string) bool { + for _, elem := range splitPathElements(path) { + if elem == ".." { + return true + } + } + return false +} + +func splitPathElements(path string) []string { + if path == "" { + return nil + } + vol := filepath.VolumeName(path) + trimmed := strings.TrimPrefix(path, vol) + trimmed = strings.TrimPrefix(trimmed, string(filepath.Separator)) + if trimmed == "" { + return nil + } + return strings.Split(trimmed, string(filepath.Separator)) +} + +// resolveSymlinks wraps filepath.EvalSymlinks; a missing final component is not +// an error here because containment may still fail uniformly. +func resolveSymlinks(path string) (string, error) { + resolved, err := filepath.EvalSymlinks(path) + if err != nil { + if os.IsNotExist(err) { + return filepath.Clean(path), nil + } + return "", err + } + return resolved, nil +} + +// pathContainedInRoot reports whether filePath is inside rootPath by path +// element (not string prefix). Both paths must be clean; rootPath is a directory. +func pathContainedInRoot(rootPath, filePath string) (bool, error) { + if !filepath.IsAbs(rootPath) || !filepath.IsAbs(filePath) { + return false, fmt.Errorf("containment requires absolute paths") + } + rootPath = filepath.Clean(rootPath) + filePath = filepath.Clean(filePath) + + if pathEqual(rootPath, filePath) { + return false, nil + } + + rel, err := filepath.Rel(rootPath, filePath) + if err != nil { + return false, err + } + if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return false, nil + } + first := rel + if i := strings.IndexByte(rel, filepath.Separator); i >= 0 { + first = rel[:i] + } + if first == ".." { + return false, nil + } + return true, nil +} + +func pathEqual(a, b string) bool { + if runtime.GOOS == "windows" { + return strings.EqualFold(filepath.Clean(a), filepath.Clean(b)) + } + return filepath.Clean(a) == filepath.Clean(b) +} + +// matchingRoot returns the allowed root that contains resolvedPath, or "". +func (p *FilePolicy) matchingRoot(resolvedPath string) (string, error) { + for _, root := range p.AllowedRoots { + resolvedRoot, err := resolveSymlinks(root) + if err != nil { + continue + } + ok, err := pathContainedInRoot(resolvedRoot, resolvedPath) + if err != nil { + return "", err + } + if ok { + return resolvedRoot, nil + } + } + return "", nil +} + +func (p *FilePolicy) deniedByPath(resolvedPath string) bool { + if resolvedPath == "" || p.Scope != ScopeUpstream { + return false + } + deny := p.Deny + if deny.ConfigFile != "" && pathEqual(resolvedPath, deny.ConfigFile) { + return true + } + if deny.DataDir != "" { + if deny.DataSecretsDir != "" { + if contained, _ := pathContainedInRoot(deny.DataSecretsDir, resolvedPath); contained { + return false + } + } + if contained, _ := pathContainedInRoot(deny.DataDir, resolvedPath); contained { + return true + } + } + return false +} + +// PathWithinAllowList reports whether path passes the allow-list part of the +// policy: absolute, no raw "..", and (unless wildcard) contained in an allowed +// root after resolving symlinks. No file is opened and the deny list is not +// consulted; it answers only "would secret_file_dirs let this path through". +func (p *FilePolicy) PathWithinAllowList(path string) bool { + if p == nil || p.Disabled { + return false + } + if path == "" || !filepath.IsAbs(path) || containsRawDotDot(path) { + return false + } + if p.Wildcard { + return true + } + resolved, err := resolveSymlinks(path) + if err != nil { + return false + } + root, err := p.matchingRoot(resolved) + return err == nil && root != "" +} + +// ReadFileWithPolicy reads a secret file according to policy. +func ReadFileWithPolicy(path string, policy *FilePolicy) (string, error) { + if path == "" { + return "", fmt.Errorf("secret file path is empty") + } + if !filepath.IsAbs(path) { + return "", fmt.Errorf("secret file path %q must be absolute", path) + } + if err := rejectPlatformAbsolutePath(path); err != nil { + return "", err + } + if containsRawDotDot(path) { + return "", ErrSecretFileDenied + } + + resolved, err := resolveSymlinks(path) + if err != nil { + return "", ErrSecretFileDenied + } + + if policy != nil { + if policy.Disabled { + return "", ErrSecretFileDenied + } + if policy.deniedByPath(resolved) { + return "", ErrSecretFileDenied + } + if !policy.Wildcard { + root, err := policy.matchingRoot(resolved) + if err != nil { + return "", ErrSecretFileDenied + } + if root == "" { + return "", ErrSecretFileDenied + } + return readRegularFileFromRoot(policy, root, resolved) + } + } + return readRegularFileAt(policy, resolved) +} + +func readRegularFileFromRoot(policy *FilePolicy, rootPath, resolvedPath string) (string, error) { + rel, err := filepath.Rel(rootPath, resolvedPath) + if err != nil { + return "", ErrSecretFileDenied + } + rel = filepath.ToSlash(strings.TrimPrefix(rel, string(filepath.Separator))) + if rel == ".." || strings.HasPrefix(rel, "../") || rel == "" { + return "", ErrSecretFileDenied + } + rel = strings.TrimSuffix(rel, "/") + if rel == "" { + return "", ErrSecretFileDenied + } + + root, err := os.OpenRoot(rootPath) + if err != nil { + return "", ErrSecretFileDenied + } + defer root.Close() + + invokeBeforeSecretOpenHook() + + f, err := openSecretInRoot(root, rel) + if err != nil { + return "", ErrSecretFileDenied + } + defer f.Close() + + return readOpenedSecret(policy, f, resolvedPath) +} + +func readRegularFileAt(policy *FilePolicy, path string) (string, error) { + invokeBeforeSecretOpenHook() + f, err := openSecretPath(path) + if err != nil { + if policy != nil && (policy.Scope == ScopeUpstream || !policy.Wildcard) { + return "", ErrSecretFileDenied + } + return "", fmt.Errorf("cannot read secret file %q: %w", path, unwrapPathError(err)) + } + defer f.Close() + return readOpenedSecret(policy, f, path) +} + +func readOpenedSecret(policy *FilePolicy, f *os.File, labelPath string) (string, error) { + info, err := f.Stat() + if err != nil { + if policy != nil && policy.Scope == ScopeUpstream { + return "", ErrSecretFileDenied + } + return "", fmt.Errorf("cannot read secret file %q: %w", labelPath, unwrapPathError(err)) + } + if !info.Mode().IsRegular() { + if policy != nil && policy.Scope == ScopeUpstream { + return "", ErrSecretFileDenied + } + return "", fmt.Errorf("secret file %q is not a regular file", labelPath) + } + if policy != nil && policy.deniedByHandleAtRead(f, info) { + return "", ErrSecretFileDenied + } + // An upstream read refuses a file with more than one hard link. The + // identity check above compares the handle with the inodes the proxy files + // have now; a link made to an earlier inode (SaveConfig renames a new file + // over mcp_config.json, the old inode still holds api_key) or to a file + // outside the listed state directories would pass it. Secret files have no + // reason to be hard-linked, so the link count closes the whole class. + if policy != nil && policy.Scope == ScopeUpstream { + n, err := handleLinkCount(f, info) + if err != nil || n > 1 { + return "", ErrSecretFileDenied + } + } + return readSecretFromFile(f, labelPath) +} + +func readSecretFromFile(f *os.File, labelPath string) (string, error) { + info, err := f.Stat() + if err != nil { + return "", fmt.Errorf("cannot read secret file %q: %w", labelPath, unwrapPathError(err)) + } + if !info.Mode().IsRegular() { + return "", fmt.Errorf("secret file %q is not a regular file", labelPath) + } + + data, err := io.ReadAll(io.LimitReader(f, MaxSecretFileBytes+1)) + if err != nil { + return "", fmt.Errorf("cannot read secret file %q: %w", labelPath, unwrapPathError(err)) + } + if len(data) > MaxSecretFileBytes { + return "", fmt.Errorf("secret file %q is larger than %d bytes", labelPath, MaxSecretFileBytes) + } + if bytes.IndexByte(data, 0) >= 0 { + return "", fmt.Errorf("secret file %q contains a NUL byte", labelPath) + } + + switch { + case bytes.HasSuffix(data, []byte("\r\n")): + data = data[:len(data)-2] + case bytes.HasSuffix(data, []byte("\n")): + data = data[:len(data)-1] + } + return string(data), nil +} diff --git a/internal/secret/file_policy_security_test.go b/internal/secret/file_policy_security_test.go new file mode 100644 index 000000000..40dedd16d --- /dev/null +++ b/internal/secret/file_policy_security_test.go @@ -0,0 +1,88 @@ +//go:build unix + +package secret + +import ( + "os" + "path/filepath" + "syscall" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestReadFileWithPolicy_AdminKeyInsideAllowedRootDenied(t *testing.T) { + root := t.TempDir() + allowed := filepath.Join(root, "secrets") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + admin := filepath.Join(root, "admin-key") + require.NoError(t, os.WriteFile(admin, []byte("admin\n"), 0o600)) + link := filepath.Join(allowed, "via-symlink") + require.NoError(t, os.Symlink(admin, link)) + + policy := &FilePolicy{ + AllowedRoots: []string{allowed}, + Scope: ScopeUpstream, + Deny: DenyPaths{ + AdminKeyPaths: []string{admin}, + }, + } + + _, err := ReadFileWithPolicy(link, policy) + require.ErrorIs(t, err, ErrSecretFileDenied) +} + +func TestReadFileWithPolicy_HardlinkToConfigDenied(t *testing.T) { + root := t.TempDir() + allowed := filepath.Join(root, "secrets") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + cfg := filepath.Join(root, "mcp_config.json") + require.NoError(t, os.WriteFile(cfg, []byte("x"), 0o600)) + hard := filepath.Join(allowed, "alias") + require.NoError(t, os.Link(cfg, hard)) + + policy := &FilePolicy{ + AllowedRoots: []string{allowed}, + Scope: ScopeUpstream, + Deny: DenyPaths{ + ConfigFile: cfg, + }, + } + _, err := ReadFileWithPolicy(hard, policy) + require.ErrorIs(t, err, ErrSecretFileDenied) +} + +func TestReadFileWithPolicy_FIFOInAllowedRootDoesNotHang(t *testing.T) { + root := t.TempDir() + allowed := filepath.Join(root, "secrets") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + fifo := filepath.Join(allowed, "token.fifo") + require.NoError(t, syscall.Mkfifo(fifo, 0o600)) + policy := &FilePolicy{AllowedRoots: []string{allowed}, Scope: ScopeUpstream} + + done := make(chan error, 1) + go func() { _, err := ReadFileWithPolicy(fifo, policy); done <- err }() + select { + case err := <-done: + require.Error(t, err) + case <-time.After(3 * time.Second): + t.Fatal("ReadFileWithPolicy blocked on a FIFO") + } +} + +func TestReadFileWithPolicy_ParentDirSymlinkEscapeDenied(t *testing.T) { + root := t.TempDir() + allowed := filepath.Join(root, "secrets") + outside := filepath.Join(root, "outside") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + require.NoError(t, os.Mkdir(outside, 0o700)) + secret := filepath.Join(outside, "key") + require.NoError(t, os.WriteFile(secret, []byte("stolen\n"), 0o600)) + // key -> ..data/key style escape via symlink to outside file + require.NoError(t, os.Symlink(secret, filepath.Join(allowed, "escape"))) + + policy := &FilePolicy{AllowedRoots: []string{allowed}, Scope: ScopeUpstream} + _, err := ReadFileWithPolicy(filepath.Join(allowed, "escape"), policy) + require.ErrorIs(t, err, ErrSecretFileDenied) +} diff --git a/internal/secret/file_policy_stale_deny_test.go b/internal/secret/file_policy_stale_deny_test.go new file mode 100644 index 000000000..df905b220 --- /dev/null +++ b/internal/secret/file_policy_stale_deny_test.go @@ -0,0 +1,142 @@ +//go:build unix + +package secret + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestReadFileWithPolicy_RefusesHardlinkAfterConfigRename(t *testing.T) { + root := t.TempDir() + allowed := filepath.Join(root, "secrets") + cfgDir := filepath.Join(root, "data") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + require.NoError(t, os.MkdirAll(cfgDir, 0o700)) + cfgPath := filepath.Join(cfgDir, "mcp_config.json") + require.NoError(t, os.WriteFile(cfgPath, []byte("{}"), 0o600)) + + policy := &FilePolicy{ + AllowedRoots: []string{allowed}, + Scope: ScopeUpstream, + Deny: DenyPaths{ConfigFile: cfgPath}, + } + + tmp := cfgPath + ".new" + require.NoError(t, os.WriteFile(tmp, []byte(`{"x":1}`), 0o600)) + require.NoError(t, os.Rename(tmp, cfgPath)) + + link := filepath.Join(allowed, "cfg-link") + require.NoError(t, os.Link(cfgPath, link)) + _, err := ReadFileWithPolicy(link, policy) + require.ErrorIs(t, err, ErrSecretFileDenied) +} + +func TestReadFileWithPolicy_RefusesHardlinkToConfigDB(t *testing.T) { + root := t.TempDir() + allowed := filepath.Join(root, "secrets") + dataDir := filepath.Join(root, "data") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + require.NoError(t, os.MkdirAll(dataDir, 0o700)) + db := filepath.Join(dataDir, "config.db") + require.NoError(t, os.WriteFile(db, []byte("db"), 0o600)) + + policy := &FilePolicy{ + AllowedRoots: []string{allowed}, + Scope: ScopeUpstream, + Deny: DenyPaths{DataDir: dataDir}, + } + link := filepath.Join(allowed, "db-link") + require.NoError(t, os.Link(db, link)) + _, err := ReadFileWithPolicy(link, policy) + require.ErrorIs(t, err, ErrSecretFileDenied) +} + +// A hardlink made before a save keeps pointing at the old config inode (which +// still holds api_key) after SaveConfig's temp-file + rename gives the live +// config a new inode. The deny list only knows the new inode, so the link +// count is what refuses it. +func TestReadFileWithPolicy_RefusesHardlinkToEarlierConfigInode(t *testing.T) { + root := t.TempDir() + allowed := filepath.Join(root, "secrets") + cfgDir := filepath.Join(root, "data") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + require.NoError(t, os.MkdirAll(cfgDir, 0o700)) + cfgPath := filepath.Join(cfgDir, "mcp_config.json") + require.NoError(t, os.WriteFile(cfgPath, []byte(`{"api_key":"old"}`), 0o600)) + + policy := &FilePolicy{ + AllowedRoots: []string{allowed}, + Scope: ScopeUpstream, + Deny: DenyPaths{ConfigFile: cfgPath, DataDir: cfgDir}, + } + + link := filepath.Join(allowed, "cfg-link") + require.NoError(t, os.Link(cfgPath, link)) + + // SaveConfig: note the old identity, write a temp file, rename it over + // the config. After the rename the old inode has one link (cfg-link), so + // the link count alone cannot see it. + NoteSupersededProxyFile(cfgPath) + tmp := cfgPath + ".tmp" + require.NoError(t, os.WriteFile(tmp, []byte(`{"api_key":"new"}`), 0o600)) + require.NoError(t, os.Rename(tmp, cfgPath)) + + _, err := ReadFileWithPolicy(link, policy) + require.ErrorIs(t, err, ErrSecretFileDenied) + + // Wildcard mode refuses it too. + wild := &FilePolicy{Wildcard: true, Scope: ScopeUpstream, Deny: policy.Deny} + _, err = ReadFileWithPolicy(link, wild) + require.ErrorIs(t, err, ErrSecretFileDenied) +} + +// logs/ is outside the per-file identity deny list; a hardlink into it is +// refused by the link count. +func TestReadFileWithPolicy_RefusesHardlinkIntoLogs(t *testing.T) { + root := t.TempDir() + allowed := filepath.Join(root, "secrets") + dataDir := filepath.Join(root, "data") + logs := filepath.Join(dataDir, "logs") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + require.NoError(t, os.MkdirAll(logs, 0o700)) + logFile := filepath.Join(logs, "main.log") + require.NoError(t, os.WriteFile(logFile, []byte("log line"), 0o600)) + + policy := &FilePolicy{ + AllowedRoots: []string{allowed}, + Scope: ScopeUpstream, + Deny: DenyPaths{DataDir: dataDir}, + } + link := filepath.Join(allowed, "log-link") + require.NoError(t, os.Link(logFile, link)) + _, err := ReadFileWithPolicy(link, policy) + require.ErrorIs(t, err, ErrSecretFileDenied) +} + +// The link-count rule is upstream-only: a proxy-scope read of a hard-linked +// file still works, and a plain upstream secret (one link) still works. +func TestReadFileWithPolicy_LinkCountRuleScope(t *testing.T) { + root := t.TempDir() + allowed := filepath.Join(root, "secrets") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + plain := filepath.Join(allowed, "token") + require.NoError(t, os.WriteFile(plain, []byte("v1\n"), 0o600)) + + up := &FilePolicy{AllowedRoots: []string{allowed}, Scope: ScopeUpstream} + got, err := ReadFileWithPolicy(plain, up) + require.NoError(t, err) + require.Equal(t, "v1", got) + + require.NoError(t, os.Link(plain, filepath.Join(allowed, "token2"))) + _, err = ReadFileWithPolicy(plain, up) + require.ErrorIs(t, err, ErrSecretFileDenied) + + proxy := &FilePolicy{AllowedRoots: []string{allowed}, Scope: ScopeProxy} + got, err = ReadFileWithPolicy(plain, proxy) + require.NoError(t, err) + require.Equal(t, "v1", got) +} diff --git a/internal/secret/file_policy_swap_test.go b/internal/secret/file_policy_swap_test.go new file mode 100644 index 000000000..07438ad90 --- /dev/null +++ b/internal/secret/file_policy_swap_test.go @@ -0,0 +1,77 @@ +//go:build unix + +package secret + +import ( + "os" + "path/filepath" + "syscall" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestReadFileWithPolicy_SwapHooks(t *testing.T) { + root := t.TempDir() + allowed := filepath.Join(root, "secrets") + outside := filepath.Join(root, "outside") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + require.NoError(t, os.Mkdir(outside, 0o700)) + target := filepath.Join(allowed, "token") + require.NoError(t, os.WriteFile(target, []byte("ok\n"), 0o600)) + + policy := &FilePolicy{AllowedRoots: []string{allowed}, Scope: ScopeUpstream} + + t.Run("final file swapped to symlink outside root", func(t *testing.T) { + outFile := filepath.Join(outside, "outer") + require.NoError(t, os.WriteFile(outFile, []byte("stolen\n"), 0o600)) + SetBeforeSecretOpenHookForTest(func() { + require.NoError(t, os.Remove(target)) + require.NoError(t, os.Symlink(outFile, target)) + }) + t.Cleanup(func() { SetBeforeSecretOpenHookForTest(nil) }) + _, err := ReadFileWithPolicy(target, policy) + require.ErrorIs(t, err, ErrSecretFileDenied) + }) + + t.Run("final file swapped to admin key inside root", func(t *testing.T) { + admin := filepath.Join(allowed, "admin") + require.NoError(t, os.WriteFile(admin, []byte("key\n"), 0o600)) + p2 := *policy + p2.Deny.AdminKeyPaths = []string{admin} + require.NoError(t, os.WriteFile(target, []byte("ok\n"), 0o600)) + SetBeforeSecretOpenHookForTest(func() { + require.NoError(t, os.Remove(target)) + require.NoError(t, os.Symlink(admin, target)) + }) + t.Cleanup(func() { SetBeforeSecretOpenHookForTest(nil) }) + _, err := ReadFileWithPolicy(target, &p2) + require.ErrorIs(t, err, ErrSecretFileDenied) + }) + + t.Run("parent directory swapped to symlink outside root", func(t *testing.T) { + inner := filepath.Join(root, "inner", "secrets") + require.NoError(t, os.MkdirAll(inner, 0o700)) + innerFile := filepath.Join(inner, "k") + require.NoError(t, os.WriteFile(innerFile, []byte("x\n"), 0o600)) + p3 := &FilePolicy{AllowedRoots: []string{inner}, Scope: ScopeUpstream, Wildcard: true} + SetBeforeSecretOpenHookForTest(func() { + require.NoError(t, os.RemoveAll(filepath.Join(root, "inner"))) + require.NoError(t, os.Symlink(outside, filepath.Join(root, "inner"))) + }) + t.Cleanup(func() { SetBeforeSecretOpenHookForTest(nil) }) + _, err := ReadFileWithPolicy(innerFile, p3) + require.ErrorIs(t, err, ErrSecretFileDenied) + }) + + t.Run("final file swapped to FIFO", func(t *testing.T) { + require.NoError(t, os.WriteFile(target, []byte("ok\n"), 0o600)) + SetBeforeSecretOpenHookForTest(func() { + require.NoError(t, os.Remove(target)) + require.NoError(t, syscall.Mkfifo(target, 0o600)) + }) + t.Cleanup(func() { SetBeforeSecretOpenHookForTest(nil) }) + _, err := ReadFileWithPolicy(target, policy) + require.ErrorIs(t, err, ErrSecretFileDenied) + }) +} diff --git a/internal/secret/file_policy_test.go b/internal/secret/file_policy_test.go new file mode 100644 index 000000000..70aac4b78 --- /dev/null +++ b/internal/secret/file_policy_test.go @@ -0,0 +1,161 @@ +package secret + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestReadFileWithPolicy_AllowedAndRefused(t *testing.T) { + root := t.TempDir() + allowed := filepath.Join(root, "secrets") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + keyPath := filepath.Join(allowed, "token") + require.NoError(t, os.WriteFile(keyPath, []byte("secret\n"), 0o600)) + + outside := filepath.Join(t.TempDir(), "outside") + require.NoError(t, os.WriteFile(outside, []byte("nope\n"), 0o600)) + + policy := &FilePolicy{ + AllowedRoots: []string{allowed}, + Scope: ScopeUpstream, + } + + got, err := ReadFileWithPolicy(keyPath, policy) + require.NoError(t, err) + assert.Equal(t, "secret", got) + + _, err = ReadFileWithPolicy(outside, policy) + require.ErrorIs(t, err, ErrSecretFileDenied) + + _, err = ReadFileWithPolicy(filepath.Join(allowed, "..", "..", "etc", "passwd"), policy) + require.ErrorIs(t, err, ErrSecretFileDenied) +} + +func TestReadFileWithPolicy_OptOutModes(t *testing.T) { + path := writeSecretFile(t, "x\n") + t.Run("wildcard", func(t *testing.T) { + _, err := ReadFileWithPolicy(path, NewWildcardFilePolicy(ScopeUpstream)) + require.NoError(t, err) + }) + t.Run("disabled", func(t *testing.T) { + _, err := ReadFileWithPolicy(path, NewDisabledFilePolicy(ScopeUpstream)) + require.ErrorIs(t, err, ErrSecretFileDenied) + }) +} + +func TestReadFileWithPolicy_DenyPathsEvenInWildcard(t *testing.T) { + root := t.TempDir() + cfg := filepath.Join(root, "mcp_config.json") + require.NoError(t, os.WriteFile(cfg, []byte("x"), 0o600)) + require.NoError(t, os.WriteFile(filepath.Join(root, "config.db"), []byte("db"), 0o600)) + + policy := NewWildcardFilePolicy(ScopeUpstream) + policy.Deny = DenyPaths{ + ConfigFile: cfg, + DataDir: root, + DataSecretsDir: filepath.Join(root, "secrets"), + } + policy.Deny.AdminKeyPaths = nil + + _, err := ReadFileWithPolicy(cfg, policy) + require.ErrorIs(t, err, ErrSecretFileDenied) + _, err = ReadFileWithPolicy(filepath.Join(root, "config.db"), policy) + require.ErrorIs(t, err, ErrSecretFileDenied) + + secrets := filepath.Join(root, "secrets") + require.NoError(t, os.MkdirAll(secrets, 0o700)) + okPath := filepath.Join(secrets, "key") + require.NoError(t, os.WriteFile(okPath, []byte("k\n"), 0o600)) + _, err = ReadFileWithPolicy(okPath, policy) + require.NoError(t, err) +} + +func TestReadFileWithPolicy_ErrorTextDoesNotLeakPath(t *testing.T) { + root := t.TempDir() + allowed := filepath.Join(root, "secrets") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + policy := &FilePolicy{AllowedRoots: []string{allowed}, Scope: ScopeUpstream} + + outside := filepath.Join(root, "nope") + _, err := ReadFileWithPolicy(outside, policy) + require.ErrorIs(t, err, ErrSecretFileDenied) + assert.Equal(t, ErrSecretFileDenied.Error(), err.Error()) + assert.NotContains(t, err.Error(), outside) + + missing := filepath.Join(allowed, "missing") + _, err = ReadFileWithPolicy(missing, policy) + require.ErrorIs(t, err, ErrSecretFileDenied) + assert.Equal(t, err.Error(), ErrSecretFileDenied.Error()) +} + +func TestPathContainedInRoot_PrefixTrap(t *testing.T) { + root := t.TempDir() + allowed := filepath.Join(root, "secrets") + trap := filepath.Join(root, "secrets-old") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + require.NoError(t, os.MkdirAll(trap, 0o700)) + file := filepath.Join(trap, "x") + require.NoError(t, os.WriteFile(file, []byte("a"), 0o600)) + + policy := &FilePolicy{AllowedRoots: []string{allowed}, Scope: ScopeUpstream} + _, err := ReadFileWithPolicy(file, policy) + require.ErrorIs(t, err, ErrSecretFileDenied) +} + +func TestReadFileWithPolicy_SymlinkEscape(t *testing.T) { + root := t.TempDir() + allowed := filepath.Join(root, "secrets") + outside := filepath.Join(root, "outside") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + require.NoError(t, os.Mkdir(outside, 0o700)) + target := filepath.Join(outside, "key") + require.NoError(t, os.WriteFile(target, []byte("stolen\n"), 0o600)) + link := filepath.Join(allowed, "link") + require.NoError(t, os.Symlink(target, link)) + + policy := &FilePolicy{AllowedRoots: []string{allowed}, Scope: ScopeUpstream} + _, err := ReadFileWithPolicy(link, policy) + require.ErrorIs(t, err, ErrSecretFileDenied) +} + +func TestReadFileWithPolicy_KubernetesLayout(t *testing.T) { + root := t.TempDir() + mount := filepath.Join(root, "mount") + require.NoError(t, os.MkdirAll(mount, 0o700)) + ts := filepath.Join(mount, "..2026_10_21_00_00_00.000000000") + require.NoError(t, os.MkdirAll(ts, 0o700)) + real := filepath.Join(ts, "key") + require.NoError(t, os.WriteFile(real, []byte("kube\n"), 0o600)) + require.NoError(t, os.Symlink(ts, filepath.Join(mount, "..data"))) + require.NoError(t, os.Symlink(filepath.Join("..data", "key"), filepath.Join(mount, "key"))) + + policy := &FilePolicy{AllowedRoots: []string{mount}, Scope: ScopeUpstream} + got, err := ReadFileWithPolicy(filepath.Join(mount, "key"), policy) + require.NoError(t, err) + assert.Equal(t, "kube", got) +} + +func TestReadFileWithPolicy_TraversalInPath(t *testing.T) { + root := t.TempDir() + allowed := filepath.Join(root, "secrets") + outside := filepath.Join(root, "outside") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + require.NoError(t, os.MkdirAll(outside, 0o700)) + outFile := filepath.Join(outside, "passwd") + require.NoError(t, os.WriteFile(outFile, []byte("x\n"), 0o600)) + traversal := filepath.Join(allowed, "..", "outside", "passwd") + policy := &FilePolicy{AllowedRoots: []string{allowed}, Scope: ScopeUpstream} + _, err := ReadFileWithPolicy(traversal, policy) + require.ErrorIs(t, err, ErrSecretFileDenied) +} + +func TestIsReservedMCPProxyEnv(t *testing.T) { + assert.True(t, ReservedMCPProxyEnvName("MCPPROXY_API_KEY", "linux")) + assert.True(t, ReservedMCPProxyEnvName("MCPPROXY_FOO", "linux")) + assert.False(t, ReservedMCPProxyEnvName("OTHER", "linux")) + assert.False(t, ReservedMCPProxyEnvName("MCPROXY_API_KEY", "linux")) +} diff --git a/internal/secret/file_policy_unix.go b/internal/secret/file_policy_unix.go new file mode 100644 index 000000000..5ad18a01c --- /dev/null +++ b/internal/secret/file_policy_unix.go @@ -0,0 +1,7 @@ +//go:build !windows + +package secret + +func rejectPlatformAbsolutePath(path string) error { + return nil +} diff --git a/internal/secret/file_policy_windows.go b/internal/secret/file_policy_windows.go new file mode 100644 index 000000000..494531202 --- /dev/null +++ b/internal/secret/file_policy_windows.go @@ -0,0 +1,80 @@ +//go:build windows + +package secret + +import ( + "fmt" + "path/filepath" + "strings" +) + +func rejectPlatformAbsolutePath(path string) error { + if isForbiddenDeviceNamespace(path) { + return fmt.Errorf("secret file path %q uses a forbidden prefix", path) + } + if isForbiddenUNCPath(path) { + return fmt.Errorf("secret file path %q uses a forbidden prefix", path) + } + vol := filepath.VolumeName(path) + if vol != "" && len(vol) == 2 && vol[1] == ':' { + afterVol := strings.TrimPrefix(path, vol) + if afterVol == "" { + return fmt.Errorf("secret file path %q must be absolute", path) + } + if afterVol[0] != '\\' && afterVol[0] != '/' { + // Drive-relative path such as C:foo (no root after the colon). + return fmt.Errorf("secret file path %q must be absolute", path) + } + } + if strings.HasPrefix(path, `\`) && !strings.HasPrefix(path, `\\`) { + return fmt.Errorf("secret file path %q must be absolute", path) + } + return nil +} + +// isForbiddenDeviceNamespace reports Win32 device-namespace spellings (\\?\, //?/, +// and mixed separator forms) that must not be used for secret file reads. +func isForbiddenDeviceNamespace(path string) bool { + if len(path) < 4 { + return false + } + pairs := [][2]byte{{'\\', '\\'}, {'/', '/'}, {'\\', '/'}, {'/', '\\'}} + for _, p := range pairs { + if path[0] == p[0] && path[1] == p[1] { + if (path[2] == '?' || path[2] == '.') && (path[3] == '\\' || path[3] == '/') { + return true + } + } + } + return false +} + +// isForbiddenUNCPath reports UNC paths (\\server\share, //server/share, and +// mixed separator spellings). VolumeName returns a UNC prefix longer than a +// drive letter, or starting with two separators. +func isForbiddenUNCPath(path string) bool { + vol := filepath.VolumeName(path) + if vol != "" { + if len(vol) > 2 { + return true + } + if len(vol) >= 2 && vol[0] == '\\' && vol[1] == '\\' { + return true + } + } + if len(path) < 3 { + return false + } + a, b := path[0], path[1] + if (a != '\\' && a != '/') || (b != '\\' && b != '/') { + return false + } + if a == b && (path[2] == '?' || path[2] == '.') { + return false // device namespace + } + if a == b { + return true // \\server or //server + } + // Mixed // or \/ at the start (UNC spelling). + return true +} diff --git a/internal/secret/file_policy_windows_test.go b/internal/secret/file_policy_windows_test.go new file mode 100644 index 000000000..652b3b0c1 --- /dev/null +++ b/internal/secret/file_policy_windows_test.go @@ -0,0 +1,44 @@ +//go:build windows + +package secret + +import ( + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestRejectPlatformAbsolutePath_WindowsDriveAbsolute(t *testing.T) { + root := t.TempDir() + abs := filepath.Join(root, "key") + require.NoError(t, rejectPlatformAbsolutePath(abs)) + assert.NoError(t, rejectPlatformAbsolutePath(`C:\ProgramData\mcpproxy\key`)) + assert.NoError(t, rejectPlatformAbsolutePath(`C:/ProgramData/mcpproxy/key`)) + require.Error(t, rejectPlatformAbsolutePath(`C:relative\key`)) +} + +func TestRejectPlatformAbsolutePath_ForbidsUNCAndDevice(t *testing.T) { + unc := []string{ + `\\server\share\secret`, + `//server/share/secret`, + `\//server/share/secret`, + `/\server\share\secret`, + } + for _, p := range unc { + require.Error(t, rejectPlatformAbsolutePath(p), p) + } + + dev := []string{ + `\\?\C:\secret`, + `\\.\CON`, + `//?/C:/secret`, + `//./CON`, + `\\?/C:\secret`, + `/\?\C:\secret`, + } + for _, p := range dev { + require.Error(t, rejectPlatformAbsolutePath(p), p) + } +} diff --git a/internal/secret/file_provider.go b/internal/secret/file_provider.go index b07882718..9f400f10a 100644 --- a/internal/secret/file_provider.go +++ b/internal/secret/file_provider.go @@ -18,11 +18,13 @@ const ( // of ReadFile. // // The file is read each time a reference is resolved; nothing is cached or logged. -type FileProvider struct{} +type FileProvider struct { + policy *FilePolicy +} // NewFileProvider creates a new file provider. -func NewFileProvider() *FileProvider { - return &FileProvider{} +func NewFileProvider(policy *FilePolicy) *FileProvider { + return &FileProvider{policy: policy} } // CanResolve returns true if this provider can handle the given secret type. @@ -37,7 +39,7 @@ func (p *FileProvider) Resolve(_ context.Context, ref Ref) (string, error) { if !p.CanResolve(ref.Type) { return "", fmt.Errorf("file provider cannot resolve secret type: %s", ref.Type) } - value, err := ReadFile(ref.Name) + value, err := ReadFileWithPolicy(ref.Name, p.policy) if err != nil { return "", err } diff --git a/internal/secret/file_provider_test.go b/internal/secret/file_provider_test.go index 447abceff..862d327cc 100644 --- a/internal/secret/file_provider_test.go +++ b/internal/secret/file_provider_test.go @@ -12,7 +12,7 @@ import ( ) func TestFileProvider_Resolve(t *testing.T) { - p := NewFileProvider() + p := NewFileProvider(NewWildcardFilePolicy(ScopeUpstream)) assert.True(t, p.CanResolve("file")) assert.False(t, p.CanResolve("env")) assert.True(t, p.IsAvailable()) @@ -36,7 +36,7 @@ func TestFileProvider_Resolve(t *testing.T) { } func TestFileProvider_ReadsTheFileEachTime(t *testing.T) { - p := NewFileProvider() + p := NewFileProvider(NewWildcardFilePolicy(ScopeUpstream)) path := writeSecretFile(t, "v1") ref := Ref{Type: "file", Name: path} @@ -51,7 +51,7 @@ func TestFileProvider_ReadsTheFileEachTime(t *testing.T) { } func TestResolver_ExpandsFileReferences(t *testing.T) { - r := NewResolver() + r := NewTestWildcardResolver() lf := writeSecretFile(t, "same-value\n") crlf := writeSecretFile(t, "same-value\r\n") @@ -68,7 +68,7 @@ func TestResolver_ExpandsFileReferences(t *testing.T) { } func TestResolver_FileReferenceErrorsNameTheReferenceNotTheValue(t *testing.T) { - r := NewResolver() + r := NewTestWildcardResolver() const sentinel = "SENTINEL-p3Wv9Qd" missing := filepath.Join(t.TempDir(), "missing") diff --git a/internal/secret/file_read.go b/internal/secret/file_read.go index 7db38bfc9..0ca05e51b 100644 --- a/internal/secret/file_read.go +++ b/internal/secret/file_read.go @@ -1,12 +1,8 @@ package secret import ( - "bytes" "errors" - "fmt" - "io" "os" - "path/filepath" ) // MaxSecretFileBytes caps how much of a secret file is read. A token, a @@ -35,58 +31,11 @@ const MaxSecretFileBytes = 64 * 1024 // An empty result is returned as "" with no error, so a caller can decide // whether empty is acceptable for its field. Errors name the path and the // reason and never include any of the file's content. +// ReadFile reads a secret without secret_file_dirs constraints. Callers that +// enforce policy (the file provider, or MCPPROXY_API_KEY_FILE after separate +// admin-path checks) use ReadFileWithPolicy instead. func ReadFile(path string) (string, error) { - if path == "" { - return "", errors.New("secret file path is empty") - } - if !filepath.IsAbs(path) { - return "", fmt.Errorf("secret file path %q must be absolute", path) - } - - // Check the type before opening: open(2) on a FIFO blocks until a writer - // appears, and on some devices it has side effects, so a mis-pointed path - // must be refused without ever reaching open. The check is repeated on the - // open descriptor so a path swapped in between is still refused. - if info, err := os.Stat(path); err != nil { - return "", fmt.Errorf("cannot read secret file %q: %w", path, unwrapPathError(err)) - } else if !info.Mode().IsRegular() { - return "", fmt.Errorf("secret file %q is not a regular file", path) - } - - f, err := os.Open(path) - if err != nil { - return "", fmt.Errorf("cannot read secret file %q: %w", path, unwrapPathError(err)) - } - defer f.Close() - - info, err := f.Stat() - if err != nil { - return "", fmt.Errorf("cannot read secret file %q: %w", path, unwrapPathError(err)) - } - if !info.Mode().IsRegular() { - return "", fmt.Errorf("secret file %q is not a regular file", path) - } - - // Read one byte past the cap so an oversized file is detected from what - // was read, not from a size that may have changed since Stat. - data, err := io.ReadAll(io.LimitReader(f, MaxSecretFileBytes+1)) - if err != nil { - return "", fmt.Errorf("cannot read secret file %q: %w", path, unwrapPathError(err)) - } - if len(data) > MaxSecretFileBytes { - return "", fmt.Errorf("secret file %q is larger than %d bytes", path, MaxSecretFileBytes) - } - if bytes.IndexByte(data, 0) >= 0 { - return "", fmt.Errorf("secret file %q contains a NUL byte", path) - } - - switch { - case bytes.HasSuffix(data, []byte("\r\n")): - data = data[:len(data)-2] - case bytes.HasSuffix(data, []byte("\n")): - data = data[:len(data)-1] - } - return string(data), nil + return ReadFileWithPolicy(path, NewWildcardFilePolicy(ScopeProxy)) } // unwrapPathError drops the "open :" prefix of an *os.PathError so the diff --git a/internal/secret/keyring_available_test.go b/internal/secret/keyring_available_test.go index 918e336ef..2a16b3303 100644 --- a/internal/secret/keyring_available_test.go +++ b/internal/secret/keyring_available_test.go @@ -132,7 +132,7 @@ func TestKeyringProvider_IsAvailableWithReason_ProbeFails(t *testing.T) { // registered keyring provider's reasoned probe. func TestResolver_KeyringAvailability(t *testing.T) { t.Setenv("CI", "true") - r := NewResolver() + r := NewTestWildcardResolver() ok, reason := r.KeyringAvailability() if ok { t.Fatal("expected unavailable in CI") diff --git a/internal/secret/keyring_write_opt_in_test.go b/internal/secret/keyring_write_opt_in_test.go index 1f4395438..6a4fc59a1 100644 --- a/internal/secret/keyring_write_opt_in_test.go +++ b/internal/secret/keyring_write_opt_in_test.go @@ -103,7 +103,7 @@ func TestResolver_KeyringWriteOptInRequired(t *testing.T) { t.Fatalf("KeyringWriteOptInRequired() = %v, want %v on %s", got, want, runtime.GOOS) } - r.RegisterProvider("keyring", NewEnvProvider()) + r.RegisterProvider("keyring", NewEnvProvider(false)) if r.KeyringWriteOptInRequired() { t.Fatal("a provider without a write gate requires no opt-in") } diff --git a/internal/secret/link_count_unix.go b/internal/secret/link_count_unix.go new file mode 100644 index 000000000..1da8da0e8 --- /dev/null +++ b/internal/secret/link_count_unix.go @@ -0,0 +1,19 @@ +//go:build unix + +package secret + +import ( + "fmt" + "os" + "syscall" +) + +// handleLinkCount returns the number of hard links of the opened file, taken +// from the handle (fstat), not from a path. +func handleLinkCount(_ *os.File, info os.FileInfo) (uint64, error) { + st, ok := info.Sys().(*syscall.Stat_t) + if !ok || st == nil { + return 0, fmt.Errorf("link count unavailable") + } + return uint64(st.Nlink), nil //nolint:unconvert // Nlink is uint16 on darwin, uint64 on linux +} diff --git a/internal/secret/link_count_windows.go b/internal/secret/link_count_windows.go new file mode 100644 index 000000000..1821178d3 --- /dev/null +++ b/internal/secret/link_count_windows.go @@ -0,0 +1,18 @@ +//go:build windows + +package secret + +import ( + "os" + "syscall" +) + +// handleLinkCount returns the number of hard links of the opened file, read +// from the handle with GetFileInformationByHandle. +func handleLinkCount(f *os.File, _ os.FileInfo) (uint64, error) { + var d syscall.ByHandleFileInformation + if err := syscall.GetFileInformationByHandle(syscall.Handle(f.Fd()), &d); err != nil { + return 0, err + } + return uint64(d.NumberOfLinks), nil +} diff --git a/internal/secret/mcpproxy_env_scope_test.go b/internal/secret/mcpproxy_env_scope_test.go new file mode 100644 index 000000000..54328e097 --- /dev/null +++ b/internal/secret/mcpproxy_env_scope_test.go @@ -0,0 +1,28 @@ +package secret + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestMCPProxyEnvGuard_ProxyScopeAllowsUpstreamRefuses(t *testing.T) { + const ref = "${env:MCPPROXY_SCOPE_TEST_VAR}" + t.Setenv("MCPPROXY_SCOPE_TEST_VAR", "ok") + + proxy := NewResolverWithOptions(ResolverOptions{ + Scope: ScopeProxy, + FilePolicy: NewWildcardFilePolicy(ScopeProxy), + }) + got, err := proxy.ExpandSecretRefs(context.Background(), ref) + require.NoError(t, err) + require.Equal(t, "ok", got) + + upstream := NewResolverWithOptions(ResolverOptions{ + Scope: ScopeUpstream, + FilePolicy: NewWildcardFilePolicy(ScopeUpstream), + }) + _, err = upstream.ExpandSecretRefs(context.Background(), ref) + require.ErrorIs(t, err, ErrReservedEnvVar) +} diff --git a/internal/secret/open_hook.go b/internal/secret/open_hook.go new file mode 100644 index 000000000..fa3ba69dc --- /dev/null +++ b/internal/secret/open_hook.go @@ -0,0 +1,16 @@ +package secret + +// beforeSecretOpenHook runs in tests between policy checks and opening a secret +// file. Production code never sets it. +var beforeSecretOpenHook func() + +// SetBeforeSecretOpenHookForTest installs beforeSecretOpenHook. Pass nil to clear. +func SetBeforeSecretOpenHookForTest(hook func()) { + beforeSecretOpenHook = hook +} + +func invokeBeforeSecretOpenHook() { + if beforeSecretOpenHook != nil { + beforeSecretOpenHook() + } +} diff --git a/internal/secret/open_unix.go b/internal/secret/open_unix.go new file mode 100644 index 000000000..7b360a76f --- /dev/null +++ b/internal/secret/open_unix.go @@ -0,0 +1,18 @@ +//go:build unix + +package secret + +import ( + "os" + "syscall" +) + +const secretOpenFlags = os.O_RDONLY | syscall.O_NONBLOCK + +func openSecretPath(path string) (*os.File, error) { + return os.OpenFile(path, secretOpenFlags, 0) +} + +func openSecretInRoot(root *os.Root, rel string) (*os.File, error) { + return root.OpenFile(rel, secretOpenFlags, 0) +} diff --git a/internal/secret/open_windows.go b/internal/secret/open_windows.go new file mode 100644 index 000000000..ab93dd30c --- /dev/null +++ b/internal/secret/open_windows.go @@ -0,0 +1,13 @@ +//go:build windows + +package secret + +import "os" + +func openSecretPath(path string) (*os.File, error) { + return os.OpenFile(path, os.O_RDONLY, 0) +} + +func openSecretInRoot(root *os.Root, rel string) (*os.File, error) { + return root.OpenFile(rel, os.O_RDONLY, 0) +} diff --git a/internal/secret/policy.go b/internal/secret/policy.go new file mode 100644 index 000000000..188edaaac --- /dev/null +++ b/internal/secret/policy.go @@ -0,0 +1,8 @@ +package secret + +import "errors" + +// IsPolicyDenial reports whether err is a fixed upstream secret-policy refusal. +func IsPolicyDenial(err error) bool { + return errors.Is(err, ErrSecretFileDenied) || errors.Is(err, ErrReservedEnvVar) +} diff --git a/internal/secret/policy_message.go b/internal/secret/policy_message.go new file mode 100644 index 000000000..cb97160c6 --- /dev/null +++ b/internal/secret/policy_message.go @@ -0,0 +1,17 @@ +package secret + +import "errors" + +// PublicPolicyMessage returns the fixed operator-facing text for a policy denial. +func PublicPolicyMessage(err error) string { + if err == nil { + return "" + } + if errors.Is(err, ErrSecretFileDenied) { + return ErrSecretFileDenied.Error() + } + if errors.Is(err, ErrReservedEnvVar) { + return ErrReservedEnvVar.Error() + } + return ErrSecretFileDenied.Error() +} diff --git a/internal/secret/resolver.go b/internal/secret/resolver.go index 05fa4b7da..5f31dfdd8 100644 --- a/internal/secret/resolver.go +++ b/internal/secret/resolver.go @@ -7,20 +7,65 @@ import ( "strings" ) -// NewResolver creates a new secret resolver +// NewResolver returns a safe proxy-scoped resolver with file reads disabled. +// Production code must use config.BuildSecretResolver or another explicit policy; +// tests that need legacy wildcard upstream behaviour use NewTestWildcardResolver. func NewResolver() *Resolver { + return NewResolverWithOptions(ResolverOptions{ + Scope: ScopeProxy, + FilePolicy: NewDisabledFilePolicy(ScopeProxy), + }) +} + +// NewTestWildcardResolver is the pre-#1721 upstream wildcard resolver for tests only. +func NewTestWildcardResolver() *Resolver { + return NewResolverWithOptions(ResolverOptions{ + Scope: ScopeUpstream, + FilePolicy: NewWildcardFilePolicy(ScopeUpstream), + }) +} + +// NewResolverWithOptions builds a resolver for production use. +func NewResolverWithOptions(opts ResolverOptions) *Resolver { + policy := opts.FilePolicy + if policy == nil { + policy = NewWildcardFilePolicy(opts.Scope) + } + policy.Scope = opts.Scope + r := &Resolver{ - providers: make(map[string]Provider), + providers: make(map[string]Provider), + scope: opts.Scope, + filePolicy: policy, } - // Register default providers - r.RegisterProvider("env", NewEnvProvider()) - r.RegisterProvider(SecretTypeFile, NewFileProvider()) + guard := opts.Scope == ScopeUpstream + r.RegisterProvider(SecretTypeEnv, NewEnvProvider(guard)) + r.RegisterProvider(SecretTypeFile, NewFileProvider(policy)) r.RegisterProvider("keyring", NewKeyringProvider()) return r } +// Scope returns the resolver's scope. +func (r *Resolver) Scope() ResolveScope { + if r == nil { + return ScopeUpstream + } + return r.scope +} + +// FilePolicy returns a copy of the file policy, if any. +func (r *Resolver) FilePolicy() *FilePolicy { + if r == nil || r.filePolicy == nil { + return nil + } + cp := *r.filePolicy + cp.AllowedRoots = append([]string(nil), r.filePolicy.AllowedRoots...) + cp.Deny.AdminKeyPaths = append([]string(nil), r.filePolicy.Deny.AdminKeyPaths...) + return &cp +} + // RegisterProvider registers a new secret provider func (r *Resolver) RegisterProvider(secretType string, provider Provider) { r.providers[secretType] = provider diff --git a/internal/secret/resolver_options.go b/internal/secret/resolver_options.go new file mode 100644 index 000000000..1fb99bc4e --- /dev/null +++ b/internal/secret/resolver_options.go @@ -0,0 +1,42 @@ +package secret + +// ResolveScope selects which guards apply when resolving secret references. +type ResolveScope int + +const ( + // ScopeProxy resolves proxy-owned fields (api_key on load, data_dir, + // server-edition OAuth secrets). secret_file_dirs applies; the MCPPROXY_ + // environment guard does not. + ScopeProxy ResolveScope = iota + // ScopeUpstream resolves upstream server entry fields. secret_file_dirs, + // MCPPROXY_ environment guard and proxy data deny paths all apply. + ScopeUpstream +) + +// DenyPaths lists paths for cheap pre-open checks and for fresh stat-at-read +// identity checks (config, admin-key sources, data-dir files). +type DenyPaths struct { + ConfigFile string + DataDir string + DataSecretsDir string + AdminKeyPaths []string +} + +// FilePolicy governs ${file:} resolution for one resolver. +type FilePolicy struct { + // Wildcard disables the allow-list (compatibility mode). Deny paths still + // apply for ScopeUpstream. + Wildcard bool + // Disabled refuses every ${file:} reference (explicit secret_file_dirs: []). + Disabled bool + // AllowedRoots are absolute, symlink-resolved directory roots. + AllowedRoots []string + Scope ResolveScope + Deny DenyPaths +} + +// ResolverOptions configures a production resolver. +type ResolverOptions struct { + Scope ResolveScope + FilePolicy *FilePolicy +} diff --git a/internal/secret/resolver_test.go b/internal/secret/resolver_test.go index 5c1834f38..4b856a208 100644 --- a/internal/secret/resolver_test.go +++ b/internal/secret/resolver_test.go @@ -229,7 +229,7 @@ func TestResolver_AnalyzeForMigration(t *testing.T) { } func TestNewResolver(t *testing.T) { - resolver := NewResolver() + resolver := NewTestWildcardResolver() assert.NotNil(t, resolver) assert.NotNil(t, resolver.providers) diff --git a/internal/secret/struct_refs.go b/internal/secret/struct_refs.go new file mode 100644 index 000000000..af9d6e780 --- /dev/null +++ b/internal/secret/struct_refs.go @@ -0,0 +1,68 @@ +package secret + +import "reflect" + +// StructFileRefPaths returns the path of every ${file:} reference in the +// fields ExpandStructSecretsCollectErrors would expand in v, in walk order. +// It visits exactly what that walk visits (exported struct fields through +// pointers, slices, arrays, map values that are strings or interfaces holding +// strings) and nothing else, so an opaque carrier such as a struct with only +// unexported fields contributes nothing. Nothing is resolved or read. +// v must be a pointer, as for ExpandStructSecretsCollectErrors. +func StructFileRefPaths(v interface{}) []string { + var out []string + walkStructRefStrings(reflect.ValueOf(v), func(s string) { + if !IsSecretRef(s) { + return + } + for _, ref := range FindSecretRefs(s) { + if ref.Type == SecretTypeFile { + out = append(out, ref.Name) + } + } + }) + return out +} + +// walkStructRefStrings mirrors expandValueCollectErrors' traversal. +func walkStructRefStrings(v reflect.Value, fn func(string)) { + if !v.IsValid() { + return + } + if v.Kind() == reflect.Pointer { + if v.IsNil() { + return + } + walkStructRefStrings(v.Elem(), fn) + return + } + switch v.Kind() { + case reflect.String: + if v.CanSet() { + fn(v.String()) + } + case reflect.Struct: + t := v.Type() + for i := 0; i < v.NumField(); i++ { + field := v.Field(i) + if !field.CanInterface() || !t.Field(i).IsExported() { + continue + } + walkStructRefStrings(field, fn) + } + case reflect.Slice, reflect.Array: + for i := 0; i < v.Len(); i++ { + walkStructRefStrings(v.Index(i), fn) + } + case reflect.Map: + for _, key := range v.MapKeys() { + mv := v.MapIndex(key) + switch { + case mv.Kind() == reflect.String: + fn(mv.String()) + case mv.Kind() == reflect.Interface && mv.Elem().Kind() == reflect.String: + fn(mv.Elem().String()) + } + } + } +} diff --git a/internal/secret/struct_refs_test.go b/internal/secret/struct_refs_test.go new file mode 100644 index 000000000..f22eac61c --- /dev/null +++ b/internal/secret/struct_refs_test.go @@ -0,0 +1,59 @@ +package secret + +import ( + "context" + "sort" + "testing" + + "github.com/stretchr/testify/assert" +) + +type refsInner struct { + Path string + List []string +} + +type refsOpaque struct { + raw string //nolint:unused // stands in for an opaque carrier the resolver never walks +} + +type refsSample struct { + Env map[string]string + Any map[string]interface{} + Args []string + Inner *refsInner + Opaque *refsOpaque + hidden string //nolint:unused // unexported: the resolver skips it +} + +// StructFileRefPaths must see exactly the fields the resolver expands. +func TestStructFileRefPaths_MatchesResolverWalk(t *testing.T) { + newSample := func() *refsSample { + return &refsSample{ + Env: map[string]string{"A": "${file:/a}", "B": "plain"}, + Any: map[string]interface{}{"C": "${file:/c}", "N": 3}, + Args: []string{"--x", "pre ${file:/d} post"}, + Inner: &refsInner{Path: "${file:/e}", List: []string{"${file:/f}"}}, + Opaque: &refsOpaque{raw: "${file:/opaque}"}, + hidden: "${file:/hidden}", + } + } + + got := StructFileRefPaths(newSample()) + sort.Strings(got) + assert.Equal(t, []string{"/a", "/c", "/d", "/e", "/f"}, got) + + // The resolver, with ${file:} disabled, reports one error per field it + // tried; the same paths must come back. + r := NewResolverWithOptions(ResolverOptions{Scope: ScopeUpstream, FilePolicy: NewDisabledFilePolicy(ScopeUpstream)}) + var fromResolver []string + for _, e := range r.ExpandStructSecretsCollectErrors(context.Background(), newSample()) { + for _, ref := range FindSecretRefs(e.Reference) { + if ref.Type == SecretTypeFile { + fromResolver = append(fromResolver, ref.Name) + } + } + } + sort.Strings(fromResolver) + assert.Equal(t, got, fromResolver) +} diff --git a/internal/secret/types.go b/internal/secret/types.go index 1d31a5a82..6a044df62 100644 --- a/internal/secret/types.go +++ b/internal/secret/types.go @@ -34,7 +34,9 @@ type Provider interface { // Resolver manages secret resolution using multiple providers type Resolver struct { - providers map[string]Provider + providers map[string]Provider + scope ResolveScope + filePolicy *FilePolicy } // ResolveResult contains the result of secret resolution diff --git a/internal/server/concurrency_shed_test.go b/internal/server/concurrency_shed_test.go index 393a214c4..0b1b3b779 100644 --- a/internal/server/concurrency_shed_test.go +++ b/internal/server/concurrency_shed_test.go @@ -142,7 +142,7 @@ func TestCodeExecutionToolCaller_IsSubjectToAdmission(t *testing.T) { } cfg := &config.Config{Servers: []*config.ServerConfig{serverCfg}} - um := newTestUpstreamManager(t, zap.NewNop(), cfg, nil, secret.NewResolver(), nil) + um := newTestUpstreamManager(t, zap.NewNop(), cfg, nil, secret.NewTestWildcardResolver(), nil) require.NoError(t, um.AddServerConfig("db", serverCfg)) client, ok := um.GetClient("db") require.True(t, ok) @@ -185,7 +185,7 @@ func TestCodeExecutionToolCaller_ShedIsAttributedInternally(t *testing.T) { } cfg := &config.Config{Servers: []*config.ServerConfig{serverCfg}} - um := newTestUpstreamManager(t, zap.NewNop(), cfg, nil, secret.NewResolver(), nil) + um := newTestUpstreamManager(t, zap.NewNop(), cfg, nil, secret.NewTestWildcardResolver(), nil) require.NoError(t, um.AddServerConfig("db", serverCfg)) client, ok := um.GetClient("db") require.True(t, ok) diff --git a/internal/server/e2e_concurrency_limits_test.go b/internal/server/e2e_concurrency_limits_test.go index f4ebc47f3..fbcf25802 100644 --- a/internal/server/e2e_concurrency_limits_test.go +++ b/internal/server/e2e_concurrency_limits_test.go @@ -146,7 +146,7 @@ func newLimitedManager(t *testing.T, up *slowUpstream, maxConcurrent, queueSize // legal configuration (FR-023). require.Empty(t, cfg.ValidateDetailed(), "concurrency limits must pass config validation") - um := newTestUpstreamManager(t, zap.NewNop(), cfg, nil, secret.NewResolver(), nil) + um := newTestUpstreamManager(t, zap.NewNop(), cfg, nil, secret.NewTestWildcardResolver(), nil) require.NoError(t, um.AddServerConfig(slowUpstreamName, serverCfg)) require.NoError(t, um.ConnectAll(context.Background())) diff --git a/internal/server/mcp.go b/internal/server/mcp.go index 40a62109b..7cf264a50 100644 --- a/internal/server/mcp.go +++ b/internal/server/mcp.go @@ -6511,6 +6511,10 @@ func (p *MCPProxyServer) handleAddUpstream(ctx context.Context, request mcp.Call if errors.As(createErr, &exists) { return mcp.NewToolResultError(fmt.Sprintf("%v; use operation 'update' or 'patch' to modify it, or choose another name", exists)), nil } + var verr *config.InvalidServerUpdateError + if errors.As(createErr, &verr) { + return mcp.NewToolResultError(joinMCPSecretPolicyMessages(verr.Errors)), nil + } return mcp.NewToolResultError(fmt.Sprintf("Failed to add upstream: %v", createErr)), nil } @@ -6702,9 +6706,12 @@ func (p *MCPProxyServer) mergeUpstreamPatch(name string, request mcp.CallToolReq }) if err != nil { var userErr *mcpUserError + var verr *config.InvalidServerUpdateError switch { case errors.As(err, &userErr): return nil, nil, 0, mcp.NewToolResultError(userErr.msg) + case errors.As(err, &verr): + return nil, nil, 0, mcp.NewToolResultError(joinMCPSecretPolicyMessages(verr.Errors)) case errors.Is(err, errUpstreamNotFound): return nil, nil, 0, mcp.NewToolResultError(fmt.Sprintf("Server '%s' not found", name)) default: diff --git a/internal/server/mcp_activation_test.go b/internal/server/mcp_activation_test.go index f862d3b54..db58a53af 100644 --- a/internal/server/mcp_activation_test.go +++ b/internal/server/mcp_activation_test.go @@ -68,7 +68,7 @@ func buildMCPProxyWithActivation(t *testing.T) (*MCPProxyServer, *runtime.Runtim idx := rt.IndexManager() require.NotNil(t, idx) - secretResolver := secret.NewResolver() + secretResolver := secret.NewTestWildcardResolver() um := newTestUpstreamManager(t, logger, cfg, nil, secretResolver, nil) cm, err := cache.NewManager(rt.StorageManager().GetDB(), logger) diff --git a/internal/server/mcp_activity_truncation_test.go b/internal/server/mcp_activity_truncation_test.go index 1bd74671a..401b66138 100644 --- a/internal/server/mcp_activity_truncation_test.go +++ b/internal/server/mcp_activity_truncation_test.go @@ -60,7 +60,7 @@ func newTruncatingRetrieveToolsProxy(t *testing.T, responseLimit int) (*MCPProxy require.NoError(t, err) t.Cleanup(func() { _ = idx.Close() }) - um := newTestUpstreamManager(t, logger, cfg, nil, secret.NewResolver(), nil) + um := newTestUpstreamManager(t, logger, cfg, nil, secret.NewTestWildcardResolver(), nil) cm, err := cache.NewManager(sm.GetDB(), logger) require.NoError(t, err) diff --git a/internal/server/mcp_auth_scope_test.go b/internal/server/mcp_auth_scope_test.go index e48442b38..9d6d6b11e 100644 --- a/internal/server/mcp_auth_scope_test.go +++ b/internal/server/mcp_auth_scope_test.go @@ -36,7 +36,7 @@ func createTestMCPProxyServer(t *testing.T) *MCPProxyServer { require.NoError(t, err) t.Cleanup(func() { idx.Close() }) - secretResolver := secret.NewResolver() + secretResolver := secret.NewTestWildcardResolver() cfg := config.DefaultConfig() cfg.DataDir = tmpDir cfg.ToolsLimit = 20 diff --git a/internal/server/mcp_block_tools_test.go b/internal/server/mcp_block_tools_test.go index c93cb45c5..36f6a2fb1 100644 --- a/internal/server/mcp_block_tools_test.go +++ b/internal/server/mcp_block_tools_test.go @@ -57,7 +57,7 @@ func createTestProxyWithRuntimeCfg(t *testing.T, servers []*config.ServerConfig, require.NoError(t, err) t.Cleanup(func() { _ = idx.Close() }) - um := newTestUpstreamManager(t, logger, cfg, nil, secret.NewResolver(), nil) + um := newTestUpstreamManager(t, logger, cfg, nil, secret.NewTestWildcardResolver(), nil) cm, err := cache.NewManager(sm.GetDB(), logger) require.NoError(t, err) diff --git a/internal/server/mcp_call_tool_args_test.go b/internal/server/mcp_call_tool_args_test.go index 9863d1d7e..86373df37 100644 --- a/internal/server/mcp_call_tool_args_test.go +++ b/internal/server/mcp_call_tool_args_test.go @@ -54,7 +54,7 @@ func TestCallToolVariantSchemaAdvertisesArgsObject(t *testing.T) { // path actually works, not just the schema. func TestHandleCallToolVariantAcceptsArgsObject(t *testing.T) { mockProxy := &MCPProxyServer{ - upstreamManager: newTestUpstreamManager(t, zap.NewNop(), config.DefaultConfig(), nil, secret.NewResolver(), nil), + upstreamManager: newTestUpstreamManager(t, zap.NewNop(), config.DefaultConfig(), nil, secret.NewTestWildcardResolver(), nil), logger: zap.NewNop(), config: &config.Config{}, } @@ -95,7 +95,7 @@ func TestHandleCallToolVariantAcceptsArgsObject(t *testing.T) { // precedence. This preserves existing behavior so migration is gradual. func TestHandleCallToolVariantArgsJSONWinsWhenBothProvided(t *testing.T) { mockProxy := &MCPProxyServer{ - upstreamManager: newTestUpstreamManager(t, zap.NewNop(), config.DefaultConfig(), nil, secret.NewResolver(), nil), + upstreamManager: newTestUpstreamManager(t, zap.NewNop(), config.DefaultConfig(), nil, secret.NewTestWildcardResolver(), nil), logger: zap.NewNop(), config: &config.Config{}, } diff --git a/internal/server/mcp_code_execution_callstats_test.go b/internal/server/mcp_code_execution_callstats_test.go index 918ce9932..af8da7897 100644 --- a/internal/server/mcp_code_execution_callstats_test.go +++ b/internal/server/mcp_code_execution_callstats_test.go @@ -26,7 +26,7 @@ func TestCodeExecutionToolCaller_RecordsCallOutcome(t *testing.T) { QueueTimeout: shedDurPtr(30 * time.Second), } cfg := &config.Config{Servers: []*config.ServerConfig{serverCfg}} - um := newTestUpstreamManager(t, zap.NewNop(), cfg, nil, secret.NewResolver(), nil) + um := newTestUpstreamManager(t, zap.NewNop(), cfg, nil, secret.NewTestWildcardResolver(), nil) require.NoError(t, um.AddServerConfig("db", serverCfg)) client, ok := um.GetClient("db") require.True(t, ok) diff --git a/internal/server/mcp_code_execution_test.go b/internal/server/mcp_code_execution_test.go index 7e0c5ab64..73c2f7076 100644 --- a/internal/server/mcp_code_execution_test.go +++ b/internal/server/mcp_code_execution_test.go @@ -55,7 +55,7 @@ func TestCodeExecution_WithNilMainServer(t *testing.T) { require.NoError(t, err) defer indexManager.Close() - secretResolver := secret.NewResolver() + secretResolver := secret.NewTestWildcardResolver() upstreamManager := upstream.NewManager(logger, cfg, storageManager.GetBoltDB(), secretResolver, storageManager) defer shutdownUpstreamManager(upstreamManager) @@ -122,7 +122,7 @@ func newCodeExecProxy(t *testing.T) *server.MCPProxyServer { require.NoError(t, err) t.Cleanup(func() { indexManager.Close() }) - secretResolver := secret.NewResolver() + secretResolver := secret.NewTestWildcardResolver() upstreamManager := upstream.NewManager(logger, cfg, storageManager.GetBoltDB(), secretResolver, storageManager) t.Cleanup(func() { shutdownUpstreamManager(upstreamManager) }) @@ -256,7 +256,7 @@ func TestCodeExecution_TypeScript(t *testing.T) { require.NoError(t, err) defer indexManager.Close() - secretResolver := secret.NewResolver() + secretResolver := secret.NewTestWildcardResolver() upstreamManager := upstream.NewManager(logger, cfg, storageManager.GetBoltDB(), secretResolver, storageManager) defer shutdownUpstreamManager(upstreamManager) @@ -319,7 +319,7 @@ func TestCodeExecution_JavaScriptBackwardCompat(t *testing.T) { require.NoError(t, err) defer indexManager.Close() - secretResolver := secret.NewResolver() + secretResolver := secret.NewTestWildcardResolver() upstreamManager := upstream.NewManager(logger, cfg, storageManager.GetBoltDB(), secretResolver, storageManager) defer shutdownUpstreamManager(upstreamManager) @@ -382,7 +382,7 @@ func TestCodeExecution_InvalidLanguage(t *testing.T) { require.NoError(t, err) defer indexManager.Close() - secretResolver := secret.NewResolver() + secretResolver := secret.NewTestWildcardResolver() upstreamManager := upstream.NewManager(logger, cfg, storageManager.GetBoltDB(), secretResolver, storageManager) defer shutdownUpstreamManager(upstreamManager) diff --git a/internal/server/mcp_code_scripts_test.go b/internal/server/mcp_code_scripts_test.go index f9d706957..fcaeef9ef 100644 --- a/internal/server/mcp_code_scripts_test.go +++ b/internal/server/mcp_code_scripts_test.go @@ -72,7 +72,7 @@ func newStoredScriptProxyCfg(t *testing.T, configure func(*config.Config), opts configure(cfg) } - um := newTestUpstreamManager(t, logger, cfg, sm.GetBoltDB(), secret.NewResolver(), sm) + um := newTestUpstreamManager(t, logger, cfg, sm.GetBoltDB(), secret.NewTestWildcardResolver(), sm) cm, err := cache.NewManager(sm.GetDB(), logger) require.NoError(t, err) diff --git a/internal/server/mcp_prompt_scope_test.go b/internal/server/mcp_prompt_scope_test.go index 70db414e0..961276cd5 100644 --- a/internal/server/mcp_prompt_scope_test.go +++ b/internal/server/mcp_prompt_scope_test.go @@ -250,7 +250,7 @@ func TestAggregatedPrompt_ScopeUsesCanonicalOwner(t *testing.T) { qOff := false proxy.config.QuarantineEnabled = &qOff - um := newTestUpstreamManager(t, zap.NewNop(), proxy.config, nil, secret.NewResolver(), nil) + um := newTestUpstreamManager(t, zap.NewNop(), proxy.config, nil, secret.NewTestWildcardResolver(), nil) for _, name := range []string{"a", "a__b"} { testServer := servertest.NewTestStreamableHTTPServer(newTestRefreshPromptsUpstream(t)) t.Cleanup(func() { closeHTTPFixture(testServer) }) @@ -372,7 +372,7 @@ func TestAggregatedPrompt_LateEnableStillFiltered(t *testing.T) { qOff := false proxy.config.QuarantineEnabled = &qOff - um := newTestUpstreamManager(t, zap.NewNop(), proxy.config, nil, secret.NewResolver(), nil) + um := newTestUpstreamManager(t, zap.NewNop(), proxy.config, nil, secret.NewTestWildcardResolver(), nil) for _, name := range []string{"a", "hidden"} { testServer := servertest.NewTestStreamableHTTPServer(newTestRefreshPromptsUpstream(t)) t.Cleanup(func() { closeHTTPFixture(testServer) }) diff --git a/internal/server/mcp_routing_test.go b/internal/server/mcp_routing_test.go index c76b9938e..b50c0ba18 100644 --- a/internal/server/mcp_routing_test.go +++ b/internal/server/mcp_routing_test.go @@ -1050,7 +1050,7 @@ func TestRefreshPrompts_AggregatesBuiltinsAndUpstream(t *testing.T) { testServer := servertest.NewTestStreamableHTTPServer(upstreamSrv) t.Cleanup(func() { closeHTTPFixture(testServer) }) - um := newTestUpstreamManager(t, zap.NewNop(), proxy.config, nil, secret.NewResolver(), nil) + um := newTestUpstreamManager(t, zap.NewNop(), proxy.config, nil, secret.NewTestWildcardResolver(), nil) require.NoError(t, um.AddServerConfig("srv-a", &config.ServerConfig{ Name: "server-a", Protocol: "streamable-http", @@ -1088,7 +1088,7 @@ func TestRefreshPrompts_RugPullBaseline_WithholdsFirstSeen(t *testing.T) { testServer := servertest.NewTestStreamableHTTPServer(upstreamSrv) t.Cleanup(func() { closeHTTPFixture(testServer) }) - um := newTestUpstreamManager(t, zap.NewNop(), proxy.config, nil, secret.NewResolver(), nil) + um := newTestUpstreamManager(t, zap.NewNop(), proxy.config, nil, secret.NewTestWildcardResolver(), nil) require.NoError(t, um.AddServerConfig("srv-a", &config.ServerConfig{ Name: "server-a", Protocol: "streamable-http", URL: testServer.URL, Enabled: true, })) @@ -1125,7 +1125,7 @@ func TestRefreshPrompts_AggregationDisabled_BuiltinsOnly(t *testing.T) { testServer := servertest.NewTestStreamableHTTPServer(upstreamSrv) t.Cleanup(func() { closeHTTPFixture(testServer) }) - um := newTestUpstreamManager(t, zap.NewNop(), proxy.config, nil, secret.NewResolver(), nil) + um := newTestUpstreamManager(t, zap.NewNop(), proxy.config, nil, secret.NewTestWildcardResolver(), nil) require.NoError(t, um.AddServerConfig("srv-a", &config.ServerConfig{ Name: "server-a", Protocol: "streamable-http", @@ -1175,7 +1175,7 @@ func TestRefreshPrompts_ReadsLiveAggregateFlag(t *testing.T) { testServer := servertest.NewTestStreamableHTTPServer(upstreamSrv) t.Cleanup(func() { closeHTTPFixture(testServer) }) - um := newTestUpstreamManager(t, zap.NewNop(), live, nil, secret.NewResolver(), nil) + um := newTestUpstreamManager(t, zap.NewNop(), live, nil, secret.NewTestWildcardResolver(), nil) require.NoError(t, um.AddServerConfig("srv-a", &config.ServerConfig{ Name: "server-a", Protocol: "streamable-http", @@ -1199,7 +1199,7 @@ func TestRefreshPrompts_ReadsLiveAggregateFlag(t *testing.T) { func TestRefreshPrompts_NoUpstreamClients_RegistersOnlyBuiltins(t *testing.T) { proxy, _ := createTestProxyWithRuntime(t, nil) proxy.config.EnablePrompts = true - proxy.upstreamManager = newTestUpstreamManager(t, zap.NewNop(), proxy.config, nil, secret.NewResolver(), nil) + proxy.upstreamManager = newTestUpstreamManager(t, zap.NewNop(), proxy.config, nil, secret.NewTestWildcardResolver(), nil) proxy.RefreshPrompts() @@ -1227,7 +1227,7 @@ func TestRefreshPrompts_PopulatesRoutingModeServers(t *testing.T) { testServer := servertest.NewTestStreamableHTTPServer(upstreamSrv) t.Cleanup(func() { closeHTTPFixture(testServer) }) - um := newTestUpstreamManager(t, zap.NewNop(), proxy.config, nil, secret.NewResolver(), nil) + um := newTestUpstreamManager(t, zap.NewNop(), proxy.config, nil, secret.NewTestWildcardResolver(), nil) require.NoError(t, um.AddServerConfig("srv-a", &config.ServerConfig{ Name: "server-a", Protocol: "streamable-http", diff --git a/internal/server/mcp_secret_policy.go b/internal/server/mcp_secret_policy.go new file mode 100644 index 000000000..132ae89bc --- /dev/null +++ b/internal/server/mcp_secret_policy.go @@ -0,0 +1,15 @@ +package server + +import ( + "strings" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" +) + +func joinMCPSecretPolicyMessages(errs []config.ValidationError) string { + msgs := make([]string, 0, len(errs)) + for _, e := range errs { + msgs = append(msgs, e.Message) + } + return strings.Join(msgs, "; ") +} diff --git a/internal/server/mcp_test.go b/internal/server/mcp_test.go index ea89c8567..b7171f04b 100644 --- a/internal/server/mcp_test.go +++ b/internal/server/mcp_test.go @@ -698,7 +698,7 @@ func TestHandleCallToolErrorRecovery(t *testing.T) { // This test verifies the core issue mentioned in the error logs mockProxy := &MCPProxyServer{ - upstreamManager: newTestUpstreamManager(t, zap.NewNop(), config.DefaultConfig(), nil, secret.NewResolver(), nil), + upstreamManager: newTestUpstreamManager(t, zap.NewNop(), config.DefaultConfig(), nil, secret.NewTestWildcardResolver(), nil), logger: zap.NewNop(), } @@ -740,7 +740,7 @@ func TestHandleCallToolCompleteErrorHandling(t *testing.T) { // Test comprehensive error handling scenarios including self-referential calls mockProxy := &MCPProxyServer{ - upstreamManager: newTestUpstreamManager(t, zap.NewNop(), config.DefaultConfig(), nil, secret.NewResolver(), nil), + upstreamManager: newTestUpstreamManager(t, zap.NewNop(), config.DefaultConfig(), nil, secret.NewTestWildcardResolver(), nil), logger: zap.NewNop(), config: &config.Config{}, // Add minimal config for testing } diff --git a/internal/server/mcp_upstream_secret_policy_test.go b/internal/server/mcp_upstream_secret_policy_test.go new file mode 100644 index 000000000..ce5e9f86f --- /dev/null +++ b/internal/server/mcp_upstream_secret_policy_test.go @@ -0,0 +1,75 @@ +package server + +import ( + "context" + "os" + "path/filepath" + "testing" + + mcp "github.com/mark3labs/mcp-go/mcp" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func withSecretFileDirsOnProxy(t *testing.T, proxy *MCPProxyServer) { + t.Helper() + dir := proxy.config.DataDir + allowed := filepath.Join(dir, "secrets") + require.NoError(t, os.MkdirAll(allowed, 0o700)) + w := config.SecretFileDirs{allowed} + proxy.config.SecretFileDirs = &w + require.NotNil(t, proxy.mainServer) + _, err := proxy.mainServer.runtime.ApplyConfig(proxy.config, "") + require.NoError(t, err) +} + +func TestHandleAddUpstream_RefusesSecretPolicyBeforeSave(t *testing.T) { + proxy := newAddFromRegistryTestServer(t) + withSecretFileDirsOnProxy(t, proxy) + + req := mcp.CallToolRequest{} + req.Params.Name = "upstream_servers" + req.Params.Arguments = map[string]interface{}{ + "operation": "add", + "name": "policy-blocked", + "url": "http://127.0.0.1:9/mcp", + "enabled": false, + "env_json": `{"K":"${env:MCPPROXY_API_KEY}"}`, + } + res, err := proxy.handleAddUpstream(context.Background(), req) + require.NoError(t, err) + require.True(t, res.IsError) + text := res.Content[0].(mcp.TextContent).Text + assert.Contains(t, text, secret.ErrReservedEnvVar.Error()) + _, err = proxy.mainServer.runtime.StorageManager().GetUpstreamServer("policy-blocked") + assert.Error(t, err) +} + +func TestHandleUpstreamServers_Patch_RefusesSecretPolicyBeforeSave(t *testing.T) { + proxy := newAddFromRegistryTestServer(t) + withSecretFileDirsOnProxy(t, proxy) + + _, err := proxy.mainServer.runtime.Commit("create_server", func(tx *runtime.CommitTx) error { + return tx.CreateServer(&config.ServerConfig{ + Name: "s", + URL: "http://127.0.0.1:9/mcp", + Enabled: false, + }) + }) + require.NoError(t, err) + + req := mcp.CallToolRequest{} + req.Params.Name = "upstream_servers" + req.Params.Arguments = map[string]interface{}{ + "operation": "patch", + "name": "s", + "env_json": `{"K":"${env:MCPPROXY_API_KEY}"}`, + } + res, err := proxy.handleUpstreamServers(context.Background(), req) + require.NoError(t, err) + require.True(t, res.IsError) + assert.Contains(t, res.Content[0].(mcp.TextContent).Text, secret.ErrReservedEnvVar.Error()) +} diff --git a/internal/server/preflight_glue_test.go b/internal/server/preflight_glue_test.go index 2c771738c..93552c65f 100644 --- a/internal/server/preflight_glue_test.go +++ b/internal/server/preflight_glue_test.go @@ -64,7 +64,7 @@ func newPreflightFixture(t *testing.T, mutate func(cfg *config.Config)) *preflig mutate(cfg) } - um := newTestUpstreamManager(t, logger, cfg, nil, secret.NewResolver(), nil) + um := newTestUpstreamManager(t, logger, cfg, nil, secret.NewTestWildcardResolver(), nil) cm, err := cache.NewManager(sm.GetDB(), logger) require.NoError(t, err) t.Cleanup(func() { cm.Close() }) diff --git a/internal/server/rest_upstream_secret_policy_test.go b/internal/server/rest_upstream_secret_policy_test.go new file mode 100644 index 000000000..7c6d48c93 --- /dev/null +++ b/internal/server/rest_upstream_secret_policy_test.go @@ -0,0 +1,118 @@ +package server + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/httpapi" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" +) + +func newSpec116ServerWithSecretDirs(t *testing.T, allowed string, servers ...*config.ServerConfig) (*Server, string) { + t.Helper() + require.NoError(t, os.MkdirAll(allowed, 0o700)) + cfg := config.DefaultConfig() + cfg.DataDir = t.TempDir() + cfg.Listen = "127.0.0.1:0" + cfg.APIKey = spec116APIKey + cfg.Servers = servers + w := config.SecretFileDirs{allowed} + cfg.SecretFileDirs = &w + cfgPath := filepath.Join(t.TempDir(), "mcp_config.json") + raw, err := json.MarshalIndent(cfg, "", " ") + require.NoError(t, err) + require.NoError(t, os.WriteFile(cfgPath, raw, 0o600)) + loaded, err := config.LoadFromFile(cfgPath) + require.NoError(t, err) + loaded.DataDir = cfg.DataDir + loaded.SecretFileDirs = &w + srv, err := NewServerWithConfigPath(loaded, cfgPath, zap.NewNop()) + require.NoError(t, err) + t.Cleanup(func() { _ = srv.Shutdown() }) + bootSpec116(t, srv) + return srv, cfgPath +} + +func TestREST_AddServer_RefusesSecretPolicyBeforeSave(t *testing.T) { + dir := t.TempDir() + allowed := filepath.Join(dir, "secrets") + srv, cfgPath := newSpec116ServerWithSecretDirs(t, allowed) + api := httpapi.NewServer(srv, zap.NewNop().Sugar(), nil) + + body, _ := json.Marshal(map[string]any{ + "name": "blocked", + "url": "http://127.0.0.1:9/mcp", + "enabled": false, + "env": map[string]string{"K": "${env:MCPPROXY_API_KEY}"}, + }) + req := httptest.NewRequest(http.MethodPost, "/api/v1/servers", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-API-Key", spec116APIKey) + rec := httptest.NewRecorder() + api.Router().ServeHTTP(rec, req) + + require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String()) + assert.Contains(t, rec.Body.String(), secret.ErrReservedEnvVar.Error()) + assert.Nil(t, liveServer(srv, "blocked")) + assert.Nil(t, diskServer(t, cfgPath, "blocked")) +} + +func TestREST_PatchServer_RefusesSecretPolicyBeforeSave(t *testing.T) { + dir := t.TempDir() + allowed := filepath.Join(dir, "secrets") + existing := &config.ServerConfig{ + Name: "s", URL: "http://127.0.0.1:9/mcp", Protocol: "streamable-http", Enabled: false, + } + srv, cfgPath := newSpec116ServerWithSecretDirs(t, allowed, existing) + api := httpapi.NewServer(srv, zap.NewNop().Sugar(), nil) + + rec := restPatch(t, api, "s", `{"env":{"K":"${env:MCPPROXY_API_KEY}"}}`) + require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String()) + assert.Contains(t, rec.Body.String(), secret.ErrReservedEnvVar.Error()) + assert.Empty(t, liveServer(srv, "s").Env) + assert.Empty(t, diskServer(t, cfgPath, "s").Env) +} + +func TestImportServersJSON_RealCommit_RefusesSecretPolicyBeforeSave(t *testing.T) { + dir := t.TempDir() + allowed := filepath.Join(dir, "secrets") + srv, _ := newSpec116ServerWithSecretDirs(t, allowed) + api := httpapi.NewServer(srv, zap.NewNop().Sugar(), nil) + + body, _ := json.Marshal(httpapi.ImportRequest{ + Content: `{"mcpServers": { + "bad": {"url": "http://127.0.0.1:9/mcp", "enabled": false, "env": {"K": "${env:MCPPROXY_API_KEY}"}}, + "good": {"command": "true", "enabled": false} + }}`, + }) + req := httptest.NewRequest(http.MethodPost, "/api/v1/servers/import/json", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-API-Key", spec116APIKey) + rec := httptest.NewRecorder() + api.Router().ServeHTTP(rec, req) + + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + var wrapped struct { + Data struct { + Failed []struct { + Name string `json:"name"` + Details string `json:"details"` + } `json:"failed"` + } `json:"data"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &wrapped)) + require.Len(t, wrapped.Data.Failed, 1) + assert.Equal(t, "bad", wrapped.Data.Failed[0].Name) + assert.Contains(t, wrapped.Data.Failed[0].Details, secret.ErrReservedEnvVar.Error()) + assert.NotNil(t, liveServer(srv, "good")) + assert.Nil(t, liveServer(srv, "bad")) +} diff --git a/internal/server/scope_cache_fixtures_test.go b/internal/server/scope_cache_fixtures_test.go index 2720dc6dd..1b50d10a4 100644 --- a/internal/server/scope_cache_fixtures_test.go +++ b/internal/server/scope_cache_fixtures_test.go @@ -64,7 +64,7 @@ func newRestartableProxy(t *testing.T, dir string) (*MCPProxyServer, func()) { cfg := config.DefaultConfig() cfg.DataDir = dir cfg.ToolsLimit = 20 - um := newTestUpstreamManager(t, logger, cfg, nil, secret.NewResolver(), nil) + um := newTestUpstreamManager(t, logger, cfg, nil, secret.NewTestWildcardResolver(), nil) cm, err := cache.NewManager(sm.GetDB(), logger) require.NoError(t, err) tr := truncate.NewTruncator(0) diff --git a/internal/server/scope_retained_effects_test.go b/internal/server/scope_retained_effects_test.go index f661da562..4b8590386 100644 --- a/internal/server/scope_retained_effects_test.go +++ b/internal/server/scope_retained_effects_test.go @@ -279,7 +279,7 @@ func connectPromptUpstream(t *testing.T, proxy *MCPProxyServer, servers map[stri qOff := false proxy.config.QuarantineEnabled = &qOff - um := newTestUpstreamManager(t, zap.NewNop(), proxy.config, nil, secret.NewResolver(), nil) + um := newTestUpstreamManager(t, zap.NewNop(), proxy.config, nil, secret.NewTestWildcardResolver(), nil) for name, prompts := range servers { mcpSrv := mcpserver.NewMCPServer(name, "1.0.0-test", mcpserver.WithPromptCapabilities(true)) for _, p := range prompts { diff --git a/internal/server/server.go b/internal/server/server.go index 852e84b83..301c81927 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -379,13 +379,12 @@ func NewServerWithConfigPath(cfg *config.Config, configPath string, logger *zap. } // Initialize management service and set it on runtime - secretResolver := secret.NewResolver() mgmtService := management.NewService( - rt, // RuntimeOperations - cfg, // Config - rt.ConfigPath(), // Config file path for deprecation checks - rt, // EventEmitter - secretResolver, // SecretResolver + rt, // RuntimeOperations + cfg, // Config + rt.ConfigPath(), // Config file path for deprecation checks + rt, // EventEmitter + rt.GetSecretResolver(), // SecretResolver logger.Sugar(), ) rt.SetManagementService(mgmtService) @@ -3765,7 +3764,7 @@ func (s *Server) startCustomHTTPServer(ctx context.Context, streamableServer *se secService.InvalidateServerState(name) } }) - secService.SetSecretStore(&keyringSecretStore{resolver: secret.NewResolver()}) + secService.SetSecretStore(&keyringSecretStore{resolver: s.runtime.GetSecretResolver()}) secService.CleanupStaleJobs() httpAPIServer.SetSecurityController(secService) // Plumb scan summaries through management.ListServers so the SSE diff --git a/internal/server/toolslist_profiles_v3_test.go b/internal/server/toolslist_profiles_v3_test.go index 2bac2e1c4..708da957c 100644 --- a/internal/server/toolslist_profiles_v3_test.go +++ b/internal/server/toolslist_profiles_v3_test.go @@ -44,7 +44,7 @@ func newToolsListProxy(t *testing.T, configure func(*config.Config)) *MCPProxySe if configure != nil { configure(cfg) } - um := newTestUpstreamManager(t, logger, cfg, nil, secret.NewResolver(), nil) + um := newTestUpstreamManager(t, logger, cfg, nil, secret.NewTestWildcardResolver(), nil) cm, err := cache.NewManager(sm.GetDB(), logger) require.NoError(t, err) t.Cleanup(func() { cm.Close() }) diff --git a/internal/server/toon_surface_isolation_test.go b/internal/server/toon_surface_isolation_test.go index c81dd14d0..68a9d4ea0 100644 --- a/internal/server/toon_surface_isolation_test.go +++ b/internal/server/toon_surface_isolation_test.go @@ -126,7 +126,7 @@ func TestSurfaceIsolation_CodeExecution(t *testing.T) { require.NoError(t, err) t.Cleanup(func() { idx.Close() }) - um := newTestUpstreamManager(t, logger, cfg, sm.GetBoltDB(), secret.NewResolver(), sm) + um := newTestUpstreamManager(t, logger, cfg, sm.GetBoltDB(), secret.NewTestWildcardResolver(), sm) cm, err := cache.NewManager(sm.GetDB(), logger) require.NoError(t, err) @@ -172,7 +172,7 @@ func TestSurfaceIsolation_DirectMode(t *testing.T) { require.NoError(t, err) t.Cleanup(func() { sm.Close() }) - um := newTestUpstreamManager(t, logger, cfg, sm.GetBoltDB(), secret.NewResolver(), sm) + um := newTestUpstreamManager(t, logger, cfg, sm.GetBoltDB(), secret.NewTestWildcardResolver(), sm) proxy := &MCPProxyServer{ config: cfg, diff --git a/internal/server/truncator_reload_test.go b/internal/server/truncator_reload_test.go index 6412dedfa..6b7d72fdd 100644 --- a/internal/server/truncator_reload_test.go +++ b/internal/server/truncator_reload_test.go @@ -49,7 +49,7 @@ func TestTruncatorHotReloadOnServingPath(t *testing.T) { require.NoError(t, err) t.Cleanup(func() { idx.Close() }) - um := newTestUpstreamManager(t, logger, cfg, sm.GetBoltDB(), secret.NewResolver(), sm) + um := newTestUpstreamManager(t, logger, cfg, sm.GetBoltDB(), secret.NewTestWildcardResolver(), sm) cm, err := cache.NewManager(sm.GetDB(), logger) require.NoError(t, err) diff --git a/internal/server/upstream_test.go b/internal/server/upstream_test.go index 68e7459ca..7c9d52cbc 100644 --- a/internal/server/upstream_test.go +++ b/internal/server/upstream_test.go @@ -46,7 +46,7 @@ func TestUpstreamServersHandlerPerformance(t *testing.T) { defer indexManager.Close() // Create upstream manager - upstreamManager := newTestUpstreamManager(t, zap.NewNop(), cfg, nil, secret.NewResolver(), nil) + upstreamManager := newTestUpstreamManager(t, zap.NewNop(), cfg, nil, secret.NewTestWildcardResolver(), nil) // Create cache manager cacheManager, err := cache.NewManager(storageManager.GetDB(), zap.NewNop()) @@ -142,7 +142,7 @@ func TestUpstreamServersListOperation(t *testing.T) { defer indexManager.Close() // Create upstream manager - upstreamManager := newTestUpstreamManager(t, zap.NewNop(), cfg, nil, secret.NewResolver(), nil) + upstreamManager := newTestUpstreamManager(t, zap.NewNop(), cfg, nil, secret.NewTestWildcardResolver(), nil) // Create cache manager cacheManager, err := cache.NewManager(storageManager.GetDB(), zap.NewNop()) diff --git a/internal/serveredition/auth/oauth_handler.go b/internal/serveredition/auth/oauth_handler.go index da30b3855..8ac5b99c4 100644 --- a/internal/serveredition/auth/oauth_handler.go +++ b/internal/serveredition/auth/oauth_handler.go @@ -21,7 +21,6 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" "github.com/smart-mcp-proxy/mcpproxy-go/internal/reqcontext" - "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" "github.com/smart-mcp-proxy/mcpproxy-go/internal/serveredition/users" ) @@ -234,8 +233,8 @@ func NewOAuthHandler( // failure here (the env var was unset in between) is // treated as "not configured" rather than sending the // literal placeholder text to the IdP. - resolvedID, idErr := secret.NewResolver().ExpandSecretRefs(context.Background(), h.oauthCfg.ClientID) - resolvedSecret, secretErr := secret.NewResolver().ExpandSecretRefs(context.Background(), h.oauthCfg.ClientSecret) + resolvedID, idErr := config.ResolveOAuthSecretRef(h.oauthCfg.ClientID) + resolvedSecret, secretErr := config.ResolveOAuthSecretRef(h.oauthCfg.ClientSecret) if idErr != nil || secretErr != nil || resolvedID == "" || resolvedSecret == "" { if logger != nil { logger.Errorw("server_edition.oauth.client_id/client_secret failed to resolve at handler construction", diff --git a/internal/upstream/addserver_connecting_race_test.go b/internal/upstream/addserver_connecting_race_test.go index 14494bbd8..79c98d08d 100644 --- a/internal/upstream/addserver_connecting_race_test.go +++ b/internal/upstream/addserver_connecting_race_test.go @@ -20,7 +20,7 @@ import ( // RegisterServerIdentity for that server. An in-flight connect owned by // someone else is not a failure of AddServer. func TestAddServer_UnchangedServerAlreadyConnectingIsNotAnError(t *testing.T) { - m := NewManager(zap.NewNop(), &config.Config{}, nil, secret.NewResolver(), nil) + m := NewManager(zap.NewNop(), &config.Config{}, nil, secret.NewTestWildcardResolver(), nil) sc := &config.ServerConfig{ Name: "fx", Command: "/nonexistent/never-run", Protocol: "stdio", Enabled: true, } diff --git a/internal/upstream/cli/client.go b/internal/upstream/cli/client.go index 3e42c812a..f5c044b8f 100644 --- a/internal/upstream/cli/client.go +++ b/internal/upstream/cli/client.go @@ -81,8 +81,7 @@ func NewClient(serverName string, globalConfig *config.Config, logLevel string) db = boltDB } - // Create secret resolver for CLI operations - secretResolver := secret.NewResolver() + secretResolver := config.BuildSecretResolver(globalConfig, globalConfig.ConfigFilePathForPolicy(), secret.ScopeUpstream) // Create core client directly for CLI operations (with persistent storage for OAuth tokens) coreClient, err := core.NewClientWithOptions(serverName, serverConfig, logger, logConfig, globalConfig, db, true, secretResolver) diff --git a/internal/upstream/client_test.go b/internal/upstream/client_test.go index 101dfa49a..a994e9697 100644 --- a/internal/upstream/client_test.go +++ b/internal/upstream/client_test.go @@ -60,7 +60,7 @@ func TestClient_Connect_SSE_NotSupported(t *testing.T) { require.NoError(t, err) // Create client with all required parameters - client, err := managed.NewClient("test-client", cfg, logger, nil, nil, nil, secret.NewResolver()) + client, err := managed.NewClient("test-client", cfg, logger, nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) require.NotNil(t, client) @@ -123,7 +123,7 @@ func TestClient_Connect_SSE_ErrorContainsAlternatives(t *testing.T) { logger, err := zap.NewDevelopment() require.NoError(t, err) - client, err := managed.NewClient("test-client", cfg, logger, nil, nil, nil, secret.NewResolver()) + client, err := managed.NewClient("test-client", cfg, logger, nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) @@ -213,7 +213,7 @@ func TestClient_Connect_WorkingTransports(t *testing.T) { logger, err := zap.NewDevelopment() require.NoError(t, err) - client, err := managed.NewClient("test-client", cfg, logger, nil, nil, nil, secret.NewResolver()) + client, err := managed.NewClient("test-client", cfg, logger, nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) @@ -304,7 +304,7 @@ func TestClient_Headers_Support(t *testing.T) { logger, err := zap.NewDevelopment() require.NoError(t, err) - client, err := managed.NewClient("test-client", cfg, logger, nil, nil, nil, secret.NewResolver()) + client, err := managed.NewClient("test-client", cfg, logger, nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) require.NotNil(t, client) diff --git a/internal/upstream/concurrency_test.go b/internal/upstream/concurrency_test.go index 5a2b2572b..240da508b 100644 --- a/internal/upstream/concurrency_test.go +++ b/internal/upstream/concurrency_test.go @@ -46,7 +46,7 @@ func newConcurrencyManager(t *testing.T, cfg *config.Config, serverCfg *config.S t.Helper() t.Setenv("CI", "") - m := NewManager(zap.NewNop(), cfg, nil, secret.NewResolver(), nil) + m := NewManager(zap.NewNop(), cfg, nil, secret.NewTestWildcardResolver(), nil) t.Cleanup(func() { m.shutdownCancel() }) require.NoError(t, m.AddServerConfig(serverCfg.Name, serverCfg)) @@ -219,7 +219,7 @@ func TestApplyConcurrencyLimits_GlobalAndDisabledServers(t *testing.T) { Servers: []*config.ServerConfig{enabled, disabled, quarantined}, } - m := NewManager(zap.NewNop(), cfg, nil, secret.NewResolver(), nil) + m := NewManager(zap.NewNop(), cfg, nil, secret.NewTestWildcardResolver(), nil) t.Cleanup(func() { m.shutdownCancel() }) global := m.Limiters().Global() @@ -242,7 +242,7 @@ func TestZeroConfig_AdmissionIsPassthroughButCounted(t *testing.T) { sc := &config.ServerConfig{Name: "plain", URL: "http://127.0.0.1:1", Protocol: "http", Enabled: true} cfg := &config.Config{Servers: []*config.ServerConfig{sc}} - m := NewManager(zap.NewNop(), cfg, nil, secret.NewResolver(), nil) + m := NewManager(zap.NewNop(), cfg, nil, secret.NewTestWildcardResolver(), nil) t.Cleanup(func() { m.shutdownCancel() }) assert.Equal(t, 0, m.Limiters().Global().Limits().Max, "no global cap must be published") @@ -268,7 +268,7 @@ func TestHotEnableSeesGrandfatheredCalls(t *testing.T) { sc := &config.ServerConfig{Name: "late", URL: "http://127.0.0.1:1", Protocol: "http", Enabled: true} cfg := &config.Config{Servers: []*config.ServerConfig{sc}} - m := NewManager(zap.NewNop(), cfg, nil, secret.NewResolver(), nil) + m := NewManager(zap.NewNop(), cfg, nil, secret.NewTestWildcardResolver(), nil) t.Cleanup(func() { m.shutdownCancel() }) // Three unlimited calls in flight. diff --git a/internal/upstream/core/calltool_interrupt_log_test.go b/internal/upstream/core/calltool_interrupt_log_test.go index 1b93f4328..83e469de9 100644 --- a/internal/upstream/core/calltool_interrupt_log_test.go +++ b/internal/upstream/core/calltool_interrupt_log_test.go @@ -61,7 +61,7 @@ func blockingCallClient(t *testing.T, callTimeout time.Duration) (*Client, *obse cfg := &config.ServerConfig{Name: "blk", Protocol: "streamable-http", URL: srv.URL, Enabled: true} gc := &config.Config{CallToolTimeout: config.Duration(callTimeout)} obsCore, logs := observer.New(zapcore.DebugLevel) - c, err := NewClient("blk", cfg, zap.New(obsCore), nil, gc, nil, secret.NewResolver()) + c, err := NewClient("blk", cfg, zap.New(obsCore), nil, gc, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() diff --git a/internal/upstream/core/client.go b/internal/upstream/core/client.go index 55f384f78..9e65b64d8 100644 --- a/internal/upstream/core/client.go +++ b/internal/upstream/core/client.go @@ -248,6 +248,14 @@ func NewClientWithOptions(id string, serverConfig *config.ServerConfig, logger * // Decided on the resolved copy, exactly as Connect decides. overHTTP := proxytransport.DetermineTransportType(resolvedServerConfig) != proxytransport.TransportStdio for _, e := range errs { + if secret.IsPolicyDenial(e.Err) { + pe := policyExpansionError(serverConfig.Name, e) + logger.Warn("Secret policy refused upstream configuration", + zap.String("server", serverConfig.Name), + zap.String("field", e.FieldPath), + zap.String("reason", pe.Public)) + return nil, pe + } // Log the references only, never the field's value (release QA // F9): the value may hold literal credentials around them. var refNames []string diff --git a/internal/upstream/core/client_secret_test.go b/internal/upstream/core/client_secret_test.go index e0296640c..beacd30e7 100644 --- a/internal/upstream/core/client_secret_test.go +++ b/internal/upstream/core/client_secret_test.go @@ -54,7 +54,7 @@ func TestClient_HeaderSecretResolution(t *testing.T) { // Setup mock secret provider mockProvider := &MockSecretProvider{} - resolver := secret.NewResolver() + resolver := secret.NewTestWildcardResolver() resolver.RegisterProvider("env", mockProvider) // Create a temporary database for testing @@ -110,7 +110,7 @@ func TestClient_HeaderSecretResolution(t *testing.T) { t.Run("resolve multiple secrets in headers", func(t *testing.T) { // Create a fresh mock provider for this test freshMockProvider := &MockSecretProvider{} - freshResolver := secret.NewResolver() + freshResolver := secret.NewTestWildcardResolver() freshResolver.RegisterProvider("env", freshMockProvider) serverConfig := &config.ServerConfig{ @@ -220,7 +220,7 @@ func TestClient_HeaderSecretResolution(t *testing.T) { // makeResolverWithMock creates a Resolver with a "mock" provider for testing. func makeResolverWithMock(mockP *MockSecretProvider) *secret.Resolver { - r := secret.NewResolver() + r := secret.NewTestWildcardResolver() r.RegisterProvider("mock", mockP) return r } diff --git a/internal/upstream/core/dispatch_recheck_test.go b/internal/upstream/core/dispatch_recheck_test.go index ce4ce4e89..a99313728 100644 --- a/internal/upstream/core/dispatch_recheck_test.go +++ b/internal/upstream/core/dispatch_recheck_test.go @@ -59,7 +59,7 @@ func countingCallClient(t *testing.T) (*Client, *atomic.Int32, *observer.Observe cfg := &config.ServerConfig{Name: "cnt", Protocol: "streamable-http", URL: srv.URL, Enabled: true} obsCore, logs := observer.New(zapcore.DebugLevel) - c, err := NewClient("cnt", cfg, zap.New(obsCore), nil, &config.Config{}, nil, secret.NewResolver()) + c, err := NewClient("cnt", cfg, zap.New(obsCore), nil, &config.Config{}, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() diff --git a/internal/upstream/core/headerfwd_test.go b/internal/upstream/core/headerfwd_test.go index ba1d21986..1c783400e 100644 --- a/internal/upstream/core/headerfwd_test.go +++ b/internal/upstream/core/headerfwd_test.go @@ -118,7 +118,7 @@ func newFwdClient(t *testing.T, u *fwdUpstream, mutate func(*config.ServerConfig mutate(cfg) } obsCore, logs := observer.New(zapcore.DebugLevel) - c, err := NewClient("fwd", cfg, zap.New(obsCore), nil, nil, nil, secret.NewResolver()) + c, err := NewClient("fwd", cfg, zap.New(obsCore), nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() diff --git a/internal/upstream/core/lifecycle_container_evidence_test.go b/internal/upstream/core/lifecycle_container_evidence_test.go index ca4a40e2e..b38233a28 100644 --- a/internal/upstream/core/lifecycle_container_evidence_test.go +++ b/internal/upstream/core/lifecycle_container_evidence_test.go @@ -242,7 +242,7 @@ func TestConnectStdioDirectDockerRun_ContainerEvidence(t *testing.T) { Enabled: true, } mainCore, mainLogs := observer.New(zap.DebugLevel) - c, err := NewClient("a", cfg, zap.New(mainCore), nil, nil, nil, secret.NewResolver()) + c, err := NewClient("a", cfg, zap.New(mainCore), nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) arm.preset(c) diff --git a/internal/upstream/core/prompts_test.go b/internal/upstream/core/prompts_test.go index 7e625f37b..261bbf304 100644 --- a/internal/upstream/core/prompts_test.go +++ b/internal/upstream/core/prompts_test.go @@ -63,7 +63,7 @@ func connectedTestClient(t *testing.T, url string, exposePrompts *bool) *Client Enabled: true, ExposePrompts: exposePrompts, } - c, err := NewClient("test-client", cfg, zap.NewNop(), nil, nil, nil, secret.NewResolver()) + c, err := NewClient("test-client", cfg, zap.NewNop(), nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) @@ -210,7 +210,7 @@ func TestClient_GetPrompt_SetExposePromptsFalse_TakesEffectWithoutReconnect(t *t func unconnectedTestClient(t *testing.T) *Client { t.Helper() cfg := &config.ServerConfig{Name: "test-server", Protocol: "streamable-http", URL: "http://127.0.0.1:1"} - c, err := NewClient("test-client", cfg, zap.NewNop(), nil, nil, nil, secret.NewResolver()) + c, err := NewClient("test-client", cfg, zap.NewNop(), nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) return c } diff --git a/internal/upstream/core/protocol_pin_test.go b/internal/upstream/core/protocol_pin_test.go index b0be42472..986c8dd31 100644 --- a/internal/upstream/core/protocol_pin_test.go +++ b/internal/upstream/core/protocol_pin_test.go @@ -124,7 +124,7 @@ func TestUpstreamHandshakeRequestsLegacyProtocolVersion(t *testing.T) { URL: upstream.URL, Enabled: true, } - client, err := NewClient("pin-probe", cfg, zap.NewNop(), nil, nil, nil, secret.NewResolver()) + client, err := NewClient("pin-probe", cfg, zap.NewNop(), nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) @@ -183,7 +183,7 @@ func TestUpstreamRejectsAModernNegotiatedEra(t *testing.T) { URL: upstream.URL, Enabled: true, } - client, err := NewClient("rogue-era", cfg, zap.NewNop(), nil, nil, nil, secret.NewResolver()) + client, err := NewClient("rogue-era", cfg, zap.NewNop(), nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) diff --git a/internal/upstream/core/retire_test.go b/internal/upstream/core/retire_test.go index 89e47c5f1..5e46c87e7 100644 --- a/internal/upstream/core/retire_test.go +++ b/internal/upstream/core/retire_test.go @@ -36,7 +36,7 @@ import ( func newRetireCoreClient(t *testing.T, cfg *config.ServerConfig, st *storage.BoltDB) *Client { t.Helper() - c, err := NewClient(cfg.Name, cfg, zap.NewNop(), nil, &config.Config{}, st, secret.NewResolver()) + c, err := NewClient(cfg.Name, cfg, zap.NewNop(), nil, &config.Config{}, st, secret.NewTestWildcardResolver()) require.NoError(t, err) return c } diff --git a/internal/upstream/core/secret_env_fields_test.go b/internal/upstream/core/secret_env_fields_test.go new file mode 100644 index 000000000..bcf1e6dfc --- /dev/null +++ b/internal/upstream/core/secret_env_fields_test.go @@ -0,0 +1,38 @@ +package core + +import ( + "context" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" + "github.com/stretchr/testify/require" +) + +func TestUpstreamEnvGuard_AllServerFields(t *testing.T) { + ref := "${env:MCPPROXY_API_KEY}" + r := secret.NewResolverWithOptions(secret.ResolverOptions{ + Scope: secret.ScopeUpstream, + FilePolicy: secret.NewWildcardFilePolicy(secret.ScopeUpstream), + }) + + srv := &config.ServerConfig{ + Name: "test", + Command: ref, + URL: ref, + Args: []string{ref}, + Env: map[string]string{"K": ref}, + Headers: map[string]string{"H": ref}, + OAuth: &config.OAuthConfig{ + ClientSecret: ref, + }, + Isolation: &config.IsolationConfig{ + WorkingDir: ref, + }, + } + errs := r.ExpandStructSecretsCollectErrors(context.Background(), srv) + require.NotEmpty(t, errs) + for _, e := range errs { + require.ErrorIs(t, e.Err, secret.ErrReservedEnvVar, e.FieldPath) + } +} diff --git a/internal/upstream/core/secret_policy.go b/internal/upstream/core/secret_policy.go new file mode 100644 index 000000000..fbf90e079 --- /dev/null +++ b/internal/upstream/core/secret_policy.go @@ -0,0 +1,38 @@ +package core + +import ( + "errors" + "fmt" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" +) + +// ErrUpstreamSecretPolicy blocks connect/spawn for one upstream without stopping the daemon. +var ErrUpstreamSecretPolicy = errors.New("upstream secret reference refused by policy") + +// UpstreamSecretPolicyError carries the fixed public message for status, doctor and logs. +type UpstreamSecretPolicyError struct { + ServerName string + Public string + Field string +} + +func (e *UpstreamSecretPolicyError) Error() string { + if e == nil { + return "" + } + return fmt.Sprintf("server %q: %s", e.ServerName, e.Public) +} + +func (e *UpstreamSecretPolicyError) Unwrap() error { + return ErrUpstreamSecretPolicy +} + +func policyExpansionError(serverName string, e secret.SecretExpansionError) *UpstreamSecretPolicyError { + pub := secret.PublicPolicyMessage(e.Err) + return &UpstreamSecretPolicyError{ + ServerName: serverName, + Public: pub, + Field: e.FieldPath, + } +} diff --git a/internal/upstream/core/secret_policy_test.go b/internal/upstream/core/secret_policy_test.go new file mode 100644 index 000000000..af02cfce7 --- /dev/null +++ b/internal/upstream/core/secret_policy_test.go @@ -0,0 +1,28 @@ +package core + +import ( + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" + "github.com/stretchr/testify/require" + "go.uber.org/zap" +) + +func TestNewClientWithOptions_PolicyDenialFailsClient(t *testing.T) { + srv := &config.ServerConfig{ + Name: "blocked", + Command: "echo", + Env: map[string]string{"K": "${env:MCPPROXY_API_KEY}"}, + } + r := secret.NewResolverWithOptions(secret.ResolverOptions{ + Scope: secret.ScopeUpstream, + FilePolicy: secret.NewWildcardFilePolicy(secret.ScopeUpstream), + }) + _, err := NewClientWithOptions("id", srv, zap.NewNop(), nil, &config.Config{}, nil, false, r) + require.Error(t, err) + require.ErrorIs(t, err, ErrUpstreamSecretPolicy) + var pe *UpstreamSecretPolicyError + require.ErrorAs(t, err, &pe) + require.Equal(t, secret.ErrReservedEnvVar.Error(), pe.Public) +} diff --git a/internal/upstream/core/session_reinit_mcpgo_test.go b/internal/upstream/core/session_reinit_mcpgo_test.go index 0ff2f60a0..a8419ca9d 100644 --- a/internal/upstream/core/session_reinit_mcpgo_test.go +++ b/internal/upstream/core/session_reinit_mcpgo_test.go @@ -144,7 +144,7 @@ func TestCoreSessionSnapshotAndReinitialize(t *testing.T) { defer srv.Close() cfg := &config.ServerConfig{Name: "sess", Protocol: "streamable-http", URL: srv.URL, Enabled: true} - c, err := NewClient("sess", cfg, zap.NewNop(), nil, nil, nil, secret.NewResolver()) + c, err := NewClient("sess", cfg, zap.NewNop(), nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() diff --git a/internal/upstream/docker_dependency_test.go b/internal/upstream/docker_dependency_test.go index 38898b589..26d12442d 100644 --- a/internal/upstream/docker_dependency_test.go +++ b/internal/upstream/docker_dependency_test.go @@ -26,7 +26,7 @@ import ( func TestConnectBudget_ServerRunningDockerItself(t *testing.T) { logger := zap.NewNop() gc := &config.Config{DockerIsolation: &config.DockerIsolationConfig{Enabled: true}} - m := NewManager(logger, gc, nil, secret.NewResolver(), nil) + m := NewManager(logger, gc, nil, secret.NewTestWildcardResolver(), nil) sc := &config.ServerConfig{ Name: "already-dockerised", @@ -35,7 +35,7 @@ func TestConnectBudget_ServerRunningDockerItself(t *testing.T) { Protocol: "stdio", Enabled: true, } - client, err := managed.NewClient("already-dockerised", sc, logger, nil, gc, nil, secret.NewResolver()) + client, err := managed.NewClient("already-dockerised", sc, logger, nil, gc, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) assert.Equal(t, 3*time.Minute, m.resolveConnectTimeout(sc, client.DependsOnDocker()), diff --git a/internal/upstream/init_timeout_test.go b/internal/upstream/init_timeout_test.go index 109de80fc..1effed171 100644 --- a/internal/upstream/init_timeout_test.go +++ b/internal/upstream/init_timeout_test.go @@ -24,37 +24,37 @@ func TestResolveConnectTimeout(t *testing.T) { logger := zap.NewNop() t.Run("unset → 30s default (no regression)", func(t *testing.T) { - m := NewManager(logger, &config.Config{}, nil, secret.NewResolver(), nil) + m := NewManager(logger, &config.Config{}, nil, secret.NewTestWildcardResolver(), nil) sc := &config.ServerConfig{Name: "s"} assert.Equal(t, 30*time.Second, m.resolveConnectTimeout(sc, false)) }) t.Run("per-server init_timeout honored on un-isolated stdio (the #760 bite)", func(t *testing.T) { - m := NewManager(logger, &config.Config{}, nil, secret.NewResolver(), nil) + m := NewManager(logger, &config.Config{}, nil, secret.NewTestWildcardResolver(), nil) sc := &config.ServerConfig{Name: "slack", InitTimeout: durPtr(120 * time.Second)} assert.Equal(t, 120*time.Second, m.resolveConnectTimeout(sc, false)) }) t.Run("global init_timeout applies when server unset", func(t *testing.T) { - m := NewManager(logger, &config.Config{InitTimeout: durPtr(90 * time.Second)}, nil, secret.NewResolver(), nil) + m := NewManager(logger, &config.Config{InitTimeout: durPtr(90 * time.Second)}, nil, secret.NewTestWildcardResolver(), nil) sc := &config.ServerConfig{Name: "s"} assert.Equal(t, 90*time.Second, m.resolveConnectTimeout(sc, false)) }) t.Run("per-server overrides global", func(t *testing.T) { - m := NewManager(logger, &config.Config{InitTimeout: durPtr(90 * time.Second)}, nil, secret.NewResolver(), nil) + m := NewManager(logger, &config.Config{InitTimeout: durPtr(90 * time.Second)}, nil, secret.NewTestWildcardResolver(), nil) sc := &config.ServerConfig{Name: "s", InitTimeout: durPtr(45 * time.Second)} assert.Equal(t, 45*time.Second, m.resolveConnectTimeout(sc, false)) }) t.Run("docker-isolated keeps 3m floor for small init_timeout", func(t *testing.T) { - m := NewManager(logger, &config.Config{}, nil, secret.NewResolver(), nil) + m := NewManager(logger, &config.Config{}, nil, secret.NewTestWildcardResolver(), nil) sc := &config.ServerConfig{Name: "s", InitTimeout: durPtr(30 * time.Second)} assert.Equal(t, 3*time.Minute, m.resolveConnectTimeout(sc, true)) }) t.Run("docker-isolated honors a larger init_timeout above the floor", func(t *testing.T) { - m := NewManager(logger, &config.Config{}, nil, secret.NewResolver(), nil) + m := NewManager(logger, &config.Config{}, nil, secret.NewTestWildcardResolver(), nil) sc := &config.ServerConfig{Name: "s", InitTimeout: durPtr(10 * time.Minute)} assert.Equal(t, 10*time.Minute, m.resolveConnectTimeout(sc, true)) }) diff --git a/internal/upstream/listtools_logging_test.go b/internal/upstream/listtools_logging_test.go index c18218b39..7fa775d7f 100644 --- a/internal/upstream/listtools_logging_test.go +++ b/internal/upstream/listtools_logging_test.go @@ -29,7 +29,7 @@ func newObservedManager(t *testing.T) (*Manager, *observer.ObservedLogs) { require.NoError(t, err) t.Cleanup(func() { _ = storageManager.Close() }) - m := NewManager(zap.New(core), cfg, storageManager, secret.NewResolver(), nil) + m := NewManager(zap.New(core), cfg, storageManager, secret.NewTestWildcardResolver(), nil) t.Cleanup(func() { m.DisconnectAll() }) return m, logs } diff --git a/internal/upstream/managed/connect_disconnect_race_test.go b/internal/upstream/managed/connect_disconnect_race_test.go index 43cc6cefc..5c9cfb52b 100644 --- a/internal/upstream/managed/connect_disconnect_race_test.go +++ b/internal/upstream/managed/connect_disconnect_race_test.go @@ -35,7 +35,7 @@ func TestConnect_DisconnectDuringDialDoesNotReportReady(t *testing.T) { t.Cleanup(func() { closeHTTPFixture(ts) }) cfg := &config.ServerConfig{Name: "race-server", Protocol: "streamable-http", URL: ts.URL, Enabled: true} - mc, err := NewClient("race-server", cfg, zap.NewNop(), nil, nil, nil, secret.NewResolver()) + mc, err := NewClient("race-server", cfg, zap.NewNop(), nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) t.Cleanup(func() { _ = mc.Disconnect() }) @@ -82,7 +82,7 @@ func TestConnect_DisconnectDuringFailingDialKeepsDisconnected(t *testing.T) { closeHTTPFixture(ts) cfg := &config.ServerConfig{Name: "race-fail", Protocol: "streamable-http", URL: deadURL, Enabled: true} - mc, err := NewClient("race-fail", cfg, zap.NewNop(), nil, nil, nil, secret.NewResolver()) + mc, err := NewClient("race-fail", cfg, zap.NewNop(), nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) t.Cleanup(func() { _ = mc.Disconnect() }) @@ -119,7 +119,7 @@ func TestConnect_NewerAttemptSupersedesTheOlderOne(t *testing.T) { t.Cleanup(func() { closeHTTPFixture(ts) }) cfg := &config.ServerConfig{Name: "race-newer", Protocol: "streamable-http", URL: ts.URL, Enabled: true} - mc, err := NewClient("race-newer", cfg, zap.NewNop(), nil, nil, nil, secret.NewResolver()) + mc, err := NewClient("race-newer", cfg, zap.NewNop(), nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) t.Cleanup(func() { _ = mc.Disconnect() }) @@ -166,7 +166,7 @@ func TestConnect_ReconnectTeardownSupersedesADialingAttempt(t *testing.T) { t.Cleanup(func() { closeHTTPFixture(ts) }) cfg := &config.ServerConfig{Name: "race-reconnect", Protocol: "streamable-http", URL: ts.URL, Enabled: true} - mc, err := NewClient("race-reconnect", cfg, zap.NewNop(), nil, nil, nil, secret.NewResolver()) + mc, err := NewClient("race-reconnect", cfg, zap.NewNop(), nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) t.Cleanup(func() { _ = mc.Disconnect() }) @@ -228,7 +228,7 @@ func TestConnect_AttemptAdmittedAfterReconnectTeardownOwnsTheClient(t *testing.T t.Cleanup(func() { closeHTTPFixture(ts) }) cfg := &config.ServerConfig{Name: "race-admitted", Protocol: "streamable-http", URL: ts.URL, Enabled: true} - mc, err := NewClient("race-admitted", cfg, zap.NewNop(), nil, nil, nil, secret.NewResolver()) + mc, err := NewClient("race-admitted", cfg, zap.NewNop(), nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) t.Cleanup(func() { _ = mc.Disconnect() }) @@ -268,7 +268,7 @@ func TestReconnectTeardown_ExcludesConnectAdmission(t *testing.T) { for _, helper := range []string{"TryReconnectSync", "tryReconnect"} { t.Run(helper, func(t *testing.T) { cfg := &config.ServerConfig{Name: "race-window", Protocol: "streamable-http", URL: ts.URL, Enabled: true} - mc, err := NewClient("race-window", cfg, zap.NewNop(), nil, nil, nil, secret.NewResolver()) + mc, err := NewClient("race-window", cfg, zap.NewNop(), nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) t.Cleanup(func() { _ = mc.Disconnect() }) diff --git a/internal/upstream/managed/dead_transport_fixture_test.go b/internal/upstream/managed/dead_transport_fixture_test.go index e63446ff7..99d0d7778 100644 --- a/internal/upstream/managed/dead_transport_fixture_test.go +++ b/internal/upstream/managed/dead_transport_fixture_test.go @@ -67,7 +67,7 @@ func TestStdioChildKilled_ClientLeavesReadyAndRespawns(t *testing.T) { Enabled: true, HealthCheckInterval: &interval, } - mc, err := NewClient(cfg.Name, cfg, zap.NewNop(), nil, &config.Config{}, nil, secret.NewResolver()) + mc, err := NewClient(cfg.Name, cfg, zap.NewNop(), nil, &config.Config{}, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) diff --git a/internal/upstream/managed/headerfwd_test.go b/internal/upstream/managed/headerfwd_test.go index 0d7492df9..2f0a5abbb 100644 --- a/internal/upstream/managed/headerfwd_test.go +++ b/internal/upstream/managed/headerfwd_test.go @@ -72,7 +72,7 @@ func (u *mgdUpstream) handler() http.Handler { func TestManagedForwardPolicy_LiveFromAtomicConfigs(t *testing.T) { cfg := &config.ServerConfig{Name: "s", Protocol: "streamable-http", URL: "http://127.0.0.1:1/mcp", ForwardHeaders: []string{"X-Tenant-Id"}, Headers: map[string]string{"X-Static": "v"}} - mc, err := NewClient("s", cfg, zap.NewNop(), nil, &config.Config{}, nil, secret.NewResolver()) + mc, err := NewClient("s", cfg, zap.NewNop(), nil, &config.Config{}, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) p := mc.forwardPolicy() @@ -102,7 +102,7 @@ func TestManagedCallTool_HotReloadNoReconnect(t *testing.T) { cfg := &config.ServerConfig{Name: "s", Protocol: "streamable-http", URL: srv.URL, Enabled: true, ForwardHeaders: []string{"X-Tenant-Id"}} - mc, err := NewClient("s", cfg, zap.NewNop(), nil, &config.Config{}, nil, secret.NewResolver()) + mc, err := NewClient("s", cfg, zap.NewNop(), nil, &config.Config{}, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() @@ -147,7 +147,7 @@ func TestManagedCallTool_HotReloadNoReconnect(t *testing.T) { func TestManagedWarnForwardHeaders_OnceNamesOnly(t *testing.T) { obsCore, logs := observer.New(zapcore.WarnLevel) mk := func(cfg *config.ServerConfig) *Client { - mc, err := NewClient(cfg.Name, cfg, zap.New(obsCore), nil, &config.Config{}, nil, secret.NewResolver()) + mc, err := NewClient(cfg.Name, cfg, zap.New(obsCore), nil, &config.Config{}, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) return mc } diff --git a/internal/upstream/managed/health_monitor_race_test.go b/internal/upstream/managed/health_monitor_race_test.go index 6aaeb3c69..4c443b6fb 100644 --- a/internal/upstream/managed/health_monitor_race_test.go +++ b/internal/upstream/managed/health_monitor_race_test.go @@ -174,7 +174,7 @@ func newStoppedLoopClient(t *testing.T, name string) (*Client, <-chan struct{}) t.Cleanup(func() { closeHTTPFixture(ts) }) cfg := &config.ServerConfig{Name: name, Protocol: "streamable-http", URL: ts.URL, Enabled: true} - mc, err := NewClient(name, cfg, zap.NewNop(), nil, nil, nil, secret.NewResolver()) + mc, err := NewClient(name, cfg, zap.NewNop(), nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) t.Cleanup(func() { _ = mc.Disconnect() }) diff --git a/internal/upstream/managed/pending_auth_probe_test.go b/internal/upstream/managed/pending_auth_probe_test.go index a1611a432..51d2a7d32 100644 --- a/internal/upstream/managed/pending_auth_probe_test.go +++ b/internal/upstream/managed/pending_auth_probe_test.go @@ -26,7 +26,7 @@ import ( func newLadderClient(t *testing.T, url string) *Client { t.Helper() cfg := &config.ServerConfig{Name: "gh1537", URL: url, Protocol: "streamable-http", Enabled: true, Created: time.Now()} - mc, err := NewClient(cfg.Name, cfg, zap.NewNop(), nil, &config.Config{}, nil, secret.NewResolver()) + mc, err := NewClient(cfg.Name, cfg, zap.NewNop(), nil, &config.Config{}, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) return mc } diff --git a/internal/upstream/managed/prompts_test.go b/internal/upstream/managed/prompts_test.go index 3756153eb..2c45b7812 100644 --- a/internal/upstream/managed/prompts_test.go +++ b/internal/upstream/managed/prompts_test.go @@ -62,7 +62,7 @@ func connectedManagedTestClient(t *testing.T, url string) *Client { URL: url, Enabled: true, } - mc, err := NewClient("test-client", cfg, zap.NewNop(), nil, nil, nil, secret.NewResolver()) + mc, err := NewClient("test-client", cfg, zap.NewNop(), nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) diff --git a/internal/upstream/managed/retry_after_test.go b/internal/upstream/managed/retry_after_test.go index d368444ee..45833ea8e 100644 --- a/internal/upstream/managed/retry_after_test.go +++ b/internal/upstream/managed/retry_after_test.go @@ -38,7 +38,7 @@ func coreClientThatWasRateLimited(t *testing.T, retryAfter string) *core.Client Protocol: "http", Enabled: true, Created: time.Now(), - }, zap.NewNop(), nil, nil, nil, secret.NewResolver()) + }, zap.NewNop(), nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) diff --git a/internal/upstream/managed/session_reinit_test.go b/internal/upstream/managed/session_reinit_test.go index f0a0d5429..e2fc9571b 100644 --- a/internal/upstream/managed/session_reinit_test.go +++ b/internal/upstream/managed/session_reinit_test.go @@ -143,7 +143,7 @@ func newSessionClient(t *testing.T) (*Client, *sessUpstream) { t.Cleanup(srv.Close) cfg := &config.ServerConfig{Name: "sess", Protocol: "streamable-http", URL: srv.URL, Enabled: true} - mc, err := NewClient("sess", cfg, zap.NewNop(), nil, &config.Config{}, nil, secret.NewResolver()) + mc, err := NewClient("sess", cfg, zap.NewNop(), nil, &config.Config{}, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() diff --git a/internal/upstream/managed/terminal_classification_test.go b/internal/upstream/managed/terminal_classification_test.go index babdd2006..4011951d6 100644 --- a/internal/upstream/managed/terminal_classification_test.go +++ b/internal/upstream/managed/terminal_classification_test.go @@ -19,7 +19,7 @@ import ( func newClientForConnect(t *testing.T, cfg *config.ServerConfig) *Client { t.Helper() t.Setenv("MCPPROXY_DISABLE_OAUTH", "true") - mc, err := NewClient(cfg.Name, cfg, zap.NewNop(), nil, &config.Config{}, nil, secret.NewResolver()) + mc, err := NewClient(cfg.Name, cfg, zap.NewNop(), nil, &config.Config{}, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) return mc } diff --git a/internal/upstream/manager.go b/internal/upstream/manager.go index 3048d6d0d..0a5afdf84 100644 --- a/internal/upstream/manager.go +++ b/internal/upstream/manager.go @@ -140,6 +140,9 @@ type Manager struct { storage *storage.BoltDB notificationMgr *NotificationManager secretResolver *secret.Resolver + // secretResolverMu guards secretResolver, which SetSecretResolver swaps on + // a secret_file_dirs hot reload while connects read it. + secretResolverMu sync.RWMutex // lastSweptAt tracks, per server name, the last time the periodic // tool-discovery sweep listed that server's tools. Used to honor per-server @@ -268,6 +271,24 @@ func cloneServerConfig(cfg *config.ServerConfig) *config.ServerConfig { return &clone } +// SetSecretResolver replaces the resolver used when expanding upstream server +// secrets (hot-reloaded secret_file_dirs). +func (m *Manager) SetSecretResolver(secretResolver *secret.Resolver) { + if m == nil { + return + } + m.secretResolverMu.Lock() + m.secretResolver = secretResolver + m.secretResolverMu.Unlock() +} + +// currentSecretResolver returns the resolver new clients are built with. +func (m *Manager) currentSecretResolver() *secret.Resolver { + m.secretResolverMu.RLock() + defer m.secretResolverMu.RUnlock() + return m.secretResolver +} + // NewManager creates a new upstream manager func NewManager(logger *zap.Logger, globalConfig *config.Config, boltStorage *storage.BoltDB, secretResolver *secret.Resolver, storageMgr *storage.Manager) *Manager { // Scope this process's Docker container-ownership instance ID to its data @@ -2972,7 +2993,7 @@ func (m *Manager) StartManualOAuth(serverName string, force bool) error { } // Create a transient core client that uses the daemon's storage - coreClient, err := core.NewClientWithOptions(cfg.Name, cfg, m.logger, m.logConfig, m.globalConfig.Load(), m.storage, false, m.secretResolver) + coreClient, err := core.NewClientWithOptions(cfg.Name, cfg, m.logger, m.logConfig, m.globalConfig.Load(), m.storage, false, m.currentSecretResolver()) if err == nil { // Spec 116 PR4 (FR-024): the login runs behind the registered // instance's gate, so retiring the instance (removal, replacement, @@ -3009,7 +3030,7 @@ func (m *Manager) StartManualOAuth(serverName string, force bool) error { noAuthTransport := transport.DetermineTransportType(&cpy) if noAuthTransport == "http" || noAuthTransport == "streamable-http" || noAuthTransport == "sse" { m.logger.Info("Running preflight no-auth initialize to check OAuth requirement", zap.String("server", cfg.Name)) - testClient, err2 := core.NewClientWithOptions(cfg.Name, &cpy, m.logger, m.logConfig, m.globalConfig.Load(), m.storage, false, m.secretResolver) + testClient, err2 := core.NewClientWithOptions(cfg.Name, &cpy, m.logger, m.logConfig, m.globalConfig.Load(), m.storage, false, m.currentSecretResolver()) if err2 == nil { testClient.SetGate(client.Gate()) testClient.SetCredentialBinding(client.CredentialBinding()) @@ -3068,7 +3089,7 @@ func (m *Manager) StartManualOAuthQuick(serverName string) (*core.OAuthStartResu } // Create a transient core client that uses the daemon's storage - coreClient, err := core.NewClientWithOptions(cfg.Name, cfg, m.logger, m.logConfig, m.globalConfig.Load(), m.storage, false, m.secretResolver) + coreClient, err := core.NewClientWithOptions(cfg.Name, cfg, m.logger, m.logConfig, m.globalConfig.Load(), m.storage, false, m.currentSecretResolver()) if err != nil { return nil, fmt.Errorf("failed to create core client for OAuth: %w", err) } @@ -3187,7 +3208,7 @@ func (m *Manager) StartManualOAuthWithInfo(serverName string, force bool) (*core } // Create a transient core client that uses the daemon's storage - coreClient, err := core.NewClientWithOptions(cfg.Name, cfg, m.logger, m.logConfig, m.globalConfig.Load(), m.storage, false, m.secretResolver) + coreClient, err := core.NewClientWithOptions(cfg.Name, cfg, m.logger, m.logConfig, m.globalConfig.Load(), m.storage, false, m.currentSecretResolver()) if err == nil { // Spec 116 PR4 (FR-024): the login runs behind the registered // instance's gate, so retiring the instance (removal, replacement, @@ -3216,7 +3237,7 @@ func (m *Manager) StartManualOAuthWithInfo(serverName string, force bool) (*core noAuthTransport := transport.DetermineTransportType(&cpy) if noAuthTransport == "http" || noAuthTransport == "streamable-http" || noAuthTransport == "sse" { m.logger.Info("Running preflight no-auth initialize to check OAuth requirement", zap.String("server", cfg.Name)) - testClient, err2 := core.NewClientWithOptions(cfg.Name, &cpy, m.logger, m.logConfig, m.globalConfig.Load(), m.storage, false, m.secretResolver) + testClient, err2 := core.NewClientWithOptions(cfg.Name, &cpy, m.logger, m.logConfig, m.globalConfig.Load(), m.storage, false, m.currentSecretResolver()) if err2 == nil { testClient.SetGate(client.Gate()) testClient.SetCredentialBinding(client.CredentialBinding()) diff --git a/internal/upstream/manager_bench_test.go b/internal/upstream/manager_bench_test.go index 0ac59c6f4..5acdf360c 100644 --- a/internal/upstream/manager_bench_test.go +++ b/internal/upstream/manager_bench_test.go @@ -20,7 +20,7 @@ func BenchmarkAddServer(b *testing.B) { storageManager, _ := storage.NewBoltDB(tmpDir, zap.NewNop().Sugar()) defer storageManager.Close() - manager := NewManager(logger, cfg, storageManager, secret.NewResolver(), nil) + manager := NewManager(logger, cfg, storageManager, secret.NewTestWildcardResolver(), nil) defer manager.DisconnectAll() serverConfig := &config.ServerConfig{ @@ -45,7 +45,7 @@ func BenchmarkConnectAll(b *testing.B) { storageManager, _ := storage.NewBoltDB(tmpDir, zap.NewNop().Sugar()) defer storageManager.Close() - manager := NewManager(logger, cfg, storageManager, secret.NewResolver(), nil) + manager := NewManager(logger, cfg, storageManager, secret.NewTestWildcardResolver(), nil) defer manager.DisconnectAll() // Add several disconnected servers @@ -77,7 +77,7 @@ func BenchmarkDiscoverTools(b *testing.B) { storageManager, _ := storage.NewBoltDB(tmpDir, zap.NewNop().Sugar()) defer storageManager.Close() - manager := NewManager(logger, cfg, storageManager, secret.NewResolver(), nil) + manager := NewManager(logger, cfg, storageManager, secret.NewTestWildcardResolver(), nil) defer manager.DisconnectAll() // Add servers (they won't connect, but structure is present) @@ -109,7 +109,7 @@ func BenchmarkGetStats(b *testing.B) { storageManager, _ := storage.NewBoltDB(tmpDir, zap.NewNop().Sugar()) defer storageManager.Close() - manager := NewManager(logger, cfg, storageManager, secret.NewResolver(), nil) + manager := NewManager(logger, cfg, storageManager, secret.NewTestWildcardResolver(), nil) defer manager.DisconnectAll() // Add several servers @@ -138,7 +138,7 @@ func BenchmarkCallToolWithLock(b *testing.B) { storageManager, _ := storage.NewBoltDB(tmpDir, zap.NewNop().Sugar()) defer storageManager.Close() - manager := NewManager(logger, cfg, storageManager, secret.NewResolver(), nil) + manager := NewManager(logger, cfg, storageManager, secret.NewTestWildcardResolver(), nil) defer manager.DisconnectAll() serverConfig := &config.ServerConfig{ @@ -167,7 +167,7 @@ func BenchmarkRemoveServer(b *testing.B) { storageManager, _ := storage.NewBoltDB(tmpDir, zap.NewNop().Sugar()) defer storageManager.Close() - manager := NewManager(logger, cfg, storageManager, secret.NewResolver(), nil) + manager := NewManager(logger, cfg, storageManager, secret.NewTestWildcardResolver(), nil) defer manager.DisconnectAll() b.ResetTimer() diff --git a/internal/upstream/manager_callhealth_notify_test.go b/internal/upstream/manager_callhealth_notify_test.go index ad0794a0c..52e189d46 100644 --- a/internal/upstream/manager_callhealth_notify_test.go +++ b/internal/upstream/manager_callhealth_notify_test.go @@ -52,7 +52,7 @@ func (n *notifyRecorder) count() int { func newNotifyManager(t *testing.T) (*Manager, *notifyRecorder, *fakeClock) { t.Helper() - m := NewManager(zap.NewNop(), &config.Config{}, nil, secret.NewResolver(), nil) + m := NewManager(zap.NewNop(), &config.Config{}, nil, secret.NewTestWildcardResolver(), nil) t.Cleanup(func() { m.shutdownCancel(); m.stopCallHealthTimers() }) now := &fakeClock{t: time.Date(2026, 10, 5, 12, 0, 0, 0, time.UTC)} m.callStats.SetClock(now.Now) diff --git a/internal/upstream/manager_container_ownership_test.go b/internal/upstream/manager_container_ownership_test.go index adf3ed841..4e6941e7a 100644 --- a/internal/upstream/manager_container_ownership_test.go +++ b/internal/upstream/manager_container_ownership_test.go @@ -284,7 +284,7 @@ func newSweepManager(t *testing.T) (*Manager, *observer.ObservedLogs) { t.Helper() t.Setenv("CI", "") mainCore, mainLogs := observer.New(zap.DebugLevel) - m := NewManager(zap.New(mainCore), &config.Config{}, nil, secret.NewResolver(), nil) + m := NewManager(zap.New(mainCore), &config.Config{}, nil, secret.NewTestWildcardResolver(), nil) t.Cleanup(func() { m.shutdownCancel() }) for _, name := range []string{"a", "a/b"} { require.NoError(t, m.AddServerConfig(name, &config.ServerConfig{Name: name, Protocol: "http", URL: "http://127.0.0.1:1/mcp", Enabled: false})) @@ -483,7 +483,7 @@ func TestHasDockerContainers_AppliesCanonicalOwnership(t *testing.T) { func TestSweeps_NoConfiguredServers_MutateNothing(t *testing.T) { fd := installManagerFakeDocker(t, sweepFixture(core.GetInstanceID())) t.Setenv("CI", "") - m := NewManager(zap.NewNop(), &config.Config{}, nil, secret.NewResolver(), nil) + m := NewManager(zap.NewNop(), &config.Config{}, nil, secret.NewTestWildcardResolver(), nil) t.Cleanup(func() { m.shutdownCancel() }) m.cleanupAllManagedContainers(context.Background()) diff --git a/internal/upstream/manager_generation.go b/internal/upstream/manager_generation.go index c14c6016e..0221feaaf 100644 --- a/internal/upstream/manager_generation.go +++ b/internal/upstream/manager_generation.go @@ -372,7 +372,7 @@ func (m *Manager) installLocked(name string, client *managed.Client) { // the manager's callbacks and admission control into it before it becomes // reachable. Caller holds mu. func (m *Manager) newWiredClientLocked(id string, cfg *config.ServerConfig, gen int64) (*managed.Client, error) { - client, err := managed.NewClientAt(id, cfg, gen, m.logger, m.logConfig, m.globalConfig.Load(), m.storage, m.secretResolver) + client, err := managed.NewClientAt(id, cfg, gen, m.logger, m.logConfig, m.globalConfig.Load(), m.storage, m.currentSecretResolver()) if err != nil { return nil, fmt.Errorf("failed to create client for server %s: %w", cfg.Name, err) } diff --git a/internal/upstream/manager_generation_test.go b/internal/upstream/manager_generation_test.go index 37fb331ad..181c86b35 100644 --- a/internal/upstream/manager_generation_test.go +++ b/internal/upstream/manager_generation_test.go @@ -32,7 +32,7 @@ func newGenTestManager(t *testing.T) *Manager { desired: make(map[string]desiredGen), logger: zap.NewNop(), storage: db, - secretResolver: secret.NewResolver(), + secretResolver: secret.NewTestWildcardResolver(), callStats: callstats.NewRegistry(), } m.globalConfig.Store(&config.Config{}) diff --git a/internal/upstream/manager_oauth_failure_test.go b/internal/upstream/manager_oauth_failure_test.go index c6ccbc5c4..49e4da0fb 100644 --- a/internal/upstream/manager_oauth_failure_test.go +++ b/internal/upstream/manager_oauth_failure_test.go @@ -35,10 +35,10 @@ func newFailureTestManager(t *testing.T, serverName string) (*Manager, *managed. manager := &Manager{ clients: make(map[string]*managed.Client), logger: logger, - secretResolver: secret.NewResolver(), + secretResolver: secret.NewTestWildcardResolver(), } - client, err := managed.NewClient(serverName, serverConfig, logger, nil, &config.Config{}, nil, secret.NewResolver()) + client, err := managed.NewClient(serverName, serverConfig, logger, nil, &config.Config{}, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) manager.clients[serverName] = client diff --git a/internal/upstream/manager_oauth_test.go b/internal/upstream/manager_oauth_test.go index 176148952..41a0e1a06 100644 --- a/internal/upstream/manager_oauth_test.go +++ b/internal/upstream/manager_oauth_test.go @@ -80,7 +80,7 @@ func TestRefreshOAuthToken_DynamicOAuthDiscovery(t *testing.T) { clients: make(map[string]*managed.Client), logger: logger, storage: db, - secretResolver: secret.NewResolver(), + secretResolver: secret.NewTestWildcardResolver(), } // Create a managed client for the server @@ -91,7 +91,7 @@ func TestRefreshOAuthToken_DynamicOAuthDiscovery(t *testing.T) { nil, // logConfig &config.Config{}, // globalConfig db, // bolt storage - secret.NewResolver(), + secret.NewTestWildcardResolver(), ) require.NoError(t, err) manager.clients["test-dynamic-oauth"] = client @@ -140,7 +140,7 @@ func TestRefreshOAuthToken_StaticOAuthConfig(t *testing.T) { clients: make(map[string]*managed.Client), logger: logger, storage: db, - secretResolver: secret.NewResolver(), + secretResolver: secret.NewTestWildcardResolver(), } client, err := managed.NewClient( @@ -150,7 +150,7 @@ func TestRefreshOAuthToken_StaticOAuthConfig(t *testing.T) { nil, &config.Config{}, db, - secret.NewResolver(), + secret.NewTestWildcardResolver(), ) require.NoError(t, err) manager.clients["test-static-oauth"] = client @@ -245,12 +245,12 @@ func TestScanForNewTokens_OnlyOnNewToken(t *testing.T) { clients: make(map[string]*managed.Client), logger: logger, storage: db, - secretResolver: secret.NewResolver(), + secretResolver: secret.NewTestWildcardResolver(), tokenReconnect: make(map[string]time.Time), tokenFingerprints: make(map[string]string), } - client, err := managed.NewClient("parked-server", serverConfig, logger, nil, &config.Config{}, db, secret.NewResolver()) + client, err := managed.NewClient("parked-server", serverConfig, logger, nil, &config.Config{}, db, secret.NewTestWildcardResolver()) require.NoError(t, err) manager.clients["parked-server"] = client diff --git a/internal/upstream/manager_prompts_test.go b/internal/upstream/manager_prompts_test.go index 8288eb1a6..6e22a9dc1 100644 --- a/internal/upstream/manager_prompts_test.go +++ b/internal/upstream/manager_prompts_test.go @@ -49,7 +49,7 @@ func newTestManager(t *testing.T) *Manager { require.NoError(t, err) t.Cleanup(func() { _ = storageManager.Close() }) - m := NewManager(zap.NewNop(), cfg, storageManager, secret.NewResolver(), nil) + m := NewManager(zap.NewNop(), cfg, storageManager, secret.NewTestWildcardResolver(), nil) t.Cleanup(func() { m.DisconnectAll() }) return m } diff --git a/internal/upstream/manager_reconnect_test.go b/internal/upstream/manager_reconnect_test.go index 9e66841f7..01acbafd9 100644 --- a/internal/upstream/manager_reconnect_test.go +++ b/internal/upstream/manager_reconnect_test.go @@ -34,7 +34,7 @@ func createTestManagerWithClient(t *testing.T, serverConfig *config.ServerConfig clients: make(map[string]*managed.Client), logger: logger, storage: db, - secretResolver: secret.NewResolver(), + secretResolver: secret.NewTestWildcardResolver(), } client, err := managed.NewClient( @@ -44,7 +44,7 @@ func createTestManagerWithClient(t *testing.T, serverConfig *config.ServerConfig nil, &config.Config{}, db, - secret.NewResolver(), + secret.NewTestWildcardResolver(), ) require.NoError(t, err) manager.clients[serverConfig.Name] = client @@ -232,7 +232,7 @@ func TestTryReconnectSync_PreventsStorms(t *testing.T) { nil, &config.Config{}, db, - secret.NewResolver(), + secret.NewTestWildcardResolver(), ) require.NoError(t, err) @@ -288,7 +288,7 @@ func TestTryReconnectSync_RespectsContextCancellation(t *testing.T) { nil, &config.Config{}, db, - secret.NewResolver(), + secret.NewTestWildcardResolver(), ) require.NoError(t, err) diff --git a/internal/upstream/manager_retire_test.go b/internal/upstream/manager_retire_test.go index de19f942e..43f29ca8b 100644 --- a/internal/upstream/manager_retire_test.go +++ b/internal/upstream/manager_retire_test.go @@ -21,7 +21,7 @@ func retireTestServer(url string) *config.ServerConfig { func TestManager_EndpointReplacementRetiresOldClient(t *testing.T) { t.Setenv("CI", "") - m := NewManager(zap.NewNop(), &config.Config{}, nil, secret.NewResolver(), nil) + m := NewManager(zap.NewNop(), &config.Config{}, nil, secret.NewTestWildcardResolver(), nil) t.Cleanup(func() { m.shutdownCancel() }) require.NoError(t, m.AddServerConfig("srv", retireTestServer("http://127.0.0.1:1/a"))) diff --git a/internal/upstream/manager_url_redact_test.go b/internal/upstream/manager_url_redact_test.go index 8ef7cc436..95bb1420c 100644 --- a/internal/upstream/manager_url_redact_test.go +++ b/internal/upstream/manager_url_redact_test.go @@ -74,7 +74,7 @@ func TestConnectAll_DoesNotLogTheConfiguredURLCredential(t *testing.T) { "precondition: the site under test must have run") } -func secret2Resolver() *secret.Resolver { return secret.NewResolver() } +func secret2Resolver() *secret.Resolver { return secret.NewTestWildcardResolver() } func hasEntryContaining(entries []observer.LoggedEntry, msg string) bool { for _, e := range entries { diff --git a/internal/upstream/manual_oauth_relogin_test.go b/internal/upstream/manual_oauth_relogin_test.go index d00d0f52e..2abcdf6fb 100644 --- a/internal/upstream/manual_oauth_relogin_test.go +++ b/internal/upstream/manual_oauth_relogin_test.go @@ -42,7 +42,7 @@ func TestStartManualOAuthQuick_RecentCompletionDoesNotCancelLogin(t *testing.T) } }) - m := NewManager(zap.NewNop(), &config.Config{}, db, secret.NewResolver(), nil) + m := NewManager(zap.NewNop(), &config.Config{}, db, secret.NewTestWildcardResolver(), nil) t.Cleanup(func() { m.shutdownCancel() }) require.NoError(t, m.AddServerConfig(name, &config.ServerConfig{ Name: name, URL: srv.MCPURL, Protocol: "http", Enabled: true, diff --git a/internal/upstream/retire_manual_oauth_test.go b/internal/upstream/retire_manual_oauth_test.go index ad2750f1b..977358d7c 100644 --- a/internal/upstream/retire_manual_oauth_test.go +++ b/internal/upstream/retire_manual_oauth_test.go @@ -42,7 +42,7 @@ func newManualOAuthManager(t *testing.T, url string) *Manager { t.Helper() t.Setenv("CI", "") t.Setenv("HEADLESS", "") - m := NewManager(zap.NewNop(), &config.Config{}, nil, secret.NewResolver(), nil) + m := NewManager(zap.NewNop(), &config.Config{}, nil, secret.NewTestWildcardResolver(), nil) t.Cleanup(func() { m.shutdownCancel() }) require.NoError(t, m.AddServerConfig("srv", &config.ServerConfig{ Name: "srv", URL: url, Protocol: "http", Enabled: true, diff --git a/internal/upstream/retry_after_connect_test.go b/internal/upstream/retry_after_connect_test.go index 7fb0f2799..4f4e1ff60 100644 --- a/internal/upstream/retry_after_connect_test.go +++ b/internal/upstream/retry_after_connect_test.go @@ -51,7 +51,7 @@ func connectToRateLimited(t *testing.T, url, protocol string, headers ...map[str cfg.Headers = headers[0] } - client, err := managed.NewClient("retry-after-test", cfg, zap.NewNop(), nil, nil, nil, secret.NewResolver()) + client, err := managed.NewClient("retry-after-test", cfg, zap.NewNop(), nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) @@ -183,7 +183,7 @@ func TestConnect_RetryAfterIsPerAttempt(t *testing.T) { Created: time.Now(), } - client, err := core.NewClient("retry-after-attempt-test", cfg, zap.NewNop(), nil, nil, nil, secret.NewResolver()) + client, err := core.NewClient("retry-after-attempt-test", cfg, zap.NewNop(), nil, nil, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) diff --git a/internal/upstream/secret_resolver_swap_test.go b/internal/upstream/secret_resolver_swap_test.go new file mode 100644 index 000000000..b6673ca72 --- /dev/null +++ b/internal/upstream/secret_resolver_swap_test.go @@ -0,0 +1,34 @@ +package upstream + +import ( + "sync" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" +) + +// A secret_file_dirs hot reload swaps the resolver while connects read it; +// under -race this fails if the swap is unsynchronised. +func TestManager_SetSecretResolverConcurrentWithReads(t *testing.T) { + m := &Manager{secretResolver: secret.NewTestWildcardResolver()} + var wg sync.WaitGroup + for i := 0; i < 4; i++ { + wg.Add(2) + go func() { + defer wg.Done() + for j := 0; j < 200; j++ { + m.SetSecretResolver(secret.NewTestWildcardResolver()) + } + }() + go func() { + defer wg.Done() + for j := 0; j < 200; j++ { + if m.currentSecretResolver() == nil { + t.Error("resolver is nil") + return + } + } + }() + } + wg.Wait() +} diff --git a/internal/upstream/secure_env_integration_test.go b/internal/upstream/secure_env_integration_test.go index 7729465b9..b3da29757 100644 --- a/internal/upstream/secure_env_integration_test.go +++ b/internal/upstream/secure_env_integration_test.go @@ -70,7 +70,7 @@ func TestSecureEnvironmentIntegration(t *testing.T) { // Create upstream client logger := zap.NewNop() - client, err := managed.NewClient("test-id", serverConfig, logger, nil, cfg, nil, secret.NewResolver()) + client, err := managed.NewClient("test-id", serverConfig, logger, nil, cfg, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) require.NotNil(t, client) @@ -154,7 +154,7 @@ func TestConfigurationIntegration(t *testing.T) { cfg := config.DefaultConfig() logger := zap.NewNop() - manager := NewManager(logger, cfg, nil, secret.NewResolver(), nil) + manager := NewManager(logger, cfg, nil, secret.NewTestWildcardResolver(), nil) require.NotNil(t, manager) assert.Equal(t, cfg, manager.globalConfig.Load()) }) @@ -183,7 +183,7 @@ func TestServerSpecificEnvironmentVariables(t *testing.T) { globalConfig.Environment.CustomVars["OVERRIDE_VAR"] = "global_value" logger := zap.NewNop() - client, err := managed.NewClient("test-id", serverConfig, logger, nil, globalConfig, nil, secret.NewResolver()) + client, err := managed.NewClient("test-id", serverConfig, logger, nil, globalConfig, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) envVars := client.GetEnvManager().(*secureenv.Manager).BuildSecureEnvironment() @@ -242,7 +242,7 @@ func TestEnvironmentInheritanceDisabled(t *testing.T) { } logger := zap.NewNop() - client, err := managed.NewClient("test-id", serverConfig, logger, nil, cfg, nil, secret.NewResolver()) + client, err := managed.NewClient("test-id", serverConfig, logger, nil, cfg, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) envVars := client.GetEnvManager().(*secureenv.Manager).BuildSecureEnvironment() @@ -293,7 +293,7 @@ func TestRealWorldNpxScenario(t *testing.T) { } logger := zap.NewNop() - client, err := managed.NewClient("test-id", serverConfig, logger, nil, cfg, nil, secret.NewResolver()) + client, err := managed.NewClient("test-id", serverConfig, logger, nil, cfg, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) // Verify that PATH is available in the secure environment @@ -356,7 +356,7 @@ func TestSecurityCompliance(t *testing.T) { } logger := zap.NewNop() - client, err := managed.NewClient("test-id", serverConfig, logger, nil, cfg, nil, secret.NewResolver()) + client, err := managed.NewClient("test-id", serverConfig, logger, nil, cfg, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) envVars := client.GetEnvManager().(*secureenv.Manager).BuildSecureEnvironment() @@ -409,7 +409,7 @@ func TestWildcardMatching(t *testing.T) { } logger := zap.NewNop() - client, err := managed.NewClient("test-id", serverConfig, logger, nil, cfg, nil, secret.NewResolver()) + client, err := managed.NewClient("test-id", serverConfig, logger, nil, cfg, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) envVars := client.GetEnvManager().(*secureenv.Manager).BuildSecureEnvironment() @@ -450,7 +450,7 @@ func TestProxyForwardingWiring(t *testing.T) { buildEnvMap := func(forward bool) map[string]string { cfg := config.DefaultConfig() cfg.ForwardProxyEnv = forward - client, err := managed.NewClient("test-id", serverConfig, logger, nil, cfg, nil, secret.NewResolver()) + client, err := managed.NewClient("test-id", serverConfig, logger, nil, cfg, nil, secret.NewTestWildcardResolver()) require.NoError(t, err) envMap := make(map[string]string) for _, envVar := range client.GetEnvManager().(*secureenv.Manager).BuildSecureEnvironment() { diff --git a/internal/upstream/token_rate_config_test.go b/internal/upstream/token_rate_config_test.go index d5242d6b4..50cd03ff1 100644 --- a/internal/upstream/token_rate_config_test.go +++ b/internal/upstream/token_rate_config_test.go @@ -17,7 +17,7 @@ import ( func TestAgentTokenRateLimit_FollowsTheConfig(t *testing.T) { t.Setenv("CI", "") - m := NewManager(zap.NewNop(), &config.Config{}, nil, secret.NewResolver(), nil) + m := NewManager(zap.NewNop(), &config.Config{}, nil, secret.NewTestWildcardResolver(), nil) t.Cleanup(func() { m.shutdownCancel() }) rates := m.Limiters().TokenRates() assert.False(t, rates.Default().Enabled(), "no config, no limit") @@ -43,7 +43,7 @@ func TestNewManager_AppliesTheConfiguredAgentTokenRateLimit(t *testing.T) { t.Setenv("CI", "") cfg := &config.Config{AgentTokenRateLimit: &config.AgentTokenRateLimit{PerMinute: 30, Burst: 3}} - m := NewManager(zap.NewNop(), cfg, nil, secret.NewResolver(), nil) + m := NewManager(zap.NewNop(), cfg, nil, secret.NewTestWildcardResolver(), nil) t.Cleanup(func() { m.shutdownCancel() }) assert.Equal(t, limiter.RateSpec{PerMinute: 30, Burst: 3}, m.Limiters().TokenRates().Default()) } diff --git a/oas/docs.go b/oas/docs.go index 1c0c964fa..c64c4a0c7 100644 --- a/oas/docs.go +++ b/oas/docs.go @@ -6,7 +6,7 @@ import "github.com/swaggo/swag/v2" const docTemplate = `{ "schemes": {{ marshal .Schemes }}, - "components": {"schemas":{"auth.CredentialIssuer":{"properties":{"actor_kind":{"type":"string"},"actor_name":{"type":"string"},"surface":{"type":"string"}},"type":"object"},"config.AgentTokenRateLimit":{"description":"AgentTokenRateLimit caps how many upstream tool calls ONE agent token may\nmake: PerMinute on average, Burst at once (issue #1699). Every token is\ncounted separately, and a token's own rate_limit (set when it is created)\nreplaces this default for that token. Only agent-token callers are\nlimited; the admin API key, the unix socket and an unauthenticated /mcp\ncaller are not. Absent or per_minute 0 = no limit (default, zero behavior\nchange). The counters are in memory: a restart gives every token a full\nallowance again. Hot-reloadable. File/API-configured only, no env scheme.","properties":{"burst":{"description":"Burst is how many calls a token may make at once after a quiet spell.\n0 = the PerMinute value.","type":"integer"},"per_minute":{"description":"PerMinute is the sustained rate. 0 = no limit.","type":"integer"}},"type":"object"},"config.AuditLogConfig":{"description":"AuditLog configures the Spec 107 edition-neutral audit sink\n(internal/audit). nil means \"use the per-edition/per-transport\ndefault\" (EffectiveAuditLog); restart-pinned (bound at sink\nconstruction). See audit_log.go.","properties":{"compress":{"type":"boolean"},"enabled":{"type":"boolean"},"max_age_days":{"type":"integer"},"max_backups":{"type":"integer"},"max_size_mb":{"type":"integer"},"path":{"type":"string"},"stdout":{"type":"boolean"}},"type":"object"},"config.ConcurrencyDefaults":{"description":"ServerConcurrencyDefaults is scope (b) of FR-020: the blanket per-server\ndefault set inherited by every server that does not override a setting.\nAbsent (the default) = no per-server limiting unless a server configures\nit explicitly. File/API-configured only — no env scheme (FR-022).","properties":{"max_concurrent_requests":{"type":"integer"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"}},"type":"object"},"config.Config":{"properties":{"activity_cleanup_interval_min":{"description":"Background cleanup interval in minutes (default: 60)","type":"integer"},"activity_max_records":{"description":"Max records before pruning (default: 400000)","type":"integer"},"activity_max_response_size":{"description":"Response truncation limit in bytes (default: 65536)","type":"integer"},"activity_max_size_mb":{"description":"ActivityMaxSizeMB caps the total activity-log size in MB before the\noldest records are pruned. Omit the key for the 256MB default; set it to\n0 to disable the size cap.","type":"integer"},"activity_retention_days":{"description":"Activity logging settings (RFC-003)","type":"integer"},"advertise_upstream_servers":{"description":"AdvertiseUpstreamServers controls whether MCP clients are told the\nnames of the upstream servers they can reach — in the initialize\ninstructions and the retrieve_tools description — so agents use the\nproxied tools instead of falling back to shell CLIs. Names are always\nfiltered to the caller's profile and agent-token scope. Default true;\nset false to keep server names out of client context. Read live.","type":"boolean"},"agent_token_rate_limit":{"$ref":"#/components/schemas/config.AgentTokenRateLimit"},"aggregate_upstream_prompts":{"description":"AggregateUpstreamPrompts, when true, aggregates every connected upstream\nserver's advertised MCP prompts into mcpproxy's own prompts/list\n(exposed as \"\u003cserver\u003e__\u003cprompt\u003e\"). OFF by default: users are safe by\ndefault and opt in deliberately. EnablePrompts still governs the built-in\nprompts + the prompts capability; this flag gates ONLY the upstream\naggregation performed by RefreshPrompts. Hot-reloadable.","type":"boolean"},"allow_private_registry_fetch":{"description":"AllowPrivateRegistryFetch opts out of the registry SSRF guard (MCP-1076,\nCWE-918). By default (false) registry fetches refuse any host that is — or\nresolves to — a non-routable address (loopback, RFC1918/CGNAT private,\nlink-local incl. the 169.254.169.254 cloud-metadata endpoint), so a\nmalicious or typo'd registry source cannot turn the daemon into a\nrequest-forgery vector against internal services.\n\nThis opt-out is BLANKET (all-or-nothing): setting it true disables the\nguard for EVERY non-routable range at once — loopback, RFC1918/CGNAT\nprivate, link-local AND the 169.254.169.254 cloud-metadata endpoint. There\nis no way to allow only loopback; enabling it for a localhost dev registry\nalso re-opens the cloud-metadata SSRF vector. Set true ONLY when you\nintentionally run a trusted registry mirror on an internal/private address,\nideally on a host with no cloud-metadata exposure. The change takes effect\nonly on daemon (re)start or config reload.","type":"boolean"},"allow_server_add":{"type":"boolean"},"allow_server_remove":{"type":"boolean"},"anonymous_profile":{"description":"AnonymousProfile confines every caller whose request authenticates as\ncredential kind \"anonymous\" (no credential, or an unrecognised\nnon-agent token accepted by the require_mcp_auth:false back-compat\nbranch) to the named profile (Spec 108 FR-008). Empty (default) means\nunconfined, legacy anonymous behaviour. A name that does not match any\nconfigured profile resolves anonymous callers to deny-all and is\nreported as a validation warning (data-model.md §1).","type":"string"},"api_key":{"description":"Security settings","type":"string"},"audit_log":{"$ref":"#/components/schemas/config.AuditLogConfig"},"call_tool_timeout":{"type":"string"},"check_server_repo":{"description":"Repository detection settings","type":"boolean"},"code_execution_max_parallel":{"description":"Default concurrency for call_tools() batches (1-32, default: 8)","type":"integer"},"code_execution_max_tool_calls":{"description":"Max tool calls per execution (0 = unlimited, default: 0)","type":"integer"},"code_execution_pool_size":{"description":"JavaScript runtime pool size (default: 10)","type":"integer"},"code_execution_timeout_ms":{"description":"Timeout in milliseconds (default: 120000, max: 600000)","type":"integer"},"data_dir":{"type":"string"},"debug_search":{"type":"boolean"},"direct_tool_response_mode":{"description":"DirectToolResponseMode selects the serialization of the DIRECT\nenumeration surface (Spec 102). Valid values: \"\" (= full), \"full\"\n(default: today's schema-bearing entries), \"deferred\" (description +\ncompact signature, with a minimal permissive input schema; upstream\ninputSchema and outputSchema are stripped and recovered on demand via\ndescribe_tool).\n\nDeliberately NOT an extension of tool_response_mode: reusing that axis\nwould silently change /mcp/all output for every deployment already\nrunning compact, which FR-015 forbids. Serialization-only — it never\nchanges WHICH tools are listed, only how (FR-008). Hot-reloadable.","type":"string"},"disable_management":{"type":"boolean"},"docker_isolation":{"$ref":"#/components/schemas/config.DockerIsolationConfig"},"docker_recovery":{"$ref":"#/components/schemas/config.DockerRecoveryConfig"},"enable_code_execution":{"description":"Code execution settings","type":"boolean"},"enable_prompts":{"description":"Prompts settings","type":"boolean"},"enable_skills":{"description":"EnableSkills, when true, makes mcpproxy read the skills that upstream\nservers expose through the MCP skills extension. OFF by default. Unlike\nEnablePrompts this is hot-reloadable. No CLI flag, no environment\nvariable.","type":"boolean"},"enable_socket":{"description":"Enable Unix socket/named pipe for local IPC (default: true)","type":"boolean"},"enable_tray":{"description":"Deprecated: EnableTray is unused and has no runtime effect. Kept for backward compatibility.","type":"boolean"},"environment":{"$ref":"#/components/schemas/secureenv.EnvConfig"},"features":{"$ref":"#/components/schemas/config.FeatureFlags"},"forward_client_headers":{"description":"ForwardClientHeaders is the global switch for client header forwarding\n(Spec 112): copying allowlisted headers from the inbound /mcp request into\nthe upstream tools/call request. nil (absent) means enabled; because every\nper-server forward_headers allowlist is empty by default, the default\nforwards nothing. false disables forwarding for every server. Read via\nIsClientHeaderForwardingEnabled(); MCPPROXY_FORWARD_CLIENT_HEADERS\noverrides it for the process. Distinct from ForwardedHeaders/trusted_proxies\n(Spec 107), which trusts inbound X-Forwarded-*.","type":"boolean"},"forward_proxy_env":{"description":"ForwardProxyEnv opts in to forwarding the ambient HTTP(S)/ALL/NO/FTP proxy\nenvironment variables to spawned stdio upstream servers (MCP-2769). OFF by\ndefault: proxy URLs commonly embed credentials (http://user:pass@proxy), so\nforwarding them to every upstream is a credential-leak risk. When enabled,\nvalues are forwarded with their userinfo (credentials) redacted.","type":"boolean"},"health_check_interval":{"description":"Discovery \u0026 health-check cadence (spec 074, #608). Both are *Duration\ntri-state pointers: nil = inherit the built-in default; a pointer to 0s =\nthe loop is disabled; a positive value = that interval. Defaults live only\nin the resolvers (ResolveHealthCheckInterval / ResolveToolDiscoveryInterval)\nso an unset key behaves exactly as before this feature (SC-005). Validated\nin Validate(): health-check ∈ {0} ∪ [5s,1h]; tool-discovery ∈ {0} ∪ [30s,24h].","type":"string"},"http_idle_timeout":{"description":"HTTPIdleTimeout caps how long an idle keep-alive connection is kept open.\nUnset = 180s. \"0s\" removes the dedicated idle deadline, but net/http then\nfalls back to ReadTimeout — idle is fully unbounded only when\nhttp_read_timeout is also \"0s\". Requires a restart.","type":"string"},"http_read_timeout":{"description":"HTTPReadTimeout caps how long reading a whole request (headers + body)\nmay take. Unset = 120s; \"0s\" disables it. Requires a restart.","type":"string"},"http_write_timeout":{"description":"HTTPWriteTimeout caps how long producing a whole response may take on\nnon-streaming endpoints (REST, Web UI, health). Unset = 120s; \"0s\"\ndisables it globally. MCP and SSE /events routes are exempt by design.","type":"string"},"init_timeout":{"description":"InitTimeout is the global default deadline for an upstream's MCP\n` + "`" + `initialize` + "`" + ` handshake (MCP-3322 / GH #760). *Duration tri-state: nil =\ninherit the built-in 30s default; a positive value = that deadline. A\nper-server InitTimeout overrides this. Resolved by ResolveInitTimeout;\nvalidated to {0} ∪ [1s, 30m] in Validate(). Servers doing legitimate\nfirst-run warmup (cache/index build) before answering ` + "`" + `initialize` + "`" + ` can\nraise this so they are not killed mid-startup.","type":"string"},"instructions":{"description":"Instructions text returned in the MCP initialize response to guide AI agents.\nWhen empty, a built-in default is used that explains retrieve_tools workflow.","type":"string"},"intent_declaration":{"$ref":"#/components/schemas/config.IntentDeclarationConfig"},"listen":{"type":"string"},"logging":{"$ref":"#/components/schemas/config.LogConfig"},"max_concurrent_requests":{"description":"Concurrency limits (spec 093, GH #955). Scope (a) of FR-020: the GLOBAL\nAGGREGATE limiter — one proxy-wide cap on concurrently running upstream\ntool calls, with its own bounded wait queue. Tri-state pointers: absent =\nthe limiter does not exist (default, zero behavior change); an explicit 0\nmax also disables it; positive = that cap. This scope is NEVER a\nper-server inheritance source — per-server values come from\nServerConcurrencyDefaults / the per-server overrides — but a server's\neffective concurrency is bounded by BOTH its own limiter and this one.\nResolved by ResolveGlobalConcurrency; hot-reloadable; overridable via\nMCPPROXY_MAX_CONCURRENT_REQUESTS / _QUEUE_SIZE / _QUEUE_TIMEOUT (FR-022).","type":"integer"},"max_result_size_chars":{"description":"MaxResultSizeChars is advertised on every tool as\n` + "`" + `_meta.anthropic/maxResultSizeChars` + "`" + `; it raises Claude Code's\ninline-response ceiling from 50k to up to 500k chars. Omit the key for\nthe 500000 default; set it to 0 to disable the annotation.","type":"integer"},"mcpServers":{"items":{"$ref":"#/components/schemas/config.ServerConfig"},"type":"array","uniqueItems":false},"mcp_oauth_enabled":{"description":"MCPOAuthEnabled turns on browser login (OAuth 2.1 + PKCE) for MCP\nclients on the loopback listener (Spec 132). Experimental, default false:\nwith it off nothing changes. Env override MCPPROXY_MCP_OAUTH_ENABLED is\nprocess-only and never persisted. Live, no restart needed.","type":"boolean"},"mcp_reject_query_apikey":{"description":"MCPRejectQueryAPIKey makes every MCP endpoint (/mcp*) refuse a request that\ncarries a ?apikey= query parameter, with a 401, instead of honouring it. A credential in a URL ends up in access logs,\nproxy logs and browser history; MCP clients can send Authorization:\nBearer or X-API-Key instead. Default false (the query form keeps\nworking, for clients that can only configure a URL). It covers only the\nMCP endpoints: the Web UI and its SSE stream (/events) still use the\nquery form. Live, no restart needed.","type":"boolean"},"oauth_expiry_warning_hours":{"description":"Health status settings","type":"number"},"oauth_token_encryption_key":{"description":"OAuthTokenEncryptionKey seals the upstream OAuth tokens stored in\nconfig.db (Spec 123). Empty (the default) leaves them as plain JSON. It\ntakes a secret reference (${file:/abs/path}, ${env:NAME},\n${keyring:NAME}) or a literal standard-base64 32-byte key; the\nMCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY[_FILE] variables override it. The key\nis resolved only where config.db is opened (ResolveOAuthTokenKey), never\nstored on Config, and is restart-gated, so every save writes the field\nas configured.","type":"string"},"observability":{"$ref":"#/components/schemas/config.ObservabilityConfig"},"output_sanitisation":{"$ref":"#/components/schemas/config.OutputSanitisationConfig"},"output_validation":{"$ref":"#/components/schemas/config.OutputValidationConfig"},"profiles":{"description":"Profiles are optional named, server-scoped views exposed at /mcp/p/\u003cname\u003e\n(Spec 057). Absent/empty is fully supported — /mcp is unchanged and configs\nwithout this key serialize byte-identically (SC-004).","items":{"$ref":"#/components/schemas/config.ProfileConfig"},"type":"array","uniqueItems":false},"quarantine_enabled":{"description":"QuarantineEnabled controls whether quarantine is active. It gates two\nthings together:\n 1. Server-level auto-quarantine for newly added servers (issue #370).\n When true, servers added via the upstream_servers MCP tool or the\n REST API default to quarantined=true; when false, they default to\n quarantined=false. Explicit per-request values always win.\n 2. Tool-level quarantine (Spec 032): per-tool SHA-256 approval of\n tool descriptions/schemas.\nWhen nil (default), quarantine is enabled (secure by default). Set to\nexplicit false to opt out of both. Per-server SkipQuarantine still\napplies for the tool-level check on individual servers.","type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"read_only_mode":{"type":"boolean"},"registries":{"description":"Registries configuration for MCP server discovery","items":{"$ref":"#/components/schemas/config.RegistryEntry"},"type":"array","uniqueItems":false},"registries_locked":{"description":"RegistriesLocked is an enterprise stub knob (MCP-866): when true, runtime\nadditions of custom registries (e.g. ` + "`" + `registry add-source` + "`" + `, the REST/MCP\nadd-source surface) are rejected so an administrator can pin the discovery\nsources. Built-in defaults are unaffected. Documented but otherwise inert\nbeyond the add-source rejection.","type":"boolean"},"require_mcp_auth":{"description":"Require authentication on /mcp endpoint (default: false)","type":"boolean"},"reveal_secret_headers":{"description":"RevealSecretHeaders, when true, disables the redaction of the\nsecret-bearing server fields — sensitive header values (Authorization,\nX-API-Key, Cookie, …), env-var secrets, and URL query credentials — in\nresponses from the ` + "`" + `upstream_servers` + "`" + ` MCP tool, the ` + "`" + `/api/v1/servers` + "`" + `\nREST API, and the SSE event stream. It also lets URL secrets echoed\ninto last_error / health.detail through unscrubbed.\n\nDefault false — sensitive values are surfaced masked as\n` + "`" + `••••\u003clast2\u003e (\u003cN\u003e chars)` + "`" + ` (error strings use ` + "`" + `***REDACTED***` + "`" + `) so an\nMCP agent cannot read Bearer tokens / API keys / URL secrets out of\nanother upstream's config (PR #425, issue #872). ${env:…}/${keyring:…}\nreferences are labels, not secrets, and pass through unchanged.\n\nThe Web UI / macOS tray edit forms work without seeing the real\nvalues: PATCH /api/v1/servers/{id} deep-merges (omitted keys are\npreserved, see ` + "`" + `headers_remove` + "`" + ` / ` + "`" + `env_remove` + "`" + ` for explicit\ndeletes), so clients compute a diff and only send the keys that\nactually changed. Redacted-but-unchanged values never round-trip\n— the backend keeps the real string. Set this to true if a\ndownstream tool genuinely needs raw values in the response.","type":"boolean"},"routing_mode":{"description":"Routing mode (Spec 031): how MCP tools are exposed to clients\nValid values: \"retrieve_tools\" (default), \"direct\", \"code_execution\"","type":"string"},"security":{"$ref":"#/components/schemas/config.SecurityConfig"},"sensitive_data_detection":{"$ref":"#/components/schemas/config.SensitiveDataDetectionConfig"},"server_concurrency_defaults":{"$ref":"#/components/schemas/config.ConcurrencyDefaults"},"session_retention_days":{"description":"SessionRetentionDays is how long a work session is listed and kept whole\nin the activity log (Spec 124, default 7). Read at start.","type":"integer"},"telemetry":{"$ref":"#/components/schemas/config.TelemetryConfig"},"tls":{"$ref":"#/components/schemas/config.TLSConfig"},"tokenizer":{"$ref":"#/components/schemas/config.TokenizerConfig"},"tool_call_max_records_per_server":{"description":"Calls retained per server (default: 1000)","type":"integer"},"tool_call_max_response_size":{"description":"Bounds for the per-server tool-call history behind GET /api/v1/tool-calls\n(#1176). It is a recent-debugging window, not an audit log — the activity\nlog is the durable record — and it kept every upstream response whole,\nper server, forever. A non-positive value means \"use the default\", not\n\"disable\": this store must never be unbounded again, so there is\ndeliberately no off switch.","type":"integer"},"tool_discovery_interval":{"type":"string"},"tool_response_limit":{"type":"integer"},"tool_response_mode":{"description":"Tool response mode (Spec 085): how retrieve_tools serializes results.\nValid values: \"\" (= full), \"full\" (default: today's schema-bearing\nentries), \"compact\" (signature + first-sentence entries). Orthogonal to\nrouting_mode — routing_mode selects the tool SURFACE, this selects the\nSERIALIZATION within the retrieve_tools surface. Serialization-only: it\nnever affects the query, ranking, or result set. Hot-reloadable.","type":"string"},"tool_response_session_risk_warning":{"description":"ToolResponseSessionRiskWarning controls whether the prose ` + "`" + `warning` + "`" + ` field\nis included in the ` + "`" + `session_risk` + "`" + ` object returned by ` + "`" + `retrieve_tools` + "`" + `.\nThe structured fields (level, lethal_trifecta, has_open_world_tools, etc.)\nare always included. Default: false (quiet for LLM clients) — see issue #406.\nMost tools lack annotations, so the MCP-spec defaults treat them as fully\npermissive across all three risk axes, which makes the prose warning fire\non almost every call and wastes tokens.","type":"boolean"},"tools_limit":{"type":"integer"},"toon_min_savings_pct":{"description":"ToonMinSavingsPct is the minimum byte-savings percentage (validated\n1-90; 0/unset → 15) the complete TOON emission (marker + hint + body)\nmust achieve over the exact passthrough emission for adaptive mode to\nencode a block. Byte savings approximate token savings for the tabular\npayload class; the spec-083 profiler reports true token deltas.\nGlobal-only (no per-server override, FR-001).","type":"integer"},"toon_output":{"description":"ToonOutput selects the TOON encoding mode for call_tool_* result text\nblocks (spec 084): \"off\" (default — responses byte-identical to\npre-feature behavior), \"adaptive\" (encode only tabular-uniform payloads\nthat beat compact JSON by ToonMinSavingsPct), or \"always\"\n(benchmark/debug only — encodes every JSON-parseable block and can\nINCREASE token cost). Per-server override: ServerConfig.ToonOutput.\nResolved by ResolveToonOutput; hot-reloadable.","type":"string"},"top_k":{"description":"Deprecated: TopK is superseded by ToolsLimit and has no runtime effect. Kept for backward compatibility.","type":"integer"},"tray_endpoint":{"description":"Tray endpoint override (unix:// or npipe://)","type":"string"},"trusted_hosts":{"description":"TrustedHosts lists non-loopback Host header values accepted on loopback\nlisteners (GH #898). DNS-rebinding protection rejects requests whose Host\nheader is not a loopback address when mcpproxy listens on loopback; a\nreverse proxy (nginx → 127.0.0.1) forwarding the public domain in Host\ntrips it. Entries are hostnames, case-insensitive; an entry without a\nport matches any port, with a port it must match exactly; a leading dot\n(\".example.com\") is a subdomain wildcard. The single entry \"*\" disables\nHost and Origin validation entirely. The same list also validates the\nOrigin header when present (MCP spec DNS-rebinding defense). Empty\n(default) keeps full protection. Env override: MCPPROXY_TRUSTED_HOSTS\n(comma-separated).","items":{"type":"string"},"type":"array","uniqueItems":false},"trusted_proxies":{"description":"TrustedProxies lists the CIDRs or IP addresses whose X-Forwarded-For /\nX-Real-IP / X-Forwarded-Proto / X-Forwarded-Host headers are believed\n(Spec 107 FR-027). Empty (default) trusts nobody. Edition-neutral, live\n(hot-reloadable). Env override: MCPPROXY_TRUSTED_PROXIES (comma-separated).\nThe one reader is ForwardedHeaders; validation is validateTrustedProxies.","items":{"type":"string"},"type":"array","uniqueItems":false},"update_check":{"$ref":"#/components/schemas/config.UpdateCheckConfig"}},"type":"object"},"config.CustomPattern":{"properties":{"category":{"description":"Category (defaults to \"custom\")","type":"string"},"keywords":{"description":"Keywords to match (mutually exclusive with Regex)","items":{"type":"string"},"type":"array","uniqueItems":false},"name":{"description":"Unique identifier for this pattern","type":"string"},"regex":{"description":"Regex pattern (mutually exclusive with Keywords)","type":"string"},"severity":{"description":"Risk level: critical, high, medium, low","type":"string"}},"type":"object"},"config.DeepScanConfig":{"description":"DeepScan is the opt-in \"deep scan\" layer (Spec 077 US3). It subsumes the\ndeprecated top-level scanner_fetch_package_source / scanner_disable_no_new_privileges\nkeys (migrated on load) and gates the heavy Docker-based scanners + source\nextraction. Disabled by default (FR-006): only the deterministic in-process\nbaseline scanner runs. A deep-scan failure NEVER changes the baseline verdict\n(FR-007/FR-008).","properties":{"disable_no_new_privileges":{"description":"DisableNoNewPrivileges, when true, omits the ` + "`" + `--security-opt\nno-new-privileges` + "`" + ` flag from scanner container runs (snap-docker/AppArmor\nescape hatch). Absorbs the deprecated top-level\nscanner_disable_no_new_privileges. Default false.","type":"boolean"},"enabled":{"description":"Enabled is the master opt-in for the heavy layer (FR-006). Default false.","type":"boolean"},"fetch_package_source":{"description":"FetchPackageSource controls whether the scanner fetches the PUBLISHED\nsource of package-runner servers (npx/uvx) — without executing it — when\nno local source is available. Absorbs the deprecated top-level\nscanner_fetch_package_source. Default (nil) is ENABLED within deep scan.","type":"boolean"},"scanners":{"description":"Scanners optionally restricts which deep scanners may run under the\numbrella (by scanner id). Empty ⇒ all enabled deep scanners are eligible.","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"config.DockerIsolationConfig":{"description":"Docker isolation settings","properties":{"cpu_limit":{"description":"CPU limit for containers","type":"string"},"default_images":{"additionalProperties":{"type":"string"},"description":"Map of runtime type to Docker image","type":"object"},"enable_cache_volume":{"description":"Mount shared cache volumes for faster restarts (default: true)","type":"boolean"},"enabled":{"description":"Global enable/disable for Docker isolation (legacy; superseded by Mode)","type":"boolean"},"extra_args":{"description":"Additional docker run arguments","items":{"type":"string"},"type":"array","uniqueItems":false},"log_driver":{"description":"Docker log driver (default: json-file)","type":"string"},"log_max_files":{"description":"Maximum number of log files (default: 3)","type":"string"},"log_max_size":{"description":"Maximum size of log files (default: 100m)","type":"string"},"memory_limit":{"description":"Memory limit for containers","type":"string"},"mode":{"description":"Isolation mode: \"docker\" | \"sandbox\" | \"none\" (MCP-34.2). Unset per-server inherits the global mode; unset globally falls back to the legacy \"enabled\" flag (true ⇒ docker, false ⇒ none)","type":"string","x-enum-varnames":["IsolationModeDocker","IsolationModeSandbox","IsolationModeNone"]},"network_mode":{"description":"Docker network mode (default: bridge)","type":"string"},"registry":{"description":"Custom registry (defaults to docker.io)","type":"string"},"timeout":{"description":"Container startup timeout","type":"string"}},"type":"object"},"config.DockerRecoveryConfig":{"description":"Docker recovery settings","properties":{"enabled":{"description":"Enable Docker recovery monitoring (default: true)","type":"boolean"},"max_retries":{"description":"Maximum retry attempts (0 = unlimited)","type":"integer"},"notify_on_failure":{"description":"Show notification on recovery failure (default: true)","type":"boolean"},"notify_on_retry":{"description":"Show notification on each retry (default: false)","type":"boolean"},"notify_on_start":{"description":"Show notification when recovery starts (default: true)","type":"boolean"},"notify_on_success":{"description":"Show notification on successful recovery (default: true)","type":"boolean"},"persistent_state":{"description":"Save recovery state across restarts (default: true)","type":"boolean"}},"type":"object"},"config.FeatureFlags":{"description":"Deprecated: Features flags are unused and have no runtime effect. Kept for backward compatibility.","properties":{"enable_async_storage":{"type":"boolean"},"enable_caching":{"type":"boolean"},"enable_contract_tests":{"type":"boolean"},"enable_debug_logging":{"description":"Development features","type":"boolean"},"enable_docker_isolation":{"type":"boolean"},"enable_event_bus":{"type":"boolean"},"enable_health_checks":{"type":"boolean"},"enable_metrics":{"type":"boolean"},"enable_oauth":{"description":"Security features","type":"boolean"},"enable_observability":{"description":"Observability features","type":"boolean"},"enable_quarantine":{"type":"boolean"},"enable_runtime":{"description":"Runtime features","type":"boolean"},"enable_search":{"description":"Storage features","type":"boolean"},"enable_sse":{"type":"boolean"},"enable_tracing":{"type":"boolean"},"enable_tray":{"type":"boolean"},"enable_web_ui":{"description":"UI features","type":"boolean"}},"type":"object"},"config.IntentDeclarationConfig":{"description":"Intent declaration settings (Spec 018)","properties":{"strict_server_validation":{"description":"StrictServerValidation controls whether server annotation mismatches\ncause rejection (true) or just warnings (false).\nDefault: true (reject mismatches)","type":"boolean"}},"type":"object"},"config.IsolationConfig":{"description":"Per-server isolation settings","properties":{"enabled":{"description":"Enable Docker isolation for this server (nil = inherit global; legacy, superseded by Mode)","type":"boolean"},"extra_args":{"description":"Additional docker run arguments for this server","items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"description":"Custom Docker image (overrides default)","type":"string"},"log_driver":{"description":"Docker log driver override for this server","type":"string"},"log_max_files":{"description":"Maximum number of log files override","type":"string"},"log_max_size":{"description":"Maximum size of log files override","type":"string"},"mode":{"$ref":"#/components/schemas/config.IsolationMode"},"network_mode":{"description":"Custom network mode for this server","type":"string"},"working_dir":{"description":"Custom working directory in container","type":"string"}},"type":"object"},"config.IsolationMode":{"description":"Isolation mode: \"docker\" | \"sandbox\" | \"none\" (MCP-34.2). Unset per-server inherits the global mode; unset globally falls back to the legacy \"enabled\" flag (true ⇒ docker, false ⇒ none)","type":"string","x-enum-varnames":["IsolationModeDocker","IsolationModeSandbox","IsolationModeNone"]},"config.LogConfig":{"description":"Logging configuration","properties":{"compress":{"type":"boolean"},"enable_console":{"type":"boolean"},"enable_file":{"type":"boolean"},"filename":{"type":"string"},"json_format":{"type":"boolean"},"level":{"type":"string"},"log_dir":{"description":"Custom log directory","type":"string"},"max_age":{"description":"days","type":"integer"},"max_backups":{"description":"number of backup files","type":"integer"},"max_size":{"description":"MB","type":"integer"}},"type":"object"},"config.MetricsExporterConfig":{"description":"Metrics gates the Prometheus /metrics scrape endpoint (MCP-32). Disabled\nby default — operators opt in for k8s/enterprise deployments.","properties":{"enabled":{"description":"Enabled exposes /metrics on the existing HTTP listener when true.\nThe endpoint is admin-authenticated (SEC-07): scrapers must present the\nglobal API key, via X-API-Key or an Authorization: Bearer header.","type":"boolean"}},"type":"object"},"config.OAuthConfig":{"description":"OAuth configuration (keep even when empty to signal OAuth requirement)","properties":{"auth_server_metadata_url":{"type":"string"},"authorization_endpoint":{"description":"Spec 113-b: optional per-server discovery overrides. Each is an absolute\nhttps URL (http only on a loopback host) with no query, fragment or\nuserinfo; validated at write time only (ValidateOAuthEndpointOverrides).\nThe endpoint overrides rewrite the matching fields of the authorization\nserver metadata mcp-go reads; AuthServerMetadataURL replaces discovery.","type":"string"},"callback_base_url":{"type":"string"},"client_id":{"type":"string"},"client_secret":{"type":"string"},"extra_params":{"additionalProperties":{"type":"string"},"description":"Additional OAuth parameters (e.g., RFC 8707 resource)","type":"object"},"pkce_enabled":{"type":"boolean"},"redirect_uri":{"type":"string"},"refresh_replay_enabled":{"description":"Opt in only when token_endpoint supports idempotent refresh replay for at least 30 seconds.","type":"boolean"},"registration_endpoint":{"type":"string"},"scopes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"token_endpoint":{"type":"string"}},"type":"object"},"config.ObservabilityConfig":{"description":"Observability settings (Spec 069): usage aggregate cache/persistence cadence.","properties":{"metrics":{"$ref":"#/components/schemas/config.MetricsExporterConfig"},"tracing":{"$ref":"#/components/schemas/config.TracingExporterConfig"},"usage_cache_ttl":{"description":"UsageCacheTTL bounds the freshness of the usage endpoint's read cache for\nwide windows (FR-005). Default 5s.","type":"string"},"usage_persist_interval":{"description":"UsagePersistInterval is how often the actor-owned usage aggregate snapshot\nis flushed to storage. Default 30s.","type":"string"}},"type":"object"},"config.OutputSanitisationConfig":{"description":"Output sanitisation settings (Spec 054 Track B)","properties":{"max_redactions":{"description":"cap on redactions per response; default 100","type":"integer"},"response_action":{"description":"\"spotlight\" | \"redact\" | \"block\"; default \"spotlight\"","type":"string"},"spotlight_untrusted":{"description":"wrap untrusted output in spotlight markers; default true","type":"boolean"},"strip_classes":{"description":"classes to strip: ansi/c0c1/bidi/zero_width","items":{"type":"string"},"type":"array","uniqueItems":false},"strip_control_chars":{"description":"strip control-character classes; default false","type":"boolean"}},"type":"object"},"config.OutputValidationConfig":{"description":"Output-schema validation settings (Spec 056)","properties":{"max_bytes":{"description":"structured payload byte cap; default 5\u003c\u003c20","type":"integer"},"max_depth":{"description":"nesting depth cap; default 64","type":"integer"},"missing_structured_content":{"description":"\"allow\" | \"block\"; default \"allow\"","type":"string"},"mode":{"description":"\"off\" | \"warn\" | \"strict\"; default \"warn\"","type":"string"}},"type":"object"},"config.ProfileConfig":{"properties":{"code_execution":{"description":"CodeExecution: nil = inherit the global enable_code_execution gate;\nnon-nil narrows it (a profile can only narrow, never widen, FR-006).","type":"boolean"},"description":{"description":"\u003c= 500 chars (FR-001)","type":"string"},"management_tools":{"description":"ManagementTools: nil = legacy/inherit (FR-016); non-nil sets the\nprofile-level visibility of upstream_servers/quarantine_security.","type":"boolean"},"max_tier":{"description":"MaxTier caps the tier a tool may run at under this profile: \"\" (no\ncap) | \"read\" | \"write\" | \"destructive\" (FR-001).","type":"string"},"name":{"description":"slug (Spec 057 rules unchanged)","type":"string"},"servers":{"description":"references to mcpServers[].name","items":{"type":"string"},"type":"array","uniqueItems":false},"switchable_to":{"description":"SwitchableTo is the list of profile names a session under this\nprofile may ` + "`" + `set_profile` + "`" + ` into (FR-022). nil = legacy/none (research\nD6); a non-nil EMPTY list is an explicit \"none\" and must round-trip as\n` + "`" + `[]` + "`" + `, never be dropped by omitempty — hence the pointer (see the\nMarshalJSON note below, and profiles_v3_test.go's switchable_to round\ntrip case).","items":{"type":"string"},"type":"array","uniqueItems":false},"title":{"description":"display only, \u003c= 80 chars (FR-001)","type":"string"},"tools":{"$ref":"#/components/schemas/config.ProfileToolRules"},"unannotated":{"description":"Unannotated is this profile's handling of a tool whose effective\nannotations carry no tier hint: \"\" (unset, see EffectiveUnannotated) |\n\"deny\" | \"as_write\" | \"as_read\" (FR-001, FR-003).","type":"string"}},"type":"object"},"config.ProfileToolRules":{"description":"Tools holds the allow/deny/classify rule set (FR-001, FR-004, FR-005).","properties":{"allow":{"items":{"type":"string"},"type":"array","uniqueItems":false},"classify":{"additionalProperties":{"type":"string"},"type":"object"},"deny":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"config.RegistryEntry":{"properties":{"count":{"description":"number or string","type":"string"},"description":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"},"protocol":{"type":"string"},"provenance":{"description":"Provenance is the trust tag for this registry (MCP-866):\nRegistryProvenanceOfficial for built-in defaults, RegistryProvenanceCustom\nfor user-added registries. It is authoritatively (re)computed by the\nregistries merge from whether the ID is a shipped default — a user cannot\nclaim \"official\" by writing it into their config.","type":"string"},"requires_key":{"description":"RequiresKey marks a registry that needs an API key to be queried. When\ntrue and no key is configured, the registry is skipped/marked unavailable\nrather than failing the whole search (FR-008).","type":"boolean"},"servers_url":{"type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"url":{"type":"string"}},"type":"object"},"config.SecurityConfig":{"description":"Security scanner settings (Spec 039)","properties":{"auto_baseline_scan":{"description":"AutoBaselineScan is the kill-switch for the AUTOMATIC, informational\nPass-1 baseline scan: the free in-process TPA scan mcpproxy runs for every\nnewly admitted server (any trust mode) and, once per installation, over\npre-existing servers that have never been scanned.\n\nInformational ONLY: the resulting verdict populates the security badge and\nthe scan summary, and NEVER gates quarantine or approval. The\ntrust_mode:\"scan\" admission gate is a separate path and is unaffected by\nthis flag.\n\nDefault (nil) is ENABLED. Set to false to suppress every automatic scan\n(manual scans keep working). Env override: MCPPROXY_AUTO_BASELINE_SCAN,\nwhich wins over this field on every path.","type":"boolean"},"auto_rescan_on_change":{"description":"AutoRescanOnChange is the finer switch for the automatic, informational\nrescan that follows a tool-definition hash change: the in-process TPA scan\nof the changed (or newly pending) tool, recorded as hold evidence, and a\ndebounced informational server rescan that brings the review screen's scan\ncoverage back to \"current\".\n\nEvidence and freshness ONLY: this switch approves nothing. Under \"manual\"\nevery change is held for review whatever the verdict (RT-02); under\n\"scan\" the gate's own synchronous scan approves a clean change that\npasses the spec 120 structural gate (spec 119 FR-004), and this switch\ndoes not affect that path. Runs in every trust mode except \"auto\".\n\nDefault (nil) is ENABLED. It only takes effect while auto_baseline_scan is\nalso enabled, so a user can keep the admission scan and turn off per-change\nrescans with this key alone. Env override: MCPPROXY_AUTO_RESCAN_ON_CHANGE,\nwhich wins over this field on every path.","type":"boolean"},"deep_scan":{"$ref":"#/components/schemas/config.DeepScanConfig"},"integrity_check_interval":{"type":"string"},"integrity_check_on_restart":{"type":"boolean"},"require_signed_bundle":{"description":"RequireSignedBundle makes the detached signature sidecar mandatory for\nfile-dropped bundles (FR-007). Default false (maintainer decision D2):\nexisting unsigned drops keep working, but an unsigned external bundle\nalways runs with DEGRADED coverage (scan-mode auto-approval suspended).","type":"boolean"},"runtime_read_only":{"type":"boolean"},"runtime_tmpfs_size":{"type":"string"},"scan_timeout_default":{"type":"string"},"scanner_disable_no_new_privileges":{"description":"Deprecated (Spec 077 US3): migrated on load into DeepScan.DisableNoNewPrivileges\n(see migrateDeepScanConfig). Retained only so existing configs that still carry\nthe top-level key parse; consumers MUST read the effective value via\nSecurityConfig.IsDisableNoNewPrivileges. Cleared after migration.\n\nScannerDisableNoNewPrivileges, when true, omits the\n` + "`" + `--security-opt no-new-privileges` + "`" + ` flag from scanner container runs.\n\nBackground: snap-installed Docker on Ubuntu confines dockerd under the\n` + "`" + `snap.docker.dockerd` + "`" + ` AppArmor profile. When runc tries to transition\nthe container into the inner ` + "`" + `docker-default` + "`" + ` profile to exec the\nentrypoint, AppArmor refuses the transition because NO_NEW_PRIVS\nforbids privilege/profile changes on exec — the result is EPERM\n(\"operation not permitted\") and every scanner fails immediately.\n\nSet this to true ONLY on hosts hitting that incompatibility. Scanner\ncontainers still run with read-only rootfs, tmpfs /tmp, no-network by\ndefault, and read-only source mounts, so the marginal isolation loss\nis small. The preferred fix remains replacing snap docker with a\ndistro-packaged docker.","type":"boolean"},"scanner_fetch_package_source":{"description":"Deprecated (Spec 077 US3): migrated on load into DeepScan.FetchPackageSource\n(see migrateDeepScanConfig). Retained only so existing configs that still carry\nthe top-level key parse; consumers MUST read the effective value via\nSecurityConfig.EffectiveFetchPackageSource. Cleared after migration.\n\nScannerFetchPackageSource controls whether the scanner fetches the\nPUBLISHED source of package-runner servers (npx/uvx) — without executing\nit — when no local source is available (no Docker container, no local\npackage cache, no working_dir). This is the primary quarantine/scan\ntarget: a quarantined-on-add server is never run locally, so without this\nthe scan degrades to tool-definitions-only (no real source-level\nanalysis). See MCP-2206.\n\nFetching uses ` + "`" + `npm pack --ignore-scripts` + "`" + ` (npm) and ` + "`" + `uv pip download` + "`" + ` /\n` + "`" + `pip download` + "`" + ` with ` + "`" + `--only-binary=:all:` + "`" + ` (Python), which only download +\nunpack archives and NEVER run install, build, or setup.py — a scanner must\nnot execute the untrusted code it is scanning. The Python\n` + "`" + `--only-binary=:all:` + "`" + ` flag is required because downloading an sdist would\ninvoke its build backend (setup.py); packages with no wheel fall back to\ntool-definitions-only instead. Extraction is hardened against path\ntraversal and decompression bombs.\n\nDefault (nil) is ENABLED. Set to false on air-gapped deployments to\nforbid the scanner's network egress; such servers then fall back to the\ntool-definitions-only scan with no regression.","type":"boolean"},"scanner_registry_url":{"type":"string"},"tpa_active_root":{"description":"TPAActiveRoot declares which signing authority's bundles may activate\n(FR-004b): \"publisher\" (default, the keys embedded in this binary) or\n\"operator\" (TPAOperatorSigners). A bundle verified by the other root is\nrefused as authority_not_active, so whoever can write the bundle path\ncannot choose the authority.","type":"string"},"tpa_bundle_path":{"description":"TPABundlePath is the filesystem path to the tpa-db scanner-bundle.json\nthe offline TPA scanner runs (spec 086 FR-019: the signature-DB location\nMUST be configuration-driven, not hardcoded). Empty (the default) runs the\ncorpus embedded in this build.\n\nEnv override: MCPPROXY_TPA_BUNDLE_PATH. Hot-reloadable — the path is\nre-read on every config.reloaded event via\nscanner.Service.ApplySecurityConfig, so a corpus refresh needs no restart.\nA configured bundle that fails to read/parse/version-check/compile is\nREFUSED and the previously active corpus stays live (fail-closed, never\nfail-empty); the reason is logged and surfaced in the security overview's\nsignature_bundle.load_error.","type":"string"},"tpa_fetch_enabled":{"description":"TPAFetchEnabled opts in to the network fetch leg. Default false; the\nenvironment override is MCPPROXY_TPA_FETCH_ENABLED (EnvTPAFetchEnabled).","type":"boolean"},"tpa_fetch_url":{"description":"TPAFetchURL is the channel URL: a GitHub Releases \"latest\" API URL or a\ndirect bundle URL. Empty (the default) means the fetch leg is off; no URL\nis compiled into the binary.","type":"string"},"tpa_operator_baseline":{"description":"TPAOperatorBaseline seeds the operator authority's anti-downgrade\nwatermark (FR-009b): an operator-signed bundle must carry a sequence\nABOVE it (a rollback target may sit at it). It survives a data-directory\nwipe because it lives here. Absent means the operator authority has no\nanti-downgrade floor and an active operator bundle runs DEGRADED.","type":"integer"},"tpa_operator_epoch":{"description":"TPAOperatorEpoch is the operator authority's trust epoch (FR-005a).\nBumping it (after an operator key compromise) re-baselines the operator\nwatermark and retires prior-epoch pins. Absent means 0.","type":"integer"},"tpa_operator_signers":{"description":"TPAOperatorSigners lists operator Ed25519 public keys, each the standard\nbase64 encoding of the 32 raw key bytes (FR-004). Their key ids are the\nlowercase-hex SHA-256 of those bytes. Malformed or duplicate entries are\nrejected on write and dropped (with a log) on load.","items":{"type":"string"},"type":"array","uniqueItems":false},"tpa_refresh_interval":{"description":"TPARefreshInterval is the cadence of the refresh cycle (the network-free\nfile leg, then the optional fetch leg). Absent or 0 means 24h; the runtime\nclamps to at least 1h. There is no refresh-enable key: the file leg is\nidempotent and always on.","type":"string"},"tpa_stale_after_days":{"description":"TPAStaleAfterDays is the age in days after which the active bundle reads\nas stale. Absent means 30; an explicit 0 disables the stale flag and the\ndoctor stale warning.","type":"integer"}},"type":"object"},"config.SensitiveDataDetectionConfig":{"description":"Sensitive data detection settings (Spec 026)","properties":{"categories":{"additionalProperties":{"type":"boolean"},"description":"Enable/disable specific detection categories","type":"object"},"custom_patterns":{"description":"User-defined detection patterns","items":{"$ref":"#/components/schemas/config.CustomPattern"},"type":"array","uniqueItems":false},"enabled":{"description":"Enable sensitive data detection (default: true)","type":"boolean"},"entropy_threshold":{"description":"Shannon entropy threshold for high-entropy detection (default: 4.5)","type":"number"},"max_payload_size_kb":{"description":"Max size to scan before truncating (default: 1024)","type":"integer"},"scan_requests":{"description":"Scan tool call arguments (default: true)","type":"boolean"},"scan_responses":{"description":"Scan tool responses (default: true)","type":"boolean"},"sensitive_keywords":{"description":"Keywords to flag","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"config.ServerConfig":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges is the per-server intent to auto-approve tool\nchanges/additions (disabling per-server rug-pull protection). Supersedes\nskip_quarantine. MCP-2930 only ACCEPTS, persists, and migrates this flag — it\nis NOT yet consulted at runtime; auto-approval is still governed by\nSkipQuarantine until the trust-baseline behavior change (MCP-2931) migrates the\nruntime consumers onto it.\nTri-state pointer (mirrors QuarantineEnabled): nil = unset (inherit/migrate\nfrom legacy skip_quarantine), explicit true/false = honored as-is so an\nexplicit auto_approve_tool_changes:false overrides a legacy skip_quarantine:true.\nRead via IsAutoApproveToolChanges().","type":"boolean"},"command":{"type":"string"},"created":{"type":"string"},"disabled_tools":{"description":"Denylist: these tools are hidden; mutually exclusive with enabled_tools","items":{"type":"string"},"type":"array","uniqueItems":false},"enabled":{"type":"boolean"},"enabled_tools":{"description":"Allowlist: only these tools are exposed; mutually exclusive with disabled_tools","items":{"type":"string"},"type":"array","uniqueItems":false},"env":{"additionalProperties":{"type":"string"},"type":"object"},"expose_prompts":{"description":"ExposePrompts overrides whether this server's advertised MCP prompts are\naggregated into mcpproxy's prompts/list. nil (default) inherits the\ndefault-aggregate behavior (included if the server advertises\nCapabilities.Prompts); false excludes it regardless of capability.","type":"boolean"},"expose_skills":{"description":"ExposeSkills overrides whether this server's skills (MCP skills\nextension) are read when Config.EnableSkills is on. nil (default)\ninherits (included if the server supports skills); false excludes it.","type":"boolean"},"forward_headers":{"description":"ForwardHeaders lists inbound MCP-client header NAMES (never values) that\nare copied into this server's upstream tools/call requests (Spec 112).\nExact names, case-insensitive, at most 32, no wildcards. Empty forwards\nnothing. Only HTTP-based transports (http, streamable-http) forward; the\ndeny list (Authorization, Host, hop-by-hop, ...) is enforced at runtime\nregardless of what is configured here.","items":{"type":"string"},"type":"array","uniqueItems":false},"headers":{"additionalProperties":{"type":"string"},"description":"For HTTP servers","type":"object"},"health_check_interval":{"description":"Per-server discovery \u0026 health-check overrides (spec 074). Same *Duration\ntri-state as the global keys: nil = inherit the global value (or default),\npointer to 0s = disabled for this server, positive = that interval.\nHealthCheckInterval is fully wired into the per-server health loop;\nToolDiscoveryInterval is accepted/validated and round-trips for\nforward-compat, but the periodic index sweep is governed by the global\ncadence in this iteration (see spec 074 plan §C).","type":"string"},"init_timeout":{"description":"InitTimeout overrides the global init_timeout for this server's MCP\n` + "`" + `initialize` + "`" + ` handshake deadline (MCP-3322 / GH #760). *Duration tri-state:\nnil = inherit the global value (or 30s default), positive = that deadline.\nResolved by Config.ResolveInitTimeout; validated to {0} ∪ [1s, 30m]. Raise\nthis for upstreams that do legitimate first-run warmup (e.g. caching many\nchannels/users) before responding to ` + "`" + `initialize` + "`" + `.","type":"string"},"isolation":{"$ref":"#/components/schemas/config.IsolationConfig"},"launcher_wait_timeout":{"description":"LauncherWaitTimeout caps how long mcpproxy will wait for a locally-launched\nHTTP/SSE upstream's URL to become reachable after Spawn(). Only consulted\nwhen the server is configured with both Command and an HTTP/SSE URL — i.e.,\nmcpproxy starts the process AND connects via network. Stdio servers ignore\nthis field. Zero or unset → 30s default.","type":"string"},"max_concurrent_requests":{"description":"Per-server concurrency overrides — scope (c) of FR-020 (spec 093, #955).\nTri-state per setting, exactly like HealthCheckInterval: absent = inherit\nthe per-server default set (server_concurrency_defaults), explicit 0 =\ndisable that setting for this server (0 max = no per-server limiter at\nall; 0 queue_size = no pending capacity, shed immediately at the cap),\npositive = override. The global aggregate limiter is never inherited from\nhere — it applies on top, so effective concurrency is min(per-server,\nglobal). Resolved by Config.ResolveServerConcurrency.","type":"integer"},"name":{"type":"string"},"oauth":{"$ref":"#/components/schemas/config.OAuthConfig"},"protocol":{"description":"stdio, http, sse, streamable-http, auto","type":"string"},"quarantined":{"description":"Security quarantine status","type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_on_use":{"description":"Attempt reconnection when a tool call targets a disconnected server","type":"boolean"},"shared":{"description":"Server edition: shared with all users","type":"boolean"},"skip_quarantine":{"description":"SkipQuarantine is DEPRECATED (MCP-2930): use AutoApproveToolChanges instead.\nKept for back-compat parsing; on config load a legacy skip_quarantine:true is\nmigrated to auto_approve_tool_changes:true only when the new field is unset\n(see normalizeServerQuarantineFlags).","type":"boolean"},"source_registry_id":{"description":"SourceRegistryID records which registry this server was added from (empty\nfor manually-configured servers). MCP-866: surfaced in the approval /\nquarantine view so a reviewer can see a server's origin.","type":"string"},"source_registry_provenance":{"description":"SourceRegistryProvenance records the source registry's provenance at add\ntime (RegistryProvenanceOfficial / RegistryProvenanceCustom). It is purely\ninformational (MCP-1072) — surfaced so a reviewer can see a server's origin\n— and no longer gates quarantine or skip_quarantine.","type":"string"},"tool_argument_error_mode":{"description":"ToolArgumentErrorMode stores the per-upstream argument-error policy.\nEmpty and detailed retain detailed errors; redacted opts into redaction.\nUpdates omit/keep an empty value; detailed explicitly resets the policy.","type":"string"},"tool_discovery_interval":{"type":"string"},"toon_output":{"description":"ToonOutput overrides the global toon_output mode for this server's\ntools (spec 084, FR-001). Plain string, not a pointer: \"\"/absent =\ninherit the global value; \"off\"|\"adaptive\"|\"always\" = override (\"off\"\nis the explicit force-off). Resolved by Config.ResolveToonOutput.","type":"string"},"trust_mode":{"description":"TrustMode is the per-server trust tier: auto|scan|manual. Supersedes\nauto_approve_tool_changes (spec 086). An empty value is derived from the\nlegacy fields at load via normalizeServerQuarantineFlags; the single\nresolution point is EffectiveTrustMode(), which treats an empty value as\nscan (DefaultTrustMode, spec 119) and an unrecognized value as manual\n(fail closed). Read via\nEffectiveTrustMode(), never the raw string.","type":"string"},"updated":{"type":"string"},"url":{"type":"string"},"working_dir":{"description":"Working directory for stdio servers","type":"string"}},"type":"object"},"config.TLSConfig":{"description":"TLS configuration","properties":{"cert_file":{"description":"CertFile is the absolute path of an operator-provided server certificate\n(PEM, leaf first), served instead of a generated one. Needs KeyFile.","type":"string"},"certs_dir":{"description":"Directory for certificates","type":"string"},"enabled":{"description":"Enable HTTPS","type":"boolean"},"extra_sans":{"description":"ExtraSANs are DNS names and IP addresses added to the generated server\ncertificate, which is signed by the same local CA. Not used with CertFile.","items":{"type":"string"},"type":"array","uniqueItems":false},"hsts":{"description":"Enable HTTP Strict Transport Security","type":"boolean"},"key_file":{"description":"KeyFile is the absolute path of the private key for CertFile (PEM).","type":"string"},"require_client_cert":{"description":"Enable mTLS","type":"boolean"}},"type":"object"},"config.TelemetryConfig":{"description":"Telemetry settings (Spec 036)","properties":{"anonymous_id":{"description":"Auto-generated UUIDv4","type":"string"},"anonymous_id_created_at":{"description":"Spec 042 (Tier 2) additions — all default-zero, all backwards-compatible.","type":"string"},"enabled":{"description":"Default: true (opt-out)","type":"boolean"},"endpoint":{"description":"Override for testing","type":"string"},"last_reported_version":{"description":"Upgrade funnel","type":"string"},"last_startup_outcome":{"description":"success|port_conflict|db_locked|...","type":"string"},"notice_shown":{"description":"First-run notice flag","type":"boolean"}},"type":"object"},"config.TokenizerConfig":{"description":"Tokenizer configuration for token counting","properties":{"default_model":{"description":"Default model for tokenization (e.g., \"gpt-4\")","type":"string"},"enabled":{"description":"Enable token counting","type":"boolean"},"encoding":{"description":"Default encoding (e.g., \"cl100k_base\")","type":"string"}},"type":"object"},"config.TracingExporterConfig":{"description":"Tracing gates the OpenTelemetry OTLP trace exporter (MCP-32). Disabled by\ndefault.","properties":{"enabled":{"description":"Enabled turns on OTLP trace export for tool calls and upstream hops.","type":"boolean"},"endpoint":{"description":"Endpoint is the collector address as host:port (no scheme), e.g.\n\"localhost:4318\" for http or \"localhost:4317\" for grpc.","type":"string"},"protocol":{"description":"Protocol selects the OTLP transport: \"http\" or \"grpc\".","type":"string"},"sample_rate":{"description":"SampleRate is the head-based trace sampling ratio in [0,1]. Default 0.1.\nOmit the key for the 0.1 default; set it to 0 to sample nothing.","type":"number"}},"type":"object"},"config.UpdateCheckConfig":{"description":"Update-check settings (Spec 079 FR-012): config-file control of the\nbackground upgrade-awareness checker (internal/updatecheck). nil =\nenabled on the stable channel (existing default behavior). The existing\nenvironment switches keep working and WIN over these keys (FR-014):\nMCPPROXY_DISABLE_AUTO_UPDATE=true force-disables even when\nenabled=true, and MCPPROXY_ALLOW_PRERELEASE_UPDATES=true force-selects\nthe rc channel even when channel=stable.","properties":{"channel":{"description":"Channel selects which releases are offered as updates: \"stable\"\n(default; prereleases never offered) or \"rc\" (prereleases included).\nEmpty resolves to stable. Validated in ValidateDetailed.\n\nNOTE: for a RELEASED build the running binary's own version is\nauthoritative and overrides this field — a stable build is never\noffered an RC (even with channel=rc), and an RC build always tracks the\nrc channel. This field only takes effect on dev/unstamped builds. See\ninternal/updatecheck.Checker.IncludePrereleases.","type":"string"},"enabled":{"description":"Enabled gates all update checking. Tri-state: nil/absent = enabled\n(default true, matching pre-079 behavior). When false, no network\ncheck is performed and no upgrade nudge appears on any surface\n(FR-015) — /api/v1/info omits the update object entirely.","type":"boolean"}},"type":"object"},"configimport.FailedServer":{"properties":{"details":{"type":"string"},"error":{"type":"string"},"name":{"type":"string"}},"type":"object"},"configimport.ImportSummary":{"properties":{"failed":{"type":"integer"},"imported":{"type":"integer"},"skipped":{"type":"integer"},"total":{"type":"integer"}},"type":"object"},"configimport.SkippedServer":{"properties":{"name":{"type":"string"},"reason":{"description":"\"already_exists\", \"filtered_out\", \"invalid_name\", \"self_reference\"","type":"string"}},"type":"object"},"connect.ConnectResult":{"description":"The full result; its action mirrors the top-level one","properties":{"action":{"description":"\"created\", \"updated\", \"already_exists\", \"removed\", \"not_found\"","type":"string"},"auth":{"description":"Auth is \"oauth\" when the entry holds the per-client browser login\naddress and no credential (Spec 132). Empty for an API-key entry.","type":"string"},"auth_note":{"description":"AuthNote says what Connect left alone: an oauth write does not revoke the\nclient's existing API key.","type":"string"},"backup_path":{"type":"string"},"cleanup_error":{"description":"CleanupError is set when a disconnect removed the entry but could not list\nthe config's directory to remove the undo records of a browser-login\nconnect (Spec 132). The disconnect still succeeded.","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":{"auth":{"description":"Auth is \"key\" (default) or \"oauth\" (Spec 132): \"oauth\" writes the\nclient's browser login address and no credential. It is refused while\nmcp_oauth_enabled is off, for a client that does not support it, in the\nserver edition, and together with keyless, profile or mode.","enum":["key","oauth"],"type":"string"},"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"}}}, + "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"},"secret_file_dirs":{"description":"SecretFileDirs lists absolute directories where ${file:} references may\nbe resolved. Absent (nil) uses platform defaults; an explicit empty array\ndisables file references; exactly [\"*\"] allows any path (compatibility mode).","items":{"type":"string"},"type":"array","uniqueItems":false},"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"},"auth":{"description":"Auth is \"oauth\" when the entry holds the per-client browser login\naddress and no credential (Spec 132). Empty for an API-key entry.","type":"string"},"auth_note":{"description":"AuthNote says what Connect left alone: an oauth write does not revoke the\nclient's existing API key.","type":"string"},"backup_path":{"type":"string"},"cleanup_error":{"description":"CleanupError is set when a disconnect removed the entry but could not list\nthe config's directory to remove the undo records of a browser-login\nconnect (Spec 132). The disconnect still succeeded.","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":{"auth":{"description":"Auth is \"key\" (default) or \"oauth\" (Spec 132): \"oauth\" writes the\nclient's browser login address and no credential. It is refused while\nmcp_oauth_enabled is off, for a client that does not support it, in the\nserver edition, and together with keyless, profile or mode.","enum":["key","oauth"],"type":"string"},"force":{"description":"Overwrite existing entry","type":"boolean"},"keyless":{"type":"boolean"},"mode":{"type":"string"},"precondition_token":{"description":"PreconditionToken is the opaque token from the preview this write was\nconfirmed against (Spec 091 FR-005). When present, the core rechecks it\nat write time and responds 409 with action \"precondition_failed\" —\nwriting nothing — if the config or the entry MCPProxy would write has\ndrifted since; the caller then re-previews instead of retrying. Absent\nmeans exactly the pre-091 behavior. A replace-classified flow sends this\nTOGETHER with force=true: the token, not the absence of force, is the\noverwrite safety.","type":"string"},"profile":{"description":"Profile, Mode and Keyless are the client-credential intent (Spec 108\nFR-024). Profile names the profile the client's credential binds to;\n\"\" is the built-in All servers scope. Omitted means \"not specified\": a\nfresh credential defaults to All servers and a reconnect keeps the\nclient's existing binding (a reconnect never silently widens a locked\nclient). Mode is locked|switchable (default locked for a named profile,\nswitchable for All servers). Keyless writes a credential-less entry and\nis only possible while require_mcp_auth is off; it cannot carry a\nprofile or mode.","type":"string"},"server_name":{"description":"Defaults to \"mcpproxy\"","type":"string"}},"type":"object"},"httpapi.CreateClientRequest":{"properties":{"display_name":{"type":"string"},"expires_in":{"description":"ExpiresIn is a duration like 30d or 720h; default and cap are 365 days.","type":"string"},"id":{"type":"string"},"mode":{"type":"string"},"profile":{"type":"string"},"purpose":{"description":"Purpose is the stated, unenforced task brief (Spec 115), at most 500\ncharacters; screened for secrets before anything is stored.","type":"string"}},"type":"object"},"httpapi.CreateClientResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"credential":{"type":"string"},"snippet":{"$ref":"#/components/schemas/httpapi.ClientSnippet"}},"type":"object"},"httpapi.EffectiveToolsData":{"properties":{"counts":{"$ref":"#/components/schemas/runtime.EffectiveCounts"},"profile":{"type":"string"},"stale_classification_reasons":{"additionalProperties":{"type":"string"},"description":"StaleClassificationReasons maps each stale classify entry to why it no\nlonger applies: profile.StaleClassificationAnnotated or\nprofile.StaleClassificationMissing. It is computed over the UNFILTERED\ntool set, so a server or reason filter never changes it. Administrators\nonly.","type":"object"},"stale_classifications":{"description":"StaleClassifications lists classify entries for tools that are now\nannotated or no longer exist (FR-005). Administrators only.","items":{"type":"string"},"type":"array","uniqueItems":false},"tools":{"items":{"$ref":"#/components/schemas/runtime.EffectiveTool"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.EnvFieldPreview":{"properties":{"empty_or_placeholder":{"type":"boolean"},"name":{"type":"string"},"secret_like":{"type":"boolean"},"value_present":{"type":"boolean"}},"type":"object"},"httpapi.FinalizeClientResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"rotation":{"$ref":"#/components/schemas/httpapi.RotationState"}},"type":"object"},"httpapi.ForgetClientResponse":{"properties":{"disconnect_error":{"type":"string"},"disconnected":{"type":"boolean"},"revoked":{"type":"string"}},"type":"object"},"httpapi.GuardBinding":{"properties":{"client_id":{"type":"string"},"mode":{"type":"string"},"profile":{"type":"string"},"token_name":{"type":"string"}},"type":"object"},"httpapi.GuardFixOption":{"properties":{"kind":{"type":"string"},"target":{"type":"string"}},"type":"object"},"httpapi.HeaderFieldPreview":{"properties":{"empty_or_placeholder":{"type":"boolean"},"name":{"type":"string"},"secret_like":{"type":"boolean"},"value_present":{"type":"boolean"}},"type":"object"},"httpapi.ImportFromPathRequest":{"properties":{"format":{"description":"Optional format hint","type":"string"},"path":{"description":"File path to import from","type":"string"},"rename":{"additionalProperties":{"type":"string"},"description":"Rename maps a server name → new name. Applied after parsing so the\ncaller can disambiguate cross-source name collisions (Spec 046 v2 —\ne.g. \"mcpproxy\" → \"mcpproxy_claude_code\"). Keys are matched against\neither the raw source name (OriginalName) or the sanitized name shown\nin the preview (Server.Name); these differ for names that need\nsanitizing (e.g. \"Figma Desktop\" → \"Figma_Desktop\"). Keys not present\nin the imported set are ignored.","type":"object"},"server_names":{"description":"Optional: import only these servers","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportRequest":{"properties":{"allow_paste_fallback":{"description":"AllowPasteFallback opts into detecting a bare URL or a single command\nline (FR-064) when Format/format detection would otherwise fail — see\nconfigimport.ImportOptions.AllowPasteFallback for why this must stay\nopt-in (review round 4 F-E). Only the interactive Paste tab sets this;\nevery other caller of this endpoint (the general \"Import config\"\npanel, or a direct API call) leaves it false and gets a clear\n\"unable to detect configuration format\" error for a plain one-liner\ninstead of it being silently guessed at and, on apply, added as a\nreal server with no confirmation step.","type":"boolean"},"content":{"description":"Raw JSON or TOML content","type":"string"},"env_override":{"additionalProperties":{"type":"string"},"description":"EnvOverride/HeaderOverride (Spec 109 FR-064/065, PR review round 4\nF-A/F-D fix): the Paste tab's per-field Value/Secret edits — a plain\nvalue the user typed, or a keyring ref path if they chose Secret —\nkeyed by field name. Applied to the matching imported server's\nEnv/Headers ONLY when preview=false, directly on the server this\nrequest's own raw Content parses to server-side. This is what lets\nthe apply call carry the user's edited env/header values without\never round-tripping the redacted preview: url/command/args on apply\nalways come from re-parsing Content here, never from a client-held\npreview response, so a credential embedded in a URL query param or\nargv flag (which the preview necessarily redacted for display) is\nnever overwritten with the masked placeholder.","type":"object"},"format":{"description":"Optional format hint","type":"string"},"header_override":{"additionalProperties":{"type":"string"},"type":"object"},"server_names":{"description":"Optional: import only these servers","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportResponse":{"properties":{"failed":{"items":{"$ref":"#/components/schemas/configimport.FailedServer"},"type":"array","uniqueItems":false},"format":{"type":"string"},"format_name":{"type":"string"},"imported":{"items":{"$ref":"#/components/schemas/httpapi.ImportedServerResponse"},"type":"array","uniqueItems":false},"skipped":{"items":{"$ref":"#/components/schemas/configimport.SkippedServer"},"type":"array","uniqueItems":false},"summary":{"$ref":"#/components/schemas/configimport.ImportSummary"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportedServerResponse":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"command":{"type":"string"},"env":{"items":{"$ref":"#/components/schemas/httpapi.EnvFieldPreview"},"type":"array","uniqueItems":false},"fields_skipped":{"items":{"type":"string"},"type":"array","uniqueItems":false},"headers":{"items":{"$ref":"#/components/schemas/httpapi.HeaderFieldPreview"},"type":"array","uniqueItems":false},"name":{"type":"string"},"original_name":{"type":"string"},"protocol":{"type":"string"},"source_format":{"type":"string"},"summary":{"description":"Summary, Tags, Env and Headers are the Spec 109 FR-064 preview\nenrichment (contracts/rest-api.md \"Import preview\"). Summary and Tags\nare built from the already-redacted URL/Command/Args above, so a\nsecret embedded in argv or a URL query never reaches Summary either.\nEnv/Headers never carry the raw value — only its presence and two\nbooleans a surface uses to default the Value/Secret toggle (FR-065).","type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"url":{"type":"string"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.IsolationRequest":{"description":"Isolation carries per-server Docker isolation overrides (enabled,\nmode_override, image, network_mode, extra_args, working_dir). A nil\npointer means \"do not touch isolation config\". A present object is\napplied field-by-field ON TOP of the persisted overrides, so omitting a\nfield leaves it alone; clear an individual override by sending it\nexplicitly (` + "`" + `\"enabled\": null` + "`" + `, ` + "`" + `\"image\": \"\"` + "`" + `).","properties":{"enabled":{"description":"Enabled exists ONLY to detect and reject an echoed-back read. It is the\neffective state on the read surface and is never writable; see validate().","type":"boolean"},"enabled_override":{"description":"EnabledOverride is the tri-state per-server override — the RAW value, the\nsame one reads return as ` + "`" + `enabled_override` + "`" + `. It has THREE meaningful wire\nstates, and collapsing them is what silently un-isolated servers\n(GH #1142):\n - absent → leave the persisted override untouched\n - null → clear the override, back to inheriting the global\n - true / false → set an explicit opt-in / opt-out","type":"boolean"},"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"mode_override":{"description":"ModeOverride sets ` + "`" + `isolation.mode` + "`" + ` (\"docker\" | \"sandbox\" | \"none\").\nnil leaves the persisted value alone; an empty string clears it. An\nunrecognized value is rejected with a 400 rather than persisted.","type":"string"},"network_mode":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"httpapi.OAuthApprovalBody":{"properties":{"binding_revision":{"type":"string"},"client":{"$ref":"#/components/schemas/httpapi.OAuthClientChoice"},"mode":{"type":"string"},"profile":{"type":"string"},"replace_grant":{"type":"string"}},"type":"object"},"httpapi.OAuthClientChoice":{"properties":{"id":{"type":"string"},"new":{"$ref":"#/components/schemas/httpapi.OAuthNewClient"}},"type":"object"},"httpapi.OAuthDecisionResponse":{"properties":{"redirect_url":{"type":"string"}},"type":"object"},"httpapi.OAuthNewClient":{"properties":{"display_name":{"type":"string"},"id":{"type":"string"}},"type":"object"},"httpapi.OnboardingMarkRequest":{"properties":{"connect_step_status":{"description":"ConnectStepStatus is one of: \"\", \"completed\", \"skipped\". Empty\npreserves the existing value. The stored enum is wider (Spec 080\nFR-001): a \"skipped\" request for a previously untouched connect step\nis upgraded server-side to \"completed_external\" when the install\nshows positive evidence of an external connection (Spec 080 FR-002).\n\"completed_external\" is NOT accepted from clients — it must never be\npersisted without that server-verified evidence (edge case: \"never\nguess completed_external without positive evidence\").","type":"string"},"connected_client_id":{"description":"ConnectedClientID records a successful connect write for this client id\n(Spec 109-b FR-042, review round 6). The REST connect endpoint\n(POST /api/v1/connect/{client}) already records this itself on success;\nthis field exists so ` + "`" + `mcpproxy connect` + "`" + ` — which writes the client's\nconfig file directly, without going through that endpoint, so the\ncommand still works when no daemon is running — can relay the same\nevent to a daemon that IS running, keeping ClientConnectedAt in sync\nacross both surfaces. Must be a known id from the fixed connect client\nregistry (internal/connect.GetAllClients); any other value is rejected,\nmatching the field's \"bounded by the registry\" invariant\n(data-model.md §7).","type":"string"},"disconnected_client_id":{"description":"DisconnectedClientID relays a successful local CLI disconnect to a running\ndaemon, which cannot observe the CLI's direct config-file edit itself.\nLike ConnectedClientID, it is bounded to the fixed client registry.","type":"string"},"engaged":{"description":"Engaged marks the wizard as engaged (completed or explicitly skipped).\nOnce true, the wizard does not auto-show again.","type":"boolean"},"mark_shown":{"description":"MarkShown records the wizard's first display time if not already set.","type":"boolean"},"server_step_status":{"description":"ServerStepStatus is one of: \"\", \"completed\", \"skipped\". Empty\npreserves the existing value.","type":"string"}},"type":"object"},"httpapi.OnboardingStateResponse":{"properties":{"configured_server_count":{"description":"ConfiguredServerCount is the number of upstream MCP servers configured\nin mcpproxy (counts both enabled and disabled).","type":"integer"},"connected_client_count":{"description":"ConnectedClientCount is the number of supported clients currently\npointing at mcpproxy.","type":"integer"},"connected_client_ids":{"description":"ConnectedClientIDs are the identifiers of supported clients currently\npointing at mcpproxy. Drawn exclusively from the fixed adapter table —\nuser-entered values never appear here.","items":{"type":"string"},"type":"array","uniqueItems":false},"first_mcp_client_ever":{"description":"FirstMCPClientEver is true once any MCP client has successfully completed\nan ` + "`" + `initialize` + "`" + ` round-trip with this mcpproxy. Sourced from the Spec 044\nactivation bucket. Drives the Verify tab's \"green check\" state.","type":"boolean"},"has_configured_server":{"description":"HasConfiguredServer is true if at least one upstream MCP server is\nconfigured (regardless of current connection health).","type":"boolean"},"has_connected_client":{"description":"HasConnectedClient is true if at least one supported AI client currently\nhas mcpproxy registered in its config.","type":"boolean"},"has_usable_server":{"description":"HasUsableServer is true once at least one enabled, non-quarantined\nserver has usable health and at least one approved (non-disabled) tool.\nThis is the real \"the wizard has something to try\" signal:\nHasConfiguredServer only means a server entry exists, even while every\none of them sits quarantined, requires sign-in, or has zero approved\ntools. The Servers step and Setup badge use this instead of\nHasConfiguredServer, which is kept above for compatibility.\nHealthStatus.Usable is the shared\nreadiness contract used by every UI surface (Spec 109-c, tasks.md T051).","type":"boolean"},"incomplete_tab_count":{"description":"IncompleteTabCount is the number of wizard tabs whose state is incomplete.\nDrives the sidebar Setup entry's badge. Formula:\n +1 if HasConnectedClient == false\n +1 if HasUsableServer == false\n +1 if FirstMCPClientEver == false","type":"integer"},"mcp_clients_seen_ever":{"description":"MCPClientsSeenEver is the capped list of recognized client names that\nhave ever called this mcpproxy. Names come from the MCP ` + "`" + `initialize` + "`" + `\npayload's ` + "`" + `clientInfo.name` + "`" + ` field, sanitized. Surfaces on the Verify tab\nso the user can see whether their real IDE — not a test client — has\nconnected.","items":{"type":"string"},"type":"array","uniqueItems":false},"should_show_wizard":{"description":"ShouldShowWizard is the derived flag the frontend uses to decide\nwhether to auto-show. True when not engaged and IncompleteTabCount \u003e 0\n(Spec 046 v2 — semantics widened to also count the Verify tab).","type":"boolean"},"state":{"$ref":"#/components/schemas/storage.OnboardingState"},"usable_servers":{"description":"UsableServers lists the names behind HasUsableServer, for the Verify\nstep's suggested-prompt generator (FR-042): prompts are only built from\ntools of servers in this list, never from a quarantined or toolless one.","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileConflictResponse":{"properties":{"code":{"type":"string"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"description":"Always false","type":"boolean"},"used_by":{"$ref":"#/components/schemas/httpapi.ProfileUsedByData"}},"type":"object"},"httpapi.ProfileDeleteData":{"properties":{"anonymous_profile_moved_to":{"type":"string"},"deleted":{"type":"string"},"moved":{"$ref":"#/components/schemas/runtime.MovedRefs"}},"type":"object"},"httpapi.ProfileListData":{"properties":{"anonymous_profile":{"type":"string"},"profiles":{"items":{"$ref":"#/components/schemas/runtime.ProfileView"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileRenameData":{"properties":{"moved":{"$ref":"#/components/schemas/runtime.MovedRefs"},"profile":{"$ref":"#/components/schemas/runtime.ProfileView"}},"type":"object"},"httpapi.ProfileTryData":{"properties":{"hidden":{"items":{"$ref":"#/components/schemas/runtime.TryHidden"},"type":"array","uniqueItems":false},"hidden_by_profile":{"type":"integer"},"hidden_truncated":{"type":"boolean"},"results":{"items":{"additionalProperties":{},"type":"object"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileUsedByData":{"properties":{"anonymous_profile":{"type":"boolean"},"clients":{"items":{"$ref":"#/components/schemas/runtime.UsedByClient"},"type":"array","uniqueItems":false},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ProfileViewData":{"properties":{"blocked_24h":{"type":"integer"},"calls_24h":{"type":"integer"},"code_execution":{"type":"boolean"},"description":{"type":"string"},"effective_code_execution":{"type":"boolean"},"effective_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"effective_unannotated":{"type":"string"},"is_legacy":{"type":"boolean"},"management_tools":{"type":"boolean"},"max_tier":{"type":"string"},"name":{"type":"string"},"servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"switchable_to":{"items":{"type":"string"},"type":"array","uniqueItems":false},"title":{"type":"string"},"tool_count":{"description":"ToolCount is the v2 field: indexed tools on the effective servers.\nDeprecated: use tool_counts.","type":"integer"},"tool_counts":{"$ref":"#/components/schemas/runtime.ToolCounts"},"tools":{"$ref":"#/components/schemas/config.ProfileToolRules"},"unannotated":{"type":"string"},"used_by":{"$ref":"#/components/schemas/runtime.UsedBy"}},"type":"object"},"httpapi.ProfileWriteData":{"properties":{"profile":{"$ref":"#/components/schemas/runtime.ProfileView"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.PutClientBindingRequest":{"properties":{"mode":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.RenameProfileRequest":{"properties":{"new_name":{"type":"string"}},"type":"object"},"httpapi.RevokeCredentialResponse":{"properties":{"changed":{"type":"boolean"}},"type":"object"},"httpapi.RotateClientRequest":{"properties":{"precondition_token":{"description":"PreconditionToken is the token of GET /connect/{client}/preview; it\nbinds a supported client's rotation to what the preview showed.","type":"string"}},"type":"object"},"httpapi.RotateClientResponse":{"properties":{"client":{"$ref":"#/components/schemas/httpapi.clientPresence"},"connect":{"$ref":"#/components/schemas/connect.ConnectResult"},"credential":{"type":"string"},"rotation":{"$ref":"#/components/schemas/httpapi.RotationState"},"snippet":{"$ref":"#/components/schemas/httpapi.ClientSnippet"}},"type":"object"},"httpapi.RotationState":{"properties":{"state":{"type":"string"}},"type":"object"},"httpapi.SetActiveProfileRequest":{"properties":{"active_profile":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.StaleReviewErrorResponse":{"properties":{"error":{"type":"string"},"error_code":{"type":"string"},"request_id":{"type":"string"},"stale_tools":{"$ref":"#/components/schemas/httpapi.StaleToolsDetail"},"success":{"type":"boolean"}},"type":"object"},"httpapi.StaleToolsDetail":{"properties":{"changed":{"items":{"type":"string"},"type":"array","uniqueItems":false},"missing_blocks":{"items":{"type":"string"},"type":"array","uniqueItems":false},"unreviewed":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.TryProfileRequest":{"properties":{"limit":{"type":"integer"},"profile":{"$ref":"#/components/schemas/config.ProfileConfig"},"query":{"type":"string"}},"type":"object"},"httpapi.UndoConnectRequest":{"properties":{"backup_name":{"description":"BackupName is the bare filename (filepath.Base) of the backup returned as\nbackup_path by the preceding connect — a name, never a path. Undo resolves\nthe full path server-side by joining it with the client's own config\ndirectory, so a client-supplied value can never contribute a directory\ncomponent (traversal is impossible by construction). Empty means the\nconnect created the file (no prior file existed), so undo removes it.","type":"string"},"server_name":{"description":"Defaults to \"mcpproxy\"","type":"string"}},"type":"object"},"httpapi.UpdateFailureRequest":{"properties":{"stage":{"description":"Stage is the failure stage of the update session.","enum":["appcast","download","install","other"],"type":"string"}},"type":"object"},"httpapi.UpgradeAdminKeyHoldersRequest":{"properties":{"apply":{"type":"boolean"},"mode":{"type":"string"},"precondition_token":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.approveToolsRequest":{"properties":{"approve_all":{"type":"boolean"},"expected_hashes":{"additionalProperties":{"type":"string"},"description":"ExpectedHashes binds the approval to the reviewed definitions (Spec\n117 PR-2, #1566): tool name -\u003e the review's current_hash. Absent or\nnull is an unbound (legacy) request; {} is bound.","type":["object","null"]},"expected_incarnation":{"description":"ExpectedIncarnation binds the approval to the server the client\nreviewed (Spec 116 FR-017); 409 server_replaced on a mismatch. It is\nindependent of ExpectedHashes and the two may be sent together.","type":"integer"},"tools":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.attentionResponse":{"properties":{"count":{"type":"integer"},"generated_at":{"type":"string"},"items":{"items":{"$ref":"#/components/schemas/contracts.AttentionItem"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.bundleRollbackRequest":{"properties":{"digest":{"description":"Digest is the full 64-character lowercase hex SHA-256 of the target.","type":"string"},"embedded":{"description":"Embedded rolls back to the corpus compiled into this binary.","type":"boolean"},"path":{"description":"Path is where to find the target bundle (a hint only).","type":"string"}},"type":"object"},"httpapi.clientPresence":{"properties":{"active_sessions":{"type":"integer"},"blocked_24h":{"type":"integer"},"browser_login_disabled":{"type":"boolean"},"calls_24h":{"type":"integer"},"config_path":{"type":"string"},"connected":{"type":"boolean"},"connection_unverified":{"type":"boolean"},"credential_checked_at":{"type":"string"},"credential_state":{"$ref":"#/components/schemas/profile.CredentialState"},"credentials":{"description":"Spec 132: the client's credentials (API key and browser logins) and\nwhether browser login is off right now. Both exist only once browser\nlogin was used on this install; until then a row is exactly what it was.\n\nCredentials is a pointer so that once the feature was used a row with no\ncredential serialises \"credentials\": [] instead of omitting the field.","items":{"$ref":"#/components/schemas/httpapi.ClientCredential"},"type":"array","uniqueItems":false},"display_name":{"type":"string"},"display_path":{"type":"string"},"expires_at":{"type":"string"},"icon":{"type":"string"},"id":{"type":"string"},"installed":{"type":"boolean"},"issuer":{"$ref":"#/components/schemas/auth.CredentialIssuer"},"kind":{"type":"string"},"last_seen":{"type":"string"},"lease":{"type":"boolean"},"profile":{"type":"string"},"profile_missing":{"type":"boolean"},"profile_mode":{"type":"string"},"profile_source":{"description":"profile_source is pin (locked) or binding (switchable) and is empty when\ncredential_state is not client.","type":"string"},"profile_state":{"type":"string"},"profile_title":{"type":"string"},"purpose":{"type":"string"},"reload_hint":{"type":"string"},"revoked_at":{"description":"Spec 115 lifecycle fields of the client's credential record (additive):\nwhen it was revoked, who issued it, its stated (unenforced) purpose,\nwhether it is a task lease (lifetime at issue \u003c= 24h) and whether its\nprofile still exists (ok | dangling | none).","type":"string"},"rotation_pending":{"type":"boolean"},"sessions":{"items":{"$ref":"#/components/schemas/httpapi.clientSession"},"type":"array","uniqueItems":false},"state":{"type":"string"},"token_name":{"type":"string"}},"type":"object"},"httpapi.clientSession":{"properties":{"id":{"type":"string"},"last_activity":{"type":"string"},"profile":{"description":"Profile and ProfileSource are the session's latest effective resolution\n(Spec 108-e FR-033); empty on legacy sessions.","type":"string"},"profile_source":{"type":"string"},"started_at":{"type":"string"},"work_session_id":{"type":"string"}},"type":"object"},"httpapi.clientsResponse":{"properties":{"clients":{"items":{"$ref":"#/components/schemas/httpapi.clientPresence"},"type":"array","uniqueItems":false},"routing":{},"warnings":{"items":{"$ref":"#/components/schemas/httpapi.ClientWarning"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.expectedIncarnationBody":{"properties":{"expected_incarnation":{"type":"integer"}},"type":"object"},"httpapi.securityApproveRequest":{"properties":{"block":{"items":{"type":"string"},"type":"array","uniqueItems":false},"expected_hashes":{"additionalProperties":{"type":"string"},"description":"ExpectedHashes binds the approval to the reviewed definitions (Spec\n117 PR-2, #1566): tool name -\u003e the review's current_hash. Absent or\nnull is an unbound (legacy) request; {} binds to the empty snapshot.\nIndependent of ExpectedIncarnation: a request may carry both, and the\ntwo refusals stay distinct (review_out_of_date vs server_replaced).","type":["object","null"]},"expected_incarnation":{"description":"ExpectedIncarnation binds the approval to the server the client\nreviewed (Spec 116 FR-017): a remove and re-add since then is refused\nwith 409 server_replaced and the replacement stays quarantined.","type":"integer"},"force":{"type":"boolean"}},"type":"object"},"management.BulkOperationResult":{"properties":{"errors":{"additionalProperties":{"type":"string"},"description":"Map of server name to error message","type":"object"},"failed":{"description":"Number of failed operations","type":"integer"},"successful":{"description":"Number of successful operations","type":"integer"},"total":{"description":"Total servers processed","type":"integer"}},"type":"object"},"observability.HealthResponse":{"properties":{"components":{"items":{"$ref":"#/components/schemas/observability.HealthStatus"},"type":"array","uniqueItems":false},"status":{"description":"\"healthy\" or \"unhealthy\"","type":"string"},"timestamp":{"type":"string"}},"type":"object"},"observability.HealthStatus":{"properties":{"error":{"type":"string"},"latency":{"type":"string"},"name":{"type":"string"},"status":{"description":"\"healthy\" or \"unhealthy\"","type":"string"}},"type":"object"},"observability.ReadinessResponse":{"properties":{"components":{"items":{"$ref":"#/components/schemas/observability.HealthStatus"},"type":"array","uniqueItems":false},"status":{"description":"\"ready\" or \"not_ready\"","type":"string"},"timestamp":{"type":"string"}},"type":"object"},"profile.AccessStepStatus":{"type":"string","x-enum-varnames":["AccessStepPass","AccessStepFail","AccessStepSkip"]},"profile.AccessSubjectKind":{"type":"string","x-enum-varnames":["AccessSubjectClient","AccessSubjectProfile","AccessSubjectToken","AccessSubjectAnonymous"]},"profile.BlockReason":{"type":"string","x-enum-varnames":["BlockReasonTier","BlockReasonRule","BlockReasonUnannotated","BlockReasonCodeExecution","BlockReasonManagement","BlockReasonServerScope"]},"profile.CredentialState":{"description":"Spec 108-f ClientView additions (data-model §7). The Spec 109 fields above\nare unchanged; everything below is additive.\n\ncredential_state is what the client's connection carries (client |\nadmin_key | none | revoked | expired | unknown). The stat-only list never\nreads a config: it reports the token store, else the last on-demand\nobservation (credential_checked_at says when), else unknown.","type":"string","x-enum-varnames":["CredentialStateClient","CredentialStateAdminKey","CredentialStateNone","CredentialStateRevoked","CredentialStateExpired","CredentialStateUnknown"]},"profile.ExplainStep":{"type":"string","x-enum-varnames":["StepCredential","StepProfile","StepServerInScope","StepToolRule","StepTierCap","StepTokenPermission","StepGlobalGate","StepServerState","StepToolApproval"]},"profile.ExplainVerdict":{"type":"string","x-enum-varnames":["ExplainVerdictAllowed","ExplainVerdictBlocked","ExplainVerdictHidden"]},"profile.FixAction":{"type":"string","x-enum-varnames":["FixAllowInProfile","FixClassifyInProfile","FixAddServerToProfile","FixMoveClient","FixEditToken","FixEnableServer","FixApproveTool","FixChangeSetting","FixReconnectClient"]},"profile.WarningCode":{"type":"string","x-enum-varnames":["WarningAnonymousDeniedByBindingGuard","WarningClientHoldsAdminKey","WarningClientCredentialExpiring","WarningClientRotationPending","WarningProfileMissing","WarningClientTokenNameConflict"]},"profile.WarningSeverity":{"type":"string","x-enum-varnames":["WarningSeverityWarn","WarningSeverityInfo"]},"runtime.AccessSuggestion":{"properties":{"block_reason":{"$ref":"#/components/schemas/profile.BlockReason"},"clients":{"items":{"type":"string"},"type":"array","uniqueItems":false},"count":{"type":"integer"},"first_seen":{"type":"string"},"fixes":{"description":"Fixes are the access explainer's remediations of the first failing step,\nin preference order. Empty for a deny rule and for the built-in tools.","items":{"$ref":"#/components/schemas/runtime.Fix"},"type":"array","uniqueItems":false},"last_seen":{"type":"string"},"needs_input":{"description":"NeedsInput names what a person must supply before a change is\napply-ready (classify: \"tier\").","items":{"type":"string"},"type":"array","uniqueItems":false},"note":{"type":"string"},"profile":{"type":"string"},"server":{"type":"string"},"suggestion":{"$ref":"#/components/schemas/runtime.SuggestionKind"},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false},"tool":{"description":"\"server:tool\", or the built-in name","type":"string"},"warning":{"description":"Warning is set for profile_code_execution and profile_management: both\nchange what a profile can do beyond tool access.","type":"string"}},"type":"object"},"runtime.BindingRef":{"properties":{"client_id":{"type":"string"},"mode":{"type":"string"},"profile":{"type":"string"},"token_name":{"type":"string"}},"type":"object"},"runtime.EffectiveCounts":{"properties":{"by_reason":{"additionalProperties":{"type":"integer"},"type":"object"},"callable":{"type":"integer"},"hidden":{"type":"integer"},"visible":{"type":"integer"}},"type":"object"},"runtime.EffectiveTool":{"properties":{"access":{"$ref":"#/components/schemas/runtime.ToolAccessView"},"classification_stale":{"type":"boolean"},"intrinsic_tier":{"type":"string"},"profile_tier":{"type":"string"},"server":{"type":"string"},"tool":{"type":"string"}},"type":"object"},"runtime.ExplainProfileView":{"properties":{"name":{"type":"string"},"source":{"type":"string"}},"type":"object"},"runtime.ExplainStepView":{"properties":{"detail":{"type":"string"},"status":{"$ref":"#/components/schemas/profile.AccessStepStatus"},"step":{"$ref":"#/components/schemas/profile.ExplainStep"}},"type":"object"},"runtime.ExplainSubjectView":{"properties":{"kind":{"$ref":"#/components/schemas/profile.AccessSubjectKind"},"name":{"type":"string"}},"type":"object"},"runtime.Fix":{"properties":{"action":{"$ref":"#/components/schemas/profile.FixAction"},"label":{"type":"string"},"profile":{"description":"Profile is set for move_client only: the destination profile slug the fix\nmoves the client to. Target stays the client id (UIs navigate by it) and\nLabel carries the title, so neither can name the slug.","type":"string"},"step":{"type":"string","x-enum-varnames":["StepCredential","StepProfile","StepServerInScope","StepToolRule","StepTierCap","StepTokenPermission","StepGlobalGate","StepServerState","StepToolApproval"]},"target":{"type":"string"}},"type":"object"},"runtime.GuardFix":{"properties":{"kind":{"type":"string"},"target":{"type":"string"}},"type":"object"},"runtime.MovedRefs":{"properties":{"clients":{"items":{"type":"string"},"type":"array","uniqueItems":false},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"runtime.ProfilePatch":{"properties":{"changes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"profile":{"type":"string"},"proposed":{"$ref":"#/components/schemas/config.ProfileConfig"}},"type":"object"},"runtime.ProfileView":{"properties":{"blocked_24h":{"type":"integer"},"calls_24h":{"type":"integer"},"code_execution":{"type":"boolean"},"description":{"type":"string"},"effective_code_execution":{"type":"boolean"},"effective_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"effective_unannotated":{"type":"string"},"is_legacy":{"type":"boolean"},"management_tools":{"type":"boolean"},"max_tier":{"type":"string"},"name":{"type":"string"},"servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"switchable_to":{"items":{"type":"string"},"type":"array","uniqueItems":false},"title":{"type":"string"},"tool_count":{"description":"ToolCount is the v2 field: indexed tools on the effective servers.\nDeprecated: use tool_counts.","type":"integer"},"tool_counts":{"$ref":"#/components/schemas/runtime.ToolCounts"},"tools":{"$ref":"#/components/schemas/config.ProfileToolRules"},"unannotated":{"type":"string"},"used_by":{"$ref":"#/components/schemas/runtime.UsedBy"}},"type":"object"},"runtime.SuggestionKind":{"type":"string","x-enum-varnames":["SuggestAllow","SuggestAddServer","SuggestClassify","SuggestNone"]},"runtime.ToolAccessView":{"properties":{"callable":{"type":"boolean"},"reason":{"type":"string"},"visible":{"type":"boolean"}},"type":"object"},"runtime.ToolCounts":{"properties":{"destructive":{"type":"integer"},"read":{"type":"integer"},"unannotated_hidden":{"type":"integer"},"write":{"type":"integer"}},"type":"object"},"runtime.TryHidden":{"properties":{"reason":{"type":"string"},"server":{"type":"string"},"tool":{"type":"string"}},"type":"object"},"runtime.UsedBy":{"properties":{"anonymous_profile":{"type":"boolean"},"clients":{"items":{"$ref":"#/components/schemas/runtime.UsedByClient"},"type":"array","uniqueItems":false},"tokens":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"runtime.UsedByClient":{"properties":{"id":{"type":"string"},"mode":{"type":"string"}},"type":"object"},"runtime.WarningAction":{"properties":{"kind":{"type":"string"},"target":{"type":"string"}},"type":"object"},"scanner.BundleInfo":{"properties":{"authority":{"description":"Authority is the signing root serving this bundle: \"publisher\" (the\nembedded default, or verified against a publisher key), \"operator\", or \"\"\nfor an unsigned external bundle.","type":"string"},"bundle_version":{"description":"BundleVersion / SchemaVersion are the corpus's own declared versions.","type":"string"},"coverage_degraded":{"description":"CoverageDegraded suspends scan-mode auto-approval; DegradedReason says\nwhy (one of the Degraded* constants).","type":"boolean"},"declared_skipped":{"type":"integer"},"degraded_reason":{"type":"string"},"fingerprint":{"description":"Fingerprint is the first 12 hex chars of the SHA-256 of the corpus bytes:\na stable identity an operator (or automation) can compare across hosts\nwithout shipping the whole file around.","type":"string"},"full_digest":{"description":"FullDigest is the complete lowercase-hex SHA-256 of the bundle bytes —\nthe ONLY value rollback accepts (FR-010). Fingerprint stays the 12-hex\nhuman label beside it.","type":"string"},"generated_at":{"description":"GeneratedAt is the corpus freshness stamp. It is the bundle's own\n` + "`" + `generated_at` + "`" + ` key when present; for a file-sourced bundle without one it\nfalls back to the file's modification time, so a years-stale corpus is\ndistinguishable from a fresh export.","type":"string"},"last_activated_at":{"description":"LastActivatedAt is when the serving external bundle was activated; nil\nfor the embedded default.","type":"string"},"last_checked_at":{"description":"LastCheckedAt is the end of the most recent pipeline run, including\nno-op runs the idempotence short-circuit skipped.","type":"string"},"last_rejection":{"$ref":"#/components/schemas/scanner.BundleRejection"},"load_error":{"description":"LoadError is the reason the LAST configured-path load failed, if any. The\npreviously active (or embedded) corpus stays live — a bundle problem must\nnever leave the scanner with no signatures — but the failure is surfaced\nhere rather than swallowed.","type":"string"},"loaded_at":{"description":"LoadedAt is when this corpus became active in this process.","type":"string"},"path":{"description":"Path is the configured filesystem path, when Source is \"file\".","type":"string"},"pinned":{"description":"Pinned is true while an operator rollback pin governs activation.","type":"boolean"},"refresh":{"$ref":"#/components/schemas/scanner.BundleRefreshStatus"},"reprotect":{"$ref":"#/components/schemas/scanner.BundleReprotectStatus"},"rollback":{"description":"Rollback is true when the active bundle was activated by an explicit\nrollback.","type":"boolean"},"runnable_rules":{"description":"RunnableRules is how many rules are LIVE in the offline tier; SkippedRules\nand DeclaredSkipped are the not-runnable / bundle-declared-skipped\nremainder (FR-006/FR-007) — un-evaluated coverage, never clean coverage.","type":"integer"},"schema_version":{"type":"string"},"sequence":{"description":"Sequence is the manifest sequence as published (decimal string), \"\" when\nthe bundle carries none.","type":"string"},"signature_count":{"description":"SignatureCount is the bundle's self-declared signature count.","type":"integer"},"signature_verified":{"description":"SignatureVerified reports whether the active bundle's detached signature\nverified. Always false for the embedded default (it is binary-trusted).","type":"boolean"},"skipped_rules":{"type":"integer"},"source":{"description":"Source is BundleSourceEmbedded, BundleSourceFile or BundleSourceFetch.","type":"string"},"stale":{"description":"Stale and StaleAfterDays are computed at read time next to\nStalenessDays; a future generated_at is never stale. StaleAfterDays nil\nmeans the flag is not evaluated.","type":"boolean"},"stale_after_days":{"type":"integer"},"staleness_days":{"description":"StalenessDays is the whole days since GeneratedAt (nil when unknown).","type":"integer"},"trust_epoch":{"description":"TrustEpoch is the epoch the bundle was published under.","type":"integer"}},"type":"object"},"scanner.BundleRefreshStatus":{"description":"Refresh is the refresh-cycle status (nil before any cycle or setting is\nknown). Reprotect is the post-activation re-protection sweep status,\nset from the server through SetReprotectStatus.","properties":{"consecutive_failures":{"type":"integer"},"fetch_enabled":{"type":"boolean"},"fetch_host":{"description":"FetchHost is the host of the configured fetch URL (\"\" when none).","type":"string"},"fetch_reason":{"type":"string"},"fetch_state":{"description":"FetchState and FetchReason are the fetch leg's own last answer (one of the\nRefreshOutcome* values and its reason), kept apart from LastOutcome: a file\nactivation owns the merged cycle outcome but must not hide a fetch leg that\ncannot run (B16 warning 3).","type":"string"},"interval_seconds":{"type":"integer"},"last_attempt_at":{"type":"string"},"last_outcome":{"type":"string"},"last_reason":{"type":"string"},"last_trigger":{"description":"LastTrigger, LastOutcome and LastReason use the closed vocabularies above.","type":"string"},"next_check_at":{"type":"string"}},"type":"object"},"scanner.BundleRejection":{"description":"LastRejection is the most recent refused candidate. It is retained\nacross a later successful load so \"what did it refuse, and when\"\nsurvives.","properties":{"at":{"type":"string"},"detail":{"description":"Detail is a short human string (which ceiling, which key id, which\nepoch, the bundlesig contract code). Never parsed.","type":"string"},"reason":{"description":"Reason is one of the Reject* constants; the only field to branch on.","type":"string"}},"type":"object"},"scanner.BundleReprotectStatus":{"properties":{"last_completed_at":{"type":"string"},"reason":{"description":"Reason qualifies suspended and failed (for example\nReprotectReasonAutoBaselineScanOff).","type":"string"},"servers_scanned":{"type":"integer"},"servers_with_hits":{"type":"integer"},"state":{"description":"State is one of the ReprotectState* constants.","type":"string"}},"type":"object"},"secureenv.EnvConfig":{"description":"Environment configuration for secure variable filtering","properties":{"allowed_system_vars":{"items":{"type":"string"},"type":"array","uniqueItems":false},"custom_vars":{"additionalProperties":{"type":"string"},"type":"object"},"enhance_path":{"description":"Enable PATH enhancement for Launchd scenarios","type":"boolean"},"forward_proxy_env":{"description":"ForwardProxyEnv opts in to forwarding the ambient HTTP(S)/ALL/NO/FTP proxy\nenvironment variables to spawned upstream servers (MCP-2769). It is OFF by\ndefault and deliberately kept out of the AllowedSystemVars default list:\nproxy URLs frequently carry credentials (http://user:pass@proxy), so\nforwarding them to every stdio upstream is a credential-leak risk. When\nenabled, values are forwarded with their userinfo (credentials) redacted.","type":"boolean"},"inherit_system_safe":{"type":"boolean"}},"type":"object"},"storage.ClientCredentialObservation":{"properties":{"at":{"type":"string"},"state":{"type":"string"}},"type":"object"},"storage.OnboardingState":{"description":"State is the persisted wizard engagement record. Engaged is true once\nthe wizard was shown and the user completed or skipped it.","properties":{"client_connected_at":{"additionalProperties":{"type":"string"},"description":"ClientConnectedAt records, per client id from the fixed connect client\nregistry (internal/connect.GetAllClients — never user input), the last\ntime a connect write succeeded for that client (Spec 109-b FR-042).\nWritten by the connect success path through UpdateOnboardingState so a\nconcurrent onboarding/mark write can never drop it. Consumed by the\nVerify step / presence layer to tell \"connected, never seen\" apart from\n\"connected seconds ago, hasn't reconnected yet\".","type":"object"},"client_credential_observed":{"additionalProperties":{"$ref":"#/components/schemas/storage.ClientCredentialObservation"},"description":"ClientCredentialObserved records, per client id, the LAST credential\nclassification an on-demand read produced (Spec 108-f FR-025, F11): what\nthe client's config held (client | admin_key | none | revoked | expired)\nand when it was read. The stat-only GET /clients listing never reads a\nconfig (Spec 075: no macOS App-Data prompt from a list), so this is how\nit still reports a client that holds the admin key across restarts. It is\nwritten only when the classification CHANGES, by every on-demand read\n(GET /clients/{id}, GET /connect/{client}, the admin-key upgrade preview,\na connect write) and deleted on disconnect. Additive: an older binary\nignores it, and a record without it reads as \"unknown\".","type":"object"},"client_disconnected_at":{"additionalProperties":{"type":"string"},"type":"object"},"client_last_seen":{"additionalProperties":{"type":"string"},"description":"ClientLastSeen records the latest MCP initialize for a recognised client\nalias. It is intentionally kept with onboarding state: presence is a\nlocal UI concern and must still work when telemetry is disabled.","type":"object"},"connect_step_status":{"description":"ConnectStepStatus is one of: \"\", \"completed\", \"completed_external\",\n\"skipped\" (Spec 080 FR-001). \"completed_external\" records a dismissal\nwhere the connect step was untouched but the install was already\nconnected outside the wizard (CLI, ConnectModal, manual config).","type":"string"},"engaged":{"description":"Engaged is true once the wizard was shown and the user completed or\nskipped it. Once true, the wizard does not auto-show again, even if\nstate regresses (e.g. user disconnects all clients).","type":"boolean"},"engaged_at":{"description":"EngagedAt is the timestamp of completion or explicit skip.","type":"string"},"first_shown_at":{"description":"FirstShownAt is the timestamp of first wizard render.","type":"string"},"server_step_status":{"description":"ServerStepStatus is one of: \"\", \"completed\", \"skipped\".","type":"string"}},"type":"object"},"telemetry.DiagnosticsCounters":{"properties":{"current_error_codes":{"additionalProperties":{"type":"integer"},"description":"CurrentErrorCodes is the STANDING state at heartbeat time: stable MCPX_\ncode -\u003e number of configured servers currently in that state. It is not\na counter and is never persisted — it is recomputed each heartbeat from\nthe supervisor's live stateview.\n\nSchema v11 (MCP-2967). It exists because error_code_counts_24h became\nedge-triggered in the same change: previously the supervisor re-counted\nevery standing failure on its 30s reconcile ticker, so a parked install\ninflated the counter by ~2880/day/server. Edge-triggering alone would\nhave swung the error to the other side — the 24h window decays, this\nstruct is omitempty via isZero(), so a permanently broken install would\nemit once and then disappear from the payload entirely, and absent reads\nas zero. The two fields answer different questions and are only correct\ntogether: \"how often did something newly break\" and \"how many servers\nare broken right now\".\n\nSafe: only MCPX_* enum constants as keys, never server names, URLs,\ncommands, or free text; values are non-negative server counts.","type":"object"},"error_code_counts_24h":{"additionalProperties":{"type":"integer"},"description":"ErrorCodeCounts24h maps stable MCPX_ code strings to 24h occurrence counts.\nSafe: only MCPX_* enum constants are stored here, never free text, paths,\nserver names, or user-entered values.","type":"object"},"fix_attempted_24h":{"description":"FixAttempted24h counts POST /api/v1/diagnostics/fix calls in the last 24h.","type":"integer"},"fix_succeeded_24h":{"description":"FixSucceeded24h counts fix invocations with outcome=\"success\" in the last 24h.","type":"integer"},"unique_codes_ever":{"description":"UniqueCodesEver is the cardinality of the all-time error code set.\nBounded by the MCPX_ catalog size (~30 codes), never approaches PII risk.","type":"integer"}},"type":"object"},"telemetry.FeedbackContext":{"properties":{"anonymous_id":{"description":"AnonymousID is the install's telemetry anonymous ID (heartbeat value).","type":"string"},"arch":{"type":"string"},"connected_server_count":{"type":"integer"},"diagnostics":{"$ref":"#/components/schemas/telemetry.DiagnosticsCounters"},"edition":{"type":"string"},"go_version":{"type":"string"},"last_error_code":{"description":"LastErrorCode is the most recent MCPX_* error code.","type":"string"},"last_startup_outcome":{"description":"LastStartupOutcome is the previous startup's outcome word.","type":"string"},"machine_id":{"description":"MachineID is the hashed machine identifier (heartbeat value).","type":"string"},"os":{"type":"string"},"previous_shutdown":{"description":"PreviousShutdown is how the previous run ended (clean, crash, ...).","type":"string"},"routing_mode":{"type":"string"},"server_count":{"type":"integer"},"tool_count":{"type":"integer"},"uptime_minutes":{"description":"UptimeMinutes is the daemon's uptime. Omitted from short-lived CLI\nsubmissions, where the process uptime says nothing about the daemon.","type":"integer"},"version":{"type":"string"}},"type":"object"},"telemetry.FeedbackRequest":{"properties":{"category":{"description":"bug, feature, other","type":"string"},"context":{"$ref":"#/components/schemas/telemetry.FeedbackContext"},"email":{"type":"string"},"message":{"type":"string"}},"type":"object"},"telemetry.FeedbackResponse":{"properties":{"error":{"type":"string"},"issue_url":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}},"securitySchemes":{"ApiKeyAuth":{"description":"API key authentication via query parameter. Use ?apikey=your-key","in":"query","name":"apikey","type":"apiKey"}}}, "info": {"contact":{"name":"MCPProxy Support","url":"https://github.com/smart-mcp-proxy/mcpproxy-go"},"description":"{{escape .Description}}","license":{"name":"MIT","url":"https://opensource.org/licenses/MIT"},"title":"{{.Title}}","version":"{{.Version}}"}, "externalDocs": {"description":"","url":""}, "paths": {"/api/v1/access/explain":{"get":{"description":"For one subject (exactly one of client=\u003cid\u003e, token=\u003cname\u003e, profile=\u003cname\u003e or anonymous=true) and one upstream tool (server:tool), returns the ordered chain of gates a real call would meet - credential, profile, server_in_scope, tool_rule, tier_cap, token_permission, global_gate, server_state, tool_approval - the overall verdict (allowed, blocked, hidden), the first failing step and the fixes for it in preference order. The chain is the one every discovery and dispatch path walks, so ` + "`" + `allowed` + "`" + ` equals what a real call does. Built-in management tools are not explained (400). A client credential is explained with client=, never token=. Administrators only.","parameters":[{"description":"Upstream tool as server:tool","in":"query","name":"tool","required":true,"schema":{"type":"string"}},{"description":"Client id","in":"query","name":"client","schema":{"type":"string"}},{"description":"Regular agent token name","in":"query","name":"token","schema":{"type":"string"}},{"description":"Profile name","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Explain an anonymous (credential-less) caller","in":"query","name":"anonymous","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The explanation"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Not exactly one subject, a built-in tool, or token=client-\u003cid\u003e"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"client / token / profile not found"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Explain why a tool is or is not reachable","tags":["access"]}},"/api/v1/access/suggest":{"get":{"description":"Reads the profile refusals in the activity log over a look-back window and groups them by profile, tool and block reason. Each group is re-checked with the access explainer, so tools that are already reachable drop out, and carries the explainer's fixes. A deny-rule block is reported and never offered for widening; an unannotated tool is never given a tier. Nothing is applied. patch=true also returns the proposed profile document per profile (the body PUT /api/v1/profiles/{name} takes).","parameters":[{"description":"Look-back window: a duration such as 90m, 24h or 7d (default 24h; the audit-log retention is the only limit)","in":"query","name":"since","schema":{"type":"string"}},{"description":"Only refusals under this profile","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Only refusals of this token","in":"query","name":"token","schema":{"type":"string"}},{"description":"Also return the proposed profile document per profile","in":"query","name":"patch","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The suggestions"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid since"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Suggest profile changes from blocked calls","tags":["access"]}},"/api/v1/activity":{"get":{"description":"Returns paginated list of activity records with optional filtering","parameters":[{"description":"Filter by activity type(s), comma-separated for multiple (Spec 024)","in":"query","name":"type","schema":{"enum":["tool_call","policy_decision","quarantine_change","server_change","system_start","system_stop","internal_tool_call","config_change","preflight","prompt_get","profile_change","upstream_event"],"type":"string"}},{"description":"Filter by server name","in":"query","name":"server","schema":{"type":"string"}},{"description":"Filter by tool name","in":"query","name":"tool","schema":{"type":"string"}},{"description":"Filter by MCP transport session ID","in":"query","name":"session_id","schema":{"type":"string"}},{"description":"Filter by work session (one client, one project, across reconnects)","in":"query","name":"work_session_id","schema":{"type":"string"}},{"description":"Filter by status","in":"query","name":"status","schema":{"enum":["success","error","blocked","rejected"],"type":"string"}},{"description":"Filter by intent operation type (Spec 018)","in":"query","name":"intent_type","schema":{"enum":["read","write","destructive"],"type":"string"}},{"description":"Filter by HTTP request ID for log correlation (Spec 021)","in":"query","name":"request_id","schema":{"type":"string"}},{"description":"Filter by parent call id — returns the sub-calls one code_execution issued","in":"query","name":"parent_id","schema":{"type":"string"}},{"description":"Filter by call-error class (Spec 113-c)","in":"query","name":"error_class","schema":{"enum":["network","timeout","http","jsonrpc","tool_error","session_terminated","auth","proxy_policy","proxy_internal","cancelled"],"type":"string"}},{"description":"Filter by fault domain (Spec 113-c)","in":"query","name":"fault_domain","schema":{"enum":["upstream","proxy","client"],"type":"string"}},{"description":"Include successful call_tool_* internal tool calls (default: false, excluded to avoid duplicates)","in":"query","name":"include_call_tool","schema":{"type":"boolean"}},{"description":"Filter by sensitive data detection (true=has detections, false=no detections)","in":"query","name":"sensitive_data","schema":{"type":"boolean"}},{"description":"Filter by specific detection type (e.g., 'aws_access_key', 'credit_card')","in":"query","name":"detection_type","schema":{"type":"string"}},{"description":"Filter by severity level","in":"query","name":"severity","schema":{"enum":["critical","high","medium","low"],"type":"string"}},{"description":"Alias of token (Spec 028)","in":"query","name":"agent","schema":{"type":"string"}},{"description":"Filter by the token in effect for the call; - selects records with no token (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Filter by the profile in effect for the call; - selects records with no profile (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Filter by client id; - selects records with no client (Spec 108)","in":"query","name":"client","schema":{"type":"string"}},{"description":"Filter by the client's self-reported name (advisory; Spec 108)","in":"query","name":"client_name","schema":{"type":"string"}},{"description":"Filter by auth type (Spec 028)","in":"query","name":"auth_type","schema":{"enum":["admin","agent"],"type":"string"}},{"description":"Filter activities after this time (RFC3339)","in":"query","name":"start_time","schema":{"type":"string"}},{"description":"Filter activities before this time (RFC3339)","in":"query","name":"end_time","schema":{"type":"string"}},{"description":"Maximum records to return (1-100, default 50)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Pagination offset (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Omit arguments, response and metadata except a contextual whitelist (intent.reason, intent.operation_type, decision, reason, client_name, client_version) (default: false). For clients that render summary fields only; has_sensitive_data is still derived before metadata is dropped.","in":"query","name":"exclude_payloads","schema":{"type":"boolean"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"List activity records","tags":["Activity"]}},"/api/v1/activity/export":{"get":{"description":"Exports activity records in JSON Lines or CSV format for compliance","parameters":[{"description":"Export format: json (default) or csv","in":"query","name":"format","schema":{"type":"string"}},{"description":"Filter by activity type","in":"query","name":"type","schema":{"type":"string"}},{"description":"Filter by server name","in":"query","name":"server","schema":{"type":"string"}},{"description":"Filter by tool name","in":"query","name":"tool","schema":{"type":"string"}},{"description":"Filter by MCP transport session ID","in":"query","name":"session_id","schema":{"type":"string"}},{"description":"Filter by work session (one client, one project, across reconnects)","in":"query","name":"work_session_id","schema":{"type":"string"}},{"description":"Filter by status","in":"query","name":"status","schema":{"type":"string"}},{"description":"Filter by HTTP request ID for log correlation (Spec 021)","in":"query","name":"request_id","schema":{"type":"string"}},{"description":"Filter by parent call id — exports the sub-calls one code_execution issued","in":"query","name":"parent_id","schema":{"type":"string"}},{"description":"Filter by call-error class (Spec 113-c)","in":"query","name":"error_class","schema":{"enum":["network","timeout","http","jsonrpc","tool_error","session_terminated","auth","proxy_policy","proxy_internal","cancelled"],"type":"string"}},{"description":"Filter by fault domain (Spec 113-c)","in":"query","name":"fault_domain","schema":{"enum":["upstream","proxy","client"],"type":"string"}},{"description":"Alias of token (Spec 028)","in":"query","name":"agent","schema":{"type":"string"}},{"description":"Filter by the token in effect for the call; - selects records with no token (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Filter by the profile in effect for the call; - selects records with no profile (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Filter by client id; - selects records with no client (Spec 108)","in":"query","name":"client","schema":{"type":"string"}},{"description":"Filter by the client's self-reported name (advisory; Spec 108)","in":"query","name":"client_name","schema":{"type":"string"}},{"description":"Filter activities after this time (RFC3339)","in":"query","name":"start_time","schema":{"type":"string"}},{"description":"Filter activities before this time (RFC3339)","in":"query","name":"end_time","schema":{"type":"string"}},{"description":"Maximum records to export (1-50000, default 10000)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Pagination offset (default 0)","in":"query","name":"offset","schema":{"type":"integer"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"type":"string"}},"application/x-ndjson":{"schema":{"type":"string"}},"text/csv":{"schema":{"type":"string"}}},"description":"Streamed activity records"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Export activity records","tags":["Activity"]}},"/api/v1/activity/summary":{"get":{"description":"Returns aggregated activity statistics for a time period","parameters":[{"description":"Time period: 1h, 24h (default), 7d, 30d","in":"query","name":"period","schema":{"type":"string"}},{"description":"Group by: server, tool (optional)","in":"query","name":"group_by","schema":{"type":"string"}},{"description":"Alias of token (Spec 028)","in":"query","name":"agent","schema":{"type":"string"}},{"description":"Count only records made under this token; - selects records with no token (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Count only records made under this profile; - selects records with no profile (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Count only records made by this client id; - selects records with no client (Spec 108)","in":"query","name":"client","schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Get activity summary statistics","tags":["Activity"]}},"/api/v1/activity/usage":{"get":{"description":"Returns the actor-owned usage aggregate (per-tool rollup + timeline + tokens-saved headline) for the Web UI usage graphs (Spec 069). Served from an in-memory snapshot — never a per-request full-log scan. Per-tool metrics are lifetime-cumulative; ` + "`" + `window` + "`" + ` scopes the timeline and filters the tool list to tools active within the span.","parameters":[{"description":"Time window for timeline + tool-list membership","in":"query","name":"window","schema":{"enum":["24h","7d","all"],"type":"string"}},{"description":"Filter to one server","in":"query","name":"server","schema":{"type":"string"}},{"description":"Filter to one tool","in":"query","name":"tool","schema":{"type":"string"}},{"description":"Filter to tools with activity of this status","in":"query","name":"status","schema":{"enum":["success","error","blocked","rejected"],"type":"string"}},{"description":"Top-N tools by sort key; remainder folded into 'other' (default 20)","in":"query","name":"top","schema":{"type":"integer"}},{"description":"Ranking key for the per-tool list","in":"query","name":"sort","schema":{"enum":["calls","resp_bytes","error_rate","p95"],"type":"string"}},{"description":"Alias of token (Spec 028)","in":"query","name":"agent","schema":{"type":"string"}},{"description":"Restrict to calls made under this token; - selects records with no token. Computed from a window-bounded scan (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Restrict to calls made under this profile; - selects records with no profile. Computed from a window-bounded scan (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Restrict to calls made by this client id; - selects records with no client. Computed from a window-bounded scan (Spec 108)","in":"query","name":"client","schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Get usage statistics aggregate","tags":["Activity"]}},"/api/v1/activity/{id}":{"get":{"description":"Returns full details for a single activity record","parameters":[{"description":"Activity record ID (ULID)","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Not Found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Get activity record details","tags":["Activity"]}},"/api/v1/annotations/coverage":{"get":{"description":"Reports how many upstream tools have MCP annotations vs don't, broken down by server","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Annotation coverage report"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get annotation coverage report","tags":["annotations"]}},"/api/v1/attention":{"get":{"description":"One list, one count, every surface (Web UI, macOS tray/Home, CLI) reads from it. Filtered per caller: an administrator sees every item; a scoped caller (agent token, or a non-admin server-edition OAuth user session) sees only server items whose server it may enumerate (for a profile-pinned token: servers within its pin); every other subject type (client, setting) and the skill_review kind (Spec 125 held skills) are administrator-only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.attentionResponse"}}},"description":"The needs-attention list"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the needs-attention list","tags":["attention"]}},"/api/v1/catalog/search":{"get":{"description":"Fans out to every enabled catalog source (registry) in parallel, merges, de-duplicates and ranks the results (FR-060/061). An empty q returns official + popular sections instead of a flat list. Open to any authenticated caller — added is the only field filtered per caller scope (FR-007).","parameters":[{"description":"Free-text search","in":"query","name":"q","schema":{"type":"string"}},{"description":"Narrow to one catalog source id","in":"query","name":"source","schema":{"type":"string"}},{"description":"Not supported: catalog entries carry no tags; a non-empty value returns 400","in":"query","name":"tag","schema":{"type":"string"}},{"description":"Max results (default 20, max 50)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"tag filtering is not supported"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"configured servers could not be listed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Search the server catalog across every enabled source","tags":["catalog"]}},"/api/v1/clients":{"get":{"description":"Lists every client row (supported, other and custom) with its presence, its credential and its profile binding, plus response-level warnings. The list is content-read-free (Spec 075): credential_state comes from the token store, else the last on-demand observation (credential_checked_at), else unknown. It runs only the time-based half of the rotation reconciler. The profile and client filters match the CURRENT binding and are applied AFTER warnings are computed over the full set.","parameters":[{"description":"Rows whose active credential is bound to this profile; - = bound to All servers","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Exact client id","in":"query","name":"client","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Client rows, routing and warnings"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List clients","tags":["clients"]},"post":{"description":"Creates a per-client credential for a client that is NOT in the connect registry (a script, a CI job, an editor without a connect adapter). The secret (mcp_cli_...) is returned ONCE, with a paste-ready snippet that carries it in the X-API-Key header. The id follows the client-id rule (lower-case letters, digits, '-' or '_', at most 56 characters) and must not be a supported client's id. A named profile binds the credential locked unless mode says otherwise. Refused with 409 binding_bypassable_without_auth when the binding would be bypassable while require_mcp_auth is off (FR-008a), and 409 conflicting_token when a regular token holds client-\u003cid\u003e. Every value (id, display_name, profile, mode, expires_in, purpose) passes the shared secret-shaped input screen first: a credential, the API key or a detector-flagged secret answers 400 secret_in_argument naming the field, and nothing is minted. A malformed body answers a sanitized 400 that never echoes a caller key or value. Writes one profile_change record with change issue (Spec 115) and publishes credentials.changed. Personal edition only.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.CreateClientRequest"}}},"description":"id (required), optional display_name, profile, mode, expires_in and purpose","required":true},"responses":{"201":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The new client row, its credential (once) and a snippet"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"binding_bypassable_without_auth, or conflicting_token (ClientCredentialConflictResponse)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add a custom client","tags":["clients"]}},"/api/v1/clients/bulk-assign":{"post":{"description":"Moves every client credential bound to from_profile (\"\" = All servers) onto to_profile (\"\" = All servers). The guard and the credential precondition apply PER CLIENT: a refused client is reported in skipped[] with the code the single operation returns, the others move and each writes its own assign record and emits client.binding_changed. Personal edition only.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BulkAssignRequest"}}},"description":"from_profile and to_profile (both required; empty = All servers) and optional mode","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Moved client ids and the clients that were skipped"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Move every client of one profile to another","tags":["clients"]}},"/api/v1/clients/upgrade-admin-key-holders":{"post":{"description":"Without apply: classifies every supported client whose config still holds the instance admin API key (an on-demand read per client) and returns preview[] (display path, what would change, the masked credential mcp_cli_••••, the binding and a precondition_token per client), a combined precondition_token, and guard when the whole request would be refused by FR-008a; next_step is rotate_admin_api_key when nothing holds the key. Nothing is written or minted. With apply=true: recomputes the preview, refuses with 409 precondition_failed when a sent precondition_token no longer matches, runs the FR-008a guard over the WHOLE request (409 binding_bypassable_without_auth, nothing minted, no file written), then connects each client with force bound to its own token; one client's failure does not stop the others. Each mint writes its own assign record. The guard only applies when a named profile is given. Personal edition only.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.UpgradeAdminKeyHoldersRequest"}}},"description":"Optional profile and mode for every upgraded client; apply and precondition_token"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"UpgradePreview (no apply) or UpgradeResult (apply)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"precondition_failed, or binding_bypassable_without_auth"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Upgrade every client that holds the admin API key","tags":["clients"]}},"/api/v1/clients/{client}":{"delete":{"description":"Revokes the client's credential; it stops authenticating at once. With disconnect=true a SUPPORTED client's mcpproxy entry is removed from its config FIRST, but the credential is revoked either way: revocation never waits for a config write, so a failed write (for example a macOS App-Data denial) leaves the client cut off and is reported as disconnected:false with disconnect_error. A client with no credential record is 409 no_client_credential. disconnect=true on a custom client is ignored. Writes one forget record naming the revoked token. The FR-008a guard is not involved: revoking only removes a binding.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}},{"description":"Also remove the entry from the client's config (supported clients)","in":"query","name":"disconnect","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Revoked token name and what happened to the config entry"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"no_client_credential"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Forget a client (revoke its credential)","tags":["clients"]},"get":{"description":"Returns one client row with its sessions (newest 20, each with its latest effective profile). This is the only read that may open the client's config file: it runs the full rotation reconciler first, classifies the credential the config holds and records the observation. No scope filter is honoured on this route.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Client row"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"client not found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get one client","tags":["clients"]}},"/api/v1/clients/{client}/api-key":{"delete":{"description":"Revokes the client's mcp_cli_ credential alone: its browser logins and its binding stay. 404 no_client_credential when the client has no active API key. Writes a revoke record. Administrator only.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The key was revoked"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid client id"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"no_client_credential"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Revoke a client's API key only","tags":["clients"]}},"/api/v1/clients/{client}/binding":{"put":{"description":"Changes the profile binding (and optionally the locked/switchable mode) of a\nclient that holds an active client credential. One service operation shared by\nevery surface: it updates the credential in the token store, clears the stored\nset_profile selection of every live session of that credential, sends\nnotifications/tools/list_changed to each, emits client.binding_changed and writes\none profile_change activity record. It never touches the client's config file.\nA client without an active client credential (none, admin key, revoked or expired)\nis refused with 409 no_client_credential and nothing is minted or written. A\nreassignment that would leave the binding bypassable while require_mcp_auth is off\nis refused with 409 binding_bypassable_without_auth (FR-008a). Personal edition only.","parameters":[{"description":"Client id (lower-case letters, digits, '-' or '_', at most 56 characters)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.PutClientBindingRequest"}}},"description":"profile (required; empty = All servers) and optional mode (locked|switchable)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The client row after the change, with its warnings"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"no_client_credential, connect_in_progress (a connect of this client is mid-write), or binding_bypassable_without_auth with bindings and fixes"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Reassign a client's profile and/or mode","tags":["clients"]}},"/api/v1/clients/{client}/logins/{grant_id}":{"delete":{"description":"Revokes the login (reason admin): its access token stops authenticating on the next request, live sessions are told to re-list, and a revoke record names the administrator. Works while browser login is on and while it is off after use. An already revoked login answers changed:false; an unknown login (or one of another client) is 404. Administrator only.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}},{"description":"Login id","in":"path","name":"grant_id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Whether the login changed"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"login not found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Revoke one browser login of a client","tags":["clients"]}},"/api/v1/clients/{client}/rotate":{"post":{"description":"Replaces a client's secret without ever invalidating the old one mid-flight (FR-021a). A SUPPORTED client is rewritten through connect: staged rotation, binding kept, finalized when the config write succeeds, rolled back (the old secret keeps working) when it fails; a preview's precondition_token binds the call, a mismatch is the connect 409 precondition_failed. A CUSTOM client gets a new secret returned ONCE with a snippet; both secrets authenticate until POST /clients/{client}/rotate/finalize or 24 hours. A client with no active credential is 409 no_client_credential. The FR-008a guard is not involved: a rotation never changes a binding's reach. Writes one rotate record when it finalizes.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.RotateClientRequest"}}},"description":"Optional precondition_token of a connect preview"},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The client row and the rotation state"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required (or macOS App-Data block)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectConflictResponse"}}},"description":"no_client_credential, precondition_failed, connect_in_progress (another connect of this client is mid-write), or credential_superseded (the written credential was replaced or revoked before it could be finalized; reconnect)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Rotate a client's credential","tags":["clients"]}},"/api/v1/clients/{client}/rotate/finalize":{"post":{"description":"Promotes a client's pending secret: the old secret stops authenticating. Idempotent: with no rotation in progress it is a no-op success. A client with no client credential is 409 no_client_credential. Writes one rotate record when it promotes.","parameters":[{"description":"Client id","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The client row; rotation.state is finalized"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"no_client_credential, or connect_in_progress (a connect of this client is mid-write)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Finalize a staged rotation","tags":["clients"]}},"/api/v1/code/scripts":{"get":{"description":"List the stored scripts available to the code_execution tool. Scripts are ` + "`" + `\u003cname\u003e.js` + "`" + ` / ` + "`" + `\u003cname\u003e.ts` + "`" + ` files in the ` + "`" + `scripts/` + "`" + ` directory next to the active configuration file. Entries are advisory: ` + "`" + `ok` + "`" + ` scripts are invocable, ` + "`" + `ambiguous` + "`" + ` names have both extensions, and ` + "`" + `invalid` + "`" + ` ones report why (empty, oversized, unreadable, non-regular). Read-only — there is no write surface for stored scripts. Administrator-only (Spec 105 FR-012): an agent token, whatever its server scope, is refused with 403 — the listing is the enumeration the missing-script error withholds from a scoped caller.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Stored scripts and the directory they were read from"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot list stored scripts"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List stored code-execution scripts","tags":["code"]}},"/api/v1/config":{"get":{"description":"Retrieves the current MCPProxy configuration including all server definitions, global settings, and runtime parameters","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetConfigResponse"}}},"description":"Configuration retrieved successfully"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read the configuration document"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get current configuration","tags":["config"]},"patch":{"description":"Deep-merges only the fields present in the request body onto the live in-memory configuration and routes the result through the existing apply pipeline (validation, change detection, disk persistence, hot-reload). Fields the client omits — including masked secrets such as ` + "`" + `api_key` + "`" + ` and secret request headers — are preserved verbatim. Nested objects are merged recursively; arrays and scalars replace wholesale.","requestBody":{"content":{"application/json":{"schema":{"type":"object"}}},"description":"Partial configuration with only the fields to change","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ConfigApplyResult"}}},"description":"Configuration patch applied (inspect validation_errors for rejected values)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload or empty patch"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate configuration)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"binding_bypassable_without_auth: the patch would let a client bound to a named profile escape it while require_mcp_auth is off (FR-008a); nothing was written"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"telemetry.enabled is locked while an environment variable (DO_NOT_TRACK, CI, MCPPROXY_TELEMETRY=false) disables telemetry; nothing was written (FR-044a)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to read or apply configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Partially update configuration","tags":["config"]}},"/api/v1/config/apply":{"post":{"description":"Applies a new MCPProxy configuration. Validates and persists the configuration to disk. Some changes apply immediately, while others may require a restart. Returns detailed information about applied changes and restart requirements.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.Config"}}},"description":"Configuration to apply","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ConfigApplyResult"}}},"description":"Configuration applied successfully with change details"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate configuration)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"binding_bypassable_without_auth: the write would let a client bound to a named profile escape it while require_mcp_auth is off (FR-008a); nothing was written"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"telemetry.enabled is locked while an environment variable (DO_NOT_TRACK, CI, MCPPROXY_TELEMETRY=false) disables telemetry; nothing was written (FR-044a)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to apply configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Apply configuration","tags":["config"]}},"/api/v1/config/docker-isolation":{"patch":{"description":"Convenience endpoint to flip ` + "`" + `docker_isolation.enabled` + "`" + ` without resending the full config. Persists to disk via the existing config writer — the file watcher then hot-reloads the change. Returns the new state and whether a restart is required for existing connections to pick it up.","requestBody":{"content":{"application/json":{"schema":{"properties":{"enabled":{"type":"boolean"}},"type":"object"}}},"description":"New isolation state","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ConfigApplyResult"}}},"description":"Isolation toggle applied"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate configuration)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BindingGuardResponse"}}},"description":"binding_bypassable_without_auth (FR-008a); nothing was written"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to apply configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Toggle global Docker isolation","tags":["config"]}},"/api/v1/config/validate":{"post":{"description":"Validates a provided MCPProxy configuration without applying it. Checks for syntax errors, invalid server definitions, conflicting settings, and other configuration issues.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.Config"}}},"description":"Configuration to validate","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ValidateConfigResponse"}}},"description":"Configuration validation result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Validation failed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Validate configuration","tags":["config"]}},"/api/v1/connect":{"get":{"description":"Returns the connection status for all known MCP client applications.\nEach entry indicates whether the client config file exists and whether\nMCPProxy is currently registered in it. This stat-only listing never reads\na client config (Spec 075), so a client whose config exists reports\ncredential_state \"unknown\"; GET /connect/{client} resolves it.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"List of ClientStatus objects"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List client connection status","tags":["connect"]}},"/api/v1/connect/{client}":{"delete":{"description":"Remove the MCPProxy entry from the specified client's configuration file.\nCreates a backup of the existing config before modifying.\nAlso revokes the client's credential (it stops authenticating at once); the result names it in credential_revoked, or reports credential_revoke_error when the revoke failed after the entry was removed. Undoing a disconnect does not restore the credential: a later connect mints a new one.","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectRequest"}}},"description":"Optional parameters (server_name)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectResult"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Permission denied (macOS App-Data block)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client or entry not found"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Disconnect MCPProxy from a client","tags":["connect"]},"get":{"description":"Resolves one client's status by reading its config file on demand.\nThis is the only Connect endpoint that opens a client config file, so\non macOS it is the sole place an App-Data privacy prompt may legitimately\nappear (scoped to this user action). Resolves access_state to\naccessible|absent|denied|malformed and populates remediation when denied.\nFor a connected client it also resolves credential_state (Spec 108 FR-025):\nclient (an active per-client credential), admin_key (the instance admin API\nkey), none, revoked (a rotated-away or revoked credential) or expired. The\ncredential value is classified and never echoed.","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ClientStatus"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get a single client's connection status (on-demand)","tags":["connect"]},"post":{"description":"Register MCPProxy as an MCP server in the specified client's configuration file.\nCreates a backup of the existing config before modifying.\nOptionally accepts precondition_token from a preview (Spec 091): when supplied,\nthe core rechecks the raw pre-write state and the entry it would write, and\nrefuses a drifted write with 409 before taking any backup. The 409 body's\naction discriminates the two conflict kinds: \"precondition_failed\" (stale\npreview — re-preview, do not retry) vs \"already_exists\" (entry present — pass\nforce=true). force=true never rescues a stale token.\n\nSpec 108 FR-024: the entry carries a per-client mcp_cli_ credential bound to the\nrequested profile (default: All servers, switchable; a reconnect keeps the client's\nexisting binding unless a profile is given), never the instance admin API key.\nReconnecting over an active credential is a staged rotation: the old secret keeps\nworking until the config write succeeds. keyless=true writes no credential and is\nonly possible while require_mcp_auth is off (400 otherwise, and with a profile).\nA write that would let the client escape its profile by omitting its credential\nwhile require_mcp_auth is off is refused with 409 binding_bypassable_without_auth\n(nothing minted or written); a token named client-\u003cid\u003e held by a regular agent\ntoken is refused with 409 conflicting_token.","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectRequest"}}},"description":"Optional connection parameters (server_name, force, precondition_token, profile, mode, keyless, auth)"},"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); an auth=oauth write is refused with 400 while mcp_oauth_enabled is off, for a client that does not support browser login, in the server edition, or together with keyless, profile or mode"},"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"}},{"description":"key (default) or oauth: preview the browser login address (Spec 132; refused while mcp_oauth_enabled is off or for a client without support)","in":"query","name":"auth","schema":{"enum":["key","oauth"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectPreview"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid intent (field names the input; keyless with auth on or with a profile)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required or access denied by macOS App Data"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Preview the change a connect would make (no write)","tags":["connect"]}},"/api/v1/connect/{client}/undo":{"post":{"description":"Reverts the connect that produced the named backup (Spec 078 US3):\nrestores the client config byte-for-byte from that backup, or — when\nbackup_name is empty because the connect created the file — deletes the\ncreated file. backup_name is the bare filename of the backup the connect\nreturned (never a path); undo resolves the full path server-side inside\nthe client's own config directory, so a client value cannot escape it.\nRefuses with 409 when the config changed since the connect (undo never\nclobbers later edits; use DELETE /connect/{client} for a surgical entry\nremoval instead). Takes its own safety backup first; its path is returned\nas backup_path in the result. Undo is \"as if the connect never happened\": a\nclient credential the connect minted or rotated is revoked unless the restored\nconfig still holds it, and the result names it in credential_revoked.","parameters":[{"description":"Client ID (claude-code, claude-desktop, copilot, cursor, windsurf, vscode, codex, gemini, opencode, zcode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.UndoConnectRequest"}}},"description":"Undo parameters (server_name, backup_name = the bare filename of the backup the preceding connect returned)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectResult (action restored|deleted)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (e.g. backup_name is a path, or not a backup of this client's config)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Permission denied (macOS App-Data block)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client or backup no longer exists"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Config changed since connect; undo refused"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Undo a connect, restoring the pre-connect config","tags":["connect"]}},"/api/v1/diagnostics":{"get":{"description":"Get comprehensive health diagnostics including upstream errors, OAuth requirements, missing secrets, and Docker status","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.Diagnostics"}}},"description":"Health diagnostics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get health diagnostics","tags":["diagnostics"]}},"/api/v1/docker/status":{"get":{"description":"Retrieve current Docker availability and recovery status","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Docker status information"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get Docker status","tags":["docker"]}},"/api/v1/doctor":{"get":{"description":"Get comprehensive health diagnostics including upstream errors, OAuth requirements, missing secrets, and Docker status","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.Diagnostics"}}},"description":"Health diagnostics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get health diagnostics","tags":["diagnostics"]}},"/api/v1/feedback":{"post":{"description":"Submit a bug report, feature request, or general feedback","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/telemetry.FeedbackRequest"}}},"description":"Feedback request","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/telemetry.FeedbackResponse"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"additionalProperties":{"type":"string"},"type":"object"}}},"description":"Bad Request"},"429":{"content":{"application/json":{"schema":{"additionalProperties":{"type":"string"},"type":"object"}}},"description":"Too Many Requests"},"500":{"content":{"application/json":{"schema":{"additionalProperties":{"type":"string"},"type":"object"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyAuth":[]}],"summary":"Submit feedback","tags":["feedback"]}},"/api/v1/index/search":{"get":{"description":"Search across all upstream MCP server tools using BM25 keyword search","parameters":[{"description":"Search query","in":"query","name":"q","required":true,"schema":{"type":"string"}},{"description":"Maximum number of results","in":"query","name":"limit","schema":{"default":10,"maximum":100,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SearchToolsResponse"}}},"description":"Search results"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing query parameter)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Search for tools","tags":["tools"]}},"/api/v1/info":{"get":{"description":"Get essential server metadata including version, web UI URL, endpoint addresses, and update availability\nweb_ui_url carries the ?apikey= credential ONLY for an authenticated admin; a scoped agent token receives the bare URL\nThis endpoint is designed for tray-core communication and version checking\nUse refresh=true query parameter to force an immediate update check against GitHub\nThe launched_by field reports durable launch provenance (\"tray\", \"installer\", or \"\" for user-launched/unknown)","parameters":[{"description":"Force immediate update check against GitHub","in":"query","name":"refresh","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Server information with optional update info"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server information","tags":["status"]}},"/api/v1/oauth/authorizations":{"get":{"description":"Pending browser-login requests, newest first: id, a sanitised client label and the times. Used by the tray and Home. 404 feature_disabled while browser login is off. Administrator only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Pending requests"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"feature_disabled"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List pending sign-in requests","tags":["clients"]}},"/api/v1/oauth/authorizations/{id}":{"get":{"description":"Everything the consent view needs: the reported (unverified) name, the redirect URI, the resource, how the address fixes the client, the profiles, whether a profile must be chosen, the previous login of the same registration and, for a fixed client that has a binding, the guard verdict. One uniform 404 for an unknown, expired, decided or cancelled id. Administrator only.","parameters":[{"description":"Request id","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"The request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"request_not_found or feature_disabled"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Read one sign-in request","tags":["clients"]}},"/api/v1/oauth/authorizations/{id}/approve":{"post":{"description":"Records the decision and issues the code; the login itself is stored when the client exchanges the code. 409 already_decided, 409 binding_changed (the binding differs from binding_revision), 409 binding_bypassable_without_auth (with the guard's fixes), 422 profile_required, client_fixed, identity_exists, reserved_identity, 404 profile_not_found. Writes an approve record naming the administrator. Administrator only.","parameters":[{"description":"Request id","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.OAuthApprovalBody"}}},"description":"client, profile, mode, binding_revision, replace_grant","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Where the page navigates"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"request_not_found, profile_not_found or feature_disabled"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"already_decided, binding_changed or binding_bypassable_without_auth"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"profile_required, client_fixed, identity_exists, reserved_identity"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Approve a sign-in request","tags":["clients"]}},"/api/v1/oauth/authorizations/{id}/deny":{"post":{"description":"The redirect carries error=access_denied. 409 already_decided. Writes a deny record naming the administrator. Administrator only.","parameters":[{"description":"Request id","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Where the page navigates"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"request_not_found or feature_disabled"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"already_decided"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Deny a sign-in request","tags":["clients"]}},"/api/v1/oauth/authorizations/{id}/preview":{"post":{"description":"Read-only: for a proposed client (existing or new), profile and mode, returns whether the choice is complete, the access sentence and the binding guard's verdict with its fixes. Writes nothing. The same 422 codes as approve for an invalid choice. Administrator only.","parameters":[{"description":"Request id","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.OAuthApprovalBody"}}},"description":"client, profile, mode","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"The preview"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"request_not_found, profile_not_found or feature_disabled"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"client_fixed, identity_exists, reserved_identity"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Preview a sign-in decision","tags":["clients"]}},"/api/v1/onboarding/mark":{"post":{"description":"Updates wizard engagement and per-step status. Once engaged is\ntrue, the wizard does not auto-show again, even if state regresses.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.OnboardingMarkRequest"}}},"description":"Mark request","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Updated OnboardingStateResponse"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read onboarding state"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Mark onboarding wizard state (Spec 046)","tags":["onboarding"]}},"/api/v1/onboarding/state":{"get":{"description":"Returns the wizard engagement record alongside live predicates\n(whether any client is connected, whether any server is configured),\nplus a derived ShouldShowWizard flag the frontend can rely on.","responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OnboardingStateResponse"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read onboarding state"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get onboarding wizard state and predicates (Spec 046)","tags":["onboarding"]}},"/api/v1/preflight":{"post":{"description":"Deterministic, side-effect-free availability check for a caller-supplied list of tool IDs (Spec 098). Performs zero upstream calls and mutates no runtime state. HTTP status reports whether the CHECK executed: a fully blocked set is still 200, with the availability verdict in the body. Every executed preflight writes an activity record before the response is returned.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.PreflightRequest"}}},"description":"Tool IDs (1-100 before dedup), optional profile, annotation policy filters and wait budget","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Preflight verdict and per-tool results"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Validation error (malformed, oversized, doubled or unknown-field body; empty or oversized tool list; conflicting duplicate pins; unknown profile; wait_ms out of range)"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Missing or invalid credentials"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Runtime unavailable, evaluator infrastructure read failure, or the activity record could not be persisted"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Preflight required tools","tags":["tools"]}},"/api/v1/profiles":{"get":{"description":"Lists every profile as a ProfileView: the config fields as stored, the derived effective values, visible tool counts by tier, 24 h calls and blocked calls, and (administrators only) used_by and the anonymous_profile. A caller that is not an administrator sees only the profiles its entitlement reaches, with servers, rules and switchable_to narrowed to what it may see; an unreachable profile is omitted, never shown empty.","responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Profile list"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Configuration unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List configured profiles","tags":["profiles"]},"post":{"description":"Adds a profile. The body is a ProfileConfig. A name that already exists is 409 profile_exists; ` + "`" + `active` + "`" + ` and ` + "`" + `try` + "`" + ` are reserved by the REST API; a fatal validation rule is 400 with the offending field and the unchanged FR-007 text. A write that would let a client bound to a named profile escape it while require_mcp_auth is off is refused 409 binding_bypassable_without_auth (FR-008a) and nothing is written. Writes one profile_change record.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.ProfileConfig"}}},"description":"The profile","required":true},"responses":{"201":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Created, with the validator's warnings"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ProfileConflictResponse"}}},"description":"profile_exists, or binding_bypassable_without_auth (BindingGuardResponse)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Create a profile","tags":["profiles"]}},"/api/v1/profiles/active":{"get":{"description":"Deprecated (Spec 108 FR-039; sends a Deprecation header, successor GET /api/v1/profiles). Get the server-level default active profile used by UI surfaces (Web UI / tray). Empty string means \"all servers\". Note: within a live MCP session, the set_profile tool selection takes precedence over this default.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Active profile"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the default active profile","tags":["profiles"]},"put":{"description":"Deprecated (Spec 108 FR-039; sends a Deprecation header, successor GET /api/v1/profiles). Set the server-level default active profile for UI surfaces. The slug must match a configured profile; pass an empty string to clear. This does not affect live MCP sessions, which use the set_profile tool.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.SetActiveProfileRequest"}}},"description":"Profile slug to activate (empty clears)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Active profile updated"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request body"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot change the active profile)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown profile"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Set the default active profile","tags":["profiles"]}},"/api/v1/profiles/try":{"post":{"description":"Evaluates a DRAFT profile against a query exactly as retrieve_tools would (policy is applied before the limit) and returns the hits plus what the draft hides (hidden_by_profile and up to 100 {server, tool, reason}). The draft is validated as if it replaced the same-named profile, or was appended under a placeholder name when it has none. Nothing is persisted, no record is written, no event is published and the FR-008a guard does not run. Administrators only.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.TryProfileRequest"}}},"description":"draft profile, query and optional limit (default 10, max 50)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Search result under the draft"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid draft; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Try a draft profile","tags":["profiles"]}},"/api/v1/profiles/{name}":{"delete":{"description":"Deletes a profile. 409 profile_in_use (with used_by) while clients or tokens point at it, unless reassign_to names another existing profile (every pin moves there) or force is set (pins are left dangling, which the resolver treats as deny-all). 409 profile_is_anonymous_profile whenever it is the anonymous_profile and reassign_to is absent, even with force. Both paths remove the name from every switchable_to. Guarded by FR-008a. Writes one ` + "`" + `delete` + "`" + ` record.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}},{"description":"Another existing profile that takes over the pins","in":"query","name":"reassign_to","schema":{"type":"string"}},{"description":"Delete although in use, leaving pins dangling","in":"query","name":"force","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Deleted"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"reassign_to does not name another existing profile"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ProfileConflictResponse"}}},"description":"profile_in_use, profile_is_anonymous_profile, or binding_bypassable_without_auth (BindingGuardResponse)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Delete a profile","tags":["profiles"]},"get":{"description":"Returns the ProfileView of the named profile. A caller that is not an administrator gets the same 404 for an unreachable profile as for an unknown one.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"The profile"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get one profile","tags":["profiles"]},"put":{"description":"Replaces the named profile with the body (a ProfileConfig whose name, when sent non-empty, must equal the path; 409 name_mismatch otherwise - a rename has its own route; an omitted or empty name takes the path's). A write whose only change is tools.classify is recorded as ` + "`" + `classify` + "`" + `. Guarded by FR-008a like a create.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.ProfileConfig"}}},"description":"The profile","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Updated, with the validator's warnings"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ProfileConflictResponse"}}},"description":"name_mismatch, or binding_bypassable_without_auth (BindingGuardResponse)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Replace a profile","tags":["profiles"]}},"/api/v1/profiles/{name}/effective-tools":{"get":{"description":"One row per catalog tool with the verdict of the access chain (the same rendering GET /tools?profile= uses): server, tool, intrinsic_tier, profile_tier, access{visible, callable, reason} and classification_stale. With client=\u003cid\u003e the client's credential is evaluated UNDER this profile (\"what would Cursor get here\"). An administrator gets every row plus counts.callable, counts.by_reason and stale_classifications; every other caller gets only visible rows and counts{visible, hidden}, and client= and reason= are refused 403. An unreachable profile answers exactly like an unknown one.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}},{"description":"Evaluate this client's credential under the profile (administrators only)","in":"query","name":"client","schema":{"type":"string"}},{"description":"Keep only this server's rows","in":"query","name":"server","schema":{"type":"string"}},{"description":"Keep only rows with this access reason (administrators only)","in":"query","name":"reason","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Effective tools"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"operation requires admin access"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found / client not found"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Effective tools of a profile","tags":["profiles"]}},"/api/v1/profiles/{name}/rename":{"post":{"description":"Renames a profile and moves every reference to it - token pins, client bindings, other profiles' switchable_to and the anonymous_profile - in one write (D19). Tokens move first, so a failure part-way never widens a scope. Guarded by FR-008a. Writes one ` + "`" + `rename` + "`" + ` record.","parameters":[{"description":"Profile name","in":"path","name":"name","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.RenameProfileRequest"}}},"description":"new_name","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Renamed; moved lists the clients and tokens that followed"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ClientBindingErrorResponse"}}},"description":"Invalid input; field names the offending input"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"profile not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ProfileConflictResponse"}}},"description":"profile_exists, or binding_bypassable_without_auth (BindingGuardResponse)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Rename a profile","tags":["profiles"]}},"/api/v1/registries":{"get":{"description":"Retrieves list of all MCP server registries that can be browsed for discovering and installing new upstream servers. Includes registry metadata, server counts, and API endpoints.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetRegistriesResponse"}}},"description":"Registries retrieved successfully"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to list registries"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List available MCP server registries","tags":["registries"]},"post":{"description":"Adds a generic modelcontextprotocol/registry v0.1 https endpoint as a custom registry (MCP-866). The source is always tagged custom/unverified, so every server discovered through it lands quarantined and can never skip quarantine.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.AddRegistrySourceRequest"}}},"description":"Registry source (https url + optional protocol/id/name)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Registry source added"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"invalid_registry_url"},"403":{"content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/contracts.ErrorResponse"},{"$ref":"#/components/schemas/contracts.ErrorResponse"}]}}},"description":"Forbidden (agent tokens cannot mutate registries)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_shadows_builtin | duplicate_registry"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add a user-supplied registry source","tags":["registries"]}},"/api/v1/registries/{id}":{"delete":{"description":"Removes a custom/unverified registry previously added via add-source (MCP-1057). Built-in registries are refused with registry_shadows_builtin; an unknown id yields registry_not_found. The change is persisted copy-on-write.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Registry source removed"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID is required"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registries_locked"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_not_found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_shadows_builtin"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Remove a user-added custom registry source","tags":["registries"]},"put":{"description":"Updates a custom registry previously added via add-source (MCP-1072): name, url, servers-url. Empty fields are left unchanged. Built-in registries are refused with registry_shadows_builtin; an unknown id yields registry_not_found; a non-https url yields invalid_registry_url. The change is persisted copy-on-write.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.EditRegistrySourceRequest"}}},"description":"Fields to update (name/url/servers_url; empty = unchanged)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Registry source updated"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID is required | invalid_registry_url"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registries_locked"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_not_found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_shadows_builtin"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Edit a user-added custom registry source","tags":["registries"]}},"/api/v1/registries/{id}/refresh":{"post":{"description":"Invalidates the cached server lists for a registry so the next search re-fetches fresh data from the source (spec 070 FR-007). Returns how many cache entries were dropped.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.RefreshRegistryResponse"}}},"description":"Registry cache refreshed"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID is required"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to refresh registry cache"}},"summary":"Refresh a registry's cached server list","tags":["registries"]}},"/api/v1/registries/{id}/servers":{"get":{"description":"Searches for MCP servers within a specific registry by keyword or tag. Returns server metadata including installation commands, source code URLs, and npm package information for easy discovery and installation.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Search query keyword","in":"query","name":"q","schema":{"type":"string"}},{"description":"Filter by tag","in":"query","name":"tag","schema":{"type":"string"}},{"description":"Maximum number of results (default 10)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SearchRegistryServersResponse"}}},"description":"Servers retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to search servers"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Search MCP servers in a registry","tags":["registries"]}},"/api/v1/registries/{id}/servers/{serverId}/add":{"post":{"description":"Resolves a registry server reference server-side, re-derives a validated config, and persists it quarantined (spec 070 keystone). The client never sends a config blob — command/args/url and the quarantine flag are derived from the registry entry, not the request.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Server ID within the registry","in":"path","name":"serverId","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.AddFromRegistryRequest"}}},"description":"Optional overrides (name, env, enabled)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server added (quarantined)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"no_install_info | missing_required_input | duplicate_name"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot add servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_not_found | server_not_found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add an upstream server from a registry reference","tags":["registries"]}},"/api/v1/review":{"get":{"description":"Returns one row per quarantined server, trusted server with pending or changed tools, or (Spec 125) server with held skills (kind skill_review; skills_pending / skills_changed counts). Scoped callers see only servers they may enumerate (for a profile-pinned token: servers within its pin), with count recomputed; held-skill counts and skill_review rows are administrator-only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Review queue"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to load review queue"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the server review queue","tags":["review"]}},"/api/v1/routing":{"get":{"description":"Get the current routing mode and available MCP endpoints.\nrouting_mode is what /mcp is actually serving; pending_routing_mode carries a\nrestart-pending value persisted on disk (empty when there is none).\ntool_response_mode and direct_tool_response_mode report the two serialization axes, resolved.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Routing mode information"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get routing mode information","tags":["status"]}},"/api/v1/secrets":{"post":{"description":"Stores a secret value in the operating system's secure keyring. The secret can then be referenced in configuration using ${keyring:secret-name} syntax. Automatically notifies runtime to restart affected servers.","requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{},"type":"object"}}},"description":"Secret stored successfully with reference syntax"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload, missing name/value, or unsupported type"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Secret resolver not available or failed to store secret"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Store a secret in OS keyring","tags":["secrets"]}},"/api/v1/secrets/{name}":{"delete":{"description":"Deletes a secret from the operating system's secure keyring. Automatically notifies runtime to restart affected servers. Only keyring type is supported for security.","parameters":[{"description":"Name of the secret to delete","in":"path","name":"name","required":true,"schema":{"type":"string"}},{"description":"Secret type (only 'keyring' supported, defaults to 'keyring')","in":"query","name":"type","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{},"type":"object"}}},"description":"Secret deleted successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Missing secret name or unsupported type"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Secret resolver not available or failed to delete secret"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Delete a secret from OS keyring","tags":["secrets"]}},"/api/v1/security/bundle":{"get":{"description":"Reports the offline TPA signature corpus this install is serving: full SHA-256 digest, sequence, authority, trust epoch, signature verification, staleness (with the stale flag and its threshold), degraded coverage with its reason, rollback pin, and the last refused candidate. Also carries the refresh status (last checked and activated times, last cycle outcome, next check, consecutive failures; the fetch host only, never the URL) and the post-activation re-protection sweep status. Admin only.","responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Bundle status"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the TPA signature bundle status","tags":["security"]}},"/api/v1/security/bundle/history":{"get":{"description":"Append-only list of bundle activations, oldest first, each with its full SHA-256 digest. It is the trustworthy source of the digest to name in a rollback. Admin only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Activation history (data is an array of TPABundleActivation)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"History could not be read"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the TPA signature bundle activation history","tags":["security"]}},"/api/v1/security/bundle/refresh":{"post":{"description":"Runs one refresh cycle immediately: the local file leg (always network-free) followed by the optional fetch leg when security.tpa_fetch_enabled is on and a trusted signer and URL are configured. A cycle already in flight is joined, so one download and at most one activation happen per distinct candidate. The response is the resulting bundle status; the cycle outcome is in its refresh block (activated, unchanged, not_modified, rejected, fetch_unavailable, channel_invalid, superseded, disabled). Network failures are reported as fetch_unavailable and never as a rejection; last-known-good keeps serving. Unlike reload, refresh may make an outbound request. Admin API key only.","responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Updated bundle status; the refresh block holds the cycle outcome"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Refresh the TPA signature bundle now","tags":["security"]}},"/api/v1/security/bundle/reload":{"post":{"description":"Re-runs the single-flight bundle pipeline against the configured source and current policy. A refused candidate leaves last-known-good serving and is reported as last_rejection in the returned status. Admin API key only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Updated bundle status"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Reload the TPA signature bundle","tags":["security"]}},"/api/v1/security/bundle/rollback":{"post":{"description":"The one operator override of the downgrade watermark. Exactly one of embedded or path must be given, and digest must be the FULL 64-character lowercase hex SHA-256 of the target (the 12-character fingerprint is refused). On success the target serves and is pinned. A refusal (for example rollback_target_mismatch) returns 409 with the rejection reason and last-known-good keeps serving. Admin API key only; agent tokens are refused.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.bundleRollbackRequest"}}},"description":"Rollback target","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Updated bundle status"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Usage error: both or neither of embedded/path, or digest is not 64 lowercase hex"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.BundleRollbackRefusedResponse"}}},"description":"Rollback refused; the response carries the rejection reason"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal error"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Roll the TPA signature bundle back to a named artifact","tags":["security"]}},"/api/v1/security/bundle/unpin":{"post":{"description":"Clears the rollback pin and re-validates the serving bundle under the normal downgrade watermark, so a rolled-back target below the watermark no longer serves. A quiet no-op when nothing is pinned. Admin API key only.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Updated bundle status"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Admin credentials required"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"The unpin could not be recorded"},"501":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Security scanner not configured"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Clear the TPA signature bundle rollback pin","tags":["security"]}},"/api/v1/servers":{"get":{"description":"Get a list of all configured upstream MCP servers with their connection status and statistics","parameters":[{"description":"Restrict to the profile's effective servers; tool_count becomes the number of that server's tools visible under the profile (Spec 108 FR-032)","in":"query","name":"profile","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServersResponse"}}},"description":"Server list with statistics"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unsupported scope filter (client/token), or '-' on a server filter"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown or unreachable profile"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List all upstream MCP servers","tags":["servers"]},"post":{"description":"Add a new MCP upstream server to the configuration. New servers are quarantined by default for security. Isolation: ` + "`" + `isolation.enabled` + "`" + ` is READ-ONLY (it reports the effective state on reads) and is rejected with 400; set the per-server override via ` + "`" + `isolation.enabled_override` + "`" + ` (true | false | null to clear, omit to leave unchanged). An unrecognized ` + "`" + `isolation.mode_override` + "`" + ` is rejected with 400.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.AddServerRequest"}}},"description":"Server configuration","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server added successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid configuration"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Conflict - server with this name already exists"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add a new upstream server","tags":["servers"]}},"/api/v1/servers/disable_all":{"post":{"description":"Disable all configured upstream MCP servers with partial failure handling","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/management.BulkOperationResult"}}},"description":"Bulk disable results with success/failure counts"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Disable all servers","tags":["servers"]}},"/api/v1/servers/enable_all":{"post":{"description":"Enable all configured upstream MCP servers with partial failure handling","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/management.BulkOperationResult"}}},"description":"Bulk enable results with success/failure counts"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable all servers","tags":["servers"]}},"/api/v1/servers/import":{"post":{"description":"Import MCP server configurations from a Claude Desktop, Claude Code, Cursor IDE, Codex CLI, or Gemini CLI configuration file","parameters":[{"description":"If true, return preview without importing","in":"query","name":"preview","schema":{"type":"boolean"}},{"description":"Force format (claude-desktop, claude-code, cursor, codex, gemini)","in":"query","name":"format","schema":{"type":"string"}},{"description":"Comma-separated list of server names to import","in":"query","name":"server_names","schema":{"type":"string"}}],"requestBody":{"content":{"multipart/form-data":{"schema":{"type":"file"}}},"description":"Configuration file to import","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportResponse"}}},"description":"Import result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid file or format"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Import servers from uploaded configuration file","tags":["servers"]}},"/api/v1/servers/import/json":{"post":{"description":"Import MCP server configurations from raw JSON or TOML content (useful for pasting configurations)","parameters":[{"description":"If true, return preview without importing","in":"query","name":"preview","schema":{"type":"boolean"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportRequest"}}},"description":"Import request with content","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportResponse"}}},"description":"Import result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid content or format"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Import servers from JSON/TOML content","tags":["servers"]}},"/api/v1/servers/import/path":{"post":{"description":"Import MCP server configurations by reading a file from the server's filesystem. A preview (preview=true) of a file with no MCP servers (empty, {}, or no/empty server map) answers 200 with an empty imported list; an apply of such a file and a malformed file still answer 400.","parameters":[{"description":"If true, return preview without importing","in":"query","name":"preview","schema":{"type":"boolean"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportFromPathRequest"}}},"description":"Import request with file path","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportResponse"}}},"description":"Import result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid path or format"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"File not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Import servers from a file path","tags":["servers"]}},"/api/v1/servers/import/paths":{"get":{"description":"Returns well-known configuration file paths for supported formats with existence check","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.CanonicalConfigPathsResponse"}}},"description":"Canonical config paths"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get canonical config file paths","tags":["servers"]}},"/api/v1/servers/reconnect":{"post":{"description":"Force reconnection to all upstream MCP servers","parameters":[{"description":"Reason for reconnection","in":"query","name":"reason","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"All servers reconnected successfully"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Reconnect all servers","tags":["servers"]}},"/api/v1/servers/restart_all":{"post":{"description":"Restart all configured upstream MCP servers sequentially with partial failure handling","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/management.BulkOperationResult"}}},"description":"Bulk restart results with success/failure counts"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Restart all servers","tags":["servers"]}},"/api/v1/servers/{id}":{"delete":{"description":"Remove an MCP upstream server from the configuration. This stops the server if running and removes it from config.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server removed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Remove an upstream server","tags":["servers"]},"patch":{"description":"Update specific fields of an existing upstream MCP server configuration. Isolation: ` + "`" + `isolation.enabled` + "`" + ` is READ-ONLY (it reports the effective state on reads) and is rejected with 400; set the per-server override via ` + "`" + `isolation.enabled_override` + "`" + ` (true | false | null to clear, omit to leave unchanged). An unrecognized ` + "`" + `isolation.mode_override` + "`" + ` is rejected with 400.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.AddServerRequest"}}},"description":"Fields to update (all optional)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server updated successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - no fields or invalid body"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Partially update an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/config-to-secret":{"post":{"description":"Atomically reads the real value from the server config, stores it in the OS keyring, and rewrites the config field to ` + "`" + `${keyring:\u003cname\u003e}` + "`" + `. Unblocks the UI's Convert-to-secret affordance for values the API redacts on the read path.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{},"type":"object"}}},"description":"Secret stored, config updated with reference"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad scope/key/secret_name, or value is already a reference / empty"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or key not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Secret resolver or config update failed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Convert a header / env value to a keyring secret","tags":["servers"]}},"/api/v1/servers/{id}/disable":{"post":{"description":"Disable a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server disabled successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Disable an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/discover-tools":{"post":{"description":"Manually trigger tool discovery and indexing for a specific upstream MCP server. This forces an immediate refresh of the server's tool cache.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Tool discovery triggered successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot discover tools)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to discover tools"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Discover tools for a specific server","tags":["servers"]}},"/api/v1/servers/{id}/enable":{"post":{"description":"Enable a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server enabled successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/login":{"post":{"description":"Initiate OAuth authentication flow for a specific upstream MCP server. Returns structured OAuth start response with correlation ID for tracking.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.OAuthStartResponse"}}},"description":"OAuth login initiated successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.OAuthFlowError"}}},"description":"OAuth error (client_id required, DCR failed, etc.)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Trigger OAuth login for server","tags":["servers"]}},"/api/v1/servers/{id}/logout":{"post":{"description":"Clear OAuth authentication token and disconnect a specific upstream MCP server. The server will need to re-authenticate before tools can be used again.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"OAuth logout completed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled or read-only mode)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Clear OAuth token and disconnect server","tags":["servers"]}},"/api/v1/servers/{id}/logs":{"get":{"description":"Retrieve log entries for a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Number of log lines to retrieve","in":"query","name":"tail","schema":{"default":100,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServerLogsResponse"}}},"description":"Server logs retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server logs","tags":["servers"]}},"/api/v1/servers/{id}/quarantine":{"post":{"description":"Place a specific upstream MCP server in quarantine to prevent tool execution","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server quarantined successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Quarantine a server","tags":["servers"]}},"/api/v1/servers/{id}/refresh":{"post":{"description":"Re-discover and re-index a specific upstream MCP server's tools without changing any security state. Alias of discover-tools, named for the upstream_servers 'refresh' operation; use it to make just-approved tools searchable immediately.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Tool refresh triggered successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot refresh)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to refresh tools"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Refresh a server's tools","tags":["servers"]}},"/api/v1/servers/{id}/restart":{"post":{"description":"Restart the connection to a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server restarted successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Restart an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/review":{"get":{"description":"Returns redacted server configuration, captured tool definitions, annotations, scan verdicts, and diffs. Scoped callers receive the same 404 for invisible and missing servers.","parameters":[{"description":"Server name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server review"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to load server review"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get review details for a server","tags":["review"]}},"/api/v1/servers/{id}/security/approve":{"post":{"description":"Saves the integrity baseline and optionally blocks selected tools atomically before unquarantining the server. With expected_hashes (tool name -\u003e the review's current_hash; {} for an empty review) the approval is bound to the reviewed definitions: when a tool the approval would make reachable (pending, or approved and enabled, minus block) changed or appeared since the review, or a block target no longer exists, the response is 409 review_out_of_date, nothing is written and the server stays quarantined. Tools listed after the approval wait for review.","parameters":[{"description":"Server name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.securityApproveRequest"}}},"description":"Force approval and tool names to keep disabled"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server approved"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request or unknown tool block target"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not configured"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.StaleReviewErrorResponse"}}},"description":"Dangerous scan verdict requires force, approval failed, the review is out of date (error_code review_out_of_date), or server_replaced (the server was removed or re-added since expected_incarnation)"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Approve a server after security review","tags":["security"]}},"/api/v1/servers/{id}/skills":{"get":{"description":"Lists the skills of one upstream server. An administrator sees every record: status, hashes, files, scan result and the availability an agent would see. A scoped agent token with the server in its reach sees only the available skills, as the approved copy (id, uri, path, name, description, status \"approved\", approved_hash, files, total_size; contracts.SkillsAgentListResponse) and nothing about any other skill; a server outside its reach is 404. With enable_skills off the answer is {\"enabled\": false, \"skills\": []} and no upstream is contacted.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsListResponse"}}},"description":"Skills of the server"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found, or outside the caller's reach"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List the skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/skills/approve":{"post":{"description":"Administrator only. Approves the named skills for exactly the content the reviewer saw: expected_hashes maps each skill path to the current_hash from the listing, and expected_incarnation (the listing's incarnation) binds the approval to the server that was reviewed. When a hash differs, or a named skill has no expected hash, the response is 409 review_out_of_date with the changed and unreviewed names and nothing is approved; 409 server_replaced when the server was removed or replaced since the review; 422 skill_unusable for a skill that cannot be approved (a failed check or a dynamic file list). A skill already approved for its current content is left as it is and not counted. The blocked mark is never touched. A scoped agent token is refused with 403.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsApproveRequest"}}},"description":"Skills to approve, with the review binding","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsApproveResponse"}}},"description":"Number of skills newly approved (inside the data envelope)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or skill not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsStaleReviewResponse"}}},"description":"review_out_of_date, server_replaced or skills_disabled"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsUnusableResponse"}}},"description":"skill_unusable"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Approve skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/skills/block":{"post":{"description":"Administrator only. Sets the blocked mark on the named skills: a blocked skill is never offered to an agent, and no refresh, content change or automatic approval clears the mark. expected_incarnation is optional (0 binds to the current server). 409 server_replaced when the server was removed or replaced since it was reviewed. A scoped agent token is refused with 403.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsBlockRequest"}}},"description":"Skills to block","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsBlockResponse"}}},"description":"Number of skills whose mark changed (inside the data envelope)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or skill not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"server_replaced or skills_disabled"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Block skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/skills/content":{"get":{"description":"Returns a chunk of one stored text file of a skill. An administrator reads the current copy by default; a scoped agent token with the server in its reach reads the approved copy of an available skill only (copy is forced to approved), and gets one 404 for every other skill or file. A server outside its reach is 404. Offsets are byte positions; a chunk never splits a UTF-8 character, so it can be a few bytes shorter than limit. next_offset is absent at the end of the file. 404 for an unknown skill or file (or with enable_skills off), 415 for a binary file, 409 stored_copy_damaged when the stored bytes no longer match their digest.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Skill path, e.g. hf-cli","in":"query","name":"skill","required":true,"schema":{"type":"string"}},{"description":"File path inside the skill (default SKILL.md)","in":"query","name":"file","schema":{"type":"string"}},{"description":"current (default) or approved","in":"query","name":"copy","schema":{"type":"string"}},{"description":"Byte offset to start at (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Maximum bytes (default and maximum 65536)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillContentResponse"}}},"description":"A chunk of the file"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad parameters"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"output_blocked: the output sanitisation policy withholds the text (scoped caller)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server, skill or file not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"stored_copy_damaged (administrator)"},"415":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"The file is binary"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Read one text file of a skill","tags":["servers"]}},"/api/v1/servers/{id}/skills/refresh":{"post":{"description":"Administrator only. Reads the server's skills from the upstream again, verifies every file and returns the listing once applied. A refresh that is already running is joined. 409 skills_disabled when enable_skills is off; 409 skills_not_supported when the server does not announce the skills extension.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsListResponse"}}},"description":"Skills of the server after the refresh"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"skills_disabled, skills_not_supported or refresh_superseded"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Refresh failed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Refresh the skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/skills/unblock":{"post":{"description":"Administrator only. Clears the blocked mark on the named skills. The skill's approval state is not changed: a skill that is not approved stays unavailable. expected_incarnation is optional (0 binds to the current server). 409 server_replaced when the server was removed or replaced since it was reviewed. A scoped agent token is refused with 403.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsBlockRequest"}}},"description":"Skills to unblock","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsBlockResponse"}}},"description":"Number of skills whose mark changed (inside the data envelope)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Administrator credentials required"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or skill not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SkillsErrorResponse"}}},"description":"server_replaced or skills_disabled"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Unblock skills of a server","tags":["servers"]}},"/api/v1/servers/{id}/tool-calls":{"get":{"description":"Retrieves tool call history filtered by upstream server ID. Returns recent tool executions for the specified server including timestamps, arguments, results, and errors. Useful for server-specific debugging and monitoring.","parameters":[{"description":"Upstream server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Maximum number of records to return (1-100, default 50)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServerToolCallsResponse"}}},"description":"Server tool calls retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get server tool calls"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call history for specific server","tags":["tool-calls"]}},"/api/v1/servers/{id}/tools":{"get":{"description":"Retrieve all available tools for a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServerToolsResponse"}}},"description":"Server tools retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server kept being removed or replaced while its tools were read"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/approve":{"post":{"description":"Approves the given pending/changed tools (or all of them with approve_all). With expected_hashes (tool name -\u003e the review's current_hash) the approval is bound to the reviewed definitions: when a requested tool (approve_all: any pending or changed tool) no longer matches, the response is 409 review_out_of_date and nothing is approved.","parameters":[{"description":"Server name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.approveToolsRequest"}}},"description":"Tools to approve, or approve_all, with an optional review binding","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Approval outcome"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.StaleReviewErrorResponse"}}},"description":"The review is out of date; nothing was approved"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Approve tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/block":{"post":{"description":"Atomically approves AND disables the given tools (or all pending/changed tools when block_all=true) for a server. The approve and disable land in a single write per tool, so a tool is never left in the approved+enabled state. The \"blocked\" field counts tools actually blocked. An optional expected_incarnation binds the write to the reviewed server (Spec 116): a remove and re-add since then answers 409 server_replaced and writes nothing.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Block result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server was removed or re-added since expected_incarnation"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Block (approve+disable) tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/disable_all":{"post":{"description":"Bulk-toggles every known tool of a server. The \"changed\" field","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.expectedIncarnationBody"}}},"description":"Optional incarnation of the reviewed server (Spec 116)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Operation result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server was removed or re-added since expected_incarnation"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable or disable all tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/enable_all":{"post":{"description":"Bulk-toggles every known tool of a server. The \"changed\" field","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.expectedIncarnationBody"}}},"description":"Optional incarnation of the reviewed server (Spec 116)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Operation result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server was removed or re-added since expected_incarnation"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable or disable all tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/unquarantine":{"post":{"description":"Remove a specific upstream MCP server from quarantine to allow tool execution","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.expectedIncarnationBody"}}},"description":"Optional incarnation of the reviewed server (Spec 116)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server unquarantined successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"server_replaced: the server was removed or re-added since expected_incarnation"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Unquarantine a server","tags":["servers"]}},"/api/v1/sessions":{"get":{"description":"Retrieves paginated list of active and recent MCP client sessions. Each session represents a connection from an MCP client to MCPProxy, tracking initialization time, tool calls, and connection status.","parameters":[{"description":"Maximum number of sessions to return (1-100, default 10)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Number of sessions to skip for pagination (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Filter by session status","in":"query","name":"status","schema":{"enum":["active","closed"],"type":"string"}},{"description":"Filter by the session's latest effective profile; - selects sessions with none (Spec 108)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Filter by the client id the session's credential is bound to; - selects sessions with none (Spec 108)","in":"query","name":"client","schema":{"type":"string"}},{"description":"Filter by the token name the session initialized with; - selects sessions with none (Spec 108)","in":"query","name":"token","schema":{"type":"string"}},{"description":"Alias of token","in":"query","name":"agent","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetSessionsResponse"}}},"description":"Sessions retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid status filter, token and agent naming different tokens, or client_name (not supported here; filter by client)"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read MCP session history"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get sessions"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get active MCP sessions","tags":["sessions"]}},"/api/v1/sessions/{id}":{"get":{"description":"Retrieves detailed information about a specific MCP client session including initialization parameters, connection status, tool call count, and activity timestamps.","parameters":[{"description":"Session ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetSessionDetailResponse"}}},"description":"Session details retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Session ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read MCP session history"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Session not found"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get MCP session details by ID","tags":["sessions"]}},"/api/v1/stats/tokens":{"get":{"description":"Retrieve token savings statistics across all servers and sessions","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Token statistics"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read deployment-wide token statistics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get token savings statistics","tags":["stats"]}},"/api/v1/status":{"get":{"description":"Get comprehensive server status including running state, listen address, upstream statistics, and timestamp. For a scoped caller (an agent token; for a profile-pinned token, its allowed_servers intersected with the pin) upstream_stats lists only the servers it may enumerate and every counter is recomputed over them.\ntelemetry (admin only): effective telemetry state {enabled, source: env|config|default, disabled_by}","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server status information"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server status","tags":["status"]}},"/api/v1/telemetry/payload":{"get":{"description":"Render the exact JSON heartbeat payload that mcpproxy would next send to the telemetry endpoint, without making a network call. Counters in the payload reflect the current in-memory state. Spec 042.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Telemetry heartbeat payload"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read the deployment telemetry payload"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Telemetry service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Preview next telemetry heartbeat payload","tags":["telemetry"]}},"/api/v1/telemetry/update-failure":{"post":{"description":"Records one terminal update-session failure, identified only by its\nstage (appcast, download, install, other). The body carries no error\ntext, URL, or version — the stage is the only value transmitted.\nReturns 204 both when the occurrence was durably persisted and when\ntelemetry is inactive at event time (config opt-out, environment\nopt-out, CI, or dev build), in which case nothing is recorded.\nCallers cannot and need not distinguish the two.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.UpdateFailureRequest"}}},"description":"Update failure stage","required":true},"responses":{"204":{"description":"Accepted (recorded, or a deliberate no-op while telemetry is inactive)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Malformed body, unknown field, trailing value, or stage outside the closed set"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Persistence failure"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Record a desktop auto-update failure occurrence (Spec 095)","tags":["telemetry"]}},"/api/v1/tool-calls":{"get":{"description":"Retrieves paginated tool call history across all upstream servers or filtered by session ID. Includes execution timestamps, arguments, results, and error information for debugging and auditing.","parameters":[{"description":"Maximum number of records to return (1-100, default 50)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Number of records to skip for pagination (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Filter tool calls by MCP session ID","in":"query","name":"session_id","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetToolCallsResponse"}}},"description":"Tool calls retrieved successfully"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get tool calls"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call history","tags":["tool-calls"]}},"/api/v1/tool-calls/{id}":{"get":{"description":"Retrieves detailed information about a specific tool call execution including full request arguments, response data, execution time, and any errors encountered.","parameters":[{"description":"Tool call ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetToolCallDetailResponse"}}},"description":"Tool call details retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call not found"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call details by ID","tags":["tool-calls"]}},"/api/v1/tool-calls/{id}/replay":{"post":{"description":"Re-executes a previous tool call with optional modified arguments. Useful for debugging and testing tool behavior with different inputs. Creates a new tool call record linked to the original.","parameters":[{"description":"Original tool call ID to replay","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ReplayToolCallRequest"}}},"description":"Optional modified arguments for replay"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ReplayToolCallResponse"}}},"description":"Tool call replayed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call ID required or invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Replay refused: tool quarantined or not callable, server quarantined, outside the profile policy, or the token lacks the tool's permission tier"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"429":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Shed by a concurrency limit or an agent token call rate limit (Retry-After header carries the wait hint)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to replay tool call"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Replay a tool call","tags":["tool-calls"]}},"/api/v1/tools":{"get":{"description":"Consolidated, read-only listing of all tools from every configured server (including disabled servers and disabled/config-denied tools), enriched with approval state and 30-day usage. Backs the global Tools page and the CLI global ` + "`" + `tools list` + "`" + ` (spec 050, issue #437).","parameters":[{"description":"View-as (administrator only): the tools this client would see, each with its access verdict {visible, callable, reason} and profile_tier (Spec 108 FR-032)","in":"query","name":"client","schema":{"type":"string"}},{"description":"View-as: the tools this profile would expose. An administrator gets every row with a verdict; any other caller gets only the visible rows plus counts {visible, hidden} (Spec 108 FR-032)","in":"query","name":"profile","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GlobalToolsResponse"}}},"description":"All tools across all servers"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unsupported scope filter (token), both client and profile, or '-' on a tools filter"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"client= requires administrator credentials"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown or unreachable client / profile"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Could not enumerate servers"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List every tool across all servers","tags":["tools"]}},"/api/v1/tools/call":{"post":{"description":"Execute a tool on an upstream MCP server (wrapper around MCP tool calls)","requestBody":{"content":{"application/json":{"schema":{"properties":{"arguments":{"type":"object"},"tool_name":{"type":"string"}},"type":"object"}}},"description":"Tool call request with tool name and arguments","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Tool call result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (invalid payload or missing tool name)"},"429":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Shed by a concurrency limit or an agent token call rate limit (Retry-After header carries the wait hint)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error or tool execution failure"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Call a tool","tags":["tools"]}},"/api/v1/work-sessions":{"get":{"description":"Lists work sessions (one agent's run of work) with their failure facts. An agent token sees only its own sessions, and only the part of each that touched servers in its reach.","parameters":[{"description":"Only sessions with at least one failure","in":"query","name":"failed","schema":{"type":"boolean"}},{"description":"With failed: count policy blocks as failures (default true)","in":"query","name":"include_blocked","schema":{"type":"boolean"}},{"description":"Filter by agent token name","in":"query","name":"token","schema":{"type":"string"}},{"description":"Filter by client id","in":"query","name":"client","schema":{"type":"string"}},{"description":"Filter by profile (administrators only)","in":"query","name":"profile","schema":{"type":"string"}},{"description":"Filter by run name","in":"query","name":"run","schema":{"type":"string"}},{"description":"Filter by the error class of the last failure","in":"query","name":"error_class","schema":{"type":"string"}},{"description":"Only sessions active at or after this time (RFC3339)","in":"query","name":"since","schema":{"type":"string"}},{"description":"Only sessions active at or before this time (RFC3339)","in":"query","name":"until","schema":{"type":"string"}},{"description":"last_activity (default) or last_failure","in":"query","name":"sort","schema":{"enum":["last_activity","last_failure"],"type":"string"}},{"description":"Page size (default 25, max 100)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Page offset","in":"query","name":"offset","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.WorkSessionListEnvelope"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad Request"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List work sessions","tags":["activity"]}},"/api/v1/work-sessions/{id}":{"get":{"parameters":[{"description":"Work session id","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.WorkSessionEnvelope"}}},"description":"OK"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Not Found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get one work session","tags":["activity"]}},"/api/v1/work-sessions/{id}/timeline":{"get":{"description":"Returns the session's activity rows and the upstream events of the servers it called, in time order, positioned at a failure, a row or the end. Bodies are omitted unless include_bodies is set.","parameters":[{"description":"Work session id","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"first_failure (default), failure:\u003cn\u003e, row:\u003cactivity id\u003e or end","in":"query","name":"at","schema":{"type":"string"}},{"description":"Rows before the position (default 20, max 250)","in":"query","name":"before","schema":{"type":"integer"}},{"description":"Rows after the position (default 20, max 250)","in":"query","name":"after","schema":{"type":"integer"}},{"description":"Include argument and response bodies","in":"query","name":"include_bodies","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.WorkSessionTimelineEnvelope"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad Request"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Not Found"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get a work session's timeline","tags":["activity"]}},"/healthz":{"get":{"description":"Get comprehensive health status including all component health (Kubernetes-compatible liveness probe)","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.HealthResponse"}}},"description":"Service is healthy"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.HealthResponse"}}},"description":"Service is unhealthy"}},"summary":"Get health status","tags":["health"]}},"/readyz":{"get":{"description":"Get readiness status including all component readiness checks (Kubernetes-compatible readiness probe)","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.ReadinessResponse"}}},"description":"Service is ready"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.ReadinessResponse"}}},"description":"Service is not ready"}},"summary":"Get readiness status","tags":["health"]}}}, diff --git a/oas/swagger.yaml b/oas/swagger.yaml index 291114a1c..709576f41 100644 --- a/oas/swagger.yaml +++ b/oas/swagger.yaml @@ -411,6 +411,15 @@ components: Routing mode (Spec 031): how MCP tools are exposed to clients Valid values: "retrieve_tools" (default), "direct", "code_execution" type: string + secret_file_dirs: + description: |- + SecretFileDirs lists absolute directories where ${file:} references may + be resolved. Absent (nil) uses platform defaults; an explicit empty array + disables file references; exactly ["*"] allows any path (compatibility mode). + items: + type: string + type: array + uniqueItems: false security: $ref: '#/components/schemas/config.SecurityConfig' sensitive_data_detection: diff --git a/specs/111-personal-docker-image/spec.md b/specs/111-personal-docker-image/spec.md index ec79677c3..0e4e59dc9 100644 --- a/specs/111-personal-docker-image/spec.md +++ b/specs/111-personal-docker-image/spec.md @@ -280,7 +280,7 @@ The maintainer wants to know how many installs use each official image and needs **Secrets** - **FR-029**: `${env:NAME}` references MUST be documented as the primary way to pass secrets to upstream servers in containers. OS-keyring references MUST fail with a message that says the keyring is unavailable in containers and names the alternatives. -- **FR-030**: The proxy MUST support `${file:/absolute/path}` secret references that read a secret from a file, strip one trailing newline (and, when present, a preceding carriage return, so CRLF-terminated Windows-authored secret files resolve the same value as LF-terminated ones), never write the value back to config, and never show it in logs or API responses. A `${file:}` reference is accepted wherever `${env:}` and `${keyring:}` are, which includes the proxy's own `api_key` (`"api_key": "${file:/run/secrets/key}"`): there it is resolved when the config is loaded, as a process-only override, so the effective config runs with the secret while every save, including the one a `PATCH /api/v1/config` triggers, writes the reference back; an `api_key` reference that does not resolve fails the load and never falls back to a generated key; and a key from the environment overrides the file's, in which case the reference is not read. The same read rules apply to every file-sourced secret, including `MCPPROXY_API_KEY_FILE` (FR-014): the path MUST be absolute, a symlink is followed but its target MUST be a regular file (Kubernetes secret volumes are symlinks), at most 64 KiB is read (a larger file is an error, not a truncated secret), a NUL byte is rejected, and an error names the path and the reason but never any of the content. +- **FR-030**: The proxy MUST support `${file:/absolute/path}` secret references that read a secret from a file, strip one trailing newline (and, when present, a preceding carriage return, so CRLF-terminated Windows-authored secret files resolve the same value as LF-terminated ones), never write the value back to config, and never show it in logs or API responses. A `${file:}` reference is accepted wherever `${env:}` and `${keyring:}` are, which includes the proxy's own `api_key` (`"api_key": "${file:/run/secrets/key}"`): there it is resolved when the config is loaded, as a process-only override, so the effective config runs with the secret while every save, including the one a `PATCH /api/v1/config` triggers, writes the reference back; an `api_key` reference that does not resolve fails the load and never falls back to a generated key; and a key from the environment overrides the file's, in which case the reference is not read. Resolution is constrained by the top-level `secret_file_dirs` allow-list (defaults: `/run/secrets`, `/run/credentials`, and `/secrets` on Linux; `/secrets` on macOS and Windows; plus `CREDENTIALS_DIRECTORY` when set; explicit `[]` disables `${file:}`; `["*"]` restores unrestricted reads with a startup warning). Upstream server fields MUST NOT resolve `${env:MCPPROXY_*}` references. The same read rules apply to every file-sourced secret, including `MCPPROXY_API_KEY_FILE` (FR-014) except that variable is not subject to `secret_file_dirs` (operator-controlled) but MUST NOT name the active config file or any path under the data directory except `/secrets`: the path MUST be absolute, a symlink is followed but its target MUST be a regular file (Kubernetes secret volumes are symlinks), at most 64 KiB is read (a larger file is an error, not a truncated secret), a NUL byte is rejected, and policy denials for upstream fields use fixed errors that do not echo paths or content. **Updates and telemetry**