Build Your Own Kubernetes MCP Server in Under an Hour
The MCP ecosystem is growing rapidly, but there are still gaps — tools specific to your organisation’s internal systems, custom Kubernetes operators, proprietary APIs, or combinations of multiple sources that no community server handles well. When you hit one of those gaps, the answer is straightforward: build your own MCP server. With the official Python SDK, a working server with multiple tools takes under an hour.
This tutorial builds a complete, production-quality Kubernetes MCP server from scratch: designing the tool surface, implementing each tool with the Python SDK, handling authentication, adding proper error handling and logging, testing locally with Claude Desktop, and deploying it as a containerised service that your team can share. Every code block in this guide is production-tested and ready to adapt.
By the end of this tutorial you will have: a working MCP server that exposes 8 Kubernetes tools, a Claude Desktop configuration that connects to it, a Docker container for team sharing, and the mental model to extend it with your own custom tools.
PREREQUISITES
Python 3.10+, pip, kubectl configured with cluster access, Claude Desktop installed. Estimated time: 45–60 minutes for the complete server; 15 minutes for the minimal working version.
Step 1: Project Setup (5 minutes)
# Create project directory
mkdir k8s-mcp-server && cd k8s-mcp-server
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # Windows: .venvScriptsactivate
# Install dependencies
pip install mcp kubernetes python-dotenv
# Project structure
.
├── server.py # Main MCP server
├── tools/
│ ├── pods.py # Pod-related tools
│ ├── deployments.py # Deployment tools
│ ├── nodes.py # Node tools
│ └── events.py # Event tools
├── .env # Local credentials (never committed)
├── Dockerfile
└── requirements.txt
# Create project directory
mkdir k8s-mcp-server && cd k8s-mcp-server
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # Windows: .venvScriptsactivate
# Install dependencies
pip install mcp kubernetes python-dotenv
# Project structure
.
├── server.py # Main MCP server
├── tools/
│ ├── pods.py # Pod-related tools
│ ├── deployments.py # Deployment tools
│ ├── nodes.py # Node tools
│ └── events.py # Event tools
├── .env # Local credentials (never committed)
├── Dockerfile
└── requirements.txt
Step 2: The Server Foundation (10 minutes)
The MCP server is the central orchestrator: it initialises the Kubernetes client, registers all tools, and handles the MCP protocol communication. The server.py file is the entry point.
# server.py
import asyncio
import logging
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp import types
from kubernetes import client, config
from kubernetes.client.rest import ApiException
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(name)s] %(levelname)s: %(message)s'
)
log = logging.getLogger('k8s-mcp')
# Initialise MCP server
server = Server('kubernetes-mcp')
# Initialise Kubernetes client
def init_k8s():
try:
config.load_kube_config() # Uses ~/.kube/config
log.info('Loaded kubeconfig from ~/.kube/config')
except config.ConfigException:
config.load_incluster_config() # Fallback: running inside a pod
log.info('Loaded in-cluster Kubernetes config')
init_k8s()
# Register tool modules (imported below)
from tools.pods import register_pod_tools
from tools.deployments import register_deployment_tools
from tools.nodes import register_node_tools
from tools.events import register_event_tools
register_pod_tools(server)
register_deployment_tools(server)
register_node_tools(server)
register_event_tools(server)
async def main():
async with stdio_server() as (read_stream, write_stream):
log.info('Kubernetes MCP server starting...')
await server.run(read_stream, write_stream,
server.create_initialization_options())
if __name__ == '__main__':
asyncio.run(main())
# server.py
import asyncio
import logging
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp import types
from kubernetes import client, config
from kubernetes.client.rest import ApiException
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(name)s] %(levelname)s: %(message)s'
)
log = logging.getLogger('k8s-mcp')
# Initialise MCP server
server = Server('kubernetes-mcp')
# Initialise Kubernetes client
def init_k8s():
try:
config.load_kube_config() # Uses ~/.kube/config
log.info('Loaded kubeconfig from ~/.kube/config')
except config.ConfigException:
config.load_incluster_config() # Fallback: running inside a pod
log.info('Loaded in-cluster Kubernetes config')
init_k8s()
# Register tool modules (imported below)
from tools.pods import register_pod_tools
from tools.deployments import register_deployment_tools
from tools.nodes import register_node_tools
from tools.events import register_event_tools
register_pod_tools(server)
register_deployment_tools(server)
register_node_tools(server)
register_event_tools(server)
async def main():
async with stdio_server() as (read_stream, write_stream):
log.info('Kubernetes MCP server starting...')
await server.run(read_stream, write_stream,
server.create_initialization_options())
if __name__ == '__main__':
asyncio.run(main())
Step 3: Implementing the Pod Tools (15 minutes)
The pod tools module implements the four most-used Kubernetes operations: listing pods, getting logs, describing a pod, and executing a command. Each tool is decorated with @server.call_tool and includes a matching @server.list_tools registration.
list[types.Tool]:
return [
types.Tool(
name='list_pods',
description='List pods in a Kubernetes namespace with their status, restarts, and age. '
'Use this to get an overview of what is running or to find failing pods.',
inputSchema={
'type': 'object',
'properties': {
'namespace': {'type': 'string', 'description': 'Namespace to list pods from. Use "all" for all namespaces. Default: default'},
'label_selector': {'type': 'string', 'description': 'Optional: filter by label e.g. "app=payments"'},
'field_selector': {'type': 'string', 'description': 'Optional: filter by field e.g. "status.phase=Failed"'},
},
'required': [],
}
),
types.Tool(
name='get_pod_logs',
description='Retrieve logs from a specific pod container. Use this to diagnose errors or understand pod behaviour.',
inputSchema={
'type': 'object',
'properties': {
'pod_name': {'type': 'string', 'description': 'Name of the pod'},
'namespace': {'type': 'string', 'description': 'Namespace of the pod', 'default': 'default'},
'container': {'type': 'string', 'description': 'Container name (optional if pod has one container)'},
'tail_lines': {'type': 'integer', 'description': 'Number of recent log lines to return', 'default': 100},
'previous': {'type': 'boolean', 'description': 'Return logs from previous (crashed) container instance', 'default': False},
},
'required': ['pod_name'],
}
),
]
@server.call_tool()
async def call_pod_tool(name: str, arguments: dict) -> list[types.TextContent]:
v1 = client.CoreV1Api()
if name == 'list_pods':
namespace = arguments.get('namespace', 'default')
label_sel = arguments.get('label_selector', None)
field_sel = arguments.get('field_selector', None)
try:
if namespace == 'all':
pods = v1.list_pod_for_all_namespaces(
label_selector=label_sel, field_selector=field_sel)
else:
pods = v1.list_namespaced_pod(
namespace, label_selector=label_sel, field_selector=field_sel)
result = []
for pod in pods.items:
containers = pod.spec.containers
restarts = sum(
cs.restart_count for cs in (pod.status.container_statuses or []))
result.append({
'name': pod.metadata.name,
'namespace': pod.metadata.namespace,
'phase': pod.status.phase,
'restarts': restarts,
'node': pod.spec.node_name,
'containers': [c.name for c in containers],
'age': str(pod.metadata.creation_timestamp),
})
return [types.TextContent(type='text',
text=f'Found {len(result)} pods:n' + json.dumps(result, indent=2, default=str))]
except ApiException as e:
return [types.TextContent(type='text', text=f'Kubernetes API error: {e.reason} ({e.status})')]
elif name == 'get_pod_logs':
try:
logs = v1.read_namespaced_pod_log(
name=arguments['pod_name'],
namespace=arguments.get('namespace', 'default'),
container=arguments.get('container'),
tail_lines=arguments.get('tail_lines', 100),
previous=arguments.get('previous', False),
)
return [types.TextContent(type='text', text=logs or '(no logs found)')]
except ApiException as e:
return [types.TextContent(type='text', text=f'Error fetching logs: {e.reason}')]” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
# tools/pods.py
from mcp.server import Server
from mcp import types
from kubernetes import client
from kubernetes.client.rest import ApiException
import json, logging
log = logging.getLogger('k8s-mcp.pods')
def register_pod_tools(server: Server):
@server.list_tools()
async def list_pod_tools() -> list[types.Tool]:
return [
types.Tool(
name='list_pods',
description='List pods in a Kubernetes namespace with their status, restarts, and age. '
'Use this to get an overview of what is running or to find failing pods.',
inputSchema={
'type': 'object',
'properties': {
'namespace': {'type': 'string', 'description': 'Namespace to list pods from. Use "all" for all namespaces. Default: default'},
'label_selector': {'type': 'string', 'description': 'Optional: filter by label e.g. "app=payments"'},
'field_selector': {'type': 'string', 'description': 'Optional: filter by field e.g. "status.phase=Failed"'},
},
'required': [],
}
),
types.Tool(
name='get_pod_logs',
description='Retrieve logs from a specific pod container. Use this to diagnose errors or understand pod behaviour.',
inputSchema={
'type': 'object',
'properties': {
'pod_name': {'type': 'string', 'description': 'Name of the pod'},
'namespace': {'type': 'string', 'description': 'Namespace of the pod', 'default': 'default'},
'container': {'type': 'string', 'description': 'Container name (optional if pod has one container)'},
'tail_lines': {'type': 'integer', 'description': 'Number of recent log lines to return', 'default': 100},
'previous': {'type': 'boolean', 'description': 'Return logs from previous (crashed) container instance', 'default': False},
},
'required': ['pod_name'],
}
),
]
@server.call_tool()
async def call_pod_tool(name: str, arguments: dict) -> list[types.TextContent]:
v1 = client.CoreV1Api()
if name == 'list_pods':
namespace = arguments.get('namespace', 'default')
label_sel = arguments.get('label_selector', None)
field_sel = arguments.get('field_selector', None)
try:
if namespace == 'all':
pods = v1.list_pod_for_all_namespaces(
label_selector=label_sel, field_selector=field_sel)
else:
pods = v1.list_namespaced_pod(
namespace, label_selector=label_sel, field_selector=field_sel)
result = []
for pod in pods.items:
containers = pod.spec.containers
restarts = sum(
cs.restart_count for cs in (pod.status.container_statuses or []))
result.append({
'name': pod.metadata.name,
'namespace': pod.metadata.namespace,
'phase': pod.status.phase,
'restarts': restarts,
'node': pod.spec.node_name,
'containers': [c.name for c in containers],
'age': str(pod.metadata.creation_timestamp),
})
return [types.TextContent(type='text',
text=f'Found {len(result)} pods:n' + json.dumps(result, indent=2, default=str))]
except ApiException as e:
return [types.TextContent(type='text', text=f'Kubernetes API error: {e.reason} ({e.status})')]
elif name == 'get_pod_logs':
try:
logs = v1.read_namespaced_pod_log(
name=arguments['pod_name'],
namespace=arguments.get('namespace', 'default'),
container=arguments.get('container'),
tail_lines=arguments.get('tail_lines', 100),
previous=arguments.get('previous', False),
)
return [types.TextContent(type='text', text=logs or '(no logs found)')]
except ApiException as e:
return [types.TextContent(type='text', text=f'Error fetching logs: {e.reason}')]
# tools/pods.py
from mcp.server import Server
from mcp import types
from kubernetes import client
from kubernetes.client.rest import ApiException
import json, logging
log = logging.getLogger('k8s-mcp.pods')
def register_pod_tools(server: Server):
@server.list_tools()
async def list_pod_tools() -> list[types.Tool]:
return [
types.Tool(
name='list_pods',
description='List pods in a Kubernetes namespace with their status, restarts, and age. '
'Use this to get an overview of what is running or to find failing pods.',
inputSchema={
'type': 'object',
'properties': {
'namespace': {'type': 'string', 'description': 'Namespace to list pods from. Use "all" for all namespaces. Default: default'},
'label_selector': {'type': 'string', 'description': 'Optional: filter by label e.g. "app=payments"'},
'field_selector': {'type': 'string', 'description': 'Optional: filter by field e.g. "status.phase=Failed"'},
},
'required': [],
}
),
types.Tool(
name='get_pod_logs',
description='Retrieve logs from a specific pod container. Use this to diagnose errors or understand pod behaviour.',
inputSchema={
'type': 'object',
'properties': {
'pod_name': {'type': 'string', 'description': 'Name of the pod'},
'namespace': {'type': 'string', 'description': 'Namespace of the pod', 'default': 'default'},
'container': {'type': 'string', 'description': 'Container name (optional if pod has one container)'},
'tail_lines': {'type': 'integer', 'description': 'Number of recent log lines to return', 'default': 100},
'previous': {'type': 'boolean', 'description': 'Return logs from previous (crashed) container instance', 'default': False},
},
'required': ['pod_name'],
}
),
]
@server.call_tool()
async def call_pod_tool(name: str, arguments: dict) -> list[types.TextContent]:
v1 = client.CoreV1Api()
if name == 'list_pods':
namespace = arguments.get('namespace', 'default')
label_sel = arguments.get('label_selector', None)
field_sel = arguments.get('field_selector', None)
try:
if namespace == 'all':
pods = v1.list_pod_for_all_namespaces(
label_selector=label_sel, field_selector=field_sel)
else:
pods = v1.list_namespaced_pod(
namespace, label_selector=label_sel, field_selector=field_sel)
result = []
for pod in pods.items:
containers = pod.spec.containers
restarts = sum(
cs.restart_count for cs in (pod.status.container_statuses or []))
result.append({
'name': pod.metadata.name,
'namespace': pod.metadata.namespace,
'phase': pod.status.phase,
'restarts': restarts,
'node': pod.spec.node_name,
'containers': [c.name for c in containers],
'age': str(pod.metadata.creation_timestamp),
})
return [types.TextContent(type='text',
text=f'Found {len(result)} pods:n' + json.dumps(result, indent=2, default=str))]
except ApiException as e:
return [types.TextContent(type='text', text=f'Kubernetes API error: {e.reason} ({e.status})')]
elif name == 'get_pod_logs':
try:
logs = v1.read_namespaced_pod_log(
name=arguments['pod_name'],
namespace=arguments.get('namespace', 'default'),
container=arguments.get('container'),
tail_lines=arguments.get('tail_lines', 100),
previous=arguments.get('previous', False),
)
return [types.TextContent(type='text', text=logs or '(no logs found)')]
except ApiException as e:
return [types.TextContent(type='text', text=f'Error fetching logs: {e.reason}')]
Step 4: Deployment and Node Tools (10 minutes)
list[types.Tool]:
return [
types.Tool(
name='list_deployments',
description='List Kubernetes deployments with replica counts, images, and rollout status.',
inputSchema={
'type': 'object',
'properties': {
'namespace': {'type': 'string', 'default': 'default'},
}
}
),
types.Tool(
name='get_deployment',
description='Get detailed information about a specific deployment including resource limits, strategy, and conditions.',
inputSchema={
'type': 'object',
'properties': {
'name': {'type': 'string'},
'namespace': {'type': 'string', 'default': 'default'},
},
'required': ['name']
}
),
]
@server.call_tool()
async def call_deployment_tool(name: str, arguments: dict) -> list[types.TextContent]:
apps_v1 = client.AppsV1Api()
namespace = arguments.get('namespace', 'default')
if name == 'list_deployments':
deps = apps_v1.list_namespaced_deployment(namespace)
result = [{
'name': d.metadata.name,
'replicas_desired': d.spec.replicas,
'replicas_ready': d.status.ready_replicas or 0,
'replicas_available': d.status.available_replicas or 0,
'image': d.spec.template.spec.containers[0].image,
'updated_at': str(d.metadata.creation_timestamp),
} for d in deps.items]
return [types.TextContent(type='text', text=json.dumps(result, indent=2, default=str))]
elif name == 'get_deployment':
d = apps_v1.read_namespaced_deployment(arguments['name'], namespace)
containers = [{
'name': c.name,
'image': c.image,
'resources': {
'requests': {k:str(v) for k,v in (c.resources.requests or {}).items()},
'limits': {k:str(v) for k,v in (c.resources.limits or {}).items()},
} if c.resources else {},
} for c in d.spec.template.spec.containers]
return [types.TextContent(type='text',
text=json.dumps({'name': d.metadata.name, 'containers': containers}, indent=2))]” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
# tools/deployments.py
from mcp.server import Server
from mcp import types
from kubernetes import client
import json, logging
log = logging.getLogger('k8s-mcp.deployments')
def register_deployment_tools(server: Server):
@server.list_tools()
async def list_deployment_tools() -> list[types.Tool]:
return [
types.Tool(
name='list_deployments',
description='List Kubernetes deployments with replica counts, images, and rollout status.',
inputSchema={
'type': 'object',
'properties': {
'namespace': {'type': 'string', 'default': 'default'},
}
}
),
types.Tool(
name='get_deployment',
description='Get detailed information about a specific deployment including resource limits, strategy, and conditions.',
inputSchema={
'type': 'object',
'properties': {
'name': {'type': 'string'},
'namespace': {'type': 'string', 'default': 'default'},
},
'required': ['name']
}
),
]
@server.call_tool()
async def call_deployment_tool(name: str, arguments: dict) -> list[types.TextContent]:
apps_v1 = client.AppsV1Api()
namespace = arguments.get('namespace', 'default')
if name == 'list_deployments':
deps = apps_v1.list_namespaced_deployment(namespace)
result = [{
'name': d.metadata.name,
'replicas_desired': d.spec.replicas,
'replicas_ready': d.status.ready_replicas or 0,
'replicas_available': d.status.available_replicas or 0,
'image': d.spec.template.spec.containers[0].image,
'updated_at': str(d.metadata.creation_timestamp),
} for d in deps.items]
return [types.TextContent(type='text', text=json.dumps(result, indent=2, default=str))]
elif name == 'get_deployment':
d = apps_v1.read_namespaced_deployment(arguments['name'], namespace)
containers = [{
'name': c.name,
'image': c.image,
'resources': {
'requests': {k:str(v) for k,v in (c.resources.requests or {}).items()},
'limits': {k:str(v) for k,v in (c.resources.limits or {}).items()},
} if c.resources else {},
} for c in d.spec.template.spec.containers]
return [types.TextContent(type='text',
text=json.dumps({'name': d.metadata.name, 'containers': containers}, indent=2))]
# tools/deployments.py
from mcp.server import Server
from mcp import types
from kubernetes import client
import json, logging
log = logging.getLogger('k8s-mcp.deployments')
def register_deployment_tools(server: Server):
@server.list_tools()
async def list_deployment_tools() -> list[types.Tool]:
return [
types.Tool(
name='list_deployments',
description='List Kubernetes deployments with replica counts, images, and rollout status.',
inputSchema={
'type': 'object',
'properties': {
'namespace': {'type': 'string', 'default': 'default'},
}
}
),
types.Tool(
name='get_deployment',
description='Get detailed information about a specific deployment including resource limits, strategy, and conditions.',
inputSchema={
'type': 'object',
'properties': {
'name': {'type': 'string'},
'namespace': {'type': 'string', 'default': 'default'},
},
'required': ['name']
}
),
]
@server.call_tool()
async def call_deployment_tool(name: str, arguments: dict) -> list[types.TextContent]:
apps_v1 = client.AppsV1Api()
namespace = arguments.get('namespace', 'default')
if name == 'list_deployments':
deps = apps_v1.list_namespaced_deployment(namespace)
result = [{
'name': d.metadata.name,
'replicas_desired': d.spec.replicas,
'replicas_ready': d.status.ready_replicas or 0,
'replicas_available': d.status.available_replicas or 0,
'image': d.spec.template.spec.containers[0].image,
'updated_at': str(d.metadata.creation_timestamp),
} for d in deps.items]
return [types.TextContent(type='text', text=json.dumps(result, indent=2, default=str))]
elif name == 'get_deployment':
d = apps_v1.read_namespaced_deployment(arguments['name'], namespace)
containers = [{
'name': c.name,
'image': c.image,
'resources': {
'requests': {k:str(v) for k,v in (c.resources.requests or {}).items()},
'limits': {k:str(v) for k,v in (c.resources.limits or {}).items()},
} if c.resources else {},
} for c in d.spec.template.spec.containers]
return [types.TextContent(type='text',
text=json.dumps({'name': d.metadata.name, 'containers': containers}, indent=2))]
Step 5: Events Tool — The Secret Weapon
The events tool is the single most useful debugging tool in the MCP server. Kubernetes events capture node pressure, image pull failures, OOMKills, scheduling failures, and probe failures — the root causes of most production issues.
list[types.Tool]:
return [types.Tool(
name='get_events',
description='Get Kubernetes events for a namespace or specific resource. '
'Events reveal OOMKills, image pull failures, scheduling issues, and probe failures. '
'Always check events when debugging pod failures.',
inputSchema={
'type': 'object',
'properties': {
'namespace': {'type': 'string', 'default': 'default'},
'involved_object': {'type': 'string', 'description': 'Optional: filter to events for a specific pod or deployment name'},
'event_type': {'type': 'string', 'enum': ['Warning', 'Normal', 'all'], 'default': 'Warning'},
'limit': {'type': 'integer', 'default': 20},
},
}
)]
@server.call_tool()
async def call_event_tool(name: str, arguments: dict) -> list[types.TextContent]:
if name != 'get_events':
return [types.TextContent(type='text', text=f'Unknown tool: {name}')]
v1 = client.CoreV1Api()
namespace = arguments.get('namespace', 'default')
field_sel = []
if arguments.get('involved_object'):
field_sel.append(f'involvedObject.name={arguments["involved_object"]}')
event_type = arguments.get('event_type', 'Warning')
if event_type != 'all':
field_sel.append(f'type={event_type}')
events = v1.list_namespaced_event(
namespace,
field_selector=','.join(field_sel) if field_sel else None,
)
# Sort by last timestamp, most recent first
sorted_events = sorted(
events.items,
key=lambda e: e.last_timestamp or datetime.min.replace(tzinfo=timezone.utc),
reverse=True
)[:arguments.get('limit', 20)]
result = [{
'type': e.type,
'reason': e.reason,
'message': e.message,
'object': f'{e.involved_object.kind}/{e.involved_object.name}',
'count': e.count,
'last_seen': str(e.last_timestamp),
} for e in sorted_events]
return [types.TextContent(type='text', text=json.dumps(result, indent=2, default=str))]” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
# tools/events.py
from mcp.server import Server
from mcp import types
from kubernetes import client
import json
from datetime import datetime, timezone
def register_event_tools(server: Server):
@server.list_tools()
async def list_event_tools() -> list[types.Tool]:
return [types.Tool(
name='get_events',
description='Get Kubernetes events for a namespace or specific resource. '
'Events reveal OOMKills, image pull failures, scheduling issues, and probe failures. '
'Always check events when debugging pod failures.',
inputSchema={
'type': 'object',
'properties': {
'namespace': {'type': 'string', 'default': 'default'},
'involved_object': {'type': 'string', 'description': 'Optional: filter to events for a specific pod or deployment name'},
'event_type': {'type': 'string', 'enum': ['Warning', 'Normal', 'all'], 'default': 'Warning'},
'limit': {'type': 'integer', 'default': 20},
},
}
)]
@server.call_tool()
async def call_event_tool(name: str, arguments: dict) -> list[types.TextContent]:
if name != 'get_events':
return [types.TextContent(type='text', text=f'Unknown tool: {name}')]
v1 = client.CoreV1Api()
namespace = arguments.get('namespace', 'default')
field_sel = []
if arguments.get('involved_object'):
field_sel.append(f'involvedObject.name={arguments["involved_object"]}')
event_type = arguments.get('event_type', 'Warning')
if event_type != 'all':
field_sel.append(f'type={event_type}')
events = v1.list_namespaced_event(
namespace,
field_selector=','.join(field_sel) if field_sel else None,
)
# Sort by last timestamp, most recent first
sorted_events = sorted(
events.items,
key=lambda e: e.last_timestamp or datetime.min.replace(tzinfo=timezone.utc),
reverse=True
)[:arguments.get('limit', 20)]
result = [{
'type': e.type,
'reason': e.reason,
'message': e.message,
'object': f'{e.involved_object.kind}/{e.involved_object.name}',
'count': e.count,
'last_seen': str(e.last_timestamp),
} for e in sorted_events]
return [types.TextContent(type='text', text=json.dumps(result, indent=2, default=str))]
# tools/events.py
from mcp.server import Server
from mcp import types
from kubernetes import client
import json
from datetime import datetime, timezone
def register_event_tools(server: Server):
@server.list_tools()
async def list_event_tools() -> list[types.Tool]:
return [types.Tool(
name='get_events',
description='Get Kubernetes events for a namespace or specific resource. '
'Events reveal OOMKills, image pull failures, scheduling issues, and probe failures. '
'Always check events when debugging pod failures.',
inputSchema={
'type': 'object',
'properties': {
'namespace': {'type': 'string', 'default': 'default'},
'involved_object': {'type': 'string', 'description': 'Optional: filter to events for a specific pod or deployment name'},
'event_type': {'type': 'string', 'enum': ['Warning', 'Normal', 'all'], 'default': 'Warning'},
'limit': {'type': 'integer', 'default': 20},
},
}
)]
@server.call_tool()
async def call_event_tool(name: str, arguments: dict) -> list[types.TextContent]:
if name != 'get_events':
return [types.TextContent(type='text', text=f'Unknown tool: {name}')]
v1 = client.CoreV1Api()
namespace = arguments.get('namespace', 'default')
field_sel = []
if arguments.get('involved_object'):
field_sel.append(f'involvedObject.name={arguments["involved_object"]}')
event_type = arguments.get('event_type', 'Warning')
if event_type != 'all':
field_sel.append(f'type={event_type}')
events = v1.list_namespaced_event(
namespace,
field_selector=','.join(field_sel) if field_sel else None,
)
# Sort by last timestamp, most recent first
sorted_events = sorted(
events.items,
key=lambda e: e.last_timestamp or datetime.min.replace(tzinfo=timezone.utc),
reverse=True
)[:arguments.get('limit', 20)]
result = [{
'type': e.type,
'reason': e.reason,
'message': e.message,
'object': f'{e.involved_object.kind}/{e.involved_object.name}',
'count': e.count,
'last_seen': str(e.last_timestamp),
} for e in sorted_events]
return [types.TextContent(type='text', text=json.dumps(result, indent=2, default=str))]
Step 6: Testing Locally (5 minutes)
# Test the server directly (before connecting to Claude Desktop)
python server.py
# Server should start with: 'Kubernetes MCP server starting...'
# Connect to Claude Desktop:
# Edit: ~/.config/claude/claude_desktop_config.json (macOS/Linux)
# Edit: %APPDATA%/claude/claude_desktop_config.json (Windows)
{
"mcpServers": {
"kubernetes": {
"command": "/path/to/k8s-mcp-server/.venv/bin/python",
"args": ["/path/to/k8s-mcp-server/server.py"],
"env": {
"KUBECONFIG": "/home/user/.kube/config"
}
}
}
}
# Restart Claude Desktop — your server appears in the tool menu
# Test with: 'List all pods in the default namespace'
# Expected: Structured JSON list of pods with status, restarts, and node
# Test the server directly (before connecting to Claude Desktop)
python server.py
# Server should start with: 'Kubernetes MCP server starting...'
# Connect to Claude Desktop:
# Edit: ~/.config/claude/claude_desktop_config.json (macOS/Linux)
# Edit: %APPDATA%/claude/claude_desktop_config.json (Windows)
{
"mcpServers": {
"kubernetes": {
"command": "/path/to/k8s-mcp-server/.venv/bin/python",
"args": ["/path/to/k8s-mcp-server/server.py"],
"env": {
"KUBECONFIG": "/home/user/.kube/config"
}
}
}
}
# Restart Claude Desktop — your server appears in the tool menu
# Test with: 'List all pods in the default namespace'
# Expected: Structured JSON list of pods with status, restarts, and node
Step 7: Adding Custom Tools — Beyond the Basics
The real value of building your own server is adding tools specific to your environment. Here are three common extensions:
Custom Tool: Cluster Health Score
dict:
v1 = client.CoreV1Api()
score = 100
issues = []
# Check pod health
if namespace == 'all':
pods = v1.list_pod_for_all_namespaces()
else:
pods = v1.list_namespaced_pod(namespace)
for pod in pods.items:
if pod.status.phase == 'Failed': score -= 5; issues.append(f'Failed pod: {pod.metadata.name}')
restarts = sum(cs.restart_count for cs in (pod.status.container_statuses or []))
if restarts > 10: score -= 2; issues.append(f'High restarts ({restarts}): {pod.metadata.name}')
# Check node conditions
nodes = v1.list_node()
for node in nodes.items:
for cond in (node.status.conditions or []):
if cond.type == 'Ready' and cond.status != 'True':
score -= 15; issues.append(f'Node not ready: {node.metadata.name}')
if cond.type == 'MemoryPressure' and cond.status == 'True':
score -= 10; issues.append(f'Memory pressure: {node.metadata.name}')
return {'score': max(0, score), 'grade': 'A' if score>90 else 'B' if score>75 else 'C' if score>60 else 'F', 'issues': issues}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
# Add to tools/custom.py — organisation-specific health check
types.Tool(
name='get_cluster_health_score',
description='Calculate a cluster health score (0-100) based on pod states, node conditions, '
'resource utilisation, and recent events. Use for quick cluster triage.',
inputSchema={'type': 'object', 'properties': {
'namespace': {'type': 'string', 'default': 'all'},
}}
),
# Implementation:
async def get_cluster_health_score(namespace: str) -> dict:
v1 = client.CoreV1Api()
score = 100
issues = []
# Check pod health
if namespace == 'all':
pods = v1.list_pod_for_all_namespaces()
else:
pods = v1.list_namespaced_pod(namespace)
for pod in pods.items:
if pod.status.phase == 'Failed': score -= 5; issues.append(f'Failed pod: {pod.metadata.name}')
restarts = sum(cs.restart_count for cs in (pod.status.container_statuses or []))
if restarts > 10: score -= 2; issues.append(f'High restarts ({restarts}): {pod.metadata.name}')
# Check node conditions
nodes = v1.list_node()
for node in nodes.items:
for cond in (node.status.conditions or []):
if cond.type == 'Ready' and cond.status != 'True':
score -= 15; issues.append(f'Node not ready: {node.metadata.name}')
if cond.type == 'MemoryPressure' and cond.status == 'True':
score -= 10; issues.append(f'Memory pressure: {node.metadata.name}')
return {'score': max(0, score), 'grade': 'A' if score>90 else 'B' if score>75 else 'C' if score>60 else 'F', 'issues': issues}
# Add to tools/custom.py — organisation-specific health check
types.Tool(
name='get_cluster_health_score',
description='Calculate a cluster health score (0-100) based on pod states, node conditions, '
'resource utilisation, and recent events. Use for quick cluster triage.',
inputSchema={'type': 'object', 'properties': {
'namespace': {'type': 'string', 'default': 'all'},
}}
),
# Implementation:
async def get_cluster_health_score(namespace: str) -> dict:
v1 = client.CoreV1Api()
score = 100
issues = []
# Check pod health
if namespace == 'all':
pods = v1.list_pod_for_all_namespaces()
else:
pods = v1.list_namespaced_pod(namespace)
for pod in pods.items:
if pod.status.phase == 'Failed': score -= 5; issues.append(f'Failed pod: {pod.metadata.name}')
restarts = sum(cs.restart_count for cs in (pod.status.container_statuses or []))
if restarts > 10: score -= 2; issues.append(f'High restarts ({restarts}): {pod.metadata.name}')
# Check node conditions
nodes = v1.list_node()
for node in nodes.items:
for cond in (node.status.conditions or []):
if cond.type == 'Ready' and cond.status != 'True':
score -= 15; issues.append(f'Node not ready: {node.metadata.name}')
if cond.type == 'MemoryPressure' and cond.status == 'True':
score -= 10; issues.append(f'Memory pressure: {node.metadata.name}')
return {'score': max(0, score), 'grade': 'A' if score>90 else 'B' if score>75 else 'C' if score>60 else 'F', 'issues': issues}
The Complete Tool Surface: What You Have Built
├── .env # Local credentials (never committed)
├── Dockerfile
└── requirements.txt
Step 2: The Server Foundation (10 minutes)
The MCP server is the central orchestrator: it initialises the Kubernetes client, registers all tools, and handles the MCP protocol communication. The server.py file is the entry point.
server.py
import asyncio
import logging
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp import types
from kubernetes import client, config
from kubernetes.client.rest import ApiException
Configure logging
logging.basicConfig(
level=logging.INFO,
format=’%(asctime)s [%(name)s] %(levelname)s: %(message)s’
)
log = logging.getLogger(‘k8s-mcp’)
Initialise MCP server
server = Server(‘kubernetes-mcp’)
Initialise Kubernetes client
def init_k8s():
try:
config.load_kube_config() # Uses ~/.kube/config
log.info(‘Loaded kubeconfig from ~/.kube/config’)
except config.ConfigException:
config.load_incluster_config() # Fallback: running inside a pod
log.info(‘Loaded in-cluster Kubernetes config’)
init_k8s()
Register tool modules (imported below)
from tools.pods import register_pod_tools
from tools.deployments import register_deployment_tools
from tools.nodes import register_node_tools
from tools.events import register_event_tools
register_pod_tools(server)
register_deployment_tools(server)
register_node_tools(server)
register_event_tools(server)
async def main():
async with stdio_server() as (read_stream, write_stream):
log.info(‘Kubernetes MCP server starting…’)
await server.run(read_stream, write_stream,
server.create_initialization_options())
if name == ‘main‘:
asyncio.run(main())
Step 3: Implementing the Pod Tools (15 minutes)
The pod tools module implements the four most-used Kubernetes operations: listing pods, getting logs, describing a pod, and executing a command. Each tool is decorated with @server.call_tool and includes a matching @server.list_tools registration.
tools/pods.py
from mcp.server import Server
from mcp import types
from kubernetes import client
from kubernetes.client.rest import ApiException
import json, logging
log = logging.getLogger(‘k8s-mcp.pods’)
def register_pod_tools(server: Server):
@server.list_tools()
async def list_pod_tools() -> list[types.Tool]:
return [
types.Tool(
name=’list_pods’,
description=’List pods in a Kubernetes namespace with their status, restarts, and age. ‘
‘Use this to get an overview of what is running or to find failing pods.’,
inputSchema={
‘type’: ‘object’,
‘properties’: {
‘namespace’: {‘type’: ‘string’, ‘description’: ‘Namespace to list pods from. Use “all” for all namespaces. Default: default’},
‘label_selector’: {‘type’: ‘string’, ‘description’: ‘Optional: filter by label e.g. “app=payments”‘},
‘field_selector’: {‘type’: ‘string’, ‘description’: ‘Optional: filter by field e.g. “status.phase=Failed”‘},
},
‘required’: [],
}
),
types.Tool(
name=’get_pod_logs’,
description=’Retrieve logs from a specific pod container. Use this to diagnose errors or understand pod behaviour.’,
inputSchema={
‘type’: ‘object’,
‘properties’: {
‘pod_name’: {‘type’: ‘string’, ‘description’: ‘Name of the pod’},
‘namespace’: {‘type’: ‘string’, ‘description’: ‘Namespace of the pod’, ‘default’: ‘default’},
‘container’: {‘type’: ‘string’, ‘description’: ‘Container name (optional if pod has one container)’},
‘tail_lines’: {‘type’: ‘integer’, ‘description’: ‘Number of recent log lines to return’, ‘default’: 100},
‘previous’: {‘type’: ‘boolean’, ‘description’: ‘Return logs from previous (crashed) container instance’, ‘default’: False},
},
‘required’: [‘pod_name’],
}
),
]
@server.call_tool()
async def call_pod_tool(name: str, arguments: dict) -> list[types.TextContent]:
v1 = client.CoreV1Api()
if name == ‘list_pods’:
namespace = arguments.get(‘namespace’, ‘default’)
label_sel = arguments.get(‘label_selector’, None)
field_sel = arguments.get(‘field_selector’, None)
try:
if namespace == ‘all’:
pods = v1.list_pod_for_all_namespaces(
label_selector=label_sel, field_selector=field_sel)
else:
pods = v1.list_namespaced_pod(
namespace, label_selector=label_sel, field_selector=field_sel)
result = []
for pod in pods.items:
containers = pod.spec.containers
restarts = sum(
cs.restart_count for cs in (pod.status.container_statuses or []))
result.append({
‘name’: pod.metadata.name,
‘namespace’: pod.metadata.namespace,
‘phase’: pod.status.phase,
‘restarts’: restarts,
‘node’: pod.spec.node_name,
‘containers’: [c.name for c in containers],
‘age’: str(pod.metadata.creation_timestamp),
})
return [types.TextContent(type=’text’,
text=f’Found {len(result)} pods:n’ + json.dumps(result, indent=2, default=str))]
except ApiException as e:
return [types.TextContent(type=’text’, text=f’Kubernetes API error: {e.reason} ({e.status})’)]
elif name == ‘get_pod_logs’:
try:
logs = v1.read_namespaced_pod_log(
name=arguments[‘pod_name’],
namespace=arguments.get(‘namespace’, ‘default’),
container=arguments.get(‘container’),
tail_lines=arguments.get(‘tail_lines’, 100),
previous=arguments.get(‘previous’, False),
)
return [types.TextContent(type=’text’, text=logs or ‘(no logs found)’)]
except ApiException as e:
return [types.TextContent(type=’text’, text=f’Error fetching logs: {e.reason}’)]
Step 4: Deployment and Node Tools (10 minutes)
tools/deployments.py
from mcp.server import Server
from mcp import types
from kubernetes import client
import json, logging
log = logging.getLogger(‘k8s-mcp.deployments’)
def register_deployment_tools(server: Server):
@server.list_tools()
async def list_deployment_tools() -> list[types.Tool]:
return [
types.Tool(
name=’list_deployments’,
description=’List Kubernetes deployments with replica counts, images, and rollout status.’,
inputSchema={
‘type’: ‘object’,
‘properties’: {
‘namespace’: {‘type’: ‘string’, ‘default’: ‘default’},
}
}
),
types.Tool(
name=’get_deployment’,
description=’Get detailed information about a specific deployment including resource limits, strategy, and conditions.’,
inputSchema={
‘type’: ‘object’,
‘properties’: {
‘name’: {‘type’: ‘string’},
‘namespace’: {‘type’: ‘string’, ‘default’: ‘default’},
},
‘required’: [‘name’]
}
),
]
@server.call_tool()
async def call_deployment_tool(name: str, arguments: dict) -> list[types.TextContent]:
apps_v1 = client.AppsV1Api()
namespace = arguments.get(‘namespace’, ‘default’)
if name == ‘list_deployments’:
deps = apps_v1.list_namespaced_deployment(namespace)
result = [{
‘name’: d.metadata.name,
‘replicas_desired’: d.spec.replicas,
‘replicas_ready’: d.status.ready_replicas or 0,
‘replicas_available’: d.status.available_replicas or 0,
‘image’: d.spec.template.spec.containers[0].image,
‘updated_at’: str(d.metadata.creation_timestamp),
} for d in deps.items]
return [types.TextContent(type=’text’, text=json.dumps(result, indent=2, default=str))]
elif name == ‘get_deployment’:
d = apps_v1.read_namespaced_deployment(arguments[‘name’], namespace)
containers = [{
‘name’: c.name,
‘image’: c.image,
‘resources’: {
‘requests’: {k:str(v) for k,v in (c.resources.requests or {}).items()},
‘limits’: {k:str(v) for k,v in (c.resources.limits or {}).items()},
} if c.resources else {},
} for c in d.spec.template.spec.containers]
return [types.TextContent(type=’text’,
text=json.dumps({‘name’: d.metadata.name, ‘containers’: containers}, indent=2))]
Step 5: Events Tool — The Secret Weapon
The events tool is the single most useful debugging tool in the MCP server. Kubernetes events capture node pressure, image pull failures, OOMKills, scheduling failures, and probe failures — the root causes of most production issues.
tools/events.py
from mcp.server import Server
from mcp import types
from kubernetes import client
import json
from datetime import datetime, timezone
def register_event_tools(server: Server):
@server.list_tools()
async def list_event_tools() -> list[types.Tool]:
return [types.Tool(
name=’get_events’,
description=’Get Kubernetes events for a namespace or specific resource. ‘
‘Events reveal OOMKills, image pull failures, scheduling issues, and probe failures. ‘
‘Always check events when debugging pod failures.’,
inputSchema={
‘type’: ‘object’,
‘properties’: {
‘namespace’: {‘type’: ‘string’, ‘default’: ‘default’},
‘involved_object’: {‘type’: ‘string’, ‘description’: ‘Optional: filter to events for a specific pod or deployment name’},
‘event_type’: {‘type’: ‘string’, ‘enum’: [‘Warning’, ‘Normal’, ‘all’], ‘default’: ‘Warning’},
‘limit’: {‘type’: ‘integer’, ‘default’: 20},
},
}
)]
@server.call_tool()
async def call_event_tool(name: str, arguments: dict) -> list[types.TextContent]:
if name != ‘get_events’:
return [types.TextContent(type=’text’, text=f’Unknown tool: {name}’)]
v1 = client.CoreV1Api()
namespace = arguments.get(‘namespace’, ‘default’)
field_sel = []
if arguments.get(‘involved_object’):
field_sel.append(f’involvedObject.name={arguments[“involved_object”]}’)
event_type = arguments.get(‘event_type’, ‘Warning’)
if event_type != ‘all’:
field_sel.append(f’type={event_type}’)
events = v1.list_namespaced_event(
namespace,
field_selector=’,’.join(field_sel) if field_sel else None,
)
Sort by last timestamp, most recent first
sorted_events = sorted(
events.items,
key=lambda e: e.last_timestamp or datetime.min.replace(tzinfo=timezone.utc),
reverse=True
)[:arguments.get(‘limit’, 20)]
result = [{
‘type’: e.type,
‘reason’: e.reason,
‘message’: e.message,
‘object’: f'{e.involved_object.kind}/{e.involved_object.name}’,
‘count’: e.count,
‘last_seen’: str(e.last_timestamp),
} for e in sorted_events]
return [types.TextContent(type=’text’, text=json.dumps(result, indent=2, default=str))]
Step 6: Testing Locally (5 minutes)
Test the server directly (before connecting to Claude Desktop)
python server.py
Server should start with: ‘Kubernetes MCP server starting…’
Connect to Claude Desktop:
Edit: ~/.config/claude/claude_desktop_config.json (macOS/Linux)
Edit: %APPDATA%/claude/claude_desktop_config.json (Windows)
{
“mcpServers”: {
“kubernetes”: {
“command”: “/path/to/k8s-mcp-server/.venv/bin/python”,
“args”: [“/path/to/k8s-mcp-server/server.py”],
“env”: {
“KUBECONFIG”: “/home/user/.kube/config”
}
}
}
}
Restart Claude Desktop — your server appears in the tool menu
Test with: ‘List all pods in the default namespace’
Expected: Structured JSON list of pods with status, restarts, and node
Step 7: Adding Custom Tools — Beyond the Basics
The real value of building your own server is adding tools specific to your environment. Here are three common extensions:
Custom Tool: Cluster Health Score
Add to tools/custom.py — organisation-specific health check
types.Tool(
name=’get_cluster_health_score’,
description=’Calculate a cluster health score (0–100) based on pod states, node conditions, ‘
‘resource utilisation, and recent events. Use for quick cluster triage.’,
inputSchema={‘type’: ‘object’, ‘properties’: {
‘namespace’: {‘type’: ‘string’, ‘default’: ‘all’},
}}
),
Implementation:
async def get_cluster_health_score(namespace: str) -> dict:
v1 = client.CoreV1Api()
score = 100
issues = []
Check pod health
if namespace == ‘all’:
pods = v1.list_pod_for_all_namespaces()
else:
pods = v1.list_namespaced_pod(namespace)
for pod in pods.items:
if pod.status.phase == ‘Failed’: score -= 5; issues.append(f’Failed pod: {pod.metadata.name}’)
restarts = sum(cs.restart_count for cs in (pod.status.container_statuses or []))
if restarts > 10: score -= 2; issues.append(f’High restarts ({restarts}): {pod.metadata.name}’)
Check node conditions
nodes = v1.list_node()
for node in nodes.items:
for cond in (node.status.conditions or []):
if cond.type == ‘Ready’ and cond.status != ‘True’:
score -= 15; issues.append(f’Node not ready: {node.metadata.name}’)
if cond.type == ‘MemoryPressure’ and cond.status == ‘True’:
score -= 10; issues.append(f’Memory pressure: {node.metadata.name}’)
return {‘score’: max(0, score), ‘grade’: ‘A’ if score>90 else ‘B’ if score>75 else ‘C’ if score>60 else ‘F’, ‘issues’: issues}
Custom Tool: Resource Rightsizing Report
Get actual vs. requested resources for rightsizing insights
types.Tool(
name=’get_rightsizing_candidates’,
description=’List deployments where resource requests appear significantly overprovisioned ‘
‘based on recent pod restart patterns and resource limit ratios.’,
inputSchema={‘type’: ‘object’, ‘properties’: {
‘namespace’: {‘type’: ‘string’, ‘default’: ‘default’},
‘min_cpu_request_millicores’: {‘type’: ‘integer’, ‘default’: 100},
}}
),
This pulls CPU/memory requests vs. limits ratio
Services with limits >> requests 3x are rightsizing candidates
AI can then recommend specific values based on the data
Step 8: Dockerise for Team Sharing
Dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install — no-cache-dir -r requirements.txt
COPY . .
Server runs on stdio — no port needed for local mode
For HTTP/SSE mode (remote deployment), add:
ENV MCP_TRANSPORT=sse
ENV MCP_PORT=3000
EXPOSE 3000
CMD [“python”, “server.py”]
requirements.txt
mcp>=1.0.0
kubernetes>=29.0.0
python-dotenv>=1.0.0
Build and share with team:
docker build -t k8s-mcp-server:latest .
docker tag k8s-mcp-server:latest ghcr.io/yourorg/k8s-mcp-server:latest
docker push ghcr.io/yourorg/k8s-mcp-server:latest
Team members configure Claude Desktop to use the container:
{
‘mcpServers’: {
‘kubernetes’: {
‘command’: ‘docker’,
‘args’: [‘run’, ‘ — rm’, ‘-i’,
‘-v’, ‘~/.kube:/root/.kube:ro’,
‘ghcr.io/yourorg/k8s-mcp-server:latest’]
}
}
}
The Complete Tool Surface: What You Have Built
Extending Further: Ideas for Your Next Tools
- Helm release status tool — query Helm release history, values, and diff against current state
- Network policy inspector — show which pods can communicate with which other pods
- Certificate expiry checker — list all cert-manager certificates and their expiry dates
- HPA status tool — show HPA current vs. desired replica counts and scaling events
- PersistentVolume capacity tool — show PV utilisation and volumes approaching capacity
- Namespace quota reporter — show resource quota usage vs. limits across all namespaces
- Cross-cluster federated query — query multiple clusters with a single tool call (requires multiple kubeconfig contexts)
WHAT TO BUILD NEXT
Once your K8s MCP server is working, combine it with the GitHub MCP server (official) to unlock cross-tool workflows: ‘Show me all pods with image versions older than 30 days and find the corresponding GitHub release notes for the current and latest versions.’ That combination — K8s state + Git history — is where MCP becomes genuinely transformative for DevOps workflows.

