httpapi

package
v0.53.0-rc.7 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2026 License: MIT Imports: 43 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 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

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 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) http.Handler

SetupSwaggerHandler returns a handler for Swagger UI This is exported so it can be mounted on the main mux

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 WithLogger

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

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"`
	// 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"`
	// Isolation carries per-server Docker isolation overrides (image,
	// network_mode, extra_args, working_dir, enabled). A nil pointer
	// means "do not touch isolation config"; an empty-but-present
	// object on PATCH intentionally clears the overrides.
	Isolation *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

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"`
	MaxToolCalls   int      `json:"max_tool_calls"`
	AllowedServers []string `json:"allowed_servers"`
}

CodeExecOptions represents execution options.

type CodeExecRequest

type CodeExecRequest struct {
	Code     string                 `json:"code"`
	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 ConnectConflictResponse

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 {
	Enabled     *bool     `json:"enabled,omitempty"`
	Image       *string   `json:"image,omitempty"`
	NetworkMode *string   `json:"network_mode,omitempty"`
	ExtraArgs   *[]string `json:"extra_args,omitempty"`
	WorkingDir  *string   `json:"working_dir,omitempty"`
}

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".

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) 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) SetConnectService added in v0.23.0

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

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) 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.

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)
	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)

	// 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
	GetToolCalls(limit, offset int) ([]*contracts.ToolCallRecord, int, error)
	GetToolCallByID(id string) (*contracts.ToolCallRecord, error)
	GetServerToolCalls(serverName string, limit int) ([]*contracts.ToolCallRecord, error)
	ReplayToolCall(id string, arguments map[string]interface{}) (*contracts.ToolCallRecord, error)
	GetToolCallsBySession(sessionID string, limit, offset int) ([]*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

	// 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

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

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

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)
	UpdateAgentTokenLastUsed(name 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.

Jump to

Keyboard shortcuts

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