weibaohui_kom

weibaohui_kom

by weibaohui
A Kubernetes operations tool with SDK-level kubectl and client-go encapsulation, supporting MCP server functionality.

Kubernetes Operations Manager (kom)

Overview

kom is a powerful tool designed for Kubernetes operations, providing an SDK-level encapsulation of kubectl and client-go. It offers a wide range of functionalities to manage Kubernetes resources, including creating, updating, deleting, and retrieving resources. Additionally, it supports SQL queries for Kubernetes resources and can handle Custom Resource Definitions (CRDs). With kom, you can easily perform CRUD operations, retrieve logs, and manage files within Pods.

Features

  1. Ease of Use: kom provides a rich set of features, including CRUD operations for both built-in and CRD resources.
  2. Multi-Cluster Support: Easily manage multiple Kubernetes clusters with RegisterCluster.
  3. MCP Support: Manage multi-cluster MCP with SSE mode, enabling operations on any resource via large models.
  4. Cross-Namespace Queries: Query resources across multiple namespaces.
  5. Chaining Calls: Simplify resource operations with chaining calls.
  6. CRD Support: Easily define and operate custom resources.
  7. Callback Mechanism: Extend business logic without tightly coupling with Kubernetes operations.
  8. Pod File Operations: Upload, download, and delete files within Pods.
  9. High-Frequency Operations: Encapsulate frequent operations like restarting, scaling, and stopping Deployments.
  10. SQL Queries: Use SQL to query Kubernetes resources.
  11. Query Caching: Improve query performance with cache expiration settings.

Installation

import (
    "github.com/weibaohui/kom"
    "github.com/weibaohui/kom/callbacks"
)
func main() {
    // Register callbacks first
    callbacks.RegisterInit()
    // Register clusters
    defaultKubeConfig := os.Getenv("KUBECONFIG")
    if defaultKubeConfig == "" {
        defaultKubeConfig = filepath.Join(homedir.HomeDir(), ".kube", "config")
    }
    _, _ = kom.Clusters().RegisterInCluster()
    _, _ = kom.Clusters().RegisterByPathWithID(defaultKubeConfig, "default")
    kom.Clusters().Show()
    // Other logic
}

Usage Examples

0. Multi-Cluster Kubernetes MCP Support

// Start MCP Server with one line of code
mcp.RunMCPServer("kom mcp server", "0.0.1", 9096)
# MCP Server access URL
http://IP:9096/sse
delete_k8s_resource
describe_k8s_resource
get_k8s_resource
get_pod_linked_endpoints
get_pod_linked_ingresses
get_pod_linked_pv
get_pod_linked_pvc
get_pod_linked_services
get_pod_logs
list_clusters
list_k8s_event
list_k8s_resource
pod_file_operations
restart_deployment
scale_deployment

AI Tool Integration

Claude Desktop
  1. Open Claude Desktop settings panel.
  2. Add MCP Server address in the API configuration area.
  3. Enable SSE event listening.
  4. Verify connection status.
Cursor
  1. Enter Cursor settings interface.
  2. Find the extension service configuration option.
  3. Add MCP Server URL (e.g., http://localhost:3619/sse).
  4. Enable real-time event notifications.
Windsurf
  1. Access the configuration center.
  2. Set the API server address.
  3. Enable real-time event notifications.
  4. Test the connection.

1. Multi-Cluster Management

Register Multiple Clusters

// Register InCluster cluster with the name "InCluster"
kom.Clusters().RegisterInCluster()
// Register two named clusters, "orb" and "docker-desktop"
kom.Clusters().RegisterByPathWithID("/Users/kom/.kube/orb", "orb")
kom.Clusters().RegisterByPathWithID("/Users/kom/.kube/config", "docker-desktop")
// Register a cluster named "default"
kom.Clusters().RegisterByPathWithID("/Users/kom/.kube/config", "default")

Show Registered Clusters

kom.Clusters().Show()

Select Default Cluster

// Use the default cluster to query Pods in the "kube-system" namespace
var pods []corev1.Pod
err = kom.DefaultCluster().Resource(&corev1.Pod{}).Namespace("kube-system").List(&pods).Error

Select Specific Cluster

// Select the "orb" cluster to query Pods in the "kube-system" namespace
var pods []corev1.Pod
err = kom.Cluster("orb").Resource(&corev1.Pod{}).Namespace("kube-system").List(&pods).Error

2. CRUD Operations and Watch Examples

Create a Resource

item = v1.Deployment{
    ObjectMeta: metav1.ObjectMeta{
        Name:      "nginx",
        Namespace: "default",
    },
    Spec: v1.DeploymentSpec{
        Template: corev1.PodTemplateSpec{
            Spec: corev1.PodSpec{
                Containers: []corev1.Container{
                    {Name: "test", Image: "nginx:1.14.2"},
                },
            },
        },
    },
}
err := kom.DefaultCluster().Resource(&item).Create(&item).Error

Get a Resource

// Query the Deployment named "nginx" in the "default" namespace
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").Get(&item).Error
// Query with a 5-second cache
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").WithCache(5 * time.Second).Get(&item).Error

List Resources

// Query the list of Deployments in the "default" namespace
err := kom.DefaultCluster().Resource(&item).Namespace("default").List(&items).Error
// Query Deployments in "default" and "kube-system" namespaces
err := kom.DefaultCluster().Resource(&item).Namespace("default","kube-system").List(&items).Error
// Query Deployments in all namespaces
err := kom.DefaultCluster().Resource(&item).Namespace("*").List(&items).Error
err := kom.DefaultCluster().Resource(&item).AllNamespace().List(&items).Error
// Set a 5-second cache for the list
err := kom.DefaultCluster().Resource(&item).WithCache(5 * time.Second).List(&nodeList).Error

Update a Resource

// Update the Deployment named "nginx" by adding an annotation
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").Get(&item).Error
if item.Spec.Template.Annotations == nil {
    item.Spec.Template.Annotations = map[string]string{}
}
item.Spec.Template.Annotations["kom.kubernetes.io/restartedAt"] = time.Now().Format(time.RFC3339)
err = kom.DefaultCluster().Resource(&item).Update(&item).Error

Delete a Resource

// Delete the Deployment named "nginx"
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").Delete().Error

Force Delete a Resource

// Force delete the Deployment named "nginx"
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").ForceDelete().Error

3. YAML Operations

yaml := `apiVersion: v1
kind: ConfigMap
metadata:
  name: example-config
  namespace: default
data:
  key: value
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: example-deployment
  namespace: default
spec:
  replicas: 1
  selector:
    matchLabels:
      app: example
  template:
    metadata:
      labels:
        app: example
    spec:
      containers:
        - name: example-container
          image: nginx
`
// First Apply creates the resources, returns the execution result for each resource
results := kom.DefaultCluster().Applier().Apply(yaml)
// Second Apply updates the resources, returns the execution result for each resource
results = kom.DefaultCluster().Applier().Apply(yaml)
// Delete the resources, returns the execution result for each resource
results = kom.DefaultCluster().Applier().Delete(yaml)

4. Pod Operations

Get Logs

// Get Pod logs
var stream io.ReadCloser
err := kom.DefaultCluster().Namespace("default").Name("random-char-pod").Ctl().Pod().ContainerName("container").GetLogs(&stream, &corev1.PodLogOptions{}).Error
reader := bufio.NewReader(stream)
line, _ := reader.ReadString('\n')
fmt.Println(line)

Execute Commands

// Execute the `ps -ef` command in the Pod
var execResult string
err := kom.DefaultCluster().Namespace("default").Name("random-char-pod").Ctl().Pod().ContainerName("container").Command("ps", "-ef").ExecuteCommand(&execResult).Error
fmt.Printf("execResult: %s", execResult)

Stream Commands

cb := func(data []byte) error {
    fmt.Printf("Data %s\n", string(data))
    return nil
}
err := kom.DefaultCluster().Namespace("kube-system").Name("traefik-d7c9c5778-p9nf4").Ctl().Pod().ContainerName("traefik").Command("ping", "127.0.0.1").StreamExecute(cb, cb).Error

5. CRD Operations

Create a CRD

yaml := `apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: crontabs.stable.example.com
spec:
  group: stable.example.com
  versions:
    - name: v1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                cronSpec:
                  type: string
                image:
                  type: string
                replicas:
                  type: integer
  scope: Namespaced
  names:
    plural: crontabs
    singular: crontab
    kind: CronTab
    shortNames:
    - ct`
result := kom.DefaultCluster().Applier().Apply(yaml)

Create a CR Object

item = unstructured.Unstructured{
    Object: map[string]interface{}{
        "apiVersion": "stable.example.com/v1",
        "kind":       "CronTab",
        "metadata": map[string]interface{}{
            "name":      "test-crontab",
            "namespace": "default",
        },
        "spec": map[string]interface{}{
            "cronSpec": "* * * * */8",
            "image":    "test-crontab-image",
        },
    },
}
err := kom.DefaultCluster().CRD("stable.example.com", "v1", "CronTab").Namespace(item.GetNamespace()).Name(item.GetName()).Create(&item).Error

6. Cluster Information

// Cluster documentation
kom.DefaultCluster().Status().Docs()
// Cluster resource information
kom.DefaultCluster().Status().APIResources()
// List of registered CRDs
kom.DefaultCluster().Status().CRDList()
// Cluster version information
kom.DefaultCluster().Status().ServerVersion()

7. Callback Mechanism

// Register a callback for Get operations
kom.DefaultCluster().Callback().Get().Register("get", cb)
// Register a callback for List operations
kom.DefaultCluster().Callback().List().Register("list", cb)
// Register a callback for Create operations
kom.DefaultCluster().Callback().Create().Register("create", cb)
// Register a callback for Update operations
kom.DefaultCluster().Callback().Update().Register("update", cb)
// Register a callback for Patch operations
kom.DefaultCluster().Callback().Patch().Register("patch", cb)
// Register a callback for Delete operations
kom.DefaultCluster().Callback().Delete().Register("delete", cb)
// Register a callback for Watch operations
kom.DefaultCluster().Callback().Watch().Register("watch",cb)
// Register a callback for Exec operations
kom.DefaultCluster().Callback().Exec().Register("exec", cb)
// Register a callback for Logs operations
kom.DefaultCluster().Callback().Logs().Register("logs", cb)
// Delete a callback
kom.DefaultCluster().Callback().Get().Delete("get")
// Replace a callback
kom.DefaultCluster().Callback().Get().Replace("get", cb)
// Specify callback execution order
kom.DefaultCluster().Callback().After("kom:get").Register("get", cb)
kom.DefaultCluster().Callback().Before("kom:create").Register("create", cb)

8. SQL Queries for Kubernetes Resources

Query Built-in Resources

sql := "select * from deploy where metadata.namespace='kube-system' or metadata.namespace='default' order by  metadata.creationTimestamp asc   "
var list []v1.Deployment
err := kom.DefaultCluster().Sql(sql).List(&list).Error
for _, d := range list {
    fmt.Printf("List Items foreach %s,%s at %s \n", d.GetNamespace(), d.GetName(), d.GetCreationTimestamp())
}

Query CRD Resources

sql := "select * from vm where (metadata.namespace='kube-system' or metadata.namespace='default' )  "
var list []unstructured.Unstructured
err := kom.DefaultCluster().Sql(sql).List(&list).Error
for _, d := range list {
    fmt.Printf("List Items foreach %s,%s\n", d.GetNamespace(), d.GetName())
}

9. Other Operations

Restart a Deployment

err = kom.DefaultCluster().Resource(&Deployment{}).Namespace("default").Name("nginx").Ctl().Rollout().Restart()

Scale a Deployment

// Scale the Deployment named "nginx" to 3 replicas
err = kom.DefaultCluster().Resource(&Deployment{}).Namespace("default").Name("nginx").Ctl().Scaler().Scale(3)

Stop a Deployment

// Scale the Deployment named "nginx" to 0 replicas
err = kom.DefaultCluster().Resource(&Deployment{}).Namespace("default").Name("nginx").Ctl().Scaler().Stop()

Restore a Deployment

// Restore the Deployment named "nginx" to its previous replica count
err = kom.DefaultCluster().Resource(&Deployment{}).Namespace("default").Name("nginx").Ctl().Scaler().Restore()

Update Deployment Tag

// Update the image tag of the Deployment named "nginx"
err = kom.DefaultCluster().Resource(&Deployment{}).Namespace("default").Name("nginx").Ctl().Deployment().ReplaceImageTag("main","20241124")

Kubernetes Version Compatibility

Kubernetes Version Test Result
V1.31.3
V1.31.2
V1.31.1
V1.31.0
V1.30.7
V1.29.0
V1.25.7
V1.24.7
V1.23.7
V1.22.3
V1.22.2
V1.21.0

Contact

WeChat (大罗马的太阳) Search ID: daluomadetaiyang, note: kom.

License

MIT License

Security Policy

Security Policy

Stars

85 stars

Watchers

4 watching

Forks

9 forks

Releases

116 Releases

Packages

No packages published.

Languages

Features & Capabilities

Categories
mcp_server model_context_protocol kubernetes kubectl client-go go sql multi_cluster crd api_integration ai_tools search

Implementation Details

Stats

0 Views
85 GitHub Stars

Repository Info

weibaohui Organization

Similar MCP Servers

continuedev_continue by continuedev
25049
21423
9300