ku

kubectl-mcp-server

A Model Context Protocol (MCP) server for Kubernetes that enables AI assistants like Claude, Cursor, and others to interact with Kubernetes clusters through natural language.

Publisherkubectl-mcp-server
Submitted date4/13/2025

Kubectl MCP Tool: Bridging the Gap Between AI and Kubernetes

Empower your AI assistants with seamless Kubernetes interaction using the Model Context Protocol.

Python Kubernetes MCP PyPI version PyPI - Python Version

Overview

The Kubectl MCP Tool is a powerful enabler, designed to facilitate interaction between Large Language Model (LLM) applications and Kubernetes clusters. By implementing the Model Context Protocol (MCP), this tool allows AI assistants like Claude, Cursor, and others to manage and interact with your Kubernetes infrastructure using natural language commands. This significantly lowers the barrier to entry for Kubernetes management, making it accessible to a wider range of users and use cases.

Key Features and Capabilities

This tool provides a comprehensive suite of features, enabling AI assistants to perform a wide range of Kubernetes operations:

Core Kubernetes Management

  • Cluster Connectivity: Establishes secure connections to Kubernetes clusters.
  • Resource Management: Enables listing, creating, deleting, and describing core Kubernetes resources such as pods, services, deployments, and nodes.
  • Log Retrieval: Provides access to pod logs and Kubernetes events for debugging and monitoring.
  • Helm Integration: Supports Helm v3 operations, including installation, upgrades, and uninstallation of charts.
  • kubectl Explain and API Resources: Exposes kubectl explain functionality and provides access to Kubernetes API resource definitions.
  • Contextual Awareness: Remembers the selected namespace for subsequent commands, streamlining workflows.
  • Port Forwarding: Facilitates port forwarding to pods for local access and debugging.
  • Scaling Operations: Allows scaling deployments and statefulsets to adjust application capacity.
  • Command Execution: Enables executing commands within containers for troubleshooting and administration.
  • Configuration Management: Supports managing ConfigMaps and Secrets for application configuration.
  • Rollback Capabilities: Provides the ability to rollback deployments to previous versions.
  • Networking Management: Enables management of Ingress resources and NetworkPolicies.
  • Cluster Switching: Supports seamless context switching between different Kubernetes clusters.

Natural Language Processing (NLP) Integration

  • Natural Language Queries: Processes natural language queries to translate user intent into kubectl commands.
  • Context-Aware Commands: Maintains context from previous operations to understand and execute complex commands.
  • Human-Friendly Explanations: Provides clear and concise explanations of Kubernetes concepts.
  • Intelligent Command Construction: Automatically constructs kubectl commands based on user intent.
  • Fallback Mechanism: Seamlessly falls back to direct kubectl execution when specialized tools are unavailable.
  • Mock Data Support: Enables offline testing and development using mock Kubernetes data.
  • Namespace Awareness: Automatically handles queries within the context of the selected namespace.

Monitoring and Observability

  • Cluster Health Monitoring: Provides real-time monitoring of cluster health and status.
  • Resource Utilization Tracking: Tracks resource utilization across the cluster.
  • Pod Status and Health Checks: Monitors pod status and health check results.
  • Event Monitoring and Alerting: Monitors Kubernetes events and triggers alerts based on predefined rules.
  • Node Capacity Analysis: Analyzes node capacity and resource allocation.
  • Historical Performance Tracking: Tracks historical performance data for trend analysis.
  • Resource Usage Statistics: Provides detailed resource usage statistics using kubectl top.
  • Container Readiness and Liveness Tracking: Monitors container readiness and liveness probes.

Security and Compliance

  • RBAC Validation: Validates and verifies Role-Based Access Control (RBAC) configurations.
  • Security Context Auditing: Audits security contexts to identify potential vulnerabilities.
  • Secure API Connections: Establishes secure connections to the Kubernetes API.
  • Credential Management: Provides secure management of Kubernetes credentials.
  • Network Policy Assessment: Assesses network policies to ensure proper network segmentation.
  • Container Security Scanning: Integrates with container security scanning tools.
  • Security Best Practices Enforcement: Enforces security best practices across the cluster.
  • Role and ClusterRole Management: Simplifies the management of RBAC roles and cluster roles.
  • ServiceAccount Management: Enables creation and binding of ServiceAccounts.
  • PodSecurityPolicy Analysis: Analyzes PodSecurityPolicies to identify potential security risks.
  • RBAC Permissions Auditing: Audits RBAC permissions to ensure least privilege access.
  • Security Context Validation: Validates security contexts to prevent misconfigurations.

Diagnostics and Troubleshooting

  • Cluster Diagnostics: Provides comprehensive cluster diagnostics and troubleshooting capabilities.
  • Configuration Validation: Validates Kubernetes configurations to identify errors.
  • Error Analysis and Recovery: Analyzes errors and provides recovery suggestions.
  • Connection Status Monitoring: Monitors the connection status to the Kubernetes API.
  • Log Analysis: Analyzes logs to identify patterns and anomalies.
  • Resource Constraint Identification: Identifies resource constraints that may be impacting performance.
  • Pod Health Check Diagnostics: Provides detailed diagnostics for pod health check failures.
  • Common Error Pattern Identification: Identifies common error patterns to accelerate troubleshooting.
  • Resource Validation: Validates resource configurations to prevent misconfigurations.
  • Liveness and Readiness Probe Validation: Validates liveness and readiness probe configurations.

Advanced Features

  • Multiple Transport Protocols: Supports stdio and Server-Sent Events (SSE) transport protocols.
  • Multi-Assistant Integration: Integrates with multiple AI assistants simultaneously.
  • Extensible Tool Framework: Provides an extensible framework for adding custom tools and functionalities.
  • Custom Resource Definition (CRD) Support: Supports interaction with Custom Resource Definitions.
  • Cross-Namespace Operations: Enables operations across multiple namespaces.
  • Batch Operations: Supports batch operations on multiple resources.
  • Intelligent Resource Mapping: Provides intelligent resource relationship mapping.
  • Error Explanation with Recovery: Explains errors and provides recovery suggestions.
  • Volume Management: Enables volume management and identification.

Architecture: Deep Dive

The Kubectl MCP Tool is built upon a robust architecture that leverages the Model Context Protocol (MCP) to facilitate seamless communication between AI assistants and Kubernetes clusters.

MCP Integration

The core of the architecture revolves around the Model Context Protocol (MCP), which provides a standardized interface for AI assistants to interact with external tools and data sources. The Kubectl MCP Tool implements the MCP specification, enabling AI assistants to leverage its capabilities for Kubernetes management.

The key components of the architecture are:

  1. MCP Server: A compliant server that listens for requests from MCP clients (AI assistants).
  2. Tools Registry: A registry that defines and registers Kubernetes operations as MCP tools, including their schemas and functionalities.
  3. Transport Layer: A flexible transport layer that supports multiple communication methods, including stdio, SSE, and HTTP.
  4. Core Operations: The core logic that translates MCP tool calls into corresponding Kubernetes API operations.
  5. Response Formatter: A component that converts Kubernetes API responses into MCP-compliant responses, ensuring seamless integration with AI assistants.

Request Flow

The following diagram illustrates the request flow within the Kubectl MCP Tool:

Request Flow

Dual Mode Operation

The tool operates in two distinct modes:

  1. CLI Mode: A direct command-line interface (CLI) for executing Kubernetes operations. This mode is primarily used for testing and debugging.
  2. Server Mode: The primary mode of operation, where the tool runs as an MCP server, listening for and processing requests from AI assistants.

Installation: Getting Started

For detailed installation instructions, please refer to the Installation Guide.

The recommended installation method is using pip:

pip install kubectl-mcp-tool

To install a specific version:

pip install kubectl-mcp-tool==1.1.0

The package is also available on PyPI: https://pypi.org/project/kubectl-mcp-tool/1.1.0/

Prerequisites

Before installing the Kubectl MCP Tool, ensure that you have the following prerequisites:

  • Python: Python 3.9 or higher is required.
  • kubectl: The kubectl command-line tool must be installed and configured to access your Kubernetes cluster.
  • Kubernetes Cluster Access: You need access to a Kubernetes cluster.
  • pip: The Python package manager pip is required.

Installation Methods

Global Installation

To install the latest version from PyPI:

pip install kubectl-mcp-tool

Alternatively, to install the development version directly from GitHub:

pip install git+https://github.com/rohitg00/kubectl-mcp-server.git

Local Development Installation

For local development, follow these steps:

  1. Clone the repository:

    git clone https://github.com/rohitg00/kubectl-mcp-server.git cd kubectl-mcp-server
  2. Install in development mode:

    pip install -e .

Verifying Installation

After installation, verify that the tool is working correctly by running:

kubectl-mcp --help

Note: This tool is primarily designed to function as an MCP server for AI assistants. The main command is kubectl-mcp serve, which starts the MCP server.

Integration with AI Assistants

The Kubectl MCP Tool seamlessly integrates with popular AI assistants, enabling natural language interaction with your Kubernetes cluster.

Configuration

To configure the tool to work with your AI assistant, you need to provide the path to your kubeconfig file. This file contains the necessary credentials to access your Kubernetes cluster.

Claude Desktop

Add the following configuration to ~/.config/claude/mcp.json (or %APPDATA%\Claude\mcp.json on Windows):

{ "mcpServers": { "kubernetes": { "command": "python", "args": ["-m", "kubectl_mcp_tool.minimal_wrapper"], "env": { "KUBECONFIG": "/path/to/your/.kube/config" } } } }

Cursor AI

Add a new global MCP server in your Cursor AI settings with the following configuration:

{ "mcpServers": { "kubernetes": { "command": "python", "args": ["-m", "kubectl_mcp_tool.minimal_wrapper"], "env": { "KUBECONFIG": "/path/to/your/.kube/config", "PATH": "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/homebrew/bin" } } } }

Save this configuration to ~/.cursor/mcp.json for global settings.

Windsurf

Add the following configuration to ~/.config/windsurf/mcp.json (or %APPDATA%\WindSurf\mcp.json on Windows):

{ "mcpServers": { "kubernetes": { "command": "python", "args": ["-m", "kubectl_mcp_tool.minimal_wrapper"], "env": { "KUBECONFIG": "/path/to/your/.kube/config" } } } }

Important: Replace /path/to/your/.kube/config with the actual path to your kubeconfig file. The default location is typically ~/.kube/config.

Automatic Configuration

For a streamlined setup, use the provided installation script:

bash install.sh

This script automates the following steps:

  1. Installs required dependencies.
  2. Creates configuration files for Claude, Cursor, and Windsurf.
  3. Sets up the correct paths and environment variables.
  4. Tests your Kubernetes connection.

Usage Examples

Here are some examples of how you can use the Kubectl MCP Tool with your AI assistant:

  • List Pods:

    List all pods in the default namespace
    
  • Deploy an Application:

    Create a deployment named nginx-test with 3 replicas using the nginx:latest image
    
  • Check Pod Logs:

    Get logs from the nginx-test pod
    
  • Port Forwarding:

    Forward local port 8080 to port 80 on the nginx-test pod
    

Development: Contributing to the Project

We welcome contributions to the Kubectl MCP Tool! If you're interested in contributing, follow these steps:

  1. Clone the repository:

    git clone https://github.com/rohitg00/kubectl-mcp-server.git cd kubectl-mcp-server
  2. Install dependencies:

    pip install -r requirements.txt
  3. Install in development mode:

    pip install -e .
  4. Run tests:

    python -m python_tests.test_all_features

Project Structure: Navigating the Codebase

The project structure is organized as follows:

├── kubectl_mcp_tool/         # Main package
│   ├── __init__.py           # Package initialization
│   ├── cli.py                # CLI entry point
│   ├── mcp_server.py         # MCP server implementation
│   ├── mcp_kubectl_tool.py   # Main kubectl MCP tool implementation
│   ├── natural_language.py   # Natural language processing
│   ├── diagnostics.py        # Diagnostics functionality
│   ├── core/                 # Core functionality
│   ├── security/             # Security operations
│   ├── monitoring/           # Monitoring functionality
│   ├── utils/                # Utility functions
│   └── cli/                  # CLI functionality components
├── python_tests/             # Test suite
│   ├── run_mcp_tests.py      # Test runner script
│   ├── mcp_client_simulator.py # MCP client simulator for mock testing
│   ├── test_utils.py         # Test utilities
│   ├── test_mcp_core.py      # Core MCP tests
│   ├── test_mcp_security.py  # Security tests
│   ├── test_mcp_monitoring.py # Monitoring tests
│   ├── test_mcp_nlp.py       # Natural language tests
│   ├── test_mcp_diagnostics.py # Diagnostics tests
│   └── mcp_test_strategy.md  # Test strategy documentation
├── docs/                     # Documentation
│   ├── README.md             # Documentation overview
│   ├── INSTALLATION.md       # Installation guide
│   ├── integration_guide.md  # Integration guide
│   ├── cursor/               # Cursor integration docs
│   ├── windsurf/             # Windsurf integration docs
│   └── claude/               # Claude integration docs
├── compatible_servers/       # Compatible MCP server implementations
│   ├── cursor/               # Cursor-compatible servers
│   ├── windsurf/             # Windsurf-compatible servers
│   ├── minimal/              # Minimal server implementations
│   └── generic/              # Generic MCP servers
├── requirements.txt          # Python dependencies
├── setup.py                  # Package setup script
├── pyproject.toml            # Project configuration
├── MANIFEST.in               # Package manifest
├── LICENSE                   # MIT License
├── CHANGELOG.md              # Version history
├── .gitignore                # Git ignore file
├── install.sh                # Installation script
├── publish.sh                # PyPI publishing script
└── start_mcp_server.sh       # Server startup script

Contributing: Making a Difference

We encourage contributions to the Kubectl MCP Tool. To contribute:

  1. Fork the repository.
  2. Create a feature branch (git checkout -b feature/amazing-feature).
  3. Commit your changes (git commit -m 'Add some amazing feature').
  4. Push to the branch (git push origin feature/amazing-feature).
  5. Open a Pull Request.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Visit More

View All