httpapi

package
v0.72.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 54 Imported by: 0

Documentation

Overview

Package httpapi — diagnostics fix endpoint (spec 044).

POST /api/v1/diagnostics/fix runs a registered fixer for a (server, code) tuple. Destructive fixes default to dry_run; the caller must explicitly send mode=execute to mutate state.

Rate-limited to 1 request per second per (server, code) tuple; exceeding the limit returns 429 with Retry-After.

Package httpapi — per-server diagnostics endpoint (spec 044).

GET /api/v1/servers/{id}/diagnostics returns the per-server health status plus, when an active failure is present, a structured diagnostic object with a stable error code, user-facing message, ordered fix steps, and a documentation URL.

Response is designed to be additive — healthy servers return the existing fields with an empty `diagnostic`. No fields are renamed or removed.

Index

Constants

View Source
const (
	IssuanceDecodeUnknownField = "unknown_field"
	IssuanceDecodeWrongType    = "wrong_type"
	IssuanceDecodeSyntax       = "syntax"
	IssuanceDecodeEmpty        = "empty"
	IssuanceDecodeOther        = "other"
)

Issuance decode error kinds.

View Source
const XMCPProxyClientHeader = "X-MCPProxy-Client"

XMCPProxyClientHeader is the HTTP header that clients (CLI, web UI, tray) set so the server can attribute requests to a surface for Tier 2 telemetry. Spec 042 User Story 1.

View Source
const XMCPProxySurfaceHeader = "X-MCPProxy-Surface"

XMCPProxySurfaceHeader names the surface a profile-mutating request comes from (web, macos, cli). Attribution only, never authorization: a caller can set it to anything, so it selects a label on the profile_change record and nothing else.

Variables

This section is empty.

Functions

func ExtractToken added in v0.20.0

func ExtractToken(r *http.Request) string

ExtractToken extracts the authentication token from the request. It checks (in order): X-API-Key header, Authorization: Bearer header, ?apikey= query param. Returns an empty string if no token is found.

func GetBuildVersion

func GetBuildVersion() string

GetBuildVersion returns the build version from build-time variables. This should be set during build using -ldflags.

func GetEdition added in v0.20.2

func GetEdition() string

GetEdition returns the current edition.

func GetLogger

func GetLogger(ctx context.Context) *zap.SugaredLogger

GetLogger retrieves the logger from context, or returns a nop logger if not found

func MergeConfigPatch added in v0.68.0

func MergeConfigPatch(base, patch map[string]interface{}) map[string]interface{}

MergeConfigPatch deep-merges patch into a copy of base and returns the merged document — the exact merge handlePatchConfig performs. Exported so the personal-build round-trip test (Spec 107 FR-040, T010) can drive the PATCH path without an HTTP server.

func ProfilesErrorBody added in v0.70.0

func ProfilesErrorBody(err error) (int, map[string]any)

ProfilesErrorBody maps an error of the profiles service, the clients service or an admin view to the REST error status and the error body WITHOUT the REST envelope (`success` and `request_id`). It is the single mapping behind every profile and client-binding refusal: the REST writers add the envelope, and the MCP `profiles` tool (Spec 108-h) returns the body as its error text, so the two surfaces cannot drift (FR-037).

The keys are {error, code?, field?, used_by?, bindings?, fixes?}. An error the mapping does not know is a 500 {error: "profiles operation failed"}.

func RESTEndpointHistogramMiddleware added in v0.24.0

func RESTEndpointHistogramMiddleware(getReg RegistryGetter) func(http.Handler) http.Handler

RESTEndpointHistogramMiddleware records every REST request under its Chi route template + status class. Templates with path parameters are recorded without the actual parameter values; unmatched routes are recorded under the literal key UNMATCHED. Spec 042 User Story 3.

func RequestIDLoggerMiddleware

func RequestIDLoggerMiddleware(logger *zap.SugaredLogger) func(http.Handler) http.Handler

RequestIDLoggerMiddleware creates a logger with the request ID field and adds it to context. This middleware should be registered AFTER RequestIDMiddleware.

func RequestIDMiddleware

func RequestIDMiddleware(next http.Handler) http.Handler

RequestIDMiddleware extracts or generates a request ID for each request. If the client provides a valid X-Request-Id header, it is used. Otherwise, a new UUID v4 is generated. The request ID is: - Added to the request context - Set in the response header (before calling next handler) - Available for logging via GetRequestID(ctx)

func SetEdition added in v0.20.2

func SetEdition(edition string)

SetEdition sets the edition value (called from main during startup).

func SetupSwaggerHandler

func SetupSwaggerHandler(logger *zap.SugaredLogger, trusted config.TrustedProxiesProvider) http.Handler

SetupSwaggerHandler returns a handler for Swagger UI This is exported so it can be mounted on the main mux. trusted yields the LIVE trusted_proxies list (Spec 107 FR-027): X-Forwarded-Proto/-Host shape the advertised server URL only from a trusted peer; nil trusts nobody.

func SurfaceClassifierMiddleware added in v0.24.0

func SurfaceClassifierMiddleware(getReg RegistryGetter) func(http.Handler) http.Handler

SurfaceClassifierMiddleware reads the X-MCPProxy-Client header and increments the Tier 2 surface counter for the originating client. If the registry getter returns nil, the middleware is a no-op. Spec 042 User Story 1.

func TagRequestMeta added in v0.68.0

func TagRequestMeta(mount reqcontext.Mount, trusted config.TrustedProxiesProvider) func(http.Handler) http.Handler

TagRequestMeta is the edition-neutral request-metadata tag (Spec 107 T050): it stores {ClientIP, Mount} on the context for the audit line PR-D writes. ClientIP is config.ForwardedHeaders(r, trusted).ClientIP — the forwarded address only from a trusted proxy (FR-027), read through the LIVE provider per request — and Mount is fixed by the mount point the middleware is installed on, never by a header. A nil provider trusts nobody.

func WithLogger

func WithLogger(ctx context.Context, logger *zap.SugaredLogger) context.Context

WithLogger adds a logger to the context

Types

type AccessExplanationData added in v0.70.0

type AccessExplanationData = runtime.AccessExplanation

AccessExplanationData is the data of GET /api/v1/access/explain.

type AccessSuggestionsData added in v0.72.0

type AccessSuggestionsData = runtime.AccessSuggestions

AccessSuggestionsData is the data of GET /api/v1/access/suggest.

type AddServerRequest

type AddServerRequest struct {
	Name           string             `json:"name"`
	URL            string             `json:"url,omitempty"`
	Command        string             `json:"command,omitempty"`
	Args           []string           `json:"args,omitempty"`
	Env            map[string]*string `json:"env,omitempty"`
	Headers        map[string]*string `json:"headers,omitempty"`
	WorkingDir     string             `json:"working_dir,omitempty"`
	Protocol       string             `json:"protocol,omitempty"`
	Enabled        *bool              `json:"enabled,omitempty"`
	Quarantined    *bool              `json:"quarantined,omitempty"`
	ReconnectOnUse *bool              `json:"reconnect_on_use,omitempty"`
	// AutoApproveToolChanges is the per-server intent to auto-approve
	// new/changed tools past the trust baseline (MCP-2930). Tri-state *bool:
	// a nil pointer means "leave unchanged" on PATCH; a present value
	// (including false) is applied. Mirrors config.ServerConfig's *bool
	// semantics — do NOT collapse to a plain bool, or an omitted field would
	// silently reset a previously-set value.
	AutoApproveToolChanges *bool `json:"auto_approve_tool_changes,omitempty"`
	// ExposePrompts is the per-server override for prompt aggregation (F9):
	// whether this server's advertised MCP prompts are merged into mcpproxy's
	// prompts/list. Tri-state *bool mirroring config.ServerConfig.ExposePrompts —
	// a nil pointer means "leave unchanged" on PATCH (and "inherit the default
	// aggregate behavior" on create); a present value (including false) is applied.
	ExposePrompts *bool `json:"expose_prompts,omitempty"`
	// ForwardHeaders is the per-server allowlist of inbound MCP client header
	// NAMES forwarded to this server on tools/call (Spec 112). Names only, never
	// values. On PATCH a nil slice (field omitted) leaves the stored allowlist
	// unchanged and an empty array ([]) clears it. Invalid, denied, duplicate
	// and static-header-colliding names are rejected with 400.
	ForwardHeaders []string `json:"forward_headers,omitempty"`
	// TrustMode is the per-server trust tier (spec 086): "auto", "scan", or
	// "manual". Empty means "leave unchanged" on PATCH (and inherit the migrated
	// default on create). A non-empty value is applied to ServerConfig.TrustMode
	// and resolved by EffectiveTrustMode (an unrecognized value fails closed to
	// manual). This is the REST seam for changing the trust tier via
	// POST/PATCH /api/v1/servers.
	TrustMode string `json:"trust_mode,omitempty"`
	// InitTimeout is the per-server MCP `initialize` handshake deadline override
	// (MCP-3322 / GH #760), serialized as a duration string (e.g. "120s"). A nil
	// pointer means "leave unchanged" on PATCH; a present value is applied.
	// Mirrors config.ServerConfig.InitTimeout's *Duration tri-state.
	InitTimeout *config.Duration `json:"init_timeout,omitempty" swaggertype:"string"`
	// MaxConcurrentRequests / QueueSize / QueueTimeout are the per-server
	// concurrency overrides (spec 093 / GH #955, FR-020 scope (c)). Each is
	// tri-state: a nil pointer means "leave unchanged" on PATCH and "inherit
	// server_concurrency_defaults" on create; an explicit 0 disables that
	// setting for this server; a positive value overrides it. Do NOT collapse
	// them to plain values — an omitted field would then silently reset a
	// configured limit.
	MaxConcurrentRequests *int             `json:"max_concurrent_requests,omitempty"`
	QueueSize             *int             `json:"queue_size,omitempty"`
	QueueTimeout          *config.Duration `json:"queue_timeout,omitempty" swaggertype:"string"`
	// Isolation carries per-server Docker isolation overrides (enabled,
	// mode_override, image, network_mode, extra_args, working_dir). A nil
	// pointer means "do not touch isolation config". A present object is
	// applied field-by-field ON TOP of the persisted overrides, so omitting a
	// field leaves it alone; clear an individual override by sending it
	// explicitly (`"enabled": null`, `"image": ""`).
	Isolation *IsolationRequest `json:"isolation,omitempty"`
}

AddServerRequest represents a request to add a new server.

PATCH semantics for the map-typed fields (`headers`, `env`) follow JSON Merge Patch (RFC 7396):

  • A key present with a non-null value upserts that key on the stored map.
  • A key present with a JSON null value deletes that key.
  • A key absent from the request is preserved as-is.

This lets the Web UI / macOS tray edit forms work without seeing the real values of sensitive headers — the backend redacts them on read, the client computes a diff against the redacted state, and only keys that genuinely changed round-trip. Redacted-but-untouched values stay out of the patch entirely, so the backend keeps the real string on disk.

The MCP `upstream_servers patch` tool uses the same `null = delete` convention; the two interfaces are now in sync.

`map[string]*string` is the canonical Go shape for this: encoding/json decodes a missing key into no map entry, a present non-null value into a non-nil `*string`, and a present `null` into a nil `*string`.

POST (add) ignores nil entries — they have no meaning at create time.

type BindingGuardResponse added in v0.70.0

type BindingGuardResponse struct {
	Success   bool             `json:"success"` // Always false
	Error     string           `json:"error"`   // Human-readable, byte-stable refusal text
	Code      string           `json:"code"`    // binding_bypassable_without_auth
	Bindings  []GuardBinding   `json:"bindings"`
	Fixes     []GuardFixOption `json:"fixes"`
	RequestID string           `json:"request_id,omitempty"`
}

BindingGuardResponse is the 409 body of every write refused by the FR-008a binding guard (`binding_bypassable_without_auth`): a superset of the contract `{error, code, bindings, fixes}` carrying the same envelope keys as the other typed 409 (ConnectConflictResponse), so a client reads `error`/`code` the same way everywhere.

type BulkAssignRequest added in v0.70.0

type BulkAssignRequest struct {
	FromProfile *string `json:"from_profile"`
	ToProfile   *string `json:"to_profile"`
	Mode        *string `json:"mode,omitempty"`
}

BulkAssignRequest is the body of POST /clients/bulk-assign.

type BulkAssignResponse added in v0.70.0

type BulkAssignResponse struct {
	Moved   []string            `json:"moved"`
	Skipped []BulkAssignSkipped `json:"skipped"`
}

BulkAssignResponse is the data of POST /clients/bulk-assign.

type BulkAssignSkipped added in v0.70.0

type BulkAssignSkipped = runtime.Skipped

BulkAssignSkipped is a client a bulk assign did not move.

type BundleRollbackRefusedResponse added in v0.72.0

type BundleRollbackRefusedResponse struct {
	Success   bool                    `json:"success"`
	Error     string                  `json:"error"`
	ErrorCode string                  `json:"error_code"`
	Rejection scanner.BundleRejection `json:"rejection"`
	RequestID string                  `json:"request_id,omitempty"`
}

BundleRollbackRefusedResponse is the HTTP 409 body of a well-formed rollback that the scanner refused. ErrorCode is the rejection reason (for example rollback_target_mismatch); last-known-good keeps serving.

type CanonicalConfigPath added in v0.15.1

type CanonicalConfigPath struct {
	Name        string `json:"name"`        // Display name (e.g., "Claude Desktop")
	Format      string `json:"format"`      // Format identifier (e.g., "claude_desktop")
	Path        string `json:"path"`        // Full path to the config file
	Exists      bool   `json:"exists"`      // Whether the file exists
	OS          string `json:"os"`          // Operating system (darwin, windows, linux)
	Description string `json:"description"` // Brief description
}

CanonicalConfigPath represents a well-known config file path

type CanonicalConfigPathsResponse added in v0.15.1

type CanonicalConfigPathsResponse struct {
	OS    string                `json:"os"`    // Current operating system
	Paths []CanonicalConfigPath `json:"paths"` // List of canonical config paths
}

CanonicalConfigPathsResponse represents the response for canonical config paths

type ClientBindingErrorResponse added in v0.70.0

type ClientBindingErrorResponse struct {
	Success   bool   `json:"success"` // Always false
	Error     string `json:"error"`
	Code      string `json:"code,omitempty"`
	Field     string `json:"field,omitempty"`
	RequestID string `json:"request_id,omitempty"`
}

ClientBindingErrorResponse is the 409/400 body of a refused binding write: `code` is no_client_credential (409), `field` names the offending input (400).

type ClientBindingResponse added in v0.70.0

type ClientBindingResponse struct {
	Client   clientPresence  `json:"client"`
	Warnings []ClientWarning `json:"warnings"`
}

ClientBindingResponse is the data of a successful binding write: the full decorated client row and the warnings that concern it (Spec 108-f F17).

type ClientCredentialConflictResponse added in v0.70.0

type ClientCredentialConflictResponse struct {
	Success          bool   `json:"success"` // Always false
	Error            string `json:"error"`
	ConflictingToken string `json:"conflicting_token"`
	Remediation      string `json:"remediation"`
	RequestID        string `json:"request_id,omitempty"`
}

ClientCredentialConflictResponse is the 409 body when the token name client-<id> is held by a grandfathered regular agent token: connect never touches it and mints nothing (FR-021).

type ClientSnippet added in v0.70.0

type ClientSnippet struct {
	GenericHTTP string `json:"generic_http"`
	HeaderName  string `json:"header_name"`
}

ClientSnippet is the paste-ready config of a custom client. The credential is always a header, never a query parameter.

type ClientWarning added in v0.70.0

type ClientWarning = runtime.Warning

ClientWarning is one Clients-surface warning (code, severity, action).

type CodeExecError

type CodeExecError struct {
	Message string `json:"message"`
	Code    string `json:"code"`
}

CodeExecError represents execution error details.

type CodeExecHandler

type CodeExecHandler struct {
	// contains filtered or unexported fields
}

CodeExecHandler handles POST /api/v1/code/exec requests.

func NewCodeExecHandler

func NewCodeExecHandler(toolCaller ToolCaller, logger *zap.SugaredLogger) *CodeExecHandler

NewCodeExecHandler creates a new code execution handler.

func (*CodeExecHandler) ServeHTTP

func (h *CodeExecHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type CodeExecOptions

type CodeExecOptions struct {
	TimeoutMS      *int      `json:"timeout_ms,omitempty"`
	MaxToolCalls   *int      `json:"max_tool_calls,omitempty"`
	AllowedServers *[]string `json:"allowed_servers,omitempty"`
}

CodeExecOptions represents execution options.

Every field is a pointer so the handler can tell an option the caller sent from one they left out. Inferring that from the zero value conflated the two: an explicit "timeout_ms": 0 (out of range, and rejected as such over MCP) was read as "unset" and silently replaced by the configured budget, while an explicit "max_tool_calls": 0 or "allowed_servers": [] was dropped instead of reaching the tool as the caller wrote it.

type CodeExecRequest

type CodeExecRequest struct {
	Code string `json:"code"`
	// Script names a server-side stored script to run instead of Code
	// (Spec 097). Exactly one of Code or Script may be set; the value is a
	// bare name, never a path, and only the code_execution tool resolves it.
	Script   string                 `json:"script,omitempty"`
	Language string                 `json:"language,omitempty"` // "javascript" (default) or "typescript"
	Input    map[string]interface{} `json:"input"`
	Options  CodeExecOptions        `json:"options"`
}

CodeExecRequest represents the request body for code execution.

type CodeExecResponse

type CodeExecResponse struct {
	OK        bool                   `json:"ok"`
	Result    interface{}            `json:"result,omitempty"`
	Error     *CodeExecError         `json:"error,omitempty"`
	Stats     map[string]interface{} `json:"stats,omitempty"`
	RequestID string                 `json:"request_id,omitempty"` // T016: Added for error correlation
}

CodeExecResponse represents the response format.

type CodeScriptsResponse added in v0.57.0

type CodeScriptsResponse struct {
	Scripts []codescripts.Entry `json:"scripts"`
	Dir     string              `json:"dir"`
}

CodeScriptsResponse is the payload of GET /api/v1/code/scripts: every token-valid stored script found next to the active config file, plus the directory they were read from so a caller can see WHERE the daemon looked.

type ConnectConflictResponse added in v0.53.0

type ConnectConflictResponse struct {
	Success bool                  `json:"success"` // Always false
	Data    connect.ConnectResult `json:"data"`    // The full result; its action mirrors the top-level one
	Error   string                `json:"error"`   // Human-readable message
	Action  string                `json:"action"`  // already_exists | precondition_failed
}

ConnectConflictResponse is the 409 body of POST /api/v1/connect/{client}.

It is a typed response rather than the generic error shape because Action is the machine-readable discriminator the contract depends on: "already_exists" means "an entry is there, pass force", "precondition_failed" means "your preview is stale, re-preview". A client that cannot tell them apart either loops forever or forces a write over state the user never saw (research D9), so the field must be visible in the OpenAPI document, not only in prose.

type ConnectRequest added in v0.23.0

type ConnectRequest struct {
	ServerName string `json:"server_name,omitempty"` // Defaults to "mcpproxy"
	Force      bool   `json:"force,omitempty"`       // Overwrite existing entry
	// PreconditionToken is the opaque token from the preview this write was
	// confirmed against (Spec 091 FR-005). When present, the core rechecks it
	// at write time and responds 409 with action "precondition_failed" —
	// writing nothing — if the config or the entry MCPProxy would write has
	// drifted since; the caller then re-previews instead of retrying. Absent
	// means exactly the pre-091 behavior. A replace-classified flow sends this
	// TOGETHER with force=true: the token, not the absence of force, is the
	// overwrite safety.
	PreconditionToken string `json:"precondition_token,omitempty"`

	// Profile, Mode and Keyless are the client-credential intent (Spec 108
	// FR-024). Profile names the profile the client's credential binds to;
	// "" is the built-in All servers scope. Omitted means "not specified": a
	// fresh credential defaults to All servers and a reconnect keeps the
	// client's existing binding (a reconnect never silently widens a locked
	// client). Mode is locked|switchable (default locked for a named profile,
	// switchable for All servers). Keyless writes a credential-less entry and
	// is only possible while require_mcp_auth is off; it cannot carry a
	// profile or mode.
	Profile *string `json:"profile,omitempty"`
	Mode    *string `json:"mode,omitempty"`
	Keyless bool    `json:"keyless,omitempty"`
}

ConnectRequest is the optional JSON body for POST /api/v1/connect/{client}.

type CreateClientRequest added in v0.70.0

type CreateClientRequest struct {
	ID          string  `json:"id"`
	DisplayName string  `json:"display_name,omitempty"`
	Profile     string  `json:"profile,omitempty"`
	Mode        *string `json:"mode,omitempty"`
	// ExpiresIn is a duration like 30d or 720h; default and cap are 365 days.
	ExpiresIn string `json:"expires_in,omitempty"`
	// Purpose is the stated, unenforced task brief (Spec 115), at most 500
	// characters; screened for secrets before anything is stored.
	Purpose string `json:"purpose,omitempty"`
}

CreateClientRequest is the body of POST /api/v1/clients.

type CreateClientResponse added in v0.70.0

type CreateClientResponse struct {
	Client     clientPresence `json:"client"`
	Credential string         `json:"credential"`
	Snippet    ClientSnippet  `json:"snippet"`
}

CreateClientResponse is the data of a successful POST /clients. credential is the secret, shown ONCE.

type CredentialLinks struct {
	Identity       string            `json:"identity"`
	Profile        string            `json:"profile,omitempty"`
	EffectiveTools string            `json:"effective_tools,omitempty"`
	Activity       string            `json:"activity"`
	UIPath         map[string]string `json:"ui_path"`
}

CredentialLinks are the Web UI deep links of an issued credential (Spec 115 UI-007): absolute URLs built from the listen address plus their ui_path forms. No URL carries an API key or a credential.

type EffectiveToolsData added in v0.70.0

type EffectiveToolsData = runtime.EffectiveToolsResult

EffectiveToolsData is the data of GET /api/v1/profiles/{name}/effective-tools.

type EnvFieldPreview added in v0.70.0

type EnvFieldPreview struct {
	Name               string `json:"name"`
	ValuePresent       bool   `json:"value_present"`
	SecretLike         bool   `json:"secret_like"`
	EmptyOrPlaceholder bool   `json:"empty_or_placeholder"`
}

EnvFieldPreview is one env var entry in the import preview.

type ExplainRequest added in v0.70.0

type ExplainRequest struct {
	Client    string
	Token     string
	Profile   string
	Anonymous bool
	Tool      string
}

ExplainRequest is the subject and tool of GET /access/explain: exactly one of Client, Token, Profile and Anonymous.

type FeedbackSubmitter added in v0.22.0

type FeedbackSubmitter interface {
	SubmitFeedback(ctx context.Context, req *telemetry.FeedbackRequest) (*telemetry.FeedbackResponse, error)
}

FeedbackSubmitter is the interface needed for feedback submission. This decouples the HTTP handler from the telemetry package.

type FinalizeClientResponse added in v0.70.0

type FinalizeClientResponse struct {
	Client   clientPresence `json:"client"`
	Rotation RotationState  `json:"rotation"`
}

FinalizeClientResponse is the data of POST /clients/{client}/rotate/finalize.

type ForgetClientResponse added in v0.70.0

type ForgetClientResponse struct {
	Revoked         string `json:"revoked"`
	Disconnected    bool   `json:"disconnected"`
	DisconnectError string `json:"disconnect_error,omitempty"`
}

ForgetClientResponse is the data of DELETE /clients/{client}.

type GuardBinding added in v0.70.0

type GuardBinding struct {
	ClientID  string `json:"client_id"`
	TokenName string `json:"token_name"`
	Profile   string `json:"profile"`
	Mode      string `json:"mode"`
}

GuardBinding names one client binding a guard refusal is about.

type GuardFixOption added in v0.70.0

type GuardFixOption struct {
	Kind   string `json:"kind"`
	Target string `json:"target,omitempty"`
}

GuardFixOption is one remediation of a guard refusal: kind is require_mcp_auth or set_anonymous_profile; target names the profile for the latter and is present only when that profile itself would not leave any binding bypassable.

type HeaderFieldPreview added in v0.70.0

type HeaderFieldPreview struct {
	Name               string `json:"name"`
	ValuePresent       bool   `json:"value_present"`
	SecretLike         bool   `json:"secret_like"`
	EmptyOrPlaceholder bool   `json:"empty_or_placeholder"`
}

HeaderFieldPreview is one header entry in the import preview. Like env previews, it reports whether the source supplied a value without exposing it.

type ImportFieldOverrides added in v0.70.0

type ImportFieldOverrides struct {
	Env     map[string]string
	Headers map[string]string
}

ImportFieldOverrides carries env/header values the caller wants applied to the imported server(s) on an apply (preview=false) call — see ImportRequest.EnvOverride/HeaderOverride for why this exists and how it is kept out of preview responses.

type ImportFromPathRequest added in v0.15.1

type ImportFromPathRequest struct {
	Path        string   `json:"path"`                   // File path to import from
	Format      string   `json:"format,omitempty"`       // Optional format hint
	ServerNames []string `json:"server_names,omitempty"` // Optional: import only these servers
	// Rename maps a server name → new name. Applied after parsing so the
	// caller can disambiguate cross-source name collisions (Spec 046 v2 —
	// e.g. "mcpproxy" → "mcpproxy_claude_code"). Keys are matched against
	// either the raw source name (OriginalName) or the sanitized name shown
	// in the preview (Server.Name); these differ for names that need
	// sanitizing (e.g. "Figma Desktop" → "Figma_Desktop"). Keys not present
	// in the imported set are ignored.
	Rename map[string]string `json:"rename,omitempty"`
}

ImportFromPathRequest represents a request to import from a file path

type ImportRequest added in v0.15.0

type ImportRequest struct {
	Content     string   `json:"content"`                // Raw JSON or TOML content
	Format      string   `json:"format,omitempty"`       // Optional format hint
	ServerNames []string `json:"server_names,omitempty"` // Optional: import only these servers

	// EnvOverride/HeaderOverride (Spec 109 FR-064/065, PR review round 4
	// F-A/F-D fix): the Paste tab's per-field Value/Secret edits — a plain
	// value the user typed, or a keyring ref path if they chose Secret —
	// keyed by field name. Applied to the matching imported server's
	// Env/Headers ONLY when preview=false, directly on the server this
	// request's own raw Content parses to server-side. This is what lets
	// the apply call carry the user's edited env/header values without
	// ever round-tripping the redacted preview: url/command/args on apply
	// always come from re-parsing Content here, never from a client-held
	// preview response, so a credential embedded in a URL query param or
	// argv flag (which the preview necessarily redacted for display) is
	// never overwritten with the masked placeholder.
	EnvOverride    map[string]string `json:"env_override,omitempty"`
	HeaderOverride map[string]string `json:"header_override,omitempty"`

	// AllowPasteFallback opts into detecting a bare URL or a single command
	// line (FR-064) when Format/format detection would otherwise fail — see
	// configimport.ImportOptions.AllowPasteFallback for why this must stay
	// opt-in (review round 4 F-E). Only the interactive Paste tab sets this;
	// every other caller of this endpoint (the general "Import config"
	// panel, or a direct API call) leaves it false and gets a clear
	// "unable to detect configuration format" error for a plain one-liner
	// instead of it being silently guessed at and, on apply, added as a
	// real server with no confirmation step.
	AllowPasteFallback bool `json:"allow_paste_fallback,omitempty"`
}

ImportRequest represents a request to import servers from JSON/TOML content

type ImportResponse added in v0.15.0

type ImportResponse struct {
	Format     string                       `json:"format"`
	FormatName string                       `json:"format_name"`
	Summary    configimport.ImportSummary   `json:"summary"`
	Imported   []ImportedServerResponse     `json:"imported"`
	Skipped    []configimport.SkippedServer `json:"skipped"`
	Failed     []configimport.FailedServer  `json:"failed"`
	Warnings   []string                     `json:"warnings"`
}

ImportResponse represents the response from an import operation

type ImportedServerResponse added in v0.15.0

type ImportedServerResponse struct {
	Name          string   `json:"name"`
	Protocol      string   `json:"protocol"`
	URL           string   `json:"url,omitempty"`
	Command       string   `json:"command,omitempty"`
	Args          []string `json:"args,omitempty"`
	SourceFormat  string   `json:"source_format"`
	OriginalName  string   `json:"original_name"`
	FieldsSkipped []string `json:"fields_skipped,omitempty"`
	Warnings      []string `json:"warnings,omitempty"`

	// Summary, Tags, Env and Headers are the Spec 109 FR-064 preview
	// enrichment (contracts/rest-api.md "Import preview"). Summary and Tags
	// are built from the already-redacted URL/Command/Args above, so a
	// secret embedded in argv or a URL query never reaches Summary either.
	// Env/Headers never carry the raw value — only its presence and two
	// booleans a surface uses to default the Value/Secret toggle (FR-065).
	Summary string               `json:"summary,omitempty"`
	Tags    []string             `json:"tags,omitempty"`
	Env     []EnvFieldPreview    `json:"env,omitempty"`
	Headers []HeaderFieldPreview `json:"headers,omitempty"`
}

ImportedServerResponse represents an imported server in the response

type IsolationRequest added in v0.24.8

type IsolationRequest struct {
	// EnabledOverride is the tri-state per-server override — the RAW value, the
	// same one reads return as `enabled_override`. It has THREE meaningful wire
	// states, and collapsing them is what silently un-isolated servers
	// (GH #1142):
	//   - absent          → leave the persisted override untouched
	//   - null            → clear the override, back to inheriting the global
	//   - true / false    → set an explicit opt-in / opt-out
	EnabledOverride NullableBool `json:"enabled_override,omitempty" swaggertype:"boolean"`
	// Enabled exists ONLY to detect and reject an echoed-back read. It is the
	// effective state on the read surface and is never writable; see validate().
	Enabled NullableBool `json:"enabled,omitempty" swaggertype:"boolean"`
	// ModeOverride sets `isolation.mode` ("docker" | "sandbox" | "none").
	// nil leaves the persisted value alone; an empty string clears it. An
	// unrecognized value is rejected with a 400 rather than persisted.
	ModeOverride *string   `json:"mode_override,omitempty"`
	Image        *string   `json:"image,omitempty"`
	NetworkMode  *string   `json:"network_mode,omitempty"`
	ExtraArgs    *[]string `json:"extra_args,omitempty"`
	WorkingDir   *string   `json:"working_dir,omitempty"`
}

IsolationRequest is the request-body representation of config.IsolationConfig, using pointer fields for PATCH semantics: a nil pointer means "leave this field alone", a present value (including empty string or empty slice) means "set it".

Read and write use DISJOINT key names for the isolation flag, deliberately: on a read, `isolation.enabled` is the EFFECTIVE state (see contracts.IsolationConfig), so a client that GETs a server and PATCHes the isolation object back would otherwise convert "inherits the global setting" into a permanent explicit override — the original bug arriving from the other direction (GH #1142). `enabled` is therefore refused on writes, loudly, rather than being silently applied or silently dropped; the writable key is `enabled_override`, which is also the key reads emit the raw value under.

func (IsolationRequest) MarshalJSON added in v0.64.0

func (r IsolationRequest) MarshalJSON() ([]byte, error)

MarshalJSON drops the tri-state fields the request never set.

NullableBool's own "unset" encoding is `null`, and `null` on the way IN is the clear-the-override shape — so encoding an untouched request with the default marshaller would produce a body that wipes the persisted override (and one that trips the read-only `enabled` check). Deleting the keys keeps "absent" absent, which is the whole point of the tri-state.

It re-encodes through the struct rather than listing the fields again, so a new field cannot silently miss this treatment.

type IssuanceDecodeError added in v0.71.0

type IssuanceDecodeError struct {
	Kind   string
	Field  string
	Offset int64
}

IssuanceDecodeError is a sanitized decode failure: Kind is one of the IssuanceDecode* kinds, Field a KNOWN field name or the fixed placeholder, Offset the byte offset of a syntax error. It never carries decoder text.

func (*IssuanceDecodeError) Error added in v0.71.0

func (e *IssuanceDecodeError) Error() string

type NullableBool added in v0.64.0

type NullableBool struct {
	// Set is true when the key was present in the request body at all.
	Set bool
	// Value is the decoded boolean, or nil when the key was present as `null`.
	Value *bool
}

NullableBool distinguishes an absent JSON key from an explicit `null` and from a real boolean, which a plain *bool cannot do. Used for tri-state PATCH fields where "clear this back to the default" has to be expressible.

func (NullableBool) MarshalJSON added in v0.64.0

func (n NullableBool) MarshalJSON() ([]byte, error)

MarshalJSON encodes the decoded value; an unset or explicitly-null field encodes as `null`. NOTE that `null` is the CLEAR-the-override shape on the way in, so an unset field must not survive a re-marshal — that is what IsolationRequest.MarshalJSON deletes.

func (*NullableBool) UnmarshalJSON added in v0.64.0

func (n *NullableBool) UnmarshalJSON(data []byte) error

UnmarshalJSON records that the key was present, and decodes its value unless it was the literal `null`.

type OnboardingMarkRequest added in v0.29.0

type OnboardingMarkRequest struct {
	// Engaged marks the wizard as engaged (completed or explicitly skipped).
	// Once true, the wizard does not auto-show again.
	Engaged bool `json:"engaged"`

	// ConnectStepStatus is one of: "", "completed", "skipped". Empty
	// preserves the existing value. The stored enum is wider (Spec 080
	// FR-001): a "skipped" request for a previously untouched connect step
	// is upgraded server-side to "completed_external" when the install
	// shows positive evidence of an external connection (Spec 080 FR-002).
	// "completed_external" is NOT accepted from clients — it must never be
	// persisted without that server-verified evidence (edge case: "never
	// guess completed_external without positive evidence").
	ConnectStepStatus string `json:"connect_step_status,omitempty"`

	// ServerStepStatus is one of: "", "completed", "skipped". Empty
	// preserves the existing value.
	ServerStepStatus string `json:"server_step_status,omitempty"`

	// MarkShown records the wizard's first display time if not already set.
	MarkShown bool `json:"mark_shown,omitempty"`

	// ConnectedClientID records a successful connect write for this client id
	// (Spec 109-b FR-042, review round 6). The REST connect endpoint
	// (POST /api/v1/connect/{client}) already records this itself on success;
	// this field exists so `mcpproxy connect` — which writes the client's
	// config file directly, without going through that endpoint, so the
	// command still works when no daemon is running — can relay the same
	// event to a daemon that IS running, keeping ClientConnectedAt in sync
	// across both surfaces. Must be a known id from the fixed connect client
	// registry (internal/connect.GetAllClients); any other value is rejected,
	// matching the field's "bounded by the registry" invariant
	// (data-model.md §7).
	ConnectedClientID string `json:"connected_client_id,omitempty"`

	// DisconnectedClientID relays a successful local CLI disconnect to a running
	// daemon, which cannot observe the CLI's direct config-file edit itself.
	// Like ConnectedClientID, it is bounded to the fixed client registry.
	DisconnectedClientID string `json:"disconnected_client_id,omitempty"`
}

OnboardingMarkRequest is the request body for /api/v1/onboarding/mark endpoints. Each step's status can be set independently, and the wizard can be marked engaged in the same call.

type OnboardingStateResponse added in v0.29.0

type OnboardingStateResponse struct {
	// HasConnectedClient is true if at least one supported AI client currently
	// has mcpproxy registered in its config.
	HasConnectedClient bool `json:"has_connected_client"`

	// HasConfiguredServer is true if at least one upstream MCP server is
	// configured (regardless of current connection health).
	HasConfiguredServer bool `json:"has_configured_server"`

	// ConnectedClientCount is the number of supported clients currently
	// pointing at mcpproxy.
	ConnectedClientCount int `json:"connected_client_count"`

	// ConnectedClientIDs are the identifiers of supported clients currently
	// pointing at mcpproxy. Drawn exclusively from the fixed adapter table —
	// user-entered values never appear here.
	ConnectedClientIDs []string `json:"connected_client_ids"`

	// ConfiguredServerCount is the number of upstream MCP servers configured
	// in mcpproxy (counts both enabled and disabled).
	ConfiguredServerCount int `json:"configured_server_count"`

	// State is the persisted wizard engagement record. Engaged is true once
	// the wizard was shown and the user completed or skipped it.
	State storage.OnboardingState `json:"state"`

	// ShouldShowWizard is the derived flag the frontend uses to decide
	// whether to auto-show. True when not engaged and IncompleteTabCount > 0
	// (Spec 046 v2 — semantics widened to also count the Verify tab).
	ShouldShowWizard bool `json:"should_show_wizard"`

	// FirstMCPClientEver is true once any MCP client has successfully completed
	// an `initialize` round-trip with this mcpproxy. Sourced from the Spec 044
	// activation bucket. Drives the Verify tab's "green check" state.
	FirstMCPClientEver bool `json:"first_mcp_client_ever"`

	// MCPClientsSeenEver is the capped list of recognized client names that
	// have ever called this mcpproxy. Names come from the MCP `initialize`
	// payload's `clientInfo.name` field, sanitized. Surfaces on the Verify tab
	// so the user can see whether their real IDE — not a test client — has
	// connected.
	MCPClientsSeenEver []string `json:"mcp_clients_seen_ever"`

	// IncompleteTabCount is the number of wizard tabs whose state is incomplete.
	// Drives the sidebar Setup entry's badge. Formula:
	//   +1 if HasConnectedClient == false
	//   +1 if HasUsableServer == false
	//   +1 if FirstMCPClientEver == false
	IncompleteTabCount int `json:"incomplete_tab_count"`

	// HasUsableServer is true once at least one enabled, non-quarantined
	// server has usable health and at least one approved (non-disabled) tool.
	// This is the real "the wizard has something to try" signal:
	// HasConfiguredServer only means a server entry exists, even while every
	// one of them sits quarantined, requires sign-in, or has zero approved
	// tools. The Servers step and Setup badge use this instead of
	// HasConfiguredServer, which is kept above for compatibility.
	// HealthStatus.Usable is the shared
	// readiness contract used by every UI surface (Spec 109-c, tasks.md T051).
	HasUsableServer bool `json:"has_usable_server"`

	// UsableServers lists the names behind HasUsableServer, for the Verify
	// step's suggested-prompt generator (FR-042): prompts are only built from
	// tools of servers in this list, never from a quarantined or toolless one.
	UsableServers []string `json:"usable_servers"`
}

OnboardingState is the response shape for GET /api/v1/onboarding/state. It bundles the wizard's two predicates (does the user have any client connected? any server configured?) with the persisted engagement record, so the frontend can decide whether to auto-show the wizard and which steps to render.

type ProfileConflictResponse added in v0.70.0

type ProfileConflictResponse struct {
	Success   bool               `json:"success"` // Always false
	Error     string             `json:"error"`
	Code      string             `json:"code"`
	UsedBy    *ProfileUsedByData `json:"used_by,omitempty"`
	RequestID string             `json:"request_id,omitempty"`
}

ProfileConflictResponse is the 409 body of a refused profile write.

type ProfileDeleteData added in v0.70.0

type ProfileDeleteData = runtime.DeleteResult

ProfileDeleteData is the data of DELETE /api/v1/profiles/{name}.

type ProfileListData added in v0.70.0

type ProfileListData = runtime.ProfileList

ProfileListData is the data of GET /api/v1/profiles.

type ProfileRenameData added in v0.70.0

type ProfileRenameData = runtime.RenameResult

ProfileRenameData is the data of POST /api/v1/profiles/{name}/rename.

type ProfileTryData added in v0.70.0

type ProfileTryData = runtime.TryResult

ProfileTryData is the data of POST /api/v1/profiles/try.

type ProfileUsedByData added in v0.70.0

type ProfileUsedByData = runtime.UsedBy

ProfileUsedByData is what points at a profile (administrators only).

type ProfileViewData added in v0.70.0

type ProfileViewData = runtime.ProfileView

ProfileViewData is the data of GET /api/v1/profiles/{name}.

type ProfileWriteData added in v0.70.0

type ProfileWriteData = runtime.WriteResult

ProfileWriteData is the data of POST /api/v1/profiles and PUT /api/v1/profiles/{name}.

type ProfilesAPI added in v0.70.0

ProfilesAPI is what the /profiles and /access/explain handlers need from the profiles service (Spec 108-f). *runtime.ProfilesService implements it; a test supplies a fake. Keeping it an interface means the handlers' own logic - the administrator gates, the non-administrator omission and redaction, the error mapping - is tested without a runtime behind it.

type PutClientBindingRequest added in v0.70.0

type PutClientBindingRequest struct {
	Profile *string `json:"profile"`
	Mode    *string `json:"mode,omitempty"`
}

PutClientBindingRequest is the body of PUT /api/v1/clients/{client}/binding. Profile is required ("" is the built-in All servers scope). Mode is optional: omitted keeps the credential's current mode, except that profile "" means switchable.

type RegistryGetter added in v0.24.0

type RegistryGetter func() *telemetry.CounterRegistry

RegistryGetter returns the current Tier 2 telemetry registry. Middlewares take a getter rather than the registry directly so the server can install the registry after route setup without re-mounting middlewares.

type RenameProfileRequest added in v0.70.0

type RenameProfileRequest struct {
	NewName string `json:"new_name"`
}

RenameProfileRequest is the body of POST /profiles/{name}/rename.

type RotateClientRequest added in v0.70.0

type RotateClientRequest struct {
	// PreconditionToken is the token of GET /connect/{client}/preview; it
	// binds a supported client's rotation to what the preview showed.
	PreconditionToken string `json:"precondition_token,omitempty"`
}

RotateClientRequest is the optional body of POST /clients/{client}/rotate.

type RotateClientResponse added in v0.70.0

type RotateClientResponse struct {
	Client     clientPresence         `json:"client"`
	Connect    *connect.ConnectResult `json:"connect,omitempty"`
	Credential string                 `json:"credential,omitempty"`
	Snippet    *ClientSnippet         `json:"snippet,omitempty"`
	Rotation   RotationState          `json:"rotation"`
}

RotateClientResponse is the data of POST /clients/{client}/rotate. For a supported client Connect holds the write result and the rotation is already finalized; for a custom client Credential carries the new secret ONCE, with a snippet, and the rotation stays pending until finalized (or 24 h pass).

type RotationState added in v0.70.0

type RotationState struct {
	State string `json:"state"`
}

RotationState is the `rotation` object of a rotate response.

type SecurityController added in v0.24.0

type SecurityController interface {
	ListScanners(ctx context.Context) ([]*scanner.ScannerPlugin, error)
	InstallScanner(ctx context.Context, id string) error
	RemoveScanner(ctx context.Context, id string) error
	ConfigureScanner(ctx context.Context, id string, env map[string]string, dockerImage string) error
	GetScannerStatus(ctx context.Context, id string) (*scanner.ScannerPlugin, error)

	StartScan(ctx context.Context, serverName string, dryRun bool, scannerIDs []string, sourceDir string) (*scanner.ScanJob, error)
	GetScanStatus(ctx context.Context, serverName string) (*scanner.ScanJob, error)
	GetScanStatusByPass(ctx context.Context, serverName string, pass int) (*scanner.ScanJob, error)
	GetScanReport(ctx context.Context, serverName string) (*scanner.AggregatedReport, error)
	CancelScan(ctx context.Context, serverName string) error

	ApproveServer(ctx context.Context, serverName string, force bool, approvedBy string) error
	RejectServer(ctx context.Context, serverName string) error
	CheckIntegrity(ctx context.Context, serverName string) (*scanner.IntegrityCheckResult, error)

	GetSecurityOverview(ctx context.Context) (*scanner.SecurityOverview, error)
	GetScanSummary(ctx context.Context, serverName string) *scanner.ScanSummary

	// DeepScanEnabled reports whether the opt-in deep-scan layer
	// (security.deep_scan.enabled, Spec 077 US3) is currently on. Used to warn
	// when a Docker-based scanner is enabled while the layer that would run it
	// is off (audit FIX 3b).
	DeepScanEnabled() bool

	// Batch scan operations
	ScanAll(ctx context.Context, servers []scanner.ServerStatus, scannerIDs []string) (*scanner.QueueProgress, error)
	GetQueueProgress() *scanner.QueueProgress
	CancelAllScans() error
	IsQueueRunning() bool

	// Scan history
	ListScanHistory(ctx context.Context) ([]scanner.ScanJobSummary, error)
	GetScanReportByJobID(ctx context.Context, jobID string) (*scanner.AggregatedReport, error)

	// TPA signature bundle (Spec 101): status, activation history and the
	// operator mutations (explicit rollback, unpin, reload, refresh).
	BundleStatus() scanner.BundleInfo
	BundleHistory() ([]scanner.TPABundleActivation, error)
	RollbackBundle(req scanner.BundleRollbackRequest) (scanner.BundleInfo, error)
	UnpinBundle() (scanner.BundleInfo, error)
	ReloadBundle() scanner.BundleInfo
	// RefreshBundle runs one joined refresh cycle (file leg then optional
	// fetch leg) and returns the resulting status (Spec 087 FR-004, B20).
	RefreshBundle(ctx context.Context) scanner.BundleInfo
}

SecurityController defines the interface for security scanner operations (Spec 039).

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server provides HTTP API endpoints with chi router

func NewServer

func NewServer(controller ServerController, logger *zap.SugaredLogger, obs *observability.Manager) *Server

NewServer creates a new HTTP API server

func (*Server) ActivityProjector added in v0.68.0

func (s *Server) ActivityProjector() func(*storage.ActivityRecord) contracts.ActivityRecord

ActivityProjector returns the convert+mask composition core GET /activity applies to a storage record before it reaches a caller (Spec 107 T086, contracts/rest-endpoints.md §"user/activity"): the server-edition GET /api/v1/user/activity door holds *storage.ActivityRecord values and has no access to this package's unexported storageToContractActivity/maskActivityPayloads, so this is the one exported seam that lets it emit the same JSON shape and the same masking as the core door for the same record.

It does NOT apply redactForeignIdentity: the projector has no request context, so auth_type/agent_name pass through. That is safe only because its one consumer pre-filters to the caller's own records (filter.UserID); a new consumer that serves other callers' rows must redact them itself.

func (*Server) ClientBindingData added in v0.70.0

func (s *Server) ClientBindingData(ctx context.Context, clientID string) (map[string]any, error)

ClientBindingData is the `data` of PUT /clients/{client}/binding as a generic JSON object ({client, warnings}): the decorated client row after a change and the warnings that concern it (F17).

func (*Server) ClientsListData added in v0.70.0

func (s *Server) ClientsListData(ctx context.Context, profileFilter, clientFilter string) (map[string]any, error)

ClientsListData is the `data` of GET /clients?profile=&client= as a generic JSON object ({clients, routing, warnings}). The MCP `profiles` tool's list_clients returns it without routing and the config paths (Spec 108-h, H3).

func (*Server) ClientsSupported added in v0.70.0

func (s *Server) ClientsSupported() bool

ClientsSupported reports whether this edition has per-client credentials: the personal edition does, the server edition answers "client not found".

func (*Server) CredentialSnippet added in v0.71.0

func (s *Server) CredentialSnippet(secret string) ClientSnippet

CredentialSnippet is the paste-ready config for an issued credential: the X-API-Key header snippet POST /clients returns (Spec 115 FR-004).

func (s *Server) CredentialUILinks(client, token, profileName string) CredentialLinks

CredentialUILinks builds the deep links for a client (client != "") or a token, bound or pinned to profileName.

func (*Server) EffectiveToolsData added in v0.70.0

func (s *Server) EffectiveToolsData(ctx context.Context, name, client, server, reason string) (*internalRuntime.EffectiveToolsResult, error)

EffectiveToolsData is GET /profiles/{name}/effective-tools for an administrator. client evaluates that client's credential under the profile; it is refused as unknown where the edition has no client credentials.

func (*Server) ExplainAccess added in v0.70.0

ExplainAccess is GET /access/explain for an administrator.

func (*Server) MCPEndpoint added in v0.71.0

func (s *Server) MCPEndpoint() string

MCPEndpoint is this instance's MCP endpoint URL (never carries a key).

func (*Server) ProfileListData added in v0.70.0

func (s *Server) ProfileListData(ctx context.Context) (*internalRuntime.ProfileList, error)

ProfileListData is GET /profiles for an administrator.

func (*Server) ProfileViewData added in v0.70.0

func (s *Server) ProfileViewData(ctx context.Context, name string) (*internalRuntime.ProfileView, error)

ProfileViewData is GET /profiles/{name} for an administrator.

func (*Server) Router added in v0.21.0

func (s *Server) Router() *chi.Mux

Router returns the underlying chi.Mux for external route registration. This is used by the server edition to mount OAuth routes outside the default API key authentication group.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler

func (*Server) SetClientsService added in v0.70.0

func (s *Server) SetClientsService(svc *internalRuntime.ClientsService)

SetClientsService configures the clients service behind the client binding route and the connect credential path (Spec 108).

func (*Server) SetConnectService added in v0.23.0

func (s *Server) SetConnectService(svc *connect.Service)

SetConnectService configures the client connect/disconnect service.

func (*Server) SetCredentialsService added in v0.71.0

func (s *Server) SetCredentialsService(svc *internalRuntime.CredentialsService)

SetCredentialsService configures the Spec 115 credential lifecycle service behind POST/DELETE /api/v1/tokens and POST /api/v1/clients.

func (*Server) SetFeedbackSubmitter added in v0.22.0

func (s *Server) SetFeedbackSubmitter(submitter FeedbackSubmitter)

SetFeedbackSubmitter configures the feedback submission handler (Spec 036).

func (*Server) SetPatchAfterParseHookForTest added in v0.71.0

func (s *Server) SetPatchAfterParseHookForTest(fn func(serverName string))

SetPatchAfterParseHookForTest installs the PATCH /api/v1/servers/{id} after-parse seam (Spec 116 T001). Test-only.

func (*Server) SetProfilesService added in v0.70.0

func (s *Server) SetProfilesService(svc ProfilesAPI)

SetProfilesService installs the profiles service behind the /profiles routes.

func (*Server) SetSecurityController added in v0.24.0

func (s *Server) SetSecurityController(ctrl SecurityController)

SetSecurityController configures the security scanner controller on the server. This must be called after NewServer and before serving requests to enable the /api/v1/security endpoints.

func (*Server) SetSensitiveMasker added in v0.61.0

func (s *Server) SetSensitiveMasker(detector *security.Detector)

SetSensitiveMasker configures the detector used to mask secrets out of payloads on their way to a client. Its per-category switches decide what counts as a secret; its `enabled` flag does not gate masking (see Detector.MaskText). Never calling this leaves payloads unmasked.

func (*Server) SetSessionPrincipalResolver added in v0.68.0

func (s *Server) SetSessionPrincipalResolver(f SessionPrincipalResolver)

SetSessionPrincipalResolver installs the session-principal hook. Only the server edition calls this (internal/serveredition/setup.go via internal/server/serveredition_wire.go); the personal build never does, so s.sessionPrincipalResolver stays nil and every cookie/bearer-JWT credential is refused exactly as it is today.

func (*Server) SetTelemetryPayloadProvider added in v0.24.0

func (s *Server) SetTelemetryPayloadProvider(fn func() *telemetry.Service)

SetTelemetryPayloadProvider attaches a provider that returns the live telemetry service. Used by the /api/v1/telemetry/payload endpoint to render the next heartbeat payload with runtime stats. Spec 042.

func (*Server) SetTelemetryRegistry added in v0.24.0

func (s *Server) SetTelemetryRegistry(reg *telemetry.CounterRegistry)

SetTelemetryRegistry attaches the Tier 2 counter registry. Spec 042. Must be called before the router serves requests for the surface and REST endpoint counters to populate.

func (*Server) SetTokenStore added in v0.20.0

func (s *Server) SetTokenStore(store TokenStore, dataDir string)

SetTokenStore configures agent token management on the server. This must be called after NewServer and before serving requests to enable the /api/v1/tokens endpoints.

func (*Server) SuggestAccess added in v0.72.0

SuggestAccess is GET /access/suggest for an administrator.

type ServerController

type ServerController interface {
	IsRunning() bool
	IsReady() bool
	GetListenAddress() string
	GetUpstreamStats() map[string]interface{}
	StartServer(ctx context.Context) error
	StopServer() error
	GetStatus() interface{}
	StatusChannel() <-chan interface{}
	EventsChannel() <-chan internalRuntime.Event
	// SubscribeEvents creates a new per-client event subscription channel.
	// Each SSE client should get its own channel to avoid competing for events.
	SubscribeEvents() chan internalRuntime.Event
	// UnsubscribeEvents closes and removes the subscription channel.
	UnsubscribeEvents(chan internalRuntime.Event)
	// Attention returns the current needs-attention list (Spec 109 FR-001).
	Attention() []contracts.AttentionItem

	// Server management
	GetAllServers() ([]map[string]interface{}, error)
	AddServer(ctx context.Context, serverConfig *config.ServerConfig) error // T001: Add server
	RemoveServer(ctx context.Context, serverName string) error              // T002: Remove server
	UpdateServer(ctx context.Context, serverName string, updates *config.ServerConfig) error
	EnableServer(serverName string, enabled bool) error
	GetToolApprovalStatus(serverName, toolName string) (string, error)
	// RunPreflight evaluates a required-tools preflight against local state
	// only (Spec 098). The core owns the index/storage/stateview wiring; this
	// interface is the only way the REST layer reaches it — same precedent as
	// GetToolApprovalStatus above.
	RunPreflight(ctx context.Context, params preflight.Params) (preflight.Outcome, error)
	// RecordPreflight persists one preflight run synchronously and returns the
	// write error, so the handler can answer 503 when the durable record
	// required by FR-014 could not be written.
	RecordPreflight(rec internalRuntime.PreflightActivity) error
	RestartServer(serverName string) error
	ForceReconnectAllServers(reason string) error
	GetDockerRecoveryStatus() *storage.DockerRecoveryState
	// IsDockerAvailable reports genuine Docker daemon reachability via a real
	// probe (not the synthetic recovery-state value returned when isolation is
	// off). Used by /api/v1/docker/status — see MCP-2478.
	IsDockerAvailable() bool
	QuarantineServer(serverName string, quarantined bool) error
	GetQuarantinedServers() ([]map[string]interface{}, error)
	UnquarantineServer(serverName string) error
	// GetManagementService returns the unified lifecycle/diagnostics service.
	// Typed, not interface{}: handlers must get a compile-time contract rather
	// than re-deriving a method set with ad-hoc assertions that fail at
	// runtime (ARC-04). May be nil before the service is installed.
	GetManagementService() management.Service
	DiscoverServerTools(ctx context.Context, serverName string) error

	// Tools and search
	GetServerTools(serverName string) ([]map[string]interface{}, error)
	SearchTools(query string, limit int) ([]map[string]interface{}, error)
	// SearchToolsScoped is SearchTools filtered to servers inScope admits
	// BEFORE the ranked cut (Spec 107 T075a): the top-`limit` of an exhaustive
	// search filtered to the caller's entitlement, with unfiltered scores.
	SearchToolsScoped(query string, limit int, inScope func(serverName string) bool) ([]map[string]interface{}, error)

	// Logs
	GetServerLogs(serverName string, tail int) ([]contracts.LogEntry, error)

	// Config and OAuth
	ReloadConfiguration() error
	GetConfigPath() string
	GetLogDir() string
	TriggerOAuthLogin(serverName string) error

	// Secrets management
	GetSecretResolver() *secret.Resolver
	// GetCurrentConfig returns the live config snapshot, or nil when none is
	// installed. Typed so apiKeyAuthMiddleware cannot be handed a value it
	// fails to recognise and then wave through unauthenticated (SEC-02).
	GetCurrentConfig() *config.Config
	NotifySecretsChanged(ctx context.Context, operation, secretName string) error

	// Tool call history. The ToolCallScope argument is the caller's server
	// entitlement (nil = unrestricted, #1166 follow-up); it is passed DOWN
	// rather than applied to the result because these reads also report a
	// `total`, and a post-filter would leave the total counting records the
	// page no longer contains.
	GetToolCalls(limit, offset int, scope storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error)
	GetToolCallByID(id string) (*contracts.ToolCallRecord, error)
	GetServerToolCalls(serverName string, limit int) ([]*contracts.ToolCallRecord, error)
	ReplayToolCall(ctx context.Context, id string, arguments map[string]interface{}) (*contracts.ToolCallRecord, error)
	GetToolCallsBySession(sessionID string, limit, offset int, scope storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error)

	// Session management. status filters on session status ("active" /
	// "closed"); an empty string means no filter.
	GetRecentSessions(f storage.SessionFilter) ([]*contracts.MCPSession, int, error)
	GetSessionByID(sessionID string) (*contracts.MCPSession, error)

	// Configuration management
	ValidateConfig(cfg *config.Config) ([]config.ValidationError, error)
	ApplyConfig(cfg *config.Config, cfgPath string) (*internalRuntime.ConfigApplyResult, error)
	GetConfig() (*config.Config, error)
	// DefaultInstructions returns the built-in default MCP instructions text
	// (independent of any user-configured custom value), so /api/v1/status can
	// surface it to the Web UI as the instructions placeholder (MCP-2176).
	DefaultInstructions() string

	// Token statistics
	GetTokenSavings() (*contracts.ServerTokenMetrics, error)

	// Tool execution
	CallTool(ctx context.Context, toolName string, arguments map[string]interface{}) (interface{}, error)

	// Registry browsing (Phase 7)
	ListRegistries() ([]interface{}, error)
	// SearchRegistryServers returns the registry's servers plus a cache
	// freshness indicator (spec 070 FR-007). A registry requiring an
	// unconfigured key surfaces as a wrapped registries.ErrRegistryKeyMissing.
	SearchRegistryServers(registryID, tag, query string, limit int) ([]interface{}, *contracts.RegistryCacheInfo, error)
	// RefreshRegistryCache drops a registry's cached server lists (FR-007).
	RefreshRegistryCache(registryID string) (int, error)
	// AddServerFromRegistryRef resolves a registry reference server-side and
	// persists it quarantined (spec 070 keystone). On failure it returns a
	// stable cross-surface error code (*contracts.RegistryAddError) alongside
	// the raw error so the handler can map code → HTTP status.
	AddServerFromRegistryRef(ctx context.Context, registryID, serverID, name string, env map[string]string, enabled *bool) (*config.ServerConfig, *contracts.RegistryAddError, error)
	// AddRegistrySourceRef adds a user-supplied generic registry source
	// (MCP-866), always tagged custom/unverified. On failure it returns a stable
	// cross-surface error code alongside the raw error.
	AddRegistrySourceRef(url, protocol, id, name string) (*config.RegistryEntry, *contracts.RegistryAddError, error)
	// RemoveRegistrySourceRef removes a user-added custom registry source
	// (MCP-1057). Built-ins are refused (registry_shadows_builtin) and an unknown
	// id yields registry_not_found. On failure it returns a stable cross-surface
	// error code alongside the raw error.
	RemoveRegistrySourceRef(id string) (*config.RegistryEntry, *contracts.RegistryAddError, error)
	// EditRegistrySourceRef updates a user-added custom registry source
	// (MCP-1072): name, url, servers-url. Built-ins are refused
	// (registry_shadows_builtin), an unknown id yields registry_not_found, and a
	// non-https url yields invalid_registry_url. On failure it returns a stable
	// cross-surface error code alongside the raw error.
	EditRegistrySourceRef(id, name, url, serversURL string) (*config.RegistryEntry, *contracts.RegistryAddError, error)

	// Version and updates
	GetVersionInfo() *updatecheck.VersionInfo
	RefreshVersionInfo() *updatecheck.VersionInfo
	// RecordUpdateFailure records one desktop auto-update failure occurrence
	// (Spec 095) as the diagnostics code matching stage. It evaluates the
	// telemetry gate and performs the durable increment behind ONE call so the
	// handler cannot observe a gate/record race. recorded=false means the gate
	// was closed at event time (config opt-out, env opt-out, CI, dev build) and
	// nothing was persisted — a deliberate no-op, not a failure.
	RecordUpdateFailure(stage string) (recorded bool, err error)
	// UpdatePolicy reports the effective update policy (Spec 092 FR-015).
	// Separate from GetVersionInfo because that one returns nil BOTH when
	// checking is disabled and when no result exists yet — the tray must be
	// able to tell those apart before deciding whether it may run its own
	// feed check.
	UpdatePolicy() updatecheck.Policy

	// Activity logging (RFC-003)
	ListActivities(filter storage.ActivityFilter) ([]*storage.ActivityRecord, int, error)
	GetActivity(id string) (*storage.ActivityRecord, error)
	StreamActivities(ctx context.Context, filter storage.ActivityFilter) <-chan *storage.ActivityRecord
	// AggregateToolUsage rolls up tool_call activity per (server,tool) since the
	// given time. Backs the global tools page usage columns (spec 050).
	AggregateToolUsage(since time.Time) (map[string]storage.ToolUsageStat, error)
	// UsageSnapshot returns the actor-owned in-memory usage aggregate snapshot
	// (spec 069 A2). The /api/v1/activity/usage endpoint reads it without a
	// full-log scan (SC-005). May be nil before the activity service is ready.
	UsageSnapshot() *internalRuntime.UsageAggregate

	// Tool-level quarantine (Spec 032)
	ListToolApprovals(serverName string) ([]*storage.ToolApprovalRecord, error)
	ApproveTools(serverName string, toolNames []string, approvedBy string) error
	ApproveAllTools(serverName string, approvedBy string) (int, error)
	// ApproveToolsReviewed / ApproveAllToolsReviewed are the review-bound
	// forms (Spec 117 PR-2, #1566): expected maps tool name to the review
	// fingerprint the client showed; nil is an unbound (legacy) request. A
	// mismatch returns *toolreview.StaleToolReviewError and writes nothing.
	ApproveToolsReviewed(serverName string, toolNames []string, expected map[string]string, approvedBy string) (int, error)
	ApproveAllToolsReviewed(serverName string, expected map[string]string, approvedBy string) (int, error)
	// BlockTools / BlockAllTools atomically approve+disable tools (MCP-2198):
	// all-or-nothing so a tool is never left approved+enabled.
	BlockTools(serverName string, toolNames []string, blockedBy string) (int, error)
	BlockAllTools(serverName string, blockedBy string) (int, error)
	GetToolApproval(serverName, toolName string) (*storage.ToolApprovalRecord, error)

	// Onboarding wizard (Spec 046)
	GetOnboardingState() (*storage.OnboardingState, error)
	SaveOnboardingState(state *storage.OnboardingState) error
	// UpdateOnboardingState runs fn against the current onboarding state and
	// persists it atomically (Spec 109-b, T035): every writer of the record
	// must use this instead of a separate Get+Save pair, so a concurrent
	// writer's field is never dropped.
	UpdateOnboardingState(fn func(*storage.OnboardingState) error) error

	// Activation state (Spec 044) — read-only access used by the v2
	// onboarding wizard's Verify tab to detect whether any MCP client has
	// successfully called this mcpproxy. Returns FirstMCPClientEver and
	// MCPClientsSeenEver from the activation bucket.
	GetActivationFirstMCPClient() (firstEver bool, seen []string)
}

ServerController defines the interface for core server functionality

type ServerNameLister added in v0.20.0

type ServerNameLister interface {
	GetAllServers() ([]map[string]interface{}, error)
}

ServerNameLister provides the list of known server names for allowed_servers validation.

type ServerPatcher added in v0.71.0

type ServerPatcher interface {
	PatchServer(ctx context.Context, serverName string, resolve func(cur *config.ServerConfig) (*config.ServerConfig, error)) error
}

ServerPatcher is implemented by controllers that resolve a partial server update inside their config commit (Spec 116 FR-006). resolve receives a copy of the LIVE entry read under the commit lock and returns the update to apply; an error from it aborts the commit with nothing written.

type SessionPrincipalResolver added in v0.68.0

type SessionPrincipalResolver func(r *http.Request, kind auth.CredentialKind, value string) (*auth.AuthContext, error)

SessionPrincipalResolver resolves a session credential — a cookie value or a bearer JWT — to an AuthContext (Spec 107 US4, contracts/entitlement-predicate.md §4). It is installed by the server edition (internal/serveredition/setup.go); nil in the personal build, which keeps today's behaviour: neither the cookie nor a non-admin/non-agent bearer authenticates anything.

Returns (nil, nil) when value is not a valid principal for kind (never a principal for that request) — the caller must then answer 401, not fall through to another credential source. An error is a resolution FAILURE (store unavailable), also handled as "not authenticated" by the caller.

type SetActiveProfileRequest added in v0.46.0

type SetActiveProfileRequest struct {
	Profile       *string `json:"profile,omitempty"`
	ActiveProfile *string `json:"active_profile,omitempty"`
}

SetActiveProfileRequest is the body of PUT /api/v1/profiles/active. Either "profile" or "active_profile" may be supplied; an empty string clears the default selection (back to all servers).

type StaleReviewErrorResponse added in v0.71.0

type StaleReviewErrorResponse struct {
	Success    bool             `json:"success"`
	Error      string           `json:"error"`
	ErrorCode  string           `json:"error_code"`
	StaleTools StaleToolsDetail `json:"stale_tools"`
	RequestID  string           `json:"request_id,omitempty"`
}

StaleReviewErrorResponse is the HTTP 409 body of an approval bound to an out-of-date review (Spec 117 PR-2, #1566). The error text contains "out of date" and never "dangerous", so clients reload the review instead of offering a force approval.

type StaleToolsDetail added in v0.71.0

type StaleToolsDetail struct {
	Changed       []string `json:"changed"`
	Unreviewed    []string `json:"unreviewed"`
	MissingBlocks []string `json:"missing_blocks"`
}

StaleToolsDetail lists why a review-bound approval was refused (Spec 117 FR-008). Every list is always present, possibly empty.

type SuggestRequest added in v0.72.0

type SuggestRequest struct {
	Since   string
	Profile string
	Token   string
	Patch   bool
}

SuggestRequest is the query of GET /access/suggest: Since is a duration (90m, 24h, 7d; empty = 24h); Profile and Token narrow the run; Patch adds the proposed profile documents.

type TokenStore added in v0.20.0

type TokenStore interface {
	CreateAgentToken(token auth.AgentToken, rawToken string, hmacKey []byte) error
	ListAgentTokens() ([]auth.AgentToken, error)
	GetAgentTokenByName(name string) (*auth.AgentToken, error)
	RevokeAgentToken(name string) error
	DeleteAgentToken(name string) error
	RegenerateAgentToken(name string, newRawToken string, hmacKey []byte) (*auth.AgentToken, error)
	ValidateAgentToken(rawToken string, hmacKey []byte) (*auth.AgentToken, error)
	// UpdateAgentTokenLastUsedByHash is keyed by the token's HMAC hash, not by
	// its name: names are unique only within an owner in the server edition,
	// so a by-name stamp could land on another tenant's token.
	UpdateAgentTokenLastUsedByHash(hash string) error
}

TokenStore defines the storage interface for agent token CRUD operations. This interface is satisfied by *storage.Manager.

type ToolCaller

type ToolCaller interface {
	CallTool(ctx context.Context, toolName string, arguments map[string]interface{}) (interface{}, error)
}

ToolCaller interface for calling tools (subset of ServerController).

type TryProfileRequest added in v0.70.0

type TryProfileRequest struct {
	Profile config.ProfileConfig `json:"profile"`
	Query   string               `json:"query"`
	Limit   int                  `json:"limit,omitempty"`
}

TryProfileRequest is the body of POST /profiles/try.

type UndoConnectRequest added in v0.47.0

type UndoConnectRequest struct {
	ServerName string `json:"server_name,omitempty"` // Defaults to "mcpproxy"
	// BackupName is the bare filename (filepath.Base) of the backup returned as
	// backup_path by the preceding connect — a name, never a path. Undo resolves
	// the full path server-side by joining it with the client's own config
	// directory, so a client-supplied value can never contribute a directory
	// component (traversal is impossible by construction). Empty means the
	// connect created the file (no prior file existed), so undo removes it.
	BackupName string `json:"backup_name,omitempty"`
}

UndoConnectRequest is the JSON body for POST /api/v1/connect/{client}/undo.

type UpdateFailureRequest added in v0.56.0

type UpdateFailureRequest struct {
	// Stage is the failure stage of the update session.
	Stage string `json:"stage" enums:"appcast,download,install,other"`
}

UpdateFailureRequest is the entire wire body of POST /api/v1/telemetry/update-failure (spec 095 FR-009). One field, one closed enum — the stage is the ONLY failure information that ever leaves the tray, so the decode is strict on both unknown fields and trailing values.

type UpgradeAdminKeyHoldersRequest added in v0.70.0

type UpgradeAdminKeyHoldersRequest struct {
	Profile           *string `json:"profile,omitempty"`
	Mode              *string `json:"mode,omitempty"`
	Apply             bool    `json:"apply,omitempty"`
	PreconditionToken string  `json:"precondition_token,omitempty"`
}

UpgradeAdminKeyHoldersRequest is the body of POST /clients/upgrade-admin-key-holders.

type ViewAsEvaluator added in v0.70.0

type ViewAsEvaluator interface {
	Evaluate(server, tool string) profile.AccessVerdict
}

ViewAsEvaluator answers the access chain for one resolved subject.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL