Kubernetes MCP Server

repository·main·Indexed 23 days ago

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

A high-performance, Go-based Model Context Protocol (MCP) server that enables AI agents to interact directly with Kubernetes and OpenShift APIs. It provides deep integration for managing resources, pods, Helm charts, and Tekton pipelines, with specialized toolsets for Kiali, NetObserv, and KubeVirt. The server includes features for RBAC management, TLS configuration, Prometheus monitoring, and OpenTelemetry support.

Tokens
45.4K
Snippets
89
Records
198
Agent score
83%

What's inside kubernetes-mcp-server

  1. What is Kubernetes MCP Server

    main

    Kubernetes MCP Server is a Go-based native implementation of the Model Context Protocol (MCP) that allows AI agents to interact directly with Kubernetes and OpenShift clusters.

    Unlike implementations that wrap CLI tools like kubectl or helm, this server communicates directly with the Kubernetes API server, providing high performance and low latency. It is distributed as a single native binary for Linux, macOS, and Windows, but is also available via npm, PyPI, and Docker.

    Key capabilities include:

    • Generic Resource Management: CRUD operations on any Kubernetes or OpenShift resource.
    • Pod Operations: Listing, getting, deleting, viewing logs, checking resource usage (top), executing commands (exec), and running container images.
    • Namespace & Event Management: Listing namespaces and viewing events.
    • OpenShift Support: Listing OpenShift Projects.
    • Helm Integration: Installing, listing, and uninstalling Helm releases.
    • Tekton Support: Managing Pipelines, PipelineRuns, Tasks, and TaskRuns.
    • Observability: Optional OpenTelemetry tracing and metrics with a /stats endpoint.
  2. Kiali task categories and examples

    main

    The Kiali task stack is organized into several functional categories. Each task is defined by a scenario name, a difficulty level, and a specific prompt for the MCP server to execute.

    Common categories include:

    • Configuration Management: Managing Istio and Gateway API resources (e.g., istio-list, istio-patch).
    • Mesh Health & Status: Auditing connectivity and namespace health (e.g., status-kiali-istio).
    • Performance Analysis: Analyzing traffic volume and latency (e.g., metrics-service-request-rate).
    • Resource Inspection: Inventorying services, workloads, and namespaces (e.g., resource-list-workloads).
    • Traffic Observability: Visualizing topology and graphs (e.g., show-topology).
    • Troubleshooting & Diagnostics: Debugging via logs and traces (e.g., troubleshooting-workload-logs).
  3. Understand the MCP Task Library structure

    main

    The MCP Task Library contains reusable task scenarios used for evaluating agents against the Kubernetes MCP Server. Tasks represent realistic cluster workflows including setup, agent actions, verification, and cleanup.

    Tasks are organized into Task Families based on the toolset they exercise:

    • Core tasks (core/): Pod creation, deployment fixes, RBAC, and debugging.
    • Config tasks (config/): Contexts and configuration management.
    • Helm tasks (helm/): Helm release management (install, list, uninstall).
    • Kiali tasks (kiali/): Service-mesh and observability (Istio, topology, mesh health).
    • KubeVirt tasks (kubevirt/): Virtual machine lifecycle and resource management.
    • Tekton tasks (tekton/): CI/CD pipelines and task runs.
    • NetObserv tasks (netobserv/): Network flows and metrics.
  4. Available Tekton MCP Evaluation Tasks

    main

    The Tekton Task Stack includes several self-contained scenarios categorized by the type of Tekton resource they exercise. These tasks test the ability of an MCP agent to manage Pipelines, PipelineRuns, and Tasks.

    Pipeline Operations

    • list-pipelines (easy): List Tekton Pipelines in a namespace.
    • get-pipeline (easy): Retrieve a specific Pipeline by name.
    • create-pipeline (easy): Create a new Pipeline from a YAML definition.
    • start-pipeline (medium): Start a Pipeline by triggering a new PipelineRun.

    PipelineRun Operations

    • list-pipelineruns (easy): List PipelineRuns in a namespace.
    • delete-pipelinerun (medium): Delete a specific PipelineRun.
    • restart-pipelinerun (medium): Restart a PipelineRun by creating a new one with the same spec.
    • cancel-pipelinerun (medium): Cancel a PipelineRun by setting spec.status=Cancelled.
    • troubleshoot-pipelinerun (hard): Gather PipelineRun status, TaskRuns, logs, events, Pipeline-as-Code Repository, and TektonConfig context for diagnosis.

    Task Operations

    • create-task (easy): Create a new Tekton Task from a YAML definition.
    • start-task (medium): Start a Task by creating a TaskRun for it.
  5. Resolve toolset names dynamically

    main

    Because toolsets can be rebranded by downstream users (e.g., kiali $\rightarrow$ ossm), do not hardcode the upstream toolset name when invoking tools. Instead, use the toolset's GetName() method to resolve the current name at runtime.

    Note on Configuration Keys: While you should resolve the toolset name dynamically for tool calls, the TOML key under [toolset_configs.<key>] remains the literal name the toolset registered under (e.g., kiali). Do not use the dynamic name for the TOML key, or lookups will fail.

  6. What are MCP Prompts and how do they work?

    main

    MCP Prompts are pre-defined workflow templates that guide AI assistants through specific tasks. They provide structured guidance, parameterization via arguments, and conversation templates to ensure consistent interactions.

    In the Kubernetes MCP Server, prompts can be provided in two ways:

    1. Configuration-based: Defined in a config.toml file (overrides toolset prompts).
    2. Toolset-based: Implemented by developers within a toolset via the GetPrompts() method.

    When an AI assistant uses a prompt, it receives a set of messages (role/content pairs) that set the context for the conversation.

  7. Maintain deterministic ordering for list-shaped structured output

    main

    To ensure consistency across different MCP clients, list-shaped structured emitters must produce a deterministic order.

    Convention:

    • Use lexicographic sorting on a stable key (e.g., the resource name).
    • Use numeric ordering only when intrinsic to the data (e.g., port numbers).
    • Warning: Lexicographic sorting of numeric-looking strings results in cluster-10 < cluster-2. This is the expected contract; ensure tests pin a middle index to detect regressions.

    Implementation Example:

    names := make([]string, 0, len(items))
    for name := range items {
        names = append(names, name)
    }
    sort.Strings(names)
  8. Use meshCluster to target specific clusters in Kiali

    main

    In multi-cluster Istio service mesh environments, Kiali tools can target specific clusters using the meshCluster parameter.

    • Default Behavior: If meshCluster is omitted, Kiali defaults to its home cluster (where Kiali is deployed).
    • Discovery: Use the <toolset>_list_mesh_clusters tool (e.g., kiali_list_mesh_clusters) to find available cluster names. The name field returned by this tool is the only valid value for the meshCluster parameter.
    • Scope: Kiali tools and prompts are not cluster-aware; the MCP server does not automatically inject a context parameter. You must explicitly use meshCluster to define the mesh scope. (Note: This differs from Core Kubernetes tools, which use context for multi-cluster support).
  9. Design principles of Test Verification Helpers

    main

    The helper functions follow these core principles:

    1. Flexible matching: Uses pattern matching instead of exact volume names to accommodate different VM creation approaches.
    2. Clear output: Prints clear success (✓) or failure (✗) messages.
    3. Warning vs Error: Some functions print warnings (⚠) for non-critical mismatches but still return success (0). Always check the documentation for specific functions to see if they return 1 on mismatch.
    4. Return codes: Functions return 0 for success and 1 for failure. For critical validations, always use || exit 1 in your scripts.
  10. How Core Eval Testing references tasks and MCP configurations

    main

    The evaluation system is designed around shared resources to ensure consistency across different agent/provider combinations:

    • Shared Tasks: All evaluation configurations reference a centralized set of task definitions located at ../../tasks/*/*/*.yaml. They use a labelSelector to filter for the specific task suite required.
    • Shared MCP Config: All configurations reference a central ../../mcp-config.yaml file to connect to the same MCP server instance.
    • Baseline Coverage: Every per-suite evaluation file (e.g., eval-helm.yaml) automatically includes the core and config task sets to ensure baseline coverage is maintained during suite-specific runs.
  11. Automatic Kubernetes error logging for tool handlers

    main

    When developing MCP tools, you do not need to manually log Kubernetes API errors. If a tool handler returns a ToolCallResult containing a StatusError (a Kubernetes API error), the server automatically categorizes it and sends a corresponding log message to the MCP client.

    Automatic Mapping

    Kubernetes Error TypeLog LevelClient Message
    Not FoundinfoResource not found - it may not exist or may have been deleted
    ForbiddenerrorPermission denied - check RBAC permissions for {tool}
    UnauthorizederrorAuthentication failed - check cluster credentials
    Already ExistswarningResource already exists
    InvaliderrorInvalid resource specification - check resource definition
    Bad RequesterrorInvalid request - check parameters
    ConflicterrorResource conflict - resource may have been modified
    TimeouterrorRequest timeout - cluster may be slow or overloaded
    Server TimeouterrorServer timeout - cluster may be slow or overloaded
    Service UnavailableerrorService unavailable - cluster may be unreachable
    Too Many RequestswarningRate limited - too many requests to the cluster
    Other K8s API errorserrorOperation failed - cluster may be unreachable or experiencing issues

    Note: Non-Kubernetes errors (like local input validation errors) are not automatically logged to clients.

  12. How OpenTelemetry observability works in kubernetes-mcp-server

    main

    The kubernetes-mcp-server provides optional distributed tracing and metrics via OpenTelemetry (OTEL). Observability is disabled by default and is automatically enabled when an OTLP endpoint is configured.

    Tracing Coverage

    • MCP Tool Calls: Automatically traced in both STDIO and HTTP modes. Includes tool name, status, duration, and error details.
    • HTTP Requests: Traced only when running in HTTP mode. Includes method, path, status, client info, and duration.

    Metrics Coverage

    • Stats Endpoint (/stats): A JSON endpoint providing real-time statistics like tool call counts, errors, HTTP request counts, and server uptime.
    • OTLP Export: Metrics are exported to your configured OTLP backend every 30 seconds.

    Note: In STDIO mode (e.g., using Claude Desktop), only MCP tool calls are traced because there is no HTTP server.