mcpserver

package
v5.55.2 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: Apache-2.0 Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const BackoffMultiplier = 2.0

BackoffMultiplier is the factor by which the reconnect backoff grows on each consecutive failure.

View Source
const DefaultRemoteTimeout = int(mcpserver.DefaultTimeout / time.Second)

DefaultRemoteTimeout is the default spec.timeout in seconds, the budget of every operation on a server of any type. This value must be kept in sync with the kubebuilder:default annotation in MCPServerSpec.Timeout (see pkg/apis/muster/v1alpha1/mcpserver_types.go).

View Source
const HealthCheckFailureThreshold = 3

HealthCheckFailureThreshold is the number of consecutive failed health probes after which a connected server's client is closed and the server is handed to the reconnect schedule. One failed ping -- a slow backend, a probe that hit a rollout -- must not cost the server its tools; three in a row (90 s at the production interval) mean the connection is dead.

View Source
const RestartGracePeriod = 200 * time.Millisecond

RestartGracePeriod is the pause between stop and start during a restart. This allows time for: - Subprocess cleanup and port release for stdio servers - Connection draining for remote HTTP/SSE servers - Upstream load balancers to detect the disconnect

View Source
const UnreachableThreshold = 3

UnreachableThreshold is the number of consecutive failures before marking a server as unreachable.

Variables

View Source
var InitialBackoff = config.DurationFromEnv("MUSTER_MCPSERVER_INITIAL_BACKOFF", 30*time.Second)

InitialBackoff is the initial retry interval after the first connection failure. Overridable via MUSTER_MCPSERVER_INITIAL_BACKOFF (a Go duration, e.g. "1s") so the integration test harness can recover from transient connect failures without waiting out production backoff.

View Source
var MaxBackoff = config.DurationFromEnv("MUSTER_MCPSERVER_MAX_BACKOFF", 2*time.Minute)

MaxBackoff caps the reconnect backoff of a remote server. The schedule doubles from InitialBackoff on every consecutive failure and stops growing here, so once the upstream heals the server is retried within this bound plus the orchestrator's retry tick, however long the outage lasted. The former 30 minute cap let a 504 window of a few minutes hide a recovery for another 4.5, then 8.5, then 16.5 minutes (issue #1163). Overridable via MUSTER_MCPSERVER_MAX_BACKOFF (a Go duration); a value below InitialBackoff makes every retry wait exactly that long.

Functions

This section is empty.

Types

type Option

type Option func(*Service)

Option configures a Service at construction time.

func WithAuthRequiredHook

func WithAuthRequiredHook(fn func(*api.MCPServer, *mcpserver.AuthRequiredError)) Option

WithAuthRequiredHook registers a function that Start calls synchronously when it encounters a 401, before UpdateState(StateAuthRequired) publishes the state-change event. Work done inside the hook (e.g. registering the server in the aggregator) is therefore visible to all subscribers before the event reaches them.

The hook receives the service's current definition rather than a creation-time snapshot, so registrations reflect configuration updates applied before a restart.

func WithKubernetesMode

func WithKubernetesMode(kubernetesMode bool) Option

WithKubernetesMode tells the service whether muster runs against an apiserver. In Kubernetes mode a stdio definition is refused rather than started, because its subprocess would run inside the muster pod under muster's ServiceAccount (issue #1067).

type Service

type Service struct {
	*services.BaseService
	// contains filtered or unexported fields
}

Service implements the Service interface for MCP server management The MCP client now handles both process management AND MCP communication

func NewService

func NewService(definition *api.MCPServer, opts ...Option) (*Service, error)

NewService creates a new MCP server service

func (*Service) CheckHealth

func (s *Service) CheckHealth(ctx context.Context) (services.HealthStatus, error)

CheckHealth implements HealthChecker. The orchestrator calls it periodically for every connected or running server. A failed probe is counted and returned; at HealthCheckFailureThreshold failures in a row the client is closed and the server moves to Failed with a reconnect due at once, so the orchestrator's retry loop -- the one place that restarts servers -- picks it up on its next tick. A passing probe resets the count.

Not every server has something to probe, and not every error says something about the connection:

  • A server reached with the caller's identity (forwardToken, tokenExchange) or protected by OAuth is served per session; the service holds no shared client after a login synced it to Connected, and the aggregator tracks those connections per session.
  • A server that is not Running/Connected is someone else's: a Stop or Restart closed the client under the probe.
  • A JSON-RPC error reply came from a live server that did not like the request; a context error is muster shutting down, not the backend.

func (*Service) ConfigurationChanged

func (s *Service) ConfigurationChanged(newConfig interface{}) bool

ConfigurationChanged returns true if the new configuration differs from the current one in a way that requires a restart. Description changes are excluded because they are metadata-only and do not affect runtime behavior.

Concurrency: must be called from the reconciler goroutine only; concurrent access to s.definition is not synchronized.

func (*Service) GetConfiguration

func (s *Service) GetConfiguration() interface{}

GetConfiguration returns the MCP server configuration

func (*Service) GetConsecutiveFailures

func (s *Service) GetConsecutiveFailures() int

GetConsecutiveFailures returns the number of consecutive connection failures. Thread-safe.

func (*Service) GetHealthCheckInterval

func (s *Service) GetHealthCheckInterval() time.Duration

GetHealthCheckInterval implements HealthChecker

func (*Service) GetLastAttempt

func (s *Service) GetLastAttempt() *time.Time

GetLastAttempt returns the time of the last connection attempt. This value is preserved after successful connections for diagnostic purposes. Thread-safe.

func (*Service) GetLastFailureHTTPStatus

func (s *Service) GetLastFailureHTTPStatus() int

GetLastFailureHTTPStatus returns the HTTP status the endpoint answered the most recent failed connection attempt with, or 0 when there was no HTTP response or the last attempt succeeded. Thread-safe.

func (*Service) GetLogContext

func (s *Service) GetLogContext() string

GetLogContext returns the logging context for this service

func (*Service) GetMCPClient

func (s *Service) GetMCPClient() interface{}

GetMCPClient returns the MCP client for this service (used by aggregator) This is now much simpler since the client IS the process manager

func (*Service) GetNextRetryAfter

func (s *Service) GetNextRetryAfter() *time.Time

GetNextRetryAfter returns the time after which the next retry should be attempted. Returns nil if no retry is scheduled (either never failed or after successful connection). Thread-safe.

func (*Service) GetServiceData

func (s *Service) GetServiceData() map[string]interface{}

GetServiceData implements ServiceDataProvider

func (*Service) GetServiceType

func (s *Service) GetServiceType() string

GetServiceType returns the service type

func (*Service) IsClientReady

func (s *Service) IsClientReady() bool

IsClientReady returns whether the MCP client is initialized and ready

func (*Service) IsHealthy

func (s *Service) IsHealthy() bool

IsHealthy checks if the MCP server is healthy

func (*Service) IsRunning

func (s *Service) IsRunning() bool

IsRunning checks if the MCP server is running (or connected for remote servers)

func (*Service) IsUnreachable

func (s *Service) IsUnreachable() bool

IsUnreachable returns true if the server is in the unreachable state.

func (*Service) LogDebug

func (s *Service) LogDebug(format string, args ...interface{})

LogDebug logs a debug message with service context

func (*Service) LogError

func (s *Service) LogError(err error, format string, args ...interface{})

LogError logs an error message with service context

func (*Service) LogInfo

func (s *Service) LogInfo(format string, args ...interface{})

LogInfo logs an info message with service context

func (*Service) LogWarn

func (s *Service) LogWarn(format string, args ...interface{})

LogWarn logs a warning message with service context

func (*Service) RecordTokenExchangeOutcome added in v5.28.0

func (s *Service) RecordTokenExchangeOutcome(err error)

RecordTokenExchangeOutcome implements api.TokenExchangeOutcomeRecorder.

A failure that is the server's -- the credentials, the token endpoint, the connector -- fails every caller the same way and is reported the same way, as the server's state: Failed, with the exchange error as the last error and its class as the failure reason.

A token endpoint that did not answer is put on the reconnect backoff with a token endpoint probe due: each retry probes the endpoint (probeTokenEndpoint) and the server returns to Awaiting Session once it answers, with no caller involved. An OAuth error from the endpoint (the credentials, the connector) is not retried: a retry would read Awaiting Session again while every exchange still fails. The server leaves Failed for it on the next successful exchange (recorded here), on a restart (Start clears the failure) or on a spec change. A failure specific to the caller's token is the session's and changes nothing here.

func (*Service) Restart

func (s *Service) Restart(ctx context.Context) error

Restart restarts the MCP server service. This method performs a graceful restart by stopping the service first (if running), waiting a brief grace period, and then starting it again.

func (*Service) Start

func (s *Service) Start(ctx context.Context) error

Start starts the MCP server service by creating and initializing the MCP client The client handles both process startup and MCP protocol initialization

If the server requires OAuth authentication, this method will return an AuthRequiredError containing the OAuth information. The caller should handle this by registering the server in auth_required state with a synthetic tool.

For remote servers, this method tracks consecutive connection failures and transitions to StateUnreachable after UnreachableThreshold failures.

func (*Service) Stop

func (s *Service) Stop(ctx context.Context) error

Stop stops the MCP server service by closing the MCP client The client handles both MCP protocol cleanup and process termination

func (*Service) UpdateConfiguration

func (s *Service) UpdateConfiguration(newConfig interface{}) error

UpdateConfiguration updates the MCP server configuration.

Concurrency: must be called from the reconciler goroutine only; concurrent access to s.definition is not synchronized.

func (*Service) ValidateConfiguration

func (s *Service) ValidateConfiguration() error

ValidateConfiguration validates the MCP server configuration

Jump to

Keyboard shortcuts

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