USP
Unlike manual CLI operations, this server provides a secure, containerized environment for Claude to execute multiple Kubernetes tools with built-in command validation and cloud provider support. It integrates seamlessly with Claude Deskto…
Use cases
- 01Deploying and managing applications with Helm
- 02Troubleshooting Kubernetes cluster issues
- 03Explaining complex Kubernetes concepts
- 04Crafting and validating Kubernetes manifests
- 05Interacting with Istio service mesh or ArgoCD
Detected files (1)
CLAUDE.mdclaude_mdShow content (4072 bytes)
# K8s MCP Server — Development Guide ## Build & Test Commands ```bash make install # Install dependencies make dev-install # Install with dev deps make test # Unit tests only (default) make test-all # All tests (incl. integration) make test-integration # Integration tests (needs kubectl + cluster) make lint # ruff check src/ tests/ make format # ruff format src/ tests/ ``` Direct commands: ```bash uv run pytest -q tests/unit/ # Fast unit tests uvx ruff check src/ tests/ # Lint python -m k8s_mcp_server # Run server locally ``` ## Architecture ### Server (`src/k8s_mcp_server/server.py`) - 8 tools: 4 `execute_*` + 4 `describe_*`, all delegating to `_execute_tool_command()` / `_describe_tool_command()` - CLI status checked at startup — tools gracefully error if CLI not installed - Uses `FieldInfo` workaround for Pydantic Field defaults in timeout parameter - `ToolAnnotations`: `readOnlyHint=True` for describe tools, `destructiveHint=True, openWorldHint=True` for execute tools ### Security (`src/k8s_mcp_server/security.py`) - `validate_command()` — blocked patterns, required resource names for destructive ops - `kubectl exec` restrictions (no interactive shells) - Per-tool security rules validated before execution ### Errors (`src/k8s_mcp_server/errors.py`) - Hierarchy: `K8sMCPError` → `CommandValidationError`, `CommandExecutionError`, `AuthenticationError`, `CommandTimeoutError` - `create_error_result()` produces structured `CommandResult` with `ErrorDetails` - Errors returned as tool results with `isError=true` (MCP spec compliant), not as JSON-RPC errors ### CLI Executor (`src/k8s_mcp_server/cli_executor.py`) - `execute_command()` — asyncio subprocess, pipe support (`|` splitting), timeout - `get_command_help()` — fetches `--help` output - `check_cli_installed()` — startup validation ### Tools (`src/k8s_mcp_server/tools.py`) - `CommandResult`: status, output, error (optional `ErrorDetails`), exit_code - `CommandHelpResult`: help_text, status, error ### Config (`src/k8s_mcp_server/config.py`) - `SUPPORTED_CLI_TOOLS = ["kubectl", "helm", "istioctl", "argocd"]` - `MCP_TRANSPORT` env var: `stdio` (default), `sse`, `streamable-http` - `DEFAULT_TIMEOUT = 300` seconds - `INSTRUCTIONS` — system prompt for the MCP server ## Testing Patterns - **Unit tests:** mock `asyncio.create_subprocess_exec`, fixtures in `conftest.py` - **Integration:** requires real kubectl + cluster — skip with `pytest -m "not integration"` - **Security tests:** `tests/unit/test_security.py` — covers all blocked commands - **Error tests:** each error type has structured output assertion ## MCP Development Guidelines ### Adding a New CLI Tool (step-by-step) 1. Add tool name to `SUPPORTED_CLI_TOOLS` in `config.py` 2. Add `execute_<tool>()` in `server.py` — follow existing pattern, delegate to `_execute_tool_command()` 3. Add `describe_<tool>()` in `server.py` — follow existing help pattern 4. Add `ToolAnnotations` to both functions 5. Add security rules in `security.py` if needed 6. Add prompt templates in `prompts.py` 7. Add unit tests for both new tools 8. Update README ### Error Handling Pattern - Catch `CommandValidationError`, `CommandExecutionError` etc. — return via `create_error_result()` - Never raise protocol errors for input validation issues - All tool functions accept `ctx: Context | None = None` ### Field Descriptions - Use `pydantic.Field(description=...)` for schema generation in tool parameters ## Code Style - **Line length:** 120 chars - **Imports:** sorted by ruff (stdlib → third-party → local) - **Type hints:** native Python (`list[str]`, not `List[str]`) - **Docstrings:** Google-style for all public functions - **Naming:** snake_case for functions/variables, PascalCase for classes ## Important - **Default branch:** `master` (not main!) - **Workflow:** branch → PR → CI green → squash merge - **NEVER push directly to `master`** - **Git commits:** do NOT add AI co-author trailers
README
K8s MCP Server
K8s MCP Server is a Docker-based server implementing Anthropic's Model Context Protocol (MCP) that enables Claude to run Kubernetes CLI tools (kubectl, istioctl, helm, argocd) in a secure, containerized environment.
Demo: Deploy and Troubleshoot WordPress
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..
How It Works
flowchart LR
A[User] --> |Asks K8s question| B[Claude]
B --> |Sends command via MCP| C[K8s MCP Server]
C --> |Executes kubectl, helm, etc.| D[Kubernetes Cluster]
D --> |Returns results| C
C --> |Returns formatted results| B
B --> |Analyzes & explains| A
Claude can help users by:
- Explaining complex Kubernetes concepts
- Running commands against your cluster
- Troubleshooting issues
- Suggesting optimizations
- Crafting Kubernetes manifests
Quick Start with Claude Desktop
Get Claude helping with your Kubernetes clusters in under 2 minutes:
-
Create or update your Claude Desktop configuration file:
- macOS: Edit
$HOME/Library/Application Support/Claude/claude_desktop_config.json - Windows: Edit
%APPDATA%\Claude\claude_desktop_config.json - Linux: Edit
$HOME/.config/Claude/claude_desktop_config.json
{ "mcpServers": { "kubernetes": { "command": "docker", "args": [ "run", "-i", "--rm", "-v", "/Users/YOUR_USER_NAME/.kube:/home/appuser/.kube:ro", "ghcr.io/alexei-led/k8s-mcp-server:latest" ] } } } - macOS: Edit
-
Restart Claude Desktop
- After restart, you'll see the Tools icon (🔨) in the bottom right of your input field
- This indicates Claude can now access K8s tools via the MCP server
-
Start using K8s tools directly in Claude Desktop:
- "What Kubernetes contexts do I have available?"
- "Show me all pods in the default namespace"
- "Create a deployment with 3 replicas of nginx:1.21"
- "Explain what's wrong with my StatefulSet 'database' in namespace 'prod'"
- "Deploy the bitnami/wordpress chart with Helm and set service type to LoadBalancer"
Note: Claude Desktop will automatically route K8s commands through the MCP server, allowing natural conversation about your clusters without leaving the Claude interface.
Cloud Providers: For AWS EKS, GKE, or Azure AKS, you'll need additional configuration. See the Cloud Provider Support guide.
Features
- Multiple Kubernetes Tools:
kubectl,helm,istioctl, andargocdin one container - Cloud Providers: Native support for AWS EKS, Google GKE, and Azure AKS
- Security: Runs as non-root user with strict command validation
- Command Piping: Support for common Unix tools like
jq,grep, andsed - Easy Configuration: Simple environment variables for customization
Transport Protocols
The server supports three transport protocols, configured via K8S_MCP_TRANSPORT:
| Transport | Description | Default |
|---|---|---|
stdio | Standard I/O (Claude Desktop default) | Yes |
streamable-http | HTTP transport (recommended for remote/web clients, MCP spec 2025-11-25) | No |
sse | Server-Sent Events (deprecated, use streamable-http instead) | No |
Example using Streamable HTTP transport:
docker run --rm -p 8000:8000 \
-v ~/.kube:/home/appuser/.kube:ro \
-e K8S_MCP_TRANSPORT=streamable-http \
ghcr.io/alexei-led/k8s-mcp-server:latest
Note: When running in Docker with HTTP transports, the server automatically binds to
0.0.0.0for proper port mapping. Outside Docker it binds to127.0.0.1.
Documentation
- Getting Started Guide - Detailed setup instructions
- Cloud Provider Support - EKS, GKE, and AKS configuration
- Supported Tools - Complete list of all included CLI tools
- Environment Variables - Configuration options
- Security Features - Security modes and custom rules
- Claude Integration - Detailed Claude Desktop setup
- Architecture - System architecture and components
- Detailed Specification - Complete technical specification
Usage Examples
Once connected, you can ask Claude to help with Kubernetes tasks using natural language:
flowchart TB
subgraph "Basic Commands"
A1["Show me all pods in the default namespace"]
A2["Get all services across all namespaces"]
A3["Display the logs for the nginx pod"]
end
subgraph "Troubleshooting"
B1["Why is my deployment not starting?"]
B2["Describe the failing pod and explain the error"]
B3["Check if my service is properly connected to the pods"]
end
subgraph "Deployments & Configuration"
C1["Deploy the Nginx Helm chart"]
C2["Create a deployment with 3 replicas of nginx:latest"]
C3["Set up an ingress for my service"]
end
subgraph "Advanced Operations"
D1["Check the status of my Istio service mesh"]
D2["Set up a canary deployment with 20% traffic to v2"]
D3["Create an ArgoCD application for my repo"]
end
Claude can understand your intent and run the appropriate kubectl, helm, istioctl, or argocd commands based on your request. It can then explain the output in simple terms or help you troubleshoot issues.
Advanced Claude Desktop Configuration
Configure Claude Desktop to optimize your Kubernetes workflow:
Target Specific Clusters and Namespaces
{
"mcpServers": {
"kubernetes": {
"command": "docker",
"args": [
"run", "-i", "--rm",
"-v", "/Users/YOUR_USER_NAME/.kube:/home/appuser/.kube:ro",
"-e", "K8S_CONTEXT=production-cluster",
"-e", "K8S_NAMESPACE=my-application",
"-e", "K8S_MCP_TIMEOUT=600",
"ghcr.io/alexei-led/k8s-mcp-server:latest"
]
}
}
}
Connect to AWS EKS Clusters
{
"mcpServers": {
"kubernetes": {
"command": "docker",
"args": [
"run", "-i", "--rm",
"-v", "/Users/YOUR_USER_NAME/.kube:/home/appuser/.kube:ro",
"-v", "/Users/YOUR_USER_NAME/.aws:/home/appuser/.aws:ro",
"-e", "AWS_PROFILE=production",
"-e", "AWS_REGION=us-west-2",
"ghcr.io/alexei-led/k8s-mcp-server:latest"
]
}
}
}
Connect to Google GKE Clusters
{
"mcpServers": {
"kubernetes": {
"command": "docker",
"args": [
"run", "-i", "--rm",
"-v", "/Users/YOUR_USER_NAME/.kube:/home/appuser/.kube:ro",
"-v", "/Users/YOUR_USER_NAME/.config/gcloud:/home/appuser/.config/gcloud:ro",
"-e", "CLOUDSDK_CORE_PROJECT=my-gcp-project",
"-e", "CLOUDSDK_COMPUTE_REGION=us-central1",
"ghcr.io/alexei-led/k8s-mcp-server:latest"
]
}
}
}
Connect to Azure AKS Clusters
{
"mcpServers": {
"kubernetes": {
"command": "docker",
"args": [
"run", "-i", "--rm",
"-v", "/Users/YOUR_USER_NAME/.kube:/home/appuser/.kube:ro",
"-v", "/Users/YOUR_USER_NAME/.azure:/home/appuser/.azure:ro",
"-e", "AZURE_SUBSCRIPTION=my-subscription-id",
"ghcr.io/alexei-led/k8s-mcp-server:latest"
]
}
}
}
Permissive Security Mode
{
"mcpServers": {
"kubernetes": {
"command": "docker",
"args": [
"run", "-i", "--rm",
"-v", "/Users/YOUR_USER_NAME/.kube:/home/appuser/.kube:ro",
"-e", "K8S_MCP_SECURITY_MODE=permissive",
"ghcr.io/alexei-led/k8s-mcp-server:latest"
]
}
}
}
For detailed security configuration options, see Security Documentation.
License
This project is licensed under the MIT License - see the LICENSE file for details.