kubectl-mcp-server 1.6.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,128 +10,95 @@ A Model Context Protocol (MCP) server for Kubernetes that enables AI assistants
10
10
  [![npm version](https://badge.fury.io/js/kubectl-mcp-server.svg)](https://www.npmjs.com/package/kubectl-mcp-server)
11
11
  [![Docker](https://img.shields.io/docker/pulls/rohitghumare64/kubectl-mcp-server.svg)](https://hub.docker.com/r/rohitghumare64/kubectl-mcp-server)
12
12
 
13
- ## 🎥 Live Demo - Watch `kubectl-mcp-tool` in Action with Claude!
13
+ ## Live Demos
14
+
15
+ ### Claude Desktop
14
16
  ![Claude MCP](./docs/claude/claude-mcp.gif)
15
17
 
16
- ## 🎥 Live Demo - Watch `kubectl-mcp-tool` in Action with Cursor!
18
+ ### Cursor AI
17
19
  ![Cursor MCP](./docs/cursor/cursor-mcp.gif)
18
20
 
19
- ## 🎥 Live Demo - Watch `kubectl-mcp-tool` in Action with Windsurf!
21
+ ### Windsurf
20
22
  ![Windsurf MCP](./docs/windsurf/windsurf-mcp.gif)
21
23
 
22
-
23
24
  ## Features
24
25
 
25
- ### Core Kubernetes Operations
26
- - [x] Connect to a Kubernetes cluster
27
- - [x] List and manage pods, services, deployments, and nodes
28
- - [x] Create, delete, and describe pods and other resources
29
- - [x] Get pod logs and Kubernetes events
30
- - [x] Support for Helm v3 operations (installation, upgrades, uninstallation)
31
- - [x] kubectl explain and api-resources support
32
- - [x] Choose namespace for next commands (memory persistence)
33
- - [x] Port forward to pods
34
- - [x] Scale deployments and statefulsets
35
- - [x] Execute commands in containers
36
- - [x] Manage ConfigMaps and Secrets
37
- - [x] Rollback deployments to previous versions
38
- - [x] Ingress and NetworkPolicy management
39
- - [x] Context switching between clusters
40
-
41
- ### Natural Language Processing
42
- - [x] Process natural language queries for kubectl operations
43
- - [x] Context-aware commands with memory of previous operations
44
- - [x] Human-friendly explanations of Kubernetes concepts
45
- - [x] Intelligent command construction from intent
46
- - [x] Fallback to kubectl when specialized tools aren't available
47
- - [x] Mock data support for offline/testing scenarios
48
- - [x] Namespace-aware query handling
49
-
50
- ### Monitoring
51
- - [x] Cluster health monitoring
52
- - [x] Resource utilization tracking
53
- - [x] Pod status and health checks
54
- - [x] Event monitoring and alerting
55
- - [x] Node capacity and allocation analysis
56
- - [x] Historical performance tracking
57
- - [x] Resource usage statistics via kubectl top
58
- - [x] Container readiness and liveness tracking
59
-
60
- ### Security
61
- - [x] RBAC validation and verification
62
- - [x] Security context auditing
63
- - [x] Secure connections to Kubernetes API
64
- - [x] Credentials management
65
- - [x] Network policy assessment
66
- - [x] Container security scanning
67
- - [x] Security best practices enforcement
68
- - [x] Role and ClusterRole management
69
- - [x] ServiceAccount creation and binding
70
- - [x] PodSecurityPolicy analysis
71
- - [x] RBAC permissions auditing
72
- - [x] Security context validation
73
-
74
- ### Diagnostics
75
- - [x] Cluster diagnostics and troubleshooting
76
- - [x] Configuration validation
77
- - [x] Error analysis and recovery suggestions
78
- - [x] Connection status monitoring
79
- - [x] Log analysis and pattern detection
80
- - [x] Resource constraint identification
81
- - [x] Pod health check diagnostics
82
- - [x] Common error pattern identification
83
- - [x] Resource validation for misconfigurations
84
- - [x] Detailed liveness and readiness probe validation
85
-
86
- ### Advanced Features
87
- - [x] Multiple transport protocols support (stdio, SSE, HTTP/streamable-http)
88
- - [x] Integration with multiple AI assistants (Claude Desktop, Claude Code, Cursor, Windsurf)
89
- - [x] Multi-cluster support with context switching
90
- - [x] Extensible tool framework
91
- - [x] Custom resource definition support
92
- - [x] Cross-namespace operations
93
- - [x] Batch operations on multiple resources
94
- - [x] Intelligent resource relationship mapping
95
- - [x] Error explanation with recovery suggestions
96
- - [x] Volume management and identification
97
- - [x] Command injection protection with input validation
98
- - [x] Non-destructive mode (`--non-destructive` flag)
99
- - [x] Secrets masking in output
100
- - [x] Helm template rendering and application
101
- - [x] Node management (cordon, drain, uncordon)
102
- - [x] Pod cleanup for failed/evicted pods
103
- - [x] Guided troubleshooting prompts
104
-
105
- ## Architecture
106
-
107
- ### Model Context Protocol (MCP) Integration
108
-
109
- The Kubectl MCP Tool implements the [Model Context Protocol (MCP)](https://github.com/modelcontextprotocol/spec), enabling AI assistants to interact with Kubernetes clusters through a standardized interface. The architecture consists of:
110
-
111
- 1. **MCP Server**: A compliant server that handles requests from MCP clients (AI assistants)
112
- 2. **Tools Registry**: Registers Kubernetes operations as MCP tools with schemas
113
- 3. **Transport Layer**: Supports stdio, SSE, and HTTP transport methods
114
- 4. **Core Operations**: Translates tool calls to Kubernetes API operations
115
- 5. **Response Formatter**: Converts Kubernetes responses to MCP-compliant responses
116
-
117
- ### Request Flow
118
-
119
- ![Request Flow](./image.png)
120
-
121
- ### Dual Mode Operation
122
-
123
- The tool operates in two modes:
26
+ ### 80+ MCP Tools for Complete Kubernetes Management
124
27
 
125
- 1. **CLI Mode**: Direct command-line interface for executing Kubernetes operations
126
- 2. **Server Mode**: Running as an MCP server to handle requests from AI assistants
28
+ | Category | Tools |
29
+ |----------|-------|
30
+ | **Pods** | `get_pods`, `get_logs`, `get_pod_events`, `check_pod_health`, `exec_in_pod`, `cleanup_pods`, `get_pod_conditions`, `get_previous_logs` |
31
+ | **Deployments** | `get_deployments`, `create_deployment`, `scale_deployment`, `kubectl_rollout`, `restart_deployment` |
32
+ | **Workloads** | `get_statefulsets`, `get_daemonsets`, `get_jobs`, `get_replicasets` |
33
+ | **Services & Networking** | `get_services`, `get_ingress`, `get_endpoints`, `diagnose_network_connectivity`, `check_dns_resolution`, `trace_service_chain` |
34
+ | **Storage** | `get_persistent_volumes`, `get_pvcs`, `get_storage_classes` |
35
+ | **Config** | `get_configmaps`, `get_secrets`, `get_resource_quotas`, `get_limit_ranges` |
36
+ | **Cluster** | `get_nodes`, `get_namespaces`, `get_cluster_info`, `get_cluster_version`, `health_check`, `get_node_metrics`, `get_pod_metrics` |
37
+ | **RBAC & Security** | `get_rbac_roles`, `get_cluster_roles`, `get_service_accounts`, `audit_rbac_permissions`, `check_secrets_security`, `get_pod_security_info`, `get_admission_webhooks` |
38
+ | **CRDs** | `get_crds`, `get_priority_classes` |
39
+ | **Helm** | `install_helm_chart`, `upgrade_helm_chart`, `uninstall_helm_chart`, `helm_template`, `helm_template_apply` |
40
+ | **Context** | `get_current_context`, `switch_context`, `list_contexts`, `list_kubeconfig_contexts` |
41
+ | **Diagnostics** | `diagnose_pod_crash`, `detect_pending_pods`, `get_evicted_pods`, `compare_namespaces` |
42
+ | **Operations** | `kubectl_apply`, `kubectl_create`, `kubectl_describe`, `kubectl_patch`, `delete_resource`, `kubectl_cp`, `backup_resource`, `label_resource`, `annotate_resource`, `taint_node`, `wait_for_condition` |
43
+ | **Autoscaling** | `get_hpa`, `get_pdb` |
44
+ | **Cost Optimization** | `get_resource_recommendations`, `get_idle_resources`, `get_resource_quotas_usage`, `get_cost_analysis`, `get_overprovisioned_resources`, `get_resource_trends`, `get_namespace_cost_allocation`, `optimize_resource_requests` |
45
+ | **Advanced** | `kubectl_generic`, `kubectl_explain`, `get_api_resources`, `port_forward`, `get_resource_usage`, `node_management` |
46
+
47
+ ### MCP Resources (FastMCP 3)
48
+
49
+ Access Kubernetes data as browsable resources:
50
+
51
+ | Resource URI | Description |
52
+ |--------------|-------------|
53
+ | `kubeconfig://contexts` | List all available kubectl contexts |
54
+ | `kubeconfig://current-context` | Get current active context |
55
+ | `namespace://current` | Get current namespace |
56
+ | `namespace://list` | List all namespaces |
57
+ | `cluster://info` | Get cluster information |
58
+ | `cluster://nodes` | Get detailed node information |
59
+ | `cluster://version` | Get Kubernetes version |
60
+ | `cluster://api-resources` | List available API resources |
61
+ | `manifest://deployments/{ns}/{name}` | Get deployment YAML |
62
+ | `manifest://services/{ns}/{name}` | Get service YAML |
63
+ | `manifest://pods/{ns}/{name}` | Get pod YAML |
64
+ | `manifest://configmaps/{ns}/{name}` | Get ConfigMap YAML |
65
+ | `manifest://secrets/{ns}/{name}` | Get secret YAML (data masked) |
66
+ | `manifest://ingresses/{ns}/{name}` | Get ingress YAML |
67
+
68
+ ### MCP Prompts (FastMCP 3)
69
+
70
+ Pre-built workflow prompts for common Kubernetes operations:
71
+
72
+ | Prompt | Description |
73
+ |--------|-------------|
74
+ | `troubleshoot_workload` | Comprehensive troubleshooting guide for pods/deployments |
75
+ | `deploy_application` | Step-by-step deployment workflow |
76
+ | `security_audit` | Security scanning and RBAC analysis workflow |
77
+ | `cost_optimization` | Resource optimization and cost analysis workflow |
78
+ | `disaster_recovery` | Backup and recovery planning workflow |
79
+ | `debug_networking` | Network debugging for services and connectivity |
80
+ | `scale_application` | Scaling guide with HPA/VPA best practices |
81
+ | `upgrade_cluster` | Kubernetes cluster upgrade planning |
82
+
83
+ ### Key Capabilities
84
+
85
+ - **Multi-Transport Support**: stdio, SSE, HTTP/streamable-http
86
+ - **AI Assistant Integration**: Claude Desktop, Claude Code, Cursor, Windsurf
87
+ - **Multi-Cluster**: Context switching between clusters
88
+ - **Security**: Non-destructive mode, secrets masking, RBAC validation
89
+ - **Diagnostics**: Pod crash analysis, network connectivity testing, DNS resolution checks
90
+ - **Helm v3**: Full Helm chart lifecycle management
91
+ - **Cost Optimization**: Resource recommendations, idle resource detection, usage analysis
92
+ - **FastMCP 3**: MCP Resources and Prompts for enhanced AI workflows
127
93
 
128
94
  ## Installation
129
95
 
130
- For detailed installation instructions, please see the [Installation Guide](./docs/INSTALLATION.md).
131
-
132
- ### npm / npx (Recommended for Node.js users)
96
+ ### Prerequisites
97
+ - Python 3.9+
98
+ - kubectl CLI installed and configured
99
+ - Access to a Kubernetes cluster
133
100
 
134
- The easiest way to run kubectl-mcp-server is via npx:
101
+ ### npm / npx (Recommended)
135
102
 
136
103
  ```bash
137
104
  # Run directly without installation
@@ -139,289 +106,33 @@ npx kubectl-mcp-server
139
106
 
140
107
  # Or install globally
141
108
  npm install -g kubectl-mcp-server
142
- kubectl-mcp-server
143
109
  ```
144
110
 
145
- The npm package is available at: [https://www.npmjs.com/package/kubectl-mcp-server](https://www.npmjs.com/package/kubectl-mcp-server)
146
-
147
- > **Note:** The npm package requires Python 3.9+ to be installed. It will automatically install the Python dependencies on first run.
148
-
149
111
  ### pip (Python)
150
112
 
151
- You can install kubectl-mcp-tool directly from PyPI:
152
-
153
113
  ```bash
154
114
  pip install kubectl-mcp-tool
155
115
  ```
156
116
 
157
- For a specific version:
158
-
159
- ```bash
160
- pip install kubectl-mcp-tool==1.4.0
161
- ```
162
-
163
- The package is available on PyPI: [https://pypi.org/project/kubectl-mcp-tool/](https://pypi.org/project/kubectl-mcp-tool/)
164
-
165
- ### Prerequisites
166
-
167
- - Python 3.9+
168
- - kubectl CLI installed and configured
169
- - Access to a Kubernetes cluster
170
- - pip (Python package manager)
171
-
172
- ### Global Installation
173
-
174
- ```bash
175
- # Install latest version from PyPI
176
- pip install kubectl-mcp-tool
177
-
178
- # Or install development version from GitHub
179
- pip install git+https://github.com/rohitg00/kubectl-mcp-server.git
180
- ```
181
-
182
- ### Local Development Installation
183
-
184
- ```bash
185
- # Clone the repository
186
- git clone https://github.com/rohitg00/kubectl-mcp-server.git
187
- cd kubectl-mcp-server
188
-
189
- # Install in development mode
190
- pip install -e .
191
- ```
192
-
193
- ### Verifying Installation
194
-
195
- After installation, verify the tool is working correctly:
196
-
197
- ```bash
198
- kubectl-mcp --help
199
- ```
200
-
201
- Note: This tool is designed to work as an MCP server that AI assistants connect to, not as a direct kubectl replacement. The primary command available is `kubectl-mcp serve` which starts the MCP server.
202
-
203
- ## Docker Image
204
-
205
- Pre-built images are available on Docker Hub:
117
+ ### Docker
206
118
 
207
119
  ```bash
208
120
  # Pull the latest image
209
121
  docker pull rohitghumare64/kubectl-mcp-server:latest
210
122
 
211
- # Or use the official MCP catalog image
212
- docker pull mcp/kubectl-mcp-server:latest
213
- ```
214
-
215
- ### Docker MCP Toolkit Integration
216
-
217
- This image is compatible with [Docker MCP Toolkit](https://docs.docker.com/ai/mcp-catalog-and-toolkit/toolkit/). The Toolkit provides a streamlined way to run MCP servers with Claude, Cursor, and other AI assistants.
218
-
219
- **Quick Setup with Docker MCP Toolkit:**
220
-
221
- 1. **Add the server to Docker MCP Toolkit:**
222
- ```bash
223
- docker mcp server add kubectl-mcp-server mcp/kubectl-mcp-server:latest
224
- ```
225
-
226
- 2. **Configure kubeconfig access:**
227
- ```bash
228
- docker mcp server configure kubectl-mcp-server --volume "$HOME/.kube:/root/.kube:ro"
229
- ```
230
-
231
- 3. **Enable the server:**
232
- ```bash
233
- docker mcp server enable kubectl-mcp-server
234
- ```
235
-
236
- 4. **Connect your AI client** (e.g., Claude Desktop):
237
- ```bash
238
- docker mcp client connect claude
239
- ```
240
-
241
- The server uses **stdio transport** by default for Docker MCP Toolkit compatibility.
242
-
243
- ### Running the image (Standalone)
244
-
245
- For SSE/HTTP transport (without Docker MCP Toolkit):
246
-
247
- ```bash
248
- # SSE transport on port 8000
249
- docker run -p 8081:8000 \
250
- -v $HOME/.kube:/root/.kube:ro \
251
- rohitghumare64/kubectl-mcp-server:latest \
252
- --transport sse --host 0.0.0.0 --port 8000
253
- ```
254
-
255
- For stdio transport (for direct MCP client connections):
256
-
257
- ```bash
258
- docker run -i \
259
- -v $HOME/.kube:/root/.kube:ro \
260
- rohitghumare64/kubectl-mcp-server:latest
261
- ```
262
-
263
- * `-i` enables interactive mode for stdio transport
264
- * `-v $HOME/.kube:/root/.kube:ro` mounts kubeconfig as read-only
265
-
266
- ### Building a multi-architecture image (AMD64 & ARM64)
267
-
268
- If you want to build and push a multi-arch image (so it runs on both x86_64 and Apple Silicon), use Docker Buildx:
269
-
270
- ```bash
271
- # Ensure Buildx and QEMU are installed once per machine
272
- # docker buildx create --name multiarch --use
273
- # docker buildx inspect --bootstrap
274
-
275
- # Build and push for linux/amd64 and linux/arm64
276
- # (replace <your_username> if you're publishing to your own registry)
277
-
278
- docker buildx build \
279
- --platform linux/amd64,linux/arm64 \
280
- -t rohitghumare64/kubectl-mcp-server:latest \
281
- --push .
282
- ```
283
-
284
- The published image will contain a manifest list with both architectures, and Docker will automatically pull the correct variant on each machine.
285
-
286
- ### Configuration
287
-
288
- The MCP server is allowed to access these paths to read your Kubernetes configuration:
289
-
290
- ```yaml
291
- run:
292
- volumes:
293
- - '{{kubectl-mcp-server.kubeconfig}}:/root/.kube'
294
- config:
295
- description: The MCP server is allowed to access this path
296
- parameters:
297
- type: object
298
- properties:
299
- kubeconfig:
300
- type: string
301
- default:
302
- $HOME/.kube
303
- required:
304
- - kubeconfig
305
- ```
306
-
307
- This configuration allows users to add their kubeconfig directory to the container, enabling the MCP server to authenticate with their Kubernetes cluster.
308
-
309
- ## Transport Modes
310
-
311
- The MCP server supports multiple transport protocols:
312
-
313
- ### stdio (default)
314
- Standard input/output transport, used by most MCP clients like Claude Desktop and Cursor:
315
- ```bash
316
- python -m kubectl_mcp_tool.mcp_server --transport stdio
317
- ```
318
-
319
- ### SSE (Server-Sent Events)
320
- HTTP-based transport using Server-Sent Events:
321
- ```bash
322
- python -m kubectl_mcp_tool.mcp_server --transport sse --host 0.0.0.0 --port 8000
323
- ```
324
-
325
- ### HTTP / Streamable HTTP
326
- Standard HTTP transport for clients that prefer JSON-RPC over HTTP:
327
- ```bash
328
- python -m kubectl_mcp_tool.mcp_server --transport http --host 0.0.0.0 --port 8000
329
- # or
330
- python -m kubectl_mcp_tool.mcp_server --transport streamable-http --host 0.0.0.0 --port 8000
331
- ```
332
-
333
- ### Command-Line Options
334
- - `--transport`: Transport mode (`stdio`, `sse`, `http`, `streamable-http`). Default: `stdio`
335
- - `--host`: Host to bind for network transports. Default: `0.0.0.0`
336
- - `--port`: Port for network transports. Default: `8000`
337
- - `--non-destructive`: Block destructive operations (delete, apply, create, etc.)
338
-
339
- ## Multi-Cluster Support
340
-
341
- The MCP server provides full multi-cluster support through context management:
342
-
343
- ```bash
344
- # List all available contexts
345
- list_contexts
346
-
347
- # Switch to a different cluster
348
- switch_context --context_name production
349
-
350
- # Get details about a specific context
351
- get_context_details --context_name staging
123
+ # Run with stdio transport
124
+ docker run -i -v $HOME/.kube:/root/.kube:ro rohitghumare64/kubectl-mcp-server:latest
352
125
 
353
- # Set default namespace for a context
354
- set_namespace_for_context --namespace kube-system --context_name production
126
+ # Run with SSE transport
127
+ docker run -p 8000:8000 -v $HOME/.kube:/root/.kube:ro rohitghumare64/kubectl-mcp-server:latest --transport sse
355
128
  ```
356
129
 
357
- For detailed monitoring features documentation, see [Monitoring Guide](./docs/monitoring.md).
358
-
359
- ## Available Tools
360
-
361
- The MCP server provides 40+ tools for Kubernetes management:
362
-
363
- | Category | Tools |
364
- |----------|-------|
365
- | **Pods** | `get_pods`, `get_logs`, `get_pod_events`, `check_pod_health`, `exec_in_pod`, `cleanup_pods` |
366
- | **Deployments** | `get_deployments`, `create_deployment`, `scale_deployment`, `kubectl_rollout` |
367
- | **Resources** | `get_services`, `get_nodes`, `get_namespaces`, `get_configmaps`, `get_secrets`, `get_events` |
368
- | **CRUD** | `kubectl_apply`, `kubectl_create`, `kubectl_describe`, `kubectl_patch`, `delete_resource`, `kubectl_cp` |
369
- | **Helm** | `install_helm_chart`, `upgrade_helm_chart`, `uninstall_helm_chart`, `helm_template`, `helm_template_apply` |
370
- | **Cluster** | `get_current_context`, `switch_context`, `list_contexts`, `list_kubeconfig_contexts`, `get_cluster_info`, `health_check` |
371
- | **Security** | `analyze_pod_security`, `analyze_network_policies`, `audit_rbac_permissions`, `check_secrets_security`, `get_rbac_roles`, `get_cluster_roles` |
372
- | **Node Ops** | `node_management` (cordon, drain, uncordon) |
373
- | **Advanced** | `kubectl_generic`, `kubectl_explain`, `get_api_resources`, `port_forward`, `get_resource_usage` |
374
-
375
- ## Usage with AI Assistants
376
-
377
- ### Using the MCP Server
378
-
379
- The MCP Server (`kubectl_mcp_tool.mcp_server`) is a robust implementation built on the FastMCP SDK that provides enhanced compatibility across different AI assistants:
380
-
381
- > **Note**: If you encounter any errors with the MCP Server implementation, you can fall back to using the minimal wrapper by replacing `kubectl_mcp_tool.mcp_server` with `kubectl_mcp_tool.minimal_wrapper` in your configuration. The minimal wrapper provides basic capabilities with simpler implementation.
382
-
383
- 1. **Direct Configuration**
384
- ```json
385
- {
386
- "mcpServers": {
387
- "kubernetes": {
388
- "command": "python",
389
- "args": ["-m", "kubectl_mcp_tool.mcp_server"],
390
- "env": {
391
- "KUBECONFIG": "/path/to/your/.kube/config",
392
- "PATH": "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",
393
- "MCP_LOG_FILE": "/path/to/logs/debug.log",
394
- "MCP_DEBUG": "1"
395
- }
396
- }
397
- }
398
- }
399
- ```
400
-
401
- 2. **Key Environment Variables**
402
- - `MCP_LOG_FILE`: Path to log file (recommended to avoid stdout pollution)
403
- - `MCP_DEBUG`: Set to "1" for verbose logging
404
- - `MCP_TEST_MOCK_MODE`: Set to "1" to use mock data instead of real cluster
405
- - `KUBECONFIG`: Path to your Kubernetes config file
406
- - `KUBECTL_MCP_LOG_LEVEL`: Set to "DEBUG", "INFO", "WARNING", or "ERROR"
407
-
408
- 3. **Testing the MCP Server**
409
- You can test if the server is working correctly with:
410
- ```bash
411
- python -m kubectl_mcp_tool.simple_ping
412
- ```
413
- This will attempt to connect to the server and execute a ping command.
414
-
415
- Alternatively, you can directly run the server with:
416
- ```bash
417
- python -m kubectl_mcp_tool
418
- ```
130
+ ## Quick Start
419
131
 
420
132
  ### Claude Desktop
421
133
 
422
- Add the following to your Claude Desktop configuration at `~/Library/Application\ Support/Claude/claude_desktop_config.json` (Windows: `%APPDATA%\Claude\mcp.json`):
134
+ Add to `~/Library/Application Support/Claude/claude_desktop_config.json`:
423
135
 
424
- **Using npx (Recommended):**
425
136
  ```json
426
137
  {
427
138
  "mcpServers": {
@@ -433,26 +144,10 @@ Add the following to your Claude Desktop configuration at `~/Library/Application
433
144
  }
434
145
  ```
435
146
 
436
- **Using Python directly:**
437
- ```json
438
- {
439
- "mcpServers": {
440
- "kubernetes": {
441
- "command": "python",
442
- "args": ["-m", "kubectl_mcp_tool.mcp_server"],
443
- "env": {
444
- "KUBECONFIG": "$HOME/.kube/config" // or whatever your path is for the config file
445
- }
446
- }
447
- }
448
- }
449
- ```
450
-
451
147
  ### Claude Code
452
148
 
453
- Claude Code is Anthropic's CLI tool for coding with Claude. Add the following to `~/.config/claude-code/mcp.json`:
149
+ Add to `~/.config/claude-code/mcp.json`:
454
150
 
455
- **Using npx (Recommended):**
456
151
  ```json
457
152
  {
458
153
  "mcpServers": {
@@ -464,28 +159,25 @@ Claude Code is Anthropic's CLI tool for coding with Claude. Add the following to
464
159
  }
465
160
  ```
466
161
 
467
- **Using Python directly:**
162
+ ### Cursor AI
163
+
164
+ Add to `~/.cursor/mcp.json`:
165
+
468
166
  ```json
469
167
  {
470
168
  "mcpServers": {
471
169
  "kubernetes": {
472
- "command": "python",
473
- "args": ["-m", "kubectl_mcp_tool.mcp_server"],
474
- "env": {
475
- "KUBECONFIG": "/path/to/your/.kube/config"
476
- }
170
+ "command": "npx",
171
+ "args": ["-y", "kubectl-mcp-server"]
477
172
  }
478
173
  }
479
174
  }
480
175
  ```
481
176
 
482
- For detailed Claude Code integration instructions, see [Claude Code Integration Guide](./docs/claude/claude_code_integration.md).
483
-
484
- ### Cursor AI
177
+ ### Windsurf
485
178
 
486
- Add the following to your Cursor AI settings under MCP by adding a new global MCP server:
179
+ Add to `~/.config/windsurf/mcp.json`:
487
180
 
488
- **Using npx (Recommended):**
489
181
  ```json
490
182
  {
491
183
  "mcpServers": {
@@ -497,7 +189,10 @@ Add the following to your Cursor AI settings under MCP by adding a new global MC
497
189
  }
498
190
  ```
499
191
 
500
- **Using Python directly:**
192
+ ### Using Python Directly
193
+
194
+ If you prefer Python over npx:
195
+
501
196
  ```json
502
197
  {
503
198
  "mcpServers": {
@@ -505,53 +200,152 @@ Add the following to your Cursor AI settings under MCP by adding a new global MC
505
200
  "command": "python",
506
201
  "args": ["-m", "kubectl_mcp_tool.mcp_server"],
507
202
  "env": {
508
- "KUBECONFIG": "/path/to/your/.kube/config",
509
- "PATH": "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/homebrew/bin"
203
+ "KUBECONFIG": "/path/to/.kube/config"
510
204
  }
511
205
  }
512
206
  }
513
207
  }
514
208
  ```
515
209
 
516
- Save this configuration to `~/.cursor/mcp.json` for global settings.
210
+ ## Transport Modes
517
211
 
518
- > **Note**: Replace `/path/to/your/.kube/config` with the actual path to your kubeconfig file. On most systems, this is `~/.kube/config`.
212
+ ```bash
213
+ # stdio (default) - for Claude Desktop, Cursor, etc.
214
+ python -m kubectl_mcp_tool.mcp_server
519
215
 
520
- ### Windsurf
216
+ # SSE - Server-Sent Events
217
+ python -m kubectl_mcp_tool.mcp_server --transport sse --port 8000
521
218
 
522
- Add the following to your Windsurf configuration at `~/.config/windsurf/mcp.json` (Windows: `%APPDATA%\WindSurf\mcp.json`):
219
+ # HTTP
220
+ python -m kubectl_mcp_tool.mcp_server --transport http --port 8000
221
+ ```
523
222
 
524
- **Using npx (Recommended):**
525
- ```json
526
- {
527
- "mcpServers": {
528
- "kubernetes": {
529
- "command": "npx",
530
- "args": ["-y", "kubectl-mcp-server"]
531
- }
532
- }
533
- }
223
+ ### Options
224
+ - `--transport`: `stdio`, `sse`, `http`, `streamable-http` (default: `stdio`)
225
+ - `--host`: Host to bind (default: `0.0.0.0`)
226
+ - `--port`: Port for network transports (default: `8000`)
227
+ - `--non-destructive`: Block destructive operations (delete, apply, create)
228
+
229
+ ## Environment Variables
230
+
231
+ | Variable | Description |
232
+ |----------|-------------|
233
+ | `KUBECONFIG` | Path to kubeconfig file (default: `~/.kube/config`) |
234
+ | `MCP_DEBUG` | Set to `1` for verbose logging |
235
+ | `MCP_LOG_FILE` | Path to log file |
236
+
237
+ ## Docker MCP Toolkit
238
+
239
+ Compatible with [Docker MCP Toolkit](https://docs.docker.com/ai/mcp-catalog-and-toolkit/toolkit/):
240
+
241
+ ```bash
242
+ # Add server
243
+ docker mcp server add kubectl-mcp-server mcp/kubectl-mcp-server:latest
244
+
245
+ # Configure kubeconfig
246
+ docker mcp server configure kubectl-mcp-server --volume "$HOME/.kube:/root/.kube:ro"
247
+
248
+ # Enable and connect
249
+ docker mcp server enable kubectl-mcp-server
250
+ docker mcp client connect claude
534
251
  ```
535
252
 
536
- **Using Python directly:**
537
- ```json
538
- {
539
- "mcpServers": {
540
- "kubernetes": {
541
- "command": "python",
542
- "args": ["-m", "kubectl_mcp_tool.mcp_server"],
543
- "env": {
544
- "KUBECONFIG": "/path/to/your/.kube/config"
545
- }
546
- }
547
- }
548
- }
253
+ ## Architecture
254
+
255
+ ```
256
+ ┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
257
+ │ AI Assistant │────▶│ MCP Server │────▶│ Kubernetes API │
258
+ (Claude/Cursor) │◀────│ (kubectl-mcp) │◀────│ (kubectl) │
259
+ └─────────────────┘ └──────────────────┘ └─────────────────┘
260
+ ```
261
+
262
+ The MCP server implements the [Model Context Protocol](https://github.com/modelcontextprotocol/spec), translating natural language requests into kubectl operations.
263
+
264
+ ## Multi-Cluster Support
265
+
266
+ ```bash
267
+ # List contexts
268
+ list_contexts
269
+
270
+ # Switch cluster
271
+ switch_context --context_name production
272
+
273
+ # Get context details
274
+ get_context_details --context_name staging
275
+ ```
276
+
277
+ ## Development & Testing
278
+
279
+ ### Setup Development Environment
280
+
281
+ ```bash
282
+ # Clone the repository
283
+ git clone https://github.com/rohitg00/kubectl-mcp-server.git
284
+ cd kubectl-mcp-server
285
+
286
+ # Create virtual environment
287
+ python -m venv venv
288
+ source venv/bin/activate # On Windows: venv\Scripts\activate
289
+
290
+ # Install development dependencies
291
+ pip install -r requirements-dev.txt
549
292
  ```
550
293
 
551
- ### Automatic Configuration
294
+ ### Running Tests
552
295
 
553
- For automatic configuration of all supported AI assistants, run the provided installation script:
296
+ ```bash
297
+ # Run all tests
298
+ pytest tests/ -v
299
+
300
+ # Run specific test file
301
+ pytest tests/test_tools.py -v
302
+
303
+ # Run with coverage
304
+ pytest tests/ --cov=kubectl_mcp_tool --cov-report=html
305
+
306
+ # Run only unit tests
307
+ pytest tests/ -v -m unit
308
+ ```
309
+
310
+ ### Test Structure
311
+
312
+ ```
313
+ tests/
314
+ ├── __init__.py # Test package
315
+ ├── conftest.py # Shared fixtures and mocks
316
+ ├── test_tools.py # Unit tests for 80+ MCP tools
317
+ ├── test_resources.py # Tests for MCP Resources
318
+ ├── test_prompts.py # Tests for MCP Prompts
319
+ └── test_server.py # Server initialization tests
320
+ ```
321
+
322
+ ### Code Quality
554
323
 
555
324
  ```bash
556
- bash install.sh
557
- ```
325
+ # Format code
326
+ black kubectl_mcp_tool tests
327
+
328
+ # Sort imports
329
+ isort kubectl_mcp_tool tests
330
+
331
+ # Lint
332
+ flake8 kubectl_mcp_tool tests
333
+
334
+ # Type checking
335
+ mypy kubectl_mcp_tool
336
+ ```
337
+
338
+ ## Contributing
339
+
340
+ Contributions are welcome! Please feel free to submit a Pull Request.
341
+
342
+ ## License
343
+
344
+ MIT License - see [LICENSE](LICENSE) for details.
345
+
346
+ ## Links
347
+
348
+ - [PyPI Package](https://pypi.org/project/kubectl-mcp-tool/)
349
+ - [npm Package](https://www.npmjs.com/package/kubectl-mcp-server)
350
+ - [Docker Hub](https://hub.docker.com/r/rohitghumare64/kubectl-mcp-server)
351
+ - [GitHub Issues](https://github.com/rohitg00/kubectl-mcp-server/issues)
package/bin/cli.js CHANGED
@@ -1,53 +1,23 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- const { spawn } = require('child_process');
4
- const { existsSync } = require('fs');
5
- const path = require('path');
6
- const os = require('os');
3
+ const { spawn, spawnSync } = require('child_process');
7
4
 
8
- // ANSI color codes
9
- const colors = {
10
- red: '\x1b[31m',
11
- green: '\x1b[32m',
12
- yellow: '\x1b[33m',
13
- blue: '\x1b[34m',
14
- reset: '\x1b[0m'
15
- };
16
-
17
- function log(message, color = 'reset') {
18
- console.error(`${colors[color]}${message}${colors.reset}`);
19
- }
5
+ const colors = { red: '\x1b[31m', green: '\x1b[32m', yellow: '\x1b[33m', reset: '\x1b[0m' };
6
+ const log = (msg, color = 'reset') => console.error(`${colors[color]}${msg}${colors.reset}`);
20
7
 
21
8
  function getPythonCommand() {
22
- // Try different Python commands
23
- const commands = process.platform === 'win32'
24
- ? ['python', 'python3', 'py']
25
- : ['python3', 'python'];
26
-
9
+ const commands = process.platform === 'win32' ? ['python', 'python3', 'py'] : ['python3', 'python'];
27
10
  for (const cmd of commands) {
28
11
  try {
29
- const result = require('child_process').spawnSync(cmd, ['--version'], {
30
- encoding: 'utf8',
31
- stdio: ['pipe', 'pipe', 'pipe']
32
- });
33
- if (result.status === 0) {
34
- return cmd;
35
- }
36
- } catch (e) {
37
- // Continue to next command
38
- }
12
+ if (spawnSync(cmd, ['--version'], { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }).status === 0) return cmd;
13
+ } catch (e) {}
39
14
  }
40
15
  return null;
41
16
  }
42
17
 
43
18
  function checkPythonPackage(pythonCmd) {
44
19
  try {
45
- const result = require('child_process').spawnSync(
46
- pythonCmd,
47
- ['-c', 'import kubectl_mcp_tool; print(kubectl_mcp_tool.__file__)'],
48
- { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }
49
- );
50
- return result.status === 0;
20
+ return spawnSync(pythonCmd, ['-c', 'import kubectl_mcp_tool'], { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }).status === 0;
51
21
  } catch (e) {
52
22
  return false;
53
23
  }
@@ -56,7 +26,6 @@ function checkPythonPackage(pythonCmd) {
56
26
  function main() {
57
27
  const args = process.argv.slice(2);
58
28
 
59
- // Handle help flag
60
29
  if (args.includes('--help') || args.includes('-h')) {
61
30
  console.log(`
62
31
  kubectl-mcp-server - MCP Server for Kubernetes
@@ -64,90 +33,47 @@ kubectl-mcp-server - MCP Server for Kubernetes
64
33
  Usage: kubectl-mcp-server [options]
65
34
 
66
35
  Options:
67
- --transport <mode> Transport mode: stdio, sse, http, streamable-http (default: stdio)
68
- --host <host> Host to bind for network transports (default: 0.0.0.0)
69
- --port <port> Port for network transports (default: 8000)
70
- --non-destructive Block destructive operations (delete, apply, create, etc.)
71
- --help, -h Show this help message
72
- --version, -v Show version
73
-
74
- Examples:
75
- kubectl-mcp-server # Start with stdio transport
76
- kubectl-mcp-server --transport sse # Start with SSE transport
77
- kubectl-mcp-server --transport http --port 3000
78
-
79
- Environment Variables:
80
- KUBECONFIG Path to kubeconfig file (default: ~/.kube/config)
81
- MCP_DEBUG Set to "1" for verbose logging
82
- MCP_LOG_FILE Path to log file
83
-
84
- For more information, visit: https://github.com/rohitg00/kubectl-mcp-server
36
+ --transport <mode> Transport: stdio, sse, http, streamable-http (default: stdio)
37
+ --host <host> Host for network transports (default: 0.0.0.0)
38
+ --port <port> Port for network transports (default: 8000)
39
+ --non-destructive Block destructive operations
40
+ --help, -h Show this help message
41
+ --version, -v Show version
42
+
43
+ For more info: https://github.com/rohitg00/kubectl-mcp-server
85
44
  `);
86
45
  process.exit(0);
87
46
  }
88
47
 
89
- // Handle version flag
90
48
  if (args.includes('--version') || args.includes('-v')) {
91
- const pkg = require('../package.json');
92
- console.log(`kubectl-mcp-server v${pkg.version}`);
49
+ console.log(`kubectl-mcp-server v${require('../package.json').version}`);
93
50
  process.exit(0);
94
51
  }
95
52
 
96
- // Check for Python
97
53
  const pythonCmd = getPythonCommand();
98
54
  if (!pythonCmd) {
99
- log('Error: Python 3.9+ is required but not found.', 'red');
100
- log('Please install Python from https://www.python.org/downloads/', 'yellow');
55
+ log('Error: Python 3.9+ is required. Install from https://python.org', 'red');
101
56
  process.exit(1);
102
57
  }
103
58
 
104
- // Check if kubectl-mcp-tool is installed
105
59
  if (!checkPythonPackage(pythonCmd)) {
106
- log('kubectl-mcp-tool Python package not found. Installing...', 'yellow');
107
-
108
- const installResult = require('child_process').spawnSync(
109
- pythonCmd,
110
- ['-m', 'pip', 'install', 'kubectl-mcp-tool'],
111
- { stdio: 'inherit' }
112
- );
113
-
114
- if (installResult.status !== 0) {
115
- log('Error: Failed to install kubectl-mcp-tool package.', 'red');
116
- log('Try installing manually: pip install kubectl-mcp-tool', 'yellow');
60
+ log('Installing kubectl-mcp-tool...', 'yellow');
61
+ if (spawnSync(pythonCmd, ['-m', 'pip', 'install', 'kubectl-mcp-tool'], { stdio: 'inherit' }).status !== 0) {
62
+ log('Failed to install. Try: pip install kubectl-mcp-tool', 'red');
117
63
  process.exit(1);
118
64
  }
119
-
120
- log('kubectl-mcp-tool installed successfully!', 'green');
65
+ log('Installed successfully!', 'green');
121
66
  }
122
67
 
123
- // Run the Python MCP server
124
- const serverArgs = ['-m', 'kubectl_mcp_tool.mcp_server', ...args];
125
-
126
- const server = spawn(pythonCmd, serverArgs, {
68
+ const server = spawn(pythonCmd, ['-m', 'kubectl_mcp_tool.mcp_server', ...args], {
127
69
  stdio: 'inherit',
128
- env: {
129
- ...process.env,
130
- PYTHONUNBUFFERED: '1'
131
- }
132
- });
133
-
134
- server.on('error', (err) => {
135
- log(`Error starting MCP server: ${err.message}`, 'red');
136
- process.exit(1);
70
+ env: { ...process.env, PYTHONUNBUFFERED: '1' }
137
71
  });
138
72
 
139
- server.on('close', (code) => {
140
- process.exit(code || 0);
141
- });
142
-
143
- // Handle signals
144
- process.on('SIGINT', () => {
145
- server.kill('SIGINT');
146
- });
147
-
148
- process.on('SIGTERM', () => {
149
- server.kill('SIGTERM');
150
- });
73
+ server.on('error', (err) => { log(`Error: ${err.message}`, 'red'); process.exit(1); });
74
+ server.on('close', (code) => process.exit(code || 0));
75
+ process.on('SIGINT', () => server.kill('SIGINT'));
76
+ process.on('SIGTERM', () => server.kill('SIGTERM'));
151
77
  }
152
78
 
153
79
  main();
@@ -1,147 +1,47 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- /**
4
- * Post-install script for kubectl-mcp-server npm package
5
- * Checks for Python and optionally installs the Python package
6
- */
7
-
8
3
  const { spawnSync } = require('child_process');
9
4
 
10
- // ANSI color codes
11
- const colors = {
12
- red: '\x1b[31m',
13
- green: '\x1b[32m',
14
- yellow: '\x1b[33m',
15
- blue: '\x1b[34m',
16
- cyan: '\x1b[36m',
17
- reset: '\x1b[0m',
18
- bold: '\x1b[1m'
19
- };
20
-
21
- function log(message, color = 'reset') {
22
- console.log(`${colors[color]}${message}${colors.reset}`);
23
- }
5
+ const colors = { green: '\x1b[32m', yellow: '\x1b[33m', cyan: '\x1b[36m', reset: '\x1b[0m', bold: '\x1b[1m' };
6
+ const log = (msg, color = 'reset') => console.log(`${colors[color]}${msg}${colors.reset}`);
24
7
 
25
8
  function getPythonCommand() {
26
- const commands = process.platform === 'win32'
27
- ? ['python', 'python3', 'py']
28
- : ['python3', 'python'];
29
-
9
+ const commands = process.platform === 'win32' ? ['python', 'python3', 'py'] : ['python3', 'python'];
30
10
  for (const cmd of commands) {
31
11
  try {
32
- const result = spawnSync(cmd, ['--version'], {
33
- encoding: 'utf8',
34
- stdio: ['pipe', 'pipe', 'pipe']
35
- });
36
- if (result.status === 0) {
37
- const version = result.stdout.trim() || result.stderr.trim();
38
- return { cmd, version };
39
- }
40
- } catch (e) {
41
- // Continue
42
- }
12
+ const result = spawnSync(cmd, ['--version'], { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] });
13
+ if (result.status === 0) return { cmd, version: (result.stdout || result.stderr).trim() };
14
+ } catch (e) {}
43
15
  }
44
16
  return null;
45
17
  }
46
18
 
47
- function checkPythonPackage(pythonCmd) {
48
- try {
49
- const result = spawnSync(
50
- pythonCmd,
51
- ['-c', 'import kubectl_mcp_tool; print(kubectl_mcp_tool.__version__ if hasattr(kubectl_mcp_tool, "__version__") else "installed")'],
52
- { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }
53
- );
54
- if (result.status === 0) {
55
- return result.stdout.trim();
56
- }
57
- return null;
58
- } catch (e) {
59
- return null;
60
- }
61
- }
62
-
63
- function checkKubectl() {
64
- try {
65
- const result = spawnSync('kubectl', ['version', '--client', '--short'], {
66
- encoding: 'utf8',
67
- stdio: ['pipe', 'pipe', 'pipe']
68
- });
69
- return result.status === 0;
70
- } catch (e) {
71
- return false;
72
- }
73
- }
74
-
75
19
  function main() {
76
20
  console.log('');
77
- log('='.repeat(60), 'cyan');
78
- log(' kubectl-mcp-server - Post-Installation Check', 'bold');
79
- log('='.repeat(60), 'cyan');
21
+ log('kubectl-mcp-server installed!', 'bold');
80
22
  console.log('');
81
23
 
82
- // Check Python
83
24
  const python = getPythonCommand();
84
- if (!python) {
85
- log('WARNING: Python 3.9+ is required but not found.', 'yellow');
86
- log('Please install Python from https://www.python.org/downloads/', 'yellow');
87
- log('The MCP server will attempt to install dependencies on first run.', 'yellow');
88
- console.log('');
89
- } else {
90
- log(`Found ${python.version}`, 'green');
91
-
92
- // Check if kubectl-mcp-tool is installed
93
- const pkgVersion = checkPythonPackage(python.cmd);
94
- if (pkgVersion) {
95
- log(`kubectl-mcp-tool Python package: v${pkgVersion}`, 'green');
96
- } else {
97
- log('kubectl-mcp-tool Python package: Not installed', 'yellow');
98
- log('It will be installed automatically on first run.', 'yellow');
99
-
100
- // Optionally install now
101
- if (process.env.KUBECTL_MCP_INSTALL_NOW === '1') {
102
- log('Installing kubectl-mcp-tool...', 'cyan');
103
- const result = spawnSync(python.cmd, ['-m', 'pip', 'install', 'kubectl-mcp-tool'], {
104
- stdio: 'inherit'
105
- });
106
- if (result.status === 0) {
107
- log('kubectl-mcp-tool installed successfully!', 'green');
108
- } else {
109
- log('Failed to install kubectl-mcp-tool. It will retry on first run.', 'yellow');
110
- }
111
- }
112
- }
113
- }
114
-
115
- // Check kubectl
116
- if (checkKubectl()) {
117
- log('kubectl CLI: Found', 'green');
25
+ if (python) {
26
+ log(`Python: ${python.version}`, 'green');
118
27
  } else {
119
- log('kubectl CLI: Not found', 'yellow');
120
- log('Please install kubectl: https://kubernetes.io/docs/tasks/tools/', 'yellow');
28
+ log('Python 3.9+ required: https://python.org', 'yellow');
121
29
  }
122
30
 
123
31
  console.log('');
124
- log('-'.repeat(60), 'cyan');
125
- log(' Quick Start', 'bold');
126
- log('-'.repeat(60), 'cyan');
127
- console.log('');
128
- log(' Run the MCP server:', 'reset');
129
- log(' npx kubectl-mcp-server', 'cyan');
32
+ log('Usage:', 'cyan');
33
+ log(' npx kubectl-mcp-server', 'reset');
34
+ log(' npx kubectl-mcp-server --transport sse --port 8000', 'reset');
130
35
  console.log('');
131
- log(' Or with options:', 'reset');
132
- log(' npx kubectl-mcp-server --transport sse --port 8000', 'cyan');
133
- console.log('');
134
- log(' Add to Claude Desktop config (claude_desktop_config.json):', 'reset');
135
- log(` {
136
- "mcpServers": {
137
- "kubernetes": {
138
- "command": "npx",
139
- "args": ["-y", "kubectl-mcp-server"]
140
- }
36
+ log('Claude Desktop config:', 'cyan');
37
+ console.log(` {
38
+ "mcpServers": {
39
+ "kubernetes": {
40
+ "command": "npx",
41
+ "args": ["-y", "kubectl-mcp-server"]
141
42
  }
142
- }`, 'cyan');
143
- console.log('');
144
- log('='.repeat(60), 'cyan');
43
+ }
44
+ }`);
145
45
  console.log('');
146
46
  }
147
47
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kubectl-mcp-server",
3
- "version": "1.6.0",
3
+ "version": "1.8.0",
4
4
  "description": "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",
5
5
  "keywords": [
6
6
  "kubernetes",