diff --git a/docs/api/rest-api.md b/docs/api/rest-api.md index 075bea7eb..23244807d 100644 --- a/docs/api/rest-api.md +++ b/docs/api/rest-api.md @@ -145,7 +145,14 @@ secrets. Setting `reveal_secret_headers: true` in [`mcp_config.json`](../configuration/config-file.md) disables redaction on -all three channels. This is **not normally needed**: the Web UI / macOS +all three channels **for an authenticated admin only** (issue #1167). An +agent token, a server-edition non-admin user and an unauthenticated caller +keep getting masked values no matter how the flag is set. The flag has no +effect at all on the `/events` SSE stream or on the `upstream_stats` block of +`GET /api/v1/status`: those payloads are produced once for a mixed-privilege +audience with no caller to check, so they are always masked. An admin +subscribed to `/events` with the flag on receives the notify-only form of +`servers.changed` and re-fetches the raw values through `GET /api/v1/servers`. This is **not normally needed**: the Web UI / macOS tray / CLI can edit, delete, and convert-to-secret without ever seeing the plaintext, because the PATCH endpoint deep-merges (omitted keys are preserved) and the [`config-to-secret`](#post-apiv1serversnameconfig-to-secret) @@ -1067,6 +1074,17 @@ Events include: - `activity.tool_call.completed` - Tool call finished - `activity.policy_decision` - Tool call blocked by policy +The stream is rendered **per connection**. An admin subscriber (API key, Web UI, +tray over the unix socket) receives every event exactly as the event bus +published it. For an agent token limited by `allowed_servers` (issue #1166): + +| Event | Delivered to a scoped subscriber | +|-------|----------------------------------| +| Names a server outside the scope, through `server_name`, `server`, `target_server` or `affected_entity` — every `activity.*`, `oauth.*` and `security.*` event | **No.** The whole frame is dropped: blanking the name still discloses the mutation, its timing, and how many servers are hidden. | +| `servers.changed` | **Yes, always** — it is coalesced last-write-wins and carries renderable state. The embedded server list is narrowed, `stats` recomputed, and a coalescer extra naming an out-of-scope server is removed. | +| `config.reloaded`, `config.saved`, `secrets.changed` | **No.** They announce mutations of the admin config document, which `GET /api/v1/config` already answers `403` for this caller. | +| Everything else (`active_profile.changed`, `activity.system.*`, `sensitive_data.detected`, `security.scanner_changed`, …) | **Yes**, unchanged: no server identity to scope. | + ## Error Responses ```json diff --git a/docs/configuration/upstream-servers.md b/docs/configuration/upstream-servers.md index 3253a0a3f..15515e098 100644 --- a/docs/configuration/upstream-servers.md +++ b/docs/configuration/upstream-servers.md @@ -146,6 +146,11 @@ To disable redaction (for debugging only), set `reveal_secret_headers: true` in `mcp_config.json`. **It's not normally needed**: the editing flow described below works without ever exposing the plaintext to the client. +The flag reveals raw values only to an **authenticated admin**, and only on +the REST and MCP read doors. It never applies to the `/events` SSE stream or +to `upstream_stats`, and `GET /api/v1/config` is denied to agent tokens +outright (issue #1167). + Since v0.64 (issue #1148) the flag additionally requires an **authenticated** caller. `/mcp` is deliberately unprotected by default (`require_mcp_auth: false`), so an unauthenticated MCP client is treated as diff --git a/docs/features/agent-tokens.md b/docs/features/agent-tokens.md index 2da194b77..1d4b34dc0 100644 --- a/docs/features/agent-tokens.md +++ b/docs/features/agent-tokens.md @@ -172,9 +172,92 @@ mcpproxy token create --name deploy-bot --servers github,gitlab --permissions re mcpproxy token create --name all-access --servers "*" --permissions read ``` -Server scoping is enforced at two levels: +Server scoping is enforced at three levels: 1. **Tool discovery** (`retrieve_tools`) — only returns tools from allowed servers 2. **Tool execution** (`call_tool_*`) — blocks calls to out-of-scope servers +3. **Enumeration** — since issue #1166, `allowed_servers` also scopes what the + REST surface will *list*, not only what the token may call. A scoped token + sees only its own servers on `GET /api/v1/servers` (array **and** the + `stats` counters), `GET /api/v1/status` (`upstream_stats`), the `/events` + SSE stream, `GET /api/v1/tools`, `GET /api/v1/index/search`, + `GET /api/v1/diagnostics` / `doctor`, `GET /api/v1/profiles`, + `GET /api/v1/annotations/coverage` and `GET /api/v1/security/scans`. + + **The whole `/api/v1/servers/{id}` subtree** answers `404 Server not found` + for a server outside the scope — `tools`, `logs`, `tool-calls`, + `diagnostics`, `scan/status`, `scan/report`, `scan/files`, `integrity`, + `tools/export`, `tools/{tool}/diff` and every sub-resource added later, since + the gate is a middleware on the subtree. It is the *same* `404` a server that + does not exist returns — byte for byte, once the echoed name is normalised — + so the response cannot be used to probe for hidden servers. `logs` matters + most: upstream stderr routinely echoes the argv and env the server process + was launched with. + + **The activity, tool-call and usage doors** are scoped to records + attributable to an allowed server: `GET /api/v1/activity`, + `/activity/summary`, `/activity/usage`, `/activity/export`, `/activity/{id}`, + `GET /api/v1/tool-calls` and `/tool-calls/{id}` (plus its `/replay`). The + entitlement is applied inside the query, so `total` and the page always + describe the same record set, and a `?server=` filter narrows *within* the + scope rather than escaping it. Records with no server attribution + (`system_start`, `config_change`, …) are operator-plane events and are not + shown. On `/activity/usage`, aggregates that cannot be re-derived per server + — the tokens-saved headline and the global timeline — are omitted rather than + reported fleet-wide. + + **Denied outright (`403`)** to agent tokens, because there is nothing + per-server to project: + - `GET /api/v1/config` — an admin document, and it carries the admin API key. + - `GET /api/v1/stats/tokens` — `per_server_tool_list_sizes` is keyed by every + configured server, and the scalars beside it are fleet-wide. + - `GET /api/v1/sessions`, `GET /api/v1/sessions/{id}` — an MCP session + describes a *client* and the user's workspace, with no server attribution. + - `GET /api/v1/security/overview`, `GET /api/v1/security/queue` — fleet-wide + scan and finding counts, and a queue that names every server waiting to be + scanned. A scoped caller reads its own server's verdict from + `GET /api/v1/servers/{id}/scan/status`, which the subtree gate scopes. + - `GET /api/v1/telemetry/payload` — the heartbeat carries `server_count`, + `connected_server_count`, `tool_count` and `server_docker_isolated_count`: + precisely the count oracle removed from `/status`. + - `GET /api/v1/onboarding/state`, `POST /api/v1/onboarding/mark` (which + echoes the same document) — `configured_server_count` is an inventory size + and `connected_client_ids` is the operator's MCP-client inventory. + - `GET /api/v1/secrets/refs`, `GET /api/v1/secrets/config` — values are + masked, so this is a credential *inventory* rather than a disclosure, but + it names the secrets of servers the caller may not enumerate. A strictly + narrower view of the document `GET /api/v1/config` already denies. + + **Withheld rather than denied.** `GET /api/v1/status` stays open — agents + legitimately poll it for liveness — but its `activation` block is omitted for + a scoped caller. `mcp_clients_seen_ever` is the operator's MCP-client + inventory and `retrieve_tools_calls_24h` is an exact deployment-wide counter, + neither of which has a per-server part to project. The key is already absent + when telemetry is unwired, so clients tolerate its absence. + + `PUT /api/v1/profiles/active` answers `403`: the active profile is + server-level shared state that decides what the Web UI and tray render, so a + read-scoped credential must not be able to change it. It is gated by the same + `config_write` policy as the other config-level writes. + + On the `/events` stream, scoping applies **per event**, not only to the + `servers.changed` server list: + + - An event that names a server the token may not enumerate — through + `server_name`, `server`, `target_server` or `affected_entity`, which is + every activity, OAuth and security event — is **not delivered** to that + subscriber at all. It is dropped rather than blanked, because a frame with + the name removed still discloses the mutation, its timing and the number + of servers being hidden. + - `servers.changed` is the exception and is always delivered, because it is + coalesced last-write-wins and carries the state a client renders. Its + server list is narrowed, its `stats` recomputed, and any coalescer extra + that names an out-of-scope server (`"server": "beta"`) is removed. + - `config.reloaded`, `config.saved` and `secrets.changed` announce mutations + of the admin config document and are dropped, matching the `403` on + `GET /api/v1/config`. + + Admin subscribers — the API key, the Web UI, the tray over the unix socket — + receive every event unchanged; the stream is rendered per connection. ## Administrative Operations Are Admin-Only @@ -186,7 +269,7 @@ Denied to agent tokens on both surfaces: - **Security state**: quarantine, unquarantine, tool approve/block, and the security scanner (scan start/cancel, security approve/reject) - **Config & registries**: applying/patching configuration (which can add/remove/enable/disable servers) and mutating registry sources — an agent must not bypass the per-server gate by rewriting config or a registry wholesale -On the MCP surface (`upstream_servers`, `quarantine_security`) these return a tool error; on the REST surface (mutating `/api/v1/servers/...`, `/api/v1/config/...`, and `/api/v1/registries/...` routes) they return **`403 Forbidden`** (`operation requires admin access`). Read-only operations stay available to scoped tokens: `upstream_servers` `list`/`tail_log`, `GET /api/v1/servers`, per-server diagnostics, config/registry reads, and `GET /api/v1/index/search` (which honors quarantine — a quarantined server's tools are withheld from search on every surface). +On the MCP surface (`upstream_servers`, `quarantine_security`) these return a tool error; on the REST surface (mutating `/api/v1/servers/...`, `/api/v1/config/...`, and `/api/v1/registries/...` routes) they return **`403 Forbidden`** (`operation requires admin access`). Read-only operations stay available to scoped tokens: `upstream_servers` `list`/`tail_log`, `GET /api/v1/servers`, per-server diagnostics, registry reads, and `GET /api/v1/index/search` (which honors quarantine — a quarantined server's tools are withheld from search on every surface). Those reads are **scope-filtered** as described above. `GET /api/v1/config` is the exception: it is an admin document (it carries the global `api_key`, every server's credentials, and a second enumeration of server names under `profiles[].servers`), so it returns `403` for an agent token rather than a filtered view. ## Profile Pinning diff --git a/frontend/src/views/Security.vue b/frontend/src/views/Security.vue index f4dcb556a..f41f5b34c 100644 --- a/frontend/src/views/Security.vue +++ b/frontend/src/views/Security.vue @@ -580,6 +580,12 @@ const historyPage = ref(1) const HISTORY_PAGE_SIZE = 20 const historyTotalPages = computed(() => Math.max(1, Math.ceil(historyTotal.value / HISTORY_PAGE_SIZE))) +// The sentinel the core substitutes for a literal scanner env value on every +// API serialization path (scanner.RedactedEnvValue, #1166 round 10 P3). It is +// truthy on purpose so "is this variable set?" still answers correctly here; +// saveConfig must never send it back, or the mask would overwrite the secret. +const REDACTED_ENV_VALUE = '***' + // Scan All state const scanAllRunning = ref(false) const scanAllStartTime = ref(0) @@ -923,10 +929,12 @@ function addCustomEnv() { async function saveConfig() { if (!configScanner.value) return - // Only send non-empty values that aren't keyring references (new values) + // Only send non-empty values that aren't keyring references or the core's + // redaction sentinel (new values). Sending the sentinel back would store + // '***' as the scanner's real API key. const toSend: Record = {} for (const [k, v] of Object.entries(configValues.value)) { - if (v && !v.startsWith('${keyring:')) { + if (v && v !== REDACTED_ENV_VALUE && !v.startsWith('${keyring:')) { toSend[k] = v } } diff --git a/frontend/src/views/settings/fields.ts b/frontend/src/views/settings/fields.ts index 9e1dd7807..d449c2f97 100644 --- a/frontend/src/views/settings/fields.ts +++ b/frontend/src/views/settings/fields.ts @@ -214,7 +214,7 @@ export const SECURITY_FIELDS: SettingField[] = [ { key: 'reveal_secret_headers', label: 'Show secret headers (debug)', - help: 'Normally mcpproxy redacts Authorization / API-Key header values in responses and logs. Turning this on shows them in clear text — debugging only.', + help: 'Normally mcpproxy redacts Authorization / API-Key header values in responses and logs. Turning this on shows them in clear text to an authenticated ADMIN only — agent tokens stay masked, and the /events stream and upstream_stats are always masked. Debugging only.', control: 'toggle', danger: { confirmValue: true, diff --git a/internal/auth/context.go b/internal/auth/context.go index 0f6cd9129..cf9b46519 100644 --- a/internal/auth/context.go +++ b/internal/auth/context.go @@ -174,3 +174,73 @@ func AdminUserContext(userID, email, displayName, provider string) *AuthContext Provider: provider, } } + +// RevealSecretsAllowed is THE shared predicate for "may this caller be handed +// raw credential values?" (issues #1148 and #1167). +// +// Both halves are required and neither is sufficient: +// +// - flagEnabled — the operator's `reveal_secret_headers` opt-in, and +// - CanRevealSecrets() — an authenticated, non-anonymous admin identity. +// +// #1167: the MCP door already ANDed the two; the REST list, the whole-config +// read, both doctor doors and the per-server diagnostics door checked the flag +// ALONE, so a read-only agent token scoped to one server received every other +// server's Authorization header, URL query credential, argv secret and env +// secret in plaintext the moment an operator turned the flag on. Every +// request-scoped door now reads the answer from here so they cannot drift +// apart again. +// +// Fails CLOSED on absence: a nil ctx (an in-process or future background +// caller) and a ctx with no AuthContext both yield false. A payload with no +// caller has no identity to check, so it gets masked values. +func RevealSecretsAllowed(ctx context.Context, flagEnabled bool) bool { + if !flagEnabled || ctx == nil { + return false + } + return AuthContextFromContext(ctx).CanRevealSecrets() +} + +// CanEnumerateServer is THE shared predicate for "may this caller SEE that a +// server named `name` exists?" (issue #1166). +// +// The MCP door has filtered upstream enumeration through +// AuthContext.CanAccessServer since Spec 028; the REST doors never did, so a +// token scoped to `allowed_servers: ["alpha"]` still enumerated every +// configured server on GET /api/v1/servers, /api/v1/config, /api/v1/tools, +// /api/v1/status and the /events stream. Reads on both surfaces now answer +// from one place. +// +// Fails OPEN on absence, deliberately and in exact mirror of +// AuthorizeServerOp: apiKeyAuthMiddleware forwards a request with NO +// AuthContext whenever the controller has no usable config (the testing / +// bootstrap passthrough), and treating that as "sees nothing" would blank the +// server list for every such caller. Absence of a token must not be stricter +// than a scoped token — it must be treated exactly as today's unrestricted +// behaviour. The unauthenticated /mcp back-compat context (AnonymousContext) +// is admin-typed and likewise unrestricted here; hiding a server's NAME from +// it is not the boundary this predicate defends, revealing its CREDENTIALS is, +// and that is what RevealSecretsAllowed refuses it. +func CanEnumerateServer(ctx context.Context, name string) bool { + if ctx == nil { + return true + } + ac := AuthContextFromContext(ctx) + if ac == nil || ac.IsAdmin() { + return true + } + return ac.CanAccessServer(name) +} + +// IsScopedCaller reports whether ctx carries a non-admin identity whose +// visibility is limited by AllowedServers. It is the cheap short-circuit for +// handlers that would otherwise copy a payload just to filter it: an admin (or +// an absent context, per CanEnumerateServer) sees everything, so the payload +// can be forwarded untouched. +func IsScopedCaller(ctx context.Context) bool { + if ctx == nil { + return false + } + ac := AuthContextFromContext(ctx) + return ac != nil && !ac.IsAdmin() +} diff --git a/internal/httpapi/activity.go b/internal/httpapi/activity.go index 4b041156d..720e5a9af 100644 --- a/internal/httpapi/activity.go +++ b/internal/httpapi/activity.go @@ -1,6 +1,7 @@ package httpapi import ( + "context" "encoding/json" "fmt" "net/http" @@ -129,6 +130,26 @@ func parseActivityFilters(r *http.Request) storage.ActivityFilter { return filter } +// applyActivityScope stamps the caller's server entitlement onto a filter +// (#1166 follow-up, G2). +// +// The activity log is the widest read door on the mux: it carries tool-call +// ARGUMENTS and RESPONSES for every server, which is strictly more than the +// enumeration the earlier round closed. The entitlement goes into +// storage.ActivityFilter so ListActivities' `total` and StreamActivities' whole +// pass see the same predicate the page does — a post-filter would shrink the +// page while `total` kept counting the records it removed. +// +// It is applied AFTER parseActivityFilters on purpose: a caller-supplied +// ?server= narrows within the entitlement, and can never widen past it, because +// both live in the same Matches() call and the authorization term is evaluated +// first. +func applyActivityScope(ctx context.Context, filter *storage.ActivityFilter) { + if allowed, scoped := scopeAllowedServers(ctx); scoped { + filter.AllowedServers = allowed + } +} + // handleListActivity handles GET /api/v1/activity // @Summary List activity records // @Description Returns paginated list of activity records with optional filtering @@ -164,6 +185,7 @@ func parseActivityFilters(r *http.Request) storage.ActivityFilter { // @Router /api/v1/activity [get] func (s *Server) handleListActivity(w http.ResponseWriter, r *http.Request) { filter := parseActivityFilters(r) + applyActivityScope(r.Context(), &filter) activities, total, err := s.controller.ListActivities(filter) if err != nil { @@ -238,7 +260,12 @@ func (s *Server) handleGetActivityDetail(w http.ResponseWriter, r *http.Request) return } - if activity == nil { + // #1166 follow-up (G2): a record the caller is not entitled to takes the + // SAME exit as one that does not exist — same status, same message. The + // oracle is status parity with an absent id, not "the body omits the server + // name": this route's 404 body carries no echo of the caller's input, so an + // absence assertion would pass vacuously. + if activity == nil || !canSeeServer(r.Context(), activity.ServerName) { s.writeError(w, r, http.StatusNotFound, "Activity not found") return } @@ -520,6 +547,7 @@ func storageToContractActivityForExport(a *storage.ActivityRecord, includeBodies // @Router /api/v1/activity/export [get] func (s *Server) handleExportActivity(w http.ResponseWriter, r *http.Request) { filter := parseActivityFilters(r) + applyActivityScope(r.Context(), &filter) // Re-parse limit/offset from query for export — parseActivityFilters caps at 100 via Validate(), // but export supports up to 50000. Re-read raw values and apply export-specific validation. @@ -709,6 +737,7 @@ func (s *Server) handleActivitySummary(w http.ResponseWriter, r *http.Request) { filter.StartTime = startTime filter.EndTime = endTime filter.Limit = 0 + applyActivityScope(r.Context(), &filter) // Calculate summary statistics var totalCount, successCount, errorCount, blockedCount, rejectedCount, otherCount int @@ -892,7 +921,8 @@ const ( usageTokenSource = "bytes" // size-based proxy (FR-006); FR-010 → "estimated_tokens" ) -// usageParams holds the validated query parameters for the usage endpoint. +// usageParams holds the validated query parameters for the usage endpoint, +// plus the caller's server entitlement (#1166 follow-up, G2). type usageParams struct { window string // "24h" | "7d" | "all" server string @@ -900,11 +930,70 @@ type usageParams struct { status string // "" | "success" | "error" | "blocked" | "rejected" top int sort string // "calls" | "resp_bytes" | "error_rate" | "p95" + + // allowed is the scoped caller's server entitlement; scoped says whether + // one applies at all. They are separate because a token allowed NO servers + // produces an empty-but-non-nil slice that must hide everything, while an + // admin (or the no-AuthContext bootstrap passthrough) is unrestricted. + allowed []string + scoped bool +} + +// canSee reports whether this caller may see rows attributed to serverName. +func (p usageParams) canSee(serverName string) bool { + if !p.scoped { + return true + } + if serverName == "" { + return false + } + for _, allowed := range p.allowed { + if allowed == "*" || allowed == serverName { + return true + } + } + return false } // cacheKey is a stable identity for the params, used by the short-TTL cache. +// +// The caller's entitlement is PART of that identity. handleActivityUsage caches +// the built response for usage_cache_ttl in a process-wide map: without the +// scope term the first agent token to ask would seed the entry the admin Web UI +// (and every other tenant) then read for the rest of the TTL, and vice versa. +// Two tokens with the same allowed-server set legitimately share an entry; +// nothing else does. +// +// The encoding is LENGTH-PREFIXED, and that is a correctness property, not a +// style choice (round 10, P6). Joining the terms with a bare separator is not +// injective when the separator can appear inside a term: config validation +// rejects only a colon in a server name, so a single server literally named +// `a,b` produced the same key as the scope ["a","b"], and a `?server=` filter +// value containing a pipe collided across fields the same way. A collision here +// serves one tenant's cached response to another — the disclosure this whole +// door exists to prevent, arriving through the cache instead of the query. func (p usageParams) cacheKey() string { - return strings.Join([]string{p.window, p.server, p.tool, p.status, p.sort, strconv.Itoa(p.top)}, "|") + var b strings.Builder + write := func(part string) { + b.WriteString(strconv.Itoa(len(part))) + b.WriteByte(':') + b.WriteString(part) + } + for _, part := range []string{p.window, p.server, p.tool, p.status, p.sort, strconv.Itoa(p.top)} { + write(part) + } + if !p.scoped { + write("admin") + return b.String() + } + sorted := append([]string(nil), p.allowed...) + sort.Strings(sorted) + write("scoped") + write(strconv.Itoa(len(sorted))) + for _, name := range sorted { + write(name) + } + return b.String() } // windowStart returns the lower time bound for the window relative to now, plus @@ -932,6 +1021,10 @@ func parseUsageParams(r *http.Request) (usageParams, error) { top: usageDefaultTop, sort: usageDefaultSort, } + // Resolved HERE, not at the call site, so the entitlement cannot be + // forgotten by a future caller and — more importantly — so it is inside + // cacheKey() by construction. + p.allowed, p.scoped = scopeAllowedServers(r.Context()) if v := q.Get("window"); v != "" { switch v { @@ -1040,7 +1133,15 @@ func buildUsageResponse(snap *internalRuntime.UsageAggregate, tokens *contracts. Tools: make([]contracts.UsageToolStat, 0), Timeline: make([]contracts.UsageTimeBucket, 0), } - if tokens != nil { + // #1166 follow-up (G3): the tokens-saved headline and the timeline below are + // FLEET-WIDE aggregates. Neither can be re-derived per server — the token + // metrics are computed across the whole inventory, and snap.Timeline() is a + // set of global buckets with no per-server breakdown — so for a scoped + // caller they are dropped rather than reported wrongly. Same position + // recomputeServerStats already takes on the same struct (it drops + // TokenMetrics from GET /api/v1/servers instead of projecting it), so the + // three doors that touch contracts.ServerTokenMetrics agree. + if tokens != nil && !p.scoped { resp.TokensSaved = tokens.SavedTokens resp.TokensSavedPercentage = tokens.SavedTokensPercentage } @@ -1058,6 +1159,13 @@ func buildUsageResponse(snap *internalRuntime.UsageAggregate, tokens *contracts. // Per-tool rollup: filter by membership, project to contract rows. rows := make([]contracts.UsageToolStat, 0, len(snap.Tools)) for _, tu := range snap.Tools { + // Entitlement first, so no query parameter below can widen past it. + // Each row names a server and a tool: without this a scoped token read + // the whole fleet's tool inventory plus its call volumes off a route + // with no gate at all. + if !p.canSee(tu.Server) { + continue + } if p.server != "" && tu.Server != p.server { continue } @@ -1075,6 +1183,30 @@ func buildUsageResponse(snap *internalRuntime.UsageAggregate, tokens *contracts. sortUsageRows(rows, p.sort) + // Round 10 (P7): the headline for a scoped caller is summed HERE, over the + // rows it may see, before the top-N fold discards the tail. + // + // The early return below skips the timeline loop, which is where an admin's + // TotalCalls / TotalErrors are accumulated — so a scoped caller used to be + // served `"total_calls":0` beside per-tool rows whose calls plainly summed + // to a non-zero number. The response contradicted itself, and a client with + // no way to know why reads a zero as "no traffic". + // + // The population differs from an admin's, and the field comment on + // contracts.UsageAggregateResponse says why it must: the timeline is + // window-bucketed and global, this sum is the lifetime-cumulative rollup of + // the tools active in the window. A scoped caller cannot be given the + // former (there is no per-server timeline to project) so it is given a + // number that agrees with the rest of ITS OWN response instead of one that + // contradicts it. Nothing new is disclosed: every addend is a row the same + // response already carries. + if p.scoped { + for i := range rows { + resp.TotalCalls += rows[i].Calls + resp.TotalErrors += rows[i].Errors + } + } + // Top-N + 'other' fold. if len(rows) > p.top { other := &contracts.UsageOtherBucket{} @@ -1092,6 +1224,16 @@ func buildUsageResponse(snap *internalRuntime.UsageAggregate, tokens *contracts. // window's headline count — computed here, server-side, from the same bars // the response carries, so the tiles and the histogram beneath them agree // and so the Activity Log can print the same number (F1, #1046). + // + // GLOBAL is the operative word, and it is why a scoped caller gets none of + // it: the buckets aggregate every server's traffic with no per-server + // breakdown to project, so emitting them would hand a tenant the whole + // deployment's call and error volume over time. Empty timeline, zero totals + // — the same "cannot be re-derived, so not reported" rule as the tokens + // headline above. + if p.scoped { + return resp + } for _, b := range snap.Timeline() { if bounded && b.Start.Before(start) { continue diff --git a/internal/httpapi/contracts_test.go b/internal/httpapi/contracts_test.go index a7ca9f3a5..1fdac3775 100644 --- a/internal/httpapi/contracts_test.go +++ b/internal/httpapi/contracts_test.go @@ -176,7 +176,7 @@ func (m *MockServerController) GetRecentSessions(_ int, _ string) ([]*contracts. func (m *MockServerController) GetSessionByID(_ string) (*contracts.MCPSession, error) { return nil, nil } -func (m *MockServerController) GetToolCallsBySession(_ string, _ int, _ int) ([]*contracts.ToolCallRecord, int, error) { +func (m *MockServerController) GetToolCallsBySession(_ string, _ int, _ int, _ storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error) { return []*contracts.ToolCallRecord{}, 0, nil } @@ -235,7 +235,7 @@ func (m *MockServerController) NotifySecretsChanged(_ context.Context, _, _ stri func (m *MockServerController) GetCurrentConfig() interface{} { return map[string]interface{}{} } // Tool call history methods -func (m *MockServerController) GetToolCalls(_ int, _ int) ([]*contracts.ToolCallRecord, int, error) { +func (m *MockServerController) GetToolCalls(_ int, _ int, _ storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error) { return []*contracts.ToolCallRecord{}, 0, nil } func (m *MockServerController) GetToolCallByID(_ string) (*contracts.ToolCallRecord, error) { diff --git a/internal/httpapi/diagnostics_per_server.go b/internal/httpapi/diagnostics_per_server.go index c4e8af5a9..3d9c9cc82 100644 --- a/internal/httpapi/diagnostics_per_server.go +++ b/internal/httpapi/diagnostics_per_server.go @@ -80,7 +80,17 @@ func (s *Server) handleGetServerDiagnostics(w http.ResponseWriter, r *http.Reque break } } - if hit == nil { + // #1166: a server the caller may not enumerate takes the SAME exit as one + // that does not exist — same status, same message — so the response cannot + // be used to probe for hidden servers. + // + // The scopedServerSubtree middleware now applies exactly this rule to the + // whole /servers/{id} subtree, so for a scoped caller the request no longer + // reaches this line. Kept anyway: it is the route's own absent-server exit + // (hit == nil, which still fires for an admin), and the redundant scope + // term costs one predicate call while making this handler correct on its + // own if it is ever remounted somewhere without that middleware. + if hit == nil || !canSeeServer(r.Context(), serverID) { s.writeError(w, r, http.StatusNotFound, "Server not found: "+serverID) return } @@ -88,11 +98,10 @@ func (s *Server) handleGetServerDiagnostics(w http.ResponseWriter, r *http.Reque // Issue #872: health.detail and diagnostic.cause echo the raw connect // error, which carries the full upstream URL (query secrets and all). // Scrub them in parity with the /api/v1/servers list route unless the - // operator opted out via reveal_secret_headers. - reveal := false - if cfg, cfgErr := s.controller.GetConfig(); cfgErr == nil && cfg != nil { - reveal = cfg.RevealSecretHeaders - } + // operator opted out via reveal_secret_headers AND the caller is an + // authenticated admin (#1167 — this read the flag alone, with `r` in + // scope and its AuthContext simply never consulted). + reveal := s.revealSecrets(r.Context()) resp := map[string]interface{}{ "server": serverID, diff --git a/internal/httpapi/onboarding.go b/internal/httpapi/onboarding.go index 672198a72..3d103cd84 100644 --- a/internal/httpapi/onboarding.go +++ b/internal/httpapi/onboarding.go @@ -103,9 +103,20 @@ type OnboardingMarkRequest struct { // @Security ApiKeyAuth // @Security ApiKeyQuery // @Success 200 {object} contracts.APIResponse "OnboardingStateResponse" +// @Failure 403 {object} contracts.ErrorResponse "Agent tokens cannot read onboarding state" // @Failure 503 {object} contracts.ErrorResponse "Service unavailable" // @Router /api/v1/onboarding/state [get] func (s *Server) handleGetOnboardingState(w http.ResponseWriter, r *http.Request) { + // #1166 round 10 (P4): DENIED to a non-admin caller. The wizard document is + // an OPERATOR document twice over — configured_server_count is the size of + // the whole inventory (the oracle /servers now withholds), and + // connected_client_ids plus mcp_clients_seen_ever are the operator's + // MCP-client inventory, the same class of fact /sessions already 403s for. + // Neither has a per-server projection, so the whole document is denied. + if !s.requireAdminRead(w, r, onboardingDenialMessage) { + return + } + resp, err := s.computeOnboardingState() if err != nil { s.writeError(w, r, http.StatusInternalServerError, fmt.Sprintf("compute onboarding state: %v", err)) @@ -126,9 +137,17 @@ func (s *Server) handleGetOnboardingState(w http.ResponseWriter, r *http.Request // @Param body body OnboardingMarkRequest true "Mark request" // @Success 200 {object} contracts.APIResponse "Updated OnboardingStateResponse" // @Failure 400 {object} contracts.ErrorResponse "Bad request" +// @Failure 403 {object} contracts.ErrorResponse "Agent tokens cannot read onboarding state" // @Failure 503 {object} contracts.ErrorResponse "Service unavailable" // @Router /api/v1/onboarding/mark [post] func (s *Server) handleMarkOnboardingState(w http.ResponseWriter, r *http.Request) { + // The mark POST ECHOES the same recomputed document on success, so gating + // the GET alone would leave the disclosure one POST away. It also writes + // operator wizard state, which an agent token has no business moving. + if !s.requireAdminRead(w, r, onboardingDenialMessage) { + return + } + var req OnboardingMarkRequest if r.Body != nil && r.ContentLength > 0 { if err := json.NewDecoder(r.Body).Decode(&req); err != nil { diff --git a/internal/httpapi/profiles.go b/internal/httpapi/profiles.go index d7b4eeec1..68cbc1170 100644 --- a/internal/httpapi/profiles.go +++ b/internal/httpapi/profiles.go @@ -3,6 +3,7 @@ package httpapi import ( "encoding/json" "fmt" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" "net/http" "strings" ) @@ -60,7 +61,23 @@ func (s *Server) handleListProfiles(w http.ResponseWriter, r *http.Request) { toolCounts := s.serverToolCounts() out := make([]ProfileSummary, 0, len(cfg.Profiles)) for i := range cfg.Profiles { + // #1166: profiles[].servers enumerates upstream server names a second + // time, independently of mcpServers — which is precisely why + // GET /api/v1/config denies a scoped caller rather than filtering. The + // denial buys nothing if this sibling route hands the same names back, + // so narrow the list here too. EffectiveServers returns a fresh slice, + // but it is rebuilt anyway rather than compacted, so nothing derived + // from the live config is ever mutated. eff := cfg.Profiles[i].EffectiveServers(cfg) + if auth.IsScopedCaller(r.Context()) { + scoped := make([]string, 0, len(eff)) + for _, name := range eff { + if canSeeServer(r.Context(), name) { + scoped = append(scoped, name) + } + } + eff = scoped + } tc := 0 for _, name := range eff { tc += toolCounts[name] @@ -110,6 +127,7 @@ type SetActiveProfileRequest struct { // @Param body body SetActiveProfileRequest true "Profile slug to activate (empty clears)" // @Success 200 {object} contracts.SuccessResponse "Active profile updated" // @Failure 400 {object} contracts.ErrorResponse "Invalid request body" +// @Failure 403 {object} contracts.ErrorResponse "Forbidden (agent tokens cannot change the active profile)" // @Failure 404 {object} contracts.ErrorResponse "Unknown profile" // @Router /api/v1/profiles/active [put] func (s *Server) handleSetActiveProfile(w http.ResponseWriter, r *http.Request) { diff --git a/internal/httpapi/scope.go b/internal/httpapi/scope.go new file mode 100644 index 000000000..5eef1998a --- /dev/null +++ b/internal/httpapi/scope.go @@ -0,0 +1,191 @@ +package httpapi + +import ( + "context" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts" +) + +// This file holds the two caller-aware predicates every REST read door reads +// from, plus the payload shapers built on top of them. Issues #1166 and #1167 +// were the same defect twice: five-plus doors each re-derived the answer to +// "what may this caller see?" from a config flag alone, so the MCP surface and +// the REST surface drifted apart and a scoped, read-only agent token received +// both the full server inventory and every server's plaintext credentials. +// +// Rule for anyone adding a read route under /api/v1: do not read +// cfg.RevealSecretHeaders and do not call CanAccessServer directly. Call +// s.revealSecrets(ctx) for values and canSeeServer / visibleServers for +// existence, so the two surfaces answer from one place. + +// canSeeServer reports whether the caller carried by ctx may learn that a +// server named `name` exists. Thin wrapper over the shared predicate so +// handlers in this package never reach for the AuthContext themselves. +func canSeeServer(ctx context.Context, name string) bool { + return auth.CanEnumerateServer(ctx, name) +} + +// visibleServers returns the subset of servers the caller carried by ctx is +// entitled to enumerate. +// +// It ALWAYS returns a freshly allocated slice for a scoped caller and never +// compacts in place: the backing array reaching this function is shared with +// the management service (and, on the SSE path, with every other subscriber), +// so an in-place compaction would corrupt an admin's view of the same data. +// The allocation is `make(..., 0, n)` so an empty result marshals as `[]` and +// not `null` — the Swift tray decodes contracts.GetServersResponse strictly. +// +// An admin, or a request with no AuthContext at all, gets the input slice back +// untouched (see auth.CanEnumerateServer for why absence is unrestricted). +func visibleServers(ctx context.Context, servers []contracts.Server) []contracts.Server { + if !auth.IsScopedCaller(ctx) { + return servers + } + out := make([]contracts.Server, 0, len(servers)) + for i := range servers { + if canSeeServer(ctx, servers[i].Name) { + out = append(out, servers[i]) + } + } + return out +} + +// upstreamStatsScalars are the aggregate counters that sit BESIDE the +// per-server map in an `upstream_stats` payload. They are computed over the +// unfiltered inventory by both producers (internal/server.Server.GetUpstreamStats +// and upstream.Manager.GetStats), so filtering only the "servers" sub-map would +// leave `total_servers` as an exact oracle for how many servers were hidden. +var upstreamStatsScalars = []string{ + "total_servers", + "connected_servers", + "connecting_servers", + "quarantined_servers", + "total_tools", +} + +// filterUpstreamStatsServers narrows an `upstream_stats` map to the servers the +// caller may enumerate, recomputing the sibling scalar counters from the +// surviving entries. +// +// The returned map is a fresh shallow copy for a scoped caller. That is +// load-bearing rather than tidy: this same map is handed to the SSE writer, +// which runs one goroutine per connection over payloads the event bus and the +// controller share, and a mutation here would be an unsynchronised map write +// concurrent with another goroutine's json.Marshal — a fatal, unrecoverable +// runtime error that takes the whole core down for every client. +func filterUpstreamStatsServers(ctx context.Context, stats map[string]interface{}) map[string]interface{} { + if stats == nil || !auth.IsScopedCaller(ctx) { + return stats + } + servers, ok := stats["servers"].(map[string]interface{}) + if !ok { + return stats + } + + filtered := make(map[string]interface{}, len(servers)) + connected, connecting, quarantined, totalTools := 0, 0, 0, 0 + for name, raw := range servers { + if !canSeeServer(ctx, name) { + continue + } + filtered[name] = raw + entry, ok := raw.(map[string]interface{}) + if !ok { + continue + } + if v, ok := entry["connected"].(bool); ok && v { + connected++ + } + if v, ok := entry["connecting"].(bool); ok && v { + connecting++ + } + if v, ok := entry["quarantined"].(bool); ok && v { + quarantined++ + } + totalTools += genericToolCount(entry["tool_count"]) + } + + out := make(map[string]interface{}, len(stats)) + for k, v := range stats { + out[k] = v + } + out["servers"] = filtered + // Only rewrite a scalar the producer actually emitted, so this cannot + // invent a key a client would then treat as authoritative. + recomputed := map[string]int{ + "total_servers": len(filtered), + "connected_servers": connected, + "connecting_servers": connecting, + "quarantined_servers": quarantined, + "total_tools": totalTools, + } + for _, key := range upstreamStatsScalars { + if _, present := stats[key]; present { + out[key] = recomputed[key] + } + } + return out +} + +// genericToolCount coerces a tool_count leaf into an int. The map reaches this +// function both straight from Go (int) and after a JSON round-trip (float64), +// so both encodings must be accepted — the same reason +// contracts.genericInt exists. +func genericToolCount(v interface{}) int { + switch n := v.(type) { + case int: + return n + case int64: + return int(n) + case float64: + return int(n) + default: + return 0 + } +} + +// recomputeServerStats rebuilds the aggregate counters of a GetServersResponse +// over the filtered slice. Without it the array shrinks while +// stats.total_servers keeps reporting the true inventory size — a precise +// count oracle for exactly what the filter just hid. +// +// DockerContainers and TokenMetrics are deployment-wide aggregates that cannot +// be re-derived per server; they are dropped for a scoped caller rather than +// reported wrongly. +func recomputeServerStats(ctx context.Context, filtered []contracts.Server, full contracts.ServerStats) contracts.ServerStats { + if !auth.IsScopedCaller(ctx) { + return full + } + out := contracts.ServerStats{TotalServers: len(filtered)} + for i := range filtered { + if filtered[i].Connected { + out.ConnectedServers++ + } + if filtered[i].Quarantined { + out.QuarantinedServers++ + } + if config.ServerContributesTools(filtered[i].Enabled, filtered[i].Quarantined) { + out.TotalTools += filtered[i].ToolCount + } + } + return out +} + +// revealSecrets is the ONE place this package decides whether a response may +// carry raw credential values (#1167). +// +// It ANDs the operator's `reveal_secret_headers` opt-in with the caller's +// identity, exactly as the MCP door has always done. Before this, four +// handlers in this package read the flag alone with the *http.Request sitting +// right there in scope, so an mcp_agt_ token got the operator's answer. +// +// Fails closed when the config cannot be read. +func (s *Server) revealSecrets(ctx context.Context) bool { + cfg, err := s.controller.GetConfig() + if err != nil || cfg == nil { + return false + } + return auth.RevealSecretsAllowed(ctx, cfg.RevealSecretHeaders) +} diff --git a/internal/httpapi/scope_reveal_harness_test.go b/internal/httpapi/scope_reveal_harness_test.go new file mode 100644 index 000000000..5d59ba5d0 --- /dev/null +++ b/internal/httpapi/scope_reveal_harness_test.go @@ -0,0 +1,388 @@ +package httpapi + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/require" + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts" + internalRuntime "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// Harness for issues #1166 (REST enumeration ignores allowed_servers) and +// #1167 (reveal_secret_headers checked without caller identity). +// +// Everything here drives the PRODUCTION chi route table through +// (*Server).ServeHTTP and the real apiKeyAuthMiddleware. The token is a real +// mcp_agt_ token validated by the real handleAgentTokenAuth, so the tests +// exercise the same AuthContext a live agent gets — no hand-built router and no +// mock that answers for any input. + +const ( + scopeAdminAPIKey = "admin-api-key-for-scope-tests" + alphaHeaderSecret = "SUPERSECRET_ALPHA_HEADER" + alphaQuerySecret = "SUPERSECRET_ALPHA_QUERY" + betaArgvSecret = "SUPERSECRET_BETA_ARGV" + betaEnvSecret = "SUPERSECRET_BETA_ENV" + // betaHealthDetail is the free-text health detail the diagnostics doors + // echo. It carries a URL query credential, which is the #872 shape + // oauth.ScrubUpstreamText exists for. + betaHealthDetail = `Post "https://beta.example.com/mcp?token=` + betaEnvSecret + `": no such host` +) + +// scopeFixtureServers returns the two-server inventory every test in this +// group runs against: `alpha`, which the scoped token MAY see, and `beta`, +// which it may not. Both carry credentials, in all four classes the live +// reproduction found leaking (header, URL query, argv, env). +func scopeFixtureServers() []contracts.Server { + return []contracts.Server{ + { + ID: "alpha", + Name: "alpha", + Protocol: "http", + URL: "https://alpha.example.com/mcp?token=" + alphaQuerySecret, + Headers: map[string]string{"Authorization": "Bearer " + alphaHeaderSecret}, + Enabled: true, + Connected: true, + Status: "Ready", + ToolCount: 3, + }, + { + ID: "beta", + Name: "beta", + Protocol: "stdio", + Command: "npx", + Args: []string{"beta-server", "--token=" + betaArgvSecret}, + Env: map[string]string{"BETA_API_KEY": betaEnvSecret}, + Enabled: true, + Connected: true, + Status: "Ready", + ToolCount: 7, + LastError: betaHealthDetail, + Health: &contracts.HealthStatus{ + Level: "unhealthy", + AdminState: "enabled", + Summary: "Connection error", + Detail: betaHealthDetail, + Action: "restart", + }, + }, + } +} + +func scopeFixtureConfig(reveal bool) *config.Config { + return &config.Config{ + Listen: "127.0.0.1:8080", + APIKey: scopeAdminAPIKey, + RevealSecretHeaders: reveal, + Servers: []*config.ServerConfig{ + { + Name: "alpha", + Protocol: "http", + URL: "https://alpha.example.com/mcp?token=" + alphaQuerySecret, + Headers: map[string]string{"Authorization": "Bearer " + alphaHeaderSecret}, + Enabled: true, + }, + { + Name: "beta", + Protocol: "stdio", + Command: "npx", + Args: []string{"beta-server", "--token=" + betaArgvSecret}, + Env: map[string]string{"BETA_API_KEY": betaEnvSecret}, + Enabled: true, + }, + }, + } +} + +// scopeMgmtService is the management-service half of the harness. It is a +// distinct type from mockManagementService so the fixture is under this test's +// control. +type scopeMgmtService struct { + servers []contracts.Server +} + +func (m *scopeMgmtService) ListServers(context.Context) ([]*contracts.Server, *contracts.ServerStats, error) { + out := make([]*contracts.Server, 0, len(m.servers)) + stats := &contracts.ServerStats{} + for i := range m.servers { + srv := m.servers[i] + out = append(out, &srv) + stats.TotalServers++ + if srv.Connected { + stats.ConnectedServers++ + } + if srv.Quarantined { + stats.QuarantinedServers++ + } + stats.TotalTools += srv.ToolCount + } + return out, stats, nil +} + +func (m *scopeMgmtService) GetServerTools(_ context.Context, name string) ([]map[string]interface{}, error) { + return []map[string]interface{}{ + {"name": name + "_tool", "server_name": name, "description": "tool of " + name}, + }, nil +} + +// scopeController drives both handleGetServers branches. When withManagement is +// false GetManagementService returns an UNTYPED nil so the legacy fallback is +// genuinely selected — a typed nil pointer would still be a non-nil interface +// and would silently re-select the management branch, which is exactly how a +// one-branch fix ships looking complete. +type scopeController struct { + MockServerController + cfg *config.Config + servers []contracts.Server + withManagement bool + + mu sync.Mutex + subs []chan internalRuntime.Event +} + +func (c *scopeController) GetManagementService() interface{} { + if !c.withManagement { + return nil + } + return &scopeMgmtService{servers: c.servers} +} + +// GetCurrentConfig must return a real *config.Config or apiKeyAuthMiddleware +// forwards the request with NO AuthContext at all and every scoped assertion +// below would pass for the wrong reason. +func (c *scopeController) GetCurrentConfig() interface{} { return c.cfg } + +func (c *scopeController) GetConfig() (*config.Config, error) { return c.cfg, nil } + +func (c *scopeController) GetAllServers() ([]map[string]interface{}, error) { + out := make([]map[string]interface{}, 0, len(c.servers)) + for i := range c.servers { + srv := c.servers[i] + raw, err := json.Marshal(srv) + if err != nil { + return nil, err + } + var generic map[string]interface{} + if err := json.Unmarshal(raw, &generic); err != nil { + return nil, err + } + // GetAllServers hands health out as the typed pointer in production; + // keep that shape so extractHealthFromMap and redactHealthDetail take + // the same branch they take at runtime. + generic["health"] = srv.Health + out = append(out, generic) + } + return out, nil +} + +func (c *scopeController) GetServerTools(name string) ([]map[string]interface{}, error) { + return []map[string]interface{}{ + {"name": name + "_tool", "server_name": name, "description": "tool of " + name}, + }, nil +} + +func (c *scopeController) SearchTools(_ string, _ int) ([]map[string]interface{}, error) { + out := make([]map[string]interface{}, 0, len(c.servers)) + for i := range c.servers { + out = append(out, map[string]interface{}{ + "tool": map[string]interface{}{ + "name": c.servers[i].Name + ":" + c.servers[i].Name + "_tool", + "server_name": c.servers[i].Name, + }, + "score": 0.9, + }) + } + return out, nil +} + +func (c *scopeController) ListToolApprovals(_ string) ([]*storage.ToolApprovalRecord, error) { + return nil, nil +} + +// GetUpstreamStats mirrors the real producer's shape: a per-server map keyed by +// name PLUS the aggregate scalars that sit beside it. Literal ints, not a JSON +// round-trip: ConvertUpstreamStatsToServerStats type-asserts tool_count as +// .(int) and a float64 would silently zero TotalTools, making a +// "total_tools equals the allowed server's count" oracle pass trivially. +func (c *scopeController) GetUpstreamStats() map[string]interface{} { + servers := map[string]interface{}{} + connected, totalTools := 0, 0 + for i := range c.servers { + servers[c.servers[i].Name] = map[string]interface{}{ + "name": c.servers[i].Name, + "connected": c.servers[i].Connected, + "connecting": false, + "quarantined": c.servers[i].Quarantined, + "tool_count": c.servers[i].ToolCount, + "url": c.servers[i].URL, + } + if c.servers[i].Connected { + connected++ + } + totalTools += c.servers[i].ToolCount + } + return map[string]interface{}{ + "servers": servers, + "total_servers": len(c.servers), + "connected_servers": connected, + "connecting_servers": 0, + "quarantined_servers": 0, + "total_tools": totalTools, + } +} + +func (c *scopeController) GetStatus() interface{} { + return map[string]interface{}{"phase": "Ready"} +} + +// StatusChannel returns a live (never-closed) channel. The default mock closes +// it immediately, which makes the SSE handler's select spin on a closed channel +// and return before any runtime event is delivered. +func (c *scopeController) StatusChannel() <-chan interface{} { + return make(chan interface{}) +} + +func (c *scopeController) SubscribeEvents() chan internalRuntime.Event { + // Buffered well past the largest burst any test publishes (the whole + // server-identity event class in one go). publishToAll gives up on a full + // channel after 2s exactly as publishEvent drops immediately, so an + // undersized buffer would silently turn a leak into a pass. + ch := make(chan internalRuntime.Event, 128) + c.mu.Lock() + c.subs = append(c.subs, ch) + c.mu.Unlock() + return ch +} + +func (c *scopeController) UnsubscribeEvents(ch chan internalRuntime.Event) { + c.mu.Lock() + defer c.mu.Unlock() + for i, sub := range c.subs { + if sub == ch { + c.subs = append(c.subs[:i], c.subs[i+1:]...) + return + } + } +} + +func (c *scopeController) subscriberCount() int { + c.mu.Lock() + defer c.mu.Unlock() + return len(c.subs) +} + +// publishToAll fans ONE event value out to every subscriber, exactly as +// runtime.publishEvent does — same map pointer, same slice backing array. That +// sharing is the whole reason renderEventPayloadForCaller must never mutate. +func (c *scopeController) publishToAll(evt internalRuntime.Event) { + c.mu.Lock() + subs := append([]chan internalRuntime.Event(nil), c.subs...) + c.mu.Unlock() + for _, ch := range subs { + select { + case ch <- evt: + case <-time.After(2 * time.Second): + } + } +} + +// scopedAgentServer wires a Server with a real agent token limited to +// allowedServers. agentTokenServer (tool_quarantine_test.go) hardcodes ["*"] +// and has no parameter for the scope, so this group needs its own. +func scopedAgentServer(t *testing.T, ctrl ServerController, allowedServers []string) (*Server, string) { + t.Helper() + tmpDir := t.TempDir() + _, err := auth.GetOrCreateHMACKey(tmpDir) + require.NoError(t, err) + + rawToken, err := auth.GenerateToken() + require.NoError(t, err) + + agentToken := &auth.AgentToken{ + Name: "scoped-ci", + TokenPrefix: auth.TokenPrefix(rawToken), + AllowedServers: allowedServers, + Permissions: []string{auth.PermRead}, + ExpiresAt: time.Now().Add(24 * time.Hour), + CreatedAt: time.Now(), + } + + store := &testTokenStore{ + validateFunc: func(token string, _ []byte) (*auth.AgentToken, error) { + if token == rawToken { + return agentToken, nil + } + return nil, fmt.Errorf("token not found") + }, + } + + srv := NewServer(ctrl, zap.NewNop().Sugar(), nil) + srv.SetTokenStore(store, tmpDir) + return srv, rawToken +} + +// scopeGet issues a GET through the production route table with the given +// X-API-Key and returns the recorder. +func scopeGet(t *testing.T, srv *Server, path, apiKey string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodGet, path, http.NoBody) + if apiKey != "" { + req.Header.Set("X-API-Key", apiKey) + } + rec := httptest.NewRecorder() + srv.ServeHTTP(rec, req) + return rec +} + +// scopeDecodeData decodes the `data` object of the standard API envelope. +func scopeDecodeData(t *testing.T, rec *httptest.ResponseRecorder) map[string]interface{} { + t.Helper() + var envelope struct { + Success bool `json:"success"` + Data map[string]interface{} `json:"data"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &envelope), "body: %s", rec.Body.String()) + require.True(t, envelope.Success, "body: %s", rec.Body.String()) + return envelope.Data +} + +func scopeServerNames(t *testing.T, data map[string]interface{}) []string { + t.Helper() + raw, ok := data["servers"].([]interface{}) + require.True(t, ok, "no servers array in %#v", data) + names := make([]string, 0, len(raw)) + for _, entry := range raw { + m, ok := entry.(map[string]interface{}) + require.True(t, ok) + name, _ := m["name"].(string) + names = append(names, name) + } + return names +} + +func scopeServerEntry(t *testing.T, data map[string]interface{}, name string) map[string]interface{} { + t.Helper() + raw, ok := data["servers"].([]interface{}) + require.True(t, ok, "no servers array in %#v", data) + for _, entry := range raw { + m, ok := entry.(map[string]interface{}) + require.True(t, ok) + if n, _ := m["name"].(string); n == name { + return m + } + } + t.Fatalf("server %q not present in response: %#v", name, data) + return nil +} diff --git a/internal/httpapi/scope_reveal_test.go b/internal/httpapi/scope_reveal_test.go new file mode 100644 index 000000000..412cd937e --- /dev/null +++ b/internal/httpapi/scope_reveal_test.go @@ -0,0 +1,446 @@ +package httpapi + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "regexp" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/oauth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/transport" +) + +// --------------------------------------------------------------------------- +// #1167 — reveal_secret_headers must be ANDed with caller identity +// --------------------------------------------------------------------------- + +// TestGetServers_RevealRequiresAuthenticatedAdmin pins the sharpest half of +// #1167: with reveal_secret_headers on, a scoped read-only agent token received +// all four credential classes in plaintext on GET /api/v1/servers. +// +// The oracle is VALUE EQUALITY against the same fixture put through the shared +// redactor, not "the body does not contain the secret" — an empty body, a 500 +// or a dropped field would pass a substring-absence oracle vacuously. The +// agent is entitled to SEE `alpha`, so its presence is asserted as a positive +// control: only the credential is withheld. +func TestGetServers_RevealRequiresAuthenticatedAdmin(t *testing.T) { + expectedMasked := scopeFixtureServers()[0] + oauth.RedactServerSecretFields(&expectedMasked) + + t.Run("agent token gets masked values", func(t *testing.T) { + ctrl := &scopeController{cfg: scopeFixtureConfig(true), servers: scopeFixtureServers(), withManagement: true} + srv, token := scopedAgentServer(t, ctrl, []string{"alpha"}) + + rec := scopeGet(t, srv, "/api/v1/servers", token) + require.Equal(t, http.StatusOK, rec.Code, "body: %s", rec.Body.String()) + data := scopeDecodeData(t, rec) + + // Positive control: the fixture landed and the route matched. + require.Contains(t, scopeServerNames(t, data), "alpha", + "precondition: the scoped agent must still SEE its own server") + + entry := scopeServerEntry(t, data, "alpha") + headers, _ := entry["headers"].(map[string]interface{}) + require.NotNil(t, headers, "alpha must still carry a headers map: %#v", entry) + assert.Equal(t, expectedMasked.Headers["Authorization"], headers["Authorization"], + "an agent token must get the SHARED redactor's output, not the raw Bearer token") + assert.Equal(t, expectedMasked.URL, entry["url"], + "the URL query credential must take the shared live rule for an agent token") + assert.NotContains(t, rec.Body.String(), alphaHeaderSecret) + assert.NotContains(t, rec.Body.String(), alphaQuerySecret) + }) + + t.Run("admin api key still gets the operator opt-in", func(t *testing.T) { + ctrl := &scopeController{cfg: scopeFixtureConfig(true), servers: scopeFixtureServers(), withManagement: true} + srv, _ := scopedAgentServer(t, ctrl, []string{"alpha"}) + + rec := scopeGet(t, srv, "/api/v1/servers", scopeAdminAPIKey) + require.Equal(t, http.StatusOK, rec.Code, "body: %s", rec.Body.String()) + data := scopeDecodeData(t, rec) + + entry := scopeServerEntry(t, data, "alpha") + headers, _ := entry["headers"].(map[string]interface{}) + require.NotNil(t, headers) + assert.Equal(t, "Bearer "+alphaHeaderSecret, headers["Authorization"], + "this is a NARROWING, not a removal: the operator opt-in must still work for an admin") + }) + + t.Run("no auth context at all is unprivileged", func(t *testing.T) { + // The middleware's testing/bootstrap passthrough forwards with NO + // AuthContext. Absence of an identity must not satisfy a gate that a + // scoped token fails. + ctrl := &scopeController{cfg: scopeFixtureConfig(true), servers: scopeFixtureServers(), withManagement: true} + srv := NewServer(passthroughController{ctrl}, zap.NewNop().Sugar(), nil) + + rec := scopeGet(t, srv, "/api/v1/servers", "") + require.Equal(t, http.StatusOK, rec.Code, "body: %s", rec.Body.String()) + data := scopeDecodeData(t, rec) + entry := scopeServerEntry(t, data, "alpha") + headers, _ := entry["headers"].(map[string]interface{}) + require.NotNil(t, headers) + assert.Equal(t, expectedMasked.Headers["Authorization"], headers["Authorization"], + "an unauthenticated caller must not be handed raw credentials") + }) +} + +// passthroughController forces apiKeyAuthMiddleware down its no-usable-config +// branch (GetCurrentConfig returns a non-*config.Config), which forwards the +// request with a nil AuthContext. +type passthroughController struct{ *scopeController } + +func (p passthroughController) GetCurrentConfig() interface{} { return map[string]interface{}{} } + +// TestGetServerDiagnostics_RevealRequiresAuthenticatedAdmin covers the +// per-server diagnostics door, where health.detail echoes the raw connect error +// with its URL credential. +// +// The oracle keys on FIELD VALUES only. A NotContains(body, "beta") oracle +// would be meaningless here: the server id is a path parameter this route +// echoes back into the body. +func TestGetServerDiagnostics_RevealRequiresAuthenticatedAdmin(t *testing.T) { + ctrl := &scopeController{cfg: scopeFixtureConfig(true), servers: scopeFixtureServers(), withManagement: true} + srv, token := scopedAgentServer(t, ctrl, []string{"alpha", "beta"}) + + t.Run("agent token gets the scrubbed detail", func(t *testing.T) { + rec := scopeGet(t, srv, "/api/v1/servers/beta/diagnostics", token) + require.Equal(t, http.StatusOK, rec.Code, "body: %s", rec.Body.String()) + data := scopeDecodeData(t, rec) + health, _ := data["health"].(map[string]interface{}) + require.NotNil(t, health, "precondition: the fixture must carry a health block: %#v", data) + assert.Equal(t, oauth.ScrubUpstreamText(betaHealthDetail), health["detail"], + "health.detail must take the one shared free-text rule for a non-admin caller") + }) + + t.Run("admin api key still gets the raw detail", func(t *testing.T) { + rec := scopeGet(t, srv, "/api/v1/servers/beta/diagnostics", scopeAdminAPIKey) + require.Equal(t, http.StatusOK, rec.Code, "body: %s", rec.Body.String()) + data := scopeDecodeData(t, rec) + health, _ := data["health"].(map[string]interface{}) + require.NotNil(t, health) + assert.Equal(t, betaHealthDetail, health["detail"], + "the operator opt-in must still work for an authenticated admin") + }) +} + +// --------------------------------------------------------------------------- +// #1166 — REST enumeration must honour allowed_servers +// --------------------------------------------------------------------------- + +// TestGetServers_AgentTokenSeesOnlyAllowedSubset_ManagementPath pins the +// management-service branch. The stats half is what a naive array-only filter +// fails: total_servers would stay an exact count oracle for what was hidden. +func TestGetServers_AgentTokenSeesOnlyAllowedSubset_ManagementPath(t *testing.T) { + ctrl := &scopeController{cfg: scopeFixtureConfig(false), servers: scopeFixtureServers(), withManagement: true} + srv, token := scopedAgentServer(t, ctrl, []string{"alpha"}) + + rec := scopeGet(t, srv, "/api/v1/servers", token) + require.Equal(t, http.StatusOK, rec.Code, "body: %s", rec.Body.String()) + data := scopeDecodeData(t, rec) + + assert.Equal(t, []string{"alpha"}, scopeServerNames(t, data), + "a token scoped to alpha must enumerate exactly alpha") + + stats, _ := data["stats"].(map[string]interface{}) + require.NotNil(t, stats, "precondition: the response must carry stats: %#v", data) + assert.Equal(t, float64(1), stats["total_servers"], "stats must narrow with the array") + assert.Equal(t, float64(3), stats["total_tools"], "total_tools must count only alpha's tools") +} + +// TestGetServers_AgentTokenSeesOnlyAllowedSubset_LegacyPath pins the OTHER +// branch. A fix applied only inside the `if mgmtSvc != nil` block passes the +// management test and fails this one. +func TestGetServers_AgentTokenSeesOnlyAllowedSubset_LegacyPath(t *testing.T) { + ctrl := &scopeController{cfg: scopeFixtureConfig(false), servers: scopeFixtureServers(), withManagement: false} + require.Nil(t, ctrl.GetManagementService(), + "precondition: this harness must genuinely select the legacy fallback") + srv, token := scopedAgentServer(t, ctrl, []string{"alpha"}) + + rec := scopeGet(t, srv, "/api/v1/servers", token) + require.Equal(t, http.StatusOK, rec.Code, "body: %s", rec.Body.String()) + data := scopeDecodeData(t, rec) + + assert.Equal(t, []string{"alpha"}, scopeServerNames(t, data)) + stats, _ := data["stats"].(map[string]interface{}) + require.NotNil(t, stats) + assert.Equal(t, float64(1), stats["total_servers"]) + assert.Equal(t, float64(3), stats["total_tools"]) +} + +// TestGetServers_AdminContextsUnfiltered is a REGRESSION GUARD, not a bite +// test: it asserts the unfiltered result, which is what unfixed code returns +// too. It exists because a fix that empties an admin's server list is a worse +// bug than the one being fixed, and case (c) — the middleware's nil-AuthContext +// passthrough — is the regression that would blank the list for most of this +// package's existing tests. +func TestGetServers_AdminContextsUnfiltered(t *testing.T) { + newCtrl := func() *scopeController { + return &scopeController{cfg: scopeFixtureConfig(false), servers: scopeFixtureServers(), withManagement: true} + } + + t.Run("global api key", func(t *testing.T) { + srv, _ := scopedAgentServer(t, newCtrl(), []string{"alpha"}) + data := scopeDecodeData(t, scopeGet(t, srv, "/api/v1/servers", scopeAdminAPIKey)) + assert.ElementsMatch(t, []string{"alpha", "beta"}, scopeServerNames(t, data)) + stats, _ := data["stats"].(map[string]interface{}) + require.NotNil(t, stats) + assert.Equal(t, float64(2), stats["total_servers"]) + assert.Equal(t, float64(10), stats["total_tools"]) + }) + + t.Run("tray unix socket", func(t *testing.T) { + srv, _ := scopedAgentServer(t, newCtrl(), []string{"alpha"}) + req := httptest.NewRequest(http.MethodGet, "/api/v1/servers", http.NoBody) + req = req.WithContext(transport.TagConnectionContext(req.Context(), transport.ConnectionSourceTray)) + rec := httptest.NewRecorder() + srv.ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code, "body: %s", rec.Body.String()) + assert.ElementsMatch(t, []string{"alpha", "beta"}, scopeServerNames(t, scopeDecodeData(t, rec))) + }) + + t.Run("no auth context passthrough", func(t *testing.T) { + srv := NewServer(passthroughController{newCtrl()}, zap.NewNop().Sugar(), nil) + rec := scopeGet(t, srv, "/api/v1/servers", "") + require.Equal(t, http.StatusOK, rec.Code, "body: %s", rec.Body.String()) + assert.ElementsMatch(t, []string{"alpha", "beta"}, scopeServerNames(t, scopeDecodeData(t, rec)), + "absence of a token must be treated as unrestricted, exactly as auth.AuthorizeServerOp does") + }) +} + +// TestGetConfig_AgentTokenForbidden_AdminUnaffected covers BOTH issues on the +// widest door on the tree. It is not in #1167's site list but the live +// reproduction showed it leaking every credential class AND the whole +// inventory, and the document also carries the global admin api_key — a +// privilege-escalation primitive for a scoped token. +func TestGetConfig_AgentTokenForbidden_AdminUnaffected(t *testing.T) { + ctrl := &scopeController{cfg: scopeFixtureConfig(true), servers: scopeFixtureServers(), withManagement: true} + srv, token := scopedAgentServer(t, ctrl, []string{"alpha"}) + + t.Run("agent token is denied", func(t *testing.T) { + rec := scopeGet(t, srv, "/api/v1/config", token) + require.Equal(t, http.StatusForbidden, rec.Code, "body: %s", rec.Body.String()) + body := rec.Body.String() + assert.NotContains(t, body, scopeAdminAPIKey, "the admin api_key must never reach an agent token") + assert.NotContains(t, body, alphaHeaderSecret) + assert.NotContains(t, body, alphaQuerySecret) + assert.NotContains(t, body, betaArgvSecret) + assert.NotContains(t, body, betaEnvSecret) + assert.NotContains(t, body, `"beta"`, "the config document must not enumerate a server outside the token's scope") + }) + + t.Run("admin api key is unaffected", func(t *testing.T) { + rec := scopeGet(t, srv, "/api/v1/config", scopeAdminAPIKey) + require.Equal(t, http.StatusOK, rec.Code, "body: %s", rec.Body.String()) + body := rec.Body.String() + assert.Contains(t, body, `"alpha"`, "an admin must still read the whole document") + assert.Contains(t, body, `"beta"`) + assert.Contains(t, body, alphaHeaderSecret, + "with reveal_secret_headers on, an authenticated admin still gets raw values") + }) +} + +// TestGetStatus_UpstreamStatsScoped pins the most-polled door. The nested +// assertion matters: withLiveUpstreamStats rebuilds data.status from the same +// map, so a fix that filters only the top-level field leaves the nested copy +// leaking. +func TestGetStatus_UpstreamStatsScoped(t *testing.T) { + ctrl := &scopeController{cfg: scopeFixtureConfig(false), servers: scopeFixtureServers(), withManagement: true} + srv, token := scopedAgentServer(t, ctrl, []string{"alpha"}) + + statsKeys := func(data map[string]interface{}, path ...string) map[string]interface{} { + cur := data + for _, p := range path { + next, ok := cur[p].(map[string]interface{}) + require.True(t, ok, "missing %q in %#v", p, cur) + cur = next + } + return cur + } + + t.Run("agent token sees only its own server", func(t *testing.T) { + rec := scopeGet(t, srv, "/api/v1/status", token) + require.Equal(t, http.StatusOK, rec.Code, "body: %s", rec.Body.String()) + data := scopeDecodeData(t, rec) + + top := statsKeys(data, "upstream_stats") + servers := statsKeys(data, "upstream_stats", "servers") + require.Len(t, servers, 1, "%#v", servers) + require.Contains(t, servers, "alpha", "precondition: the allowed server must still be reported") + assert.Equal(t, float64(1), top["total_servers"], + "the sibling scalar must be recomputed or it stays an exact count oracle") + assert.Equal(t, float64(3), top["total_tools"]) + + nested := statsKeys(data, "status", "upstream_stats", "servers") + require.Len(t, nested, 1, "the NESTED snapshot must narrow too: %#v", nested) + require.Contains(t, nested, "alpha") + }) + + t.Run("admin sees everything", func(t *testing.T) { + rec := scopeGet(t, srv, "/api/v1/status", scopeAdminAPIKey) + data := scopeDecodeData(t, rec) + servers := statsKeys(data, "upstream_stats", "servers") + assert.Len(t, servers, 2) + assert.Equal(t, float64(2), statsKeys(data, "upstream_stats")["total_servers"]) + }) +} + +// TestGetGlobalTools_ScopedToAllowedServers. After #1166 filters /api/v1/servers +// a scoped token would otherwise get a STRICTLY LARGER inventory here — every +// server_name plus every tool name and description. Its MCP twin filters via +// serverInScope. +func TestGetGlobalTools_ScopedToAllowedServers(t *testing.T) { + ctrl := &scopeController{cfg: scopeFixtureConfig(false), servers: scopeFixtureServers(), withManagement: true} + srv, token := scopedAgentServer(t, ctrl, []string{"alpha"}) + + toolServerNames := func(rec *httptest.ResponseRecorder) []string { + data := scopeDecodeData(t, rec) + raw, ok := data["tools"].([]interface{}) + require.True(t, ok, "no tools array in %#v", data) + names := make([]string, 0, len(raw)) + for _, entry := range raw { + m, _ := entry.(map[string]interface{}) + name, _ := m["server_name"].(string) + names = append(names, name) + } + return names + } + + agent := scopeGet(t, srv, "/api/v1/tools", token) + require.Equal(t, http.StatusOK, agent.Code, "body: %s", agent.Body.String()) + assert.Equal(t, []string{"alpha"}, toolServerNames(agent), + "GET /api/v1/tools must not hand back the inventory GET /api/v1/servers just denied") + + admin := scopeGet(t, srv, "/api/v1/tools", scopeAdminAPIKey) + require.Equal(t, http.StatusOK, admin.Code) + assert.ElementsMatch(t, []string{"alpha", "beta"}, toolServerNames(admin), + "an admin must still see every server's tools") +} + +// TestSearchTools_ScopedToAllowedServers covers the discovery surface, whose +// MCP twin (retrieve_tools) filters through serverInScope. +func TestSearchTools_ScopedToAllowedServers(t *testing.T) { + ctrl := &scopeController{cfg: scopeFixtureConfig(false), servers: scopeFixtureServers(), withManagement: true} + srv, token := scopedAgentServer(t, ctrl, []string{"alpha"}) + + hits := func(rec *httptest.ResponseRecorder) []string { + data := scopeDecodeData(t, rec) + raw, ok := data["results"].([]interface{}) + require.True(t, ok, "no results array in %#v", data) + names := make([]string, 0, len(raw)) + for _, entry := range raw { + m, _ := entry.(map[string]interface{}) + tool, _ := m["tool"].(map[string]interface{}) + name, _ := tool["server_name"].(string) + names = append(names, name) + } + return names + } + + agent := scopeGet(t, srv, "/api/v1/index/search?q=tool", token) + require.Equal(t, http.StatusOK, agent.Code, "body: %s", agent.Body.String()) + assert.Equal(t, []string{"alpha"}, hits(agent)) + + admin := scopeGet(t, srv, "/api/v1/index/search?q=tool", scopeAdminAPIKey) + assert.ElementsMatch(t, []string{"alpha", "beta"}, hits(admin)) +} + +// TestServerDiagnostics_UnentitledIsIndistinguishableFromAbsent is the +// STATUS-PARITY oracle. "The body must not contain the server name" would pass +// vacuously here — a 404 on this route echoes the caller's own path parameter +// straight back into the message. +// +// The positive control on the same router is what stops the whole test passing +// for the wrong reason (a broken fixture, a route that never matched, a 404 for +// everyone). +func TestServerDiagnostics_UnentitledIsIndistinguishableFromAbsent(t *testing.T) { + ctrl := &scopeController{cfg: scopeFixtureConfig(false), servers: scopeFixtureServers(), withManagement: true} + srv, token := scopedAgentServer(t, ctrl, []string{"alpha"}) + + // Positive control: the fixture landed, the route matched, and the token + // genuinely reaches the handler. + allowed := scopeGet(t, srv, "/api/v1/servers/alpha/diagnostics", token) + require.Equal(t, http.StatusOK, allowed.Code, + "precondition: the scoped token must reach this route for its OWN server; body: %s", allowed.Body.String()) + + // Second control: `beta` really does exist, and an admin can see it here. + adminBeta := scopeGet(t, srv, "/api/v1/servers/beta/diagnostics", scopeAdminAPIKey) + require.Equal(t, http.StatusOK, adminBeta.Code, + "precondition: beta must exist and be visible to an admin; body: %s", adminBeta.Body.String()) + + unentitled := scopeGet(t, srv, "/api/v1/servers/beta/diagnostics", token) + absent := scopeGet(t, srv, "/api/v1/servers/does-not-exist-at-all/diagnostics", token) + + assert.Equal(t, absent.Code, unentitled.Code, + "an unentitled server must return the same status as one that does not exist") + assert.Equal(t, http.StatusNotFound, absent.Code, + "precondition: an absent server must be distinguishable from a successful read, or the parity above is vacuous") + + // Same body modulo the echoed path parameter and the per-request id. + requestIDPattern := regexp.MustCompile(`"request_id":"[^"]*"`) + normalize := func(rec *httptest.ResponseRecorder, name string) string { + body := strings.ReplaceAll(rec.Body.String(), name, "") + return requestIDPattern.ReplaceAllString(body, `"request_id":""`) + } + assert.Equal(t, normalize(absent, "does-not-exist-at-all"), normalize(unentitled, "beta"), + "the two responses must be byte-identical once the echoed name is normalised") +} + +// --------------------------------------------------------------------------- +// The shared predicate itself +// --------------------------------------------------------------------------- + +func TestRevealSecretsAllowed_RequiresBothHalves(t *testing.T) { + admin := auth.WithAuthContext(t.Context(), auth.AdminContext()) + agent := auth.WithAuthContext(t.Context(), &auth.AuthContext{Type: auth.AuthTypeAgent, AllowedServers: []string{"alpha"}}) + anon := auth.WithAuthContext(t.Context(), auth.AnonymousContext()) + + assert.True(t, auth.RevealSecretsAllowed(admin, true)) + assert.False(t, auth.RevealSecretsAllowed(admin, false), "the operator flag is still required") + assert.False(t, auth.RevealSecretsAllowed(agent, true), "a scoped agent token is not the operator") + assert.False(t, auth.RevealSecretsAllowed(anon, true), "an unauthenticated back-compat admin proved no identity") + assert.False(t, auth.RevealSecretsAllowed(t.Context(), true), "no AuthContext means no identity") + var nilCtx context.Context + assert.False(t, auth.RevealSecretsAllowed(nilCtx, true), "a nil ctx must fail closed, not panic") +} + +func TestCanEnumerateServer_AbsenceIsUnrestricted(t *testing.T) { + agent := auth.WithAuthContext(t.Context(), &auth.AuthContext{Type: auth.AuthTypeAgent, AllowedServers: []string{"alpha"}}) + wildcard := auth.WithAuthContext(t.Context(), &auth.AuthContext{Type: auth.AuthTypeAgent, AllowedServers: []string{"*"}}) + + assert.True(t, auth.CanEnumerateServer(agent, "alpha")) + assert.False(t, auth.CanEnumerateServer(agent, "beta")) + assert.True(t, auth.CanEnumerateServer(wildcard, "beta")) + assert.True(t, auth.CanEnumerateServer(t.Context(), "beta"), + "no AuthContext must stay unrestricted — the middleware forwards that way on its no-config path") + var nilCtx context.Context + assert.True(t, auth.CanEnumerateServer(nilCtx, "beta"), "a nil ctx must not panic") + assert.True(t, auth.CanEnumerateServer(auth.WithAuthContext(t.Context(), auth.AdminContext()), "beta")) +} + +// TestVisibleServers_NeverCompactsInPlace pins the aliasing rule the SSE path +// depends on: the input slice's backing array is shared with the event bus and +// every other subscriber, so a compaction here would corrupt an admin's view +// concurrently. +func TestVisibleServers_NeverCompactsInPlace(t *testing.T) { + agent := auth.WithAuthContext(t.Context(), &auth.AuthContext{Type: auth.AuthTypeAgent, AllowedServers: []string{"beta"}}) + input := scopeFixtureServers() + + out := visibleServers(agent, input) + require.Len(t, out, 1) + assert.Equal(t, "beta", out[0].Name) + assert.Equal(t, []string{"alpha", "beta"}, []string{input[0].Name, input[1].Name}, + "the caller's slice must be untouched") + + empty := visibleServers(auth.WithAuthContext(t.Context(), &auth.AuthContext{Type: auth.AuthTypeAgent}), input) + raw, err := json.Marshal(map[string]interface{}{"servers": empty}) + require.NoError(t, err) + assert.Contains(t, string(raw), `"servers":[]`, + "an empty subset must marshal as [] and not null — the Swift tray decodes this strictly") +} diff --git a/internal/httpapi/scope_round10_test.go b/internal/httpapi/scope_round10_test.go new file mode 100644 index 000000000..9f3efd016 --- /dev/null +++ b/internal/httpapi/scope_round10_test.go @@ -0,0 +1,500 @@ +package httpapi + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts" + internalRuntime "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/security/scanner" +) + +// Round 10 of the #1166/#1167 cross-review. Every test here runs the PRODUCTION +// chi route table with the real agent-token middleware against the shared +// two-server fixture: `alpha`, which the scoped token may see, and `beta`, +// which it may not. +// +// The headline finding is P1: GET /api/v1/info handed the GLOBAL ADMIN API KEY +// to a scoped agent token inside web_ui_url, which made every other control in +// this branch decorative — a scoped caller read the admin key and stopped being +// scoped. + +// scopeRound10Server wires the fixture with a security controller attached, so +// the /security routes reach their handlers rather than 501. +func scopeRound10Server(t *testing.T, sec *mockSecurityController) (*Server, string) { + t.Helper() + ctrl := &scopeController{cfg: scopeFixtureConfig(false), servers: scopeFixtureServers(), withManagement: true} + srv, token := scopedAgentServer(t, ctrl, []string{"alpha"}) + if sec != nil { + srv.SetSecurityController(sec) + } + return srv, token +} + +// TestInfo_ScopedCallerNeverReceivesTheAdminAPIKey is the P1 regression. +// +// Verified live on a running instance before the fix: a read-only token scoped +// to one server received +// +// "web_ui_url":"http://127.0.0.1:18413/ui/?apikey=devkey-abc123" +// +// and could authenticate as an admin with it. +// +// The oracle is not "the body does not mention the key" — it is that the query +// carrier is absent for the scoped caller while an ADMIN on the same route, +// same fixture, same request still receives it. Without that second half the +// assertion would pass just as happily against a /info that returned nothing at +// all, or against a fixture whose config had no API key to leak. +func TestInfo_ScopedCallerNeverReceivesTheAdminAPIKey(t *testing.T) { + srv, token := scopeRound10Server(t, nil) + + adminRec := scopeGet(t, srv, "/api/v1/info", scopeAdminAPIKey) + require.Equal(t, http.StatusOK, adminRec.Code) + adminURL, _ := scopeDecodeData(t, adminRec)["web_ui_url"].(string) + require.Equal(t, "http://127.0.0.1:8080/ui/?apikey="+scopeAdminAPIKey, adminURL, + "positive control: an authenticated admin must still get the copy-paste URL, "+ + "or this test proves nothing about who was denied") + + agentRec := scopeGet(t, srv, "/api/v1/info", token) + require.Equal(t, http.StatusOK, agentRec.Code, + "/info stays readable — only the credential in it is withheld") + agentData := scopeDecodeData(t, agentRec) + agentURL, ok := agentData["web_ui_url"].(string) + require.True(t, ok, "web_ui_url must still be present for a scoped caller: %#v", agentData) + + assert.Equal(t, "http://127.0.0.1:8080/ui/", agentURL, + "the admin API key must not be handed to a scoped agent token") + assert.NotContains(t, agentRec.Body.String(), scopeAdminAPIKey, + "the admin API key must not appear anywhere in the /info payload") + assert.NotContains(t, agentURL, "apikey=", + "no credential carrier may survive in the URL") +} + +// TestSSE_IdentityBearingFrameWithNoServerNameIsDropped is the P2 regression. +// +// eventVisibleToCaller dropped a frame only when an identity key held a +// NON-EMPTY string. Runtime.EmitActivityInternalToolCall omits `target_server` +// entirely when it is empty — every built-in call not routed to one upstream — +// so those frames reached a scoped subscriber whole, carrying `arguments` and +// `response`, i.e. the fleet inventory the door exists to withhold. +func TestSSE_IdentityBearingFrameWithNoServerNameIsDropped(t *testing.T) { + ctrl := &scopeController{cfg: scopeFixtureConfig(false), servers: scopeFixtureServers(), withManagement: true} + srv, token := scopedAgentServer(t, ctrl, []string{"alpha"}) + + ts := httptest.NewServer(srv) + defer ts.Close() + + adminBody, adminClose := sseSubscribe(t, ts.URL, scopeAdminAPIKey) + defer adminClose() + agentBody, agentClose := sseSubscribe(t, ts.URL, token) + defer agentClose() + + require.Eventually(t, func() bool { return ctrl.subscriberCount() == 2 }, 5*time.Second, 20*time.Millisecond) + + // An internal tool call with NO target_server at all — the exact shape the + // producer emits for retrieve_tools — carrying a beta secret in the + // response it would hand the subscriber. + leak := internalRuntime.Event{ + Type: internalRuntime.EventTypeActivityInternalToolCall, + Payload: map[string]any{ + "internal_tool_name": "retrieve_tools", + "status": "ok", + "response": "tools of every server including " + betaEnvSecret, + "response_truncated": false, + }, + Timestamp: time.Now(), + } + // A servers.changed published AFTER it: never dropped for anyone, so both + // readers are guaranteed to see a frame and the agent's read cannot hang + // waiting for one that will never arrive. + marker := internalRuntime.Event{ + Type: internalRuntime.EventTypeServersChanged, + Payload: map[string]any{"reason": "round10-marker"}, + Timestamp: time.Now(), + } + ctrl.publishToAll(leak) + ctrl.publishToAll(marker) + + adminFirst := sseReadRuntimeEvent(t, adminBody) + require.Equal(t, string(internalRuntime.EventTypeActivityInternalToolCall), adminFirst.event, + "positive control: the frame must actually be published, or the agent's silence means nothing") + assert.Contains(t, adminFirst.data, betaEnvSecret, + "positive control: the admin must receive the payload that was planted") + + agentFirst := sseReadRuntimeEvent(t, agentBody) + assert.Equal(t, string(internalRuntime.EventTypeServersChanged), agentFirst.event, + "the scoped subscriber must skip straight to the marker: an identity-bearing frame "+ + "that names no server is undecidable and must fail closed") + assert.NotContains(t, agentFirst.data, betaEnvSecret) +} + +// TestSSE_IdentityBearingEventTypesCoverEveryNamingProducer keeps the +// production set honest. sseIdentityEventFixtures is the test's own catalogue +// of event types that name a server; identityBearingEventTypes is the one the +// SHIPPED filter reads. If those two ever drift, a type gains an empty-identity +// hole the moment its producer stops populating the field. +func TestSSE_IdentityBearingEventTypesCoverEveryNamingProducer(t *testing.T) { + fixtures := map[internalRuntime.EventType]bool{} + for _, e := range sseIdentityEventFixtures("beta") { + fixtures[e.Type] = true + } + require.NotEmpty(t, fixtures, "no fixtures parsed — the guard would pass vacuously") + + for typ := range fixtures { + _, ok := identityBearingEventTypes[typ] + assert.True(t, ok, "event type %q names a server in the fixtures but is missing from "+ + "identityBearingEventTypes, so a frame of that type with an empty name reaches a scoped subscriber", typ) + } + for typ := range identityBearingEventTypes { + assert.True(t, fixtures[typ], "event type %q is declared identity-bearing in production but has no "+ + "fixture proving it is scoped end-to-end", typ) + } +} + +// TestSecurityScanners_ConfiguredEnvSecretsAreRedacted is the P3 regression. +// The struct's own comment claimed "secrets redacted in API"; nothing redacted +// them, so the vendor API keys an operator typed into the scanner config dialog +// came back in the clear on both scanner read doors. +func TestSecurityScanners_ConfiguredEnvSecretsAreRedacted(t *testing.T) { + const vendorKey = "SUPERSECRET_SCANNER_VENDOR_KEY" + const keyringRef = "${keyring:scanner/other}" + sec := &mockSecurityController{ + scanners: []*scanner.ScannerPlugin{{ + ID: "ramparts", + Name: "Ramparts", + Status: scanner.ScannerStatusConfigured, + ConfiguredEnv: map[string]string{ + "VENDOR_API_KEY": vendorKey, + "OTHER_API_KEY": keyringRef, + }, + }}, + } + srv, _ := scopeRound10Server(t, sec) + + for _, path := range []string{"/api/v1/security/scanners", "/api/v1/security/scanners/ramparts/status"} { + rec := scopeGet(t, srv, path, scopeAdminAPIKey) + require.Equal(t, http.StatusOK, rec.Code, path) + body := rec.Body.String() + + assert.Contains(t, body, "ramparts", + "positive control: the scanner fixture must actually be serialized by %s", path) + assert.Contains(t, body, "VENDOR_API_KEY", + "positive control: the configured env must still be reported as SET by %s", path) + assert.NotContains(t, body, vendorKey, + "%s must not serialize the literal scanner secret", path) + assert.Contains(t, body, scanner.RedactedEnvValue, + "%s must report the value as redacted, not omit the key", path) + assert.Contains(t, body, keyringRef, + "a ${keyring:} reference is a pointer, not a secret, and the UI reads it to say "+ + "'stored in keyring' — %s must preserve it verbatim", path) + } + + // Redaction must not corrupt the registry's own copy: a later scan has to + // launch the scanner with the REAL value. + assert.Equal(t, vendorKey, sec.scanners[0].ConfiguredEnv["VENDOR_API_KEY"], + "redaction must copy, never mutate the controller's record") +} + +// TestSecurityFleetDoors_DeniedToScopedCaller is the P4 regression for the two +// deployment-wide security documents. Both were reachable at 200 by a scoped +// token: /security/queue enumerates every queued ServerName, /security/overview +// reports fleet-wide scan and finding counts. +func TestSecurityFleetDoors_DeniedToScopedCaller(t *testing.T) { + sec := &mockSecurityController{ + overview: &scanner.SecurityOverview{TotalScans: 4, ServersScanned: 2, ScannersEnabled: 1}, + queueProgress: &scanner.QueueProgress{ + BatchID: "batch-1", + Status: "running", + Total: 2, + Items: []scanner.QueueItem{ + {ServerName: "alpha"}, + {ServerName: "beta"}, + }, + }, + } + srv, token := scopeRound10Server(t, sec) + + for _, path := range []string{"/api/v1/security/queue", "/api/v1/security/overview"} { + adminRec := scopeGet(t, srv, path, scopeAdminAPIKey) + require.Equal(t, http.StatusOK, adminRec.Code, + "positive control: %s must be a live, reachable route for an admin", path) + + agentRec := scopeGet(t, srv, path, token) + assert.Equal(t, http.StatusForbidden, agentRec.Code, "%s must be denied to a scoped caller", path) + assert.Contains(t, agentRec.Body.String(), securityFleetDenialMessage, path) + assert.NotContains(t, agentRec.Body.String(), "beta", + "%s must not name a server the caller may not enumerate", path) + } + + // The queue really did carry the inventory an admin can see, so the denial + // above withheld something real. + assert.Contains(t, scopeGet(t, srv, "/api/v1/security/queue", scopeAdminAPIKey).Body.String(), "beta") +} + +// TestSecurityScanReportByJobID_ScopedTo404 is the P4 regression for the +// per-server report reached by JOB id, which walked around the /servers/{id} +// subtree gate. +// +// It is SCOPED, not denied: the document is per-server, so a caller entitled to +// the server keeps it. The denial for an unentitled server is the same 404 the +// unknown-job branch already returns, so "not yours" and "no such job" are +// indistinguishable. +func TestSecurityScanReportByJobID_ScopedTo404(t *testing.T) { + betaReport := &scanner.AggregatedReport{JobID: "scan-beta-1", ServerName: "beta", RiskScore: 91} + sec := &mockSecurityController{report: betaReport} + srv, token := scopeRound10Server(t, sec) + + adminRec := scopeGet(t, srv, "/api/v1/security/scans/scan-beta-1/report", scopeAdminAPIKey) + require.Equal(t, http.StatusOK, adminRec.Code, + "positive control: the report fixture must be reachable for an admin") + require.Contains(t, adminRec.Body.String(), "beta") + + agentRec := scopeGet(t, srv, "/api/v1/security/scans/scan-beta-1/report", token) + assert.Equal(t, http.StatusNotFound, agentRec.Code, + "a scoped caller must not read another server's scan report by job id") + + // Status parity with a job that genuinely does not exist. The mock returns + // an error for any id once `report` is cleared, which is the absent case. + sec.report = nil + absentRec := scopeGet(t, srv, "/api/v1/security/scans/scan-beta-1/report", token) + assert.Equal(t, absentRec.Code, agentRec.Code, + "'not yours' and 'no such job' must be the same status") + + // And the entitled server still resolves, so the gate scopes rather than + // blanks the route. + sec.report = &scanner.AggregatedReport{JobID: "scan-alpha-1", ServerName: "alpha"} + alphaRec := scopeGet(t, srv, "/api/v1/security/scans/scan-alpha-1/report", token) + assert.Equal(t, http.StatusOK, alphaRec.Code, + "a scoped caller must still read the report for a server it may see") +} + +// TestTelemetryPayload_DeniedToScopedCaller is the P4 regression for the +// heartbeat preview: a fleet-wide census (server_count, connected_server_count, +// tool_count, server_docker_isolated_count) — the exact count oracle this +// branch removed from /status. +// +// No telemetry provider is wired, so the admin's 503 is the positive control: +// it proves the request passed the gate and reached the handler body, i.e. the +// gate is the only difference between the two callers. +func TestTelemetryPayload_DeniedToScopedCaller(t *testing.T) { + srv, token := scopeRound10Server(t, nil) + + adminRec := scopeGet(t, srv, "/api/v1/telemetry/payload", scopeAdminAPIKey) + require.Equal(t, http.StatusServiceUnavailable, adminRec.Code, + "positive control: an admin must reach the handler body (no provider wired here)") + + agentRec := scopeGet(t, srv, "/api/v1/telemetry/payload", token) + assert.Equal(t, http.StatusForbidden, agentRec.Code) + assert.Contains(t, agentRec.Body.String(), telemetryPayloadDenialMessage) +} + +// TestOnboardingState_DeniedToScopedCaller is the P4 regression for the wizard +// document: configured_server_count over the whole inventory plus +// connected_client_ids, the operator's MCP-client inventory. The branch already +// 403s /sessions for that same class. +func TestOnboardingState_DeniedToScopedCaller(t *testing.T) { + srv, token := scopeRound10Server(t, nil) + + adminRec := scopeGet(t, srv, "/api/v1/onboarding/state", scopeAdminAPIKey) + require.Equal(t, http.StatusOK, adminRec.Code) + adminData := scopeDecodeData(t, adminRec) + require.EqualValues(t, 2, adminData["configured_server_count"], + "positive control: the document must really report the whole inventory for an admin") + + agentRec := scopeGet(t, srv, "/api/v1/onboarding/state", token) + assert.Equal(t, http.StatusForbidden, agentRec.Code) + assert.Contains(t, agentRec.Body.String(), onboardingDenialMessage) + + // The POST echoes the same recomputed document, so gating the GET alone + // would have left the disclosure one request away. + markReq := httptest.NewRequest(http.MethodPost, "/api/v1/onboarding/mark", strings.NewReader(`{"engaged":true}`)) + markReq.Header.Set("X-API-Key", token) + markRec := httptest.NewRecorder() + srv.ServeHTTP(markRec, markReq) + assert.Equal(t, http.StatusForbidden, markRec.Code, "/onboarding/mark must be denied too") + assert.NotContains(t, markRec.Body.String(), "configured_server_count") +} + +// TestSecretsInventory_DeniedToScopedCaller is the P5 regression. Values are +// masked on these routes, so this is a credential INVENTORY rather than a +// disclosure — but it names the secrets of servers the caller cannot see, and +// it is a strictly narrower view of the document /api/v1/config already denies. +// +// No secret resolver is wired, so the admin's 500 is the positive control that +// the request passed the gate and reached the handler body. +func TestSecretsInventory_DeniedToScopedCaller(t *testing.T) { + srv, token := scopeRound10Server(t, nil) + + for _, path := range []string{"/api/v1/secrets/refs", "/api/v1/secrets/config"} { + adminRec := scopeGet(t, srv, path, scopeAdminAPIKey) + require.Equal(t, http.StatusInternalServerError, adminRec.Code, + "positive control: an admin must reach the handler body of %s", path) + + agentRec := scopeGet(t, srv, path, token) + assert.Equal(t, http.StatusForbidden, agentRec.Code, "%s must be denied to a scoped caller", path) + assert.Contains(t, agentRec.Body.String(), secretsInventoryDenialMessage, path) + } +} + +// scopeErrInventoryController fails every inventory read, which is what a +// transient storage error looks like to the subtree gate. +type scopeErrInventoryController struct { + *scopeController + fail bool +} + +func (c *scopeErrInventoryController) GetAllServers() ([]map[string]interface{}, error) { + if c.fail { + return nil, assertInventoryReadFailure + } + return c.scopeController.GetAllServers() +} + +var assertInventoryReadFailure = errInventoryRead{} + +type errInventoryRead struct{} + +func (errInventoryRead) Error() string { return "bbolt: transient read failure" } + +// TestScopedSubtree_TransientInventoryErrorIs503NotNotFound is the P8 +// regression. serverExists folded every controller error into "does not +// exist", so a transient inventory-read failure told an ENTITLED caller that +// its own server had been deleted, on a hot path (/servers/{id}/logs). +func TestScopedSubtree_TransientInventoryErrorIs503NotNotFound(t *testing.T) { + base := &scopeController{cfg: scopeFixtureConfig(false), servers: scopeFixtureServers(), withManagement: true} + ctrl := &scopeErrInventoryController{scopeController: base} + srv, token := scopedAgentServer(t, ctrl, []string{"alpha"}) + + // Positive control: with the inventory readable, the entitled server + // resolves and the unentitled one 404s. + require.NotEqual(t, http.StatusNotFound, scopeGet(t, srv, "/api/v1/servers/alpha/logs", token).Code, + "positive control: alpha must resolve while the inventory is readable") + require.Equal(t, http.StatusNotFound, scopeGet(t, srv, "/api/v1/servers/beta/logs", token).Code, + "positive control: beta must stay hidden") + + ctrl.fail = true + rec := scopeGet(t, srv, "/api/v1/servers/alpha/logs", token) + assert.Equal(t, http.StatusServiceUnavailable, rec.Code, + "'could not determine' must not be reported as 'does not exist'") + + // An unentitled name is still 404 even when the inventory cannot be read: + // entitlement is decided before the inventory is consulted, so the 503 can + // never become an existence oracle. + assert.Equal(t, http.StatusNotFound, scopeGet(t, srv, "/api/v1/servers/beta/logs", token).Code, + "an unentitled name must not learn from the read failure") +} + +// TestUsageCacheKey_IsInjective is the P6 regression. The key joined the +// allowed-server names with a bare comma and the fields with a bare pipe, +// neither escaped, and config validation rejects only a COLON in a server name. +// A collision serves one tenant's cached response to another. +func TestUsageCacheKey_IsInjective(t *testing.T) { + base := usageParams{window: "24h", top: usageDefaultTop, sort: usageDefaultSort} + + oneCommaName := base + oneCommaName.scoped = true + oneCommaName.allowed = []string{"a,b"} + + twoNames := base + twoNames.scoped = true + twoNames.allowed = []string{"a", "b"} + + assert.NotEqual(t, twoNames.cacheKey(), oneCommaName.cacheKey(), + `a token scoped to the single server "a,b" must not share a cache entry with one scoped to ["a","b"]`) + + pipeInServer := base + pipeInServer.server = "x|y" + + splitAcrossFields := base + splitAcrossFields.server = "x" + splitAcrossFields.tool = "y" + + assert.NotEqual(t, pipeInServer.cacheKey(), splitAcrossFields.cacheKey(), + "an unescaped separator inside a filter value must not collide with the next field") + + // Positive control: identical params still share an entry, or the cache + // would simply never hit and the test above would be trivially satisfiable. + assert.Equal(t, twoNames.cacheKey(), twoNames.cacheKey()) + same := base + same.scoped = true + same.allowed = []string{"b", "a"} + assert.Equal(t, twoNames.cacheKey(), same.cacheKey(), + "scope order must not fragment the cache") +} + +// TestUsageResponse_ScopedHeadlineAgreesWithItsOwnRows is the P7 regression. +// The scoped early return skipped the timeline loop, which is also where +// total_calls / total_errors are accumulated, so the headline read 0 beside +// per-tool rows that plainly summed to a non-zero number. +func TestUsageResponse_ScopedHeadlineAgreesWithItsOwnRows(t *testing.T) { + now := time.Now() + snap := &internalRuntime.UsageAggregate{ + Tools: map[string]*internalRuntime.ToolUsage{ + "alpha:t1": {Server: "alpha", Tool: "t1", Calls: 7, Errors: 2, LastUsed: now}, + "beta:t9": {Server: "beta", Tool: "t9", Calls: 99, Errors: 40, LastUsed: now}, + }, + UpdatedAt: now, + } + + p := usageParams{window: "24h", top: usageDefaultTop, sort: usageDefaultSort, scoped: true, allowed: []string{"alpha"}} + resp := buildUsageResponse(snap, nil, p, now) + + require.Len(t, resp.Tools, 1, "positive control: the scoped caller must see exactly its own row") + require.EqualValues(t, 7, resp.Tools[0].Calls) + + var rowCalls, rowErrors int64 + for _, row := range resp.Tools { + rowCalls += row.Calls + rowErrors += row.Errors + } + assert.Equal(t, rowCalls, resp.TotalCalls, + "the headline must agree with the rows the same response carries") + assert.Equal(t, rowErrors, resp.TotalErrors) + assert.EqualValues(t, 7, resp.TotalCalls, "beta's traffic must not be folded into the headline") + assert.Empty(t, resp.Timeline, "the global timeline is still withheld from a scoped caller") +} + +// sseRuntimeFrame is one `event:`/`data:` pair read off the stream. +type sseRuntimeFrame struct { + event string + data string +} + +// sseReadRuntimeEvent reads forward to the next RUNTIME event, skipping the +// status/ping frames the handler emits on its own schedule. +func sseReadRuntimeEvent(t *testing.T, body interface { + ReadString(delim byte) (string, error) +}) sseRuntimeFrame { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + var frame sseRuntimeFrame + for time.Now().Before(deadline) { + line, err := body.ReadString('\n') + require.NoError(t, err) + line = strings.TrimRight(line, "\r\n") + switch { + case strings.HasPrefix(line, "event: "): + frame.event = strings.TrimPrefix(line, "event: ") + case strings.HasPrefix(line, "data: "): + frame.data = strings.TrimPrefix(line, "data: ") + if frame.event != "" && frame.event != "status" && frame.event != "ping" { + return frame + } + frame = sseRuntimeFrame{} + } + } + t.Fatal("timed out waiting for a runtime SSE frame") + return frame +} + +// scopeUnusedRefs keeps the imports honest for helpers this file shares with +// the rest of the group. +var _ = json.Marshal +var _ = contracts.UsageToolStat{} diff --git a/internal/httpapi/scope_round11_test.go b/internal/httpapi/scope_round11_test.go new file mode 100644 index 000000000..2b5915826 --- /dev/null +++ b/internal/httpapi/scope_round11_test.go @@ -0,0 +1,196 @@ +package httpapi + +import ( + "bytes" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.etcd.io/bbolt" + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/telemetry" +) + +// Round-11 cross-review findings on the #1166/#1167 branch. Same discipline as +// round 9: every test drives the PRODUCTION chi route table through +// (*Server).ServeHTTP with a real mcp_agt_ token, and every scoped assertion is +// paired with an admin control on the SAME router proving the fixture landed +// and the route matched. + +// --------------------------------------------------------------------------- +// M1 — GET /api/v1/status served the activation block to any agent token +// --------------------------------------------------------------------------- + +// Distinctive fixture values. They are strings/counts no other part of a +// /status response can produce, so a raw-body assertion cannot pass because the +// value happened to be absent for an unrelated reason. +const ( + activationClientAlpha = "cursor-on-operators-laptop" + activationClientBeta = "claude-desktop-on-operators-laptop" + // A count no other field of a /status response can produce: the sibling + // numbers are unix timestamps and single-digit server counts, so a raw-body + // "4711" assertion cannot pass for an unrelated reason. + activationCalls24h = 4711 + activationSavedBucket = "10k_100k" +) + +// scopeR11ActivationServer wires a scoped agent token onto the shared #1166 +// fixture and attaches a telemetry service whose activation store is loaded +// with the values above. The store and DB are real (telemetry.NewActivationStore +// over a temp BBolt file), not a fake, so the handler takes exactly the +// production branch: provider → service → store → db → Load. +func scopeR11ActivationServer(t *testing.T) (*Server, string) { + t.Helper() + + ctrl := &scopeController{cfg: scopeFixtureConfig(false), servers: scopeFixtureServers(), withManagement: true} + srv, token := scopedAgentServer(t, ctrl, []string{"alpha"}) + + db, err := bbolt.Open(filepath.Join(t.TempDir(), "activation.db"), 0o600, &bbolt.Options{Timeout: 2 * time.Second}) + require.NoError(t, err) + // The counter is only writable one increment at a time, and Load applies a + // 24h decay window to it. NoSync keeps 4711 transactions to well under a + // second; durability is irrelevant to a temp-dir fixture. + db.NoSync = true + t.Cleanup(func() { _ = db.Close() }) + + store := telemetry.NewActivationStore() + // Flags and the client list go through Save; the 24h counters have their + // own encoding (count + window start) that Save deliberately does not + // touch, so they are driven through the same mutators production uses. + require.NoError(t, store.Save(db, telemetry.ActivationState{ + FirstConnectedServerEver: true, + FirstMCPClientEver: true, + FirstRetrieveToolsCallEver: true, + FirstRealToolCallEver: true, + MCPClientsSeenEver: []string{activationClientAlpha, activationClientBeta}, + })) + for i := 0; i < activationCalls24h; i++ { + require.NoError(t, store.IncrementRetrieveToolsCall(db)) + } + require.NoError(t, store.AddTokensSaved(db, 50_000)) + + svc := telemetry.New(ctrl.cfg, "", "v0.0.0-test", "personal", zap.NewNop()) + svc.SetActivationStore(store, db) + srv.SetTelemetryPayloadProvider(func() *telemetry.Service { return svc }) + + return srv, token +} + +// TestGetStatus_ActivationBlockIsOperatorOnly. +// +// `activation` is the operator plane in one object: mcp_clients_seen_ever is +// the operator's entire MCP-client inventory (the class /sessions and +// /onboarding/state answer 403 for) and retrieve_tools_calls_24h / +// configured_ide_count are exact deployment-wide counters — the same count +// oracle this very route removed from upstream_stats.total_servers. +// +// The admin half is a real positive control: it proves the store is wired and +// the values genuinely reach the wire on this route, so the scoped half cannot +// pass because nothing was ever there. +func TestGetStatus_ActivationBlockIsOperatorOnly(t *testing.T) { + srv, token := scopeR11ActivationServer(t) + + admin := scopeGet(t, srv, "/api/v1/status", scopeAdminAPIKey) + require.Equal(t, http.StatusOK, admin.Code, "body: %s", admin.Body.String()) + adminActivation, ok := scopeDecodeData(t, admin)["activation"].(map[string]interface{}) + require.True(t, ok, "precondition: an admin really is served the activation block: %s", admin.Body.String()) + require.Equal(t, float64(activationCalls24h), adminActivation["retrieve_tools_calls_24h"], + "precondition: the fixture's counter reaches the wire") + require.Equal(t, activationSavedBucket, adminActivation["estimated_tokens_saved_24h_bucket"], + "precondition: the tokens-saved bucket reaches the wire") + require.Contains(t, admin.Body.String(), activationClientAlpha, + "precondition: the client inventory reaches the wire") + + agent := scopeGet(t, srv, "/api/v1/status", token) + require.Equal(t, http.StatusOK, agent.Code, "body: %s", agent.Body.String()) + agentData := scopeDecodeData(t, agent) + + _, present := agentData["activation"] + assert.False(t, present, "the activation block must be withheld from a scoped caller: %s", agent.Body.String()) + + // Raw-body assertions, not just the decoded key: a projection that kept the + // values under a different key would still be a leak. + body := agent.Body.String() + assert.NotContains(t, body, activationClientAlpha, "MCP-client inventory leaked to a scoped caller") + assert.NotContains(t, body, activationClientBeta, "MCP-client inventory leaked to a scoped caller") + assert.NotContains(t, body, "4711", "exact deployment-wide retrieve_tools count leaked to a scoped caller") + assert.NotContains(t, body, activationSavedBucket, "deployment-wide tokens-saved bucket leaked to a scoped caller") + // Key names too, so a projection that kept the numbers under a renamed or + // re-nested key would still fail. + for _, key := range []string{ + "mcp_clients_seen_ever", + "retrieve_tools_calls_24h", + "estimated_tokens_saved_24h_bucket", + "first_real_tool_call_ever", + } { + assert.NotContains(t, body, key, "activation field %q reached a scoped caller", key) + } + + // /status is a liveness surface an agent legitimately polls: withholding + // one block must not turn into denying the route. Blanking the whole + // response would be a different bug, so assert the neighbours survive. + assert.Equal(t, true, agentData["running"], "scoped caller must still get liveness from /status") + assert.NotEmpty(t, agentData["timestamp"]) + assert.Contains(t, agentData, "env_kind") +} + +// --------------------------------------------------------------------------- +// M2 — PUT /api/v1/profiles/active had no admin gate +// --------------------------------------------------------------------------- + +// scopeR11Put issues a PUT through the production route table. +func scopeR11Put(t *testing.T, srv *Server, path, apiKey, body string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodPut, path, bytes.NewBufferString(body)) + req.Header.Set("Content-Type", "application/json") + if apiKey != "" { + req.Header.Set("X-API-Key", apiKey) + } + rec := httptest.NewRecorder() + srv.ServeHTTP(rec, req) + return rec +} + +// activeProfileOf reads the server-level active profile through the GET door, +// so the assertion is about observable state rather than a private field. +func activeProfileOf(t *testing.T, srv *Server) string { + t.Helper() + rec := scopeGet(t, srv, "/api/v1/profiles/active", scopeAdminAPIKey) + require.Equal(t, http.StatusOK, rec.Code, "body: %s", rec.Body.String()) + active, _ := scopeDecodeData(t, rec)["active_profile"].(string) + return active +} + +// TestSetActiveProfile_DeniedToScopedCaller. +// +// The active profile is server-level SHARED state: it decides which servers the +// Web UI and the tray render. A read-scoped agent token could rewrite it, +// changing what the operator sees. The admin control proves the profile is +// really settable on this router, so the 403 is the gate and not a 404, a +// decode failure, or an unknown-profile rejection. +func TestSetActiveProfile_DeniedToScopedCaller(t *testing.T) { + cfg := scopeFixtureConfig(false) + cfg.Profiles = []config.ProfileConfig{{Name: "alpha-only", Servers: []string{"alpha"}}} + ctrl := &scopeController{cfg: cfg, servers: scopeFixtureServers(), withManagement: true} + srv, token := scopedAgentServer(t, ctrl, []string{"alpha"}) + + require.Empty(t, activeProfileOf(t, srv), "precondition: nothing is active yet") + + agent := scopeR11Put(t, srv, "/api/v1/profiles/active", token, `{"profile":"alpha-only"}`) + assert.Equal(t, http.StatusForbidden, agent.Code, + "a read-scoped agent token must not mutate server-level shared state: %s", agent.Body.String()) + assert.Empty(t, activeProfileOf(t, srv), + "the write must not have landed") + + // Positive control on the SAME router: the route exists, the body parses, + // and the profile is genuinely settable — so the 403 above is the gate. + admin := scopeR11Put(t, srv, "/api/v1/profiles/active", scopeAdminAPIKey, `{"profile":"alpha-only"}`) + require.Equal(t, http.StatusOK, admin.Code, "body: %s", admin.Body.String()) + require.Equal(t, "alpha-only", activeProfileOf(t, srv)) +} diff --git a/internal/httpapi/scope_round9_harness_test.go b/internal/httpapi/scope_round9_harness_test.go new file mode 100644 index 000000000..bebe84634 --- /dev/null +++ b/internal/httpapi/scope_round9_harness_test.go @@ -0,0 +1,265 @@ +package httpapi + +import ( + "fmt" + "time" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts" + internalRuntime "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// Harness extension for the round-9 cross-review findings: the /servers/{id} +// read subtree (G1), the activity / tool-call / session doors (G2), the token +// stats aggregate (G3) and the status message (G7). +// +// These are methods on the SAME scopeController the #1166/#1167 tests use, so +// every test in the group runs against one two-server fixture (`alpha`, which +// the scoped token may see; `beta`, which it may not) through the production +// chi route table and the real agent-token middleware. + +const ( + // Payloads that must never reach a token scoped to alpha. Each is planted + // in the record type the corresponding door serves. + betaLogSecret = "SUPERSECRET_BETA_STDERR_ARGV" + betaActivityArg = "SUPERSECRET_BETA_ACTIVITY_ARG" + betaToolCallArg = "SUPERSECRET_BETA_TOOLCALL_ARG" + alphaActivityArg = "alpha-activity-argument" + betaActivityID = "01BETA00000000000000000000" + alphaActivityID = "01ALPHA0000000000000000000" + systemActivityID = "01SYSTEM000000000000000000" + betaToolCallID = "beta-tool-call-1" + alphaToolCallID = "alpha-tool-call-1" + scopeStatusMessage = "Connected to 1/2 servers, retrying..." +) + +// scopeActivities is the activity-log fixture: one record per allowed server, +// one per denied server, and one operator-plane record with NO server +// attribution (a config change), which a scoped caller must not see either. +func scopeActivities() []*storage.ActivityRecord { + // Relative to now, not a fixed date: /activity/summary filters on a period + // window, and a fixed timestamp silently ages out of it — which would leave + // the summary test asserting "beta is absent" against an EMPTY summary. + base := time.Now().UTC().Add(-time.Hour) + return []*storage.ActivityRecord{ + { + ID: alphaActivityID, + Type: storage.ActivityTypeToolCall, + ServerName: "alpha", + ToolName: "alpha_tool", + Status: storage.ActivityStatusSuccess, + Timestamp: base, + Arguments: map[string]interface{}{"token": alphaActivityArg}, + Response: "alpha response", + }, + { + ID: betaActivityID, + Type: storage.ActivityTypeToolCall, + ServerName: "beta", + ToolName: "beta_tool", + Status: storage.ActivityStatusSuccess, + Timestamp: base.Add(time.Minute), + Arguments: map[string]interface{}{"token": betaActivityArg}, + Response: "beta response containing " + betaEnvSecret, + }, + { + ID: systemActivityID, + Type: storage.ActivityTypeConfigChange, + Status: storage.ActivityStatusSuccess, + Timestamp: base.Add(2 * time.Minute), + Arguments: map[string]interface{}{"field": "api_key"}, + }, + } +} + +func (c *scopeController) ListActivities(filter storage.ActivityFilter) ([]*storage.ActivityRecord, int, error) { + // Mirrors storage.Manager.ListActivities: ONE Matches() pass produces both + // the page and the total, so a filter that leaks shows up in both. + var matched []*storage.ActivityRecord + for _, rec := range scopeActivities() { + if filter.Matches(rec) { + matched = append(matched, rec) + } + } + total := len(matched) + if filter.Offset < len(matched) { + matched = matched[filter.Offset:] + } else { + matched = nil + } + if filter.Limit > 0 && len(matched) > filter.Limit { + matched = matched[:filter.Limit] + } + return matched, total, nil +} + +func (c *scopeController) StreamActivities(filter storage.ActivityFilter) <-chan *storage.ActivityRecord { + ch := make(chan *storage.ActivityRecord, len(scopeActivities())) + for _, rec := range scopeActivities() { + if filter.Matches(rec) { + ch <- rec + } + } + close(ch) + return ch +} + +func (c *scopeController) GetActivity(id string) (*storage.ActivityRecord, error) { + for _, rec := range scopeActivities() { + if rec.ID == id { + return rec, nil + } + } + return nil, nil +} + +// scopeToolCalls is the tool-call fixture, one record per server. +func scopeToolCalls() []*contracts.ToolCallRecord { + base := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC) + return []*contracts.ToolCallRecord{ + { + ID: alphaToolCallID, + ServerID: "alpha", + ServerName: "alpha", + ToolName: "alpha_tool", + Arguments: map[string]interface{}{"q": "alpha argument"}, + Timestamp: base, + }, + { + ID: betaToolCallID, + ServerID: "beta", + ServerName: "beta", + ToolName: "beta_tool", + Arguments: map[string]interface{}{"q": betaToolCallArg}, + Timestamp: base.Add(time.Minute), + }, + } +} + +func (c *scopeController) GetToolCalls(limit, offset int, scope storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error) { + // Mirrors runtime.GetToolCalls: scope applied BEFORE pagination, so total + // and page describe the same set. + var visible []*contracts.ToolCallRecord + for _, rec := range scopeToolCalls() { + if scope.Allows(rec.ServerName) { + visible = append(visible, rec) + } + } + total := len(visible) + if offset < len(visible) { + visible = visible[offset:] + } else { + visible = nil + } + if limit > 0 && len(visible) > limit { + visible = visible[:limit] + } + return visible, total, nil +} + +func (c *scopeController) GetToolCallsBySession(_ string, limit, offset int, scope storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error) { + return c.GetToolCalls(limit, offset, scope) +} + +func (c *scopeController) GetToolCallByID(id string) (*contracts.ToolCallRecord, error) { + for _, rec := range scopeToolCalls() { + if rec.ID == id { + return rec, nil + } + } + return nil, fmt.Errorf("tool call not found: %s", id) +} + +func (c *scopeController) GetServerToolCalls(serverName string, _ int) ([]*contracts.ToolCallRecord, error) { + out := make([]*contracts.ToolCallRecord, 0, 1) + for _, rec := range scopeToolCalls() { + if rec.ServerName == serverName { + out = append(out, rec) + } + } + return out, nil +} + +// GetServerLogs plants the sharpest payload in the finding: upstream stderr +// echoing the argv/env the process was launched with. +func (c *scopeController) GetServerLogs(serverName string, _ int) ([]contracts.LogEntry, error) { + secret := "alpha-log-line" + if serverName == "beta" { + secret = betaLogSecret + } + return []contracts.LogEntry{{ + Timestamp: time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC), + Level: "INFO", + Message: "spawned: npx beta-server --token=" + secret, + Server: serverName, + }}, nil +} + +// GetToolApproval makes /servers/{id}/tools/{tool}/diff a real 200 for an +// admin. MockServerController returns (nil, nil) there, which the handler +// nil-derefs into a recovered 500 — a control that never proves the route +// serves anything. +func (c *scopeController) GetToolApproval(serverName, toolName string) (*storage.ToolApprovalRecord, error) { + return &storage.ToolApprovalRecord{ + ServerName: serverName, + ToolName: toolName, + Status: storage.ToolApprovalStatusChanged, + ApprovedHash: "hash-old", + CurrentHash: "hash-new", + }, nil +} + +// GetTokenSavings carries the per-server map that IS the inventory (G3). +func (c *scopeController) GetTokenSavings() (*contracts.ServerTokenMetrics, error) { + return &contracts.ServerTokenMetrics{ + TotalServerToolListSize: 1000, + AverageQueryResultSize: 100, + SavedTokens: 900, + SavedTokensPercentage: 90, + PerServerToolListSizes: map[string]int{"alpha": 300, "beta": 700}, + }, nil +} + +func (c *scopeController) UsageSnapshot() *internalRuntime.UsageAggregate { + now := time.Now().UTC() + return &internalRuntime.UsageAggregate{ + UpdatedAt: now, + Tools: map[string]*internalRuntime.ToolUsage{ + "alpha:alpha_tool": {Server: "alpha", Tool: "alpha_tool", Calls: 3, RespBytesSum: 30, SizedRespCalls: 3, LastUsed: now}, + "beta:beta_tool": {Server: "beta", Tool: "beta_tool", Calls: 7, RespBytesSum: 70, SizedRespCalls: 7, LastUsed: now}, + }, + Buckets: map[int64]*internalRuntime.TimeBucket{ + now.Truncate(time.Hour).Unix(): {Start: now.Truncate(time.Hour), Calls: 10, Errors: 1, RespBytesSum: 100}, + }, + } +} + +func (c *scopeController) GetRecentSessions(_ int, _ string) ([]*contracts.MCPSession, int, error) { + return []*contracts.MCPSession{{ + ID: "session-1", + ClientName: "claude-code", + Status: "active", + WorkspaceName: "secret-project", + }}, 1, nil +} + +func (c *scopeController) GetSessionByID(id string) (*contracts.MCPSession, error) { + return &contracts.MCPSession{ID: id, ClientName: "claude-code", WorkspaceName: "secret-project"}, nil +} + +// scopeStatusController is scopeController with a status snapshot that carries +// the runtime's real `message` shape — "Connected to %d/%d servers, retrying…", +// a verbatim count of the WHOLE inventory (G7). The base harness returns only +// `phase`, so this is a separate type rather than a change to it: the existing +// #1166 status test asserts against that shape. +type scopeStatusController struct{ *scopeController } + +func (c scopeStatusController) GetStatus() interface{} { + return map[string]interface{}{ + "phase": "Ready", + "message": scopeStatusMessage, + "tools_indexed": 10, + } +} + +var _ ServerController = (*scopeController)(nil) diff --git a/internal/httpapi/scope_round9_test.go b/internal/httpapi/scope_round9_test.go new file mode 100644 index 000000000..f4e0e96d3 --- /dev/null +++ b/internal/httpapi/scope_round9_test.go @@ -0,0 +1,703 @@ +package httpapi + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "regexp" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// Round-9 cross-review findings on the #1166/#1167 branch. Every test here +// drives the PRODUCTION chi route table through (*Server).ServeHTTP with a real +// mcp_agt_ token, and every scoped assertion is paired with the admin control +// proving the fixture landed and the route matched. + +func scopeR9Server(t *testing.T) (*Server, string, *scopeController) { + t.Helper() + ctrl := &scopeController{cfg: scopeFixtureConfig(false), servers: scopeFixtureServers(), withManagement: true} + srv, token := scopedAgentServer(t, ctrl, []string{"alpha"}) + return srv, token, ctrl +} + +var scopeR9RequestID = regexp.MustCompile(`"request_id":"[^"]*"`) + +func scopeR9Normalize(rec *httptest.ResponseRecorder, name string) string { + body := strings.ReplaceAll(rec.Body.String(), name, "") + return scopeR9RequestID.ReplaceAllString(body, `"request_id":""`) +} + +// --------------------------------------------------------------------------- +// G1 — the /servers/{id} read subtree +// --------------------------------------------------------------------------- + +// scopeR9ServerSubtreeReads enumerates the sub-resources that had NO scope gate. +// Adding a new read sub-resource under /servers/{id} without covering it here +// should make this table incomplete — keep it in sync. +var scopeR9ServerSubtreeReads = []struct { + name string + path string // %s is the server name +}{ + {"tools", "/api/v1/servers/%s/tools"}, + {"logs", "/api/v1/servers/%s/logs"}, + {"tool-calls", "/api/v1/servers/%s/tool-calls"}, + {"scan-status", "/api/v1/servers/%s/scan/status"}, + {"scan-report", "/api/v1/servers/%s/scan/report"}, + {"scan-files", "/api/v1/servers/%s/scan/files"}, + {"integrity", "/api/v1/servers/%s/integrity"}, + {"tools-export", "/api/v1/servers/%s/tools/export"}, + {"tool-diff", "/api/v1/servers/%s/tools/does_not_matter/diff"}, + {"diagnostics", "/api/v1/servers/%s/diagnostics"}, +} + +// TestServerSubtree_UnentitledIsIndistinguishableFromAbsent is the STATUS-PARITY +// oracle for the whole subtree. +// +// "The body must not contain the server name" would pass vacuously on several of +// these routes — they echo the caller's own path parameter back into the +// response. So the assertion is: the unentitled response is byte-identical to +// the absent one once the echoed name and the per-request id are normalised, +// AND the absent response is genuinely distinguishable from a successful read. +// +// Two positive controls stop the whole thing passing for the wrong reason: the +// scoped token reaching the same route for its OWN server, and an admin reading +// beta on the same router. +func TestServerSubtree_UnentitledIsIndistinguishableFromAbsent(t *testing.T) { + for _, rt := range scopeR9ServerSubtreeReads { + t.Run(rt.name, func(t *testing.T) { + srv, token, _ := scopeR9Server(t) + pathFor := func(name string) string { return strings.Replace(rt.path, "%s", name, 1) } + + // Control 1: the token genuinely reaches this route for alpha. + allowed := scopeGet(t, srv, pathFor("alpha"), token) + require.NotEqual(t, http.StatusNotFound, allowed.Code, + "precondition: the scoped token must reach %s for its OWN server; body: %s", rt.path, allowed.Body.String()) + + // Control 2: beta exists and an admin can read it here. + adminBeta := scopeGet(t, srv, pathFor("beta"), scopeAdminAPIKey) + require.NotEqual(t, http.StatusNotFound, adminBeta.Code, + "precondition: beta must exist and be visible to an admin; body: %s", adminBeta.Body.String()) + + unentitled := scopeGet(t, srv, pathFor("beta"), token) + absent := scopeGet(t, srv, pathFor("does-not-exist-at-all"), token) + + assert.Equal(t, http.StatusNotFound, absent.Code, + "precondition: an absent server must 404, or the parity below is vacuous") + assert.Equal(t, absent.Code, unentitled.Code, + "an unentitled server must return the same status as one that does not exist") + assert.Equal(t, scopeR9Normalize(absent, "does-not-exist-at-all"), scopeR9Normalize(unentitled, "beta"), + "the two responses must be byte-identical once the echoed name is normalised") + }) + } +} + +// TestServerSubtree_AbsentServerInScopeStill404s pins the EXISTENCE half of the +// gate, which the parity test above cannot reach. +// +// Scope alone already makes an out-of-scope name and an unknown name identical, +// because both fall outside AllowedServers and take the same 404. The case it +// does NOT cover is a name the token IS entitled to that does not exist — the +// handlers behind this subtree answer 200 for that, so the response shape +// (entitled+absent = 200, not entitled = 404) becomes a second, independent +// readout of the boundary that no longer agrees with the first. This asserts +// one answer for both. +func TestServerSubtree_AbsentServerInScopeStill404s(t *testing.T) { + ctrl := &scopeController{cfg: scopeFixtureConfig(false), servers: scopeFixtureServers(), withManagement: true} + // The token names a server the inventory does not contain. + srv, token := scopedAgentServer(t, ctrl, []string{"alpha", "ghost-server"}) + + allowed := scopeGet(t, srv, "/api/v1/servers/alpha/tools", token) + require.Equal(t, http.StatusOK, allowed.Code, + "precondition: an entitled, EXISTING server must still read; body: %s", allowed.Body.String()) + + ghost := scopeGet(t, srv, "/api/v1/servers/ghost-server/tools", token) + unentitled := scopeGet(t, srv, "/api/v1/servers/beta/tools", token) + + assert.Equal(t, http.StatusNotFound, ghost.Code, + "an entitled name that does not exist must 404, not fall through to the handler's 200-on-absent; body: %s", ghost.Body.String()) + assert.Equal(t, unentitled.Code, ghost.Code, + "absent and unentitled must be one answer") + assert.Equal(t, scopeR9Normalize(unentitled, "beta"), scopeR9Normalize(ghost, "ghost-server")) +} + +// TestServerLogs_ScopedTokenNeverSeesAnotherServersStderr is the sharpest +// single case: upstream stderr routinely echoes the argv and env the process was +// launched with, and nothing redacts a log tail — so this walks around the +// #1158 log-redaction work entirely. +// +// The oracle is NOT "the body omits the secret" alone: that would pass on a 500 +// or an empty body. The admin control asserts the same route DOES serve the +// secret, so the scoped 404 is proved to be a denial and not a broken fixture. +func TestServerLogs_ScopedTokenNeverSeesAnotherServersStderr(t *testing.T) { + srv, token, _ := scopeR9Server(t) + + adminBeta := scopeGet(t, srv, "/api/v1/servers/beta/logs", scopeAdminAPIKey) + require.Equal(t, http.StatusOK, adminBeta.Code, "body: %s", adminBeta.Body.String()) + require.Contains(t, adminBeta.Body.String(), betaLogSecret, + "precondition: this route really does serve the launch secret to an admin") + + allowed := scopeGet(t, srv, "/api/v1/servers/alpha/logs", token) + require.Equal(t, http.StatusOK, allowed.Code, + "precondition: the scoped token must still read its OWN server's logs; body: %s", allowed.Body.String()) + + denied := scopeGet(t, srv, "/api/v1/servers/beta/logs", token) + assert.Equal(t, http.StatusNotFound, denied.Code, "body: %s", denied.Body.String()) + assert.NotContains(t, denied.Body.String(), betaLogSecret) +} + +// TestServerSubtree_AdminUnaffected is a REGRESSION GUARD, not a bite test: a +// gate that 404s the Web UI is a worse bug than the one being closed. It covers +// the admin key, the tray socket, and the no-AuthContext bootstrap passthrough +// — including the 200-on-absent quirk the gate must NOT extend to admins. +func TestServerSubtree_AdminUnaffected(t *testing.T) { + newCtrl := func() *scopeController { + return &scopeController{cfg: scopeFixtureConfig(false), servers: scopeFixtureServers(), withManagement: true} + } + + t.Run("admin reads every server's tools", func(t *testing.T) { + srv, _ := scopedAgentServer(t, newCtrl(), []string{"alpha"}) + for _, name := range []string{"alpha", "beta"} { + rec := scopeGet(t, srv, "/api/v1/servers/"+name+"/tools", scopeAdminAPIKey) + assert.Equal(t, http.StatusOK, rec.Code, "%s: %s", name, rec.Body.String()) + } + }) + + t.Run("no auth context passthrough is unrestricted", func(t *testing.T) { + srv := NewServer(passthroughController{newCtrl()}, zap.NewNop().Sugar(), nil) + rec := scopeGet(t, srv, "/api/v1/servers/beta/logs", "") + assert.Equal(t, http.StatusOK, rec.Code, "body: %s", rec.Body.String()) + assert.Contains(t, rec.Body.String(), betaLogSecret, + "absence of a token must stay as permissive as it is today") + }) + + t.Run("admin still gets the pre-existing 200 for an absent server", func(t *testing.T) { + srv, _ := scopedAgentServer(t, newCtrl(), []string{"alpha"}) + rec := scopeGet(t, srv, "/api/v1/servers/does-not-exist-at-all/tools", scopeAdminAPIKey) + assert.Equal(t, http.StatusOK, rec.Code, + "the gate must not change admin behaviour on this subtree; body: %s", rec.Body.String()) + }) +} + +// --------------------------------------------------------------------------- +// G2 — the activity / tool-call / session doors +// --------------------------------------------------------------------------- + +func scopeR9ActivityIDs(t *testing.T, rec *httptest.ResponseRecorder) []string { + t.Helper() + data := scopeDecodeData(t, rec) + raw, ok := data["activities"].([]interface{}) + require.True(t, ok, "no activities array in %#v", data) + ids := make([]string, 0, len(raw)) + for _, entry := range raw { + m, _ := entry.(map[string]interface{}) + id, _ := m["id"].(string) + ids = append(ids, id) + } + return ids +} + +// TestListActivity_ScopedToAllowedServers. The activity log is strictly wider +// than the enumeration the branch already closed: it carries the ARGUMENTS and +// RESPONSES of every call on every server. +// +// `total` is asserted alongside the array because a post-filter would shrink +// the page while the total kept counting the hidden records — which is a count +// oracle for exactly what was hidden, and a broken pager besides. +func TestListActivity_ScopedToAllowedServers(t *testing.T) { + srv, token, _ := scopeR9Server(t) + + admin := scopeGet(t, srv, "/api/v1/activity", scopeAdminAPIKey) + require.Equal(t, http.StatusOK, admin.Code, "body: %s", admin.Body.String()) + require.ElementsMatch(t, []string{alphaActivityID, betaActivityID, systemActivityID}, scopeR9ActivityIDs(t, admin), + "precondition: an admin must see the whole fixture") + require.Contains(t, admin.Body.String(), betaActivityArg, + "precondition: this door really does serve another server's arguments") + + agent := scopeGet(t, srv, "/api/v1/activity", token) + require.Equal(t, http.StatusOK, agent.Code, "body: %s", agent.Body.String()) + assert.Equal(t, []string{alphaActivityID}, scopeR9ActivityIDs(t, agent), + "a token scoped to alpha must see only alpha's records") + assert.NotContains(t, agent.Body.String(), betaActivityArg) + + agentData := scopeDecodeData(t, agent) + assert.Equal(t, float64(1), agentData["total"], + "total must narrow with the page or it is an exact count oracle for what was hidden") + adminData := scopeDecodeData(t, admin) + assert.Equal(t, float64(3), adminData["total"]) +} + +// TestListActivity_ServerParamCannotWidenScope: ?server= is a user filter that +// narrows WITHIN the entitlement. Naming a server outside it must return +// nothing, not that server's records. +func TestListActivity_ServerParamCannotWidenScope(t *testing.T) { + srv, token, _ := scopeR9Server(t) + + rec := scopeGet(t, srv, "/api/v1/activity?server=beta", token) + require.Equal(t, http.StatusOK, rec.Code, "body: %s", rec.Body.String()) + assert.Empty(t, scopeR9ActivityIDs(t, rec)) + assert.Equal(t, float64(0), scopeDecodeData(t, rec)["total"]) + + admin := scopeGet(t, srv, "/api/v1/activity?server=beta", scopeAdminAPIKey) + require.Equal(t, http.StatusOK, admin.Code) + assert.Equal(t, []string{betaActivityID}, scopeR9ActivityIDs(t, admin), + "precondition: the same query really does return beta's record for an admin") +} + +// TestActivityDetail_UnentitledIsIndistinguishableFromAbsent. This route's 404 +// body echoes nothing of the request, so status parity plus the admin positive +// control is the whole oracle. +func TestActivityDetail_UnentitledIsIndistinguishableFromAbsent(t *testing.T) { + srv, token, _ := scopeR9Server(t) + + adminBeta := scopeGet(t, srv, "/api/v1/activity/"+betaActivityID, scopeAdminAPIKey) + require.Equal(t, http.StatusOK, adminBeta.Code, + "precondition: the record exists and an admin can read it; body: %s", adminBeta.Body.String()) + + allowed := scopeGet(t, srv, "/api/v1/activity/"+alphaActivityID, token) + require.Equal(t, http.StatusOK, allowed.Code, + "precondition: the scoped token reaches this route for its OWN record; body: %s", allowed.Body.String()) + + unentitled := scopeGet(t, srv, "/api/v1/activity/"+betaActivityID, token) + absent := scopeGet(t, srv, "/api/v1/activity/01NOSUCHRECORD000000000000", token) + + assert.Equal(t, http.StatusNotFound, absent.Code) + assert.Equal(t, absent.Code, unentitled.Code) + assert.Equal(t, scopeR9Normalize(absent, "01NOSUCHRECORD000000000000"), scopeR9Normalize(unentitled, betaActivityID)) + assert.NotContains(t, unentitled.Body.String(), betaActivityArg) +} + +// TestActivitySummary_ScopedToAllowedServers covers the counting door, which +// streams the whole window rather than a page. +func TestActivitySummary_ScopedToAllowedServers(t *testing.T) { + srv, token, _ := scopeR9Server(t) + + topServers := func(rec *httptest.ResponseRecorder) []string { + data := scopeDecodeData(t, rec) + raw, _ := data["top_servers"].([]interface{}) + names := make([]string, 0, len(raw)) + for _, entry := range raw { + m, _ := entry.(map[string]interface{}) + name, _ := m["name"].(string) + names = append(names, name) + } + return names + } + + admin := scopeGet(t, srv, "/api/v1/activity/summary?period=30d", scopeAdminAPIKey) + require.Equal(t, http.StatusOK, admin.Code, "body: %s", admin.Body.String()) + require.ElementsMatch(t, []string{"alpha", "beta"}, topServers(admin), + "precondition: the summary really does name every server for an admin") + require.Equal(t, float64(3), scopeDecodeData(t, admin)["total_count"]) + + agent := scopeGet(t, srv, "/api/v1/activity/summary?period=30d", token) + require.Equal(t, http.StatusOK, agent.Code, "body: %s", agent.Body.String()) + assert.Equal(t, []string{"alpha"}, topServers(agent), + "a scoped caller must not learn beta exists from the summary, and must still see its own") + assert.Equal(t, float64(1), scopeDecodeData(t, agent)["total_count"], + "the counters must be computed over the entitled records only") +} + +// TestActivityExport_ScopedToAllowedServers. Export is the widest projection of +// all — it can include full request/response bodies. +func TestActivityExport_ScopedToAllowedServers(t *testing.T) { + srv, token, _ := scopeR9Server(t) + + admin := scopeGet(t, srv, "/api/v1/activity/export?include_bodies=true", scopeAdminAPIKey) + require.Equal(t, http.StatusOK, admin.Code) + require.Contains(t, admin.Body.String(), betaActivityArg, + "precondition: export really does carry another server's arguments for an admin") + + agent := scopeGet(t, srv, "/api/v1/activity/export?include_bodies=true", token) + require.Equal(t, http.StatusOK, agent.Code) + assert.NotContains(t, agent.Body.String(), betaActivityArg) + assert.Contains(t, agent.Body.String(), alphaActivityArg, + "positive control: its own records must still export") +} + +// TestActivityUsage_ScopedToAllowedServers covers the per-tool rollup, and the +// fleet-wide aggregates that are dropped rather than reported wrongly. +func TestActivityUsage_ScopedToAllowedServers(t *testing.T) { + srv, token, _ := scopeR9Server(t) + + toolServers := func(rec *httptest.ResponseRecorder) []string { + data := scopeDecodeData(t, rec) + raw, ok := data["tools"].([]interface{}) + require.True(t, ok, "no tools array in %#v", data) + names := make([]string, 0, len(raw)) + for _, entry := range raw { + m, _ := entry.(map[string]interface{}) + name, _ := m["server"].(string) + names = append(names, name) + } + return names + } + + admin := scopeGet(t, srv, "/api/v1/activity/usage?window=all", scopeAdminAPIKey) + require.Equal(t, http.StatusOK, admin.Code, "body: %s", admin.Body.String()) + require.ElementsMatch(t, []string{"alpha", "beta"}, toolServers(admin), + "precondition: the usage rollup really does name every server for an admin") + assert.Equal(t, float64(900), scopeDecodeData(t, admin)["tokens_saved"], + "precondition: the fleet-wide headline is served to an admin") + + agent := scopeGet(t, srv, "/api/v1/activity/usage?window=all", token) + require.Equal(t, http.StatusOK, agent.Code, "body: %s", agent.Body.String()) + assert.Equal(t, []string{"alpha"}, toolServers(agent)) + + agentData := scopeDecodeData(t, agent) + assert.Equal(t, float64(0), agentData["tokens_saved"], + "a fleet-wide aggregate that cannot be re-derived per server is dropped, not reported") + assert.Empty(t, agentData["timeline"], + "the global timeline aggregates every server's traffic and has no per-server breakdown") +} + +// TestActivityUsage_CacheKeyIncludesCallerScope is the cache-poisoning oracle. +// handleActivityUsage caches by params alone; without the scope term the FIRST +// caller of a given query seeds the entry every other caller then reads for the +// whole TTL. The agent asks first here, so an unscoped key would serve the +// admin the agent's narrowed view. +func TestActivityUsage_CacheKeyIncludesCallerScope(t *testing.T) { + srv, token, _ := scopeR9Server(t) + + agent := scopeGet(t, srv, "/api/v1/activity/usage?window=all", token) + require.Equal(t, http.StatusOK, agent.Code, "body: %s", agent.Body.String()) + + admin := scopeGet(t, srv, "/api/v1/activity/usage?window=all", scopeAdminAPIKey) + require.Equal(t, http.StatusOK, admin.Code, "body: %s", admin.Body.String()) + + data := scopeDecodeData(t, admin) + raw, ok := data["tools"].([]interface{}) + require.True(t, ok, "no tools array in %#v", data) + assert.Len(t, raw, 2, + "the admin must not be served the agent's cached, narrowed view") + assert.Equal(t, float64(900), data["tokens_saved"], + "nor the agent's dropped fleet aggregate") +} + +func scopeR9ToolCallIDs(t *testing.T, rec *httptest.ResponseRecorder) []string { + t.Helper() + data := scopeDecodeData(t, rec) + raw, ok := data["tool_calls"].([]interface{}) + require.True(t, ok, "no tool_calls array in %#v", data) + ids := make([]string, 0, len(raw)) + for _, entry := range raw { + m, _ := entry.(map[string]interface{}) + id, _ := m["id"].(string) + ids = append(ids, id) + } + return ids +} + +// TestToolCalls_ScopedToAllowedServers pins the list door AND the coherence of +// its `total` with the page. +func TestToolCalls_ScopedToAllowedServers(t *testing.T) { + srv, token, _ := scopeR9Server(t) + + admin := scopeGet(t, srv, "/api/v1/tool-calls", scopeAdminAPIKey) + require.Equal(t, http.StatusOK, admin.Code, "body: %s", admin.Body.String()) + require.ElementsMatch(t, []string{alphaToolCallID, betaToolCallID}, scopeR9ToolCallIDs(t, admin), + "precondition: an admin sees the whole fixture") + require.Contains(t, admin.Body.String(), betaToolCallArg, + "precondition: this door really does serve another server's arguments") + + agent := scopeGet(t, srv, "/api/v1/tool-calls", token) + require.Equal(t, http.StatusOK, agent.Code, "body: %s", agent.Body.String()) + assert.Equal(t, []string{alphaToolCallID}, scopeR9ToolCallIDs(t, agent)) + assert.NotContains(t, agent.Body.String(), betaToolCallArg) + assert.Equal(t, float64(1), scopeDecodeData(t, agent)["total"], + "total must narrow with the page") + assert.Equal(t, float64(2), scopeDecodeData(t, admin)["total"]) +} + +// TestToolCallDetail_UnentitledIsIndistinguishableFromAbsent, plus the replay +// twin: replay dispatches a REAL call against the recorded server, so it must +// answer the same question with the same status. +func TestToolCallDetail_UnentitledIsIndistinguishableFromAbsent(t *testing.T) { + srv, token, _ := scopeR9Server(t) + + adminBeta := scopeGet(t, srv, "/api/v1/tool-calls/"+betaToolCallID, scopeAdminAPIKey) + require.Equal(t, http.StatusOK, adminBeta.Code, + "precondition: the record exists and an admin can read it; body: %s", adminBeta.Body.String()) + + allowed := scopeGet(t, srv, "/api/v1/tool-calls/"+alphaToolCallID, token) + require.Equal(t, http.StatusOK, allowed.Code, + "precondition: the scoped token reaches this route for its OWN record; body: %s", allowed.Body.String()) + + unentitled := scopeGet(t, srv, "/api/v1/tool-calls/"+betaToolCallID, token) + absent := scopeGet(t, srv, "/api/v1/tool-calls/no-such-call", token) + assert.Equal(t, http.StatusNotFound, absent.Code) + assert.Equal(t, absent.Code, unentitled.Code) + assert.Equal(t, scopeR9Normalize(absent, "no-such-call"), scopeR9Normalize(unentitled, betaToolCallID)) + assert.NotContains(t, unentitled.Body.String(), betaToolCallArg) +} + +func TestReplayToolCall_UnentitledIsIndistinguishableFromAbsent(t *testing.T) { + srv, token, _ := scopeR9Server(t) + + post := func(id, key string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPost, "/api/v1/tool-calls/"+id+"/replay", + strings.NewReader(`{"arguments":{}}`)) + req.Header.Set("X-API-Key", key) + rec := httptest.NewRecorder() + srv.ServeHTTP(rec, req) + return rec + } + + allowed := post(alphaToolCallID, token) + require.NotEqual(t, http.StatusNotFound, allowed.Code, + "precondition: the scoped token reaches replay for its OWN record; body: %s", allowed.Body.String()) + + unentitled := post(betaToolCallID, token) + absent := post("no-such-call", token) + assert.Equal(t, http.StatusNotFound, unentitled.Code, + "replay must not dispatch against a server the caller may not see; body: %s", unentitled.Body.String()) + assert.Equal(t, absent.Code, unentitled.Code) +} + +// TestSessions_DeniedToAgentTokens. A contracts.MCPSession has no server +// attribution to project — it names the CLIENT and the user's workspace — so +// the door is denied outright, like /api/v1/config. +func TestSessions_DeniedToAgentTokens(t *testing.T) { + srv, token, _ := scopeR9Server(t) + + for _, path := range []string{"/api/v1/sessions", "/api/v1/sessions/session-1"} { + t.Run(path, func(t *testing.T) { + admin := scopeGet(t, srv, path, scopeAdminAPIKey) + require.Equal(t, http.StatusOK, admin.Code, "body: %s", admin.Body.String()) + require.Contains(t, admin.Body.String(), "secret-project", + "precondition: this door really does serve the workspace name to an admin") + + agent := scopeGet(t, srv, path, token) + assert.Equal(t, http.StatusForbidden, agent.Code, "body: %s", agent.Body.String()) + assert.NotContains(t, agent.Body.String(), "secret-project") + }) + } +} + +// --------------------------------------------------------------------------- +// G3 — GET /api/v1/stats/tokens +// --------------------------------------------------------------------------- + +// TestTokenStats_DeniedToAgentTokens. PerServerToolListSizes is keyed by every +// configured server name: a complete inventory enumeration on a route the +// branch left untouched. Denied rather than projected, because the scalars +// beside the map are fleet-wide and cannot be re-derived per server — see the +// comment on handleGetTokenStats. +func TestTokenStats_DeniedToAgentTokens(t *testing.T) { + srv, token, _ := scopeR9Server(t) + + admin := scopeGet(t, srv, "/api/v1/stats/tokens", scopeAdminAPIKey) + require.Equal(t, http.StatusOK, admin.Code, "body: %s", admin.Body.String()) + require.Contains(t, admin.Body.String(), `"beta"`, + "precondition: the per-server map really does enumerate every server for an admin") + + agent := scopeGet(t, srv, "/api/v1/stats/tokens", token) + assert.Equal(t, http.StatusForbidden, agent.Code, "body: %s", agent.Body.String()) + assert.NotContains(t, agent.Body.String(), `"beta"`, + "the inventory must not reach a scoped token") +} + +// --------------------------------------------------------------------------- +// G4 — quarantined_servers must be recomputable for a scoped caller +// --------------------------------------------------------------------------- + +// TestFilterUpstreamStatsServers_RecomputesQuarantined pins the filter against +// the exact entry shape BOTH producers now emit. Before this, neither wrote a +// per-entry `quarantined` key, so the recomputed scalar was always 0 and a +// scoped caller's security surface read clean while its own server sat +// quarantined. +func TestFilterUpstreamStatsServers_RecomputesQuarantined(t *testing.T) { + ctx := auth.WithAuthContext(t.Context(), + &auth.AuthContext{Type: auth.AuthTypeAgent, AllowedServers: []string{"alpha"}}) + + stats := map[string]interface{}{ + "servers": map[string]interface{}{ + "alpha": map[string]interface{}{"connected": true, "quarantined": true, "tool_count": 0}, + "beta": map[string]interface{}{"connected": true, "quarantined": true, "tool_count": 7}, + }, + "total_servers": 2, + "connected_servers": 2, + "quarantined_servers": 2, + "total_tools": 7, + } + + out := filterUpstreamStatsServers(ctx, stats) + assert.Equal(t, 1, out["total_servers"]) + assert.Equal(t, 1, out["quarantined_servers"], + "the scoped caller's OWN quarantined server must still be counted") +} + +// TestConvertUpstreamStatsToServerStats_CountsQuarantined pins the same key on +// the typed converter, which had the identical latent hole. +func TestConvertUpstreamStatsToServerStats_CountsQuarantined(t *testing.T) { + stats := contracts.ConvertUpstreamStatsToServerStats(map[string]interface{}{ + "servers": map[string]interface{}{ + "alpha": map[string]interface{}{"connected": true, "quarantined": true, "tool_count": 0}, + "beta": map[string]interface{}{"connected": true, "quarantined": false, "tool_count": 7}, + }, + }) + assert.Equal(t, 1, stats.QuarantinedServers) +} + +// --------------------------------------------------------------------------- +// G6 — one mux must not carry two definitions of "not admin" +// --------------------------------------------------------------------------- + +// TestRequireAdminRead_DeniesNonAdminUserContext. apiKeyAuthMiddleware installs +// only admin and agent contexts today, so this drives the handler directly with +// the server-edition AuthTypeUser identity that would otherwise have passed an +// AuthTypeAgent-only test and read the whole config document. +// +// The oracle is status parity with the agent identity on the same handler, plus +// the admin positive control proving the handler serves the document at all. +func TestRequireAdminRead_DeniesNonAdminUserContext(t *testing.T) { + ctrl := &scopeController{cfg: scopeFixtureConfig(true), servers: scopeFixtureServers(), withManagement: true} + srv := NewServer(ctrl, zap.NewNop().Sugar(), nil) + + call := func(ac *auth.AuthContext) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, "/api/v1/config", http.NoBody) + if ac != nil { + req = req.WithContext(auth.WithAuthContext(req.Context(), ac)) + } + rec := httptest.NewRecorder() + srv.handleGetConfig(rec, req) + return rec + } + + adminRec := call(auth.AdminContext()) + require.Equal(t, http.StatusOK, adminRec.Code, + "precondition: this handler serves the document to an admin; body: %s", adminRec.Body.String()) + require.Contains(t, adminRec.Body.String(), alphaHeaderSecret, + "precondition: the document really does carry credentials") + + agentRec := call(&auth.AuthContext{Type: auth.AuthTypeAgent, AllowedServers: []string{"alpha"}}) + require.Equal(t, http.StatusForbidden, agentRec.Code, "body: %s", agentRec.Body.String()) + + userRec := call(auth.UserContext("u1", "u@example.com", "U", "google")) + assert.Equal(t, agentRec.Code, userRec.Code, + "an OAuth user is not an admin and must be denied exactly as an agent token is") + assert.NotContains(t, userRec.Body.String(), alphaHeaderSecret) + assert.NotContains(t, userRec.Body.String(), scopeAdminAPIKey) + + adminUserRec := call(auth.AdminUserContext("u2", "a@example.com", "A", "google")) + assert.Equal(t, http.StatusOK, adminUserRec.Code, + "an OAuth ADMIN user must keep admin access; body: %s", adminUserRec.Body.String()) +} + +// --------------------------------------------------------------------------- +// G7 — status.message leaks the true server count +// --------------------------------------------------------------------------- + +// TestGetStatus_MessageDoesNotLeakServerCount. total_servers on this very route +// was recomputed precisely so it would stop being a count oracle; the sibling +// `message` carried "Connected to 1/2 servers" verbatim. +func TestGetStatus_MessageDoesNotLeakServerCount(t *testing.T) { + base := &scopeController{cfg: scopeFixtureConfig(false), servers: scopeFixtureServers(), withManagement: true} + srv, token := scopedAgentServer(t, scopeStatusController{base}, []string{"alpha"}) + + statusMessage := func(rec *httptest.ResponseRecorder) string { + data := scopeDecodeData(t, rec) + status, ok := data["status"].(map[string]interface{}) + require.True(t, ok, "no status object in %#v", data) + msg, _ := status["message"].(string) + return msg + } + + admin := scopeGet(t, srv, "/api/v1/status", scopeAdminAPIKey) + require.Equal(t, http.StatusOK, admin.Code, "body: %s", admin.Body.String()) + require.Equal(t, scopeStatusMessage, statusMessage(admin), + "precondition: the message really is served, with its counts, to an admin") + + agent := scopeGet(t, srv, "/api/v1/status", token) + require.Equal(t, http.StatusOK, agent.Code, "body: %s", agent.Body.String()) + assert.Empty(t, statusMessage(agent), + "a scoped caller must not be handed the true server count in prose") + assert.NotContains(t, agent.Body.String(), "1/2 servers") + + // The neighbouring, count-free field must survive — blanking the whole + // snapshot would be a different bug. + agentStatus, _ := scopeDecodeData(t, agent)["status"].(map[string]interface{}) + assert.Equal(t, "Ready", agentStatus["phase"]) +} + +// --------------------------------------------------------------------------- +// The predicates themselves +// --------------------------------------------------------------------------- + +func TestActivityFilterAllowedServers(t *testing.T) { + rec := &storage.ActivityRecord{ServerName: "beta"} + unattributed := &storage.ActivityRecord{} + + assert.True(t, (&storage.ActivityFilter{}).Matches(rec), "nil means unrestricted") + assert.True(t, (&storage.ActivityFilter{AllowedServers: []string{"beta"}}).Matches(rec)) + assert.True(t, (&storage.ActivityFilter{AllowedServers: []string{"*"}}).Matches(rec)) + assert.False(t, (&storage.ActivityFilter{AllowedServers: []string{"alpha"}}).Matches(rec)) + assert.False(t, (&storage.ActivityFilter{AllowedServers: []string{}}).Matches(rec), + "empty-but-non-nil must match NOTHING — it is the shape a token allowed no servers produces") + assert.False(t, (&storage.ActivityFilter{AllowedServers: []string{"*"}}).Matches(unattributed), + "an operator-plane record has no server to be entitled to") +} + +func TestToolCallScopeAllows(t *testing.T) { + var unrestricted storage.ToolCallScope + assert.True(t, unrestricted.Allows("beta")) + assert.True(t, storage.ToolCallScope{"beta"}.Allows("beta")) + assert.True(t, storage.ToolCallScope{"*"}.Allows("beta")) + assert.False(t, storage.ToolCallScope{"alpha"}.Allows("beta")) + assert.False(t, storage.ToolCallScope{}.Allows("beta")) + assert.False(t, storage.ToolCallScope{"*"}.Allows("")) +} + +func TestScopeAllowedServers(t *testing.T) { + allowed, scoped := scopeAllowedServers(t.Context()) + assert.False(t, scoped, "no AuthContext is unrestricted, not scoped-to-nothing") + assert.Nil(t, allowed) + + allowed, scoped = scopeAllowedServers(auth.WithAuthContext(t.Context(), auth.AdminContext())) + assert.False(t, scoped) + assert.Nil(t, allowed) + + allowed, scoped = scopeAllowedServers(auth.WithAuthContext(t.Context(), + &auth.AuthContext{Type: auth.AuthTypeAgent})) + assert.True(t, scoped) + assert.NotNil(t, allowed, "a token allowed nothing must produce an EMPTY, non-nil set") + assert.Empty(t, allowed) + + var nilCtx context.Context + allowed, scoped = scopeAllowedServers(nilCtx) + assert.False(t, scoped, "a nil ctx must not panic") + assert.Nil(t, allowed) +} + +// TestUsageCacheKey_SeparatesScopes is the unit twin of the cache test above. +func TestUsageCacheKey_SeparatesScopes(t *testing.T) { + adminKey := usageParams{window: "all", top: 20, sort: "calls"}.cacheKey() + alpha := usageParams{window: "all", top: 20, sort: "calls", scoped: true, allowed: []string{"alpha"}}.cacheKey() + beta := usageParams{window: "all", top: 20, sort: "calls", scoped: true, allowed: []string{"beta"}}.cacheKey() + + assert.NotEqual(t, adminKey, alpha) + assert.NotEqual(t, alpha, beta) + assert.Equal(t, + usageParams{window: "all", top: 20, sort: "calls", scoped: true, allowed: []string{"alpha", "beta"}}.cacheKey(), + usageParams{window: "all", top: 20, sort: "calls", scoped: true, allowed: []string{"beta", "alpha"}}.cacheKey(), + "the same entitlement in a different order is the same cache identity") +} + +// scopeR9DecodeEnvelope is used where the body is not the standard data envelope. +func scopeR9DecodeEnvelope(t *testing.T, rec *httptest.ResponseRecorder) map[string]interface{} { + t.Helper() + var out map[string]interface{} + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &out), "body: %s", rec.Body.String()) + return out +} + +var _ = scopeR9DecodeEnvelope diff --git a/internal/httpapi/scope_subtree.go b/internal/httpapi/scope_subtree.go new file mode 100644 index 000000000..cea3cd39e --- /dev/null +++ b/internal/httpapi/scope_subtree.go @@ -0,0 +1,196 @@ +package httpapi + +import ( + "context" + "net/http" + + "github.com/go-chi/chi/v5" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" +) + +// This file extends internal/httpapi/scope.go with the per-server subtree gate +// and the shared "what may this caller see?" projection helpers the activity / +// tool-call doors read. Same rule as scope.go: a read route under /api/v1 does +// not re-derive visibility for itself — it answers from here. + +// --------------------------------------------------------------------------- +// Scope vs profile — the boundary this package defends +// --------------------------------------------------------------------------- +// +// Three things in this tree look like "scope" and only ONE of them is an +// authorization boundary: +// +// 1. auth.CanEnumerateServer — token scope (AllowedServers) alone. This is the +// boundary. It is the only one of the three that decides whether a caller +// may learn that a server exists, and it is what every read door in this +// package answers from. +// +// 2. server.serverInScope (internal/server/mcp_visibility.go) — token scope +// AND the active PROFILE. The profile half is an ERGONOMIC filter: it +// narrows what an agent is offered so a 300-tool fleet does not drown one +// task, and the user flips it at will with set_profile. It is deliberately +// NOT intersected into (1): a profile switch would then silently change +// what a token is authorized to read, and because the profile is +// caller-selectable while the token scope is not, a caller could WIDEN its +// own visibility by switching profiles. +// +// 3. preflight.ResolveScope (the REST /preflight door) — token scope ∩ token +// PIN ∩ requested profile. The pin (AuthContext.ProfilePin) is operator-set +// and not caller-selectable, so intersecting it there genuinely narrows; +// the requested-profile half is again ergonomics, and preflight is a +// "would these tools resolve under profile X?" question that has to answer +// under the profile the caller names. See the comment on +// handleAgentTokenAuth, which describes THAT door and not this predicate. +// +// So (1) ⊇ (2) and (1) ⊇ (3) always. A REST read door must be gated by (1); +// anything (2) or (3) additionally hides is hidden for convenience, not safety. + +// scopeAllowedServers returns the server names a scoped caller may see, plus +// whether the caller is scoped at all. +// +// The slice is non-nil for a scoped caller EVEN WHEN EMPTY: the downstream +// filters (storage.ActivityFilter.AllowedServers, storage.ToolCallScope) read +// nil as "unrestricted", so handing them a nil for a token that is allowed +// nothing would open the door it was meant to close. "*" is preserved and +// honoured by those filters exactly as AuthContext.CanAccessServer honours it. +func scopeAllowedServers(ctx context.Context) ([]string, bool) { + if !auth.IsScopedCaller(ctx) { + return nil, false + } + ac := auth.AuthContextFromContext(ctx) + out := make([]string, 0, len(ac.AllowedServers)) + out = append(out, ac.AllowedServers...) + return out, true +} + +// sessionsDenialMessage is why /api/v1/sessions and /api/v1/sessions/{id} are +// DENIED to a non-admin caller rather than filtered. +// +// A contracts.MCPSession has no server attribution at all — it describes a +// CLIENT connected to the proxy (client name and version, workspace basename, +// work-session grouping, tool-call and token totals). There is no server name +// to project through canSeeServer, so "filtering" it would mean either handing +// over the operator's whole client-and-workspace inventory or inventing an +// attribution the record does not carry. Same call as /api/v1/config: it is an +// operator document, not a per-server one. +const sessionsDenialMessage = "Agent tokens cannot read MCP session history" + +// The round-10 denial messages. Each names a route class whose whole document +// is a DEPLOYMENT-WIDE aggregate: it either enumerates the inventory outright +// or reports scalars computed across it that cannot be re-derived from the +// caller's own slice. Filtering such a document leaves the scalars beside the +// filtered part as an exact oracle for what was hidden, which is why every one +// of them takes the /api/v1/config and /stats/tokens answer — 403 — instead. +const ( + // /security/overview and /security/queue. QueueProgress.Items names every + // queued server; the overview is fleet-wide scan and finding counts. + securityFleetDenialMessage = "Agent tokens cannot read deployment-wide security scan state" + + // /telemetry/payload. The heartbeat carries server_count, + // connected_server_count, tool_count and server_docker_isolated_count — + // precisely the count oracle removed from /status. + telemetryPayloadDenialMessage = "Agent tokens cannot read the deployment telemetry payload" + + // /onboarding/state and /onboarding/mark (which echoes the same document). + // configured_server_count is an inventory size and connected_client_ids is + // the operator's MCP-client inventory — the same class as /sessions. + onboardingDenialMessage = "Agent tokens cannot read onboarding state" + + // /secrets/refs and /secrets/config. Values are masked, so this is a + // credential INVENTORY rather than a disclosure — but it names the secrets + // belonging to servers the caller may not enumerate, along with the keyring + // reference text and whether each resolves. It is a strictly narrower view + // of the document GET /api/v1/config already answers 403 for. + secretsInventoryDenialMessage = "Agent tokens cannot read the configuration's secret inventory" +) + +// serverExists reports whether a server with this exact name is configured. +// +// It reads GetAllServers — the same inventory the /servers list and the +// per-server diagnostics door answer from — so "exists" cannot mean one thing +// to the gate and another to the handler behind it. +// +// The error is RETURNED rather than folded into the boolean (round 10, P8). +// Collapsing it to false made a transient inventory read failure answer "no +// such server" on hot paths like /servers/{id}/logs and /servers/{id}/tools: +// the caller is told its own server has been deleted, retries stop, and the +// operator chases a phantom deletion instead of the read error. "Does not +// exist" and "could not determine" are different answers and get different +// statuses — 404 and 503. +func (s *Server) serverExists(name string) (bool, error) { + if name == "" { + return false, nil + } + servers, err := s.controller.GetAllServers() + if err != nil { + return false, err + } + for _, sv := range servers { + if n, _ := sv["name"].(string); n == name { + return true, nil + } + } + return false, nil +} + +// scopedServerSubtree is the ONE scope gate for /api/v1/servers/{id}/**. +// +// It is a middleware, not a per-handler check, for the same reason +// decodeServerIDParam is: this subtree keeps growing sub-resources (tools, +// logs, tool-calls, scan/status, scan/report, scan/files, integrity, +// tools/export, tools/{tool}/diff …) and each one answered for itself. Only +// /diagnostics had a gate; the rest handed a token scoped to `alpha` beta's +// tool list, its scan report, its scanned file tree, its per-server tool-call +// history — and, sharpest, its raw stdout/stderr, which routinely echoes the +// argv and env the upstream process was launched with. That is a credential +// disclosure that walks straight around the log-redaction work in #1158, +// because nothing redacts a log tail. +// +// It also supplies the EXISTENCE half. The earlier round deferred this subtree +// because these handlers answer 200 for a server that does not exist, so there +// was no 404 to be at status parity WITH. That is a reason to fix the existence +// check, not to leave the hole: for a scoped caller both cases are now the same +// 404 with the same body, so "not yours" and "not there" are indistinguishable. +// +// Admin callers are untouched — including the no-AuthContext bootstrap +// passthrough, per auth.CanEnumerateServer — so the 200-on-absent quirk and +// every existing admin behaviour on this subtree is preserved exactly. +// +// It runs on every method, not only GET. The mutating routes here already +// answer a uniform 403 from requireServerOp before they look anything up, so +// they leak nothing either way; ordering the 404 first just means an agent gets +// one consistent answer about servers it may not see. +func (s *Server) scopedServerSubtree(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + if !auth.IsScopedCaller(ctx) { + next.ServeHTTP(w, r) + return + } + // decodeServerIDParam is registered first on this subtree, so the + // value here is the real server name, not its percent-encoded form. + id := chi.URLParam(r, "id") + if !canSeeServer(ctx, id) { + s.writeError(w, r, http.StatusNotFound, "Server not found: "+id) + return + } + exists, err := s.serverExists(id) + if err != nil { + // The caller IS entitled to this name, so no existence fact leaks + // by admitting we could not read the inventory. Saying 404 here + // would tell an entitled caller its own server is gone (P8). + s.logger.Errorw("Scope gate could not read the server inventory", + "server", id, "error", err) + s.writeError(w, r, http.StatusServiceUnavailable, "Server inventory temporarily unavailable") + return + } + if exists { + next.ServeHTTP(w, r) + return + } + // Same status and same message as the absent case on every route in + // the subtree — this IS the absent case, as far as the caller can tell. + s.writeError(w, r, http.StatusNotFound, "Server not found: "+id) + }) +} diff --git a/internal/httpapi/security_scanner.go b/internal/httpapi/security_scanner.go index 5bca35499..2aa1f2bf2 100644 --- a/internal/httpapi/security_scanner.go +++ b/internal/httpapi/security_scanner.go @@ -10,6 +10,7 @@ import ( "github.com/go-chi/chi/v5" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" "github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts" "github.com/smart-mcp-proxy/mcpproxy-go/internal/security/scanner" ) @@ -79,7 +80,9 @@ func (s *Server) handleListScanners(w http.ResponseWriter, r *http.Request) { s.writeError(w, r, http.StatusInternalServerError, err.Error()) return } - s.writeSuccess(w, scanners) + // #1166 round 10 (P3): ConfiguredEnv holds the vendor API keys an operator + // typed into the scanner config dialog. They went out in the clear here. + s.writeSuccess(w, scanner.RedactScannersForAPI(scanners)) } func (s *Server) handleInstallScanner(w http.ResponseWriter, r *http.Request) { @@ -139,6 +142,33 @@ func (s *Server) handleRemoveScanner(w http.ResponseWriter, r *http.Request) { s.writeSuccess(w, map[string]string{"status": "disabled", "id": id}) } +// stripRedactedScannerEnv removes every entry whose value is the API redaction +// sentinel, returning a fresh map plus whether anything was dropped. A nil or +// empty input yields a nil map, so the caller's "nothing to do" check is +// unchanged. +// +// It never mutates the caller's map: the decoded request body is not shared +// today, but the whole point of this guard is that a future caller must not be +// able to reintroduce the write by handing us a map it also uses. +func stripRedactedScannerEnv(env map[string]string) (map[string]string, bool) { + if len(env) == 0 { + return nil, false + } + out := make(map[string]string, len(env)) + dropped := false + for k, v := range env { + if v == scanner.RedactedEnvValue { + dropped = true + continue + } + out[k] = v + } + if len(out) == 0 { + return nil, dropped + } + return out, dropped +} + func (s *Server) handleConfigureScanner(w http.ResponseWriter, r *http.Request) { if !s.requireSecurity(w, r) { return @@ -157,12 +187,28 @@ func (s *Server) handleConfigureScanner(w http.ResponseWriter, r *http.Request) s.writeError(w, r, http.StatusBadRequest, "invalid request body") return } - if len(req.Env) == 0 && req.DockerImage == "" { + // #1166 round 11: the read doors redact every literal env value to + // scanner.RedactedEnvValue, so a client that GETs /security/scanners and + // posts the document back would store the sentinel OVER the operator's real + // API key — a silent credential destruction that leaves the scanner + // authenticating as "***". The Web UI was taught to skip the sentinel, but + // the server must not depend on a cooperating client; any API caller, CLI + // or script can round-trip the redacted document. Drop those entries here. + // ConfigureScanner MERGES into ConfiguredEnv, so an omitted key keeps its + // stored value — which is exactly the semantics the sentinel means. + env, droppedRedacted := stripRedactedScannerEnv(req.Env) + if len(env) == 0 && req.DockerImage == "" { + if droppedRedacted { + s.writeError(w, r, http.StatusBadRequest, + "env values must not be the redaction placeholder "+scanner.RedactedEnvValue+ + " — omit a key to keep its stored value") + return + } s.writeError(w, r, http.StatusBadRequest, "env map or docker_image is required") return } - if err := s.securityController.ConfigureScanner(r.Context(), id, req.Env, req.DockerImage); err != nil { + if err := s.securityController.ConfigureScanner(r.Context(), id, env, req.DockerImage); err != nil { s.writeError(w, r, http.StatusInternalServerError, err.Error()) return } @@ -184,7 +230,9 @@ func (s *Server) handleGetScannerStatus(w http.ResponseWriter, r *http.Request) s.writeError(w, r, http.StatusNotFound, err.Error()) return } - s.writeSuccess(w, sc) + // Same redaction as the list door — one scanner is not a lesser disclosure + // than all of them (P3). + s.writeSuccess(w, sc.RedactedForAPI()) } // --- Scan operation handlers --- @@ -346,6 +394,17 @@ func (s *Server) handleSecurityOverview(w http.ResponseWriter, r *http.Request) if !s.requireSecurity(w, r) { return } + // #1166 round 10 (P4): DENIED to a non-admin caller, not filtered. The + // overview is nothing but deployment-wide scan and finding counts — + // scanned/unscanned server totals and severity tallies computed across the + // whole inventory. There is no per-server breakdown to project through + // canSeeServer, and the scalars themselves are the count oracle for exactly + // what /servers now withholds. Same call as /stats/tokens and + // /telemetry/payload; a scoped caller reads its own server's verdict from + // /servers/{id}/scan/status, which the subtree gate already scopes. + if !s.requireAdminRead(w, r, securityFleetDenialMessage) { + return + } overview, err := s.securityController.GetSecurityOverview(r.Context()) if err != nil { s.writeError(w, r, http.StatusInternalServerError, err.Error()) @@ -575,6 +634,17 @@ func (s *Server) handleGetQueueProgress(w http.ResponseWriter, r *http.Request) return } + // #1166 round 10 (P4): DENIED to a non-admin caller. QueueProgress.Items + // carries a ServerName per queued server — the full inventory, live, on a + // route that sits right beside the subtree gate — and the counters around + // it (total/pending/running/completed/failed) are fleet-wide scalars that + // cannot be re-derived from a filtered item list. Filtering the items alone + // would leave those scalars as an exact count of what was hidden, so the + // whole document is denied, as /stats/tokens and /security/overview are. + if !s.requireAdminRead(w, r, securityFleetDenialMessage) { + return + } + progress := s.securityController.GetQueueProgress() if progress == nil { s.writeSuccess(w, map[string]interface{}{ @@ -638,6 +708,20 @@ func (s *Server) handleListScanHistory(w http.ResponseWriter, r *http.Request) { return less }) + // #1166: each summary carries ServerName, so an unfiltered history is a + // complete inventory enumeration on a route that is otherwise about scan + // results. Rebuild rather than compact — `summaries` comes straight from + // the controller. + if auth.IsScopedCaller(r.Context()) { + scoped := make([]scanner.ScanJobSummary, 0, len(summaries)) + for _, sum := range summaries { + if canSeeServer(r.Context(), sum.ServerName) { + scoped = append(scoped, sum) + } + } + summaries = scoped + } + // Status filter if statusFilter := r.URL.Query().Get("status"); statusFilter != "" { filtered := summaries[:0] @@ -697,6 +781,20 @@ func (s *Server) handleGetScanReportByJobID(w http.ResponseWriter, r *http.Reque return } + // #1166 round 10 (P4): this is the per-server scan report reached by JOB id + // instead of by server name, so it walked around the /servers/{id} subtree + // gate — a scoped token read another tenant's findings, scanned file paths + // and risk score by guessing or reading a job id. Unlike the queue and the + // overview this document IS per-server, so it is scoped rather than denied: + // a caller entitled to the server still gets its report. + // + // The 404 is the same status and shape the unknown-job branch above returns, + // so "not yours" and "no such job" are indistinguishable to the caller. + if report != nil && !canSeeServer(r.Context(), report.ServerName) { + s.writeError(w, r, http.StatusNotFound, "scan report not found: "+jobID) + return + } + // Strip sarif_raw unless requested if r.URL.Query().Get("include_sarif") != "true" { for i := range report.Reports { diff --git a/internal/httpapi/security_scanner_redaction_write_test.go b/internal/httpapi/security_scanner_redaction_write_test.go new file mode 100644 index 000000000..49fdc6463 --- /dev/null +++ b/internal/httpapi/security_scanner_redaction_write_test.go @@ -0,0 +1,149 @@ +package httpapi + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/security/scanner" +) + +// M3 (#1166 round 11) — the read doors redact every literal scanner env value +// to scanner.RedactedEnvValue. Nothing stopped that sentinel coming back in on +// the WRITE door, so a client that read GET /security/scanners and posted the +// document back stored "***" over the operator's real vendor API key. The +// frontend was taught to skip the sentinel; the server must not depend on a +// cooperating client, because any CLI or script can round-trip the document. + +const scannerRealSecret = "sk-live-REAL-VENDOR-KEY" + +func putScannerConfig(t *testing.T, srv *Server, body string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodPut, "/api/v1/security/scanners/mcp-scan/config", bytes.NewBufferString(body)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + srv.ServeHTTP(rec, req) + return rec +} + +// TestConfigureScanner_RejectsRedactionSentinel is the end-to-end round-trip: +// read the redacted document off the production GET door, post it back +// verbatim, and assert the real secret is never overwritten. +// +// The GET half is the positive control — it proves the sentinel is genuinely +// what a client reads back, so the write guard is defending against a shape the +// API really produces rather than one invented by the test. +func TestConfigureScanner_RejectsRedactionSentinel(t *testing.T) { + secCtrl := &mockSecurityController{ + scanners: []*scanner.ScannerPlugin{{ + ID: "mcp-scan", + Name: "MCP Scan", + Status: scanner.ScannerStatusInstalled, + ConfiguredEnv: map[string]string{ + "VENDOR_API_KEY": scannerRealSecret, + "KEYRING_REF": "${keyring:vendor-key}", + }, + }}, + } + srv := newTestServerWithSecurity(t, secCtrl) + + // 1. Read the document back the way any API client would. + getReq := httptest.NewRequest(http.MethodGet, "/api/v1/security/scanners/mcp-scan/status", nil) + getRec := httptest.NewRecorder() + srv.ServeHTTP(getRec, getReq) + require.Equal(t, http.StatusOK, getRec.Code, "body: %s", getRec.Body.String()) + + var got scanner.ScannerPlugin + secParseData(t, getRec.Body, &got) + require.Equal(t, scanner.RedactedEnvValue, got.ConfiguredEnv["VENDOR_API_KEY"], + "precondition: the read door really hands back the sentinel") + require.Equal(t, "${keyring:vendor-key}", got.ConfiguredEnv["KEYRING_REF"], + "precondition: a keyring REFERENCE is preserved verbatim and must keep round-tripping") + + // 2. Post it straight back, plus one genuinely new value — exactly what a + // naive "edit one field and PUT the whole document" client does. + got.ConfiguredEnv["NEW_KEY"] = "brand-new-value" + payload, err := json.Marshal(map[string]interface{}{"env": got.ConfiguredEnv}) + require.NoError(t, err) + + rec := putScannerConfig(t, srv, string(payload)) + require.Equal(t, http.StatusOK, rec.Code, "body: %s", rec.Body.String()) + + // 3. The sentinel must never reach the service. The service MERGES, so an + // absent key keeps its stored value — which is what the sentinel means. + require.Equal(t, 1, secCtrl.configureCalls) + assert.NotContains(t, secCtrl.configuredEnv, "VENDOR_API_KEY", + "the redaction sentinel would have been stored over the real key") + for k, v := range secCtrl.configuredEnv { + assert.NotEqual(t, scanner.RedactedEnvValue, v, "env %q carried the redaction sentinel through to storage", k) + } + + // The entries that are NOT the sentinel must still go through, or the guard + // would have broken configuration instead of protecting it. + assert.Equal(t, "brand-new-value", secCtrl.configuredEnv["NEW_KEY"]) + assert.Equal(t, "${keyring:vendor-key}", secCtrl.configuredEnv["KEYRING_REF"], + "a keyring reference is a pointer, not a secret, and must remain writable") +} + +// TestConfigureScanner_SentinelOnlyBodyIsRejected. A body whose every value is +// the sentinel carries no instruction at all. Silently answering 200 would tell +// the client its edit was saved when nothing was written, so it is a 400 that +// names the cause. +func TestConfigureScanner_SentinelOnlyBodyIsRejected(t *testing.T) { + secCtrl := &mockSecurityController{} + srv := newTestServerWithSecurity(t, secCtrl) + + rec := putScannerConfig(t, srv, `{"env":{"VENDOR_API_KEY":"`+scanner.RedactedEnvValue+`"}}`) + + assert.Equal(t, http.StatusBadRequest, rec.Code, "body: %s", rec.Body.String()) + assert.Contains(t, rec.Body.String(), "redaction placeholder") + assert.Zero(t, secCtrl.configureCalls, "nothing may reach the service") +} + +// TestConfigureScanner_SentinelWithDockerImageStillConfigures. Dropping the +// sentinel must not swallow the rest of the request: a body that also carries a +// docker_image is a real instruction and has to be applied. +func TestConfigureScanner_SentinelWithDockerImageStillConfigures(t *testing.T) { + secCtrl := &mockSecurityController{} + srv := newTestServerWithSecurity(t, secCtrl) + + rec := putScannerConfig(t, srv, + `{"env":{"VENDOR_API_KEY":"`+scanner.RedactedEnvValue+`"},"docker_image":"ghcr.io/example/scan:v2"}`) + + require.Equal(t, http.StatusOK, rec.Code, "body: %s", rec.Body.String()) + assert.Equal(t, "ghcr.io/example/scan:v2", secCtrl.configuredImage) + assert.Empty(t, secCtrl.configuredEnv, "the sentinel-only env must not reach the service") +} + +// TestStripRedactedScannerEnv covers the predicate directly, including that it +// never mutates the caller's map. +func TestStripRedactedScannerEnv(t *testing.T) { + in := map[string]string{ + "REAL": "value", + "MASKED": scanner.RedactedEnvValue, + "KEYRING": "${keyring:name}", + "EMPTY": "", + } + out, dropped := stripRedactedScannerEnv(in) + + assert.True(t, dropped) + assert.Equal(t, map[string]string{"REAL": "value", "KEYRING": "${keyring:name}", "EMPTY": ""}, out) + assert.Equal(t, scanner.RedactedEnvValue, in["MASKED"], "the caller's map must not be mutated") + + out, dropped = stripRedactedScannerEnv(map[string]string{"REAL": "value"}) + assert.False(t, dropped) + assert.Equal(t, map[string]string{"REAL": "value"}, out) + + out, dropped = stripRedactedScannerEnv(nil) + assert.False(t, dropped) + assert.Nil(t, out) + + out, dropped = stripRedactedScannerEnv(map[string]string{"MASKED": scanner.RedactedEnvValue}) + assert.True(t, dropped) + assert.Empty(t, out, "an all-sentinel map yields nothing to write") +} diff --git a/internal/httpapi/security_scanner_test.go b/internal/httpapi/security_scanner_test.go index 7e91be822..64f17eefe 100644 --- a/internal/httpapi/security_scanner_test.go +++ b/internal/httpapi/security_scanner_test.go @@ -41,6 +41,11 @@ type mockSecurityController struct { queueRunning bool deepScanEnabled bool + + // What the last ConfigureScanner call carried. + configuredEnv map[string]string + configuredImage string + configureCalls int } func (m *mockSecurityController) DeepScanEnabled() bool { @@ -60,6 +65,13 @@ func (m *mockSecurityController) RemoveScanner(_ context.Context, id string) err } func (m *mockSecurityController) ConfigureScanner(_ context.Context, id string, env map[string]string, dockerImage string) error { + // Captured so a test can assert what the handler actually forwarded to the + // service, not merely that the request returned 200. The real service + // MERGES env into ConfiguredEnv, so "the sentinel never arrives" and "the + // stored secret survives" are the same assertion. + m.configuredEnv = env + m.configuredImage = dockerImage + m.configureCalls++ return m.configureErr } diff --git a/internal/httpapi/security_test.go b/internal/httpapi/security_test.go index 8bebd7cf1..e51c38522 100644 --- a/internal/httpapi/security_test.go +++ b/internal/httpapi/security_test.go @@ -269,7 +269,7 @@ func (m *baseController) GetLogDir() string func (m *baseController) TriggerOAuthLogin(serverName string) error { return nil } func (m *baseController) GetSecretResolver() *secret.Resolver { return nil } func (m *baseController) NotifySecretsChanged(ctx context.Context, op, name string) error { return nil } -func (m *baseController) GetToolCalls(limit, offset int) ([]*contracts.ToolCallRecord, int, error) { +func (m *baseController) GetToolCalls(limit, offset int, _ storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error) { return nil, 0, nil } func (m *baseController) GetToolCallByID(id string) (*contracts.ToolCallRecord, error) { @@ -317,7 +317,7 @@ func (m *baseController) GetSessionByID(id string) (*contracts.MCPSession, error func (m *baseController) GetRecentSessions(limit int, status string) ([]*contracts.MCPSession, int, error) { return nil, 0, nil } -func (m *baseController) GetToolCallsBySession(sessionID string, limit, offset int) ([]*contracts.ToolCallRecord, int, error) { +func (m *baseController) GetToolCallsBySession(sessionID string, limit, offset int, _ storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error) { return nil, 0, nil } func (m *baseController) GetVersionInfo() *updatecheck.VersionInfo { return nil } diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index abba5081c..808f218dc 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -156,12 +156,16 @@ type ServerController interface { GetCurrentConfig() interface{} NotifySecretsChanged(ctx context.Context, operation, secretName string) error - // Tool call history - GetToolCalls(limit, offset int) ([]*contracts.ToolCallRecord, int, error) + // Tool call history. The ToolCallScope argument is the caller's server + // entitlement (nil = unrestricted, #1166 follow-up); it is passed DOWN + // rather than applied to the result because these reads also report a + // `total`, and a post-filter would leave the total counting records the + // page no longer contains. + GetToolCalls(limit, offset int, scope storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error) GetToolCallByID(id string) (*contracts.ToolCallRecord, error) GetServerToolCalls(serverName string, limit int) ([]*contracts.ToolCallRecord, error) ReplayToolCall(ctx context.Context, id string, arguments map[string]interface{}) (*contracts.ToolCallRecord, error) - GetToolCallsBySession(sessionID string, limit, offset int) ([]*contracts.ToolCallRecord, int, error) + GetToolCallsBySession(sessionID string, limit, offset int, scope storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error) // Session management. status filters on session status ("active" / // "closed"); an empty string means no filter. @@ -561,9 +565,18 @@ func (s *Server) handleAgentTokenAuth(w http.ResponseWriter, r *http.Request, ne // Built through the shared constructor so every field the MCP path carries // reaches the REST path too — notably ProfilePin, which this path dropped - // before Spec 098. Evaluation scope is token scope ∩ token pin ∩ requested - // profile (preflight.ResolveScope), so a dropped pin silently widened what - // a pinned token could see. + // before Spec 098. PREFLIGHT's evaluation scope is token scope ∩ token pin ∩ + // requested profile (preflight.ResolveScope), so a dropped pin silently + // widened what a pinned token could resolve there. + // + // That intersection is preflight's, not this package's ENUMERATION + // boundary. Every read door under /api/v1 answers from + // auth.CanEnumerateServer — token scope alone. The profile terms are + // ergonomic filters and one of them (the requested profile) is + // caller-selectable, so folding them into the enumeration boundary would + // let a caller change what it is authorized to see by switching profiles. + // The three notions of scope, and why only one of them is a boundary, are + // laid out at the top of scope_subtree.go. authCtx := agentToken.AuthContext() ctx := auth.WithAuthContext(r.Context(), authCtx) @@ -757,7 +770,12 @@ func (s *Server) setupRoutes() { // Profiles (Profiles v2 T2) — list + default active get/set for UI surfaces r.Get("/profiles", s.handleListProfiles) r.Get("/profiles/active", s.handleGetActiveProfile) - r.Put("/profiles/active", s.handleSetActiveProfile) + // #1166 round 11: the ONLY mutating route in this group, and it was + // ungated. The active profile is server-level shared state — it decides + // which servers the Web UI and the tray render — so a READ-scoped agent + // token could reshape the operator's view. Same gate as every other + // config-level write. + r.Put("/profiles/active", s.requireServerOp(auth.ServerOpConfigWrite, s.handleSetActiveProfile)) // Server management r.Get("/servers", s.handleGetServers) @@ -784,6 +802,12 @@ func (s *Server) setupRoutes() { // MCP-1056). Centralising the decode also prevents new sub-resource // routes from silently reintroducing the gap. r.Use(decodeServerIDParam) + // #1166 follow-up: ONE scope gate for the whole subtree, so a new + // sub-resource inherits it instead of shipping open. Registered + // after decodeServerIDParam so it sees the decoded name. For a + // scoped caller an unentitled server and an absent one are the same + // 404; admins are unaffected. See scopedServerSubtree. + r.Use(s.scopedServerSubtree) // Mutating per-server routes carry the shared agent-token gate // (issues #877/#878). r.Patch("/", s.requireServerOp(auth.ServerOpPatch, s.handlePatchServer)) // Partial update server config @@ -1117,7 +1141,7 @@ func (s *Server) writeSuccess(w http.ResponseWriter, data interface{}) { // @Success 200 {object} contracts.SuccessResponse "Server status information" // @Failure 500 {object} contracts.ErrorResponse "Internal server error" // @Router /api/v1/status [get] -func (s *Server) handleGetStatus(w http.ResponseWriter, _ *http.Request) { +func (s *Server) handleGetStatus(w http.ResponseWriter, r *http.Request) { // Get routing mode from config routingMode := config.RoutingModeRetrieveTools // …and the data directory, which is where the tray's autostart sidecar @@ -1137,14 +1161,20 @@ func (s *Server) handleGetStatus(w http.ResponseWriter, _ *http.Request) { // One traversal, used for both the top-level field and the nested snapshot, // so the two cannot disagree and the O(servers) walk happens once (#1084). - liveUpstreamStats := s.controller.GetUpstreamStats() + // + // #1166: `upstream_stats.servers` is keyed by every server name, so this + // route was a complete inventory enumeration on the single most-polled + // door. Scope it once, here, and BOTH the top-level field and the nested + // snapshot narrow together — the #1084 single-traversal property is what + // makes one filter enough. + liveUpstreamStats := filterUpstreamStatsServers(r.Context(), s.controller.GetUpstreamStats()) response := map[string]interface{}{ "running": s.controller.IsRunning(), "edition": editionValue, "listen_addr": s.controller.GetListenAddress(), "upstream_stats": liveUpstreamStats, - "status": withLiveUpstreamStats(s.controller.GetStatus(), liveUpstreamStats), + "status": withLiveUpstreamStats(r.Context(), s.controller.GetStatus(), liveUpstreamStats), "routing_mode": routingMode, "timestamp": time.Now().Unix(), // Unix seconds at which this core process started, so a UI can render a @@ -1168,7 +1198,18 @@ func (s *Server) handleGetStatus(w http.ResponseWriter, _ *http.Request) { // env_kind. Read-only — mutation happens on MCP/connect events, never // through this endpoint. nil when the telemetry service (or activation // store) is not wired (e.g. very early startup). - if s.telemetryPayloadProvider != nil { + // + // #1166 round 11: OMITTED for a scoped caller. /status stays open to an + // agent token because it is a liveness surface agents legitimately poll — + // but this block is pure operator plane and has no per-server part to + // project. mcp_clients_seen_ever is the operator's entire MCP-client + // inventory, the same class /sessions and /onboarding/state answer 403 for; + // retrieve_tools_calls_24h and configured_ide_count are exact + // deployment-wide counters, the count-oracle shape this very route already + // removed from upstream_stats.total_servers. Withholding the key rather + // than denying the route is safe for clients: `activation` is already + // absent whenever telemetry is unwired, so every consumer tolerates it. + if !auth.IsScopedCaller(r.Context()) && s.telemetryPayloadProvider != nil { if svc := s.telemetryPayloadProvider(); svc != nil { if store := svc.ActivationStore(); store != nil { if db := svc.ActivationDB(); db != nil { @@ -1336,6 +1377,7 @@ func (s *Server) desiredConfigForPatch() (*config.Config, error) { // handleGetInfo godoc // @Summary Get server information // @Description Get essential server metadata including version, web UI URL, endpoint addresses, and update availability +// @Description web_ui_url carries the ?apikey= credential ONLY for an authenticated admin; a scoped agent token receives the bare URL // @Description This endpoint is designed for tray-core communication and version checking // @Description Use refresh=true query parameter to force an immediate update check against GitHub // @Description The launched_by field reports durable launch provenance ("tray", "installer", or "" for user-launched/unknown) @@ -1427,16 +1469,48 @@ func buildWebUIURL(listenAddr string, r *http.Request) string { return fmt.Sprintf("%s://%s/ui/", protocol, listenAddr) } -// buildWebUIURLWithAPIKey constructs the web UI URL with API key included if configured +// buildWebUIURLWithAPIKey constructs the web UI URL, appending the GLOBAL ADMIN +// API key as a `?apikey=` query ONLY for a caller entitled to hold it. +// +// #1166 round 10, PRIVILEGE ESCALATION. GET /api/v1/info was registered with no +// gate at all and handed this string to anybody who could reach the route — +// including a read-only agent token scoped to one server, which received +// +// "web_ui_url":"http://127.0.0.1:8080/ui/?apikey=" +// +// and could then re-authenticate as an admin. That made every scope control on +// this mux moot: a scoped caller simply read the key out of /info and stopped +// being scoped. The defect predates this branch; it must not survive it. +// +// The route is NOT denied, and the field is NOT dropped. /info is version, +// endpoint, pid, provenance and update-policy metadata that agents and the CLI +// legitimately poll, and the base URL discloses nothing the same payload's +// `listen_addr` does not. Exactly one thing in it is privileged — the +// credential in the query string — so exactly that is what is withheld. A +// scoped caller gets `http://127.0.0.1:8080/ui/` and no way in. +// +// The predicate is CanRevealSecrets, not IsAdmin: it is the same test the other +// raw-credential doors answer from (#1148/#1167), it fails CLOSED on a nil +// AuthContext, and it refuses the unauthenticated /mcp back-compat admin +// context, which has proved no identity. Absence is treated as unprivileged +// HERE, unlike auth.CanEnumerateServer, because the two questions differ: not +// knowing who is calling is a reason to withhold a credential and not a reason +// to hide a server's name. Every real operator path carries an explicit admin +// context — the API key over TCP, the Unix socket, the Windows named pipe — so +// nothing first-party changes. func (s *Server) buildWebUIURLWithAPIKey(listenAddr string, r *http.Request) string { baseURL := buildWebUIURL(listenAddr, r) if baseURL == "" { return "" } + if !auth.AuthContextFromContext(r.Context()).CanRevealSecrets() { + return baseURL + } + // Add API key if configured cfg, err := s.controller.GetConfig() - if err == nil && cfg.APIKey != "" { + if err == nil && cfg != nil && cfg.APIKey != "" { return baseURL + "?apikey=" + cfg.APIKey } @@ -1539,7 +1613,7 @@ func (s *Server) handleGetServers(w http.ResponseWriter, r *http.Request) { // so they send only the diff — redacted-but-unchanged values // stay out of the patch and the backend keeps the real string. // See PR #425 for the original threat model. - s.redactServerSecrets(serverValues) + s.redactServerSecrets(r.Context(), serverValues) // Dereference stats pointer var statsValue contracts.ServerStats @@ -1547,6 +1621,12 @@ func (s *Server) handleGetServers(w http.ResponseWriter, r *http.Request) { statsValue = *stats } + // #1166: enumeration is scoped LAST, so a reviewer sees one obvious + // final gate. The stats must narrow with the array or total_servers + // stays an exact count oracle for what the filter just hid. + serverValues = visibleServers(r.Context(), serverValues) + statsValue = recomputeServerStats(r.Context(), serverValues, statsValue) + response := contracts.GetServersResponse{ Servers: serverValues, Stats: statsValue, @@ -1570,9 +1650,16 @@ func (s *Server) handleGetServers(w http.ResponseWriter, r *http.Request) { s.enrichServersWithQuarantineStats(servers) // See note above the management-service path for redaction rationale. - s.redactServerSecrets(servers) + s.redactServerSecrets(r.Context(), servers) - stats := contracts.ConvertUpstreamStatsToServerStats(s.controller.GetUpstreamStats()) + // #1166, legacy branch. This branch is invisible to a test suite whose + // default mock returns a non-nil management service, which is exactly how + // a one-branch fix ships looking complete. + servers = visibleServers(r.Context(), servers) + // Filtering the upstream-stats map BEFORE the conversion is free + // correctness: ConvertUpstreamStatsToServerStats derives every counter by + // walking stats["servers"], so the counts narrow with it. + stats := contracts.ConvertUpstreamStatsToServerStats(filterUpstreamStatsServers(r.Context(), s.controller.GetUpstreamStats())) response := contracts.GetServersResponse{ Servers: servers, @@ -1605,18 +1692,22 @@ func flattenNullableMap(m map[string]*string) map[string]string { // …), env-var secrets, URL query credentials, and any URL secrets echoed into // the last_error / health.detail strings. Sensitive values render as the // masked-display format `•••• ( chars)` (references pass through); -// error strings use the `***REDACTED***` sentinel. Skips redaction entirely -// when `reveal_secret_headers: true` is set in the loaded config, matching the -// behaviour of the `upstream_servers` MCP tool and the SSE event stream. +// error strings use the `***REDACTED***` sentinel. Skips redaction only when +// `reveal_secret_headers: true` is set in the loaded config AND the caller is +// an authenticated admin, matching the `upstream_servers` MCP tool exactly +// (issue #1167). // // The UI edit-and-save flow works without seeing the real values because // PATCH /api/v1/servers/{id} deep-merges (omitted keys preserved), so the // client computes a diff and only sends the keys that actually changed. // Redacted-but-unchanged values never round-trip — the backend keeps the // real string on disk. -func (s *Server) redactServerSecrets(servers []contracts.Server) { - cfg, err := s.controller.GetConfig() - if err == nil && cfg != nil && cfg.RevealSecretHeaders { +func (s *Server) redactServerSecrets(ctx context.Context, servers []contracts.Server) { + // #1167: this used to read the flag alone, with no ctx parameter at all — + // identity was not merely unchecked, it was unreachable at this frame. + // Both callers hold the *http.Request, so the caller is threaded in and + // the answer comes from the shared predicate. + if s.revealSecrets(ctx) { return } for i := range servers { @@ -3555,6 +3646,14 @@ func (s *Server) handleGetGlobalTools(w http.ResponseWriter, r *http.Request) { if name == "" { continue } + // #1166: without this, a token scoped to one server was denied the + // inventory on GET /api/v1/servers and then handed a STRICTLY LARGER + // one here — every server_name plus every tool name, description and + // schema. Skipping is not a fetch failure, so it must not set + // Partial / FailedServers. + if !canSeeServer(r.Context(), name) { + continue + } // #1064: a quarantined server contributes nothing here -- its tools are // unreachable (SECURITY BLOCK at dispatch) and its descriptions are the // TPA payload #1061 removed from the index. Skipping is not a failure, @@ -3690,6 +3789,19 @@ func (s *Server) handleSearchTools(w http.ResponseWriter, r *http.Request) { // Convert to typed search results typedResults := contracts.ConvertGenericSearchResultsToTyped(results) + // #1166: the MCP twin of this discovery surface filters through + // serverInScope (internal/server/mcp_visibility.go); this one returned + // tool_name + server_name pairs for the whole index to any scoped token. + if auth.IsScopedCaller(r.Context()) { + scoped := make([]contracts.SearchResult, 0, len(typedResults)) + for i := range typedResults { + if canSeeServer(r.Context(), typedResults[i].Tool.ServerName) { + scoped = append(scoped, typedResults[i]) + } + } + typedResults = scoped + } + // Restore the bare-tool-name contract on this REST surface (#871). The index // read seams canonicalize the name to "server:tool" for the MCP discovery // path, but external consumers of /api/v1/index/search assemble the id @@ -3774,12 +3886,15 @@ func (s *Server) handleSSEEvents(w http.ResponseWriter, r *http.Request) { defer heartbeat.Stop() // Send initial status - initialLiveStats := s.controller.GetUpstreamStats() + // #1166: /events sits behind the same apiKeyAuthMiddleware as /servers, so + // a scoped agent token can subscribe. Scoping /servers while leaving this + // stream unfiltered closes the front door and leaves the window open. + initialLiveStats := filterUpstreamStatsServers(r.Context(), s.controller.GetUpstreamStats()) initialStatus := map[string]interface{}{ "running": s.controller.IsRunning(), "listen_addr": s.controller.GetListenAddress(), "upstream_stats": initialLiveStats, - "status": withLiveUpstreamStats(s.controller.GetStatus(), initialLiveStats), + "status": withLiveUpstreamStats(r.Context(), s.controller.GetStatus(), initialLiveStats), "timestamp": time.Now().Unix(), "started_at": processStart.Unix(), } @@ -3813,12 +3928,12 @@ func (s *Server) handleSSEEvents(w http.ResponseWriter, r *http.Request) { // The channel snapshot is a point-in-time capture that never // passes through GetStatus(), so without this the stream's nested // stats stay stale for the life of the connection (#1084). - eventLiveStats := s.controller.GetUpstreamStats() + eventLiveStats := filterUpstreamStatsServers(r.Context(), s.controller.GetUpstreamStats()) response := map[string]interface{}{ "running": s.controller.IsRunning(), "listen_addr": s.controller.GetListenAddress(), "upstream_stats": eventLiveStats, - "status": withLiveUpstreamStats(status, eventLiveStats), + "status": withLiveUpstreamStats(r.Context(), status, eventLiveStats), "timestamp": time.Now().Unix(), "started_at": processStart.Unix(), } @@ -3833,8 +3948,17 @@ func (s *Server) handleSSEEvents(w http.ResponseWriter, r *http.Request) { continue } + // #1166 — most event types name a server in a scalar field + // rather than in the servers.changed embed, so a scoped caller + // learned about servers it cannot see through activity, oauth and + // security frames. Decided per subscriber, before rendering: + // nothing is written back to the shared event. + if !eventVisibleToCaller(r.Context(), evt) { + continue + } + eventPayload := map[string]interface{}{ - "payload": s.maskEventPayload(evt.Payload), + "payload": s.maskEventPayload(s.renderEventPayloadForCaller(r.Context(), evt)), "timestamp": evt.Timestamp.Unix(), } @@ -3846,6 +3970,91 @@ func (s *Server) handleSSEEvents(w http.ResponseWriter, r *http.Request) { } } +// renderEventPayloadForCaller renders a runtime event for ONE SSE subscriber. +// +// The rule this function exists to obey: the payload map, and the +// []contracts.Server inside it, are built ONCE in +// runtime.buildServersChangedPayload and fanned out BY POINTER to every +// subscriber (internal/runtime/event_bus.go publishEvent). Other SSE +// goroutines - the admin Web UI, the Swift tray - are concurrently inside +// json.Marshal on that same map. So a per-connection view is RENDERED into a +// fresh map and a fresh slice; nothing here ever writes into evt.Payload. +// Editing it in place would (a) empty the admin's server list, because the Web +// UI's mergeServers treats each payload as authoritative and deletes absent +// fields, and (b) be an unsynchronised concurrent map write, which Go turns +// into a fatal error that takes the whole core down for every client. +// +// Three narrowings, all only for servers.changed — every OTHER event type that +// names a server is dropped for a scoped caller before it reaches this +// function, by eventVisibleToCaller (sse_scope.go), which also explains why +// this one type is rendered instead of dropped: +// +// - #1166 - the coalescer extras that NAME a server ("server": "beta") are +// removed when the caller may not enumerate it. That extra survived the +// original embed filter, and on the notify-only path it was the entire +// payload. +// - #1166 - a scoped caller gets only the servers it may enumerate, with +// `stats` recomputed so total_servers is not a count oracle for the rest. +// - #1167 - a caller who MAY see raw values gets the embed dropped entirely +// (notify-only). The bus masks this payload unconditionally now, because a +// payload produced once for a mixed-privilege audience has no caller to +// gate against and must be masked for the least-privileged member of that +// audience. Handing an admin the masked embed while GET /api/v1/servers +// hands them the real one would make the UI's authoritative merge flicker +// between the two, so the embed is degraded to the notify-only shape +// buildServersChangedPayload already documents as its fallback, and the +// client re-fetches through the gated REST door. Costs one extra GET per +// coalescing window, and only when reveal_secret_headers is on. +func (s *Server) renderEventPayloadForCaller(ctx context.Context, evt internalRuntime.Event) map[string]interface{} { + payload := evt.Payload + if evt.Type != internalRuntime.EventTypeServersChanged || len(payload) == 0 { + return payload + } + + if s.revealSecrets(ctx) { + out := make(map[string]interface{}, len(payload)) + for k, v := range payload { + if k == "servers" || k == "stats" { + continue + } + out[k] = v + } + return out + } + + if !auth.IsScopedCaller(ctx) { + return payload + } + + // The coalescer's extras name the server whose change won the window + // ("server": "beta"), so narrowing the embed alone left the name on the + // wire beside it — and on the notify-only path (ListServers failed + // upstream, so there is no embed) that extra was the WHOLE payload. The + // copy is unconditional now for that reason: there is always something to + // scope, embed or not. + out := make(map[string]interface{}, len(payload)) + for k, v := range payload { + if isOutOfScopeIdentityField(ctx, k, v) { + continue + } + out[k] = v + } + + servers, ok := payload["servers"].([]contracts.Server) + if !ok { + // Notify-only payload (ListServers failed upstream) - no embed to + // narrow, but the extras above still were. + return out + } + scoped := visibleServers(ctx, servers) + out["servers"] = scoped + if stats, ok := payload["stats"].(*contracts.ServerStats); ok && stats != nil { + recomputed := recomputeServerStats(ctx, scoped, *stats) + out["stats"] = &recomputed + } + return out +} + // eventPayloadTextFields are the runtime-event payload keys whose PRESENCE // marks an event as carrying a tool call's own text. They are the trigger for // masking, not its scope: once an event qualifies, every string in it is @@ -3925,6 +4134,16 @@ func (s *Server) writeSSEEvent(w http.ResponseWriter, flusher http.Flusher, canF // Secrets management handlers func (s *Server) handleGetSecretRefs(w http.ResponseWriter, r *http.Request) { + // #1166 round 10 (P5): DENIED to a non-admin caller. Values are masked, so + // this enumerates rather than discloses — but it enumerates every keyring + // and env secret reference in the whole configuration, including the ones + // belonging to servers the caller may not know exist, and the reference + // text names them. It is a strictly narrower view of the document + // GET /api/v1/config already answers 403 for. + if !s.requireAdminRead(w, r, secretsInventoryDenialMessage) { + return + } + resolver := s.controller.GetSecretResolver() if resolver == nil { s.writeError(w, r, http.StatusInternalServerError, "Secret resolver not available") @@ -3997,6 +4216,12 @@ func (s *Server) handleMigrateSecrets(w http.ResponseWriter, r *http.Request) { } func (s *Server) handleGetConfigSecrets(w http.ResponseWriter, r *http.Request) { + // Same document as /secrets/refs, projected through the config instead of + // the providers, and denied for the same reason (P5). + if !s.requireAdminRead(w, r, secretsInventoryDenialMessage) { + return + } + resolver := s.controller.GetSecretResolver() if resolver == nil { s.writeError(w, r, http.StatusInternalServerError, "Secret resolver not available") @@ -4239,13 +4464,16 @@ func (s *Server) handleGetDiagnostics(w http.ResponseWriter, r *http.Request) { // Convert to typed servers servers := contracts.ConvertGenericServersToTyped(genericServers) + // #1166: scope the inventory before anything is derived from it, so the + // per-server error/oauth/secret detail below cannot describe a server the + // caller may not know exists. + servers = visibleServers(r.Context(), servers) + // Issue #872: last_error can echo the full upstream URL, including query // credentials. Scrub it before surfacing on the doctor route unless the - // operator opted out via reveal_secret_headers. - reveal := false - if cfg, cfgErr := s.controller.GetConfig(); cfgErr == nil && cfg != nil { - reveal = cfg.RevealSecretHeaders - } + // operator opted out via reveal_secret_headers AND the caller is an + // authenticated admin (#1167 — this read the flag alone with `r` in scope). + reveal := s.revealSecrets(r.Context()) // Collect diagnostics (legacy format) var upstreamErrors []contracts.DiagnosticIssue @@ -4309,6 +4537,7 @@ func (s *Server) handleGetDiagnostics(w http.ResponseWriter, r *http.Request) { // @Security ApiKeyAuth // @Security ApiKeyQuery // @Success 200 {object} contracts.SuccessResponse "Telemetry heartbeat payload" +// @Failure 403 {object} contracts.ErrorResponse "Agent tokens cannot read the deployment telemetry payload" // @Failure 503 {object} contracts.ErrorResponse "Telemetry service unavailable" // @Router /api/v1/telemetry/payload [get] func (s *Server) handleGetTelemetryPayload(w http.ResponseWriter, r *http.Request) { @@ -4317,6 +4546,15 @@ func (s *Server) handleGetTelemetryPayload(w http.ResponseWriter, r *http.Reques return } + // #1166 round 10 (P4): DENIED to a non-admin caller. The heartbeat is a + // fleet-wide census — server_count, connected_server_count, tool_count, + // server_docker_isolated_count — computed over the whole inventory with no + // per-server breakdown to project. It is the exact count oracle this branch + // removed from GET /api/v1/status, reachable through a preview route. + if !s.requireAdminRead(w, r, telemetryPayloadDenialMessage) { + return + } + if s.telemetryPayloadProvider == nil { s.writeError(w, r, http.StatusServiceUnavailable, "telemetry service unavailable") return @@ -4340,6 +4578,7 @@ func (s *Server) handleGetTelemetryPayload(w http.ResponseWriter, r *http.Reques // @Security ApiKeyAuth // @Security ApiKeyQuery // @Success 200 {object} contracts.SuccessResponse "Token statistics" +// @Failure 403 {object} contracts.ErrorResponse "Agent tokens cannot read deployment-wide token statistics" // @Failure 500 {object} contracts.ErrorResponse "Internal server error" // @Router /api/v1/stats/tokens [get] func (s *Server) handleGetTokenStats(w http.ResponseWriter, r *http.Request) { @@ -4348,6 +4587,23 @@ func (s *Server) handleGetTokenStats(w http.ResponseWriter, r *http.Request) { return } + // #1166 follow-up (G3): DENIED to a non-admin caller, not filtered. + // + // contracts.ServerTokenMetrics.PerServerToolListSizes is a map keyed by + // EVERY configured server name — a complete inventory enumeration, which is + // the exact thing GET /api/v1/servers now withholds. Projecting the map + // through canSeeServer would not be enough: the scalars beside it + // (SavedTokens, SavedTokensPercentage, the baseline sizes) are computed over + // the whole fleet and cannot be re-derived per server, so a scoped caller + // would still hold a cross-tenant oracle in numbers that merely LOOKED + // filtered. recomputeServerStats already takes the same position on the same + // struct — it DROPS TokenMetrics from GET /api/v1/servers rather than report + // it wrongly — and this route is nothing but that struct, so the consistent + // answer for the whole document is the one /api/v1/config gets: 403. + if !s.requireAdminRead(w, r, "Agent tokens cannot read deployment-wide token statistics") { + return + } + tokenStats, err := s.controller.GetTokenSavings() if err != nil { s.logger.Errorw("Failed to calculate token savings", "error", err) @@ -4480,11 +4736,22 @@ func (s *Server) handleGetToolCalls(w http.ResponseWriter, r *http.Request) { var total int var err error + // #1166 follow-up (G2): the caller's entitlement goes DOWN into the read, + // not over its result. These records carry the arguments and responses of + // every tool call on every server; a scoped token had no gate here at all. + // Filtering the returned page instead would leave `total` counting the + // records the page no longer contains — a broken pager, and a count oracle + // for exactly what was hidden. + var scope storage.ToolCallScope + if allowed, scoped := scopeAllowedServers(r.Context()); scoped { + scope = allowed + } + // Get tool calls - either filtered by session or all if sessionID != "" { - toolCalls, total, err = s.controller.GetToolCallsBySession(sessionID, limit, offset) + toolCalls, total, err = s.controller.GetToolCallsBySession(sessionID, limit, offset, scope) } else { - toolCalls, total, err = s.controller.GetToolCalls(limit, offset) + toolCalls, total, err = s.controller.GetToolCalls(limit, offset, scope) } if err != nil { @@ -4537,6 +4804,15 @@ func (s *Server) handleGetToolCallDetail(w http.ResponseWriter, r *http.Request) return } + // #1166 follow-up (G2): a record on a server the caller may not see takes + // the SAME exit as an id that does not exist — same status, same message. + // The oracle for this is status parity with an unknown id, not "the body + // omits the server name": this 404 body echoes nothing of the request. + if toolCall == nil || !canSeeServer(r.Context(), toolCall.ServerName) { + s.writeError(w, r, http.StatusNotFound, "Tool call not found") + return + } + detail := *toolCall s.maskToolCallRecord(&detail) @@ -4676,6 +4952,19 @@ func (s *Server) handleReplayToolCall(w http.ResponseWriter, r *http.Request) { return } + // #1166 follow-up (G2): replay dispatches a real call to the recorded + // server, so it must answer the same entitlement question the read door + // does — and with the same 404, so it cannot be used to probe for ids the + // caller may not read. Same shape as the /servers/{id} subtree gate: an + // out-of-scope record and an unknown id are one response. + if auth.IsScopedCaller(r.Context()) { + recorded, lookupErr := s.controller.GetToolCallByID(id) + if lookupErr != nil || recorded == nil || !canSeeServer(r.Context(), recorded.ServerName) { + s.writeError(w, r, http.StatusNotFound, "Tool call not found") + return + } + } + // Replay the tool call with modified arguments. The request context travels // with it so a client that disconnects while the replay waits for a // concurrency slot releases that slot immediately (spec 093 FR-005). @@ -4725,6 +5014,7 @@ func (s *Server) handleReplayToolCall(w http.ResponseWriter, r *http.Request) { // @Produce json // @Success 200 {object} contracts.GetConfigResponse "Configuration retrieved successfully" // @Failure 401 {object} contracts.ErrorResponse "Unauthorized - missing or invalid API key" +// @Failure 403 {object} contracts.ErrorResponse "Agent tokens cannot read the configuration document" // @Failure 500 {object} contracts.ErrorResponse "Failed to get configuration" // @Security ApiKeyAuth // @Security ApiKeyQuery @@ -4735,6 +5025,28 @@ func (s *Server) handleGetConfig(w http.ResponseWriter, r *http.Request) { return } + // Issues #1166 and #1167. This route was registered as a bare + // r.Get("/config", …) beside POST/PATCH twins that DO carry + // auth.ServerOpConfigWrite, so a scoped read-only agent token GET the + // whole document: every server name (the #1166 enumeration), and — with + // reveal_secret_headers on — every env value, header, oauth.client_secret, + // URL credential AND the global admin api_key. That last one is a + // privilege-escalation primitive: the scoped token reads the key that + // grants full admin on every route it is denied. + // + // This is an admin document, not a server list, so it is DENIED rather + // than filtered. Filtering it leaf by leaf is an open-ended allowlist + // problem (profiles[].servers enumerates names a second time, api_key, + // listen, docker_isolation.extra_args, registries, telemetry endpoints…) + // and it is a GET-then-POST-back document whose write twin binds + // mcpServers BY NAME — serving a truncated document that looks complete is + // the #1142 corruption shape. A denial has no allowlist to keep in sync. + // Agents that need server metadata have GET /api/v1/servers, which returns + // their scoped subset with richer runtime state than this document holds. + if !s.requireAdminRead(w, r, "Agent tokens cannot read the configuration document") { + return + } + // The DESIRED config — what the file holds and what the next start will // use. This endpoint backs the raw-JSON editor and every client that // round-trips the config through PUT/POST, so serving the running one would @@ -4768,11 +5080,12 @@ func (s *Server) handleGetConfig(w http.ResponseWriter, r *http.Request) { // the #1142 corruption. The two are one change. // // `reveal_secret_headers` opts out exactly as it does on GET - // /api/v1/servers and the /events payload; the flag is read off the RUNNING - // config, not the desired one, so a client cannot widen its own read by - // staging the flag and re-reading before the restart. + // /api/v1/servers; the flag is read off the RUNNING config, not the desired + // one, so a client cannot widen its own read by staging the flag and + // re-reading before the restart, and (#1167) it is ANDed with the caller's + // identity so only an authenticated admin can exercise the opt-out. published := cfg - if !s.revealSecretHeaders() { + if !s.revealSecrets(r.Context()) { published = oauth.RedactedConfig(cfg) if published == nil { // Fail CLOSED. Serving the unmasked config because the walk could @@ -4792,14 +5105,6 @@ func (s *Server) handleGetConfig(w http.ResponseWriter, r *http.Request) { s.writeSuccess(w, response) } -// revealSecretHeaders reports the operator's opt-out of secret masking. Read -// from the RUNNING config, which is the same source redactServerSecrets uses, -// so the two doors cannot disagree about whether this response is masked. -func (s *Server) revealSecretHeaders() bool { - cfg, err := s.controller.GetConfig() - return err == nil && cfg != nil && cfg.RevealSecretHeaders -} - // handleValidateConfig godoc // @Summary Validate configuration // @Description Validates a provided MCPProxy configuration without applying it. Checks for syntax errors, invalid server definitions, conflicting settings, and other configuration issues. @@ -5151,7 +5456,14 @@ func (s *Server) writeApplyConfigError(w http.ResponseWriter, r *http.Request, m // Copies rather than mutates: the SSE value is a map owned by the publisher, // and refreshing it in place would edit something another goroutine may hold. // Keys are preserved rather than dropped — clients read data.status.*. -func withLiveUpstreamStats(status interface{}, live map[string]interface{}) interface{} { +// +// ctx carries the caller so `message` can be scoped. That string is written by +// runtime.UpdatePhaseMessage as "Connected to %d/%d servers, retrying..." — a +// verbatim count of the WHOLE inventory, sitting one key away from the +// total_servers that #1166 recomputed precisely so it would stop being a count +// oracle. A scoped caller gets it blanked; `phase` (Ready/Loading/…) survives, +// carries no counts, and is what clients switch on. +func withLiveUpstreamStats(ctx context.Context, status interface{}, live map[string]interface{}) interface{} { snapshot, ok := status.(map[string]interface{}) if !ok || live == nil { return status @@ -5164,6 +5476,9 @@ func withLiveUpstreamStats(status interface{}, live map[string]interface{}) inte if totalTools, ok := live["total_tools"].(int); ok { refreshed["tools_indexed"] = totalTools } + if _, present := refreshed["message"]; present && auth.IsScopedCaller(ctx) { + refreshed["message"] = "" + } return refreshed } @@ -5740,6 +6055,7 @@ func getBool(m map[string]interface{}, key string) bool { // @Success 200 {object} contracts.GetSessionsResponse "Sessions retrieved successfully" // @Failure 400 {object} contracts.ErrorResponse "Invalid status filter" // @Failure 401 {object} contracts.ErrorResponse "Unauthorized - missing or invalid API key" +// @Failure 403 {object} contracts.ErrorResponse "Agent tokens cannot read MCP session history" // @Failure 405 {object} contracts.ErrorResponse "Method not allowed" // @Failure 500 {object} contracts.ErrorResponse "Failed to get sessions" // @Security ApiKeyAuth @@ -5751,6 +6067,10 @@ func (s *Server) handleGetSessions(w http.ResponseWriter, r *http.Request) { return } + if !s.requireAdminRead(w, r, sessionsDenialMessage) { + return + } + // Parse query parameters limitStr := r.URL.Query().Get("limit") offsetStr := r.URL.Query().Get("offset") @@ -5813,6 +6133,7 @@ func (s *Server) handleGetSessions(w http.ResponseWriter, r *http.Request) { // @Success 200 {object} contracts.GetSessionDetailResponse "Session details retrieved successfully" // @Failure 400 {object} contracts.ErrorResponse "Session ID required" // @Failure 401 {object} contracts.ErrorResponse "Unauthorized - missing or invalid API key" +// @Failure 403 {object} contracts.ErrorResponse "Agent tokens cannot read MCP session history" // @Failure 404 {object} contracts.ErrorResponse "Session not found" // @Failure 405 {object} contracts.ErrorResponse "Method not allowed" // @Security ApiKeyAuth @@ -5824,6 +6145,10 @@ func (s *Server) handleGetSessionDetail(w http.ResponseWriter, r *http.Request) return } + if !s.requireAdminRead(w, r, sessionsDenialMessage) { + return + } + id := chi.URLParam(r, "id") if id == "" { s.writeError(w, r, http.StatusBadRequest, "Session ID required") @@ -6273,6 +6598,11 @@ func (s *Server) handleAnnotationCoverage(w http.ResponseWriter, r *http.Request if name == "" { continue } + // #1166: same enumeration gate as GET /api/v1/tools — this route emits + // one row per server name. + if !canSeeServer(r.Context(), name) { + continue + } // #1064: a quarantined server's tools are not available, so they are // not part of the annotation-coverage denominator either. if quarantined, _ := srv["quarantined"].(bool); quarantined { diff --git a/internal/httpapi/sse_scope.go b/internal/httpapi/sse_scope.go new file mode 100644 index 000000000..a8632d193 --- /dev/null +++ b/internal/httpapi/sse_scope.go @@ -0,0 +1,211 @@ +package httpapi + +import ( + "context" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + internalRuntime "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" +) + +// The /events door, second half of #1166. +// +// Scoping the servers.changed EMBED (see renderEventPayloadForCaller) closed +// one window in one room. The event bus publishes twenty-odd types and most of +// them name a server in a scalar field, so a token scoped to `alpha` still +// learned, live, that `beta` exists, that it was just disabled, what its +// previous and new state were, when its OAuth refresh failed and what a +// security scan found on it. Observed on the wire by a token scoped to alpha, +// on a second subscriber, while an admin was watching the same stream: +// +// data: {"payload":{"action":"server_disabled","affected_entity":"beta", +// "changed_fields":["enabled"],"new_values":{"enabled":false}, +// "previous_values":{"enabled":true},"source":"api"},...} +// +// That is the same disclosure #1166 is about — the name, the state and the +// mutation history of a server outside the caller's scope — reaching the same +// door through a different event type. + +// eventServerIdentityFields are the runtime-event payload keys whose VALUE is +// the name of an upstream server. Enumerated from every publishEvent call site +// in internal/runtime (event_bus.go, tool_quarantine.go, lifecycle.go): +// +// server_name — activity.tool_call.{started,completed,rejected}, +// activity.policy_decision, activity.quarantine_change, +// activity.tool_quarantine_change, +// activity.prompt_get.completed, oauth.token_refreshed, +// oauth.refresh_failed, security.scan_settled, +// security.integrity_alert +// server — the servers.changed coalescer extras (enable_toggle, +// quarantine_toggle, restart, tools_changed, tools_approved, +// tools_blocked, server_connected, server_disconnected, +// server_state_changed, …) +// target_server — activity.internal_tool_call.completed +// affected_entity — activity.config_change +// +// A key counts only when its value is a NON-EMPTY string, so an event that +// carries no server name at all (config.saved's `path`, +// security.scanner_changed's `scanner_id`) is unaffected, and an empty name is +// not read as "a server called empty-string". +// +// Round 10 corrected what "unaffected" means for a frame that OUGHT to name a +// server and does not — that is undecidable, not harmless, and it is decided by +// identityBearingEventTypes below rather than by this list. +// +// This is a KEY list rather than a per-type table on purpose: a new event type +// that names a server through one of these keys — the shape every producer in +// the tree already uses — is scoped on the day it is added, instead of leaking +// until someone remembers to extend a table. A producer inventing a brand new +// key name is the one remaining gap, and that is what +// TestSSE_EveryRuntimeEventTypeIsClassified pins. +var eventServerIdentityFields = []string{ + "server_name", + "server", + "target_server", + "affected_entity", +} + +// adminConfigEventTypes carry no server identity at all, but they announce a +// mutation of the ADMIN CONFIG DOCUMENT: which file was reloaded or saved, and +// which secret was added, changed or deleted. +// +// They are dropped for a scoped caller for parity with the door beside them. +// This change made GET /api/v1/config a 403 for an agent token rather than a +// filtered document, because it is an admin document and not a server list; a +// live notification stream about that same document must not be the way back +// in. Nothing first-party is affected: the Web UI and the tray read this +// stream as admins. +var adminConfigEventTypes = map[internalRuntime.EventType]struct{}{ + internalRuntime.EventTypeConfigReloaded: {}, + internalRuntime.EventTypeConfigSaved: {}, + internalRuntime.EventTypeSecretsChanged: {}, +} + +// identityBearingEventTypes are the event types whose payload is ABOUT one +// upstream server. Membership is a property of the TYPE, not of whether the +// producer happened to fill the field in on this particular publish. +// +// #1166 round 10. The key scan below drops a frame only when an identity key +// holds a NON-EMPTY string, so an identity-bearing frame whose name is missing +// sailed through to a scoped subscriber intact. That is not hypothetical: +// Runtime.EmitActivityInternalToolCall OMITS `target_server` entirely when it is +// empty (event_bus.go), which is every built-in call that is not routed to one +// upstream — retrieve_tools, describe_tool, upstream_servers — and those frames +// carry `arguments` and `response`, i.e. the fleet-wide tool inventory the rest +// of this door exists to withhold. EmitActivityPromptGet and the tool-call +// emitters always SET `server_name` and would publish it as "" on the same +// paths. +// +// The safe default for "this frame is about a server and I cannot tell which" +// is to DROP it, for the same reason auth.RevealSecretsAllowed fails closed: +// an unidentifiable payload cannot be checked against a scope, so it cannot be +// shown to a scoped caller. Deciding by type rather than by populated value +// also means a producer that starts omitting a field — the exact regression +// shape above — cannot silently reopen the door. +// +// servers.changed is deliberately absent: it is the coalesced, state-carrying +// event that eventVisibleToCaller never drops and +// renderEventPayloadForCaller narrows instead. +// +// TestSSE_IdentityBearingEventTypesCoverEveryNamingProducer pins this set +// against the fixtures that exercise each type end-to-end, and +// TestSSE_EveryRuntimeEventTypeIsClassified pins those fixtures against the +// runtime's own constants — so a new event type must be classified in BOTH +// places before it ships. +var identityBearingEventTypes = map[internalRuntime.EventType]struct{}{ + internalRuntime.EventTypeActivityConfigChange: {}, + internalRuntime.EventTypeActivityInternalToolCall: {}, + internalRuntime.EventTypeActivityToolCallStarted: {}, + internalRuntime.EventTypeActivityToolCallCompleted: {}, + internalRuntime.EventTypeActivityToolCallRejected: {}, + internalRuntime.EventTypeActivityPolicyDecision: {}, + internalRuntime.EventTypeActivityQuarantineChange: {}, + internalRuntime.EventTypeActivityToolQuarantineChange: {}, + internalRuntime.EventTypeActivityPromptGet: {}, + internalRuntime.EventTypeOAuthTokenRefreshed: {}, + internalRuntime.EventTypeOAuthRefreshFailed: {}, + internalRuntime.EventTypeSecurityScanSettled: {}, + internalRuntime.EventTypeSecurityIntegrityAlert: {}, +} + +// eventVisibleToCaller reports whether a runtime event may be delivered to the +// SSE subscriber carried by ctx AT ALL. +// +// DROPPING the frame, rather than redacting the identifying field, is the +// deliberate choice: +// +// - These are audit notifications ABOUT one resource. Blanking the name +// leaves `{"action":"server_disabled","changed_fields":["enabled"], +// "previous_values":{"enabled":true}}` on the wire — the mutation, its +// shape and its timing, which is most of what the disclosure was — and the +// surviving frame is still an exact count oracle for how many servers the +// caller cannot see, one frame at a time, live. +// - No consumer depends on receiving every frame. The Web UI's authoritative +// mergeServers — the reason renderEventPayloadForCaller renders rather than +// edits — keys off servers.changed, which is never dropped, and the Web UI +// authenticates with the admin API key. The Swift tray reads the same +// stream over the unix socket, which bypasses the API key entirely +// (OS-level auth) and is never scoped either. A scoped subscriber is an +// mcp_agt_ token, and every frame dropped here is about a resource it +// cannot GET, list, or call. +// +// servers.changed is the ONE type never dropped, whatever its extras name. It +// is the state-carrying event and it is COALESCED last-write-wins: a window in +// which both alpha and beta changed publishes ONE event whose marker may name +// beta, so dropping on that name would strand the scoped subscriber's view of +// alpha until some unrelated change happened to fire. It is RENDERED instead — +// renderEventPayloadForCaller narrows the embed and removes the out-of-scope +// extras — which is the narrowing the coalescer's shape actually permits. +// +// An admin, or a request that carries no AuthContext at all, gets every event +// untouched (see auth.CanEnumerateServer for why absence is unrestricted). +func eventVisibleToCaller(ctx context.Context, evt internalRuntime.Event) bool { + if !auth.IsScopedCaller(ctx) { + return true + } + if evt.Type == internalRuntime.EventTypeServersChanged { + return true + } + if _, adminOnly := adminConfigEventTypes[evt.Type]; adminOnly { + return false + } + named := false + for _, key := range eventServerIdentityFields { + name, ok := evt.Payload[key].(string) + if !ok || name == "" { + continue + } + named = true + if !canSeeServer(ctx, name) { + return false + } + } + // The frame is about a server but names none: undecidable, so fail closed. + // See identityBearingEventTypes for why this is keyed on the TYPE and not + // on whether the producer happened to populate the field. + if _, bearsIdentity := identityBearingEventTypes[evt.Type]; bearsIdentity && !named { + return false + } + return true +} + +// isOutOfScopeIdentityField reports whether a payload key must be withheld from +// the caller carried by ctx because its value names a server that caller may +// not enumerate. +// +// It applies to the one event type eventVisibleToCaller never drops. Without +// it, a servers.changed whose embed was correctly narrowed to `alpha` still +// shipped `"server":"beta"` beside it in the coalescer extras — and on the +// notify-only path (ListServers failed upstream, so there is no embed to +// narrow) that extra WAS the entire disclosure. +func isOutOfScopeIdentityField(ctx context.Context, key string, value interface{}) bool { + name, ok := value.(string) + if !ok || name == "" { + return false + } + for _, identity := range eventServerIdentityFields { + if key == identity { + return !canSeeServer(ctx, name) + } + } + return false +} diff --git a/internal/httpapi/sse_scope_reveal_test.go b/internal/httpapi/sse_scope_reveal_test.go new file mode 100644 index 000000000..58c729648 --- /dev/null +++ b/internal/httpapi/sse_scope_reveal_test.go @@ -0,0 +1,532 @@ +package httpapi + +import ( + "bufio" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "regexp" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/oauth" + internalRuntime "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" +) + +// sseEvent is one decoded `event:`/`data:` pair off the wire. +type sseEvent struct { + Name string + Data map[string]interface{} +} + +// readSSEUntil consumes the live SSE body until `want` arrives or the deadline +// passes. It drives the real handler over a real http.Client against a real +// httptest.Server, so the flusher, the per-connection subscription and the +// production route table are all genuine. +func readSSEUntil(t *testing.T, body *bufio.Reader, want string, deadline time.Time) sseEvent { + t.Helper() + var name string + for time.Now().Before(deadline) { + line, err := body.ReadString('\n') + if err != nil { + t.Fatalf("SSE stream ended before %q arrived: %v", want, err) + } + line = strings.TrimRight(line, "\r\n") + switch { + case strings.HasPrefix(line, "event: "): + name = strings.TrimPrefix(line, "event: ") + case strings.HasPrefix(line, "data: "): + if name != want { + continue + } + var decoded map[string]interface{} + require.NoError(t, json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &decoded)) + return sseEvent{Name: name, Data: decoded} + } + } + t.Fatalf("timed out waiting for SSE event %q", want) + return sseEvent{} +} + +// readSSEFramesUntil consumes the live SSE body and returns EVERY frame it saw +// up to and including the first one `stop` accepts. +// +// readSSEUntil skips past frames it is not waiting for, which is fine for +// asserting the shape of an event that DID arrive and useless for asserting +// that one did not. Proving a drop needs the whole run of frames between a +// publish and a sentinel the subscriber is guaranteed to receive. +func readSSEFramesUntil(t *testing.T, body *bufio.Reader, deadline time.Time, stop func(sseEvent) bool) []sseEvent { + t.Helper() + var frames []sseEvent + var name string + for time.Now().Before(deadline) { + line, err := body.ReadString('\n') + if err != nil { + t.Fatalf("SSE stream ended before the sentinel arrived (frames so far: %d): %v", len(frames), err) + } + line = strings.TrimRight(line, "\r\n") + switch { + case strings.HasPrefix(line, "event: "): + name = strings.TrimPrefix(line, "event: ") + case strings.HasPrefix(line, "data: "): + var decoded map[string]interface{} + require.NoError(t, json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &decoded)) + frame := sseEvent{Name: name, Data: decoded} + frames = append(frames, frame) + if stop(frame) { + return frames + } + } + } + t.Fatalf("timed out waiting for the sentinel frame (frames so far: %d)", len(frames)) + return nil +} + +// sseIdentityEventFixtures is THE enumerated class this change closes: one +// event per runtime event type that carries a server identity to an SSE +// subscriber, each naming `server`, each with the payload shape its producer in +// internal/runtime actually builds. +// +// The first entry is the frame observed live on a scoped subscriber's stream +// while an admin watched the same stream and `beta` was disabled — the gap the +// servers.changed-only filter missed. +func sseIdentityEventFixtures(server string) []internalRuntime.Event { + now := time.Now() + evt := func(t internalRuntime.EventType, payload map[string]any) internalRuntime.Event { + return internalRuntime.Event{Type: t, Payload: payload, Timestamp: now} + } + return []internalRuntime.Event{ + // affected_entity + evt(internalRuntime.EventTypeActivityConfigChange, map[string]any{ + "action": "server_disabled", + "affected_entity": server, + "source": "api", + "changed_fields": []string{"enabled"}, + "previous_values": map[string]any{"enabled": true}, + "new_values": map[string]any{"enabled": false}, + }), + // target_server + evt(internalRuntime.EventTypeActivityInternalToolCall, map[string]any{ + "internal_tool_name": "call_tool_read", + "target_server": server, + "target_tool": "read_file", + "status": "ok", + }), + // server_name + evt(internalRuntime.EventTypeActivityToolCallStarted, map[string]any{"server_name": server, "tool_name": "t"}), + evt(internalRuntime.EventTypeActivityToolCallCompleted, map[string]any{"server_name": server, "tool_name": "t", "status": "ok"}), + evt(internalRuntime.EventTypeActivityToolCallRejected, map[string]any{"server_name": server, "tool_name": "t", "reason": "queue_full"}), + evt(internalRuntime.EventTypeActivityPolicyDecision, map[string]any{"server_name": server, "tool_name": "t", "decision": "blocked"}), + evt(internalRuntime.EventTypeActivityQuarantineChange, map[string]any{"server_name": server, "quarantined": true}), + evt(internalRuntime.EventTypeActivityToolQuarantineChange, map[string]any{"server_name": server, "tool_name": "t", "action": "pending"}), + evt(internalRuntime.EventTypeActivityPromptGet, map[string]any{"server_name": server, "prompt_name": "p", "status": "ok"}), + evt(internalRuntime.EventTypeOAuthTokenRefreshed, map[string]any{"server_name": server, "expires_at": now.Format(time.RFC3339)}), + evt(internalRuntime.EventTypeOAuthRefreshFailed, map[string]any{"server_name": server, "error": "re-auth required"}), + evt(internalRuntime.EventTypeSecurityScanSettled, map[string]any{"server_name": server, "status": "completed"}), + evt(internalRuntime.EventTypeSecurityIntegrityAlert, map[string]any{"server_name": server, "alert_type": "hash_mismatch", "action": "quarantined"}), + } +} + +// sseAdminConfigEventFixtures are the config-document events: no server +// identity, but a live notification about the document GET /api/v1/config now +// answers 403 for an agent token. +func sseAdminConfigEventFixtures() []internalRuntime.Event { + now := time.Now() + return []internalRuntime.Event{ + {Type: internalRuntime.EventTypeConfigSaved, Payload: map[string]any{"path": "/home/operator/.mcpproxy/mcp_config.json"}, Timestamp: now}, + {Type: internalRuntime.EventTypeConfigReloaded, Payload: map[string]any{"path": "/home/operator/.mcpproxy/mcp_config.json"}, Timestamp: now}, + {Type: internalRuntime.EventTypeSecretsChanged, Payload: map[string]any{"operation": "set", "secret_name": "keyring:beta/api_key"}, Timestamp: now}, + } +} + +func sseSubscribe(t *testing.T, base, apiKey string) (*bufio.Reader, func()) { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/events", http.NoBody) + require.NoError(t, err) + req.Header.Set("X-API-Key", apiKey) + resp, err := http.DefaultClient.Do(req) //nolint:bodyclose // closed by the returned cleanup + require.NoError(t, err) + require.Equal(t, http.StatusOK, resp.StatusCode) + return bufio.NewReader(resp.Body), func() { + cancel() + resp.Body.Close() + } +} + +// TestSSE_ServersChangedRenderedPerSubscriber is the sharpest test in this +// change. It runs an ADMIN and a SCOPED agent as CONCURRENT subscribers to one +// live /events stream and fans the same Event value (same map pointer, same +// slice backing array) out to both, exactly as runtime.publishEvent does. +// +// It pins three things at once: +// +// 1. #1166 — the scoped subscriber's servers.changed embed carries only the +// server it may enumerate, with `stats` recomputed. +// 2. #1167 — neither subscriber receives a raw credential; the bus masks this +// payload unconditionally because it has no caller to gate against. +// 3. The admin's view is NOT corrupted by the scoped subscriber's rendering. +// Under `-race` a shared-map write here would also be an unsynchronised +// write concurrent with the other goroutine's json.Marshal. +func TestSSE_ServersChangedRenderedPerSubscriber(t *testing.T) { + ctrl := &scopeController{cfg: scopeFixtureConfig(false), servers: scopeFixtureServers(), withManagement: true} + srv, token := scopedAgentServer(t, ctrl, []string{"alpha"}) + + ts := httptest.NewServer(srv) + defer ts.Close() + + adminBody, adminClose := sseSubscribe(t, ts.URL, scopeAdminAPIKey) + defer adminClose() + agentBody, agentClose := sseSubscribe(t, ts.URL, token) + defer agentClose() + + // Both handlers must have subscribed before the event is published, or one + // of them silently misses it and the test passes for the wrong reason. + require.Eventually(t, func() bool { return ctrl.subscriberCount() == 2 }, 5*time.Second, 20*time.Millisecond, + "precondition: both SSE connections must be subscribed to the event bus") + + // Build the payload exactly as runtime.buildServersChangedPayload does: + // masked ONCE, ONE map and ONE slice, shared by every subscriber. + shared := scopeFixtureServers() + for i := range shared { + oauth.RedactServerSecretFields(&shared[i]) + } + stats := &contracts.ServerStats{TotalServers: 2, ConnectedServers: 2, TotalTools: 10} + payload := map[string]any{"reason": "test", "servers": shared, "stats": stats} + evt := internalRuntime.Event{ + Type: internalRuntime.EventTypeServersChanged, + Payload: payload, + Timestamp: time.Now(), + } + + var wg sync.WaitGroup + var adminEvt, agentEvt sseEvent + deadline := time.Now().Add(10 * time.Second) + wg.Add(2) + go func() { defer wg.Done(); adminEvt = readSSEUntil(t, adminBody, "servers.changed", deadline) }() + go func() { defer wg.Done(); agentEvt = readSSEUntil(t, agentBody, "servers.changed", deadline) }() + + ctrl.publishToAll(evt) + wg.Wait() + + names := func(e sseEvent) []string { + inner, ok := e.Data["payload"].(map[string]interface{}) + require.True(t, ok, "no payload in %#v", e.Data) + raw, ok := inner["servers"].([]interface{}) + require.True(t, ok, "no servers embed in %#v", inner) + out := make([]string, 0, len(raw)) + for _, entry := range raw { + m, _ := entry.(map[string]interface{}) + n, _ := m["name"].(string) + out = append(out, n) + } + return out + } + + assert.ElementsMatch(t, []string{"alpha", "beta"}, names(adminEvt), + "the admin's servers.changed embed must be untouched by the scoped subscriber's rendering") + assert.Equal(t, []string{"alpha"}, names(agentEvt), + "a token scoped to alpha must not receive beta over /events") + + agentPayload := agentEvt.Data["payload"].(map[string]interface{}) + agentStats, ok := agentPayload["stats"].(map[string]interface{}) + require.True(t, ok, "no stats in %#v", agentPayload) + assert.Equal(t, float64(1), agentStats["total_servers"], "the embed's stats must narrow with the array") + + // The event bus's own map must be intact after both renders. + assert.Len(t, payload["servers"].([]contracts.Server), 2, + "the shared payload must never be edited in place") + assert.Equal(t, 2, stats.TotalServers, "the shared stats struct must never be edited in place") + + // ------------------------------------------------------------------ + // Part two: the rest of the class. + // + // servers.changed was one event type of twenty-odd. Live, with these same + // two concurrent subscribers, disabling `beta` delivered its name, its + // state and its mutation history to the scoped subscriber through + // activity.config_change — a different type, the same door. Every type + // that names a server is published here, in one burst, and the scoped + // subscriber must learn nothing about `beta` from any of them while the + // admin's stream stays complete. + // ------------------------------------------------------------------ + betaEvents := sseIdentityEventFixtures("beta") + adminOnly := sseAdminConfigEventFixtures() + // An event about the server the token MAY see: the filter must be a scope + // check, not a mute button. + alphaProbe := internalRuntime.Event{ + Type: internalRuntime.EventTypeActivityToolCallCompleted, + Payload: map[string]any{"server_name": "alpha", "tool_name": "alpha_probe", "status": "ok"}, + Timestamp: time.Now(), + } + // The sentinel both subscribers are guaranteed to receive, so "did not + // arrive" is a decision rather than a race. It carries the coalescer extra + // that named an out-of-scope server BESIDE a correctly narrowed embed. + sentinelServers := scopeFixtureServers() + for i := range sentinelServers { + oauth.RedactServerSecretFields(&sentinelServers[i]) + } + sentinelPayload := map[string]any{ + "reason": "sentinel", + "server": "beta", + "servers": sentinelServers, + "stats": &contracts.ServerStats{TotalServers: 2}, + } + sentinel := internalRuntime.Event{ + Type: internalRuntime.EventTypeServersChanged, + Payload: sentinelPayload, + Timestamp: time.Now(), + } + + isSentinel := func(e sseEvent) bool { + if e.Name != string(internalRuntime.EventTypeServersChanged) { + return false + } + inner, ok := e.Data["payload"].(map[string]interface{}) + return ok && inner["reason"] == "sentinel" + } + + var adminFrames, agentFrames []sseEvent + deadline = time.Now().Add(15 * time.Second) + wg.Add(2) + go func() { defer wg.Done(); adminFrames = readSSEFramesUntil(t, adminBody, deadline, isSentinel) }() + go func() { defer wg.Done(); agentFrames = readSSEFramesUntil(t, agentBody, deadline, isSentinel) }() + + for _, e := range betaEvents { + ctrl.publishToAll(e) + } + for _, e := range adminOnly { + ctrl.publishToAll(e) + } + ctrl.publishToAll(alphaProbe) + ctrl.publishToAll(sentinel) + wg.Wait() + + frameNames := func(frames []sseEvent) []string { + out := make([]string, 0, len(frames)) + for _, f := range frames { + out = append(out, f.Name) + } + return out + } + adminNames := frameNames(adminFrames) + agentNames := frameNames(agentFrames) + + // The admin's stream is complete: a per-subscriber drop must not remove + // the frame from the shared bus. + for _, e := range betaEvents { + assert.Contains(t, adminNames, string(e.Type), + "the admin subscriber must still receive every event about beta") + } + for _, e := range adminOnly { + assert.Contains(t, adminNames, string(e.Type), + "the admin subscriber must still receive the config-document events") + } + + // The scoped stream learns nothing about a server it may not enumerate — + // not the name, not the mutation, not the fact that a frame existed. + agentRaw, err := json.Marshal(agentFrames) + require.NoError(t, err) + assert.NotContains(t, string(agentRaw), "beta", + "a token scoped to alpha must not learn beta exists from ANY event type: %s", string(agentRaw)) + for _, e := range betaEvents { + // activity.tool_call.completed is deliberately excluded: the alpha + // probe below has the same TYPE, so absence-by-type would be an + // assertion about the wrong thing. The exact-sequence assertion that + // follows covers it, and covers it harder. + if e.Type == alphaProbe.Type { + continue + } + assert.NotContains(t, agentNames, string(e.Type), + "%s named beta and must be dropped for the scoped subscriber, not redacted into an empty-shell frame", e.Type) + } + for _, e := range adminOnly { + assert.NotContains(t, agentNames, string(e.Type), + "%s announces a mutation of the admin config document, which GET /api/v1/config answers 403 for this caller", e.Type) + } + + // The scoped subscriber's stream over this burst, exactly: the one event + // about the server it MAY see, then the sentinel. Nothing dropped that + // should have arrived, nothing arrived that should have been dropped — + // including a same-type frame about beta hiding behind the alpha probe. + assert.Equal(t, + []string{string(alphaProbe.Type), string(internalRuntime.EventTypeServersChanged)}, + agentNames, + "the scoped subscriber must receive exactly the alpha event and the sentinel") + assert.Contains(t, string(agentRaw), "alpha_probe", + "the filter must be a scope check, not a mute button") + + // The sentinel: the coalescer extra is removed for the scoped subscriber + // and intact for the admin. servers.changed is never dropped, because it + // is coalesced last-write-wins and dropping on the winning marker's name + // would strand the scoped subscriber's view of alpha. + sentinelPayloadOf := func(frames []sseEvent) map[string]interface{} { + last := frames[len(frames)-1] + require.True(t, isSentinel(last), "the last frame collected must be the sentinel") + return last.Data["payload"].(map[string]interface{}) + } + assert.Equal(t, "beta", sentinelPayloadOf(adminFrames)["server"], + "the admin's servers.changed extras must be untouched by the scoped subscriber's rendering") + assert.NotContains(t, sentinelPayloadOf(agentFrames), "server", + "the coalescer extra naming an out-of-scope server must be removed, not merely left beside a narrowed embed") + + // The bus's own map, once more, after the second burst. + assert.Equal(t, "beta", sentinelPayload["server"], + "the shared payload must never be edited in place") + assert.Len(t, sentinelPayload["servers"].([]contracts.Server), 2, + "the shared payload must never be edited in place") +} + +// TestSSE_ScopedSubscriberGetsNotifyOnlyEventWithoutTheName pins the notify-only +// path of servers.changed — the branch where ListServers failed upstream, so +// there is no embed to narrow and the coalescer extra IS the whole payload. +// +// The original filter returned that payload verbatim ("nothing to scope"), +// which is precisely when the name was the only thing in it. +func TestSSE_ScopedSubscriberGetsNotifyOnlyEventWithoutTheName(t *testing.T) { + ctrl := &scopeController{cfg: scopeFixtureConfig(false), servers: scopeFixtureServers(), withManagement: true} + srv, token := scopedAgentServer(t, ctrl, []string{"alpha"}) + + ts := httptest.NewServer(srv) + defer ts.Close() + + agentBody, agentClose := sseSubscribe(t, ts.URL, token) + defer agentClose() + require.Eventually(t, func() bool { return ctrl.subscriberCount() == 1 }, 5*time.Second, 20*time.Millisecond) + + payload := map[string]any{"reason": "server_disconnected", "server": "beta"} + ctrl.publishToAll(internalRuntime.Event{ + Type: internalRuntime.EventTypeServersChanged, + Payload: payload, + Timestamp: time.Now(), + }) + + got := readSSEUntil(t, agentBody, "servers.changed", time.Now().Add(10*time.Second)) + inner, ok := got.Data["payload"].(map[string]interface{}) + require.True(t, ok, "no payload in %#v", got.Data) + assert.Equal(t, "server_disconnected", inner["reason"], + "the notify-only event still reaches the scoped subscriber; only the name is withheld") + assert.NotContains(t, inner, "server", + "a notify-only servers.changed must not carry the name of a server the caller cannot enumerate") + assert.Equal(t, "beta", payload["server"], "the shared payload must never be edited in place") +} + +// TestSSE_EveryRuntimeEventTypeIsClassified reads the event-type constants out +// of internal/runtime/events.go and requires each one to be classified here. +// +// The fix scopes on payload KEY, not on event type, so a new producer that +// names a server through server_name / server / target_server / affected_entity +// is covered the day it lands. This test covers the other half: a new event +// type that invents a NEW key name would slip through silently, so adding one +// fails here until someone puts it in a list and, in doing so, looks at whether +// it names a server. +func TestSSE_EveryRuntimeEventTypeIsClassified(t *testing.T) { + // Types that carry a server identity, exercised end-to-end over the wire + // by TestSSE_ServersChangedRenderedPerSubscriber. + carriesServerIdentity := map[string]bool{} + for _, e := range sseIdentityEventFixtures("beta") { + carriesServerIdentity[string(e.Type)] = true + } + + // Types that carry NO server identity. Each is either rendered per + // subscriber (servers.changed), dropped as an admin config document, or + // delivered unchanged because there is nothing in it to scope. + noServerIdentity := map[string]string{ + "servers.changed": "rendered per subscriber, never dropped: coalesced last-write-wins", + "config.reloaded": "admin config document — dropped for a scoped caller", + "config.saved": "admin config document — dropped for a scoped caller", + "secrets.changed": "admin config document — dropped for a scoped caller", + "active_profile.changed": "profile slug only", + "upstream.prompts_changed": "nil payload", + "sensitive_data.detected": "activity id + severity counts, no server name", + "security.scanner_changed": "scanner plugin id, not a server", + "security.scan_started": "never published (no-op producer)", + "security.scan_progress": "never published (no-op producer)", + "security.scan_completed": "folded into security.scan_settled by the debouncer", + "security.scan_failed": "folded into security.scan_settled by the debouncer", + "activity.system.start": "version / listen address / config path, no server name", + "activity.system.stop": "reason / signal / uptime, no server name", + } + + src, err := os.ReadFile(filepath.Join("..", "runtime", "events.go")) + require.NoError(t, err, "the event-type constants must be readable for this guard to mean anything") + + re := regexp.MustCompile(`(?m)^\s*EventType\w+\s+EventType\s*=\s*"([^"]+)"`) + matches := re.FindAllStringSubmatch(string(src), -1) + require.NotEmpty(t, matches, "no event-type constants parsed — the guard would pass vacuously") + + for _, m := range matches { + name := m[1] + _, classifiedAsNoIdentity := noServerIdentity[name] + assert.True(t, carriesServerIdentity[name] || classifiedAsNoIdentity, + "runtime event %q is not classified for the /events door: add it to sseIdentityEventFixtures if it names a server "+ + "(server_name / server / target_server / affected_entity), or to noServerIdentity with the reason it cannot", name) + } +} + +// TestSSE_ScopedSubscriberGetsNoRawSecretEvenWithRevealOn pins the #1167 half +// of the /events door: the live reproduction showed a scoped read-only token +// receiving all four credential classes in the servers.changed payload. +// +// It also pins the notify-only DEGRADE for a caller who MAY see raw values. +// The bus masks unconditionally, so handing an admin the masked embed while +// GET /api/v1/servers hands them the real one would make the Web UI's +// authoritative merge flicker; the embed is dropped instead and the client +// re-fetches through the gated REST door. +func TestSSE_ScopedSubscriberGetsNoRawSecretEvenWithRevealOn(t *testing.T) { + ctrl := &scopeController{cfg: scopeFixtureConfig(true), servers: scopeFixtureServers(), withManagement: true} + srv, token := scopedAgentServer(t, ctrl, []string{"alpha"}) + + ts := httptest.NewServer(srv) + defer ts.Close() + + adminBody, adminClose := sseSubscribe(t, ts.URL, scopeAdminAPIKey) + defer adminClose() + agentBody, agentClose := sseSubscribe(t, ts.URL, token) + defer agentClose() + + require.Eventually(t, func() bool { return ctrl.subscriberCount() == 2 }, 5*time.Second, 20*time.Millisecond) + + shared := scopeFixtureServers() + for i := range shared { + oauth.RedactServerSecretFields(&shared[i]) + } + evt := internalRuntime.Event{ + Type: internalRuntime.EventTypeServersChanged, + Payload: map[string]any{"reason": "test", "servers": shared, "stats": &contracts.ServerStats{TotalServers: 2}}, + Timestamp: time.Now(), + } + + var wg sync.WaitGroup + var adminEvt, agentEvt sseEvent + deadline := time.Now().Add(10 * time.Second) + wg.Add(2) + go func() { defer wg.Done(); adminEvt = readSSEUntil(t, adminBody, "servers.changed", deadline) }() + go func() { defer wg.Done(); agentEvt = readSSEUntil(t, agentBody, "servers.changed", deadline) }() + + ctrl.publishToAll(evt) + wg.Wait() + + agentPayload := agentEvt.Data["payload"].(map[string]interface{}) + require.Contains(t, agentPayload, "servers", "precondition: the scoped subscriber still receives an embed") + agentRaw, err := json.Marshal(agentPayload) + require.NoError(t, err) + for _, secret := range []string{alphaHeaderSecret, alphaQuerySecret, betaArgvSecret, betaEnvSecret} { + assert.NotContains(t, string(agentRaw), secret, + "reveal_secret_headers must not open the /events door for a scoped token") + } + + adminPayload := adminEvt.Data["payload"].(map[string]interface{}) + assert.NotContains(t, adminPayload, "servers", + "a subscriber who MAY see raw values gets the notify-only shape, so it re-fetches through the gated REST door instead of merging a masked embed") + assert.NotContains(t, adminPayload, "stats") + assert.Equal(t, "test", adminPayload["reason"], "the notify-only degrade must keep the rest of the payload") +} diff --git a/internal/httpapi/status_live_stats_test.go b/internal/httpapi/status_live_stats_test.go index fb5f763a6..5e7796b3a 100644 --- a/internal/httpapi/status_live_stats_test.go +++ b/internal/httpapi/status_live_stats_test.go @@ -32,7 +32,7 @@ func liveStats() map[string]interface{} { } func TestWithLiveUpstreamStats_RefreshesTheStaleNestedFields(t *testing.T) { - out, ok := withLiveUpstreamStats(staleSnapshot(), liveStats()).(map[string]interface{}) + out, ok := withLiveUpstreamStats(t.Context(), staleSnapshot(), liveStats()).(map[string]interface{}) require.True(t, ok) assert.Equal(t, 13, out["tools_indexed"], "tools_indexed must track the live count") @@ -49,7 +49,7 @@ func TestWithLiveUpstreamStats_RefreshesTheStaleNestedFields(t *testing.T) { // Unrelated keys survive: clients read data.status.* and the fix must refresh, // not replace, the snapshot. func TestWithLiveUpstreamStats_PreservesEverythingElse(t *testing.T) { - out := withLiveUpstreamStats(staleSnapshot(), liveStats()).(map[string]interface{}) + out := withLiveUpstreamStats(t.Context(), staleSnapshot(), liveStats()).(map[string]interface{}) assert.Equal(t, true, out["running"]) assert.Equal(t, "Ready", out["phase"]) assert.Equal(t, "127.0.0.1:8080", out["listen_addr"]) @@ -59,7 +59,7 @@ func TestWithLiveUpstreamStats_PreservesEverythingElse(t *testing.T) { // it in place would mutate something another goroutine may still hold. func TestWithLiveUpstreamStats_DoesNotMutateItsInput(t *testing.T) { in := staleSnapshot() - withLiveUpstreamStats(in, liveStats()) + withLiveUpstreamStats(t.Context(), in, liveStats()) assert.Equal(t, 0, in["tools_indexed"], "the caller's snapshot must be untouched") original := in["upstream_stats"].(map[string]interface{}) @@ -68,18 +68,18 @@ func TestWithLiveUpstreamStats_DoesNotMutateItsInput(t *testing.T) { // Degenerate inputs must pass through rather than panic or blank the payload. func TestWithLiveUpstreamStats_PassesThroughWhenItCannotRefresh(t *testing.T) { - assert.Nil(t, withLiveUpstreamStats(nil, liveStats())) + assert.Nil(t, withLiveUpstreamStats(t.Context(), nil, liveStats())) // A non-map status (a future typed snapshot) is returned untouched. - assert.Equal(t, "opaque", withLiveUpstreamStats("opaque", liveStats())) + assert.Equal(t, "opaque", withLiveUpstreamStats(t.Context(), "opaque", liveStats())) // No live stats to apply: keep what we had rather than emit nothing. - unchanged := withLiveUpstreamStats(staleSnapshot(), nil).(map[string]interface{}) + unchanged := withLiveUpstreamStats(t.Context(), staleSnapshot(), nil).(map[string]interface{}) assert.Equal(t, 0, unchanged["tools_indexed"]) // total_tools absent or wrongly typed leaves tools_indexed alone rather // than zeroing it. - partial := withLiveUpstreamStats(staleSnapshot(), map[string]interface{}{"servers": map[string]interface{}{}}).(map[string]interface{}) + partial := withLiveUpstreamStats(t.Context(), staleSnapshot(), map[string]interface{}{"servers": map[string]interface{}{}}).(map[string]interface{}) assert.Equal(t, 0, partial["tools_indexed"]) assert.NotNil(t, partial["upstream_stats"]) } diff --git a/internal/httpapi/tokens.go b/internal/httpapi/tokens.go index 6e3c8de8d..fe0d22938 100644 --- a/internal/httpapi/tokens.go +++ b/internal/httpapi/tokens.go @@ -84,9 +84,28 @@ const defaultExpiryDuration = 30 * 24 * time.Hour // requireAdminAuth checks that the request is authenticated as admin (not an agent token). // Returns true if the request should proceed, false if a 403 was written. func (s *Server) requireAdminAuth(w http.ResponseWriter, r *http.Request) bool { + return s.requireAdminRead(w, r, "Agent tokens cannot manage tokens") +} + +// requireAdminRead is requireAdminAuth with a caller-supplied denial message, +// so a route outside token management does not 403 with "Agent tokens cannot +// manage tokens" (#1166 — GET /api/v1/config reuses this gate). +// +// It keys on !IsAdmin(), the SAME test auth.IsScopedCaller and +// (*Server).revealSecrets use. It used to key on Type == AuthTypeAgent, which +// is identical today — agent is the only non-admin type apiKeyAuthMiddleware +// installs on this mux — but would fail OPEN the moment a server-edition +// AuthTypeUser context reached it: a plain OAuth user is not an admin, yet +// would have passed an AuthTypeAgent-only test and read GET /api/v1/config. +// One mux must not carry two different definitions of "not admin". +// +// A request with NO AuthContext is still allowed through: that is the +// middleware's testing/bootstrap passthrough, and it must stay exactly as +// permissive as it is today (same rule as auth.CanEnumerateServer). +func (s *Server) requireAdminRead(w http.ResponseWriter, r *http.Request, message string) bool { ac := auth.AuthContextFromContext(r.Context()) - if ac != nil && ac.Type == auth.AuthTypeAgent { - s.writeError(w, r, http.StatusForbidden, "Agent tokens cannot manage tokens") + if ac != nil && !ac.IsAdmin() { + s.writeError(w, r, http.StatusForbidden, message) return false } return true diff --git a/internal/httpapi/tool_quarantine_test.go b/internal/httpapi/tool_quarantine_test.go index 5d1229476..4325cd1bc 100644 --- a/internal/httpapi/tool_quarantine_test.go +++ b/internal/httpapi/tool_quarantine_test.go @@ -52,6 +52,15 @@ func (m *mockToolQuarantineController) GetCurrentConfig() any { } } +// GetAllServers must report the server these tests address. The /servers/{id} +// subtree gate answers 404 to a scoped caller for a server that does not exist +// (#1166 follow-up), and baseController's default reports none — so without +// this the agent-token cases below would assert the tool-toggle gate's 403 +// against a request that never reached that gate. +func (m *mockToolQuarantineController) GetAllServers() ([]map[string]interface{}, error) { + return []map[string]interface{}{{"name": "github", "id": "github"}}, nil +} + func (m *mockToolQuarantineController) ListToolApprovals(serverName string) ([]*storage.ToolApprovalRecord, error) { var result []*storage.ToolApprovalRecord for _, a := range m.approvals { diff --git a/internal/management/diagnostics.go b/internal/management/diagnostics.go index 2988db17a..61f09e1ca 100644 --- a/internal/management/diagnostics.go +++ b/internal/management/diagnostics.go @@ -9,6 +9,7 @@ import ( "go.uber.org/zap" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" "github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts" "github.com/smart-mcp-proxy/mcpproxy-go/internal/health" @@ -64,14 +65,22 @@ func (s *service) Doctor(ctx context.Context) (*contracts.Diagnostics, error) { secretsMap := make(map[string][]string) // secret name -> list of servers using it // Issue #872: connect errors echoed into Health.Detail / last_error can - // carry the full upstream URL, including query-string credentials. Scrub - // them before they land in UpstreamErrors.ErrorMessage — parity with the - // /api/v1/servers list route — unless the operator opted out. + // carry the full upstream URL, including query-string credentials. + // + // Issue #1167: the gate is the SHARED predicate, not the flag alone. + // Doctor has exactly two callers in the tree - httpapi.handleGetDiagnostics + // (GET /api/v1/diagnostics, GET /api/v1/doctor) and mcp.handleDoctor - + // and BOTH pass a request context carrying an AuthContext, which this + // function already received as its first parameter and simply ignored in + // favour of the service's stored config. Neither door carries an admin + // gate of its own, so this was also the one site where the MCP surface + // leaked too. Evaluated once, here, so no branch below can re-derive it. + reveal := auth.RevealSecretsAllowed(ctx, s.config != nil && s.config.RevealSecretHeaders) redactErr := func(msg string) string { - if s.config != nil && s.config.RevealSecretHeaders { + if reveal { return msg } - // Round 8 finding 2: the ONE shared free-text rule — the same one + // Round 8 finding 2: the ONE shared free-text rule - the same one // oauth.RedactServerSecretFields applies to health.detail and last_error // on the REST/SSE door these strings are copied from. return oauth.ScrubUpstreamText(msg) @@ -82,9 +91,30 @@ func (s *service) Doctor(ctx context.Context) (*contracts.Diagnostics, error) { serverName := getStringFromMap(srvRaw, "name") lastError := getStringFromMap(srvRaw, "last_error") + // #1166: a server the caller may not enumerate contributes nothing to + // the diagnosis it is handed. Same predicate the REST list uses. + if !auth.CanEnumerateServer(ctx, serverName) { + continue + } + // Extract health status from server using helper that handles both // struct pointer (from GetAllServers) and map (from JSON) healthAction, healthDetail := extractHealthFromMap(srvRaw) + rawHealthDetail := healthDetail + + // Scrub the two free-text strings ONCE, here, rather than at each use + // site. Applying redactErr per branch is what let the ActionConfigure + // case below emit this same healthDetail RAW into + // contracts.OAuthIssue.Error while the ActionRestart case scrubbed it - + // serialized verbatim by writeSuccess on /api/v1/doctor and by + // mcp.handleDoctor, to any caller, with reveal_secret_headers OFF. + // health.ExtractOAuthConfigError returns last_error VERBATIM for the + // OAuth-config patterns, and last_error is the wrapped upstream connect + // error - exactly the free-form text ScrubUpstreamText exists for. + // Scrubbing at the top of the loop means a future health.Action case + // cannot reintroduce a raw copy. + healthDetail = redactErr(healthDetail) + lastError = redactErr(lastError) // Aggregate based on Health.Action switch healthAction { @@ -97,7 +127,7 @@ func (s *service) Doctor(ctx context.Context) (*contracts.Diagnostics, error) { } diag.UpstreamErrors = append(diag.UpstreamErrors, contracts.UpstreamError{ ServerName: serverName, - ErrorMessage: redactErr(healthDetail), + ErrorMessage: healthDetail, Timestamp: errorTime, }) @@ -110,7 +140,12 @@ func (s *service) Doctor(ctx context.Context) (*contracts.Diagnostics, error) { case health.ActionConfigure: // Extract parameter name from error - paramName := extractParameterName(healthDetail) + // The parameter NAME is read off the pre-scrub string: it is an + // OAuth parameter identifier ('resource', 'audience'), never a + // credential, and scrubbing can move the quote positions this + // scanner keys on. Only the free-text Error field below is + // narrowed, which is the field that carries the URL. + paramName := extractParameterName(rawHealthDetail) diag.OAuthIssues = append(diag.OAuthIssues, contracts.OAuthIssue{ ServerName: serverName, Issue: "OAuth provider parameter mismatch", @@ -141,7 +176,7 @@ func (s *service) Doctor(ctx context.Context) (*contracts.Diagnostics, error) { } diag.UpstreamErrors = append(diag.UpstreamErrors, contracts.UpstreamError{ ServerName: serverName, - ErrorMessage: redactErr(lastError), + ErrorMessage: lastError, Timestamp: errorTime, }) } diff --git a/internal/management/diagnostics_scope_reveal_test.go b/internal/management/diagnostics_scope_reveal_test.go new file mode 100644 index 000000000..5122e7998 --- /dev/null +++ b/internal/management/diagnostics_scope_reveal_test.go @@ -0,0 +1,163 @@ +package management + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap/zaptest" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/health" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/oauth" +) + +// oauthConfigDetail is the shape health.ExtractOAuthConfigError produces: it +// returns the wrapped upstream connect error VERBATIM whenever it matches an +// OAuth-config pattern, so the string carries the full URL — query credential +// and all — into contracts.OAuthIssue.Error. +const oauthConfigDetail = `failed to connect to https://provider.example.com/mcp?api_key=OAUTHISSUELEAK: ` + + `oauth config validation failed: requires 'resource' parameter` + +func doctorService(t *testing.T, cfg *config.Config, servers []map[string]interface{}) *service { + t.Helper() + rt := newMockRuntime() + rt.servers = servers + return NewService(rt, cfg, "", &mockEventEmitter{}, nil, zaptest.NewLogger(t).Sugar()).(*service) +} + +// TestDoctor_OAuthIssueErrorIsScrubbedForNonAdmin closes the hole the +// adversarial pass found in the #1167 design: redactErr was applied to only TWO +// of the fields Doctor builds out of healthDetail. The health.ActionConfigure +// branch emitted the SAME variable RAW into contracts.OAuthIssue.Error, which +// both /api/v1/doctor (writeSuccess) and the MCP handleDoctor serialize +// verbatim — and neither door carries an admin gate of its own. +// +// Note this leaked with reveal_secret_headers OFF as well as on, so the flag is +// deliberately false for the non-admin cases below. +func TestDoctor_OAuthIssueErrorIsScrubbedForNonAdmin(t *testing.T) { + servers := []map[string]interface{}{ + { + "name": "oauthy", + "last_error": oauthConfigDetail, + "health": map[string]interface{}{ + "level": "unhealthy", + "admin_state": "enabled", + "summary": "OAuth configuration error", + "detail": oauthConfigDetail, + "action": health.ActionConfigure, + }, + }, + } + + cases := []struct { + name string + ctx func() context.Context + }{ + {"no auth context", func() context.Context { return context.Background() }}, + {"anonymous back-compat admin", func() context.Context { + return auth.WithAuthContext(context.Background(), auth.AnonymousContext()) + }}, + {"scoped agent token", func() context.Context { + return auth.WithAuthContext(context.Background(), &auth.AuthContext{ + Type: auth.AuthTypeAgent, AllowedServers: []string{"*"}, + }) + }}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + // reveal is OFF here on purpose: this field bypassed the gate + // entirely, so it leaked at the default configuration. + svc := doctorService(t, &config.Config{}, servers) + diag, err := svc.Doctor(tc.ctx()) + require.NoError(t, err) + require.Len(t, diag.OAuthIssues, 1, "precondition: the ActionConfigure branch must have fired") + assert.Equal(t, oauth.ScrubUpstreamText(oauthConfigDetail), diag.OAuthIssues[0].Error, + "oauth_issues[].error must take the one shared free-text rule") + assert.NotContains(t, diag.OAuthIssues[0].Error, "OAUTHISSUELEAK") + // The parameter name is not a credential and must survive, or the + // scrub has broken the diagnosis it exists to deliver. + assert.Equal(t, []string{"resource"}, diag.OAuthIssues[0].MissingParams, + "the OAuth parameter name must still be extracted after scrubbing") + }) + } + + t.Run("authenticated admin with the opt-in still gets raw", func(t *testing.T) { + svc := doctorService(t, &config.Config{RevealSecretHeaders: true}, servers) + diag, err := svc.Doctor(auth.WithAuthContext(context.Background(), auth.AdminContext())) + require.NoError(t, err) + require.Len(t, diag.OAuthIssues, 1) + assert.Equal(t, oauthConfigDetail, diag.OAuthIssues[0].Error, + "the operator opt-in must still work for an authenticated admin") + }) +} + +// TestDoctor_RevealRequiresAuthenticatedAdmin pins the #1167 gate itself on the +// UpstreamErrors field. Equality against the shared scrub rule, not substring +// absence, so a nil/empty ErrorMessage cannot pass. +func TestDoctor_RevealRequiresAuthenticatedAdmin(t *testing.T) { + const msg = `Post "https://api.example.com/mcp?token=DOCTORLEAK": no such host` + servers := []map[string]interface{}{{"name": "leaky", "last_error": msg}} + cfg := func() *config.Config { return &config.Config{RevealSecretHeaders: true} } + + scrubbed := []struct { + name string + ctx context.Context + }{ + {"no auth context", context.Background()}, + {"anonymous", auth.WithAuthContext(context.Background(), auth.AnonymousContext())}, + {"scoped agent token", auth.WithAuthContext(context.Background(), &auth.AuthContext{ + Type: auth.AuthTypeAgent, AllowedServers: []string{"*"}, + })}, + } + for _, tc := range scrubbed { + t.Run(tc.name, func(t *testing.T) { + diag, err := doctorService(t, cfg(), servers).Doctor(tc.ctx) + require.NoError(t, err) + require.Len(t, diag.UpstreamErrors, 1) + assert.Equal(t, oauth.ScrubUpstreamText(msg), diag.UpstreamErrors[0].ErrorMessage, + "reveal_secret_headers alone must not hand a non-admin the raw error") + }) + } + + t.Run("authenticated admin", func(t *testing.T) { + diag, err := doctorService(t, cfg(), servers). + Doctor(auth.WithAuthContext(context.Background(), auth.AdminContext())) + require.NoError(t, err) + require.Len(t, diag.UpstreamErrors, 1) + assert.Equal(t, msg, diag.UpstreamErrors[0].ErrorMessage) + }) +} + +// TestDoctor_ScopedTokenSeesOnlyAllowedServers pins #1166 on the doctor +// aggregator, which enumerates every server with its last_error. +func TestDoctor_ScopedTokenSeesOnlyAllowedServers(t *testing.T) { + servers := []map[string]interface{}{ + {"name": "alpha", "last_error": "alpha is down"}, + {"name": "beta", "last_error": "beta is down"}, + } + + scoped := auth.WithAuthContext(context.Background(), &auth.AuthContext{ + Type: auth.AuthTypeAgent, AllowedServers: []string{"alpha"}, + }) + diag, err := doctorService(t, &config.Config{}, servers).Doctor(scoped) + require.NoError(t, err) + require.Len(t, diag.UpstreamErrors, 1, + "a token scoped to alpha must be diagnosed only about alpha") + assert.Equal(t, "alpha", diag.UpstreamErrors[0].ServerName) + + // Regression guard: an admin must still be diagnosed about everything. + adminDiag, err := doctorService(t, &config.Config{}, servers). + Doctor(auth.WithAuthContext(context.Background(), auth.AdminContext())) + require.NoError(t, err) + require.Len(t, adminDiag.UpstreamErrors, 2) + + // And so must a caller with no AuthContext (the in-process / bootstrap + // path), or every existing caller loses its diagnosis. + bareDiag, err := doctorService(t, &config.Config{}, servers).Doctor(context.Background()) + require.NoError(t, err) + require.Len(t, bareDiag.UpstreamErrors, 2) +} diff --git a/internal/management/diagnostics_test.go b/internal/management/diagnostics_test.go index 6383613e6..d033e5154 100644 --- a/internal/management/diagnostics_test.go +++ b/internal/management/diagnostics_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/require" "go.uber.org/zap/zaptest" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" ) @@ -136,6 +137,9 @@ func TestDoctorRedactsUpstreamErrorSecrets(t *testing.T) { assert.NotContains(t, diag.UpstreamErrors[0].ErrorMessage, "LEAKED123") }) + // #1167: the opt-out now also requires an authenticated admin identity on + // the ctx. This subtest used to pass context.Background(); it would + // otherwise flip to failing for the right reason. t.Run("reveal_secret_headers keeps the raw error", func(t *testing.T) { cfg := &config.Config{RevealSecretHeaders: true} emitter := &mockEventEmitter{} @@ -148,7 +152,7 @@ func TestDoctorRedactsUpstreamErrorSecrets(t *testing.T) { } svc := NewService(runtime, cfg, "", emitter, nil, logger) - diag, err := svc.Doctor(context.Background()) + diag, err := svc.Doctor(auth.WithAuthContext(context.Background(), auth.AdminContext())) require.NoError(t, err) require.Len(t, diag.UpstreamErrors, 1) diff --git a/internal/oauth/round8_doorscan_test.go b/internal/oauth/round8_doorscan_test.go index b6bb2b0f6..ab24d0ab0 100644 --- a/internal/oauth/round8_doorscan_test.go +++ b/internal/oauth/round8_doorscan_test.go @@ -62,10 +62,12 @@ var rawServerLeafDoors = map[string]string{ "oauth.RedactServerSecretFields.", // --- redacted at the return of the same function --- - "internal/server/server.go:(m).GetUpstreamStats": "the per-server entries are built raw and the whole map is " + - "handed to oauth.RedactUpstreamStats at every return, reveal-gated. Issue #1148 round 8: this is the " + + "internal/server/server.go:upstreamStatsFromSnapshot": "the per-server entries are built raw and the whole map is " + + "handed to oauth.RedactUpstreamStats at the single return, reveal-gated. Issue #1148 round 8: this is the " + "upstream_stats implementation that actually runs (the StateView path); round 4 masked only the " + - "upstream.Manager fallback.", + "upstream.Manager fallback. Issue #1166 extracted this body out of (m).GetUpstreamStats so the entry " + + "shape is reachable from a test without standing up a Supervisor; the redaction moved with it, and " + + "GetUpstreamStats now pins reveal=false before delegating here (issue #1167).", // --- already-redacted input; the function holds no config --- "cmd/mcpproxy-tray/internal/api/adapter.go:(m).GetAllServers": "re-shapes the payload the tray fetched from " + diff --git a/internal/runtime/event_bus.go b/internal/runtime/event_bus.go index 02dbf4b9b..337e312e6 100644 --- a/internal/runtime/event_bus.go +++ b/internal/runtime/event_bus.go @@ -319,7 +319,26 @@ func (r *Runtime) enrichServersWithQuarantineStats(servers []contracts.Server) { } // redactServerSecrets masks the secret-bearing fields of every server in an SSE -// payload unless the loaded config opts out via reveal_secret_headers: true. +// payload. ALWAYS - there is no opt-out on this door. +// +// Issue #1167. A payload produced ONCE for a mixed-privilege audience is +// masked for the least-privileged member of that audience. This function has +// no caller to gate against by construction: publishEvent fans one Event value +// out to every subscriber channel under eventMu, and the subscribers are one +// SSE connection per HTTP client (each with its own privilege level) plus +// three in-process consumers. There is no request context at build time, and +// the payload map and the []contracts.Server it holds are shared, so no +// consumer may re-render it in place either. Emitting raw here and trusting +// each consumer to mask is the fail-open shape #1167 is made of - it is how a +// scoped, read-only agent token subscribed to /events and received every +// server Authorization header, URL credential, argv secret and env secret in +// the clear. +// +// The cost of that, for an operator who deliberately set the opt-in flag, is +// paid at the per-subscriber seam instead: httpapi.renderEventPayloadForCaller +// degrades this embed to the notify-only shape for a caller who MAY see raw +// values, so the client re-fetches through the gated REST door and the two +// doors stay in parity rather than flickering masked/raw. // // The field list AND the rules are oauth.RedactServerSecretFields — the same // function the REST list path calls, applying the same oauth.LiveRedaction the @@ -333,10 +352,6 @@ func (r *Runtime) enrichServersWithQuarantineStats(servers []contracts.Server) { // as authoritative, so a masked-vs-plaintext mismatch between the two would // flicker on every delivery. func (r *Runtime) redactServerSecrets(servers []contracts.Server) { - cfg := r.Config() - if cfg != nil && cfg.RevealSecretHeaders { - return - } for i := range servers { oauth.RedactServerSecretFields(&servers[i]) } diff --git a/internal/runtime/event_bus_payload_test.go b/internal/runtime/event_bus_payload_test.go index f38b1f155..12c6c8c44 100644 --- a/internal/runtime/event_bus_payload_test.go +++ b/internal/runtime/event_bus_payload_test.go @@ -3,6 +3,7 @@ package runtime import ( "context" "errors" + "fmt" "sync/atomic" "testing" "time" @@ -13,6 +14,7 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" "github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/oauth" ) // fakeServersLister is a minimal implementation of the serversLister interface @@ -295,3 +297,60 @@ func TestBuildServersChangedPayload_HonoursCancelledParentCtx(t *testing.T) { _, hasServers := evt.Payload["servers"] assert.False(t, hasServers, "no servers key when ListServers errors") } + +// TestEmitServersChanged_MasksEvenWhenRevealSet pins the Class-B rule of issue +// #1167: this producer has NO caller to gate against. +// +// publishEvent fans one Event value out to every subscriber channel — one SSE +// connection per HTTP client, each with its own privilege level, plus three +// in-process consumers — so there is no request context at build time and the +// payload map and its []contracts.Server are shared. A payload produced once +// for a mixed-privilege audience is masked for the LEAST-privileged member of +// that audience, always. Honouring reveal_secret_headers here is what let a +// scoped read-only agent token subscribe to /events and receive every server's +// raw Authorization header, URL credential, argv secret and env secret. +// +// The parity cost for an operator who set the flag is paid at the +// per-subscriber seam instead (httpapi.renderEventPayloadForCaller degrades +// the embed to notify-only for a caller who may see raw values), not here. +func TestEmitServersChanged_MasksEvenWhenRevealSet(t *testing.T) { + servers := []*contracts.Server{ + { + Name: "alpha", + URL: "https://api.example.com/mcp?apikey=supersecretkey123", + Headers: map[string]string{"Authorization": "Bearer secret-token-value"}, + Env: map[string]string{"GITHUB_TOKEN": "ghp_fake_secret_value_1234"}, + }, + } + stats := &contracts.ServerStats{TotalServers: 1} + + rt := newPayloadTestRuntime(t, &fakeServersLister{servers: servers, stats: stats}) + rt.cfg = &config.Config{RevealSecretHeaders: true} + ch := rt.SubscribeEvents() + defer rt.UnsubscribeEvents(ch) + + rt.emitServersChanged("reveal-has-no-effect-here", nil) + + evt := receiveServersChanged(t, ch) + gotServers, ok := evt.Payload["servers"].([]contracts.Server) + require.True(t, ok) + require.Len(t, gotServers, 1) + require.Equal(t, "alpha", gotServers[0].Name, "precondition: the fixture reached the payload") + + // Equality against the shared rule, not substring absence, so a dropped + // field cannot pass vacuously. + expected := contracts.Server{ + Name: "alpha", + URL: "https://api.example.com/mcp?apikey=supersecretkey123", + Headers: map[string]string{"Authorization": "Bearer secret-token-value"}, + Env: map[string]string{"GITHUB_TOKEN": "ghp_fake_secret_value_1234"}, + } + oauth.RedactServerSecretFields(&expected) + + assert.Equal(t, expected.Headers, gotServers[0].Headers, + "reveal_secret_headers must have no effect on the fan-out payload") + assert.Equal(t, expected.URL, gotServers[0].URL) + assert.Equal(t, expected.Env, gotServers[0].Env) + assert.NotContains(t, fmt.Sprint(evt.Payload), "supersecretkey123") + assert.NotContains(t, fmt.Sprint(evt.Payload), "secret-token-value") +} diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index f0d3b5fa7..ec5da3b92 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -1114,8 +1114,14 @@ func convertToolAnnotations(a *config.ToolAnnotations) *contracts.ToolAnnotation } } -// GetToolCalls retrieves tool call history with pagination -func (r *Runtime) GetToolCalls(limit, offset int) ([]*contracts.ToolCallRecord, int, error) { +// GetToolCalls retrieves tool call history with pagination. +// +// scope restricts the result to a set of server names (nil = unrestricted, +// #1166 follow-up). It is applied BEFORE pagination so `total`, the page and +// the offset all describe the same record set — a post-filter in the handler +// would shrink the page while the total kept counting the hidden records, which +// is both a broken pager and an exact oracle for what was hidden. +func (r *Runtime) GetToolCalls(limit, offset int, scope storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error) { r.mu.RLock() defer r.mu.RUnlock() @@ -1146,6 +1152,17 @@ func (r *Runtime) GetToolCalls(limit, offset int) ([]*contracts.ToolCallRecord, allCalls = append(allCalls, codeExecCalls...) } + // Entitlement filter, before the sort and before pagination. + if scope != nil { + visible := make([]*storage.ToolCallRecord, 0, len(allCalls)) + for _, call := range allCalls { + if call != nil && scope.Allows(call.ServerName) { + visible = append(visible, call) + } + } + allCalls = visible + } + // Sort by timestamp (most recent first) sort.Slice(allCalls, func(i, j int) bool { return allCalls[i].Timestamp.After(allCalls[j].Timestamp) @@ -1424,12 +1441,16 @@ func (r *Runtime) ReplayToolCall(ctx context.Context, id string, arguments map[s }, nil } -// GetToolCallsBySession returns tool calls filtered by session ID -func (r *Runtime) GetToolCallsBySession(sessionID string, limit, offset int) ([]*contracts.ToolCallRecord, int, error) { +// GetToolCallsBySession returns tool calls filtered by session ID. +// +// scope restricts the result to a set of server names (nil = unrestricted). It +// is pushed down into storage so it lands in the same pass that computes +// `total` (#1166 follow-up). +func (r *Runtime) GetToolCallsBySession(sessionID string, limit, offset int, scope storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error) { r.mu.RLock() defer r.mu.RUnlock() - storageRecords, total, err := r.storageManager.GetToolCallsBySession(sessionID, limit, offset) + storageRecords, total, err := r.storageManager.GetToolCallsBySession(sessionID, limit, offset, scope) if err != nil { return nil, 0, fmt.Errorf("failed to get tool calls by session: %w", err) } diff --git a/internal/security/scanner/types.go b/internal/security/scanner/types.go index cf33154f6..e5c9a4b92 100644 --- a/internal/security/scanner/types.go +++ b/internal/security/scanner/types.go @@ -2,6 +2,7 @@ package scanner import ( "encoding/json" + "strings" "time" "github.com/smart-mcp-proxy/mcpproxy-go/internal/security/detect" @@ -79,9 +80,12 @@ type ScannerPlugin struct { // source/Docker (MCP-2082). InProcess bool `json:"in_process,omitempty"` // Runtime state (not in registry) - Status string `json:"status"` // available, installed, configured, error - InstalledAt time.Time `json:"installed_at,omitempty"` - ConfiguredEnv map[string]string `json:"configured_env,omitempty"` // Set env values (secrets redacted in API) + Status string `json:"status"` // available, installed, configured, error + InstalledAt time.Time `json:"installed_at,omitempty"` + // ConfiguredEnv holds the env values an operator set for this scanner — + // vendor API keys, in practice. RedactedForAPI() is what makes the "secrets + // redacted in API" promise true; call it on every serialization path. + ConfiguredEnv map[string]string `json:"configured_env,omitempty"` // Set env values (secrets redacted in API — see RedactedForAPI) ImageOverride string `json:"image_override,omitempty"` // User override for DockerImage LastUsedAt time.Time `json:"last_used_at,omitempty"` ErrorMsg string `json:"error_message,omitempty"` @@ -122,6 +126,54 @@ func copyEnv(env map[string]string) map[string]string { return out } +// RedactedEnvValue replaces a literal scanner env value on every API +// serialization path. It is a fixed sentinel rather than a partial mask so it +// carries no information about the secret's length or shape, and it is TRUTHY +// so a client can still tell that the variable is set — which is all the Web UI +// ever needed from the value (it renders "(configured)" and gates the "needs an +// API key" badge on presence). +const RedactedEnvValue = "***" + +// RedactedForAPI returns a copy of the plugin safe to serialize to an API +// client: every literal ConfiguredEnv value is replaced by RedactedEnvValue. +// +// #1166 round 10, P3. GET /api/v1/security/scanners and +// /security/scanners/{id}/status marshalled this struct straight out, so the +// vendor API keys an operator had typed into the scanner config dialog came +// back down the wire in the clear — while the field's own comment claimed they +// were "redacted in API". Redacting HERE, at the type, rather than at each +// handler is what keeps that comment true for a serialization path added later. +// +// A `${keyring:...}` value is preserved verbatim: it is a REFERENCE to a +// secret, not the secret, and the UI reads it to distinguish "stored in your +// keychain" from "stored in the config file". Preserving it also keeps the +// save path honest — the dialog re-submits only values that are neither a +// keyring reference nor the redaction sentinel, so a round-trip through this +// function can never overwrite a real secret with its own mask. +func (s *ScannerPlugin) RedactedForAPI() *ScannerPlugin { + if s == nil { + return nil + } + cp := s.clone() + for k, v := range cp.ConfiguredEnv { + if v == "" || strings.HasPrefix(v, "${keyring:") { + continue + } + cp.ConfiguredEnv[k] = RedactedEnvValue + } + return cp +} + +// RedactScannersForAPI applies RedactedForAPI to a whole list, allocating a new +// slice so the registry's own records are never touched. +func RedactScannersForAPI(list []*ScannerPlugin) []*ScannerPlugin { + out := make([]*ScannerPlugin, 0, len(list)) + for _, sc := range list { + out = append(out, sc.RedactedForAPI()) + } + return out +} + // EffectiveImage returns ImageOverride if set, otherwise DockerImage. func (s *ScannerPlugin) EffectiveImage() string { if s.ImageOverride != "" { diff --git a/internal/server/mcp.go b/internal/server/mcp.go index d1439a727..3d16642ff 100644 --- a/internal/server/mcp.go +++ b/internal/server/mcp.go @@ -3789,8 +3789,13 @@ func (p *MCPProxyServer) handleListUpstreams(ctx context.Context) (*mcp.CallTool // that endpoint got the raw values the flag was meant to hand the // operator. CanRevealSecrets is nil-safe: an in-process/stdio caller with // no context gets masked values rather than admin-by-absence. - revealHeaders := p.config != nil && p.config.RevealSecretHeaders && - auth.AuthContextFromContext(ctx).CanRevealSecrets() + // + // Issue #1167 moved the expression itself into auth.RevealSecretsAllowed. + // This door was already correct; five REST/SSE/doctor doors checked the + // flag alone. Rather than leave the right answer written out in one place + // and the wrong one in five, every door now reads it from the shared + // predicate, so they cannot drift apart again. + revealHeaders := auth.RevealSecretsAllowed(ctx, p.config != nil && p.config.RevealSecretHeaders) for i, server := range servers { // The secret-bearing fields are sourced from redactedServerView — the // shared walker over the config's own JSON — rather than from a diff --git a/internal/server/server.go b/internal/server/server.go index beb8e465a..9b36e46cb 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -33,6 +33,7 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/observability" "github.com/smart-mcp-proxy/mcpproxy-go/internal/profile" "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime/stateview" "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" "github.com/smart-mcp-proxy/mcpproxy-go/internal/security" "github.com/smart-mcp-proxy/mcpproxy-go/internal/security/scanner" @@ -1192,139 +1193,165 @@ func (s *Server) SuggestAlternateListen(baseAddr string) (string, error) { return findAvailableListenAddress(baseAddr, defaultPortSuggestionAttempts) } -// GetUpstreamStats returns statistics about upstream servers -func (s *Server) GetUpstreamStats() map[string]interface{} { - // Issue #1148, round 8. This is the SECOND implementation of - // `upstream_stats` and the one that actually runs: round 4 masked - // upstream.Manager.GetStats, which is only the fallback below, so the - // StateView path served `url` and `last_error` verbatim on - // GET /api/v1/status and on every SSE status event. Both implementations - // now hand their map to the one shared rule at this boundary. - reveal := false - if cfg, err := s.GetConfig(); err == nil && cfg != nil { - reveal = cfg.RevealSecretHeaders - } - - if supervisor := s.runtime.Supervisor(); supervisor != nil { - if view := supervisor.StateView(); view != nil { - snapshot := view.Snapshot() - - connectedCount := 0 - connectingCount := 0 - quarantinedCount := 0 - totalTools := 0 +// upstreamStatsFromSnapshot builds the `upstream_stats` payload from a +// StateView snapshot. +// +// Split out of GetUpstreamStats so the entry shape both #1064 (tool_count +// zeroing) and #1166 (the per-entry `quarantined` bit every consumer recomputes +// the sibling scalar from) depend on is reachable from a test without standing +// up a supervisor. The caller supplies `reveal`; see GetUpstreamStats for why it +// is unconditionally false there. +func upstreamStatsFromSnapshot(snapshot *stateview.ServerStatusSnapshot, reveal bool) map[string]interface{} { + connectedCount := 0 + connectingCount := 0 + quarantinedCount := 0 + totalTools := 0 + + serverStats := make(map[string]interface{}, len(snapshot.Servers)) + + for name, status := range snapshot.Servers { + if status == nil { + continue + } - serverStats := make(map[string]interface{}, len(snapshot.Servers)) + var connInfo *types.ConnectionInfo + if meta, ok := status.Metadata["connection_info"]; ok { + if info, ok := meta.(*types.ConnectionInfo); ok { + connInfo = info + } + } - for name, status := range snapshot.Servers { - if status == nil { - continue + state := status.State + if connInfo != nil { + state = connInfo.State.String() + } + if state == "" { + if status.Enabled { + if status.Connected { + state = "Ready" + } else { + state = "Disconnected" } + } else { + state = "Disabled" + } + } - var connInfo *types.ConnectionInfo - if meta, ok := status.Metadata["connection_info"]; ok { - if info, ok := meta.(*types.ConnectionInfo); ok { - connInfo = info - } - } + connecting := strings.EqualFold(state, "connecting") - state := status.State - if connInfo != nil { - state = connInfo.State.String() - } - if state == "" { - if status.Enabled { - if status.Connected { - state = "Ready" - } else { - state = "Disconnected" - } - } else { - state = "Disabled" - } - } + // #1064: a quarantined server contributes no available tools. + // tool_count is therefore ALREADY zeroed here rather than left + // for a consumer to gate — `quarantined` below says why it is + // zero, it does not license a second subtraction. + availableToolCount := status.ToolCount + if status.Quarantined { + availableToolCount = 0 + } - connecting := strings.EqualFold(state, "connecting") + entry := map[string]interface{}{ + "state": state, + "connected": status.Connected, + "connecting": connecting, + "retry_count": status.RetryCount, + "should_retry": false, + "name": status.Name, + "tool_count": availableToolCount, + // Per-entry quarantine bit. Every consumer that recomputes + // the sibling `quarantined_servers` scalar from the entries + // — httpapi.filterUpstreamStatsServers on the scoped-caller + // path, contracts.ConvertUpstreamStatsToServerStats — reads + // exactly this key. Neither producer emitted it, so both + // counted 0 unconditionally and a scoped caller's security + // surface read falsely clean even when one of its OWN + // allowed servers was quarantined. + "quarantined": status.Quarantined, + } - // #1064: a quarantined server contributes no available tools. - // This entry map carries no enabled/quarantined key, so - // downstream consumers (contracts.ConvertUpstreamStatsToServerStats) - // cannot gate on it -- the value has to be zeroed here. - availableToolCount := status.ToolCount - if status.Quarantined { - availableToolCount = 0 - } + if entry["name"] == "" { + entry["name"] = name + } - entry := map[string]interface{}{ - "state": state, - "connected": status.Connected, - "connecting": connecting, - "retry_count": status.RetryCount, - "should_retry": false, - "name": status.Name, - "tool_count": availableToolCount, - } + if status.Config != nil { + if status.Config.URL != "" { + entry["url"] = status.Config.URL + } + if status.Config.Protocol != "" { + entry["protocol"] = status.Config.Protocol + } + } - if entry["name"] == "" { - entry["name"] = name - } + if connInfo != nil { + entry["retry_count"] = connInfo.RetryCount + if connInfo.LastError != nil { + entry["last_error"] = connInfo.LastError.Error() + } + if !connInfo.LastRetryTime.IsZero() { + entry["last_retry_time"] = connInfo.LastRetryTime + } + if connInfo.ServerName != "" { + entry["server_name"] = connInfo.ServerName + } + if connInfo.ServerVersion != "" { + entry["server_version"] = connInfo.ServerVersion + } + } else { + if status.LastError != "" { + entry["last_error"] = status.LastError + } + if status.LastErrorTime != nil { + entry["last_retry_time"] = *status.LastErrorTime + } + } - if status.Config != nil { - if status.Config.URL != "" { - entry["url"] = status.Config.URL - } - if status.Config.Protocol != "" { - entry["protocol"] = status.Config.Protocol - } - } + if status.Connected { + connectedCount++ + } + if connecting { + connectingCount++ + } + if status.Quarantined { + quarantinedCount++ + } + if config.ServerContributesTools(status.Enabled, status.Quarantined) { + totalTools += status.ToolCount + } - if connInfo != nil { - entry["retry_count"] = connInfo.RetryCount - if connInfo.LastError != nil { - entry["last_error"] = connInfo.LastError.Error() - } - if !connInfo.LastRetryTime.IsZero() { - entry["last_retry_time"] = connInfo.LastRetryTime - } - if connInfo.ServerName != "" { - entry["server_name"] = connInfo.ServerName - } - if connInfo.ServerVersion != "" { - entry["server_version"] = connInfo.ServerVersion - } - } else { - if status.LastError != "" { - entry["last_error"] = status.LastError - } - if status.LastErrorTime != nil { - entry["last_retry_time"] = *status.LastErrorTime - } - } + serverStats[name] = entry + } - if status.Connected { - connectedCount++ - } - if connecting { - connectingCount++ - } - if status.Quarantined { - quarantinedCount++ - } - if config.ServerContributesTools(status.Enabled, status.Quarantined) { - totalTools += status.ToolCount - } + return oauth.RedactUpstreamStats(map[string]interface{}{ + "connected_servers": connectedCount, + "connecting_servers": connectingCount, + "quarantined_servers": quarantinedCount, + "total_servers": len(snapshot.Servers), + "servers": serverStats, + "total_tools": totalTools, + }, reveal) +} - serverStats[name] = entry - } +// GetUpstreamStats returns statistics about upstream servers +func (s *Server) GetUpstreamStats() map[string]interface{} { + // Issue #1148, round 8. This is the SECOND implementation of + // `upstream_stats` and the one that actually runs: round 4 masked + // upstream.Manager.GetStats, which is only the fallback below, so the + // StateView path served `url` and `last_error` verbatim on + // GET /api/v1/status and on every SSE status event. Both implementations + // now hand their map to the one shared rule at this boundary. + // + // Issue #1167: the reveal_secret_headers opt-out is GONE from this + // producer. GetUpstreamStats takes no ctx and its caller + // httpapi.handleGetStatus used to discard the *http.Request outright, so + // there is no caller here to AND the flag with - and with the flag on, a + // scoped agent token polling /api/v1/status received every server's raw + // url and last_error. Masking unconditionally is the only shape that + // cannot fail open. An operator with the flag on loses nothing they + // cannot read on a gated door: GET /api/v1/servers and GET /api/v1/config + // still hand an authenticated admin the real values. + const reveal = false - return oauth.RedactUpstreamStats(map[string]interface{}{ - "connected_servers": connectedCount, - "connecting_servers": connectingCount, - "quarantined_servers": quarantinedCount, - "total_servers": len(snapshot.Servers), - "servers": serverStats, - "total_tools": totalTools, - }, reveal) + if supervisor := s.runtime.Supervisor(); supervisor != nil { + if view := supervisor.StateView(); view != nil { + return upstreamStatsFromSnapshot(view.Snapshot(), reveal) } } @@ -3521,9 +3548,10 @@ func (s *Server) GetCurrentConfig() interface{} { return s.runtime.GetCurrentConfig() } -// GetToolCalls retrieves tool call history with pagination -func (s *Server) GetToolCalls(limit, offset int) ([]*contracts.ToolCallRecord, int, error) { - return s.runtime.GetToolCalls(limit, offset) +// GetToolCalls retrieves tool call history with pagination. scope restricts the +// result to a set of server names (nil = unrestricted). +func (s *Server) GetToolCalls(limit, offset int, scope storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error) { + return s.runtime.GetToolCalls(limit, offset, scope) } // GetToolCallByID retrieves a single tool call by ID @@ -3543,9 +3571,10 @@ func (s *Server) ReplayToolCall(ctx context.Context, id string, arguments map[st return s.runtime.ReplayToolCall(ctx, id, arguments) } -// GetToolCallsBySession retrieves tool calls filtered by session ID -func (s *Server) GetToolCallsBySession(sessionID string, limit, offset int) ([]*contracts.ToolCallRecord, int, error) { - return s.runtime.GetToolCallsBySession(sessionID, limit, offset) +// GetToolCallsBySession retrieves tool calls filtered by session ID. scope +// restricts the result to a set of server names (nil = unrestricted). +func (s *Server) GetToolCallsBySession(sessionID string, limit, offset int, scope storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error) { + return s.runtime.GetToolCallsBySession(sessionID, limit, offset, scope) } // GetRecentSessions retrieves recent MCP sessions, optionally filtered by diff --git a/internal/server/upstream_stats_quarantine_test.go b/internal/server/upstream_stats_quarantine_test.go new file mode 100644 index 000000000..4ed340142 --- /dev/null +++ b/internal/server/upstream_stats_quarantine_test.go @@ -0,0 +1,58 @@ +package server + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime/stateview" +) + +// #1166 follow-up (G4). Two consumers recompute the `quarantined_servers` +// scalar from a PER-ENTRY `quarantined` key — httpapi.filterUpstreamStatsServers +// on the scoped-caller path, and contracts.ConvertUpstreamStatsToServerStats — +// and NEITHER upstream_stats producer emitted it. Both therefore counted zero +// unconditionally, so a scoped caller's security surface read clean even when +// one of its own allowed servers was quarantined. +// +// The oracle is the CONSUMER's answer, not the presence of a map key: asserting +// `entry["quarantined"] != nil` would pass on a producer that emitted the key +// under a different name or type and left the count broken all the same. +func TestUpstreamStatsFromSnapshot_EntryCarriesQuarantined(t *testing.T) { + view := stateview.New() + view.UpdateServer("alpha", func(st *stateview.ServerStatus) { + st.Name = "alpha" + st.Config = &config.ServerConfig{Name: "alpha", Protocol: "stdio"} + st.Enabled = true + st.Connected = true + st.State = "Ready" + st.Quarantined = true + st.ToolCount = 5 + }) + view.UpdateServer("beta", func(st *stateview.ServerStatus) { + st.Name = "beta" + st.Config = &config.ServerConfig{Name: "beta", Protocol: "stdio"} + st.Enabled = true + st.Connected = true + st.State = "Ready" + st.ToolCount = 7 + }) + + stats := upstreamStatsFromSnapshot(view.Snapshot(), false) + + // Precondition: the producer really did describe both servers, so a zero + // count below would mean the key is missing rather than the fixture. + servers, ok := stats["servers"].(map[string]interface{}) + require.True(t, ok, "no servers map in %#v", stats) + require.Len(t, servers, 2) + require.Equal(t, 1, stats["quarantined_servers"], + "precondition: the producer's own scalar counts the quarantined server") + + derived := contracts.ConvertUpstreamStatsToServerStats(stats) + assert.Equal(t, 1, derived.QuarantinedServers, + "a consumer recomputing the scalar from the entries must reach the producer's own answer") + assert.Equal(t, 2, derived.TotalServers) +} diff --git a/internal/storage/activity_models.go b/internal/storage/activity_models.go index dfba06cf1..69008ec4f 100644 --- a/internal/storage/activity_models.go +++ b/internal/storage/activity_models.go @@ -280,6 +280,24 @@ type ActivityFilter struct { AgentName string // Filter by agent token name in metadata AuthType string // Filter by auth type: "admin" or "agent" + // AllowedServers is an AUTHORIZATION filter, not a user-facing one (#1166 + // follow-up): nil means unrestricted, a non-nil slice restricts matches to + // records attributable to one of these server names ("*" is a wildcard, as + // in auth.AuthContext.AllowedServers). + // + // It lives HERE, in the predicate ListActivities and StreamActivities both + // run, rather than as a post-filter over a returned page. A post-filter + // shrinks the page while `total` keeps counting the records it removed — + // which is its own count oracle for exactly what was hidden, and breaks + // pagination for the caller besides. + // + // An empty non-nil slice matches NOTHING, deliberately: it is the shape a + // token allowed no servers produces, and treating it as unrestricted would + // open the door it exists to close. A record with no ServerName (system + // start/stop, config change) is likewise not matched — those are + // operator-plane events with no server to be entitled to. + AllowedServers []string + // ExcludeCallToolSuccess filters out call_tool_* internal tool calls, which // are always paired with a canonical record carrying the same request_id: // successful and failed ones with the upstream tool_call record @@ -328,7 +346,25 @@ func (f *ActivityFilter) ValidateForExport() { } } -// Matches checks if an activity record matches the filter criteria +// serverAllowed applies the AllowedServers authorization filter. nil means +// unrestricted; see the field comment for why empty-but-non-nil matches nothing +// and why an unattributed record is not matched. +func (f *ActivityFilter) serverAllowed(serverName string) bool { + if f.AllowedServers == nil { + return true + } + if serverName == "" { + return false + } + for _, allowed := range f.AllowedServers { + if allowed == "*" || allowed == serverName { + return true + } + } + return false +} + +// Matches checks if an activity record matches the filter criteria. func (f *ActivityFilter) Matches(record *ActivityRecord) bool { // Check types filter (Spec 024: OR logic for multiple types) if len(f.Types) > 0 { @@ -344,6 +380,12 @@ func (f *ActivityFilter) Matches(record *ActivityRecord) bool { } } + // Authorization filter first: a caller must never be able to widen its own + // visibility with any of the query-string filters below it. + if !f.serverAllowed(record.ServerName) { + return false + } + // Check server filter if f.Server != "" && record.ServerName != f.Server { return false diff --git a/internal/storage/manager.go b/internal/storage/manager.go index 567069ad4..4c1b8a0a3 100644 --- a/internal/storage/manager.go +++ b/internal/storage/manager.go @@ -1830,7 +1830,10 @@ func (m *Manager) CloseInactiveSessions(inactivityTimeout time.Duration) (int, e } // GetToolCallsBySession retrieves tool calls filtered by session ID -func (m *Manager) GetToolCallsBySession(sessionID string, limit, offset int) ([]*ToolCallRecord, int, error) { +// scope restricts the read to a set of server names; nil is unrestricted. It is +// applied inside the same pass that computes `total`, so the page and the total +// never describe different record sets (#1166 follow-up). +func (m *Manager) GetToolCallsBySession(sessionID string, limit, offset int, scope ToolCallScope) ([]*ToolCallRecord, int, error) { m.mu.RLock() defer m.mu.RUnlock() @@ -1853,8 +1856,8 @@ func (m *Manager) GetToolCallsBySession(sessionID string, limit, offset int) ([] continue } - // Filter by session ID - if record.MCPSessionID == sessionID { + // Filter by session ID, then by the caller's entitlement. + if record.MCPSessionID == sessionID && scope.Allows(record.ServerName) { total++ if total > offset && len(toolCalls) < limit { toolCalls = append(toolCalls, &record) diff --git a/internal/storage/tool_call_scope.go b/internal/storage/tool_call_scope.go new file mode 100644 index 000000000..c7f1109fa --- /dev/null +++ b/internal/storage/tool_call_scope.go @@ -0,0 +1,32 @@ +package storage + +// ToolCallScope restricts a tool-call read to a set of upstream server names +// (#1166 follow-up). +// +// nil means UNRESTRICTED — an admin caller, or an internal caller with no +// identity to check. A non-nil value restricts, and an EMPTY non-nil value +// restricts to nothing: that is the shape an agent token allowed no servers +// produces, and reading it as "unrestricted" would open the door it exists to +// close. "*" is a wildcard, matching auth.AuthContext.CanAccessServer. +// +// It is threaded into the read itself rather than applied to a returned page +// because the reads it guards also report a `total`: post-filtering shrinks the +// page while the total keeps counting the records it removed, which is both a +// broken pager and a precise count oracle for what was hidden. +type ToolCallScope []string + +// Allows reports whether records attributed to serverName are in scope. +func (s ToolCallScope) Allows(serverName string) bool { + if s == nil { + return true + } + if serverName == "" { + return false + } + for _, allowed := range s { + if allowed == "*" || allowed == serverName { + return true + } + } + return false +} diff --git a/internal/upstream/manager.go b/internal/upstream/manager.go index 86cda2ae7..f31c8a78d 100644 --- a/internal/upstream/manager.go +++ b/internal/upstream/manager.go @@ -1697,13 +1697,17 @@ func (m *Manager) HasDockerContainers() bool { // server list on those same payloads, which httpapi.redactServerSecrets and // Runtime.redactServerSecrets already mask. Leaving `url` and `last_error` raw // here meant one half of a single response was masked and the other half was -// not. Mask them at the point they are written, honouring the same -// reveal_secret_headers opt-out the two sibling redactors honour. +// not. Mask them at the point they are written. +// +// Issue #1167: unconditionally, with no reveal_secret_headers opt-out. This +// producer takes no ctx and neither does its consumer chain, so there is no +// caller identity to AND the operator flag with - and the flag alone handed a +// scoped agent token every server's raw url and last_error on /api/v1/status +// and on every SSE status event. Same rule, same reason, as the StateView +// implementation in internal/server.Server.GetUpstreamStats, which is the one +// that actually runs. func (m *Manager) GetStats() map[string]interface{} { - revealSecrets := false - if gc := m.globalConfig.Load(); gc != nil { - revealSecrets = gc.RevealSecretHeaders - } + const revealSecrets = false // Phase 6: Copy client references while holding lock briefly m.mu.RLock() @@ -1732,8 +1736,10 @@ func (m *Manager) GetStats() map[string]interface{} { // Read config through the thread-safe accessor to avoid racing with // SetConfig on the reconcile add path (MCP-770). name, url, protocol := "", "", "" + quarantined := false if cfg := client.GetConfig(); cfg != nil { name, url, protocol = cfg.Name, cfg.URL, cfg.Protocol + quarantined = cfg.Quarantined if cfg.Quarantined { quarantinedCount++ } @@ -1748,6 +1754,12 @@ func (m *Manager) GetStats() map[string]interface{} { "name": name, "url": url, "protocol": protocol, + // Emitted by BOTH upstream_stats producers (see the twin in + // internal/server.Server.GetUpstreamStats): every consumer that + // recomputes `quarantined_servers` from the entries — the + // scoped-caller filter and contracts.ConvertUpstreamStatsToServerStats + // — keys on it, and neither producer used to write it. + "quarantined": quarantined, } if connectionInfo.State == types.StateReady { diff --git a/internal/upstream/manager_url_redact_test.go b/internal/upstream/manager_url_redact_test.go index 020ba7771..8ef7cc436 100644 --- a/internal/upstream/manager_url_redact_test.go +++ b/internal/upstream/manager_url_redact_test.go @@ -128,10 +128,14 @@ func TestGetStats_MasksURLAndErrorCredentials(t *testing.T) { assert.Contains(t, rendered, "debug=1", "non-sensitive parameters must stay readable") } -// TestGetStats_RevealSecretHeadersOptOut mirrors the escape hatch the two -// sibling redactors honour, so a user who has deliberately opted in still sees -// the real URL on every surface rather than only some of them. -func TestGetStats_RevealSecretHeadersOptOut(t *testing.T) { +// TestGetStats_MasksURLEvenWhenRevealSet is the DELIBERATE inversion of the old +// TestGetStats_RevealSecretHeadersOptOut (issue #1167). The escape hatch it +// used to assert is gone from this producer on purpose: GetStats takes no ctx, +// so there is no caller identity to AND the operator flag with, and the flag +// alone handed a scoped agent token the real URL on /api/v1/status. See +// TestGetStats_MasksEvenWhenRevealSet in round8_stats_rule_test.go for the +// full rationale. +func TestGetStats_MasksURLEvenWhenRevealSet(t *testing.T) { const urlSecret = "urlsecret999" logger := zap.NewNop() @@ -158,6 +162,9 @@ func TestGetStats_RevealSecretHeadersOptOut(t *testing.T) { require.NoError(t, err) manager.clients[serverConfig.Name] = client - assert.Contains(t, fmt.Sprint(manager.GetStats()), urlSecret, - "reveal_secret_headers:true must expose the real URL, as it does on /api/v1/servers") + rendered := fmt.Sprint(manager.GetStats()) + assert.NotContains(t, rendered, urlSecret, + "reveal_secret_headers:true must NOT expose the real URL on a producer with no caller (#1167)") + assert.Contains(t, rendered, "host/mcp", + "precondition: the status map still carries the URL, only the credential is masked") } diff --git a/internal/upstream/round8_stats_rule_test.go b/internal/upstream/round8_stats_rule_test.go index 6f58e5a07..72876fc28 100644 --- a/internal/upstream/round8_stats_rule_test.go +++ b/internal/upstream/round8_stats_rule_test.go @@ -75,16 +75,32 @@ func TestGetStats_UsesTheSharedFreeTextRuleForLastError(t *testing.T) { "upstream_stats must scrub `last_error` with the one shared free-text rule") } -func TestGetStats_RevealSecretHeadersStillOptsOut(t *testing.T) { +// TestGetStats_MasksEvenWhenRevealSet is the DELIBERATE inversion of the old +// TestGetStats_RevealSecretHeadersStillOptsOut (issue #1167), not a regression +// of the round-4/round-8 work. +// +// GetStats takes no ctx, and its consumer chain is context-free too, so this +// producer has no caller to AND the operator flag with. Honouring the flag here +// meant a scoped, read-only agent token polling GET /api/v1/status (or +// subscribing to /events) received every server's raw url and last_error the +// moment an operator opted in. A producer with no caller masks for the +// least-privileged possible reader. The operator still reads the real values on +// the gated doors: GET /api/v1/servers and GET /api/v1/config. +func TestGetStats_MasksEvenWhenRevealSet(t *testing.T) { rawURL := "https://h/mcp?opaque=" + round8GHPToken + msg := "boom " + round8GHPToken manager, client := newStatsManager(t, &config.ServerConfig{ Name: "leaky", Protocol: "http", URL: rawURL, Enabled: true, }, &config.Config{RevealSecretHeaders: true}) - client.StateManager.SetError(errors.New("boom " + round8GHPToken)) + client.StateManager.SetError(errors.New(msg)) rendered := fmt.Sprint(manager.GetStats()) - assert.Contains(t, rendered, rawURL, "the opt-out must still expose the real URL") - assert.Contains(t, rendered, "boom "+round8GHPToken, "the opt-out must still expose the real error") + assert.NotContains(t, rendered, round8GHPToken, + "reveal_secret_headers must NOT expose a credential on a producer with no caller (#1167)") + assert.Equal(t, oauth.LiveRedaction.URLValue(rawURL), statsServerField(t, manager, "leaky", "url"), + "`url` must take the one shared live rule regardless of the flag") + assert.Equal(t, oauth.ScrubUpstreamText(msg), statsServerField(t, manager, "leaky", "last_error"), + "`last_error` must take the one shared free-text rule regardless of the flag") } func statsServerField(t *testing.T, m *Manager, server, field string) string { diff --git a/oas/docs.go b/oas/docs.go index 8449801a0..21cfe19ea 100644 --- a/oas/docs.go +++ b/oas/docs.go @@ -9,7 +9,7 @@ const docTemplate = `{ "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"},"retry_stopped":{"description":"RetryStopped reports that automatic reconnection has been given up for\ngood because the failure is deterministic and unrecoverable — a missing\nbinary, an image without the interpreter, an unparseable config (GH\n#1145). It is NOT ordinary exponential backoff, which keeps retrying;\nnothing will happen until the user fixes the config or restarts the\nserver. RetryStoppedCode is the stable MCPX_* code that proved it and\nRetryStoppedReason the catalog message explaining how to fix it. All three\nare omitted for servers that are healthy or still retrying.","type":"boolean"},"retry_stopped_code":{"type":"string"},"retry_stopped_reason":{"type":"string"},"security_scan":{"$ref":"#/components/schemas/contracts.SecurityScanSummary"},"should_retry":{"type":"boolean"},"source_registry_id":{"description":"MCP-901 — registry provenance of an upstream that was added from a\nregistry. SourceRegistryID names the source registry (empty for\nmanually-configured servers); SourceRegistryProvenance is the trust tag\nrecorded at add time (\"official/trusted\" or \"custom/unverified\"). Both\nare projected from config.ServerConfig so the approval/quarantine view\ncan render an \"added from \u003cregistry\u003e · unverified\" origin badge. Optional\nand omitted when empty — clients that pre-date this treat them as absent.","type":"string"},"source_registry_provenance":{"type":"string"},"status":{"type":"string"},"token_expires_at":{"description":"When the OAuth token expires (ISO 8601)","type":"string"},"tool_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. 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"]}}}, + "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"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read the configuration document"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get current configuration","tags":["config"]},"patch":{"description":"Deep-merges only the fields present in the request body onto the live in-memory configuration and routes the result through the existing apply pipeline (validation, change detection, disk persistence, hot-reload). Fields the client omits — including masked secrets such as ` + "`" + `api_key` + "`" + ` and secret request headers — are preserved verbatim. Nested objects are merged recursively; arrays and scalars replace wholesale.","requestBody":{"content":{"application/json":{"schema":{"type":"object"}}},"description":"Partial configuration with only the fields to change","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ConfigApplyResult"}}},"description":"Configuration patch applied (inspect validation_errors for rejected values)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload or empty patch"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate configuration)"},"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\nweb_ui_url carries the ?apikey= credential ONLY for an authenticated admin; a scoped agent token receives the bare URL\nThis endpoint is designed for tray-core communication and version checking\nUse refresh=true query parameter to force an immediate update check against GitHub\nThe launched_by field reports durable launch provenance (\"tray\", \"installer\", or \"\" for user-launched/unknown)","parameters":[{"description":"Force immediate update check against GitHub","in":"query","name":"refresh","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Server information with optional update info"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server information","tags":["status"]}},"/api/v1/onboarding/mark":{"post":{"description":"Updates wizard engagement and per-step status. Once engaged is\ntrue, the wizard does not auto-show again, even if state regresses.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.OnboardingMarkRequest"}}},"description":"Mark request","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Updated OnboardingStateResponse"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read onboarding state"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Mark onboarding wizard state (Spec 046)","tags":["onboarding"]}},"/api/v1/onboarding/state":{"get":{"description":"Returns the wizard engagement record alongside live predicates\n(whether any client is connected, whether any server is configured),\nplus a derived ShouldShowWizard flag the frontend can rely on.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"OnboardingStateResponse"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read onboarding state"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get onboarding wizard state and predicates (Spec 046)","tags":["onboarding"]}},"/api/v1/preflight":{"post":{"description":"Deterministic, side-effect-free availability check for a caller-supplied list of tool IDs (Spec 098). Performs zero upstream calls and mutates no runtime state. HTTP status reports whether the CHECK executed: a fully blocked set is still 200, with the availability verdict in the body. Every executed preflight writes an activity record before the response is returned.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.PreflightRequest"}}},"description":"Tool IDs (1-100 before dedup), optional profile, annotation policy filters and wait budget","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Preflight verdict and per-tool results"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Validation error (malformed, oversized, doubled or unknown-field body; empty or oversized tool list; conflicting duplicate pins; unknown profile; wait_ms out of range)"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Missing or invalid credentials"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Runtime unavailable, evaluator infrastructure read failure, or the activity record could not be persisted"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Preflight required tools","tags":["tools"]}},"/api/v1/profiles":{"get":{"description":"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"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot change the active profile)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown profile"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Set the default active profile","tags":["profiles"]}},"/api/v1/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"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read MCP session history"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get sessions"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get active MCP sessions","tags":["sessions"]}},"/api/v1/sessions/{id}":{"get":{"description":"Retrieves detailed information about a specific MCP client session including initialization parameters, connection status, tool call count, and activity timestamps.","parameters":[{"description":"Session ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetSessionDetailResponse"}}},"description":"Session details retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Session ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read MCP session history"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Session not found"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get MCP session details by ID","tags":["sessions"]}},"/api/v1/stats/tokens":{"get":{"description":"Retrieve token savings statistics across all servers and sessions","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Token statistics"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read deployment-wide token statistics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get token savings statistics","tags":["stats"]}},"/api/v1/status":{"get":{"description":"Get comprehensive server status including running state, listen address, upstream statistics, and timestamp","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server status information"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server status","tags":["status"]}},"/api/v1/telemetry/payload":{"get":{"description":"Render the exact JSON heartbeat payload that mcpproxy would next send to the telemetry endpoint, without making a network call. Counters in the payload reflect the current in-memory state. Spec 042.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Telemetry heartbeat payload"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Agent tokens cannot read the deployment telemetry payload"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Telemetry service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Preview next telemetry heartbeat payload","tags":["telemetry"]}},"/api/v1/telemetry/update-failure":{"post":{"description":"Records one terminal update-session failure, identified only by its\nstage (appcast, download, install, other). The body carries no error\ntext, URL, or version — the stage is the only value transmitted.\nReturns 204 both when the occurrence was durably persisted and when\ntelemetry is inactive at event time (config opt-out, environment\nopt-out, CI, or dev build), in which case nothing is recorded.\nCallers cannot and need not distinguish the two.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.UpdateFailureRequest"}}},"description":"Update failure stage","required":true},"responses":{"204":{"description":"Accepted (recorded, or a deliberate no-op while telemetry is inactive)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Malformed body, unknown field, trailing value, or stage outside the closed set"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Persistence failure"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Record a desktop auto-update failure occurrence (Spec 095)","tags":["telemetry"]}},"/api/v1/tool-calls":{"get":{"description":"Retrieves paginated tool call history across all upstream servers or filtered by session ID. Includes execution timestamps, arguments, results, and error information for debugging and auditing.","parameters":[{"description":"Maximum number of records to return (1-100, default 50)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Number of records to skip for pagination (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Filter tool calls by MCP session ID","in":"query","name":"session_id","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetToolCallsResponse"}}},"description":"Tool calls retrieved successfully"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get tool calls"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call history","tags":["tool-calls"]}},"/api/v1/tool-calls/{id}":{"get":{"description":"Retrieves detailed information about a specific tool call execution including full request arguments, response data, execution time, and any errors encountered.","parameters":[{"description":"Tool call ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetToolCallDetailResponse"}}},"description":"Tool call details retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call not found"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call details by ID","tags":["tool-calls"]}},"/api/v1/tool-calls/{id}/replay":{"post":{"description":"Re-executes a previous tool call with optional modified arguments. Useful for debugging and testing tool behavior with different inputs. Creates a new tool call record linked to the original.","parameters":[{"description":"Original tool call ID to replay","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ReplayToolCallRequest"}}},"description":"Optional modified arguments for replay"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ReplayToolCallResponse"}}},"description":"Tool call replayed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call ID required or invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"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 f81cc553c..304195954 100644 --- a/oas/swagger.yaml +++ b/oas/swagger.yaml @@ -4177,6 +4177,12 @@ paths: schema: $ref: '#/components/schemas/contracts.ErrorResponse' description: Unauthorized - missing or invalid API key + "403": + content: + application/json: + schema: + $ref: '#/components/schemas/contracts.ErrorResponse' + description: Agent tokens cannot read the configuration document "500": content: application/json: @@ -4866,6 +4872,7 @@ paths: get: description: |- Get essential server metadata including version, web UI URL, endpoint addresses, and update availability + web_ui_url carries the ?apikey= credential ONLY for an authenticated admin; a scoped agent token receives the bare URL This endpoint is designed for tray-core communication and version checking Use refresh=true query parameter to force an immediate update check against GitHub The launched_by field reports durable launch provenance ("tray", "installer", or "" for user-launched/unknown) @@ -4930,6 +4937,12 @@ paths: schema: $ref: '#/components/schemas/contracts.ErrorResponse' description: Bad request + "403": + content: + application/json: + schema: + $ref: '#/components/schemas/contracts.ErrorResponse' + description: Agent tokens cannot read onboarding state "503": content: application/json: @@ -4955,6 +4968,12 @@ paths: schema: $ref: '#/components/schemas/contracts.APIResponse' description: OnboardingStateResponse + "403": + content: + application/json: + schema: + $ref: '#/components/schemas/contracts.ErrorResponse' + description: Agent tokens cannot read onboarding state "503": content: application/json: @@ -5093,6 +5112,12 @@ paths: schema: $ref: '#/components/schemas/contracts.ErrorResponse' description: Invalid request body + "403": + content: + application/json: + schema: + $ref: '#/components/schemas/contracts.ErrorResponse' + description: Forbidden (agent tokens cannot change the active profile) "404": content: application/json: @@ -6824,6 +6849,12 @@ paths: schema: $ref: '#/components/schemas/contracts.ErrorResponse' description: Unauthorized - missing or invalid API key + "403": + content: + application/json: + schema: + $ref: '#/components/schemas/contracts.ErrorResponse' + description: Agent tokens cannot read MCP session history "405": content: application/json: @@ -6873,6 +6904,12 @@ paths: schema: $ref: '#/components/schemas/contracts.ErrorResponse' description: Unauthorized - missing or invalid API key + "403": + content: + application/json: + schema: + $ref: '#/components/schemas/contracts.ErrorResponse' + description: Agent tokens cannot read MCP session history "404": content: application/json: @@ -6901,6 +6938,12 @@ paths: schema: $ref: '#/components/schemas/contracts.SuccessResponse' description: Token statistics + "403": + content: + application/json: + schema: + $ref: '#/components/schemas/contracts.ErrorResponse' + description: Agent tokens cannot read deployment-wide token statistics "500": content: application/json: @@ -6948,6 +6991,12 @@ paths: schema: $ref: '#/components/schemas/contracts.SuccessResponse' description: Telemetry heartbeat payload + "403": + content: + application/json: + schema: + $ref: '#/components/schemas/contracts.ErrorResponse' + description: Agent tokens cannot read the deployment telemetry payload "503": content: application/json: