kubectl-mcp-server 1.4.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Rohit Ghumare
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,557 @@
1
+ # Kubectl MCP Server
2
+
3
+ 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.
4
+
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+ [![Python](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/)
7
+ [![Kubernetes](https://img.shields.io/badge/kubernetes-%23326ce5.svg?style=flat&logo=kubernetes&logoColor=white)](https://kubernetes.io/)
8
+ [![MCP](https://img.shields.io/badge/MCP-compatible-green.svg)](https://github.com/modelcontextprotocol/modelcontextprotocol)
9
+ [![PyPI version](https://badge.fury.io/py/kubectl-mcp-tool.svg)](https://pypi.org/project/kubectl-mcp-tool/)
10
+ [![npm version](https://badge.fury.io/js/kubectl-mcp-server.svg)](https://www.npmjs.com/package/kubectl-mcp-server)
11
+ [![Docker](https://img.shields.io/docker/pulls/rohitghumare64/kubectl-mcp-server.svg)](https://hub.docker.com/r/rohitghumare64/kubectl-mcp-server)
12
+
13
+ ## 🎥 Live Demo - Watch `kubectl-mcp-tool` in Action with Claude!
14
+ ![Claude MCP](./docs/claude/claude-mcp.gif)
15
+
16
+ ## 🎥 Live Demo - Watch `kubectl-mcp-tool` in Action with Cursor!
17
+ ![Cursor MCP](./docs/cursor/cursor-mcp.gif)
18
+
19
+ ## 🎥 Live Demo - Watch `kubectl-mcp-tool` in Action with Windsurf!
20
+ ![Windsurf MCP](./docs/windsurf/windsurf-mcp.gif)
21
+
22
+
23
+ ## Features
24
+
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:
124
+
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
127
+
128
+ ## Installation
129
+
130
+ For detailed installation instructions, please see the [Installation Guide](./docs/INSTALLATION.md).
131
+
132
+ ### npm / npx (Recommended for Node.js users)
133
+
134
+ The easiest way to run kubectl-mcp-server is via npx:
135
+
136
+ ```bash
137
+ # Run directly without installation
138
+ npx kubectl-mcp-server
139
+
140
+ # Or install globally
141
+ npm install -g kubectl-mcp-server
142
+ kubectl-mcp-server
143
+ ```
144
+
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
+ ### pip (Python)
150
+
151
+ You can install kubectl-mcp-tool directly from PyPI:
152
+
153
+ ```bash
154
+ pip install kubectl-mcp-tool
155
+ ```
156
+
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:
206
+
207
+ ```bash
208
+ # Pull the latest image
209
+ docker pull rohitghumare64/kubectl-mcp-server:latest
210
+
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
352
+
353
+ # Set default namespace for a context
354
+ set_namespace_for_context --namespace kube-system --context_name production
355
+ ```
356
+
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
+ ```
419
+
420
+ ### Claude Desktop
421
+
422
+ Add the following to your Claude Desktop configuration at `~/Library/Application\ Support/Claude/claude_desktop_config.json` (Windows: `%APPDATA%\Claude\mcp.json`):
423
+
424
+ **Using npx (Recommended):**
425
+ ```json
426
+ {
427
+ "mcpServers": {
428
+ "kubernetes": {
429
+ "command": "npx",
430
+ "args": ["-y", "kubectl-mcp-server"]
431
+ }
432
+ }
433
+ }
434
+ ```
435
+
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
+ ### Claude Code
452
+
453
+ Claude Code is Anthropic's CLI tool for coding with Claude. Add the following to `~/.config/claude-code/mcp.json`:
454
+
455
+ **Using npx (Recommended):**
456
+ ```json
457
+ {
458
+ "mcpServers": {
459
+ "kubernetes": {
460
+ "command": "npx",
461
+ "args": ["-y", "kubectl-mcp-server"]
462
+ }
463
+ }
464
+ }
465
+ ```
466
+
467
+ **Using Python directly:**
468
+ ```json
469
+ {
470
+ "mcpServers": {
471
+ "kubernetes": {
472
+ "command": "python",
473
+ "args": ["-m", "kubectl_mcp_tool.mcp_server"],
474
+ "env": {
475
+ "KUBECONFIG": "/path/to/your/.kube/config"
476
+ }
477
+ }
478
+ }
479
+ }
480
+ ```
481
+
482
+ For detailed Claude Code integration instructions, see [Claude Code Integration Guide](./docs/claude/claude_code_integration.md).
483
+
484
+ ### Cursor AI
485
+
486
+ Add the following to your Cursor AI settings under MCP by adding a new global MCP server:
487
+
488
+ **Using npx (Recommended):**
489
+ ```json
490
+ {
491
+ "mcpServers": {
492
+ "kubernetes": {
493
+ "command": "npx",
494
+ "args": ["-y", "kubectl-mcp-server"]
495
+ }
496
+ }
497
+ }
498
+ ```
499
+
500
+ **Using Python directly:**
501
+ ```json
502
+ {
503
+ "mcpServers": {
504
+ "kubernetes": {
505
+ "command": "python",
506
+ "args": ["-m", "kubectl_mcp_tool.mcp_server"],
507
+ "env": {
508
+ "KUBECONFIG": "/path/to/your/.kube/config",
509
+ "PATH": "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/homebrew/bin"
510
+ }
511
+ }
512
+ }
513
+ }
514
+ ```
515
+
516
+ Save this configuration to `~/.cursor/mcp.json` for global settings.
517
+
518
+ > **Note**: Replace `/path/to/your/.kube/config` with the actual path to your kubeconfig file. On most systems, this is `~/.kube/config`.
519
+
520
+ ### Windsurf
521
+
522
+ Add the following to your Windsurf configuration at `~/.config/windsurf/mcp.json` (Windows: `%APPDATA%\WindSurf\mcp.json`):
523
+
524
+ **Using npx (Recommended):**
525
+ ```json
526
+ {
527
+ "mcpServers": {
528
+ "kubernetes": {
529
+ "command": "npx",
530
+ "args": ["-y", "kubectl-mcp-server"]
531
+ }
532
+ }
533
+ }
534
+ ```
535
+
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
+ }
549
+ ```
550
+
551
+ ### Automatic Configuration
552
+
553
+ For automatic configuration of all supported AI assistants, run the provided installation script:
554
+
555
+ ```bash
556
+ bash install.sh
557
+ ```
package/bin/cli.js ADDED
@@ -0,0 +1,153 @@
1
+ #!/usr/bin/env node
2
+
3
+ const { spawn } = require('child_process');
4
+ const { existsSync } = require('fs');
5
+ const path = require('path');
6
+ const os = require('os');
7
+
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
+ }
20
+
21
+ function getPythonCommand() {
22
+ // Try different Python commands
23
+ const commands = process.platform === 'win32'
24
+ ? ['python', 'python3', 'py']
25
+ : ['python3', 'python'];
26
+
27
+ for (const cmd of commands) {
28
+ 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
+ }
39
+ }
40
+ return null;
41
+ }
42
+
43
+ function checkPythonPackage(pythonCmd) {
44
+ 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;
51
+ } catch (e) {
52
+ return false;
53
+ }
54
+ }
55
+
56
+ function main() {
57
+ const args = process.argv.slice(2);
58
+
59
+ // Handle help flag
60
+ if (args.includes('--help') || args.includes('-h')) {
61
+ console.log(`
62
+ kubectl-mcp-server - MCP Server for Kubernetes
63
+
64
+ Usage: kubectl-mcp-server [options]
65
+
66
+ 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
85
+ `);
86
+ process.exit(0);
87
+ }
88
+
89
+ // Handle version flag
90
+ if (args.includes('--version') || args.includes('-v')) {
91
+ const pkg = require('../package.json');
92
+ console.log(`kubectl-mcp-server v${pkg.version}`);
93
+ process.exit(0);
94
+ }
95
+
96
+ // Check for Python
97
+ const pythonCmd = getPythonCommand();
98
+ 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');
101
+ process.exit(1);
102
+ }
103
+
104
+ // Check if kubectl-mcp-tool is installed
105
+ 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');
117
+ process.exit(1);
118
+ }
119
+
120
+ log('kubectl-mcp-tool installed successfully!', 'green');
121
+ }
122
+
123
+ // Run the Python MCP server
124
+ const serverArgs = ['-m', 'kubectl_mcp_tool.mcp_server', ...args];
125
+
126
+ const server = spawn(pythonCmd, serverArgs, {
127
+ 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);
137
+ });
138
+
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
+ });
151
+ }
152
+
153
+ main();
@@ -0,0 +1,148 @@
1
+ #!/usr/bin/env node
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
+ const { spawnSync } = require('child_process');
9
+
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
+ }
24
+
25
+ function getPythonCommand() {
26
+ const commands = process.platform === 'win32'
27
+ ? ['python', 'python3', 'py']
28
+ : ['python3', 'python'];
29
+
30
+ for (const cmd of commands) {
31
+ 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
+ }
43
+ }
44
+ return null;
45
+ }
46
+
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
+ function main() {
76
+ console.log('');
77
+ log('='.repeat(60), 'cyan');
78
+ log(' kubectl-mcp-server - Post-Installation Check', 'bold');
79
+ log('='.repeat(60), 'cyan');
80
+ console.log('');
81
+
82
+ // Check Python
83
+ 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');
118
+ } else {
119
+ log('kubectl CLI: Not found', 'yellow');
120
+ log('Please install kubectl: https://kubernetes.io/docs/tasks/tools/', 'yellow');
121
+ }
122
+
123
+ 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');
130
+ 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
+ }
141
+ }
142
+ }`, 'cyan');
143
+ console.log('');
144
+ log('='.repeat(60), 'cyan');
145
+ console.log('');
146
+ }
147
+
148
+ main();
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "kubectl-mcp-server",
3
+ "version": "1.4.0",
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
+ "keywords": [
6
+ "kubernetes",
7
+ "kubectl",
8
+ "mcp",
9
+ "model-context-protocol",
10
+ "claude",
11
+ "cursor",
12
+ "ai",
13
+ "devops",
14
+ "k8s"
15
+ ],
16
+ "author": "Rohit Ghumare",
17
+ "license": "MIT",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/rohitg00/kubectl-mcp-server.git"
21
+ },
22
+ "bugs": {
23
+ "url": "https://github.com/rohitg00/kubectl-mcp-server/issues"
24
+ },
25
+ "homepage": "https://github.com/rohitg00/kubectl-mcp-server#readme",
26
+ "bin": {
27
+ "kubectl-mcp-server": "./bin/cli.js"
28
+ },
29
+ "files": [
30
+ "bin/"
31
+ ],
32
+ "engines": {
33
+ "node": ">=16.0.0"
34
+ },
35
+ "os": [
36
+ "darwin",
37
+ "linux",
38
+ "win32"
39
+ ],
40
+ "scripts": {
41
+ "postinstall": "node bin/postinstall.js"
42
+ }
43
+ }