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 DetailedHealthResponse
- type FederationHealthStatus
- type HealthChecker
- func (h *HealthChecker) DetailedHealthHandler() http.Handler
- func (h *HealthChecker) IsReady() bool
- func (h *HealthChecker) LivenessHandler() http.Handler
- func (h *HealthChecker) ReadinessHandler() http.Handler
- func (h *HealthChecker) RegisterHealthEndpoints(mux *http.ServeMux)
- func (h *HealthChecker) SetReady(ready bool)
- type HealthResponse
- type InstrumentationHealthCheck
- type Logger
- type ManagementClusterStatus
- 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) SetHealthChecker(hc *HealthChecker)
- func (s *OAuthHTTPServer) Shutdown(ctx context.Context) error
- func (s *OAuthHTTPServer) Start(addr string, config OAuthConfig) error
- type OAuthStorageConfig
- type OAuthStorageType
- 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 WithDownstreamOAuthStrict(enabled bool) Option
- func WithDryRun(enabled bool) Option
- func WithFederationManager(manager federation.ClusterClientManager) Option
- func WithInCluster(enabled bool) Option
- func WithInstrumentationProvider(provider *instrumentation.Provider) Option
- func WithK8sClient(client k8s.Client) Option
- func WithLogLevel(level string) Option
- func WithLogger(logger Logger) Option
- func WithNonDestructiveMode(enabled bool) Option
- func WithOutputConfig(output *OutputConfig) Option
- func WithRestrictedNamespaces(namespaces []string) Option
- func WithServerName(name string) Option
- type OutputConfig
- type ServerContext
- func (sc *ServerContext) ClientFactory() k8s.ClientFactory
- func (sc *ServerContext) Config() *Config
- func (sc *ServerContext) Context() context.Context
- func (sc *ServerContext) DecrementActiveSessions(ctx context.Context)
- func (sc *ServerContext) DownstreamOAuthEnabled() bool
- func (sc *ServerContext) DownstreamOAuthStrictEnabled() bool
- func (sc *ServerContext) FederationEnabled() bool
- func (sc *ServerContext) FederationManager() federation.ClusterClientManager
- func (sc *ServerContext) FederationStats() *federation.ManagerStats
- func (sc *ServerContext) GetActiveSessionCount() int
- func (sc *ServerContext) GetActiveSessions() map[string]*k8s.PortForwardSession
- func (sc *ServerContext) InClusterMode() bool
- func (sc *ServerContext) IncrementActiveSessions(ctx context.Context)
- func (sc *ServerContext) InstrumentationProvider() *instrumentation.Provider
- func (sc *ServerContext) IsShutdown() bool
- func (sc *ServerContext) K8sClient() k8s.Client
- func (sc *ServerContext) K8sClientForContext(ctx context.Context) (k8s.Client, error)
- func (sc *ServerContext) Logger() Logger
- func (sc *ServerContext) OutputConfig() *OutputConfig
- func (sc *ServerContext) RecordK8sOperation(ctx context.Context, operation, resourceType, namespace, status string, ...)
- func (sc *ServerContext) RecordPodOperation(ctx context.Context, operation, namespace, status string, ...)
- 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)
- type ValkeyStorageConfig
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") // ErrOAuthTokenMissing is returned when no OAuth access token is present in the // request context while downstream OAuth strict mode is enabled. ErrOAuthTokenMissing = errors.New("authentication required: no OAuth token present in request") // ErrOAuthClientFailed is returned when the bearer token client cannot be created // (e.g., invalid token format, connection issues) while strict mode is enabled. ErrOAuthClientFailed = errors.New("authentication failed: could not create Kubernetes client with OAuth token") )
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"`
// Output processing settings for fleet-scale operations
Output *OutputConfig `json:"output,omitempty"`
}
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 DetailedHealthResponse ¶ added in v0.0.67
type DetailedHealthResponse struct {
Status string `json:"status"`
Mode string `json:"mode"`
Version string `json:"version,omitempty"`
Uptime string `json:"uptime"`
ManagementCluster *ManagementClusterStatus `json:"management_cluster,omitempty"`
Federation *FederationHealthStatus `json:"federation,omitempty"`
Instrumentation *InstrumentationHealthCheck `json:"instrumentation,omitempty"`
}
DetailedHealthResponse provides comprehensive health information including federation status.
type FederationHealthStatus ¶ added in v0.0.67
type FederationHealthStatus struct {
Enabled bool `json:"enabled"`
CachedClients int `json:"cached_clients"`
}
FederationHealthStatus provides health information about federation functionality.
type HealthChecker ¶ added in v0.0.46
type HealthChecker struct {
// contains filtered or unexported fields
}
HealthChecker provides health check endpoints for Kubernetes probes.
func NewHealthChecker ¶ added in v0.0.46
func NewHealthChecker(sc *ServerContext) *HealthChecker
NewHealthChecker creates a new HealthChecker.
func (*HealthChecker) DetailedHealthHandler ¶ added in v0.0.67
func (h *HealthChecker) DetailedHealthHandler() http.Handler
DetailedHealthHandler returns an HTTP handler for the /healthz/detailed endpoint. This endpoint provides comprehensive health information including federation status.
func (*HealthChecker) IsReady ¶ added in v0.0.46
func (h *HealthChecker) IsReady() bool
IsReady returns whether the server is ready to receive traffic.
func (*HealthChecker) LivenessHandler ¶ added in v0.0.46
func (h *HealthChecker) LivenessHandler() http.Handler
LivenessHandler returns an HTTP handler for the /healthz endpoint. Liveness probes indicate whether the process should be restarted. This should be a simple check that the server process is running.
func (*HealthChecker) ReadinessHandler ¶ added in v0.0.46
func (h *HealthChecker) ReadinessHandler() http.Handler
ReadinessHandler returns an HTTP handler for the /readyz endpoint. Readiness probes indicate whether the server is ready to receive traffic.
func (*HealthChecker) RegisterHealthEndpoints ¶ added in v0.0.46
func (h *HealthChecker) RegisterHealthEndpoints(mux *http.ServeMux)
RegisterHealthEndpoints registers health check endpoints on the given mux.
func (*HealthChecker) SetReady ¶ added in v0.0.46
func (h *HealthChecker) SetReady(ready bool)
SetReady sets the readiness state of the server.
type HealthResponse ¶ added in v0.0.46
type HealthResponse struct {
Status string `json:"status"`
Checks map[string]string `json:"checks,omitempty"`
Version string `json:"version,omitempty"`
}
HealthResponse represents the JSON response for health endpoints.
type InstrumentationHealthCheck ¶ added in v0.0.67
type InstrumentationHealthCheck struct {
Enabled bool `json:"enabled"`
MetricsExporter string `json:"metrics_exporter,omitempty"`
TracingExporter string `json:"tracing_exporter,omitempty"`
}
InstrumentationHealthCheck provides health information about instrumentation.
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 ManagementClusterStatus ¶ added in v0.0.67
type ManagementClusterStatus struct {
Connected bool `json:"connected"`
CAPICRDAvailable bool `json:"capi_crd_available"`
}
ManagementClusterStatus provides health information about the management cluster connection.
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
// InstrumentationProvider is the OpenTelemetry instrumentation provider for metrics/tracing
InstrumentationProvider *instrumentation.Provider
// Storage configures the token storage backend
// Defaults to in-memory storage if not specified
Storage OAuthStorageConfig
}
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) SetHealthChecker ¶ added in v0.0.46
func (s *OAuthHTTPServer) SetHealthChecker(hc *HealthChecker)
SetHealthChecker sets the health checker for health check endpoints.
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 OAuthStorageConfig ¶ added in v0.0.78
type OAuthStorageConfig struct {
// Type is the storage backend type: "memory" or "valkey" (default: "memory")
Type OAuthStorageType
// Valkey configuration (used when Type is "valkey")
Valkey ValkeyStorageConfig
}
OAuthStorageConfig holds configuration for OAuth token storage backend.
type OAuthStorageType ¶ added in v0.0.78
type OAuthStorageType string
OAuthStorageType represents the type of token storage backend.
const ( // OAuthStorageTypeMemory uses in-memory storage (default, not recommended for production) OAuthStorageTypeMemory OAuthStorageType = "memory" // OAuthStorageTypeValkey uses Valkey (Redis-compatible) for persistent storage OAuthStorageTypeValkey OAuthStorageType = "valkey" )
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 WithDownstreamOAuthStrict ¶ added in v0.0.73
WithDownstreamOAuthStrict enables strict mode for downstream OAuth authentication. When strict mode is enabled (the default via CLI), requests without valid OAuth tokens will fail with an authentication error instead of falling back to the service account.
Security implications of strict mode (enabled by default):
- Prevents privilege escalation through service account fallback
- Ensures audit logs always reflect the actual user identity
- Detects OIDC misconfiguration early (fails visibly instead of silently)
- Complies with the security principle of "fail closed"
When strict mode is disabled (NOT recommended for production):
- Falls back to service account if OAuth token is missing or invalid
- May cause unexpected permission changes if OIDC is misconfigured
- Audit logs may show service account instead of user
func WithFederationManager ¶ added in v0.0.52
func WithFederationManager(manager federation.ClusterClientManager) Option
WithFederationManager sets the multi-cluster federation manager. This enables operations across multiple Kubernetes clusters via CAPI. When set, the server can perform operations on both the Management Cluster and Workload Clusters discovered through Cluster API resources.
func WithInCluster ¶ added in v0.0.61
WithInCluster enables in-cluster mode. When enabled, the server uses service account token authentication instead of kubeconfig. This disables kubeContext-related functionality as it's not applicable in-cluster.
func WithInstrumentationProvider ¶ added in v0.0.46
func WithInstrumentationProvider(provider *instrumentation.Provider) Option
WithInstrumentationProvider sets the OpenTelemetry instrumentation provider. This enables production-grade observability including metrics and tracing.
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 WithOutputConfig ¶ added in v0.0.64
func WithOutputConfig(output *OutputConfig) Option
WithOutputConfig sets the output processing configuration. This controls how large responses are handled to prevent context overflow.
func WithRestrictedNamespaces ¶
WithRestrictedNamespaces sets the list of restricted namespaces.
func WithServerName ¶
WithServerName sets the server name in the configuration.
type OutputConfig ¶ added in v0.0.64
type OutputConfig struct {
// MaxItems limits the number of resources returned per query.
// Default: 100, Absolute max: 1000
MaxItems int `json:"maxItems" yaml:"maxItems"`
// MaxClusters limits clusters in fleet-wide queries.
// Default: 20, Absolute max: 100
MaxClusters int `json:"maxClusters" yaml:"maxClusters"`
// MaxResponseBytes is a hard limit on response size in bytes.
// Default: 512KB, Absolute max: 2MB
MaxResponseBytes int `json:"maxResponseBytes" yaml:"maxResponseBytes"`
// SlimOutput enables removal of verbose fields that rarely help AI agents.
// Default: true
SlimOutput bool `json:"slimOutput" yaml:"slimOutput"`
// MaskSecrets replaces secret data with "***REDACTED***".
// Default: true (security critical - should rarely be disabled)
MaskSecrets bool `json:"maskSecrets" yaml:"maskSecrets"`
// SummaryThreshold is the item count above which summary mode is suggested.
// Default: 500
SummaryThreshold int `json:"summaryThreshold" yaml:"summaryThreshold"`
}
OutputConfig holds configuration for output processing. This controls how large responses are handled to prevent context overflow.
func NewDefaultOutputConfig ¶ added in v0.0.64
func NewDefaultOutputConfig() *OutputConfig
NewDefaultOutputConfig creates default output processing 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) DecrementActiveSessions ¶ added in v0.0.46
func (sc *ServerContext) DecrementActiveSessions(ctx context.Context)
DecrementActiveSessions decrements the active port-forward sessions metric.
func (*ServerContext) DownstreamOAuthEnabled ¶ added in v0.0.43
func (sc *ServerContext) DownstreamOAuthEnabled() bool
DownstreamOAuthEnabled returns true if downstream OAuth authentication is enabled.
func (*ServerContext) DownstreamOAuthStrictEnabled ¶ added in v0.0.73
func (sc *ServerContext) DownstreamOAuthStrictEnabled() bool
DownstreamOAuthStrictEnabled returns true if downstream OAuth strict mode is enabled. When strict mode is enabled, requests without valid OAuth tokens will fail with an authentication error instead of falling back to the service account.
func (*ServerContext) FederationEnabled ¶ added in v0.0.52
func (sc *ServerContext) FederationEnabled() bool
FederationEnabled returns true if multi-cluster federation is enabled.
func (*ServerContext) FederationManager ¶ added in v0.0.52
func (sc *ServerContext) FederationManager() federation.ClusterClientManager
FederationManager returns the multi-cluster federation manager. Returns nil if federation is not enabled.
func (*ServerContext) FederationStats ¶ added in v0.0.67
func (sc *ServerContext) FederationStats() *federation.ManagerStats
FederationStats returns statistics about the federation manager. Returns nil if federation is not 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) InClusterMode ¶ added in v0.0.61
func (sc *ServerContext) InClusterMode() bool
InClusterMode returns true if the server is running inside a Kubernetes cluster. When true, kubeconfig-based context switching is not available.
func (*ServerContext) IncrementActiveSessions ¶ added in v0.0.46
func (sc *ServerContext) IncrementActiveSessions(ctx context.Context)
IncrementActiveSessions increments the active port-forward sessions metric.
func (*ServerContext) InstrumentationProvider ¶ added in v0.0.46
func (sc *ServerContext) InstrumentationProvider() *instrumentation.Provider
InstrumentationProvider returns the OpenTelemetry instrumentation provider.
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
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.
When downstream OAuth strict mode is enabled (the default via CLI):
- If no access token is available, returns ErrOAuthTokenMissing
- If the bearer token client cannot be created, returns ErrOAuthClientFailed
When strict mode is disabled (NOT recommended for production):
- Falls back to the shared service account client if authentication fails
Returns (client, nil) on success, or (nil, error) when strict mode denies access.
func (*ServerContext) Logger ¶
func (sc *ServerContext) Logger() Logger
Logger returns the logger interface.
func (*ServerContext) OutputConfig ¶ added in v0.0.64
func (sc *ServerContext) OutputConfig() *OutputConfig
OutputConfig returns the output processing configuration. Returns default config if not explicitly set.
func (*ServerContext) RecordK8sOperation ¶ added in v0.0.46
func (sc *ServerContext) RecordK8sOperation(ctx context.Context, operation, resourceType, namespace, status string, duration time.Duration)
RecordK8sOperation records a Kubernetes operation metric if instrumentation is enabled. This is a convenience method that handles nil checks internally.
func (*ServerContext) RecordPodOperation ¶ added in v0.0.46
func (sc *ServerContext) RecordPodOperation(ctx context.Context, operation, namespace, status string, duration time.Duration)
RecordPodOperation records a pod operation metric if instrumentation is enabled. This is a convenience method that handles nil checks internally.
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.
type ValkeyStorageConfig ¶ added in v0.0.78
type ValkeyStorageConfig struct {
// URL is the Valkey server address (e.g., "valkey.namespace.svc:6379")
URL string
// Password is the optional password for Valkey authentication
Password string
// TLSEnabled enables TLS for Valkey connections
TLSEnabled bool
// KeyPrefix is the prefix for all Valkey keys (default: "mcp:")
KeyPrefix string
// DB is the Valkey database number (default: 0)
DB int
}
ValkeyStorageConfig holds configuration for Valkey storage backend.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package middleware provides HTTP middleware for the MCP Kubernetes server.
|
Package middleware provides HTTP middleware for the MCP Kubernetes server. |