Documentation
¶
Overview ¶
Package health provides unified health status calculation for upstream MCP servers.
Package health provides unified health status calculation for upstream MCP servers.
IMPORTANT: These constants are mirrored in TypeScript. When adding or modifying health levels, admin states, or actions, update cmd/generate-types/main.go and regenerate frontend/src/types/contracts.ts by running: go run ./cmd/generate-types
Index ¶
- Constants
- Variables
- func ActionLabel(action string) string
- func CalculateHealth(input HealthCalculatorInput, cfg *HealthCalculatorConfig) *contracts.HealthStatus
- func ExtractMissingSecret(lastError string) string
- func ExtractOAuthConfigError(lastError string) string
- func ExtractOAuthTokenUndecryptable(lastError string) string
- func IsHealthy(health *contracts.HealthStatus, legacyConnected bool) bool
- func IsOAuthTokenUndecryptable(hs *contracts.HealthStatus) bool
- func StatusLabel(status string) string
- type HealthCalculatorConfig
- type HealthCalculatorInput
- type RefreshState
Constants ¶
const ( // CallFailureWindow is the rolling window the recorder keeps. CallFailureWindow = 5 * time.Minute // CallFailureMinSamples is the minimum counted calls before the rate applies. CallFailureMinSamples = 5 // CallFailureRatio is the failure ratio that must be exceeded (strictly). CallFailureRatio = 0.5 )
Call failure rate thresholds (Spec 113 FR-065). Constants, not config.
const ( LevelHealthy = "healthy" LevelDegraded = "degraded" LevelUnhealthy = "unhealthy" )
Health levels
const ( StateEnabled = "enabled" StateDisabled = "disabled" StateQuarantined = "quarantined" )
Admin states
const ( ActionNone = "" ActionLogin = "login" ActionRestart = "restart" ActionEnable = "enable" ActionApprove = "approve" ActionViewLogs = "view_logs" ActionSetSecret = "set_secret" ActionConfigure = "configure" // ActionEditURL is offered when the endpoint itself is unusable — the host // does not resolve, the scheme is unsupported, or the URL is malformed. // Restarting cannot fix any of those; editing the address can. ActionEditURL = "edit_url" )
Actions - suggested remediation for health issues
const ( StatusReady = "ready" StatusConnecting = "connecting" StatusSignInRequired = "sign_in_required" StatusNeedsReview = "needs_review" StatusNeedsSecret = "needs_secret" StatusNeedsConfig = "needs_config" StatusError = "error" StatusDisabled = "disabled" )
Status values - the ONE vocabulary every surface (Web UI, macOS, tray, CLI) renders as text (Spec 109 FR-010/FR-011). Level stays a severity signal for badges/tray coloring only; no renderer may print Level as text.
Variables ¶
var ActionLabels = map[string]string{ ActionLogin: "Sign in", ActionSetSecret: "Add secret", ActionConfigure: "Fix config", ActionEditURL: "Edit URL", ActionApprove: "Review", ActionRestart: "Restart", ActionViewLogs: "View logs", ActionEnable: "Enable", }
ActionLabels is the one label table for a primary button keyed on Actions[0] (Spec 109 FR-014).
var ActionPriority = []string{ ActionLogin, ActionSetSecret, ActionConfigure, ActionEditURL, ActionApprove, ActionRestart, ActionViewLogs, ActionEnable, }
ActionPriority is the fixed cross-surface priority order for entries in HealthStatus.Actions (Spec 109 FR-012). Every branch of CalculateHealth already emits its Actions slice in this order; it is exported so other code (tests, generators) can assert on it without duplicating the literal order.
var StatusLabels = map[string]string{ StatusReady: "Online", StatusConnecting: "Connecting", StatusSignInRequired: "Sign-in required", StatusNeedsReview: "Needs review", StatusNeedsSecret: "Secret required", StatusNeedsConfig: "Needs configuration", StatusError: "Error", StatusDisabled: "Disabled", }
StatusLabels is the one label table for `status`, binding for the Web UI, the macOS window and tray, and the CLI table (Spec 109 FR-014).
var StatusOrder = []string{ StatusReady, StatusConnecting, StatusSignInRequired, StatusNeedsReview, StatusNeedsSecret, StatusNeedsConfig, StatusError, StatusDisabled, }
StatusOrder lists every Status* value in the priority order Spec 109 documents them. Used to iterate StatusLabels deterministically (e.g. code gen).
Functions ¶
func ActionLabel ¶ added in v0.70.0
ActionLabel returns the cross-surface button label for an action value, or "" for ActionNone / an unrecognized value.
func CalculateHealth ¶
func CalculateHealth(input HealthCalculatorInput, cfg *HealthCalculatorConfig) *contracts.HealthStatus
CalculateHealth calculates the unified health status for a server. The algorithm uses a priority-based approach where admin state is checked first, followed by connection state, then OAuth state.
A server that would otherwise report ready/healthy is downgraded to degraded when its rolling tool-call failure rate is high (Spec 113-d). Every other outcome (disabled, quarantined, connecting, unhealthy, OAuth, refresh) takes precedence and is returned untouched.
func ExtractMissingSecret ¶
ExtractMissingSecret extracts the secret name from an error message if the error indicates a missing secret reference (e.g., unresolved environment variable). Returns the secret name or empty string if the error is not about missing secrets.
func ExtractOAuthConfigError ¶
ExtractOAuthConfigError extracts an OAuth configuration error from the error message. Returns the config error description or empty string if not an OAuth config issue.
func ExtractOAuthTokenUndecryptable ¶ added in v0.74.0
ExtractOAuthTokenUndecryptable returns the "stored OAuth token cannot be decrypted: <reason>" sentence from a connection error, or "" when the error is about something else. The sentence ends at the first ';' or newline (the producer appends the ways out after it).
func IsHealthy ¶
func IsHealthy(health *contracts.HealthStatus, legacyConnected bool) bool
IsHealthy returns true if the server is considered healthy. It uses health.level as the source of truth, with a fallback to the legacy connected field for backward compatibility when health is nil.
func IsOAuthTokenUndecryptable ¶ added in v0.74.0
func IsOAuthTokenUndecryptable(hs *contracts.HealthStatus) bool
IsOAuthTokenUndecryptable reports whether hs is the undecryptable-row outcome.
func StatusLabel ¶ added in v0.70.0
StatusLabel returns the cross-surface label for a status value, or the raw value itself if it is not recognized (defensive default; every value CalculateHealth emits is a key of StatusLabels).
Types ¶
type HealthCalculatorConfig ¶
type HealthCalculatorConfig struct {
// ExpiryWarningDuration is the duration before token expiry to show degraded status.
// Default: 1 hour
ExpiryWarningDuration time.Duration
}
HealthCalculatorConfig contains configurable thresholds for health calculation.
func DefaultHealthConfig ¶
func DefaultHealthConfig() *HealthCalculatorConfig
DefaultHealthConfig returns the default health calculator configuration.
type HealthCalculatorInput ¶
type HealthCalculatorInput struct {
// Server identification
Name string
// Admin state
Enabled bool
Quarantined bool
// Connection state
State string // "connected", "connecting", "error", "idle", "disconnected"
Connected bool
LastError string
// HasEndpointURL reports whether this server is addressed by a configured
// URL (an HTTP/SSE server) rather than by a spawned command (stdio). It
// gates ActionEditURL: a stdio server can perfectly well emit "no such
// host" — an npx/uvx install failing to reach its package registry does
// exactly that — and offering "Edit URL" for it would point the user at a
// field that does not exist.
HasEndpointURL bool
// OAuth state (only for OAuth-enabled servers)
OAuthRequired bool
OAuthStatus string // "authenticated", "expired", "error", "none"
TokenExpiresAt *time.Time // When token expires
HasRefreshToken bool // True if refresh token exists
UserLoggedOut bool // True if user explicitly logged out
// CallTimeOAuthRequired is set when a server connected anonymously (no config
// OAuth) and listed tools successfully, but a tool call returned an
// "authorization required" / 401 — i.e. the endpoint enforces OAuth only at
// tools/call time (e.g. Google's sqladmin MCP). The managed client records
// this on a call-time auth failure so we can surface a proactive Sign-in CTA
// instead of reporting the server as fully healthy. MCP-2084.
CallTimeOAuthRequired bool
// Secret/config detection
MissingSecret string // Secret name if unresolved (e.g., "GITHUB_TOKEN")
OAuthConfigErr string // OAuth config error (e.g., "requires 'resource' parameter")
// OAuthTokenUndecryptable is set when the server's stored OAuth row cannot
// be decrypted with the configured key (Spec 123 FR-031): the detail
// sentence ("stored OAuth token cannot be decrypted: <reason>"). The
// connection error carries the same sentence, so it is also derived from
// LastError (ExtractOAuthTokenUndecryptable). Never a login state.
OAuthTokenUndecryptable string
// Tool info
ToolCount int
// RetryStopped reports that automatic reconnection has been permanently
// given up because the classifier proved the failure deterministic (GH
// #1145). It is checked ahead of the generic connection-state branches: a
// parked server IS in "error", but reporting it as an ordinary error hides
// the one thing the user needs to know — that nothing will retry on its own.
RetryStopped bool
// RetryStoppedCode is the stable MCPX_* code that justified stopping.
RetryStoppedCode string
// RetryStoppedReason is the human-readable cause from the diagnostics catalog.
RetryStoppedReason string
// RetryCount is the number of consecutive failed connection attempts, used
// only to say how many were made before giving up.
RetryCount int
// NetworkFailure reports that the server's current Error is a network
// failure (DNS, dial, refused, timeout before any upstream answered):
// mcpproxy retries it automatically and reconnects it as soon as the
// network is back (GH #1929). NextRetryAt is when the next automatic
// attempt is due, nil when unknown.
NetworkFailure bool
NextRetryAt *time.Time
// NetworkGaveUp: the client stopped its regular retries (20 failures) and
// now probes every 30 minutes, besides reconnecting when the network is
// back. The outage then stays an attention item (status error).
NetworkGaveUp bool
// Refresh state (for health status integration - Spec 023)
RefreshState RefreshState // Current refresh state from RefreshManager
RefreshRetryCount int // Number of retry attempts
RefreshLastError string // Human-readable error message
RefreshNextAttempt *time.Time // When next retry will occur
// Rolling tool-call failure rate (Spec 113-d). CallsInWindow counts only
// calls that say something about the upstream (successes and transport/
// HTTP/JSON-RPC/timeout failures); isError tool results and proxy-side
// refusals are excluded by the recorder. DominantCallFailureKind is a short
// label ("timeout", "network", ...) used only in the detail text.
CallsInWindow int
CallFailuresInWindow int
DominantCallFailureKind string
}
HealthCalculatorInput contains all fields needed to calculate health status. This struct normalizes data from different sources (StateView, storage, config).
type RefreshState ¶ added in v0.16.0
type RefreshState int
RefreshState represents the current state of token refresh for health reporting. Mirrors oauth.RefreshState for decoupling.
const ( // RefreshStateIdle means no refresh is pending or in progress. RefreshStateIdle RefreshState = iota // RefreshStateScheduled means a proactive refresh is scheduled at 80% lifetime. RefreshStateScheduled // RefreshStateRetrying means refresh failed and is retrying with exponential backoff. RefreshStateRetrying // RefreshStateFailed means refresh permanently failed (e.g., invalid_grant). RefreshStateFailed )