diff --git a/cmd/mcpproxy/activity_cmd.go b/cmd/mcpproxy/activity_cmd.go index d8c831378..4758ee4f2 100644 --- a/cmd/mcpproxy/activity_cmd.go +++ b/cmd/mcpproxy/activity_cmd.go @@ -41,6 +41,7 @@ var ( activityOffset int activityIntentType string // Spec 018: Filter by operation type (read, write, destructive) activityRequestID string // Spec 021: Filter by HTTP request ID for correlation + activityParentID string // Activity transparency: filter to sub-calls of a code_execution parent activityNoIcons bool // Disable emoji icons in output activityDetectionType string // Spec 026: Filter by detection type (e.g., "aws_access_key") activitySeverity string // Spec 026: Filter by severity level (critical, high, medium, low) @@ -73,6 +74,7 @@ type ActivityFilter struct { Offset int IntentType string // Spec 018: Filter by operation type (read, write, destructive) RequestID string // Spec 021: Filter by HTTP request ID for correlation + ParentID string // Activity transparency: filter to sub-calls of a code_execution parent SensitiveData *bool // Spec 026: Filter by sensitive data detection DetectionType string // Spec 026: Filter by detection type Severity string // Spec 026: Filter by severity level @@ -228,6 +230,11 @@ func (f *ActivityFilter) ToQueryParams() url.Values { if f.RequestID != "" { q.Set("request_id", f.RequestID) } + // Activity transparency: parent_id joins a code_execution record to the + // sandboxed sub-calls it made (child.parent_id == parent.request_id). + if f.ParentID != "" { + q.Set("parent_id", f.ParentID) + } // Spec 026: Add sensitive data filters if f.SensitiveData != nil { q.Set("sensitive_data", fmt.Sprintf("%t", *f.SensitiveData)) @@ -856,6 +863,9 @@ Examples: # List activity by request ID (for error correlation) mcpproxy activity list --request-id abc123-def456 + # List the sub-calls a code_execution made (value = the parent's request_id) + mcpproxy activity list --parent-id abc123-def456 + # List only activities with sensitive data detected mcpproxy activity list --sensitive-data @@ -932,7 +942,10 @@ Examples: mcpproxy activity export --format csv --output activity.csv # Export to stdout for piping - mcpproxy activity export --format csv | gzip > activity.csv.gz`, + mcpproxy activity export --format csv | gzip > activity.csv.gz + + # Export just the sub-calls of one code_execution + mcpproxy activity export --parent-id abc123-def456`, RunE: runActivityExport, } ) @@ -962,6 +975,7 @@ func init() { activityListCmd.Flags().IntVar(&activityOffset, "offset", 0, "Pagination offset") activityListCmd.Flags().StringVar(&activityIntentType, "intent-type", "", "Filter by intent operation type: read, write, destructive") activityListCmd.Flags().StringVar(&activityRequestID, "request-id", "", "Filter by HTTP request ID for log correlation") + activityListCmd.Flags().StringVar(&activityParentID, "parent-id", "", "List child tool calls of a code_execution activity (value = the parent record request_id)") activityListCmd.Flags().BoolVar(&activityNoIcons, "no-icons", false, "Disable emoji icons in output (use text instead)") // Spec 026: Sensitive data detection filters activityListCmd.Flags().Bool("sensitive-data", false, "Filter to show only activities with sensitive data detected") @@ -995,6 +1009,7 @@ func init() { activityExportCmd.Flags().StringVar(&activitySessionID, "session", "", "Filter by session — a work session id (ws-...) or a raw MCP transport session id") activityExportCmd.Flags().StringVar(&activityStartTime, "start-time", "", "Filter after this time (RFC3339)") activityExportCmd.Flags().StringVar(&activityEndTime, "end-time", "", "Filter before this time (RFC3339)") + activityExportCmd.Flags().StringVar(&activityParentID, "parent-id", "", "Export only child tool calls of a code_execution activity (value = the parent record request_id)") } // getActivityClient creates an HTTP client for the daemon @@ -1045,6 +1060,7 @@ func runActivityList(cmd *cobra.Command, _ []string) error { Offset: activityOffset, IntentType: activityIntentType, RequestID: activityRequestID, + ParentID: activityParentID, SensitiveData: sensitiveDataPtr, DetectionType: activityDetectionType, Severity: activitySeverity, @@ -1147,7 +1163,9 @@ func runActivityList(cmd *cobra.Command, _ []string) error { sourceIcon, actType, server, - tool, + // Activity transparency: a sub-call of a code_execution parent is + // indented so a mixed list reads as a tree, not a flat run of rows. + activityChildToolCell(act, tool), intentStr, sensitiveStr, // Spec 026: Show sensitive data indicator status, @@ -1433,6 +1451,8 @@ func formatToolCallEvent(event map[string]interface{}, timestamp string) string statusIcon := formatStatusIcon(status) line := fmt.Sprintf("[%s] [%s] %s:%s %s %s", timestamp, sourceIcon, server, tool, statusIcon, formatActivityDuration(int64(durationMs))) + // Activity transparency: mark sub-calls made from inside a code_execution. + line += formatParentMarker(event) if errMsg != "" { line += " " + errMsg } @@ -1465,6 +1485,7 @@ func formatInternalToolCallEvent(event map[string]interface{}, timestamp string) } line := fmt.Sprintf("[%s] [INT] %s%s %s %s", timestamp, internalTool, target, statusIcon, formatActivityDuration(int64(durationMs))) + line += formatParentMarker(event) if errMsg != "" { line += " " + errMsg } @@ -1547,6 +1568,41 @@ func formatStatusIcon(status string) string { } } +// activityChildToolCell renders the TOOL cell for a list row, marking records +// that are sub-calls of a code_execution parent (ParentID == parent request_id). +func activityChildToolCell(act map[string]interface{}, tool string) string { + if getStringField(act, "parent_id") == "" { + return tool + } + return "└ " + tool +} + +// formatParentMarker renders the short "[child of ]" suffix used by +// `activity watch`, so a sub-call is recognisable in the live stream. +func formatParentMarker(event map[string]interface{}) string { + parentID := getStringField(event, "parent_id") + if parentID == "" { + return "" + } + return fmt.Sprintf(" [child of %s]", parentID) +} + +// isCodeExecutionParent reports whether a record is the code_execution activity +// that sandboxed sub-calls hang off. Only the internal_tool_call record spawns +// children; a same-named upstream tool_call does not. +func isCodeExecutionParent(activity map[string]interface{}) bool { + if getStringField(activity, "type") != string(storage.ActivityTypeInternalToolCall) { + return false + } + if getStringField(activity, "tool_name") == "code_execution" { + return true + } + if metadata := getMapField(activity, "metadata"); metadata != nil { + return getStringField(metadata, "internal_tool_name") == "code_execution" + } + return false +} + // runActivityShow implements the activity show command func runActivityShow(cmd *cobra.Command, args []string) error { activityID := args[0] @@ -1621,10 +1677,22 @@ func runActivityShow(cmd *cobra.Command, args []string) error { // Spec 098 (SC-005): the request id is how a preflight record is joined to // the tool calls of the same workflow (`activity list --request-id `), // so the detail view has to show it, not just accept it as a filter. - if requestID := getStringField(activity, "request_id"); requestID != "" { + requestID := getStringField(activity, "request_id") + if requestID != "" { fmt.Printf("Request ID: %s\n", requestID) } + // Activity transparency: both directions of the code_execution ↔ sub-call + // link are navigable from the detail view. + // child → parent: the Parent ID line below + // parent → children: the hint below it + if parentID := getStringField(activity, "parent_id"); parentID != "" { + fmt.Printf("Parent ID: %s\n", parentID) + fmt.Printf(" (sub-call of a code_execution — 'mcpproxy activity list --request-id %s' shows the parent)\n", parentID) + } else if isCodeExecutionParent(activity) && requestID != "" { + fmt.Printf("\nUse 'mcpproxy activity list --parent-id %s' to see sub-calls.\n", requestID) + } + if errMsg := getStringField(activity, "error_message"); errMsg != "" { fmt.Printf("Error: %s\n", errMsg) } @@ -1779,6 +1847,43 @@ func runActivitySummary(cmd *cobra.Command, _ []string) error { return nil } +// activityExportQueryParams builds the export query string from the export +// flags. Export does NOT go through ActivityFilter.ToQueryParams, so every +// filter flag has to be wired here as well or it is a silent no-op. +func activityExportQueryParams() url.Values { + q := url.Values{} + q.Set("format", activityExportFormat) + if activityType != "" { + q.Set("type", activityType) + } + if activityServer != "" { + q.Set("server", activityServer) + } + if activityTool != "" { + q.Set("tool", activityTool) + } + if activityStatus != "" { + q.Set("status", activityStatus) + } + if activitySessionID != "" { + q.Set(sessionQueryParam(activitySessionID), activitySessionID) + } + if activityStartTime != "" { + q.Set("start_time", activityStartTime) + } + if activityEndTime != "" { + q.Set("end_time", activityEndTime) + } + // Activity transparency: export the sub-calls of one code_execution. + if activityParentID != "" { + q.Set("parent_id", activityParentID) + } + if activityIncludeBodies { + q.Set("include_bodies", "true") + } + return q +} + // runActivityExport implements the activity export command func runActivityExport(cmd *cobra.Command, _ []string) error { // Setup logger @@ -1812,34 +1917,7 @@ func runActivityExport(cmd *cobra.Command, _ []string) error { transport, baseURL := activityTransport(endpoint, logger.Sugar()) exportURL := baseURL + "/api/v1/activity/export" - q := url.Values{} - q.Set("format", activityExportFormat) - if activityType != "" { - q.Set("type", activityType) - } - if activityServer != "" { - q.Set("server", activityServer) - } - if activityTool != "" { - q.Set("tool", activityTool) - } - if activityStatus != "" { - q.Set("status", activityStatus) - } - if activitySessionID != "" { - q.Set(sessionQueryParam(activitySessionID), activitySessionID) - } - if activityStartTime != "" { - q.Set("start_time", activityStartTime) - } - if activityEndTime != "" { - q.Set("end_time", activityEndTime) - } - if activityIncludeBodies { - q.Set("include_bodies", "true") - } - - exportURL += "?" + q.Encode() + exportURL += "?" + activityExportQueryParams().Encode() // Create HTTP request ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) diff --git a/cmd/mcpproxy/activity_parent_id_test.go b/cmd/mcpproxy/activity_parent_id_test.go new file mode 100644 index 000000000..d42214d98 --- /dev/null +++ b/cmd/mcpproxy/activity_parent_id_test.go @@ -0,0 +1,144 @@ +package main + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +// Activity transparency: a code_execution parent and its sandboxed sub-calls are +// joined by ParentID (the parent record's request_id). The CLI has to be able to +// (a) ask for the children, (b) mark them in the table, (c) point back at the +// parent from the detail view, and (d) carry the filter into export. + +func TestActivityFilter_ToQueryParams_ParentID(t *testing.T) { + tests := []struct { + name string + filter ActivityFilter + wantKey string + wantVal string + wantNone bool + }{ + { + name: "parent id is sent as parent_id", + filter: ActivityFilter{ParentID: "req-parent-123"}, + wantKey: "parent_id", + wantVal: "req-parent-123", + }, + { + name: "empty parent id is omitted", + filter: ActivityFilter{}, + wantKey: "parent_id", + wantNone: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + params := tt.filter.ToQueryParams() + if tt.wantNone { + assert.False(t, params.Has(tt.wantKey), "param %s should be omitted", tt.wantKey) + return + } + assert.Equal(t, tt.wantVal, params.Get(tt.wantKey)) + }) + } +} + +func TestActivityListCmd_ParentIDFlag(t *testing.T) { + f := activityListCmd.Flags().Lookup("parent-id") + assert.NotNil(t, f, "--parent-id flag should exist on activity list") + if f != nil { + assert.Equal(t, "", f.DefValue) + assert.Contains(t, f.Usage, "code_execution") + } +} + +func TestActivityExportCmd_ParentIDFlag(t *testing.T) { + f := activityExportCmd.Flags().Lookup("parent-id") + assert.NotNil(t, f, "--parent-id flag should exist on activity export") +} + +// The export command hand-builds its query string (it does not go through +// ToQueryParams), so the flag has to be wired there separately or it is a +// silent no-op. +func TestActivityExportQueryParams_ParentID(t *testing.T) { + prevParent := activityParentID + prevFormat := activityExportFormat + t.Cleanup(func() { + activityParentID = prevParent + activityExportFormat = prevFormat + }) + + activityExportFormat = "json" + + activityParentID = "" + assert.False(t, activityExportQueryParams().Has("parent_id"), "empty parent id should be omitted") + + activityParentID = "req-parent-123" + q := activityExportQueryParams() + assert.Equal(t, "req-parent-123", q.Get("parent_id")) + assert.Equal(t, "json", q.Get("format")) +} + +func TestActivityChildToolCell(t *testing.T) { + child := map[string]interface{}{"parent_id": "req-parent-123"} + assert.Equal(t, "└ github:create_issue", activityChildToolCell(child, "github:create_issue")) + + parent := map[string]interface{}{} + assert.Equal(t, "code_execution", activityChildToolCell(parent, "code_execution"), + "a record with no parent_id must not be marked as a child") +} + +func TestFormatParentMarker(t *testing.T) { + withParent := map[string]interface{}{"parent_id": "req-parent-123"} + marker := formatParentMarker(withParent) + assert.Contains(t, marker, "child of") + assert.Contains(t, marker, "req-parent-123") + + assert.Equal(t, "", formatParentMarker(map[string]interface{}{})) +} + +func TestIsCodeExecutionParent(t *testing.T) { + byToolName := map[string]interface{}{ + "type": "internal_tool_call", + "tool_name": "code_execution", + } + assert.True(t, isCodeExecutionParent(byToolName)) + + byMetadata := map[string]interface{}{ + "type": "internal_tool_call", + "metadata": map[string]interface{}{ + "internal_tool_name": "code_execution", + }, + } + assert.True(t, isCodeExecutionParent(byMetadata)) + + otherInternal := map[string]interface{}{ + "type": "internal_tool_call", + "tool_name": "retrieve_tools", + } + assert.False(t, isCodeExecutionParent(otherInternal)) + + // A plain tool_call that happens to be named code_execution is not a parent + // record — only the internal_tool_call record spawns sub-calls. + wrongType := map[string]interface{}{ + "type": "tool_call", + "tool_name": "code_execution", + } + assert.False(t, isCodeExecutionParent(wrongType)) +} + +func TestFormatToolCallEvent_ChildMarker(t *testing.T) { + event := map[string]interface{}{ + "source": "mcp", + "server_name": "github", + "tool_name": "create_issue", + "status": "success", + "parent_id": "req-parent-123", + } + line := formatToolCallEvent(event, "12:00:00") + assert.True(t, strings.Contains(line, "[child of req-parent-123]"), + "watch output should mark sub-calls, got: %s", line) +} diff --git a/docs/api/rest-api.md b/docs/api/rest-api.md index 8ccb0da65..edcf783f5 100644 --- a/docs/api/rest-api.md +++ b/docs/api/rest-api.md @@ -1141,6 +1141,7 @@ List recent MCP sessions. |-----------|------|-------------| | `limit` | integer | Max sessions (1-100, default: 10) | | `offset` | integer | Pagination offset (default: 0) | +| `parent_id` | string | Return only the sub-calls of one `code_execution` (value = the parent record's `request_id`) | | `status` | string | Filter by session status: `active`, `closed`. Any other value returns `400`. | The `status` filter is applied during the storage walk, **before** the `limit` diff --git a/docs/cli/activity-commands.md b/docs/cli/activity-commands.md index e8f17b8d6..a80bf1a02 100644 --- a/docs/cli/activity-commands.md +++ b/docs/cli/activity-commands.md @@ -60,6 +60,7 @@ mcpproxy activity list [flags] | `--status` | | | Filter by status: `success`, `error`, `blocked`, `rejected` (shed by a concurrency limit, see [Concurrency Limits](../configuration/config-file.md#concurrency-limits--request-queueing)) | | `--intent-type` | | | Filter by intent operation type: `read`, `write`, `destructive` | | `--request-id` | | | Filter by HTTP request ID for log correlation | +| `--parent-id` | | | List child tool calls of a `code_execution` activity (value = the parent record `request_id`) | | `--no-icons` | | | Disable emoji icons in output (use text instead) | | `--session` | | | Filter by MCP session ID | | `--start-time` | | | Filter records after this time (RFC3339) | @@ -88,6 +89,9 @@ mcpproxy activity list --intent-type destructive --limit 100 # Find activity by request ID (useful for error correlation) mcpproxy activity list --request-id a1b2c3d4-e5f6-7890-abcd-ef1234567890 +# List the sub-calls one code_execution made (value = the parent's request_id) +mcpproxy activity list --parent-id a1b2c3d4-e5f6-7890-abcd-ef1234567890 + # List activity as JSON mcpproxy activity list -o json @@ -220,7 +224,7 @@ Source indicators (`[MCP]`, `[CLI]`, `[API]`) show how the tool call was trigger - Automatically reconnects on connection loss (exponential backoff) - Exits cleanly on SIGINT (Ctrl+C) or SIGTERM - Buffers high-volume events to prevent terminal flooding -- **Filters out successful `call_tool_*` internal tool calls** to avoid duplicates (they have corresponding `tool_call` entries) +- **Filters out `call_tool_*` internal tool calls** to avoid duplicates (every dispatch — successful, failed, or shed — has a corresponding `tool_call` or rejection record) ### Exit Codes @@ -294,6 +298,12 @@ Response: URL: https://github.com/owner/repo/issues/123 ``` +**Code execution links:** when the record is a `code_execution` parent, the +detail view prints a hint (`Use 'mcpproxy activity list --parent-id ' +to see sub-calls`). When the record is one of those sub-calls, it prints a +`Parent ID:` line instead. See +[Drill into a `code_execution`](#drill-into-a-code_execution). + **Source Values:** - `MCP (AI agent via MCP protocol)` - Tool called by AI agent - `CLI (CLI command)` - Tool called via `mcpproxy call tool` CLI command @@ -417,6 +427,7 @@ mcpproxy activity export [flags] | `--output` | | | Output file path (stdout if not specified) | | `--format` | `-f` | json | Export format: `json`, `csv` | | `--include-bodies` | | false | Include full request/response bodies | +| `--parent-id` | | | Export only child tool calls of a `code_execution` activity (value = the parent record `request_id`) | | *(filter flags)* | | | Same filters as `activity list` | ### Examples @@ -448,6 +459,9 @@ mcpproxy activity export --type tool_call,internal_tool_call --output tool-calls # Export config changes for audit mcpproxy activity export --type config_change --output config-audit.jsonl + +# Export the sub-calls of one code_execution run +mcpproxy activity export --parent-id a1b2c3d4-e5f6-7890-abcd-ef1234567890 --output sandbox-run.jsonl ``` ### Output (JSON - JSON Lines) @@ -487,6 +501,39 @@ mcpproxy activity list --status error --limit 5 mcpproxy activity show --include-response ``` +### Drill into a `code_execution` + +A `code_execution` call runs a sandboxed script that may call several upstream +tools. Each of those sub-calls is recorded as its own `tool_call` activity with +its own `request_id`, plus a `parent_id` pointing at the `request_id` of the +`code_execution` record that spawned it. That link is what makes a sandboxed run +auditable instead of a single opaque row. + +```bash +# 1. Spot the code_execution in the list (type internal_tool_call, tool code_execution) +mcpproxy activity list --type internal_tool_call --limit 20 + +# 2. Open it — the detail view prints its Request ID and the drill-in hint +mcpproxy activity show + +# 3. List the sub-calls it made, using the parent's request_id +mcpproxy activity list --parent-id + +# 4. From any sub-call, walk back up to the parent +mcpproxy activity show # prints "Parent ID: ..." +mcpproxy activity list --request-id +``` + +In table output, sub-calls are indented with `└` in the TOOL column, and +`activity watch` marks them inline with `[child of ]`. In JSON output +the `parent_id` field is present on every child record, so the whole run can be +reassembled: + +```bash +# All sub-calls of one run as JSON +mcpproxy activity list --parent-id -o json | jq '.activities[] | {tool_name, status, duration_ms}' +``` + ### Monitor Agent Behavior ```bash @@ -579,7 +626,7 @@ The activity log captures the following event types: | `server_change` | Server enable/disable/restart events | :::note Duplicate Filtering for call_tool_* -By default, **successful** `call_tool_*` internal tool calls are filtered out from `activity list`, `activity watch`, and the Web UI because they appear as duplicates alongside their corresponding upstream `tool_call` entries. **Failed** `call_tool_*` calls are always shown since they have no corresponding tool call entry. +By default, all `call_tool_*` internal records are filtered out from `activity list`, `activity watch`, and the Web UI — every dispatch (successful, failed, or shed) has a corresponding upstream `tool_call` or rejection record carrying the same `request_id`, so showing both would double-count the call. To include all internal tool calls in API responses, use `include_call_tool=true` query parameter. ::: diff --git a/docs/code_execution/overview.md b/docs/code_execution/overview.md index 72589fe85..2198cd80c 100644 --- a/docs/code_execution/overview.md +++ b/docs/code_execution/overview.md @@ -203,6 +203,7 @@ Code execution **respects existing MCPProxy security features**: - Quarantined servers cannot be called via `call_tool()` - Server enable/disable settings are enforced - Authentication requirements are preserved +- Every upstream tool call a script makes is recorded as a first-class activity record with `parent_id` linking it to the `code_execution` run — drill in with `mcpproxy activity list --parent-id `; policy-blocked sub-calls are recorded with status `blocked` ## Getting Started diff --git a/docs/features/activity-log.md b/docs/features/activity-log.md index bb8d440dd..c6ce59cbc 100644 --- a/docs/features/activity-log.md +++ b/docs/features/activity-log.md @@ -71,9 +71,9 @@ Internal tool calls log when internal proxy tools are used: ``` :::note Duplicate Filtering -By default, **successful** `call_tool_*` internal tool calls (`call_tool_read`, `call_tool_write`, `call_tool_destructive`) are excluded from activity listings because they appear as duplicates alongside their corresponding upstream `tool_call` entries. **Failed** `call_tool_*` calls are always shown since they have no corresponding upstream tool call entry. +By default, all `call_tool_*` internal tool calls (`call_tool_read`, `call_tool_write`, `call_tool_destructive`) are excluded from activity listings — every dispatch (successful, failed, or shed) has a corresponding upstream `tool_call` or rejection record carrying the same `request_id`, so showing both would double-count the call. -To include all internal tool calls including successful `call_tool_*`, use `include_call_tool=true` in the API query parameter. +To include the `call_tool_*` records anyway, use `include_call_tool=true` in the API query parameter. ::: ### Config Change Events @@ -125,6 +125,18 @@ Each tool call record includes: } ``` +#### Sub-calls made by code_execution + +Every upstream tool call a sandboxed `code_execution` script makes is recorded +as a first-class `tool_call` record with its own `request_id` and a `parent_id` +equal to the parent `code_execution` record's `request_id` (`source` is +`internal`; a policy-refused sub-call is recorded with status `blocked`). +Filter with `parent_id=` to list a script's sub-calls, or +`request_id=` to find the parent — the Web UI drawer, the +macOS Activity window, and `mcpproxy activity list --parent-id` all expose the +same navigation (see the "Drill into a code_execution" workflow in the CLI +activity commands reference). + ### Intent Tracking Every tool call includes intent information for security auditing: @@ -294,7 +306,8 @@ GET /api/v1/activity | `end_time` | string | Filter before this time (RFC3339) | | `limit` | integer | Max records (1-100, default: 50) | | `offset` | integer | Pagination offset (default: 0) | -| `include_call_tool` | boolean | Include successful `call_tool_*` internal tool calls (default: false). By default, successful `call_tool_*` are excluded because they appear as duplicates alongside their upstream `tool_call` entries. Failed `call_tool_*` are always shown. | +| `include_call_tool` | boolean | Include `call_tool_*` internal tool calls (default: false). Excluded by default because every dispatch has a paired `tool_call` (or rejection) record with the same `request_id`. | +| `parent_id` | string | Return only the sub-calls one `code_execution` issued (value = the parent record's `request_id`). Child→parent is the reverse lookup: `request_id=`. | | `exclude_payloads` | boolean | Omit the bulky fields — `arguments`, `response` — and narrow `metadata` to a contextual whitelist (default: false). See below. | #### `exclude_payloads` and the contextual metadata whitelist diff --git a/frontend/package-lock.json b/frontend/package-lock.json index afbfcbd71..eaede1f20 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -743,6 +743,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -759,6 +760,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -775,6 +777,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -791,6 +794,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -807,6 +811,7 @@ "cpu": [ "arm" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -823,9 +828,7 @@ "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -842,9 +845,7 @@ "cpu": [ "arm64" ], - "libc": [ - "musl" - ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -861,9 +862,7 @@ "cpu": [ "ppc64" ], - "libc": [ - "glibc" - ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -880,9 +879,7 @@ "cpu": [ "s390x" ], - "libc": [ - "glibc" - ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -899,9 +896,7 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -918,9 +913,7 @@ "cpu": [ "x64" ], - "libc": [ - "musl" - ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -937,6 +930,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -953,6 +947,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -969,6 +964,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -3469,6 +3465,7 @@ "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, "hasInstallScript": true, "license": "MIT", "optional": true, @@ -3700,7 +3697,7 @@ "version": "2.7.0", "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", - "devOptional": true, + "dev": true, "license": "MIT", "bin": { "jiti": "lib/jiti-cli.mjs" @@ -5513,6 +5510,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MPL-2.0", "optional": true, "os": [ @@ -5533,6 +5531,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MPL-2.0", "optional": true, "os": [ @@ -5553,6 +5552,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MPL-2.0", "optional": true, "os": [ @@ -5573,6 +5573,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MPL-2.0", "optional": true, "os": [ @@ -5593,6 +5594,7 @@ "cpu": [ "arm" ], + "dev": true, "license": "MPL-2.0", "optional": true, "os": [ @@ -5613,9 +5615,7 @@ "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], + "dev": true, "license": "MPL-2.0", "optional": true, "os": [ @@ -5636,9 +5636,7 @@ "cpu": [ "arm64" ], - "libc": [ - "musl" - ], + "dev": true, "license": "MPL-2.0", "optional": true, "os": [ @@ -5659,9 +5657,7 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], + "dev": true, "license": "MPL-2.0", "optional": true, "os": [ @@ -5682,9 +5678,7 @@ "cpu": [ "x64" ], - "libc": [ - "musl" - ], + "dev": true, "license": "MPL-2.0", "optional": true, "os": [ @@ -5705,6 +5699,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MPL-2.0", "optional": true, "os": [ @@ -5725,6 +5720,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MPL-2.0", "optional": true, "os": [ diff --git a/frontend/src/components/ActivityWidget.vue b/frontend/src/components/ActivityWidget.vue index 2fa8fda71..bafcfad84 100644 --- a/frontend/src/components/ActivityWidget.vue +++ b/frontend/src/components/ActivityWidget.vue @@ -64,7 +64,18 @@ {{ formatPreflightSummary(activity.metadata) || 'Preflight' }} -
{{ formatRelativeTime(activity.timestamp) }}
+
+
{{ formatRelativeTime(activity.timestamp) }}
+ + + ↳ via code_execution + +
`, child → parent with + * `?request_id=`. + */ + parent_id?: string metadata?: Record // Spec 026: Sensitive data detection fields has_sensitive_data?: boolean diff --git a/frontend/src/utils/activity.ts b/frontend/src/utils/activity.ts index 6ef4c1cd5..b1b2c3677 100644 --- a/frontend/src/utils/activity.ts +++ b/frontend/src/utils/activity.ts @@ -130,6 +130,40 @@ const MAX_PREFLIGHT_SUMMARY_REASONS = 3 export const isPreflightActivity = (activity?: { type?: string } | null): boolean => activity?.type === 'preflight' +// --- code_execution parent / sub-call linkage ------------------------------ +// +// One `code_execution` call runs a script that may invoke many upstream tools. +// The activity log records that as a TREE, not a flat list: +// +// internal_tool_call code_execution request_id = +// └─ tool_call github:create_issue parent_id = +// └─ tool_call slack:post_message parent_id = +// +// Both ends are recognisable from a single record, so the table, the widget and +// the detail drawer all agree on what is a parent and what is a sub-call. + +/** Minimal record shape the linkage helpers need. */ +interface ActivityLinkFields { + type?: string + tool_name?: string + parent_id?: string + metadata?: Record | null +} + +/** + * True for the PARENT record of a sandboxed run: the built-in `code_execution` + * tool. `metadata.internal_tool_name` is the authoritative field; `tool_name` is + * the fallback for records that only carry it there. The `internal_tool_call` + * type is required in both cases — an upstream server is free to expose a tool + * of its own called "code_execution", and that one fans out into nothing. + */ +export const isCodeExecutionActivity = (a?: ActivityLinkFields | null): boolean => + a?.type === 'internal_tool_call' && + (a?.metadata?.internal_tool_name === 'code_execution' || a?.tool_name === 'code_execution') + +/** True for a sub-call: a record that names the parent it was dispatched from. */ +export const isChildCall = (a?: ActivityLinkFields | null): boolean => Boolean(a?.parent_id) + /** * Read `metadata.reasons` into a DETERMINISTIC order: most frequent first, ties * broken alphabetically. Object key order is insertion-dependent, so without the diff --git a/frontend/src/views/Activity.vue b/frontend/src/views/Activity.vue index 0e01f1ec6..c860faff9 100644 --- a/frontend/src/views/Activity.vue +++ b/frontend/src/views/Activity.vue @@ -287,6 +287,19 @@ + + + ↳ Sub-calls of {{ shortId(filterParentId) }} + + + + Server: {{ filterServer }} Status: {{ filterStatus }} Auth: {{ filterAuthType === 'admin' ? '🔑 Admin' : '🤖 Agent' }} @@ -358,6 +371,7 @@ {{ formatRelativeTime(activity.timestamp) }}
-
- {{ getTypeIcon(activity.type) }} - {{ formatType(activity.type) }} +
+
+ {{ getTypeIcon(activity.type) }} + {{ formatType(activity.type) }} +
+ + + ↳ via code_execution + + + 🧩 code_execution +
@@ -569,6 +606,41 @@ Source: {{ selectedActivity.source }}
+
+ Request ID: + {{ selectedActivity.request_id }} +
+
+ Parent call: + {{ selectedActivity.parent_id }} +
+ + + +
+ +
@@ -786,6 +858,8 @@ import { import { formatPreflightSummary, getPreflightVerdictBadgeClass, + isChildCall, + isCodeExecutionActivity, isPreflightActivity, preflightIdsCount, preflightPerTool, @@ -816,6 +890,10 @@ const filterAuthType = ref('') // Spec 028: '' | 'admin' | 'agent' const filterAgentName = ref('') // Spec 028: filter by agent token name const filterStartDate = ref('') const filterEndDate = ref('') +// Sub-call view: the request_id of a code_execution parent. Applied BOTH +// client-side (so the visible list narrows immediately) and as a server-side +// query param (so sub-calls beyond the 200 loaded rows are included). +const filterParentId = ref('') // Activity types configuration (Spec 024: includes new types) const activityTypes = [ @@ -1026,12 +1104,18 @@ const getSessionLabel = (sessionId: string): string => { } const hasActiveFilters = computed(() => { - return selectedTypes.value.length > 0 || filterServer.value || filterSession.value || filterStatus.value || filterSensitiveData.value || filterSeverity.value || filterAuthType.value || filterAgentName.value || filterStartDate.value || filterEndDate.value + return selectedTypes.value.length > 0 || filterServer.value || filterSession.value || filterStatus.value || filterSensitiveData.value || filterSeverity.value || filterAuthType.value || filterAgentName.value || filterStartDate.value || filterEndDate.value || filterParentId.value }) const filteredActivities = computed(() => { let result = activities.value + // Sub-calls of one code_execution run. Kept client-side as well as on the + // request so the list is correct even if a refresh (SSE, poll) races ahead. + if (filterParentId.value) { + result = result.filter(a => a.parent_id === filterParentId.value) + } + // Multi-type filter (Spec 024): OR logic - show activities matching ANY selected type if (selectedTypes.value.length > 0) { result = result.filter(a => selectedTypes.value.includes(a.type)) @@ -1122,7 +1206,7 @@ const loadActivities = async () => { try { const [activitiesResponse, summaryResponse] = await Promise.all([ - api.getActivities({ limit: 200 }), + api.getActivities({ limit: 200, parent_id: filterParentId.value || undefined }), api.getActivitySummary('24h') ]) @@ -1155,6 +1239,87 @@ const clearFilters = () => { filterStartDate.value = '' filterEndDate.value = '' currentPage.value = 1 + + // The parent filter is the only one narrowed on the SERVER too, so leaving it + // needs a refetch — the loaded rows are just this run's sub-calls. + const hadParentFilter = Boolean(filterParentId.value) + filterParentId.value = '' + if (hadParentFilter) void loadActivities() +} + +/** Last 8 chars of a correlation id — enough to recognise, short enough to fit. */ +const shortId = (id: string): string => (id.length > 8 ? `…${id.slice(-8)}` : id) + +/** Sub-calls of this run among the rows we hold. */ +const subCallCount = (parent: ActivityRecord): number => { + if (!parent.request_id) return 0 + return activities.value.filter(a => a.parent_id === parent.request_id).length +} + +/** + * Parent -> children. Narrows the list to this run's sub-calls and refetches + * with `parent_id` so children outside the loaded page come along. + */ +const viewSubCalls = async (parent: ActivityRecord) => { + if (!parent.request_id) return + filterParentId.value = parent.request_id + currentPage.value = 1 + closeDetailDrawer() + await loadActivities() +} + +/** Leave the sub-call view and restore the normal list. */ +const clearParentFilter = async () => { + if (!filterParentId.value) return + filterParentId.value = '' + currentPage.value = 1 + await loadActivities() +} + +/** + * Child -> parent. The parent is never a child of itself, so it cannot be in a + * parent_id-filtered list: drop the filter, then locate the parent by exact + * correlation id — from the loaded rows, else straight from the API (the run may + * be older than the 200 rows we hold). + */ +const viewParentCall = async (child: ActivityRecord) => { + const parentId = child.parent_id + if (!parentId) return + + const hadParentFilter = Boolean(filterParentId.value) + filterParentId.value = '' + currentPage.value = 1 + + let parent = activities.value.find(a => a.request_id === parentId) + if (hadParentFilter || !parent) { + await loadActivities() + parent = activities.value.find(a => a.request_id === parentId) + } + + if (!parent) { + const response = await api.getActivities({ request_id: parentId, limit: 1 }) + const fetched = response.success ? response.data?.activities?.[0] : undefined + if (fetched) { + parent = fetched + // Splice it in so the row the drawer describes is also in the table. + if (!activities.value.some(a => a.id === fetched.id)) { + activities.value = [fetched, ...activities.value] + } + } + } + + if (parent) { + selectActivity(parent) + return + } + + // Retention (90 days) can outlive a record's parent; say so instead of + // silently doing nothing, but never blank the table over it. + systemStore.addToast({ + type: 'warning', + title: 'Parent call not found', + message: `No activity record with request id ${parentId} is still available.`, + }) } // Toggle type filter (Spec 024: multi-select support) @@ -1209,6 +1374,8 @@ const exportActivities = (format: 'json' | 'csv') => { type: selectedTypes.value.length > 0 ? selectedTypes.value.join(',') : undefined, server: filterServer.value || undefined, status: filterStatus.value || undefined, + // Exporting from the sub-call view exports that run's sub-calls. + parent_id: filterParentId.value || undefined, }) window.open(url, '_blank') } diff --git a/frontend/tests/unit/activity-parent-child.spec.ts b/frontend/tests/unit/activity-parent-child.spec.ts new file mode 100644 index 000000000..b434a56de --- /dev/null +++ b/frontend/tests/unit/activity-parent-child.spec.ts @@ -0,0 +1,66 @@ +import { describe, it, expect } from 'vitest' +import { isChildCall, isCodeExecutionActivity } from '../../src/utils/activity' + +// Activity transparency: a `code_execution` call fans out into N sandboxed +// sub-calls. The parent keeps ONE internal_tool_call record (request_id = +// parentCallID); every sub-call gets its own tool_call record carrying +// parent_id = parentCallID. The Web UI has to be able to recognise both ends of +// that link from a record alone, without re-deriving the rule in two templates. + +describe('isCodeExecutionActivity', () => { + it('is true for an internal_tool_call whose metadata names code_execution', () => { + expect( + isCodeExecutionActivity({ + type: 'internal_tool_call', + metadata: { internal_tool_name: 'code_execution' }, + }) + ).toBe(true) + }) + + it('is true for an internal_tool_call whose tool_name is code_execution', () => { + // Older records (and the CLI surface) put the built-in name in tool_name. + expect( + isCodeExecutionActivity({ type: 'internal_tool_call', tool_name: 'code_execution' }) + ).toBe(true) + }) + + it('is false for another internal tool', () => { + expect( + isCodeExecutionActivity({ + type: 'internal_tool_call', + metadata: { internal_tool_name: 'retrieve_tools' }, + }) + ).toBe(false) + }) + + it('is false for an upstream tool_call, even one literally named code_execution', () => { + // A rogue upstream server may expose a tool called "code_execution"; only + // the built-in (internal_tool_call) is the sandbox parent. + expect(isCodeExecutionActivity({ type: 'tool_call', tool_name: 'code_execution' })).toBe(false) + }) + + it('is false for missing / empty input', () => { + expect(isCodeExecutionActivity(null)).toBe(false) + expect(isCodeExecutionActivity(undefined)).toBe(false) + expect(isCodeExecutionActivity({})).toBe(false) + }) +}) + +describe('isChildCall', () => { + it('is true when the record carries a parent_id', () => { + expect(isChildCall({ parent_id: 'req-parent-1' })).toBe(true) + }) + + it('is false for a top-level record', () => { + expect(isChildCall({ type: 'tool_call' })).toBe(false) + }) + + it('is false for an empty parent_id (omitempty absent field, never a blank link)', () => { + expect(isChildCall({ parent_id: '' })).toBe(false) + }) + + it('is false for missing input', () => { + expect(isChildCall(null)).toBe(false) + expect(isChildCall(undefined)).toBe(false) + }) +}) diff --git a/frontend/tests/unit/activity-parent-navigation.spec.ts b/frontend/tests/unit/activity-parent-navigation.spec.ts new file mode 100644 index 000000000..90cd1d5ab --- /dev/null +++ b/frontend/tests/unit/activity-parent-navigation.spec.ts @@ -0,0 +1,192 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest' +import { mount, flushPromises } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import { createRouter, createWebHistory } from 'vue-router' + +// Activity transparency: one `code_execution` run must be navigable in BOTH +// directions from the Activity Log — +// parent -> children GET /api/v1/activity?parent_id= +// child -> parent GET /api/v1/activity?request_id= +// The sub-call view is a real filter (server-side too, so children beyond the +// loaded page are included) and clearing it restores the normal list. + +const PARENT = { + id: 'act-parent', + type: 'internal_tool_call', + status: 'success', + timestamp: '2026-08-21T10:00:00Z', + tool_name: 'code_execution', + request_id: 'req-parent-abcdefgh', + duration_ms: 900, + metadata: { internal_tool_name: 'code_execution' }, +} + +const CHILD_A = { + id: 'act-child-a', + type: 'tool_call', + status: 'success', + timestamp: '2026-08-21T10:00:01Z', + server_name: 'github', + tool_name: 'create_issue', + request_id: 'req-child-a', + parent_id: 'req-parent-abcdefgh', + duration_ms: 120, +} + +const CHILD_B = { + id: 'act-child-b', + type: 'tool_call', + status: 'error', + timestamp: '2026-08-21T10:00:02Z', + server_name: 'slack', + tool_name: 'post_message', + request_id: 'req-child-b', + parent_id: 'req-parent-abcdefgh', + duration_ms: 80, +} + +const UNRELATED = { + id: 'act-plain', + type: 'tool_call', + status: 'success', + timestamp: '2026-08-21T09:59:00Z', + server_name: 'github', + tool_name: 'list_repos', + request_id: 'req-plain', + duration_ms: 40, +} + +vi.mock('@/services/api', () => { + const ok = (data: unknown) => Promise.resolve({ success: true, data }) + return { + default: { + // The mock behaves like the contract: parent_id narrows to sub-calls, + // request_id resolves one record by correlation id. + getActivities: vi.fn((params?: { parent_id?: string; request_id?: string }) => { + const all = [PARENT, CHILD_A, CHILD_B, UNRELATED] + let activities = all + if (params?.parent_id) { + activities = all.filter(a => (a as { parent_id?: string }).parent_id === params.parent_id) + } else if (params?.request_id) { + activities = all.filter(a => a.request_id === params.request_id) + } + return ok({ activities, total: activities.length, limit: 200, offset: 0 }) + }), + getActivitySummary: vi.fn(() => + ok({ + period: '24h', + total_count: 4, + success_count: 3, + error_count: 1, + blocked_count: 0, + rejected_count: 0, + }) + ), + getSessions: vi.fn(() => ok({ sessions: [] })), + getActivityExportUrl: vi.fn(() => 'http://localhost/api/v1/activity/export?format=json'), + }, + } +}) + +async function mountActivity() { + const api = (await import('@/services/api')).default + const Activity = (await import('@/views/Activity.vue')).default + const router = createRouter({ + history: createWebHistory(), + routes: [ + { path: '/activity', component: { template: '
' } }, + { path: '/servers/:serverName', component: { template: '
' } }, + ], + }) + await router.push('/activity') + await router.isReady() + const wrapper = mount(Activity, { global: { plugins: [createPinia(), router] } }) + await flushPromises() + return { wrapper, api: api as unknown as { getActivities: ReturnType } } +} + +type Wrapper = Awaited>['wrapper'] + +const rows = (wrapper: Wrapper) => wrapper.findAll('[data-test="activity-row"]') + +/** The one row carrying the code_execution PARENT badge. */ +const parentRowOf = (wrapper: Wrapper) => + rows(wrapper).find(r => r.find('[data-test="activity-parent-badge"]').exists())! + +describe('Activity Log — code_execution parent/sub-call navigation', () => { + beforeEach(() => { + setActivePinia(createPinia()) + vi.clearAllMocks() + }) + + it('badges sub-call rows and the code_execution parent row', async () => { + const { wrapper } = await mountActivity() + + expect(rows(wrapper)).toHaveLength(4) + expect(wrapper.findAll('[data-test="activity-child-badge"]')).toHaveLength(2) + expect(wrapper.find('[data-test="activity-child-badge"]').text()).toContain('via code_execution') + expect(wrapper.findAll('[data-test="activity-parent-badge"]')).toHaveLength(1) + }) + + it('filters to the sub-calls of a run and refetches with parent_id', async () => { + const { wrapper, api } = await mountActivity() + + // Open the parent row's drawer. Sub-call rows also mention code_execution + // (in their "↳ via" badge), so key on the parent badge instead. + const parentRow = parentRowOf(wrapper) + await parentRow.trigger('click') + await flushPromises() + + const viewSubCalls = wrapper.find('[data-test="activity-view-subcalls"]') + expect(viewSubCalls.exists()).toBe(true) + expect(viewSubCalls.text()).toContain('(2)') + + await viewSubCalls.trigger('click') + await flushPromises() + + expect(api.getActivities).toHaveBeenCalledWith( + expect.objectContaining({ parent_id: 'req-parent-abcdefgh' }) + ) + const visible = rows(wrapper) + expect(visible).toHaveLength(2) + expect(visible.map(r => r.text()).join(' ')).not.toContain('list_repos') + expect(wrapper.find('[data-test="activity-parent-filter-chip"]').exists()).toBe(true) + }) + + it('restores the full list when the sub-call filter chip is cleared', async () => { + const { wrapper } = await mountActivity() + + const parentRow = parentRowOf(wrapper) + await parentRow.trigger('click') + await flushPromises() + await wrapper.find('[data-test="activity-view-subcalls"]').trigger('click') + await flushPromises() + expect(rows(wrapper)).toHaveLength(2) + + await wrapper.find('[data-test="activity-parent-filter-chip"]').trigger('click') + await flushPromises() + + expect(rows(wrapper)).toHaveLength(4) + expect(wrapper.find('[data-test="activity-parent-filter-chip"]').exists()).toBe(false) + }) + + it('jumps from a sub-call back to its parent call', async () => { + const { wrapper } = await mountActivity() + + const childRow = rows(wrapper).find(r => r.text().includes('create_issue'))! + await childRow.trigger('click') + await flushPromises() + + const viewParent = wrapper.find('[data-test="activity-view-parent"]') + expect(viewParent.exists()).toBe(true) + + await viewParent.trigger('click') + await flushPromises() + + // The drawer now describes the parent run. + const drawer = wrapper.find('.drawer-side') + expect(drawer.text()).toContain('req-parent-abcdefgh') + expect(wrapper.find('[data-test="activity-view-subcalls"]').exists()).toBe(true) + expect(wrapper.find('[data-test="activity-view-parent"]').exists()).toBe(false) + }) +}) diff --git a/internal/contracts/activity.go b/internal/contracts/activity.go index 563964457..70d19b472 100644 --- a/internal/contracts/activity.go +++ b/internal/contracts/activity.go @@ -47,6 +47,7 @@ type ActivityRecord struct { SessionID string `json:"session_id,omitempty"` // MCP transport session ID (regenerated on every reconnect) WorkSessionID string `json:"work_session_id,omitempty"` // Spec 082: one client, one project, across reconnects RequestID string `json:"request_id,omitempty"` // HTTP request ID for correlation + ParentID string `json:"parent_id,omitempty"` // Correlation id of the parent call (the code_execution whose sandbox issued this sub-call) Metadata map[string]interface{} `json:"metadata,omitempty" swaggertype:"object"` // Additional context-specific data // Sensitive data detection fields (Spec 026) diff --git a/internal/httpapi/activity.go b/internal/httpapi/activity.go index d81bd2e7c..d13cdd0c8 100644 --- a/internal/httpapi/activity.go +++ b/internal/httpapi/activity.go @@ -88,6 +88,13 @@ func parseActivityFilters(r *http.Request) storage.ActivityFilter { filter.RequestID = requestID } + // Parent ID filter: the sub-calls one code_execution issued. Navigation is + // symmetric — parent→children is ?parent_id=, and + // child→parent is ?request_id=. + if parentID := q.Get("parent_id"); parentID != "" { + filter.ParentID = parentID + } + // Include call_tool_* internal tool calls (default: exclude the ones a // tool_call record already covers — successful and concurrency-rejected). // Set include_call_tool=true to show every internal tool call. @@ -135,6 +142,7 @@ func parseActivityFilters(r *http.Request) storage.ActivityFilter { // @Param status query string false "Filter by status" Enums(success, error, blocked, rejected) // @Param intent_type query string false "Filter by intent operation type (Spec 018)" Enums(read, write, destructive) // @Param request_id query string false "Filter by HTTP request ID for log correlation (Spec 021)" +// @Param parent_id query string false "Filter by parent call id — returns the sub-calls one code_execution issued" // @Param include_call_tool query bool false "Include successful call_tool_* internal tool calls (default: false, excluded to avoid duplicates)" // @Param sensitive_data query bool false "Filter by sensitive data detection (true=has detections, false=no detections)" // @Param detection_type query string false "Filter by specific detection type (e.g., 'aws_access_key', 'credit_card')" @@ -311,6 +319,7 @@ func storageToContractActivity(a *storage.ActivityRecord) contracts.ActivityReco SessionID: a.SessionID, WorkSessionID: a.WorkSessionID, RequestID: a.RequestID, + ParentID: a.ParentID, Metadata: a.Metadata, // Sensitive data detection fields (Spec 026) HasSensitiveData: hasSensitiveData, @@ -407,6 +416,7 @@ func storageToContractActivityForExport(a *storage.ActivityRecord, includeBodies SessionID: a.SessionID, WorkSessionID: a.WorkSessionID, RequestID: a.RequestID, + ParentID: a.ParentID, Metadata: a.Metadata, // Sensitive data detection fields (Spec 026) HasSensitiveData: hasSensitiveData, @@ -436,6 +446,8 @@ func storageToContractActivityForExport(a *storage.ActivityRecord, includeBodies // @Param session_id query string false "Filter by MCP transport session ID" // @Param work_session_id query string false "Filter by work session (one client, one project, across reconnects)" // @Param status query string false "Filter by status" +// @Param request_id query string false "Filter by HTTP request ID for log correlation (Spec 021)" +// @Param parent_id query string false "Filter by parent call id — exports the sub-calls one code_execution issued" // @Param start_time query string false "Filter activities after this time (RFC3339)" // @Param end_time query string false "Filter activities before this time (RFC3339)" // @Param limit query int false "Maximum records to export (1-50000, default 10000)" @@ -496,7 +508,9 @@ func (s *Server) handleExportActivity(w http.ResponseWriter, r *http.Request) { // Write CSV header if format is CSV if format == "csv" { - csvHeader := "id,type,source,server_name,tool_name,status,error_message,duration_ms,timestamp,session_id,request_id,response_truncated\n" + // parent_id is APPENDED, never inserted: existing CSV consumers index by + // column position, so a new column has to land after the last one. + csvHeader := "id,type,source,server_name,tool_name,status,error_message,duration_ms,timestamp,session_id,request_id,response_truncated,parent_id\n" if _, err := w.Write([]byte(csvHeader)); err != nil { s.logger.Errorw("Failed to write CSV header", "error", err) return @@ -569,6 +583,7 @@ func activityToCSVRow(a *storage.ActivityRecord) string { escapeCSV(a.SessionID), escapeCSV(a.RequestID), strconv.FormatBool(a.ResponseTruncated), + escapeCSV(a.ParentID), }, ",") + "\n" } @@ -620,26 +635,29 @@ func (s *Server) handleActivitySummary(w http.ResponseWriter, r *http.Request) { endTime := time.Now().UTC() startTime := endTime.Add(-duration) - // Build filter for the time range + // Build filter for the time range. + // + // Limit stays 0 and the records are STREAMED rather than listed: this is a + // counting query over the whole period, and ListActivities runs + // ActivityFilter.Validate(), which coerces limit 0 to 50 and caps it at 100. + // The summary therefore used to describe the newest 50 records and label the + // answer "24h" — on a busy proxy the totals, the status split and the top + // server/tool lists were all computed from a few minutes of traffic. + // StreamActivities applies the same Matches() filter but treats limit 0 as + // "no limit", so the counters see every record in the window. filter := storage.DefaultActivityFilter() filter.StartTime = startTime filter.EndTime = endTime - filter.Limit = 0 // Get all records - - // Get all activities in the time range - activities, _, err := s.controller.ListActivities(filter) - if err != nil { - s.logger.Errorw("Failed to list activities for summary", "error", err) - s.writeError(w, r, http.StatusInternalServerError, "Failed to get activity summary") - return - } + filter.Limit = 0 // Calculate summary statistics var totalCount, successCount, errorCount, blockedCount, rejectedCount int serverCounts := make(map[string]int) toolCounts := make(map[string]int) - for _, a := range activities { + // The stream holds a read transaction open until the channel is drained or + // closed, so this loop must always run to completion. + for a := range s.controller.StreamActivities(filter) { totalCount++ switch a.Status { case storage.ActivityStatusSuccess: diff --git a/internal/httpapi/activity_summary_scope_test.go b/internal/httpapi/activity_summary_scope_test.go new file mode 100644 index 000000000..594867c42 --- /dev/null +++ b/internal/httpapi/activity_summary_scope_test.go @@ -0,0 +1,124 @@ +package httpapi + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// summaryScopeController serves the same record set through both the paginated +// list path and the streaming path, so a summary computed over either one is +// comparable. +type summaryScopeController struct { + baseController + activities []*storage.ActivityRecord +} + +func (m *summaryScopeController) GetCurrentConfig() any { + return &config.Config{APIKey: "test-key"} +} + +func (m *summaryScopeController) ListActivities(filter storage.ActivityFilter) ([]*storage.ActivityRecord, int, error) { + // storage.Manager.ListActivities normalises the filter before it reads + // anything, and that normalisation is the whole bug: Validate() turns limit + // 0 into 50 and caps it at 100. A mock that skipped it would let the + // regression pass unnoticed. + filter.Validate() + + var matched []*storage.ActivityRecord + for _, a := range m.activities { + if filter.Matches(a) { + matched = append(matched, a) + } + } + total := len(matched) + if filter.Limit > 0 && len(matched) > filter.Limit { + matched = matched[:filter.Limit] + } + return matched, total, nil +} + +func (m *summaryScopeController) StreamActivities(filter storage.ActivityFilter) <-chan *storage.ActivityRecord { + ch := make(chan *storage.ActivityRecord) + go func() { + defer close(ch) + sent := 0 + for _, a := range m.activities { + if !filter.Matches(a) { + continue + } + if filter.Limit > 0 && sent >= filter.Limit { + return + } + ch <- a + sent++ + } + }() + return ch +} + +// GET /api/v1/activity/summary answers a question about a PERIOD ("24h"), so it +// has to see the whole period. It used to run through the paginated list path, +// whose Validate() turns limit 0 into 50 and caps it at 100 — so on any proxy +// busier than a demo, the totals and the status split described the newest 50 +// records while claiming to describe 24 hours. +func TestActivitySummary_CountsEveryRecordInThePeriodNotJustAPage(t *testing.T) { + const ( + successes = 120 + errors = 40 + total = successes + errors + ) + now := time.Now().UTC() + + var activities []*storage.ActivityRecord + // Newest first, matching the storage cursor's order: the errors are OLDER + // than a 50-record page, so a paginated summary misses all of them. + for i := 0; i < successes; i++ { + activities = append(activities, &storage.ActivityRecord{ + ID: fmt.Sprintf("ok-%d", i), Type: storage.ActivityTypeToolCall, + ServerName: "github", ToolName: "search", + Status: storage.ActivityStatusSuccess, Timestamp: now.Add(-time.Duration(i) * time.Minute), + }) + } + for i := 0; i < errors; i++ { + activities = append(activities, &storage.ActivityRecord{ + ID: fmt.Sprintf("err-%d", i), Type: storage.ActivityTypeToolCall, + ServerName: "gitlab", ToolName: "list", + Status: storage.ActivityStatusError, Timestamp: now.Add(-time.Duration(successes+i) * time.Minute), + }) + } + + srv := NewServer(&summaryScopeController{activities: activities}, zap.NewNop().Sugar(), nil) + + req := httptest.NewRequest(http.MethodGet, "/api/v1/activity/summary?period=24h", nil) + req.Header.Set("X-API-Key", "test-key") + w := httptest.NewRecorder() + srv.ServeHTTP(w, req) + + require.Equal(t, http.StatusOK, w.Code) + + var resp struct { + Success bool `json:"success"` + Data contracts.ActivitySummaryResponse `json:"data"` + } + require.NoError(t, json.NewDecoder(w.Body).Decode(&resp)) + require.True(t, resp.Success) + + assert.Equal(t, total, resp.Data.TotalCount, "the summary covers the period, not the first page") + assert.Equal(t, successes, resp.Data.SuccessCount) + assert.Equal(t, errors, resp.Data.ErrorCount, "the older errors must not fall off the end of a page") + require.NotEmpty(t, resp.Data.TopServers) + assert.Equal(t, "github", resp.Data.TopServers[0].Name) + require.Len(t, resp.Data.TopServers, 2, "both servers are in range, not only the newest page's") +} diff --git a/internal/runtime/activity_service.go b/internal/runtime/activity_service.go index 160021fbc..f27ff61d9 100644 --- a/internal/runtime/activity_service.go +++ b/internal/runtime/activity_service.go @@ -568,6 +568,9 @@ func (s *ActivityService) handleToolCallCompleted(evt Event) { // Spec 084 FR-007b: pre-encoding detection scan input; empty means "scan // response as before". detectionText := getStringPayload(evt.Payload, "detection_text") + // Correlation id of the parent code_execution call (empty for a top-level + // dispatch). First-class on the record so ?parent_id= can filter on it. + parentID := getStringPayload(evt.Payload, "parent_id") // Default source to "mcp" if not specified (backwards compatibility) activitySource := storage.ActivitySourceMCP if source != "" { @@ -620,6 +623,7 @@ func (s *ActivityService) handleToolCallCompleted(evt Event) { SessionID: sessionID, WorkSessionID: s.resolveWorkSession(sessionID), RequestID: requestID, + ParentID: parentID, Metadata: metadata, RequestBytes: requestBytes, ResponseBytes: responseBytes, @@ -908,6 +912,17 @@ func (s *ActivityService) handleInternalToolCall(evt Event) { zap.String("id", record.ID), zap.String("internal_tool_name", internalToolName), zap.String("status", status)) + + // Fold into the usage aggregate so the timeline matches the glance. + // Without this the LIVE aggregate skipped every built-in call while a + // cold-start rebuild (which re-scans persisted records through the same + // Apply) counted them — so the histogram silently changed shape on + // restart. Apply itself decides what is admissible: call_tool_* records + // are dropped there, because the direct dispatch already emitted a + // paired tool_call. + if s.usage != nil { + s.usage.Apply(record) + } } } diff --git a/internal/runtime/event_bus.go b/internal/runtime/event_bus.go index caf550c2c..17ca7db80 100644 --- a/internal/runtime/event_bus.go +++ b/internal/runtime/event_bus.go @@ -427,7 +427,9 @@ func (r *Runtime) EmitActivityToolCallStarted(serverName, toolName, sessionID, r // detectionText is the spec-084 pre-encoding sensitive-data scan input (FR-007b); // empty means "scan response as before" (feature off / non-call_tool_* paths) // toonOutput is the spec-084 per-block encoding decision metadata (FR-010) - optional -func (r *Runtime) EmitActivityToolCallCompleted(serverName, toolName, sessionID, requestID, source, status, errorMsg string, durationMs int64, arguments map[string]interface{}, response string, responseTruncated bool, toolVariant string, intent map[string]interface{}, contentTrust, profile string, requestBytes, responseBytes int, detectionText string, toonOutput map[string]interface{}) { +// parentID is the correlation id of the parent code_execution call for a +// sandbox sub-call; empty for every top-level dispatch +func (r *Runtime) EmitActivityToolCallCompleted(serverName, toolName, sessionID, requestID, source, status, errorMsg string, durationMs int64, arguments map[string]interface{}, response string, responseTruncated bool, toolVariant string, intent map[string]interface{}, contentTrust, profile string, requestBytes, responseBytes int, detectionText string, toonOutput map[string]interface{}, parentID string) { // Spec 042: classify failed tool calls into the upstream error categories. // We never record the error message itself; only a fixed enum value. if status == "error" && errorMsg != "" { @@ -490,6 +492,13 @@ func (r *Runtime) EmitActivityToolCallCompleted(serverName, toolName, sessionID, if toonOutput != nil { payload["toon_output"] = toonOutput } + // Correlation id of the code_execution whose sandbox issued this sub-call. + // Only set when there IS a parent, so every top-level dispatch keeps the + // payload it emitted before — and the SSE /events stream, which forwards + // this map verbatim, carries parent_id for free. + if parentID != "" { + payload["parent_id"] = parentID + } r.publishEvent(newEvent(EventTypeActivityToolCallCompleted, payload)) } diff --git a/internal/runtime/prechurn_lifecycle_test.go b/internal/runtime/prechurn_lifecycle_test.go index 2a9c90435..8ef26efb4 100644 --- a/internal/runtime/prechurn_lifecycle_test.go +++ b/internal/runtime/prechurn_lifecycle_test.go @@ -168,7 +168,7 @@ func TestRuntimeCloseWaitsForActivityWritersBeforeMarkerResolve(t *testing.T) { for { rt.EmitActivityToolCallCompleted( "prechurn-srv", "prechurn-tool", "sess-1", "req-1", "mcp", - "success", "", 7, nil, "ok", false, "", nil, "", "", 0, 0, "", nil) + "success", "", 7, nil, "ok", false, "", nil, "", "", 0, 0, "", nil, "") if snap := rt.ActivityService().UsageSnapshot(); snap != nil && len(snap.Tools) > 0 { break } diff --git a/internal/runtime/usage_aggregate.go b/internal/runtime/usage_aggregate.go index 43fe2c6d4..39db6337f 100644 --- a/internal/runtime/usage_aggregate.go +++ b/internal/runtime/usage_aggregate.go @@ -2,6 +2,7 @@ package runtime import ( "sort" + "strings" "sync" "sync/atomic" "time" @@ -139,12 +140,26 @@ type UsageAggregate struct { Tools map[string]*ToolUsage `json:"tools"` Buckets map[int64]*TimeBucket `json:"buckets"` // key = bucket start unix seconds UpdatedAt time.Time `json:"updated_at"` + // AdmissionVersion stamps which population rule built this aggregate. A + // persisted snapshot whose stamp differs from usageAdmissionVersion was + // counted under a different rule and cannot be patched incrementally — + // the loader discards it and rebuilds from a full activity scan instead. + AdmissionVersion int `json:"admission_version,omitempty"` } +// usageAdmissionVersion identifies the CURRENT admission rule for the +// aggregate. Bump it whenever Apply changes which records are counted (2: +// internal tool calls and blocked policy decisions joined the timeline; 3: +// management built-ins excluded again per GlanceSelection rule 1), so +// pre-change snapshots are rebuilt instead of carried forward with hours +// counted under the old rule. +const usageAdmissionVersion = 3 + func newUsageAggregate() *UsageAggregate { return &UsageAggregate{ - Tools: make(map[string]*ToolUsage), - Buckets: make(map[int64]*TimeBucket), + Tools: make(map[string]*ToolUsage), + Buckets: make(map[int64]*TimeBucket), + AdmissionVersion: usageAdmissionVersion, } } @@ -169,11 +184,25 @@ func (a *UsageAggregate) tool(server, toolName string) *ToolUsage { return tu } -// Apply folds a single activity record into the aggregate. It accepts executed -// tool_calls and blocked policy_decisions (the form a policy-prevented tool -// attempt is persisted as — MCP-835); all other records, and records without a -// tool name, are ignored. Apply is not safe for concurrent use; it is called -// only by the owning goroutine (see UsageStore). +// Apply folds a single activity record into the aggregate. Apply is not safe +// for concurrent use; it is called only by the owning goroutine (see +// UsageStore). +// +// Two populations live in here and they are NOT the same: +// +// - the per-tool rollup (ToolUsage) describes UPSTREAM TOOLS: calls, latency +// percentiles, byte averages, blocked and shed attempts. Only records that +// name an upstream tool belong in it. +// - the timeline (TimeBucket) describes WHAT THE USER SAW. It must match the +// glance row-for-row, or the bars under the list disagree with the list +// above them — the single most confusing thing a dashboard can do. +// +// The glance shows tool_calls, the internal tool calls that are mcpproxy's own +// work (retrieve_tools, describe_tool, code_execution, upstream_servers …) and +// blocked policy decisions, so all three enter the timeline. Internal +// call_tool_* records are the one exclusion: they mirror a direct dispatch that +// ALREADY emitted its own tool_call record with the same request id, so +// counting them too would double every direct call. func (a *UsageAggregate) Apply(rec *storage.ActivityRecord) { if rec == nil || rec.ToolName == "" { return @@ -185,9 +214,20 @@ func (a *UsageAggregate) Apply(rec *storage.ActivityRecord) { // averages or the executed-call timeline. a.applyRejected(rec) return + case rec.Type == storage.ActivityTypeToolCall && rec.Status == storage.ActivityStatusBlocked: + // A policy gate refused the dispatch (today: a code_execution sub-call, + // emitSubCallRefused). Same shape as a blocked policy_decision: the + // upstream never ran it, so it takes the Blocked counter and a failed + // bar in the timeline, not the executed-call statistics. + a.applyBlocked(rec) + return case rec.Type == storage.ActivityTypeToolCall: // folded below - case rec.Type == storage.ActivityTypePolicyDecision && rec.Status == storage.ActivityStatusBlocked: + case rec.Type == storage.ActivityTypeInternalToolCall: + a.applyInternalToolCall(rec) + return + case rec.Type == storage.ActivityTypePolicyDecision && + (rec.Status == storage.ActivityStatusBlocked || rec.Status == storage.ActivityStatusRejected): a.applyBlocked(rec) return default: @@ -221,16 +261,76 @@ func (a *UsageAggregate) Apply(rec *storage.ActivityRecord) { // applyBlocked folds a policy-blocked attempt into the per-tool Blocked counter. // A blocked attempt never executed the tool, so it contributes no Calls, -// latency, or bytes, and does not enter the executed-call timeline — it only -// bumps Blocked and LastUsed. This keeps the contract's per-tool `blocked` -// count non-zero (the field was previously dead) without polluting latency -// percentiles or byte averages with non-executed attempts. +// latency, or bytes to the PER-TOOL rollup — it only bumps Blocked and +// LastUsed, which keeps latency percentiles and byte averages free of attempts +// that never ran. +// +// It does enter the TIMELINE, as a call and as an error. The timeline mirrors +// the glance, and in the glance a blocked attempt is a red row the user made +// and did not get: leaving it out made a run that policy refused wholesale +// render as a flat, empty histogram under a list full of failures. func (a *UsageAggregate) applyBlocked(rec *storage.ActivityRecord) { tu := a.tool(rec.ServerName, rec.ToolName) tu.Blocked++ if rec.Timestamp.After(tu.LastUsed) { tu.LastUsed = rec.Timestamp } + a.countInTimeBucket(rec, true) +} + +// applyInternalToolCall folds one of mcpproxy's OWN tool calls (retrieve_tools, +// describe_tool, code_execution, upstream_servers, quarantine_security …) into +// the timeline only. +// +// Timeline-only is the point: these records name a BUILT-IN, not an upstream +// tool — most carry no server at all — so admitting them to the per-tool +// rollup would invent tool rows that no upstream owns and mix mcpproxy's own +// latency into upstream percentiles. But the user sees them in the glance, and +// before this the bars under that list counted none of them: an agent whose +// traffic was mostly retrieve_tools and code_execution saw an almost empty +// histogram. +// +// call_tool_* records are skipped because the direct dispatch that produced +// them also emitted a tool_call record for the same call (see +// handleCallToolVariant, which emits both) — counting both would double it. +// +// SUCCESSFUL internal calls count only for the built-ins the glance actually +// rows (GlanceSelection rule 3: retrieve_tools, describe_tool, +// code_execution): a successful upstream_servers or quarantine_security call +// is management chatter the glance hides, and counting it would put bars over +// hours with no rows. Failures count regardless — any internal failure is a +// glance row. +func (a *UsageAggregate) applyInternalToolCall(rec *storage.ActivityRecord) { + if strings.HasPrefix(rec.ToolName, storage.InternalCallToolPrefix) { + return + } + // Management built-ins never row in the glance, whatever their status + // (GlanceSelection rule 1), so they never bar either. + if glanceManagementBuiltins[rec.ToolName] { + return + } + if rec.Status == storage.ActivityStatusSuccess && !glanceInternalTools[rec.ToolName] { + return + } + // Anything the built-in did not complete is a failed row in the glance, + // whether it errored or a policy refused it. + a.countInTimeBucket(rec, rec.Status != storage.ActivityStatusSuccess) +} + +// glanceInternalTools are the built-ins whose SUCCESSFUL calls appear as rows +// in the tray glance (GlanceSelection.swift rule 3) and therefore in the +// timeline; glanceManagementBuiltins are excluded from the glance entirely +// (rule 1), success or failure. Keep both in lockstep with the Swift sets and +// with AppState.countsTowardUsageTimeline. +var glanceInternalTools = map[string]bool{ + "retrieve_tools": true, + "describe_tool": true, + "code_execution": true, +} + +var glanceManagementBuiltins = map[string]bool{ + "upstream_servers": true, + "quarantine_security": true, } // applyRejected folds a concurrency-limiter shed into the per-tool Rejected @@ -244,7 +344,18 @@ func (a *UsageAggregate) applyRejected(rec *storage.ActivityRecord) { } } +// applyTimeBucket counts an executed tool_call in the timeline, classifying it +// by its own status. func (a *UsageAggregate) applyTimeBucket(rec *storage.ActivityRecord) { + a.countInTimeBucket(rec, rec.Status == storage.ActivityStatusError) +} + +// countInTimeBucket is applyTimeBucket with the error classification supplied +// by the caller. The populations that reach the timeline disagree about what +// counts as a failure — a policy block is one, a built-in that answered +// "blocked" is one, an upstream tool_call is only one when its status is +// "error" — so the decision belongs to the admitting path, not here. +func (a *UsageAggregate) countInTimeBucket(rec *storage.ActivityRecord, isError bool) { start := rec.Timestamp.UTC().Truncate(usageBucketWidth) k := start.Unix() b := a.Buckets[k] @@ -253,7 +364,7 @@ func (a *UsageAggregate) applyTimeBucket(rec *storage.ActivityRecord) { a.Buckets[k] = b } b.Calls++ - if rec.Status == "error" { + if isError { b.Errors++ } if rec.ResponseBytes > 0 { @@ -291,9 +402,10 @@ func (a *UsageAggregate) Timeline() []TimeBucket { // clone returns a deep copy safe to publish to readers. func (a *UsageAggregate) clone() *UsageAggregate { c := &UsageAggregate{ - Tools: make(map[string]*ToolUsage, len(a.Tools)), - Buckets: make(map[int64]*TimeBucket, len(a.Buckets)), - UpdatedAt: a.UpdatedAt, + Tools: make(map[string]*ToolUsage, len(a.Tools)), + Buckets: make(map[int64]*TimeBucket, len(a.Buckets)), + UpdatedAt: a.UpdatedAt, + AdmissionVersion: a.AdmissionVersion, } for k, tu := range a.Tools { c.Tools[k] = tu.clone() diff --git a/internal/runtime/usage_aggregate_test.go b/internal/runtime/usage_aggregate_test.go index ab5d7c665..3e093cf96 100644 --- a/internal/runtime/usage_aggregate_test.go +++ b/internal/runtime/usage_aggregate_test.go @@ -41,15 +41,18 @@ func TestUsageAggregate_Apply_CountsAndBytes(t *testing.T) { require.NotNil(t, tu) assert.Equal(t, "github", tu.Server) assert.Equal(t, "search", tu.Tool) - assert.Equal(t, int64(5), tu.Calls) + // A blocked tool_call never executed (a policy gate refused the dispatch), + // so like a blocked policy_decision it takes only the Blocked counter and + // a failed timeline bar — not Calls, latency or byte statistics. + assert.Equal(t, int64(4), tu.Calls) assert.Equal(t, int64(1), tu.Errors) assert.Equal(t, int64(1), tu.Blocked) - // Byte sums exclude 0-byte records. + // Byte sums exclude 0-byte records and the refused dispatch. assert.Equal(t, int64(1000+2000+500), tu.RespBytesSum) assert.Equal(t, int64(3), tu.SizedRespCalls, "3 records had ResponseBytes>0") - assert.Equal(t, int64(200*4), tu.ReqBytesSum, "4 records had RequestBytes>0") - assert.Equal(t, int64(4), tu.SizedReqCalls) + assert.Equal(t, int64(200*3), tu.ReqBytesSum, "3 executed records had RequestBytes>0") + assert.Equal(t, int64(3), tu.SizedReqCalls) } func TestUsageAggregate_Apply_IgnoresNonToolCalls(t *testing.T) { @@ -67,9 +70,14 @@ func TestUsageAggregate_Apply_IgnoresNonToolCalls(t *testing.T) { // TestUsageAggregate_Apply_CountsBlockedPolicyDecisions (MCP-835 / Codex // finding #2): blocked tool attempts are persisted as policy_decision records, // not tool_calls. The aggregate must still count them so the contract's -// per-tool `blocked` field is non-zero. A blocked attempt never executed, so it -// contributes ONLY to Blocked (and LastUsed) — not Calls, latency, bytes, or -// the timeline (which tracks executed calls). +// per-tool `blocked` field is non-zero. A blocked attempt never executed, so in +// the PER-TOOL rollup it contributes ONLY to Blocked (and LastUsed) — not +// Calls, latency or bytes. +// +// It does enter the TIMELINE, and as an error: the timeline has to match the +// glance the user is looking at, and there a blocked attempt is a red row. A +// run that policy refused wholesale used to render as an empty histogram under +// a list full of failures. func TestUsageAggregate_Apply_CountsBlockedPolicyDecisions(t *testing.T) { agg := newUsageAggregate() ts := time.Date(2026, 6, 1, 10, 0, 0, 0, time.UTC) @@ -89,7 +97,11 @@ func TestUsageAggregate_Apply_CountsBlockedPolicyDecisions(t *testing.T) { latencyTotal += c } assert.Equal(t, int64(0), latencyTotal, "blocked attempts have no latency sample") - assert.Empty(t, agg.Buckets, "blocked attempts do not enter the executed-call timeline") + + timeline := agg.Timeline() + require.Len(t, timeline, 1, "both attempts fall in the same hourly bucket") + assert.Equal(t, int64(2), timeline[0].Calls, "a blocked attempt is a row the user saw") + assert.Equal(t, int64(2), timeline[0].Errors, "and it is a FAILED row") } func TestToolUsage_Averages_ExcludeZeroByteCalls(t *testing.T) { diff --git a/internal/runtime/usage_catchup_test.go b/internal/runtime/usage_catchup_test.go new file mode 100644 index 000000000..367c00d04 --- /dev/null +++ b/internal/runtime/usage_catchup_test.go @@ -0,0 +1,157 @@ +package runtime + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// The usage snapshot is flushed every 30s. Anything persisted after the last +// flush is saved but not folded in, so restoring the snapshot alone loses it — +// and because the aggregate is never rebuilt afterwards, the loss is permanent: +// the histogram drifts further from the activity list with every unclean stop. +// +// After init, the aggregate must contain the snapshot PLUS the tail. +func TestActivityService_SnapshotLoad_ReplaysRecordsPersistedAfterTheFlush(t *testing.T) { + svc, mgr := newUsageTestService(t) + base := time.Date(2026, 6, 1, 10, 0, 0, 0, time.UTC) + + // One call that was both persisted and folded into the flushed snapshot. + saveToolCall(t, mgr, "github", "search", "success", 1000, base) + svc.usage = newUsageStore() + svc.usage.Apply(&storage.ActivityRecord{ + Type: storage.ActivityTypeToolCall, ServerName: "github", ToolName: "search", + Status: storage.ActivityStatusSuccess, ResponseBytes: 1000, Timestamp: base, + }) + snap := svc.usage.Snapshot() + require.NotNil(t, snap) + // Stamp the snapshot at a known instant and persist it: everything written + // after this point is the "lost tail". + flushedAt := base.Add(time.Minute) + snap.UpdatedAt = flushedAt + data, err := encodeUsageAggregate(snap) + require.NoError(t, err) + require.NoError(t, mgr.SaveUsageSnapshot(data)) + + // Two more calls land, then the process dies before the next flush. + saveToolCall(t, mgr, "github", "search", "success", 500, flushedAt.Add(time.Second)) + saveToolCall(t, mgr, "github", "search", "error", 700, flushedAt.Add(2*time.Second)) + + // Cold start. + restarted, _ := newUsageTestServiceOn(t, mgr) + restarted.initUsageFromStorage() + + loaded := restarted.UsageSnapshot() + require.NotNil(t, loaded) + tu := loaded.Tools[toolKey("github", "search")] + require.NotNil(t, tu) + assert.EqualValues(t, 3, tu.Calls, "the snapshot's call plus the two saved after the flush") + assert.EqualValues(t, 1, tu.Errors) + assert.EqualValues(t, 2200, tu.RespBytesSum) + + var timelineCalls int64 + for _, b := range loaded.Timeline() { + timelineCalls += b.Calls + } + assert.EqualValues(t, 3, timelineCalls, "the timeline must catch up too") +} + +// The replay bound is strictly greater than the snapshot stamp, so a record +// already inside the snapshot can never be counted a second time. +func TestActivityService_SnapshotLoad_DoesNotDoubleCountTheSnapshotItself(t *testing.T) { + svc, mgr := newUsageTestService(t) + base := time.Date(2026, 6, 1, 10, 0, 0, 0, time.UTC) + + saveToolCall(t, mgr, "github", "search", "success", 1000, base) + svc.usage = newUsageStore() + svc.usage.Apply(&storage.ActivityRecord{ + Type: storage.ActivityTypeToolCall, ServerName: "github", ToolName: "search", + Status: storage.ActivityStatusSuccess, ResponseBytes: 1000, Timestamp: base, + }) + snap := svc.usage.Snapshot() + snap.UpdatedAt = base.Add(time.Minute) // flushed after the record was written + data, err := encodeUsageAggregate(snap) + require.NoError(t, err) + require.NoError(t, mgr.SaveUsageSnapshot(data)) + + restarted, _ := newUsageTestServiceOn(t, mgr) + restarted.initUsageFromStorage() + + tu := restarted.UsageSnapshot().Tools[toolKey("github", "search")] + require.NotNil(t, tu) + assert.EqualValues(t, 1, tu.Calls, "the record was already in the snapshot") +} + +// A snapshot with no stamp gives no safe lower bound, so replaying from the +// beginning would double everything it already holds. It is left as loaded. +func TestActivityService_SnapshotLoad_SkipsReplayWhenTheSnapshotIsUndated(t *testing.T) { + svc, mgr := newUsageTestService(t) + base := time.Date(2026, 6, 1, 10, 0, 0, 0, time.UTC) + + saveToolCall(t, mgr, "github", "search", "success", 1000, base) + svc.usage = newUsageStore() + svc.usage.Apply(&storage.ActivityRecord{ + Type: storage.ActivityTypeToolCall, ServerName: "github", ToolName: "search", + Status: storage.ActivityStatusSuccess, ResponseBytes: 1000, Timestamp: base, + }) + snap := svc.usage.Snapshot() + snap.UpdatedAt = time.Time{} + data, err := encodeUsageAggregate(snap) + require.NoError(t, err) + require.NoError(t, mgr.SaveUsageSnapshot(data)) + + restarted, _ := newUsageTestServiceOn(t, mgr) + restarted.initUsageFromStorage() + + tu := restarted.UsageSnapshot().Tools[toolKey("github", "search")] + require.NotNil(t, tu) + assert.EqualValues(t, 1, tu.Calls, "no replay, no double count") +} + +// newUsageTestServiceOn builds a second ActivityService over an EXISTING +// storage manager, which is how these tests model a restart: same database, +// fresh in-memory aggregate. +func newUsageTestServiceOn(t *testing.T, mgr *storage.Manager) (*ActivityService, *storage.Manager) { + t.Helper() + return NewActivityService(mgr, zap.NewNop()), mgr +} + +// A snapshot flushed by a build with a DIFFERENT admission rule cannot be +// patched incrementally — the hours it already contains were counted under the +// old rule (e.g. no internal calls). The loader must discard it and rebuild +// from the activity scan, once, so upgraded installs do not carry a 24h +// histogram that disagrees with the list. +func TestActivityService_SnapshotLoad_RebuildsWhenTheAdmissionRuleChanged(t *testing.T) { + svc, mgr := newUsageTestService(t) + base := time.Date(2026, 6, 1, 10, 0, 0, 0, time.UTC) + + // The store holds an internal call the OLD rule never counted. + require.NoError(t, mgr.SaveActivity(&storage.ActivityRecord{ + Type: storage.ActivityTypeInternalToolCall, ToolName: "code_execution", + Status: storage.ActivityStatusSuccess, Timestamp: base, + })) + + // A pre-upgrade snapshot: stamped, but with no AdmissionVersion (0). + old := newUsageAggregate() + old.AdmissionVersion = 0 + old.UpdatedAt = base.Add(time.Hour) + data, err := encodeUsageAggregate(old) + require.NoError(t, err) + require.NoError(t, mgr.SaveUsageSnapshot(data)) + + svc.initUsageFromStorage() + + loaded := svc.UsageSnapshot() + require.NotNil(t, loaded) + var timelineCalls int64 + for _, b := range loaded.Timeline() { + timelineCalls += b.Calls + } + assert.EqualValues(t, 1, timelineCalls, + "the stale-rule snapshot must be discarded and the internal call rescanned in") +} diff --git a/internal/runtime/usage_glance_parity_test.go b/internal/runtime/usage_glance_parity_test.go new file mode 100644 index 000000000..c2575f477 --- /dev/null +++ b/internal/runtime/usage_glance_parity_test.go @@ -0,0 +1,146 @@ +package runtime + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// glanceRows applies the SAME admission rule the activity list uses by default +// (storage.DefaultActivityFilter) so the two populations can be compared +// directly rather than by eye. +func glanceRows(records []*storage.ActivityRecord) int { + filter := storage.DefaultActivityFilter() + n := 0 + for _, rec := range records { + if filter.Matches(rec) { + n++ + } + } + return n +} + +// The bars under the Recent list have to count the rows in it. They used to +// count tool_calls only, so an agent whose traffic was mostly retrieve_tools +// and code_execution — which is most agents — looked at a list of work under an +// almost empty histogram. +func TestUsageAggregate_TimelineMatchesTheGlancePopulation(t *testing.T) { + ts := time.Date(2026, 6, 1, 10, 0, 0, 0, time.UTC) + records := []*storage.ActivityRecord{ + // Upstream dispatches. + {Type: storage.ActivityTypeToolCall, ServerName: "github", ToolName: "search", Status: storage.ActivityStatusSuccess, DurationMs: 12, Timestamp: ts}, + {Type: storage.ActivityTypeToolCall, ServerName: "github", ToolName: "search", Status: storage.ActivityStatusError, DurationMs: 8, Timestamp: ts}, + // mcpproxy's own built-ins: visible in the glance, and until now + // invisible in the histogram. + {Type: storage.ActivityTypeInternalToolCall, ToolName: "retrieve_tools", Status: storage.ActivityStatusSuccess, DurationMs: 5, Timestamp: ts}, + {Type: storage.ActivityTypeInternalToolCall, ToolName: "code_execution", Status: storage.ActivityStatusSuccess, DurationMs: 400, Timestamp: ts}, + {Type: storage.ActivityTypeInternalToolCall, ToolName: "describe_tool", Status: storage.ActivityStatusError, DurationMs: 2, Timestamp: ts}, + // A policy block: a red row in the glance. + {Type: storage.ActivityTypePolicyDecision, ServerName: "evil", ToolName: "exfil", Status: storage.ActivityStatusBlocked, Timestamp: ts}, + } + + agg := newUsageAggregate() + for _, rec := range records { + agg.Apply(rec) + } + + timeline := agg.Timeline() + require.Len(t, timeline, 1) + assert.EqualValues(t, glanceRows(records), timeline[0].Calls, + "every row the user sees must be a call in the histogram") + assert.EqualValues(t, 3, timeline[0].Errors, + "the failed dispatch, the failed built-in and the block are all failures") +} + +// The direct dispatch path emits BOTH a tool_call record and a call_tool_* +// internal record for one call. The glance hides the internal one; so must the +// histogram, or every direct call is counted twice. +func TestUsageAggregate_InternalCallToolRecordsAreNotDoubleCounted(t *testing.T) { + ts := time.Date(2026, 6, 1, 10, 0, 0, 0, time.UTC) + records := []*storage.ActivityRecord{ + {Type: storage.ActivityTypeToolCall, ServerName: "github", ToolName: "search", Status: storage.ActivityStatusSuccess, DurationMs: 12, Timestamp: ts, RequestID: "r1"}, + {Type: storage.ActivityTypeInternalToolCall, ServerName: "github", ToolName: "call_tool_read", Status: storage.ActivityStatusSuccess, DurationMs: 13, Timestamp: ts, RequestID: "r1"}, + } + + agg := newUsageAggregate() + for _, rec := range records { + agg.Apply(rec) + } + + timeline := agg.Timeline() + require.Len(t, timeline, 1) + assert.EqualValues(t, 1, timeline[0].Calls, "one dispatch, one bar unit") + assert.EqualValues(t, glanceRows(records), timeline[0].Calls) + + // And the mirror record must not invent a per-tool row for the variant name. + assert.Nil(t, agg.Tools[toolKey("github", "call_tool_read")]) +} + +// The per-tool rollup describes UPSTREAM tools. A built-in has no upstream +// server, and its latency is mcpproxy's, not an upstream's — admitting it would +// invent tool rows and skew percentiles. +func TestUsageAggregate_BuiltinsStayOutOfThePerToolRollup(t *testing.T) { + ts := time.Date(2026, 6, 1, 10, 0, 0, 0, time.UTC) + agg := newUsageAggregate() + agg.Apply(&storage.ActivityRecord{ + Type: storage.ActivityTypeInternalToolCall, ToolName: "retrieve_tools", + Status: storage.ActivityStatusSuccess, DurationMs: 5, ResponseBytes: 900, Timestamp: ts, + }) + + assert.Empty(t, agg.Tools, "a built-in is not an upstream tool") + require.Len(t, agg.Timeline(), 1) + assert.EqualValues(t, 1, agg.Timeline()[0].Calls) +} + +// Successful management built-ins (upstream_servers, quarantine_security, …) +// are not glance rows — GlanceSelection rule 3 admits only retrieve_tools, +// describe_tool and code_execution plus any internal failure — so a config +// sweep must not paint bars over an hour with no visible rows. +func TestUsageAggregate_SuccessfulManagementBuiltinsStayOutOfTheTimeline(t *testing.T) { + ts := time.Date(2026, 6, 1, 10, 0, 0, 0, time.UTC) + agg := newUsageAggregate() + + agg.Apply(&storage.ActivityRecord{Type: storage.ActivityTypeInternalToolCall, ToolName: "upstream_servers", Status: storage.ActivityStatusSuccess, Timestamp: ts}) + agg.Apply(&storage.ActivityRecord{Type: storage.ActivityTypeInternalToolCall, ToolName: "quarantine_security", Status: storage.ActivityStatusSuccess, Timestamp: ts}) + assert.Empty(t, agg.Timeline(), "successful management calls are hidden rows, so no bars") + + agg.Apply(&storage.ActivityRecord{Type: storage.ActivityTypeInternalToolCall, ToolName: "search_servers", Status: storage.ActivityStatusError, Timestamp: ts}) + timeline := agg.Timeline() + require.Len(t, timeline, 1) + assert.EqualValues(t, 1, timeline[0].Calls, "a non-management internal failure IS a glance row") + assert.EqualValues(t, 1, timeline[0].Errors) +} + +// A blocked tool_call (a policy gate refused a code_execution sub-call before +// dispatch) never executed: like a blocked policy_decision it takes a failed +// timeline bar and the Blocked counter, never Calls/latency/bytes. +func TestUsageAggregate_BlockedToolCallIsARefusalNotAnExecutedCall(t *testing.T) { + ts := time.Date(2026, 6, 1, 10, 0, 0, 0, time.UTC) + agg := newUsageAggregate() + agg.Apply(&storage.ActivityRecord{Type: storage.ActivityTypeToolCall, ServerName: "github", ToolName: "search", Status: storage.ActivityStatusBlocked, DurationMs: 3, RequestBytes: 100, Timestamp: ts}) + + tu := agg.Tools[toolKey("github", "search")] + require.NotNil(t, tu) + assert.EqualValues(t, 0, tu.Calls) + assert.EqualValues(t, 1, tu.Blocked) + assert.EqualValues(t, 0, tu.ReqBytesSum) + + timeline := agg.Timeline() + require.Len(t, timeline, 1) + assert.EqualValues(t, 1, timeline[0].Calls) + assert.EqualValues(t, 1, timeline[0].Errors) +} + +// Management built-ins never row in the glance regardless of status +// (GlanceSelection rule 1), so even their FAILURES must not bar. +func TestUsageAggregate_ManagementBuiltinsNeverEnterTheTimeline(t *testing.T) { + ts := time.Date(2026, 6, 1, 10, 0, 0, 0, time.UTC) + agg := newUsageAggregate() + agg.Apply(&storage.ActivityRecord{Type: storage.ActivityTypeInternalToolCall, ToolName: "upstream_servers", Status: storage.ActivityStatusError, Timestamp: ts}) + agg.Apply(&storage.ActivityRecord{Type: storage.ActivityTypeInternalToolCall, ToolName: "quarantine_security", Status: storage.ActivityStatusError, Timestamp: ts}) + assert.Empty(t, agg.Timeline(), "rule 1 hides these rows whatever their status, so no bars") +} diff --git a/internal/runtime/usage_service.go b/internal/runtime/usage_service.go index e9e676a0c..f484ed04c 100644 --- a/internal/runtime/usage_service.go +++ b/internal/runtime/usage_service.go @@ -30,6 +30,11 @@ func encodeUsageAggregate(a *UsageAggregate) ([]byte, error) { // defaults for any maps absent from the blob. func decodeUsageAggregate(data []byte) (*UsageAggregate, error) { agg := newUsageAggregate() + // A pre-versioning snapshot has no admission_version field, and Unmarshal + // leaves absent fields alone — so the constructor's CURRENT stamp must be + // cleared first, or every legacy snapshot would masquerade as current and + // skip the rebuild the version check exists for. + agg.AdmissionVersion = 0 if err := json.Unmarshal(data, agg); err != nil { return nil, err } @@ -83,10 +88,20 @@ func (s *ActivityService) initUsageFromStorage() { } else if len(data) > 0 { if agg, derr := decodeUsageAggregate(data); derr != nil { s.logger.Warn("Failed to decode usage snapshot; rebuilding from scan", zap.Error(derr)) + } else if agg.AdmissionVersion != usageAdmissionVersion { + // Counted under a different admission rule (e.g. before internal + // calls joined the timeline): incremental catch-up cannot fix the + // hours it already contains, so rebuild from scratch once. + s.logger.Info("Usage snapshot predates the current admission rule; rebuilding from scan", + zap.Int("snapshot_version", agg.AdmissionVersion), + zap.Int("current_version", usageAdmissionVersion)) } else { s.usage.Replace(agg) + replayed := s.replayActivitiesSince(agg.UpdatedAt) s.logger.Info("Loaded usage aggregate from persisted snapshot", - zap.Int("tools", len(agg.Tools))) + zap.Int("tools", len(agg.Tools)), + zap.Time("snapshot_updated_at", agg.UpdatedAt), + zap.Int("records_replayed", replayed)) return } } @@ -106,6 +121,39 @@ func (s *ActivityService) initUsageFromStorage() { zap.Int("tools", len(agg.Tools))) } +// replayActivitiesSince folds every activity record persisted AFTER the loaded +// snapshot was stamped into the aggregate, and reports how many it applied. +// +// Without it, restoring a snapshot silently dropped every record written since +// the last 30s flush. On a clean shutdown that tail is small (the flush-on-stop +// covers it); on a crash or a kill it is up to 30 seconds of calls, and the +// loss is PERMANENT — the aggregate is never rebuilt again, so the usage +// histogram drifts further from the activity list with every unclean stop. +// +// Safe to run on every start because the write path persists a record BEFORE +// folding it in (ActivityService.handleToolCallCompleted), so "saved but not +// counted" is the only inconsistency possible, never "counted but not saved". +// The bound is strictly greater than the stamp, so nothing already in the +// snapshot can be applied a second time. +func (s *ActivityService) replayActivitiesSince(since time.Time) int { + if since.IsZero() { + // Snapshot from a build that did not stamp its aggregate: there is no + // safe lower bound, and replaying from the beginning would double every + // record it already contains. Keep the snapshot as loaded. + s.logger.Warn("Persisted usage snapshot has no timestamp; skipping catch-up replay") + return 0 + } + replayed := 0 + if err := s.storage.ScanActivitiesAfter(since, func(rec *storage.ActivityRecord) { + replayed++ + s.usage.Apply(rec) + }); err != nil { + s.logger.Warn("Failed to replay activity records into the usage aggregate", + zap.Error(err), zap.Time("since", since)) + } + return replayed +} + // persistUsage flushes the current snapshot to storage. No-op if usage tracking // is uninitialized or no snapshot exists yet. func (s *ActivityService) persistUsage() { diff --git a/internal/server/code_exec_activity_test.go b/internal/server/code_exec_activity_test.go new file mode 100644 index 000000000..4ba02d81e --- /dev/null +++ b/internal/server/code_exec_activity_test.go @@ -0,0 +1,149 @@ +package server + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" + "time" + "unicode/utf8" + + "github.com/mark3labs/mcp-go/mcp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/upstream/limiter" +) + +// jsruntime.Execute takes its options BY VALUE and only fills a missing +// ExecutionID on its own copy, so leaving it unset in the handler left every +// consumer of options.ExecutionID holding "". The parent history record is the +// visible symptom: it is keyed by the correlation id it was minted with, and +// its RequestID — the handle `activity list --request-id` takes — was empty, so +// nothing could be correlated back to the execution that produced it. +func TestCodeExecution_ParentRecordCarriesItsCorrelationID(t *testing.T) { + proxy, _ := newStoredScriptProxy(t) + + request := mcp.CallToolRequest{Params: mcp.CallToolParams{ + Name: "code_execution", + Arguments: map[string]interface{}{ + "code": `1 + 1`, + "input": map[string]interface{}{}, + "options": map[string]interface{}{"timeout_ms": 10000}, + }, + }} + result, err := proxy.handleCodeExecution(context.Background(), request) + require.NoError(t, err) + require.NotNil(t, result) + + records, err := proxy.storage.GetServerToolCalls("code_execution", 10) + require.NoError(t, err) + require.Len(t, records, 1) + + rec := records[0] + assert.NotEmpty(t, rec.RequestID, "the execution id must reach the record") + assert.Equal(t, rec.ID, rec.RequestID, + "the parent call id and its correlation handle are the same value") +} + +// A nested call must be linkable to the execution that issued it. The link is +// the parent's correlation id, carried on the nested record as both RequestID +// (the shared correlation handle) and ParentCallID. +func TestCodeExecution_NestedHistoryLinksToTheParentExecution(t *testing.T) { + proxy, _ := newStoredScriptProxy(t) + + serverCfg := &config.ServerConfig{ + Name: "time", URL: "http://localhost:1/mcp", Protocol: "streamable-http", Enabled: true, + } + require.NoError(t, proxy.storage.SaveUpstreamServer(serverCfg)) + + request := mcp.CallToolRequest{Params: mcp.CallToolParams{ + Name: "code_execution", + Arguments: map[string]interface{}{ + // The server is configured but has no client, so the call fails + // inside the sandbox — which is exactly a path that must still be + // recorded and still be linked to its parent. + "code": `var r = call_tool("time", "get_current_time", {}); ({ ok: r.ok })`, + "input": map[string]interface{}{}, + "options": map[string]interface{}{"timeout_ms": 10000}, + }, + }} + _, err := proxy.handleCodeExecution(context.Background(), request) + require.NoError(t, err) + + parents, err := proxy.storage.GetServerToolCalls("code_execution", 10) + require.NoError(t, err) + require.Len(t, parents, 1) + parentID := parents[0].ID + + nested, err := proxy.storage.GetServerToolCalls(storage.GenerateServerID(serverCfg), 10) + require.NoError(t, err) + require.Len(t, nested, 1, "the sandboxed call must be recorded") + + assert.Equal(t, parentID, nested[0].ParentCallID) + assert.Equal(t, parentID, nested[0].RequestID, + "the nested record shares the parent's correlation handle") + assert.NotEqual(t, parentID, nested[0].ID, "but it is its own record") +} + +// The status recorded for a sandboxed sub-call is DERIVED, never assumed. An +// upstream that answered isError:true failed even though the transport hop +// succeeded, and a Go error wins over the upstream's own words. +func TestSubCallActivityOutcome_ClassifiesEveryExit(t *testing.T) { + t.Run("normal answer", func(t *testing.T) { + status, errMsg, response, truncated := subCallActivityOutcome(mcp.NewToolResultText("42"), nil) + assert.Equal(t, storage.ActivityStatusSuccess, status) + assert.Empty(t, errMsg) + assert.Contains(t, response, "42") + assert.False(t, truncated) + }) + + t.Run("upstream answered isError", func(t *testing.T) { + status, errMsg, _, _ := subCallActivityOutcome(mcp.NewToolResultError("Invalid timezone"), nil) + assert.Equal(t, storage.ActivityStatusError, status) + assert.Contains(t, errMsg, "Invalid timezone") + }) + + t.Run("policy refusal / transport error", func(t *testing.T) { + status, errMsg, response, truncated := subCallActivityOutcome(nil, errors.New("server \"evil\" is quarantined")) + assert.Equal(t, storage.ActivityStatusError, status) + assert.Contains(t, errMsg, "quarantined") + assert.Empty(t, response, "a call that never happened has no response") + assert.False(t, truncated) + }) + + t.Run("oversized answers are capped", func(t *testing.T) { + _, _, response, truncated := subCallActivityOutcome( + mcp.NewToolResultText(strings.Repeat("é", subCallActivityResponseLimit)), nil) + assert.True(t, truncated, "one script can issue many calls; each record is capped") + assert.LessOrEqual(t, len(response), subCallActivityResponseLimit) + assert.True(t, utf8.ValidString(response), "truncation must not split a rune") + }) +} + +// emitSubCallActivity runs on a caller that unit tests drive without a proxy at +// all. It must stay a no-op there rather than panicking. +func TestEmitSubCallActivity_NoProxyIsANoOp(t *testing.T) { + u := &upstreamToolCaller{logger: zap.NewNop()} + assert.NotPanics(t, func() { + u.emitSubCallActivity("time", "now", nil, nil, errors.New("boom"), time.Now(), time.Millisecond) + }) +} + +// A QUEUE shed already lands in the activity log via the limiter's +// origin-independent observer (spec 093 FR-012) — the sandbox emitter must not +// add a second record for it. server_unavailable never reaches the observer +// (managed.reportRejection filters it out), so it MUST be recorded here. +func TestEmitSubCallActivity_SkipsOnlyObservedSheds(t *testing.T) { + detect := shedHasCanonicalRecord + require.True(t, detect(fmt.Errorf("dispatch: %w", &limiter.LimitError{Reason: limiter.ReasonQueueFull})), + "queue_full has a canonical rejected record — skip") + require.True(t, detect(&limiter.LimitError{Reason: limiter.ReasonQueueTimeout})) + require.False(t, detect(&limiter.LimitError{Reason: limiter.ReasonServerUnavailable}), + "server_unavailable has NO canonical record — the sandbox emit is its only witness") + require.False(t, detect(errors.New("plain failure"))) +} diff --git a/internal/server/mcp.go b/internal/server/mcp.go index 5d6b38d75..06a84b5e0 100644 --- a/internal/server/mcp.go +++ b/internal/server/mcp.go @@ -698,9 +698,13 @@ func (p *MCPProxyServer) emitActivityToolCallStarted(serverName, toolName, sessi // detectionText is the spec-084 pre-encoding detection scan input (FR-007b) — // empty when TOON is off or on non-call_tool_* paths (detector falls back to response) // toonDecisions are the spec-084 per-block encoding decisions (FR-010) — nil when the feature did not run -func (p *MCPProxyServer) emitActivityToolCallCompleted(serverName, toolName, sessionID, requestID, source, status, errorMsg string, durationMs int64, arguments map[string]interface{}, response string, responseTruncated bool, toolVariant string, intent map[string]interface{}, contentTrust, profile string, requestBytes, responseBytes int, detectionText string, toonDecisions []toonenc.Decision) { +// parentID is the correlation id of the code_execution whose sandbox issued this +// sub-call (issue C) — empty for every top-level dispatch. It is the LAST +// parameter on purpose: TestActivityCompletionNeverHardcodesSuccess pins the +// position of `status`, so new parameters have to go after it. +func (p *MCPProxyServer) emitActivityToolCallCompleted(serverName, toolName, sessionID, requestID, source, status, errorMsg string, durationMs int64, arguments map[string]interface{}, response string, responseTruncated bool, toolVariant string, intent map[string]interface{}, contentTrust, profile string, requestBytes, responseBytes int, detectionText string, toonDecisions []toonenc.Decision, parentID string) { if p.mainServer != nil && p.mainServer.runtime != nil { - p.mainServer.runtime.EmitActivityToolCallCompleted(serverName, toolName, sessionID, requestID, source, status, errorMsg, durationMs, arguments, response, responseTruncated, toolVariant, intent, contentTrust, profile, requestBytes, responseBytes, detectionText, toonOutputMetadata(toonDecisions)) + p.mainServer.runtime.EmitActivityToolCallCompleted(serverName, toolName, sessionID, requestID, source, status, errorMsg, durationMs, arguments, response, responseTruncated, toolVariant, intent, contentTrust, profile, requestBytes, responseBytes, detectionText, toonOutputMetadata(toonDecisions), parentID) } } @@ -2341,7 +2345,7 @@ func (p *MCPProxyServer) handleCallToolVariant(ctx context.Context, request mcp. } errMsg := fmt.Sprintf("invalid arguments for %s: %s", toolName, detail) p.emitActivityToolCallStarted(serverName, actualToolName, sessionID, requestID, activitySource, activityArgs) - p.emitActivityToolCallCompleted(serverName, actualToolName, sessionID, requestID, activitySource, "error", errMsg, 0, activityArgs, errMsg, false, toolVariant, intentMap, contentTrust, profileSlug, 0, 0, "", nil) + p.emitActivityToolCallCompleted(serverName, actualToolName, sessionID, requestID, activitySource, "error", errMsg, 0, activityArgs, errMsg, false, toolVariant, intentMap, contentTrust, profileSlug, 0, 0, "", nil, "") return invalidParamsErrorResult(toolName, meta.ParamsJSON, detail), nil } } @@ -2362,7 +2366,7 @@ func (p *MCPProxyServer) handleCallToolVariant(ctx context.Context, request mcp. intentMap = intent.ToMap() } p.emitActivityToolCallStarted(serverName, actualToolName, sessionID, requestID, activitySource, activityArgs) - p.emitActivityToolCallCompleted(serverName, actualToolName, sessionID, requestID, activitySource, "error", errMsg, 0, activityArgs, errMsg, false, toolVariant, intentMap, contentTrust, profileSlug, 0, 0, "", nil) + p.emitActivityToolCallCompleted(serverName, actualToolName, sessionID, requestID, activitySource, "error", errMsg, 0, activityArgs, errMsg, false, toolVariant, intentMap, contentTrust, profileSlug, 0, 0, "", nil, "") return mcp.NewToolResultError(errMsg), nil } } else { @@ -2387,7 +2391,7 @@ func (p *MCPProxyServer) handleCallToolVariant(ctx context.Context, request mcp. intentMap = intent.ToMap() } p.emitActivityToolCallStarted(serverName, actualToolName, sessionID, requestID, activitySource, activityArgs) - p.emitActivityToolCallCompleted(serverName, actualToolName, sessionID, requestID, activitySource, "error", errMsg, 0, activityArgs, errMsg, false, toolVariant, intentMap, contentTrust, profileSlug, 0, 0, "", nil) + p.emitActivityToolCallCompleted(serverName, actualToolName, sessionID, requestID, activitySource, "error", errMsg, 0, activityArgs, errMsg, false, toolVariant, intentMap, contentTrust, profileSlug, 0, 0, "", nil, "") return mcp.NewToolResultError(errMsg), nil } @@ -2520,7 +2524,7 @@ func (p *MCPProxyServer) handleCallToolVariant(ctx context.Context, request mcp. if intent != nil { intentMap = intent.ToMap() } - p.emitActivityToolCallCompleted(serverName, actualToolName, sessionID, requestID, activitySource, "error", err.Error(), duration.Milliseconds(), activityArgs, "", false, toolVariant, intentMap, contentTrust, profileSlug, 0, 0, "", nil) + p.emitActivityToolCallCompleted(serverName, actualToolName, sessionID, requestID, activitySource, "error", err.Error(), duration.Milliseconds(), activityArgs, "", false, toolVariant, intentMap, contentTrust, profileSlug, 0, 0, "", nil, "") // Spec 024: Emit internal tool call event for error internalToolName := "call_tool_" + intent.OperationType // e.g., "call_tool_read" @@ -2650,7 +2654,7 @@ func (p *MCPProxyServer) handleCallToolVariant(ctx context.Context, request mcp. if intent != nil { intentMap = intent.ToMap() } - p.emitActivityToolCallCompleted(serverName, actualToolName, sessionID, requestID, activitySource, activityStatus, activityErrMsg, duration.Milliseconds(), activityArgs, response, responseTruncated, toolVariant, intentMap, contentTrust, profileSlug, activityRequestBytes, activityResponseBytes, toonDetectionText, toonDecisions) + p.emitActivityToolCallCompleted(serverName, actualToolName, sessionID, requestID, activitySource, activityStatus, activityErrMsg, duration.Milliseconds(), activityArgs, response, responseTruncated, toolVariant, intentMap, contentTrust, profileSlug, activityRequestBytes, activityResponseBytes, toonDetectionText, toonDecisions, "") // Spec 024: Emit internal tool call event. It carries the SAME classification // as the tool_call record above (issue #935) — the two describe one dispatch, @@ -2846,7 +2850,7 @@ func (p *MCPProxyServer) handleCallTool(ctx context.Context, request mcp.CallToo } // Log the early failure to activity (Spec 024) p.emitActivityToolCallStarted(serverName, actualToolName, sessionID, requestID, activitySource, activityArgs) - p.emitActivityToolCallCompleted(serverName, actualToolName, sessionID, requestID, activitySource, "error", errMsg, 0, activityArgs, errMsg, false, "", nil, "", "", 0, 0, "", nil) + p.emitActivityToolCallCompleted(serverName, actualToolName, sessionID, requestID, activitySource, "error", errMsg, 0, activityArgs, errMsg, false, "", nil, "", "", 0, 0, "", nil, "") return mcp.NewToolResultError(errMsg), nil } } else { @@ -2855,7 +2859,7 @@ func (p *MCPProxyServer) handleCallTool(ctx context.Context, request mcp.CallToo errMsg := fmt.Sprintf("No client found for server: %s", serverName) // Log the early failure to activity (Spec 024) p.emitActivityToolCallStarted(serverName, actualToolName, sessionID, requestID, activitySource, activityArgs) - p.emitActivityToolCallCompleted(serverName, actualToolName, sessionID, requestID, activitySource, "error", errMsg, 0, activityArgs, errMsg, false, "", nil, "", "", 0, 0, "", nil) + p.emitActivityToolCallCompleted(serverName, actualToolName, sessionID, requestID, activitySource, "error", errMsg, 0, activityArgs, errMsg, false, "", nil, "", "", 0, 0, "", nil, "") return mcp.NewToolResultError(errMsg), nil } @@ -2991,7 +2995,7 @@ func (p *MCPProxyServer) handleCallTool(ctx context.Context, request mcp.CallToo } // Emit activity completed event for error with determined source (legacy - no intent) - p.emitActivityToolCallCompleted(serverName, actualToolName, sessionID, requestID, activitySource, "error", err.Error(), duration.Milliseconds(), activityArgs, "", false, "", nil, "", "", 0, 0, "", nil) + p.emitActivityToolCallCompleted(serverName, actualToolName, sessionID, requestID, activitySource, "error", err.Error(), duration.Milliseconds(), activityArgs, "", false, "", nil, "", "", 0, 0, "", nil, "") return p.createDetailedErrorResponse(err, serverName, actualToolName), nil } @@ -3087,7 +3091,7 @@ func (p *MCPProxyServer) handleCallTool(ctx context.Context, request mcp.CallToo // Emit activity completed event with determined source (legacy - no intent). // Status comes from the upstream result, not from err alone (issue #935). responseTruncated := tokenMetrics != nil && tokenMetrics.WasTruncated - p.emitActivityToolCallCompleted(serverName, actualToolName, sessionID, requestID, activitySource, activityStatus, activityErrMsg, duration.Milliseconds(), activityArgs, response, responseTruncated, "", nil, "", "", legacyRequestBytes, legacyResponseBytes, "", nil) + p.emitActivityToolCallCompleted(serverName, actualToolName, sessionID, requestID, activitySource, activityStatus, activityErrMsg, duration.Milliseconds(), activityArgs, response, responseTruncated, "", nil, "", "", legacyRequestBytes, legacyResponseBytes, "", nil, "") return forwarded, nil } diff --git a/internal/server/mcp_code_execution.go b/internal/server/mcp_code_execution.go index a68e81d62..7559c8660 100644 --- a/internal/server/mcp_code_execution.go +++ b/internal/server/mcp_code_execution.go @@ -3,6 +3,7 @@ package server import ( "context" "encoding/json" + "errors" "fmt" "math" "sync" @@ -16,6 +17,7 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/reqcontext" "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" "github.com/smart-mcp-proxy/mcpproxy-go/internal/upstream" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/upstream/limiter" "github.com/mark3labs/mcp-go/mcp" mcpserver "github.com/mark3labs/mcp-go/server" @@ -161,6 +163,14 @@ func (p *MCPProxyServer) handleCodeExecution(ctx context.Context, request mcp.Ca executionStart := time.Now() parentCallID := mintCorrelationIDAt(executionStart, "code_execution") + // The execution id IS the parent call id. jsruntime.Execute takes options + // BY VALUE and only fills a missing ExecutionID on its own copy, so leaving + // this unset left every downstream consumer of options.ExecutionID — + // toolCaller.executionID, the parent history record's RequestID and the + // nested history records' RequestID — with the empty string, which broke + // exactly the correlation those fields exist for. + options.ExecutionID = parentCallID + // Config path for history records (empty when no authority was wired). configPath := p.activeConfigFilePath() @@ -706,6 +716,7 @@ func (u *upstreamToolCaller) CallTool(ctx context.Context, serverName, toolName duration := time.Since(startTime) u.recordToolCall(serverName, toolName, startTime, duration, false, refusal.Error()) u.storeToolCallInHistory(serverName, toolName, args, nil, refusal, startTime, duration) + u.emitSubCallRefused(serverName, toolName, args, refusal, startTime, duration) return nil, refusal } @@ -716,6 +727,7 @@ func (u *upstreamToolCaller) CallTool(ctx context.Context, serverName, toolName duration := time.Since(startTime) u.recordToolCall(serverName, toolName, startTime, duration, false, err.Error()) u.storeToolCallInHistory(serverName, toolName, args, nil, err, startTime, duration) + u.emitSubCallActivity(serverName, toolName, args, nil, err, startTime, duration) return nil, err } @@ -729,6 +741,7 @@ func (u *upstreamToolCaller) CallTool(ctx context.Context, serverName, toolName // upstream rejection is a clean success here and an error there. u.recordUpstreamCall(serverName, toolName, startTime, duration, result, err) u.storeToolCallInHistory(serverName, toolName, args, result, err, startTime, duration) + u.emitSubCallActivity(serverName, toolName, args, result, err, startTime, duration) u.logger.Debug("upstream tool call completed", zap.String("execution_id", u.executionID), @@ -745,6 +758,124 @@ func (u *upstreamToolCaller) CallTool(ctx context.Context, serverName, toolName return result, nil } +// subCallActivityResponseLimit caps the response text recorded for ONE +// sandboxed sub-call. One execution can issue up to max_tool_calls of them, so +// the per-record budget is deliberately far smaller than the 64KB a single +// direct dispatch is allowed. +const subCallActivityResponseLimit = 8 * 1024 + +// emitSubCallActivity records one call issued from inside the JS sandbox as a +// first-class tool_call activity record. +// +// Before this, a sandboxed call reached the in-memory tool list and the legacy +// tool-call history and nothing else — so the activity log, which is what the +// tray glance, GET /api/v1/activity and the usage aggregate all read, showed +// the code_execution wrapper and none of the work it actually did. A script +// that made twenty upstream calls was one row. +// +// Every sub-call gets a FRESH request id and carries ParentID = the parent +// code_execution's correlation id, which makes navigation one query in each +// direction: +// +// parent → children: /api/v1/activity?parent_id= +// child → parent: /api/v1/activity?request_id= +// +// The record is emitted on EVERY exit of CallTool — policy refusal, unknown +// server, and dispatch (success or failure) — because a call the sandbox was +// refused is exactly the kind of thing the transparency surfaces exist to show. +// +// Source is "internal" for the same reason the dispatch context is (Spec 093 +// FR-012): the call was issued by the script, not by whoever started it. No +// `started` event is emitted: for a nested call it would arrive after the work +// already finished, and it would double the SSE traffic of a busy script for +// nothing — started events are never persisted anyway. +func (u *upstreamToolCaller) emitSubCallActivity(serverName, toolName string, args map[string]interface{}, result interface{}, callErr error, startTime time.Time, duration time.Duration) { + // nil in the unit tests that drive the caller directly (see the field + // comment on upstreamToolCaller.proxy) — there is no runtime to emit into. + if u.proxy == nil { + return + } + + // A queue shed already produced its canonical "rejected" activity record + // at the admission point inside the managed client (spec 093 FR-012, + // installRejectionObserver) — that seam is origin-independent and fired + // for this very call. Emitting a second record here would count one + // refused attempt twice, once as rejected and once as an executed error. + // Only queue_full/queue_timeout reach the observer (reportRejection); + // server_unavailable is an ordinary error with no canonical record, so it + // must fall through and be recorded here like any other failure. + if shedHasCanonicalRecord(callErr) { + return + } + + status, errMsg, responseText, truncated := subCallActivityOutcome(result, callErr) + + requestID := mintCorrelationIDAt(startTime, serverName, toolName) + u.proxy.emitActivityToolCallCompleted( + serverName, toolName, u.sessionID, requestID, string(storage.ActivitySourceInternal), + status, errMsg, duration.Milliseconds(), args, responseText, truncated, + "", nil, "", "", 0, 0, "", nil, u.parentCallID) +} + +// emitSubCallRefused records a sandbox sub-call that the policy gate refused +// before dispatch (quarantined, disabled, approval-locked — spec 098 FR-002). +// Status is "blocked", not "error": the upstream never saw the call, and the +// aggregate routes blocked tool_calls off the executed-call statistics +// (Calls/latency) while still giving the attempt a failed bar in the timeline, +// the same treatment a direct-path policy_decision gets. +func (u *upstreamToolCaller) emitSubCallRefused(serverName, toolName string, args map[string]interface{}, refusal error, startTime time.Time, duration time.Duration) { + if u.proxy == nil { + return + } + requestID := mintCorrelationIDAt(startTime, serverName, toolName) + u.proxy.emitActivityToolCallCompleted( + serverName, toolName, u.sessionID, requestID, string(storage.ActivitySourceInternal), + storage.ActivityStatusBlocked, refusal.Error(), duration.Milliseconds(), args, "", false, + "", nil, "", "", 0, 0, "", nil, u.parentCallID) +} + +// shedHasCanonicalRecord reports whether callErr is a limiter shed the +// admission observer already recorded (managed.reportRejection forwards only +// queue_full/queue_timeout; server_unavailable travels the ordinary error path +// and has no canonical record). +func shedHasCanonicalRecord(callErr error) bool { + var limitErr *limiter.LimitError + return errors.As(callErr, &limitErr) && + (limitErr.Reason == limiter.ReasonQueueFull || limitErr.Reason == limiter.ReasonQueueTimeout) +} + +// subCallActivityOutcome classifies one sandboxed sub-call for the activity log +// and produces the response text to record with it. +// +// Split out of emitSubCallActivity so the classification is testable without a +// runtime to emit into — and so the rule stays in ONE place: never hardcode a +// status. An upstream that ANSWERED isError:true has failed even though the +// transport hop succeeded (issue #935), and a Go error wins over the upstream's +// own text because a call that never completed has no upstream text worth +// keeping. This is the same precedence nestedCallFailure applies to the legacy +// history record, so the two cannot disagree about one call. +func subCallActivityOutcome(result interface{}, callErr error) (status, errMsg, response string, truncated bool) { + status, errMsg = activityStatusForResult(result) + if callErr != nil { + return storage.ActivityStatusError, callErr.Error(), "", false + } + if result == nil { + return status, errMsg, "", false + } + encoded, mErr := json.Marshal(result) + if mErr != nil { + return status, errMsg, "", false + } + response = string(encoded) + if len(response) > subCallActivityResponseLimit { + // safeTruncateBytes backs the cut up to a rune boundary, so the stored + // text is always valid UTF-8. + response = response[:safeTruncateBytes(response, subCallActivityResponseLimit)] + truncated = true + } + return status, errMsg, response, truncated +} + // policyRefusal evaluates the shared per-tool policy gates for a sandboxed call // and returns the refusal a script sees, or nil when the tool is callable. func (u *upstreamToolCaller) policyRefusal(serverName, toolName string) error { diff --git a/internal/server/mcp_routing.go b/internal/server/mcp_routing.go index ed9f76c04..8e97ac003 100644 --- a/internal/server/mcp_routing.go +++ b/internal/server/mcp_routing.go @@ -264,7 +264,7 @@ func (p *MCPProxyServer) makeDirectModeHandler(serverName, toolName string, anno return shedToolResult(limitErr), nil } // Emit error activity - p.emitActivityToolCallCompleted(serverName, toolName, sessionID, requestID, "mcp", "error", err.Error(), durationMs, enrichedArgs, "", false, "", nil, directContentTrust, "", 0, 0, "", nil) + p.emitActivityToolCallCompleted(serverName, toolName, sessionID, requestID, "mcp", "error", err.Error(), durationMs, enrichedArgs, "", false, "", nil, directContentTrust, "", 0, 0, "", nil, "") return mcp.NewToolResultError(fmt.Sprintf("Error calling %s:%s: %v", serverName, toolName, err)), nil } @@ -344,7 +344,7 @@ func (p *MCPProxyServer) makeDirectModeHandler(serverName, toolName string, anno // Spec 069 A1: pre-truncation sizes; result was measured before the truncation loop above. routingResponseBytes := rawByteSize(result) routingRequestBytes := rawByteSize(enrichedArgs) - p.emitActivityToolCallCompleted(serverName, toolName, sessionID, requestID, "mcp", activityStatus, activityErrMsg, durationMs, enrichedArgs, responseText, truncated, toolVariant, nil, directContentTrust, "", routingRequestBytes, routingResponseBytes, "", nil) + p.emitActivityToolCallCompleted(serverName, toolName, sessionID, requestID, "mcp", activityStatus, activityErrMsg, durationMs, enrichedArgs, responseText, truncated, toolVariant, nil, directContentTrust, "", routingRequestBytes, routingResponseBytes, "", nil, "") return forwarded, nil } diff --git a/internal/storage/activity_models.go b/internal/storage/activity_models.go index 8a648472d..dfba06cf1 100644 --- a/internal/storage/activity_models.go +++ b/internal/storage/activity_models.go @@ -100,6 +100,15 @@ var ValidActivityStatuses = []string{ ActivityStatusRejected, } +// InternalCallToolPrefix marks the internal_tool_call records that MIRROR a +// direct upstream dispatch (call_tool_read / _write / _destructive). Every one +// of them is paired with a tool_call record for the same dispatch, which is why +// both the list filter and the usage aggregate key off this prefix to avoid +// counting one call twice. Internal records WITHOUT it (retrieve_tools, +// describe_tool, code_execution, upstream_servers, quarantine_security …) are +// mcpproxy's own work and have no paired record. +const InternalCallToolPrefix = "call_tool_" + // Metadata keys carried by an ActivityStatusRejected record (spec 093 FR-012). const ( // MetadataKeyRejectionReason is "queue_full" or "queue_timeout". @@ -195,6 +204,18 @@ type ActivityRecord struct { RequestID string `json:"request_id,omitempty"` // HTTP request ID for correlation Metadata map[string]interface{} `json:"metadata,omitempty"` // Additional context-specific data + // ParentID is the correlation id of the record that CAUSED this one: today + // the code_execution call whose sandbox issued this sub-call. It equals the + // parent record's RequestID, so the two directions are one query each: + // parent → children: /api/v1/activity?parent_id= + // child → parent: /api/v1/activity?request_id= + // + // First-class rather than metadata for the same reason as WorkSessionID: + // ActivityFilter.Matches compares struct fields, so a value tucked into + // Metadata would be stored but not filterable. Empty for every top-level + // call and for every record written before this field existed. + ParentID string `json:"parent_id,omitempty"` + // WorkSessionID groups records into one unit of USER WORK (Spec 082): one // client, in one project, under one principal, across reconnects. Unlike // SessionID it survives the client re-initializing, which real clients do @@ -241,6 +262,10 @@ type ActivityFilter struct { IntentType string // Filter by intent operation type: read, write, destructive (Spec 018) RequestID string // Filter by HTTP request ID for correlation (Spec 021) + // ParentID selects the CHILDREN of one parent call (exact match on + // ActivityRecord.ParentID) — the sub-calls a code_execution script issued. + ParentID string + // WorkSessionID filters by a unit of user work (Spec 082) — one client, one // project, across reconnects. This is what the UI's "Session" filter means; // SessionID above is the raw transport connection. @@ -255,11 +280,13 @@ type ActivityFilter struct { AgentName string // Filter by agent token name in metadata AuthType string // Filter by auth type: "admin" or "agent" - // ExcludeCallToolSuccess filters out call_tool_* internal tool calls that are - // already represented by a tool_call record: successful ones (the upstream - // call is logged) and rejected ones (the concurrency limiter logged the shed, - // spec 093). Failed call_tool_* calls are still shown — they have no - // corresponding tool_call entry. + // 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 + // (mcp.go emits both on every dispatched outcome), rejected ones with the + // concurrency limiter's shed record (spec 093). Pre-dispatch failures + // (arg validation, server not found) emit ONLY a tool_call record, so no + // call_tool_* row is ever the sole witness of a call. // Default: true (to avoid duplicate entries in UI/CLI) ExcludeCallToolSuccess bool } @@ -363,18 +390,23 @@ func (f *ActivityFilter) Matches(record *ActivityRecord) bool { return false } + // Check parent_id filter: the sub-calls one code_execution issued. + if f.ParentID != "" && record.ParentID != f.ParentID { + return false + } + // Exclude call_tool_* internal tool calls that are already represented by a // canonical tool_call entry, so one dispatch is never counted twice. // - // A SUCCESSFUL call_tool_* has the upstream's own tool_call record; a - // REJECTED one has the record the concurrency limiter wrote at the shed - // (spec 093 FR-012), which every origin produces — the variant handler - // merely adds a second, MCP-flavoured row on top of it. Failed call_tool_* - // calls stay visible: they have no corresponding tool_call. + // A SUCCESSFUL or FAILED call_tool_* has the upstream's own tool_call + // record (mcp.go emits both on every dispatched outcome, sharing one + // request_id); a REJECTED one has the record the concurrency limiter wrote + // at the shed (spec 093 FR-012), which every origin produces — the variant + // handler merely adds a second, MCP-flavoured row on top of it. So every + // call_tool_* row duplicates a canonical record and is hidden by default. if f.ExcludeCallToolSuccess { if record.Type == ActivityTypeInternalToolCall && - (record.Status == ActivityStatusSuccess || record.Status == ActivityStatusRejected) && - strings.HasPrefix(record.ToolName, "call_tool_") { + strings.HasPrefix(record.ToolName, InternalCallToolPrefix) { return false } } diff --git a/internal/storage/activity_parent_test.go b/internal/storage/activity_parent_test.go new file mode 100644 index 000000000..2e3924077 --- /dev/null +++ b/internal/storage/activity_parent_test.go @@ -0,0 +1,142 @@ +package storage + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" +) + +func newActivityTestManager(t *testing.T) *Manager { + t.Helper() + mgr, err := NewManager(t.TempDir(), zap.NewNop().Sugar()) + require.NoError(t, err) + t.Cleanup(func() { _ = mgr.Close() }) + return mgr +} + +// A code_execution and the sub-calls its sandbox issued are linked by one id in +// both directions, and each direction has to be a single query: +// +// parent → children: filter by ParentID +// child → parent: filter by RequestID +func TestActivityFilter_ParentID_SelectsChildrenOfOneParent(t *testing.T) { + parent := &ActivityRecord{ + Type: ActivityTypeInternalToolCall, + ToolName: "code_execution", + Status: ActivityStatusSuccess, + RequestID: "parent-1", + } + child := &ActivityRecord{ + Type: ActivityTypeToolCall, + ServerName: "github", + ToolName: "search", + Status: ActivityStatusSuccess, + RequestID: "child-1", + ParentID: "parent-1", + } + otherChild := &ActivityRecord{ + Type: ActivityTypeToolCall, + ServerName: "github", + ToolName: "search", + Status: ActivityStatusSuccess, + RequestID: "child-2", + ParentID: "parent-2", + } + topLevel := &ActivityRecord{ + Type: ActivityTypeToolCall, + ServerName: "github", + ToolName: "search", + Status: ActivityStatusSuccess, + RequestID: "top-1", + } + + byParent := ActivityFilter{ParentID: "parent-1"} + assert.True(t, byParent.Matches(child)) + assert.False(t, byParent.Matches(otherChild)) + assert.False(t, byParent.Matches(topLevel), "a top-level call has no parent") + assert.False(t, byParent.Matches(parent), "the parent is not its own child") + + byRequest := ActivityFilter{RequestID: child.ParentID} + assert.True(t, byRequest.Matches(parent), "child -> parent is one request_id query") + assert.False(t, byRequest.Matches(child)) +} + +// The default filter drops the internal call_tool_* rows a direct dispatch +// already covers. Sandbox sub-calls are tool_call records, so that exclusion +// must not touch them — otherwise the feature would ship invisible. +func TestActivityFilter_DefaultDoesNotHideSandboxChildren(t *testing.T) { + filter := DefaultActivityFilter() + require.True(t, filter.ExcludeCallToolSuccess) + + child := &ActivityRecord{ + Type: ActivityTypeToolCall, + ServerName: "github", + ToolName: "search", + Status: ActivityStatusSuccess, + RequestID: "child-1", + ParentID: "parent-1", + } + assert.True(t, filter.Matches(child)) +} + +// ParentID must survive the BBolt round-trip: it is a first-class field, not +// metadata, precisely so it can be stored AND filtered on. +func TestActivityRecord_ParentIDRoundTripsThroughStorage(t *testing.T) { + mgr := newActivityTestManager(t) + base := time.Now().UTC().Add(-time.Minute) + + require.NoError(t, mgr.SaveActivity(&ActivityRecord{ + Type: ActivityTypeInternalToolCall, ToolName: "code_execution", + Status: ActivityStatusSuccess, RequestID: "parent-1", Timestamp: base, + })) + require.NoError(t, mgr.SaveActivity(&ActivityRecord{ + Type: ActivityTypeToolCall, ServerName: "github", ToolName: "search", + Status: ActivityStatusSuccess, RequestID: "child-1", ParentID: "parent-1", + Timestamp: base.Add(time.Second), + })) + require.NoError(t, mgr.SaveActivity(&ActivityRecord{ + Type: ActivityTypeToolCall, ServerName: "github", ToolName: "search", + Status: ActivityStatusError, RequestID: "child-2", ParentID: "parent-1", + Timestamp: base.Add(2 * time.Second), + })) + require.NoError(t, mgr.SaveActivity(&ActivityRecord{ + Type: ActivityTypeToolCall, ServerName: "github", ToolName: "search", + Status: ActivityStatusSuccess, RequestID: "unrelated", Timestamp: base.Add(3 * time.Second), + })) + + records, total, err := mgr.ListActivities(ActivityFilter{ParentID: "parent-1"}) + require.NoError(t, err) + assert.Equal(t, 2, total) + require.Len(t, records, 2) + for _, rec := range records { + assert.Equal(t, "parent-1", rec.ParentID) + } +} + +// ScanActivitiesAfter is the usage aggregate's catch-up replay. Its bound is +// STRICTLY greater than the snapshot stamp, because a record at or before the +// stamp is already folded in and re-applying it would double it. +func TestScanActivitiesAfter_IsStrictlyExclusiveOfTheBound(t *testing.T) { + mgr := newActivityTestManager(t) + base := time.Date(2026, 6, 1, 10, 0, 0, 0, time.UTC) + + for i, ts := range []time.Time{base.Add(-time.Minute), base, base.Add(time.Nanosecond), base.Add(time.Minute)} { + require.NoError(t, mgr.SaveActivity(&ActivityRecord{ + Type: ActivityTypeToolCall, ServerName: "s", ToolName: "t", + Status: ActivityStatusSuccess, RequestID: string(rune('a' + i)), Timestamp: ts, + })) + } + + var seen []string + require.NoError(t, mgr.ScanActivitiesAfter(base, func(rec *ActivityRecord) { + seen = append(seen, rec.RequestID) + })) + assert.Equal(t, []string{"c", "d"}, seen, + "the record AT the bound is already counted; only strictly newer ones replay") + + assert.Error(t, mgr.ScanActivitiesAfter(time.Time{}, func(*ActivityRecord) {}), + "a zero bound has no safe meaning and must not silently replay everything") +} diff --git a/internal/storage/activity_stats.go b/internal/storage/activity_stats.go index 700ed990d..53045bc85 100644 --- a/internal/storage/activity_stats.go +++ b/internal/storage/activity_stats.go @@ -2,6 +2,7 @@ package storage import ( "fmt" + "time" "go.etcd.io/bbolt" ) @@ -88,3 +89,52 @@ func (m *Manager) ScanAllActivities(visit func(*ActivityRecord)) error { return nil }) } + +// ScanActivitiesAfter visits every activity record STRICTLY newer than `since`, +// oldest first. It is the catch-up replay behind a persisted usage snapshot: a +// snapshot is flushed every 30s, so an unclean shutdown always leaves a tail of +// records that were saved but never folded in, and loading the snapshot alone +// left that tail permanently missing from the aggregate while the activity list +// showed it. +// +// The bound is real work avoided, not a convenience: activity keys are +// "<20-digit unix nanos>_", so seeking to the nanosecond after `since` +// skips the entire history in one cursor move instead of unmarshalling it. +// +// Strictly-greater is what makes the replay safe to run every start: records +// are persisted BEFORE they are folded into the aggregate, so anything at or +// before the snapshot's stamp is already counted and re-applying it would +// double it. +// +// A zero `since` is rejected rather than treated as "everything": the caller +// that cannot date its snapshot must rebuild from a full scan, not replay a +// history it may already contain. +func (m *Manager) ScanActivitiesAfter(since time.Time, visit func(*ActivityRecord)) error { + if since.IsZero() { + return fmt.Errorf("ScanActivitiesAfter requires a non-zero lower bound") + } + seek := []byte(fmt.Sprintf("%020d_", since.UnixNano()+1)) + + return m.db.db.View(func(tx *bbolt.Tx) error { + bucket := tx.Bucket([]byte(ActivityRecordsBucket)) + if bucket == nil { + return nil + } + cursor := bucket.Cursor() + for k, v := cursor.Seek(seek); k != nil; k, v = cursor.Next() { + var record ActivityRecord + if err := record.UnmarshalBinary(v); err != nil { + m.logger.Warnw("Failed to unmarshal activity record during usage catch-up", + "key", string(k), "error", err) + continue + } + // Belt and braces: the key encodes record.Timestamp, but a record + // written with a mismatched key must never be applied twice. + if !record.Timestamp.After(since) { + continue + } + visit(&record) + } + return nil + }) +} diff --git a/internal/storage/activity_test.go b/internal/storage/activity_test.go index 0c6b3fe92..3a02670a0 100644 --- a/internal/storage/activity_test.go +++ b/internal/storage/activity_test.go @@ -998,8 +998,8 @@ func TestActivityFilter_OneRejectedRowPerShed(t *testing.T) { assert.True(t, def.Matches(canonical), "the limiter's rejected row is the canonical one") assert.False(t, def.Matches(variantEcho), "the variant handler's rejected echo duplicates the canonical row and must be hidden by default") - assert.True(t, def.Matches(failedVariant), - "a failed call_tool_* has no corresponding tool_call and must stay visible") + assert.False(t, def.Matches(failedVariant), + "a failed call_tool_* duplicates the paired tool_call error record and must be hidden by default") // The code_execution and replay origins never reach the variant handler, so // their shed produces the canonical row only — still exactly one. diff --git a/native/macos/MCPProxy/MCPProxy/API/Models.swift b/native/macos/MCPProxy/MCPProxy/API/Models.swift index f3f36e982..fbae11dbb 100644 --- a/native/macos/MCPProxy/MCPProxy/API/Models.swift +++ b/native/macos/MCPProxy/MCPProxy/API/Models.swift @@ -548,6 +548,16 @@ struct ActivityEntry: Codable, Identifiable, Equatable { let timestamp: String let sessionId: String? let requestId: String? + /// Correlation id of the `code_execution` call this record is a sub-call of, + /// or nil for a top-level record. + /// + /// It is the PARENT's `requestId` (the core mints one `parentCallID` per + /// `code_execution` dispatch and stamps every sandboxed `call_tool` with + /// it), so `?parent_id=` fetches a parent's children and + /// `?request_id=` fetches a child's parent. Children carry + /// fresh request ids of their own, which is what keeps rule 4 from + /// collapsing a whole script into one row. + let parentId: String? let metadata: [String: JSONValue]? let hasSensitiveData: Bool? let detectionTypes: [String]? @@ -562,6 +572,7 @@ struct ActivityEntry: Codable, Identifiable, Equatable { case durationMs = "duration_ms" case sessionId = "session_id" case requestId = "request_id" + case parentId = "parent_id" case hasSensitiveData = "has_sensitive_data" case detectionTypes = "detection_types" case maxSeverity = "max_severity" @@ -639,12 +650,32 @@ enum OutcomeClass: String, Equatable { case blocked } +/// How a record *ended*, coarsened to what a row can render (spec 090 FR-004). +/// +/// The second half of the group key, and the reason it exists: with only +/// `OutcomeClass` in the key, a stretch of calls to one tool that failed twice +/// in the middle was ONE run, rendered with the failure mark and a `×N` that +/// counted the successes too — a row claiming twelve failures where two +/// happened. Splitting the stretch by status class keeps every run homogeneous, +/// so a `×N` is always a count of the thing the row is marked as. +/// +/// Three classes, not one per raw status: `running`, `blocked` and anything +/// else the core may write are all "not finished the way a row cares about", +/// and bucketing them keeps an unfamiliar status from fragmenting a run record +/// by record. +enum StatusClass: String, Equatable { + case success + case failure + case pending +} + // MARK: - Glance accessors (spec 090) // // Derived, no stored fields. They exist so the tray's pure row pipeline reads -// one vocabulary — `reason`, `outcomeClass` — instead of re-deriving the -// metadata layout at every call site, and so a live SSE-adapted entry and a -// polled entry answer identically (`GlanceEvent` populates the same slots). +// one vocabulary — `reason`, `outcomeClass`, `statusClass` — instead of +// re-deriving the metadata layout at every call site, and so a live SSE-adapted +// entry and a polled entry answer identically (`GlanceEvent` populates the same +// slots). extension ActivityEntry { /// Reason a policy decision gives for itself: `metadata.reason`. @@ -683,6 +714,21 @@ extension ActivityEntry { return ActivityEntry.blockingDecisions.contains(decision) ? .blocked : .call } + /// Grouping class for the record's outcome (FR-004). + /// + /// Deliberately parallel to `outcomeClass` rather than folded into it: rule + /// 6 (`GlanceSelection.qualifies`) asks "did policy stop this call?", which + /// is a question about the record's KIND, while grouping also has to ask + /// "how did it end?". One enum answering both would make a blocked record + /// and a failed call indistinguishable at the qualification gate. + var statusClass: StatusClass { + switch status { + case "success": return .success + case "error": return .failure + default: return .pending + } + } + /// Activity record type of a policy decision (`storage.ActivityTypePolicyDecision`). static let policyDecisionType = "policy_decision" diff --git a/native/macos/MCPProxy/MCPProxy/Menu/Glance/GlanceEvent.swift b/native/macos/MCPProxy/MCPProxy/Menu/Glance/GlanceEvent.swift index 961463fab..f51e6f0b4 100644 --- a/native/macos/MCPProxy/MCPProxy/Menu/Glance/GlanceEvent.swift +++ b/native/macos/MCPProxy/MCPProxy/Menu/Glance/GlanceEvent.swift @@ -89,6 +89,10 @@ enum GlanceEvent { timestamp: timestamp, sessionId: nonEmptyString(payload["session_id"]), requestId: requestId, + // Carried live for the same reason the reason is: a child sub-call + // of a `code_execution` script must not lose its parent link for + // the 30 seconds before the reconciling poll re-ids it. + parentId: nonEmptyString(payload["parent_id"]), metadata: contextMetadata(from: payload), hasSensitiveData: nil, detectionTypes: nil, diff --git a/native/macos/MCPProxy/MCPProxy/Menu/Glance/GlanceFormatting.swift b/native/macos/MCPProxy/MCPProxy/Menu/Glance/GlanceFormatting.swift index 9915b7d30..831e15e96 100644 --- a/native/macos/MCPProxy/MCPProxy/Menu/Glance/GlanceFormatting.swift +++ b/native/macos/MCPProxy/MCPProxy/Menu/Glance/GlanceFormatting.swift @@ -18,9 +18,9 @@ enum GlanceFormatting { /// cross and an exclamation mark are three distinct glyphs. /// /// Keyed on the status *string* rather than a record, because a glance row - /// is a run of records and the outcome it shows is the run's worst - /// (`GlanceRun.worstStatus`), which may belong to none of the run's other - /// records. + /// is a run of records and the outcome it shows is the run's own + /// (`GlanceRun.status`) — the newest record's, which every other record in + /// the run shares, since a run never mixes success and failure. /// A block gets a triangle, not a differently-coloured circle: a policy /// block and an upstream failure are different events, and the difference /// has to survive greyscale and a red-green deficiency (spec 090 FR-011). diff --git a/native/macos/MCPProxy/MCPProxy/Menu/Glance/GlanceSection.swift b/native/macos/MCPProxy/MCPProxy/Menu/Glance/GlanceSection.swift index b9dc7435c..c7c7ea7ed 100644 --- a/native/macos/MCPProxy/MCPProxy/Menu/Glance/GlanceSection.swift +++ b/native/macos/MCPProxy/MCPProxy/Menu/Glance/GlanceSection.swift @@ -368,10 +368,15 @@ final class GlanceSection { /// and click payload all describe `run`. /// /// A row shows a *run* — one or more consecutive records of the same - /// (server, tool, outcome class) — so what it says is assembled from the - /// run, not from one record: the clock and the click payload come from the - /// newest record, the mark and the error clause from the worst/newest - /// failing one, and the `×N` suffix from how many there are. + /// (server, tool, outcome class, status class) — so what it says is + /// assembled from the run, not from one record: the clock, the click payload + /// and the mark come from the newest record, the error clause from the + /// newest failing one, and the `×N` suffix from how many there are. + /// + /// The run is homogeneous in outcome (status class is part of its key), so + /// the mark and the count always describe the same records: a row marked + /// failed with `×2` stands for two failures, never for two successes and a + /// failure among them. /// /// When the row has changed run every one of those is written back /// unconditionally: with a fixed set of rows each new event shifts which run @@ -395,7 +400,7 @@ final class GlanceSection { let countSuffix = run.count > 1 ? " ×\(run.count)" : "" let spokenCount = run.count > 1 ? ", repeated \(run.count) times" : "" let age = GlanceFormatting.relativeTime(run.timestamp, now: now) - let status = run.worstStatus + let status = run.status let failed = status != "success" let clause = failed ? Self.firstClause(of: run.errorMessage) : nil @@ -465,7 +470,7 @@ final class GlanceSection { /// Nil on systems without the subtitle mechanism (FR-005). private func subtitleText(for run: GlanceRun) -> String? { guard supportsRowSubtitles else { return nil } - if run.worstStatus != "success", let clause = Self.firstClause(of: run.errorMessage) { + if run.status != "success", let clause = Self.firstClause(of: run.errorMessage) { return GlanceFormatting.tailTruncated(clause, limit: GlanceFormatting.reasonBudget) } guard let reason = run.displayReason else { return nil } @@ -532,7 +537,8 @@ final class GlanceSection { /// This lives here rather than in `GlanceFormatting` because that file is /// deliberately AppKit-free (`import Foundation` only) and `NSColor` is not. /// Keyed on the status string, not a record: a row stands for a run, and the - /// outcome it shows is the run's worst (`GlanceRun.worstStatus`). + /// outcome it shows is the run's own (`GlanceRun.status`), which every + /// record in the run shares. static func statusTint(forStatus status: String) -> NSColor { switch status { case "success": diff --git a/native/macos/MCPProxy/MCPProxy/Menu/Glance/GlanceSelection.swift b/native/macos/MCPProxy/MCPProxy/Menu/Glance/GlanceSelection.swift index cecf6b323..35bcf2472 100644 --- a/native/macos/MCPProxy/MCPProxy/Menu/Glance/GlanceSelection.swift +++ b/native/macos/MCPProxy/MCPProxy/Menu/Glance/GlanceSelection.swift @@ -8,13 +8,20 @@ import Foundation /// One rendered activity row: a maximal run of *consecutive* qualifying records -/// that share a group key (server, tool, outcome class) — spec 090 FR-001…004. +/// that share a group key (server, tool, outcome class, status class) — spec 090 +/// FR-001…004. /// /// Consecutive-only is the whole point: the glance is a timeline, and clustering /// non-adjacent calls would claim an ordering that never happened. A burst of 19 /// `jira_get_issue` calls becomes one row; the same tool called again after /// something else stays a second row. /// +/// A run is also HOMOGENEOUS in outcome: successes and failures never share one. +/// The row is the count's subject, so "×12, failed" has to mean twelve failures +/// — and until status class joined the key it did not, because one error in a +/// stretch of successes marked the whole stretch failed and counted the +/// successes into it. +/// /// The run is a *view* over the records, not a summary of them: every derived /// value names the record it came from, so a row can always be traced back. struct GlanceRun: Equatable { @@ -24,15 +31,24 @@ struct GlanceRun: Equatable { /// Outcome class is in the key so a policy block never merges into a run of /// calls to the same tool (FR-002): "27 blocked attempts" and "27 calls" are /// different stories, and blocks are the ones worth reading. + /// + /// Status class is in it for the same reason one level down (FR-004): "×12 + /// failed" and "×10 succeeded, ×2 failed" are different stories too, and a + /// single key for both told the alarming one about ten calls that were fine. + /// The two are separate fields rather than one merged enum because rule 6 + /// (`qualifies`) asks only whether policy STOPPED the call, and merging + /// would make a block indistinguishable from a failure at that gate. struct Key: Equatable { let server: String let tool: String let outcomeClass: OutcomeClass + let statusClass: StatusClass init(for entry: ActivityEntry) { self.server = entry.serverName ?? "" self.tool = entry.toolName ?? "" self.outcomeClass = entry.outcomeClass + self.statusClass = entry.statusClass } } @@ -69,14 +85,23 @@ struct GlanceRun: Equatable { /// The newest failing record in the run, if any. `records` is newest-first, /// so `first` is the newest. + /// + /// Either every record in the run is failing or none is — status class is + /// part of the key — so this is the newest record itself on a failed run, + /// and nil on every other kind. var newestErroring: ActivityEntry? { records.first { $0.status == "error" } } - /// Worst outcome in the run, error beating success (FR-004). A run with no - /// failure reports the newest record's own status, so a call still running - /// is never announced as a failure. - var worstStatus: String { newestErroring?.status ?? newest.status } - - /// The error clause to show, from the NEWEST erroring record (FR-004). + /// The status the row renders (FR-004). + /// + /// The newest record's own, and that is now the whole rule: a run cannot + /// mix success and failure, so there is no "worst" to pick. It used to be + /// `newestErroring?.status ?? newest.status` — one error anywhere in the + /// stretch dominated the row — which is exactly what made a `×12` row of + /// mostly-successful calls read as twelve failures. + var status: String { newest.status } + + /// The error clause to show, from the NEWEST erroring record (FR-004) — + /// on a failed run, the newest record. var errorMessage: String? { newestErroring?.errorMessage } /// The reason to show: the newest record in the run that has one (FR-004) — @@ -147,16 +172,24 @@ enum GlanceSelection { /// upstream calls carry distinct ids structurally. A group is therefore a /// wrapper plus its upstream partner, never a fan-out. /// - /// What would invalidate that: `internal/server/mcp_code_execution.go` sets + /// The sub-calls a `code_execution` script makes are visible here now, and + /// they do NOT break that: `emitSubCallActivity` + /// (`internal/server/mcp_code_execution.go`) mints a FRESH correlation id + /// per sub-call — the counter suffix in `mintCorrelationIDAt` is what makes + /// it unique — and names the script through `parent_id`, which carries the + /// parent's request id rather than a shared one. No child shares an id with + /// another child or with the parent, so a multi-tool script renders as the + /// script's own row plus one row per sub-call (the transparency the feature + /// exists for) instead of collapsing to one. + /// + /// Note the legacy `ToolCallRecord` written beside it still carries /// `RequestID: u.executionID` ("Use execution ID as request ID to link - /// nested calls") on every nested call a `code_execution` script makes, so - /// all of them share ONE id. Those records are currently invisible here — - /// the nested caller only writes to the legacy history via - /// `storage.RecordToolCall` and emits no activity event. If nested calls - /// are ever wired into the activity stream, this function would collapse an - /// entire multi-tool script down to a single row. At that point rule 4 must - /// narrow to "collapse a wrapper with its upstream partner" rather than - /// deduplicating a whole request id. + /// nested calls") — one id for the whole script. That is the history table, + /// not the activity stream this pipeline reads. Should the ACTIVITY records + /// ever be given that shape, this function would collapse an entire script + /// down to a single row, and rule 4 would have to narrow to "collapse a + /// wrapper with its upstream partner" rather than deduplicating a whole + /// request id. static func collapseByRequestID(_ entries: [ActivityEntry]) -> [ActivityEntry] { var winners: [String: ActivityEntry] = [:] for entry in entries { diff --git a/native/macos/MCPProxy/MCPProxy/State/AppState.swift b/native/macos/MCPProxy/MCPProxy/State/AppState.swift index 513da3f8d..bb0ab5b2d 100644 --- a/native/macos/MCPProxy/MCPProxy/State/AppState.swift +++ b/native/macos/MCPProxy/MCPProxy/State/AppState.swift @@ -447,14 +447,33 @@ final class AppState: ObservableObject { /// Whether a live SSE row will show up in the usage timeline's call count /// once the poll catches up. /// - /// The core's aggregate counts records of type `tool_call` and nothing else - /// — a blocked policy decision never executed, and an internal (built-in) - /// call is not an upstream one (`UsageAggregate.Apply`, - /// internal/runtime/usage_aggregate.go). Counting anything wider here would - /// swap one disagreement for the opposite one: the header would overshoot - /// the rows and then jump BACK at the next poll. + /// Mirrors `UsageAggregate.Apply` (internal/runtime/usage_aggregate.go), + /// whose timeline matches the glance population: executed `tool_call`s + /// (sheds rejected by the concurrency limiter never ran and stay out, + /// spec 093), mcpproxy's own internal calls except the `call_tool_*` + /// variant echoes (those mirror a dispatch that already emitted its own + /// `tool_call` record), and blocked/rejected policy decisions. Anything + /// wider or narrower here makes the header disagree with the bars until + /// the next poll corrects it. static func countsTowardUsageTimeline(_ entry: ActivityEntry) -> Bool { - entry.type == "tool_call" && !(entry.toolName ?? "").isEmpty + guard let name = entry.toolName, !name.isEmpty else { return false } + switch entry.type { + case "tool_call": + return entry.status != "rejected" + case "internal_tool_call": + // Mirrors GlanceSelection: management built-ins never row (rule 1), + // call_tool_* echoes never do (their dispatch emitted its own + // tool_call record), and other internal calls row on success only + // for the discovery/execution set, on failure always (rule 3). + guard !name.hasPrefix("call_tool_"), + !GlanceSelection.managementBuiltIns.contains(name) else { return false } + return entry.status != "success" + || GlanceSelection.glanceInternalTools.contains(name) + case ActivityEntry.policyDecisionType: + return entry.status == "blocked" || entry.status == "rejected" + default: + return false + } } /// Calls recorded on the 24-hour axis ending at `now` — the same window diff --git a/native/macos/MCPProxy/MCPProxy/Views/ActivityView.swift b/native/macos/MCPProxy/MCPProxy/Views/ActivityView.swift index 263dcce7c..8d3477974 100644 --- a/native/macos/MCPProxy/MCPProxy/Views/ActivityView.swift +++ b/native/macos/MCPProxy/MCPProxy/Views/ActivityView.swift @@ -28,6 +28,14 @@ struct ActivityView: View { @State private var filterServer = "all" @State private var filterStatus = "all" @State private var filterText = "" + /// When set, the list shows only the sub-calls of this code_execution + /// (records whose parent_id equals it). Set by "View sub-calls" in the + /// detail panel; cleared by the filter chip or "View parent call". + @State private var filterParentId: String? + /// Monotonic ticket for loadActivities: only the NEWEST in-flight load may + /// publish its results, so a slow unfiltered fetch can never overwrite the + /// sub-call view the user just asked for (or vice versa). + @State private var loadGeneration = 0 private var apiClient: APIClient? { appState.apiClient } @@ -83,9 +91,44 @@ struct ActivityView: View { if filterType != "all" { parts.append("type=\(filterType)") } if filterServer != "all" { parts.append("server=\(filterServer)") } if filterStatus != "all" { parts.append("status=\(filterStatus)") } + if let parentId = filterParentId, !parentId.isEmpty { + parts.append("parent_id=\(parentId)") + } return parts.joined(separator: "&") } + // MARK: - Parent/child navigation (code_execution sub-calls) + + /// Filter the list down to the children of one code_execution call. + /// The parent's own selection is dropped: it is not in the filtered list, + /// and keeping it would silently reopen its detail panel the moment the + /// chip is cleared and the parent scrolls back in. + private func showSubCalls(of parentRequestId: String) { + filterParentId = parentRequestId + selectedActivityID = nil + Task { await loadActivities() } + } + + /// Jump from a child back to its parent code_execution record: drop the + /// sub-call filter, reload the normal list, and select the parent. When + /// the parent has already scrolled past the 100-row page, fetch it by + /// request_id and pin it to the top so the jump never dead-ends. + private func showParent(requestId: String) async { + filterParentId = nil + await loadActivities() + if let parent = activities.first(where: { $0.requestId == requestId }) { + selectedActivityID = parent.id + return + } + guard let client = apiClient else { return } + if let data = try? await client.fetchRaw(path: "/api/v1/activity?request_id=\(requestId)&limit=1"), + let wrapper = try? JSONDecoder().decode(APIResponse.self, from: data), + let parent = wrapper.data?.activities.first { + activities.insert(parent, at: 0) + selectedActivityID = parent.id + } + } + // MARK: - Column widths // Kept tight so that with the detail panel open the list can still coexist // with the outer NavigationSplitView sidebar at the default 800pt window width. @@ -160,7 +203,13 @@ struct ActivityView: View { ActivityDetailView( entry: selected, recentSessions: appState.recentSessions, - onDismiss: { selectedActivityID = nil } + onDismiss: { selectedActivityID = nil }, + onShowSubCalls: { parentRequestId in + showSubCalls(of: parentRequestId) + }, + onShowParent: { parentRequestId in + Task { await showParent(requestId: parentRequestId) } + } ) .frame(minWidth: 300, idealWidth: 380, maxWidth: 520, maxHeight: .infinity) .layoutPriority(1) @@ -331,11 +380,47 @@ struct ActivityView: View { .buttonStyle(.borderless) } } + + // Sub-call filter chip: the list is narrowed to one code_execution's + // children until the chip is dismissed. + if let parentId = filterParentId { + HStack(spacing: 6) { + Image(systemName: "arrow.turn.down.right") + .font(.scaled(.caption, scale: fontScale)) + Text("Sub-calls of \(Self.shortCorrelationId(parentId))") + .font(.scaled(.caption, scale: fontScale)) + .lineLimit(1) + .truncationMode(.middle) + Button { + filterParentId = nil + Task { await loadActivities() } + } label: { + Image(systemName: "xmark.circle.fill") + .foregroundStyle(.secondary) + } + .buttonStyle(.borderless) + .help("Show all activity") + .accessibilityLabel("Clear sub-call filter") + .accessibilityIdentifier("activity-clear-parent-filter") + Spacer() + } + .padding(.horizontal, 10) + .padding(.vertical, 5) + .background(Color.accentColor.opacity(0.12)) + .clipShape(Capsule()) + .accessibilityIdentifier("activity-parent-filter-chip") + } } .padding(.horizontal) .padding(.bottom, 8) } + /// Correlation ids are long ("-code_execution-17"); the chip shows + /// the tail, which is the part a human can actually tell apart. + static func shortCorrelationId(_ id: String) -> String { + id.count <= 24 ? id : "…" + id.suffix(24) + } + // MARK: - Empty State @ViewBuilder @@ -383,6 +468,8 @@ struct ActivityView: View { } private func loadActivities() async { + loadGeneration += 1 + let ticket = loadGeneration isLoading = true defer { isLoading = false } guard let client = apiClient else { @@ -392,6 +479,10 @@ struct ActivityView: View { do { let data = try await client.fetchRaw(path: "/api/v1/activity?\(filterQueryString)") + // A newer load was issued while this one was in flight (the user + // toggled the sub-call chip, changed a filter …) — its answer is + // the one the current filter state describes, not this one. + guard ticket == loadGeneration else { return } let decoder = JSONDecoder() if let wrapper = try? decoder.decode(APIResponse.self, from: data), let payload = wrapper.data { @@ -402,6 +493,7 @@ struct ActivityView: View { totalCount = direct.total } } catch { + guard ticket == loadGeneration else { return } activities = appState.recentActivity } } @@ -483,6 +575,15 @@ struct ActivityTableRow: View { // Details column (tool name) HStack(spacing: 4) { + // A sub-call made inside a code_execution script: marked so the + // list reads as parent-with-children, not five unrelated calls. + if let parentId = entry.parentId, !parentId.isEmpty { + Image(systemName: "arrow.turn.down.right") + .foregroundStyle(.secondary) + .font(.scaled(.caption2, scale: fontScale)) + .help("Sub-call of a code_execution") + .accessibilityLabel("Sub-call of a code execution") + } Text(entry.toolName ?? "-") .font(.scaled(.caption, scale: fontScale)) .lineLimit(1) @@ -704,9 +805,37 @@ struct ActivityDetailView: View { let entry: ActivityEntry var recentSessions: [APIClient.MCPSession] = [] var onDismiss: (() -> Void)? = nil + /// Invoked with the entry's request_id when the user asks to see the + /// sub-calls of this code_execution record. + var onShowSubCalls: ((String) -> Void)? = nil + /// Invoked with the entry's parent_id when the user asks to jump from a + /// sub-call back to its parent code_execution record. + var onShowParent: ((String) -> Void)? = nil @Environment(\.fontScale) var fontScale @State private var copiedField: String? + /// The record is the PARENT of sandbox sub-calls: the built-in + /// code_execution call whose request_id its children carry as parent_id. + private var isCodeExecutionParent: Bool { + entry.type == "internal_tool_call" + && entry.toolName == "code_execution" + && !(entry.requestId ?? "").isEmpty + } + + /// The `code` argument of a code_execution record, when present — pulled + /// out of the JSON so it can render as source instead of an escaped string. + private var codeArgument: String? { + guard case .string(let code)? = entry.arguments?["code"], !code.isEmpty else { return nil } + return code + } + + /// Request arguments minus the extracted `code` field. + private var argumentsWithoutCode: [String: JSONValue]? { + guard var args = entry.arguments, codeArgument != nil else { return entry.arguments } + args.removeValue(forKey: "code") + return args.isEmpty ? nil : args + } + /// Resolve a human-readable client name from the session ID. private var clientName: String? { guard let sessionId = entry.sessionId, !sessionId.isEmpty else { return nil } @@ -745,14 +874,25 @@ struct ActivityDetailView: View { // Metadata grid metadataGrid + // Parent/child navigation for code_execution records + if isCodeExecutionParent || !(entry.parentId ?? "").isEmpty { + parentChildNavigation + } + // Intent Declaration if entry.intent != nil { Divider() intentSection } - // Request Arguments - if let args = entry.arguments, !args.isEmpty { + // Executed code, rendered as source (code_execution records) + if let code = codeArgument { + Divider() + codeSection(code: code) + } + + // Request Arguments (minus the code, which has its own section) + if let args = argumentsWithoutCode, !args.isEmpty { Divider() jsonSection( label: "Request Arguments", @@ -924,6 +1064,142 @@ struct ActivityDetailView: View { } } + // MARK: - Parent/child navigation + + @ViewBuilder + private var parentChildNavigation: some View { + VStack(alignment: .leading, spacing: 6) { + if isCodeExecutionParent, let requestId = entry.requestId, let onShowSubCalls { + Button { + onShowSubCalls(requestId) + } label: { + Label("View sub-calls", systemImage: "arrow.turn.down.right") + .font(.scaled(.subheadline, scale: fontScale)) + } + .help("Show only the tool calls this code_execution made") + .accessibilityIdentifier("activity-view-subcalls") + } + if let parentId = entry.parentId, !parentId.isEmpty { + HStack(spacing: 6) { + Text("Sub-call of code_execution") + .font(.scaled(.caption, scale: fontScale)) + .foregroundStyle(.secondary) + if let onShowParent { + Button { + onShowParent(parentId) + } label: { + Label("View parent call", systemImage: "arrow.uturn.up") + .font(.scaled(.subheadline, scale: fontScale)) + } + .help("Jump to the code_execution that made this call") + .accessibilityIdentifier("activity-view-parent") + } + } + } + } + } + + // MARK: - Code Section (code_execution source) + + @ViewBuilder + private func codeSection(code: String) -> some View { + let language = languageBadge + VStack(alignment: .leading, spacing: 4) { + HStack { + Text("Code") + .font(.scaled(.headline, scale: fontScale)) + Text(language) + .font(.scaled(.caption2, scale: fontScale).bold()) + .padding(.horizontal, 8) + .padding(.vertical, 3) + .background(Color.orange.opacity(0.15)) + .foregroundStyle(.orange) + .clipShape(Capsule()) + Spacer() + copyButton(text: code, field: "code") + } + + Text(Self.formatScriptForDisplay(code)) + .font(.scaledMonospaced(.caption, scale: fontScale)) + .textSelection(.enabled) + .padding(10) + .frame(maxWidth: .infinity, alignment: .leading) + .background(Color(.controlBackgroundColor)) + .cornerRadius(8) + .accessibilityIdentifier("activity-code-block") + } + } + + private var languageBadge: String { + if case .string(let lang)? = entry.arguments?["language"], !lang.isEmpty { + return lang.uppercased() + } + return "JAVASCRIPT" + } + + /// Break a one-line script into readable lines for display: agents send + /// `code` as a single line, and rendering it verbatim is an unreadable + /// wall. Statement ends (`;`) and block braces get a newline — but only + /// OUTSIDE string literals, so a semicolon inside 'a; b' never splits. + /// Scripts that already contain newlines are shown verbatim: their author + /// formatted them. + /// + /// DISPLAY-ONLY, deliberately conservative: regex literals and template + /// substitutions with nested backticks are not parsed (that needs a real + /// tokenizer), so a `/a;b/` regex may gain a line break on screen. The + /// Copy button always yields the verbatim original, never this rendering. + static func formatScriptForDisplay(_ code: String) -> String { + guard !code.contains("\n") else { return code } + var out = "" + var quote: Character? + var escaped = false + var depth = 0 + var parenDepth = 0 + var skipLeadingSpace = false + for ch in code { + if let q = quote { + out.append(ch) + if escaped { + escaped = false + } else if ch == "\\" { + escaped = true + } else if ch == q { + quote = nil + } + continue + } + if skipLeadingSpace { + if ch == " " { continue } + skipLeadingSpace = false + } + switch ch { + case "'", "\"", "`": + quote = ch + out.append(ch) + case ";" where parenDepth == 0: + out.append(ch) + out.append("\n") + out.append(String(repeating: " ", count: depth)) + skipLeadingSpace = true + case "(": + parenDepth += 1 + out.append(ch) + case ")": + parenDepth = max(0, parenDepth - 1) + out.append(ch) + case "{": + depth += 1 + out.append(ch) + case "}": + depth = max(0, depth - 1) + out.append(ch) + default: + out.append(ch) + } + } + return out + } + // MARK: - JSON Section (colored) @ViewBuilder diff --git a/native/macos/MCPProxy/MCPProxyTests/ActivityCodeFormattingTests.swift b/native/macos/MCPProxy/MCPProxyTests/ActivityCodeFormattingTests.swift new file mode 100644 index 000000000..7ff6de981 --- /dev/null +++ b/native/macos/MCPProxy/MCPProxyTests/ActivityCodeFormattingTests.swift @@ -0,0 +1,50 @@ +import XCTest +@testable import MCPProxy + +/// The Activity detail panel renders a code_execution's `code` argument as +/// source, not as an escaped JSON string — and one-line agent scripts are +/// broken at statement boundaries for readability. +final class ActivityCodeFormattingTests: XCTestCase { + + func testOneLineScriptBreaksAfterSemicolons() { + let code = "var a = call_tool('s', 't', {x: 1}); var b = 2; ({a: a, b: b})" + let formatted = ActivityDetailView.formatScriptForDisplay(code) + XCTAssertEqual(formatted.components(separatedBy: "\n").count, 3, + "two statement ends -> three lines, got: \(formatted)") + XCTAssertTrue(formatted.hasPrefix("var a = call_tool('s', 't', {x: 1});\n")) + } + + func testSemicolonInsideAStringLiteralNeverSplits() { + let code = "var s = 'a; b'; done(s)" + let formatted = ActivityDetailView.formatScriptForDisplay(code) + XCTAssertEqual(formatted, "var s = 'a; b';\ndone(s)") + } + + func testEscapedQuoteInsideStringDoesNotEndTheString() { + let code = "var s = 'it\\'s; fine'; next()" + let formatted = ActivityDetailView.formatScriptForDisplay(code) + XCTAssertEqual(formatted, "var s = 'it\\'s; fine';\nnext()") + } + + func testSemicolonInsideABlockIndents() { + let code = "for (var i = 0; i < 3; i++) { push(i); } done()" + let formatted = ActivityDetailView.formatScriptForDisplay(code) + XCTAssertTrue(formatted.contains("{ push(i);\n }"), + "statement inside a block gets one indent level, got: \(formatted)") + XCTAssertTrue(formatted.hasPrefix("for (var i = 0; i < 3; i++) {"), + "a for-header's semicolons are inside parens and must not split, got: \(formatted)") + } + + func testAlreadyFormattedScriptIsShownVerbatim() { + let code = "line1();\nline2();" + XCTAssertEqual(ActivityDetailView.formatScriptForDisplay(code), code) + } + + func testShortCorrelationIdPassesThroughAndLongOneKeepsTheTail() { + XCTAssertEqual(ActivityView.shortCorrelationId("abc-42"), "abc-42") + let long = "1787315011981233000-code_execution-17" + let short = ActivityView.shortCorrelationId(long) + XCTAssertTrue(short.hasPrefix("…")) + XCTAssertTrue(long.hasSuffix(short.dropFirst())) + } +} diff --git a/native/macos/MCPProxy/MCPProxyTests/AppStateGlanceTests.swift b/native/macos/MCPProxy/MCPProxyTests/AppStateGlanceTests.swift index e5c7b3d75..dea66fab4 100644 --- a/native/macos/MCPProxy/MCPProxyTests/AppStateGlanceTests.swift +++ b/native/macos/MCPProxy/MCPProxyTests/AppStateGlanceTests.swift @@ -163,6 +163,30 @@ final class AppStateGlanceTests: XCTestCase { XCTAssertEqual(state.glanceActivity.first?.status, "error") } + /// …and that correction now moves more than a mark: status is part of the + /// group key, so a late flip on one record of a run SPLITS the run. The + /// fingerprint has to carry the flip through for the split to happen at all + /// — an id-only guard would leave the menu showing one merged row forever. + func testALateStatusFlipSplitsTheRunItWasPartOf() throws { + let state = AppState() + state.coreState = .connected + let page = [ + try Self.activity(id: "a1", type: "tool_call", request: "r1"), + try Self.activity(id: "a2", type: "tool_call", request: "r2") + ] + state.updateGlanceActivity(page) + XCTAssertEqual(GlanceSelection.activityRows(from: state.glanceActivity).map(\.count), [2]) + + state.updateGlanceActivity([ + try Self.activity(id: "a1", type: "tool_call", status: "error", request: "r1"), + page[1] + ]) + + let rows = GlanceSelection.activityRows(from: state.glanceActivity) + XCTAssertEqual(rows.map(\.count), [1, 1], "the failed record left the successful run") + XCTAssertEqual(rows.map(\.status), ["error", "success"]) + } + // MARK: - Reconcile vs live SSE rows /// `AppState` is reached through `await`, and the poll suspends on the diff --git a/native/macos/MCPProxy/MCPProxyTests/GlanceEventTests.swift b/native/macos/MCPProxy/MCPProxyTests/GlanceEventTests.swift index d3366cf5a..848fc0ff3 100644 --- a/native/macos/MCPProxy/MCPProxyTests/GlanceEventTests.swift +++ b/native/macos/MCPProxy/MCPProxyTests/GlanceEventTests.swift @@ -33,6 +33,32 @@ final class GlanceEventTests: XCTestCase { XCTAssertEqual(entry.sessionId, "sess-1") XCTAssertEqual(entry.requestId, "req-1") XCTAssertNil(entry.errorMessage, "empty error_message must not become a failure detail") + XCTAssertNil(entry.parentId, "a top-level call has no parent") + } + + /// A sub-call made from inside a `code_execution` script carries its own + /// request id plus the script's, and the live row must keep the link — the + /// reconciling poll is 30 seconds away, and a child that arrives without a + /// parent is a row that cannot be navigated back to the script that ran it. + func testASubCallPayloadCarriesItsParentID() throws { + let json = """ + {"payload":{"server_name":"github","tool_name":"create_issue", + "session_id":"sess-1","request_id":"child-7", + "parent_id":"1753800000-sess-1-code_execution","status":"success", + "duration_ms":12},"timestamp":1753800000} + """ + let entry = try XCTUnwrap(GlanceEvent.adapt( + eventName: "activity.tool_call.completed", + data: Data(json.utf8) + )) + + XCTAssertEqual(entry.requestId, "child-7") + XCTAssertEqual(entry.parentId, "1753800000-sess-1-code_execution") + XCTAssertNotEqual(entry.requestId, entry.parentId, + "a child's own id is fresh, which is what keeps rule 4 from " + + "collapsing a whole script into one row") + XCTAssertTrue(GlanceSelection.qualifies(entry), + "sub-calls are ordinary tool calls and get ordinary rows") } /// Internal calls carry `internal_tool_name`, and `target_server` only when diff --git a/native/macos/MCPProxy/MCPProxyTests/GlanceGroupingTests.swift b/native/macos/MCPProxy/MCPProxyTests/GlanceGroupingTests.swift index babdfd1b2..e04409900 100644 --- a/native/macos/MCPProxy/MCPProxyTests/GlanceGroupingTests.swift +++ b/native/macos/MCPProxy/MCPProxyTests/GlanceGroupingTests.swift @@ -21,6 +21,7 @@ final class GlanceGroupingTests: XCTestCase { XCTAssertEqual(runs[0].key.server, "jira-gcore") XCTAssertEqual(runs[0].key.tool, "jira_get_issue") XCTAssertEqual(runs[0].key.outcomeClass, .call) + XCTAssertEqual(runs[0].key.statusClass, .success) XCTAssertEqual(runs[1].count, 1) XCTAssertEqual(runs[1].newest.id, "gh-0") } @@ -73,9 +74,14 @@ final class GlanceGroupingTests: XCTestCase { XCTAssertEqual(runs[0].records.map(\.id), ["newer", "older"]) } + /// Both calls fail here on purpose: the wrapper only qualifies when it + /// failed, and the surviving upstream record has to share the run's status + /// class with `newer` or the split would be the status change, not the + /// wrapper — which would prove nothing about rule 4. func testACollapsedWrapperDoesNotSplitTheRun() { let page = [ - Self.call(id: "newer", server: "s", tool: "t", requestId: "req-1"), + Self.call(id: "newer", server: "s", tool: "t", + status: "error", error: "newer boom", requestId: "req-1"), Self.internalCall(id: "wrapper", tool: "call_tool_read", status: "error", requestId: "req-2"), Self.call(id: "older", server: "s", tool: "t", @@ -86,9 +92,13 @@ final class GlanceGroupingTests: XCTestCase { XCTAssertEqual(runs[0].records.map(\.id), ["newer", "older"]) } - // MARK: - Worst outcome (FR-004) + // MARK: - Status class is part of the key (FR-004) - func testOneFailureInARunMarksTheWholeRunFailed() { + /// A stretch of calls to one tool that changed outcome mid-way is NOT one + /// run: a row marked failed with a ×12 that counts ten successes claims + /// twelve failures. The stretch splits where the outcome changed, so each + /// row's count is a count of its own records. + func testAMixedOutcomeStretchSplitsIntoOneRunPerStatus() { var page: [ActivityEntry] = [] for i in 0..<4 { page.append(Self.call(id: "ok-\(i)", server: "s", tool: "t")) @@ -101,13 +111,18 @@ final class GlanceGroupingTests: XCTestCase { page.append(Self.call(id: "ok-late-\(i)", server: "s", tool: "t")) } - let run = GlanceSelection.activityRows(from: page)[0] + let runs = GlanceSelection.activityRows(from: page) - XCTAssertEqual(run.count, 12) - XCTAssertEqual(run.worstStatus, "error", "failure dominates the group") - XCTAssertEqual(run.newestErroring?.id, "bad-new") - XCTAssertEqual(run.errorMessage, "auth failed: token expired", - "the clause comes from the NEWEST erroring record") + XCTAssertEqual(runs.count, 3, "success → failure → success is three runs, not one") + XCTAssertEqual(runs.map(\.count), [4, 2, 6], + "a failed run's ×N counts only its own records") + XCTAssertEqual(runs.map(\.key.statusClass), [.success, .failure, .success]) + XCTAssertEqual(runs.map(\.status), ["success", "error", "success"]) + XCTAssertEqual(runs[1].newestErroring?.id, "bad-new") + XCTAssertEqual(runs[1].errorMessage, "auth failed: token expired", + "the clause comes from the NEWEST record of the failing run") + XCTAssertNil(runs[0].errorMessage) + XCTAssertNil(runs[2].errorMessage) } func testAnAllSuccessRunKeepsTheSuccessStatus() { @@ -116,21 +131,37 @@ final class GlanceGroupingTests: XCTestCase { Self.call(id: "2", server: "s", tool: "t") ] let run = GlanceSelection.activityRows(from: page)[0] - XCTAssertEqual(run.worstStatus, "success") + XCTAssertEqual(run.count, 2) + XCTAssertEqual(run.status, "success") XCTAssertNil(run.newestErroring) XCTAssertNil(run.errorMessage) } - /// A call still running is not a failure, and must not be promoted to one - /// just because it shares a run with successes. - func testARunningRecordDoesNotBecomeAFailure() { + /// A call still running is not a failure — and it is not a success either, + /// so it does not join the run of finished calls before it. + func testARunningRecordDoesNotJoinTheRunOfFinishedCalls() { let page = [ Self.call(id: "running", server: "s", tool: "t", status: "running"), Self.call(id: "done", server: "s", tool: "t") ] + let runs = GlanceSelection.activityRows(from: page) + XCTAssertEqual(runs.map(\.count), [1, 1]) + XCTAssertEqual(runs.map(\.status), ["running", "success"]) + XCTAssertEqual(runs.map(\.key.statusClass), [.pending, .success]) + XCTAssertNil(runs[0].newestErroring) + } + + /// Consecutive failures at one tool are still one run — the split is by + /// outcome, not per record. + func testConsecutiveFailuresStayOneRun() { + let page = [ + Self.call(id: "e1", server: "s", tool: "t", status: "error", error: "newest: boom"), + Self.call(id: "e2", server: "s", tool: "t", status: "error", error: "older: boom") + ] let run = GlanceSelection.activityRows(from: page)[0] - XCTAssertEqual(run.worstStatus, "running") - XCTAssertNil(run.newestErroring) + XCTAssertEqual(run.count, 2) + XCTAssertEqual(run.status, "error") + XCTAssertEqual(run.errorMessage, "newest: boom") } // MARK: - Reason (FR-004) @@ -244,7 +275,7 @@ final class GlanceGroupingTests: XCTestCase { XCTAssertEqual(runs.count, 1) XCTAssertEqual(runs[0].count, 27) XCTAssertEqual(runs[0].key.outcomeClass, .blocked) - XCTAssertEqual(runs[0].worstStatus, "blocked") + XCTAssertEqual(runs[0].status, "blocked") } // MARK: - Helpers diff --git a/native/macos/MCPProxy/MCPProxyTests/GlanceHeaderConsistencyTests.swift b/native/macos/MCPProxy/MCPProxyTests/GlanceHeaderConsistencyTests.swift index 47da34465..332cf5823 100644 --- a/native/macos/MCPProxy/MCPProxyTests/GlanceHeaderConsistencyTests.swift +++ b/native/macos/MCPProxy/MCPProxyTests/GlanceHeaderConsistencyTests.swift @@ -176,14 +176,44 @@ final class GlanceHeaderConsistencyTests: XCTestCase { } /// Only what the usage timeline itself counts. A blocked call never - /// executed — the core's aggregate excludes it (`UsageAggregate.Apply`) — - /// so counting it here would make the header disagree with the poll that - /// follows it, in the other direction. - func testABlockedCallIsNotAddedToTheCallCount() { + /// executed, but it IS a red row in the glance and the core's aggregate now + /// counts it in the timeline (`UsageAggregate.applyBlocked`) — so the live + /// increment must count it too, or the header lags the bars by one until + /// the next poll. + func testABlockedCallIsAddedToTheCallCount() { let state = Self.connectedState() state.updateUsage(timeline: [Self.bucket(calls: 12)], now: Self.now) - state.prependGlanceActivity(Self.blockedEntry(), generation: state.connectionGeneration) - XCTAssertEqual(state.glanceCallsThisHour(now: Self.now), 12) + state.prependGlanceActivity( + Self.blockedEntry(timestamp: "2027-01-15T08:00:30Z"), + generation: state.connectionGeneration + ) + XCTAssertEqual(state.glanceCallsThisHour(now: Self.now), 13) + } + + /// The live-increment rule mirrors `UsageAggregate.Apply` case by case: + /// internal built-ins count except the `call_tool_*` variant echoes (they + /// mirror a dispatch whose own `tool_call` record is also on the stream), + /// and a `tool_call` shed by the concurrency limiter never executed. + func testLiveIncrementMirrorsTheAggregatesTimelineRule() { + XCTAssertTrue(AppState.countsTowardUsageTimeline( + Self.typedEntry(type: "internal_tool_call", tool: "code_execution", status: "success"))) + XCTAssertTrue(AppState.countsTowardUsageTimeline( + Self.typedEntry(type: "internal_tool_call", tool: "retrieve_tools", status: "error"))) + XCTAssertFalse(AppState.countsTowardUsageTimeline( + Self.typedEntry(type: "internal_tool_call", tool: "call_tool_read", status: "error"))) + XCTAssertFalse(AppState.countsTowardUsageTimeline( + Self.typedEntry(type: "internal_tool_call", tool: "upstream_servers", status: "success")), + "management built-ins are never glance rows, so no bar") + XCTAssertFalse(AppState.countsTowardUsageTimeline( + Self.typedEntry(type: "internal_tool_call", tool: "upstream_servers", status: "error")), + "rule 1 hides management built-ins whatever their status") + XCTAssertTrue(AppState.countsTowardUsageTimeline( + Self.typedEntry(type: "internal_tool_call", tool: "search_servers", status: "error")), + "any non-management internal failure is a glance row") + XCTAssertFalse(AppState.countsTowardUsageTimeline( + Self.typedEntry(type: "tool_call", tool: "create_issue", status: "rejected"))) + XCTAssertTrue(AppState.countsTowardUsageTimeline( + Self.typedEntry(type: "tool_call", tool: "create_issue", status: "error"))) } /// A live call from the hour that just ended belongs to that hour's bucket, @@ -273,12 +303,27 @@ final class GlanceHeaderConsistencyTests: XCTestCase { UsageBucket(start: AppState.floorToHour(now), calls: calls, errors: 0, totalRespBytes: 0) } - private static func blockedEntry() -> ActivityEntry { + private static func typedEntry(type: String, tool: String, status: String) -> ActivityEntry { + let json: [String: Any] = [ + "id": "typed-\(type)-\(tool)-\(status)", + "type": type, + "status": status, + "timestamp": "2027-01-15T08:00:00Z", + "request_id": "req-typed-\(tool)-\(status)", + "server_name": "github", + "tool_name": tool + ] + let data = try! JSONSerialization.data(withJSONObject: json) + // swiftlint:disable:next force_try + return try! JSONDecoder().decode(ActivityEntry.self, from: data) + } + + private static func blockedEntry(timestamp: String = "2027-01-15T08:00:00Z") -> ActivityEntry { let json: [String: Any] = [ "id": "blocked-1", "type": ActivityEntry.policyDecisionType, "status": "blocked", - "timestamp": "2027-01-15T08:00:00Z", + "timestamp": timestamp, "request_id": "req-blocked-1", "server_name": "github", "tool_name": "create_issue" diff --git a/native/macos/MCPProxy/MCPProxyTests/GlanceSectionTests.swift b/native/macos/MCPProxy/MCPProxyTests/GlanceSectionTests.swift index 5b65e31e5..356c92d09 100644 --- a/native/macos/MCPProxy/MCPProxyTests/GlanceSectionTests.swift +++ b/native/macos/MCPProxy/MCPProxyTests/GlanceSectionTests.swift @@ -211,8 +211,10 @@ final class GlanceSectionTests: XCTestCase { XCTAssertEqual(row.title, "github:create_issue — 30s") } - /// FR-004: one failure marks the whole run, with the NEWEST failure's clause. - func testAFailureInsideARunMarksTheRowWithTheNewestErrorClause() { + /// FR-004: a stretch that changed outcome is two rows, not one — the + /// successful call keeps its unmarked row, and the failures get a row of + /// their own whose ×N counts failures only, with the NEWEST failure's clause. + func testAFailureAfterASuccessBecomesItsOwnRowWithTheNewestErrorClause() { let state = Self.busyState() state.glanceActivity = [ Self.entry(id: "n1", server: "jira", tool: "get_issue", @@ -225,15 +227,22 @@ final class GlanceSectionTests: XCTestCase { timestamp: "2027-01-15T07:58:00Z", session: "sess-n3") ] let section = Self.makeSection() - let row = section.items(for: state, now: Self.now)[4] + let items = section.items(for: state, now: Self.now) - XCTAssertEqual(row.title, "jira:get_issue ×3 — 30s") - XCTAssertEqual(Self.subtitle(of: row), "auth failed", + let succeeded = items[4] + XCTAssertEqual(succeeded.title, "jira:get_issue — 30s") + XCTAssertTrue(succeeded.image === GlanceSection.clearRowImage, + "the successful call must not be marked by the failures beside it") + + let failed = items[5] + XCTAssertEqual(failed.title, "jira:get_issue ×2 — 1m", + "the failed row's ×N counts only its own records") + XCTAssertEqual(Self.subtitle(of: failed), "auth failed", "the newest failure's clause takes the second line") - XCTAssertEqual(row.image?.accessibilityDescription, "failed") - XCTAssertEqual(row.toolTip, "jira:get_issue\nauth failed: token expired") - XCTAssertEqual(row.accessibilityLabel(), - "jira:get_issue, repeated 3 times, failed: auth failed, 30s ago") + XCTAssertEqual(failed.image?.accessibilityDescription, "failed") + XCTAssertEqual(failed.toolTip, "jira:get_issue\nauth failed: token expired") + XCTAssertEqual(failed.accessibilityLabel(), + "jira:get_issue, repeated 2 times, failed: auth failed, 1m ago") } func testTheRepeatCountIsSpokenNotJustDrawn() { @@ -299,38 +308,52 @@ final class GlanceSectionTests: XCTestCase { XCTAssertEqual(items[4].representedObject as? String, "sess-o1") } - /// A late status correction on the run's newest record still lands: "same - /// run" must not mean "skip the update". - func testASameRunStillPicksUpALateFailure() { + /// A late status flip on the newest record of a ×3 run now SPLITS that run: + /// the record leaves the success run and becomes a failed run of its own. + /// That is a row appearing, which resizes an open menu — structural, so it + /// waits for close (FR-023) — and the rebuild that follows shows the split. + func testALateFailureSplitsTheRunAndIsStructural() { let state = Self.burstState() let section = Self.makeSection() - // One-line rows: with subtitles the late failure would gain a line, - // which is the structural case the next test pins. + // One-line rows so the assertion below is about the split, not about a + // second line arriving with it. section.supportsRowSubtitles = false - let items = section.items(for: state, now: Self.now) + _ = section.items(for: state, now: Self.now) state.glanceActivity[0] = Self.entry( id: "j1", server: "jira", tool: "get_issue", status: "error", error: "rate limited: try later", timestamp: "2027-01-15T07:59:30Z", session: "sess-j1") - XCTAssertTrue(section.updateInPlace(for: state, now: Self.now)) - XCTAssertEqual(items[4].title, "jira:get_issue ×3 · rate limited — 30s") + XCTAssertFalse(section.updateInPlace(for: state, now: Self.now), + "2 activity rows becoming 3 is structural") + + let rebuilt = Self.makeSection() + rebuilt.supportsRowSubtitles = false + let items = rebuilt.items(for: state, now: Self.now) + XCTAssertEqual(items[4].title, "jira:get_issue · rate limited — 30s") XCTAssertEqual(items[4].image?.accessibilityDescription, "failed") + XCTAssertEqual(items[5].title, "jira:get_issue ×2 — 1m", + "the successes that did not fail keep their own row and count") + XCTAssertTrue(items[5].image === GlanceSection.clearRowImage) + XCTAssertEqual(items[6].title, "github:create_issue — 3m") } /// With subtitles available, a late failure ADDS the error line — a row /// growing a line resizes the menu, so it is structural and waits for - /// close (FR-023), exactly like a run gaining its reason. + /// close (FR-023), exactly like a run gaining its reason. Asserted on a + /// single-record row, where the row COUNT is unchanged, so the refusal can + /// only come from the line-count preflight. func testALateFailureGainingItsErrorLineIsStructural() { - let state = Self.burstState() + let state = Self.busyState() let section = Self.makeSection() - _ = section.items(for: state, now: Self.now) + let items = section.items(for: state, now: Self.now) + XCTAssertEqual(items[4].title, "github:create_issue — 30s") state.glanceActivity[0] = Self.entry( - id: "j1", server: "jira", tool: "get_issue", status: "error", + id: "a", server: "github", tool: "create_issue", status: "error", error: "rate limited: try later", - timestamp: "2027-01-15T07:59:30Z", session: "sess-j1") + timestamp: "2027-01-15T07:59:30Z", session: "sess-a") XCTAssertFalse(section.updateInPlace(for: state, now: Self.now)) } diff --git a/native/macos/MCPProxy/MCPProxyTests/GlanceSelectionTests.swift b/native/macos/MCPProxy/MCPProxyTests/GlanceSelectionTests.swift index adee51d36..9d201f09b 100644 --- a/native/macos/MCPProxy/MCPProxyTests/GlanceSelectionTests.swift +++ b/native/macos/MCPProxy/MCPProxyTests/GlanceSelectionTests.swift @@ -113,6 +113,45 @@ final class GlanceSelectionTests: XCTestCase { XCTAssertEqual(rows.first?.displayReason, "Quarantined server") } + // MARK: - code_execution sub-calls (issue C) + + /// A `code_execution` script and the tools it called are separate rows, and + /// that is the point: the sub-calls are the transparency the parent row + /// cannot give. Rule 4 does not fold them together because every child gets + /// a request id of its own — it names the script through `parent_id`, which + /// carries the PARENT's request id, not a shared one. + func testCodeExecutionSubCallsEachKeepTheirOwnRow() { + let parentCallID = "1770000000-sess-code_execution" + let rows = GlanceSelection.activityRows(from: [ + Self.entry(id: "c2", type: "tool_call", server: "jira", tool: "get_issue", + requestId: "child-2", parentId: parentCallID), + Self.entry(id: "c1", type: "tool_call", server: "github", tool: "create_issue", + requestId: "child-1", parentId: parentCallID), + Self.entry(id: "p", type: "internal_tool_call", tool: "code_execution", + requestId: parentCallID) + ]) + + XCTAssertEqual(rows.count, 3, "a script's sub-calls must not collapse into its own row") + XCTAssertEqual(rows.map(\.newest.id), ["c2", "c1", "p"]) + XCTAssertEqual(rows.map(\.count), [1, 1, 1]) + XCTAssertEqual(rows.last?.newest.parentId, nil, "the parent row has no parent of its own") + XCTAssertEqual(Set(rows.dropLast().compactMap(\.newest.parentId)), [parentCallID], + "each child names the parent's request id, which is how a row navigates up") + } + + /// Two sub-calls to the SAME tool are still one run, like any other pair of + /// consecutive identical calls — grouping does not know about parentage. + func testConsecutiveSubCallsToOneToolStillGroup() { + let parentCallID = "1770000000-sess-code_execution" + let rows = GlanceSelection.activityRows(from: [ + Self.entry(id: "c2", type: "tool_call", server: "jira", tool: "get_issue", + requestId: "child-2", parentId: parentCallID), + Self.entry(id: "c1", type: "tool_call", server: "jira", tool: "get_issue", + requestId: "child-1", parentId: parentCallID) + ]) + XCTAssertEqual(rows.map(\.count), [2]) + } + // MARK: - Helpers static func entry( @@ -122,6 +161,7 @@ final class GlanceSelectionTests: XCTestCase { tool: String? = nil, status: String = "success", requestId: String? = nil, + parentId: String? = nil, decision: String? = nil, reason: String? = nil ) -> ActivityEntry { @@ -134,6 +174,7 @@ final class GlanceSelectionTests: XCTestCase { if let server { json["server_name"] = server } if let tool { json["tool_name"] = tool } if let requestId { json["request_id"] = requestId } + if let parentId { json["parent_id"] = parentId } // A policy decision's own reason sits at the top of metadata, beside the // decision — the shape `activity_service.go` persists and the projection // whitelist keeps. diff --git a/native/macos/MCPProxy/MCPProxyTests/ModelsTests.swift b/native/macos/MCPProxy/MCPProxyTests/ModelsTests.swift index c11487d3b..95a610030 100644 --- a/native/macos/MCPProxy/MCPProxyTests/ModelsTests.swift +++ b/native/macos/MCPProxy/MCPProxyTests/ModelsTests.swift @@ -969,7 +969,8 @@ final class ModelsTests: XCTestCase { id: String = "e", type: String, status: String, - metadata: [String: Any]? = nil + metadata: [String: Any]? = nil, + extra: [String: Any] = [:] ) throws -> ActivityEntry { var json: [String: Any] = [ "id": id, @@ -978,6 +979,7 @@ final class ModelsTests: XCTestCase { "timestamp": "2026-03-23T12:00:00Z" ] if let metadata { json["metadata"] = metadata } + for (key, value) in extra { json[key] = value } let data = try JSONSerialization.data(withJSONObject: json) return try JSONDecoder().decode(ActivityEntry.self, from: data) } @@ -1060,4 +1062,29 @@ final class ModelsTests: XCTestCase { XCTAssertEqual(try entry(type: "policy_decision", status: "block").outcomeClass, .blocked) XCTAssertEqual(try entry(type: "policy_decision", status: "warning").outcomeClass, .call) } + + /// The second half of the group key (FR-004): three coarse classes, so a + /// success and a failure at the same tool can never share a run. + func testStatusClassCoarsensTheStatusIntoThreeGroups() throws { + XCTAssertEqual(try entry(type: "tool_call", status: "success").statusClass, .success) + XCTAssertEqual(try entry(type: "tool_call", status: "error").statusClass, .failure) + XCTAssertEqual(try entry(type: "tool_call", status: "running").statusClass, .pending) + XCTAssertEqual(try entry(type: "tool_call", status: "pending").statusClass, .pending) + // Everything the core may ever write that is neither of the two known + // terminal statuses lands in one bucket, so an unrecognised status + // never fragments a run record by record. + XCTAssertEqual(try entry(type: "policy_decision", status: "blocked").statusClass, .pending) + XCTAssertEqual(try entry(type: "tool_call", status: "something-new").statusClass, .pending) + } + + /// A `parent_id` on the wire is the correlation id of the `code_execution` + /// call that made this sub-call. It must survive decoding so the tray can + /// route a child row back to its parent. + func testActivityEntryDecodesParentID() throws { + let child = try entry(type: "tool_call", status: "success", + extra: ["parent_id": "1770000000-abc-code_execution"]) + XCTAssertEqual(child.parentId, "1770000000-abc-code_execution") + XCTAssertNil(try entry(type: "tool_call", status: "success").parentId, + "a record with no parent decodes with none") + } } diff --git a/oas/docs.go b/oas/docs.go index 35c024081..d58aaa6a2 100644 --- a/oas/docs.go +++ b/oas/docs.go @@ -6,10 +6,10 @@ import "github.com/swaggo/swag/v2" const docTemplate = `{ "schemes": {{ marshal .Schemes }}, - "components": {"schemas":{"config.ConcurrencyDefaults":{"description":"ServerConcurrencyDefaults is scope (b) of FR-020: the blanket per-server\ndefault set inherited by every server that does not override a setting.\nAbsent (the default) = no per-server limiting unless a server configures\nit explicitly. File/API-configured only — no env scheme (FR-022).","properties":{"max_concurrent_requests":{"type":"integer"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"}},"type":"object"},"config.Config":{"properties":{"activity_cleanup_interval_min":{"description":"Background cleanup interval in minutes (default: 60)","type":"integer"},"activity_max_records":{"description":"Max records before pruning (default: 100000)","type":"integer"},"activity_max_response_size":{"description":"Response truncation limit in bytes (default: 65536)","type":"integer"},"activity_max_size_mb":{"description":"Max total activity-log size in MB before pruning oldest (default: 256, 0=disabled)","type":"integer"},"activity_retention_days":{"description":"Activity logging settings (RFC-003)","type":"integer"},"aggregate_upstream_prompts":{"description":"AggregateUpstreamPrompts, when true, aggregates every connected upstream\nserver's advertised MCP prompts into mcpproxy's own prompts/list\n(exposed as \"\u003cserver\u003e__\u003cprompt\u003e\"). OFF by default: users are safe by\ndefault and opt in deliberately. EnablePrompts still governs the built-in\nprompts + the prompts capability; this flag gates ONLY the upstream\naggregation performed by RefreshPrompts. Hot-reloadable.","type":"boolean"},"allow_private_registry_fetch":{"description":"AllowPrivateRegistryFetch opts out of the registry SSRF guard (MCP-1076,\nCWE-918). By default (false) registry fetches refuse any host that is — or\nresolves to — a non-routable address (loopback, RFC1918/CGNAT private,\nlink-local incl. the 169.254.169.254 cloud-metadata endpoint), so a\nmalicious or typo'd registry source cannot turn the daemon into a\nrequest-forgery vector against internal services.\n\nThis opt-out is BLANKET (all-or-nothing): setting it true disables the\nguard for EVERY non-routable range at once — loopback, RFC1918/CGNAT\nprivate, link-local AND the 169.254.169.254 cloud-metadata endpoint. There\nis no way to allow only loopback; enabling it for a localhost dev registry\nalso re-opens the cloud-metadata SSRF vector. Set true ONLY when you\nintentionally run a trusted registry mirror on an internal/private address,\nideally on a host with no cloud-metadata exposure. The change takes effect\nonly on daemon (re)start or config reload.","type":"boolean"},"allow_server_add":{"type":"boolean"},"allow_server_remove":{"type":"boolean"},"api_key":{"description":"Security settings","type":"string"},"call_tool_timeout":{"type":"string"},"check_server_repo":{"description":"Repository detection settings","type":"boolean"},"code_execution_max_parallel":{"description":"Default concurrency for call_tools() batches (1-32, default: 8)","type":"integer"},"code_execution_max_tool_calls":{"description":"Max tool calls per execution (0 = unlimited, default: 0)","type":"integer"},"code_execution_pool_size":{"description":"JavaScript runtime pool size (default: 10)","type":"integer"},"code_execution_timeout_ms":{"description":"Timeout in milliseconds (default: 120000, max: 600000)","type":"integer"},"data_dir":{"type":"string"},"debug_search":{"type":"boolean"},"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":{"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"},"request_id":{"description":"HTTP request ID for correlation","type":"string"},"response":{"description":"Tool response (potentially truncated)","type":"string"},"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"},"end_time":{"description":"End of the period (RFC3339)","type":"string"},"error_count":{"description":"Count of error activities","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\", or \"\" (none)","type":"string"},"admin_state":{"description":"AdminState indicates the admin state: \"enabled\", \"disabled\", or \"quarantined\"","type":"string"},"detail":{"description":"Detail is an optional longer explanation of the status","type":"string"},"level":{"description":"Level indicates the health level: \"healthy\", \"degraded\", or \"unhealthy\"","type":"string"},"summary":{"description":"Summary is a human-readable status message (e.g., \"Connected (5 tools)\")","type":"string"}},"type":"object"},"contracts.InfoEndpoints":{"description":"Available API endpoints","properties":{"http":{"description":"HTTP endpoint address (e.g., \"127.0.0.1:8080\")","type":"string"},"socket":{"description":"Unix socket path (empty if disabled)","type":"string"}},"type":"object"},"contracts.InfoResponse":{"properties":{"endpoints":{"$ref":"#/components/schemas/contracts.InfoEndpoints"},"launched_by":{"description":"LaunchedBy is the durable launch provenance of the running core (Spec\n092 FR-001a): \"tray\" when a tray spawned it, \"installer\" when the macOS\nPKG postinstall did, \"\" when user-launched or unknown. Always present\n(possibly empty) so a tray can distinguish \"old core, not mine\" from\n\"old core I may supersede\".","type":"string"},"listen_addr":{"description":"Listen address (e.g., \"127.0.0.1:8080\")","type":"string"},"pid":{"description":"PID is the operating-system process id of the running core (Spec 092\nFR-002). A tray that merely ATTACHED to a core holds no Process handle\nfor it, so without this there is no mechanism at all to stop a stale\ncore — the consent action would have nothing to act on and could only\nprint instructions. Paired with LaunchedBy it is what lets a newer tray\nsupersede a core an older tray started.","type":"integer"},"update":{"$ref":"#/components/schemas/contracts.UpdateInfo"},"update_policy":{"$ref":"#/components/schemas/contracts.UpdatePolicy"},"version":{"description":"Current MCPProxy version","type":"string"},"web_ui_url":{"description":"URL to access the web control panel","type":"string"}},"type":"object"},"contracts.IsolationConfig":{"properties":{"cpu_limit":{"type":"string"},"enabled":{"type":"boolean"},"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"memory_limit":{"type":"string"},"network_mode":{"type":"string"},"timeout":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"contracts.IsolationDefaults":{"description":"IsolationDefaults exposes the resolved baseline values that\nwould apply when no per-server override is set. Populated on\nlist/get responses; never consumed on PATCH requests.","properties":{"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"network_mode":{"type":"string"},"runtime_type":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"contracts.LogEntry":{"properties":{"fields":{"type":"object"},"level":{"type":"string"},"message":{"type":"string"},"server":{"type":"string"},"timestamp":{"type":"string"}},"type":"object"},"contracts.MCPSession":{"properties":{"client_name":{"type":"string"},"client_version":{"type":"string"},"end_time":{"type":"string"},"experimental":{"items":{"type":"string"},"type":"array","uniqueItems":false},"has_roots":{"description":"MCP Client Capabilities","type":"boolean"},"has_sampling":{"type":"boolean"},"id":{"type":"string"},"last_activity":{"type":"string"},"start_time":{"type":"string"},"status":{"type":"string"},"tool_call_count":{"type":"integer"},"total_tokens":{"type":"integer"},"work_session_id":{"type":"string"},"workspace_name":{"description":"Workspace / work session (Spec 082). WorkspaceName is the project's\nbasename — the full local path is never exposed. WorkSessionID groups the\nreconnects that make up one stretch of user work.","type":"string"}},"type":"object"},"contracts.MetadataStatus":{"properties":{"authorization_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"error":{"type":"string"},"found":{"type":"boolean"},"url_checked":{"type":"string"}},"type":"object"},"contracts.MissingSecretInfo":{"properties":{"secret_name":{"type":"string"},"used_by":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.NPMPackageInfo":{"properties":{"exists":{"type":"boolean"},"install_cmd":{"type":"string"}},"type":"object"},"contracts.OAuthConfig":{"properties":{"auth_url":{"type":"string"},"client_id":{"type":"string"},"extra_params":{"additionalProperties":{"type":"string"},"type":"object"},"pkce_enabled":{"type":"boolean"},"redirect_port":{"type":"integer"},"scopes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"token_expires_at":{"description":"When the OAuth token expires","type":"string"},"token_url":{"type":"string"},"token_valid":{"description":"Whether token is currently valid","type":"boolean"}},"type":"object"},"contracts.OAuthErrorDetails":{"description":"Structured discovery/failure details","properties":{"authorization_server_metadata":{"$ref":"#/components/schemas/contracts.MetadataStatus"},"dcr_status":{"$ref":"#/components/schemas/contracts.DCRStatus"},"protected_resource_metadata":{"$ref":"#/components/schemas/contracts.MetadataStatus"},"server_url":{"type":"string"}},"type":"object"},"contracts.OAuthFlowError":{"properties":{"correlation_id":{"description":"Flow tracking ID for log correlation","type":"string"},"debug_hint":{"description":"CLI command for log lookup","type":"string"},"details":{"$ref":"#/components/schemas/contracts.OAuthErrorDetails"},"error_code":{"description":"Machine-readable error code (e.g., OAUTH_NO_METADATA)","type":"string"},"error_type":{"description":"Category of OAuth runtime failure","type":"string"},"message":{"description":"Human-readable error description","type":"string"},"request_id":{"description":"HTTP request ID (from PR #237)","type":"string"},"server_name":{"description":"Server that failed OAuth","type":"string"},"success":{"description":"Always false","type":"boolean"},"suggestion":{"description":"Actionable remediation hint","type":"string"}},"type":"object"},"contracts.OAuthIssue":{"properties":{"documentation_url":{"type":"string"},"error":{"type":"string"},"issue":{"type":"string"},"missing_params":{"items":{"type":"string"},"type":"array","uniqueItems":false},"resolution":{"type":"string"},"server_name":{"type":"string"}},"type":"object"},"contracts.OAuthRequirement":{"properties":{"expires_at":{"type":"string"},"message":{"type":"string"},"server_name":{"type":"string"},"state":{"type":"string"}},"type":"object"},"contracts.OAuthStartResponse":{"properties":{"auth_url":{"description":"Authorization URL (always included for manual use)","type":"string"},"browser_error":{"description":"Error message if browser launch failed","type":"string"},"browser_opened":{"description":"Whether browser launch succeeded","type":"boolean"},"correlation_id":{"description":"UUID for tracking this flow","type":"string"},"message":{"description":"Human-readable status message","type":"string"},"server_name":{"description":"Name of the server being authenticated","type":"string"},"success":{"description":"Always true for successful start","type":"boolean"}},"type":"object"},"contracts.PreflightPolicy":{"properties":{"exclude_destructive":{"type":"boolean"},"exclude_open_world":{"type":"boolean"},"read_only_only":{"type":"boolean"}},"type":"object"},"contracts.PreflightReason":{"type":"string","x-enum-varnames":["PreflightReasonServerInitializing","PreflightReasonServerUnhealthy","PreflightReasonServerDisabled","PreflightReasonServerQuarantined","PreflightReasonToolPendingApproval","PreflightReasonToolChanged","PreflightReasonToolBlockedByUser","PreflightReasonOAuthRequired","PreflightReasonHashMismatch","PreflightReasonServerNotInScope","PreflightReasonToolDeniedByConfig","PreflightReasonMissingAnnotation","PreflightReasonPolicyFiltered","PreflightReasonNotFound","PreflightReasonServerNotConfigured"]},"contracts.PreflightRequest":{"properties":{"policy":{"$ref":"#/components/schemas/contracts.PreflightPolicy"},"profile":{"description":"Profile evaluates under a named profile's server scope. Unknown: 400.","type":"string"},"tools":{"description":"Tools is 1..100 entries BEFORE dedup; duplicates are collapsed, and\nduplicate ids carrying different pins are a validation error.","items":{"$ref":"#/components/schemas/contracts.PreflightToolRef"},"type":"array","uniqueItems":false},"wait_ms":{"description":"WaitMS polls local state for up to this many milliseconds (cap 10000)\nwhile every failure is retryable-class.","type":"integer"}},"type":"object"},"contracts.PreflightResponse":{"properties":{"checked_at":{"type":"string"},"tools":{"description":"Tools are ordered by first occurrence of each unique id in the request.","items":{"$ref":"#/components/schemas/contracts.PreflightToolResult"},"type":"array","uniqueItems":false},"verdict":{"$ref":"#/components/schemas/contracts.PreflightVerdict"},"waited_ms":{"description":"WaitedMS is present when wait_ms was requested (0 when the wait\nsemaphore was exhausted and the request resolved immediately).","type":"integer"}},"type":"object"},"contracts.PreflightStatus":{"type":"string","x-enum-varnames":["PreflightStatusReady","PreflightStatusUnavailable"]},"contracts.PreflightToolRef":{"properties":{"id":{"description":"ID is a canonical \"\u003cserver\u003e:\u003ctool\u003e\" id. A malformed id is answered with a\nper-ID not_found carrying a format hint, never a request-level error.","type":"string"},"pin_hash":{"description":"PinHash is \"sha256/v{N}:{hex}\" — the schema version is embedded so a\nproxy-side hash-algorithm bump is distinguishable from upstream drift.","type":"string"}},"type":"object"},"contracts.PreflightToolResult":{"properties":{"action":{"type":"string"},"detail":{"type":"string"},"did_you_mean":{"description":"DidYouMean carries up to 3 nearest caller-visible ids on not_found. It\nnever crosses a scope boundary and never names a quarantined server's\ntools.","items":{"type":"string"},"type":"array","uniqueItems":false},"hash":{"description":"Hash is the tool's current pin (\"sha256/v{N}:{hex}\") — operator tier,\nready results only. Never disclosed to an agent token.","type":"string"},"id":{"type":"string"},"reason":{"$ref":"#/components/schemas/contracts.PreflightReason"},"remediation":{"type":"string"},"retryable":{"type":"boolean"},"status":{"$ref":"#/components/schemas/contracts.PreflightStatus"}},"type":"object"},"contracts.PreflightVerdict":{"type":"string","x-enum-varnames":["PreflightVerdictReady","PreflightVerdictDegradedRetryable","PreflightVerdictBlocked","PreflightVerdictUnknownIDs"]},"contracts.QuarantineStats":{"description":"Tool quarantine metrics for this server","properties":{"blocked_count":{"description":"Number of disabled (blocked) tools","type":"integer"},"changed_count":{"description":"Number of tools whose description/schema changed since approval","type":"integer"},"pending_count":{"description":"Number of newly discovered tools awaiting approval","type":"integer"}},"type":"object"},"contracts.RefreshRegistryResponse":{"properties":{"cleared":{"description":"number of cached entries dropped","type":"integer"},"registry_id":{"type":"string"}},"type":"object"},"contracts.Registry":{"properties":{"count":{"description":"number or string","type":"string"},"description":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"},"protocol":{"type":"string"},"provenance":{"description":"Provenance is the trust tag (MCP-866): \"official/trusted\" for built-in\ndefaults, \"custom/unverified\" for user-added registries.","type":"string"},"servers_url":{"type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"trusted":{"description":"Trusted indicates whether this is an official, shipped-by-default\nregistry. Trust is derived from membership in the default set, never\nfrom self-assertion in config.","type":"boolean"},"url":{"type":"string"}},"type":"object"},"contracts.RegistryCacheInfo":{"properties":{"age_seconds":{"type":"number"},"stale":{"type":"boolean"}},"type":"object"},"contracts.RegistryUnavailable":{"properties":{"reason":{"type":"string"}},"type":"object"},"contracts.ReplayToolCallRequest":{"properties":{"arguments":{"description":"Modified arguments for replay","type":"object"}},"type":"object"},"contracts.ReplayToolCallResponse":{"properties":{"error":{"description":"Error if replay failed","type":"string"},"new_call_id":{"description":"ID of the newly created call","type":"string"},"new_tool_call":{"$ref":"#/components/schemas/contracts.ToolCallRecord"},"replayed_from":{"description":"Original call ID","type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.RepositoryInfo":{"description":"Detected package info","properties":{"npm":{"$ref":"#/components/schemas/contracts.NPMPackageInfo"}},"type":"object"},"contracts.RepositoryServer":{"properties":{"connect_url":{"description":"Alternative connection URL","type":"string"},"created_at":{"type":"string"},"description":{"type":"string"},"id":{"type":"string"},"install_cmd":{"description":"Installation command","type":"string"},"name":{"type":"string"},"registry":{"description":"Which registry this came from","type":"string"},"repository_info":{"$ref":"#/components/schemas/contracts.RepositoryInfo"},"source_code_url":{"description":"Source repository URL","type":"string"},"updated_at":{"type":"string"},"url":{"description":"MCP endpoint for remote servers only","type":"string"}},"type":"object"},"contracts.SearchRegistryServersResponse":{"properties":{"cache":{"$ref":"#/components/schemas/contracts.RegistryCacheInfo"},"query":{"type":"string"},"registry_id":{"type":"string"},"servers":{"items":{"$ref":"#/components/schemas/contracts.RepositoryServer"},"type":"array","uniqueItems":false},"tag":{"type":"string"},"total":{"type":"integer"},"unavailable":{"$ref":"#/components/schemas/contracts.RegistryUnavailable"}},"type":"object"},"contracts.SearchResult":{"properties":{"matches":{"type":"integer"},"score":{"type":"number"},"snippet":{"type":"string"},"tool":{"$ref":"#/components/schemas/contracts.Tool"}},"type":"object"},"contracts.SearchToolsResponse":{"properties":{"query":{"type":"string"},"results":{"items":{"$ref":"#/components/schemas/contracts.SearchResult"},"type":"array","uniqueItems":false},"took":{"type":"string"},"total":{"type":"integer"}},"type":"object"},"contracts.SecurityScanSummary":{"description":"Latest security scan results summary","properties":{"deep_scan":{"$ref":"#/components/schemas/contracts.DeepScanDescriptor"},"finding_counts":{"$ref":"#/components/schemas/contracts.FindingCounts"},"last_scan_at":{"type":"string"},"risk_score":{"description":"0-100","type":"integer"},"scanners_failed":{"type":"integer"},"scanners_run":{"description":"Scanner coverage for the primary (baseline) scan pass — informational only.\nSpec 077 US3 (FR-008/FR-014): Status is derived SOLELY from the\ndeterministic baseline findings; a failed Docker deep scanner no longer\ndowngrades a clean verdict. That failure is surfaced via DeepScan instead.","type":"integer"},"scanners_total":{"type":"integer"},"status":{"description":"\"clean\", \"warnings\", \"dangerous\", \"failed\", \"not_scanned\", \"scanning\"","type":"string"}},"type":"object"},"contracts.Server":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"authenticated":{"description":"OAuth authentication status","type":"boolean"},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges mirrors config.ServerConfig.AutoApproveToolChanges\n(MCP-2930): the per-server intent to auto-approve new/changed tools past\nthe trust baseline. Tri-state *bool — nil means \"never set\" (omitted from\nthe payload), so the Web UI toggle (MCP-2932) can distinguish unset from\nan explicit false. Read-only on the GET path; PATCH/POST accept it via\nAddServerRequest.","type":"boolean"},"command":{"type":"string"},"connected":{"type":"boolean"},"connected_at":{"type":"string"},"connecting":{"type":"boolean"},"created":{"type":"string"},"diagnostic":{"$ref":"#/components/schemas/contracts.Diagnostic"},"enabled":{"type":"boolean"},"env":{"additionalProperties":{"type":"string"},"type":"object"},"error_code":{"type":"string"},"expose_prompts":{"description":"ExposePrompts mirrors config.ServerConfig.ExposePrompts (F9): the per-server\nprompt-aggregation override. Tri-state *bool — nil/omitted means \"inherit\ndefault aggregation\". Surfaced on GET so a caller that PATCHed the override\ncan read it back; PATCH/POST accept it via AddServerRequest.","type":"boolean"},"headers":{"additionalProperties":{"type":"string"},"type":"object"},"health":{"$ref":"#/components/schemas/contracts.HealthStatus"},"id":{"type":"string"},"init_timeout":{"description":"InitTimeout mirrors config.ServerConfig.InitTimeout (MCP-3322 / GH #760):\nthe per-server MCP ` + "`" + `initialize` + "`" + ` handshake deadline override. Serialized as\na duration string (e.g. \"120s\"); nil/omitted means \"inherit the global\ndefault\". Surfaced on the GET path so clients can read back a configured\noverride; PATCH/POST accept it via AddServerRequest.","type":"string"},"isolation":{"$ref":"#/components/schemas/contracts.IsolationConfig"},"isolation_defaults":{"$ref":"#/components/schemas/contracts.IsolationDefaults"},"last_error":{"type":"string"},"last_reconnect_at":{"type":"string"},"last_retry_time":{"type":"string"},"max_concurrent_requests":{"description":"Spec 093 (GH #955) — per-server concurrency overrides, scope (c) of\nFR-020. Each setting is tri-state: nil (omitted) means \"inherit\nserver_concurrency_defaults\", 0 disables that setting for this server,\npositive overrides it. Surfaced on the GET path so a caller can read back\nwhat it set; PATCH/POST accept them via AddServerRequest. The effective\nconcurrency for a server is additionally bounded by the global aggregate\nlimiter, which is NOT an inheritance source for these fields.","type":"integer"},"name":{"type":"string"},"oauth":{"$ref":"#/components/schemas/contracts.OAuthConfig"},"oauth_status":{"description":"OAuth status: \"authenticated\", \"expired\", \"error\", \"none\"","type":"string"},"protocol":{"type":"string"},"quarantine":{"$ref":"#/components/schemas/contracts.QuarantineStats"},"quarantined":{"type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_count":{"type":"integer"},"reconnect_on_use":{"description":"Attempt reconnection when a tool call targets this disconnected server","type":"boolean"},"retry_count":{"type":"integer"},"security_scan":{"$ref":"#/components/schemas/contracts.SecurityScanSummary"},"should_retry":{"type":"boolean"},"source_registry_id":{"description":"MCP-901 — registry provenance of an upstream that was added from a\nregistry. SourceRegistryID names the source registry (empty for\nmanually-configured servers); SourceRegistryProvenance is the trust tag\nrecorded at add time (\"official/trusted\" or \"custom/unverified\"). Both\nare projected from config.ServerConfig so the approval/quarantine view\ncan render an \"added from \u003cregistry\u003e · unverified\" origin badge. Optional\nand omitted when empty — clients that pre-date this treat them as absent.","type":"string"},"source_registry_provenance":{"type":"string"},"status":{"type":"string"},"token_expires_at":{"description":"When the OAuth token expires (ISO 8601)","type":"string"},"tool_count":{"type":"integer"},"tool_list_token_size":{"description":"Token size for this server's tools","type":"integer"},"trust_mode":{"description":"TrustMode mirrors config.ServerConfig.TrustMode (spec 086): the per-server\ntrust tier (\"auto\"/\"scan\"/\"manual\"). Surfaced on the GET path so clients can\nread back the persisted mode; PATCH/POST accept it via AddServerRequest.\nOmitted when empty (server predates the field / relies on legacy flags).","type":"string"},"updated":{"type":"string"},"url":{"type":"string"},"user_logged_out":{"description":"True if user explicitly logged out (prevents auto-reconnection)","type":"boolean"},"working_dir":{"type":"string"}},"type":"object"},"contracts.ServerActionResponse":{"properties":{"action":{"type":"string"},"async":{"type":"boolean"},"server":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.ServerStats":{"properties":{"connected_servers":{"type":"integer"},"docker_containers":{"type":"integer"},"quarantined_servers":{"type":"integer"},"token_metrics":{"$ref":"#/components/schemas/contracts.ServerTokenMetrics"},"total_servers":{"type":"integer"},"total_tools":{"type":"integer"}},"type":"object"},"contracts.ServerTokenMetrics":{"properties":{"average_query_result_size":{"description":"Typical retrieve_tools output (tokens)","type":"integer"},"per_server_tool_list_sizes":{"additionalProperties":{"type":"integer"},"description":"Token size per server","type":"object"},"saved_tokens":{"description":"Difference","type":"integer"},"saved_tokens_percentage":{"description":"Percentage saved","type":"number"},"total_server_tool_list_size":{"description":"All upstream tools combined (tokens)","type":"integer"}},"type":"object"},"contracts.SuccessResponse":{"properties":{"data":{"type":"object"},"success":{"type":"boolean"}},"type":"object"},"contracts.TokenMetrics":{"description":"Token usage metrics (nil for older records)","properties":{"encoding":{"description":"Encoding used (e.g., cl100k_base)","type":"string"},"estimated_cost":{"description":"Optional cost estimate","type":"number"},"input_tokens":{"description":"Tokens in the request","type":"integer"},"model":{"description":"Model used for tokenization","type":"string"},"output_tokens":{"description":"Tokens in the response","type":"integer"},"total_tokens":{"description":"Total tokens (input + output)","type":"integer"},"truncated_tokens":{"description":"Tokens removed by truncation","type":"integer"},"was_truncated":{"description":"Whether response was truncated","type":"boolean"}},"type":"object"},"contracts.Tool":{"properties":{"annotations":{"$ref":"#/components/schemas/contracts.ToolAnnotation"},"approval_status":{"type":"string"},"config_denied":{"description":"ConfigDenied is true when the tool is denied by the server's static\nenabled_tools / disabled_tools config. The user cannot override this toggle.","type":"boolean"},"description":{"type":"string"},"disabled":{"description":"Disabled mirrors ToolApprovalRecord.Disabled so per-tool enable state is\navailable without a second round-trip to the approvals endpoint. Absent\nin the JSON when false (default) to keep responses compact.","type":"boolean"},"hash":{"description":"Hash is the tool's current stored hash rendered in the preflight pin\nformat \"sha256/v{N}:{hex}\" (Spec 098 FR-011), where N is the approval\nrecord's HashSchemaVersion. It is the authoring surface for\n` + "`" + `POST /api/v1/preflight` + "`" + ` pins and ` + "`" + `mcpproxy tools preflight --pin` + "`" + `:\ncopy the value straight into a pin.\n\nDisclosure is OPERATOR TIER ONLY — same rule as the preflight per-tool\nresult. The field is omitted for agent-token callers and for tools with\nno stored hash (no approval record yet, or a record written before\nhashes existed).","type":"string"},"held_reason":{"description":"HeldReason, HeldVerdict and HeldSignals mirror the same-named fields on\nstorage.ToolApprovalRecord: the offline-scan evidence that made\ntrust_mode: scan hold this tool for review (spec 086 FR-018). HeldSignals\nnames the matched deterministic check ids, e.g.\n\"tpa.TPA-2026-0001.hidden_instruction\", so a reviewer can see WHY the tool\nis held. All three are omitted for tools that are not held by the scan gate\n(including every record written before the field existed).","type":"string"},"held_signals":{"items":{"type":"string"},"type":"array","uniqueItems":false},"held_verdict":{"type":"string"},"last_used":{"type":"string"},"name":{"type":"string"},"schema":{"type":"object"},"server_name":{"type":"string"},"usage":{"type":"integer"}},"type":"object"},"contracts.ToolAnnotation":{"description":"Tool behavior hints snapshot","properties":{"destructiveHint":{"type":"boolean"},"idempotentHint":{"type":"boolean"},"openWorldHint":{"type":"boolean"},"readOnlyHint":{"type":"boolean"},"title":{"type":"string"}},"type":"object"},"contracts.ToolCallRecord":{"description":"The new tool call record","properties":{"annotations":{"$ref":"#/components/schemas/contracts.ToolAnnotation"},"arguments":{"description":"Tool arguments","type":"object"},"config_path":{"description":"Active config file path","type":"string"},"duration":{"description":"Duration in nanoseconds","type":"integer"},"error":{"description":"Error message (failure only)","type":"string"},"execution_type":{"description":"\"direct\" or \"code_execution\"","type":"string"},"id":{"description":"Unique identifier","type":"string"},"mcp_client_name":{"description":"MCP client name from InitializeRequest","type":"string"},"mcp_client_version":{"description":"MCP client version","type":"string"},"mcp_session_id":{"description":"MCP session identifier","type":"string"},"metrics":{"$ref":"#/components/schemas/contracts.TokenMetrics"},"parent_call_id":{"description":"Links nested calls to parent code_execution","type":"string"},"request_id":{"description":"Request correlation ID","type":"string"},"response":{"description":"Tool response (success only)","type":"object"},"server_id":{"description":"Server identity hash","type":"string"},"server_name":{"description":"Human-readable server name","type":"string"},"timestamp":{"description":"When the call was made","type":"string"},"tool_name":{"description":"Tool name (without server prefix)","type":"string"}},"type":"object"},"contracts.UpdateInfo":{"description":"Update information (if available)","properties":{"available":{"description":"Whether an update is available","type":"boolean"},"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"},"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"}},"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},"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_ms":{"type":"integer"},"p95_ms":{"type":"integer"},"rejected":{"description":"spec 093: shed by a concurrency limit; never executed, so excluded from calls/latency","type":"integer"},"server":{"type":"string"},"sized_calls":{"description":"calls with known response size (basis for avg_resp_bytes)","type":"integer"},"tool":{"type":"string"},"total_req_bytes":{"type":"integer"},"total_resp_bytes":{"type":"integer"}},"type":"object"},"contracts.ValidateConfigResponse":{"properties":{"errors":{"items":{"$ref":"#/components/schemas/contracts.ValidationError"},"type":"array","uniqueItems":false},"valid":{"type":"boolean"}},"type":"object"},"contracts.ValidationError":{"properties":{"field":{"type":"string"},"message":{"type":"string"}},"type":"object"},"data":{"properties":{"data":{"$ref":"#/components/schemas/contracts.InfoResponse"}},"type":"object"},"httpapi.AddServerRequest":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges is the per-server intent to auto-approve\nnew/changed tools past the trust baseline (MCP-2930). Tri-state *bool:\na nil pointer means \"leave unchanged\" on PATCH; a present value\n(including false) is applied. Mirrors config.ServerConfig's *bool\nsemantics — do NOT collapse to a plain bool, or an omitted field would\nsilently reset a previously-set value.","type":"boolean"},"command":{"type":"string"},"enabled":{"type":"boolean"},"env":{"additionalProperties":{"type":"string"},"type":"object"},"expose_prompts":{"description":"ExposePrompts is the per-server override for prompt aggregation (F9):\nwhether this server's advertised MCP prompts are merged into mcpproxy's\nprompts/list. Tri-state *bool mirroring config.ServerConfig.ExposePrompts —\na nil pointer means \"leave unchanged\" on PATCH (and \"inherit the default\naggregate behavior\" on create); a present value (including false) is applied.","type":"boolean"},"headers":{"additionalProperties":{"type":"string"},"type":"object"},"init_timeout":{"description":"InitTimeout is the per-server MCP ` + "`" + `initialize` + "`" + ` handshake deadline override\n(MCP-3322 / GH #760), serialized as a duration string (e.g. \"120s\"). A nil\npointer means \"leave unchanged\" on PATCH; a present value is applied.\nMirrors config.ServerConfig.InitTimeout's *Duration tri-state.","type":"string"},"isolation":{"$ref":"#/components/schemas/httpapi.IsolationRequest"},"max_concurrent_requests":{"description":"MaxConcurrentRequests / QueueSize / QueueTimeout are the per-server\nconcurrency overrides (spec 093 / GH #955, FR-020 scope (c)). Each is\ntri-state: a nil pointer means \"leave unchanged\" on PATCH and \"inherit\nserver_concurrency_defaults\" on create; an explicit 0 disables that\nsetting for this server; a positive value overrides it. Do NOT collapse\nthem to plain values — an omitted field would then silently reset a\nconfigured limit.","type":"integer"},"name":{"type":"string"},"protocol":{"type":"string"},"quarantined":{"type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_on_use":{"type":"boolean"},"trust_mode":{"description":"TrustMode is the per-server trust tier (spec 086): \"auto\", \"scan\", or\n\"manual\". Empty means \"leave unchanged\" on PATCH (and inherit the migrated\ndefault on create). A non-empty value is applied to ServerConfig.TrustMode\nand resolved by EffectiveTrustMode (an unrecognized value fails closed to\nmanual). This is the REST seam for changing the trust tier via\nPOST/PATCH /api/v1/servers.","type":"string"},"url":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"httpapi.CanonicalConfigPath":{"properties":{"description":{"description":"Brief description","type":"string"},"exists":{"description":"Whether the file exists","type":"boolean"},"format":{"description":"Format identifier (e.g., \"claude_desktop\")","type":"string"},"name":{"description":"Display name (e.g., \"Claude Desktop\")","type":"string"},"os":{"description":"Operating system (darwin, windows, linux)","type":"string"},"path":{"description":"Full path to the config file","type":"string"}},"type":"object"},"httpapi.CanonicalConfigPathsResponse":{"properties":{"os":{"description":"Current operating system","type":"string"},"paths":{"description":"List of canonical config paths","items":{"$ref":"#/components/schemas/httpapi.CanonicalConfigPath"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ConnectConflictResponse":{"properties":{"action":{"description":"already_exists | precondition_failed","type":"string"},"data":{"$ref":"#/components/schemas/connect.ConnectResult"},"error":{"description":"Human-readable message","type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.ConnectRequest":{"properties":{"force":{"description":"Overwrite existing entry","type":"boolean"},"precondition_token":{"description":"PreconditionToken is the opaque token from the preview this write was\nconfirmed against (Spec 091 FR-005). When present, the core rechecks it\nat write time and responds 409 with action \"precondition_failed\" —\nwriting nothing — if the config or the entry MCPProxy would write has\ndrifted since; the caller then re-previews instead of retrying. Absent\nmeans exactly the pre-091 behavior. A replace-classified flow sends this\nTOGETHER with force=true: the token, not the absence of force, is the\noverwrite safety.","type":"string"},"server_name":{"description":"Defaults to \"mcpproxy\"","type":"string"}},"type":"object"},"httpapi.ImportFromPathRequest":{"properties":{"format":{"description":"Optional format hint","type":"string"},"path":{"description":"File path to import from","type":"string"},"rename":{"additionalProperties":{"type":"string"},"description":"Rename maps a server name → new name. Applied after parsing so the\ncaller can disambiguate cross-source name collisions (Spec 046 v2 —\ne.g. \"mcpproxy\" → \"mcpproxy_claude_code\"). Keys are matched against\neither the raw source name (OriginalName) or the sanitized name shown\nin the preview (Server.Name); these differ for names that need\nsanitizing (e.g. \"Figma Desktop\" → \"Figma_Desktop\"). Keys not present\nin the imported set are ignored.","type":"object"},"server_names":{"description":"Optional: import only these servers","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportRequest":{"properties":{"content":{"description":"Raw JSON or TOML content","type":"string"},"format":{"description":"Optional format hint","type":"string"},"server_names":{"description":"Optional: import only these servers","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportResponse":{"properties":{"failed":{"items":{"$ref":"#/components/schemas/configimport.FailedServer"},"type":"array","uniqueItems":false},"format":{"type":"string"},"format_name":{"type":"string"},"imported":{"items":{"$ref":"#/components/schemas/httpapi.ImportedServerResponse"},"type":"array","uniqueItems":false},"skipped":{"items":{"$ref":"#/components/schemas/configimport.SkippedServer"},"type":"array","uniqueItems":false},"summary":{"$ref":"#/components/schemas/configimport.ImportSummary"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportedServerResponse":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"command":{"type":"string"},"fields_skipped":{"items":{"type":"string"},"type":"array","uniqueItems":false},"name":{"type":"string"},"original_name":{"type":"string"},"protocol":{"type":"string"},"source_format":{"type":"string"},"url":{"type":"string"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.IsolationRequest":{"description":"Isolation carries per-server Docker isolation overrides (image,\nnetwork_mode, extra_args, working_dir, enabled). A nil pointer\nmeans \"do not touch isolation config\"; an empty-but-present\nobject on PATCH intentionally clears the overrides.","properties":{"enabled":{"type":"boolean"},"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"network_mode":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"httpapi.OnboardingMarkRequest":{"properties":{"connect_step_status":{"description":"ConnectStepStatus is one of: \"\", \"completed\", \"skipped\". Empty\npreserves the existing value. The stored enum is wider (Spec 080\nFR-001): a \"skipped\" request for a previously untouched connect step\nis upgraded server-side to \"completed_external\" when the install\nshows positive evidence of an external connection (Spec 080 FR-002).\n\"completed_external\" is NOT accepted from clients — it must never be\npersisted without that server-verified evidence (edge case: \"never\nguess completed_external without positive evidence\").","type":"string"},"engaged":{"description":"Engaged marks the wizard as engaged (completed or explicitly skipped).\nOnce true, the wizard does not auto-show again.","type":"boolean"},"mark_shown":{"description":"MarkShown records the wizard's first display time if not already set.","type":"boolean"},"server_step_status":{"description":"ServerStepStatus is one of: \"\", \"completed\", \"skipped\". Empty\npreserves the existing value.","type":"string"}},"type":"object"},"httpapi.SetActiveProfileRequest":{"properties":{"active_profile":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.UndoConnectRequest":{"properties":{"backup_name":{"description":"BackupName is the bare filename (filepath.Base) of the backup returned as\nbackup_path by the preceding connect — a name, never a path. Undo resolves\nthe full path server-side by joining it with the client's own config\ndirectory, so a client-supplied value can never contribute a directory\ncomponent (traversal is impossible by construction). Empty means the\nconnect created the file (no prior file existed), so undo removes it.","type":"string"},"server_name":{"description":"Defaults to \"mcpproxy\"","type":"string"}},"type":"object"},"httpapi.UpdateFailureRequest":{"properties":{"stage":{"description":"Stage is the failure stage of the update session.","enum":["appcast","download","install","other"],"type":"string"}},"type":"object"},"management.BulkOperationResult":{"properties":{"errors":{"additionalProperties":{"type":"string"},"description":"Map of server name to error message","type":"object"},"failed":{"description":"Number of failed operations","type":"integer"},"successful":{"description":"Number of successful operations","type":"integer"},"total":{"description":"Total servers processed","type":"integer"}},"type":"object"},"observability.HealthResponse":{"properties":{"components":{"items":{"$ref":"#/components/schemas/observability.HealthStatus"},"type":"array","uniqueItems":false},"status":{"description":"\"healthy\" or \"unhealthy\"","type":"string"},"timestamp":{"type":"string"}},"type":"object"},"observability.HealthStatus":{"properties":{"error":{"type":"string"},"latency":{"type":"string"},"name":{"type":"string"},"status":{"description":"\"healthy\" or \"unhealthy\"","type":"string"}},"type":"object"},"observability.ReadinessResponse":{"properties":{"components":{"items":{"$ref":"#/components/schemas/observability.HealthStatus"},"type":"array","uniqueItems":false},"status":{"description":"\"ready\" or \"not_ready\"","type":"string"},"timestamp":{"type":"string"}},"type":"object"},"secureenv.EnvConfig":{"description":"Environment configuration for secure variable filtering","properties":{"allowed_system_vars":{"items":{"type":"string"},"type":"array","uniqueItems":false},"custom_vars":{"additionalProperties":{"type":"string"},"type":"object"},"enhance_path":{"description":"Enable PATH enhancement for Launchd scenarios","type":"boolean"},"forward_proxy_env":{"description":"ForwardProxyEnv opts in to forwarding the ambient HTTP(S)/ALL/NO/FTP proxy\nenvironment variables to spawned upstream servers (MCP-2769). It is OFF by\ndefault and deliberately kept out of the AllowedSystemVars default list:\nproxy URLs frequently carry credentials (http://user:pass@proxy), so\nforwarding them to every stdio upstream is a credential-leak risk. When\nenabled, values are forwarded with their userinfo (credentials) redacted.","type":"boolean"},"inherit_system_safe":{"type":"boolean"}},"type":"object"},"telemetry.FeedbackContext":{"properties":{"arch":{"type":"string"},"connected_server_count":{"type":"integer"},"edition":{"type":"string"},"os":{"type":"string"},"routing_mode":{"type":"string"},"server_count":{"type":"integer"},"version":{"type":"string"}},"type":"object"},"telemetry.FeedbackRequest":{"properties":{"category":{"description":"bug, feature, other","type":"string"},"context":{"$ref":"#/components/schemas/telemetry.FeedbackContext"},"email":{"type":"string"},"message":{"type":"string"}},"type":"object"},"telemetry.FeedbackResponse":{"properties":{"error":{"type":"string"},"issue_url":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}},"securitySchemes":{"ApiKeyAuth":{"description":"API key authentication via query parameter. Use ?apikey=your-key","in":"query","name":"apikey","type":"apiKey"}}}, + "components": {"schemas":{"config.ConcurrencyDefaults":{"description":"ServerConcurrencyDefaults is scope (b) of FR-020: the blanket per-server\ndefault set inherited by every server that does not override a setting.\nAbsent (the default) = no per-server limiting unless a server configures\nit explicitly. File/API-configured only — no env scheme (FR-022).","properties":{"max_concurrent_requests":{"type":"integer"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"}},"type":"object"},"config.Config":{"properties":{"activity_cleanup_interval_min":{"description":"Background cleanup interval in minutes (default: 60)","type":"integer"},"activity_max_records":{"description":"Max records before pruning (default: 100000)","type":"integer"},"activity_max_response_size":{"description":"Response truncation limit in bytes (default: 65536)","type":"integer"},"activity_max_size_mb":{"description":"Max total activity-log size in MB before pruning oldest (default: 256, 0=disabled)","type":"integer"},"activity_retention_days":{"description":"Activity logging settings (RFC-003)","type":"integer"},"aggregate_upstream_prompts":{"description":"AggregateUpstreamPrompts, when true, aggregates every connected upstream\nserver's advertised MCP prompts into mcpproxy's own prompts/list\n(exposed as \"\u003cserver\u003e__\u003cprompt\u003e\"). OFF by default: users are safe by\ndefault and opt in deliberately. EnablePrompts still governs the built-in\nprompts + the prompts capability; this flag gates ONLY the upstream\naggregation performed by RefreshPrompts. Hot-reloadable.","type":"boolean"},"allow_private_registry_fetch":{"description":"AllowPrivateRegistryFetch opts out of the registry SSRF guard (MCP-1076,\nCWE-918). By default (false) registry fetches refuse any host that is — or\nresolves to — a non-routable address (loopback, RFC1918/CGNAT private,\nlink-local incl. the 169.254.169.254 cloud-metadata endpoint), so a\nmalicious or typo'd registry source cannot turn the daemon into a\nrequest-forgery vector against internal services.\n\nThis opt-out is BLANKET (all-or-nothing): setting it true disables the\nguard for EVERY non-routable range at once — loopback, RFC1918/CGNAT\nprivate, link-local AND the 169.254.169.254 cloud-metadata endpoint. There\nis no way to allow only loopback; enabling it for a localhost dev registry\nalso re-opens the cloud-metadata SSRF vector. Set true ONLY when you\nintentionally run a trusted registry mirror on an internal/private address,\nideally on a host with no cloud-metadata exposure. The change takes effect\nonly on daemon (re)start or config reload.","type":"boolean"},"allow_server_add":{"type":"boolean"},"allow_server_remove":{"type":"boolean"},"api_key":{"description":"Security settings","type":"string"},"call_tool_timeout":{"type":"string"},"check_server_repo":{"description":"Repository detection settings","type":"boolean"},"code_execution_max_parallel":{"description":"Default concurrency for call_tools() batches (1-32, default: 8)","type":"integer"},"code_execution_max_tool_calls":{"description":"Max tool calls per execution (0 = unlimited, default: 0)","type":"integer"},"code_execution_pool_size":{"description":"JavaScript runtime pool size (default: 10)","type":"integer"},"code_execution_timeout_ms":{"description":"Timeout in milliseconds (default: 120000, max: 600000)","type":"integer"},"data_dir":{"type":"string"},"debug_search":{"type":"boolean"},"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":{"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_id":{"description":"HTTP request ID for correlation","type":"string"},"response":{"description":"Tool response (potentially truncated)","type":"string"},"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"},"end_time":{"description":"End of the period (RFC3339)","type":"string"},"error_count":{"description":"Count of error activities","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\", or \"\" (none)","type":"string"},"admin_state":{"description":"AdminState indicates the admin state: \"enabled\", \"disabled\", or \"quarantined\"","type":"string"},"detail":{"description":"Detail is an optional longer explanation of the status","type":"string"},"level":{"description":"Level indicates the health level: \"healthy\", \"degraded\", or \"unhealthy\"","type":"string"},"summary":{"description":"Summary is a human-readable status message (e.g., \"Connected (5 tools)\")","type":"string"}},"type":"object"},"contracts.InfoEndpoints":{"description":"Available API endpoints","properties":{"http":{"description":"HTTP endpoint address (e.g., \"127.0.0.1:8080\")","type":"string"},"socket":{"description":"Unix socket path (empty if disabled)","type":"string"}},"type":"object"},"contracts.InfoResponse":{"properties":{"endpoints":{"$ref":"#/components/schemas/contracts.InfoEndpoints"},"launched_by":{"description":"LaunchedBy is the durable launch provenance of the running core (Spec\n092 FR-001a): \"tray\" when a tray spawned it, \"installer\" when the macOS\nPKG postinstall did, \"\" when user-launched or unknown. Always present\n(possibly empty) so a tray can distinguish \"old core, not mine\" from\n\"old core I may supersede\".","type":"string"},"listen_addr":{"description":"Listen address (e.g., \"127.0.0.1:8080\")","type":"string"},"pid":{"description":"PID is the operating-system process id of the running core (Spec 092\nFR-002). A tray that merely ATTACHED to a core holds no Process handle\nfor it, so without this there is no mechanism at all to stop a stale\ncore — the consent action would have nothing to act on and could only\nprint instructions. Paired with LaunchedBy it is what lets a newer tray\nsupersede a core an older tray started.","type":"integer"},"update":{"$ref":"#/components/schemas/contracts.UpdateInfo"},"update_policy":{"$ref":"#/components/schemas/contracts.UpdatePolicy"},"version":{"description":"Current MCPProxy version","type":"string"},"web_ui_url":{"description":"URL to access the web control panel","type":"string"}},"type":"object"},"contracts.IsolationConfig":{"properties":{"cpu_limit":{"type":"string"},"enabled":{"type":"boolean"},"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"memory_limit":{"type":"string"},"network_mode":{"type":"string"},"timeout":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"contracts.IsolationDefaults":{"description":"IsolationDefaults exposes the resolved baseline values that\nwould apply when no per-server override is set. Populated on\nlist/get responses; never consumed on PATCH requests.","properties":{"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"network_mode":{"type":"string"},"runtime_type":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"contracts.LogEntry":{"properties":{"fields":{"type":"object"},"level":{"type":"string"},"message":{"type":"string"},"server":{"type":"string"},"timestamp":{"type":"string"}},"type":"object"},"contracts.MCPSession":{"properties":{"client_name":{"type":"string"},"client_version":{"type":"string"},"end_time":{"type":"string"},"experimental":{"items":{"type":"string"},"type":"array","uniqueItems":false},"has_roots":{"description":"MCP Client Capabilities","type":"boolean"},"has_sampling":{"type":"boolean"},"id":{"type":"string"},"last_activity":{"type":"string"},"start_time":{"type":"string"},"status":{"type":"string"},"tool_call_count":{"type":"integer"},"total_tokens":{"type":"integer"},"work_session_id":{"type":"string"},"workspace_name":{"description":"Workspace / work session (Spec 082). WorkspaceName is the project's\nbasename — the full local path is never exposed. WorkSessionID groups the\nreconnects that make up one stretch of user work.","type":"string"}},"type":"object"},"contracts.MetadataStatus":{"properties":{"authorization_servers":{"items":{"type":"string"},"type":"array","uniqueItems":false},"error":{"type":"string"},"found":{"type":"boolean"},"url_checked":{"type":"string"}},"type":"object"},"contracts.MissingSecretInfo":{"properties":{"secret_name":{"type":"string"},"used_by":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"contracts.NPMPackageInfo":{"properties":{"exists":{"type":"boolean"},"install_cmd":{"type":"string"}},"type":"object"},"contracts.OAuthConfig":{"properties":{"auth_url":{"type":"string"},"client_id":{"type":"string"},"extra_params":{"additionalProperties":{"type":"string"},"type":"object"},"pkce_enabled":{"type":"boolean"},"redirect_port":{"type":"integer"},"scopes":{"items":{"type":"string"},"type":"array","uniqueItems":false},"token_expires_at":{"description":"When the OAuth token expires","type":"string"},"token_url":{"type":"string"},"token_valid":{"description":"Whether token is currently valid","type":"boolean"}},"type":"object"},"contracts.OAuthErrorDetails":{"description":"Structured discovery/failure details","properties":{"authorization_server_metadata":{"$ref":"#/components/schemas/contracts.MetadataStatus"},"dcr_status":{"$ref":"#/components/schemas/contracts.DCRStatus"},"protected_resource_metadata":{"$ref":"#/components/schemas/contracts.MetadataStatus"},"server_url":{"type":"string"}},"type":"object"},"contracts.OAuthFlowError":{"properties":{"correlation_id":{"description":"Flow tracking ID for log correlation","type":"string"},"debug_hint":{"description":"CLI command for log lookup","type":"string"},"details":{"$ref":"#/components/schemas/contracts.OAuthErrorDetails"},"error_code":{"description":"Machine-readable error code (e.g., OAUTH_NO_METADATA)","type":"string"},"error_type":{"description":"Category of OAuth runtime failure","type":"string"},"message":{"description":"Human-readable error description","type":"string"},"request_id":{"description":"HTTP request ID (from PR #237)","type":"string"},"server_name":{"description":"Server that failed OAuth","type":"string"},"success":{"description":"Always false","type":"boolean"},"suggestion":{"description":"Actionable remediation hint","type":"string"}},"type":"object"},"contracts.OAuthIssue":{"properties":{"documentation_url":{"type":"string"},"error":{"type":"string"},"issue":{"type":"string"},"missing_params":{"items":{"type":"string"},"type":"array","uniqueItems":false},"resolution":{"type":"string"},"server_name":{"type":"string"}},"type":"object"},"contracts.OAuthRequirement":{"properties":{"expires_at":{"type":"string"},"message":{"type":"string"},"server_name":{"type":"string"},"state":{"type":"string"}},"type":"object"},"contracts.OAuthStartResponse":{"properties":{"auth_url":{"description":"Authorization URL (always included for manual use)","type":"string"},"browser_error":{"description":"Error message if browser launch failed","type":"string"},"browser_opened":{"description":"Whether browser launch succeeded","type":"boolean"},"correlation_id":{"description":"UUID for tracking this flow","type":"string"},"message":{"description":"Human-readable status message","type":"string"},"server_name":{"description":"Name of the server being authenticated","type":"string"},"success":{"description":"Always true for successful start","type":"boolean"}},"type":"object"},"contracts.PreflightPolicy":{"properties":{"exclude_destructive":{"type":"boolean"},"exclude_open_world":{"type":"boolean"},"read_only_only":{"type":"boolean"}},"type":"object"},"contracts.PreflightReason":{"type":"string","x-enum-varnames":["PreflightReasonServerInitializing","PreflightReasonServerUnhealthy","PreflightReasonServerDisabled","PreflightReasonServerQuarantined","PreflightReasonToolPendingApproval","PreflightReasonToolChanged","PreflightReasonToolBlockedByUser","PreflightReasonOAuthRequired","PreflightReasonHashMismatch","PreflightReasonServerNotInScope","PreflightReasonToolDeniedByConfig","PreflightReasonMissingAnnotation","PreflightReasonPolicyFiltered","PreflightReasonNotFound","PreflightReasonServerNotConfigured"]},"contracts.PreflightRequest":{"properties":{"policy":{"$ref":"#/components/schemas/contracts.PreflightPolicy"},"profile":{"description":"Profile evaluates under a named profile's server scope. Unknown: 400.","type":"string"},"tools":{"description":"Tools is 1..100 entries BEFORE dedup; duplicates are collapsed, and\nduplicate ids carrying different pins are a validation error.","items":{"$ref":"#/components/schemas/contracts.PreflightToolRef"},"type":"array","uniqueItems":false},"wait_ms":{"description":"WaitMS polls local state for up to this many milliseconds (cap 10000)\nwhile every failure is retryable-class.","type":"integer"}},"type":"object"},"contracts.PreflightResponse":{"properties":{"checked_at":{"type":"string"},"tools":{"description":"Tools are ordered by first occurrence of each unique id in the request.","items":{"$ref":"#/components/schemas/contracts.PreflightToolResult"},"type":"array","uniqueItems":false},"verdict":{"$ref":"#/components/schemas/contracts.PreflightVerdict"},"waited_ms":{"description":"WaitedMS is present when wait_ms was requested (0 when the wait\nsemaphore was exhausted and the request resolved immediately).","type":"integer"}},"type":"object"},"contracts.PreflightStatus":{"type":"string","x-enum-varnames":["PreflightStatusReady","PreflightStatusUnavailable"]},"contracts.PreflightToolRef":{"properties":{"id":{"description":"ID is a canonical \"\u003cserver\u003e:\u003ctool\u003e\" id. A malformed id is answered with a\nper-ID not_found carrying a format hint, never a request-level error.","type":"string"},"pin_hash":{"description":"PinHash is \"sha256/v{N}:{hex}\" — the schema version is embedded so a\nproxy-side hash-algorithm bump is distinguishable from upstream drift.","type":"string"}},"type":"object"},"contracts.PreflightToolResult":{"properties":{"action":{"type":"string"},"detail":{"type":"string"},"did_you_mean":{"description":"DidYouMean carries up to 3 nearest caller-visible ids on not_found. It\nnever crosses a scope boundary and never names a quarantined server's\ntools.","items":{"type":"string"},"type":"array","uniqueItems":false},"hash":{"description":"Hash is the tool's current pin (\"sha256/v{N}:{hex}\") — operator tier,\nready results only. Never disclosed to an agent token.","type":"string"},"id":{"type":"string"},"reason":{"$ref":"#/components/schemas/contracts.PreflightReason"},"remediation":{"type":"string"},"retryable":{"type":"boolean"},"status":{"$ref":"#/components/schemas/contracts.PreflightStatus"}},"type":"object"},"contracts.PreflightVerdict":{"type":"string","x-enum-varnames":["PreflightVerdictReady","PreflightVerdictDegradedRetryable","PreflightVerdictBlocked","PreflightVerdictUnknownIDs"]},"contracts.QuarantineStats":{"description":"Tool quarantine metrics for this server","properties":{"blocked_count":{"description":"Number of disabled (blocked) tools","type":"integer"},"changed_count":{"description":"Number of tools whose description/schema changed since approval","type":"integer"},"pending_count":{"description":"Number of newly discovered tools awaiting approval","type":"integer"}},"type":"object"},"contracts.RefreshRegistryResponse":{"properties":{"cleared":{"description":"number of cached entries dropped","type":"integer"},"registry_id":{"type":"string"}},"type":"object"},"contracts.Registry":{"properties":{"count":{"description":"number or string","type":"string"},"description":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"},"protocol":{"type":"string"},"provenance":{"description":"Provenance is the trust tag (MCP-866): \"official/trusted\" for built-in\ndefaults, \"custom/unverified\" for user-added registries.","type":"string"},"servers_url":{"type":"string"},"tags":{"items":{"type":"string"},"type":"array","uniqueItems":false},"trusted":{"description":"Trusted indicates whether this is an official, shipped-by-default\nregistry. Trust is derived from membership in the default set, never\nfrom self-assertion in config.","type":"boolean"},"url":{"type":"string"}},"type":"object"},"contracts.RegistryCacheInfo":{"properties":{"age_seconds":{"type":"number"},"stale":{"type":"boolean"}},"type":"object"},"contracts.RegistryUnavailable":{"properties":{"reason":{"type":"string"}},"type":"object"},"contracts.ReplayToolCallRequest":{"properties":{"arguments":{"description":"Modified arguments for replay","type":"object"}},"type":"object"},"contracts.ReplayToolCallResponse":{"properties":{"error":{"description":"Error if replay failed","type":"string"},"new_call_id":{"description":"ID of the newly created call","type":"string"},"new_tool_call":{"$ref":"#/components/schemas/contracts.ToolCallRecord"},"replayed_from":{"description":"Original call ID","type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.RepositoryInfo":{"description":"Detected package info","properties":{"npm":{"$ref":"#/components/schemas/contracts.NPMPackageInfo"}},"type":"object"},"contracts.RepositoryServer":{"properties":{"connect_url":{"description":"Alternative connection URL","type":"string"},"created_at":{"type":"string"},"description":{"type":"string"},"id":{"type":"string"},"install_cmd":{"description":"Installation command","type":"string"},"name":{"type":"string"},"registry":{"description":"Which registry this came from","type":"string"},"repository_info":{"$ref":"#/components/schemas/contracts.RepositoryInfo"},"source_code_url":{"description":"Source repository URL","type":"string"},"updated_at":{"type":"string"},"url":{"description":"MCP endpoint for remote servers only","type":"string"}},"type":"object"},"contracts.SearchRegistryServersResponse":{"properties":{"cache":{"$ref":"#/components/schemas/contracts.RegistryCacheInfo"},"query":{"type":"string"},"registry_id":{"type":"string"},"servers":{"items":{"$ref":"#/components/schemas/contracts.RepositoryServer"},"type":"array","uniqueItems":false},"tag":{"type":"string"},"total":{"type":"integer"},"unavailable":{"$ref":"#/components/schemas/contracts.RegistryUnavailable"}},"type":"object"},"contracts.SearchResult":{"properties":{"matches":{"type":"integer"},"score":{"type":"number"},"snippet":{"type":"string"},"tool":{"$ref":"#/components/schemas/contracts.Tool"}},"type":"object"},"contracts.SearchToolsResponse":{"properties":{"query":{"type":"string"},"results":{"items":{"$ref":"#/components/schemas/contracts.SearchResult"},"type":"array","uniqueItems":false},"took":{"type":"string"},"total":{"type":"integer"}},"type":"object"},"contracts.SecurityScanSummary":{"description":"Latest security scan results summary","properties":{"deep_scan":{"$ref":"#/components/schemas/contracts.DeepScanDescriptor"},"finding_counts":{"$ref":"#/components/schemas/contracts.FindingCounts"},"last_scan_at":{"type":"string"},"risk_score":{"description":"0-100","type":"integer"},"scanners_failed":{"type":"integer"},"scanners_run":{"description":"Scanner coverage for the primary (baseline) scan pass — informational only.\nSpec 077 US3 (FR-008/FR-014): Status is derived SOLELY from the\ndeterministic baseline findings; a failed Docker deep scanner no longer\ndowngrades a clean verdict. That failure is surfaced via DeepScan instead.","type":"integer"},"scanners_total":{"type":"integer"},"status":{"description":"\"clean\", \"warnings\", \"dangerous\", \"failed\", \"not_scanned\", \"scanning\"","type":"string"}},"type":"object"},"contracts.Server":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"authenticated":{"description":"OAuth authentication status","type":"boolean"},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges mirrors config.ServerConfig.AutoApproveToolChanges\n(MCP-2930): the per-server intent to auto-approve new/changed tools past\nthe trust baseline. Tri-state *bool — nil means \"never set\" (omitted from\nthe payload), so the Web UI toggle (MCP-2932) can distinguish unset from\nan explicit false. Read-only on the GET path; PATCH/POST accept it via\nAddServerRequest.","type":"boolean"},"command":{"type":"string"},"connected":{"type":"boolean"},"connected_at":{"type":"string"},"connecting":{"type":"boolean"},"created":{"type":"string"},"diagnostic":{"$ref":"#/components/schemas/contracts.Diagnostic"},"enabled":{"type":"boolean"},"env":{"additionalProperties":{"type":"string"},"type":"object"},"error_code":{"type":"string"},"expose_prompts":{"description":"ExposePrompts mirrors config.ServerConfig.ExposePrompts (F9): the per-server\nprompt-aggregation override. Tri-state *bool — nil/omitted means \"inherit\ndefault aggregation\". Surfaced on GET so a caller that PATCHed the override\ncan read it back; PATCH/POST accept it via AddServerRequest.","type":"boolean"},"headers":{"additionalProperties":{"type":"string"},"type":"object"},"health":{"$ref":"#/components/schemas/contracts.HealthStatus"},"id":{"type":"string"},"init_timeout":{"description":"InitTimeout mirrors config.ServerConfig.InitTimeout (MCP-3322 / GH #760):\nthe per-server MCP ` + "`" + `initialize` + "`" + ` handshake deadline override. Serialized as\na duration string (e.g. \"120s\"); nil/omitted means \"inherit the global\ndefault\". Surfaced on the GET path so clients can read back a configured\noverride; PATCH/POST accept it via AddServerRequest.","type":"string"},"isolation":{"$ref":"#/components/schemas/contracts.IsolationConfig"},"isolation_defaults":{"$ref":"#/components/schemas/contracts.IsolationDefaults"},"last_error":{"type":"string"},"last_reconnect_at":{"type":"string"},"last_retry_time":{"type":"string"},"max_concurrent_requests":{"description":"Spec 093 (GH #955) — per-server concurrency overrides, scope (c) of\nFR-020. Each setting is tri-state: nil (omitted) means \"inherit\nserver_concurrency_defaults\", 0 disables that setting for this server,\npositive overrides it. Surfaced on the GET path so a caller can read back\nwhat it set; PATCH/POST accept them via AddServerRequest. The effective\nconcurrency for a server is additionally bounded by the global aggregate\nlimiter, which is NOT an inheritance source for these fields.","type":"integer"},"name":{"type":"string"},"oauth":{"$ref":"#/components/schemas/contracts.OAuthConfig"},"oauth_status":{"description":"OAuth status: \"authenticated\", \"expired\", \"error\", \"none\"","type":"string"},"protocol":{"type":"string"},"quarantine":{"$ref":"#/components/schemas/contracts.QuarantineStats"},"quarantined":{"type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_count":{"type":"integer"},"reconnect_on_use":{"description":"Attempt reconnection when a tool call targets this disconnected server","type":"boolean"},"retry_count":{"type":"integer"},"security_scan":{"$ref":"#/components/schemas/contracts.SecurityScanSummary"},"should_retry":{"type":"boolean"},"source_registry_id":{"description":"MCP-901 — registry provenance of an upstream that was added from a\nregistry. SourceRegistryID names the source registry (empty for\nmanually-configured servers); SourceRegistryProvenance is the trust tag\nrecorded at add time (\"official/trusted\" or \"custom/unverified\"). Both\nare projected from config.ServerConfig so the approval/quarantine view\ncan render an \"added from \u003cregistry\u003e · unverified\" origin badge. Optional\nand omitted when empty — clients that pre-date this treat them as absent.","type":"string"},"source_registry_provenance":{"type":"string"},"status":{"type":"string"},"token_expires_at":{"description":"When the OAuth token expires (ISO 8601)","type":"string"},"tool_count":{"type":"integer"},"tool_list_token_size":{"description":"Token size for this server's tools","type":"integer"},"trust_mode":{"description":"TrustMode mirrors config.ServerConfig.TrustMode (spec 086): the per-server\ntrust tier (\"auto\"/\"scan\"/\"manual\"). Surfaced on the GET path so clients can\nread back the persisted mode; PATCH/POST accept it via AddServerRequest.\nOmitted when empty (server predates the field / relies on legacy flags).","type":"string"},"updated":{"type":"string"},"url":{"type":"string"},"user_logged_out":{"description":"True if user explicitly logged out (prevents auto-reconnection)","type":"boolean"},"working_dir":{"type":"string"}},"type":"object"},"contracts.ServerActionResponse":{"properties":{"action":{"type":"string"},"async":{"type":"boolean"},"server":{"type":"string"},"success":{"type":"boolean"}},"type":"object"},"contracts.ServerStats":{"properties":{"connected_servers":{"type":"integer"},"docker_containers":{"type":"integer"},"quarantined_servers":{"type":"integer"},"token_metrics":{"$ref":"#/components/schemas/contracts.ServerTokenMetrics"},"total_servers":{"type":"integer"},"total_tools":{"type":"integer"}},"type":"object"},"contracts.ServerTokenMetrics":{"properties":{"average_query_result_size":{"description":"Typical retrieve_tools output (tokens)","type":"integer"},"per_server_tool_list_sizes":{"additionalProperties":{"type":"integer"},"description":"Token size per server","type":"object"},"saved_tokens":{"description":"Difference","type":"integer"},"saved_tokens_percentage":{"description":"Percentage saved","type":"number"},"total_server_tool_list_size":{"description":"All upstream tools combined (tokens)","type":"integer"}},"type":"object"},"contracts.SuccessResponse":{"properties":{"data":{"type":"object"},"success":{"type":"boolean"}},"type":"object"},"contracts.TokenMetrics":{"description":"Token usage metrics (nil for older records)","properties":{"encoding":{"description":"Encoding used (e.g., cl100k_base)","type":"string"},"estimated_cost":{"description":"Optional cost estimate","type":"number"},"input_tokens":{"description":"Tokens in the request","type":"integer"},"model":{"description":"Model used for tokenization","type":"string"},"output_tokens":{"description":"Tokens in the response","type":"integer"},"total_tokens":{"description":"Total tokens (input + output)","type":"integer"},"truncated_tokens":{"description":"Tokens removed by truncation","type":"integer"},"was_truncated":{"description":"Whether response was truncated","type":"boolean"}},"type":"object"},"contracts.Tool":{"properties":{"annotations":{"$ref":"#/components/schemas/contracts.ToolAnnotation"},"approval_status":{"type":"string"},"config_denied":{"description":"ConfigDenied is true when the tool is denied by the server's static\nenabled_tools / disabled_tools config. The user cannot override this toggle.","type":"boolean"},"description":{"type":"string"},"disabled":{"description":"Disabled mirrors ToolApprovalRecord.Disabled so per-tool enable state is\navailable without a second round-trip to the approvals endpoint. Absent\nin the JSON when false (default) to keep responses compact.","type":"boolean"},"hash":{"description":"Hash is the tool's current stored hash rendered in the preflight pin\nformat \"sha256/v{N}:{hex}\" (Spec 098 FR-011), where N is the approval\nrecord's HashSchemaVersion. It is the authoring surface for\n` + "`" + `POST /api/v1/preflight` + "`" + ` pins and ` + "`" + `mcpproxy tools preflight --pin` + "`" + `:\ncopy the value straight into a pin.\n\nDisclosure is OPERATOR TIER ONLY — same rule as the preflight per-tool\nresult. The field is omitted for agent-token callers and for tools with\nno stored hash (no approval record yet, or a record written before\nhashes existed).","type":"string"},"held_reason":{"description":"HeldReason, HeldVerdict and HeldSignals mirror the same-named fields on\nstorage.ToolApprovalRecord: the offline-scan evidence that made\ntrust_mode: scan hold this tool for review (spec 086 FR-018). HeldSignals\nnames the matched deterministic check ids, e.g.\n\"tpa.TPA-2026-0001.hidden_instruction\", so a reviewer can see WHY the tool\nis held. All three are omitted for tools that are not held by the scan gate\n(including every record written before the field existed).","type":"string"},"held_signals":{"items":{"type":"string"},"type":"array","uniqueItems":false},"held_verdict":{"type":"string"},"last_used":{"type":"string"},"name":{"type":"string"},"schema":{"type":"object"},"server_name":{"type":"string"},"usage":{"type":"integer"}},"type":"object"},"contracts.ToolAnnotation":{"description":"Tool behavior hints snapshot","properties":{"destructiveHint":{"type":"boolean"},"idempotentHint":{"type":"boolean"},"openWorldHint":{"type":"boolean"},"readOnlyHint":{"type":"boolean"},"title":{"type":"string"}},"type":"object"},"contracts.ToolCallRecord":{"description":"The new tool call record","properties":{"annotations":{"$ref":"#/components/schemas/contracts.ToolAnnotation"},"arguments":{"description":"Tool arguments","type":"object"},"config_path":{"description":"Active config file path","type":"string"},"duration":{"description":"Duration in nanoseconds","type":"integer"},"error":{"description":"Error message (failure only)","type":"string"},"execution_type":{"description":"\"direct\" or \"code_execution\"","type":"string"},"id":{"description":"Unique identifier","type":"string"},"mcp_client_name":{"description":"MCP client name from InitializeRequest","type":"string"},"mcp_client_version":{"description":"MCP client version","type":"string"},"mcp_session_id":{"description":"MCP session identifier","type":"string"},"metrics":{"$ref":"#/components/schemas/contracts.TokenMetrics"},"parent_call_id":{"description":"Links nested calls to parent code_execution","type":"string"},"request_id":{"description":"Request correlation ID","type":"string"},"response":{"description":"Tool response (success only)","type":"object"},"server_id":{"description":"Server identity hash","type":"string"},"server_name":{"description":"Human-readable server name","type":"string"},"timestamp":{"description":"When the call was made","type":"string"},"tool_name":{"description":"Tool name (without server prefix)","type":"string"}},"type":"object"},"contracts.UpdateInfo":{"description":"Update information (if available)","properties":{"available":{"description":"Whether an update is available","type":"boolean"},"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"},"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"}},"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},"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_ms":{"type":"integer"},"p95_ms":{"type":"integer"},"rejected":{"description":"spec 093: shed by a concurrency limit; never executed, so excluded from calls/latency","type":"integer"},"server":{"type":"string"},"sized_calls":{"description":"calls with known response size (basis for avg_resp_bytes)","type":"integer"},"tool":{"type":"string"},"total_req_bytes":{"type":"integer"},"total_resp_bytes":{"type":"integer"}},"type":"object"},"contracts.ValidateConfigResponse":{"properties":{"errors":{"items":{"$ref":"#/components/schemas/contracts.ValidationError"},"type":"array","uniqueItems":false},"valid":{"type":"boolean"}},"type":"object"},"contracts.ValidationError":{"properties":{"field":{"type":"string"},"message":{"type":"string"}},"type":"object"},"data":{"properties":{"data":{"$ref":"#/components/schemas/contracts.InfoResponse"}},"type":"object"},"httpapi.AddServerRequest":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"auto_approve_tool_changes":{"description":"AutoApproveToolChanges is the per-server intent to auto-approve\nnew/changed tools past the trust baseline (MCP-2930). Tri-state *bool:\na nil pointer means \"leave unchanged\" on PATCH; a present value\n(including false) is applied. Mirrors config.ServerConfig's *bool\nsemantics — do NOT collapse to a plain bool, or an omitted field would\nsilently reset a previously-set value.","type":"boolean"},"command":{"type":"string"},"enabled":{"type":"boolean"},"env":{"additionalProperties":{"type":"string"},"type":"object"},"expose_prompts":{"description":"ExposePrompts is the per-server override for prompt aggregation (F9):\nwhether this server's advertised MCP prompts are merged into mcpproxy's\nprompts/list. Tri-state *bool mirroring config.ServerConfig.ExposePrompts —\na nil pointer means \"leave unchanged\" on PATCH (and \"inherit the default\naggregate behavior\" on create); a present value (including false) is applied.","type":"boolean"},"headers":{"additionalProperties":{"type":"string"},"type":"object"},"init_timeout":{"description":"InitTimeout is the per-server MCP ` + "`" + `initialize` + "`" + ` handshake deadline override\n(MCP-3322 / GH #760), serialized as a duration string (e.g. \"120s\"). A nil\npointer means \"leave unchanged\" on PATCH; a present value is applied.\nMirrors config.ServerConfig.InitTimeout's *Duration tri-state.","type":"string"},"isolation":{"$ref":"#/components/schemas/httpapi.IsolationRequest"},"max_concurrent_requests":{"description":"MaxConcurrentRequests / QueueSize / QueueTimeout are the per-server\nconcurrency overrides (spec 093 / GH #955, FR-020 scope (c)). Each is\ntri-state: a nil pointer means \"leave unchanged\" on PATCH and \"inherit\nserver_concurrency_defaults\" on create; an explicit 0 disables that\nsetting for this server; a positive value overrides it. Do NOT collapse\nthem to plain values — an omitted field would then silently reset a\nconfigured limit.","type":"integer"},"name":{"type":"string"},"protocol":{"type":"string"},"quarantined":{"type":"boolean"},"queue_size":{"type":"integer"},"queue_timeout":{"type":"string"},"reconnect_on_use":{"type":"boolean"},"trust_mode":{"description":"TrustMode is the per-server trust tier (spec 086): \"auto\", \"scan\", or\n\"manual\". Empty means \"leave unchanged\" on PATCH (and inherit the migrated\ndefault on create). A non-empty value is applied to ServerConfig.TrustMode\nand resolved by EffectiveTrustMode (an unrecognized value fails closed to\nmanual). This is the REST seam for changing the trust tier via\nPOST/PATCH /api/v1/servers.","type":"string"},"url":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"httpapi.CanonicalConfigPath":{"properties":{"description":{"description":"Brief description","type":"string"},"exists":{"description":"Whether the file exists","type":"boolean"},"format":{"description":"Format identifier (e.g., \"claude_desktop\")","type":"string"},"name":{"description":"Display name (e.g., \"Claude Desktop\")","type":"string"},"os":{"description":"Operating system (darwin, windows, linux)","type":"string"},"path":{"description":"Full path to the config file","type":"string"}},"type":"object"},"httpapi.CanonicalConfigPathsResponse":{"properties":{"os":{"description":"Current operating system","type":"string"},"paths":{"description":"List of canonical config paths","items":{"$ref":"#/components/schemas/httpapi.CanonicalConfigPath"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ConnectConflictResponse":{"properties":{"action":{"description":"already_exists | precondition_failed","type":"string"},"data":{"$ref":"#/components/schemas/connect.ConnectResult"},"error":{"description":"Human-readable message","type":"string"},"success":{"description":"Always false","type":"boolean"}},"type":"object"},"httpapi.ConnectRequest":{"properties":{"force":{"description":"Overwrite existing entry","type":"boolean"},"precondition_token":{"description":"PreconditionToken is the opaque token from the preview this write was\nconfirmed against (Spec 091 FR-005). When present, the core rechecks it\nat write time and responds 409 with action \"precondition_failed\" —\nwriting nothing — if the config or the entry MCPProxy would write has\ndrifted since; the caller then re-previews instead of retrying. Absent\nmeans exactly the pre-091 behavior. A replace-classified flow sends this\nTOGETHER with force=true: the token, not the absence of force, is the\noverwrite safety.","type":"string"},"server_name":{"description":"Defaults to \"mcpproxy\"","type":"string"}},"type":"object"},"httpapi.ImportFromPathRequest":{"properties":{"format":{"description":"Optional format hint","type":"string"},"path":{"description":"File path to import from","type":"string"},"rename":{"additionalProperties":{"type":"string"},"description":"Rename maps a server name → new name. Applied after parsing so the\ncaller can disambiguate cross-source name collisions (Spec 046 v2 —\ne.g. \"mcpproxy\" → \"mcpproxy_claude_code\"). Keys are matched against\neither the raw source name (OriginalName) or the sanitized name shown\nin the preview (Server.Name); these differ for names that need\nsanitizing (e.g. \"Figma Desktop\" → \"Figma_Desktop\"). Keys not present\nin the imported set are ignored.","type":"object"},"server_names":{"description":"Optional: import only these servers","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportRequest":{"properties":{"content":{"description":"Raw JSON or TOML content","type":"string"},"format":{"description":"Optional format hint","type":"string"},"server_names":{"description":"Optional: import only these servers","items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportResponse":{"properties":{"failed":{"items":{"$ref":"#/components/schemas/configimport.FailedServer"},"type":"array","uniqueItems":false},"format":{"type":"string"},"format_name":{"type":"string"},"imported":{"items":{"$ref":"#/components/schemas/httpapi.ImportedServerResponse"},"type":"array","uniqueItems":false},"skipped":{"items":{"$ref":"#/components/schemas/configimport.SkippedServer"},"type":"array","uniqueItems":false},"summary":{"$ref":"#/components/schemas/configimport.ImportSummary"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.ImportedServerResponse":{"properties":{"args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"command":{"type":"string"},"fields_skipped":{"items":{"type":"string"},"type":"array","uniqueItems":false},"name":{"type":"string"},"original_name":{"type":"string"},"protocol":{"type":"string"},"source_format":{"type":"string"},"url":{"type":"string"},"warnings":{"items":{"type":"string"},"type":"array","uniqueItems":false}},"type":"object"},"httpapi.IsolationRequest":{"description":"Isolation carries per-server Docker isolation overrides (image,\nnetwork_mode, extra_args, working_dir, enabled). A nil pointer\nmeans \"do not touch isolation config\"; an empty-but-present\nobject on PATCH intentionally clears the overrides.","properties":{"enabled":{"type":"boolean"},"extra_args":{"items":{"type":"string"},"type":"array","uniqueItems":false},"image":{"type":"string"},"network_mode":{"type":"string"},"working_dir":{"type":"string"}},"type":"object"},"httpapi.OnboardingMarkRequest":{"properties":{"connect_step_status":{"description":"ConnectStepStatus is one of: \"\", \"completed\", \"skipped\". Empty\npreserves the existing value. The stored enum is wider (Spec 080\nFR-001): a \"skipped\" request for a previously untouched connect step\nis upgraded server-side to \"completed_external\" when the install\nshows positive evidence of an external connection (Spec 080 FR-002).\n\"completed_external\" is NOT accepted from clients — it must never be\npersisted without that server-verified evidence (edge case: \"never\nguess completed_external without positive evidence\").","type":"string"},"engaged":{"description":"Engaged marks the wizard as engaged (completed or explicitly skipped).\nOnce true, the wizard does not auto-show again.","type":"boolean"},"mark_shown":{"description":"MarkShown records the wizard's first display time if not already set.","type":"boolean"},"server_step_status":{"description":"ServerStepStatus is one of: \"\", \"completed\", \"skipped\". Empty\npreserves the existing value.","type":"string"}},"type":"object"},"httpapi.SetActiveProfileRequest":{"properties":{"active_profile":{"type":"string"},"profile":{"type":"string"}},"type":"object"},"httpapi.UndoConnectRequest":{"properties":{"backup_name":{"description":"BackupName is the bare filename (filepath.Base) of the backup returned as\nbackup_path by the preceding connect — a name, never a path. Undo resolves\nthe full path server-side by joining it with the client's own config\ndirectory, so a client-supplied value can never contribute a directory\ncomponent (traversal is impossible by construction). Empty means the\nconnect created the file (no prior file existed), so undo removes it.","type":"string"},"server_name":{"description":"Defaults to \"mcpproxy\"","type":"string"}},"type":"object"},"httpapi.UpdateFailureRequest":{"properties":{"stage":{"description":"Stage is the failure stage of the update session.","enum":["appcast","download","install","other"],"type":"string"}},"type":"object"},"management.BulkOperationResult":{"properties":{"errors":{"additionalProperties":{"type":"string"},"description":"Map of server name to error message","type":"object"},"failed":{"description":"Number of failed operations","type":"integer"},"successful":{"description":"Number of successful operations","type":"integer"},"total":{"description":"Total servers processed","type":"integer"}},"type":"object"},"observability.HealthResponse":{"properties":{"components":{"items":{"$ref":"#/components/schemas/observability.HealthStatus"},"type":"array","uniqueItems":false},"status":{"description":"\"healthy\" or \"unhealthy\"","type":"string"},"timestamp":{"type":"string"}},"type":"object"},"observability.HealthStatus":{"properties":{"error":{"type":"string"},"latency":{"type":"string"},"name":{"type":"string"},"status":{"description":"\"healthy\" or \"unhealthy\"","type":"string"}},"type":"object"},"observability.ReadinessResponse":{"properties":{"components":{"items":{"$ref":"#/components/schemas/observability.HealthStatus"},"type":"array","uniqueItems":false},"status":{"description":"\"ready\" or \"not_ready\"","type":"string"},"timestamp":{"type":"string"}},"type":"object"},"secureenv.EnvConfig":{"description":"Environment configuration for secure variable filtering","properties":{"allowed_system_vars":{"items":{"type":"string"},"type":"array","uniqueItems":false},"custom_vars":{"additionalProperties":{"type":"string"},"type":"object"},"enhance_path":{"description":"Enable PATH enhancement for Launchd scenarios","type":"boolean"},"forward_proxy_env":{"description":"ForwardProxyEnv opts in to forwarding the ambient HTTP(S)/ALL/NO/FTP proxy\nenvironment variables to spawned upstream servers (MCP-2769). It is OFF by\ndefault and deliberately kept out of the AllowedSystemVars default list:\nproxy URLs frequently carry credentials (http://user:pass@proxy), so\nforwarding them to every stdio upstream is a credential-leak risk. When\nenabled, values are forwarded with their userinfo (credentials) redacted.","type":"boolean"},"inherit_system_safe":{"type":"boolean"}},"type":"object"},"telemetry.FeedbackContext":{"properties":{"arch":{"type":"string"},"connected_server_count":{"type":"integer"},"edition":{"type":"string"},"os":{"type":"string"},"routing_mode":{"type":"string"},"server_count":{"type":"integer"},"version":{"type":"string"}},"type":"object"},"telemetry.FeedbackRequest":{"properties":{"category":{"description":"bug, feature, other","type":"string"},"context":{"$ref":"#/components/schemas/telemetry.FeedbackContext"},"email":{"type":"string"},"message":{"type":"string"}},"type":"object"},"telemetry.FeedbackResponse":{"properties":{"error":{"type":"string"},"issue_url":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}},"securitySchemes":{"ApiKeyAuth":{"description":"API key authentication via query parameter. Use ?apikey=your-key","in":"query","name":"apikey","type":"apiKey"}}}, "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":"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 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","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Routing mode information"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get routing mode information","tags":["status"]}},"/api/v1/secrets":{"post":{"description":"Stores a secret value in the operating system's secure keyring. The secret can then be referenced in configuration using ${keyring:secret-name} syntax. Automatically notifies runtime to restart affected servers.","requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{},"type":"object"}}},"description":"Secret stored successfully with reference syntax"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload, missing name/value, or unsupported type"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Secret resolver not available or failed to store secret"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Store a secret in OS keyring","tags":["secrets"]}},"/api/v1/secrets/{name}":{"delete":{"description":"Deletes a secret from the operating system's secure keyring. Automatically notifies runtime to restart affected servers. Only keyring type is supported for security.","parameters":[{"description":"Name of the secret to delete","in":"path","name":"name","required":true,"schema":{"type":"string"}},{"description":"Secret type (only 'keyring' supported, defaults to 'keyring')","in":"query","name":"type","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{},"type":"object"}}},"description":"Secret deleted successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Missing secret name or unsupported type"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Secret resolver not available or failed to delete secret"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Delete a secret from OS keyring","tags":["secrets"]}},"/api/v1/servers":{"get":{"description":"Get a list of all configured upstream MCP servers with their connection status and statistics","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServersResponse"}}},"description":"Server list with statistics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List all upstream MCP servers","tags":["servers"]},"post":{"description":"Add a new MCP upstream server to the configuration. New servers are quarantined by default for security.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.AddServerRequest"}}},"description":"Server configuration","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server added successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid configuration"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Conflict - server with this name already exists"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add a new upstream server","tags":["servers"]}},"/api/v1/servers/disable_all":{"post":{"description":"Disable all configured upstream MCP servers with partial failure handling","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/management.BulkOperationResult"}}},"description":"Bulk disable results with success/failure counts"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Disable all servers","tags":["servers"]}},"/api/v1/servers/enable_all":{"post":{"description":"Enable all configured upstream MCP servers with partial failure handling","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/management.BulkOperationResult"}}},"description":"Bulk enable results with success/failure counts"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable all servers","tags":["servers"]}},"/api/v1/servers/import":{"post":{"description":"Import MCP server configurations from a Claude Desktop, Claude Code, Cursor IDE, Codex CLI, or Gemini CLI configuration file","parameters":[{"description":"If true, return preview without importing","in":"query","name":"preview","schema":{"type":"boolean"}},{"description":"Force format (claude-desktop, claude-code, cursor, codex, gemini)","in":"query","name":"format","schema":{"type":"string"}},{"description":"Comma-separated list of server names to import","in":"query","name":"server_names","schema":{"type":"string"}}],"requestBody":{"content":{"multipart/form-data":{"schema":{"type":"file"}}},"description":"Configuration file to import","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportResponse"}}},"description":"Import result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid file or format"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Import servers from uploaded configuration file","tags":["servers"]}},"/api/v1/servers/import/json":{"post":{"description":"Import MCP server configurations from raw JSON or TOML content (useful for pasting configurations)","parameters":[{"description":"If true, return preview without importing","in":"query","name":"preview","schema":{"type":"boolean"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportRequest"}}},"description":"Import request with content","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportResponse"}}},"description":"Import result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid content or format"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Import servers from JSON/TOML content","tags":["servers"]}},"/api/v1/servers/import/path":{"post":{"description":"Import MCP server configurations by reading a file from the server's filesystem","parameters":[{"description":"If true, return preview without importing","in":"query","name":"preview","schema":{"type":"boolean"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportFromPathRequest"}}},"description":"Import request with file path","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportResponse"}}},"description":"Import result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid path or format"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"File not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Import servers from a file path","tags":["servers"]}},"/api/v1/servers/import/paths":{"get":{"description":"Returns well-known configuration file paths for supported formats with existence check","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.CanonicalConfigPathsResponse"}}},"description":"Canonical config paths"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get canonical config file paths","tags":["servers"]}},"/api/v1/servers/reconnect":{"post":{"description":"Force reconnection to all upstream MCP servers","parameters":[{"description":"Reason for reconnection","in":"query","name":"reason","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"All servers reconnected successfully"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Reconnect all servers","tags":["servers"]}},"/api/v1/servers/restart_all":{"post":{"description":"Restart all configured upstream MCP servers sequentially with partial failure handling","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/management.BulkOperationResult"}}},"description":"Bulk restart results with success/failure counts"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Restart all servers","tags":["servers"]}},"/api/v1/servers/{id}":{"delete":{"description":"Remove an MCP upstream server from the configuration. This stops the server if running and removes it from config.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server removed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Remove an upstream server","tags":["servers"]},"patch":{"description":"Update specific fields of an existing upstream MCP server configuration.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.AddServerRequest"}}},"description":"Fields to update (all optional)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server updated successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - no fields or invalid body"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Partially update an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/config-to-secret":{"post":{"description":"Atomically reads the real value from the server config, stores it in the OS keyring, and rewrites the config field to ` + "`" + `${keyring:\u003cname\u003e}` + "`" + `. Unblocks the UI's Convert-to-secret affordance for values the API redacts on the read path.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{},"type":"object"}}},"description":"Secret stored, config updated with reference"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad scope/key/secret_name, or value is already a reference / empty"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or key not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Secret resolver or config update failed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Convert a header / env value to a keyring secret","tags":["servers"]}},"/api/v1/servers/{id}/disable":{"post":{"description":"Disable a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server disabled successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Disable an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/discover-tools":{"post":{"description":"Manually trigger tool discovery and indexing for a specific upstream MCP server. This forces an immediate refresh of the server's tool cache.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Tool discovery triggered successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot discover tools)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to discover tools"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Discover tools for a specific server","tags":["servers"]}},"/api/v1/servers/{id}/enable":{"post":{"description":"Enable a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server enabled successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/login":{"post":{"description":"Initiate OAuth authentication flow for a specific upstream MCP server. Returns structured OAuth start response with correlation ID for tracking.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.OAuthStartResponse"}}},"description":"OAuth login initiated successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.OAuthFlowError"}}},"description":"OAuth error (client_id required, DCR failed, etc.)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Trigger OAuth login for server","tags":["servers"]}},"/api/v1/servers/{id}/logout":{"post":{"description":"Clear OAuth authentication token and disconnect a specific upstream MCP server. The server will need to re-authenticate before tools can be used again.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"OAuth logout completed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled or read-only mode)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Clear OAuth token and disconnect server","tags":["servers"]}},"/api/v1/servers/{id}/logs":{"get":{"description":"Retrieve log entries for a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Number of log lines to retrieve","in":"query","name":"tail","schema":{"default":100,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServerLogsResponse"}}},"description":"Server logs retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server logs","tags":["servers"]}},"/api/v1/servers/{id}/quarantine":{"post":{"description":"Place a specific upstream MCP server in quarantine to prevent tool execution","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server quarantined successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Quarantine a server","tags":["servers"]}},"/api/v1/servers/{id}/refresh":{"post":{"description":"Re-discover and re-index a specific upstream MCP server's tools without changing any security state. Alias of discover-tools, named for the upstream_servers 'refresh' operation; use it to make just-approved tools searchable immediately.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Tool refresh triggered successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot refresh)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to refresh tools"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Refresh a server's tools","tags":["servers"]}},"/api/v1/servers/{id}/restart":{"post":{"description":"Restart the connection to a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server restarted successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Restart an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/tool-calls":{"get":{"description":"Retrieves tool call history filtered by upstream server ID. Returns recent tool executions for the specified server including timestamps, arguments, results, and errors. Useful for server-specific debugging and monitoring.","parameters":[{"description":"Upstream server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Maximum number of records to return (1-100, default 50)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServerToolCallsResponse"}}},"description":"Server tool calls retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get server tool calls"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call history for specific server","tags":["tool-calls"]}},"/api/v1/servers/{id}/tools":{"get":{"description":"Retrieve all available tools for a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServerToolsResponse"}}},"description":"Server tools retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/block":{"post":{"description":"Atomically approves AND disables the given tools (or all pending/changed tools when block_all=true) for a server. The approve and disable land in a single write per tool, so a tool is never left in the approved+enabled state. The \"blocked\" field counts tools actually blocked.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Block result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Block (approve+disable) tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/disable_all":{"post":{"description":"Bulk-toggles every known tool of a server. The \"changed\" field","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Operation result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable or disable all tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/enable_all":{"post":{"description":"Bulk-toggles every known tool of a server. The \"changed\" field","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Operation result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable or disable all tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/unquarantine":{"post":{"description":"Remove a specific upstream MCP server from quarantine to allow tool execution","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server unquarantined successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Unquarantine a server","tags":["servers"]}},"/api/v1/sessions":{"get":{"description":"Retrieves paginated list of active and recent MCP client sessions. Each session represents a connection from an MCP client to MCPProxy, tracking initialization time, tool calls, and connection status.","parameters":[{"description":"Maximum number of sessions to return (1-100, default 10)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Number of sessions to skip for pagination (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Filter by session status","in":"query","name":"status","schema":{"enum":["active","closed"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetSessionsResponse"}}},"description":"Sessions retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid status filter"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get sessions"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get active MCP sessions","tags":["sessions"]}},"/api/v1/sessions/{id}":{"get":{"description":"Retrieves detailed information about a specific MCP client session including initialization parameters, connection status, tool call count, and activity timestamps.","parameters":[{"description":"Session ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetSessionDetailResponse"}}},"description":"Session details retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Session ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Session not found"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get MCP session details by ID","tags":["sessions"]}},"/api/v1/stats/tokens":{"get":{"description":"Retrieve token savings statistics across all servers and sessions","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Token statistics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get token savings statistics","tags":["stats"]}},"/api/v1/status":{"get":{"description":"Get comprehensive server status including running state, listen address, upstream statistics, and timestamp","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server status information"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server status","tags":["status"]}},"/api/v1/telemetry/payload":{"get":{"description":"Render the exact JSON heartbeat payload that mcpproxy would next send to the telemetry endpoint, without making a network call. Counters in the payload reflect the current in-memory state. Spec 042.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Telemetry heartbeat payload"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Telemetry service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Preview next telemetry heartbeat payload","tags":["telemetry"]}},"/api/v1/telemetry/update-failure":{"post":{"description":"Records one terminal update-session failure, identified only by its\nstage (appcast, download, install, other). The body carries no error\ntext, URL, or version — the stage is the only value transmitted.\nReturns 204 both when the occurrence was durably persisted and when\ntelemetry is inactive at event time (config opt-out, environment\nopt-out, CI, or dev build), in which case nothing is recorded.\nCallers cannot and need not distinguish the two.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.UpdateFailureRequest"}}},"description":"Update failure stage","required":true},"responses":{"204":{"description":"Accepted (recorded, or a deliberate no-op while telemetry is inactive)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Malformed body, unknown field, trailing value, or stage outside the closed set"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Persistence failure"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Record a desktop auto-update failure occurrence (Spec 095)","tags":["telemetry"]}},"/api/v1/tool-calls":{"get":{"description":"Retrieves paginated tool call history across all upstream servers or filtered by session ID. Includes execution timestamps, arguments, results, and error information for debugging and auditing.","parameters":[{"description":"Maximum number of records to return (1-100, default 50)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Number of records to skip for pagination (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Filter tool calls by MCP session ID","in":"query","name":"session_id","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetToolCallsResponse"}}},"description":"Tool calls retrieved successfully"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get tool calls"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call history","tags":["tool-calls"]}},"/api/v1/tool-calls/{id}":{"get":{"description":"Retrieves detailed information about a specific tool call execution including full request arguments, response data, execution time, and any errors encountered.","parameters":[{"description":"Tool call ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetToolCallDetailResponse"}}},"description":"Tool call details retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call not found"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call details by ID","tags":["tool-calls"]}},"/api/v1/tool-calls/{id}/replay":{"post":{"description":"Re-executes a previous tool call with optional modified arguments. Useful for debugging and testing tool behavior with different inputs. Creates a new tool call record linked to the original.","parameters":[{"description":"Original tool call ID to replay","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ReplayToolCallRequest"}}},"description":"Optional modified arguments for replay"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ReplayToolCallResponse"}}},"description":"Tool call replayed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call ID required or invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"429":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Shed by a concurrency limit (Retry-After header carries the wait hint)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to replay tool call"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Replay a tool call","tags":["tool-calls"]}},"/api/v1/tools":{"get":{"description":"Consolidated, read-only listing of all tools from every configured server (including disabled servers and disabled/config-denied tools), enriched with approval state and 30-day usage. Backs the global Tools page and the CLI global ` + "`" + `tools list` + "`" + ` (spec 050, issue #437).","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GlobalToolsResponse"}}},"description":"All tools across all servers"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Could not enumerate servers"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List every tool across all servers","tags":["tools"]}},"/api/v1/tools/call":{"post":{"description":"Execute a tool on an upstream MCP server (wrapper around MCP tool calls)","requestBody":{"content":{"application/json":{"schema":{"properties":{"arguments":{"type":"object"},"tool_name":{"type":"string"}},"type":"object"}}},"description":"Tool call request with tool name and arguments","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Tool call result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (invalid payload or missing tool name)"},"429":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Shed by a concurrency limit (Retry-After header carries the wait hint)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error or tool execution failure"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Call a tool","tags":["tools"]}},"/healthz":{"get":{"description":"Get comprehensive health status including all component health (Kubernetes-compatible liveness probe)","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.HealthResponse"}}},"description":"Service is healthy"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.HealthResponse"}}},"description":"Service is unhealthy"}},"summary":"Get health status","tags":["health"]}},"/readyz":{"get":{"description":"Get readiness status including all component readiness checks (Kubernetes-compatible readiness probe)","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.ReadinessResponse"}}},"description":"Service is ready"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.ReadinessResponse"}}},"description":"Service is not ready"}},"summary":"Get readiness status","tags":["health"]}}}, + "paths": {"/api/v1/activity":{"get":{"description":"Returns paginated list of activity records with optional filtering","parameters":[{"description":"Filter by activity type(s), comma-separated for multiple (Spec 024)","in":"query","name":"type","schema":{"enum":["tool_call","policy_decision","quarantine_change","server_change","system_start","system_stop","internal_tool_call","config_change","preflight","prompt_get"],"type":"string"}},{"description":"Filter by server name","in":"query","name":"server","schema":{"type":"string"}},{"description":"Filter by tool name","in":"query","name":"tool","schema":{"type":"string"}},{"description":"Filter by MCP transport session ID","in":"query","name":"session_id","schema":{"type":"string"}},{"description":"Filter by work session (one client, one project, across reconnects)","in":"query","name":"work_session_id","schema":{"type":"string"}},{"description":"Filter by status","in":"query","name":"status","schema":{"enum":["success","error","blocked","rejected"],"type":"string"}},{"description":"Filter by intent operation type (Spec 018)","in":"query","name":"intent_type","schema":{"enum":["read","write","destructive"],"type":"string"}},{"description":"Filter by HTTP request ID for log correlation (Spec 021)","in":"query","name":"request_id","schema":{"type":"string"}},{"description":"Filter by parent call id — returns the sub-calls one code_execution issued","in":"query","name":"parent_id","schema":{"type":"string"}},{"description":"Include successful call_tool_* internal tool calls (default: false, excluded to avoid duplicates)","in":"query","name":"include_call_tool","schema":{"type":"boolean"}},{"description":"Filter by sensitive data detection (true=has detections, false=no detections)","in":"query","name":"sensitive_data","schema":{"type":"boolean"}},{"description":"Filter by specific detection type (e.g., 'aws_access_key', 'credit_card')","in":"query","name":"detection_type","schema":{"type":"string"}},{"description":"Filter by severity level","in":"query","name":"severity","schema":{"enum":["critical","high","medium","low"],"type":"string"}},{"description":"Filter by agent token name (Spec 028)","in":"query","name":"agent","schema":{"type":"string"}},{"description":"Filter by auth type (Spec 028)","in":"query","name":"auth_type","schema":{"enum":["admin","agent"],"type":"string"}},{"description":"Filter activities after this time (RFC3339)","in":"query","name":"start_time","schema":{"type":"string"}},{"description":"Filter activities before this time (RFC3339)","in":"query","name":"end_time","schema":{"type":"string"}},{"description":"Maximum records to return (1-100, default 50)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Pagination offset (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Omit arguments, response and metadata except a contextual whitelist (intent.reason, intent.operation_type, decision, reason, client_name, client_version) (default: false). For clients that render summary fields only; has_sensitive_data is still derived before metadata is dropped.","in":"query","name":"exclude_payloads","schema":{"type":"boolean"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"List activity records","tags":["Activity"]}},"/api/v1/activity/export":{"get":{"description":"Exports activity records in JSON Lines or CSV format for compliance","parameters":[{"description":"Export format: json (default) or csv","in":"query","name":"format","schema":{"type":"string"}},{"description":"Filter by activity type","in":"query","name":"type","schema":{"type":"string"}},{"description":"Filter by server name","in":"query","name":"server","schema":{"type":"string"}},{"description":"Filter by tool name","in":"query","name":"tool","schema":{"type":"string"}},{"description":"Filter by MCP transport session ID","in":"query","name":"session_id","schema":{"type":"string"}},{"description":"Filter by work session (one client, one project, across reconnects)","in":"query","name":"work_session_id","schema":{"type":"string"}},{"description":"Filter by status","in":"query","name":"status","schema":{"type":"string"}},{"description":"Filter by HTTP request ID for log correlation (Spec 021)","in":"query","name":"request_id","schema":{"type":"string"}},{"description":"Filter by parent call id — exports the sub-calls one code_execution issued","in":"query","name":"parent_id","schema":{"type":"string"}},{"description":"Filter activities after this time (RFC3339)","in":"query","name":"start_time","schema":{"type":"string"}},{"description":"Filter activities before this time (RFC3339)","in":"query","name":"end_time","schema":{"type":"string"}},{"description":"Maximum records to export (1-50000, default 10000)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Pagination offset (default 0)","in":"query","name":"offset","schema":{"type":"integer"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"type":"string"}},"application/x-ndjson":{"schema":{"type":"string"}},"text/csv":{"schema":{"type":"string"}}},"description":"Streamed activity records"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Export activity records","tags":["Activity"]}},"/api/v1/activity/summary":{"get":{"description":"Returns aggregated activity statistics for a time period","parameters":[{"description":"Time period: 1h, 24h (default), 7d, 30d","in":"query","name":"period","schema":{"type":"string"}},{"description":"Group by: server, tool (optional)","in":"query","name":"group_by","schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Get activity summary statistics","tags":["Activity"]}},"/api/v1/activity/usage":{"get":{"description":"Returns the actor-owned usage aggregate (per-tool rollup + timeline + tokens-saved headline) for the Web UI usage graphs (Spec 069). Served from an in-memory snapshot — never a per-request full-log scan. Per-tool metrics are lifetime-cumulative; ` + "`" + `window` + "`" + ` scopes the timeline and filters the tool list to tools active within the span.","parameters":[{"description":"Time window for timeline + tool-list membership","in":"query","name":"window","schema":{"enum":["24h","7d","all"],"type":"string"}},{"description":"Filter to one server","in":"query","name":"server","schema":{"type":"string"}},{"description":"Filter to one tool","in":"query","name":"tool","schema":{"type":"string"}},{"description":"Filter to tools with activity of this status","in":"query","name":"status","schema":{"enum":["success","error","blocked","rejected"],"type":"string"}},{"description":"Top-N tools by sort key; remainder folded into 'other' (default 20)","in":"query","name":"top","schema":{"type":"integer"}},{"description":"Ranking key for the per-tool list","in":"query","name":"sort","schema":{"enum":["calls","resp_bytes","error_rate","p95"],"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Bad Request"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Get usage statistics aggregate","tags":["Activity"]}},"/api/v1/activity/{id}":{"get":{"description":"Returns full details for a single activity record","parameters":[{"description":"Activity record ID (ULID)","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"OK"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Unauthorized"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Not Found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Get activity record details","tags":["Activity"]}},"/api/v1/annotations/coverage":{"get":{"description":"Reports how many upstream tools have MCP annotations vs don't, broken down by server","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Annotation coverage report"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get annotation coverage report","tags":["annotations"]}},"/api/v1/code/scripts":{"get":{"description":"List the stored scripts available to the code_execution tool. Scripts are ` + "`" + `\u003cname\u003e.js` + "`" + ` / ` + "`" + `\u003cname\u003e.ts` + "`" + ` files in the ` + "`" + `scripts/` + "`" + ` directory next to the active configuration file. Entries are advisory: ` + "`" + `ok` + "`" + ` scripts are invocable, ` + "`" + `ambiguous` + "`" + ` names have both extensions, and ` + "`" + `invalid` + "`" + ` ones report why (empty, oversized, unreadable, non-regular). Read-only — there is no write surface for stored scripts.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Stored scripts and the directory they were read from"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List stored code-execution scripts","tags":["code"]}},"/api/v1/config":{"get":{"description":"Retrieves the current MCPProxy configuration including all server definitions, global settings, and runtime parameters","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetConfigResponse"}}},"description":"Configuration retrieved successfully"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get current configuration","tags":["config"]},"patch":{"description":"Deep-merges only the fields present in the request body onto the live in-memory configuration and routes the result through the existing apply pipeline (validation, change detection, disk persistence, hot-reload). Fields the client omits — including masked secrets such as ` + "`" + `api_key` + "`" + ` and secret request headers — are preserved verbatim. Nested objects are merged recursively; arrays and scalars replace wholesale.","requestBody":{"content":{"application/json":{"schema":{"type":"object"}}},"description":"Partial configuration with only the fields to change","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ConfigApplyResult"}}},"description":"Configuration patch applied (inspect validation_errors for rejected values)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload or empty patch"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate configuration)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to read or apply configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Partially update configuration","tags":["config"]}},"/api/v1/config/apply":{"post":{"description":"Applies a new MCPProxy configuration. Validates and persists the configuration to disk. Some changes apply immediately, while others may require a restart. Returns detailed information about applied changes and restart requirements.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.Config"}}},"description":"Configuration to apply","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ConfigApplyResult"}}},"description":"Configuration applied successfully with change details"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate configuration)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to apply configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Apply configuration","tags":["config"]}},"/api/v1/config/docker-isolation":{"patch":{"description":"Convenience endpoint to flip ` + "`" + `docker_isolation.enabled` + "`" + ` without resending the full config. Persists to disk via the existing config writer — the file watcher then hot-reloads the change. Returns the new state and whether a restart is required for existing connections to pick it up.","requestBody":{"content":{"application/json":{"schema":{"properties":{"enabled":{"type":"boolean"}},"type":"object"}}},"description":"New isolation state","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ConfigApplyResult"}}},"description":"Isolation toggle applied"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate configuration)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to apply configuration"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Toggle global Docker isolation","tags":["config"]}},"/api/v1/config/validate":{"post":{"description":"Validates a provided MCPProxy configuration without applying it. Checks for syntax errors, invalid server definitions, conflicting settings, and other configuration issues.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/config.Config"}}},"description":"Configuration to validate","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ValidateConfigResponse"}}},"description":"Configuration validation result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Validation failed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Validate configuration","tags":["config"]}},"/api/v1/connect":{"get":{"description":"Returns the connection status for all known MCP client applications.\nEach entry indicates whether the client config file exists and whether\nMCPProxy is currently registered in it.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"List of ClientStatus objects"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List client connection status","tags":["connect"]}},"/api/v1/connect/{client}":{"delete":{"description":"Remove the MCPProxy entry from the specified client's configuration file.\nCreates a backup of the existing config before modifying.","parameters":[{"description":"Client ID (claude-code, claude-desktop, cursor, windsurf, vscode, codex, gemini, opencode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectRequest"}}},"description":"Optional parameters (server_name)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectResult"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Permission denied (macOS App-Data block)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client or entry not found"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Disconnect MCPProxy from a client","tags":["connect"]},"get":{"description":"Resolves one client's status by reading its config file on demand.\nThis is the only Connect endpoint that opens a client config file, so\non macOS it is the sole place an App-Data privacy prompt may legitimately\nappear (scoped to this user action). Resolves access_state to\naccessible|absent|denied|malformed and populates remediation when denied.","parameters":[{"description":"Client ID (claude-code, claude-desktop, cursor, windsurf, vscode, codex, gemini, opencode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ClientStatus"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get a single client's connection status (on-demand)","tags":["connect"]},"post":{"description":"Register MCPProxy as an MCP server in the specified client's configuration file.\nCreates a backup of the existing config before modifying.\nOptionally accepts precondition_token from a preview (Spec 091): when supplied,\nthe core rechecks the raw pre-write state and the entry it would write, and\nrefuses a drifted write with 409 before taking any backup. The 409 body's\naction discriminates the two conflict kinds: \"precondition_failed\" (stale\npreview — re-preview, do not retry) vs \"already_exists\" (entry present — pass\nforce=true). force=true never rescues a stale token.","parameters":[{"description":"Client ID (claude-code, claude-desktop, cursor, windsurf, vscode, codex, gemini, opencode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectRequest"}}},"description":"Optional connection parameters (server_name, force, precondition_token)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectResult"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Permission denied (macOS App-Data block)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ConnectConflictResponse"}}},"description":"Conflict: action=already_exists (use force=true) or action=precondition_failed (preview is stale; re-preview)"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Connect MCPProxy to a client","tags":["connect"]}},"/api/v1/connect/{client}/preview":{"get":{"description":"Returns the exact entry a subsequent connect would add to the client's\nconfig — target path, server key, entry name, and entry contents — WITHOUT\nmodifying the file or creating a backup (Spec 078 US1). The embedded API key\nis masked in the payload; contains_api_key flags that a credential is written.\nentry_exists distinguishes a create from an overwrite of a same-named entry.\nReads the config on demand to classify create-vs-overwrite, so on macOS this\nmay raise an App-Data privacy prompt; a denial returns 403 + remediation.\nSpec 091 adds three fields: existing_entry_summary (present only when\nentry_exists — a sanitized, non-secret projection of the entry being replaced:\nits name, type, endpoint with query/userinfo stripped, command, and header and\nenv NAMES, never values); precondition_token (always present — an opaque keyed\ndigest of the raw pre-write state and the pending entry, echoed back on POST\nconnect to detect drift); and connect_refusal (present when the write would\nrefuse regardless of intent, e.g. a non-create-capable client with no config —\ntreat its presence as \"Connect unavailable\").","parameters":[{"description":"Client ID (claude-code, claude-desktop, cursor, windsurf, vscode, codex, gemini, opencode)","in":"path","name":"client","required":true,"schema":{"type":"string"}},{"description":"Entry name to preview (defaults to mcpproxy); mirror the value passed to POST connect","in":"query","name":"server_name","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectPreview"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Permission denied (macOS App-Data block)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Preview the change a connect would make (no write)","tags":["connect"]}},"/api/v1/connect/{client}/undo":{"post":{"description":"Reverts the connect that produced the named backup (Spec 078 US3):\nrestores the client config byte-for-byte from that backup, or — when\nbackup_name is empty because the connect created the file — deletes the\ncreated file. backup_name is the bare filename of the backup the connect\nreturned (never a path); undo resolves the full path server-side inside\nthe client's own config directory, so a client value cannot escape it.\nRefuses with 409 when the config changed since the connect (undo never\nclobbers later edits; use DELETE /connect/{client} for a surgical entry\nremoval instead). Takes its own safety backup first; its path is returned\nas backup_path in the result.","parameters":[{"description":"Client ID (claude-code, claude-desktop, cursor, windsurf, vscode, codex, gemini, opencode)","in":"path","name":"client","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.UndoConnectRequest"}}},"description":"Undo parameters (server_name, backup_name = the bare filename of the backup the preceding connect returned)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"ConnectResult (action restored|deleted)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (e.g. backup_name is a path, or not a backup of this client's config)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Permission denied (macOS App-Data block)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown client or backup no longer exists"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Config changed since connect; undo refused"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Undo a connect, restoring the pre-connect config","tags":["connect"]}},"/api/v1/diagnostics":{"get":{"description":"Get comprehensive health diagnostics including upstream errors, OAuth requirements, missing secrets, and Docker status","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.Diagnostics"}}},"description":"Health diagnostics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get health diagnostics","tags":["diagnostics"]}},"/api/v1/docker/status":{"get":{"description":"Retrieve current Docker availability and recovery status","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Docker status information"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get Docker status","tags":["docker"]}},"/api/v1/doctor":{"get":{"description":"Get comprehensive health diagnostics including upstream errors, OAuth requirements, missing secrets, and Docker status","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.Diagnostics"}}},"description":"Health diagnostics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get health diagnostics","tags":["diagnostics"]}},"/api/v1/feedback":{"post":{"description":"Submit a bug report, feature request, or general feedback","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/telemetry.FeedbackRequest"}}},"description":"Feedback request","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/telemetry.FeedbackResponse"}}},"description":"OK"},"400":{"content":{"application/json":{"schema":{"additionalProperties":{"type":"string"},"type":"object"}}},"description":"Bad Request"},"429":{"content":{"application/json":{"schema":{"additionalProperties":{"type":"string"},"type":"object"}}},"description":"Too Many Requests"},"500":{"content":{"application/json":{"schema":{"additionalProperties":{"type":"string"},"type":"object"}}},"description":"Internal Server Error"}},"security":[{"ApiKeyAuth":[]}],"summary":"Submit feedback","tags":["feedback"]}},"/api/v1/index/search":{"get":{"description":"Search across all upstream MCP server tools using BM25 keyword search","parameters":[{"description":"Search query","in":"query","name":"q","required":true,"schema":{"type":"string"}},{"description":"Maximum number of results","in":"query","name":"limit","schema":{"default":10,"maximum":100,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SearchToolsResponse"}}},"description":"Search results"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing query parameter)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Search for tools","tags":["tools"]}},"/api/v1/info":{"get":{"description":"Get essential server metadata including version, web UI URL, endpoint addresses, and update availability\nThis endpoint is designed for tray-core communication and version checking\nUse refresh=true query parameter to force an immediate update check against GitHub\nThe launched_by field reports durable launch provenance (\"tray\", \"installer\", or \"\" for user-launched/unknown)","parameters":[{"description":"Force immediate update check against GitHub","in":"query","name":"refresh","schema":{"type":"boolean"}}],"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Server information with optional update info"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server information","tags":["status"]}},"/api/v1/onboarding/mark":{"post":{"description":"Updates wizard engagement and per-step status. Once engaged is\ntrue, the wizard does not auto-show again, even if state regresses.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.OnboardingMarkRequest"}}},"description":"Mark request","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Updated OnboardingStateResponse"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Mark onboarding wizard state (Spec 046)","tags":["onboarding"]}},"/api/v1/onboarding/state":{"get":{"description":"Returns the wizard engagement record alongside live predicates\n(whether any client is connected, whether any server is configured),\nplus a derived ShouldShowWizard flag the frontend can rely on.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"OnboardingStateResponse"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get onboarding wizard state and predicates (Spec 046)","tags":["onboarding"]}},"/api/v1/preflight":{"post":{"description":"Deterministic, side-effect-free availability check for a caller-supplied list of tool IDs (Spec 098). Performs zero upstream calls and mutates no runtime state. HTTP status reports whether the CHECK executed: a fully blocked set is still 200, with the availability verdict in the body. Every executed preflight writes an activity record before the response is returned.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.PreflightRequest"}}},"description":"Tool IDs (1-100 before dedup), optional profile, annotation policy filters and wait budget","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/data"}],"properties":{"data":{"type":"object"},"error":{"type":"string"},"request_id":{"type":"string"},"success":{"type":"boolean"}},"type":"object"}}},"description":"Preflight verdict and per-tool results"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Validation error (malformed, oversized, doubled or unknown-field body; empty or oversized tool list; conflicting duplicate pins; unknown profile; wait_ms out of range)"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Missing or invalid credentials"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.APIResponse"}}},"description":"Runtime unavailable, evaluator infrastructure read failure, or the activity record could not be persisted"}},"security":[{"ApiKeyHeader":[]},{"ApiKeyQuery":[]}],"summary":"Preflight required tools","tags":["tools"]}},"/api/v1/profiles":{"get":{"description":"List all configured profiles with their effective servers and indexed tool count (Profiles v2). A profile scopes tool discovery and calls to a named subset of upstream servers.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Profile list"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Configuration unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List configured profiles","tags":["profiles"]}},"/api/v1/profiles/active":{"get":{"description":"Get the server-level default active profile used by UI surfaces (Web UI / tray). Empty string means \"all servers\". Note: within a live MCP session, the set_profile tool selection takes precedence over this default.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Active profile"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get the default active profile","tags":["profiles"]},"put":{"description":"Set the server-level default active profile for UI surfaces. The slug must match a configured profile; pass an empty string to clear. This does not affect live MCP sessions, which use the set_profile tool.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.SetActiveProfileRequest"}}},"description":"Profile slug to activate (empty clears)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Active profile updated"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid request body"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unknown profile"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Set the default active profile","tags":["profiles"]}},"/api/v1/registries":{"get":{"description":"Retrieves list of all MCP server registries that can be browsed for discovering and installing new upstream servers. Includes registry metadata, server counts, and API endpoints.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetRegistriesResponse"}}},"description":"Registries retrieved successfully"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to list registries"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List available MCP server registries","tags":["registries"]},"post":{"description":"Adds a generic modelcontextprotocol/registry v0.1 https endpoint as a custom registry (MCP-866). The source is always tagged custom/unverified, so every server discovered through it lands quarantined and can never skip quarantine.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.AddRegistrySourceRequest"}}},"description":"Registry source (https url + optional protocol/id/name)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Registry source added"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"invalid_registry_url"},"403":{"content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/contracts.ErrorResponse"},{"$ref":"#/components/schemas/contracts.ErrorResponse"}]}}},"description":"Forbidden (agent tokens cannot mutate registries)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_shadows_builtin | duplicate_registry"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add a user-supplied registry source","tags":["registries"]}},"/api/v1/registries/{id}":{"delete":{"description":"Removes a custom/unverified registry previously added via add-source (MCP-1057). Built-in registries are refused with registry_shadows_builtin; an unknown id yields registry_not_found. The change is persisted copy-on-write.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Registry source removed"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID is required"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registries_locked"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_not_found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_shadows_builtin"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Remove a user-added custom registry source","tags":["registries"]},"put":{"description":"Updates a custom registry previously added via add-source (MCP-1072): name, url, servers-url. Empty fields are left unchanged. Built-in registries are refused with registry_shadows_builtin; an unknown id yields registry_not_found; a non-https url yields invalid_registry_url. The change is persisted copy-on-write.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.EditRegistrySourceRequest"}}},"description":"Fields to update (name/url/servers_url; empty = unchanged)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Registry source updated"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID is required | invalid_registry_url"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registries_locked"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_not_found"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_shadows_builtin"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Edit a user-added custom registry source","tags":["registries"]}},"/api/v1/registries/{id}/refresh":{"post":{"description":"Invalidates the cached server lists for a registry so the next search re-fetches fresh data from the source (spec 070 FR-007). Returns how many cache entries were dropped.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.RefreshRegistryResponse"}}},"description":"Registry cache refreshed"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID is required"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to refresh registry cache"}},"summary":"Refresh a registry's cached server list","tags":["registries"]}},"/api/v1/registries/{id}/servers":{"get":{"description":"Searches for MCP servers within a specific registry by keyword or tag. Returns server metadata including installation commands, source code URLs, and npm package information for easy discovery and installation.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Search query keyword","in":"query","name":"q","schema":{"type":"string"}},{"description":"Filter by tag","in":"query","name":"tag","schema":{"type":"string"}},{"description":"Maximum number of results (default 10)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SearchRegistryServersResponse"}}},"description":"Servers retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Registry ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to search servers"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Search MCP servers in a registry","tags":["registries"]}},"/api/v1/registries/{id}/servers/{serverId}/add":{"post":{"description":"Resolves a registry server reference server-side, re-derives a validated config, and persists it quarantined (spec 070 keystone). The client never sends a config blob — command/args/url and the quarantine flag are derived from the registry entry, not the request.","parameters":[{"description":"Registry ID","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Server ID within the registry","in":"path","name":"serverId","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.AddFromRegistryRequest"}}},"description":"Optional overrides (name, env, enabled)"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server added (quarantined)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"no_install_info | missing_required_input | duplicate_name"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot add servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"registry_not_found | server_not_found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add an upstream server from a registry reference","tags":["registries"]}},"/api/v1/routing":{"get":{"description":"Get the current routing mode and available MCP endpoints","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Routing mode information"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get routing mode information","tags":["status"]}},"/api/v1/secrets":{"post":{"description":"Stores a secret value in the operating system's secure keyring. The secret can then be referenced in configuration using ${keyring:secret-name} syntax. Automatically notifies runtime to restart affected servers.","requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{},"type":"object"}}},"description":"Secret stored successfully with reference syntax"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid JSON payload, missing name/value, or unsupported type"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Secret resolver not available or failed to store secret"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Store a secret in OS keyring","tags":["secrets"]}},"/api/v1/secrets/{name}":{"delete":{"description":"Deletes a secret from the operating system's secure keyring. Automatically notifies runtime to restart affected servers. Only keyring type is supported for security.","parameters":[{"description":"Name of the secret to delete","in":"path","name":"name","required":true,"schema":{"type":"string"}},{"description":"Secret type (only 'keyring' supported, defaults to 'keyring')","in":"query","name":"type","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{},"type":"object"}}},"description":"Secret deleted successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Missing secret name or unsupported type"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Secret resolver not available or failed to delete secret"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Delete a secret from OS keyring","tags":["secrets"]}},"/api/v1/servers":{"get":{"description":"Get a list of all configured upstream MCP servers with their connection status and statistics","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServersResponse"}}},"description":"Server list with statistics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List all upstream MCP servers","tags":["servers"]},"post":{"description":"Add a new MCP upstream server to the configuration. New servers are quarantined by default for security.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.AddServerRequest"}}},"description":"Server configuration","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server added successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid configuration"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"409":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Conflict - server with this name already exists"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Add a new upstream server","tags":["servers"]}},"/api/v1/servers/disable_all":{"post":{"description":"Disable all configured upstream MCP servers with partial failure handling","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/management.BulkOperationResult"}}},"description":"Bulk disable results with success/failure counts"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Disable all servers","tags":["servers"]}},"/api/v1/servers/enable_all":{"post":{"description":"Enable all configured upstream MCP servers with partial failure handling","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/management.BulkOperationResult"}}},"description":"Bulk enable results with success/failure counts"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable all servers","tags":["servers"]}},"/api/v1/servers/import":{"post":{"description":"Import MCP server configurations from a Claude Desktop, Claude Code, Cursor IDE, Codex CLI, or Gemini CLI configuration file","parameters":[{"description":"If true, return preview without importing","in":"query","name":"preview","schema":{"type":"boolean"}},{"description":"Force format (claude-desktop, claude-code, cursor, codex, gemini)","in":"query","name":"format","schema":{"type":"string"}},{"description":"Comma-separated list of server names to import","in":"query","name":"server_names","schema":{"type":"string"}}],"requestBody":{"content":{"multipart/form-data":{"schema":{"type":"file"}}},"description":"Configuration file to import","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportResponse"}}},"description":"Import result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid file or format"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Import servers from uploaded configuration file","tags":["servers"]}},"/api/v1/servers/import/json":{"post":{"description":"Import MCP server configurations from raw JSON or TOML content (useful for pasting configurations)","parameters":[{"description":"If true, return preview without importing","in":"query","name":"preview","schema":{"type":"boolean"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportRequest"}}},"description":"Import request with content","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportResponse"}}},"description":"Import result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid content or format"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Import servers from JSON/TOML content","tags":["servers"]}},"/api/v1/servers/import/path":{"post":{"description":"Import MCP server configurations by reading a file from the server's filesystem","parameters":[{"description":"If true, return preview without importing","in":"query","name":"preview","schema":{"type":"boolean"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportFromPathRequest"}}},"description":"Import request with file path","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.ImportResponse"}}},"description":"Import result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - invalid path or format"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"File not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Import servers from a file path","tags":["servers"]}},"/api/v1/servers/import/paths":{"get":{"description":"Returns well-known configuration file paths for supported formats with existence check","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.CanonicalConfigPathsResponse"}}},"description":"Canonical config paths"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get canonical config file paths","tags":["servers"]}},"/api/v1/servers/reconnect":{"post":{"description":"Force reconnection to all upstream MCP servers","parameters":[{"description":"Reason for reconnection","in":"query","name":"reason","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"All servers reconnected successfully"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Reconnect all servers","tags":["servers"]}},"/api/v1/servers/restart_all":{"post":{"description":"Restart all configured upstream MCP servers sequentially with partial failure handling","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/management.BulkOperationResult"}}},"description":"Bulk restart results with success/failure counts"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Restart all servers","tags":["servers"]}},"/api/v1/servers/{id}":{"delete":{"description":"Remove an MCP upstream server from the configuration. This stops the server if running and removes it from config.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server removed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Remove an upstream server","tags":["servers"]},"patch":{"description":"Update specific fields of an existing upstream MCP server configuration.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.AddServerRequest"}}},"description":"Fields to update (all optional)","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server updated successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request - no fields or invalid body"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Partially update an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/config-to-secret":{"post":{"description":"Atomically reads the real value from the server config, stores it in the OS keyring, and rewrites the config field to ` + "`" + `${keyring:\u003cname\u003e}` + "`" + `. Unblocks the UI's Convert-to-secret affordance for values the API redacts on the read path.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":{},"type":"object"}}},"description":"Secret stored, config updated with reference"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad scope/key/secret_name, or value is already a reference / empty"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server or key not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Secret resolver or config update failed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Convert a header / env value to a keyring secret","tags":["servers"]}},"/api/v1/servers/{id}/disable":{"post":{"description":"Disable a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server disabled successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Disable an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/discover-tools":{"post":{"description":"Manually trigger tool discovery and indexing for a specific upstream MCP server. This forces an immediate refresh of the server's tool cache.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Tool discovery triggered successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot discover tools)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to discover tools"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Discover tools for a specific server","tags":["servers"]}},"/api/v1/servers/{id}/enable":{"post":{"description":"Enable a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server enabled successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/login":{"post":{"description":"Initiate OAuth authentication flow for a specific upstream MCP server. Returns structured OAuth start response with correlation ID for tracking.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.OAuthStartResponse"}}},"description":"OAuth login initiated successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.OAuthFlowError"}}},"description":"OAuth error (client_id required, DCR failed, etc.)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Trigger OAuth login for server","tags":["servers"]}},"/api/v1/servers/{id}/logout":{"post":{"description":"Clear OAuth authentication token and disconnect a specific upstream MCP server. The server will need to re-authenticate before tools can be used again.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"OAuth logout completed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (management disabled or read-only mode)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Clear OAuth token and disconnect server","tags":["servers"]}},"/api/v1/servers/{id}/logs":{"get":{"description":"Retrieve log entries for a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Number of log lines to retrieve","in":"query","name":"tail","schema":{"default":100,"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServerLogsResponse"}}},"description":"Server logs retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server logs","tags":["servers"]}},"/api/v1/servers/{id}/quarantine":{"post":{"description":"Place a specific upstream MCP server in quarantine to prevent tool execution","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server quarantined successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Quarantine a server","tags":["servers"]}},"/api/v1/servers/{id}/refresh":{"post":{"description":"Re-discover and re-index a specific upstream MCP server's tools without changing any security state. Alias of discover-tools, named for the upstream_servers 'refresh' operation; use it to make just-approved tools searchable immediately.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Tool refresh triggered successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot refresh)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to refresh tools"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Refresh a server's tools","tags":["servers"]}},"/api/v1/servers/{id}/restart":{"post":{"description":"Restart the connection to a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server restarted successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Restart an upstream server","tags":["servers"]}},"/api/v1/servers/{id}/tool-calls":{"get":{"description":"Retrieves tool call history filtered by upstream server ID. Returns recent tool executions for the specified server including timestamps, arguments, results, and errors. Useful for server-specific debugging and monitoring.","parameters":[{"description":"Upstream server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}},{"description":"Maximum number of records to return (1-100, default 50)","in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServerToolCallsResponse"}}},"description":"Server tool calls retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get server tool calls"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call history for specific server","tags":["tool-calls"]}},"/api/v1/servers/{id}/tools":{"get":{"description":"Retrieve all available tools for a specific upstream MCP server","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetServerToolsResponse"}}},"description":"Server tools retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/block":{"post":{"description":"Atomically approves AND disables the given tools (or all pending/changed tools when block_all=true) for a server. The approve and disable land in a single write per tool, so a tool is never left in the approved+enabled state. The \"blocked\" field counts tools actually blocked.","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Block result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Block (approve+disable) tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/disable_all":{"post":{"description":"Bulk-toggles every known tool of a server. The \"changed\" field","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Operation result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable or disable all tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/tools/enable_all":{"post":{"description":"Bulk-toggles every known tool of a server. The \"changed\" field","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Operation result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Enable or disable all tools for a server","tags":["servers"]}},"/api/v1/servers/{id}/unquarantine":{"post":{"description":"Remove a specific upstream MCP server from quarantine to allow tool execution","parameters":[{"description":"Server ID or name","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ServerActionResponse"}}},"description":"Server unquarantined successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (missing server ID)"},"403":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Forbidden (agent tokens cannot mutate servers)"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Server not found"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Unquarantine a server","tags":["servers"]}},"/api/v1/sessions":{"get":{"description":"Retrieves paginated list of active and recent MCP client sessions. Each session represents a connection from an MCP client to MCPProxy, tracking initialization time, tool calls, and connection status.","parameters":[{"description":"Maximum number of sessions to return (1-100, default 10)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Number of sessions to skip for pagination (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Filter by session status","in":"query","name":"status","schema":{"enum":["active","closed"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetSessionsResponse"}}},"description":"Sessions retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Invalid status filter"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get sessions"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get active MCP sessions","tags":["sessions"]}},"/api/v1/sessions/{id}":{"get":{"description":"Retrieves detailed information about a specific MCP client session including initialization parameters, connection status, tool call count, and activity timestamps.","parameters":[{"description":"Session ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetSessionDetailResponse"}}},"description":"Session details retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Session ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Session not found"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get MCP session details by ID","tags":["sessions"]}},"/api/v1/stats/tokens":{"get":{"description":"Retrieve token savings statistics across all servers and sessions","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Token statistics"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get token savings statistics","tags":["stats"]}},"/api/v1/status":{"get":{"description":"Get comprehensive server status including running state, listen address, upstream statistics, and timestamp","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Server status information"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get server status","tags":["status"]}},"/api/v1/telemetry/payload":{"get":{"description":"Render the exact JSON heartbeat payload that mcpproxy would next send to the telemetry endpoint, without making a network call. Counters in the payload reflect the current in-memory state. Spec 042.","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Telemetry heartbeat payload"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Telemetry service unavailable"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Preview next telemetry heartbeat payload","tags":["telemetry"]}},"/api/v1/telemetry/update-failure":{"post":{"description":"Records one terminal update-session failure, identified only by its\nstage (appcast, download, install, other). The body carries no error\ntext, URL, or version — the stage is the only value transmitted.\nReturns 204 both when the occurrence was durably persisted and when\ntelemetry is inactive at event time (config opt-out, environment\nopt-out, CI, or dev build), in which case nothing is recorded.\nCallers cannot and need not distinguish the two.","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/httpapi.UpdateFailureRequest"}}},"description":"Update failure stage","required":true},"responses":{"204":{"description":"Accepted (recorded, or a deliberate no-op while telemetry is inactive)"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Malformed body, unknown field, trailing value, or stage outside the closed set"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Persistence failure"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Record a desktop auto-update failure occurrence (Spec 095)","tags":["telemetry"]}},"/api/v1/tool-calls":{"get":{"description":"Retrieves paginated tool call history across all upstream servers or filtered by session ID. Includes execution timestamps, arguments, results, and error information for debugging and auditing.","parameters":[{"description":"Maximum number of records to return (1-100, default 50)","in":"query","name":"limit","schema":{"type":"integer"}},{"description":"Number of records to skip for pagination (default 0)","in":"query","name":"offset","schema":{"type":"integer"}},{"description":"Filter tool calls by MCP session ID","in":"query","name":"session_id","schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetToolCallsResponse"}}},"description":"Tool calls retrieved successfully"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to get tool calls"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call history","tags":["tool-calls"]}},"/api/v1/tool-calls/{id}":{"get":{"description":"Retrieves detailed information about a specific tool call execution including full request arguments, response data, execution time, and any errors encountered.","parameters":[{"description":"Tool call ID","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GetToolCallDetailResponse"}}},"description":"Tool call details retrieved successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call ID required"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"404":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call not found"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Get tool call details by ID","tags":["tool-calls"]}},"/api/v1/tool-calls/{id}/replay":{"post":{"description":"Re-executes a previous tool call with optional modified arguments. Useful for debugging and testing tool behavior with different inputs. Creates a new tool call record linked to the original.","parameters":[{"description":"Original tool call ID to replay","in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ReplayToolCallRequest"}}},"description":"Optional modified arguments for replay"},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ReplayToolCallResponse"}}},"description":"Tool call replayed successfully"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Tool call ID required or invalid JSON payload"},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Unauthorized - missing or invalid API key"},"405":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Method not allowed"},"429":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Shed by a concurrency limit (Retry-After header carries the wait hint)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Failed to replay tool call"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Replay a tool call","tags":["tool-calls"]}},"/api/v1/tools":{"get":{"description":"Consolidated, read-only listing of all tools from every configured server (including disabled servers and disabled/config-denied tools), enriched with approval state and 30-day usage. Backs the global Tools page and the CLI global ` + "`" + `tools list` + "`" + ` (spec 050, issue #437).","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.GlobalToolsResponse"}}},"description":"All tools across all servers"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Could not enumerate servers"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"List every tool across all servers","tags":["tools"]}},"/api/v1/tools/call":{"post":{"description":"Execute a tool on an upstream MCP server (wrapper around MCP tool calls)","requestBody":{"content":{"application/json":{"schema":{"properties":{"arguments":{"type":"object"},"tool_name":{"type":"string"}},"type":"object"}}},"description":"Tool call request with tool name and arguments","required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.SuccessResponse"}}},"description":"Tool call result"},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Bad request (invalid payload or missing tool name)"},"429":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Shed by a concurrency limit (Retry-After header carries the wait hint)"},"500":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/contracts.ErrorResponse"}}},"description":"Internal server error or tool execution failure"}},"security":[{"ApiKeyAuth":[]},{"ApiKeyQuery":[]}],"summary":"Call a tool","tags":["tools"]}},"/healthz":{"get":{"description":"Get comprehensive health status including all component health (Kubernetes-compatible liveness probe)","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.HealthResponse"}}},"description":"Service is healthy"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.HealthResponse"}}},"description":"Service is unhealthy"}},"summary":"Get health status","tags":["health"]}},"/readyz":{"get":{"description":"Get readiness status including all component readiness checks (Kubernetes-compatible readiness probe)","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.ReadinessResponse"}}},"description":"Service is ready"},"503":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/observability.ReadinessResponse"}}},"description":"Service is not ready"}},"summary":"Get readiness status","tags":["health"]}}}, "openapi": "3.1.0" }` diff --git a/oas/swagger.yaml b/oas/swagger.yaml index b3de0f316..0c3c68faf 100644 --- a/oas/swagger.yaml +++ b/oas/swagger.yaml @@ -1255,6 +1255,10 @@ components: 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_id: description: HTTP request ID for correlation type: string @@ -3446,6 +3450,12 @@ paths: 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 @@ -3657,6 +3667,17 @@ paths: 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 diff --git a/specs/024-expand-activity-log/spec.md b/specs/024-expand-activity-log/spec.md index f1529487b..5a02dfa33 100644 --- a/specs/024-expand-activity-log/spec.md +++ b/specs/024-expand-activity-log/spec.md @@ -38,7 +38,7 @@ As an AI agent developer, I want to see all internal MCPProxy tool calls (retrie 3. **Given** an AI agent calls `call_tool_write` or `call_tool_destructive`, **When** the tool completes, **Then** an activity record is created with intent, target server, tool name, and execution duration 4. **Given** code_execution is enabled and used, **When** code execution completes, **Then** an activity record is created with the code executed, input data, and result summary -**Note on Duplicate Filtering**: Successful `call_tool_*` internal tool calls are excluded by default from activity listings (Web UI, CLI, API) because they appear as duplicates alongside their corresponding upstream `tool_call` entries. Failed `call_tool_*` calls are still shown since they have no corresponding upstream tool call entry. Use `include_call_tool=true` query parameter (API) to show all internal tool calls including successful `call_tool_*`. +**Note on Duplicate Filtering**: All `call_tool_*` internal tool calls are excluded by default from activity listings (Web UI, CLI, API): every one is paired with a canonical record carrying the same request_id — successful and failed calls with the upstream `tool_call` record, concurrency-rejected calls with the limiter's shed record (Spec 093) — and pre-dispatch failures emit only a `tool_call` record, so no `call_tool_*` row is ever the sole witness of a call. Use `include_call_tool=true` query parameter (API) to show them. *(Superseded: failed `call_tool_*` records used to be shown because they were once the only record of a failed dispatch; the dispatch path has emitted a paired `tool_call` record on every outcome since PR #1016.)* --- diff --git a/specs/069-observability-usage-graphs/contracts/usage-endpoint.md b/specs/069-observability-usage-graphs/contracts/usage-endpoint.md index 0c2561dab..29fe8ce05 100644 --- a/specs/069-observability-usage-graphs/contracts/usage-endpoint.md +++ b/specs/069-observability-usage-graphs/contracts/usage-endpoint.md @@ -55,7 +55,7 @@ Auth: `X-API-Key` (REST default). - `token_source: "bytes"` labels the size-based proxy (FR-006); FR-010 will switch this to `"estimated_tokens"`. - `tokens_saved*` echoed from existing `ServerTokenMetrics` (FR-007 / SC-008). - `avg_*` computed over `sized_calls` only (records with `0` bytes excluded); `null`/omitted when `sized_calls == 0`. -- `blocked` counts policy-prevented attempts (persisted as blocked `policy_decision` records, not executed tool_calls). A blocked attempt never ran, so it is **not** included in `calls` and contributes no latency/bytes — it only increments `blocked` and `last_used`. The timeline tracks executed calls and excludes blocked attempts. +- `blocked` counts policy-prevented attempts (persisted as blocked `policy_decision` records, not executed tool_calls). A blocked attempt never ran, so it is **not** included in `calls` and contributes no latency/bytes — it only increments `blocked` and `last_used`. The timeline mirrors the tray glance row-for-row: it counts executed tool calls, blocked attempts (as calls and errors), and mcpproxy's own internal calls (`retrieve_tools`, `describe_tool`, `code_execution`; plus any failed non-management built-in), and excludes `call_tool_*` echo records, management built-ins (`upstream_servers`, `quarantine_security`), and concurrency-rejected sheds. *(Amended by PR #1016 — the timeline previously tracked executed upstream tool_calls only, which left the histogram empty under retrieve_tools/code_execution-heavy traffic; the glance↔timeline parity is pinned by usage_glance_parity_test.go with the Go and Swift admission sets kept in lockstep.)* - `other` present only when the tool list was truncated to `top`. - Empty log → `tools: []`, `timeline: []`, `tokens_saved` from metrics (or 0) — never an error (FR-009 / SC-007). diff --git a/specs/090-tray-glance-v2/data-model.md b/specs/090-tray-glance-v2/data-model.md index df11cda5e..80fe4accd 100644 --- a/specs/090-tray-glance-v2/data-model.md +++ b/specs/090-tray-glance-v2/data-model.md @@ -26,11 +26,11 @@ A maximal run of consecutive qualifying records sharing a group key. | Field | Type | Rule | |-------|------|------| | `records` | `[ActivityEntry]` | newest-first, ≥1 | -| `key` | `(server: String, tool: String, outcomeClass: OutcomeClass)` | grouping key (FR-002) | +| `key` | `(server: String, tool: String, outcomeClass: OutcomeClass, statusClass: StatusClass)` | grouping key (FR-002); `statusClass` ∈ {success, failure, pending} keeps a run homogeneous in outcome | | `count` | `Int` | `records.count`; suffix `×N` rendered when > 1 (FR-003) | -| `newest` | `ActivityEntry` | supplies age; error clause comes from newest *erroring* record (FR-004) | +| `newest` | `ActivityEntry` | supplies age and status; on a failed run it is also the newest erroring record, which supplies the error clause (FR-004) | | `identity` | `String` | `recordKey(oldest)` — stable across head-extension (FR-024) | -| `worstStatus` | `String` | error > success within `.call` runs; `.blocked` runs are uniformly blocked (FR-002/004) | +| `status` | `String` | `newest.status`; every record in the run shares its status class, so there is no worst to pick (FR-004). Was `worstStatus` (error > success within a run) until mixed runs were split | | `displayReason` | `String?` | newest record in run having a reason (FR-004) | Pipeline (FR-001, all in `GlanceSelection`): diff --git a/specs/090-tray-glance-v2/spec.md b/specs/090-tray-glance-v2/spec.md index 6ab725d11..4fc5d49dc 100644 --- a/specs/090-tray-glance-v2/spec.md +++ b/specs/090-tray-glance-v2/spec.md @@ -30,7 +30,7 @@ An agent hammers one tool (e.g. 19 consecutive `jira_get_issue` calls) while wor 1. **Given** the activity feed holds 19 consecutive `jira_get_issue` calls followed by older calls to other tools, **When** the user opens the menu, **Then** the first row reads as one entry with a ×19 count and the remaining rows show the older distinct tools. 2. **Given** a run of identical calls, **When** the row renders, **Then** its age is the age of the newest call in the run. 3. **Given** calls to tool A, then tool B, then tool A again, **When** rows render, **Then** the two A episodes remain separate rows (grouping is consecutive-only, preserving the timeline). -4. **Given** a run of 12 calls where one failed, **When** the row renders, **Then** the row is marked as failed (failure dominates the group) and shows the newest failing call's error clause. +4. **Given** a stretch of 12 consecutive calls to one tool of which 2 consecutive calls failed, **When** the rows render, **Then** the stretch renders as separate runs at each outcome change — the failures form their own row, marked as failed with a ×2 that counts only them and the newest failing call's error clause, and the surrounding successful calls keep their own unmarked rows. 5. **Given** a single (non-repeated) call, **When** the row renders, **Then** no count suffix is shown. 6. **Given** two calls to the same tool separated only by records that never render (management built-ins, collapsed wrapper records), **When** rows render, **Then** the two calls belong to one run — exclusion happens before grouping, so excluded records never split a run. @@ -129,9 +129,10 @@ The Activity (24h) histogram entry sits directly under the summary line, above t **Row pipeline** (pure, unit-testable, in this exact order): - **FR-001**: The row pipeline MUST process fetched records in four ordered steps: (1) qualify records (drop management built-ins and other non-qualifying records), (2) collapse wrapper/upstream record pairs sharing a request identity, (3) group maximal runs of consecutive surviving records sharing the same group key, (4) take the first five groups. Records dropped in steps 1–2 MUST NOT split a run in step 3. -- **FR-002**: The group key MUST be (server, tool, outcome class), where outcome class separates policy blocks from calls: blocked records group only with blocked records; successful and errored calls group together. +- **FR-002**: The group key MUST be (server, tool, outcome class, status class). Outcome class separates policy blocks from calls: blocked records group only with blocked records. Status class separates outcomes: successes group only with successes, failures only with failures, and records that are neither (still running, or any status the tray does not recognize) only with each other. - **FR-003**: A group of N > 1 records MUST render a "×N" suffix; a single-record group renders no suffix. -- **FR-004**: A grouped row MUST derive its age from the newest record of the run, its reason from the newest record in the run that has one, and its status from the worst outcome in the run, ordered error > success. When a run contains an error, the displayed error clause comes from the newest erroring record. +- **FR-004**: A grouped row MUST derive its age from the newest record of the run, its reason from the newest record in the run that has one, and its status from the newest record of the run. Runs never mix success and failure (status class is part of the group key, FR-002), so a failed row's ×N counts only failed records and a successful row's ×N counts only successful ones. When a run is a failed run, the displayed error clause comes from its newest record. + - Superseded: the original rule was "status from the worst outcome in the run, ordered error > success". One failure anywhere in a stretch of calls to the same tool marked the whole stretch failed while the ×N kept counting the successes, so a row reading "×12, failed" could stand for two failures and ten successful calls. The split above is what makes the mark and the count describe the same records. **Reason display**: @@ -177,7 +178,7 @@ The Activity (24h) histogram entry sits directly under the summary line, above t ### Key Entities - **Activity record**: One proxied event — a tool call, internal tool call, or policy decision — with server, tool, outcome, timestamp, optional reason (caller intent or policy block reason), optional error message, and a request identity used for wrapper collapse and live/poll reconciliation (absent only on legacy policy records, which are then never collapsed). -- **Glance run (grouped row)**: A maximal sequence of consecutive qualifying records sharing a group key (server, tool, outcome class), presented as one row with count, newest age, newest available reason, and worst outcome; identified across updates by its oldest record. +- **Glance run (grouped row)**: A maximal sequence of consecutive qualifying records sharing a group key (server, tool, outcome class, status class), presented as one row with count, newest age, newest available reason, and the outcome every record in it shares; identified across updates by its oldest record. - **Client presence**: A deduplicated view of one client application derived from its retained sessions: display name, version, last-activity time, and derived state (active / idle / seen). ## Success Criteria *(mandatory)*