How to Build an AI Agent That Manages Your Kubernetes Cluster
For years, the dream of self-managing Kubernetes infrastructure has been expressed in Operators and controllers — code that watches for a specific resource type, compares current state against desired state, and makes targeted changes to close the gap. Operators are powerful, but they are brittle: each Operator is hand-coded to handle the scenarios its authors anticipated. The scenarios they did not anticipate — the unusual combination of events that causes a real production incident — require human intervention.
AI agents with tool access to the Kubernetes API are changing this. An AI agent is not limited to the scenarios it was explicitly programmed for. It can reason about novel situations, draw on its training knowledge about Kubernetes operational patterns, query multiple information sources simultaneously, and propose (or execute) actions appropriate to the specific context. This is qualitatively different from a traditional Operator — and it is moving from research prototype to production deployment in 2026.
This guide is a practical blueprint for building an AI agent that manages a Kubernetes cluster: the architecture, the tools, the MCP server configuration, the safety constraints, and the specific use cases where AI agent management delivers the most value. This is not a theoretical guide — every component described here is available and production-deployable today.
WHO THIS IS FOR
Platform engineers and SRE engineers who manage Kubernetes clusters and want to automate operational tasks with AI agents. Some Kubernetes operational experience assumed; basic familiarity with Python and LLM APIs helpful. No prior AI agent development experience required.
Architecture: The AI Kubernetes Management Stack
An AI Kubernetes management agent consists of five layers:
The critical design principle: the AI agent does not need direct kubectl access. It operates through MCP servers that expose a typed, audited tool interface. Every tool call is logged, every parameter is validated against defined constraints, and write operations can be intercepted by the approval layer before execution. This controlled interface is what makes AI cluster management safe to deploy in production.
Step 1: Setting Up the Kubernetes MCP Server
Installation and configuration
The Kubernetes MCP server exposes cluster operations as typed tools that the AI can call. Multiple community implementations exist; the most complete in 2026 supports the full kubectl API surface including read operations (get, describe, logs), write operations (apply, patch, delete), and diagnostic operations (exec, port-forward, top).
k8s-mcp-rbac.yaml <
# Install the Kubernetes MCP server
pip install kubernetes-mcp-server
# Configure RBAC for the MCP server service account
# Start with read-only for initial deployment
cat > k8s-mcp-rbac.yaml << 'EOF'
apiVersion: v1
kind: ServiceAccount
metadata:
name: ai-agent-readonly
namespace: platform-tools
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: ai-agent-readonly
rules:
- apiGroups: ['*']
resources: ['*']
verbs: ['get', 'list', 'watch']
- apiGroups: ['']
resources: ['pods/log', 'pods/exec']
verbs: ['get', 'create']
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: ai-agent-readonly
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: ai-agent-readonly
subjects:
- kind: ServiceAccount
name: ai-agent-readonly
namespace: platform-tools
EOF
kubectl apply -f k8s-mcp-rbac.yaml
# Install the Kubernetes MCP server
pip install kubernetes-mcp-server
# Configure RBAC for the MCP server service account
# Start with read-only for initial deployment
cat > k8s-mcp-rbac.yaml << 'EOF'
apiVersion: v1
kind: ServiceAccount
metadata:
name: ai-agent-readonly
namespace: platform-tools
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: ai-agent-readonly
rules:
- apiGroups: ['*']
resources: ['*']
verbs: ['get', 'list', 'watch']
- apiGroups: ['']
resources: ['pods/log', 'pods/exec']
verbs: ['get', 'create']
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: ai-agent-readonly
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: ai-agent-readonly
subjects:
- kind: ServiceAccount
name: ai-agent-readonly
namespace: platform-tools
EOF
kubectl apply -f k8s-mcp-rbac.yaml
Tool surface exposed to the agent
Configure which tools the MCP server exposes to the agent. Start with a conservative set and expand as you validate agent behavior:
# mcp-server-config.yaml
tools:
# READ tools - always available
enabled:
- kubernetes_get_pods
- kubernetes_get_deployments
- kubernetes_get_services
- kubernetes_get_nodes
- kubernetes_get_events
- kubernetes_get_pod_logs
- kubernetes_describe_resource
- kubernetes_get_resource_usage
- kubernetes_get_hpa_status
# WRITE tools - require approval gate (phase 2)
gated:
- kubernetes_apply_manifest
- kubernetes_patch_resource
- kubernetes_rollout_restart
- kubernetes_scale_deployment
- kubernetes_delete_resource
# DIAGNOSTIC tools - available with logging
logged:
- kubernetes_exec_command
- kubernetes_port_forward
# mcp-server-config.yaml
tools:
# READ tools - always available
enabled:
- kubernetes_get_pods
- kubernetes_get_deployments
- kubernetes_get_services
- kubernetes_get_nodes
- kubernetes_get_events
- kubernetes_get_pod_logs
- kubernetes_describe_resource
- kubernetes_get_resource_usage
- kubernetes_get_hpa_status
# WRITE tools - require approval gate (phase 2)
gated:
- kubernetes_apply_manifest
- kubernetes_patch_resource
- kubernetes_rollout_restart
- kubernetes_scale_deployment
- kubernetes_delete_resource
# DIAGNOSTIC tools - available with logging
logged:
- kubernetes_exec_command
- kubernetes_port_forward
Step 2: Connecting Observability Context
A Kubernetes agent that can only see cluster state (pod status, deployment specs, resource limits) has incomplete context for meaningful operational decisions. It needs observability data: metrics, logs, and traces. Connect additional MCP servers to provide this context:
Prometheus/Datadog MCP for metrics
# Configure Prometheus MCP server
# Agent can now query: pod CPU/memory, service error rates,
# HPA metrics, custom application metrics
prometheus_mcp_config:
endpoint: http://prometheus.monitoring.svc:9090
allowed_queries:
- 'rate(http_requests_total[5m])'
- 'container_memory_working_set_bytes'
- 'container_cpu_usage_seconds_total'
- 'kube_pod_container_resource_limits'
- 'kube_deployment_status_replicas_available'
read_only: true
max_query_range: 24h
# Configure Prometheus MCP server
# Agent can now query: pod CPU/memory, service error rates,
# HPA metrics, custom application metrics
prometheus_mcp_config:
endpoint: http://prometheus.monitoring.svc:9090
allowed_queries:
- 'rate(http_requests_total[5m])'
- 'container_memory_working_set_bytes'
- 'container_cpu_usage_seconds_total'
- 'kube_pod_container_resource_limits'
- 'kube_deployment_status_replicas_available'
read_only: true
max_query_range: 24h
Loki/CloudWatch MCP for logs
# Log query MCP configuration
# Agent can search structured logs without direct pod exec
loki_mcp_config:
endpoint: http://loki.monitoring.svc:3100
max_lines_per_query: 1000
max_time_range: 6h
allowed_label_selectors:
- 'namespace'
- 'app'
- 'pod'
- 'level'
# Log query MCP configuration
# Agent can search structured logs without direct pod exec
loki_mcp_config:
endpoint: http://loki.monitoring.svc:3100
max_lines_per_query: 1000
max_time_range: 6h
allowed_label_selectors:
- 'namespace'
- 'app'
- 'pod'
- 'level'
Step 3: Building the Agent
Choosing the LLM backbone
For production Kubernetes management agents in 2026, Claude 3.7 Sonnet (Anthropic) and GPT-4o (OpenAI) are the most reliable choices for complex multi-step reasoning with tool use. Key requirements for Kubernetes agent use cases: large context window (cluster state dumps can be verbose), reliable tool-calling with parameter validation, and strong reasoning about causal relationships between cluster events.
Agent implementation with LangGraph
from langchain_anthropic import ChatAnthropic
from langchain_mcp import MCPToolkit
from langgraph.prebuilt import create_react_agent
from langgraph.checkpoint.sqlite import SqliteSaver
# Initialize MCP toolkits
k8s_toolkit = MCPToolkit(server='kubernetes-mcp', config=k8s_config)
prom_toolkit = MCPToolkit(server='prometheus-mcp', config=prom_config)
log_toolkit = MCPToolkit(server='loki-mcp', config=loki_config)
# Combine all tools
tools = k8s_toolkit.get_tools() + prom_toolkit.get_tools() + log_toolkit.get_tools()
# System prompt defining agent role and constraints
SYSTEM_PROMPT = '''
You are a Kubernetes SRE agent with read-only access to cluster state,
metrics, and logs. Your role is to:
1. Investigate operational issues when given a symptom or alert
2. Diagnose root causes using available tools
3. Propose specific remediation actions with clear reasoning
4. NEVER execute write operations without explicit human approval
When investigating, always check in this order:
1. Pod status and recent events
2. Resource utilization (CPU, memory) vs limits
3. Recent deployments and config changes
4. Application logs for error patterns
5. Upstream service dependencies
'''
# Create agent with persistent memory (SQLite for dev, PostgreSQL for prod)
memory = SqliteSaver.from_conn_string(':memory:')
model = ChatAnthropic(model='claude-3-7-sonnet-20250219')
agent = create_react_agent(model, tools, checkpointer=memory,
state_modifier=SYSTEM_PROMPT)
from langchain_anthropic import ChatAnthropic
from langchain_mcp import MCPToolkit
from langgraph.prebuilt import create_react_agent
from langgraph.checkpoint.sqlite import SqliteSaver
# Initialize MCP toolkits
k8s_toolkit = MCPToolkit(server='kubernetes-mcp', config=k8s_config)
prom_toolkit = MCPToolkit(server='prometheus-mcp', config=prom_config)
log_toolkit = MCPToolkit(server='loki-mcp', config=loki_config)
# Combine all tools
tools = k8s_toolkit.get_tools() + prom_toolkit.get_tools() + log_toolkit.get_tools()
# System prompt defining agent role and constraints
SYSTEM_PROMPT = '''
You are a Kubernetes SRE agent with read-only access to cluster state,
metrics, and logs. Your role is to:
1. Investigate operational issues when given a symptom or alert
2. Diagnose root causes using available tools
3. Propose specific remediation actions with clear reasoning
4. NEVER execute write operations without explicit human approval
When investigating, always check in this order:
1. Pod status and recent events
2. Resource utilization (CPU, memory) vs limits
3. Recent deployments and config changes
4. Application logs for error patterns
5. Upstream service dependencies
'''
# Create agent with persistent memory (SQLite for dev, PostgreSQL for prod)
memory = SqliteSaver.from_conn_string(':memory:')
model = ChatAnthropic(model='claude-3-7-sonnet-20250219')
agent = create_react_agent(model, tools, checkpointer=memory,
state_modifier=SYSTEM_PROMPT)
Step 4: The Approval Gate Pattern
The approval gate is the mechanism that separates ‘AI-advised operations’ from ‘AI-executed operations.’ Every write operation the agent proposes must pass through an approval gate before execution. In 2026, the most practical approval gate implementation uses Slack for the approval UI — on-call engineers can approve or reject proposed actions from their phone.
Slack approval integration
bool:
'''
Intercept write operations and require Slack approval.
Returns True if approved, False if rejected or timed out.
'''
slack = WebClient(token=SLACK_BOT_TOKEN)
message = slack.chat_postMessage(
channel=channel,
blocks=[
{'type': 'section', 'text': {'type': 'mrkdwn',
'text': f'*AI Agent Requesting Approval*n`{action_type}`'}},
{'type': 'section', 'text': {'type': 'mrkdwn',
'text': f'*Parameters:*n```{json.dumps(action_params, indent=2)}```'}},
{'type': 'section', 'text': {'type': 'mrkdwn',
'text': f'*Agent Reasoning:*n{agent_reasoning}'}},
{'type': 'actions', 'elements': [
{'type': 'button', 'text': {'type': 'plain_text', 'text': '✅ Approve'},
'style': 'primary', 'value': 'approve', 'action_id': 'approve'},
{'type': 'button', 'text': {'type': 'plain_text', 'text': '❌ Reject'},
'style': 'danger', 'value': 'reject', 'action_id': 'reject'}
]}
]
)
# Poll for response (30 minute timeout for production operations)
return wait_for_slack_approval(message['ts'], timeout_seconds=1800)” 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″>
from slack_sdk import WebClient
import time, json
def approval_gate(action_type: str, action_params: dict,
agent_reasoning: str, channel: str) -> bool:
'''
Intercept write operations and require Slack approval.
Returns True if approved, False if rejected or timed out.
'''
slack = WebClient(token=SLACK_BOT_TOKEN)
message = slack.chat_postMessage(
channel=channel,
blocks=[
{'type': 'section', 'text': {'type': 'mrkdwn',
'text': f'*AI Agent Requesting Approval*n`{action_type}`'}},
{'type': 'section', 'text': {'type': 'mrkdwn',
'text': f'*Parameters:*n```{json.dumps(action_params, indent=2)}```'}},
{'type': 'section', 'text': {'type': 'mrkdwn',
'text': f'*Agent Reasoning:*n{agent_reasoning}'}},
{'type': 'actions', 'elements': [
{'type': 'button', 'text': {'type': 'plain_text', 'text': '✅ Approve'},
'style': 'primary', 'value': 'approve', 'action_id': 'approve'},
{'type': 'button', 'text': {'type': 'plain_text', 'text': '❌ Reject'},
'style': 'danger', 'value': 'reject', 'action_id': 'reject'}
]}
]
)
# Poll for response (30 minute timeout for production operations)
return wait_for_slack_approval(message['ts'], timeout_seconds=1800)
from slack_sdk import WebClient
import time, json
def approval_gate(action_type: str, action_params: dict,
agent_reasoning: str, channel: str) -> bool:
'''
Intercept write operations and require Slack approval.
Returns True if approved, False if rejected or timed out.
'''
slack = WebClient(token=SLACK_BOT_TOKEN)
message = slack.chat_postMessage(
channel=channel,
blocks=[
{'type': 'section', 'text': {'type': 'mrkdwn',
'text': f'*AI Agent Requesting Approval*n`{action_type}`'}},
{'type': 'section', 'text': {'type': 'mrkdwn',
'text': f'*Parameters:*n```{json.dumps(action_params, indent=2)}```'}},
{'type': 'section', 'text': {'type': 'mrkdwn',
'text': f'*Agent Reasoning:*n{agent_reasoning}'}},
{'type': 'actions', 'elements': [
{'type': 'button', 'text': {'type': 'plain_text', 'text': '✅ Approve'},
'style': 'primary', 'value': 'approve', 'action_id': 'approve'},
{'type': 'button', 'text': {'type': 'plain_text', 'text': '❌ Reject'},
'style': 'danger', 'value': 'reject', 'action_id': 'reject'}
]}
]
)
# Poll for response (30 minute timeout for production operations)
return wait_for_slack_approval(message['ts'], timeout_seconds=1800)
Step 5: Use Case Implementation — Autonomous Incident Triage
The investigation workflow
The most impactful use case for an AI Kubernetes agent is automated incident triage: when an alert fires, the agent investigates the cluster state, collects relevant evidence, and produces a structured diagnosis — all before the on-call engineer has even opened their laptop.
dict:
'''
Triggered when PagerDuty alert fires.
Returns structured diagnosis for the on-call engineer.
'''
service_name = alert['labels']['service']
alert_type = alert['labels']['alertname']
namespace = alert['labels']['namespace']
# Construct investigation goal
goal = f'''
Alert: {alert_type} fired for service {service_name} in namespace {namespace}.
Firing since: {alert['startsAt']}
Please investigate this alert comprehensively:
1. Check pod status and recent events for {service_name}
2. Review metrics for the last 30 minutes (CPU, memory, error rate, latency)
3. Check recent deployments (last 2 hours)
4. Analyze pod logs for error patterns
5. Check downstream dependencies
Provide:
– Root cause hypothesis (confidence: High/Medium/Low)
– Supporting evidence from the tools you called
– Recommended remediation steps
– Whether the remediation is safe to execute autonomously
'''
# Run agent investigation (read-only, no approval needed)
result = agent.invoke(
{'messages': [('user', goal)]},
config={'configurable': {'thread_id': alert['fingerprint']}}
)
return parse_agent_diagnosis(result['messages'][-1].content)” 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″>
def handle_alert(alert: dict) -> dict:
'''
Triggered when PagerDuty alert fires.
Returns structured diagnosis for the on-call engineer.
'''
service_name = alert['labels']['service']
alert_type = alert['labels']['alertname']
namespace = alert['labels']['namespace']
# Construct investigation goal
goal = f'''
Alert: {alert_type} fired for service {service_name} in namespace {namespace}.
Firing since: {alert['startsAt']}
Please investigate this alert comprehensively:
1. Check pod status and recent events for {service_name}
2. Review metrics for the last 30 minutes (CPU, memory, error rate, latency)
3. Check recent deployments (last 2 hours)
4. Analyze pod logs for error patterns
5. Check downstream dependencies
Provide:
- Root cause hypothesis (confidence: High/Medium/Low)
- Supporting evidence from the tools you called
- Recommended remediation steps
- Whether the remediation is safe to execute autonomously
'''
# Run agent investigation (read-only, no approval needed)
result = agent.invoke(
{'messages': [('user', goal)]},
config={'configurable': {'thread_id': alert['fingerprint']}}
)
return parse_agent_diagnosis(result['messages'][-1].content)
def handle_alert(alert: dict) -> dict:
'''
Triggered when PagerDuty alert fires.
Returns structured diagnosis for the on-call engineer.
'''
service_name = alert['labels']['service']
alert_type = alert['labels']['alertname']
namespace = alert['labels']['namespace']
# Construct investigation goal
goal = f'''
Alert: {alert_type} fired for service {service_name} in namespace {namespace}.
Firing since: {alert['startsAt']}
Please investigate this alert comprehensively:
1. Check pod status and recent events for {service_name}
2. Review metrics for the last 30 minutes (CPU, memory, error rate, latency)
3. Check recent deployments (last 2 hours)
4. Analyze pod logs for error patterns
5. Check downstream dependencies
Provide:
- Root cause hypothesis (confidence: High/Medium/Low)
- Supporting evidence from the tools you called
- Recommended remediation steps
- Whether the remediation is safe to execute autonomously
'''
# Run agent investigation (read-only, no approval needed)
result = agent.invoke(
{'messages': [('user', goal)]},
config={'configurable': {'thread_id': alert['fingerprint']}}
)
return parse_agent_diagnosis(result['messages'][-1].content)
Step 6: Additional Use Cases
Continuous drift detection and correction
Run the agent on a schedule (every 30 minutes) to detect and report on configuration drift between what Terraform/Argo CD declared and what is actually running in the cluster. The agent queries the Kubernetes API, compares against known-good state stored in a vector database, identifies discrepancies, and generates correction PRs via the GitHub MCP server.
# Drift detection scheduled task
def drift_detection_scan():
goal = '''
Perform a comprehensive drift detection scan of the cluster.
For each namespace in the production cluster:
1. List all Deployments, Services, ConfigMaps, and Secrets
2. Compare resource limits and requests against the baseline in the knowledge base
3. Check for any resources without required labels (team, env, cost-center)
4. Identify any pods running images with the 'latest' tag
5. Check for any ClusterRoleBindings with overly permissive rules
Output a structured drift report with:
- Severity (Critical/High/Medium/Low) for each finding
- Affected resource and namespace
- Specific deviation from expected state
- Recommended remediation
'''
return agent.invoke({'messages': [('user', goal)]})
# Drift detection scheduled task
def drift_detection_scan():
goal = '''
Perform a comprehensive drift detection scan of the cluster.
For each namespace in the production cluster:
1. List all Deployments, Services, ConfigMaps, and Secrets
2. Compare resource limits and requests against the baseline in the knowledge base
3. Check for any resources without required labels (team, env, cost-center)
4. Identify any pods running images with the 'latest' tag
5. Check for any ClusterRoleBindings with overly permissive rules
Output a structured drift report with:
- Severity (Critical/High/Medium/Low) for each finding
- Affected resource and namespace
- Specific deviation from expected state
- Recommended remediation
'''
return agent.invoke({'messages': [('user', goal)]})
Right-sizing recommendations
Run weekly resource utilization analysis: the agent queries Prometheus for 7-day CPU and memory utilization patterns for every deployment, compares against current resource requests and limits, and generates a structured right-sizing report with recommended changes. Feed this into Goldilocks or your FinOps workflow for cost optimization tracking.
Security posture scanning
Run nightly security posture checks: the agent scans for pods running as root, containers without read-only root filesystems, services with public LoadBalancer IPs, RBAC bindings with cluster-admin, and images from unapproved registries. Generate a prioritized finding report and optionally create Kyverno policy violations as GitHub issues for remediation tracking.
Capacity planning assistance
Monthly capacity analysis: the agent queries current resource utilization trends, Kubernetes HPA events, and pod scheduling failures, then projects when capacity constraints will become incident-causing bottlenecks. Generate actionable capacity recommendations — which node pools need more capacity, which namespaces are approaching resource quotas — with enough lead time for procurement cycles.
Production Deployment Checklist
- RBAC: agent service account uses least-privilege permissions scoped to specific namespaces
- Audit logging: all MCP tool calls logged to immutable append-only storage
- Approval gates: all write operations above Tier 1 require Slack or PagerDuty approval
- Rate limiting: agent cannot make more than N tool calls per minute to prevent runaway loops
- Circuit breaker: agent pauses all write operations if error rate in last 10 actions exceeds 20%
- Human override: on-call engineer can immediately disable agent write access via Slack command
- Rollback procedure: every autonomous action records rollback command that executes on failure
- Blast radius limits: agent cannot modify more than 5 resources in a single task without approval
- Credential isolation: agent uses separate, narrow-scoped credentials for each MCP server
- Observability: agent decision logs, tool call logs, and outcome logs sent to Grafana/Datadog
Measuring Success
What to Avoid
Over-trusting early results: an agent that looks impressive in demos may behave incorrectly on edge cases in production. Run in advisory mode (AI diagnoses, humans execute) for at least 30 days before enabling any autonomous write operations. Build a record of diagnosis accuracy before trusting autonomous remediation.
Under-scoping RBAC: giving the agent broad cluster-admin permissions ‘to make it more capable’ is the fastest path to a production incident caused by the agent. Start with read-only and add specific write permissions for specific, proven use cases. The discipline of narrow RBAC is what makes production AI cluster management safe.
Skipping the audit trail: without a complete audit trail, you cannot diagnose why the agent took a wrong action, validate that it behaved correctly, or satisfy compliance requirements for automated production changes. Structured audit logging is non-negotiable from day one.
Conclusion
Building an AI agent that manages your Kubernetes cluster is no longer a research project — it is an engineering project. The components are available: Kubernetes MCP servers, LLM APIs with reliable tool use, orchestration frameworks like LangGraph, and Slack approval gate integrations. The patterns are proven: read-only investigation first, human approval for write operations, confidence thresholds for autonomy, comprehensive audit logging.
The teams that deploy this architecture in 2026 are reducing on-call cognitive load, improving MTTI, and catching operational issues proactively. The investment is a few weeks of platform engineering work to configure the MCP servers, implement the approval gates, and validate agent behavior on your specific cluster. The return is a continuously available, tireless operational assistant that knows your cluster as well as you do — and is available at 3am without a phone call.
NEXT STEP
Fork the LangGraph Kubernetes agent reference implementation, configure it with read-only MCP access to your staging cluster, and run it in advisory mode for one week. Log every diagnosis it produces. Compare against what actually happened. The accuracy data from that one week will tell you exactly which use cases are ready for production deployment and which need more tuning.

