Skip to main content
Glama
bharathmadvar123

Kubernetes MCP Server

README.md
# Kubernetes MCP Server

A comprehensive Model Context Protocol (MCP) server for secure Kubernetes operations with configurable security modes.

![alt text](image.png)


## šŸš€ Features

- **šŸ”’ Security-First**: Multiple security modes (Non-destructive, Read-only, Custom, Full access)
- **šŸ“¦ Modular Architecture**: Clean separation of concerns with dedicated modules
- **🐳 Docker Ready**: Production-ready containerized deployment
- **⚔ FastMCP Integration**: Built on FastMCP 2.11.3 framework
- **šŸŽÆ Comprehensive Coverage**: Support for all major Kubernetes and Istio resources
- **šŸ’¾ Backup Operations**: Safe backup-before-delete functionality
- **šŸ”§ Helm Support**: Complete Helm chart lifecycle management

## šŸ“‹ Prerequisites

- Python 3.12+
- Docker (for containerized deployment)
- Kubernetes cluster access
- kubectl configured
- Helm 3.x (optional, for Helm operations)

## šŸ› ļø Installation

### Option 1: Docker Deployment (Recommended)

```bash
# Build the Docker image
docker build -t kubectl-mcp-server:latest .

# Run with non-destructive security mode
docker run -d \
  --name kubectl-mcp-server \
  -p 8000:8000 \
  -v ~/.kube:/root/.kube:ro \
  -e KUBECONFIG=/root/.kube/config \
  -e ALLOW_ONLY_NON_DESTRUCTIVE_TOOLS=true \
  kubectl-mcp-server:latest
```

### Option 2: Local Development

```bash
# Install dependencies
pip install -r requirements.txt

# Run the server
python run_server.py --transport stdio
```

## šŸ” Security Modes

### 1. Non-Destructive Mode (Recommended for Production)
```bash
export ALLOW_ONLY_NON_DESTRUCTIVE_TOOLS=true
```
- āœ… **Allows**: All read operations, create, scale, backup
- āŒ **Blocks**: Delete operations, Helm uninstalls

### 2. Read-Only Mode (Monitoring/Observability)
```bash
export ALLOW_ONLY_READONLY_TOOLS=true
```
- āœ… **Allows**: Get/list operations, logs, health checks
- āŒ **Blocks**: All write operations

### 3. Custom Mode (Granular Control)
```bash
export ALLOWED_TOOLS="get_pods,get_deployments,get_services"
```
- āœ… **Allows**: Only specified tools
- āŒ **Blocks**: Everything else

### 4. Full Access Mode (Development Only)
```bash
# No environment variables set
```
- āœ… **Allows**: All operations
- āš ļø **Warning**: Use only in development environments

## šŸŽÆ Supported Resources

### Core Kubernetes Resources
- **Workloads**: Pods, Deployments, ReplicaSets, StatefulSets, DaemonSets
- **Services**: Services, Endpoints, Ingresses
- **Configuration**: ConfigMaps, Secrets
- **Storage**: PersistentVolumes, PersistentVolumeClaims, StorageClasses
- **RBAC**: Roles, ClusterRoles, RoleBindings, ClusterRoleBindings, ServiceAccounts
- **Networking**: NetworkPolicies
- **Cluster**: Namespaces, Nodes, Events

### Istio Service Mesh
- **Traffic Management**: VirtualServices, DestinationRules, Gateways
- **Security**: ServiceEntries

### Helm Operations
- **Chart Management**: Install, upgrade, uninstall
- **Release Operations**: List, status, values
- **Repository Management**: Add, list repositories

## šŸ”§ Configuration

### Environment Variables

| Variable | Description | Default | Example |
|----------|-------------|---------|---------|
| `ALLOW_ONLY_NON_DESTRUCTIVE_TOOLS` | Enable non-destructive mode | `false` | `true` |
| `ALLOW_ONLY_READONLY_TOOLS` | Enable read-only mode | `false` | `true` |
| `ALLOWED_TOOLS` | Custom tool whitelist | `""` | `"get_pods,get_services"` |
| `KUBECONFIG` | Kubernetes config path | `~/.kube/config` | `/path/to/config` |
| `TRANSPORT` | MCP transport method | `stdio` | `stdio` or `sse` |

### Windsurf Integration

Add to your Windsurf MCP configuration (`~/.codeium/windsurf/mcp_config.json`):

```json
{
  "mcpServers": {
    "kubectl-safe": {
      "command": "docker",
      "args": [
        "run", "--rm", "-i",
        "-v", "/Users/yourusername/.kube:/root/.kube:ro",
        "-e", "KUBECONFIG=/root/.kube/config",
        "-e", "ALLOW_ONLY_NON_DESTRUCTIVE_TOOLS=true",
        "-e", "TRANSPORT=stdio",
        "kubectl-mcp-server:latest",
        "python", "run_server.py", "--transport", "stdio"
      ]
    }
  }
}
```

## šŸ“š Usage Examples

### Basic Operations

```bash
# List all pods
python run_server.py --transport stdio
# Then use MCP client to call: get_pods_tool

# Get deployments in specific namespace
# MCP call: get_deployments_tool(namespace="production")

# Scale a deployment
# MCP call: scale_deployment_tool(name="myapp", replicas=3, namespace="default")
```

### Backup Operations

```bash
# Backup a resource before deletion
# MCP call: backup_resource_tool(name="myapp", resource_type="deployment", namespace="default")

# Safe delete (backup + delete)
# MCP call: backup_and_delete_resource_tool(name="myapp", resource_type="deployment")
```

### Helm Operations

```bash
# Install a Helm chart
# MCP call: install_helm_chart_tool(name="myapp", chart="nginx", namespace="default")

# List Helm releases
# MCP call: list_helm_releases_tool(namespace="default")
```

## šŸ—ļø Architecture

```
kubectl-mcp-server/
ā”œā”€ā”€ run_server.py                 # Main entry point
ā”œā”€ā”€ kubectl_mcp_tool/
│   ā”œā”€ā”€ mcp_server.py            # MCP server implementation
│   └── tools/                   # Modular tool implementations
│       ā”œā”€ā”€ kubectl_get.py       # Read operations
│       ā”œā”€ā”€ kubectl_operations.py # Utility operations
│       ā”œā”€ā”€ kubectl_delete.py    # Destructive operations
│       ā”œā”€ā”€ kubectl_backup.py    # Backup operations
│       └── helm_operations.py   # Helm chart operations
ā”œā”€ā”€ Dockerfile                   # Container configuration
└── requirements.txt            # Python dependencies
```

## šŸ”’ Security Best Practices

1. **Use Non-Destructive Mode** in production environments
2. **Mount kubeconfig read-only** in containers
3. **Regularly backup** critical resources
4. **Monitor logs** for security events
5. **Use least-privilege** RBAC policies
6. **Validate configurations** before deployment

## šŸ› Troubleshooting

### Common Issues

#### Authentication Errors
```bash
# Check kubeconfig
kubectl config current-context

# Verify cluster access
kubectl get nodes
```

#### Container Issues
```bash
# Check container logs
docker logs kubectl-mcp-server

# Verify volume mounts
docker exec -it kubectl-mcp-server ls -la /root/.kube/
```

#### MCP Connection Issues
```bash
# Test server directly
python run_server.py --transport stdio --debug

# Validate JSON configuration
cat ~/.codeium/windsurf/mcp_config.json | python3 -m json.tool
```

## šŸ“Š Monitoring

### Health Checks
- Server startup logs indicate security mode
- Failed operations are logged with details
- Resource access attempts are audited

### Metrics
- Operation success/failure rates
- Security mode violations
- Resource access patterns

## šŸ¤ Contributing

1. Fork the repository
2. Create a feature branch
3. Add tests for new functionality
4. Ensure security modes work correctly
5. Submit a pull request

## šŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

## šŸ†˜ Support

For issues and questions:
1. Check the troubleshooting section
2. Review container logs
3. Validate Kubernetes connectivity
4. Verify MCP configuration

## šŸ”„ Version History

- **v1.0.0**: Initial release with security modes and comprehensive Kubernetes support
- FastMCP 2.11.3 integration
- Docker containerization
- Windsurf integration