K8s-mcp-server is a Model Context Protocol (MCP) server that enables AI assistants like Claude to securely execute Kubernetes commands. It provides a bridge between language models and essential Kubernetes CLI tools including kubectl, helm, istioctl, and argocd, allowing AI systems to assist with cluster management, troubleshooting, and deployments
K8s MCP Server is a server for Anthropic's MCP (Model Context Protocol) that allows running Kubernetes CLI tools such as kubectl
, istioctl
, helm
, and argocd
in a safe, containerized environment.
K8s MCP Server acts as a secure bridge between language models (like Claude) and Kubernetes CLI tools. It enables language models to execute validated Kubernetes commands, retrieve command documentation, and process command output in a structured way.
Session 1: Using k8s-mcp-server and Helm CLI to deploy a WordPress application in the claude-demo namespace, then intentionally breaking it by scaling the MariaDB StatefulSet to zero.
Session 2: Troubleshooting session where we use k8s-mcp-server to diagnose the broken WordPress site through kubectl commands, identify the missing database issue, and fix it by scaling up the StatefulSet and configuring ingress access..
K8s MCP Server is designed with a focus on security, performance, and extensibility. The system comprises the following core components:
flowchart TD
A[AI Assistant] <-->|HTTP/WebSocket<br>MCP Protocol| B[FastMCP Server]
B --> C[Tool Registration<br>Logging & Context]
B --> D[Prompt Templates]
C --> E[Command Validation]
E --> F[CLI Executor]
F --> G[Tool-specific Handlers]
G --> H[kubectl]
G --> I[helm]
G --> J[istioctl]
G --> K[argocd]
F --> L[Security Validator]
classDef core fill:#f9f,stroke:#333,stroke-width:2px
classDef tools fill:#bbf,stroke:#333,stroke-width:1px
classDef security fill:#fbb,stroke:#333,stroke-width:1px
class B,C,D,F core
class G,H,I,J,K tools
class E,L security
Server Component: Central controller that initializes the MCP server, registers tools and prompts, and handles client requests.
Security Validator: Checks command structure and content to prevent potentially dangerous operations, enforcing strict validation rules.
CLI Executor: Manages command execution, timeout handling, and output processing for all Kubernetes CLI tools.
Tool-specific Handlers: Specialized functions for each supported tool (kubectl, helm, istioctl, argocd) that provide appropriate command preprocessing and response formatting.
Prompt Templates: Pre-defined natural language templates for common Kubernetes operations to improve language model interactions.
The following diagram illustrates how commands flow through the system:
sequenceDiagram
participant LM as Language Model
participant MCP as MCP Server
participant Val as Security Validator
participant Exec as CLI Executor
participant K8s as K8s CLI Tools
LM->>MCP: Tool request via MCP
MCP->>Val: Validate command
alt Invalid Command
Val-->>MCP: Validation error
MCP-->>LM: Error response
else Valid Command
Val->>Exec: Execute command
Exec->>K8s: Run CLI tool
K8s-->>Exec: Command output
Exec-->>MCP: Formatted response
MCP-->>LM: Success response
end
kubectl
: Kubernetes command-line toolistioctl
: Command-line tool for Istio service meshhelm
: Kubernetes package managerargocd
: GitOps continuous delivery tool for KubernetesTo use K8s MCP Server with Claude Desktop, you need:
~/.kube/config
K8s MCP Server can be configured via environment variables that can be passed to the Docker container:
Environment Variable | Description | Default | Required |
---|---|---|---|
K8S_MCP_TIMEOUT | Default timeout for commands (seconds) | 300 | No |
K8S_MCP_MAX_OUTPUT | Maximum output size (characters) | 100000 | No |
K8S_MCP_TRANSPORT | Transport protocol to use ("stdio" or "sse") | stdio | No |
K8S_CONTEXT | Kubernetes context to use | current context | No |
K8S_NAMESPACE | Default Kubernetes namespace | default | No |
K8S_MCP_SECURITY_MODE | Security mode ("strict" or "permissive") | strict | No |
K8S_MCP_SECURITY_CONFIG | Path to security configuration YAML file | None | No |
For example, to use specific context and namespace, modify your Claude Desktop configuration:
{
"mcpServers": {
"k8s-mcp-server": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-v",
"~/.kube:/home/appuser/.kube:ro",
"-e",
"K8S_CONTEXT=my-cluster",
"-e",
"K8S_NAMESPACE=my-namespace",
"ghcr.io/alexei-led/k8s-mcp-server:latest"
]
}
}
}
To use a custom security configuration file, mount it into the container and set the environment variable:
{
"mcpServers": {
"k8s-mcp-server": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-v",
"~/.kube:/home/appuser/.kube:ro",
"-v",
"/path/to/my-security-config.yaml:/app/security_config.yaml:ro",
"-e",
"K8S_MCP_SECURITY_CONFIG=/app/security_config.yaml",
"ghcr.io/alexei-led/k8s-mcp-server:latest"
]
}
}
}
To run in permissive mode (allow all commands, including potentially dangerous ones):
{
"mcpServers": {
"k8s-mcp-server": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-v",
"~/.kube:/home/appuser/.kube:ro",
"-e",
"K8S_MCP_SECURITY_MODE=permissive",
"ghcr.io/alexei-led/k8s-mcp-server:latest"
]
}
}
}
To integrate K8s MCP Server with Claude Desktop, follow these steps:
Locate the Claude Desktop configuration file:
~/Library/Application Support/Claude/claude_desktop_config.json
%APPDATA%\Claude\claude_desktop_config.json
Edit the configuration file to include the K8s MCP Server:
{
"mcpServers": {
"kubernetes": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-v",
"~/.kube:/home/appuser/.kube:ro",
"ghcr.io/alexei-led/k8s-mcp-server:latest"
]
}
}
}
Note: Make sure to replace
~/.kube
with the absolute path to your Kubernetes configuration directory, and update the image name if using a custom image.
Restart Claude Desktop to apply the changes
flowchart TD
subgraph "User Device"
config[Edit claude_desktop_config.json]
claude[Claude Desktop]
docker[Docker Container]
k8s_config[Kubernetes Config]
end
subgraph "Kubernetes Cluster"
k8s[Kubernetes Services]
end
config -->|Add MCP Server Config| claude
claude -->|Docker Run Command| docker
k8s_config -->|Mount Read-only| docker
docker -->|kubectl & other CLI tools| k8s
Once configured, you can ask Claude to perform Kubernetes operations:
Claude will automatically use the appropriate Kubernetes CLI tools via the K8s MCP Server.
## API Reference
The server implements the [Model Context Protocol (MCP)](https://docs.anthropic.com/en/docs/agents-and-tools/model-context-protocol-mcp/) and provides the following tools:
### Documentation Tools
Each Kubernetes CLI tool has its own documentation function:
- `describe_kubectl(command=None)`: Get documentation for kubectl commands
- `describe_helm(command=None)`: Get documentation for Helm commands
- `describe_istioctl(command=None)`: Get documentation for Istio commands
- `describe_argocd(command=None)`: Get documentation for ArgoCD commands
### Execution Tools
Each Kubernetes CLI tool has its own execution function:
- `execute_kubectl(command, timeout=None)`: Execute kubectl commands
- `execute_helm(command, timeout=None)`: Execute Helm commands
- `execute_istioctl(command, timeout=None)`: Execute Istio commands
- `execute_argocd(command, timeout=None)`: Execute ArgoCD commands
### Command Piping
All execution tools support Unix command piping to filter and transform output:
```python
execute_kubectl(command="get pods -o json | jq '.items[].metadata.name'")
execute_helm(command="list | grep nginx")
Variable | Description | Default | Notes |
---|---|---|---|
K8S_MCP_TIMEOUT | Command execution timeout (seconds) | 300 | Applies to all commands |
K8S_MCP_MAX_OUTPUT | Maximum output size (characters) | 100000 | Truncates output if exceeded |
K8S_MCP_TRANSPORT | Transport protocol | "stdio" | "stdio" or "sse" |
K8S_CONTEXT | Kubernetes context | current | Uses kubectl current-context if empty |
K8S_NAMESPACE | Default namespace | "default" | Applied to all commands |
K8S_MCP_SECURITY_MODE | Security validation mode | "strict" | "strict" or "permissive" |
K8S_MCP_SECURITY_CONFIG | Path to security config file | None | YAML configuration file |
The security configuration file uses YAML format with the following structure:
# Dangerous command prefixes (prefix-based matching)
dangerous_commands:
kubectl:
- "kubectl delete"
- "kubectl drain"
# ...more dangerous commands
# Safe pattern exceptions (prefix-based matching)
safe_patterns:
kubectl:
- "kubectl delete pod"
- "kubectl delete deployment"
# ...more safe patterns
# Advanced regex pattern rules
regex_rules:
kubectl:
- pattern: "kubectl\\s+delete\\s+(-[A-Za-z]+\\s+)*--all\\b"
description: "Deleting all resources of a type"
error_message: "Custom error message shown to the user"
# ...more regex rules
Execute and manage Kubernetes resources:
kubectl get pods
kubectl get deployments
kubectl describe pod my-pod
Manage Istio service mesh configuration:
istioctl analyze
istioctl proxy-status
istioctl dashboard
Manage Helm charts and releases:
helm list
helm install my-release my-chart
helm upgrade my-release my-chart
Manage ArgoCD applications:
argocd app list
argocd app get my-app
argocd app sync my-app
K8s MCP Server includes comprehensive test coverage with both unit and integration tests. The testing architecture is designed to be lightweight, fast, and representative of real-world usage.
flowchart TD
A[Testing Framework] --> B[Unit Tests]
A --> C[Integration Tests]
B --> D[Mock Executor]
B --> E[Validation Tests]
B --> F[Security Tests]
C --> G[KWOK Cluster]
C --> H[Local Cluster]
classDef unit fill:#bbf,stroke:#333,stroke-width:1px
classDef integ fill:#fbb,stroke:#333,stroke-width:1px
class B,D,E,F unit
class C,G,H integ
Integration tests validate the command execution and response handling of k8s-mcp-server. By default, the tests use KWOK (Kubernetes Without Kubelet) to create a lightweight simulated Kubernetes cluster for testing.
Integration tests require:
kubectl
installed and in your PATHkwokctl
installed for the default KWOK-based testing (see below)helm
for Helm-related testsKWOK (Kubernetes Without Kubelet) provides a lightweight simulation of a Kubernetes cluster without requiring actual node or container execution. This is the default and recommended approach for running the integration tests.
Install KWOK:
# For macOS with Homebrew:
brew install kwokctl
# For Linux or manual installation:
KWOK_VERSION=$(curl -s https://api.github.com/repos/kubernetes-sigs/kwok/releases/latest | grep tag_name | cut -d '"' -f 4)
curl -Lo kwokctl https://github.com/kubernetes-sigs/kwok/releases/download/${KWOK_VERSION}/kwokctl-$(go env GOOS)-$(go env GOARCH)
curl -Lo kwok https://github.com/kubernetes-sigs/kwok/releases/download/${KWOK_VERSION}/kwok-$(go env GOOS)-$(go env GOARCH)
chmod +x kwokctl kwok
sudo mv kwokctl kwok /usr/local/bin/
Run Integration Tests:
# Run all integration tests (KWOK cluster will be created automatically)
pytest tests/integration -v
# Run specific test
pytest tests/integration/test_k8s_tools.py::test_kubectl_version -v
# Skip cleanup of KWOK cluster for debugging
K8S_SKIP_CLEANUP=true pytest tests/integration -v
The test framework will:
K8S_SKIP_CLEANUP=true
)Benefits of using KWOK:
If you need to test against a real Kubernetes implementation, Rancher Desktop provides a convenient way to run Kubernetes locally:
Enable Kubernetes in Rancher Desktop:
Configure Environment Variables:
# Required: Tell tests to use your existing cluster instead of KWOK
export K8S_MCP_TEST_USE_EXISTING_CLUSTER=true
# Optional: Specify Rancher Desktop context
export K8S_CONTEXT=rancher-desktop
# Optional: Skip cleanup of test namespaces
export K8S_SKIP_CLEANUP=true
Run Integration Tests:
pytest tests/integration -v
For testing against production-like environments or specific Kubernetes distributions:
# Set required environment variables
export K8S_MCP_TEST_USE_EXISTING_CLUSTER=true
# Optionally specify a context
export K8S_CONTEXT=my-cluster-context
# Run the tests
pytest -m integration
This approach works with any Kubernetes distribution (EKS, GKE, AKS, k3s, k0s, etc.).
For local development, we recommend setting up a lightweight Kubernetes cluster:
Using k3s (Recommended for Linux):
k3s is a certified lightweight Kubernetes distribution:
# Install k3s
curl -sfL https://get.k3s.io | sh -
# Get kubeconfig (sudo is required to read the config)
sudo cat /etc/rancher/k3s/k3s.yaml > ~/.kube/k3s-config
# Fix permissions
chmod 600 ~/.kube/k3s-config
# Set KUBECONFIG to use this file
export KUBECONFIG=~/.kube/k3s-config
# Verify it's running
kubectl get nodes
Using k0s (Recommended for all platforms):
k0s is a zero-friction Kubernetes distribution:
# Install k0s
curl -sSLf https://get.k0s.sh | sh
# Create a single-node cluster
sudo k0s install controller --single
sudo k0s start
# Get kubeconfig
sudo k0s kubeconfig admin > ~/.kube/k0s-config
chmod 600 ~/.kube/k0s-config
export KUBECONFIG=~/.kube/k0s-config
# Verify it's running
kubectl get nodes
Using Minikube:
Minikube creates a local Kubernetes cluster within a VM or container:
# Install Minikube
# macOS with Homebrew:
brew install minikube
# Start a cluster
minikube start
# Verify it's running
kubectl get nodes
Using Kind (Kubernetes in Docker):
Kind runs Kubernetes clusters using Docker containers as nodes:
# Install Kind
# macOS with Homebrew:
brew install kind
# Create a cluster
kind create cluster --name k8s-mcp-test
# Verify it's running
kubectl get nodes
Using K3d (Lightweight Kubernetes):
K3d is a lightweight wrapper to run k3s in Docker:
# Install K3d
# macOS with Homebrew:
brew install k3d
# Create a cluster
k3d cluster create k8s-mcp-test
# Verify it's running
kubectl get nodes
You can customize the integration tests with these environment variables:
Environment Variable | Description | Default |
---|---|---|
K8S_MCP_TEST_USE_KWOK | Use KWOK to create a test cluster | true |
K8S_MCP_TEST_USE_EXISTING_CLUSTER | Use existing cluster instead of creating a new one | false |
K8S_CONTEXT | Kubernetes context to use for tests | current context |
K8S_SKIP_CLEANUP | Skip cleanup of test resources | false |
Example usage:
# Force using KWOK even if other variables are set
export K8S_MCP_TEST_USE_KWOK=true
pytest -m integration
# Use existing cluster with a specific context
export K8S_MCP_TEST_USE_EXISTING_CLUSTER=true
export K8S_CONTEXT=my-dev-cluster
pytest -m integration
# Skip cleanup of test resources (useful for debugging)
export K8S_SKIP_CLEANUP=true
pytest -m integration
The project includes GitHub Actions workflows that automatically run integration tests:
The integration test workflow:
You can also manually trigger the integration tests from the GitHub Actions tab, with an option to enable debugging if needed.
KWOK (Kubernetes Without Kubelet) provides significant advantages for testing Kubernetes command execution:
Since our integration tests primarily validate command formation, execution, and output parsing rather than actual workload behavior, KWOK provides an ideal balance of fidelity and efficiency.
The server includes several safety features:
-v ~/.kube:/home/appuser/.kube:ro
)K8s MCP Server supports two security modes and customizable security rules:
To run in permissive mode (allow all commands):
{
"mcpServers": {
"k8s-mcp-server": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-v",
"~/.kube:/home/appuser/.kube:ro",
"-e",
"K8S_MCP_SECURITY_MODE=permissive",
"ghcr.io/alexei-led/k8s-mcp-server:latest"
]
}
}
}
Security rules can be customized using a YAML configuration file. This allows for more flexibility than the built-in rules.
Create a Security Configuration File:
Create a YAML file with your custom rules (e.g., security_config.yaml
):
# Security configuration for k8s-mcp-server
# Potentially dangerous command patterns (prefix-based)
dangerous_commands:
kubectl:
- "kubectl delete"
- "kubectl drain"
# Add your custom dangerous commands here
# Safe pattern overrides (prefix-based)
safe_patterns:
kubectl:
- "kubectl delete pod"
- "kubectl delete deployment"
# Add your custom safe patterns here
# Advanced regex pattern rules
regex_rules:
kubectl:
- pattern: "kubectl\\s+delete\\s+(-[A-Za-z]+\\s+)*--all\\b"
description: "Deleting all resources of a type"
error_message: "Deleting all resources is restricted. Specify individual resources to delete."
# Add your custom regex rules here
Mount the Configuration File in Docker:
{
"mcpServers": {
"k8s-mcp-server": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-v",
"~/.kube:/home/appuser/.kube:ro",
"-v",
"/path/to/security_config.yaml:/security_config.yaml:ro",
"-e",
"K8S_MCP_SECURITY_CONFIG=/security_config.yaml",
"ghcr.io/alexei-led/k8s-mcp-server:latest"
]
}
}
}
The security configuration YAML file has three main sections:
Each regex rule should include:
Example 1: Restricting Namespace Operations
regex_rules:
kubectl:
- pattern: "kubectl\\s+.*\\s+--namespace=kube-system\\b"
description: "Operations in kube-system namespace"
error_message: "Operations in kube-system namespace are restricted."
Example 2: Allowing Additional Safe Patterns
safe_patterns:
kubectl:
- "kubectl delete pod"
- "kubectl delete job"
- "kubectl delete cronjob"
Example 3: Restricting Dangerous File System Access
regex_rules:
kubectl:
- pattern: "kubectl\\s+exec\\s+.*\\s+-[^-]*c\\s+.*(rm|mv|cp|curl|wget|chmod)\\b"
description: "Dangerous file operations in exec"
error_message: "File system operations within kubectl exec are restricted."
K8s MCP Server is organized around a modular architecture that separates concerns and promotes maintainability:
flowchart TD
A[__main__.py] --> B[server.py]
B --> C[config.py]
B --> D[cli_executor.py]
B --> E[prompts.py]
D --> F[security.py]
D --> G[tools.py]
D --> H[errors.py]
B --> I[logging_utils.py]
classDef core fill:#f9f,stroke:#333,stroke-width:2px
classDef utils fill:#bbf,stroke:#333,stroke-width:1px
class A,B,D core
class C,E,F,G,H,I utils
server.py: The central component that initializes the MCP server, registers tools and prompts, and manages client connections. It implements the Model Context Protocol and handles request/response lifecycle.
cli_executor.py: Manages the execution of CLI commands with proper validation, timeout handling, and error capture. It translates between the abstract tool requests and the concrete CLI commands.
security.py: Implements command validation rules and security checks to prevent potentially dangerous operations. It enforces restrictions on allowed commands and parameters.
tools.py: Defines common utilities, data structures, and helper functions for working with Kubernetes commands.
prompts.py: Registers and defines template prompts for common Kubernetes operations to improve AI interactions.
config.py: Manages configuration settings for the server, including environment variables, default values, and supported CLI tools.
errors.py: Provides standardized error handling, custom exceptions, and error formatting.
logging_utils.py: Implements consistent logging infrastructure across the application.
This architecture allows for flexibility while maintaining simplicity, with clear interfaces between components and well-defined responsibilities.
If you're interested in contributing to K8s MCP Server, here's an overview of the project structure:
k8s-mcp-server/
├── src/
│ └── k8s_mcp_server/
│ ├── server.py # MCP server initialization and tool registration
│ ├── cli_executor.py # Command execution and process management
│ ├── security.py # Command validation and security rules
│ ├── tools.py # Shared utilities and data structures
│ ├── errors.py # Standardized error handling
│ ├── prompts.py # Prompt templates for common operations
│ ├── config.py # Configuration and settings
│ └── logging_utils.py # Logging infrastructure
├── tests/
│ ├── unit/ # Unit tests (no K8s cluster required)
│ └── integration/ # Integration tests (requires K8s cluster or KWOK)
└── deploy/
└── docker/ # Docker deployment configuration
Setup Development Environment:
git clone https://github.com/alexei-led/k8s-mcp-server.git
cd k8s-mcp-server
uv venv -p 3.13
source .venv/bin/activate
uv pip install -e ".[dev]"
Run Tests:
# Unit tests
pytest -m unit
# Integration tests (using KWOK)
pytest -m integration
Submit Pull Requests:
git checkout -b feature/amazing-feature
)git commit -m 'Add some amazing feature'
)git push origin feature/amazing-feature
)ruff
)K8s MCP Server is built using the Model Context Protocol Python SDK. Here are some tips for developing and debugging:
The MCP Inspector is a powerful tool for local development and testing:
# Install the MCP CLI if not already installed
pip install "mcp[cli]"
# Run the server with the inspector
mcp dev src/k8s_mcp_server/server.py
The inspector provides:
For quick iteration during development:
# Set up a development environment
uv venv -p 3.13
source .venv/bin/activate
uv pip install -e ".[dev]"
# Run the server directly
python -m k8s_mcp_server
# Or use the MCP run command
mcp run src/k8s_mcp_server/server.py
Enable Debug Logging:
export LOGLEVEL=DEBUG
python -m k8s_mcp_server
Test Individual Tools: Use the MCP Inspector to test specific tools in isolation before integrating with Claude.
Inspect MCP Protocol: Monitor the raw MCP protocol messages using the inspector to understand how Claude interacts with your server.
Local Testing with Claude Desktop: During development, you can point Claude Desktop to your local server instead of using Docker:
{
"mcpServers": {
"k8s-mcp-server": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"--network=host",
"-v",
"/Users/YOUR_USER_NAME/.kube:/home/appuser/.kube",
"ghcr.io/alexei-led/k8s-mcp-server:latest"
]
}
}
}
This project is licensed under the MIT License - see the LICENSE file for details.