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
- Variables
- func CreateOAuthServer(config OAuthConfig) (*oauth.Server, storage.TokenStore, error)
- 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 Metrics
- type OAuthConfig
- type OAuthHTTPServer
- func (s *OAuthHTTPServer) GetOAuthHandler() *oauth.Handler
- func (s *OAuthHTTPServer) GetOAuthServer() *oauth.Server
- func (s *OAuthHTTPServer) GetTokenStore() storage.TokenStore
- func (s *OAuthHTTPServer) Shutdown(ctx context.Context) error
- func (s *OAuthHTTPServer) Start(addr string, config OAuthConfig) error
- type Option
- func WithAuth(allowedOperations []string) Option
- func WithClientFactory(factory k8s.ClientFactory) Option
- func WithConfig(config *Config) Option
- func WithDefaultNamespace(namespace string) Option
- func WithDownstreamOAuth(enabled bool) 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) ClientFactory() k8s.ClientFactory
- func (sc *ServerContext) Config() *Config
- func (sc *ServerContext) Context() context.Context
- func (sc *ServerContext) DownstreamOAuthEnabled() bool
- 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) K8sClientForContext(ctx context.Context) k8s.Client
- func (sc *ServerContext) Logger() Logger
- func (sc *ServerContext) Metrics() *Metrics
- 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 ¶
const ( // OAuth provider constants OAuthProviderDex = "dex" OAuthProviderGoogle = "google" // DefaultOAuthScopes are the default Google OAuth scopes for Kubernetes management DefaultOAuthScopes = "" /* 142-byte string literal not displayed */ // DefaultRefreshTokenTTL is the default TTL for refresh tokens (90 days) DefaultRefreshTokenTTL = 90 * 24 * time.Hour // DefaultIPRateLimit is the default rate limit for requests per IP (requests/second) DefaultIPRateLimit = 10 // DefaultIPBurst is the default burst size for IP rate limiting DefaultIPBurst = 20 // DefaultUserRateLimit is the default rate limit for authenticated users (requests/second) DefaultUserRateLimit = 100 // DefaultUserBurst is the default burst size for authenticated user rate limiting DefaultUserBurst = 200 // DefaultMaxClientsPerIP is the default maximum number of clients per IP address DefaultMaxClientsPerIP = 10 // DefaultReadHeaderTimeout is the default timeout for reading request headers DefaultReadHeaderTimeout = 10 * time.Second // DefaultWriteTimeout is the default timeout for writing responses (increased for long-running MCP operations) DefaultWriteTimeout = 120 * time.Second // DefaultIdleTimeout is the default idle timeout for keepalive connections DefaultIdleTimeout = 120 * time.Second // DefaultShutdownTimeout is the default timeout for graceful server shutdown DefaultShutdownTimeout = 30 * time.Second )
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 ¶
func CreateOAuthServer ¶ added in v0.0.43
func CreateOAuthServer(config OAuthConfig) (*oauth.Server, storage.TokenStore, error)
CreateOAuthServer creates an OAuth server for use with HTTP transport This allows creating the server before the HTTP server to inject the token store
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 error output.
type Metrics ¶ added in v0.0.43
type Metrics struct {
// OAuth downstream authentication metrics
PerUserAuthSuccess int64 // Successful per-user authentications
PerUserAuthFallback int64 // Fallbacks to service account
BearerClientFailures int64 // Failed bearer client creations
// contains filtered or unexported fields
}
Metrics tracks operational metrics for monitoring
func NewMetrics ¶ added in v0.0.43
func NewMetrics() *Metrics
NewMetrics creates a new Metrics instance
func (*Metrics) GetMetrics ¶ added in v0.0.43
GetMetrics returns a snapshot of current metrics
func (*Metrics) IncrementBearerClientFailures ¶ added in v0.0.43
func (m *Metrics) IncrementBearerClientFailures()
IncrementBearerClientFailures increments the bearer client failure counter
func (*Metrics) IncrementPerUserAuthFallback ¶ added in v0.0.43
func (m *Metrics) IncrementPerUserAuthFallback()
IncrementPerUserAuthFallback increments the fallback counter
func (*Metrics) IncrementPerUserAuthSuccess ¶ added in v0.0.43
func (m *Metrics) IncrementPerUserAuthSuccess()
IncrementPerUserAuthSuccess increments the per-user auth success counter
type OAuthConfig ¶ added in v0.0.43
type OAuthConfig struct {
// BaseURL is the MCP server base URL (e.g., https://mcp.example.com)
BaseURL string
// Provider specifies the OAuth provider: "dex" or "google"
Provider string
// GoogleClientID is the Google OAuth Client ID
GoogleClientID string
// GoogleClientSecret is the Google OAuth Client Secret
GoogleClientSecret string
// DexIssuerURL is the Dex OIDC issuer URL
DexIssuerURL string
// DexClientID is the Dex OAuth Client ID
DexClientID string
// DexClientSecret is the Dex OAuth Client Secret
DexClientSecret string
// DexConnectorID is the optional Dex connector ID to bypass connector selection
DexConnectorID string
// DisableStreaming disables streaming for streamable-http transport
DisableStreaming bool
// DebugMode enables debug logging
DebugMode bool
// EncryptionKey is the AES-256 key for encrypting tokens at rest (32 bytes)
// If empty, tokens are stored unencrypted in memory
EncryptionKey []byte
// RegistrationAccessToken is the token required for client registration
// Required if AllowPublicClientRegistration is false
RegistrationAccessToken string
// AllowPublicClientRegistration allows unauthenticated dynamic client registration
// WARNING: This can lead to DoS attacks. Default: false
AllowPublicClientRegistration bool
// AllowInsecureAuthWithoutState allows authorization requests without state parameter
// WARNING: Disabling this weakens CSRF protection. Default: false
AllowInsecureAuthWithoutState bool
// MaxClientsPerIP limits the number of clients that can be registered per IP
MaxClientsPerIP int
// EnableHSTS enables HSTS header (for reverse proxy scenarios)
EnableHSTS bool
// AllowedOrigins is a comma-separated list of allowed CORS origins
AllowedOrigins string
// Interstitial configures the OAuth success page for custom URL schemes
// If nil, uses the default mcp-oauth interstitial page
Interstitial *oauthserver.InterstitialConfig
}
OAuthConfig holds MCP-specific OAuth configuration Uses the mcp-oauth library's types directly to avoid duplication
type OAuthHTTPServer ¶ added in v0.0.43
type OAuthHTTPServer struct {
// contains filtered or unexported fields
}
OAuthHTTPServer wraps an MCP server with OAuth 2.1 authentication
func NewOAuthHTTPServer ¶ added in v0.0.43
func NewOAuthHTTPServer(mcpServer *mcpserver.MCPServer, serverType string, config OAuthConfig) (*OAuthHTTPServer, error)
NewOAuthHTTPServer creates a new OAuth-enabled HTTP server
func NewOAuthHTTPServerWithServer ¶ added in v0.0.43
func NewOAuthHTTPServerWithServer(mcpServer *mcpserver.MCPServer, serverType string, oauthServer *oauth.Server, tokenStore storage.TokenStore, disableStreaming bool) (*OAuthHTTPServer, error)
NewOAuthHTTPServerWithServer creates a new OAuth-enabled HTTP server with an existing OAuth server
func (*OAuthHTTPServer) GetOAuthHandler ¶ added in v0.0.43
func (s *OAuthHTTPServer) GetOAuthHandler() *oauth.Handler
GetOAuthHandler returns the OAuth handler for testing or direct access
func (*OAuthHTTPServer) GetOAuthServer ¶ added in v0.0.43
func (s *OAuthHTTPServer) GetOAuthServer() *oauth.Server
GetOAuthServer returns the OAuth server for testing or direct access
func (*OAuthHTTPServer) GetTokenStore ¶ added in v0.0.43
func (s *OAuthHTTPServer) GetTokenStore() storage.TokenStore
GetTokenStore returns the token store for downstream OAuth passthrough
func (*OAuthHTTPServer) Shutdown ¶ added in v0.0.43
func (s *OAuthHTTPServer) Shutdown(ctx context.Context) error
Shutdown gracefully shuts down the server
func (*OAuthHTTPServer) Start ¶ added in v0.0.43
func (s *OAuthHTTPServer) Start(addr string, config OAuthConfig) error
Start starts the OAuth-enabled HTTP server
type Option ¶
type Option func(*ServerContext) error
Option is a functional option for configuring ServerContext.
func WithClientFactory ¶ added in v0.0.43
func WithClientFactory(factory k8s.ClientFactory) Option
WithClientFactory sets the client factory for creating per-user Kubernetes clients. This is used for OAuth downstream authentication where each user's OAuth token is used to authenticate with Kubernetes.
func WithConfig ¶
WithConfig sets the configuration for the ServerContext.
func WithDefaultNamespace ¶
WithDefaultNamespace sets the default namespace for Kubernetes operations.
func WithDownstreamOAuth ¶ added in v0.0.43
WithDownstreamOAuth enables downstream OAuth authentication. When enabled and a client factory is set, the server will create per-user Kubernetes clients using the user's OAuth token for authentication. This requires the Kubernetes cluster to be configured to accept the OAuth provider's tokens (e.g., Google OIDC for GKE).
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) ClientFactory ¶ added in v0.0.43
func (sc *ServerContext) ClientFactory() k8s.ClientFactory
ClientFactory returns the client factory for creating per-user clients.
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) DownstreamOAuthEnabled ¶ added in v0.0.43
func (sc *ServerContext) DownstreamOAuthEnabled() bool
DownstreamOAuthEnabled returns true if downstream OAuth authentication is enabled.
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. Note: For OAuth downstream mode, consider using K8sClientForContext instead.
func (*ServerContext) K8sClientForContext ¶ added in v0.0.43
func (sc *ServerContext) K8sClientForContext(ctx context.Context) k8s.Client
K8sClientForContext returns a Kubernetes client appropriate for the request context. If downstream OAuth is enabled and an access token is present in the context, it returns a per-user client using the bearer token. Otherwise, it returns the shared service account client.
func (*ServerContext) Logger ¶
func (sc *ServerContext) Logger() Logger
Logger returns the logger interface.
func (*ServerContext) Metrics ¶ added in v0.0.43
func (sc *ServerContext) Metrics() *Metrics
Metrics returns the metrics tracker.
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.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package middleware provides HTTP middleware for the MCP Kubernetes server.
|
Package middleware provides HTTP middleware for the MCP Kubernetes server. |