server

package
v0.0.24 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2025 License: Apache-2.0 Imports: 7 Imported by: 0

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

Constants

This section is empty.

Variables

View Source
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.

func (*Config) Clone

func (c *Config) Clone() *Config

Clone creates a deep copy of the configuration.

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 WithAuth

func WithAuth(allowedOperations []string) Option

WithAuth enables authentication with the specified allowed operations.

func WithConfig

func WithConfig(config *Config) Option

WithConfig sets the configuration for the ServerContext.

func WithDefaultNamespace

func WithDefaultNamespace(namespace string) Option

WithDefaultNamespace sets the default namespace for Kubernetes operations.

func WithDryRun

func WithDryRun(enabled bool) Option

WithDryRun enables or disables dry-run mode.

func WithK8sClient

func WithK8sClient(client k8s.Client) Option

WithK8sClient sets the Kubernetes client for the ServerContext.

func WithLogLevel

func WithLogLevel(level string) Option

WithLogLevel sets the logging level.

func WithLogger

func WithLogger(logger Logger) Option

WithLogger sets the logger for the ServerContext.

func WithNonDestructiveMode

func WithNonDestructiveMode(enabled bool) Option

WithNonDestructiveMode enables or disables non-destructive mode.

func WithRestrictedNamespaces

func WithRestrictedNamespaces(namespaces []string) Option

WithRestrictedNamespaces sets the list of restricted namespaces.

func WithServerName

func WithServerName(name string) Option

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.

Jump to

Keyboard shortcuts

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