Documentation
¶
Overview ¶
Package k8s provides interfaces and types for Kubernetes operations.
This package defines the core Client interface that abstracts all Kubernetes operations needed by the MCP tools. The interface is designed to support:
- Multi-cluster operations through context parameters
- All kubectl operations (get, list, describe, create, apply, delete, patch, scale)
- Pod-specific operations (logs, exec, port-forward)
- Cluster management (API resources, health checks)
The interfaces are broken down into focused concerns:
- ContextManager: Kubernetes context operations
- ResourceManager: General resource CRUD operations
- PodManager: Pod-specific operations
- ClusterManager: Cluster-level operations
All operations support multi-cluster scenarios by accepting kubeContext parameters, enabling the MCP server to work with multiple Kubernetes clusters simultaneously.
Example usage:
// Get a pod from a specific cluster and namespace
pod, err := client.Get(ctx, "production", "default", "pod", "my-pod")
if err != nil {
return err
}
// List all deployments across all namespaces in a cluster
deployments, err := client.List(ctx, "staging", "", "deployment",
ListOptions{AllNamespaces: true})
if err != nil {
return err
}
// Get logs from a pod container
logs, err := client.GetLogs(ctx, "production", "default", "my-pod", "app",
LogOptions{Follow: true, TailLines: &tailLines})
if err != nil {
return err
}
The package focuses on interface definitions and types, with concrete implementations provided in separate packages to maintain clean separation of concerns and enable easy testing through dependency injection.
Package k8s provides Kubernetes client implementations.
Index ¶
- Constants
- func NewClient(config *ClientConfig) (*kubernetesClient, error)
- type APIResourceInfo
- type BearerTokenClientFactory
- type CacheMetricsCallback
- type CacheStats
- type Client
- type ClientCacheConfig
- type ClientConfig
- type ClientFactory
- type ClusterHealth
- type ClusterManager
- type ComponentHealth
- type ContextInfo
- type ContextManager
- type ExecOptions
- type ExecResult
- type FederatedClient
- func (c *FederatedClient) Apply(ctx context.Context, _, namespace string, obj runtime.Object) (runtime.Object, error)
- func (c *FederatedClient) ClusterName() string
- func (c *FederatedClient) Create(ctx context.Context, _, namespace string, obj runtime.Object) (runtime.Object, error)
- func (c *FederatedClient) Delete(ctx context.Context, _, namespace, resourceType, apiGroup, name string) error
- func (c *FederatedClient) Describe(ctx context.Context, _, namespace, resourceType, apiGroup, name string) (*ResourceDescription, error)
- func (c *FederatedClient) Exec(ctx context.Context, _, namespace, podName, containerName string, ...) (*ExecResult, error)
- func (c *FederatedClient) Get(ctx context.Context, _, namespace, resourceType, apiGroup, name string) (runtime.Object, error)
- func (c *FederatedClient) GetAPIResources(ctx context.Context, _ string, limit, offset int, apiGroup string, ...) (*PaginatedAPIResourceResponse, error)
- func (c *FederatedClient) GetClusterHealth(ctx context.Context, _ string) (*ClusterHealth, error)
- func (c *FederatedClient) GetCurrentContext(_ context.Context) (*ContextInfo, error)
- func (c *FederatedClient) GetLogs(ctx context.Context, _, namespace, podName, containerName string, ...) (io.ReadCloser, error)
- func (c *FederatedClient) List(ctx context.Context, _, namespace, resourceType, apiGroup string, ...) (*PaginatedListResponse, error)
- func (c *FederatedClient) ListContexts(_ context.Context) ([]ContextInfo, error)
- func (c *FederatedClient) Patch(ctx context.Context, _, namespace, resourceType, apiGroup, name string, ...) (runtime.Object, error)
- func (c *FederatedClient) PortForward(ctx context.Context, _, namespace, podName string, ports []string, ...) (*PortForwardSession, error)
- func (c *FederatedClient) PortForwardToService(ctx context.Context, _, namespace, serviceName string, ports []string, ...) (*PortForwardSession, error)
- func (c *FederatedClient) Scale(ctx context.Context, _, namespace, resourceType, apiGroup, name string, ...) error
- func (c *FederatedClient) SwitchContext(_ context.Context, _ string) error
- type FederatedClientConfig
- type GroupVersion
- type ListOptions
- type LogOptions
- type Logger
- type NodeHealth
- type PaginatedAPIResourceResponse
- type PaginatedListResponse
- type PodManager
- type PortForwardOptions
- type PortForwardSession
- type ResourceDescription
- type ResourceManager
Constants ¶
const ( // Service account paths - default Kubernetes in-cluster locations DefaultServiceAccountPath = "/var/run/secrets/kubernetes.io/serviceaccount" DefaultTokenPath = DefaultServiceAccountPath + "/token" DefaultCACertPath = DefaultServiceAccountPath + "/ca.crt" DefaultNamespacePath = DefaultServiceAccountPath + "/namespace" // Default performance settings DefaultQPSLimit = 20.0 DefaultBurstLimit = 30 DefaultTimeout = 30 // seconds // Discovery timeout DiscoveryTimeoutSeconds = 30 // In-cluster context name InClusterContext = "in-cluster" )
const DefaultClientCacheCleanupInterval = 1 * time.Minute
DefaultClientCacheCleanupInterval is how often the cache cleanup runs. This is separate from TTL - entries are also removed on access if expired.
const DefaultClientCacheMaxEntries = 100
DefaultClientCacheMaxEntries is the default maximum number of entries in the cache. This prevents unbounded memory growth in high-traffic multi-tenant scenarios. With a 5-minute TTL, this allows for ~100 concurrent users before LRU eviction kicks in.
const DefaultClientCacheTTL = 5 * time.Minute
DefaultClientCacheTTL is the default time-to-live for cached clients.
This value is intentionally much shorter than typical OAuth token expiry (usually 1 hour for Google OAuth) to ensure:
- We don't hold stale credentials longer than necessary
- Memory usage stays bounded with many distinct users
- Configuration changes (e.g., RBAC updates) take effect within a reasonable time
The tradeoff is that users making requests more than 5 minutes apart will incur the cost of creating a new client, but this is acceptable given the security and resource benefits.
Variables ¶
This section is empty.
Functions ¶
func NewClient ¶ added in v0.0.3
func NewClient(config *ClientConfig) (*kubernetesClient, error)
NewClient creates a new Kubernetes client with the given configuration.
Types ¶
type APIResourceInfo ¶
type APIResourceInfo struct {
Name string `json:"name"`
SingularName string `json:"singularName"`
Namespaced bool `json:"namespaced"`
Kind string `json:"kind"`
Verbs []string `json:"verbs"`
Group string `json:"group"`
Version string `json:"version"`
}
APIResourceInfo represents information about an API resource.
type BearerTokenClientFactory ¶ added in v0.0.43
type BearerTokenClientFactory struct {
// contains filtered or unexported fields
}
BearerTokenClientFactory creates bearer token clients from in-cluster configuration. It implements the ClientFactory interface.
func NewBearerTokenClientFactory ¶ added in v0.0.43
func NewBearerTokenClientFactory(config *ClientConfig) (*BearerTokenClientFactory, error)
NewBearerTokenClientFactory creates a new factory for bearer token clients. It reads the in-cluster configuration to get the cluster host and CA cert.
func (*BearerTokenClientFactory) Close ¶ added in v0.0.88
func (f *BearerTokenClientFactory) Close()
Close releases resources held by the factory, including the client cache. This should be called when the factory is no longer needed.
func (*BearerTokenClientFactory) CreateBearerTokenClient ¶ added in v0.0.43
func (f *BearerTokenClientFactory) CreateBearerTokenClient(bearerToken string) (Client, error)
CreateBearerTokenClient creates a new Kubernetes client that uses the provided bearer token for authentication. Clients are cached by token hash to avoid creating new clients for every request, improving performance significantly.
type CacheMetricsCallback ¶ added in v0.0.88
type CacheMetricsCallback interface {
// OnCacheHit is called when a cache hit occurs.
OnCacheHit()
// OnCacheMiss is called when a cache miss occurs.
OnCacheMiss()
// OnCacheEviction is called when an entry is evicted with the reason.
// Reasons: "expired", "lru"
OnCacheEviction(reason string)
// OnCacheSizeChange is called when the cache size changes.
OnCacheSizeChange(size int)
}
CacheMetricsCallback is an interface for recording cache metrics. This allows the cache to report metrics without depending on the instrumentation package.
type CacheStats ¶ added in v0.0.88
Stats returns cache statistics for monitoring.
type Client ¶
type Client interface {
// Context Management Operations
ContextManager
// Resource Management Operations
ResourceManager
// Pod Operations
PodManager
// Cluster Operations
ClusterManager
}
Client defines the interface for Kubernetes operations. It supports multi-cluster operations by accepting kubecontext parameters and provides comprehensive functionality for all MCP tools.
type ClientCacheConfig ¶ added in v0.0.88
type ClientCacheConfig struct {
// TTL is the time-to-live for cached entries. Defaults to DefaultClientCacheTTL.
TTL time.Duration
// MaxEntries is the maximum number of entries before LRU eviction. Defaults to DefaultClientCacheMaxEntries.
// Set to 0 for no limit (not recommended in production).
MaxEntries int
// Metrics is an optional callback for recording cache metrics.
Metrics CacheMetricsCallback
}
ClientCacheConfig holds configuration options for the client cache.
type ClientConfig ¶ added in v0.0.3
type ClientConfig struct {
// Kubeconfig settings
KubeconfigPath string
Context string
// Authentication mode
InCluster bool // Use in-cluster service account authentication instead of kubeconfig
// Safety settings
NonDestructiveMode bool
DryRun bool
AllowedOperations []string
RestrictedNamespaces []string
// Performance settings
QPSLimit float32
BurstLimit int
Timeout time.Duration
// Cache settings (for bearer token client factory)
CacheTTL time.Duration // TTL for cached clients. Defaults to 5 minutes.
CacheMaxEntries int // Max entries before LRU eviction. Defaults to 100.
CacheMetrics CacheMetricsCallback // Optional metrics callback for cache observability.
// Debug settings
DebugMode bool
// Logging
Logger logging.Logger
}
ClientConfig holds configuration for the Kubernetes client.
type ClientFactory ¶ added in v0.0.43
type ClientFactory interface {
// CreateBearerTokenClient creates a new Kubernetes client that uses the provided
// bearer token for authentication. This is used for OAuth passthrough where
// the user's Google OAuth access token is used to authenticate with Kubernetes.
// The baseClient provides the cluster connection details (host, CA cert).
CreateBearerTokenClient(bearerToken string) (Client, error)
}
ClientFactory creates Kubernetes clients with custom authentication. This is used for creating per-user clients when OAuth passthrough is enabled.
type ClusterHealth ¶
type ClusterHealth struct {
Status string `json:"status"`
Components []ComponentHealth `json:"components"`
Nodes []NodeHealth `json:"nodes"`
}
ClusterHealth represents the health status of a Kubernetes cluster.
type ClusterManager ¶
type ClusterManager interface {
// GetAPIResources returns available API resources with pagination support.
GetAPIResources(ctx context.Context, kubeContext string, limit, offset int, apiGroup string, namespacedOnly bool, verbs []string) (*PaginatedAPIResourceResponse, error)
// GetClusterHealth returns the health status of the cluster.
GetClusterHealth(ctx context.Context, kubeContext string) (*ClusterHealth, error)
}
ClusterManager handles cluster-level operations.
type ComponentHealth ¶
type ComponentHealth struct {
Name string `json:"name"`
Status string `json:"status"`
Message string `json:"message,omitempty"`
}
ComponentHealth represents the health of a cluster component.
type ContextInfo ¶
type ContextInfo struct {
Name string `json:"name"`
Cluster string `json:"cluster"`
User string `json:"user"`
Namespace string `json:"namespace"`
Current bool `json:"current"`
}
ContextInfo represents information about a Kubernetes context.
type ContextManager ¶
type ContextManager interface {
// ListContexts returns all available Kubernetes contexts.
ListContexts(ctx context.Context) ([]ContextInfo, error)
// GetCurrentContext returns the currently active context.
GetCurrentContext(ctx context.Context) (*ContextInfo, error)
// SwitchContext changes the active Kubernetes context.
SwitchContext(ctx context.Context, contextName string) error
}
ContextManager handles Kubernetes context operations.
type ExecOptions ¶
type ExecOptions struct {
Stdin io.Reader `json:"-"`
Stdout io.Writer `json:"-"`
Stderr io.Writer `json:"-"`
TTY bool `json:"tty,omitempty"`
}
ExecOptions configures command execution in pods.
type ExecResult ¶
type ExecResult struct {
ExitCode int `json:"exitCode"`
Stdout string `json:"stdout,omitempty"`
Stderr string `json:"stderr,omitempty"`
}
ExecResult contains the result of command execution.
type FederatedClient ¶ added in v0.0.90
type FederatedClient struct {
// contains filtered or unexported fields
}
FederatedClient implements the Client interface for federated multi-cluster operations. It wraps kubernetes.Interface and dynamic.Interface from the federation manager to provide a consistent k8s.Client interface for remote workload clusters.
Unlike kubernetesClient, FederatedClient operates on a single target cluster and does not support context switching (all kubeContext parameters are ignored).
Thread Safety ¶
FederatedClient is safe for concurrent use. All underlying clients are thread-safe, and the struct contains no mutable state.
Security ¶
The underlying clients are pre-configured with user impersonation headers, ensuring all operations are performed under the authenticated user's identity.
func NewFederatedClient ¶ added in v0.0.90
func NewFederatedClient(config *FederatedClientConfig) (*FederatedClient, error)
NewFederatedClient creates a new FederatedClient from federation manager clients. All required fields must be provided or an error is returned.
func (*FederatedClient) Apply ¶ added in v0.0.90
func (c *FederatedClient) Apply(ctx context.Context, _, namespace string, obj runtime.Object) (runtime.Object, error)
Apply applies a resource configuration (create or update). The kubeContext parameter is ignored (federated clients operate on a single cluster).
func (*FederatedClient) ClusterName ¶ added in v0.0.90
func (c *FederatedClient) ClusterName() string
ClusterName returns the name of the target cluster.
func (*FederatedClient) Create ¶ added in v0.0.90
func (c *FederatedClient) Create(ctx context.Context, _, namespace string, obj runtime.Object) (runtime.Object, error)
Create creates a new resource from the provided object. The kubeContext parameter is ignored (federated clients operate on a single cluster).
func (*FederatedClient) Delete ¶ added in v0.0.90
func (c *FederatedClient) Delete(ctx context.Context, _, namespace, resourceType, apiGroup, name string) error
Delete removes a resource by name and namespace. The kubeContext parameter is ignored (federated clients operate on a single cluster).
func (*FederatedClient) Describe ¶ added in v0.0.90
func (c *FederatedClient) Describe(ctx context.Context, _, namespace, resourceType, apiGroup, name string) (*ResourceDescription, error)
Describe provides detailed information about a resource. The kubeContext parameter is ignored (federated clients operate on a single cluster).
func (*FederatedClient) Exec ¶ added in v0.0.90
func (c *FederatedClient) Exec(ctx context.Context, _, namespace, podName, containerName string, command []string, opts ExecOptions) (*ExecResult, error)
Exec executes a command inside a pod container. The kubeContext parameter is ignored (federated clients operate on a single cluster).
func (*FederatedClient) Get ¶ added in v0.0.90
func (c *FederatedClient) Get(ctx context.Context, _, namespace, resourceType, apiGroup, name string) (runtime.Object, error)
Get retrieves a specific resource by name and namespace. The kubeContext parameter is ignored (federated clients operate on a single cluster).
func (*FederatedClient) GetAPIResources ¶ added in v0.0.90
func (c *FederatedClient) GetAPIResources(ctx context.Context, _ string, limit, offset int, apiGroup string, namespacedOnly bool, verbs []string) (*PaginatedAPIResourceResponse, error)
GetAPIResources returns available API resources with pagination support. The kubeContext parameter is ignored (federated clients operate on a single cluster).
func (*FederatedClient) GetClusterHealth ¶ added in v0.0.90
func (c *FederatedClient) GetClusterHealth(ctx context.Context, _ string) (*ClusterHealth, error)
GetClusterHealth returns the health status of the cluster. The kubeContext parameter is ignored (federated clients operate on a single cluster).
func (*FederatedClient) GetCurrentContext ¶ added in v0.0.90
func (c *FederatedClient) GetCurrentContext(_ context.Context) (*ContextInfo, error)
GetCurrentContext returns the current context (always the target cluster).
func (*FederatedClient) GetLogs ¶ added in v0.0.90
func (c *FederatedClient) GetLogs(ctx context.Context, _, namespace, podName, containerName string, opts LogOptions) (io.ReadCloser, error)
GetLogs retrieves logs from a pod container. The kubeContext parameter is ignored (federated clients operate on a single cluster).
func (*FederatedClient) List ¶ added in v0.0.90
func (c *FederatedClient) List(ctx context.Context, _, namespace, resourceType, apiGroup string, opts ListOptions) (*PaginatedListResponse, error)
List retrieves resources with pagination support. The kubeContext parameter is ignored (federated clients operate on a single cluster).
func (*FederatedClient) ListContexts ¶ added in v0.0.90
func (c *FederatedClient) ListContexts(_ context.Context) ([]ContextInfo, error)
ListContexts returns a single context representing this federated cluster. Context switching is not supported for federated clients.
func (*FederatedClient) Patch ¶ added in v0.0.90
func (c *FederatedClient) Patch(ctx context.Context, _, namespace, resourceType, apiGroup, name string, patchType types.PatchType, data []byte) (runtime.Object, error)
Patch updates specific fields of a resource. The kubeContext parameter is ignored (federated clients operate on a single cluster).
func (*FederatedClient) PortForward ¶ added in v0.0.90
func (c *FederatedClient) PortForward(ctx context.Context, _, namespace, podName string, ports []string, opts PortForwardOptions) (*PortForwardSession, error)
PortForward sets up port forwarding to a pod. The kubeContext parameter is ignored (federated clients operate on a single cluster).
func (*FederatedClient) PortForwardToService ¶ added in v0.0.90
func (c *FederatedClient) PortForwardToService(ctx context.Context, _, namespace, serviceName string, ports []string, opts PortForwardOptions) (*PortForwardSession, error)
PortForwardToService sets up port forwarding to the first available pod behind a service. The kubeContext parameter is ignored (federated clients operate on a single cluster).
func (*FederatedClient) Scale ¶ added in v0.0.90
func (c *FederatedClient) Scale(ctx context.Context, _, namespace, resourceType, apiGroup, name string, replicas int32) error
Scale changes the number of replicas for scalable resources. The kubeContext parameter is ignored (federated clients operate on a single cluster).
func (*FederatedClient) SwitchContext ¶ added in v0.0.90
func (c *FederatedClient) SwitchContext(_ context.Context, _ string) error
SwitchContext is not supported for federated clients. The client is bound to a single target cluster.
type FederatedClientConfig ¶ added in v0.0.90
type FederatedClientConfig struct {
// ClusterName is the name of the target cluster (for logging/debugging)
ClusterName string
// Clientset is the Kubernetes clientset from the federation manager
Clientset kubernetes.Interface
// DynamicClient is the dynamic client from the federation manager
DynamicClient dynamic.Interface
// RestConfig is the REST configuration from the federation manager
RestConfig *rest.Config
}
FederatedClientConfig holds the configuration for creating a FederatedClient.
type GroupVersion ¶ added in v0.0.3
GroupVersion represents a Kubernetes API group and version.
type ListOptions ¶
type ListOptions struct {
LabelSelector string `json:"labelSelector,omitempty"`
FieldSelector string `json:"fieldSelector,omitempty"`
AllNamespaces bool `json:"allNamespaces,omitempty"`
// Pagination options
Limit int64 `json:"limit,omitempty"` // Maximum number of items to return (0 = no limit)
Continue string `json:"continue,omitempty"` // Continue token from previous request
}
ListOptions provides configuration for list operations.
type LogOptions ¶
type LogOptions struct {
Follow bool `json:"follow,omitempty"`
Previous bool `json:"previous,omitempty"`
Timestamps bool `json:"timestamps,omitempty"`
SinceTime *time.Time `json:"sinceTime,omitempty"`
TailLines *int64 `json:"tailLines,omitempty"`
// Pagination options for log output
SinceLines *int64 `json:"sinceLines,omitempty"` // Skip this many lines from the beginning
MaxLines *int64 `json:"maxLines,omitempty"` // Maximum number of lines to return
}
LogOptions configures log retrieval.
type Logger ¶ added in v0.0.3
Logger is an alias for logging.Logger for backward compatibility. New code should use logging.Logger directly.
type NodeHealth ¶
type NodeHealth struct {
Name string `json:"name"`
Ready bool `json:"ready"`
Conditions []corev1.NodeCondition `json:"conditions"`
}
NodeHealth represents the health of a cluster node.
type PaginatedAPIResourceResponse ¶ added in v0.0.17
type PaginatedAPIResourceResponse struct {
Items []APIResourceInfo `json:"items"`
TotalItems int `json:"totalItems"` // Number of items in this response
TotalCount int `json:"totalCount"` // Total number of items available
HasMore bool `json:"hasMore"` // Whether there are more items available
NextOffset int `json:"nextOffset"` // Offset for next page (if hasMore is true)
}
PaginatedAPIResourceResponse contains a paginated list of API resources
type PaginatedListResponse ¶ added in v0.0.17
type PaginatedListResponse struct {
Items []runtime.Object `json:"items"`
Continue string `json:"continue,omitempty"` // Token for next page
RemainingItems *int64 `json:"remainingItems,omitempty"` // Estimated remaining items (if available)
ResourceVersion string `json:"resourceVersion,omitempty"` // Resource version for consistency
TotalItems int `json:"totalItems"` // Number of items in this response
}
PaginatedListResponse contains a paginated list of resources with metadata
type PodManager ¶
type PodManager interface {
// GetLogs retrieves logs from a pod container.
GetLogs(ctx context.Context, kubeContext, namespace, podName, containerName string, opts LogOptions) (io.ReadCloser, error)
// Exec executes a command inside a pod container.
Exec(ctx context.Context, kubeContext, namespace, podName, containerName string, command []string, opts ExecOptions) (*ExecResult, error)
// PortForward sets up port forwarding to a pod.
PortForward(ctx context.Context, kubeContext, namespace, podName string, ports []string, opts PortForwardOptions) (*PortForwardSession, error)
// PortForwardToService sets up port forwarding to the first available pod behind a service.
PortForwardToService(ctx context.Context, kubeContext, namespace, serviceName string, ports []string, opts PortForwardOptions) (*PortForwardSession, error)
}
PodManager handles pod-specific operations.
type PortForwardOptions ¶
PortForwardOptions configures port forwarding.
type PortForwardSession ¶
type PortForwardSession struct {
LocalPorts []int `json:"localPorts"`
RemotePorts []int `json:"remotePorts"`
StopChan chan struct{} `json:"-"`
ReadyChan chan struct{} `json:"-"`
Forwarder *portforward.PortForwarder `json:"-"`
}
PortForwardSession represents an active port forwarding session.
type ResourceDescription ¶
type ResourceDescription struct {
Resource runtime.Object `json:"resource"`
Events []corev1.Event `json:"events,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
ResourceDescription contains detailed information about a resource.
type ResourceManager ¶
type ResourceManager interface {
// Get retrieves a specific resource by name and namespace.
Get(ctx context.Context, kubeContext, namespace, resourceType, apiGroup, name string) (runtime.Object, error)
// List retrieves resources with pagination support.
List(ctx context.Context, kubeContext, namespace, resourceType, apiGroup string, opts ListOptions) (*PaginatedListResponse, error)
// Describe provides detailed information about a resource.
Describe(ctx context.Context, kubeContext, namespace, resourceType, apiGroup, name string) (*ResourceDescription, error)
// Create creates a new resource from the provided object.
Create(ctx context.Context, kubeContext, namespace string, obj runtime.Object) (runtime.Object, error)
// Apply applies a resource configuration (create or update).
Apply(ctx context.Context, kubeContext, namespace string, obj runtime.Object) (runtime.Object, error)
// Delete removes a resource by name and namespace.
Delete(ctx context.Context, kubeContext, namespace, resourceType, apiGroup, name string) error
// Patch updates specific fields of a resource.
Patch(ctx context.Context, kubeContext, namespace, resourceType, apiGroup, name string, patchType types.PatchType, data []byte) (runtime.Object, error)
// Scale changes the number of replicas for scalable resources.
Scale(ctx context.Context, kubeContext, namespace, resourceType, apiGroup, name string, replicas int32) error
}
ResourceManager handles Kubernetes resource operations.