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
- func ExtractToken(r *http.Request) string
- func GetBuildVersion() string
- func GetEdition() string
- func GetLogger(ctx context.Context) *zap.SugaredLogger
- func MergeConfigPatch(base, patch map[string]interface{}) map[string]interface{}
- func RESTEndpointHistogramMiddleware(getReg RegistryGetter) func(http.Handler) http.Handler
- func RequestIDLoggerMiddleware(logger *zap.SugaredLogger) func(http.Handler) http.Handler
- func RequestIDMiddleware(next http.Handler) http.Handler
- func SetEdition(edition string)
- func SetupSwaggerHandler(logger *zap.SugaredLogger, trusted config.TrustedProxiesProvider) http.Handler
- func SurfaceClassifierMiddleware(getReg RegistryGetter) func(http.Handler) http.Handler
- func TagRequestMeta(mount reqcontext.Mount, trusted config.TrustedProxiesProvider) func(http.Handler) http.Handler
- func WithLogger(ctx context.Context, logger *zap.SugaredLogger) context.Context
- type AddServerRequest
- type CanonicalConfigPath
- type CanonicalConfigPathsResponse
- type CodeExecError
- type CodeExecHandler
- type CodeExecOptions
- type CodeExecRequest
- type CodeExecResponse
- type CodeScriptsResponse
- type ConnectConflictResponse
- type ConnectRequest
- type FeedbackSubmitter
- type ImportFromPathRequest
- type ImportRequest
- type ImportResponse
- type ImportedServerResponse
- type IsolationRequest
- type NullableBool
- type OnboardingMarkRequest
- type OnboardingStateResponse
- type ProfileSummary
- type RegistryGetter
- type SecurityController
- type Server
- func (s *Server) ActivityProjector() func(*storage.ActivityRecord) contracts.ActivityRecord
- func (s *Server) Router() *chi.Mux
- func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *Server) SetConnectService(svc *connect.Service)
- func (s *Server) SetFeedbackSubmitter(submitter FeedbackSubmitter)
- func (s *Server) SetSecurityController(ctrl SecurityController)
- func (s *Server) SetSensitiveMasker(detector *security.Detector)
- func (s *Server) SetSessionPrincipalResolver(f SessionPrincipalResolver)
- func (s *Server) SetTelemetryPayloadProvider(fn func() *telemetry.Service)
- func (s *Server) SetTelemetryRegistry(reg *telemetry.CounterRegistry)
- func (s *Server) SetTokenStore(store TokenStore, dataDir string)
- type ServerController
- type ServerNameLister
- type SessionPrincipalResolver
- type SetActiveProfileRequest
- type TokenStore
- type ToolCaller
- type UndoConnectRequest
- type UpdateFailureRequest
Constants ¶
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.
Variables ¶
This section is empty.
Functions ¶
func ExtractToken ¶ added in v0.20.0
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 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
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 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 ¶
RequestIDLoggerMiddleware creates a logger with the request ID field and adds it to context. This middleware should be registered AFTER RequestIDMiddleware.
func RequestIDMiddleware ¶
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 ¶
WithLogger adds a logger to the context
Types ¶
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"`
// 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 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 CodeExecError ¶
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"`
}
ConnectRequest is the optional JSON body for POST /api/v1/connect/{client}.
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 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
}
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"`
}
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 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"`
}
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 HasConfiguredServer == false
// +1 if FirstMCPClientEver == false
IncompleteTabCount int `json:"incomplete_tab_count"`
}
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 ProfileSummary ¶ added in v0.46.0
type ProfileSummary struct {
Name string `json:"name"`
Servers []string `json:"servers"`
ToolCount int `json:"tool_count"`
}
ProfileSummary is one entry of the GET /api/v1/profiles listing (Profiles v2 T2).
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 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)
}
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 exact 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.
func (*Server) Router ¶ added in v0.21.0
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) SetConnectService ¶ added in v0.23.0
SetConnectService configures the client connect/disconnect service.
func (*Server) SetFeedbackSubmitter ¶ added in v0.22.0
func (s *Server) SetFeedbackSubmitter(submitter FeedbackSubmitter)
SetFeedbackSubmitter configures the feedback submission handler (Spec 036).
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
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
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.
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)
// 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() interface{} // Returns the management service for unified operations
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() interface{}
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(limit int, status string) ([]*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(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)
// 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
// 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
ServerNameLister provides the list of known server names for allowed_servers validation.
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 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 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.
Source Files
¶
- activity.go
- code_exec.go
- code_scripts.go
- concurrency_shed.go
- connect.go
- diagnostics_fix.go
- diagnostics_per_server.go
- doctor_telemetry.go
- feedback.go
- import.go
- middleware.go
- onboarding.go
- preflight.go
- profiles.go
- scope.go
- scope_subtree.go
- security_scanner.go
- server.go
- session_principal.go
- sse_scope.go
- swagger.go
- tokens.go
- update_failure.go