diff --git a/cmd/generate-types/main.go b/cmd/generate-types/main.go index 24d58db0a..007f9684b 100644 --- a/cmd/generate-types/main.go +++ b/cmd/generate-types/main.go @@ -230,6 +230,7 @@ export interface PreflightResponse { updated: string; // ISO date string isolation?: IsolationConfig; isolation_defaults?: IsolationDefaults; // Resolved baseline values (read-only, used as placeholders) + isolation_effective?: IsolationEffective; // Resolved isolation state + why (read-only) oauth_status?: 'authenticated' | 'expired' | 'error' | 'none'; // OAuth authentication status token_expires_at?: string; // ISO date string when OAuth token expires user_logged_out?: boolean; // True if user explicitly logged out (prevents auto-reconnection) @@ -282,7 +283,15 @@ export interface OAuthConfig { } export interface IsolationConfig { + // EFFECTIVE isolation state, after global + per-server + structural + // resolution. NOT the raw per-server override — read enabled_override for + // that. Always present on stdio servers. enabled: boolean; + // RAW per-server override. Absent = inherit the global setting, which is a + // distinct state from an explicit false. + enabled_override?: boolean; + // RAW per-server mode override. Absent = inherit. + mode_override?: string; image?: string; network_mode?: string; extra_args?: string[]; @@ -292,6 +301,17 @@ export interface IsolationConfig { timeout?: string; } +// IsolationEffective reports the resolved isolation state of a server and the +// rule that produced it, so the UI can explain "inherits global: docker" +// instead of rendering an ambiguous toggle. Read-only; never sent on PATCH. +export interface IsolationEffective { + mode: string; // 'docker' | 'sandbox' | 'none' — what the spawn path branches on + isolated: boolean; // actually CONFINED; not simply mode !== 'none' (see 'sandbox-unavailable') + global_mode?: string; + inherited: boolean; // no per-server enabled/mode override is set + source?: string; // 'global' | 'server-mode' | 'server-opt-out' | 'server-opt-in-ignored' | 'not-stdio' | 'already-docker' | 'sandbox-unavailable' | 'unsupported-mode'; treat unknown as 'global' +} + // IsolationDefaults reports the resolved baseline Docker isolation // values the backend will apply when no per-server override is set. // Populated on server-list / server-get responses; the Web UI uses these diff --git a/cmd/release-gate/client.go b/cmd/release-gate/client.go index 551064174..2a101495b 100644 --- a/cmd/release-gate/client.go +++ b/cmd/release-gate/client.go @@ -313,8 +313,16 @@ type addServerRequest struct { } // isolationRequest mirrors httpapi.IsolationRequest (the subset we use). +// +// The writable key is `enabled_override`, NOT `enabled`: on a read +// `isolation.enabled` is the EFFECTIVE state (global setting + per-server +// override + structural gates), so the write surfaces refuse it with a 400 +// rather than let a read-modify-write client turn "inherits the global +// setting" into a permanent explicit override (GH #1142). Tri-state, matching +// the server: absent leaves the persisted override alone, `false` is an +// explicit opt-out. type isolationRequest struct { - Enabled *bool `json:"enabled,omitempty"` + EnabledOverride *bool `json:"enabled_override,omitempty"` } func (c *Client) addServer(ctx context.Context, req addServerRequest) error { diff --git a/cmd/release-gate/invariants.go b/cmd/release-gate/invariants.go index 3ff7e74c2..c687c0ad9 100644 --- a/cmd/release-gate/invariants.go +++ b/cmd/release-gate/invariants.go @@ -298,6 +298,29 @@ type quarantineFlowDeps struct { ConnectTimeout time.Duration } +// quarantineFixtureAddRequest builds the POST /api/v1/servers body for the +// quarantine-flow fixture. +// +// Isolation is opted out PER SERVER: this fixture runs a host binary and the +// matrix run may have global docker isolation enabled for the docker cell, so +// without the opt-out the docker cell would wrap the host path in a container +// and the fixture would never start. +// +// Extracted so the wire shape is unit-testable: `isolation.enabled` is +// read-only on writes (GH #1142) and a body carrying it is answered with 400, +// which would fail add-server and every invariant downstream of it. +func quarantineFixtureAddRequest(serverName, binPath string) addServerRequest { + enabled, isolate := true, false + return addServerRequest{ + Name: serverName, + Command: binPath, + Args: []string{"--transport", "stdio"}, + Protocol: "stdio", + Enabled: &enabled, + Isolation: &isolationRequest{EnabledOverride: &isolate}, + } +} + // checkQuarantineFlow adds a fresh stdio fixture server mid-run via the // management API and asserts the full Spec 032 lifecycle: // @@ -344,19 +367,9 @@ func checkQuarantineFlow(ctx context.Context, c *Client, deps quarantineFlowDeps } // Add WITHOUT an explicit quarantined value: the default path must land - // the server in quarantine (issue #370 semantics). Isolation is opted - // out per-server: this fixture runs a host binary and the matrix run may - // have global docker isolation enabled for the docker cell. + // the server in quarantine (issue #370 semantics). if err := step("add-server", func() error { - t, f := true, false - return c.addServer(ctx, addServerRequest{ - Name: deps.ServerName, - Command: binPath, - Args: []string{"--transport", "stdio"}, - Protocol: "stdio", - Enabled: &t, - Isolation: &isolationRequest{Enabled: &f}, - }) + return c.addServer(ctx, quarantineFixtureAddRequest(deps.ServerName, binPath)) }); err != nil { return steps, cleanup, err } diff --git a/cmd/release-gate/isolation_write_contract_test.go b/cmd/release-gate/isolation_write_contract_test.go new file mode 100644 index 000000000..d136dc088 --- /dev/null +++ b/cmd/release-gate/isolation_write_contract_test.go @@ -0,0 +1,45 @@ +package main + +import ( + "encoding/json" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/httpapi" +) + +// TestQuarantineFixtureAddRequestUsesWritableIsolationKey pins the gate's +// add-server body to the WRITABLE isolation key. +// +// GH #1142 made `isolation.enabled` read-only on POST /api/v1/servers: it is +// the EFFECTIVE state on reads, so the handler now answers 400 rather than +// letting a read-modify-write turn "inherits the global setting" into a +// permanent override. The gate's fixture opt-out is load-bearing — it runs a +// HOST binary and must stay native when the docker matrix cell turns global +// isolation on — so it has to keep opting out, via `enabled_override`. +// +// The assertion decodes the gate's own body with the SERVER's request type, so +// it fails exactly when the real handler would reject the request, instead of +// re-stating the gate's JSON tags back at itself. +func TestQuarantineFixtureAddRequestUsesWritableIsolationKey(t *testing.T) { + body, err := json.Marshal(quarantineFixtureAddRequest("gate-fresh-abc123", "/tmp/bin/mcpfixture-gate-fresh-abc123")) + if err != nil { + t.Fatalf("marshal add-server body: %v", err) + } + + var decoded httpapi.AddServerRequest + if err := json.Unmarshal(body, &decoded); err != nil { + t.Fatalf("server-side decode of gate body %s: %v", body, err) + } + if decoded.Isolation == nil { + t.Fatalf("the per-server isolation opt-out was dropped from the gate body: %s", body) + } + if decoded.Isolation.Enabled.Set { + t.Fatalf("gate sends the read-only `isolation.enabled`; the handler answers 400 and the whole release QA gate fails: %s", body) + } + if !decoded.Isolation.EnabledOverride.Set { + t.Fatalf("gate must still opt the host fixture OUT of isolation via `enabled_override`: %s", body) + } + if decoded.Isolation.EnabledOverride.Value == nil || *decoded.Isolation.EnabledOverride.Value { + t.Fatalf("the fixture opt-out must be enabled_override=false, got %+v: %s", decoded.Isolation.EnabledOverride, body) + } +} diff --git a/docs/api/rest-api.md b/docs/api/rest-api.md index 52282d2d9..45d071c11 100644 --- a/docs/api/rest-api.md +++ b/docs/api/rest-api.md @@ -242,7 +242,7 @@ mask string. "enabled": true, "quarantined": false, "auto_approve_tool_changes": true, - "isolation": {"enabled": true, "image": "node:20"} + "isolation": {"enabled_override": true, "image": "node:20"} } ``` diff --git a/docs/docker-isolation.md b/docs/docker-isolation.md index b5d2a129d..d1c495db0 100644 --- a/docs/docker-isolation.md +++ b/docs/docker-isolation.md @@ -173,6 +173,39 @@ Per-server `isolation.enabled: true` only takes effect when the global `docker_i Starting in this release, MCPProxy emits a one-time warning in the main log when it detects this configuration (look for `per-server docker isolation opt-in ignored` in `~/.mcpproxy/logs/main.log`). To actually isolate those servers, flip the global flag on. +## Reading isolation state over the API + +Per-server `isolation.enabled` is a **tri-state** in the config file: `true`, `false`, or **absent** — and absent means *inherit the global setting*, not *off*. + +The API surfaces both halves of that, so a client never has to guess: + +| Field | Meaning | +|-------|---------| +| `isolation.enabled` | The **effective** state — is this server actually CONFINED right now, after the global setting, the per-server override, the structural gates and the host's capabilities. Always present for stdio servers. **Read-only** — see below. | +| `isolation.enabled_override` | The **raw** per-server override, exactly as persisted. **Absent = inherit.** | +| `isolation.mode_override` | The raw per-server `isolation.mode` override. Absent = inherit. | +| `isolation_effective` | `{mode, isolated, global_mode, inherited, source}` — the resolved state plus *why*. | + +`isolation_effective.source` is a small, extensible vocabulary: `global`, `server-mode`, `server-opt-out`, `server-opt-in-ignored`, `not-stdio`, `already-docker`, `sandbox-unavailable`, `unsupported-mode`. **Treat an unrecognized value as `global`.** + +`isolated` is deliberately NOT just `mode != none`. The `sandbox` mode is enforced by Landlock, which is Linux-only and absent from some kernels; where it cannot be enforced the launcher runs the server **unconfined**, so `isolated` is `false` and `source` is `sandbox-unavailable` even though `mode` stays `sandbox` (the wrapper still applies its rlimits on Linux). A mode no version implements reports `unsupported-mode`. The read surface never claims isolation the spawn path will not deliver. + +> **Changed in this release (GH #1142):** `isolation.enabled` previously carried the raw override flattened to a bool, so a server that inherited global isolation — and was genuinely running in a container — was reported as `enabled: false` and displayed as unisolated everywhere. It now reports the effective state; read `enabled_override` for the raw value. + +### Writing the override + +Reads and writes use **different key names on purpose**. `isolation.enabled` is a derived, read-only value; the writable key is `isolation.enabled_override`, the same key reads return the raw override under. `POST /api/v1/servers` and `PATCH /api/v1/servers/{id}` accept the tri-state there: + +- **omit the key** → leave the persisted override alone; +- **`null`** → clear the override, back to inheriting the global setting; +- **`true` / `false`** → set an explicit opt-in / opt-out. + +Sending `isolation.enabled` on either verb returns **400**. That is deliberate: it is the effective state on the way out, so a read-modify-write client that echoed the whole isolation object back would silently convert "inherits the global setting" into a permanent explicit override — the same corruption the effective-state reporting exists to prevent. An unrecognized `mode_override` is likewise rejected with a 400 naming the accepted vocabulary, instead of being persisted and failing the next daemon start's config validation. + +Only send `enabled_override` when the user actually changed it. Fields the request omits (including `log_driver`, `log_max_size`, `log_max_files`) are preserved. + +> The MCP `upstream_servers` tool's `isolation_json` argument is the raw config object, so its `enabled` field is the raw tri-state there, matching the config file. Its `mode` is validated the same way. + ## Telemetry When anonymous telemetry is enabled, MCPProxy reports two Docker-related counters at daily cadence: diff --git a/docs/features/sandbox-isolation.md b/docs/features/sandbox-isolation.md index b5a4bb3df..04fd35115 100644 --- a/docs/features/sandbox-isolation.md +++ b/docs/features/sandbox-isolation.md @@ -70,6 +70,12 @@ stdin/stdout pass straight through with no intervening multiplexer. | **Linux** (no Landlock) | Degraded → runs unconfined, logged | | **macOS / Windows** | Documented **no-op** → effective `none` (Landlock is Linux-only) | +The API says so too: where the sandbox cannot be enforced, a server with +`mode: sandbox` reports `isolation.enabled: false` and +`isolation_effective.source: "sandbox-unavailable"` (its `mode` stays `sandbox`, +because on Linux the wrapper still applies its rlimits). The read surface never +claims confinement the spawn path will not deliver. + See also: [Docker Isolation](/features/docker-isolation) for the Docker mode, and the [non-Docker sandbox spike](https://github.com/smart-mcp-proxy/mcpproxy-go/blob/main/docs/development/sandbox-spike-mcp-34.md) for the mechanism evaluation. diff --git a/frontend/src/types/api.ts b/frontend/src/types/api.ts index ee1b4f013..b81af8fb2 100644 --- a/frontend/src/types/api.ts +++ b/frontend/src/types/api.ts @@ -156,7 +156,15 @@ export interface SecurityScanReportSummary { // Server types export interface ServerIsolationConfig { + // EFFECTIVE isolation state, after global + per-server + structural + // resolution. NOT the raw per-server override — read enabled_override for + // that. Always present on stdio servers. enabled: boolean + // RAW per-server override. Absent = inherit the global setting, which is a + // distinct state from an explicit false. + enabled_override?: boolean + // RAW per-server mode override. Absent = inherit. + mode_override?: string image?: string network_mode?: string extra_args?: string[] @@ -169,6 +177,20 @@ export interface ServerIsolationConfig { // IsolationDefaults reports the resolved baseline Docker isolation // values the backend will apply when no per-server override is set. // Used as placeholders so "empty = inherit" is discoverable in the UI. +// IsolationEffective reports the resolved isolation state of a server and the +// rule that produced it, so the UI can explain "inherits global: docker" +// instead of rendering an ambiguous toggle. Read-only; never sent on PATCH. +export interface ServerIsolationEffective { + mode: string // 'docker' | 'sandbox' | 'none' — what the spawn path branches on + isolated: boolean // actually CONFINED; not simply mode !== 'none' (see 'sandbox-unavailable') + global_mode?: string + inherited: boolean + // 'global' | 'server-mode' | 'server-opt-out' | 'server-opt-in-ignored' | + // 'not-stdio' | 'already-docker' | 'sandbox-unavailable' | 'unsupported-mode'. + // Treat unknown values as 'global'. + source?: string +} + export interface ServerIsolationDefaults { runtime_type?: string image?: string @@ -220,6 +242,7 @@ export interface Server { reconnect_count?: number isolation?: ServerIsolationConfig // Per-server Docker isolation override isolation_defaults?: ServerIsolationDefaults // Resolved baseline values (read-only) + isolation_effective?: ServerIsolationEffective // Resolved isolation state + why (read-only) oauth?: { client_id: string auth_url: string diff --git a/frontend/src/types/contracts.ts b/frontend/src/types/contracts.ts index 03f329831..56a3011dd 100644 --- a/frontend/src/types/contracts.ts +++ b/frontend/src/types/contracts.ts @@ -172,6 +172,7 @@ export interface Server { updated: string; // ISO date string isolation?: IsolationConfig; isolation_defaults?: IsolationDefaults; // Resolved baseline values (read-only, used as placeholders) + isolation_effective?: IsolationEffective; // Resolved isolation state + why (read-only) oauth_status?: 'authenticated' | 'expired' | 'error' | 'none'; // OAuth authentication status token_expires_at?: string; // ISO date string when OAuth token expires user_logged_out?: boolean; // True if user explicitly logged out (prevents auto-reconnection) @@ -224,7 +225,15 @@ export interface OAuthConfig { } export interface IsolationConfig { + // EFFECTIVE isolation state, after global + per-server + structural + // resolution. NOT the raw per-server override — read enabled_override for + // that. Always present on stdio servers. enabled: boolean; + // RAW per-server override. Absent = inherit the global setting, which is a + // distinct state from an explicit false. + enabled_override?: boolean; + // RAW per-server mode override. Absent = inherit. + mode_override?: string; image?: string; network_mode?: string; extra_args?: string[]; @@ -234,6 +243,17 @@ export interface IsolationConfig { timeout?: string; } +// IsolationEffective reports the resolved isolation state of a server and the +// rule that produced it, so the UI can explain "inherits global: docker" +// instead of rendering an ambiguous toggle. Read-only; never sent on PATCH. +export interface IsolationEffective { + mode: string; // 'docker' | 'sandbox' | 'none' — what the spawn path branches on + isolated: boolean; // actually CONFINED; not simply mode !== 'none' (see 'sandbox-unavailable') + global_mode?: string; + inherited: boolean; // no per-server enabled/mode override is set + source?: string; // 'global' | 'server-mode' | 'server-opt-out' | 'server-opt-in-ignored' | 'not-stdio' | 'already-docker' | 'sandbox-unavailable' | 'unsupported-mode'; treat unknown as 'global' +} + // IsolationDefaults reports the resolved baseline Docker isolation // values the backend will apply when no per-server override is set. // Populated on server-list / server-get responses; the Web UI uses these diff --git a/frontend/src/utils/isolationState.ts b/frontend/src/utils/isolationState.ts new file mode 100644 index 000000000..4825ede23 --- /dev/null +++ b/frontend/src/utils/isolationState.ts @@ -0,0 +1,72 @@ +import type { Server, ServerIsolationEffective } from '../types/api' + +/** + * A human-readable account of a server's isolation state. + * + * `label` answers "is it isolated"; `detail` answers "why", which is the part + * a bare toggle could never express. Before GH #1142 the API reported the raw + * per-server override flattened to a bool, so a server inheriting the global + * setting looked identical to one explicitly opted out — the UI had no way to + * tell the difference and showed containerised servers as unisolated. + */ +export interface IsolationDescription { + isolated: boolean + /** e.g. "Isolated (docker)" / "Not isolated" */ + label: string + /** e.g. "Inherits the global setting (docker)" */ + detail: string +} + +function modeLabel(mode: string | undefined): string { + return mode && mode !== 'none' ? mode : 'none' +} + +/** + * Describes the resolved isolation state, or null when the backend sent no + * resolution block (an older core, or a server with no local process). + * + * Unknown `source` values degrade to the inherit story rather than to a wrong + * claim — the vocabulary is documented as extensible. + */ +export function describeIsolation(server: Server | null | undefined): IsolationDescription | null { + const eff: ServerIsolationEffective | undefined = server?.isolation_effective + if (!eff) return null + + const globalMode = modeLabel(eff.global_mode) + const label = eff.isolated ? `Isolated (${modeLabel(eff.mode)})` : 'Not isolated' + + let detail: string + switch (eff.source) { + case 'server-mode': + detail = `Mode set for this server: ${modeLabel(eff.mode)}` + break + case 'server-opt-out': + detail = `Turned off for this server (global setting is ${globalMode})` + break + case 'server-opt-in-ignored': + detail = 'Turned on for this server, but global isolation is off — the setting is ignored' + break + case 'not-stdio': + detail = 'No local process to isolate' + break + case 'already-docker': + detail = 'This server already runs Docker itself' + break + case 'sandbox-unavailable': + // The mode is set, but the spawn path degrades to unconfined here (any + // non-Linux host, or a Linux kernel without Landlock). + detail = 'Sandbox mode is set, but this system cannot enforce it — the server runs unconfined' + break + case 'unsupported-mode': + detail = `Isolation mode "${eff.mode}" is not one this version implements — the server runs unconfined` + break + default: + // 'global' and anything unrecognized. + detail = eff.inherited + ? `Inherits the global setting (${globalMode})` + : 'Turned on for this server' + break + } + + return { isolated: eff.isolated, label, detail } +} diff --git a/frontend/src/views/ServerDetail.vue b/frontend/src/views/ServerDetail.vue index 8144a94eb..8c77fa462 100644 --- a/frontend/src/views/ServerDetail.vue +++ b/frontend/src/views/ServerDetail.vue @@ -1107,6 +1107,16 @@

Docker Isolation Overrides

+ +
Image
{{ server.isolation.image }} @@ -1562,6 +1572,7 @@ import { serverDisplayName, scanReportPath } from '@/utils/serverRoute' import { isTerminalScanStatus, decideScanReconcile, finalizeToastKind } from '@/utils/scanState' import { selectQuarantinedTools } from '@/utils/toolQuarantine' import { oauthSignInState } from '@/utils/health' +import { describeIsolation } from '@/utils/isolationState' import { computeToolDiffSections } from '@/utils/toolDiff' import { TRUST_MODES, type TrustMode } from '@/utils/trustMode' import { parseHoldEvidence } from '@/utils/holdEvidence' @@ -3366,8 +3377,13 @@ async function commitConvert() { // Isolation Overrides section — either a per-server override or a resolved // default the user might want to inspect. Stdio servers without docker // isolation enabled have neither and the section is hidden entirely. +// Resolved isolation state ("Isolated (docker) — inherits the global setting"), +// so the panel explains WHY rather than showing a bare flag (GH #1142). +const isolationState = computed(() => describeIsolation(server.value)) + const hasIsolationData = computed(() => { if (!server.value) return false + if (server.value.isolation_effective) return true const iso = server.value.isolation const def = server.value.isolation_defaults if (iso && (iso.image || iso.network_mode || (iso.extra_args && iso.extra_args.length) || iso.working_dir || iso.memory_limit || iso.cpu_limit)) { diff --git a/frontend/tests/unit/isolation-state.spec.ts b/frontend/tests/unit/isolation-state.spec.ts new file mode 100644 index 000000000..35bb33848 --- /dev/null +++ b/frontend/tests/unit/isolation-state.spec.ts @@ -0,0 +1,185 @@ +import { describe, it, expect } from 'vitest' +import { describeIsolation } from '../../src/utils/isolationState' +import type { Server } from '../../src/types/api' + +const stdio = (over: Partial = {}): Server => + ({ + id: 'srv', + name: 'srv', + protocol: 'stdio', + command: 'uvx', + enabled: true, + quarantined: false, + connected: true, + connecting: false, + tool_count: 0, + ...over, + }) as Server + +describe('describeIsolation', () => { + // GH #1142: a server that inherits global isolation used to be reported as + // enabled:false and therefore rendered as "not isolated". + it('says isolated and names the inheritance when no override is set', () => { + const d = describeIsolation( + stdio({ + isolation: { enabled: true }, + isolation_effective: { + mode: 'docker', + isolated: true, + inherited: true, + global_mode: 'docker', + source: 'global', + }, + }) + ) + expect(d).not.toBeNull() + expect(d!.isolated).toBe(true) + expect(d!.label).toBe('Isolated (docker)') + expect(d!.detail).toBe('Inherits the global setting (docker)') + }) + + it('names an explicit per-server opt-out', () => { + const d = describeIsolation( + stdio({ + isolation: { enabled: false, enabled_override: false }, + isolation_effective: { + mode: 'none', + isolated: false, + inherited: false, + global_mode: 'docker', + source: 'server-opt-out', + }, + }) + ) + expect(d!.isolated).toBe(false) + expect(d!.label).toBe('Not isolated') + expect(d!.detail).toBe('Turned off for this server (global setting is docker)') + }) + + it('names an explicit per-server opt-in', () => { + const d = describeIsolation( + stdio({ + isolation: { enabled: true, enabled_override: true }, + isolation_effective: { + mode: 'docker', + isolated: true, + inherited: false, + global_mode: 'docker', + source: 'global', + }, + }) + ) + expect(d!.detail).toBe('Turned on for this server') + }) + + it('warns when a per-server opt-in is being ignored', () => { + const d = describeIsolation( + stdio({ + isolation: { enabled: false, enabled_override: true }, + isolation_effective: { + mode: 'none', + isolated: false, + inherited: false, + global_mode: 'none', + source: 'server-opt-in-ignored', + }, + }) + ) + expect(d!.isolated).toBe(false) + expect(d!.detail).toBe('Turned on for this server, but global isolation is off — the setting is ignored') + }) + + it('explains the structural gates', () => { + const already = describeIsolation( + stdio({ + command: 'docker', + isolation_effective: { mode: 'none', isolated: false, inherited: true, source: 'already-docker' }, + }) + ) + expect(already!.detail).toBe('This server already runs Docker itself') + + const notStdio = describeIsolation( + stdio({ + isolation_effective: { mode: 'none', isolated: false, inherited: true, source: 'not-stdio' }, + }) + ) + expect(notStdio!.detail).toBe('No local process to isolate') + }) + + it('reports a per-server mode override', () => { + const d = describeIsolation( + stdio({ + isolation: { enabled: true, mode_override: 'sandbox' }, + isolation_effective: { + mode: 'sandbox', + isolated: true, + inherited: false, + global_mode: 'docker', + source: 'server-mode', + }, + }) + ) + expect(d!.label).toBe('Isolated (sandbox)') + expect(d!.detail).toBe('Mode set for this server: sandbox') + }) + + // GH #1142: `sandbox` on a host that cannot enforce Landlock runs the server + // UNCONFINED (wrapWithSandbox returns the command unchanged). The UI must not + // show a containerised-looking badge for a server that is not confined. + it('explains a sandbox mode the host cannot enforce', () => { + const d = describeIsolation( + stdio({ + isolation: { enabled: false, mode_override: 'sandbox' }, + isolation_effective: { + mode: 'sandbox', + isolated: false, + inherited: false, + global_mode: 'docker', + source: 'sandbox-unavailable', + }, + }) + ) + expect(d!.isolated).toBe(false) + expect(d!.label).toBe('Not isolated') + expect(d!.detail).toContain('cannot enforce it') + }) + + it('explains a mode this version does not implement', () => { + const d = describeIsolation( + stdio({ + isolation: { enabled: false, mode_override: 'bogus' }, + isolation_effective: { + mode: 'bogus', + isolated: false, + inherited: false, + global_mode: 'docker', + source: 'unsupported-mode', + }, + }) + ) + expect(d!.label).toBe('Not isolated') + expect(d!.detail).toContain('runs unconfined') + }) + + // Forward-compat: an unrecognized source must degrade to the inherit story, + // never to a wrong claim. + it('treats an unknown source as inherited', () => { + const d = describeIsolation( + stdio({ + isolation: { enabled: true }, + isolation_effective: { + mode: 'docker', + isolated: true, + inherited: true, + global_mode: 'docker', + source: 'something-new', + }, + }) + ) + expect(d!.detail).toBe('Inherits the global setting (docker)') + }) + + it('returns null when the backend sent no resolution block', () => { + expect(describeIsolation(stdio())).toBeNull() + }) +}) diff --git a/internal/config/config.go b/internal/config/config.go index 0049fdca8..586b2ed87 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -828,13 +828,35 @@ func (dic *DockerIsolationConfig) ResolvedMode() IsolationMode { return IsolationModeNone } -// IsEnabled returns true if isolation is explicitly enabled, false otherwise. -// Returns false if Enabled is nil (not set). -func (ic *IsolationConfig) IsEnabled() bool { - if ic == nil || ic.Enabled == nil { - return false - } - return *ic.Enabled +// HasEnabledOverride reports whether this server sets the legacy `enabled` +// bool at all. False means "inherit the global isolation setting" (GH #1142). +func (ic *IsolationConfig) HasEnabledOverride() bool { + return ic != nil && ic.Enabled != nil +} + +// HasModeOverride reports whether this server sets a per-server +// `isolation.mode` override. A nil pointer AND a pointer to the empty string +// both mean "unset" — the empty string is documented as the unset mode, and +// treating it as an override resolved servers to a mode the spawn path does not +// implement while reporting them isolated (GH #1142). +func (ic *IsolationConfig) HasModeOverride() bool { + return ic != nil && ic.Mode != nil && *ic.Mode != "" +} + +// IsExplicitlyEnabled reports whether this server opts IN to isolation via the +// legacy `enabled` bool. A nil Enabled is "inherit", never an opt-in. +// +// This is NOT the answer to "is this server isolated" — that question has +// exactly one answer, upstream/core.IsolationManager.ResolveIsolation, which +// also accounts for the global mode and the structural gates. +func (ic *IsolationConfig) IsExplicitlyEnabled() bool { + return ic != nil && ic.Enabled != nil && *ic.Enabled +} + +// IsExplicitlyDisabled reports whether this server opts OUT of isolation via +// the legacy `enabled` bool. A nil Enabled is "inherit", never an opt-out. +func (ic *IsolationConfig) IsExplicitlyDisabled() bool { + return ic != nil && ic.Enabled != nil && !*ic.Enabled } // BoolPtr returns a pointer to the given bool value. diff --git a/internal/config/isolation_depends_docker_test.go b/internal/config/isolation_depends_docker_test.go new file mode 100644 index 000000000..a8beec3be --- /dev/null +++ b/internal/config/isolation_depends_docker_test.go @@ -0,0 +1,81 @@ +package config + +import "testing" + +// TestServerDependsOnDocker separates the two questions that used to share one +// predicate (GH #1142): "which wrapper does the spawn path apply" (Mode) versus +// "does starting this server need a working Docker daemon" (this function). +// They agree everywhere except on a server that already invokes docker itself, +// which we must never double-wrap yet which still pays image-pull latency. +func TestServerDependsOnDocker(t *testing.T) { + dockerMode, sandboxMode := IsolationModeDocker, IsolationModeSandbox + optOut := false + + tests := []struct { + name string + global *DockerIsolationConfig + srv *ServerConfig + wantMode IsolationMode + want bool + }{ + { + name: "we containerise it", + global: &DockerIsolationConfig{Enabled: true}, + srv: &ServerConfig{Name: "plain", Command: "npx"}, + wantMode: IsolationModeDocker, + want: true, + }, + { + name: "it containerises itself: mode is none, the dependency is real", + global: &DockerIsolationConfig{Enabled: true}, + srv: &ServerConfig{Name: "dockerised", Command: "docker", Args: []string{"run", "-i", "mcp/foo"}}, + wantMode: IsolationModeNone, + want: true, + }, + { + name: "it containerises itself even with isolation globally off", + global: &DockerIsolationConfig{Enabled: false}, + srv: &ServerConfig{Name: "dockerised", Command: "docker"}, + wantMode: IsolationModeNone, + want: true, + }, + { + name: "sandbox mode needs no daemon", + global: &DockerIsolationConfig{Enabled: true}, + srv: &ServerConfig{Name: "sandboxed", Command: "npx", Isolation: &IsolationConfig{Mode: &sandboxMode}}, + wantMode: IsolationModeSandbox, + want: false, + }, + { + name: "per-server docker mode over an off global", + global: &DockerIsolationConfig{Enabled: false}, + srv: &ServerConfig{Name: "moded", Command: "npx", Isolation: &IsolationConfig{Mode: &dockerMode, Enabled: &optOut}}, + wantMode: IsolationModeDocker, + want: true, + }, + { + name: "http server has no child process at all", + global: &DockerIsolationConfig{Enabled: true}, + srv: &ServerConfig{Name: "remote", URL: "https://example.test/mcp"}, + wantMode: IsolationModeNone, + want: false, + }, + { + name: "nil server", + want: false, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if tc.srv != nil { + if got := ResolveIsolation(tc.global, tc.srv).Mode; got != tc.wantMode { + t.Fatalf("precondition: ResolveIsolation().Mode = %q, want %q", got, tc.wantMode) + } + } + if got := ServerDependsOnDocker(tc.global, tc.srv); got != tc.want { + t.Errorf("ServerDependsOnDocker() = %v, want %v", got, tc.want) + } + }) + } +} diff --git a/internal/config/isolation_effective_test.go b/internal/config/isolation_effective_test.go new file mode 100644 index 000000000..f71da6bd4 --- /dev/null +++ b/internal/config/isolation_effective_test.go @@ -0,0 +1,151 @@ +package config + +import ( + "strings" + "testing" +) + +// withSandboxEnforceable swaps the host-capability probe for the duration of a +// test so the sandbox-mode matrix can be asserted on any platform. +func withSandboxEnforceable(t *testing.T, available bool) { + t.Helper() + prev := sandboxEnforceable + sandboxEnforceable = func() bool { return available } + t.Cleanup(func() { sandboxEnforceable = prev }) +} + +// TestResolveIsolation_SandboxUnenforceable is the read/spawn parity guard for +// GH #1142: `core.Client.wrapWithSandbox` returns the command UNCHANGED when +// the host cannot enforce Landlock (every non-Linux OS, and Linux kernels +// without the LSM), so the process runs unconfined. Reporting isolated:true in +// that case is a false isolation claim on exactly the surface this fix exists +// to make trustworthy. +// +// Mode stays "sandbox" — the spawn path still wraps for best-effort rlimits on +// Linux — but Isolated must tell the truth about confinement. +func TestResolveIsolation_SandboxUnenforceable(t *testing.T) { + sandbox := IsolationModeSandbox + server := &ServerConfig{ + Name: "srv", + Command: "npx", + Isolation: &IsolationConfig{Mode: &sandbox}, + } + + t.Run("host cannot enforce the sandbox", func(t *testing.T) { + withSandboxEnforceable(t, false) + got := ResolveIsolation(&DockerIsolationConfig{Enabled: true}, server) + if got.Mode != IsolationModeSandbox { + t.Errorf("Mode = %q, want %q (the spawn path still takes the sandbox branch)", got.Mode, IsolationModeSandbox) + } + if got.Isolated { + t.Errorf("Isolated = true, want false: wrapWithSandbox runs the server unconfined on this host") + } + if got.Source != IsolationSourceSandboxUnavailable { + t.Errorf("Source = %q, want %q", got.Source, IsolationSourceSandboxUnavailable) + } + }) + + t.Run("host can enforce the sandbox", func(t *testing.T) { + withSandboxEnforceable(t, true) + got := ResolveIsolation(&DockerIsolationConfig{Enabled: true}, server) + if got.Mode != IsolationModeSandbox || !got.Isolated { + t.Errorf("want sandbox/isolated, got Mode=%q Isolated=%v", got.Mode, got.Isolated) + } + if got.Source != IsolationSourceServerMode { + t.Errorf("Source = %q, want %q", got.Source, IsolationSourceServerMode) + } + }) +} + +// TestResolveIsolation_EmptyModeOverrideInherits pins the documented meaning of +// an empty per-server mode: "unset", i.e. inherit the global setting. The +// resolver used to treat a pointer-to-"" as an explicit override, producing +// mode="" isolated=true source=server-mode while the spawn path (which matches +// on "docker"/"sandbox") ran the server unconfined (GH #1142). +func TestResolveIsolation_EmptyModeOverrideInherits(t *testing.T) { + empty := IsolationMode("") + server := &ServerConfig{ + Name: "srv", + Command: "npx", + Isolation: &IsolationConfig{Mode: &empty}, + } + + got := ResolveIsolation(&DockerIsolationConfig{Enabled: true}, server) + if got.Mode != IsolationModeDocker { + t.Errorf("Mode = %q, want %q (an empty mode inherits the global setting)", got.Mode, IsolationModeDocker) + } + if !got.Isolated { + t.Errorf("Isolated = false, want true (global docker isolation applies)") + } + if !got.Inherited { + t.Errorf("Inherited = false, want true (an empty mode is not an override)") + } + if got.Source != IsolationSourceGlobal { + t.Errorf("Source = %q, want %q", got.Source, IsolationSourceGlobal) + } +} + +// TestResolveIsolation_UnrecognizedModeIsNotIsolation covers a mode the spawn +// path does not implement (a hand-edited config, or a value that predates a +// downgrade). The launcher matches only "docker" and "sandbox", so anything +// else runs unconfined and must not be reported as isolated. +func TestResolveIsolation_UnrecognizedModeIsNotIsolation(t *testing.T) { + bogus := IsolationMode("Docker") // wrong case: not the docker mode + server := &ServerConfig{ + Name: "srv", + Command: "npx", + Isolation: &IsolationConfig{Mode: &bogus}, + } + + got := ResolveIsolation(&DockerIsolationConfig{Enabled: true}, server) + if got.Isolated { + t.Errorf("Isolated = true for mode %q, want false: the spawn path implements no such mode", bogus) + } + if got.Source != IsolationSourceUnsupportedMode { + t.Errorf("Source = %q, want %q", got.Source, IsolationSourceUnsupportedMode) + } +} + +// TestValidateIsolationModeOverride is the shared gate both write surfaces +// (REST `mode_override`, MCP `isolation_json`) call so an unknown mode is +// rejected at the seam instead of being persisted and failing the NEXT daemon +// start's config validation. +func TestValidateIsolationModeOverride(t *testing.T) { + mode := func(s string) *IsolationMode { m := IsolationMode(s); return &m } + + tests := []struct { + name string + in *IsolationMode + wantErr bool + }{ + {name: "nil is inherit", in: nil}, + {name: "empty is unset", in: mode("")}, + {name: "docker", in: mode("docker")}, + {name: "sandbox", in: mode("sandbox")}, + {name: "none", in: mode("none")}, + {name: "unknown", in: mode("bogus"), wantErr: true}, + {name: "wrong case", in: mode("Docker"), wantErr: true}, + {name: "trailing space", in: mode("docker "), wantErr: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := ValidateIsolationModeOverride(tt.in) + if tt.wantErr && err == nil { + t.Fatalf("ValidateIsolationModeOverride(%v) = nil, want an error", tt.in) + } + if !tt.wantErr && err != nil { + t.Fatalf("ValidateIsolationModeOverride(%v) = %v, want nil", tt.in, err) + } + if tt.wantErr { + // The message must name the accepted vocabulary so a typo is + // self-diagnosing from the API response alone. + for _, want := range []string{"docker", "sandbox", "none"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("error %q does not name the accepted value %q", err, want) + } + } + } + }) + } +} diff --git a/internal/config/isolation_resolve.go b/internal/config/isolation_resolve.go new file mode 100644 index 000000000..3ef5c7a0e --- /dev/null +++ b/internal/config/isolation_resolve.go @@ -0,0 +1,263 @@ +package config + +import ( + "fmt" + "path/filepath" + "strings" + "sync" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/sandbox" +) + +// sandboxEnforceable reports whether the "sandbox" isolation mode can actually +// confine a child process on THIS host. It is the same predicate the spawn path +// degrades on: `core.Client.wrapWithSandbox` returns the command UNCHANGED off +// Linux, and warns that confinement will not take effect on a Linux kernel +// without Landlock. Reporting isolated:true in either case would be a false +// isolation claim, which is worse than no claim at all. +// +// `sandbox.Available()` performs a syscall, so the answer is memoized — the +// resolver runs on every tool dispatch. It is a var so tests can assert both +// halves of the matrix on any platform. +var sandboxEnforceable = sync.OnceValue(sandbox.Available) + +// SandboxEnforceable reports whether the "sandbox" isolation mode can actually +// confine a child process on this host. Exported so surfaces that explain +// isolation state (and tests that assert the mode matrix) can ask the same +// question the resolver asks, instead of re-deriving it from GOOS. +func SandboxEnforceable() bool { return sandboxEnforceable() } + +// Isolation resolution sources. These are a stable vocabulary: they are +// serialized onto the REST/MCP surfaces so a UI can explain WHY a server is (or +// is not) isolated instead of rendering a bare toggle. Clients must treat an +// unrecognized value as "inherited from the global setting". +const ( + // IsolationSourceGlobal: the effective mode came from the global config — + // either because the server sets no override, or because its explicit + // enabled:true simply agrees with the global mode. + IsolationSourceGlobal = "global" + // IsolationSourceServerMode: a per-server `isolation.mode` override won. + IsolationSourceServerMode = "server-mode" + // IsolationSourceServerOptOut: a per-server `isolation.enabled:false` + // downgraded an otherwise-active global mode. + IsolationSourceServerOptOut = "server-opt-out" + // IsolationSourceServerOptInIgnored: the server sets `isolation.enabled:true` + // but global isolation is off, so the opt-in is ignored. + IsolationSourceServerOptInIgnored = "server-opt-in-ignored" + // IsolationSourceNotStdio: structural gate — the server has no local + // command, so there is no child process to isolate. + IsolationSourceNotStdio = "not-stdio" + // IsolationSourceAlreadyDocker: structural gate — the server already + // invokes docker itself, so wrapping it would break its socket access. + IsolationSourceAlreadyDocker = "already-docker" + // IsolationSourceSandboxUnavailable: capability gate — mode is "sandbox" + // but this host cannot enforce it (any non-Linux OS, or a Linux kernel + // without Landlock), so the child process runs unconfined. + IsolationSourceSandboxUnavailable = "sandbox-unavailable" + // IsolationSourceUnsupportedMode: the configured mode is not one the spawn + // path implements, so nothing wraps the child process. Reachable from a + // hand-edited config file; the write surfaces reject unknown modes. + IsolationSourceUnsupportedMode = "unsupported-mode" +) + +// ValidateIsolationModeOverride reports whether a per-server `isolation.mode` +// override is a mode the spawn path actually implements. +// +// Both write seams (REST `mode_override`, MCP `isolation_json`) call this so an +// unknown value is refused where the operator can see it, instead of being +// persisted to BBolt and the config file and only surfacing as a failed +// validation on the NEXT daemon start. +// +// nil and the empty string are "unset" (inherit the global mode), not errors. +func ValidateIsolationModeOverride(mode *IsolationMode) error { + if mode == nil || *mode == "" { + return nil + } + if !mode.IsValid() { + return fmt.Errorf("invalid isolation mode %q: must be one of: %s, %s, %s "+ + "(values are case-sensitive; send an empty string to clear the override and inherit the global setting)", + *mode, IsolationModeDocker, IsolationModeSandbox, IsolationModeNone) + } + return nil +} + +// ResolvedIsolation is the fully-resolved isolation state of a server: what +// actually happens at spawn time, plus enough context for a UI to explain it. +// +// This is the ONLY correct answer to "is this server isolated". The raw +// per-server override (IsolationConfig.Enabled) is tri-state and means nothing +// on its own — nil is "inherit", not "off" (GH #1142). +type ResolvedIsolation struct { + // Mode is the effective isolation mode: docker | sandbox | none. This is + // exactly what the spawn path branches on, so it must never be adjusted for + // host capability — on a Linux kernel without Landlock the sandbox wrapper + // still runs and still applies its rlimits. + Mode IsolationMode + // Isolated reports whether the child process is actually CONFINED — i.e. + // whether Mode is one the spawn path implements AND this host can enforce + // it. It is not simply `Mode != none`: "sandbox" on macOS/Windows, on a + // kernel without Landlock, or a mode the launcher does not implement, all + // run the server unconfined, and the read path must never claim isolation + // the spawn path will not deliver (GH #1142). Source says which. + Isolated bool + // GlobalMode is what "inherit" resolves to right now. + GlobalMode IsolationMode + // Inherited is true when the server carries no per-server enabled/mode + // override, so its state tracks the global setting. + Inherited bool + // Source explains which rule produced Mode; one of the IsolationSource* + // constants above. + Source string +} + +// ResolveIsolation resolves the effective isolation state for a server, +// combining the global config (with legacy Enabled⇒docker back-compat), the +// optional per-server override, and the structural gates — and reports which +// rule decided the outcome. +// +// It lives in `config` rather than `upstream/core` so that every surface which +// has to answer "is this server isolated" — the spawn path, the REST/MCP +// projections, and the contracts converter (which cannot import core without a +// cycle) — provably runs one algorithm. `core.IsolationManager.ResolveIsolation` +// wraps this to add the deduplicated ignored-opt-in warning. +// +// Precedence: +// 1. A per-server explicit Mode wins outright (even over a disabled global) — +// mirroring how other per-server overrides (image, network) take priority. +// 2. Otherwise, when the global mode resolves to none, per-server bool opt-ins +// are ignored, preserving the pre-mode behavior. +// 3. When the global mode is active, a per-server bool opt-out (enabled:false) +// downgrades the server to none. A nil Enabled is "inherit", NOT an opt-out. +// +// Structural gates then apply to ALL non-none modes: servers with no command +// (HTTP transports) and servers that already invoke docker are never isolated. +// +// A final CAPABILITY gate decides Isolated (not Mode): a mode the launcher does +// not implement, and "sandbox" on a host that cannot enforce Landlock, both run +// the server unconfined, so they must not be reported as isolated. Mode is left +// alone there because the spawn path branches on it and still applies the +// sandbox wrapper's rlimits on Linux — see isolationDelivered. +func ResolveIsolation(globalConfig *DockerIsolationConfig, serverConfig *ServerConfig) ResolvedIsolation { + globalMode := globalConfig.ResolvedMode() // nil-safe; returns none for nil + + var iso *IsolationConfig + if serverConfig != nil { + iso = serverConfig.Isolation + } + inherited := !iso.HasEnabledOverride() && !iso.HasModeOverride() + + mode, source := resolveConfiguredIsolationMode(iso, globalMode) + + // Structural gates apply to ALL non-none modes. + if mode != IsolationModeNone { + switch { + case serverConfig == nil || serverConfig.Command == "": + mode, source = IsolationModeNone, IsolationSourceNotStdio + case IsDockerCommand(serverConfig.Command): + mode, source = IsolationModeNone, IsolationSourceAlreadyDocker + } + } + + // Capability gate: does the spawn path actually confine this mode here? + isolated, source := isolationDelivered(mode, source) + + return ResolvedIsolation{ + Mode: mode, + Isolated: isolated, + GlobalMode: globalMode, + Inherited: inherited, + Source: source, + } +} + +// isolationDelivered answers "will the child process really be confined" for an +// already-resolved mode, and refines the source when the answer is no for a +// reason the mode alone does not explain. +// +// This is the read-path half of the single-algorithm invariant: the spawn path +// branches on Mode (`connection_stdio.go` / `connection_launcher.go` match +// "docker" via ShouldIsolate and "sandbox" explicitly), and every OTHER value +// falls through both branches and launches unwrapped. Anything this function +// calls unisolated is exactly what those branches decline to wrap or what +// wrapWithSandbox degrades to unconfined. +func isolationDelivered(mode IsolationMode, source string) (isolated bool, refinedSource string) { + switch mode { + case IsolationModeNone: + return false, source + case IsolationModeDocker: + return true, source + case IsolationModeSandbox: + if !sandboxEnforceable() { + return false, IsolationSourceSandboxUnavailable + } + return true, source + default: + // Unset or unrecognized: the launcher implements no such mode, so the + // server runs unconfined however the value got into the config. + return false, IsolationSourceUnsupportedMode + } +} + +// resolveConfiguredIsolationMode applies the global + per-server config +// precedence, before the structural gates in ResolveIsolation. +func resolveConfiguredIsolationMode(iso *IsolationConfig, globalMode IsolationMode) (IsolationMode, string) { + // (1) A per-server explicit Mode override wins outright. A pointer to the + // empty string is "unset" (the documented meaning of an empty mode), not an + // override, so it falls through to inherit rather than resolving to a mode + // nothing implements. + if iso.HasModeOverride() { + return *iso.Mode, IsolationSourceServerMode + } + + // (2) Global isolation off: per-server bool opt-ins are ignored. + if globalMode == IsolationModeNone { + if iso.IsExplicitlyEnabled() { + return IsolationModeNone, IsolationSourceServerOptInIgnored + } + return IsolationModeNone, IsolationSourceGlobal + } + + // (3) Global isolation active: honor a per-server bool opt-out. + if iso.IsExplicitlyDisabled() { + return IsolationModeNone, IsolationSourceServerOptOut + } + + return globalMode, IsolationSourceGlobal +} + +// IsDockerCommand reports whether a server's command already invokes Docker. +// Such servers are typically pre-configured containers; wrapping them (in a +// container or a Landlock sandbox) would break their access to the Docker socket. +func IsDockerCommand(command string) bool { + return filepath.Base(command) == "docker" || strings.Contains(command, "docker") +} + +// ServerDependsOnDocker reports whether STARTING this server needs a working +// Docker daemon — which is a different question from "do we isolate it". +// +// Two disjoint ways a server ends up talking to Docker: +// +// 1. We containerise it: ResolveIsolation resolves its effective mode to +// docker, so the spawn path wraps the command in `docker run`. +// 2. It containerises itself: its own command already invokes docker, so +// ResolveIsolation's already-docker structural gate deliberately forces +// mode=none (never double-wrap) — yet the process still shells out to the +// daemon and still pays image-pull latency. +// +// Callers that care about the LAUNCH SHAPE (which wrapper runs, which +// remediation to offer) must keep asking ResolveIsolation. Callers that care +// about DOCKER-THE-DEPENDENCY — the connect budget that must survive an image +// pull, the recovery monitor, shutdown container cleanup — ask this, so the +// two questions cannot silently collapse into one predicate again (GH #1142). +// +// It is built ON TOP of the resolver plus the already-docker structural fact, +// so there is still exactly one implementation of the isolation algorithm. +func ServerDependsOnDocker(globalConfig *DockerIsolationConfig, serverConfig *ServerConfig) bool { + if serverConfig == nil { + return false + } + if ResolveIsolation(globalConfig, serverConfig).Mode == IsolationModeDocker { + return true + } + return serverConfig.Command != "" && IsDockerCommand(serverConfig.Command) +} diff --git a/internal/config/isolation_tristate_test.go b/internal/config/isolation_tristate_test.go new file mode 100644 index 000000000..05ac0237b --- /dev/null +++ b/internal/config/isolation_tristate_test.go @@ -0,0 +1,64 @@ +package config + +import "testing" + +// TestIsolationConfig_TriStatePredicates pins the tri-state semantics of +// IsolationConfig.Enabled (GH #1142). The field is a *bool where nil means +// "inherit the global isolation setting" — NOT "disabled". The old +// IsEnabled() helper collapsed nil to false, which is why an inheriting +// server was reported as unisolated across the REST/MCP surfaces. +// +// The replacement predicates are named for the question they answer so the +// nil→false trap cannot be reintroduced by a careless call site. +func TestIsolationConfig_TriStatePredicates(t *testing.T) { + tests := []struct { + name string + cfg *IsolationConfig + wantHasOverride bool + wantExplicitTrue bool + wantExplicitFalse bool + }{ + { + name: "nil config", + cfg: nil, + wantHasOverride: false, + wantExplicitTrue: false, + wantExplicitFalse: false, + }, + { + name: "nil Enabled means inherit global", + cfg: &IsolationConfig{Image: "python:3.12"}, + wantHasOverride: false, + wantExplicitTrue: false, + wantExplicitFalse: false, + }, + { + name: "explicit true", + cfg: &IsolationConfig{Enabled: BoolPtr(true)}, + wantHasOverride: true, + wantExplicitTrue: true, + wantExplicitFalse: false, + }, + { + name: "explicit false", + cfg: &IsolationConfig{Enabled: BoolPtr(false)}, + wantHasOverride: true, + wantExplicitTrue: false, + wantExplicitFalse: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.cfg.HasEnabledOverride(); got != tt.wantHasOverride { + t.Errorf("HasEnabledOverride() = %v, want %v", got, tt.wantHasOverride) + } + if got := tt.cfg.IsExplicitlyEnabled(); got != tt.wantExplicitTrue { + t.Errorf("IsExplicitlyEnabled() = %v, want %v", got, tt.wantExplicitTrue) + } + if got := tt.cfg.IsExplicitlyDisabled(); got != tt.wantExplicitFalse { + t.Errorf("IsExplicitlyDisabled() = %v, want %v", got, tt.wantExplicitFalse) + } + }) + } +} diff --git a/internal/config/merge.go b/internal/config/merge.go index 9373f36f2..d155f215d 100644 --- a/internal/config/merge.go +++ b/internal/config/merge.go @@ -498,6 +498,15 @@ func MergeIsolationConfig(base, patch *IsolationConfig, removeIfNil bool) *Isola result.Enabled = patch.Enabled } + // Mode (*IsolationMode) has the same tri-state semantics as Enabled: nil + // means "not set in the patch", so only a non-nil value overrides. Missing + // this case silently dropped the per-server isolation mode on every + // unrelated patch (GH #1142). + if patch.Mode != nil { + mode := *patch.Mode + result.Mode = &mode + } + if patch.Image != "" { result.Image = patch.Image } @@ -692,6 +701,14 @@ func CopyServerConfig(src *ServerConfig) *ServerConfig { return dst } +// CopyIsolationConfig returns a deep copy of an isolation override set, or nil +// for a nil input. Exported so the REST PATCH seam can start from the persisted +// overrides and apply only the fields the request actually carried, instead of +// dropping the ones it does not expose (GH #1142). +func CopyIsolationConfig(src *IsolationConfig) *IsolationConfig { + return copyIsolationConfig(src) +} + func copyIsolationConfig(src *IsolationConfig) *IsolationConfig { if src == nil { return nil @@ -712,6 +729,13 @@ func copyIsolationConfig(src *IsolationConfig) *IsolationConfig { dst.Enabled = &enabled } + // Same for *IsolationMode — copying the pointer would alias the source and + // let a later in-place edit leak across configs. + if src.Mode != nil { + mode := *src.Mode + dst.Mode = &mode + } + if src.ExtraArgs != nil { dst.ExtraArgs = make([]string, len(src.ExtraArgs)) copy(dst.ExtraArgs, src.ExtraArgs) diff --git a/internal/config/merge_test.go b/internal/config/merge_test.go index f2ad83e57..d3585289c 100644 --- a/internal/config/merge_test.go +++ b/internal/config/merge_test.go @@ -1235,3 +1235,76 @@ func TestMergeServerConfig_PreservesDisabledToolsOnUnrelatedPatch(t *testing.T) t.Errorf("DisabledTools dropped on unrelated patch: got %v, want [danger]", merged.DisabledTools) } } + +// TestMergeIsolationConfig_PreservesMode is a regression test for GH #1142: +// copyIsolationConfig and MergeIsolationConfig both ignored IsolationConfig.Mode, +// so patching any unrelated isolation field silently dropped the per-server +// isolation mode — the primary MCP-34.2 override. +func TestMergeIsolationConfig_PreservesMode(t *testing.T) { + sandbox := IsolationModeSandbox + base := &IsolationConfig{Mode: &sandbox, Image: "old"} + patch := &IsolationConfig{Image: "new"} + + merged := MergeIsolationConfig(base, patch, false) + if merged == nil { + t.Fatal("MergeIsolationConfig returned nil") + } + if merged.Mode == nil { + t.Fatalf("Mode was dropped by the merge (got nil, want %q)", sandbox) + } + if *merged.Mode != sandbox { + t.Errorf("Mode = %q, want %q", *merged.Mode, sandbox) + } + if merged.Image != "new" { + t.Errorf("Image = %q, want %q", merged.Image, "new") + } + // The copy must not alias the base pointer. + if merged.Mode == base.Mode { + t.Error("Mode pointer is aliased with base; copyIsolationConfig must deep-copy it") + } +} + +// TestMergeIsolationConfig_PatchModeWins pins the override direction: an +// explicit Mode on the patch replaces the base, and a nil Mode leaves it alone. +func TestMergeIsolationConfig_PatchModeWins(t *testing.T) { + sandbox := IsolationModeSandbox + docker := IsolationModeDocker + + base := &IsolationConfig{Mode: &sandbox} + merged := MergeIsolationConfig(base, &IsolationConfig{Mode: &docker}, false) + if merged.Mode == nil || *merged.Mode != docker { + t.Errorf("patch Mode should win: got %v, want %q", merged.Mode, docker) + } + + // base-only copy path (patch == nil, removeIfNil false) + copied := MergeIsolationConfig(base, nil, false) + if copied.Mode == nil || *copied.Mode != sandbox { + t.Errorf("copy path dropped Mode: got %v, want %q", copied.Mode, sandbox) + } + + // patch-only copy path (base == nil) + fromPatch := MergeIsolationConfig(nil, &IsolationConfig{Mode: &docker}, false) + if fromPatch.Mode == nil || *fromPatch.Mode != docker { + t.Errorf("patch-only path dropped Mode: got %v, want %q", fromPatch.Mode, docker) + } +} + +// TestMergeServerConfig_PreservesIsolationMode is the end-to-end version of the +// above through the ServerConfig merge that the MCP `upstream_servers patch` +// path uses. +func TestMergeServerConfig_PreservesIsolationMode(t *testing.T) { + sandbox := IsolationModeSandbox + base := &ServerConfig{Name: "srv", Isolation: &IsolationConfig{Mode: &sandbox}} + patch := &ServerConfig{Isolation: &IsolationConfig{Image: "python:3.12"}} + + merged, _, err := MergeServerConfig(base, patch, DefaultMergeOptions()) + if err != nil { + t.Fatalf("MergeServerConfig: %v", err) + } + if merged.Isolation == nil || merged.Isolation.Mode == nil { + t.Fatalf("isolation.mode dropped by an unrelated patch: %+v", merged.Isolation) + } + if *merged.Isolation.Mode != sandbox { + t.Errorf("isolation.mode = %q, want %q", *merged.Isolation.Mode, sandbox) + } +} diff --git a/internal/contracts/converters.go b/internal/contracts/converters.go index 87a3db219..099a822ac 100644 --- a/internal/contracts/converters.go +++ b/internal/contracts/converters.go @@ -8,8 +8,13 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" ) -// ConvertServerConfig converts a config.ServerConfig to a contracts.Server -func ConvertServerConfig(cfg *config.ServerConfig, status string, connected bool, toolCount int, authenticated bool) *Server { +// ConvertServerConfig converts a config.ServerConfig to a contracts.Server. +// +// globalIsolation is the global docker_isolation block; it is required to +// resolve the EFFECTIVE isolation state, which is what `isolation.enabled` +// reports on the wire (GH #1142). Pass nil only when no global config exists — +// that resolves to "no isolation", the same answer the spawn path gives. +func ConvertServerConfig(cfg *config.ServerConfig, globalIsolation *config.DockerIsolationConfig, status string, connected bool, toolCount int, authenticated bool) *Server { server := &Server{ ID: cfg.Name, Name: cfg.Name, @@ -63,22 +68,65 @@ func ConvertServerConfig(cfg *config.ServerConfig, status string, connected bool } } - // Convert isolation config if present. The per-server overrides that - // actually live on config.IsolationConfig are Image/NetworkMode/ - // ExtraArgs/WorkingDir; MemoryLimit/CPULimit/Timeout are still only - // available at the global DockerIsolationConfig level, so they stay - // empty here until that refactor lands. - if cfg.Isolation != nil { - server.Isolation = &IsolationConfig{ - Enabled: cfg.Isolation.IsEnabled(), - Image: cfg.Isolation.Image, - NetworkMode: cfg.Isolation.NetworkMode, - ExtraArgs: append([]string(nil), cfg.Isolation.ExtraArgs...), - WorkingDir: cfg.Isolation.WorkingDir, + // Convert isolation config. The per-server overrides that actually live on + // config.IsolationConfig are Enabled/Mode/Image/NetworkMode/ExtraArgs/ + // WorkingDir; MemoryLimit/CPULimit/Timeout are still only available at the + // global DockerIsolationConfig level, so they stay empty here until that + // refactor lands. + // + // `Enabled` on the wire is the EFFECTIVE state, so it needs the global + // config to resolve; the raw tri-state override travels alongside it. + server.Isolation, server.IsolationEffective = BuildIsolationView(globalIsolation, cfg) + + return server +} + +// BuildIsolationView projects a server's isolation configuration onto the wire +// types: the override block (raw tri-state preserved) and the resolved +// effective state. +// +// Both are emitted for every stdio server, even one with no `isolation` block +// at all — a client that reads `isolation?.enabled` must get a real answer for +// an inheriting server rather than the absence that used to read as "off" +// (GH #1142). Servers with no local command carry neither. +func BuildIsolationView(globalIsolation *config.DockerIsolationConfig, cfg *config.ServerConfig) (*IsolationConfig, *IsolationEffective) { + if cfg == nil { + return nil, nil + } + // A server with no local command has no child process to isolate, so the + // block is meaningless — unless it carries a stale override the operator + // should still be able to see and clear. + if cfg.Command == "" && cfg.Isolation == nil { + return nil, nil + } + + resolved := config.ResolveIsolation(globalIsolation, cfg) + + iso := &IsolationConfig{Enabled: resolved.Isolated} + if src := cfg.Isolation; src != nil { + if src.Enabled != nil { + // Copy the value: the wire type must not alias the config pointer. + iso.EnabledOverride = config.BoolPtr(*src.Enabled) + } + if src.Mode != nil { + iso.ModeOverride = string(*src.Mode) } + iso.Image = src.Image + iso.NetworkMode = src.NetworkMode + if len(src.ExtraArgs) > 0 { + iso.ExtraArgs = append([]string(nil), src.ExtraArgs...) + } + iso.WorkingDir = src.WorkingDir } - return server + eff := &IsolationEffective{ + Mode: string(resolved.Mode), + Isolated: resolved.Isolated, + GlobalMode: string(resolved.GlobalMode), + Inherited: resolved.Inherited, + Source: resolved.Source, + } + return iso, eff } // ConvertToolMetadata converts a config.ToolMetadata to a contracts.Tool diff --git a/internal/contracts/converters_test.go b/internal/contracts/converters_test.go index 4f01142f1..0a9940ad6 100644 --- a/internal/contracts/converters_test.go +++ b/internal/contracts/converters_test.go @@ -189,13 +189,13 @@ func TestConvertServerConfig_SourceRegistry(t *testing.T) { SourceRegistryProvenance: config.RegistryProvenanceCustom, } - server := ConvertServerConfig(cfg, "ready", true, 3, false) + server := ConvertServerConfig(cfg, nil, "ready", true, 3, false) require.NotNil(t, server) assert.Equal(t, "modelcontextprotocol", server.SourceRegistryID) assert.Equal(t, config.RegistryProvenanceCustom, server.SourceRegistryProvenance) // Manual server (no source registry) leaves both empty. - manual := ConvertServerConfig(&config.ServerConfig{Name: "manual", Enabled: true}, "ready", true, 0, false) + manual := ConvertServerConfig(&config.ServerConfig{Name: "manual", Enabled: true}, nil, "ready", true, 0, false) assert.Empty(t, manual.SourceRegistryID) assert.Empty(t, manual.SourceRegistryProvenance) } @@ -229,11 +229,11 @@ func TestConvertGenericServersToTyped_AutoApproveToolChanges(t *testing.T) { func TestConvertServerConfig_AutoApproveToolChanges(t *testing.T) { on := true cfg := &config.ServerConfig{Name: "on", Enabled: true, AutoApproveToolChanges: &on} - server := ConvertServerConfig(cfg, "ready", true, 0, false) + server := ConvertServerConfig(cfg, nil, "ready", true, 0, false) require.NotNil(t, server.AutoApproveToolChanges) assert.True(t, *server.AutoApproveToolChanges) - unset := ConvertServerConfig(&config.ServerConfig{Name: "unset", Enabled: true}, "ready", true, 0, false) + unset := ConvertServerConfig(&config.ServerConfig{Name: "unset", Enabled: true}, nil, "ready", true, 0, false) assert.Nil(t, unset.AutoApproveToolChanges) } @@ -243,11 +243,11 @@ func TestConvertServerConfig_AutoApproveToolChanges(t *testing.T) { func TestConvertServerConfig_InitTimeout(t *testing.T) { it := config.Duration(120 * time.Second) cfg := &config.ServerConfig{Name: "slack", Enabled: true, InitTimeout: &it} - server := ConvertServerConfig(cfg, "ready", true, 0, false) + server := ConvertServerConfig(cfg, nil, "ready", true, 0, false) require.NotNil(t, server.InitTimeout) assert.Equal(t, 120*time.Second, server.InitTimeout.Duration()) - unset := ConvertServerConfig(&config.ServerConfig{Name: "unset", Enabled: true}, "ready", true, 0, false) + unset := ConvertServerConfig(&config.ServerConfig{Name: "unset", Enabled: true}, nil, "ready", true, 0, false) assert.Nil(t, unset.InitTimeout, "unset init_timeout must stay nil") generic := ConvertGenericServersToTyped([]map[string]interface{}{ @@ -337,7 +337,7 @@ func TestConvertServerConfig_ConcurrencyOverrides(t *testing.T) { QueueSize: &queueSize, QueueTimeout: &qt, } - server := ConvertServerConfig(cfg, "ready", true, 0, false) + server := ConvertServerConfig(cfg, nil, "ready", true, 0, false) require.NotNil(t, server.MaxConcurrentRequests) assert.Equal(t, 5, *server.MaxConcurrentRequests) require.NotNil(t, server.QueueSize) @@ -345,13 +345,13 @@ func TestConvertServerConfig_ConcurrencyOverrides(t *testing.T) { require.NotNil(t, server.QueueTimeout) assert.Equal(t, 45*time.Second, server.QueueTimeout.Duration()) - unset := ConvertServerConfig(&config.ServerConfig{Name: "unset", Enabled: true}, "ready", true, 0, false) + unset := ConvertServerConfig(&config.ServerConfig{Name: "unset", Enabled: true}, nil, "ready", true, 0, false) assert.Nil(t, unset.MaxConcurrentRequests, "absent must stay nil so the server inherits the default set") assert.Nil(t, unset.QueueSize) assert.Nil(t, unset.QueueTimeout) optOut := 0 - disabled := ConvertServerConfig(&config.ServerConfig{Name: "off", Enabled: true, MaxConcurrentRequests: &optOut}, "ready", true, 0, false) + disabled := ConvertServerConfig(&config.ServerConfig{Name: "off", Enabled: true, MaxConcurrentRequests: &optOut}, nil, "ready", true, 0, false) require.NotNil(t, disabled.MaxConcurrentRequests, "an explicit 0 opt-out must survive the conversion") assert.Equal(t, 0, *disabled.MaxConcurrentRequests) @@ -371,3 +371,64 @@ func TestConvertServerConfig_ConcurrencyOverrides(t *testing.T) { assert.Nil(t, generic[1].QueueSize) assert.Nil(t, generic[1].QueueTimeout) } + +// TestBuildIsolationView_TriState pins the wire projection at the contracts +// boundary (GH #1142): `enabled` reports the EFFECTIVE state, the raw +// per-server override travels alongside as a tri-state, and every stdio server +// gets a block even with no override configured. +func TestBuildIsolationView_TriState(t *testing.T) { + global := &config.DockerIsolationConfig{Enabled: true} + stdio := func(iso *config.IsolationConfig) *config.ServerConfig { + return &config.ServerConfig{Name: "srv", Protocol: "stdio", Command: "uvx", Isolation: iso} + } + + t.Run("inherit reports isolated with no raw override", func(t *testing.T) { + iso, eff := BuildIsolationView(global, stdio(&config.IsolationConfig{Image: "python:3.12"})) + require.NotNil(t, iso) + assert.True(t, iso.Enabled) + assert.Nil(t, iso.EnabledOverride) + require.NotNil(t, eff) + assert.True(t, eff.Inherited) + assert.Equal(t, "docker", eff.Mode) + }) + + t.Run("no isolation block still yields a view", func(t *testing.T) { + iso, eff := BuildIsolationView(global, stdio(nil)) + require.NotNil(t, iso) + assert.True(t, iso.Enabled) + require.NotNil(t, eff) + assert.True(t, eff.Inherited) + }) + + t.Run("explicit opt-out is readable and effective", func(t *testing.T) { + iso, eff := BuildIsolationView(global, stdio(&config.IsolationConfig{Enabled: config.BoolPtr(false)})) + require.NotNil(t, iso) + assert.False(t, iso.Enabled) + require.NotNil(t, iso.EnabledOverride) + assert.False(t, *iso.EnabledOverride) + assert.False(t, eff.Inherited) + assert.Equal(t, config.IsolationSourceServerOptOut, eff.Source) + }) + + t.Run("override pointer does not alias the config", func(t *testing.T) { + src := &config.IsolationConfig{Enabled: config.BoolPtr(true)} + iso, _ := BuildIsolationView(global, stdio(src)) + require.NotNil(t, iso.EnabledOverride) + assert.NotSame(t, src.Enabled, iso.EnabledOverride) + }) + + t.Run("http server has no isolation block", func(t *testing.T) { + iso, eff := BuildIsolationView(global, &config.ServerConfig{ + Name: "remote", Protocol: "http", URL: "https://example.com/mcp", + }) + assert.Nil(t, iso) + assert.Nil(t, eff) + }) + + t.Run("nil global resolves to unisolated", func(t *testing.T) { + iso, eff := BuildIsolationView(nil, stdio(nil)) + require.NotNil(t, iso) + assert.False(t, iso.Enabled) + assert.Equal(t, "none", eff.Mode) + }) +} diff --git a/internal/contracts/types.go b/internal/contracts/types.go index 6f155a4f7..d695a25d4 100644 --- a/internal/contracts/types.go +++ b/internal/contracts/types.go @@ -44,17 +44,21 @@ type Server struct { // would apply when no per-server override is set. Populated on // list/get responses; never consumed on PATCH requests. IsolationDefaults *IsolationDefaults `json:"isolation_defaults,omitempty"` - Authenticated bool `json:"authenticated"` // OAuth authentication status - OAuthStatus string `json:"oauth_status,omitempty"` // OAuth status: "authenticated", "expired", "error", "none" - TokenExpiresAt *time.Time `json:"token_expires_at,omitempty"` // When the OAuth token expires (ISO 8601) - ToolListTokenSize int `json:"tool_list_token_size,omitempty"` // Token size for this server's tools - ShouldRetry bool `json:"should_retry,omitempty"` - RetryCount int `json:"retry_count,omitempty"` - LastRetryTime *time.Time `json:"last_retry_time,omitempty"` - UserLoggedOut bool `json:"user_logged_out,omitempty"` // True if user explicitly logged out (prevents auto-reconnection) - Health *HealthStatus `json:"health,omitempty"` // Unified health status calculated by the backend - Quarantine *QuarantineStats `json:"quarantine,omitempty"` // Tool quarantine metrics for this server - ReconnectOnUse bool `json:"reconnect_on_use,omitempty"` // Attempt reconnection when a tool call targets this disconnected server + // IsolationEffective exposes the resolved isolation state (and the rule + // that decided it) so clients can distinguish "inherits global" from an + // explicit per-server choice. Read-only; never consumed on PATCH. + IsolationEffective *IsolationEffective `json:"isolation_effective,omitempty"` + Authenticated bool `json:"authenticated"` // OAuth authentication status + OAuthStatus string `json:"oauth_status,omitempty"` // OAuth status: "authenticated", "expired", "error", "none" + TokenExpiresAt *time.Time `json:"token_expires_at,omitempty"` // When the OAuth token expires (ISO 8601) + ToolListTokenSize int `json:"tool_list_token_size,omitempty"` // Token size for this server's tools + ShouldRetry bool `json:"should_retry,omitempty"` + RetryCount int `json:"retry_count,omitempty"` + LastRetryTime *time.Time `json:"last_retry_time,omitempty"` + UserLoggedOut bool `json:"user_logged_out,omitempty"` // True if user explicitly logged out (prevents auto-reconnection) + Health *HealthStatus `json:"health,omitempty"` // Unified health status calculated by the backend + Quarantine *QuarantineStats `json:"quarantine,omitempty"` // Tool quarantine metrics for this server + ReconnectOnUse bool `json:"reconnect_on_use,omitempty"` // Attempt reconnection when a tool call targets this disconnected server // AutoApproveToolChanges mirrors config.ServerConfig.AutoApproveToolChanges // (MCP-2930): the per-server intent to auto-approve new/changed tools past // the trust baseline. Tri-state *bool — nil means "never set" (omitted from @@ -207,14 +211,61 @@ type OAuthConfig struct { // config.IsolationConfig so the web UI and native tray can both edit // these fields without reaching into config-file internals. type IsolationConfig struct { - Enabled bool `json:"enabled"` - Image string `json:"image,omitempty"` - NetworkMode string `json:"network_mode,omitempty"` - ExtraArgs []string `json:"extra_args,omitempty"` - MemoryLimit string `json:"memory_limit,omitempty"` - CPULimit string `json:"cpu_limit,omitempty"` - WorkingDir string `json:"working_dir,omitempty"` - Timeout string `json:"timeout,omitempty"` + // Enabled is the EFFECTIVE isolation state for this server: whether its + // process is actually CONFINED, after the global setting, the per-server + // override, the structural gates and the host's capabilities. It is NOT the + // raw per-server override — read EnabledOverride for that (GH #1142). + // + // READ-ONLY. The write surfaces reject an `enabled` key precisely because + // it is derived: echoing it back would convert "inherits the global + // setting" into a permanent explicit override. Write EnabledOverride. + // + // It stays a non-pointer bool that is always present on the wire: the macOS + // tray decodes it as a non-optional Swift Bool, so omitting or nulling the + // key would fail Codable for the whole server payload. Older clients that + // read this field now simply get a true answer. + Enabled bool `json:"enabled"` + // EnabledOverride is the RAW per-server `isolation.enabled` override, as + // persisted. Absent means "inherit the global setting" — which is a + // distinct state from an explicit false, and the distinction the reporting + // bug used to destroy. + EnabledOverride *bool `json:"enabled_override,omitempty"` + // ModeOverride is the RAW per-server `isolation.mode` override + // ("docker" | "sandbox" | "none"). Absent means "inherit". + ModeOverride string `json:"mode_override,omitempty"` + Image string `json:"image,omitempty"` + NetworkMode string `json:"network_mode,omitempty"` + ExtraArgs []string `json:"extra_args,omitempty"` + MemoryLimit string `json:"memory_limit,omitempty"` + CPULimit string `json:"cpu_limit,omitempty"` + WorkingDir string `json:"working_dir,omitempty"` + Timeout string `json:"timeout,omitempty"` +} + +// IsolationEffective reports the resolved isolation state of a server together +// with the rule that produced it, so a UI can say WHY a server is (or is not) +// isolated instead of rendering a bare toggle whose meaning is ambiguous. +// +// Read-only output; clients must not echo it back on PATCH requests. +type IsolationEffective struct { + // Mode is the effective isolation mode: "docker" | "sandbox" | "none" — + // exactly what the spawn path branches on. + Mode string `json:"mode"` + // Isolated reports whether the process is actually CONFINED. It is NOT + // simply Mode != "none": "sandbox" on a host that cannot enforce Landlock + // (any non-Linux OS, or a kernel without the LSM) runs the server + // unconfined, and Source then says "sandbox-unavailable" (GH #1142). + Isolated bool `json:"isolated"` + // GlobalMode is what "inherit" resolves to right now. + GlobalMode string `json:"global_mode,omitempty"` + // Inherited is true when the server sets neither `isolation.enabled` nor + // `isolation.mode`, so its state tracks the global setting. + Inherited bool `json:"inherited"` + // Source names the deciding rule: "global", "server-mode", + // "server-opt-out", "server-opt-in-ignored", "not-stdio", + // "already-docker", "sandbox-unavailable" or "unsupported-mode". + // Treat an unrecognized value as "global". + Source string `json:"source,omitempty"` } // IsolationDefaults reports the resolved baseline Docker isolation diff --git a/internal/diagnostics/remediation.go b/internal/diagnostics/remediation.go index 6b550a4b2..9f804687b 100644 --- a/internal/diagnostics/remediation.go +++ b/internal/diagnostics/remediation.go @@ -57,9 +57,11 @@ func RuntimeAwareRemediation(code Code, hints ClassifierHints) string { // // It is a deliberately small, side-effect-free mirror of // core.IsolationManager.DetectRuntimeType (internal/upstream/core/isolation.go) -// — the diagnostics package must not import upstream/core, and (like -// supervisor.usesDockerIsolation mirrors ShouldIsolate) faithfulness for the -// display path matters more than sharing the implementation. Unknown commands +// — the diagnostics package must not import upstream/core, and faithfulness for +// the display path matters more than sharing the implementation. (The sibling +// question, "is this server Docker-isolated at all", is NOT mirrored: +// supervisor.usesDockerIsolation delegates to config.ResolveIsolation, the +// resolver the spawn path branches on.) Unknown commands // fall back to the base command name so the message still names something // concrete rather than a generic "interpreter". func detectDockerRuntimeType(command string) string { diff --git a/internal/httpapi/handlers_test.go b/internal/httpapi/handlers_test.go index eb5b545ec..7b25214e3 100644 --- a/internal/httpapi/handlers_test.go +++ b/internal/httpapi/handlers_test.go @@ -95,7 +95,7 @@ func TestHandleAddServer(t *testing.T) { Command: "/usr/local/bin/mcpfixture", Args: []string{"--transport", "stdio"}, Protocol: "stdio", - Isolation: &IsolationRequest{Enabled: &optOut}, + Isolation: &IsolationRequest{EnabledOverride: NullableBool{Set: true, Value: &optOut}}, } body, _ := json.Marshal(reqBody) @@ -125,7 +125,7 @@ func TestHandleAddServer(t *testing.T) { Command: "/mcpfixture", Args: []string{"--transport", "stdio"}, Protocol: "stdio", - Isolation: &IsolationRequest{Enabled: &on, Image: &image}, + Isolation: &IsolationRequest{EnabledOverride: NullableBool{Set: true, Value: &on}, Image: &image}, } body, _ := json.Marshal(reqBody) diff --git a/internal/httpapi/isolation_request_test.go b/internal/httpapi/isolation_request_test.go index 2309c51dc..735f1a4e2 100644 --- a/internal/httpapi/isolation_request_test.go +++ b/internal/httpapi/isolation_request_test.go @@ -8,17 +8,17 @@ import ( "github.com/stretchr/testify/require" ) -func TestIsolationRequestToConfigNil(t *testing.T) { +func TestIsolationRequestResolveNil(t *testing.T) { var r *IsolationRequest - assert.Nil(t, r.toConfig(), "nil request must produce nil config") + assert.Nil(t, r.resolve(nil), "nil request must produce nil config") } -func TestIsolationRequestToConfigEmpty(t *testing.T) { +func TestIsolationRequestResolveEmpty(t *testing.T) { // An empty-but-present IsolationRequest means "I am touching - // isolation but setting nothing explicitly" — toConfig returns a + // isolation but setting nothing explicitly" — resolve returns a // non-nil struct so the update path can distinguish this from nil. r := &IsolationRequest{} - got := r.toConfig() + got := r.resolve(nil) require.NotNil(t, got) assert.Nil(t, got.Enabled) assert.Empty(t, got.Image) @@ -27,7 +27,7 @@ func TestIsolationRequestToConfigEmpty(t *testing.T) { assert.Empty(t, got.WorkingDir) } -func TestIsolationRequestToConfigAllFields(t *testing.T) { +func TestIsolationRequestResolveAllFields(t *testing.T) { enabled := true image := "python:3.11" networkMode := "bridge" @@ -35,13 +35,13 @@ func TestIsolationRequestToConfigAllFields(t *testing.T) { workingDir := "/vault" r := &IsolationRequest{ - Enabled: &enabled, - Image: &image, - NetworkMode: &networkMode, - ExtraArgs: &extra, - WorkingDir: &workingDir, + EnabledOverride: NullableBool{Set: true, Value: &enabled}, + Image: &image, + NetworkMode: &networkMode, + ExtraArgs: &extra, + WorkingDir: &workingDir, } - got := r.toConfig() + got := r.resolve(nil) require.NotNil(t, got) require.NotNil(t, got.Enabled) assert.True(t, *got.Enabled) @@ -51,30 +51,30 @@ func TestIsolationRequestToConfigAllFields(t *testing.T) { assert.Equal(t, workingDir, got.WorkingDir) } -func TestIsolationRequestToConfigDisabledExplicitly(t *testing.T) { +func TestIsolationRequestResolveDisabledExplicitly(t *testing.T) { // A present enabled:false must produce a pointer to false, not nil // (nil means "do not touch"; false means "set to false"). enabled := false - r := &IsolationRequest{Enabled: &enabled} - got := r.toConfig() + r := &IsolationRequest{EnabledOverride: NullableBool{Set: true, Value: &enabled}} + got := r.resolve(nil) require.NotNil(t, got) require.NotNil(t, got.Enabled) assert.False(t, *got.Enabled) } -func TestIsolationRequestToConfigExtraArgsCopies(t *testing.T) { +func TestIsolationRequestResolveExtraArgsCopies(t *testing.T) { // The resulting slice must not alias the request slice, so later // mutations on the config do not leak back into the request // (matters when the request gets held in memory by a log sink). src := []string{"-v", "/foo:/bar"} r := &IsolationRequest{ExtraArgs: &src} - got := r.toConfig() + got := r.resolve(nil) require.NotNil(t, got) got.ExtraArgs[0] = "mutated" assert.Equal(t, "-v", src[0], "request slice must remain untouched after mutating config copy") } -// Compile-time assertion that toConfig returns *config.IsolationConfig +// Compile-time assertion that resolve returns *config.IsolationConfig // (not contracts.IsolationConfig). Lives outside a test function so // static analysers don't flag the unused LHS inside a test body. -var _ func(*IsolationRequest) *config.IsolationConfig = (*IsolationRequest).toConfig +var _ func(*IsolationRequest, *config.IsolationConfig) *config.IsolationConfig = (*IsolationRequest).resolve diff --git a/internal/httpapi/isolation_tristate_test.go b/internal/httpapi/isolation_tristate_test.go new file mode 100644 index 000000000..926d3717f --- /dev/null +++ b/internal/httpapi/isolation_tristate_test.go @@ -0,0 +1,97 @@ +package httpapi + +import ( + "encoding/json" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestNullableBool_AbsentNullValue pins the three states the PATCH seam needs +// to express for a tri-state override (GH #1142): absent = leave alone, +// null = clear back to "inherit global", true/false = set explicitly. +func TestNullableBool_AbsentNullValue(t *testing.T) { + type body struct { + Enabled NullableBool `json:"enabled"` + } + + tests := []struct { + name string + raw string + wantSet bool + wantValue *bool + }{ + {name: "absent", raw: `{}`, wantSet: false, wantValue: nil}, + {name: "null clears the override", raw: `{"enabled":null}`, wantSet: true, wantValue: nil}, + {name: "explicit true", raw: `{"enabled":true}`, wantSet: true, wantValue: config.BoolPtr(true)}, + {name: "explicit false", raw: `{"enabled":false}`, wantSet: true, wantValue: config.BoolPtr(false)}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var b body + require.NoError(t, json.Unmarshal([]byte(tt.raw), &b)) + assert.Equal(t, tt.wantSet, b.Enabled.Set, "Set") + if tt.wantValue == nil { + assert.Nil(t, b.Enabled.Value, "Value") + } else { + require.NotNil(t, b.Enabled.Value) + assert.Equal(t, *tt.wantValue, *b.Enabled.Value, "Value") + } + }) + } +} + +// TestIsolationRequest_ResolvePreservesUnexposed proves that resolving a patch +// against the persisted overrides keeps the fields IsolationRequest does not +// expose (mode, log driver/size/files) instead of dropping them. +func TestIsolationRequest_ResolvePreservesUnexposed(t *testing.T) { + sandbox := config.IsolationModeSandbox + existing := &config.IsolationConfig{ + Enabled: config.BoolPtr(true), + Mode: &sandbox, + Image: "old-image", + LogDriver: "local", + LogMaxSize: "10m", + LogMaxFiles: "5", + } + newImage := "new-image" + req := &IsolationRequest{Image: &newImage} + + out := req.resolve(existing) + require.NotNil(t, out) + assert.Equal(t, "new-image", out.Image) + require.NotNil(t, out.Enabled, "an untouched enabled override must survive") + assert.True(t, *out.Enabled) + require.NotNil(t, out.Mode) + assert.Equal(t, sandbox, *out.Mode) + assert.Equal(t, "local", out.LogDriver) + assert.Equal(t, "10m", out.LogMaxSize) + assert.Equal(t, "5", out.LogMaxFiles) + // The result must not alias the persisted config. + assert.NotSame(t, existing, out) + assert.NotSame(t, existing.Enabled, out.Enabled) +} + +// TestIsolationRequest_ResolveClearsOverride pins the "back to inherit" path. +func TestIsolationRequest_ResolveClearsOverride(t *testing.T) { + existing := &config.IsolationConfig{Enabled: config.BoolPtr(false), Image: "img"} + req := &IsolationRequest{EnabledOverride: NullableBool{Set: true, Value: nil}} + + out := req.resolve(existing) + require.NotNil(t, out) + assert.Nil(t, out.Enabled, "an explicit null must clear the override back to inherit") + assert.Equal(t, "img", out.Image, "unrelated fields survive") +} + +// TestIsolationRequest_ResolveSetsExplicit covers the ordinary set path. +func TestIsolationRequest_ResolveSetsExplicit(t *testing.T) { + req := &IsolationRequest{EnabledOverride: NullableBool{Set: true, Value: config.BoolPtr(false)}} + out := req.resolve(nil) + require.NotNil(t, out) + require.NotNil(t, out.Enabled) + assert.False(t, *out.Enabled) +} diff --git a/internal/httpapi/isolation_write_contract_test.go b/internal/httpapi/isolation_write_contract_test.go new file mode 100644 index 000000000..137425f6c --- /dev/null +++ b/internal/httpapi/isolation_write_contract_test.go @@ -0,0 +1,228 @@ +package httpapi + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" +) + +// isolationPatch drives PATCH /api/v1/servers/{name} with an `isolation` body +// against a mock controller, and returns the response plus whatever the +// handler tried to persist. +func isolationPatch(t *testing.T, existing *config.ServerConfig, iso map[string]any) (*httptest.ResponseRecorder, *mockPatchServerController) { + t.Helper() + mockCtrl := &mockPatchServerController{apiKey: "test-key", existingServer: existing} + srv := NewServer(mockCtrl, zap.NewNop().Sugar(), nil) + + body, err := json.Marshal(map[string]any{"isolation": iso}) + require.NoError(t, err) + req := httptest.NewRequest(http.MethodPatch, "/api/v1/servers/"+existing.Name, bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-API-Key", "test-key") + w := httptest.NewRecorder() + srv.ServeHTTP(w, req) + return w, mockCtrl +} + +// TestPatchServer_RejectsUnknownIsolationMode is the defect this handler had +// no guard for: `mode_override` was cast straight to config.IsolationMode, so +// a typo was persisted to BBolt and the config file, and the NEXT daemon start +// failed config validation with a file the operator never hand-edited. +func TestPatchServer_RejectsUnknownIsolationMode(t *testing.T) { + existing := &config.ServerConfig{Name: "github", Protocol: "stdio", Command: "npx", Enabled: true} + + for _, bad := range []string{"bogus", "Docker", "docker ", "SANDBOX"} { + t.Run(bad, func(t *testing.T) { + w, mockCtrl := isolationPatch(t, existing, map[string]any{"mode_override": bad}) + + require.Equal(t, http.StatusBadRequest, w.Code, + "an unknown isolation mode must be rejected at the seam, body=%s", w.Body.String()) + assert.Nil(t, mockCtrl.capturedUpdates, "nothing may be persisted for a rejected mode") + + body := w.Body.String() + for _, want := range []string{"docker", "sandbox", "none"} { + assert.Contains(t, body, want, "the 400 must name the accepted vocabulary") + } + }) + } +} + +// TestPatchServer_AcceptsKnownIsolationModes guards against over-rejecting. +func TestPatchServer_AcceptsKnownIsolationModes(t *testing.T) { + existing := &config.ServerConfig{Name: "github", Protocol: "stdio", Command: "npx", Enabled: true} + + for _, good := range []string{"docker", "sandbox", "none"} { + t.Run(good, func(t *testing.T) { + w, mockCtrl := isolationPatch(t, existing, map[string]any{"mode_override": good}) + require.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String()) + require.NotNil(t, mockCtrl.capturedUpdates) + require.NotNil(t, mockCtrl.capturedUpdates.Isolation) + require.NotNil(t, mockCtrl.capturedUpdates.Isolation.Mode) + assert.Equal(t, config.IsolationMode(good), *mockCtrl.capturedUpdates.Isolation.Mode) + }) + } +} + +// TestPatchServer_EmptyModeOverrideClears keeps the documented "clear the +// override" path working alongside the new validation. +func TestPatchServer_EmptyModeOverrideClears(t *testing.T) { + sandbox := config.IsolationModeSandbox + existing := &config.ServerConfig{ + Name: "github", Protocol: "stdio", Command: "npx", Enabled: true, + Isolation: &config.IsolationConfig{Mode: &sandbox}, + } + + w, mockCtrl := isolationPatch(t, existing, map[string]any{"mode_override": ""}) + require.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String()) + require.NotNil(t, mockCtrl.capturedUpdates) + require.NotNil(t, mockCtrl.capturedUpdates.Isolation) + assert.Nil(t, mockCtrl.capturedUpdates.Isolation.Mode, `"" must clear the mode override back to inherit`) +} + +// TestAddServer_RejectsUnknownIsolationMode covers the same seam on create. +func TestAddServer_RejectsUnknownIsolationMode(t *testing.T) { + mockCtrl := &mockAddServerController{apiKey: "test-key"} + srv := NewServer(mockCtrl, zap.NewNop().Sugar(), nil) + + body, err := json.Marshal(map[string]any{ + "name": "new-server", + "command": "npx", + "isolation": map[string]any{"mode_override": "bogus"}, + }) + require.NoError(t, err) + req := httptest.NewRequest(http.MethodPost, "/api/v1/servers", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-API-Key", "test-key") + w := httptest.NewRecorder() + srv.ServeHTTP(w, req) + + require.Equal(t, http.StatusBadRequest, w.Code, "body=%s", w.Body.String()) + assert.Contains(t, w.Body.String(), "sandbox") +} + +// TestPatchServer_IsolationEnabledIsReadOnly is the read/write coherence guard +// (GH #1142). `isolation.enabled` on a READ is the EFFECTIVE state; the write +// path used to decode the same key into the RAW tri-state override. Any +// read-modify-write client — GET the server, PATCH the isolation object back — +// therefore converted "inherits the global setting" into a permanent explicit +// override, which is the original bug arriving from the other direction. +// +// The write key is `enabled_override`; `enabled` is rejected rather than +// silently applied or silently dropped. +func TestPatchServer_IsolationEnabledIsReadOnly(t *testing.T) { + existing := &config.ServerConfig{ + Name: "github", Protocol: "stdio", Command: "npx", Enabled: true, + // An operator's standing "always isolate this one". + Isolation: &config.IsolationConfig{Enabled: config.BoolPtr(true)}, + } + + for _, echoed := range []any{true, false, nil} { + t.Run(fmt.Sprintf("echoed %v", echoed), func(t *testing.T) { + w, mockCtrl := isolationPatch(t, existing, map[string]any{"enabled": echoed}) + + require.Equal(t, http.StatusBadRequest, w.Code, + "isolation.enabled is read-only on writes, body=%s", w.Body.String()) + assert.Nil(t, mockCtrl.capturedUpdates, "a rejected request must not persist anything") + assert.Contains(t, w.Body.String(), "enabled_override", + "the 400 must name the field the client should use instead") + }) + } +} + +// TestPatchServer_EnabledOverrideTriState pins the write key's three states. +func TestPatchServer_EnabledOverrideTriState(t *testing.T) { + newExisting := func() *config.ServerConfig { + return &config.ServerConfig{ + Name: "github", Protocol: "stdio", Command: "npx", Enabled: true, + Isolation: &config.IsolationConfig{Enabled: config.BoolPtr(true), Image: "python:3.12"}, + } + } + + t.Run("absent leaves the persisted override alone", func(t *testing.T) { + w, mockCtrl := isolationPatch(t, newExisting(), map[string]any{"image": "python:3.13"}) + require.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String()) + require.NotNil(t, mockCtrl.capturedUpdates.Isolation) + require.NotNil(t, mockCtrl.capturedUpdates.Isolation.Enabled, + "an unrelated field edit must not drop the standing opt-in") + assert.True(t, *mockCtrl.capturedUpdates.Isolation.Enabled) + }) + + t.Run("null clears back to inherit", func(t *testing.T) { + w, mockCtrl := isolationPatch(t, newExisting(), map[string]any{"enabled_override": nil}) + require.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String()) + require.NotNil(t, mockCtrl.capturedUpdates.Isolation) + assert.Nil(t, mockCtrl.capturedUpdates.Isolation.Enabled) + }) + + t.Run("false sets an explicit opt-out", func(t *testing.T) { + w, mockCtrl := isolationPatch(t, newExisting(), map[string]any{"enabled_override": false}) + require.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String()) + require.NotNil(t, mockCtrl.capturedUpdates.Isolation) + require.NotNil(t, mockCtrl.capturedUpdates.Isolation.Enabled) + assert.False(t, *mockCtrl.capturedUpdates.Isolation.Enabled) + }) +} + +// TestAddServer_EnabledOverrideOnCreate keeps the create-time opt-in reachable +// under the new key. +func TestAddServer_EnabledOverrideOnCreate(t *testing.T) { + mockCtrl := &mockAddServerController{apiKey: "test-key"} + srv := NewServer(mockCtrl, zap.NewNop().Sugar(), nil) + + body, err := json.Marshal(map[string]any{ + "name": "new-server", + "command": "npx", + "isolation": map[string]any{"enabled_override": true}, + }) + require.NoError(t, err) + req := httptest.NewRequest(http.MethodPost, "/api/v1/servers", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-API-Key", "test-key") + w := httptest.NewRecorder() + srv.ServeHTTP(w, req) + + require.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String()) + require.NotNil(t, mockCtrl.captured, "AddServer should have been called") + require.NotNil(t, mockCtrl.captured.Isolation) + require.NotNil(t, mockCtrl.captured.Isolation.Enabled) + assert.True(t, *mockCtrl.captured.Isolation.Enabled) +} + +// TestIsolationRequest_EnabledIsNeverWritable is the contract guard in one +// place: no key the read surface emits as a DERIVED value may also mutate +// state on the way back in. `enabled` must be refused by validate() and, if a +// call site ever forgets to call it, must still be inert in resolve(). +func TestIsolationRequest_EnabledIsNeverWritable(t *testing.T) { + var req IsolationRequest + require.NoError(t, json.Unmarshal([]byte(`{"enabled":false}`), &req)) + require.Error(t, req.validate(), "`enabled` must be rejected on writes") + + // Defense in depth: even unvalidated, it cannot rewrite the override. + existing := &config.IsolationConfig{Enabled: config.BoolPtr(true)} + out := req.resolve(existing) + require.NotNil(t, out.Enabled) + assert.True(t, *out.Enabled, "`enabled` must not reach the persisted override") +} + +// TestIsolationRequest_UnsetFieldsMarshalAway guards the re-encode trap: an +// untouched request must not serialize `enabled_override: null`, because that +// is the CLEAR-the-override shape on the way back in. +func TestIsolationRequest_UnsetFieldsMarshalAway(t *testing.T) { + raw, err := json.Marshal(IsolationRequest{}) + require.NoError(t, err) + assert.JSONEq(t, `{}`, string(raw)) + + raw, err = json.Marshal(IsolationRequest{EnabledOverride: NullableBool{Set: true}}) + require.NoError(t, err) + assert.JSONEq(t, `{"enabled_override":null}`, string(raw), + "an explicit clear must still round-trip as null") +} diff --git a/internal/httpapi/patch_server_test.go b/internal/httpapi/patch_server_test.go index b069c5b84..f9157d5ea 100644 --- a/internal/httpapi/patch_server_test.go +++ b/internal/httpapi/patch_server_test.go @@ -6,6 +6,7 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "strconv" "strings" "testing" "time" @@ -1017,3 +1018,139 @@ func TestHandlePatchServer_ExposePrompts(t *testing.T) { assert.True(t, *mockCtrl.capturedUpdates.ExposePrompts) }) } + +// TestHandlePatchServer_ImageOnlyDoesNotWriteEnabled is THE corruption +// regression test for GH #1142. The macOS tray seeded its isolation toggle +// from the flattened `enabled:false` the API reported for an INHERITING +// server, then force-added `enabled` to every isolation PATCH. Editing an +// unrelated field (the image) therefore persisted an explicit opt-out and +// silently un-containerised a server the user never meant to expose. +// +// The handler must leave a nil override nil when the request does not mention +// `enabled` at all. +func TestHandlePatchServer_ImageOnlyDoesNotWriteEnabled(t *testing.T) { + logger := zap.NewNop().Sugar() + mockCtrl := &mockPatchServerController{ + apiKey: "test-key", + existingServer: &config.ServerConfig{ + Name: "python-mcp", + Protocol: "stdio", + Command: "uvx", + Enabled: true, + // Enabled override deliberately nil: "inherit the global setting". + Isolation: &config.IsolationConfig{Image: "python:3.11"}, + }, + } + srv := NewServer(mockCtrl, logger, nil) + + body := []byte(`{"isolation":{"image":"python:3.12"}}`) + req := httptest.NewRequest(http.MethodPatch, "/api/v1/servers/python-mcp", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-API-Key", "test-key") + w := httptest.NewRecorder() + + srv.ServeHTTP(w, req) + + require.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String()) + require.NotNil(t, mockCtrl.capturedUpdates) + require.NotNil(t, mockCtrl.capturedUpdates.Isolation) + + assert.Equal(t, "python:3.12", mockCtrl.capturedUpdates.Isolation.Image) + assert.Nil(t, mockCtrl.capturedUpdates.Isolation.Enabled, + "a PATCH that never mentions `enabled` must not write an explicit opt-out") +} + +// TestHandlePatchServer_ExplicitNullClearsIsolationOverride pins the "go back +// to inheriting the global setting" path — previously inexpressible, because +// an omitted field and a cleared field were the same wire shape. +func TestHandlePatchServer_ExplicitNullClearsIsolationOverride(t *testing.T) { + logger := zap.NewNop().Sugar() + mockCtrl := &mockPatchServerController{ + apiKey: "test-key", + existingServer: &config.ServerConfig{ + Name: "python-mcp", Protocol: "stdio", Command: "uvx", Enabled: true, + Isolation: &config.IsolationConfig{Enabled: config.BoolPtr(false)}, + }, + } + srv := NewServer(mockCtrl, logger, nil) + + body := []byte(`{"isolation":{"enabled_override":null}}`) + req := httptest.NewRequest(http.MethodPatch, "/api/v1/servers/python-mcp", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-API-Key", "test-key") + w := httptest.NewRecorder() + + srv.ServeHTTP(w, req) + + require.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String()) + require.NotNil(t, mockCtrl.capturedUpdates) + require.NotNil(t, mockCtrl.capturedUpdates.Isolation) + assert.Nil(t, mockCtrl.capturedUpdates.Isolation.Enabled, + "an explicit null must clear the override back to inherit") +} + +// TestHandlePatchServer_ExplicitIsolationEnabledStillApplies guards against +// over-correcting: a caller that really does want an explicit opt-out must +// still get one. +func TestHandlePatchServer_ExplicitIsolationEnabledStillApplies(t *testing.T) { + logger := zap.NewNop().Sugar() + for _, want := range []bool{true, false} { + mockCtrl := &mockPatchServerController{ + apiKey: "test-key", + existingServer: &config.ServerConfig{ + Name: "python-mcp", Protocol: "stdio", Command: "uvx", Enabled: true, + }, + } + srv := NewServer(mockCtrl, logger, nil) + + body := []byte(`{"isolation":{"enabled_override":` + strconv.FormatBool(want) + `}}`) + req := httptest.NewRequest(http.MethodPatch, "/api/v1/servers/python-mcp", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-API-Key", "test-key") + w := httptest.NewRecorder() + + srv.ServeHTTP(w, req) + + require.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String()) + require.NotNil(t, mockCtrl.capturedUpdates.Isolation) + require.NotNil(t, mockCtrl.capturedUpdates.Isolation.Enabled) + assert.Equal(t, want, *mockCtrl.capturedUpdates.Isolation.Enabled) + } +} + +// TestHandlePatchServer_IsolationPreservesUnexposedFields pins the contract +// that lets Server.UpdateServer replace the isolation block wholesale: the +// handler resolves the patch against the persisted overrides, so fields the +// REST request cannot express (mode, log driver) survive. +func TestHandlePatchServer_IsolationPreservesUnexposedFields(t *testing.T) { + logger := zap.NewNop().Sugar() + sandbox := config.IsolationModeSandbox + mockCtrl := &mockPatchServerController{ + apiKey: "test-key", + existingServer: &config.ServerConfig{ + Name: "python-mcp", Protocol: "stdio", Command: "uvx", Enabled: true, + Isolation: &config.IsolationConfig{ + Mode: &sandbox, + LogDriver: "local", + Image: "old", + }, + }, + } + srv := NewServer(mockCtrl, logger, nil) + + body := []byte(`{"isolation":{"image":"new"}}`) + req := httptest.NewRequest(http.MethodPatch, "/api/v1/servers/python-mcp", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-API-Key", "test-key") + w := httptest.NewRecorder() + + srv.ServeHTTP(w, req) + + require.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String()) + iso := mockCtrl.capturedUpdates.Isolation + require.NotNil(t, iso) + assert.Equal(t, "new", iso.Image) + require.NotNil(t, iso.Mode, "isolation.mode is not exposed by the REST request and must survive") + assert.Equal(t, sandbox, *iso.Mode) + assert.Equal(t, "local", iso.LogDriver) +} diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index d21fbd51a..c8a76d2a0 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -1757,10 +1757,12 @@ type AddServerRequest struct { MaxConcurrentRequests *int `json:"max_concurrent_requests,omitempty"` QueueSize *int `json:"queue_size,omitempty"` QueueTimeout *config.Duration `json:"queue_timeout,omitempty" swaggertype:"string"` - // Isolation carries per-server Docker isolation overrides (image, - // network_mode, extra_args, working_dir, enabled). A nil pointer - // means "do not touch isolation config"; an empty-but-present - // object on PATCH intentionally clears the overrides. + // Isolation carries per-server Docker isolation overrides (enabled, + // mode_override, image, network_mode, extra_args, working_dir). A nil + // pointer means "do not touch isolation config". A present object is + // applied field-by-field ON TOP of the persisted overrides, so omitting a + // field leaves it alone; clear an individual override by sending it + // explicitly (`"enabled": null`, `"image": ""`). Isolation *IsolationRequest `json:"isolation,omitempty"` } @@ -1768,25 +1770,165 @@ type AddServerRequest struct { // config.IsolationConfig, using pointer fields for PATCH semantics: // a nil pointer means "leave this field alone", a present value // (including empty string or empty slice) means "set it". +// +// Read and write use DISJOINT key names for the isolation flag, deliberately: +// on a read, `isolation.enabled` is the EFFECTIVE state (see +// contracts.IsolationConfig), so a client that GETs a server and PATCHes the +// isolation object back would otherwise convert "inherits the global setting" +// into a permanent explicit override — the original bug arriving from the other +// direction (GH #1142). `enabled` is therefore refused on writes, loudly, +// rather than being silently applied or silently dropped; the writable key is +// `enabled_override`, which is also the key reads emit the raw value under. type IsolationRequest struct { - Enabled *bool `json:"enabled,omitempty"` - Image *string `json:"image,omitempty"` - NetworkMode *string `json:"network_mode,omitempty"` - ExtraArgs *[]string `json:"extra_args,omitempty"` - WorkingDir *string `json:"working_dir,omitempty"` -} - -// toConfig materializes the request into a config.IsolationConfig. -// Fields left nil on the request do not appear on the resulting struct -// so UpdateServer's merge logic (in Controller) can distinguish them -// from explicit clears. -func (r *IsolationRequest) toConfig() *config.IsolationConfig { + // EnabledOverride is the tri-state per-server override — the RAW value, the + // same one reads return as `enabled_override`. It has THREE meaningful wire + // states, and collapsing them is what silently un-isolated servers + // (GH #1142): + // - absent → leave the persisted override untouched + // - null → clear the override, back to inheriting the global + // - true / false → set an explicit opt-in / opt-out + EnabledOverride NullableBool `json:"enabled_override,omitempty" swaggertype:"boolean"` + // Enabled exists ONLY to detect and reject an echoed-back read. It is the + // effective state on the read surface and is never writable; see validate(). + Enabled NullableBool `json:"enabled,omitempty" swaggertype:"boolean"` + // ModeOverride sets `isolation.mode` ("docker" | "sandbox" | "none"). + // nil leaves the persisted value alone; an empty string clears it. An + // unrecognized value is rejected with a 400 rather than persisted. + ModeOverride *string `json:"mode_override,omitempty"` + Image *string `json:"image,omitempty"` + NetworkMode *string `json:"network_mode,omitempty"` + ExtraArgs *[]string `json:"extra_args,omitempty"` + WorkingDir *string `json:"working_dir,omitempty"` +} + +// isolationEnabledReadOnlyMessage is the operator-facing 400 body for a write +// that carries the read-only `isolation.enabled`. Like invalidTrustModeMessage +// it names the field to use instead, so the mistake is self-diagnosing from the +// response alone. +const isolationEnabledReadOnlyMessage = "isolation.enabled is read-only: on reads it reports the EFFECTIVE isolation state " + + "(global setting + per-server override + structural gates), so echoing it back would turn a server that merely " + + "inherits the global setting into an explicit override. Use isolation.enabled_override instead: " + + "true = always isolate, false = never isolate, null = clear the override and inherit the global setting; " + + "omit the key to leave it unchanged" + +// validate rejects the write-time errors that would otherwise be persisted: +// an echoed-back read-only field, and an isolation mode the spawn path does not +// implement (which would be written to BBolt and the config file, then fail the +// NEXT daemon start's config validation). +func (r *IsolationRequest) validate() error { if r == nil { return nil } - out := &config.IsolationConfig{} - if r.Enabled != nil { - out.Enabled = config.BoolPtr(*r.Enabled) + if r.Enabled.Set { + return errors.New(isolationEnabledReadOnlyMessage) + } + if r.ModeOverride != nil { + mode := config.IsolationMode(*r.ModeOverride) + if err := config.ValidateIsolationModeOverride(&mode); err != nil { + return err + } + } + return nil +} + +// NullableBool distinguishes an absent JSON key from an explicit `null` and +// from a real boolean, which a plain *bool cannot do. Used for tri-state PATCH +// fields where "clear this back to the default" has to be expressible. +type NullableBool struct { + // Set is true when the key was present in the request body at all. + Set bool + // Value is the decoded boolean, or nil when the key was present as `null`. + Value *bool +} + +// UnmarshalJSON records that the key was present, and decodes its value unless +// it was the literal `null`. +func (n *NullableBool) UnmarshalJSON(data []byte) error { + n.Set = true + if string(data) == "null" { + n.Value = nil + return nil + } + var b bool + if err := json.Unmarshal(data, &b); err != nil { + return err + } + n.Value = &b + return nil +} + +// MarshalJSON encodes the decoded value; an unset or explicitly-null field +// encodes as `null`. NOTE that `null` is the CLEAR-the-override shape on the +// way in, so an unset field must not survive a re-marshal — that is what +// IsolationRequest.MarshalJSON deletes. +func (n NullableBool) MarshalJSON() ([]byte, error) { + if !n.Set || n.Value == nil { + return []byte("null"), nil + } + return json.Marshal(*n.Value) +} + +// MarshalJSON drops the tri-state fields the request never set. +// +// NullableBool's own "unset" encoding is `null`, and `null` on the way IN is +// the clear-the-override shape — so encoding an untouched request with the +// default marshaller would produce a body that wipes the persisted override +// (and one that trips the read-only `enabled` check). Deleting the keys keeps +// "absent" absent, which is the whole point of the tri-state. +// +// It re-encodes through the struct rather than listing the fields again, so a +// new field cannot silently miss this treatment. +func (r IsolationRequest) MarshalJSON() ([]byte, error) { + type plain IsolationRequest // shed the method set to avoid recursion + raw, err := json.Marshal(plain(r)) + if err != nil { + return nil, err + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(raw, &fields); err != nil { + return nil, err + } + if !r.EnabledOverride.Set { + delete(fields, "enabled_override") + } + if !r.Enabled.Set { + delete(fields, "enabled") + } + return json.Marshal(fields) +} + +// resolve materializes the request into a complete config.IsolationConfig, +// starting from the server's PERSISTED overrides and applying only the fields +// the request actually carried. +// +// Resolving here (rather than in the controller's field-by-field merge) is what +// makes three things work at once: an omitted `enabled` cannot become an +// explicit opt-out, an explicit null CAN clear the override, and the fields this +// request type does not expose (mode, log driver/size/files) survive untouched +// — which in turn lets UpdateServer replace the block wholesale. +func (r *IsolationRequest) resolve(existing *config.IsolationConfig) *config.IsolationConfig { + if r == nil { + return nil + } + out := config.CopyIsolationConfig(existing) + if out == nil { + out = &config.IsolationConfig{} + } + + if r.EnabledOverride.Set { + if r.EnabledOverride.Value == nil { + out.Enabled = nil // back to "inherit global" + } else { + out.Enabled = config.BoolPtr(*r.EnabledOverride.Value) + } + } + if r.ModeOverride != nil { + if *r.ModeOverride == "" { + out.Mode = nil + } else { + mode := config.IsolationMode(*r.ModeOverride) + out.Mode = &mode + } } if r.Image != nil { out.Image = *r.Image @@ -1805,7 +1947,7 @@ func (r *IsolationRequest) toConfig() *config.IsolationConfig { // handleAddServer godoc // @Summary Add a new upstream server -// @Description Add a new MCP upstream server to the configuration. New servers are quarantined by default for security. +// @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. // @Tags servers // @Accept json // @Produce json @@ -1854,6 +1996,13 @@ func (s *Server) handleAddServer(w http.ResponseWriter, r *http.Request) { return } + // GH #1142: refuse a read-only `isolation.enabled` and an unrecognized + // isolation mode BEFORE anything is persisted. + if err := req.Isolation.validate(); err != nil { + s.writeError(w, r, http.StatusBadRequest, err.Error()) + return + } + // Auto-detect protocol if not specified protocol := req.Protocol if protocol == "" { @@ -1953,10 +2102,10 @@ func (s *Server) handleAddServer(w http.ResponseWriter, r *http.Request) { // silently dropped, so a caller could not, for example, opt a host-run // stdio server OUT of isolation when global docker_isolation.enabled=true // (the server would be forced into a container and fail to start). Mirror - // the update path's toConfig() mapping so the field means the same thing - // on both verbs. + // the update path's mapping so the field means the same thing on both + // verbs. There is nothing persisted yet, so the patch resolves against nil. if req.Isolation != nil { - serverConfig.Isolation = req.Isolation.toConfig() + serverConfig.Isolation = req.Isolation.resolve(nil) } // Add server via controller @@ -2025,7 +2174,7 @@ func (s *Server) handleRemoveServer(w http.ResponseWriter, r *http.Request) { // handlePatchServer godoc // @Summary Partially update an upstream server -// @Description Update specific fields of an existing upstream MCP server configuration. +// @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. // @Tags servers // @Accept json // @Produce json @@ -2060,6 +2209,13 @@ func (s *Server) handlePatchServer(w http.ResponseWriter, r *http.Request) { return } + // GH #1142: refuse a read-only `isolation.enabled` and an unrecognized + // isolation mode BEFORE anything is persisted. + if err := req.Isolation.validate(); err != nil { + s.writeError(w, r, http.StatusBadRequest, err.Error()) + return + } + // Pre-fetch existing server so we can preserve bool fields the request // did not explicitly set. `config.ServerConfig` uses non-pointer bools // whose zero value cannot be distinguished from "not set" by the time @@ -2236,8 +2392,16 @@ func (s *Server) handlePatchServer(w http.ResponseWriter, r *http.Request) { } else if existingSrv != nil { updates.QueueTimeout = existingSrv.QueueTimeout } + // Isolation is resolved against the PERSISTED overrides, so an omitted + // `enabled` cannot become an explicit opt-out and the fields the request + // does not expose (mode, log driver) survive (GH #1142). The controller + // then replaces the block wholesale. if req.Isolation != nil { - updates.Isolation = req.Isolation.toConfig() + var existingIso *config.IsolationConfig + if existingSrv != nil { + existingIso = existingSrv.Isolation + } + updates.Isolation = req.Isolation.resolve(existingIso) hasUpdates = true } diff --git a/internal/management/isolation_tristate_test.go b/internal/management/isolation_tristate_test.go new file mode 100644 index 000000000..daac640f5 --- /dev/null +++ b/internal/management/isolation_tristate_test.go @@ -0,0 +1,100 @@ +package management + +import ( + "context" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap/zaptest" +) + +// TestListServers_IsolationTriState round-trips the runtime projection through +// the map→contracts converter and asserts that the raw per-server override +// survives as a tri-state (GH #1142). Before the fix the converter read only a +// flattened `enabled` bool, so "inherits global" and "explicitly off" were +// indistinguishable at the REST boundary. +func TestListServers_IsolationTriState(t *testing.T) { + logger := zaptest.NewLogger(t).Sugar() + cfg := &config.Config{DockerIsolation: &config.DockerIsolationConfig{Enabled: true}} + emitter := &mockEventEmitter{} + + rt := newMockRuntime() + rt.servers = []map[string]interface{}{ + { + "id": "inheriting", "name": "inheriting", "protocol": "stdio", + "command": "uvx", "enabled": true, + "isolation": map[string]interface{}{ + "enabled": true, + "image": "python:3.12", + }, + "isolation_effective": map[string]interface{}{ + "mode": "docker", "isolated": true, "inherited": true, + "global_mode": "docker", "source": config.IsolationSourceGlobal, + }, + }, + { + "id": "opted-out", "name": "opted-out", "protocol": "stdio", + "command": "npx", "enabled": true, + "isolation": map[string]interface{}{ + "enabled": false, + "enabled_override": false, + }, + "isolation_effective": map[string]interface{}{ + "mode": "none", "isolated": false, "inherited": false, + "global_mode": "docker", "source": config.IsolationSourceServerOptOut, + }, + }, + { + "id": "sandboxed", "name": "sandboxed", "protocol": "stdio", + "command": "npx", "enabled": true, + "isolation": map[string]interface{}{ + "enabled": true, + "mode_override": "sandbox", + }, + "isolation_effective": map[string]interface{}{ + "mode": "sandbox", "isolated": true, "inherited": false, + "global_mode": "docker", "source": config.IsolationSourceServerMode, + }, + }, + } + + svc := NewService(rt, cfg, "", emitter, nil, logger) + servers, _, err := svc.ListServers(context.Background()) + require.NoError(t, err) + require.Len(t, servers, 3) + + byName := map[string]int{} + for i, s := range servers { + byName[s.Name] = i + } + + inheriting := servers[byName["inheriting"]] + require.NotNil(t, inheriting.Isolation) + assert.True(t, inheriting.Isolation.Enabled, "effective state: isolated") + assert.Nil(t, inheriting.Isolation.EnabledOverride, + "no per-server override was set — the tri-state must stay nil, not collapse to false") + require.NotNil(t, inheriting.IsolationEffective) + assert.True(t, inheriting.IsolationEffective.Inherited) + assert.Equal(t, "docker", inheriting.IsolationEffective.Mode) + assert.Equal(t, config.IsolationSourceGlobal, inheriting.IsolationEffective.Source) + + optedOut := servers[byName["opted-out"]] + require.NotNil(t, optedOut.Isolation) + assert.False(t, optedOut.Isolation.Enabled) + require.NotNil(t, optedOut.Isolation.EnabledOverride, + "an explicit opt-out must be readable as a set override") + assert.False(t, *optedOut.Isolation.EnabledOverride) + require.NotNil(t, optedOut.IsolationEffective) + assert.False(t, optedOut.IsolationEffective.Inherited) + assert.Equal(t, config.IsolationSourceServerOptOut, optedOut.IsolationEffective.Source) + + sandboxed := servers[byName["sandboxed"]] + require.NotNil(t, sandboxed.Isolation) + assert.Equal(t, "sandbox", sandboxed.Isolation.ModeOverride) + assert.Nil(t, sandboxed.Isolation.EnabledOverride) + require.NotNil(t, sandboxed.IsolationEffective) + assert.Equal(t, "sandbox", sandboxed.IsolationEffective.Mode) +} diff --git a/internal/management/service.go b/internal/management/service.go index 4bebbd76d..30aa55288 100644 --- a/internal/management/service.go +++ b/internal/management/service.go @@ -355,9 +355,17 @@ func (s *service) ListServers(ctx context.Context) ([]*contracts.Server, *contra // or goes through a json round-trip first. if isoRaw, ok := srvRaw["isolation"].(map[string]interface{}); ok && isoRaw != nil { iso := &contracts.IsolationConfig{} + // `enabled` is the EFFECTIVE state; `enabled_override` is the raw + // tri-state and is absent when the server inherits (GH #1142). if enabled, ok := isoRaw["enabled"].(bool); ok { iso.Enabled = enabled } + if override, ok := isoRaw["enabled_override"].(bool); ok { + iso.EnabledOverride = config.BoolPtr(override) + } + if modeOverride, ok := isoRaw["mode_override"].(string); ok { + iso.ModeOverride = modeOverride + } if img, ok := isoRaw["image"].(string); ok { iso.Image = img } @@ -380,6 +388,28 @@ func (s *service) ListServers(ctx context.Context) ([]*contracts.Server, *contra srv.Isolation = iso } + // Resolution block: explains WHY the server is (or is not) isolated so a + // UI can render "inherits global: docker" instead of a bare toggle. + if effRaw, ok := srvRaw["isolation_effective"].(map[string]interface{}); ok && effRaw != nil { + eff := &contracts.IsolationEffective{} + if mode, ok := effRaw["mode"].(string); ok { + eff.Mode = mode + } + if isolated, ok := effRaw["isolated"].(bool); ok { + eff.Isolated = isolated + } + if globalMode, ok := effRaw["global_mode"].(string); ok { + eff.GlobalMode = globalMode + } + if inherited, ok := effRaw["inherited"].(bool); ok { + eff.Inherited = inherited + } + if source, ok := effRaw["source"].(string); ok { + eff.Source = source + } + srv.IsolationEffective = eff + } + // Populate resolved isolation defaults so UI clients (macOS tray, // web UI) can render meaningful placeholders for the override // fields. Only meaningful for stdio servers — HTTP servers don't diff --git a/internal/runtime/isolation_projection.go b/internal/runtime/isolation_projection.go new file mode 100644 index 000000000..23d817c2c --- /dev/null +++ b/internal/runtime/isolation_projection.go @@ -0,0 +1,66 @@ +package runtime + +import ( + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts" +) + +// buildIsolationMaps projects a server's isolation configuration into the two +// generic maps that GetAllServers emits: the `isolation` override block and the +// `isolation_effective` resolution block. +// +// `isolation.enabled` is the EFFECTIVE state — what actually happens at spawn +// time. The raw per-server override travels beside it as `enabled_override` +// (and `mode_override`), present only when the server actually set it, so +// "inherits the global setting" stays distinguishable from an explicit opt-out +// instead of being flattened to false (GH #1142). +// +// Returns (nil, nil) when the server has no local process to isolate and no +// stale override to display. +func buildIsolationMaps( + globalIsolation *config.DockerIsolationConfig, + sc *config.ServerConfig, +) (isolation, effective map[string]interface{}) { + iso, eff := contracts.BuildIsolationView(globalIsolation, sc) + if iso == nil { + return nil, nil + } + + isolation = map[string]interface{}{ + "enabled": iso.Enabled, + } + if iso.EnabledOverride != nil { + isolation["enabled_override"] = *iso.EnabledOverride + } + if iso.ModeOverride != "" { + isolation["mode_override"] = iso.ModeOverride + } + if iso.Image != "" { + isolation["image"] = iso.Image + } + if iso.NetworkMode != "" { + isolation["network_mode"] = iso.NetworkMode + } + if len(iso.ExtraArgs) > 0 { + isolation["extra_args"] = iso.ExtraArgs + } + if iso.WorkingDir != "" { + isolation["working_dir"] = iso.WorkingDir + } + + if eff != nil { + effective = map[string]interface{}{ + "mode": eff.Mode, + "isolated": eff.Isolated, + "inherited": eff.Inherited, + } + if eff.GlobalMode != "" { + effective["global_mode"] = eff.GlobalMode + } + if eff.Source != "" { + effective["source"] = eff.Source + } + } + + return isolation, effective +} diff --git a/internal/runtime/isolation_projection_test.go b/internal/runtime/isolation_projection_test.go new file mode 100644 index 000000000..1665440b0 --- /dev/null +++ b/internal/runtime/isolation_projection_test.go @@ -0,0 +1,144 @@ +package runtime + +import ( + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func stdioServerConfig(iso *config.IsolationConfig) *config.ServerConfig { + return &config.ServerConfig{ + Name: "python-mcp", Protocol: "stdio", Command: "uvx", + Args: []string{"some-mcp"}, Isolation: iso, + } +} + +// TestBuildIsolationMaps_InheritReportsIsolated is THE regression test for +// GH #1142: a server whose isolation.enabled is nil ("inherit global") while +// global isolation is ON used to be projected as enabled:false, so every UI +// showed a containerised server as running unisolated. +func TestBuildIsolationMaps_InheritReportsIsolated(t *testing.T) { + global := &config.DockerIsolationConfig{Enabled: true} + sc := stdioServerConfig(&config.IsolationConfig{Image: "python:3.12"}) + + iso, eff := buildIsolationMaps(global, sc) + require.NotNil(t, iso, "an stdio server must carry an isolation block") + + assert.Equal(t, true, iso["enabled"], + "enabled is the EFFECTIVE state: an inheriting server under global isolation IS isolated") + assert.NotContains(t, iso, "enabled_override", + "no per-server override was set, so the raw key must be absent (= inherit)") + assert.Equal(t, "python:3.12", iso["image"]) + + require.NotNil(t, eff) + assert.Equal(t, "docker", eff["mode"]) + assert.Equal(t, true, eff["isolated"]) + assert.Equal(t, true, eff["inherited"]) + assert.Equal(t, "docker", eff["global_mode"]) + assert.Equal(t, config.IsolationSourceGlobal, eff["source"]) +} + +// TestBuildIsolationMaps_ExplicitOptOut pins the other half of the tri-state: +// an explicit enabled:false must be visible as a raw override AND must resolve +// to an unisolated effective state. +func TestBuildIsolationMaps_ExplicitOptOut(t *testing.T) { + global := &config.DockerIsolationConfig{Enabled: true} + sc := stdioServerConfig(&config.IsolationConfig{Enabled: config.BoolPtr(false)}) + + iso, eff := buildIsolationMaps(global, sc) + require.NotNil(t, iso) + + assert.Equal(t, false, iso["enabled"]) + require.Contains(t, iso, "enabled_override") + assert.Equal(t, false, iso["enabled_override"]) + + require.NotNil(t, eff) + assert.Equal(t, "none", eff["mode"]) + assert.Equal(t, false, eff["isolated"]) + assert.Equal(t, false, eff["inherited"]) + assert.Equal(t, config.IsolationSourceServerOptOut, eff["source"]) +} + +// TestBuildIsolationMaps_ExplicitOptIn keeps the raw override readable so a UI +// can render "forced on" rather than guessing from the effective state. +func TestBuildIsolationMaps_ExplicitOptIn(t *testing.T) { + global := &config.DockerIsolationConfig{Enabled: true} + sc := stdioServerConfig(&config.IsolationConfig{Enabled: config.BoolPtr(true)}) + + iso, eff := buildIsolationMaps(global, sc) + require.NotNil(t, iso) + + assert.Equal(t, true, iso["enabled"]) + require.Contains(t, iso, "enabled_override") + assert.Equal(t, true, iso["enabled_override"]) + assert.Equal(t, false, eff["inherited"]) +} + +// TestBuildIsolationMaps_NoIsolationBlockStillReportsEffective covers the other +// half of the reported bug: a server with no `isolation` key at all produced no +// block, so a client doing `isolation?.enabled ?? false` still read "off" for a +// containerised server. +func TestBuildIsolationMaps_NoIsolationBlockStillReportsEffective(t *testing.T) { + global := &config.DockerIsolationConfig{Enabled: true} + sc := stdioServerConfig(nil) + + iso, eff := buildIsolationMaps(global, sc) + require.NotNil(t, iso, "an stdio server must carry an isolation block even with no override") + assert.Equal(t, true, iso["enabled"]) + assert.NotContains(t, iso, "enabled_override") + require.NotNil(t, eff) + assert.Equal(t, true, eff["inherited"]) + assert.Equal(t, "docker", eff["mode"]) +} + +// TestBuildIsolationMaps_ModeOverride surfaces the per-server mode (MCP-34.2), +// which had no representation anywhere on the wire. +func TestBuildIsolationMaps_ModeOverride(t *testing.T) { + sandbox := config.IsolationModeSandbox + global := &config.DockerIsolationConfig{Enabled: true} + sc := stdioServerConfig(&config.IsolationConfig{Mode: &sandbox}) + + iso, eff := buildIsolationMaps(global, sc) + require.NotNil(t, iso) + assert.Equal(t, "sandbox", iso["mode_override"]) + assert.Equal(t, "sandbox", eff["mode"], "the mode is what the spawn path branches on") + + // Whether that mode actually CONFINES depends on the host: wrapWithSandbox + // runs the server unconfined off Linux and on kernels without Landlock, so + // the projection must not claim isolation the spawn path will not deliver + // (GH #1142). + if config.SandboxEnforceable() { + assert.Equal(t, true, iso["enabled"], "a sandbox-isolated server is isolated") + assert.Equal(t, config.IsolationSourceServerMode, eff["source"]) + } else { + assert.Equal(t, false, iso["enabled"], "this host cannot enforce the sandbox") + assert.Equal(t, config.IsolationSourceSandboxUnavailable, eff["source"]) + } +} + +// TestBuildIsolationMaps_HTTPServerOmitted keeps HTTP servers free of a +// meaningless isolation block. +func TestBuildIsolationMaps_HTTPServerOmitted(t *testing.T) { + global := &config.DockerIsolationConfig{Enabled: true} + sc := &config.ServerConfig{Name: "remote", Protocol: "http", URL: "https://example.com/mcp"} + + iso, eff := buildIsolationMaps(global, sc) + assert.Nil(t, iso) + assert.Nil(t, eff) +} + +// TestBuildIsolationMaps_GlobalOff proves the projection is not hardcoded to +// "isolated": with the global setting off, an inheriting server reports false. +func TestBuildIsolationMaps_GlobalOff(t *testing.T) { + global := &config.DockerIsolationConfig{Enabled: false} + sc := stdioServerConfig(nil) + + iso, eff := buildIsolationMaps(global, sc) + require.NotNil(t, iso) + assert.Equal(t, false, iso["enabled"]) + assert.Equal(t, "none", eff["mode"]) + assert.Equal(t, true, eff["inherited"]) +} diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index 8085d6518..e004fb834 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -2234,6 +2234,13 @@ func (r *Runtime) GetAllServers() ([]map[string]interface{}, error) { snapshot := stateView.Snapshot() r.logger.Debug("StateView snapshot retrieved", zap.Int("count", len(snapshot.Servers))) + // Read the global isolation block ONCE, outside the loop: every server's + // projection needs it to resolve the effective isolation state (GH #1142). + var globalIsolation *config.DockerIsolationConfig + if cfg, err := r.GetConfig(); err == nil && cfg != nil { + globalIsolation = cfg.DockerIsolation + } + result := make([]map[string]interface{}, 0, len(snapshot.Servers)) for _, serverStatus := range snapshot.Servers { // Convert StateView ServerStatus to API response format @@ -2429,23 +2436,9 @@ func (r *Runtime) GetAllServers() ([]map[string]interface{}, error) { if len(serverStatus.Config.Env) > 0 { serverMap["env"] = serverStatus.Config.Env } - if iso := serverStatus.Config.Isolation; iso != nil { - isoMap := map[string]interface{}{ - "enabled": iso.IsEnabled(), - } - if iso.Image != "" { - isoMap["image"] = iso.Image - } - if iso.NetworkMode != "" { - isoMap["network_mode"] = iso.NetworkMode - } - if len(iso.ExtraArgs) > 0 { - isoMap["extra_args"] = iso.ExtraArgs - } - if iso.WorkingDir != "" { - isoMap["working_dir"] = iso.WorkingDir - } + if isoMap, effMap := buildIsolationMaps(globalIsolation, serverStatus.Config); isoMap != nil { serverMap["isolation"] = isoMap + serverMap["isolation_effective"] = effMap } } diff --git a/internal/runtime/supervisor/isolation_classification_test.go b/internal/runtime/supervisor/isolation_classification_test.go new file mode 100644 index 000000000..120367eab --- /dev/null +++ b/internal/runtime/supervisor/isolation_classification_test.go @@ -0,0 +1,135 @@ +package supervisor + +import ( + "testing" + + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime/configsvc" +) + +func modePtr(m config.IsolationMode) *config.IsolationMode { return &m } + +// TestUsesDockerIsolation_MatchesResolver is the "one algorithm" invariant for +// the diagnostics classifier: whether the supervisor attributes a spawn failure +// to a DOCKER remediation code must agree with the resolver the SPAWN path uses +// (config.ResolveIsolation), not with a hand-rolled mirror of it. +// +// The mirror predated isolation MODES and only ever looked at the two legacy +// booleans, so it disagreed with the spawn decision in both directions: +// - a per-server `mode: "docker"` override wins outright in the resolver +// (even over a legacy `enabled: false` and a global that is off), so such a +// server IS Docker-spawned but was classified non-Docker — its docker exec +// failures got a generic stdio ENOENT remediation instead of the #696 +// Docker guidance, and the image/default-image enrichment was dropped; +// - a `mode: "sandbox"` server under global Docker isolation is NOT +// containerised, but was classified Docker-isolated and offered Docker +// remediation for a Landlock failure. +func TestUsesDockerIsolation_MatchesResolver(t *testing.T) { + optOut, optIn := false, true + + tests := []struct { + name string + global *config.DockerIsolationConfig + srv *config.ServerConfig + want bool + }{ + { + name: "per-server docker mode wins over a legacy opt-out and an off global", + global: &config.DockerIsolationConfig{Enabled: false}, + srv: &config.ServerConfig{ + Name: "moded", + Command: "npx", + Isolation: &config.IsolationConfig{Mode: modePtr(config.IsolationModeDocker), Enabled: &optOut}, + }, + want: true, + }, + { + name: "global mode docker with the legacy bool left false", + global: &config.DockerIsolationConfig{Mode: config.IsolationModeDocker}, + srv: &config.ServerConfig{Name: "inheriting", Command: "npx"}, + want: true, + }, + { + name: "sandbox mode under global docker is not containerised", + global: &config.DockerIsolationConfig{Enabled: true}, + srv: &config.ServerConfig{ + Name: "sandboxed", + Command: "npx", + Isolation: &config.IsolationConfig{Mode: modePtr(config.IsolationModeSandbox)}, + }, + want: false, + }, + { + name: "legacy opt-out still wins when there is no mode override", + global: &config.DockerIsolationConfig{Enabled: true}, + srv: &config.ServerConfig{ + Name: "opted-out", + Command: "npx", + Isolation: &config.IsolationConfig{Enabled: &optOut}, + }, + want: false, + }, + { + name: "legacy opt-in is ignored while the global mode is none", + global: &config.DockerIsolationConfig{Enabled: false}, + srv: &config.ServerConfig{ + Name: "opted-in", + Command: "npx", + Isolation: &config.IsolationConfig{Enabled: &optIn}, + }, + want: false, + }, + { + name: "inheriting stdio server under global docker", + global: &config.DockerIsolationConfig{Enabled: true}, + srv: &config.ServerConfig{Name: "plain", Command: "uvx"}, + want: true, + }, + { + name: "a server that already runs docker is never double-wrapped", + global: &config.DockerIsolationConfig{Enabled: true}, + srv: &config.ServerConfig{Name: "dockerised", Command: "docker"}, + want: false, + }, + { + name: "http server has no child process to isolate", + global: &config.DockerIsolationConfig{Enabled: true}, + srv: &config.ServerConfig{Name: "remote", URL: "https://example.test/mcp"}, + want: false, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + cfg := &config.Config{DockerIsolation: tc.global, Servers: []*config.ServerConfig{tc.srv}} + configSvc := configsvc.NewService(cfg, "/tmp/config.json", zap.NewNop()) + defer configSvc.Close() + + mockUpstream := NewMockUpstreamAdapter() + defer mockUpstream.Close() + + s := New(configSvc, mockUpstream, zap.NewNop()) + + // The resolver is the reference answer: it is what the spawn path + // branches on. + resolved := config.ResolveIsolation(tc.global, tc.srv) + wantDocker := resolved.Mode == config.IsolationModeDocker + if wantDocker != tc.want { + t.Fatalf("test case expectation disagrees with the resolver: resolver says docker=%v (mode=%q source=%q), case wants %v", + wantDocker, resolved.Mode, resolved.Source, tc.want) + } + + if got := s.usesDockerIsolation(tc.srv); got != tc.want { + t.Errorf("usesDockerIsolation() = %v, want %v (resolver mode=%q source=%q)", + got, tc.want, resolved.Mode, resolved.Source) + } + + hints := s.classifierHints(tc.srv, "stdio") + if hints.DockerIsolated != tc.want { + t.Errorf("classifierHints().DockerIsolated = %v, want %v", hints.DockerIsolated, tc.want) + } + }) + } +} diff --git a/internal/runtime/supervisor/supervisor.go b/internal/runtime/supervisor/supervisor.go index f1b2410a4..417d63627 100644 --- a/internal/runtime/supervisor/supervisor.go +++ b/internal/runtime/supervisor/supervisor.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" "fmt" - "path/filepath" "sync" "sync/atomic" "time" @@ -83,29 +82,30 @@ func (s *Supervisor) classifierHints(srv *config.ServerConfig, transport string) // usesDockerIsolation reports whether the given server would be launched // through Docker isolation, so the classifier can attribute spawn/exec failures // to DOCKER codes (#696 CLI missing, in-container interpreter missing) rather -// than a generic stdio ENOENT. This is a side-effect-free mirror of -// core.IsolationManager.ShouldIsolate (internal/upstream/core/isolation.go) — -// it is only a classifier hint, so faithfulness matters more than sharing the -// (logging) implementation. +// than a generic stdio ENOENT. +// +// It delegates to config.ResolveIsolation — the SAME resolver the spawn path +// branches on (core.IsolationManager.ShouldIsolate wraps it) — so the hint +// cannot drift from the launch decision. It previously mirrored the rules by +// hand and only read the two LEGACY booleans, which pre-date isolation modes: +// a per-server `mode: "docker"` override wins outright in the resolver, so such +// a server was Docker-spawned but classified non-Docker (generic ENOENT +// remediation, no image enrichment); and a `mode: "sandbox"` server under +// global Docker isolation was classified Docker-isolated and offered Docker +// remediation for a Landlock failure (GH #1142). +// +// The predicate is Mode == docker, not ResolvedIsolation.Isolated: the DOCKER +// remediation codes describe the container LAUNCH path, which runs whenever the +// mode is docker. func (s *Supervisor) usesDockerIsolation(srv *config.ServerConfig) bool { - if srv == nil || srv.Command == "" { + if srv == nil { return false } - snap := s.configSvc.Current() - if snap == nil || snap.Config == nil || snap.Config.DockerIsolation == nil || - !snap.Config.DockerIsolation.Enabled { - return false - } - // Per-server explicit opt-out wins over the global enable. - if srv.Isolation != nil && srv.Isolation.Enabled != nil && !*srv.Isolation.Enabled { - return false + var global *config.DockerIsolationConfig + if snap := s.configSvc.Current(); snap != nil && snap.Config != nil { + global = snap.Config.DockerIsolation } - // Servers already running docker themselves are not double-isolated. - cmdBase := filepath.Base(srv.Command) - if cmdBase == "docker" || strings.Contains(srv.Command, "docker") { - return false - } - return true + return config.ResolveIsolation(global, srv).Mode == config.IsolationModeDocker } // Supervisor manages the desired vs actual state reconciliation for upstream servers. diff --git a/internal/server/isolation_mode_validation_test.go b/internal/server/isolation_mode_validation_test.go new file mode 100644 index 000000000..d064c6f89 --- /dev/null +++ b/internal/server/isolation_mode_validation_test.go @@ -0,0 +1,72 @@ +package server + +import ( + "strings" + "testing" + + "github.com/mark3labs/mcp-go/mcp" + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" +) + +// TestBuildPatchConfig_RejectsUnknownIsolationMode covers the MCP twin of the +// REST `mode_override` hole (GH #1142): `upstream_servers patch` unmarshalled +// isolation_json straight into config.IsolationConfig, so a bogus mode was +// persisted to BBolt and ~/.mcpproxy/mcp_config.json and only surfaced as a +// failed config validation on the NEXT daemon start. +func TestBuildPatchConfig_RejectsUnknownIsolationMode(t *testing.T) { + p := &MCPProxyServer{logger: zap.NewNop()} + existing := &config.ServerConfig{Name: "srv", Protocol: "stdio", Command: "npx"} + + for _, bad := range []string{"bogus", "Docker", "docker "} { + t.Run(bad, func(t *testing.T) { + request := mcp.CallToolRequest{Params: mcp.CallToolParams{ + Name: "upstream_servers", + Arguments: map[string]interface{}{ + "operation": "patch", + "name": "srv", + "isolation_json": `{"mode":"` + bad + `"}`, + }, + }} + + patch, _, err := p.buildPatchConfigFromRequest(request, existing) + if err == nil { + t.Fatalf("expected an error for isolation mode %q, got patch %+v", bad, patch) + } + for _, want := range []string{"docker", "sandbox", "none"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("error %q does not name the accepted value %q", err, want) + } + } + }) + } +} + +// TestBuildPatchConfig_AcceptsKnownIsolationModes guards against over-rejecting +// (an empty mode is the documented "clear / inherit" value). +func TestBuildPatchConfig_AcceptsKnownIsolationModes(t *testing.T) { + p := &MCPProxyServer{logger: zap.NewNop()} + existing := &config.ServerConfig{Name: "srv", Protocol: "stdio", Command: "npx"} + + for _, good := range []string{"docker", "sandbox", "none", ""} { + t.Run("mode="+good, func(t *testing.T) { + request := mcp.CallToolRequest{Params: mcp.CallToolParams{ + Name: "upstream_servers", + Arguments: map[string]interface{}{ + "operation": "patch", + "name": "srv", + "isolation_json": `{"mode":"` + good + `"}`, + }, + }} + + patch, _, err := p.buildPatchConfigFromRequest(request, existing) + if err != nil { + t.Fatalf("mode %q must be accepted, got %v", good, err) + } + if patch == nil || patch.Isolation == nil { + t.Fatalf("expected an isolation patch, got %+v", patch) + } + }) + } +} diff --git a/internal/server/mcp.go b/internal/server/mcp.go index 1f88b8859..4683c63d5 100644 --- a/internal/server/mcp.go +++ b/internal/server/mcp.go @@ -3875,10 +3875,16 @@ func (p *MCPProxyServer) handleListUpstreams(ctx context.Context) (*mcp.CallTool if server.Command != "" { isolationManager := p.getIsolationManager() if isolationManager != nil { - shouldIsolate := isolationManager.ShouldIsolate(server) - dockerInfo["applies_to_server"] = shouldIsolate - - if shouldIsolate { + resolved := isolationManager.ResolveIsolation(server) + // applies_to_server is the EFFECTIVE answer to "is this server + // isolated": a sandbox-isolated server used to report false here + // because the check was ShouldIsolate (docker-only) (GH #1142). + dockerInfo["applies_to_server"] = resolved.Isolated + dockerInfo["isolation_mode"] = string(resolved.Mode) + dockerInfo["isolation_inherited"] = resolved.Inherited + dockerInfo["isolation_source"] = resolved.Source + + if resolved.Mode == config.IsolationModeDocker { runtimeType := isolationManager.DetectRuntimeType(server.Command) dockerInfo["runtime_detected"] = runtimeType @@ -3888,15 +3894,26 @@ func (p *MCPProxyServer) handleListUpstreams(ctx context.Context) (*mcp.CallTool } } - // Add server-specific isolation config + // Add server-specific isolation config. This block is deliberately + // the RAW per-server override — it is named server_isolation — so + // `enabled` is omitted entirely when the server inherits the global + // setting rather than being flattened to false. The effective state + // lives in applies_to_server / isolation_mode above. if server.Isolation != nil { - dockerInfo["server_isolation"] = map[string]interface{}{ - "enabled": server.Isolation.IsEnabled(), + serverIso := map[string]interface{}{ "image": server.Isolation.Image, "network_mode": server.Isolation.NetworkMode, "working_dir": server.Isolation.WorkingDir, "extra_args": server.Isolation.ExtraArgs, } + if server.Isolation.Enabled != nil { + serverIso["enabled"] = *server.Isolation.Enabled + serverIso["enabled_override"] = *server.Isolation.Enabled + } + if server.Isolation.Mode != nil { + serverIso["mode_override"] = string(*server.Isolation.Mode) + } + dockerInfo["server_isolation"] = serverIso } // Add global limits @@ -4141,6 +4158,10 @@ func (p *MCPProxyServer) getIsolationManager() IsolationChecker { // IsolationChecker interface for checking isolation settings type IsolationChecker interface { + // ResolveIsolation is the single source of truth for "is this server + // isolated" — it accounts for the global mode, the tri-state per-server + // override and the structural gates (GH #1142). + ResolveIsolation(serverConfig *config.ServerConfig) config.ResolvedIsolation ShouldIsolate(serverConfig *config.ServerConfig) bool DetectRuntimeType(command string) string GetDockerImage(serverConfig *config.ServerConfig, runtimeType string) (string, error) @@ -4646,6 +4667,11 @@ func (p *MCPProxyServer) handleAddUpstream(ctx context.Context, request mcp.Call if err := json.Unmarshal([]byte(isolationJSON), &isoConfig); err != nil { return mcp.NewToolResultError(fmt.Sprintf("Invalid isolation_json format: %v", err)), nil } + // GH #1142: an unknown mode must be refused here, not persisted and + // then rejected by the NEXT daemon start's config validation. + if err := config.ValidateIsolationModeOverride(isoConfig.Mode); err != nil { + return mcp.NewToolResultError(fmt.Sprintf("Invalid isolation_json: %v", err)), nil + } isolation = &isoConfig } @@ -5216,6 +5242,11 @@ func (p *MCPProxyServer) buildPatchConfigFromRequest(request mcp.CallToolRequest if err := json.Unmarshal([]byte(isolationJSON), &isolation); err != nil { return nil, opts, fmt.Errorf("invalid isolation_json format: %v", err) } + // GH #1142: refuse an unknown mode at the seam rather than writing + // a config file the next daemon start will reject. + if err := config.ValidateIsolationModeOverride(isolation.Mode); err != nil { + return nil, opts, fmt.Errorf("invalid isolation_json: %w", err) + } patch.Isolation = &isolation } } diff --git a/internal/server/mcp_test.go b/internal/server/mcp_test.go index 3ae270375..940a16d74 100644 --- a/internal/server/mcp_test.go +++ b/internal/server/mcp_test.go @@ -1651,7 +1651,8 @@ func TestPatchPreservesIsolationConfig(t *testing.T) { // CRITICAL: Verify Isolation config is preserved completely require.NotNil(t, merged.Isolation, "Isolation config must be preserved") - assert.True(t, merged.Isolation.IsEnabled(), "Isolation.Enabled must be preserved") + require.NotNil(t, merged.Isolation.Enabled, "Isolation.Enabled override must survive as a set pointer, not collapse to nil") + assert.True(t, *merged.Isolation.Enabled, "Isolation.Enabled must be preserved") assert.Equal(t, "python:3.11", merged.Isolation.Image, "Isolation.Image must be preserved") assert.Equal(t, "bridge", merged.Isolation.NetworkMode, "Isolation.NetworkMode must be preserved") assert.Equal(t, []string{"-v", "/host:/container"}, merged.Isolation.ExtraArgs, "Isolation.ExtraArgs must be preserved") @@ -1826,7 +1827,8 @@ func TestPatchPreservesAllFieldsOnSimpleToggle(t *testing.T) { // Deep verify nested configs require.NotNil(t, merged.Isolation) - assert.Equal(t, baseConfig.Isolation.IsEnabled(), merged.Isolation.IsEnabled()) + assert.Equal(t, baseConfig.Isolation.Enabled, merged.Isolation.Enabled, + "the tri-state enabled override must round-trip exactly (nil stays nil)") assert.Equal(t, baseConfig.Isolation.Image, merged.Isolation.Image) assert.Equal(t, baseConfig.Isolation.NetworkMode, merged.Isolation.NetworkMode) assert.Equal(t, baseConfig.Isolation.ExtraArgs, merged.Isolation.ExtraArgs) @@ -1882,7 +1884,8 @@ func TestPatchDeepMergeIsolation(t *testing.T) { assert.Equal(t, "/app", merged.Isolation.WorkingDir, "WorkingDir must be preserved") // With *bool: patch.Isolation.Enabled is nil (not set), so base value is preserved - assert.True(t, merged.Isolation.IsEnabled(), "Enabled must be preserved when patch doesn't set it") + require.NotNil(t, merged.Isolation.Enabled, "Enabled must stay a set override when the patch doesn't touch it") + assert.True(t, *merged.Isolation.Enabled, "Enabled must be preserved when patch doesn't set it") // Verify the diff contains isolation changes assert.NotNil(t, diff) @@ -1941,3 +1944,34 @@ func TestRawByteSize_MeasuredBeforeTruncation(t *testing.T) { assert.Greater(t, responseBytes, rawByteSize(forwarded), "captured ResponseBytes must exceed the post-truncation payload size") } + +// TestPatchPreservesIsolationMode is the MCP-side regression for GH #1142: +// copyIsolationConfig/MergeIsolationConfig ignored IsolationConfig.Mode, so the +// `upstream_servers patch` path silently erased a server's per-server isolation +// mode (the primary MCP-34.2 override) on any unrelated isolation edit. +func TestPatchPreservesIsolationMode(t *testing.T) { + sandbox := config.IsolationModeSandbox + baseConfig := &config.ServerConfig{ + Name: "test-mode-preserve", + Protocol: "stdio", + Command: "uvx", + Enabled: true, + Isolation: &config.IsolationConfig{ + Mode: &sandbox, + Image: "python:3.11", + }, + } + + patch := &config.ServerConfig{ + Isolation: &config.IsolationConfig{Image: "python:3.12"}, + } + + merged, _, err := config.MergeServerConfig(baseConfig, patch, config.DefaultMergeOptions()) + require.NoError(t, err) + require.NotNil(t, merged.Isolation) + assert.Equal(t, "python:3.12", merged.Isolation.Image) + require.NotNil(t, merged.Isolation.Mode, "isolation.mode must survive an unrelated isolation patch") + assert.Equal(t, sandbox, *merged.Isolation.Mode) + assert.NotSame(t, baseConfig.Isolation.Mode, merged.Isolation.Mode, + "the merged Mode pointer must not alias the base config") +} diff --git a/internal/server/server.go b/internal/server/server.go index c8f965234..3cdc08a7b 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -1738,30 +1738,18 @@ func (s *Server) UpdateServer(ctx context.Context, serverName string, updates *c existing.InitTimeout = updates.InitTimeout } - // Isolation is PATCH-semantic: nil means "leave unchanged"; a - // present struct means "replace". Within the struct, the caller - // only populates fields they want to set (handled upstream by - // IsolationRequest.toConfig), so we merge into the existing - // override set rather than wholesale replacing. + // Isolation is PATCH-semantic: nil means "leave unchanged"; a present + // struct REPLACES the override set wholesale. + // + // The old field-by-field non-zero merge here could not express a clear — + // an empty image or a nil `enabled` was indistinguishable from "not + // supplied" — which is half of why an inheriting server could never be + // restored once something wrote an explicit opt-out (GH #1142). The REST + // handler now resolves the patch against the persisted overrides + // (IsolationRequest.resolve) and hands over a complete struct, so replacing + // is both correct and the only way clears can work. if updates.Isolation != nil { - if existing.Isolation == nil { - existing.Isolation = &config.IsolationConfig{} - } - if updates.Isolation.Enabled != nil { - existing.Isolation.Enabled = updates.Isolation.Enabled - } - if updates.Isolation.Image != "" { - existing.Isolation.Image = updates.Isolation.Image - } - if updates.Isolation.NetworkMode != "" { - existing.Isolation.NetworkMode = updates.Isolation.NetworkMode - } - if updates.Isolation.ExtraArgs != nil { - existing.Isolation.ExtraArgs = updates.Isolation.ExtraArgs - } - if updates.Isolation.WorkingDir != "" { - existing.Isolation.WorkingDir = updates.Isolation.WorkingDir - } + existing.Isolation = config.CopyIsolationConfig(updates.Isolation) } // Save to storage diff --git a/internal/storage/async_ops_test.go b/internal/storage/async_ops_test.go index 6a50db4c9..40ec2f32b 100644 --- a/internal/storage/async_ops_test.go +++ b/internal/storage/async_ops_test.go @@ -118,8 +118,11 @@ func TestSaveServerSyncPreservesAllFields(t *testing.T) { if record.Isolation == nil { t.Fatal("Isolation config is nil - data loss detected!") } - if record.Isolation.IsEnabled() != serverConfig.Isolation.IsEnabled() { - t.Errorf("Isolation.Enabled mismatch: got %v, want %v", record.Isolation.IsEnabled(), serverConfig.Isolation.IsEnabled()) + // GH #1142: assert the tri-state POINTER, not a flattened bool — a nil + // (inherit) override that came back as an explicit false would otherwise + // pass unnoticed. + if !reflect.DeepEqual(record.Isolation.Enabled, serverConfig.Isolation.Enabled) { + t.Errorf("Isolation.Enabled mismatch: got %v, want %v", record.Isolation.Enabled, serverConfig.Isolation.Enabled) } // MCP-34.2: per-server isolation.mode must survive the BBolt round-trip. if !reflect.DeepEqual(record.Isolation.Mode, serverConfig.Isolation.Mode) { diff --git a/internal/upstream/core/isolation.go b/internal/upstream/core/isolation.go index 646a58f14..98d585d4a 100644 --- a/internal/upstream/core/isolation.go +++ b/internal/upstream/core/isolation.go @@ -153,6 +153,23 @@ func (im *IsolationManager) GetDockerIsolationWarning(serverConfig *config.Serve return "" } +// ResolvedIsolation is re-exported from the config package so callers in this +// package can keep referring to it without importing config explicitly. +type ResolvedIsolation = config.ResolvedIsolation + +// ResolveIsolation resolves the effective isolation state for a server — the +// single source of truth for "is this server isolated" (GH #1142). The +// algorithm lives in config.ResolveIsolation so every reporting surface runs +// the same code; this wrapper adds the deduplicated warning for a per-server +// opt-in that the global setting is ignoring. +func (im *IsolationManager) ResolveIsolation(serverConfig *config.ServerConfig) ResolvedIsolation { + resolved := config.ResolveIsolation(im.globalConfig, serverConfig) + if resolved.Source == config.IsolationSourceServerOptInIgnored && serverConfig != nil { + im.warnPerServerIgnoredOnce(serverConfig.Name) + } + return resolved +} + // ShouldIsolate determines if a server should be isolated via Docker, based on // global and server config. It is the legacy boolean view of ResolveMode and // stays in lockstep with it: it returns true iff the resolved mode is "docker". @@ -161,77 +178,11 @@ func (im *IsolationManager) ShouldIsolate(serverConfig *config.ServerConfig) boo return im.ResolveMode(serverConfig) == config.IsolationModeDocker } -// ResolveMode resolves the effective isolation mode for a server (MCP-34.2), -// combining the global config (with legacy Enabled⇒docker back-compat), an -// optional per-server override, and structural gates. -// -// Precedence: -// 1. A per-server explicit Mode wins outright (even over a disabled global) — -// mirroring how other per-server overrides (image, network) take priority. -// 2. Otherwise, when the global mode resolves to none, per-server bool opt-ins -// are ignored (and warned about once), preserving the pre-mode behavior. -// 3. When the global mode is active, a per-server bool opt-out (enabled:false) -// downgrades the server to none. -// -// Structural gates then apply to ALL non-none modes: HTTP servers (no command) -// and servers that already invoke docker are never isolated. +// ResolveMode resolves the effective isolation mode for a server (MCP-34.2) — +// the mode-only view of ResolveIsolation. See config.ResolveIsolation for the +// precedence rules and the structural gates. func (im *IsolationManager) ResolveMode(serverConfig *config.ServerConfig) config.IsolationMode { - mode := im.resolveConfiguredMode(serverConfig) - if mode == config.IsolationModeNone { - return config.IsolationModeNone - } - - // Only isolate stdio servers (HTTP servers don't need a sandbox/container). - if serverConfig == nil || serverConfig.Command == "" { - return config.IsolationModeNone - } - - // Skip isolation for servers that already invoke Docker — these are - // typically pre-configured containers, and wrapping them (in a container - // or a Landlock sandbox) would break their access to the Docker socket. - cmdName := filepath.Base(serverConfig.Command) - if cmdName == "docker" || strings.Contains(serverConfig.Command, "docker") { - return config.IsolationModeNone - } - - return mode -} - -// resolveConfiguredMode applies the global + per-server config precedence to -// produce the desired mode, before the structural gates in ResolveMode. -func (im *IsolationManager) resolveConfiguredMode(serverConfig *config.ServerConfig) config.IsolationMode { - globalMode := im.globalConfig.ResolvedMode() // nil-safe; returns none for nil - - // (1) A per-server explicit Mode override wins outright. - if serverConfig != nil && serverConfig.Isolation != nil && serverConfig.Isolation.Mode != nil { - return *serverConfig.Isolation.Mode - } - - // (2) Global isolation off: per-server bool opt-ins are ignored (warn once). - if globalMode == config.IsolationModeNone { - if im.hasExplicitPerServerOptIn(serverConfig) { - im.warnPerServerIgnoredOnce(serverConfig.Name) - } - return config.IsolationModeNone - } - - // (3) Global isolation active: honor a per-server bool opt-out. - if serverConfig != nil && serverConfig.Isolation != nil && - serverConfig.Isolation.Enabled != nil && !*serverConfig.Isolation.Enabled { - return config.IsolationModeNone - } - - return globalMode -} - -// hasExplicitPerServerOptIn returns true when the server config explicitly -// sets isolation.enabled = true. Nil / missing means "inherit global" — -// that's NOT an opt-in for our warning purposes. -func (im *IsolationManager) hasExplicitPerServerOptIn(serverConfig *config.ServerConfig) bool { - if serverConfig == nil || serverConfig.Isolation == nil { - return false - } - return serverConfig.Isolation.Enabled != nil && *serverConfig.Isolation.Enabled + return im.ResolveIsolation(serverConfig).Mode } // warnPerServerIgnoredOnce emits a one-time warning (deduped by server name) diff --git a/internal/upstream/core/isolation_resolved_test.go b/internal/upstream/core/isolation_resolved_test.go new file mode 100644 index 000000000..e10f2bd49 --- /dev/null +++ b/internal/upstream/core/isolation_resolved_test.go @@ -0,0 +1,206 @@ +package core + +import ( + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" +) + +// resolveCase is one cell of the global × per-server × structural matrix. +type resolveCase struct { + name string + global *config.DockerIsolationConfig + server *config.ServerConfig + wantMode config.IsolationMode + wantIso bool + wantSource string + wantInherit bool +} + +// sandboxSource is the resolution source expected for a server whose mode is +// "sandbox": the ordinary server-mode answer where the host can enforce +// Landlock, and the honest degradation elsewhere. +func sandboxSource() string { + if config.SandboxEnforceable() { + return config.IsolationSourceServerMode + } + return config.IsolationSourceSandboxUnavailable +} + +func stdioServer() *config.ServerConfig { + return &config.ServerConfig{Name: "srv", Command: "npx", Args: []string{"some-mcp"}} +} + +func resolveCases() []resolveCase { + withIso := func(iso *config.IsolationConfig) *config.ServerConfig { + s := stdioServer() + s.Isolation = iso + return s + } + sandbox := config.IsolationModeSandbox + + return []resolveCase{ + { + // GH #1142: this is the reported bug. No per-server override at + // all, global isolation on ⇒ the server IS isolated and the + // resolution is inherited. + name: "inherit global docker", + global: &config.DockerIsolationConfig{Enabled: true}, + server: withIso(&config.IsolationConfig{Image: "python:3.12"}), + wantMode: config.IsolationModeDocker, + wantIso: true, + wantSource: config.IsolationSourceGlobal, + wantInherit: true, + }, + { + name: "no isolation block at all inherits global docker", + global: &config.DockerIsolationConfig{Enabled: true}, + server: stdioServer(), + wantMode: config.IsolationModeDocker, + wantIso: true, + wantSource: config.IsolationSourceGlobal, + wantInherit: true, + }, + { + name: "explicit per-server opt-out under global docker", + global: &config.DockerIsolationConfig{Enabled: true}, + server: withIso(&config.IsolationConfig{Enabled: config.BoolPtr(false)}), + wantMode: config.IsolationModeNone, + wantIso: false, + wantSource: config.IsolationSourceServerOptOut, + wantInherit: false, + }, + { + name: "explicit per-server opt-in under global docker", + global: &config.DockerIsolationConfig{Enabled: true}, + server: withIso(&config.IsolationConfig{Enabled: config.BoolPtr(true)}), + wantMode: config.IsolationModeDocker, + wantIso: true, + wantSource: config.IsolationSourceGlobal, + wantInherit: false, + }, + { + name: "explicit per-server opt-in ignored when global is off", + global: &config.DockerIsolationConfig{Enabled: false}, + server: withIso(&config.IsolationConfig{Enabled: config.BoolPtr(true)}), + wantMode: config.IsolationModeNone, + wantIso: false, + wantSource: config.IsolationSourceServerOptInIgnored, + wantInherit: false, + }, + { + name: "global off, no override", + global: &config.DockerIsolationConfig{Enabled: false}, + server: stdioServer(), + wantMode: config.IsolationModeNone, + wantIso: false, + wantSource: config.IsolationSourceGlobal, + wantInherit: true, + }, + { + // The mode override decides the MODE unconditionally, but whether + // that mode actually confines depends on the host: wrapWithSandbox + // runs the server unconfined off Linux and on kernels without + // Landlock, so Isolated must follow the host, not the config + // (GH #1142). + name: "per-server mode override wins over global docker", + global: &config.DockerIsolationConfig{Enabled: true}, + server: withIso(&config.IsolationConfig{Mode: &sandbox}), + wantMode: config.IsolationModeSandbox, + wantIso: config.SandboxEnforceable(), + wantSource: sandboxSource(), + wantInherit: false, + }, + { + name: "per-server mode override wins over a disabled global", + global: &config.DockerIsolationConfig{Enabled: false}, + server: withIso(&config.IsolationConfig{Mode: &sandbox}), + wantMode: config.IsolationModeSandbox, + wantIso: config.SandboxEnforceable(), + wantSource: sandboxSource(), + wantInherit: false, + }, + { + name: "http server is never isolated", + global: &config.DockerIsolationConfig{Enabled: true}, + server: &config.ServerConfig{ + Name: "remote", URL: "https://example.com/mcp", Protocol: "http", + }, + wantMode: config.IsolationModeNone, + wantIso: false, + wantSource: config.IsolationSourceNotStdio, + wantInherit: true, + }, + { + name: "docker-command server is never re-wrapped", + global: &config.DockerIsolationConfig{Enabled: true}, + server: &config.ServerConfig{ + Name: "dockerised", Command: "docker", Args: []string{"run", "img"}, + }, + wantMode: config.IsolationModeNone, + wantIso: false, + wantSource: config.IsolationSourceAlreadyDocker, + wantInherit: true, + }, + } +} + +// TestResolveIsolation_Source pins the effective mode, the isolated flag, and +// the explanation string for every cell of the resolution matrix. The Source +// string is what makes "inherit" a distinguishable state instead of a guess, +// so it is asserted exactly (GH #1142). +func TestResolveIsolation_Source(t *testing.T) { + for _, tc := range resolveCases() { + t.Run(tc.name, func(t *testing.T) { + im := NewIsolationManager(tc.global) + got := im.ResolveIsolation(tc.server) + + if got.Mode != tc.wantMode { + t.Errorf("Mode = %q, want %q", got.Mode, tc.wantMode) + } + if got.Isolated != tc.wantIso { + t.Errorf("Isolated = %v, want %v", got.Isolated, tc.wantIso) + } + if got.Source != tc.wantSource { + t.Errorf("Source = %q, want %q", got.Source, tc.wantSource) + } + if got.Inherited != tc.wantInherit { + t.Errorf("Inherited = %v, want %v", got.Inherited, tc.wantInherit) + } + if want := tc.global.ResolvedMode(); got.GlobalMode != want { + t.Errorf("GlobalMode = %q, want %q", got.GlobalMode, want) + } + }) + } +} + +// TestResolveIsolation_NilServer guards the nil path taken by callers that +// project a server list before the config is attached. +func TestResolveIsolation_NilServer(t *testing.T) { + im := NewIsolationManager(&config.DockerIsolationConfig{Enabled: true}) + got := im.ResolveIsolation(nil) + if got.Mode != config.IsolationModeNone || got.Isolated { + t.Errorf("nil server should resolve to none/unisolated, got %+v", got) + } +} + +// TestResolveModeDelegatesToResolveIsolation pins the single-algorithm +// invariant: ResolveMode and ShouldIsolate must never drift from +// ResolveIsolation, because the spawn path and the reporting path both have to +// answer "is this server isolated" the same way (GH #1142). +func TestResolveModeDelegatesToResolveIsolation(t *testing.T) { + for _, tc := range resolveCases() { + t.Run(tc.name, func(t *testing.T) { + im := NewIsolationManager(tc.global) + resolved := im.ResolveIsolation(tc.server) + + if got := im.ResolveMode(tc.server); got != resolved.Mode { + t.Errorf("ResolveMode() = %q, ResolveIsolation().Mode = %q", got, resolved.Mode) + } + wantShould := resolved.Mode == config.IsolationModeDocker + if got := im.ShouldIsolate(tc.server); got != wantShould { + t.Errorf("ShouldIsolate() = %v, want %v", got, wantShould) + } + }) + } +} diff --git a/internal/upstream/docker_dependency_test.go b/internal/upstream/docker_dependency_test.go new file mode 100644 index 000000000..38898b589 --- /dev/null +++ b/internal/upstream/docker_dependency_test.go @@ -0,0 +1,97 @@ +package upstream + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" + + "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/managed" +) + +// TestConnectBudget_ServerRunningDockerItself is the composed regression test +// for the connect budget of a server whose OWN command is `docker`. +// +// Such a server is never CONTAINERISED by us — the resolver's already-docker +// structural gate correctly refuses to double-wrap it — but it still shells out +// to the Docker daemon and still pays image-pull latency before it answers +// `initialize`. The 3-minute floor must therefore cover it, exactly as it +// covers a server we containerise ourselves. Routing the timeout predicate +// through ResolveIsolation alone dropped it to the resolved init_timeout (30s +// by default), which can kill the server mid-pull (GH #1142). +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) + + sc := &config.ServerConfig{ + Name: "already-dockerised", + Command: "docker", + Args: []string{"run", "-i", "--rm", "mcp/foo"}, + Protocol: "stdio", + Enabled: true, + } + client, err := managed.NewClient("already-dockerised", sc, logger, nil, gc, nil, secret.NewResolver()) + require.NoError(t, err) + + assert.Equal(t, 3*time.Minute, m.resolveConnectTimeout(sc, client.DependsOnDocker()), + "a server whose own command is docker must keep the 3-minute image-pull budget") +} + +// TestShouldEnableDockerRecovery_HonorsIsolationModes covers the third +// classification site: the Docker recovery monitor (and, through +// UsesDockerIsolation, shutdown container-cleanup verification) was still +// hand-rolled from the two LEGACY booleans and never consulted isolation MODES. +// +// So a config that really does containerise its servers — a global +// `{mode:"docker", enabled:false}`, or a per-server `isolation.mode:"docker"` +// while the global legacy flag is off — left recovery monitoring off and let +// shutdown skip container cleanup, leaking containers (GH #1142). +func TestShouldEnableDockerRecovery_HonorsIsolationModes(t *testing.T) { + newManager := func(global *config.DockerIsolationConfig, servers ...*config.ServerConfig) *Manager { + m := &Manager{logger: zap.NewNop()} + m.globalConfig.Store(&config.Config{DockerIsolation: global, Servers: servers}) + return m + } + dockerMode := config.IsolationModeDocker + + t.Run("global mode docker with the legacy bool false", func(t *testing.T) { + m := newManager( + &config.DockerIsolationConfig{Mode: config.IsolationModeDocker, Enabled: false}, + &config.ServerConfig{Name: "npx-server", Command: "npx"}, + ) + assert.True(t, m.shouldEnableDockerRecovery(), + "global mode:docker containerises servers even with the legacy enabled flag false") + }) + + t.Run("per-server mode docker with global isolation off", func(t *testing.T) { + m := newManager( + &config.DockerIsolationConfig{Enabled: false}, + &config.ServerConfig{ + Name: "moded", + Command: "npx", + Isolation: &config.IsolationConfig{Mode: &dockerMode}, + }, + ) + assert.True(t, m.shouldEnableDockerRecovery(), + "a per-server mode:docker override is honoured at spawn, so its containers need recovery and cleanup") + }) + + t.Run("per-server sandbox mode under global docker still needs recovery for its siblings", func(t *testing.T) { + sandboxMode := config.IsolationModeSandbox + m := newManager( + &config.DockerIsolationConfig{Enabled: true}, + &config.ServerConfig{ + Name: "sandboxed", + Command: "npx", + Isolation: &config.IsolationConfig{Mode: &sandboxMode}, + }, + ) + assert.True(t, m.shouldEnableDockerRecovery(), + "the global mode is docker, so any server added later is containerised") + }) +} diff --git a/internal/upstream/managed/client.go b/internal/upstream/managed/client.go index ff508a2e8..2cd76e77e 100644 --- a/internal/upstream/managed/client.go +++ b/internal/upstream/managed/client.go @@ -561,19 +561,29 @@ func (mc *Client) ShouldRetry() bool { return mc.StateManager.ShouldRetry() } -// IsDockerIsolated returns true if this server will use Docker isolation. -// Used to select appropriate connect timeouts (Docker containers need more time for package installation). -func (mc *Client) IsDockerIsolated() bool { - gc := mc.globalConfig.Load() - if gc == nil || gc.DockerIsolation == nil || !gc.DockerIsolation.Enabled { - return false - } - // Check if server has isolation explicitly disabled - if mc.GetConfig().Isolation != nil && mc.GetConfig().Isolation.Enabled != nil && !*mc.GetConfig().Isolation.Enabled { - return false - } - // Only stdio servers with commands get Docker-isolated - return mc.GetConfig().Command != "" +// DependsOnDocker reports whether starting this server needs a working Docker +// daemon, and therefore whether its connect budget has to absorb an image pull. +// It is the ONLY input to the 3-minute connect-timeout floor +// (Manager.resolveConnectTimeout). +// +// It delegates to config.ServerDependsOnDocker, which is built on the SAME +// resolver the spawn path branches on, so the budget can never be chosen for a +// launch shape the server will not have — while still covering the server whose +// OWN command is `docker`, which the resolver deliberately reports as +// mode=none (we must not double-wrap it) but which pays image-pull latency all +// the same. +// +// It replaced a hand-rolled mirror of the two LEGACY booleans, which pre-date +// isolation modes: a per-server `mode: "docker"` override is honoured at spawn +// even over a legacy `enabled: false`, yet got the SHORT stdio timeout and +// could be killed mid-pull; while `mode: "sandbox"` servers were handed the long +// Docker budget they have no use for (GH #1142). +func (mc *Client) DependsOnDocker() bool { + var global *config.DockerIsolationConfig + if gc := mc.globalConfig.Load(); gc != nil { + global = gc.DockerIsolation + } + return config.ServerDependsOnDocker(global, mc.GetConfig()) } // SetUserLoggedOut marks that the user has explicitly logged out diff --git a/internal/upstream/managed/isolation_timeout_test.go b/internal/upstream/managed/isolation_timeout_test.go new file mode 100644 index 000000000..8181208b1 --- /dev/null +++ b/internal/upstream/managed/isolation_timeout_test.go @@ -0,0 +1,164 @@ +package managed + +import ( + "testing" + + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" +) + +func isoModePtr(m config.IsolationMode) *config.IsolationMode { return &m } + +// TestDependsOnDocker_MatchesResolver is the "one algorithm" invariant for the +// connect-timeout selection: DependsOnDocker picks the long Docker budget +// (image pull + package install) instead of the short stdio one, so for every +// server we CONTAINERISE it must agree with the resolver the SPAWN path +// branches on — config.ResolveIsolation. +// +// The predicate predated isolation MODES and only read the two legacy booleans, +// so it disagreed with the spawn decision in both directions: a per-server +// `mode: "docker"` override is honoured at spawn even over a legacy +// `enabled: false`, but was given the SHORT timeout and could time out mid-pull; +// while a `mode: "sandbox"` server was given the long Docker timeout it has no +// use for, stretching every failed connect. +// +// The one deliberate DIVERGENCE from the resolver is a server whose own command +// is `docker`: the resolver reports mode=none there because we must never +// double-wrap it, but it still pays image-pull latency, so it still needs the +// long budget. That case is asserted separately in +// TestDependsOnDocker_ServerRunningDockerItself. +func TestDependsOnDocker_MatchesResolver(t *testing.T) { + optOut, optIn := false, true + + tests := []struct { + name string + global *config.DockerIsolationConfig + srv *config.ServerConfig + want bool + }{ + { + name: "per-server docker mode wins over a legacy opt-out and an off global", + global: &config.DockerIsolationConfig{Enabled: false}, + srv: &config.ServerConfig{ + Name: "moded", + Command: "npx", + Isolation: &config.IsolationConfig{Mode: isoModePtr(config.IsolationModeDocker), Enabled: &optOut}, + }, + want: true, + }, + { + name: "global mode docker with the legacy bool left false", + global: &config.DockerIsolationConfig{Mode: config.IsolationModeDocker}, + srv: &config.ServerConfig{Name: "inheriting", Command: "npx"}, + want: true, + }, + { + name: "sandbox mode under global docker is not containerised", + global: &config.DockerIsolationConfig{Enabled: true}, + srv: &config.ServerConfig{ + Name: "sandboxed", + Command: "npx", + Isolation: &config.IsolationConfig{Mode: isoModePtr(config.IsolationModeSandbox)}, + }, + want: false, + }, + { + name: "legacy opt-out still wins when there is no mode override", + global: &config.DockerIsolationConfig{Enabled: true}, + srv: &config.ServerConfig{ + Name: "opted-out", + Command: "npx", + Isolation: &config.IsolationConfig{Enabled: &optOut}, + }, + want: false, + }, + { + name: "legacy opt-in is ignored while the global mode is none", + global: &config.DockerIsolationConfig{Enabled: false}, + srv: &config.ServerConfig{ + Name: "opted-in", + Command: "npx", + Isolation: &config.IsolationConfig{Enabled: &optIn}, + }, + want: false, + }, + { + name: "inheriting stdio server under global docker", + global: &config.DockerIsolationConfig{Enabled: true}, + srv: &config.ServerConfig{Name: "plain", Command: "uvx"}, + want: true, + }, + { + name: "http server has no child process to isolate", + global: &config.DockerIsolationConfig{Enabled: true}, + srv: &config.ServerConfig{Name: "remote", URL: "https://example.test/mcp"}, + want: false, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + resolved := config.ResolveIsolation(tc.global, tc.srv) + wantDocker := resolved.Mode == config.IsolationModeDocker + if wantDocker != tc.want { + t.Fatalf("test case expectation disagrees with the resolver: resolver says docker=%v (mode=%q source=%q), case wants %v", + wantDocker, resolved.Mode, resolved.Source, tc.want) + } + + mc := &Client{logger: zap.NewNop()} + mc.SetConfig(tc.srv) + mc.globalConfig.Store(&config.Config{DockerIsolation: tc.global}) + + if got := mc.DependsOnDocker(); got != tc.want { + t.Errorf("DependsOnDocker() = %v, want %v (resolver mode=%q source=%q)", + got, tc.want, resolved.Mode, resolved.Source) + } + }) + } +} + +// TestDependsOnDocker_ServerRunningDockerItself pins the deliberate divergence +// from config.ResolveIsolation described above. The resolver's already-docker +// structural gate answers the SPAWN question ("do we wrap this?" — no, never +// double-wrap), but the connect budget answers a different one ("will this +// server sit in an image pull before it answers initialize?" — yes). Collapsing +// the two dropped such a server from the 3-minute floor to the resolved +// init_timeout (30s by default), where it can be killed mid-pull (GH #1142). +func TestDependsOnDocker_ServerRunningDockerItself(t *testing.T) { + srv := &config.ServerConfig{ + Name: "dockerised", + Command: "docker", + Args: []string{"run", "-i", "--rm", "mcp/foo"}, + } + + for _, global := range []*config.DockerIsolationConfig{ + {Enabled: true}, + {Enabled: false}, + nil, + } { + resolved := config.ResolveIsolation(global, srv) + if resolved.Mode == config.IsolationModeDocker { + t.Fatalf("precondition: the resolver must NOT report mode=docker for a docker command, got %q (source %q)", + resolved.Mode, resolved.Source) + } + + mc := &Client{logger: zap.NewNop()} + mc.SetConfig(srv) + mc.globalConfig.Store(&config.Config{DockerIsolation: global}) + + if !mc.DependsOnDocker() { + t.Errorf("DependsOnDocker() = false for a command:\"docker\" server (global isolation %+v); it still pays image-pull latency", global) + } + } +} + +// TestDependsOnDocker_NilGlobalConfig keeps the hand-constructed-client path +// (no global config stored at all) answering false rather than panicking. +func TestDependsOnDocker_NilGlobalConfig(t *testing.T) { + mc := &Client{logger: zap.NewNop()} + mc.SetConfig(&config.ServerConfig{Name: "no-global", Command: "npx"}) + if mc.DependsOnDocker() { + t.Error("DependsOnDocker() = true with no global config stored, want false") + } +} diff --git a/internal/upstream/manager.go b/internal/upstream/manager.go index 7bc791ec9..0311a87ef 100644 --- a/internal/upstream/manager.go +++ b/internal/upstream/manager.go @@ -247,9 +247,31 @@ func NewManager(logger *zap.Logger, globalConfig *config.Config, boltStorage *st return manager } -// shouldEnableDockerRecovery returns true when Docker recovery should run based on config. -// It respects docker_recovery.enabled=false and only enables monitoring when Docker -// isolation is turned on or any server is explicitly using Docker commands. +// shouldEnableDockerRecovery returns true when Docker recovery should run based +// on config: does this proxy depend on a working Docker daemon at all? +// +// It respects docker_recovery.enabled=false, and otherwise composes the +// per-server config.ServerDependsOnDocker predicate into the per-manager +// question the monitor actually asks. The two halves are deliberately +// different shapes: +// +// - The GLOBAL half is forward-looking. The monitor is started once, at +// manager construction, but servers are added at runtime — so a global +// resolved mode of "docker" means "anything stdio we launch from now on is +// containerised", regardless of which servers happen to be configured now +// (this is also why an empty Servers list under global docker still +// enables recovery). +// - The PER-SERVER half then covers the configs the global mode does not: +// a per-server `isolation.mode: "docker"` override wins outright even when +// the global mode is none, and a server whose own command invokes docker +// needs the daemon whatever isolation says. +// +// It replaced a hand-rolled mirror of the two LEGACY booleans that never +// consulted isolation MODES, so `{mode:"docker", enabled:false}` (and a +// per-server mode override under a legacy-off global) left recovery monitoring +// off and let shutdown skip container cleanup, leaking containers — while a +// legacy per-server `enabled:true` under a none global mode, which the resolver +// IGNORES, switched the monitor on for containers that never exist (GH #1142). func (m *Manager) shouldEnableDockerRecovery() bool { if m == nil { return false @@ -264,22 +286,15 @@ func (m *Manager) shouldEnableDockerRecovery() bool { return false } - // Global Docker isolation enabled - if gc.DockerIsolation != nil && gc.DockerIsolation.Enabled { + // Global half: every stdio server, present or future, is containerised. + if gc.DockerIsolation.ResolvedMode() == config.IsolationModeDocker { return true } - // Detect servers that explicitly use Docker (e.g., docker run/exec commands) + // Per-server half: an override that resolves to docker, or a server whose + // own command is docker. for _, srv := range gc.Servers { - if srv == nil { - continue - } - - if srv.Isolation != nil && srv.Isolation.IsEnabled() { - return true - } - - if strings.Contains(srv.Command, "docker") { + if config.ServerDependsOnDocker(gc.DockerIsolation, srv) { return true } } @@ -288,29 +303,35 @@ func (m *Manager) shouldEnableDockerRecovery() bool { } // UsesDockerIsolation reports whether this manager could have launched -// Docker-isolated containers (global isolation on, a per-server isolation, or -// a docker command). When false, no container cleanup verification is needed -// on shutdown — shelling out to `docker ps` would be pure waste (and, in test -// processes, adds ~17s/Close via the verification loop). Same predicate the -// Docker recovery monitor uses, so behavior stays consistent. +// Docker containers (a global or per-server isolation mode that resolves to +// docker, or a server whose own command is docker). When false, no container +// cleanup verification is needed on shutdown — shelling out to `docker ps` +// would be pure waste (and, in test processes, adds ~17s/Close via the +// verification loop). Same predicate the Docker recovery monitor uses, so +// behavior stays consistent. func (m *Manager) UsesDockerIsolation() bool { return m.shouldEnableDockerRecovery() } // resolveConnectTimeout computes the deadline for an upstream's MCP `initialize` // handshake (MCP-3322 / GH #760). It resolves the per-server → global → 30s -// default init_timeout via Config.ResolveInitTimeout. For Docker-isolated -// servers — which may need to pull/install a package before answering -// `initialize` — it keeps a 3-minute floor so a small init_timeout never -// regresses the historical Docker grace period; a larger init_timeout still -// wins. Un-isolated stdio servers (the bite in #760) now get the resolved +// default init_timeout via Config.ResolveInitTimeout. For servers that depend on +// Docker — which may need to pull an image or install a package before +// answering `initialize` — it keeps a 3-minute floor so a small init_timeout +// never regresses the historical Docker grace period; a larger init_timeout +// still wins. Un-isolated stdio servers (the bite in #760) now get the resolved // deadline instead of silently inheriting the caller's ~30s context. -func (m *Manager) resolveConnectTimeout(serverConfig *config.ServerConfig, dockerIsolated bool) time.Duration { +// +// dependsOnDocker is managed.Client.DependsOnDocker: it covers BOTH "we +// containerise it" and "its own command is docker". It is deliberately not the +// launch-shape question — a server that already runs docker is never wrapped by +// us, yet pays exactly the same image-pull latency (GH #1142). +func (m *Manager) resolveConnectTimeout(serverConfig *config.ServerConfig, dependsOnDocker bool) time.Duration { timeout := 30 * time.Second if gc := m.globalConfig.Load(); gc != nil { timeout = gc.ResolveInitTimeout(serverConfig) } - if dockerIsolated && timeout < 3*time.Minute { + if dependsOnDocker && timeout < 3*time.Minute { timeout = 3 * time.Minute } return timeout @@ -542,7 +563,7 @@ func (m *Manager) AddServer(id string, serverConfig *config.ServerConfig) error // Connect to server with the resolved init_timeout (MCP-3322) to prevent // hanging while still honoring a per-server/global handshake deadline. - ctx, cancel := context.WithTimeout(context.Background(), m.resolveConnectTimeout(serverConfig, client.IsDockerIsolated())) + ctx, cancel := context.WithTimeout(context.Background(), m.resolveConnectTimeout(serverConfig, client.DependsOnDocker())) defer cancel() if err := client.Connect(ctx); err != nil { // Check if this is an OAuth error - don't fail AddServer for OAuth @@ -1523,7 +1544,7 @@ func (m *Manager) ConnectAll(ctx context.Context) error { // un-isolated stdio servers silently inherited the caller's ~30s // context — the #760 bite. resolveConnectTimeout keeps the 3min floor // for Docker isolation while honoring a per-server/global override. - connectCtx, cancel := context.WithTimeout(ctx, m.resolveConnectTimeout(c.GetConfig(), c.IsDockerIsolated())) + connectCtx, cancel := context.WithTimeout(ctx, m.resolveConnectTimeout(c.GetConfig(), c.DependsOnDocker())) defer cancel() if err := c.Connect(connectCtx); err != nil { @@ -1902,7 +1923,7 @@ func (m *Manager) RetryConnection(serverName string) error { // Honor the resolved init_timeout (MCP-3322) on the post-OAuth retry too, // with a 2-minute floor so this path never regresses below its historical // grace period. - retryTimeout := m.resolveConnectTimeout(client.GetConfig(), client.IsDockerIsolated()) + retryTimeout := m.resolveConnectTimeout(client.GetConfig(), client.DependsOnDocker()) if retryTimeout < 2*time.Minute { retryTimeout = 2 * time.Minute } diff --git a/internal/upstream/manager_docker_recovery_test.go b/internal/upstream/manager_docker_recovery_test.go index e0cce335f..a3fc35473 100644 --- a/internal/upstream/manager_docker_recovery_test.go +++ b/internal/upstream/manager_docker_recovery_test.go @@ -11,6 +11,7 @@ import ( "go.uber.org/zap" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" ) @@ -152,3 +153,82 @@ func TestFreshenLoadedDockerRecoveryState_NilSafe(t *testing.T) { }() freshenLoadedDockerRecoveryState(nil) } + +// TestShouldEnableDockerRecovery_PerServerTriState pins the behaviour of the +// per-server isolation clause in shouldEnableDockerRecovery across the legacy +// `enabled` *bool tri-state, now that the clause routes through +// config.ServerDependsOnDocker instead of reading the bool by hand (GH #1142). +// With global isolation off, NO value of the legacy bool containerises the +// server: nil is "inherit" (which the global answer already covers), false is +// an opt-out, and true is an opt-in the resolver deliberately IGNORES under a +// none global mode. Isolation MODES are covered by +// TestShouldEnableDockerRecovery_HonorsIsolationModes. +func TestShouldEnableDockerRecovery_PerServerTriState(t *testing.T) { + newManager := func(servers ...*config.ServerConfig) *Manager { + m := &Manager{logger: zap.NewNop()} + m.globalConfig.Store(&config.Config{ + DockerIsolation: &config.DockerIsolationConfig{Enabled: false}, + Servers: servers, + }) + return m + } + + t.Run("global off and per-server nil stays off", func(t *testing.T) { + m := newManager(&config.ServerConfig{ + Name: "npx-server", + Command: "npx", + Isolation: &config.IsolationConfig{Image: "node:22"}, + }) + if m.shouldEnableDockerRecovery() { + t.Error("an inheriting (nil) per-server override must not enable Docker recovery when global isolation is off") + } + }) + + t.Run("global off and per-server explicit false stays off", func(t *testing.T) { + m := newManager(&config.ServerConfig{ + Name: "npx-server", + Command: "npx", + Isolation: &config.IsolationConfig{Enabled: config.BoolPtr(false)}, + }) + if m.shouldEnableDockerRecovery() { + t.Error("an explicit opt-out must not enable Docker recovery") + } + }) + + t.Run("global off and per-server explicit true stays off", func(t *testing.T) { + // The resolver reports IsolationSourceServerOptInIgnored here: a legacy + // bool opt-in cannot revive isolation while the global mode is none, so + // the server is NOT containerised and there are no containers to + // monitor or clean up. The old hand-rolled clause started the monitor + // anyway. + m := newManager(&config.ServerConfig{ + Name: "npx-server", + Command: "npx", + Isolation: &config.IsolationConfig{Enabled: config.BoolPtr(true)}, + }) + if m.shouldEnableDockerRecovery() { + t.Error("a bool opt-in the resolver ignores must not enable Docker recovery") + } + }) + + t.Run("a server whose own command is docker enables recovery", func(t *testing.T) { + m := newManager(&config.ServerConfig{ + Name: "already-dockerised", + Command: "docker", + Args: []string{"run", "-i", "--rm", "mcp/foo"}, + }) + if !m.shouldEnableDockerRecovery() { + t.Error("a server that shells out to docker itself needs the daemon, and its containers need cleanup") + } + }) + + t.Run("global isolation on enables recovery regardless", func(t *testing.T) { + m := &Manager{logger: zap.NewNop()} + m.globalConfig.Store(&config.Config{ + DockerIsolation: &config.DockerIsolationConfig{Enabled: true}, + }) + if !m.shouldEnableDockerRecovery() { + t.Error("global isolation on must enable Docker recovery") + } + }) +} diff --git a/native/macos/MCPProxy/MCPProxy/API/Models.swift b/native/macos/MCPProxy/MCPProxy/API/Models.swift index 8158dc797..6d067c111 100644 --- a/native/macos/MCPProxy/MCPProxy/API/Models.swift +++ b/native/macos/MCPProxy/MCPProxy/API/Models.swift @@ -237,7 +237,20 @@ struct DiagnosticPayload: Codable, Equatable { /// tray can both display and edit them. Mirrors the /// `contracts.IsolationConfig` struct on the Go side. struct IsolationConfigStatus: Codable, Equatable { + /// EFFECTIVE isolation state: what actually happens when the server spawns, + /// after the global setting, the per-server override and the structural + /// gates. NOT the raw override — read `enabledOverride` for that. + /// + /// Reading this as the override is exactly what corrupted configs before + /// GH #1142: an inheriting server reported `false`, the edit form seeded a + /// toggle from it, and saving any isolation field persisted an explicit + /// opt-out that silently un-containerised the server. let enabled: Bool + /// RAW per-server override. `nil` means "inherit the global setting" — a + /// distinct state from an explicit `false`. + let enabledOverride: Bool? + /// RAW per-server mode override ("docker" | "sandbox" | "none"). + let modeOverride: String? let image: String? let networkMode: String? let extraArgs: [String]? @@ -245,12 +258,62 @@ struct IsolationConfigStatus: Codable, Equatable { enum CodingKeys: String, CodingKey { case enabled, image + case enabledOverride = "enabled_override" + case modeOverride = "mode_override" case networkMode = "network_mode" case extraArgs = "extra_args" case workingDir = "working_dir" } } +/// Resolved isolation state plus the rule that produced it, so the tray can say +/// WHY a server is (or is not) isolated instead of showing an ambiguous flag. +/// Mirrors `contracts.IsolationEffective` on the Go side. +struct IsolationEffectiveStatus: Codable, Equatable { + let mode: String // "docker" | "sandbox" | "none" + let isolated: Bool + let globalMode: String? + let inherited: Bool + /// "global" | "server-mode" | "server-opt-out" | "server-opt-in-ignored" | + /// "not-stdio" | "already-docker" | "sandbox-unavailable" | + /// "unsupported-mode". Treat anything else as "global". + let source: String? + + enum CodingKeys: String, CodingKey { + case mode, isolated, inherited, source + case globalMode = "global_mode" + } + + /// One-line explanation for the read-only Config tab. + var explanation: String { + let global = (globalMode?.isEmpty == false) ? globalMode! : "none" + switch source { + case "server-mode": + return "Mode set for this server: \(mode)" + case "server-opt-out": + return "Turned off for this server (global setting is \(global))" + case "server-opt-in-ignored": + return "Turned on for this server, but global isolation is off — the setting is ignored" + case "not-stdio": + return "No local process to isolate" + case "already-docker": + return "This server already runs Docker itself" + case "sandbox-unavailable": + // The mode is set, but the spawn path degrades to unconfined here: + // Landlock is Linux-only, so a Mac never enforces it. + return "Sandbox mode is set, but this system cannot enforce it — the server runs unconfined" + case "unsupported-mode": + return "Isolation mode \(mode) is not one this version implements — the server runs unconfined" + default: + return inherited ? "Inherits the global setting (\(global))" : "Turned on for this server" + } + } + + var label: String { + isolated ? "Isolated (\(mode))" : "Not isolated" + } +} + /// Resolved baseline isolation values for a server's detected runtime, /// computed by the backend from the global DockerIsolationConfig + the /// server's command. The tray uses these as field placeholders so the @@ -313,6 +376,7 @@ struct ServerStatus: Codable, Identifiable, Equatable { let quarantine: QuarantineStats? let isolation: IsolationConfigStatus? let isolationDefaults: IsolationDefaultsStatus? + let isolationEffective: IsolationEffectiveStatus? let error: String? /// Spec 044 — stable error code (e.g. MCPX_STDIO_SPAWN_ENOENT) and the /// structured diagnostic payload. Present only when the server has an @@ -342,6 +406,7 @@ struct ServerStatus: Codable, Identifiable, Equatable { case quarantine case isolation case isolationDefaults = "isolation_defaults" + case isolationEffective = "isolation_effective" case error case errorCode = "error_code" case diagnostic diff --git a/native/macos/MCPProxy/MCPProxy/Views/AddServerView.swift b/native/macos/MCPProxy/MCPProxy/Views/AddServerView.swift index 5fc397058..00ef96147 100644 --- a/native/macos/MCPProxy/MCPProxy/Views/AddServerView.swift +++ b/native/macos/MCPProxy/MCPProxy/Views/AddServerView.swift @@ -700,7 +700,9 @@ extension ManualServerForm { /// Extracted as a pure function so the field-gating rules (isolation is /// stdio-only; url vs command by transport) are unit-testable without a /// running app or API client. The `isolation` override is emitted ONLY for - /// stdio transports so a URL-based server can never carry an isolation flag. + /// stdio transports (so a URL-based server can never carry an isolation + /// flag) and ONLY when the toggle is on (so an untouched form leaves the + /// server inheriting the global setting). static func makeServerConfig( name: String, selectedProtocol: String, @@ -730,10 +732,23 @@ extension ManualServerForm { config["args"] = args } // The backend server-create payload takes an `isolation` object - // ({"enabled": …}); the old top-level `docker_isolation` bool it - // never read, so the toggle silently did nothing. Emit the real - // field so an stdio server actually records its isolation choice. - config["isolation"] = ["enabled": dockerIsolation] + // ({"enabled_override": …}); the old top-level `docker_isolation` + // bool it never read, so the toggle silently did nothing. + // + // The key is `enabled_override`, not `enabled`: `enabled` is the + // read-only EFFECTIVE state on the read surface and the backend + // rejects it on writes, so that reading a server and writing the + // object back cannot rewrite the override (GH #1142). + // + // Emit the object ONLY when the box is ticked. An unticked box + // means "inherit the global setting", NOT "never isolate" — sending + // a `false` unconditionally stamped a permanent explicit opt-out on + // every stdio server added here, so it would ignore global Docker + // isolation forever. Matches AddServerModal.vue, which only writes + // isolation_json when on. + if dockerIsolation { + config["isolation"] = ["enabled_override": true] + } } else { // URL transports carry no command and no isolation flag. config["url"] = url.trimmingCharacters(in: .whitespaces) diff --git a/native/macos/MCPProxy/MCPProxy/Views/ServerDetailView.swift b/native/macos/MCPProxy/MCPProxy/Views/ServerDetailView.swift index e2adc3d1a..3ee4e658e 100644 --- a/native/macos/MCPProxy/MCPProxy/Views/ServerDetailView.swift +++ b/native/macos/MCPProxy/MCPProxy/Views/ServerDetailView.swift @@ -22,6 +22,46 @@ enum ServerDetailTab: String, CaseIterable { } } +// MARK: - Isolation Override (GH #1142) + +/// The three states of the per-server `isolation.enabled` override. +/// +/// A two-state toggle cannot express this: `nil` on the wire means "inherit the +/// global setting", which is NOT the same as an explicit `false`. Collapsing +/// them is what let an ordinary image edit silently un-containerise a server. +enum IsolationOverride: Equatable { + case inherit + case forceOn + case forceOff + + /// Seeded from the RAW override — never from the effective state. + init(rawOverride: Bool?) { + switch rawOverride { + case .none: self = .inherit + case .some(true): self = .forceOn + case .some(false): self = .forceOff + } + } + + /// The value to send for `isolation.enabled_override`: a bool, or NSNull to + /// clear the override back to inherit (an omitted key means "leave alone"). + var patchValue: Any { + switch self { + case .inherit: return NSNull() + case .forceOn: return true + case .forceOff: return false + } + } +} + +/// The editable per-server isolation override fields, as text. +struct IsolationEditState: Equatable { + var image: String + var networkMode: String + var extraArgs: [String] + var workingDir: String +} + // MARK: - Server Detail View struct ServerDetailView: View { @@ -65,7 +105,8 @@ struct ServerDetailView: View { @State private var editHeaders = "" @State private var editEnabled = true @State private var editQuarantined = false - @State private var editDockerIsolation = false + @State private var editIsolationOverride: IsolationOverride = .inherit + @State private var originalIsolationOverride: IsolationOverride = .inherit @State private var editSkipQuarantine = false // Per-server Docker isolation overrides. @State private var editIsolationImage = "" @@ -551,14 +592,21 @@ struct ServerDetailView: View { hint: "When disabled, the server will not connect or be available to AI agents.") configToggleRow(label: "Quarantined", isOn: $editQuarantined, hint: "New tools must be reviewed and approved before AI agents can use them. Protects against tool poisoning attacks.") - configToggleRow(label: "Docker Isolation", isOn: $editDockerIsolation, - hint: "Runs the server in an isolated Docker container. Prevents access to your filesystem, network, and other system resources. Recommended for untrusted servers.") + // Three-state, because "inherit the global setting" + // is a real state a toggle cannot express (GH #1142). + isolationOverridePicker() configToggleRow(label: "Skip Quarantine", isOn: $editSkipQuarantine) } else { configRow(label: "Enabled", value: server.enabled ? "Yes" : "No") if server.quarantined { configRow(label: "Quarantined", value: "Yes") } + // Report the EFFECTIVE isolation state and why — + // the raw flag alone cannot say whether a server is + // inheriting or explicitly opted out. + if let eff = server.isolationEffective { + configRow(label: "Isolation", value: "\(eff.label) — \(eff.explanation)") + } } } @@ -622,11 +670,17 @@ struct ServerDetailView: View { } // Docker isolation overrides (only relevant for stdio servers). - // The global "Docker Isolation" toggle in the General section - // enables isolation for this server; these fields customize how - // that isolation is provisioned. + // The override picker in the General section decides WHETHER + // this server is isolated; these fields customize how that + // isolation is provisioned. if server.protocol == "stdio" { configSection(title: "Docker Isolation Overrides") { + // Effective state first: the raw override alone + // cannot say whether the server inherits or was + // explicitly opted out (GH #1142). + if let eff = server.isolationEffective { + configRow(label: "Effective", value: "\(eff.label) — \(eff.explanation)") + } if isEditing { let defaults = server.isolationDefaults let imagePlaceholder = isolationPlaceholder( @@ -859,6 +913,82 @@ struct ServerDetailView: View { } } + /// Builds the `isolation` PATCH body from the edit form, or nil when + /// nothing changed. + /// + /// Pure and static so the rule that matters can be unit-tested without a + /// running app: **`enabled_override` is emitted only when the override + /// picker actually moved.** The previous code force-added it to every + /// isolation patch, so editing an unrelated sub-field on a server that + /// merely INHERITED global isolation persisted an explicit opt-out and + /// silently un-containerised it (GH #1142). A move back to `.inherit` sends + /// JSON null, because an omitted key means "leave the persisted value alone". + /// + /// The key is `enabled_override`, never `enabled`: on a READ, `enabled` is + /// the EFFECTIVE state (global setting + override + structural gates), so + /// writing that key back is how a read-modify-write turns "inherits the + /// global setting" into a permanent override. The backend rejects it. + static func buildIsolationPatch( + override: IsolationOverride, + originalOverride: IsolationOverride, + edited: IsolationEditState, + original: IsolationEditState + ) -> [String: Any]? { + var iso: [String: Any] = [:] + + if override != originalOverride { + iso["enabled_override"] = override.patchValue + } + if edited.image != original.image { + iso["image"] = edited.image + } + if edited.networkMode != original.networkMode { + iso["network_mode"] = edited.networkMode + } + if edited.extraArgs != original.extraArgs { + iso["extra_args"] = edited.extraArgs + } + if edited.workingDir != original.workingDir { + iso["working_dir"] = edited.workingDir + } + + return iso.isEmpty ? nil : iso + } + + /// Three-state override control. The "Inherit" option names what the + /// global setting currently resolves to, so the user can see the + /// consequence of leaving it alone. + @ViewBuilder + private func isolationOverridePicker() -> some View { + let inheritLabel: String = { + if let g = server.isolationEffective?.globalMode, !g.isEmpty { + return "Inherit global (\(g))" + } + return "Inherit global" + }() + + VStack(alignment: .leading, spacing: 2) { + HStack { + Text("Docker Isolation") + .font(.scaled(.subheadline, scale: fontScale)) + .foregroundStyle(.secondary) + .frame(width: 140, alignment: .trailing) + Picker("", selection: $editIsolationOverride) { + Text(inheritLabel).tag(IsolationOverride.inherit) + Text("Always isolate").tag(IsolationOverride.forceOn) + Text("Never isolate").tag(IsolationOverride.forceOff) + } + .labelsHidden() + .frame(maxWidth: 220, alignment: .leading) + Spacer() + } + Text("Runs the server in an isolated Docker container, preventing access to your filesystem, network, and other system resources. \"Inherit global\" follows the app-wide setting.") + .font(.scaled(.caption2, scale: fontScale)) + .foregroundStyle(.tertiary) + .padding(.leading, 148) + } + } + @ViewBuilder private func configToggleRow(label: String, isOn: Binding, hint: String? = nil) -> some View { VStack(alignment: .leading, spacing: 2) { @@ -998,7 +1128,10 @@ struct ServerDetailView: View { .joined(separator: "\n") editEnabled = server.enabled editQuarantined = server.quarantined - editDockerIsolation = server.isolation?.enabled ?? false + // Seed from the RAW override, NOT from `enabled` (which is now the + // effective state, and was always the wrong thing to edit) — GH #1142. + editIsolationOverride = IsolationOverride(rawOverride: server.isolation?.enabledOverride) + originalIsolationOverride = editIsolationOverride editSkipQuarantine = false // read from config if available let iso = server.isolation editIsolationImage = iso?.image ?? "" @@ -1066,11 +1199,9 @@ struct ServerDetailView: View { if editEnabled != server.enabled { updates["enabled"] = editEnabled } if editQuarantined != server.quarantined { updates["quarantined"] = editQuarantined } - // Docker isolation (stdio only). Send any field that changed — - // we always include `enabled` because the handler tracks the - // boolean explicitly, and sending just the sub-fields without - // it would leave the isolation off on a server that never had - // it enabled before. + // Docker isolation (stdio only). Only genuinely-changed fields are + // sent; `enabled_override` appears ONLY when the user actually moved + // the override picker (GH #1142). if server.protocol == "stdio" { let existing = server.isolation let newExtra = editIsolationExtraArgs @@ -1081,36 +1212,22 @@ struct ServerDetailView: View { let newNetwork = editIsolationNetworkMode.trimmingCharacters(in: .whitespaces) let newWorkDir = editIsolationWorkingDir.trimmingCharacters(in: .whitespaces) - var iso: [String: Any] = [:] - var isoChanged = false - - if editDockerIsolation != (existing?.enabled ?? false) { - iso["enabled"] = editDockerIsolation - isoChanged = true - } - if newImage != (existing?.image ?? "") { - iso["image"] = newImage - isoChanged = true - } - if newNetwork != (existing?.networkMode ?? "") { - iso["network_mode"] = newNetwork - isoChanged = true - } - if newExtra != (existing?.extraArgs ?? []) { - iso["extra_args"] = newExtra - isoChanged = true - } - if newWorkDir != (existing?.workingDir ?? "") { - iso["working_dir"] = newWorkDir - isoChanged = true - } - - if isoChanged { - // Always include `enabled` alongside any sub-field change so - // the backend applies the full intended isolation state. - if iso["enabled"] == nil { - iso["enabled"] = editDockerIsolation - } + if let iso = Self.buildIsolationPatch( + override: editIsolationOverride, + originalOverride: originalIsolationOverride, + edited: IsolationEditState( + image: newImage, + networkMode: newNetwork, + extraArgs: newExtra, + workingDir: newWorkDir + ), + original: IsolationEditState( + image: existing?.image ?? "", + networkMode: existing?.networkMode ?? "", + extraArgs: existing?.extraArgs ?? [], + workingDir: existing?.workingDir ?? "" + ) + ) { updates["isolation"] = iso } } diff --git a/native/macos/MCPProxy/MCPProxyTests/AddServerIsolationFieldTests.swift b/native/macos/MCPProxy/MCPProxyTests/AddServerIsolationFieldTests.swift index b1475a60a..6a528da0c 100644 --- a/native/macos/MCPProxy/MCPProxyTests/AddServerIsolationFieldTests.swift +++ b/native/macos/MCPProxy/MCPProxyTests/AddServerIsolationFieldTests.swift @@ -51,9 +51,40 @@ final class AddServerIsolationFieldTests: XCTestCase { XCTAssertNil(config["url"], "a stdio server must not carry a url") let isolation = config["isolation"] as? [String: Any] XCTAssertEqual( - isolation?["enabled"] as? Bool, true, + isolation?["enabled_override"] as? Bool, true, "a stdio server records its isolation choice via the backend `isolation` object" ) + XCTAssertNil( + isolation?["enabled"] as Any?, + "`enabled` is the read-only EFFECTIVE state — the writable key is `enabled_override` (GH #1142)" + ) + } + + // (c-1b) The toggle OFF must emit NO isolation key at all (GH #1142). + // Emitting `["enabled": false]` unconditionally wrote a permanent explicit + // opt-out onto every stdio server added from the tray, so the server would + // ignore global Docker isolation forever — a silent security downgrade the + // user never asked for. "Off" here means "inherit the global setting", + // matching AddServerModal.vue, which only writes isolation_json when the + // box is ticked. + func testStdioToggleOffOmitsIsolation() { + let config = ManualServerForm.makeServerConfig( + name: "local-fs", + selectedProtocol: "stdio", + enabled: true, + dockerIsolation: false, + quarantined: false, + url: "", + command: "npx", + argsText: "@modelcontextprotocol/server-filesystem", + workingDir: "", + envText: "" + ) + XCTAssertEqual(config["command"] as? String, "npx") + XCTAssertNil( + config["isolation"], + "an unticked isolation box means \"inherit the global setting\" — it must not persist an explicit opt-out" + ) } // (c-2) A brand-new HTTP server config never carries an enabled isolation, diff --git a/native/macos/MCPProxy/MCPProxyTests/IsolationOverridePatchTests.swift b/native/macos/MCPProxy/MCPProxyTests/IsolationOverridePatchTests.swift new file mode 100644 index 000000000..30b4f66e4 --- /dev/null +++ b/native/macos/MCPProxy/MCPProxyTests/IsolationOverridePatchTests.swift @@ -0,0 +1,123 @@ +// IsolationOverridePatchTests.swift +// MCPProxyTests +// +// GH #1142 — the tray was a data-corruption path, not just a display bug. +// +// The API used to report the RAW per-server `isolation.enabled` override +// flattened to a bool, so a server that inherited global isolation (override +// nil, container actually running) arrived as `enabled: false`. The edit form +// seeded its toggle from that value and then force-added `enabled` to every +// isolation PATCH. Editing an unrelated field — the image — therefore persisted +// an explicit opt-out and silently un-containerised the server. +// +// These tests pin the pure edit-form → PATCH-dict builder over the tri-state. + +import XCTest +@testable import MCPProxy + +final class IsolationOverridePatchTests: XCTestCase { + + private let unchanged = IsolationEditState( + image: "python:3.11", networkMode: "", extraArgs: [], workingDir: "" + ) + + // THE regression: changing only the image must not emit `enabled`. + func testImageOnlyChangeEmitsNoEnabledKey() throws { + let patch = ServerDetailView.buildIsolationPatch( + override: .inherit, + originalOverride: .inherit, + edited: IsolationEditState( + image: "python:3.12", networkMode: "", extraArgs: [], workingDir: "" + ), + original: unchanged + ) + let iso = try XCTUnwrap(patch) + XCTAssertEqual(iso["image"] as? String, "python:3.12") + XCTAssertNil( + iso["enabled_override"] as Any?, + "an untouched isolation toggle must never appear in the PATCH — that is what silently wrote an explicit opt-out" + ) + XCTAssertNil( + iso["enabled"] as Any?, + "`enabled` is the read-only EFFECTIVE state; writing it back is the read-modify-write corruption path" + ) + } + + // Nothing changed at all → no PATCH. + func testNoChangeEmitsNoPatch() { + XCTAssertNil(ServerDetailView.buildIsolationPatch( + override: .inherit, + originalOverride: .inherit, + edited: unchanged, + original: unchanged + )) + } + + // Moving off "inherit" is a deliberate act and must be sent explicitly. + func testForceOffEmitsExplicitFalse() throws { + let patch = ServerDetailView.buildIsolationPatch( + override: .forceOff, + originalOverride: .inherit, + edited: unchanged, + original: unchanged + ) + let iso = try XCTUnwrap(patch) + XCTAssertEqual(iso["enabled_override"] as? Bool, false) + XCTAssertNil(iso["enabled"] as Any?, "the write key is `enabled_override`") + } + + func testForceOnEmitsExplicitTrue() throws { + let patch = ServerDetailView.buildIsolationPatch( + override: .forceOn, + originalOverride: .inherit, + edited: unchanged, + original: unchanged + ) + let iso = try XCTUnwrap(patch) + XCTAssertEqual(iso["enabled_override"] as? Bool, true) + XCTAssertNil(iso["enabled"] as Any?, "the write key is `enabled_override`") + } + + // Going back to "inherit" must send an explicit null, otherwise the + // override is unclearable — an omitted key means "leave alone". + func testBackToInheritEmitsNull() throws { + let patch = ServerDetailView.buildIsolationPatch( + override: .inherit, + originalOverride: .forceOff, + edited: unchanged, + original: unchanged + ) + let iso = try XCTUnwrap(patch) + XCTAssertTrue( + iso["enabled_override"] is NSNull, + "clearing the override back to inherit must send JSON null, not omit the key" + ) + } + + // A sub-field edit on a server that IS explicitly opted out must still not + // restate `enabled` — the persisted value is not the form's to re-assert. + func testSubFieldEditOnExplicitServerDoesNotRestateEnabled() throws { + let patch = ServerDetailView.buildIsolationPatch( + override: .forceOff, + originalOverride: .forceOff, + edited: IsolationEditState( + image: "", networkMode: "none", extraArgs: [], workingDir: "" + ), + original: IsolationEditState( + image: "", networkMode: "bridge", extraArgs: [], workingDir: "" + ) + ) + let iso = try XCTUnwrap(patch) + XCTAssertEqual(iso["network_mode"] as? String, "none") + XCTAssertNil(iso["enabled_override"] as Any?) + XCTAssertNil(iso["enabled"] as Any?) + } + + // The picker must be seeded from the RAW override, never from the + // effective state — that conflation is the whole bug. + func testOverrideSeededFromRawTriState() { + XCTAssertEqual(IsolationOverride(rawOverride: nil), .inherit) + XCTAssertEqual(IsolationOverride(rawOverride: true), .forceOn) + XCTAssertEqual(IsolationOverride(rawOverride: false), .forceOff) + } +} diff --git a/oas/docs.go b/oas/docs.go index 530e07a6a..7feefcfd9 100644 --- a/oas/docs.go +++ b/oas/docs.go @@ -6,10 +6,10 @@ import "github.com/swaggo/swag/v2" const docTemplate = `{ "schemes": {{ marshal .Schemes }}, - "components": {"schemas":{"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: 100000)","type":"integer"},"activity_max_response_size":{"description":"Response truncation limit in bytes (default: 65536)","type":"integer"},"activity_max_size_mb":{"description":"Max total activity-log size in MB before pruning oldest (default: 256, 0=disabled)","type":"integer"},"activity_retention_days":{"description":"Activity logging settings (RFC-003)","type":"integer"},"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"},"api_key":{"description":"Security settings","type":"string"},"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_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_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":"Advertised on every tool as ` + "`" + `_meta.anthropic/maxResultSizeChars` + "`" + `; raises Claude Code's inline-response ceiling from 50k to up to 500k chars. Set to 0 to disable.","type":"integer"},"mcpServers":{"items":{"$ref":"#/components/schemas/config.ServerConfig"},"type":"array","uniqueItems":false},"oauth_expiry_warning_hours":{"description":"Health status settings","type":"number"},"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"},"telemetry":{"$ref":"#/components/schemas/config.TelemetryConfig"},"tls":{"$ref":"#/components/schemas/config.TLSConfig"},"tokenizer":{"$ref":"#/components/schemas/config.TokenizerConfig"},"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},"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.","type":"boolean"}},"type":"object"},"config.OAuthConfig":{"description":"OAuth configuration (keep even when empty to signal OAuth requirement)","properties":{"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"},"scopes":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"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":{"name":{"description":"URL slug, validated","type":"string"},"servers":{"description":"references to mcpServers[].name","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"},"deep_scan":{"$ref":"#/components/schemas/config.DeepScanConfig"},"integrity_check_interval":{"type":"string"},"integrity_check_on_restart":{"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_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"}},"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"},"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_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 or\nunrecognized value as manual (secure by default). 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":{"certs_dir":{"description":"Directory for certificates","type":"string"},"enabled":{"description":"Enable HTTPS","type":"boolean"},"hsts":{"description":"Enable HTTP Strict Transport Security","type":"boolean"},"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.","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\"","type":"string"}},"type":"object"},"connect.ConnectResult":{"description":"The full result; its action mirrors the top-level one","properties":{"action":{"description":"\"created\", \"updated\", \"already_exists\", \"removed\", \"not_found\"","type":"string"},"backup_path":{"type":"string"},"client":{"type":"string"},"config_path":{"type":"string"},"message":{"type":"string"},"server_name":{"type":"string"},"success":{"type":"boolean"}},"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.ActivityRecord":{"properties":{"arguments":{"description":"Tool call arguments","type":"object"},"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_message":{"description":"Error details if status is \"error\"","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"},"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"},"tool_name":{"description":"Name of tool called","type":"string"},"type":{"$ref":"#/components/schemas/contracts.ActivityType"},"work_session_id":{"description":"Spec 082: one client, one project, across reconnects","type":"string"}},"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"},"period":{"description":"Time period (1h, 24h, 7d, 30d)","type":"string"},"rejected_count":{"description":"RejectedCount is the number of calls shed by a concurrency limiter before\nthey reached an upstream (spec 093). Counted separately from errors: it is\nproxy backpressure, not an upstream fault, and it is the signal an\noperator right-sizes max_concurrent_requests 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.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":{"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},"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"},"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":{"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)","type":"string"},"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"},"summary":{"description":"Summary is a human-readable status message (e.g., \"Connected (5 tools)\")","type":"string"}},"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":{"type":"boolean"},"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"memory_limit":{"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.LogEntry":{"properties":{"fields":{"type":"object"},"level":{"type":"string"},"message":{"type":"string"},"server":{"type":"string"},"timestamp":{"type":"string"}},"type":"object"},"contracts.MCPSession":{"properties":{"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"},"start_time":{"type":"string"},"status":{"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_url":{"type":"string"},"client_id":{"type":"string"},"extra_params":{"additionalProperties":{"type":"string"},"type":"object"},"pkce_enabled":{"type":"boolean"},"redirect_port":{"type":"integer"},"scopes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"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.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"]},"contracts.PreflightRequest":{"properties":{"policy":{"$ref":"#/components/schemas/contracts.PreflightPolicy"},"profile":{"description":"Profile evaluates under a named profile's server scope. 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"},"headers":{"additionalProperties":{"type":"string"},"type":"object"},"health":{"$ref":"#/components/schemas/contracts.HealthStatus"},"id":{"type":"string"},"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"},"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"},"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_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"},"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.SuccessResponse":{"properties":{"data":{"type":"object"},"success":{"type":"boolean"}},"type":"object"},"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":{"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"},"schema":{"type":"object"},"server_name":{"type":"string"},"usage":{"type":"integer"}},"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"},"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"},"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_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"},"data":{"properties":{"data":{"$ref":"#/components/schemas/contracts.InfoResponse"}},"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"},"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"},"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.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.ConnectConflictResponse":{"properties":{"action":{"description":"already_exists | precondition_failed","type":"string"},"data":{"$ref":"#/components/schemas/connect.ConnectResult"},"error":{"description":"Human-readable message","type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.ConnectRequest":{"properties":{"force":{"description":"Overwrite existing entry","type":"boolean"},"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"},"server_name":{"description":"Defaults to \"mcpproxy\"","type":"string"}},"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":{"content":{"description":"Raw JSON or TOML content","type":"string"},"format":{"description":"Optional format hint","type":"string"},"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"},"fields_skipped":{"items":{"type":"string"},"type":"array","uniqueItems":false},"name":{"type":"string"},"original_name":{"type":"string"},"protocol":{"type":"string"},"source_format":{"type":"string"},"url":{"type":"string"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.IsolationRequest":{"description":"Isolation carries per-server Docker isolation overrides (image,\nnetwork_mode, extra_args, working_dir, enabled). A nil pointer\nmeans \"do not touch isolation config\"; an empty-but-present\nobject on PATCH intentionally clears the overrides.","properties":{"enabled":{"type":"boolean"},"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"network_mode":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"httpapi.OnboardingMarkRequest":{"properties":{"connect_step_status":{"description":"ConnectStepStatus is one of: \"\", \"completed\", \"skipped\". Empty\npreserves the existing value. The stored enum is wider (Spec 080\nFR-001): a \"skipped\" request for a previously untouched connect step\nis upgraded server-side to \"completed_external\" when the install\nshows positive evidence of an external connection (Spec 080 FR-002).\n\"completed_external\" is NOT accepted from clients — it must never be\npersisted without that server-verified evidence (edge case: \"never\nguess completed_external without positive evidence\").","type":"string"},"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.SetActiveProfileRequest":{"properties":{"active_profile":{"type":"string"},"profile":{"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"},"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"},"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"},"telemetry.FeedbackContext":{"properties":{"arch":{"type":"string"},"connected_server_count":{"type":"integer"},"edition":{"type":"string"},"os":{"type":"string"},"routing_mode":{"type":"string"},"server_count":{"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":{"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: 100000)","type":"integer"},"activity_max_response_size":{"description":"Response truncation limit in bytes (default: 65536)","type":"integer"},"activity_max_size_mb":{"description":"Max total activity-log size in MB before pruning oldest (default: 256, 0=disabled)","type":"integer"},"activity_retention_days":{"description":"Activity logging settings (RFC-003)","type":"integer"},"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"},"api_key":{"description":"Security settings","type":"string"},"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_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_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":"Advertised on every tool as ` + "`" + `_meta.anthropic/maxResultSizeChars` + "`" + `; raises Claude Code's inline-response ceiling from 50k to up to 500k chars. Set to 0 to disable.","type":"integer"},"mcpServers":{"items":{"$ref":"#/components/schemas/config.ServerConfig"},"type":"array","uniqueItems":false},"oauth_expiry_warning_hours":{"description":"Health status settings","type":"number"},"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"},"telemetry":{"$ref":"#/components/schemas/config.TelemetryConfig"},"tls":{"$ref":"#/components/schemas/config.TLSConfig"},"tokenizer":{"$ref":"#/components/schemas/config.TokenizerConfig"},"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},"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.","type":"boolean"}},"type":"object"},"config.OAuthConfig":{"description":"OAuth configuration (keep even when empty to signal OAuth requirement)","properties":{"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"},"scopes":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"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":{"name":{"description":"URL slug, validated","type":"string"},"servers":{"description":"references to mcpServers[].name","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"},"deep_scan":{"$ref":"#/components/schemas/config.DeepScanConfig"},"integrity_check_interval":{"type":"string"},"integrity_check_on_restart":{"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_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"}},"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"},"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_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 or\nunrecognized value as manual (secure by default). 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":{"certs_dir":{"description":"Directory for certificates","type":"string"},"enabled":{"description":"Enable HTTPS","type":"boolean"},"hsts":{"description":"Enable HTTP Strict Transport Security","type":"boolean"},"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.","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\"","type":"string"}},"type":"object"},"connect.ConnectResult":{"description":"The full result; its action mirrors the top-level one","properties":{"action":{"description":"\"created\", \"updated\", \"already_exists\", \"removed\", \"not_found\"","type":"string"},"backup_path":{"type":"string"},"client":{"type":"string"},"config_path":{"type":"string"},"message":{"type":"string"},"server_name":{"type":"string"},"success":{"type":"boolean"}},"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.ActivityRecord":{"properties":{"arguments":{"description":"Tool call arguments","type":"object"},"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_message":{"description":"Error details if status is \"error\"","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"},"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"},"tool_name":{"description":"Name of tool called","type":"string"},"type":{"$ref":"#/components/schemas/contracts.ActivityType"},"work_session_id":{"description":"Spec 082: one client, one project, across reconnects","type":"string"}},"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"},"period":{"description":"Time period (1h, 24h, 7d, 30d)","type":"string"},"rejected_count":{"description":"RejectedCount is the number of calls shed by a concurrency limiter before\nthey reached an upstream (spec 093). Counted separately from errors: it is\nproxy backpressure, not an upstream fault, and it is the signal an\noperator right-sizes max_concurrent_requests 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.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":{"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},"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"},"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":{"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)","type":"string"},"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"},"summary":{"description":"Summary is a human-readable status message (e.g., \"Connected (5 tools)\")","type":"string"}},"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_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"},"start_time":{"type":"string"},"status":{"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_url":{"type":"string"},"client_id":{"type":"string"},"extra_params":{"additionalProperties":{"type":"string"},"type":"object"},"pkce_enabled":{"type":"boolean"},"redirect_port":{"type":"integer"},"scopes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"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.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"]},"contracts.PreflightRequest":{"properties":{"policy":{"$ref":"#/components/schemas/contracts.PreflightPolicy"},"profile":{"description":"Profile evaluates under a named profile's server scope. 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"},"headers":{"additionalProperties":{"type":"string"},"type":"object"},"health":{"$ref":"#/components/schemas/contracts.HealthStatus"},"id":{"type":"string"},"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"},"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_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"},"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.SuccessResponse":{"properties":{"data":{"type":"object"},"success":{"type":"boolean"}},"type":"object"},"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":{"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"},"schema":{"type":"object"},"server_name":{"type":"string"},"usage":{"type":"integer"}},"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"},"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"},"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_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"},"data":{"properties":{"data":{"$ref":"#/components/schemas/contracts.InfoResponse"}},"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"},"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"},"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.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.ConnectConflictResponse":{"properties":{"action":{"description":"already_exists | precondition_failed","type":"string"},"data":{"$ref":"#/components/schemas/connect.ConnectResult"},"error":{"description":"Human-readable message","type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.ConnectRequest":{"properties":{"force":{"description":"Overwrite existing entry","type":"boolean"},"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"},"server_name":{"description":"Defaults to \"mcpproxy\"","type":"string"}},"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":{"content":{"description":"Raw JSON or TOML content","type":"string"},"format":{"description":"Optional format hint","type":"string"},"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"},"fields_skipped":{"items":{"type":"string"},"type":"array","uniqueItems":false},"name":{"type":"string"},"original_name":{"type":"string"},"protocol":{"type":"string"},"source_format":{"type":"string"},"url":{"type":"string"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.IsolationRequest":{"description":"Isolation carries per-server Docker isolation overrides (enabled,\nmode_override, image, network_mode, extra_args, working_dir). A nil\npointer means \"do not touch isolation config\". A present object is\napplied field-by-field ON TOP of the persisted overrides, so omitting a\nfield leaves it alone; clear an individual override by sending it\nexplicitly (` + "`" + `\"enabled\": null` + "`" + `, ` + "`" + `\"image\": \"\"` + "`" + `).","properties":{"enabled":{"description":"Enabled exists ONLY to detect and reject an echoed-back read. It is the\neffective state on the read surface and is never writable; see validate().","type":"boolean"},"enabled_override":{"description":"EnabledOverride is the tri-state per-server override — the RAW value, the\nsame one reads return as ` + "`" + `enabled_override` + "`" + `. It has THREE meaningful wire\nstates, and collapsing them is what silently un-isolated servers\n(GH #1142):\n - absent → leave the persisted override untouched\n - null → clear the override, back to inheriting the global\n - true / false → set an explicit opt-in / opt-out","type":"boolean"},"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"mode_override":{"description":"ModeOverride sets ` + "`" + `isolation.mode` + "`" + ` (\"docker\" | \"sandbox\" | \"none\").\nnil leaves the persisted value alone; an empty string clears it. An\nunrecognized value is rejected with a 400 rather than persisted.","type":"string"},"network_mode":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"httpapi.OnboardingMarkRequest":{"properties":{"connect_step_status":{"description":"ConnectStepStatus is one of: \"\", \"completed\", \"skipped\". Empty\npreserves the existing value. The stored enum is wider (Spec 080\nFR-001): a \"skipped\" request for a previously untouched connect step\nis upgraded server-side to \"completed_external\" when the install\nshows positive evidence of an external connection (Spec 080 FR-002).\n\"completed_external\" is NOT accepted from clients — it must never be\npersisted without that server-verified evidence (edge case: \"never\nguess completed_external without positive evidence\").","type":"string"},"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.SetActiveProfileRequest":{"properties":{"active_profile":{"type":"string"},"profile":{"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"},"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"},"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"},"telemetry.FeedbackContext":{"properties":{"arch":{"type":"string"},"connected_server_count":{"type":"integer"},"edition":{"type":"string"},"os":{"type":"string"},"routing_mode":{"type":"string"},"server_count":{"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/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"],"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":"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":"Filter by agent token name (Spec 028)","in":"query","name":"agent","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 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"},"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"}}],"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"}}],"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/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.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Stored scripts and the directory they were read from"},"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"},"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)"},"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)"},"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)"},"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.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"List of ClientStatus objects"}},"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.","parameters":[{"description":"Client ID (claude-code, claude-desktop, cursor, windsurf, vscode, codex, gemini, opencode)","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.","parameters":[{"description":"Client ID (claude-code, claude-desktop, cursor, windsurf, vscode, codex, gemini, opencode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ClientStatus"},"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.","parameters":[{"description":"Client ID (claude-code, claude-desktop, cursor, windsurf, vscode, codex, gemini, opencode)","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)"},"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"},"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)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"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 embedded API key\nis masked in the payload; contains_api_key flags that a credential is written.\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, cursor, windsurf, vscode, codex, gemini, opencode)","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"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectPreview"},"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"},"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.","parameters":[{"description":"Client ID (claude-code, claude-desktop, cursor, windsurf, vscode, codex, gemini, opencode)","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\nThis endpoint is designed for tray-core communication and version checking\nUse refresh=true query parameter to force an immediate update check against GitHub\nThe launched_by field reports durable launch provenance (\"tray\", \"installer\", or \"\" for user-launched/unknown)","parameters":[{"description":"Force immediate update check against GitHub","in":"query","name":"refresh","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Server information with optional update info"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server information","tags":["status"]}},"/api/v1/onboarding/mark":{"post":{"description":"Updates wizard engagement and per-step status. Once engaged is\ntrue, the wizard does not auto-show again, even if state regresses.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.OnboardingMarkRequest"}}},"description":"Mark request","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Updated OnboardingStateResponse"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"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":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"OnboardingStateResponse"},"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":"List all configured profiles with their effective servers and indexed tool count (Profiles v2). A profile scopes tool discovery and calls to a named subset of upstream servers.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"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"]}},"/api/v1/profiles/active":{"get":{"description":"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":"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"},"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/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/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/servers":{"get":{"description":"Get a list of all configured upstream MCP servers with their connection status and statistics","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServersResponse"}}},"description":"Server list with statistics"},"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.","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","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.","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}/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"},"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/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.","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)"},"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":{"type":"object"}}}},"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"},"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":{"type":"object"}}}},"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"},"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"}}],"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"},"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"}}],"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"},"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 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"},"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"},"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","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"},"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"},"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 (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).","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GlobalToolsResponse"}}},"description":"All tools across all servers"},"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 (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"]}},"/healthz":{"get":{"description":"Get comprehensive health status including all component health (Kubernetes-compatible liveness probe)","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.HealthResponse"}}},"description":"Service is healthy"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.HealthResponse"}}},"description":"Service is unhealthy"}},"summary":"Get health status","tags":["health"]}},"/readyz":{"get":{"description":"Get readiness status including all component readiness checks (Kubernetes-compatible readiness probe)","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.ReadinessResponse"}}},"description":"Service is ready"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.ReadinessResponse"}}},"description":"Service is not ready"}},"summary":"Get readiness status","tags":["health"]}}}, + "paths": {"/api/v1/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"],"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":"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":"Filter by agent token name (Spec 028)","in":"query","name":"agent","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 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"},"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"}}],"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"}}],"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/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.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Stored scripts and the directory they were read from"},"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"},"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)"},"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)"},"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)"},"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.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"List of ClientStatus objects"}},"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.","parameters":[{"description":"Client ID (claude-code, claude-desktop, cursor, windsurf, vscode, codex, gemini, opencode)","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.","parameters":[{"description":"Client ID (claude-code, claude-desktop, cursor, windsurf, vscode, codex, gemini, opencode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ClientStatus"},"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.","parameters":[{"description":"Client ID (claude-code, claude-desktop, cursor, windsurf, vscode, codex, gemini, opencode)","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)"},"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"},"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)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"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 embedded API key\nis masked in the payload; contains_api_key flags that a credential is written.\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, cursor, windsurf, vscode, codex, gemini, opencode)","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"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectPreview"},"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"},"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.","parameters":[{"description":"Client ID (claude-code, claude-desktop, cursor, windsurf, vscode, codex, gemini, opencode)","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\nThis endpoint is designed for tray-core communication and version checking\nUse refresh=true query parameter to force an immediate update check against GitHub\nThe launched_by field reports durable launch provenance (\"tray\", \"installer\", or \"\" for user-launched/unknown)","parameters":[{"description":"Force immediate update check against GitHub","in":"query","name":"refresh","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Server information with optional update info"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server information","tags":["status"]}},"/api/v1/onboarding/mark":{"post":{"description":"Updates wizard engagement and per-step status. Once engaged is\ntrue, the wizard does not auto-show again, even if state regresses.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.OnboardingMarkRequest"}}},"description":"Mark request","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Updated OnboardingStateResponse"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"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":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"OnboardingStateResponse"},"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":"List all configured profiles with their effective servers and indexed tool count (Profiles v2). A profile scopes tool discovery and calls to a named subset of upstream servers.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"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"]}},"/api/v1/profiles/active":{"get":{"description":"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":"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"},"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/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/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/servers":{"get":{"description":"Get a list of all configured upstream MCP servers with their connection status and statistics","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServersResponse"}}},"description":"Server list with statistics"},"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","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}/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"},"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/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.","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)"},"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":{"type":"object"}}}},"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"},"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":{"type":"object"}}}},"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"},"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"}}],"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"},"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"}}],"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"},"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 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"},"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"},"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","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"},"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"},"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 (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).","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GlobalToolsResponse"}}},"description":"All tools across all servers"},"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 (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"]}},"/healthz":{"get":{"description":"Get comprehensive health status including all component health (Kubernetes-compatible liveness probe)","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.HealthResponse"}}},"description":"Service is healthy"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.HealthResponse"}}},"description":"Service is unhealthy"}},"summary":"Get health status","tags":["health"]}},"/readyz":{"get":{"description":"Get readiness status including all component readiness checks (Kubernetes-compatible readiness probe)","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.ReadinessResponse"}}},"description":"Service is ready"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.ReadinessResponse"}}},"description":"Service is not ready"}},"summary":"Get readiness status","tags":["health"]}}}, "openapi": "3.1.0" }` diff --git a/oas/swagger.yaml b/oas/swagger.yaml index 943b84f39..d18ea8bbf 100644 --- a/oas/swagger.yaml +++ b/oas/swagger.yaml @@ -1880,6 +1880,27 @@ components: cpu_limit: type: string enabled: + description: |- + Enabled is the EFFECTIVE isolation state for this server: whether its + process is actually CONFINED, after the global setting, the per-server + override, the structural gates and the host's capabilities. It is NOT the + raw per-server override — read EnabledOverride for that (GH #1142). + + READ-ONLY. The write surfaces reject an `enabled` key precisely because + it is derived: echoing it back would convert "inherits the global + setting" into a permanent explicit override. Write EnabledOverride. + + It stays a non-pointer bool that is always present on the wire: the macOS + tray decodes it as a non-optional Swift Bool, so omitting or nulling the + key would fail Codable for the whole server payload. Older clients that + read this field now simply get a true answer. + type: boolean + enabled_override: + description: |- + EnabledOverride is the RAW per-server `isolation.enabled` override, as + persisted. Absent means "inherit the global setting" — which is a + distinct state from an explicit false, and the distinction the reporting + bug used to destroy. type: boolean extra_args: items: @@ -1890,6 +1911,11 @@ components: type: string memory_limit: type: string + mode_override: + description: |- + ModeOverride is the RAW per-server `isolation.mode` override + ("docker" | "sandbox" | "none"). Absent means "inherit". + type: string network_mode: type: string timeout: @@ -1917,6 +1943,40 @@ components: working_dir: type: string type: object + contracts.IsolationEffective: + description: |- + IsolationEffective exposes the resolved isolation state (and the rule + that decided it) so clients can distinguish "inherits global" from an + explicit 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 + `isolation.mode`, so its state tracks the global setting. + type: boolean + isolated: + description: |- + Isolated reports whether the process is actually CONFINED. It is NOT + simply Mode != "none": "sandbox" on a host that cannot enforce Landlock + (any non-Linux OS, or a kernel without the LSM) runs the server + unconfined, and Source then says "sandbox-unavailable" (GH #1142). + type: boolean + mode: + description: |- + Mode is the effective isolation mode: "docker" | "sandbox" | "none" — + exactly what the spawn path branches on. + type: string + source: + description: |- + Source names the deciding rule: "global", "server-mode", + "server-opt-out", "server-opt-in-ignored", "not-stdio", + "already-docker", "sandbox-unavailable" or "unsupported-mode". + Treat an unrecognized value as "global". + type: string + type: object contracts.LogEntry: properties: fields: @@ -2513,6 +2573,8 @@ components: $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: @@ -3289,12 +3351,27 @@ components: type: object httpapi.IsolationRequest: description: |- - Isolation carries per-server Docker isolation overrides (image, - network_mode, extra_args, working_dir, enabled). A nil pointer - means "do not touch isolation config"; an empty-but-present - object on PATCH intentionally clears the overrides. + Isolation carries per-server Docker isolation overrides (enabled, + mode_override, image, network_mode, extra_args, working_dir). A nil + pointer means "do not touch isolation config". A present object is + applied field-by-field ON TOP of the persisted overrides, so omitting a + field leaves it alone; clear an individual override by sending it + explicitly (`"enabled": null`, `"image": ""`). properties: enabled: + description: |- + Enabled exists ONLY to detect and reject an echoed-back read. It is the + effective 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 + same one reads return as `enabled_override`. It has THREE meaningful wire + states, and collapsing them is what silently un-isolated servers + (GH #1142): + - absent → leave the persisted override untouched + - null → clear the override, back to inheriting the global + - true / false → set an explicit opt-in / opt-out type: boolean extra_args: items: @@ -3303,6 +3380,12 @@ components: uniqueItems: false image: type: string + mode_override: + description: |- + ModeOverride sets `isolation.mode` ("docker" | "sandbox" | "none"). + nil leaves the persisted value alone; an empty string clears it. An + unrecognized value is rejected with a 400 rather than persisted. + type: string network_mode: type: string working_dir: @@ -5488,8 +5571,12 @@ paths: tags: - servers post: - description: Add a new MCP upstream server to the configuration. New servers - are quarantined by default for security. + 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: @@ -5583,7 +5670,11 @@ paths: tags: - servers patch: - description: Update specific fields of an existing upstream MCP server configuration. + 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