MCP Server Kubernetes

repository·main·Indexed 23 days ago

https://github.com/flux159/mcp-server-kubernetes

A Model Context Protocol (MCP) server version 4.1.2 that enables AI assistants to connect to, manage, and troubleshoot Kubernetes clusters. It provides tools mapping to kubectl and Helm commands and supports multiple kubeconfig providers including AWS EKS, GCP GKE, URLs, and custom volumes. The server includes features for secure HTTP/SSE transport, IAM integration (IRSA, Workload Identity), non-destructive and read-only security modes, and is deployable via a comprehensive Helm chart.

Tokens
23.3K
Snippets
60
Records
111
Agent score
80%

What's inside mcp-server-kubernetes

  1. Use the node_management tool for Kubernetes node operations

    main

    The node_management tool allows you to manage Kubernetes nodes through several operations: listing nodes, cordoning (marking as unschedulable), draining (evicting pods for maintenance), and uncordoning (re-enabling scheduling).

    Available Operations

    • list: Lists all nodes in the cluster with their current status.
    • cordon: Marks a specific node as unschedulable to prevent new pods from being scheduled.
    • drain: Safely evicts pods from a node. This is a destructive operation that requires specific safety parameters.
    • uncordon: Re-enables scheduling on a previously cordoned node.

    Safety Features

    • Dry Run: Use dryRun: true to preview an operation without executing it.
    • Confirmation: Drain operations require confirmDrain: true to proceed.
    • DaemonSet Protection: Use ignoreDaemonsets: true to prevent drain failures caused by DaemonSet pods.
    • Timeouts: Use the timeout parameter to prevent hanging operations.
    {
      "operation": "list"
    }
  2. Use the /k8s-diagnose Prompt

    main

    The server includes a specialized prompt /k8s-diagnose designed for systematic troubleshooting of Kubernetes pods.

    Usage: Provide a keyword to identify relevant pods and an optional namespace to narrow the scope. The prompt will guide you through an autonomous flow to identify issues, collect evidence, and suggest remediation steps.

  3. Restrict server capabilities using Tool Filtering Modes

    main

    You can control which tools are exposed to the client using three prioritized modes via environment variables:

    1. ALLOWED_TOOLS: A comma-separated list of specific tool names (e.g., kubectl_get,kubectl_describe). If a name is misspelled, the server will exit with an error.
    2. ALLOW_ONLY_READONLY_TOOLS: Limits the server to tools that cannot alter cluster state. Available tools include: kubectl_get, kubectl_describe, kubectl_logs, kubectl_context, explain_resource, list_api_resources, and ping.
    3. ALLOW_ONLY_NON_DESTRUCTIVE_TOOLS: Disables all destructive operations (like delete_pod, delete_deployment, delete_namespace, uninstall_helm_chart, delete_cronjob, and cleanup) while keeping all read operations functional.
  4. Configure sampling strategies for OpenTelemetry

    main

    You can control the volume of telemetry data using different sampling strategies via OTEL_TRACES_SAMPLER:

    SamplerDescriptionUse Case
    always_on100% samplingDevelopment, debugging
    always_off0% samplingDisable tracing
    traceidratioPercentage-based (requires OTEL_TRACES_SAMPLER_ARG)Production (1-10% typical)

    Production Recommendation: Use traceidratio with 5-10% sampling to balance observability and cost.

  5. How the MCP Kubernetes server request flow works

    main

    The server follows a layered architecture to process requests from a client (like Claude Desktop or VS Code) to the Kubernetes API.

    1. Transport Layer: Receives requests via StdioTransport or SSE Transport.
    2. Tool Filter: If a tool request is made, the server checks if it is in non-destructive mode. If so, it filters out destructive tools.
    3. Request Handler: Routes the request to the appropriate handler (Tools or Resources).
    4. KubernetesManager: Executes the specific operation (kubectl, Helm, or Port Forwarding) by making API calls to the Kubernetes cluster.
    5. Response: The result is processed by the handler and sent back through the transport layer to the client.
    sequenceDiagram
        participant Client
        participant Transport as Transport Layer
        participant Server as MCP Server
        participant Filter as Tool Filter
        participant Handler as Request Handler
        participant K8sManager as KubernetesManager
        participant K8s as Kubernetes API
    
        Note over Transport: StdioTransport or<br>SSE Transport
    
        Client->>Transport: Send Request
        Transport->>Server: Forward Request
    
        alt Tools Request
            Server->>Filter: Filter available tools
            Note over Filter: Remove destructive tools<br>if in non-destructive mode
            Filter->>Handler: Route to tools handler
    
            alt kubectl operations
                Handler->>K8sManager: Execute kubectl operation
                K8sManager->>K8s: Make API call
            else Helm operations
                Handler->>K8sManager: Execute Helm operation
                K8sManager->>K8s: Make API call
            else Port Forward operations
                Handler->>K8sManager: Set up port forwarding
                K8sManager->>K8s: Make API call
            end
    
            K8s-->>K8sManager: Return result
            K8sManager-->>Handler: Process response
            Handler-->>Server: Return tool result
        else Resource Request
            Server->>Handler: Route to resource handler
            Handler->>K8sManager: Get resource data
            K8sManager->>K8s: Query API
            K8s-->>K8sManager: Return data
            K8sManager-->>Handler: Format response
            Handler-->>Server: Return resource data
        end
    
        Server-->>Transport: Send Response
        Transport-->>Client: Return Final Response
  6. Understand observability performance impact

    main

    Observability via OpenTelemetry introduces minimal overhead:

    MetricImpact
    Middleware overhead1-2ms per tool call
    Memory footprint5-10MB for span buffers
    CPU impact<1% for typical workloads
    NetworkAsync batch exports (5-second intervals)
    BlockingZero (async export)

    Performance Tips:

    • Use sampling in production to reduce overhead by 90-99%.
    • Telemetry uses async batch exports (every 5 seconds) to avoid blocking the critical path.
  7. Configure Kubernetes authentication methods

    main

    The server supports multiple authentication methods, applied in the following priority order:

    1. KUBECONFIG_YAML: Full configuration as a YAML string.
    2. KUBECONFIG_JSON: Full configuration as a JSON string.
    3. K8S_SERVER + K8S_TOKEN: Minimal environment-based configuration.
    4. In-cluster: Automatic detection if running inside a Kubernetes pod.
    5. KUBECONFIG_PATH: Path to a custom kubeconfig file.
    6. KUBECONFIG: Standard kubeconfig environment variable.
    7. Default file: ~/.kube/config.

    Note on TLS: If you provide K8S_CA_DATA (a base64-encoded CA certificate), K8S_SKIP_TLS_VERIFY is automatically forced to false to ensure secure communication.

    # Example: Minimal configuration with overrides
    export K8S_SERVER='https://prod-cluster.example.com'
    export K8S_TOKEN='eyJhbGciOiJSUzI1NiIsImtpZCI6...'
    export K8S_CA_DATA='LS0tLS1CRUdJTi...'  # base64-encoded CA certificate
    export K8S_CONTEXT='production'
    export K8S_NAMESPACE='my-app'
    export K8S_SKIP_TLS_VERIFY='false'
  8. When to use Template Mode

    main

    Enable useTemplate: true to use the helm template + kubectl apply workflow instead of the standard helm install command. This mode is recommended when you encounter:

    • Authentication issues with Helm
    • Kubeconfig API version mismatches
    • Problems with Helm's direct cluster access
    • A need for more control over the installation process

    In Template Mode, the tool generates YAML via helm template and applies it using kubectl apply, bypassing Helm's direct cluster communication.

  9. Configure Kubeconfig using URL or Custom Volumes

    main

    You can provide kubeconfigs via URLs or by mounting them from existing Kubernetes volumes (Secrets or ConfigMaps).

    URL-based provider: Set kubeconfig.provider=url and provide a list of configurations with name and url keys.

    Volume-based provider: Set kubeconfig.provider=volume. This is useful for using pre-existing Secrets/ConfigMaps or external secret managers. You must specify the path within the container, the volumeSpec (e.g., secret.secretName), and the volumeMountSpec (e.g., mountPath).

    # URL-based example
    helm install mcp-server-k8s ./helm-chart \
      --set kubeconfig.provider=url \
      --set kubeconfig.url.configs[0].name=prod-config \
      --set kubeconfig.url.configs[0].url="https://storage.company.com/prod.yaml"
    
    # Volume-based example (CLI)
    helm install mcp-server-k8s ./helm-chart \
      --set kubeconfig.provider=volume \
      --set kubeconfig.volume.path=/home/node/.kube/config \
      --set kubeconfig.volume.volumeSpec.name=kubeconfig \
      --set kubeconfig.volume.volumeSpec.secret.secretName=my-kubeconfig-secret \
      --set kubeconfig.volume.volumeMountSpec.name=kubeconfig \
      --set kubeconfig.volume.volumeMountSpec.mountPath=/home/node/.kube \
      --set kubeconfig.volume.volumeMountSpec.readOnly=true
  10. Enable Streamable HTTP Transport

    main

    To use the Streamable HTTP transport (the recommended modern transport), set ENABLE_UNSAFE_STREAMABLE_HTTP_TRANSPORT=1. This starts an HTTP server at the /mcp endpoint.

    Configuration

    • PORT: The server port (defaults to 3000).
    • HOST: The listening interface (defaults to localhost).

    DNS Rebinding Protection

    DNS rebinding protection is enabled by default. The server only accepts requests with Host headers matching localhost, 127.0.0.1, ::1, or the configured HOST value.

    To host on a custom domain (e.g., mcp.example.com), use DNS_REBINDING_ALLOWED_HOST:

    DNS_REBINDING_ALLOWED_HOST=mcp.example.com ENABLE_UNSAFE_STREAMABLE_HTTP_TRANSPORT=1 PORT=3001 HOST=0.0.0.0 npx flux159/mcp-server-kubernetes
    ENABLE_UNSAFE_STREAMABLE_HTTP_TRANSPORT=1 npx flux159/mcp-server-kubernetes