management

package
v0.75.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package management provides unified server lifecycle and diagnostic operations. It consolidates duplicate logic from CLI, REST, and MCP interfaces into a single service layer.

Index

Constants

View Source
const (
	OAuthStorageWarnLiteralKey       = "literal_key"
	OAuthStorageWarnKeyFileInDataDir = "key_file_in_data_dir"
	OAuthStorageWarnPlaintextWithKey = "plaintext_rows_with_key"
	OAuthStorageWarnCompaction       = "compaction_advised"
	OAuthStorageWarnBackupPresent    = "backup_file_present"
)

Warning codes of contracts.OAuthTokenStorageReport.Warnings.

Variables

This section is empty.

Functions

func BuildActivityRetentionReport added in v0.74.0

func BuildActivityRetentionReport(shortfall *storage.RetentionShortfall, window time.Duration) *contracts.ActivityRetentionReport

BuildActivityRetentionReport computes the section.

func BuildOAuthTokenStorageReport added in v0.74.0

func BuildOAuthTokenStorageReport(st OAuthTokenStorageState, visible func(server string) bool, admin bool) *contracts.OAuthTokenStorageReport

BuildOAuthTokenStorageReport computes the section from st. visible filters the rows to the servers the caller may see (nil = all); admin gates the key id, the key-source metadata, the row key ids and every warning: a scoped caller sees counts over its visible servers only (Spec 118 scoping).

func OAuthRowServer added in v0.74.0

func OAuthRowServer(bucketKey string) string

OAuthRowServer names the server of an oauth_tokens bucket key, falling back to the bucket key itself when it has no "<name>_<hash>" shape.

Types

type ActivityRetentionOperations added in v0.74.0

type ActivityRetentionOperations interface {
	// ActivityRetentionState returns the current shortfall record (nil when
	// the caps hold the whole window) and the work-session retention window.
	ActivityRetentionState() (*storage.RetentionShortfall, time.Duration, error)
}

ActivityRetentionOperations is implemented by the runtime (Spec 124 FR-035). The management service reads it through a type assertion, so a runtime that cannot report leaves the section out.

type BulkOperationResult

type BulkOperationResult struct {
	Total      int               `json:"total"`      // Total servers processed
	Successful int               `json:"successful"` // Number of successful operations
	Failed     int               `json:"failed"`     // Number of failed operations
	Errors     map[string]string `json:"errors"`     // Map of server name to error message
}

BulkOperationResult holds the results of a bulk operation across multiple servers.

type EventEmitter

type EventEmitter interface {
	EmitServersChanged(reason string, extra map[string]any)
}

EventEmitter defines the interface for emitting runtime events. This is used by the service to notify subscribers of state changes.

type OAuthTokenStorageOperations added in v0.74.0

type OAuthTokenStorageOperations interface {
	OAuthTokenStorageState() (OAuthTokenStorageState, error)
}

OAuthTokenStorageOperations is implemented by the runtime. The management service reads it through an optional interface so a runtime that cannot report (a test double) simply leaves the section out.

type OAuthTokenStorageState added in v0.74.0

type OAuthTokenStorageState struct {
	// KeyID is the configured key's public id; "" when encryption is off.
	KeyID string
	// KeySource is what the key resolution recorded (kind, inside data dir).
	KeySource config.KeySource
	// Rows classifies every oauth_tokens row.
	Rows []storage.OAuthTokenRow
	// CompactAdvised is the compaction-advised marker.
	CompactAdvised bool
	// BackupPresent is true when config.db.bak exists in the data directory.
	BackupPresent bool
}

OAuthTokenStorageState is the raw material of the section, read by the runtime (or, for `auth tokens status`, by the CLI) at call time. It holds the public key id and key-source metadata only: never the key, never a path.

type RuntimeOperations

type RuntimeOperations interface {
	EnableServer(serverName string, enabled bool) error
	// EnableServerCtx is EnableServer carrying the request context, so the
	// config_change row names the caller (issue #1698).
	EnableServerCtx(ctx context.Context, serverName string, enabled bool) error
	RestartServer(serverName string) error
	// RestartServerCtx is RestartServer carrying the request context (issue
	// #1698): a restart of a disabled server enables it and records who asked.
	RestartServerCtx(ctx context.Context, serverName string) error
	GetAllServers() ([]map[string]interface{}, error)
	BulkEnableServers(serverNames []string, enabled bool) (map[string]error, error)
	GetServerTools(serverName string) ([]map[string]interface{}, error)
	GetToolApproval(serverName, toolName string) (*storage.ToolApprovalRecord, error)
	TriggerOAuthLogin(serverName string) error
	// TriggerOAuthLoginQuick returns browser status immediately (Spec 020 fix)
	TriggerOAuthLoginQuick(serverName string) (*core.OAuthStartResult, error)
	TriggerOAuthLogout(serverName string) error
	RefreshOAuthToken(serverName string) error
}

RuntimeOperations defines the interface for runtime operations needed by the service. This allows the service to delegate to runtime without a direct dependency.

type SecurityScanEnricher added in v0.31.0

type SecurityScanEnricher interface {
	GetSecurityScanSummary(ctx context.Context, serverName string) *contracts.SecurityScanSummary
}

SecurityScanEnricher provides the current security scan summary for a server, shaped for inclusion in contracts.Server.SecurityScan. nil means "no summary yet for this server" (never scanned, no cached result).

ListServers calls this once per server when wired so REST and the SSE servers.changed embed (which goes through runtime.buildServersChangedPayload → lister.ListServers) share one enrichment site. Without that parity, the Web UI's mergeServers (which treats incoming server data as authoritative and deletes absent keys) silently strips security_scan from the store on every SSE delivery — same bug class as the pre-existing quarantine-stats staleness fixed by PR #463.

type Service

type Service interface {

	// ListServers returns all configured servers with their current status and aggregate statistics.
	// This method respects configuration gates but never blocks read operations.
	ListServers(ctx context.Context) ([]*contracts.Server, *contracts.ServerStats, error)

	// GetServerLogs retrieves recent log entries for a specific server.
	// The tail parameter controls how many recent entries to return.
	// Returns empty slice if server doesn't exist or has no logs.
	GetServerLogs(ctx context.Context, name string, tail int) ([]contracts.LogEntry, error)

	// EnableServer enables or disables a specific upstream server.
	// This operation respects disable_management and read_only configuration gates.
	// Emits "servers.changed" event on successful state change.
	EnableServer(ctx context.Context, name string, enabled bool) error

	// RestartServer stops and restarts the connection to a specific upstream server.
	// This operation respects disable_management and read_only configuration gates.
	// Emits "servers.changed" event on successful restart.
	RestartServer(ctx context.Context, name string) error

	// RestartAll restarts all configured servers sequentially.
	// Returns detailed results including success/failure counts and per-server errors.
	// Continues on partial failures, collecting all errors in the result.
	// This operation respects disable_management and read_only configuration gates.
	RestartAll(ctx context.Context) (*BulkOperationResult, error)

	// EnableAll enables all configured servers.
	// Returns detailed results including success/failure counts and per-server errors.
	// This operation respects disable_management and read_only configuration gates.
	EnableAll(ctx context.Context) (*BulkOperationResult, error)

	// DisableAll disables all configured servers.
	// Returns detailed results including success/failure counts and per-server errors.
	// This operation respects disable_management and read_only configuration gates.
	DisableAll(ctx context.Context) (*BulkOperationResult, error)

	// Doctor aggregates health diagnostics from all system components.
	// Returns comprehensive health information including:
	// - Upstream server connection errors
	// - OAuth authentication requirements
	// - Missing secrets referenced in configuration
	// - Docker daemon status (if isolation is enabled)
	// - General runtime warnings
	// Target completion time: <3 seconds for 20 servers.
	Doctor(ctx context.Context) (*contracts.Diagnostics, error)

	// AuthStatus returns detailed OAuth authentication status for a specific server.
	// Returns nil if server doesn't use OAuth or doesn't exist.
	AuthStatus(ctx context.Context, name string) (*contracts.AuthStatus, error)

	// GetServerTools retrieves all available tools for a specific upstream MCP server.
	// Delegates to runtime's GetServerTools() which reads from StateView cache.
	// This is a read-only operation that completes in <10ms (in-memory cache read).
	// Returns empty array if server has no tools.
	// Returns error if server name is empty, server not found, or server not connected.
	GetServerTools(ctx context.Context, name string) ([]map[string]interface{}, error)

	// TriggerOAuthLogin initiates an OAuth 2.x authentication flow for a specific server.
	// Delegates to upstream manager's StartManualOAuth() which launches browser-based flow.
	// This operation respects disable_management and read_only configuration gates.
	// Emits "servers.changed" event on successful OAuth completion.
	// Method returns immediately after starting OAuth flow (actual completion is asynchronous).
	// Returns error if server name is empty, server not found, config gates block operation,
	// or server doesn't support OAuth.
	TriggerOAuthLogin(ctx context.Context, name string) error

	// TriggerOAuthLoginQuick initiates OAuth 2.x authentication flow and returns browser status immediately.
	// Unlike TriggerOAuthLogin which runs fully async, this returns actual browser_opened status.
	// Used by HTTP handler to return accurate OAuthStartResponse (Spec 020 fix).
	TriggerOAuthLoginQuick(ctx context.Context, name string) (*core.OAuthStartResult, error)

	// TriggerOAuthLogout clears OAuth token and disconnects a specific server.
	// This operation respects disable_management and read_only configuration gates.
	// Emits "servers.changed" event on successful logout.
	// Returns error if server name is empty, server not found, config gates block operation,
	// or server doesn't support OAuth.
	TriggerOAuthLogout(ctx context.Context, name string) error

	// LogoutAllOAuth clears OAuth tokens for all OAuth-enabled servers.
	// Returns BulkOperationResult with success/failure counts.
	// This operation respects disable_management and read_only configuration gates.
	LogoutAllOAuth(ctx context.Context) (*BulkOperationResult, error)

	// SetScanSummaryEnricher wires the SecurityScanEnricher used by
	// ListServers to populate Server.SecurityScan. The scanner is constructed
	// later in the boot sequence than the management service, so this is a
	// setter rather than a constructor parameter. Optional — callers without
	// a scanner can skip the call and ListServers will return SecurityScan=nil.
	SetScanSummaryEnricher(e SecurityScanEnricher)

	// AddRuntimeWarningSource registers a producer of free-text findings that
	// Doctor appends to Diagnostics.RuntimeWarnings (and counts in
	// TotalIssues) on every call — the `mcpproxy doctor` seam for
	// configuration findings that are not errors (Spec 107 T052:
	// config.DoctorFindings over the live config; PR-D adds the audit sink's
	// failure counter). Sources are consulted in registration order.
	AddRuntimeWarningSource(source func() []string)
}

Service defines the management interface for all server lifecycle and diagnostic operations. All CLI commands, REST endpoints, and MCP tools delegate to this service.

func NewService

func NewService(
	runtime RuntimeOperations,
	cfg *config.Config,
	configPath string,
	eventEmitter EventEmitter,
	secretResolver *secret.Resolver,
	logger *zap.SugaredLogger,
) Service

NewService creates a new management service with the given dependencies. The runtime parameter should implement RuntimeOperations (typically *runtime.Runtime).

Jump to

Keyboard shortcuts

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