⚡ ~/naveed Tech Blog
⚡ Portfolio Home ✍️ Engineering Blog Deep Dives 🎯 Interview Hub 1,000+ Scenarios ☸️ Kubernetes Mastery Hub 24 Modules 🎮 DevOps Arcade & Quizzes Subnet Blitz ⚡ 🗺️ DevOps Roadmaps PDFs & Guides 🤖 Morpheus Analysis AI Quant ↗ 🛠️ Developer Tools Utilities 🧪 Labs & Experiments 📄 Interactive CV & Certs 🔗 All Links & Socials ⚡ Join The Dispatch (Weekly SRE Newsletter) →

MCP Server Tutorial for DevOps: Build Kubernetes Tools with the 2026 Spec

MCP server tutorial diagram showing Kubernetes tools connected to an AI client

This mcp server tutorial shows DevOps engineers how to build a stateless Model Context Protocol server in Python that exposes read only Kubernetes tools to AI clients. You will define typed tools, test them with MCP Inspector, secure the remote endpoint with OAuth 2.1, and deploy the server to Kubernetes with least privilege RBAC.

This mcp server tutorial shows DevOps engineers how to build a stateless Model Context Protocol server in Python that exposes read only Kubernetes tools to AI clients. You will define typed tools, test them with MCP Inspector, secure the remote endpoint with OAuth 2.1, and deploy the server to Kubernetes with least privilege RBAC.

What Does This MCP Server Tutorial Build for DevOps?

In this mcp server tutorial, you build a Python server that gives AI clients safe, read only access to Kubernetes pod and event data. The server exposes three typed tools, one runbook resource, and one triage prompt, then runs locally over stdio and remotely over Streamable HTTP with OAuth 2.1 checks.

Model Context Protocol, or MCP, gives AI clients a standard way to call tools, read context, and reuse prompt templates from a server you control. The host runs the model, the client speaks JSON-RPC to your server, and your server decides which capabilities exist. That split matters for DevOps work because cluster access stays behind code you review, test, and deploy.

This post builds a small server named k8s-mcp. It exposes three read only Kubernetes tools, one runbook resource, and one triage prompt. The same handlers run over stdio for local hosts and over Streamable HTTP for shared remote clients. Read only scope comes first, so a model can inspect pods and events without holding write access to a cluster.

PrimitiveWho starts itUse it forExample in this post
ToolModelActions and queries with typed inputslist_pods, describe_pod, list_events
ResourceClient or userRead only context by URIrunbook://crashloopbackoff
PromptUserRepeatable message templatestriage_pod

A common early mistake is to model every capability as a tool. If the model only needs to read stable guidance, a resource fits better. If a person should start a workflow on purpose, a prompt fits better. Tools stay narrow, typed, and easy to audit.

The safety line is simple. Start with read only tools, log every call, and add write tools only behind approval gates. Our ai agent guardrails for MCP write tools guide covers approval patterns for higher risk actions. This tutorial keeps the first release inspect only, which matches how platform teams usually pilot agent access.

By the end you will have server.py, a local Inspector test flow, a remote HTTP run mode, OAuth 2.1 wiring notes, and Kubernetes manifests with a least privilege ServiceAccount. The code targets the Python SDK v2 line and the 2026-07-28 MCP specification.

⚡ EXCLUSIVE SRE & KUBERNETES PLAYBOOK

The 970+ Incident Handbook & K8s Runbooks are exclusive to subscribers — unlock for FREE

Get battle-tested production runbooks, AWS architecture blueprints, and zero-downtime CI/CD post-mortems sent directly to your inbox. 100% free, no spam.

What Changed in the 2026 Spec for an MCP Server Tutorial?

In this mcp server tutorial, the 2026-07-28 spec is the baseline, so the server stays stateless at the protocol level. Clients send version and capability data with each request, discovery uses server/discover, and application state moves through explicit handles instead of a hidden session tied to one server instance.

The 2026-07-28 revision changed the protocol core from a stateful session model to a stateless request and response model. Older tutorials that start with an initialize handshake and a session header describe the 2025-11-25 era. Those pages can still teach tool design, but their transport and scaling advice needs a fresh read.

AreaBefore 2026-07-282026-07-28 baselineWhat your code does
Handshakeinitialize plus initialized noticeRemovedLet the SDK attach per request metadata
SessionMcp-Session-Id headerRemovedUse explicit handles for app state
DiscoveryCapabilities from initializeserver/discoverLet SDK v2 implement discovery
RoutingParse the JSON bodyMcp-Method and Mcp-Name headersLet gateways route on headers
ListsPlain list resultsttlMs and cacheScope fieldsTreat tool lists as cacheable data
Mid call inputServer requests over open streaminput_required plus requestStateRetry with answers and state token

Each modern request carries its protocol version, client information, and client capabilities in _meta. Results carry a resultType field. List results can carry cache hints, so clients can reuse a tool list for a short window instead of asking on every turn. When a tool needs missing input, Multi Round-Trip Requests let the server return input_required and close the exchange. The client collects answers and retries the call with an opaque requestState value.

Stateless protocol design does not ban application state. It moves state out of a hidden session and into explicit handles. A tool can return a job ID, a report ID, or a snapshot ID, and the next tool call passes that handle as a normal argument. Any healthy server instance can then answer the next request.

The spec also deprecated Roots, Sampling, Logging, the old HTTP plus SSE transport, and Dynamic Client Registration, with a minimum twelve month deprecation window. For Python authors, SDK v2 renamed the high level server class from FastMCP to MCPServer, and host plus port settings moved to the run call. If an import still points at the old fastmcp path, update the code before you debug anything else.

How Do You Set Up an MCP Server Tutorial Project in Python?

In this mcp server tutorial, setup takes Python 3.10 or newer, the mcp[cli] package, and the kubernetes client library. A small project layout keeps server code, requirements, and deployment files apart, while logging goes to stderr so stdio JSON-RPC traffic on stdout stays clean for local clients.

You need Python 3.10 or newer, a terminal, and access to a Kubernetes cluster for the tool tests. A local kind or minikube cluster works for practice. Production cluster access can wait until the deployment section, where RBAC limits keep the blast radius small.

Create the project and install the SDK with the cli extra, plus the Kubernetes client library:

mkdir k8s-mcp && cd k8s-mcp
python -m venv .venv
source .venv/bin/activate
pip install "mcp[cli]" kubernetes

Use this layout so local runs, tests, and deployment files stay easy to find:

k8s-mcp/
  server.py
  requirements.txt
  Dockerfile
  k8s/
    mcp-server.yaml

Pin the versions you test in requirements.txt before you ship. A loose install helps while learning, but a deployed server should record exact SDK and client versions so schema changes show up in review.

Start server.py with imports, logging to stderr, and the server object:

import logging
import os
import re
import sys

from kubernetes import client, config
from kubernetes.client.exceptions import ApiException
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

logging.basicConfig(level=logging.INFO, stream=sys.stderr)
log = logging.getLogger("k8s-mcp")

mcp = MCPServer("k8s-mcp")

Logging goes to stderr on purpose. Over stdio, stdout carries newline delimited JSON-RPC messages. A stray print or log line on stdout can break parsing and produce confusing client errors. Keep stdout for protocol traffic and send diagnostics to stderr or a file.

Two SDK habits shape the rest of the code. Type hints become the tool input schema, and docstrings become the descriptions the model reads when choosing a tool. Write docstrings like short API docs: say what the tool does, when to use it, when to avoid it, and what it returns. Vague descriptions lead to wrong tool choices and invented arguments.

How Do You Define Kubernetes Tools in an MCP Server Tutorial?

In this mcp server tutorial, each Kubernetes tool is a typed Python function with a clear docstring, strict input checks, and a small structured result. The tools list pods, describe one pod, and list recent events, and none of them can change cluster state during the first release.

The three tools answer the first questions in most pod incidents: which pods exist, what state is one pod in, and which recent events explain that state. Each tool validates input, calls the Kubernetes API through the official client, trims the result, and returns structured data. Structured returns help clients validate shape and help you write tests on fields instead of prose.

NAMESPACE_RE = re.compile(r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$")
POD_RE = re.compile(r"^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$")


def core_v1() -> client.CoreV1Api:
    try:
        config.load_incluster_config()
    except config.ConfigException:
        config.load_kube_config()
    return client.CoreV1Api()


def check_namespace(namespace: str) -> str:
    value = namespace.strip()
    if len(value) > 63 or not NAMESPACE_RE.match(value):
        raise ToolError("namespace must be a valid Kubernetes namespace name")
    return value


def check_limit(limit: int) -> int:
    if not 1 <= limit <= 100:
        raise ToolError("limit must be between 1 and 100")
    return limit


@mcp.tool()
def list_pods(namespace: str = "default", limit: int = 20) -> dict:
    """List pods in one namespace with phase, node, readiness, and restarts.

    Use this when the user asks which pods run in a namespace or which
    pods look unhealthy. Do not use it for cluster wide searches.
    Returns namespace, count, and a pods list.
    """
    namespace = check_namespace(namespace)
    limit = check_limit(limit)
    result = core_v1().list_namespaced_pod(namespace=namespace, limit=limit)
    pods = []
    for pod in result.items:
        statuses = pod.status.container_statuses or []
        pods.append({
            "name": pod.metadata.name,
            "phase": pod.status.phase,
            "node": pod.spec.node_name,
            "ready": sum(1 for item in statuses if item.ready),
            "containers": len(statuses),
            "restarts": sum(item.restart_count for item in statuses),
        })
    log.info("list_pods namespace=%s count=%s", namespace, len(pods))
    return {"namespace": namespace, "count": len(pods), "pods": pods}

describe_pod returns container state detail for one pod. A missing pod returns an ok false message the model can act on, such as asking the user to confirm the name. Invalid input raises ToolError. That split keeps expected cases readable and keeps protocol errors for real faults.

@mcp.tool()
def describe_pod(namespace: str, name: str) -> dict:
    """Describe one pod with container readiness, restarts, and state reasons.

    Use this after list_pods when one pod needs detail. Do not use it to
    fetch logs. Returns ok plus pod fields, or ok false with a next step.
    """
    namespace = check_namespace(namespace)
    if len(name) > 253 or not POD_RE.match(name.strip()):
        raise ToolError("name must be a valid pod name")
    try:
        pod = core_v1().read_namespaced_pod(name=name.strip(), namespace=namespace)
    except ApiException as error:
        if error.status == 404:
            return {"ok": False, "message": f"No pod {name} in {namespace}. Confirm the name and namespace."}
        raise ToolError(f"Kubernetes API error {error.status} while reading pod")
    containers = []
    for item in pod.status.container_statuses or []:
        state = item.state
        reason = None
        if state.waiting:
            reason = state.waiting.reason
        elif state.terminated:
            reason = state.terminated.reason
        containers.append({
            "name": item.name,
            "image": item.image,
            "ready": item.ready,
            "restarts": item.restart_count,
            "reason": reason,
        })
    return {
        "ok": True,
        "name": pod.metadata.name,
        "namespace": namespace,
        "phase": pod.status.phase,
        "node": pod.spec.node_name,
        "containers": containers,
    }

list_events adds the timeline. Event messages can grow long, so the tool caps each message and returns a small field set:

@mcp.tool()
def list_events(namespace: str = "default", limit: int = 20) -> dict:
    """List recent Kubernetes events in one namespace.

    Use this when a pod is pending, restarting, or failing probes.
    Returns reason, message, type, object name, and count per event.
    """
    namespace = check_namespace(namespace)
    limit = check_limit(limit)
    result = core_v1().list_namespaced_event(namespace=namespace)
    events = sorted(
        result.items,
        key=lambda item: str(item.last_timestamp or item.event_time or ""),
    )[-limit:]
    rows = []
    for event in events:
        rows.append({
            "reason": event.reason,
            "type": event.type,
            "object": event.involved_object.name,
            "count": event.count,
            "message": (event.message or "")[:300],
        })
    return {"namespace": namespace, "count": len(rows), "events": rows}

When describe_pod shows CrashLoopBackOff, pair the tool output with the Kubernetes CrashLoopBackOff troubleshooting guide and the Kubernetes production runbook atlas. The tools gather evidence. Runbooks turn evidence into a safe next step.

How Do Resources and Prompts Work in an MCP Server Tutorial?

In this mcp server tutorial, resources carry read only context and prompts carry repeatable user invoked workflows. A CrashLoopBackOff runbook resource gives the model stable guidance, while a triage prompt tells the client which tools to call, what evidence to cite, and where human approval must stop automation.

Resources and prompts keep the tool list small. A resource exposes read only context by URI, such as a runbook, a config summary, or a service inventory snapshot. A prompt packages a repeatable workflow that a user starts on purpose, such as a pod triage sequence. The model still calls tools for live data, but stable guidance lives in one reviewed place.

Add a CrashLoopBackOff runbook resource:

@mcp.resource("runbook://crashloopbackoff")
def crashloop_runbook() -> str:
    """Return the CrashLoopBackOff triage runbook."""
    return (
        "CrashLoopBackOff triage: 1) Call describe_pod and note the waiting "
        "reason and restart count. 2) Call list_events for probe, image, and "
        "scheduling messages. 3) Separate app exit, probe failure, and image "
        "pull causes before suggesting a fix. 4) Stop before any write action "
        "and ask a human to approve changes."
    )

Add a triage prompt that orders the evidence gathering:

@mcp.prompt()
def triage_pod(namespace: str, pod: str) -> str:
    """Build a pod triage prompt for one namespace and pod."""
    return (
        f"Triage pod {pod} in namespace {namespace}. First call describe_pod, "
        "then call list_events for the same namespace. Read the "
        "runbook://crashloopbackoff resource if the waiting reason matches. "
        "Cite the exact phase, restart count, and event reasons you used. "
        "Suggest read only checks first and stop before any change."
    )
NeedPrimitiveReason
Live cluster dataToolInputs vary and results change
Stable guidance textResourceClients can read and cache it
Repeatable investigationPromptUser starts the workflow on purpose
Change to cluster stateTool with approvalSide effects need gates and audit

Treat resource text and tool output as untrusted input when they contain cluster data, logs, or issue text. A pod name, event message, or annotation can carry instructions aimed at the model. Keep the prompt instruction to cite evidence and stop before changes, and review the patterns in AI agents for DevOps runbooks before you add automation around these tools.

How Do You Test an MCP Server Tutorial Build with MCP Inspector?

In this mcp server tutorial, MCP Inspector is the first test client because it shows schemas, raw responses, and error text without model behaviour in the loop. Test valid calls, invalid namespaces, missing pods, resource reads, and prompt output before you connect a desktop host or agent framework.

Test the server without a model first. MCP Inspector connects straight to the server, lists tools, resources, and prompts, and lets you call tools with hand written inputs while showing raw responses. That separation keeps schema bugs apart from model behaviour.

Run the Inspector through the SDK cli extra:

mcp dev server.py

If the cli extra is missing, install mcp[cli] again inside the active virtual environment. An npx based Inspector launch also works on machines with Node, but the SDK command keeps Python and Inspector versions close.

Work through this checklist in order:

TestInputPass signal
Tool discoveryOpen the tools listThree tools with clear schemas
Valid list callnamespace default, limit 5Count plus pod rows
Invalid namespacenamespace with spacesToolError text the model can use
Missing poddescribe_pod with a fake nameok false plus a confirm step
Resource readrunbook://crashloopbackoffRunbook text returns
Prompt buildtriage_pod with a real podPrompt names tools in order

Fix description and schema problems at this stage. If a parameter name confuses you in Inspector, it will confuse a model later. Rename tools and arguments before hosts bind to them, because the tool list becomes a public API once clients depend on it.

After Inspector passes, connect a local host over stdio. A desktop host config points at the virtual environment Python and the server file:

{
  "mcpServers": {
    "k8s-mcp": {
      "command": "/path/to/k8s-mcp/.venv/bin/python",
      "args": ["/path/to/k8s-mcp/server.py"]
    }
  }
}

Restart the host, ask for pods in a namespace you know, and compare the answer with kubectl output:

kubectl get pods -n default
kubectl get events -n default --sort-by=.lastTimestamp

Matching evidence across Inspector, the host answer, and kubectl gives you a clean baseline before remote hosting enters the picture.

How Do You Run an MCP Server Tutorial Server over Streamable HTTP?

In this mcp server tutorial, stdio serves local hosts that launch the server as a subprocess, while Streamable HTTP serves shared remote clients. The stateless HTTP design lets any healthy instance answer any request, so round robin load balancing, autoscaling, and rolling deploys work without sticky sessions or shared session storage.

The spec defines two standard transports. stdio launches the server as a subprocess and exchanges newline delimited JSON-RPC over stdin and stdout. Streamable HTTP sends each message as an HTTP POST to a single MCP endpoint and returns JSON or a request scoped stream. Same handlers, different threat model.

QuestionstdioStreamable HTTP
Best fitLocal desktop hosts and IDE toolsShared remote clients and teams
Network surfaceNoneOne HTTP endpoint
Auth modelEnvironment credentialsOAuth 2.1 token checks
ScalingOne process per hostMany instances behind a load balancer
Session needProcess lifetimeStateless requests, explicit handles

Add a transport switch at the end of server.py:

if __name__ == "__main__":
    transport = os.environ.get("MCP_TRANSPORT", "stdio")
    if transport == "streamable-http":
        mcp.run(
            transport="streamable-http",
            host="0.0.0.0",
            port=int(os.environ.get("PORT", "8000")),
        )
    else:
        mcp.run(transport="stdio")

Run the remote mode locally for a smoke test:

MCP_TRANSPORT=streamable-http PORT=8000 python server.py

Stateless requests change operations work. A load balancer can use round robin routing because no request depends on a session stored in one process. Rolling deploys can replace instances without draining protocol sessions. Autoscaling can add replicas during incident traffic, when many engineers ask the same cluster questions at once.

Keep two limits in view. First, application state still needs a home when a workflow spans calls, so return explicit handles and store records in a database or object store. Second, an HTTP endpoint is reachable by anyone who finds the URL. Ship token validation in the same change as HTTP hosting, not as a later cleanup.

How Do You Secure an MCP Server Tutorial Deployment with OAuth 2.1?

In this mcp server tutorial, remote security starts with OAuth 2.1 because the MCP server acts as a resource server, not an identity provider. Validate issuer, audience, expiry, and scope on every request, return clear 401 challenges, keep scopes read only, and never pass client tokens to downstream APIs.

Authorization applies to HTTP transports. A protected MCP server acts as an OAuth 2.1 resource server. It validates access tokens from an authorization server and serves tools when checks pass. It does not own login screens and it does not issue tokens. stdio servers take credentials from the environment instead, because the host already trusts the subprocess it launched.

Wire the SDK auth settings with your identity provider values:

from mcp.server.auth.settings import AuthSettings

mcp = MCPServer(
    "k8s-mcp",
    token_verifier=MyTokenVerifier(),
    auth=AuthSettings(
        issuer_url="https://auth.example.com",
        resource_server_url="https://mcp.example.com",
        required_scopes=["k8s:read"],
    ),
)

MyTokenVerifier is your JWT or introspection check. It must verify the signature, issuer, audience, expiry, and scope on every request. Audience checks matter: a token issued for another resource must fail here, even when the signature is valid. Invalid or expired tokens return 401 with a WWW-Authenticate challenge so clients can discover the authorization server through Protected Resource Metadata under RFC 9728.

Follow these rules for remote access:

  • Publish a small scope set, starting with k8s:read for the tools in this post.
  • Never pass a client token through to the Kubernetes API or any downstream API.
  • Use a separate upstream credential with its own least privilege policy.
  • Ask for more scope with an insufficient scope challenge instead of widening tokens by default.
  • Keep write tools behind human approval, with a plan first and a confirm step second.
  • Log tool name, scope, namespace, result status, and a correlation ID for each call.
  • Return short error text with no stack traces, tokens, or secret values.

Authorize each call against the end user scope, not only the server credential. A confused deputy bug lets one user borrow server power that the user never held. Narrow tools plus scope checks keep that risk contained. When a future tool can restart a deployment or edit a ConfigMap, treat it as a change tool from day one: approval gate, audit record, and rollback note.

How Do You Deploy an MCP Server Tutorial Server to Kubernetes?

In this mcp server tutorial, Kubernetes deployment uses a small container image, two replicas, a ClusterIP Service, and a ServiceAccount bound to a Role that can only get, list, and watch pods and events. TLS, rate limits, and network policy sit at the platform edge for remote access.

Package the server like any other platform service: small image, non root user, health checks, resource limits, and a ServiceAccount that can only read pods and events. Build the image from a slim Python base:

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY server.py .
RUN useradd --uid 10001 appuser
USER appuser
EXPOSE 8000
CMD ["python", "server.py"]

Save the manifests as k8s/mcp-server.yaml. The Role grants get, list, and watch on pods and events in one namespace. No create, update, patch, or delete verbs appear, so the tools cannot change cluster state even if a prompt asks them to try.

apiVersion: v1
kind: Namespace
metadata:
  name: mcp-tools
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: k8s-mcp
  namespace: mcp-tools
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: k8s-mcp-read
  namespace: mcp-tools
rules:
  - apiGroups: [""]
    resources: ["pods", "events"]
    verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: k8s-mcp-read
  namespace: mcp-tools
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: k8s-mcp-read
subjects:
  - kind: ServiceAccount
    name: k8s-mcp
    namespace: mcp-tools
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: k8s-mcp
  namespace: mcp-tools
spec:
  replicas: 2
  selector:
    matchLabels:
      app: k8s-mcp
  template:
    metadata:
      labels:
        app: k8s-mcp
    spec:
      serviceAccountName: k8s-mcp
      containers:
        - name: server
          image: ghcr.io/example/k8s-mcp:1.0.0
          ports:
            - containerPort: 8000
          env:
            - name: MCP_TRANSPORT
              value: streamable-http
            - name: PORT
              value: "8000"
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              cpu: 500m
              memory: 256Mi
          readinessProbe:
            tcpSocket:
              port: 8000
            initialDelaySeconds: 3
            periodSeconds: 5
          securityContext:
            runAsNonRoot: true
            allowPrivilegeEscalation: false
            capabilities:
              drop: ["ALL"]
---
apiVersion: v1
kind: Service
metadata:
  name: k8s-mcp
  namespace: mcp-tools
spec:
  selector:
    app: k8s-mcp
  ports:
    - port: 8000
      targetPort: 8000

Replace the example image with your registry path, then apply and watch the rollout:

docker build -t ghcr.io/example/k8s-mcp:1.0.0 .
docker push ghcr.io/example/k8s-mcp:1.0.0
kubectl apply -f k8s/mcp-server.yaml
kubectl rollout status deployment/k8s-mcp -n mcp-tools
kubectl port-forward svc/k8s-mcp -n mcp-tools 8000:8000

Terminate TLS at your ingress or gateway, add rate limits per client, and restrict network policy so only approved clients reach the Service. For per environment image tags and replica counts, manage overlays with the Kustomize Kubernetes guide for overlays pattern instead of copying YAML per cluster.

Why Does an MCP Server Tutorial Server Fail and How Do You Fix It?

In this mcp server tutorial, most failures come from SDK version drift, stdout logging on stdio, token audience mismatch, missing RBAC verbs, or stale tool lists. The troubleshooting table maps each symptom to a likely cause and a fix, then production rules keep tool schemas versioned like a public API.

Most early failures fall into a short list. Work from the transport inward: process start, Inspector discovery, tool call, Kubernetes API result, then host behaviour. That order keeps one fault from hiding behind another.

SymptomLikely causeFix
ModuleNotFoundError for fastmcp importSDK v2 renamed the server classImport MCPServer from mcp.server
Inspector cannot connect over stdioLogs or prints reached stdoutSend logs to stderr and remove prints
Tool missing from the listDecorator missing or stale cached listCheck @mcp.tool() and restart the client
Model picks the wrong toolVague docstring or broad tool scopeState use, avoid, and return fields
HTTP calls return 401Issuer, audience, expiry, or scope mismatchValidate token claims against IdP metadata
Kubernetes API returns forbiddenRole lacks a verb or namespace scopeAdd get, list, watch for pods and events
Pod list returns emptyWrong namespace or kube contextCompare with kubectl get pods in that namespace
Legacy client handshake errorsClient expects the old session flowUpgrade the client or SDK to the 2026 baseline

Keep these production rules from the first release:

  • Pin SDK and Kubernetes client versions, and review schema diffs in pull requests.
  • Version the tool list like a public API. Renames break hosts that bind to tool names.
  • Log server version and a hash of each tool schema at startup.
  • Tag every call with a correlation ID and record scope, namespace, and status.
  • Test invalid input and missing resource cases in CI, not only happy paths.
  • Cap result sizes so one call cannot flood model context with event text.
  • Keep read only scopes until approval, audit, and rollback paths exist for write tools.

A small read only server earns trust fast because engineers can compare every answer with kubectl. Add tools in that spirit: one narrow capability at a time, tested in Inspector, secured before remote use, and measured with real incident questions. The next step is a second read only tool set, such as deployment status or node conditions, behind the same scope and RBAC pattern.

Frequently Asked Questions

Direct answers to common technical, architectural, and production troubleshooting questions.

What is an MCP server, and what does this mcp server tutorial build?

An MCP server exposes tools, resources, and prompts that AI clients can call through JSON-RPC. This tutorial builds a Python server with three read only Kubernetes tools, one runbook resource, and one triage prompt, tested locally with MCP Inspector and deployed with least privilege RBAC.

Is MCP stateless in the 2026 spec used by this mcp server tutorial?

Yes. The 2026-07-28 spec removed the initialize handshake and the session header. Each request carries version and capability data, discovery uses server/discover, and application state moves through explicit handles. Any healthy server instance can answer any request.

How do you test the server from this mcp server tutorial?

Run mcp dev server.py to open MCP Inspector. Check tool schemas, call each tool with valid and invalid inputs, read the runbook resource, and build the triage prompt. Compare results with kubectl output before connecting a desktop host or agent framework.

How do you secure a remote server from this mcp server tutorial?

Run Streamable HTTP behind OAuth 2.1 token checks. The server acts as a resource server and validates signature, issuer, audience, expiry, and scope on every request. Keep scopes read only, return 401 challenges for bad tokens, and never pass client tokens downstream.

Can the Kubernetes tools in this mcp server tutorial change a cluster?

No. The tools only list pods, describe one pod, and list events. The deployment Role grants get, list, and watch on pods and events, with no write verbs. Add change tools later only with approval gates, audit logs, and a rollback path.

Naveed Ahmed

Naveed Ahmed (Kumbhar)

Senior DevOps & Cloud Engineer with 10+ years specializing in AWS, Kubernetes, Platform Engineering, SRE incident response, and autonomous AI infrastructure agents.

Passionate about cloud architecture & systems engineering? Connect on LinkedIn →