Skip to content

Connect Kubernetes to Claude: Audit and Scale Cluster Resources

Learn how to connect Kubernetes to Claude using a managed MCP server. Automate pod scaling, audit cluster events, and retrieve logs via natural language.

Uday Gajavalli Uday Gajavalli · · 9 min read
Connect Kubernetes to Claude: Audit and Scale Cluster Resources

If your team uses ChatGPT, check out our guide on /connect-kubernetes-to-chatgpt-manage-pods-deployments-services/ or explore our broader architectural overview on /connect-kubernetes-to-ai-agents-automate-workloads-and-logs/.

If you need to connect Kubernetes to Claude to audit cluster resources, debug failing pods, scale deployments, or inspect ingress rules, you need a Model Context Protocol (MCP) server. This server acts as the translation layer between Claude's tool calling capabilities and the Kubernetes REST API. You can either deploy and maintain this infrastructure within your own clusters, or use a managed integration platform like Truto to dynamically generate a secure, authenticated MCP server URL.

Giving a Large Language Model (LLM) read and write access to your underlying infrastructure is a massive engineering and security challenge. You have to handle cluster authentication, map the sprawling Kubernetes API specification into MCP tool definitions, and deal with complex payload structures like JSON Merge Patches. Every time a Kubernetes Custom Resource Definition (CRD) is added or an API group is deprecated, you have to update your server code and redeploy.

This guide breaks down exactly how to use Truto to generate a secure, managed MCP server for Kubernetes, connect it natively to Claude, and execute complex DevOps workflows using natural language.

The Engineering Reality of the Kubernetes API

A custom MCP server is a self-hosted integration layer. While the open MCP standard provides a predictable way for models to discover tools, the reality of implementing it against the Kubernetes API is difficult. Kubernetes is not a standard CRUD application - it is a highly extensible state machine.

If you decide to build a custom Kubernetes MCP server, here are the specific integration challenges you will face:

API Group Fragmentation and Versioning The Kubernetes API is notoriously fragmented across Groups, Versions, and Kinds (GVK). An LLM has no inherent context that a Pod lives in core/v1, while a Deployment lives in apps/v1, and a ValidatingWebhookConfiguration lives in admissionregistration-k8s-io/v1. If you expose raw endpoints to Claude, it will struggle to construct the correct URL paths. You must build an abstraction layer that maps normalized resource names to their correct API groups so the LLM does not hallucinate endpoints.

JSON Merge Patch Complexity Unlike standard APIs that accept simple PUT or PATCH payloads, Kubernetes heavily relies on specific content types for partial updates. When updating a resource, you often must send an application/merge-patch+json payload or an application/strategic-merge-patch+json payload. If the LLM sends a standard JSON payload without the correct headers or payload structure, the API server will reject it. An MCP server must enforce strict schema validation to ensure Claude formats these patches correctly.

Continuous Pagination Across Namespaces Kubernetes handles massive lists of resources (like fetching all events or pods across a cluster) using a specific pagination scheme utilizing limit and continue query parameters. If Claude asks for "all pods in the cluster," a naive integration might timeout or blow up the LLM's context window with thousands of JSON objects. The MCP tools must strictly define the continue token behavior and explicitly instruct the LLM to pass cursor values back unchanged to traverse the cluster state safely.

Step 1: Generating the Kubernetes MCP Server

Truto abstracts away the Kubernetes API complexity by dynamically generating an MCP server based on the integration's documented resources. This server handles the authentication, schema normalization, and JSON-RPC 2.0 protocol translation automatically.

You can generate the Kubernetes MCP server using either the Truto UI or the REST API.

Method 1: Via the Truto UI

If you prefer a visual interface, you can generate the MCP server directly from your Truto dashboard:

  1. Navigate to the Integrated Accounts page and select your connected Kubernetes cluster.
  2. Click the MCP Servers tab.
  3. Click Create MCP Server.
  4. Select your desired configuration (e.g., name the server "Production Cluster K8s", set allowed methods to "read" for safety, and define an optional expiration time).
  5. Click Save and copy the generated MCP server URL (e.g., https://api.truto.one/mcp/a1b2c3d4...).

Method 2: Via the Truto API

For teams building automated DevOps pipelines, you can generate MCP servers programmatically. This is particularly useful if you want to spin up a temporary, short-lived MCP server for a specific CI/CD pipeline run or incident response room.

Make an authenticated POST request to the /integrated-account/:id/mcp endpoint:

curl -X POST https://api.truto.one/admin/integrated-accounts/{integrated_account_id}/mcp \
  -H "Authorization: Bearer YOUR_TRUTO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Kubernetes Incident Triage MCP",
    "config": {
      "methods": ["read"],
      "tags": ["core", "apps"]
    },
    "expires_at": "2026-10-15T00:00:00Z"
  }'

The API will return a secure, hashed token URL. This URL is fully self-contained - it holds the cryptographic proof of which cluster to connect to and which tools to expose.

{
  "id": "mcp-7a8b9c",
  "name": "Kubernetes Incident Triage MCP",
  "config": { "methods": ["read"], "tags": ["core", "apps"] },
  "expires_at": "2026-10-15T00:00:00Z",
  "url": "https://api.truto.one/mcp/f9e8d7c6b5a4..."
}

Step 2: Connecting the MCP Server to Claude

Once you have your Truto MCP server URL, connecting it to Claude requires zero additional coding. The standard MCP JSON-RPC protocol handles the tool discovery handshake automatically.

Method 1: Via the Claude UI

For enterprise users or those using the Claude web interface, you can add the connector directly in the settings:

  1. Open Claude and navigate to Settings -> Integrations.
  2. Click Add MCP Server or Add custom connector.
  3. Paste the Truto MCP URL (https://api.truto.one/mcp/...).
  4. Click Add.

Claude will immediately ping the server, request the tools/list, and populate its context with the available Kubernetes operations.

Method 2: Via the Configuration File (Claude Desktop)

If you are running Claude Desktop locally or configuring an agentic framework, you can map the MCP server in your claude_desktop_config.json file. Because Truto's MCP servers operate over standard HTTPS POST, you use the @modelcontextprotocol/server-sse proxy package to handle the Server-Sent Events (SSE) translation.

{
  "mcpServers": {
    "kubernetes-cluster-prod": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-sse",
        "https://api.truto.one/mcp/f9e8d7c6b5a4..."
      ]
    }
  }
}

Restart Claude Desktop. The application will initialize the connection and announce itself, and the Truto router will return the Kubernetes tool capabilities.

Hero Tools for Kubernetes

Truto derives MCP tools dynamically from the Kubernetes integration documentation. Every endpoint becomes a structured tool with explicitly defined query and body schemas.

Here are 6 high-leverage "hero" tools available when you connect Kubernetes to Claude:

1. list_all_kubernetes_pods

Retrieves a list of pods running in a specific namespace. This tool automatically handles the limit and continue pagination schemas, allowing Claude to traverse large clusters without hallucinating cursor tokens.

"Claude, check the 'production' namespace and list the first 10 pods. If any are in a CrashLoopBackOff state, pull their exact names so we can investigate the logs."

2. kubernetes_pods_get_log

Reads the log output of a specified pod. This is critical for automated incident response. The schema explicitly defines the name and namespace parameters required to fetch the correct log stream.

"Fetch the logs for the pod named 'auth-service-7f8b9-x2k9' in the 'security' namespace. Look for any database connection timeout errors in the last 100 lines."

3. kubernetes_events_list_all_namespaces

Lists cluster events across all namespaces. This is a highly privileged operation (requiring cluster-wide RBAC) that allows Claude to audit node evictions, OOM kills, and scheduling failures holistically.

"Audit the cluster events across all namespaces for the last hour. Summarize any warnings related to node memory pressure or pod evictions."

4. kubernetes_api_discovery_list_api_groups

Queries the Kubernetes API server to list all available API versions and groups. This is a powerful introspection tool that allows the LLM to discover what CRDs or specific API versions (e.g., networking.k8s.io/v1) the cluster supports before attempting to manipulate them.

"Check the available API groups in this cluster. Verify if the 'flowcontrol.apiserver.k8s.io/v1' group is enabled for priority level configurations."

5. kubernetes_deployments_update_scale

Replaces the scale subresource of a specified Deployment. This allows Claude to dynamically scale up application replicas during high load or scale them down to save costs.

"The frontend deployment in the 'web' namespace is experiencing high latency. Scale the deployment up to 5 replicas to handle the incoming traffic."

6. kubernetes_namespaces_patch_status

Partially updates the status of a specific namespace using a JSON Merge Patch. This tool enforces the strict application/merge-patch+json payload format required by Kubernetes for partial updates.

"Apply a JSON merge patch to update the status of the 'staging-env' namespace to indicate it is currently undergoing maintenance."

To view the complete inventory of available Kubernetes tools, including advanced operations for Custom Resource Definitions (CRDs), StatefulSets, and DaemonSets, visit the Kubernetes integration page.

Workflows in Action

Giving Claude access to your Kubernetes API via MCP enables complex, multi-step orchestration. Here is how an IT Admin or DevOps Engineer can leverage natural language to execute real-world workflows.

Workflow 1: Incident Triage and Log Analysis

When a service degrades, DevOps engineers waste precious minutes running kubectl commands to find the failing pod and extract logs. Claude can automate this entire diagnostic loop.

"The payments service is throwing 500 errors in the 'finance' namespace. Find the pods for this service, check their statuses, and pull the logs for any pod that has restarted recently. Summarize the exact stack trace causing the crash."

Tool Execution Sequence:

  1. list_all_kubernetes_pods (Filters for pods in the 'finance' namespace with the 'payments' label).
  2. Claude identifies a pod with a high restart count.
  3. kubernetes_pods_get_log (Fetches the log stream for that specific pod).
  4. Claude analyzes the text stream and returns a concise summary of the stack trace (e.g., "The pod is crashing due to a missing environment variable for the Stripe API key").
sequenceDiagram
    participant User as DevOps Engineer
    participant Claude as Claude Desktop
    participant Truto as Truto MCP Server
    participant K8s as Kubernetes API

    User->>Claude: "Find the crashing payments pod and check logs."
    Claude->>Truto: Call list_all_kubernetes_pods(namespace="finance")
    Truto->>K8s: GET /api/v1/namespaces/finance/pods
    K8s-->>Truto: Pod list (JSON)
    Truto-->>Claude: Pod list (MCP format)
    Claude->>Truto: Call kubernetes_pods_get_log(pod="payments-abc")
    Truto->>K8s: GET /api/v1/namespaces/finance/pods/payments-abc/log
    K8s-->>Truto: Log stream data
    Truto-->>Claude: Log data (MCP format)
    Claude-->>User: "Found missing ENV var in payments-abc logs."

Workflow 2: Automated Capacity Scaling

Handling sudden spikes in traffic often requires manual intervention if Horizontal Pod Autoscalers (HPA) are not reacting fast enough. Claude can audit the cluster events and execute a scaling operation safely.

"Check the cluster events for any CPU throttling warnings on the 'inventory-api' deployment in the 'backend' namespace. If it is struggling, scale the deployment up to 8 replicas."

Tool Execution Sequence:

  1. kubernetes_events_list_all_namespaces (Filters for events involving the 'inventory-api' deployment).
  2. Claude identifies warnings related to CPU limits being hit.
  3. kubernetes_deployments_get_scale (Checks the current replica count, e.g., 3).
  4. kubernetes_deployments_update_scale (Executes a payload to update the replica count to 8).
  5. Claude reports back that the scale command was successfully applied to mitigate the CPU throttling.

Security and Access Control

Exposing Kubernetes to an AI agent demands strict governance. Truto's MCP servers operate on a Zero Trust model with multiple layers of configuration to restrict what the LLM can do.

  • Method Filtering (config.methods): You can restrict an MCP server to specific operation types. For a purely diagnostic agent, set methods: ["read"]. The Truto tool generation engine will strip out all create, update, and delete tools, completely preventing Claude from modifying the cluster state.
  • Tag Filtering (config.tags): Group tools by functional area. You can configure the server to only expose tools tagged with networking or storage, preventing the LLM from accessing unrelated IAM or RBAC resources.
  • Extra Authentication (require_api_token_auth): By default, possessing the MCP URL grants access. By setting require_api_token_auth: true, the caller must also pass a valid Truto API token in the Authorization header, adding a mandatory secondary authentication layer for highly sensitive clusters.
  • Automatic Expiration (expires_at): For temporary access (e.g., granting an external contractor's agent access to a staging cluster for a sprint), set a strict ISO datetime. Cloudflare KV and durable alarms will permanently purge the server and token once the time expires, leaving no stale access vectors.

Handling Rate Limits and Errors

It is critical to understand how Truto handles Kubernetes API constraints.

Truto does not retry, throttle, or apply backoff on rate limit errors.

If your Kubernetes API server limits incoming requests to protect the control plane and returns an HTTP 429 Too Many Requests, Truto immediately passes that 429 error directly back to Claude. Truto automatically normalizes the upstream rate limit information into standardized IETF headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset).

The AI client or agent framework calling the MCP server is entirely responsible for reading these headers, pausing execution, and implementing its own retry or exponential backoff logic. Truto will not absorb these errors or queue requests on your behalf.

Wrap-Up

Connecting Claude to Kubernetes via MCP transforms how teams interact with their infrastructure. Instead of manually parsing YAML files, crafting jq queries, or navigating complex dashboard UIs, engineers can audit and scale cluster resources conversationally.

By leveraging Truto's managed MCP architecture, you avoid the technical debt of building custom JSON-RPC routers, maintaining OAuth lifecycles, and writing endless TypeScript definitions for Kubernetes CRDs. You define the access rules, generate the URL, and let Claude handle the orchestration.

Ready to give your AI agents secure, schema-driven access to Kubernetes? Book a demo with our engineering team today.

FAQ

How do I connect Kubernetes to Claude Desktop?
You can connect Kubernetes to Claude by generating a Model Context Protocol (MCP) server URL via Truto. You then add this URL to Claude Desktop's configuration file or through the Claude UI settings to expose Kubernetes API operations as AI tools.
Can Claude modify my Kubernetes cluster state?
Yes, if configured to allow write operations. You can restrict the MCP server to read-only methods to safely allow Claude to audit logs and events, or you can allow write methods so Claude can scale deployments or restart pods.
Does Truto handle Kubernetes API rate limits?
Truto normalizes rate limit headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset) per the IETF spec, but it does not automatically retry or absorb HTTP 429 errors. The caller is responsible for implementing retry and backoff logic.
How does the MCP server authenticate with Kubernetes?
The MCP server is scoped to a specific integrated account in Truto. Truto securely manages the underlying Kubernetes service account tokens or OAuth credentials, while exposing a tokenized MCP URL for the AI client.

More from our Blog