Documentation
¶
Overview ¶
Package server provides the ServerContext pattern and related infrastructure for the MCP Kubernetes server.
This package implements the core server architecture patterns including:
- ServerContext: Encapsulates all server dependencies and lifecycle management
- Functional Options: Clean dependency injection and configuration
- Logger Interface: Abstraction for logging operations
- Configuration Management: Centralized server configuration
The ServerContext Pattern:
The ServerContext struct follows the context pattern commonly used in Go applications to encapsulate dependencies and provide clean separation of concerns. It includes:
- Kubernetes client interface
- Logger interface
- Configuration settings
- Context for cancellation and timeouts
- Lifecycle management (shutdown, cleanup)
All dependencies are injected using functional options, making the code highly testable and modular. The pattern enables:
- Easy mocking for unit tests
- Runtime configuration flexibility
- Clean dependency management
- Graceful shutdown handling
Example usage:
// Create a server context with custom configuration
ctx := context.Background()
serverCtx, err := NewServerContext(ctx,
WithK8sClient(k8sClient),
WithLogger(customLogger),
WithNonDestructiveMode(true),
WithDefaultNamespace("production"),
WithLogLevel("debug"),
)
if err != nil {
return err
}
defer serverCtx.Shutdown()
// Use the context in MCP tools
client := serverCtx.K8sClient()
logger := serverCtx.Logger()
config := serverCtx.Config()
// Check if server is shutting down
if serverCtx.IsShutdown() {
return ErrServerShutdown
}
Configuration Management:
The Config struct provides centralized configuration with sensible defaults and support for:
- Server identity (name, version)
- Kubernetes settings (default namespace, context, kubeconfig path)
- Non-destructive mode and dry-run settings
- Logging configuration (level, format)
- Security settings (authentication, allowed operations, restricted namespaces)
The configuration supports deep cloning to prevent accidental mutations and follows immutable patterns where possible.
Functional Options Pattern:
The package uses functional options for flexible and extensible configuration:
- WithK8sClient: Inject Kubernetes client
- WithLogger: Inject custom logger
- WithConfig: Provide complete configuration
- WithServerName: Set server name
- WithDefaultNamespace: Set default Kubernetes namespace
- WithNonDestructiveMode: Enable/disable non-destructive mode
- WithDryRun: Enable/disable dry-run mode
- WithLogLevel: Set logging level
- WithAuth: Configure authentication and authorization
- WithRestrictedNamespaces: Set namespace restrictions
This pattern allows for clean composition and makes the API forward-compatible as new options can be added without breaking existing code.
Index ¶
- Variables
- type Config
- type DefaultLogger
- func (l *DefaultLogger) Debug(msg string, args ...interface{})
- func (l *DefaultLogger) Error(msg string, args ...interface{})
- func (l *DefaultLogger) Info(msg string, args ...interface{})
- func (l *DefaultLogger) Warn(msg string, args ...interface{})
- func (l *DefaultLogger) With(args ...interface{}) Logger
- type Logger
- type Option
- func WithAuth(allowedOperations []string) Option
- func WithConfig(config *Config) Option
- func WithDefaultNamespace(namespace string) Option
- func WithDryRun(enabled bool) Option
- func WithK8sClient(client k8s.Client) Option
- func WithLogLevel(level string) Option
- func WithLogger(logger Logger) Option
- func WithNonDestructiveMode(enabled bool) Option
- func WithRestrictedNamespaces(namespaces []string) Option
- func WithServerName(name string) Option
- type ServerContext
- func (sc *ServerContext) Config() *Config
- func (sc *ServerContext) Context() context.Context
- func (sc *ServerContext) GetActiveSessionCount() int
- func (sc *ServerContext) GetActiveSessions() map[string]*k8s.PortForwardSession
- func (sc *ServerContext) IsShutdown() bool
- func (sc *ServerContext) K8sClient() k8s.Client
- func (sc *ServerContext) Logger() Logger
- func (sc *ServerContext) RegisterPortForwardSession(sessionID string, session *k8s.PortForwardSession)
- func (sc *ServerContext) Shutdown() error
- func (sc *ServerContext) StopAllPortForwardSessions() int
- func (sc *ServerContext) StopPortForwardSession(sessionID string) error
- func (sc *ServerContext) UnregisterPortForwardSession(sessionID string)
Constants ¶
This section is empty.
Variables ¶
var ( ErrMissingK8sClient = errors.New("kubernetes client is required") ErrMissingLogger = errors.New("logger is required") ErrMissingConfig = errors.New("configuration is required") ErrServerShutdown = errors.New("server context has been shutdown") )
Error definitions for ServerContext validation and operations.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// Server settings
ServerName string `json:"serverName"`
Version string `json:"version"`
// Kubernetes settings
DefaultNamespace string `json:"defaultNamespace"`
KubeConfigPath string `json:"kubeConfigPath"`
DefaultContext string `json:"defaultContext"`
// Non-destructive mode settings
NonDestructiveMode bool `json:"nonDestructiveMode"`
DryRun bool `json:"dryRun"`
// Logging settings
LogLevel string `json:"logLevel"`
LogFormat string `json:"logFormat"`
// Security settings
EnableAuth bool `json:"enableAuth"`
AllowedOperations []string `json:"allowedOperations"`
RestrictedNamespaces []string `json:"restrictedNamespaces"`
}
Config holds the server configuration.
func NewDefaultConfig ¶
func NewDefaultConfig() *Config
NewDefaultConfig creates a configuration with sensible defaults.
type DefaultLogger ¶
type DefaultLogger struct {
// contains filtered or unexported fields
}
DefaultLogger is a simple logger implementation that wraps the standard library logger.
func (*DefaultLogger) Debug ¶
func (l *DefaultLogger) Debug(msg string, args ...interface{})
Debug logs a debug message.
func (*DefaultLogger) Error ¶
func (l *DefaultLogger) Error(msg string, args ...interface{})
Error logs an error message.
func (*DefaultLogger) Info ¶
func (l *DefaultLogger) Info(msg string, args ...interface{})
Info logs an informational message.
func (*DefaultLogger) Warn ¶
func (l *DefaultLogger) Warn(msg string, args ...interface{})
Warn logs a warning message.
func (*DefaultLogger) With ¶
func (l *DefaultLogger) With(args ...interface{}) Logger
With returns a new logger with additional context fields.
type Logger ¶
type Logger interface {
// Info logs an informational message.
Info(msg string, args ...interface{})
// Debug logs a debug message.
Debug(msg string, args ...interface{})
// Warn logs a warning message.
Warn(msg string, args ...interface{})
// Error logs an error message.
Error(msg string, args ...interface{})
// With returns a new logger with additional context fields.
With(args ...interface{}) Logger
}
Logger defines the interface for logging operations.
func NewDefaultLogger ¶
func NewDefaultLogger() Logger
NewDefaultLogger creates a new default logger with standard output.
type Option ¶
type Option func(*ServerContext) error
Option is a functional option for configuring ServerContext.
func WithConfig ¶
WithConfig sets the configuration for the ServerContext.
func WithDefaultNamespace ¶
WithDefaultNamespace sets the default namespace for Kubernetes operations.
func WithK8sClient ¶
WithK8sClient sets the Kubernetes client for the ServerContext.
func WithLogger ¶
WithLogger sets the logger for the ServerContext.
func WithNonDestructiveMode ¶
WithNonDestructiveMode enables or disables non-destructive mode.
func WithRestrictedNamespaces ¶
WithRestrictedNamespaces sets the list of restricted namespaces.
func WithServerName ¶
WithServerName sets the server name in the configuration.
type ServerContext ¶
type ServerContext struct {
// contains filtered or unexported fields
}
ServerContext encapsulates all dependencies needed by the MCP server and provides a clean abstraction for dependency injection and lifecycle management.
func NewServerContext ¶
func NewServerContext(ctx context.Context, opts ...Option) (*ServerContext, error)
NewServerContext creates a new ServerContext with default values. Use the provided functional options to customize the context.
func (*ServerContext) Config ¶
func (sc *ServerContext) Config() *Config
Config returns the server configuration.
func (*ServerContext) Context ¶
func (sc *ServerContext) Context() context.Context
Context returns the server context for cancellation and deadlines.
func (*ServerContext) GetActiveSessionCount ¶ added in v0.0.6
func (sc *ServerContext) GetActiveSessionCount() int
GetActiveSessionCount returns the number of active port forwarding sessions.
func (*ServerContext) GetActiveSessions ¶ added in v0.0.6
func (sc *ServerContext) GetActiveSessions() map[string]*k8s.PortForwardSession
GetActiveSessions returns a copy of all active port forwarding sessions.
func (*ServerContext) IsShutdown ¶
func (sc *ServerContext) IsShutdown() bool
IsShutdown returns true if the server context has been shutdown.
func (*ServerContext) K8sClient ¶
func (sc *ServerContext) K8sClient() k8s.Client
K8sClient returns the Kubernetes client interface.
func (*ServerContext) Logger ¶
func (sc *ServerContext) Logger() Logger
Logger returns the logger interface.
func (*ServerContext) RegisterPortForwardSession ¶ added in v0.0.6
func (sc *ServerContext) RegisterPortForwardSession(sessionID string, session *k8s.PortForwardSession)
RegisterPortForwardSession registers an active port forwarding session for cleanup tracking.
func (*ServerContext) Shutdown ¶
func (sc *ServerContext) Shutdown() error
Shutdown gracefully shuts down the server context. This cancels the context and releases any resources.
func (*ServerContext) StopAllPortForwardSessions ¶ added in v0.0.6
func (sc *ServerContext) StopAllPortForwardSessions() int
StopAllPortForwardSessions stops all active port forwarding sessions.
func (*ServerContext) StopPortForwardSession ¶ added in v0.0.6
func (sc *ServerContext) StopPortForwardSession(sessionID string) error
StopPortForwardSession stops a specific port forwarding session by ID.
func (*ServerContext) UnregisterPortForwardSession ¶ added in v0.0.6
func (sc *ServerContext) UnregisterPortForwardSession(sessionID string)
UnregisterPortForwardSession removes a port forwarding session from tracking.