cmd

package
v1.0.16 Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2026 License: Apache-2.0 Imports: 35 Imported by: 0

Documentation

Overview

Package cmd provides the command-line interface for mcp-kubernetes.

This package implements a Cobra-based CLI with multiple subcommands:

  • serve: Starts the MCP server (default behavior when no subcommand is provided)
  • version: Displays the application version
  • self-update: Updates the binary to the latest version from GitHub releases

The CLI maintains backwards compatibility by running the serve command when no subcommand is specified, preserving the original behavior of the application.

Command Structure:

mcp-kubernetes [flags]                 # Starts the MCP server (default)
mcp-kubernetes serve [flags]           # Explicitly starts the MCP server
mcp-kubernetes version                 # Shows version information
mcp-kubernetes self-update             # Updates to latest release
mcp-kubernetes help [command]          # Shows help information

The serve command supports multiple transport options:

  • stdio: Standard input/output (default) - for command-line integration
  • sse: Server-Sent Events over HTTP - for web-based clients
  • streamable-http: Streamable HTTP transport - for HTTP-based integration

Transport Configuration Examples:

mcp-kubernetes serve --transport stdio           # Default STDIO transport
mcp-kubernetes serve --transport sse --http-addr :8080 --sse-endpoint /sse
mcp-kubernetes serve --transport streamable-http --http-addr :9000 --http-endpoint /mcp

The serve command also supports configuration flags for controlling Kubernetes client behavior, including non-destructive mode, dry-run mode, and API rate limiting settings.

Index

Constants

View Source
const (
	OAuthProviderDex    = server.OAuthProviderDex
	OAuthProviderGoogle = server.OAuthProviderGoogle
)

OAuth provider constants - use server package constants for consistency

View Source
const (
	OAuthStorageTypeMemory = server.OAuthStorageTypeMemory
	OAuthStorageTypeValkey = server.OAuthStorageTypeValkey
)

Storage type constants - re-exported from server package for convenience.

Variables

This section is empty.

Functions

func Execute

func Execute()

Execute is the main entry point for the CLI application. It initializes and executes the root command, which in turn handles subcommands and flags. This function is called by main.main().

func SetVersion

func SetVersion(v string)

SetVersion sets the version for the root command. This function is typically called from the main package to inject the application version at build time.

Types

type CAPIModeConfig added in v0.0.68

type CAPIModeConfig struct {
	// Enabled enables CAPI federation mode for multi-cluster operations
	Enabled bool

	// Cache configuration
	CacheTTL             string
	CacheMaxEntries      int
	CacheCleanupInterval string

	// OAuthTokenLifetime is the expected lifetime of OAuth tokens from your provider.
	// If CacheTTL exceeds this value, a warning is logged. This helps prevent
	// authentication failures from using cached clients with expired tokens.
	// Defaults to 1 hour if not specified.
	OAuthTokenLifetime string

	// Connectivity configuration
	ConnectivityTimeout        string
	ConnectivityRetryAttempts  int
	ConnectivityRetryBackoff   string
	ConnectivityRequestTimeout string
	ConnectivityQPS            float32
	ConnectivityBurst          int

	// Workload cluster authentication configuration
	WorkloadClusterAuth WorkloadClusterAuthConfig

	// Privileged access configuration (split-credential model)
	PrivilegedAccess PrivilegedAccessConfig
}

CAPIModeConfig holds CAPI federation mode configuration.

type MetricsServeConfig added in v0.0.94

type MetricsServeConfig struct {
	// Enabled determines whether to start the metrics server (default: true)
	Enabled bool

	// Addr is the address for the metrics server (e.g., ":9090")
	Addr string
}

MetricsServeConfig holds configuration for the metrics server.

type OAuthServeConfig added in v0.0.43

type OAuthServeConfig struct {
	Enabled                            bool
	BaseURL                            string
	Provider                           string // "dex" or "google"
	GoogleClientID                     string
	GoogleClientSecret                 string
	DexIssuerURL                       string
	DexClientID                        string
	DexClientSecret                    string
	DexConnectorID                     string // optional: bypasses connector selection screen
	DexCAFile                          string // optional: CA certificate file for Dex TLS verification
	DexKubernetesAuthenticatorClientID string // optional: enables cross-client audience for K8s API auth
	DisableStreaming                   bool
	RegistrationToken                  string
	AllowPublicRegistration            bool
	AllowInsecureAuthWithoutState      bool
	AllowPrivateURLs                   bool // skip private IP validation for internal deployments
	MaxClientsPerIP                    int
	EncryptionKey                      string
	TLSCertFile                        string
	TLSKeyFile                         string

	// Redirect URI Security Configuration
	// These settings control security validation of redirect URIs during client registration.
	// All settings default to secure values - operators must explicitly opt-out.
	RedirectURISecurity RedirectURISecurityConfig

	// TrustedPublicRegistrationSchemes lists URI schemes that are allowed for
	// unauthenticated client registration. Clients registering with redirect URIs
	// using ONLY these schemes do NOT need a RegistrationAccessToken.
	// This enables Cursor and other MCP clients that don't support registration tokens.
	//
	// Security: Custom URI schemes can only be intercepted by the app that registered
	// the scheme with the OS. However, this has platform-specific limitations and is
	// most appropriate for internal/development deployments. For high-security production
	// deployments, use registration tokens instead.
	//
	// Schemes must conform to RFC 3986 syntax. Dangerous schemes are blocked.
	// Example: ["cursor", "vscode", "vscode-insiders", "windsurf"]
	TrustedPublicRegistrationSchemes []string

	// DisableStrictSchemeMatching allows clients with mixed redirect URI schemes
	// (e.g., cursor:// AND https://) to register without a token if ANY URI uses
	// a trusted scheme. Default: false (all URIs must use trusted schemes).
	// WARNING: Reduces security - only enable if you have specific requirements.
	DisableStrictSchemeMatching bool

	// EnableCIMD enables Client ID Metadata Documents (CIMD) per MCP 2025-11-25.
	// When enabled, clients can use HTTPS URLs as client identifiers, and the
	// authorization server will fetch client metadata from that URL.
	// This enables decentralized client registration where clients host their
	// own metadata documents.
	// Default: true (enabled per MCP 2025-11-25 specification)
	EnableCIMD bool

	// CIMDAllowPrivateIPs allows CIMD metadata URLs that resolve to private IP addresses
	// (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 per RFC 1918). This also allows loopback
	// addresses (127.0.0.0/8, ::1) and link-local addresses.
	// WARNING: Reduces SSRF protection. Only enable for internal/VPN deployments where
	// MCP servers legitimately communicate over private networks.
	//
	// Use cases:
	//   - Home lab deployments
	//   - Air-gapped environments
	//   - Internal enterprise networks
	//   - Any deployment where MCP servers communicate over private networks
	//
	// Default: false (blocked for security)
	CIMDAllowPrivateIPs bool

	// TrustedAudiences lists client IDs whose tokens are accepted for SSO.
	// When upstream aggregators (like muster) forward a user's ID token,
	// mcp-kubernetes will accept it if the token's audience matches any
	// entry in this list. This enables Single Sign-On across the MCP ecosystem.
	//
	// Security:
	//   - Only explicitly listed client IDs are trusted
	//   - Tokens must still be from the configured issuer (Dex/Google)
	//   - The IdP's cryptographic signature proves token authenticity
	//
	// Example: ["muster-client", "another-aggregator"]
	TrustedAudiences []string

	// SSOAllowPrivateIPs allows JWKS endpoints (used for SSO token validation) that
	// resolve to private IP addresses (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 per RFC 1918).
	// This also allows loopback addresses (127.0.0.0/8, ::1) and link-local addresses.
	//
	// When TrustedAudiences is configured, mcp-kubernetes validates forwarded ID tokens
	// by fetching the IdP's JWKS (JSON Web Key Set) to verify signatures. If your IdP
	// (like Dex) is deployed on a private network, JWKS fetching will fail without this option.
	//
	// Use cases:
	//   - Home lab deployments where Dex runs on an internal network
	//   - Air-gapped environments
	//   - Internal enterprise networks
	//   - Any deployment where the IdP is only accessible over private networks
	//
	// WARNING: Reduces SSRF protection. Only enable for internal deployments
	// that are not exposed to the public internet.
	//
	// Default: false (blocked for security)
	SSOAllowPrivateIPs bool

	// TrustedIssuers lists external JWT issuers whose tokens are accepted at /mcp.
	// Populated via the OAUTH_TRUSTED_ISSUERS environment variable (JSON array).
	TrustedIssuers []server.TrustedIssuerConfig

	// Storage configuration
	Storage server.OAuthStorageConfig
}

OAuthServeConfig holds OAuth-specific configuration.

type OAuthStorageConfig added in v0.0.78

type OAuthStorageConfig = server.OAuthStorageConfig

OAuthStorageConfig holds configuration for OAuth token storage backend.

type OAuthStorageType added in v0.0.78

type OAuthStorageType = server.OAuthStorageType

OAuthStorageType represents the type of token storage backend.

type PrivilegedAccessConfig added in v0.0.153

type PrivilegedAccessConfig struct {
	// Enabled controls whether the split-credential model is active.
	//
	// When true (default), a HybridOAuthClientProvider is created and
	// WithPrivilegedAccess is passed to the Manager. The resulting
	// CredentialMode depends on PrivilegedCAPIDiscovery:
	//   - true  → CredentialModeFullPrivileged
	//   - false → CredentialModePrivilegedSecrets
	//
	// When false, no privileged provider is created and the Manager
	// uses CredentialModeUser: all operations (CAPI discovery, secret
	// access) use the user's own OAuth token and RBAC.
	//
	// Default: true
	Enabled *bool

	// Strict mode: When enabled, fails instead of falling back to user credentials
	// when ServiceAccount access is unavailable.
	//
	// SECURITY RECOMMENDATION:
	// Enable this in production to enforce the split-credential security model.
	// When disabled (default), the system falls back to user credentials,
	// which may require users to have secret read permissions (weaker security).
	//
	// Default: false (fallback enabled for backward compatibility)
	Strict bool

	// PrivilegedCAPIDiscovery controls whether CAPI cluster discovery uses
	// ServiceAccount credentials instead of user credentials.
	//
	// When enabled (default), the ServiceAccount discovers all CAPI clusters,
	// eliminating the need for users to have cluster-scoped CAPI permissions.
	// This is the recommended setting because granting every user cluster-scoped
	// CAPI permissions is impractical in multi-tenant environments.
	//
	// When disabled, users must have their own RBAC permissions to list
	// clusters.cluster.x-k8s.io resources. This limits cluster visibility
	// to what the user's RBAC allows, providing tenant-level isolation of
	// cluster discovery.
	//
	// VISIBILITY NOTE:
	// When enabled, all users can see all CAPI clusters (names, namespaces,
	// status). Access to workload cluster operations is still governed by
	// the user's own RBAC via impersonation.
	//
	// Default: true (privileged CAPI discovery enabled)
	PrivilegedCAPIDiscovery *bool

	// RateLimitPerSecond is the rate limit for privileged access per user (requests/second).
	// Prevents abuse by limiting how often a user can trigger ServiceAccount-based secret access.
	// Default: 10.0
	RateLimitPerSecond float64

	// RateLimitBurst is the burst size for privileged access per user.
	// Allows short bursts of requests above the rate limit.
	// Default: 20
	RateLimitBurst int
}

PrivilegedAccessConfig configures the split-credential model for privileged access. When enabled, the ServiceAccount token is used for kubeconfig secret access and CAPI cluster discovery instead of user OAuth tokens. This prevents users from bypassing impersonation by extracting admin credentials via kubectl.

type RedirectURISecurityConfig added in v0.0.95

type RedirectURISecurityConfig = server.RedirectURISecurityConfig

RedirectURISecurityConfig is an alias to server.RedirectURISecurityConfig. See server.RedirectURISecurityConfig for field documentation.

type ServeConfig added in v0.0.43

type ServeConfig struct {
	// Transport settings
	Transport string
	HTTPAddr  string

	// Endpoint paths
	SSEEndpoint     string
	MessageEndpoint string
	HTTPEndpoint    string

	// Kubernetes client settings
	NonDestructiveMode bool
	DryRun             bool
	QPSLimit           float32
	BurstLimit         int
	DebugMode          bool
	InCluster          bool

	// OAuth configuration
	OAuth           OAuthServeConfig
	DownstreamOAuth bool

	// CAPI Mode configuration (multi-cluster federation)
	CAPIMode CAPIModeConfig

	// Metrics server configuration
	Metrics MetricsServeConfig
}

ServeConfig holds all configuration for the serve command.

type ValkeyStorageConfig added in v0.0.78

type ValkeyStorageConfig = server.ValkeyStorageConfig

ValkeyStorageConfig holds configuration for Valkey storage backend.

type WorkloadClusterAuthConfig added in v0.0.135

type WorkloadClusterAuthConfig struct {
	// Mode determines the authentication method for workload clusters.
	// Options:
	//   - "impersonation" (default): Uses admin credentials from kubeconfig secrets
	//     with user impersonation headers.
	//   - "sso-passthrough": Forwards the user's SSO/OAuth ID token directly to
	//     workload cluster API servers. Requires WC API servers to be configured
	//     with OIDC authentication.
	Mode string

	// CAConfigMapSuffix is the suffix for CA ConfigMaps used in sso-passthrough mode.
	// The full ConfigMap name is: ${CLUSTER_NAME}${CAConfigMapSuffix}
	// These ConfigMaps contain the cluster's CA certificate (public key) for TLS verification.
	// Default: "-ca-public"
	CAConfigMapSuffix string

	// DisableCaching disables client caching in sso-passthrough mode.
	// When enabled, each request creates a fresh client with the current SSO token.
	// This is recommended for high-security deployments to ensure:
	//   - Tokens are never cached beyond their natural lifetime
	//   - Token revocation takes effect immediately
	//   - No risk of reusing expired tokens from cache
	//
	// Trade-off: Higher latency per request (no connection reuse).
	// Default: false (caching enabled for better performance)
	DisableCaching bool

	// GroupMappings is a map of source-group -> target-group for translating
	// OIDC group identifiers before setting Impersonate-Group headers.
	//
	// This is useful when the OIDC provider (e.g., Dex, Google, Okta) returns
	// group identifiers in a different format than what the workload cluster
	// RoleBindings expect. For example:
	//   - OIDC provider returns Azure AD display names ("customer:GroupA"),
	//     but workload cluster RoleBindings use Azure AD group GUIDs.
	//   - LDAP-backed provider returns group DNs, but the cluster expects short names.
	//
	// SECURITY: Mappings control which Kubernetes groups users are impersonated
	// into. Mapping to dangerous system groups (system:masters, system:nodes,
	// system:kube-controller-manager, system:kube-scheduler, system:kube-proxy)
	// is rejected at startup. Mapping to other "system:*" groups produces a
	// warning. Invalid mappings will prevent startup (fail-closed). Restrict
	// access to this configuration.
	//
	// Only used in "impersonation" mode. Unmapped groups pass through unchanged.
	// Configured via Helm values (native YAML map) or the WC_GROUP_MAPPINGS
	// environment variable (JSON-serialized by the Helm template).
	GroupMappings map[string]string
}

WorkloadClusterAuthConfig configures how mcp-kubernetes authenticates to workload clusters.

Jump to

Keyboard shortcuts

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