k8s

package
v0.0.28 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2025 License: Apache-2.0 Imports: 27 Imported by: 0

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.

Index

Constants

This section is empty.

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 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 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

	// Debug settings
	DebugMode bool

	// Logging
	Logger Logger
}

ClientConfig holds configuration for the Kubernetes client.

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 GroupVersion added in v0.0.3

type GroupVersion struct {
	Group   string
	Version string
}

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

type Logger interface {
	Debug(msg string, args ...interface{})
	Info(msg string, args ...interface{})
	Warn(msg string, args ...interface{})
	Error(msg string, args ...interface{})
}

Logger interface for client logging (simple version for now).

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

type PortForwardOptions struct {
	Stdout io.Writer `json:"-"`
	Stderr io.Writer `json:"-"`
}

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, name string) (runtime.Object, error)

	// List retrieves resources with pagination support.
	List(ctx context.Context, kubeContext, namespace, resourceType string, opts ListOptions) (*PaginatedListResponse, error)

	// Describe provides detailed information about a resource.
	Describe(ctx context.Context, kubeContext, namespace, resourceType, 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, name string) error

	// Patch updates specific fields of a resource.
	Patch(ctx context.Context, kubeContext, namespace, resourceType, 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, name string, replicas int32) error
}

ResourceManager handles Kubernetes resource operations.

Jump to

Keyboard shortcuts

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