config

package
v0.0.62 Latest Latest
Warning

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

Go to latest
Published: May 5, 2026 License: Apache-2.0 Imports: 21 Imported by: 2

Documentation

Index

Constants

View Source
const (
	DefaultDropInConfigDir = "conf.d"
)
View Source
const DefaultRateLimitBurst = 10

DefaultRateLimitBurst is the default burst size used when rate_limit_rps is set but rate_limit_burst is not specified (zero value).

Variables

This section is empty.

Functions

func ConfigDirPathFromContext added in v0.0.54

func ConfigDirPathFromContext(ctx context.Context) string

func NewTLSEnforcingClient added in v0.0.60

func NewTLSEnforcingClient(base *http.Client, requireTLS func() bool) *http.Client

NewTLSEnforcingClient creates an HTTP client that enforces HTTPS when requireTLS returns true. The requireTLS function is called on each request, allowing dynamic configuration changes.

func NewTLSEnforcingTransport added in v0.0.60

func NewTLSEnforcingTransport(base http.RoundTripper, requireTLS func() bool) http.RoundTripper

NewTLSEnforcingTransport creates a transport that enforces HTTPS when requireTLS returns true. The requireTLS function is called on each request, allowing dynamic configuration changes.

func RegisterProviderConfig added in v0.0.54

func RegisterProviderConfig(name string, parser ExtendedConfigParser)

func RegisterToolsetConfig added in v0.0.55

func RegisterToolsetConfig(name string, parser ExtendedConfigParser)

func RequireTLSFromContext added in v0.0.60

func RequireTLSFromContext(ctx context.Context) bool

func ValidateURLRequiresTLS added in v0.0.60

func ValidateURLRequiresTLS(urlStr string, fieldName string) error

ValidateURLRequiresTLS validates that a URL uses a secure scheme when TLS is required. Returns nil if the URL is empty. Returns an error if the URL does not use a secure scheme. This provides Layer 1 (config-time) validation for fail-fast feedback.

func ValidateURLsRequireTLS added in v0.0.60

func ValidateURLsRequireTLS(urls map[string]string) error

ValidateURLsRequireTLS validates multiple URLs use a secure scheme. The map keys are field names, values are the URLs to validate. All URLs are validated and errors are combined. Keys are sorted for deterministic error ordering.

Types

type Duration added in v0.0.61

type Duration time.Duration

Duration is a time.Duration that can be unmarshaled from TOML. It accepts Go duration strings like "30s", "5m", "1h30m". Note: Negative durations are accepted but effectively disable timeouts when used with http.Server (which treats zero/negative as no timeout).

func (Duration) Duration added in v0.0.61

func (d Duration) Duration() time.Duration

Duration returns the underlying time.Duration value.

func (Duration) MarshalText added in v0.0.61

func (d Duration) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler for TOML serialization.

func (*Duration) UnmarshalText added in v0.0.61

func (d *Duration) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler for TOML parsing.

type ExtendedConfigParser added in v0.0.55

type ExtendedConfigParser func(ctx context.Context, primitive toml.Primitive, md toml.MetaData) (api.ExtendedConfig, error)

type HTTPConfig added in v0.0.61

type HTTPConfig struct {
	// ReadHeaderTimeout is the amount of time allowed to read request headers.
	// This is the primary defense against Slowloris attacks.
	ReadHeaderTimeout Duration `toml:"read_header_timeout,omitempty"`

	// MaxBodyBytes is the maximum size of request body in bytes.
	// MCP payloads (tools/call with Kubernetes manifests) can be large,
	// so the default is 16MB to accommodate CRDs and ConfigMaps.
	// Type is int64 to match http.MaxBytesReader signature.
	MaxBodyBytes int64 `toml:"max_body_bytes,omitzero"`

	// RateLimitRPS is the maximum number of requests per second per session.
	// When set to 0 (default), rate limiting is disabled.
	RateLimitRPS float64 `toml:"rate_limit_rps,omitzero"`

	// RateLimitBurst is the maximum burst size for rate limiting per session.
	// Allows short bursts of requests above the rate limit.
	// Only effective when rate_limit_rps > 0.
	// When zero, the rate limiting middleware applies DefaultRateLimitBurst.
	RateLimitBurst int `toml:"rate_limit_burst,omitzero"`
}

HTTPConfig contains HTTP server configuration options for security.

func (*HTTPConfig) Validate added in v0.0.61

func (c *HTTPConfig) Validate() error

Validate checks HTTPConfig for invalid values. It rejects negative RateLimitRPS and negative RateLimitBurst.

type ReadConfigOpt added in v0.0.54

type ReadConfigOpt func(cfg *StaticConfig)

func WithDirPath added in v0.0.55

func WithDirPath(path string) ReadConfigOpt

WithDirPath returns a ReadConfigOpt that sets the config directory path.

type StaticConfig

type StaticConfig struct {
	DeniedResources []api.GroupVersionKind `toml:"denied_resources"`

	LogLevel   int    `toml:"log_level,omitzero"`
	Port       string `toml:"port,omitempty"`
	SSEBaseURL string `toml:"sse_base_url,omitempty"`
	KubeConfig string `toml:"kubeconfig,omitempty"`
	ListOutput string `toml:"list_output,omitempty"`
	// Stateless configures the MCP server to operate in stateless mode.
	// When true, the server will not send notifications to clients (e.g., tools/list_changed, prompts/list_changed).
	// This is useful for container deployments, load balancing, and serverless environments where
	// maintaining client state is not desired or possible. However, this disables dynamic tool
	// and prompt updates, requiring clients to manually refresh their tool/prompt lists.
	// Defaults to false (stateful mode with notifications enabled).
	Stateless bool `toml:"stateless,omitempty"`
	// When true, expose only tools annotated with readOnlyHint=true
	ReadOnly bool `toml:"read_only,omitempty"`
	// When true, disable tools annotated with destructiveHint=true
	DisableDestructive bool     `toml:"disable_destructive,omitempty"`
	Toolsets           []string `toml:"toolsets,omitempty"`
	// Tool configuration
	EnabledTools  []string                `toml:"enabled_tools,omitempty"`
	DisabledTools []string                `toml:"disabled_tools,omitempty"`
	ToolOverrides map[string]ToolOverride `toml:"tool_overrides,omitempty"`
	// Prompt configuration
	Prompts []api.Prompt `toml:"prompts,omitempty"`

	// Authorization-related fields
	// RequireOAuth indicates whether the server requires OAuth for authentication.
	RequireOAuth bool `toml:"require_oauth,omitempty"`
	// OAuthAudience is the valid audience for the OAuth tokens, used for offline JWT claim validation.
	OAuthAudience string `toml:"oauth_audience,omitempty"`
	// AuthorizationURL is the URL of the OIDC authorization server.
	// It is used for token validation and for STS token exchange.
	AuthorizationURL string `toml:"authorization_url,omitempty"`
	// SkipJWTVerification allows the server to accept JWTs without cryptographic
	// signature verification when require_oauth is enabled but no authorization_url
	// is configured (offline-only validation). Only use behind a trusted reverse proxy
	// that performs token verification. When false (default), the server refuses to
	// start if require_oauth is true and authorization_url is empty.
	SkipJWTVerification bool `toml:"skip_jwt_verification,omitempty"`
	// DisableDynamicClientRegistration indicates whether dynamic client registration is disabled.
	// If true, the .well-known endpoints will not expose the registration endpoint.
	DisableDynamicClientRegistration bool `toml:"disable_dynamic_client_registration,omitempty"`
	// OAuthScopes are the supported **client** scopes requested during the **client/frontend** OAuth flow.
	OAuthScopes []string `toml:"oauth_scopes,omitempty"`
	// StsClientId is the OAuth client ID used for backend token exchange
	StsClientId string `toml:"sts_client_id,omitempty"`
	// StsClientSecret is the OAuth client secret used for backend token exchange
	StsClientSecret string `toml:"sts_client_secret,omitempty"`
	// StsAudience is the audience for the STS token exchange.
	StsAudience string `toml:"sts_audience,omitempty"`
	// StsScopes is the scopes for the STS token exchange.
	StsScopes []string `toml:"sts_scopes,omitempty"`
	// TokenExchangeStrategy is the token exchange strategy to use (rfc8693, keycloak-v1, entra-obo).
	// When set with passthrough mode, the token is exchanged before being passed to the cluster.
	TokenExchangeStrategy string `toml:"token_exchange_strategy,omitempty"`
	// StsAuthStyle specifies how client credentials are sent during token exchange.
	// "params" (default): client_id/secret in request body
	// "header": HTTP Basic Authentication header
	// "assertion": JWT client assertion (RFC 7523, for Entra ID certificate auth)
	StsAuthStyle string `toml:"sts_auth_style,omitempty"`
	// StsClientCertFile is the path to the client certificate PEM file for JWT assertion auth
	StsClientCertFile string `toml:"sts_client_cert_file,omitempty"`
	// StsClientKeyFile is the path to the client private key PEM file for JWT assertion auth
	StsClientKeyFile string `toml:"sts_client_key_file,omitempty"`
	// ClusterAuthMode determines how the MCP server authenticates to the cluster.
	// Valid values: "passthrough" (forward Authorization header, with optional exchange), "kubeconfig" (use kubeconfig credentials).
	// If empty, defaults to passthrough: forwards the token when present, falls back to kubeconfig when absent.
	ClusterAuthMode      string `toml:"cluster_auth_mode,omitempty"`
	CertificateAuthority string `toml:"certificate_authority,omitempty"`
	ServerURL            string `toml:"server_url,omitempty"`
	// TrustProxyHeaders allows the server to use X-Forwarded-Host, X-Forwarded-Proto,
	// X-Forwarded-For, and X-Real-IP headers from reverse proxies.
	// Only enable this when the server is behind a trusted reverse proxy.
	// When false (default), the server requires server_url to be set for well-known
	// endpoint metadata and ignores forwarded headers for client IP and scheme detection.
	TrustProxyHeaders bool `toml:"trust_proxy_headers,omitempty"`

	// TLS configuration for the HTTP server
	// TLSCert is the path to the TLS certificate file for HTTPS
	TLSCert string `toml:"tls_cert,omitempty"`
	// TLSKey is the path to the TLS private key file for HTTPS
	TLSKey string `toml:"tls_key,omitempty"`
	// RequireTLS enforces TLS for all server and client connections.
	// When true, the server will refuse to start without TLS certificates,
	// and outbound connections to non-HTTPS endpoints will be rejected.
	RequireTLS bool `toml:"require_tls,omitempty"`

	// HTTP server configuration (timeouts, size limits)
	HTTP HTTPConfig `toml:"http,omitempty"`

	// ClusterProviderStrategy is how the server finds clusters.
	// If set to "kubeconfig", the clusters will be loaded from those in the kubeconfig.
	// If set to "in-cluster", the server will use the in cluster config
	ClusterProviderStrategy string `toml:"cluster_provider_strategy,omitempty"`

	// ClusterProvider-specific configurations
	// This map holds raw TOML primitives that will be parsed by registered provider parsers
	ClusterProviderConfigs map[string]toml.Primitive `toml:"cluster_provider_configs,omitempty"`

	// Toolset-specific configurations
	// This map holds raw TOML primitives that will be parsed by registered toolset parsers
	ToolsetConfigs map[string]toml.Primitive `toml:"toolset_configs,omitempty"`

	// Server instructions to be provided by the MCP server to the MCP client
	// This can be used to provide specific instructions on how the client should use the server
	ServerInstructions string `toml:"server_instructions,omitempty"`

	// Telemetry contains OpenTelemetry configuration options.
	// These can also be configured via OTEL_* environment variables.
	Telemetry TelemetryConfig `toml:"telemetry,omitempty"`

	// ValidationEnabled enables pre-execution validation of tool calls.
	// When enabled, validates resources, schemas, and RBAC before execution.
	// Defaults to false.
	ValidationEnabled bool `toml:"validation_enabled,omitempty"`

	// ConfirmationFallback is the global default fallback behavior when a client
	// does not support elicitation. Valid values are "deny" and "allow".
	ConfirmationFallback string `toml:"confirmation_fallback,omitempty"`
	// ConfirmationRules define rules for prompting the user before dangerous actions.
	ConfirmationRules []api.ConfirmationRule `toml:"confirmation_rules,omitempty"`
	// contains filtered or unexported fields
}

StaticConfig is the configuration for the server. It allows to configure server specific settings and tools to be enabled or disabled.

func BaseDefault added in v0.0.58

func BaseDefault() *StaticConfig

BaseDefault returns the upstream base defaults before any build-time overrides are applied. This is useful for understanding the raw upstream configuration independent of downstream customization.

func Default added in v0.0.51

func Default() *StaticConfig

Default returns the effective default configuration, with any downstream build-time overrides (from defaultOverrides) merged on top of the base defaults.

func Read added in v0.0.51

func Read(configPath, dropInConfigDir string) (*StaticConfig, error)

Read reads the toml file, applies drop-in configs from configDir (if provided), and returns the StaticConfig with any opts applied. Loading order: defaults → main config file → drop-in files (lexically sorted)

func ReadToml added in v0.0.51

func ReadToml(configData []byte, opts ...ReadConfigOpt) (*StaticConfig, error)

ReadToml reads the toml data, loads and applies drop-in configs from configDir (if provided), and returns the StaticConfig with any opts applied. Loading order: defaults → main config file → drop-in files (lexically sorted)

func (*StaticConfig) GetCertificateAuthority added in v0.0.62

func (c *StaticConfig) GetCertificateAuthority() string

func (*StaticConfig) GetClusterAuthMode added in v0.0.61

func (c *StaticConfig) GetClusterAuthMode() string

func (*StaticConfig) GetClusterProviderStrategy added in v0.0.56

func (c *StaticConfig) GetClusterProviderStrategy() string

func (*StaticConfig) GetConfirmationFallback added in v0.0.60

func (c *StaticConfig) GetConfirmationFallback() string

func (*StaticConfig) GetConfirmationRules added in v0.0.60

func (c *StaticConfig) GetConfirmationRules() []api.ConfirmationRule

func (*StaticConfig) GetDeniedResources added in v0.0.56

func (c *StaticConfig) GetDeniedResources() []api.GroupVersionKind

func (*StaticConfig) GetKubeConfigPath added in v0.0.56

func (c *StaticConfig) GetKubeConfigPath() string

func (*StaticConfig) GetProviderConfig added in v0.0.54

func (c *StaticConfig) GetProviderConfig(strategy string) (api.ExtendedConfig, bool)

func (*StaticConfig) GetStsAudience added in v0.0.57

func (c *StaticConfig) GetStsAudience() string

func (*StaticConfig) GetStsAuthStyle added in v0.0.61

func (c *StaticConfig) GetStsAuthStyle() string

func (*StaticConfig) GetStsClientCertFile added in v0.0.61

func (c *StaticConfig) GetStsClientCertFile() string

func (*StaticConfig) GetStsClientId added in v0.0.57

func (c *StaticConfig) GetStsClientId() string

func (*StaticConfig) GetStsClientKeyFile added in v0.0.61

func (c *StaticConfig) GetStsClientKeyFile() string

func (*StaticConfig) GetStsClientSecret added in v0.0.57

func (c *StaticConfig) GetStsClientSecret() string

func (*StaticConfig) GetStsScopes added in v0.0.57

func (c *StaticConfig) GetStsScopes() []string

func (*StaticConfig) GetStsStrategy added in v0.0.61

func (c *StaticConfig) GetStsStrategy() string

func (*StaticConfig) GetToolsetConfig added in v0.0.55

func (c *StaticConfig) GetToolsetConfig(name string) (api.ExtendedConfig, bool)

func (*StaticConfig) IsRequireOAuth added in v0.0.56

func (c *StaticConfig) IsRequireOAuth() bool

func (*StaticConfig) IsRequireTLS added in v0.0.60

func (c *StaticConfig) IsRequireTLS() bool

func (*StaticConfig) IsValidationEnabled added in v0.0.58

func (c *StaticConfig) IsValidationEnabled() bool

func (*StaticConfig) ResolveClusterAuthMode added in v0.0.61

func (c *StaticConfig) ResolveClusterAuthMode() string

ResolveClusterAuthMode returns the effective cluster auth mode. If explicitly set, returns that value. Otherwise defaults to passthrough, which forwards the Authorization header to the cluster when present and falls back to kubeconfig credentials when absent.

func (*StaticConfig) Validate added in v0.0.61

func (c *StaticConfig) Validate() error

Validate validates config-level invariants that must hold at both startup and on SIGHUP reload.

func (*StaticConfig) ValidateClusterAuthMode added in v0.0.61

func (c *StaticConfig) ValidateClusterAuthMode() error

ValidateClusterAuthMode validates cluster_auth_mode and its interaction with other auth-related settings (require_oauth, token exchange).

func (*StaticConfig) ValidateRequireTLS added in v0.0.60

func (c *StaticConfig) ValidateRequireTLS() error

ValidateRequireTLS validates outbound URL schemes when RequireTLS is enabled. Called at startup (root.go Validate) and on config reload (ReloadConfiguration).

func (*StaticConfig) WithProviderStrategies added in v0.0.61

func (c *StaticConfig) WithProviderStrategies(strategies []string) *StaticConfig

WithProviderStrategies sets the known cluster-provider strategies for validation. Callers that have access to the provider registry should chain this before Validate so that cluster_provider_strategy is checked:

cfg.WithProviderStrategies(kubernetes.GetRegisteredStrategies()).Validate()

func (*StaticConfig) WithTokenExchangeStrategies added in v0.0.61

func (c *StaticConfig) WithTokenExchangeStrategies(strategies []string) *StaticConfig

WithTokenExchangeStrategies sets the known token exchange strategies for validation. Callers that have access to the token exchange registry should chain this before Validate so that token_exchange_strategy is checked:

cfg.WithTokenExchangeStrategies(tokenexchange.GetRegisteredStrategies()).Validate()

type StaticConfigState added in v0.0.61

type StaticConfigState struct {
	// contains filtered or unexported fields
}

StaticConfigState holds the current StaticConfig and allows atomic, lock-free reads. This enables hot-reloading of configuration via SIGHUP while ensuring all consumers (e.g., HTTP middleware) always see the latest config snapshot.

Non-nil invariant: once constructed via NewStaticConfigState with a non-nil *StaticConfig, Load always returns a non-nil pointer. Store silently ignores nil to preserve this invariant for downstream consumers that dereference without a nil check.

func NewStaticConfigState added in v0.0.61

func NewStaticConfigState(cfg *StaticConfig) *StaticConfigState

NewStaticConfigState creates a new StaticConfigState initialized with the given config. cfg must be non-nil; passing nil violates the non-nil invariant of Load.

func (*StaticConfigState) Load added in v0.0.61

func (s *StaticConfigState) Load() *StaticConfig

Load returns the current StaticConfig. Safe for concurrent use. Guaranteed non-nil when the state was constructed via NewStaticConfigState with a non-nil config; Store(nil) is a no-op.

func (*StaticConfigState) Store added in v0.0.61

func (s *StaticConfigState) Store(cfg *StaticConfig)

Store atomically replaces the current StaticConfig. nil is silently ignored to preserve the non-nil invariant of Load.

type TLSEnforcingTransport added in v0.0.60

type TLSEnforcingTransport struct {
	Base       http.RoundTripper
	RequireTLS func() bool
}

TLSEnforcingTransport wraps an http.RoundTripper and rejects non-HTTPS requests when RequireTLS returns true. This provides Layer 2 (runtime) enforcement as defense-in-depth, catching any URLs that might have been missed during config validation. The RequireTLS function is called per-request, allowing dynamic config changes (e.g., SIGHUP).

func (*TLSEnforcingTransport) RoundTrip added in v0.0.60

func (t *TLSEnforcingTransport) RoundTrip(req *http.Request) (*http.Response, error)

type TelemetryConfig added in v0.0.57

type TelemetryConfig struct {
	// Enabled explicitly enables or disables telemetry.
	// If nil (not set), telemetry is auto-enabled when Endpoint is configured.
	// If explicitly set to false, telemetry is disabled even if env vars are set.
	Enabled *bool `toml:"enabled,omitempty"`

	// Endpoint is the OTLP endpoint URL (e.g., "http://localhost:4317").
	// Can be overridden by OTEL_EXPORTER_OTLP_ENDPOINT env var.
	Endpoint string `toml:"endpoint,omitempty"`

	// Protocol specifies the OTLP protocol: "grpc" (default) or "http/protobuf".
	// Can be overridden by OTEL_EXPORTER_OTLP_PROTOCOL env var.
	Protocol string `toml:"protocol,omitempty"`

	// TracesSampler specifies the trace sampling strategy.
	// Supported values: "always_on", "always_off", "traceidratio",
	// "parentbased_always_on", "parentbased_traceidratio".
	// Can be overridden by OTEL_TRACES_SAMPLER env var.
	TracesSampler string `toml:"traces_sampler,omitempty"`

	// TracesSamplerArg is the sampling ratio for ratio-based samplers (0.0 to 1.0).
	// Can be overridden by OTEL_TRACES_SAMPLER_ARG env var.
	TracesSamplerArg *float64 `toml:"traces_sampler_arg,omitempty"`
}

TelemetryConfig contains OpenTelemetry configuration options. Values can be set via TOML config file or environment variables. Environment variables take precedence over TOML config values.

func (*TelemetryConfig) GetEndpoint added in v0.0.57

func (c *TelemetryConfig) GetEndpoint() string

GetEndpoint returns the OTLP endpoint. Environment variable OTEL_EXPORTER_OTLP_ENDPOINT takes precedence over config.

func (*TelemetryConfig) GetProtocol added in v0.0.57

func (c *TelemetryConfig) GetProtocol() string

GetProtocol returns the OTLP protocol. Environment variable OTEL_EXPORTER_OTLP_PROTOCOL takes precedence over config.

func (*TelemetryConfig) GetTracesSampler added in v0.0.57

func (c *TelemetryConfig) GetTracesSampler() string

GetTracesSampler returns the trace sampler type. Environment variable OTEL_TRACES_SAMPLER takes precedence over config.

func (*TelemetryConfig) GetTracesSamplerArg added in v0.0.57

func (c *TelemetryConfig) GetTracesSamplerArg() string

GetTracesSamplerArg returns the trace sampler argument as a string. Environment variable OTEL_TRACES_SAMPLER_ARG takes precedence over config.

func (*TelemetryConfig) IsEnabled added in v0.0.57

func (c *TelemetryConfig) IsEnabled() bool

IsEnabled returns true if telemetry should be enabled. Logic:

  • If Enabled is explicitly set to false, return false (explicit disable)
  • If Enabled is explicitly set to true, return true only if endpoint is available
  • If Enabled is nil (not set), return true if endpoint is available (auto-enable)

type ToolOverride added in v0.0.60

type ToolOverride struct {
	Description string `toml:"description,omitempty"`
}

ToolOverride contains per-tool configuration overrides.

Jump to

Keyboard shortcuts

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