Content
# kubectl-mcp Server
[](https://golang.org)
[](LICENSE)
kubectl-mcp is a standalone Kubernetes operation and maintenance tool server based on Model Context Protocol (MCP), developed using Go. This tool serves as a backend service for AI operation and maintenance assistants, providing secure, controllable, and auditable Kubernetes cluster access capabilities through kubeconfig files.
## Project Introduction
kubectl-mcp aims to provide standardized Kubernetes operation interfaces for AI operation and maintenance assistants. By implementing the MCP protocol, AI assistants can securely perform various K8S operation and maintenance tasks, including resource querying, creation, updating, and deletion.
### Design Philosophy
- **Security First**: All cluster access must be based on kubeconfig files, prohibiting the use of plaintext tokens or certificates.
- **Controllable Operations**: Dangerous operations (CREATE/UPDATE/DELETE) require user confirmation to prevent accidental operations.
- **Complete Auditing**: Record detailed logs of all operations, including user, time, parameters, and results.
- **Multi-Cluster Management**: Support managing multiple Kubernetes clusters and contexts simultaneously.
- **Standard Protocol**: Implement the standard MCP protocol for seamless integration with any MCP client.
- **High-Performance Design**: Support concurrent request processing, connection pool management, and streaming data return.
### Applicable Scenarios
- Kubernetes operation backend for AI operation and maintenance assistants
- Multi-cluster Kubernetes management tool
- Kubernetes operation auditing and monitoring
- K8S interface layer for automated operation and maintenance platforms
## Core Features
### 🔒 Security
- ✅ Access clusters only through kubeconfig files
- ✅ Prohibit plaintext tokens, certificates, or direct API access
- ✅ API Token authentication protects HTTP interfaces
- ✅ Operation permissions are based on RBAC configurations in kubeconfig
- ✅ Sensitive data (such as Secrets) is automatically desensitized
### 🎯 Feature Completeness
- ✅ **Query Operations**: Pods, Deployments, Services, ConfigMaps, Secrets, etc.
- ✅ **Create Operations**: Support creating resources through parameters or YAML
- ✅ **Update Operations**: Scaling, image updates, restarts, Patch, etc.
- ✅ **Delete Operations**: Single or batch deletion of resources
- ✅ **Log Viewing**: Real-time viewing of Pod logs
- ✅ **Event Query**: View cluster and resource events
### 🌐 Multi-Cluster Support
- ✅ Support loading multiple kubeconfig files
- ✅ Support multiple context management
- ✅ Dynamically switch context
- ✅ Context isolation ensures operation security
### 📊 Auditing and Monitoring
- ✅ Complete operation audit logs
- ✅ Support JSON and text format logs
- ✅ Record user, time, parameters, results
- ✅ Performance metrics collection (Prometheus format)
### ⚡ High Performance
- ✅ Concurrent request processing
- ✅ K8S client connection pool
- ✅ Query result caching
- ✅ Large data streaming return
- ✅ Configurable concurrency limits and timeouts
## Quick Start
### Prerequisites
- **Go 1.21+**: Used to compile and run the server
- **Kubernetes Cluster**: Requires an accessible K8S cluster
- **kubeconfig File**: Valid cluster access configuration
- **kubectl** (Optional): Used to verify cluster connection
### Installation
#### Method 1: Compile from Source Code
```bash
# Clone the repository
git clone https://github.com/your-org/kubectl-mcp.git
cd kubectl-mcp
# Install dependencies
go mod download
# Compile
go build -o kubectl-mcp cmd/server/main.go
# Run
export KUBECONFIG=~/.kube/config
./kubectl-mcp --port 8080
```
#### Method 2: Use Docker
```bash
# Build the image
docker build -t kubectl-mcp:latest .
# Run the container
docker run -d \
--name kubectl-mcp \
-p 8080:8080 \
-v ~/.kube/config:/app/kubeconfig:ro \
-e KUBECONFIG=/app/kubeconfig \
-e KUBECTL_MCP_LOG_LEVEL=info \
kubectl-mcp:latest
```
#### Method 3: Use docker-compose
```bash
# Start the service
docker-compose up -d
# View logs
docker-compose logs -f
# Stop the service
docker-compose down
```
### Verify Installation
```bash
# Check health status
curl http://localhost:8080/health
# View available tool list
curl http://localhost:8080/tools
# View available contexts
curl http://localhost:8080/contexts
```
### First Tool Call
```bash
# Query Pods in the default namespace
curl -X POST http://localhost:8080/tool \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-api-token" \
-d '{
"tool": "get_pods",
"arguments": {
"namespace": "default"
},
"user": {
"id": "user123",
"name": "admin"
}
}'
```
### Reverse Query Example: Query Service and Deployment by Known NodePort Port Number
**Scenario**: You know a service is exposed on NodePort 30080 and need to find the corresponding Service and Deployment.
**Step 1: Reverse Lookup Service by NodePort**
```bash
curl -X POST http://localhost:8080/tool \
-H "Content-Type: application/json" \
-d '{
"tool": "find_service_by_nodeport",
"arguments": {
"nodePort": 30080,
"includeEndpoints": true
}
}'
```
**Response Example:**
```json
{
"success": true,
"data": {
"service": {
"name": "nginx-service",
"namespace": "production",
"type": "NodePort",
"port": 80,
"targetPort": 8080,
"nodePort": 30080,
"selector": {
"app": "nginx"
}
},
"endpoints": [
{
"podName": "nginx-deployment-7d64c8d5f9-abc12",
"podIP": "10.244.1.5",
"port": 8080
},
{
"podName": "nginx-deployment-7d64c8d5f9-def45",
"podIP": "10.244.2.10",
"port": 8080
}
]
}
}
```
**Step 2: Reverse Lookup Deployment by Service Selector**
```bash
curl -X POST http://localhost:8080/tool \
-H "Content-Type: application/json" \
-d '{
"tool": "find_workload_by_service",
"arguments": {
"serviceName": "nginx-service",
"namespace": "production",
"includeEndpoints": true
}
}'
```
**Response Example:**
```json
{
"success": true,
"data": {
"workloads": [
{
"kind": "Deployment",
"name": "nginx-deployment",
"namespace": "production",
"replicas": 2,
"readyReplicas": 2,
"image": "nginx:1.21",
"selector": {
"app": "nginx"
}
}
],
"endpoints": [
{
"podName": "nginx-deployment-7d64c8d5f9-abc12",
"podIP": "10.244.1.5",
"port": 8080
},
{
"podName": "nginx-deployment-7d64c8d5f9-def45",
"podIP": "10.244.2.10",
"port": 8080
}
]
}
}
```
**One-Step Solution: Complete Link Tracing**
Alternatively, use the `trace_by_nodeport` tool to get the complete link in one go (NodePort → Service → Workload):
```bash
curl -X POST http://localhost:8080/tool \
-H "Content-Type: application/json" \
-d '{
"tool": "trace_by_nodeport",
"arguments": {
"nodePort": 30080
}
}'
```
**Response Example:**
```json
{
"success": true,
"data": {
"nodePort": 30080,
"service": {
"name": "nginx-service",
"namespace": "production",
"type": "NodePort",
"port": 80,
"targetPort": 8080
},
"workloads": [
{
"kind": "Deployment",
"name": "nginx-deployment",
"namespace": "production",
"replicas": 2,
"readyReplicas": 2,
"image": "nginx:1.21"
}
],
"endpoints": [
{
"podName": "nginx-deployment-7d64c8d5f9-abc12",
"podIP": "10.244.1.5",
"port": 8080
},
{
"podName": "nginx-deployment-7d64c8d5f9-def45",
"podIP": "10.244.2.10",
"port": 8080
}
]
}
}
```
## API Interface
kubectl-mcp provides a RESTful HTTP API interface, supporting POST and GET methods.
### POST /tool
Executes a Kubernetes tool call.
**Request Headers:**
```
Content-Type: application/json
Authorization: Bearer <api-token>
```
**Request Body:**
```json
{
"tool": "get_pods",
"arguments": {
"namespace": "default",
"context": "prod-cluster",
"labelSelector": "app=nginx"
},
"user": {
"id": "user123",
"name": "admin",
"role": "operator"
}
}
```
**Response Example (Success):**
```json
{
"success": true,
"data": {
"pods": [
{
"name": "nginx-deployment-7d64c8d5f9-abc12",
"namespace": "default",
"status": "Running",
"ip": "10.244.1.5",
"node": "worker-node-1",
"labels": {
"app": "nginx"
},
"createdAt": "2026-02-04T10:30:00Z"
}
]
},
"error": null
}
```
**Response Example (Failure):**
```json
{
"success": false,
"data": null,
"error": {
"type": "CLIENT_ERROR",
"code": "RESOURCE_NOT_FOUND",
"message": "Namespace 'invalid-ns' not found",
"details": "The specified namespace does not exist in the cluster",
"suggestion": "Use 'get_namespaces' tool to list available namespaces"
}
}
```
### GET /tools
Get a list of all available tools and their metadata.
**Response Example:**
```json
{
"tools": [
{
"name": "get_pods",
"description": "Query the Pod list, supporting filtering by namespace, name, and label",
"category": "query",
"requiresConfirmation": false,
"inputSchema": {
"type": "object",
"properties": {
"namespace": {
"type": "string",
"description": "Namespace, defaults to default"
},
"name": {
"type": "string",
"description": "Pod name, supports fuzzy matching"
},
"labelSelector": {
"type": "string",
"description": "Label selector, e.g., app=nginx"
},
"context": {
"type": "string",
"description": "Target context, defaults to the current context"
}
}
}
},
{
"name": "delete_pod",
"description": "Delete the specified Pod",
"category": "delete",
"requiresConfirmation": true,
"inputSchema": {
"type": "object",
"required": ["namespace", "name"],
"properties": {
"namespace": {
"type": "string",
"description": "Namespace"
},
"name": {
"type": "string",
"description": "Pod name"
},
"force": {
"type": "boolean",
"description": "Whether to force deletion (grace period = 0)"
},
"context": {
"type": "string",
"description": "Target context"
}
}
}
}
]
}
```
### GET /health
Health check interface for container orchestration and monitoring.
**Response Example:**
```json
{
"status": "healthy",
"version": "1.0.0",
"uptime": "2h30m15s",
"contexts": ["prod-cluster", "dev-cluster", "test-cluster"],
"currentContext": "prod-cluster"
}
```
### GET /contexts
Get all available Kubernetes contexts.
**Response Example:**
```json
{
"contexts": [
{
"name": "prod-cluster",
"cluster": "prod-k8s-cluster",
"user": "admin",
"namespace": "default",
"current": true
},
{
"name": "dev-cluster",
"cluster": "dev-k8s-cluster",
"user": "developer",
"namespace": "development",
"current": false
}
],
"currentContext": "prod-cluster"
}
```
## Tool List
kubectl-mcp provides the following Kubernetes operation tools:
### READ
| Tool Name | Description | Confirmation Required |
|---------|------|---------|
| `get_nodes` | Query Node list | ❌ |
| `get_namespaces` | Query Namespace list | ❌ |
| `get_pods` | Query Pod list | ❌ |
| `get_deployments` | Query Deployment list | ❌ |
| `get_statefulsets` | Query StatefulSet list | ❌ |
| `get_daemonsets` | Query DaemonSet list | ❌ |
| `get_services` | Query Service list | ❌ |
| `get_configmaps` | Query ConfigMap list | ❌ |
| `get_secrets` | Query Secret list (auto-masked) | ❌ |
| `describe_resource` | View resource details | ❌ |
| `get_pod_logs` | View Pod logs | ❌ |
| `get_events` | View cluster events | ❌ |
### CREATE
| Tool Name | Description | Confirmation Required |
|---------|------|---------|
| `create_namespace` | Create Namespace | ✅ |
| `create_pod` | Create Pod | ✅ |
| `create_deployment` | Create Deployment | ✅ |
| `create_service` | Create Service | ✅ |
| `create_configmap` | Create ConfigMap | ✅ |
| `create_secret` | Create Secret | ✅ |
| `create_from_yaml` | Create resources from YAML | ✅ |
### UPDATE
| Tool Name | Description | Confirmation Required |
|---------|------|---------|
| `scale_deployment` | Scale Deployment | ✅ |
| `scale_statefulset` | Scale StatefulSet | ✅ |
| `update_deployment_image` | Update Deployment image | ✅ |
| `restart_deployment` | Restart Deployment | ✅ |
| `apply_yaml` | Update resources from YAML | ✅ |
| `patch_resource` | Patch Resource | ✅ |
### DELETE
| Tool Name | Description | Confirmation Required |
|---------|------|---------|
| `delete_pod` | Delete Pod | ✅ |
| `delete_deployment` | Delete Deployment | ✅ |
| `delete_service` | Delete Service | ✅ |
| `delete_configmap` | Delete ConfigMap | ✅ |
| `delete_secret` | Delete Secret | ✅ |
| `delete_namespace` | Delete Namespace (high risk) | ✅ |
| `delete_resources` | Batch delete resources | ✅ |
### Context Management Tools
| Tool Name | Description | Confirmation Required |
|---------|------|---------|
| `list_contexts` | List all contexts | ❌ |
| `switch_context` | Switch current context | ✅ |
| `get_current_context` | Get current context | ❌ |
## Configuration Instructions
kubectl-mcp supports multiple configuration methods, with priority from high to low: **Command Line Parameters > Environment Variables > Configuration File**
### Configuration File
Create a `config.yaml` file:
```yaml
# HTTP Server Configuration
host: "0.0.0.0"
port: 8080
# Kubeconfig Configuration
kubeconfigPath: "~/.kube/config"
defaultContext: "prod-cluster"
# Logging Configuration
logLevel: "info" # debug, info, warn, error
logFormat: "json" # json, text
logFile: "/var/log/kubectl-mcp/app.log"
# Performance Configuration
maxConcurrentRequests: 100
requestTimeout: "30s"
# Security Configuration
apiToken: "your-secure-api-token"
allowedOrigins:
- "*"
# Cache Configuration
enableCache: true
cacheTTL: "5m"
```
### Environment Variables
All configuration items can be overridden by environment variables, using the `KUBECTL_MCP_` prefix:
```bash
# HTTP Server
export KUBECTL_MCP_HOST="0.0.0.0"
export KUBECTL_MCP_PORT="8080"
# Kubeconfig
export KUBECONFIG="~/.kube/config"
export KUBECTL_MCP_DEFAULT_CONTEXT="prod-cluster"
# Logging
export KUBECTL_MCP_LOG_LEVEL="info"
export KUBECTL_MCP_LOG_FORMAT="json"
export KUBECTL_MCP_LOG_FILE="/var/log/kubectl-mcp/app.log"
# Security
export KUBECTL_MCP_API_TOKEN="your-secure-api-token"
```
### Command Line Parameters
```bash
kubectl-mcp \
--host 0.0.0.0 \
--port 8080 \
--kubeconfig ~/.kube/config \
--default-context prod-cluster \
--log-level info \
--log-format json \
--api-token your-secure-api-token
```
### Configuration Item Description
#### HTTP Server Configuration
| Configuration Item | Environment Variable | Default Value | Description |
|-------|---------|-------|------|
| `host` | `KUBECTL_MCP_HOST` | `0.0.0.0` | Listening address |
| `port` | `KUBECTL_MCP_PORT` | `8080` | Listening port |
#### Kubeconfig Configuration
| Configuration Item | Environment Variable | Default Value | Description |
|-------|---------|-------|------|
| `kubeconfigPath` | `KUBECONFIG` | `~/.kube/config` | kubeconfig file path |
| `defaultContext` | `KUBECTL_MCP_DEFAULT_CONTEXT` | - | Default context to use |
#### Logging Configuration
| Configuration Item | Environment Variable | Default Value | Description |
|-------|---------|-------|------|
| `logLevel` | `KUBECTL_MCP_LOG_LEVEL` | `info` | Log level: debug/info/warn/error |
| `logFormat` | `KUBECTL_MCP_LOG_FORMAT` | `json` | Log format: json/text |
| `logFile` | `KUBECTL_MCP_LOG_FILE` | - | Log file path, if empty, output to stdout |
#### Performance Configuration
| Configuration Item | Environment Variable | Default Value | Description |
|-------|---------|-------|------|
| `maxConcurrentRequests` | `KUBECTL_MCP_MAX_CONCURRENT` | `100` | Maximum concurrent requests |
| `requestTimeout` | `KUBECTL_MCP_REQUEST_TIMEOUT` | `30s` | Timeout for a single request |
#### Security Configuration
| Configuration Item | Environment Variable | Default Value | Description |
|-------|---------|-------|------|
| `apiToken` | `KUBECTL_MCP_API_TOKEN` | - | API access Token (strongly recommended) |
| `allowedOrigins` | `KUBECTL_MCP_ALLOWED_ORIGINS` | `*` | CORS allowed origins |
#### Cache Configuration
| Configuration Item | Environment Variable | Default Value | Description |
|-------|---------|-------|------|
| `enableCache` | `KUBECTL_MCP_ENABLE_CACHE` | `true` | Whether to enable query caching |
| `cacheTTL` | `KUBECTL_MCP_CACHE_TTL` | `5m` | Cache expiration time |
### Docker Deployment Configuration
When using Docker, it is recommended to configure through environment variables and Volume mounts:
```bash
docker run -d \
--name kubectl-mcp \
-p 8080:8080 \
-v ~/.kube/config:/app/kubeconfig:ro \
-v /var/log/kubectl-mcp:/var/log/kubectl-mcp \
-e KUBECONFIG=/app/kubeconfig \
-e KUBECTL_MCP_LOG_LEVEL=info \
-e KUBECTL_MCP_LOG_FILE=/var/log/kubectl-mcp/app.log \
-e KUBECTL_MCP_API_TOKEN=your-secure-token \
kubectl-mcp:latest
```
### docker-compose Configuration
`docker-compose.yml` example:
```yaml
version: '3.8'
services:
kubectl-mcp:
build: .
container_name: kubectl-mcp
ports:
- "8080:8080"
volumes:
- ~/.kube/config:/app/kubeconfig:ro
- ./logs:/var/log/kubectl-mcp
- ./config.yaml:/app/config.yaml:ro
environment:
- KUBECONFIG=/app/kubeconfig
- KUBECTL_MCP_LOG_LEVEL=info
- KUBECTL_MCP_API_TOKEN=${API_TOKEN}
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
interval: 30s
timeout: 10s
retries: 3
```
## Development Guide
### Project Structure
```
kubectl-mcp/
├── cmd/
│ └── server/
│ └── main.go # Server entry point, initialization and startup logic
├── internal/ # Internal packages, not exposed externally
│ ├── config/
│ │ └── config.go # Configuration management, supports file/environment variables/command line
│ ├── server/
│ │ ├── http.go # HTTP server implementation (Gin)
│ │ └── handler.go # HTTP request handler
│ ├── mcp/
│ │ ├── protocol.go # MCP protocol processing logic
│ │ └── types.go # MCP data type definitions
│ ├── tools/
│ │ ├── registry.go # Tool registry and routing
│ │ ├── query.go # Query tool implementation (READ)
│ │ ├── create.go # Create tool implementation (CREATE)
│ │ ├── update.go # Update tool implementation (UPDATE)
│ │ └── delete.go # Delete tool implementation (DELETE)
│ ├── k8s/
│ │ ├── client.go # K8S client manager
│ │ ├── context.go # Context management and switching
│ │ └── types.go # K8S resource data types
│ └── audit/
│ ├── logger.go # Audit logging system
│ └── metrics.go # Performance metrics collection
├── pkg/ # Public packages, can be used externally
│ └── utils/
│ └── errors.go # Error handling tools
├── test/ # Test files
│ ├── *_test.go # Unit tests
│ ├── integration/ # Integration tests
│ └── property/ # Property tests
├── docs/ # Documentation
│ ├── api.md # Detailed API documentation
│ └── deployment.md # Deployment guide
├── config.yaml.example # Configuration file example
├── Dockerfile # Docker image build
├── docker-compose.yml # Docker Compose configuration
├── go.mod # Go module definition
├── go.sum # Go dependency verification
└── README.md # Project documentation
```
### Technology Stack
- **Language**: Go 1.21+
- **HTTP Framework**: [Gin](https://github.com/gin-gonic/gin) - High-performance HTTP Web framework
- **K8S Client**: [client-go](https://github.com/kubernetes/client-go) v0.28+ - Kubernetes official Go client
- **Logging Library**: [zap](https://github.com/uber-go/zap) - High-performance structured logging library
- **Configuration Management**: [viper](https://github.com/spf13/viper) - Configuration solution
- **Testing Framework**:
- `testing` - Go standard testing library
- [testify](https://github.com/stretchr/testify) - Testing assertion library
- [gopter](https://github.com/leanovate/gopter) - Property testing library
### Development Environment Setup
1. **Install Go 1.21+**
```bash
# Download and install Go
# https://golang.org/dl/
# Verify installation
go version
```
2. **Clone the Project**
```bash
git clone https://github.com/your-org/kubectl-mcp.git
cd kubectl-mcp
```
3. **Install Dependencies**
```bash
go mod download
```
4. **Configure kubeconfig**
```bash
# Ensure a kubeconfig is available
export KUBECONFIG=~/.kube/config
# Verify cluster connection
kubectl cluster-info
```
5. **Run the Development Server**
```bash
# Run directly
go run cmd/server/main.go --port 8080
# Or compile and run
go build -o kubectl-mcp cmd/server/main.go
./kubectl-mcp --port 8080
```
### Running Tests
```bash
# Run all tests
go test ./...
# Run unit tests
go test ./internal/...
# Run tests for a specific package
go test ./internal/k8s/...
# Run tests and display coverage
go test -cover ./...
# Generate coverage report
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out
# Run integration tests (requires a real K8S cluster)
go test ./test/integration/...
# Run property tests
go test ./test/*_property_test.go -v
# Display detailed output when running tests
go test -v ./...
```
### Code Style
The project follows Go's official code style and best practices:
1. **Format Code**
```bash
# Format using gofmt
gofmt -w .
# Use goimports (recommended)
go install golang.org/x/tools/cmd/goimports@latest
goimports -w .
```
2. **Code Check**
```bash
# Check using go vet
go vet ./...
# Use golangci-lint (recommended)
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
golangci-lint run
```
3. **Naming Conventions**
- Package names: lowercase, short, meaningful
- Exported functions/types: Capitalized (PascalCase)
- Private functions/variables: lowercase (camelCase)
- Constants: uppercase or PascalCase
4. **Comment Conventions**
- Exported functions, types, and constants must have comments
- Comments start with the name, e.g., `// GetPods queries pods from Kubernetes cluster`
### Adding New Tools
To add a new Kubernetes operation tool, follow these steps:
1. **Implement the tool function in `internal/tools/`**
```go
// internal/tools/query.go
// GetReplicaSets queries a list of ReplicaSets
func GetReplicaSets(ctx context.Context, args map[string]interface{}, k8sClient *K8SClientManager) (interface{}, error) {
// Parse arguments
namespace := getStringArg(args, "namespace", "default")
// Get client
clientset, err := k8sClient.GetClient()
if err != nil {
return nil, err
}
// Call K8S API
rsList, err := clientset.AppsV1().ReplicaSets(namespace).List(ctx, metav1.ListOptions{})
if err != nil {
return nil, err
}
// Format the return result
return formatReplicaSets(rsList), nil
}
```
2. **Register the tool in `internal/tools/registry.go`**
```go
// RegisterTools registers all tools
func RegisterTools(registry *ToolRegistry) {
// ... Other tool registrations
// Register the new tool
registry.RegisterTool(&Tool{
Name: "get_replicasets",
Description: "Queries a list of ReplicaSets, supports filtering by namespace",
Category: "query",
RequiresConfirmation: false,
InputSchema: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"namespace": map[string]interface{}{
"type": "string",
"description": "Namespace, defaults to default",
},
},
},
Handler: GetReplicaSets,
})
}
```
3. **Write unit tests**
```go
// test/query_tools_test.go
func TestGetReplicaSets(t *testing.T) {
// Create fake clientset
clientset := fake.NewSimpleClientset()
// Create test data
rs := &appsv1.ReplicaSet{
ObjectMeta: metav1.ObjectMeta{
Name: "test-rs",
Namespace: "default",
},
}
clientset.AppsV1().ReplicaSets("default").Create(context.TODO(), rs, metav1.CreateOptions{})
// Test tool call
result, err := GetReplicaSets(context.TODO(), map[string]interface{}{
"namespace": "default",
}, mockK8SManager)
assert.NoError(t, err)
assert.NotNil(t, result)
}
```
### Debugging Tips
1. **Enable Debug Logging**
```bash
export KUBECTL_MCP_LOG_LEVEL=debug
./kubectl-mcp
```
2. **Use the Delve Debugger**
```bash
# Install Delve
go install github.com/go-delve/delve/cmd/dlv@latest
# Start debugging
dlv debug cmd/server/main.go -- --port 8080
```
3. **View Audit Logs**
```bash
# View logs in real-time
tail -f /var/log/kubectl-mcp/app.log
# Format JSON logs using jq
tail -f /var/log/kubectl-mcp/app.log | jq .
```
### Performance Optimization Suggestions
1. **Enable Caching**: Enable caching for frequently queried data
2. **Connection Pool Management**: Properly configure the K8S client connection pool size
3. **Concurrency Control**: Adjust `maxConcurrentRequests` based on cluster size
4. **Timeout Settings**: Adjust `requestTimeout` based on network conditions
5. **Log Level**: Use `info` or `warn` level in production environments
### Contribution Guide
Contributions are welcome! Please follow these steps:
1. Fork this repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Create a Pull Request
**Pull Request Requirements:**
- Code passes all tests
- Code conforms to Go standards (passes `gofmt` and `golangci-lint`)
- Add necessary unit tests
- Update relevant documentation
- Provide a clear PR description
### Common Issues
**Q: How to handle multiple kubeconfig files?**
A: You can use the `KUBECONFIG` environment variable to specify multiple files, separated by colons:
```bash
export KUBECONFIG=~/.kube/config1:~/.kube/config2
```
**Q: How to restrict access to tools?**
A: kubectl-mcp's permissions are entirely based on the RBAC configuration in the kubeconfig. You can restrict permissions by configuring K8S Roles and RoleBindings.
**Q: How to monitor server performance?**
A: The server provides a Prometheus-formatted performance metrics interface (planned), which can be integrated into a monitoring system.
**Q: Which Kubernetes versions are supported?**
A: Kubernetes 1.20+ versions are supported, and 1.24+ versions are recommended.
## Integration with admin-mit-backend
kubectl-mcp can be integrated with admin-mit-backend as an independent MCP Server. For detailed integration instructions, please refer to [docs/deployment.md](docs/deployment.md)
## Troubleshooting
### Common Errors and Solutions
#### 1. Kubeconfig Load Failed
**Error Message:**
```json
{
"error": {
"code": "KUBECONFIG_NOT_FOUND",
"message": "Failed to load kubeconfig"
}
}
```
**Solution:**
- Check if the `KUBECONFIG` environment variable is set correctly
- Confirm that the kubeconfig file exists and has read permissions
- Verify that the kubeconfig file format is correct: `kubectl config view`
#### 2. Cluster Connection Failed
**Error Message:**
```json
{
"error": {
"code": "CLUSTER_UNREACHABLE",
"message": "Unable to connect to the cluster"
}
}
```
**Solution:**
- Check network connectivity: `ping <cluster-api-server>`
- Verify cluster accessibility: `kubectl cluster-info`
- Check firewall and network policies
- Confirm that the certificates in the kubeconfig have not expired
#### 3. Insufficient Permissions
**Error Message:**
```json
{
"error": {
"code": "PERMISSION_DENIED",
"message": "User does not have permission to list pods"
}
}
```
**Solution:**
- Check the user's RBAC permissions in the kubeconfig
- Use `kubectl auth can-i` to verify permissions:
```bash
kubectl auth can-i list pods --namespace default
```
- Contact the cluster administrator to grant the necessary permissions
#### 4. Context Does Not Exist
**Error Message:**
```json
{
"error": {
"code": "CONTEXT_NOT_FOUND",
"message": "Context 'invalid-context' not found"
}
}
```
**Solution:**
- List all available contexts: `kubectl config get-contexts`
- Use the GET `/contexts` interface to view the contexts recognized by the server
- Confirm that the context name is spelled correctly
#### 5. API Token Authentication Failed
**Error Message:**
```json
{
"error": {
"code": "UNAUTHORIZED",
"message": "Invalid or missing API token"
}
}
```
**Solution:**
- Confirm that the request header contains the correct Authorization: `Bearer <token>`
- Check if the `apiToken` configured on the server matches the request
- Confirm that the token has not expired (if using a time-limited token)
### Log Analysis
**View Detailed Logs:**
```bash
# Set debug level
export KUBECTL_MCP_LOG_LEVEL=debug
# View real-time logs
tail -f /var/log/kubectl-mcp/app.log | jq .
```
**Key Log Fields:**
- `timestamp`: Operation time
- `level`: Log level (debug/info/warn/error)
- `tool`: Name of the tool called
- `user`: User information for the operation
- `context`: K8S context used
- `duration`: Operation duration
- `error`: Error message (if any)
## Performance Tuning
### Concurrency Configuration
Adjust concurrency parameters based on cluster size and server resources:
```yaml
# Small cluster (< 100 nodes)
maxConcurrentRequests: 50
requestTimeout: "30s"
# Medium cluster (100-500 nodes)
maxConcurrentRequests: 100
requestTimeout: "60s"
# Large cluster (> 500 nodes)
maxConcurrentRequests: 200
requestTimeout: "120s"
```
### Cache Optimization
```yaml
# Enable caching to reduce API calls
enableCache: true
# Adjust TTL based on data change frequency
cacheTTL: "5m" # Frequently changing data (e.g., Pod status)
cacheTTL: "30m" # Relatively stable data (e.g., ConfigMap)
```
### Resource Limits
**Resource limits for Docker deployment:**
```yaml
# docker-compose.yml
services:
kubectl-mcp:
# ...
deploy:
resources:
limits:
cpus: '2'
memory: 2G
reservations:
cpus: '1'
memory: 1G
```
### Monitoring Metrics
kubectl-mcp provides the following performance metrics (Prometheus format):
- `kubectl_mcp_requests_total`: Total number of requests
- `kubectl_mcp_requests_duration_seconds`: Request duration
- `kubectl_mcp_errors_total`: Total number of errors
- `kubectl_mcp_concurrent_requests`: Current number of concurrent requests
- `kubectl_mcp_k8s_api_calls_total`: Number of K8S API calls
## Security Best Practices
### 1. Kubeconfig Security
- ✅ Use read-only mount for kubeconfig: `-v ~/.kube/config:/app/kubeconfig:ro`
- ✅ Restrict kubeconfig file permissions: `chmod 600 ~/.kube/config`
- ✅ Regularly rotate credentials in kubeconfig
- ✅ Configure RBAC using the principle of least privilege
### 2. API Token Protection
- ✅ Use a strong random token: `openssl rand -hex 32`
- ✅ Pass the token through environment variables, avoid hardcoding
- ✅ Regularly rotate API tokens
- ✅ API token authentication must be enabled in production environments
### 3. Network Security
- ✅ Use HTTPS (through a reverse proxy such as Nginx)
- ✅ Configure CORS to restrict allowed origins
- ✅ Use a firewall to restrict access source IPs
- ✅ Enable request rate limiting
### 4. Container Security
- ✅ Run containers as a non-root user
- ✅ Use a minimal base image
- ✅ Regularly update dependencies and images
- ✅ Scan image vulnerabilities
### 5. Auditing and Monitoring
- ✅ Enable full operation audit logs
- ✅ Regularly review audit logs
- ✅ Configure alert rules to monitor abnormal operations
- ✅ Integrate into a SIEM system
## Production Deployment Recommendations
### High Availability Deployment
```yaml
# docker-compose.yml - Multi-instance deployment
version: '3.8'
services:
kubectl-mcp-1:
image: kubectl-mcp:latest
# ... Configuration
kubectl-mcp-2:
image: kubectl-mcp:latest
# ... Configuration
kubectl-mcp-3:
image: kubectl-mcp:latest
# ... Configuration
nginx:
image: nginx:alpine
ports:
- "8080:80"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
depends_on:
- kubectl-mcp-1
- kubectl-mcp-2
- kubectl-mcp-3
```
### Using Nginx Reverse Proxy
```nginx
# nginx.conf
upstream kubectl_mcp_backend {
least_conn;
server kubectl-mcp-1:8080;
server kubectl-mcp-2:8080;
server kubectl-mcp-3:8080;
}
server {
listen 80;
server_name kubectl-mcp.example.com;
# HTTPS redirect
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name kubectl-mcp.example.com;
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
location / {
proxy_pass http://kubectl_mcp_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# Timeout settings
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
# Health check
location /health {
proxy_pass http://kubectl_mcp_backend/health;
access_log off;
}
}
```
### Kubernetes Deployment
```yaml
# kubectl-mcp-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: kubectl-mcp
namespace: ops-tools
spec:
replicas: 3
selector:
matchLabels:
app: kubectl-mcp
template:
metadata:
labels:
app: kubectl-mcp
spec:
serviceAccountName: kubectl-mcp
containers:
- name: kubectl-mcp
image: kubectl-mcp:latest
ports:
- containerPort: 8080
env:
- name: KUBECTL_MCP_LOG_LEVEL
value: "info"
- name: KUBECTL_MCP_API_TOKEN
valueFrom:
secretKeyRef:
name: kubectl-mcp-secret
key: api-token
volumeMounts:
- name: kubeconfig
mountPath: /app/kubeconfig
readOnly: true
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 10
periodSeconds: 30
readinessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 5
periodSeconds: 10
resources:
requests:
cpu: 500m
memory: 512Mi
limits:
cpu: 2000m
memory: 2Gi
volumes:
- name: kubeconfig
secret:
secretName: kubectl-mcp-kubeconfig
---
apiVersion: v1
kind: Service
metadata:
name: kubectl-mcp
namespace: ops-tools
spec:
selector:
app: kubectl-mcp
ports:
- port: 8080
targetPort: 8080
type: ClusterIP
```
## Changelog
### v1.0.0 (2026-02-04)
**New Features:**
- ✅ Complete Kubernetes CRUD operation support
- ✅ Multi-cluster and multi-context management
- ✅ kubeconfig-based security authentication
- ✅ Complete operation audit logs
- ✅ HTTP RESTful API interface
- ✅ Docker and docker-compose deployment support
- ✅ Concurrent request processing and connection pool management
- ✅ Query result caching mechanism
- ✅ Detailed error handling and suggestions
**Known Limitations:**
- WebSocket real-time push is not supported yet
- Custom Resource Definition (CRD) operations are not supported yet
- Helm Chart management is not supported yet
## Roadmap
### v1.1.0 (Planned)
- [ ] WebSocket support for real-time resource change push
- [ ] Custom Resource Definition (CRD) operation support
- [ ] Prometheus metrics export
- [ ] More granular permission control
- [ ] Operation rollback function
### v1.2.0 (Planned)
- [ ] Helm Chart management tool
- [ ] Resource template management
- [ ] Batch operation optimization
- [ ] GraphQL API support
### v2.0.0 (Future)
- [ ] Multi-tenancy support
- [ ] Resource quota management
- [ ] Cost analysis and optimization suggestions
- [ ] AI-driven fault diagnosis
## Related Resources
- **Official Documentation**: [docs/](docs/)
- **API Documentation**: [docs/api.md](docs/api.md)
- **Deployment Guide**: [docs/deployment.md](docs/deployment.md)
- **Kubernetes Official Documentation**: https://kubernetes.io/docs/
- **client-go Documentation**: https://github.com/kubernetes/client-go
- **MCP Protocol Specification**: https://modelcontextprotocol.io/
## Community & Support
- **Issue Feedback**: [GitHub Issues](https://github.com/wangyufeng1995/kubectl-mcp/issues)
- **Feature Suggestions**: [GitHub Discussions](https://github.com/wangyufeng1995/kubectl-mcp/discussions)
- **Security Vulnerabilities**: Please send an email to wangyufeng@yunlizhihui.com
## Acknowledgments
Thanks to the following open-source projects:
- [Kubernetes](https://kubernetes.io/) - Container orchestration platform
- [client-go](https://github.com/kubernetes/client-go) - Kubernetes Go client
- [Gin](https://github.com/gin-gonic/gin) - HTTP Web framework
- [Zap](https://github.com/uber-go/zap) - High-performance logging library
- [Viper](https://github.com/spf13/viper) - Configuration management library
## License
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
## Contributors
Thanks to all the developers who have contributed to this project!
---
**Made with ❤️ by the kubectl-mcp team**
MCP Config
Below is the configuration for this MCP Server. You can copy it directly to Cursor or other MCP clients.
mcp.json
Connection Info
You Might Also Like
everything-claude-code
Complete Claude Code configuration collection - agents, skills, hooks,...
markitdown
MarkItDown-MCP is a lightweight server for converting URIs to Markdown.
servers
Model Context Protocol Servers
servers
Model Context Protocol Servers
Time
A Model Context Protocol server for time and timezone conversions.
Filesystem
Node.js MCP Server for filesystem operations with dynamic access control.