Skip to content
MCPA · Chapter 16 of 21 Day 14: Audit and observability

Day 14: Audit and observability

Goal: Log every call to an MCP server verifiably, trace calls across machine boundaries with OpenTelemetry, run a server with several replicas on Kubernetes, and put a gateway with rules and limits in front of it · Duration: about 3 h · Prerequisite: Day 8

Where we start

# on cp1
ls ~/mcpa/pyproject.toml

Expected: /home/ubuntu/mcpa/pyproject.toml

# on worker1
ls ~/mcpa/pyproject.toml

Expected: /home/ubuntu/mcpa/pyproject.toml

These are the two uv projects from Day 0 (cp1) and Day 8 (worker1). If one is missing, create it as described there. Today you need neither Keycloak nor the servers from Days 12 and 13: stop them if they are still running. On cp1 and worker1 you need two terminals each.

Introduction

So far every server ran as a single process, and when something went wrong, you looked at its terminal. In production that is not enough. There, someone asks weeks later: who restarted the print service on Tuesday at 14:45, for what reason, through which host? Or: why did the agent’s answer take twelve seconds yesterday – was it the model, the network or a tool? And the server no longer runs once but three times on Kubernetes, behind a gateway that does not even let some calls through.

Today you build all of this. The server leitwarte (control center) writes one line per request into an audit log. With OpenTelemetry you trace an operation from the client across three pods into the tools. You set up k3s on the three VMs, run leitwarte there with three replicas and show that a client without a session is spread across all three. In front of it you put Traefik as a gateway that decides based on the Mcp-Method and Mcp-Name headers – and you find a way to bypass it yourself.

Today you learn:

  • what belongs in an MCP server’s audit log and what must never go there,
  • how you capture every request in one place with an SDK server middleware,
  • why clientInfo is not an identity,
  • how the specification transports Trace Context in _meta and what the SDK does with it,
  • why an MCP server after 2026-07-28 runs with several replicas without sticky sessions,
  • how a gateway filters based on Mcp-Method and Mcp-Name, and why the server must still compare header and body,
  • how you set rate limits, size limits and resource limits.

Background

The picture for today: house ledger, routing slip and doorman

Stay in the hotel from the previous days: the front desk (the host) orders services from outside providers (the servers). Today the hotel grows, and three things are added.

  • The house ledger at the front desk is the audit log. Every order goes in: who, what, when, with what result – and who signed. What a guest writes on their own slip (“I am the director”) does not count; what counts is the checked ID (the token).
  • The routing slip is the trace. It carries a case number (trace ID) and travels with the order through every department. Each department stamps its work step on it (a span). At the end you see where the time went.
  • The doorman at the entrance is the gateway. He only reads the label on the envelope (Mcp-Method, Mcp-Name) and turns some messengers away at once. Because label and content do not have to match, the provider inside still checks for itself.

And because every order carries everything on its slip (_meta), any of three counters (replicas) can serve any messenger.

The terms

Term Meaning in the picture
audit log complete, tamper-proof record of every request house ledger
sub / azp from the token who (person) and through which client checked ID
clientInfo the client’s self-description, not an identity what the guest writes on the slip
trace / span path of a request / one work step on it routing slip / stamp
traceparent in _meta trace ID and parent span for the next service case number on the slip
replica one of several identical copies of the server counter
gateway checks requests by their headers before the server doorman
rate limit / size limit requests per time / bytes per request orders per minute / letter slot

Remember: Who did something is in the checked token, not in clientInfo. And what the doorman reads on the envelope, the server must compare with the content.

Audit and observability

The two terms sound similar but serve different purposes.

  • Audit means evidence. An audit log later answers, often months later, the questions who, what, when, with what, with which result. It must be complete, must not be modifiable afterwards, and is retained according to fixed rules. Its readers are internal audit, security and sometimes a court.
  • Observability means understanding ongoing operations: logs, metrics and traces. It may sample and discard old data. Its readers are the people who operate the service.

A good entry in an MCP server’s audit log contains:

Field Source Why
Time (UTC, milliseconds) server clock order, correlation with other logs
Who sub and azp from the verified token (Day 12) the human and the client they came through
Method and tool method, params.name what was done
Arguments params.arguments, sanitized with what; secrets only as a fingerprint
Result isError, JSON-RPC error, exception whether it worked
Duration measured anomalies, timeouts
Correlation trace ID, request ID, ticket from _meta link to traces and to the case
Approval the human’s consent (Day 11) who allowed something dangerous

What does not belong in it: access tokens, passwords, approval codes in plain text, and large content with personal data. An audit log is itself a worthwhile target: whoever can read it must find nothing in it that lets them sign in.

It is also important what is not an identity. The client itself writes the field io.modelcontextprotocol/clientInfo in _meta. Anyone can put any name there. It is useful for statistics (“which hosts use us?”), not as evidence. Who did something is in the verified token.

The specification also knows logging over the protocol: a server sends messages to the client with notifications/message. That is not an audit log – the messages end up at the client, not in your storage – and with 2026-07-28 this logging is deprecated. The server writes the audit log itself, on its own side.

Trace Context in _meta

A trace is the path of a request through all participating services. It consists of spans: each span is a unit of work with a start, an end, a name and attributes, and belongs to its trace via a trace ID. Via the parent’s span ID, the spans hang together in a tree.

For a server to attach its span under the client’s span, the client must send it the trace ID and span ID. The standard for this is W3C Trace Context with the traceparent field:

00-b6002d6d2ae03ffc3fc7480e7001c581-6a3c0e2f1b9d4c77-01

These are four parts, separated by -: the version 00, the trace ID (32 hex characters), the caller’s span ID (16 hex characters) and flags (01 = sampled).

With HTTP, traceparent normally sits in a header. But MCP also runs over stdio, where there are no headers. That is why the specification reserved the keys traceparent, tracestate and baggage in _meta for OpenTelemetry – without a prefix, as the only exception to the rule from Day 2. If they are present, their values must follow the W3C formats. They are not mandatory.

The Python SDK 2.3.0 already includes this:

  • The client opens a span MCP send <method> <name> for every request and writes traceparent into _meta.
  • The server reads traceparent in its built-in OpenTelemetryMiddleware and opens a span <method> <name> as a child of the client span. It sets attributes such as mcp.method.name, mcp.protocol.version, jsonrpc.request.id and, for tools, gen_ai.operation.name=execute_tool and gen_ai.tool.name. The names come from OpenTelemetry’s Semantic Conventions for generative AI and MCP, so that tools like Jaeger recognize them.

The SDK depends only on opentelemetry-api. Without the opentelemetry-sdk package and an exporter, everything is a no-op and costs nothing. Only when you set up a TracerProvider with an exporter do the spans go anywhere – today via OTLP (OpenTelemetry Protocol) over HTTP to Jaeger.

Several replicas and the gateway

Until 2025-11-25, MCP over HTTP had sessions (Mcp-Session-Id). If three replicas were running, a load balancer had to send each client to the same one every time (sticky sessions). Since 2026-07-28, every request carries everything the server needs in _meta. Every replica can answer every request. For Kubernetes this means: an ordinary Deployment, a Service, done.

State that you keep in the server, however, remains your responsibility. This includes handles from Day 5, open streams of subscriptions/listen from Day 9 and the sealed requestState from Day 10.

A gateway sits in front of the servers and enforces rules before a request reaches a server. So that it does not have to parse the JSON body for this, Streamable HTTP mirrors the most important fields into headers: Mcp-Method (always) and Mcp-Name (for tools/call, resources/read, prompts/get). The specification explicitly names them for load balancers, gateways and observability tools. Two rules make this safe:

  1. A server that processes the body must reject requests where header and body do not match – with HTTP 400 and -32020 HeaderMismatch (Day 8).
  2. Values that are not suitable as plain header text are encoded as =?base64?…?=. Whoever evaluates the header must decode it before comparing – the server and the gateway.

You will see in Drill 5 what happens when the gateway does not know rule 2.

Limits

An MCP server that a language model can reach gets load no human would produce: an agent in a loop calls the same tool a hundred times a minute, or a model packs a whole document into one argument. Limits therefore belong in every layer:

Layer Limit Response when exceeded
Gateway requests per time (rate limit) 429 Too Many Requests
Gateway size of the body 413 Request Entity Too Large
Gateway block tools 403 Forbidden
Server argument validation, time limits in the tool isError
Kubernetes CPU and memory per pod throttling, OOM kill

The specification requires “reasonable bounds” in several places, for example for the depth of JSON schemas, and, for intermediaries that throttle per tenant, the check of MCP-Protocol-Version. It does not specify how high the limits are.

Drill 1: An audit log as middleware

Where you are: on worker1 in the first terminal, then on cp1.

What you have afterwards: the server leitwarte on worker1, port 8010, which logs every request as a JSON line, and a client einsatz.py (operation) on cp1.

Step 1 – install OpenTelemetry. leitwarte and the client only need the packages from Drill 4 onward. You install them right away so the files do not change again today.

# on worker1
cd ~/mcpa
# on worker1
uv add opentelemetry-sdk==1.45.2 opentelemetry-exporter-otlp-proto-http==1.45.2
  • uv add adds packages to pyproject.toml and installs them into .venv.
  • opentelemetry-sdk is the implementation of the OpenTelemetry API: TracerProvider, span processors.
  • opentelemetry-exporter-otlp-proto-http sends spans via OTLP over HTTP.
  • ==1.45.2 pins the versions so your output matches this book.

Expected (excerpt, the numbers may differ):

Resolved 53 packages in 320ms
Installed 13 packages in 42ms
 + opentelemetry-exporter-otlp-proto-http==1.45.2
 + opentelemetry-sdk==1.45.2

Step 2 – the server.

# on worker1
mkdir -p ~/mcpa/tag14 && cd ~/mcpa/tag14
# on worker1
nano leitwarte.py
leitwarte.py new file
import hashlib
import json
import os
import socket
import time
from datetime import UTC, datetime

from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp.server.transport_security import TransportSecuritySettings
from mcp.types import ToolAnnotations
from opentelemetry import trace

POD = socket.gethostname()
DIENSTE = {"druckdienst", "zeiterfassung", "kantinenplan"}
# arguments whose value must never go into the log in plain text
VERTRAULICH = {"freigabecode"}

if os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT"):
    # only if a target is set: send spans via OTLP (Drill 4)
    from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
    from opentelemetry.sdk.trace import TracerProvider
    from opentelemetry.sdk.trace.export import BatchSpanProcessor

    anbieter = TracerProvider()
    anbieter.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
    trace.set_tracer_provider(anbieter)

tracer = trace.get_tracer("leitwarte")


def unkenntlich(name: str, wert: object) -> object:
    """Vertrauliche Werte durch einen Fingerabdruck ersetzen."""
    if name in VERTRAULICH:
        return "sha256:" + hashlib.sha256(str(wert).encode()).hexdigest()[:12]
    return wert


class AuditLog:
    """Schreibt pro Anfrage eine JSON-Zeile: wer, was, womit, mit welchem Ergebnis."""

    async def __call__(self, ctx, call_next):
        if ctx.request_id is None:  # do not log notifications
            return await call_next(ctx)
        beginn = time.perf_counter()
        meta = ctx.meta or {}
        params = ctx.params or {}
        argumente = params.get("arguments") or {}
        span = trace.get_current_span().get_span_context()
        eintrag = {
            "zeit": datetime.now(UTC).isoformat(timespec="milliseconds"),
            "pod": POD,
            "methode": ctx.method,
            "werkzeug": params.get("name"),
            "argumente": {k: unkenntlich(k, v) for k, v in argumente.items()},
            "client": meta.get("io.modelcontextprotocol/clientInfo", {}).get("name"),
            "ticket": meta.get("de.itdrills/ticket"),
            "trace_id": format(span.trace_id, "032x") if span.is_valid else None,
        }
        try:
            ergebnis = await call_next(ctx)
            # here the result already arrives as a dict, exactly as it goes on the wire
            fehler = isinstance(ergebnis, dict) and ergebnis.get("isError") is True
            eintrag["ergebnis"] = "fehler" if fehler else "ok"
            return ergebnis
        except Exception as ausnahme:
            eintrag["ergebnis"] = f"abgelehnt: {type(ausnahme).__name__}"
            raise
        finally:
            eintrag["dauer_ms"] = round((time.perf_counter() - beginn) * 1000, 1)
            print(json.dumps(eintrag, ensure_ascii=False), flush=True)


mcp = MCPServer(
    "leitwarte",
    instructions="Leitwarte für interne Dienste: Auskunft und Neustarts.",
    middleware=[AuditLog()],
)


@mcp.tool(title="Wo bin ich", annotations=ToolAnnotations(read_only_hint=True))
def wo_bin_ich() -> str:
    """Nennt den Rechner bzw. Pod, der diese Anfrage beantwortet."""
    return f"Antwort von {POD}"


@mcp.tool(title="Dienst neu starten", annotations=ToolAnnotations(destructive_hint=True))
def dienst_neustarten(dienst: str, grund: str, freigabecode: str) -> str:
    """Startet einen internen Dienst neu. Braucht einen Freigabecode aus dem Change."""
    if dienst not in DIENSTE:
        raise ToolError(f"Unbekannter Dienst {dienst}. Bekannt: {sorted(DIENSTE)}")
    return f"{dienst} auf {POD} neu gestartet (Grund: {grund})"


@mcp.tool(title="Bericht", annotations=ToolAnnotations(read_only_hint=True))
def bericht(sekunden: float = 1.0) -> str:
    """Erstellt einen Lagebericht. Das Sammeln der Daten dauert einige Sekunden."""
    with tracer.start_as_current_span("daten_sammeln") as span:
        span.set_attribute("leitwarte.sekunden", sekunden)
        time.sleep(sekunden)
    with tracer.start_as_current_span("bericht_schreiben"):
        time.sleep(0.1)
    return f"Lage ruhig, alle {len(DIENSTE)} Dienste laufen ({POD})"


erlaubt = os.environ.get("ERLAUBTE_HOSTS", "worker1:8010,172.16.0.228:8010").split(",")
schutz = TransportSecuritySettings(
    enable_dns_rebinding_protection=True, allowed_hosts=erlaubt, allowed_origins=[]
)

mcp.run(
    transport="streamable-http", host="0.0.0.0", port=8010, transport_security=schutz
)

The file has four parts.

Preparation. POD is the host name – on worker1 worker1, later in Kubernetes the name of the pod. DIENSTE (services) is the list of services that may be restarted. VERTRAULICH (confidential) names arguments whose value must never go into the log in plain text. The block with OTEL_EXPORTER_OTLP_ENDPOINT sets up OpenTelemetry only if this environment variable is set. Until Drill 4 it is not, and everything runs without traces. trace.get_tracer("leitwarte") returns an object you use to open your own spans. Without a TracerProvider they are no-ops.

unkenntlich (unrecognizable) replaces the value of a confidential argument with the first 12 hex characters of its SHA-256 hash. The value cannot be computed back from the hash. But whoever knows the value – for example internal audit with the change ticket – can check whether exactly this code was used.

AuditLog is a server middleware. The SDK calls await middleware(ctx, call_next) for every incoming message. The middleware sees the request before the SDK validates it and hands it to the tool, and calls the rest of the chain with await call_next(ctx). What call_next returns is the result. What it raises is an error. MCPServer(middleware=[…]) appends the list after the SDK’s built-in middlewares, including the one for OpenTelemetry. That is why the server span is already open when AuditLog runs. The fields in detail:

  • ctx.request_id is None for notifications. We do not log those.
  • ctx.method is the JSON-RPC method, ctx.params the raw parameters as a dict, not yet validated. name and arguments come from there.
  • ctx.meta is _meta from the request. The client entered io.modelcontextprotocol/clientInfo itself. de.itdrills/ticket is a custom key with its own prefix, as described in Day 2.
  • trace.get_current_span().get_span_context() returns the currently open span. If it is valid, its trace ID goes into the log as 32 hex characters (format(…, "032x")), otherwise None.
  • try … except … finally ensures that a line is written in every case: ok, fehler (error) for a tool result with isError, or abgelehnt (rejected) with the exception type for a JSON-RPC error. raise then re-raises the exception unchanged.
  • time.perf_counter() is a clock for time measurements. The difference times 1000 gives milliseconds.
  • print(json.dumps(…), flush=True) writes one line of JSON to standard output. One line per event (JSON Lines) can be evaluated with grep and jq and read by any log collector. ensure_ascii=False keeps umlauts as they are.

The tools. wo_bin_ich (where am I) says who answers. dienst_neustarten (restart service) only pretends to restart and raises a ToolError for an unknown service. bericht (report) opens two spans of its own, daten_sammeln (collect data) and bericht_schreiben (write report), so that in Drill 4 you see how the time is distributed within a tool. span.set_attribute attaches a value to the span.

At the end the server reads the allowed host names from ERLAUBTE_HOSTS. Without the variable, worker1:8010 and the IP apply – as in Day 8.

Step 3 – start the server.

# on worker1, in ~/mcpa/tag14
uv run python leitwarte.py

Expected (at the end):

INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:8010 (Press CTRL+C to quit)

Step 4 – the client. On cp1 you install the same packages and create einsatz.py: an operation with a ticket number calls four tools.

# on cp1
cd ~/mcpa
# on cp1
uv add opentelemetry-sdk==1.45.2 opentelemetry-exporter-otlp-proto-http==1.45.2
# on cp1
mkdir -p ~/mcpa/tag14 && cd ~/mcpa/tag14
# on cp1
nano einsatz.py
einsatz.py new file
import asyncio
import os
import sys

from mcp import Client
from mcp.types import Implementation
from opentelemetry import trace

URL = os.environ.get("LEITWARTE_URL", "http://worker1:8010/mcp")
TICKET = sys.argv[1] if len(sys.argv) > 1 else "CHG-1001"

if os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT"):
    from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
    from opentelemetry.sdk.trace import TracerProvider
    from opentelemetry.sdk.trace.export import BatchSpanProcessor

    anbieter = TracerProvider()
    anbieter.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
    trace.set_tracer_provider(anbieter)

tracer = trace.get_tracer("einsatz")
AUFRUFE = [
    ("wo_bin_ich", {}),
    ("dienst_neustarten", {"dienst": "druckdienst", "grund": "hängt", "freigabecode": "7731"}),
    ("dienst_neustarten", {"dienst": "mailserver", "grund": "Test", "freigabecode": "7731"}),
    ("bericht", {"sekunden": 1.5}),
]


async def main() -> None:
    kennung = Implementation(name="einsatz-cli", version="1.0")
    with tracer.start_as_current_span(f"einsatz {TICKET}") as span:
        span.set_attribute("leitwarte.ticket", TICKET)
        async with Client(URL, client_info=kennung) as client:
            for werkzeug, argumente in AUFRUFE:
                ergebnis = await client.call_tool(
                    werkzeug, argumente, meta={"de.itdrills/ticket": TICKET}
                )
                art = "FEHLER" if ergebnis.is_error else "OK"
                print(f"{werkzeug} [{art}]: {ergebnis.content[0].text}")
        trace_id = span.get_span_context().trace_id
        if trace_id:
            print(f"trace_id={trace_id:032x}")
    if os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT"):
        anbieter.shutdown()  # send buffered spans before the program ends


asyncio.run(main())
# on cp1
uv run python einsatz.py CHG-1001

What is new:

  • URL comes from the environment variable LEITWARTE_URL, otherwise it is the server on worker1. In Drill 3 you point at Kubernetes this way without changing the file. sys.argv[1] is the ticket number from the command line.
  • Client(URL, client_info=Implementation(name=…, version=…)) sets what the client says about itself in io.modelcontextprotocol/clientInfo.
  • client.call_tool(werkzeug, argumente, meta={…}) sends custom entries in _meta. The SDK adds the protocol’s keys itself.
  • tracer.start_as_current_span(name) opens a span that lasts until the end of the with block. All calls inside become its children. Without a TracerProvider its trace ID is 0, which is why the program prints it only when it is set.
  • anbieter.shutdown() flushes the buffer of the BatchSpanProcessor. It collects spans and sends them in batches. A short program must wait for it before ending, otherwise the last spans are lost.

Expected:

wo_bin_ich [OK]: Antwort von worker1
dienst_neustarten [OK]: druckdienst auf worker1 neu gestartet (Grund: hängt)
dienst_neustarten [FEHLER]: Error executing tool dienst_neustarten: Unbekannter Dienst mailserver. Bekannt: ['druckdienst', 'kantinenplan', 'zeiterfassung']
bericht [OK]: Lage ruhig, alle 3 Dienste laufen (worker1)

Step 5 – read the audit log. In the terminal of leitwarte on worker1 there are six JSON lines between uvicorn’s access lines.

Expected (excerpt, times differ):

{"zeit": "2026-11-29T14:45:36.417+00:00", "pod": "worker1", "methode": "server/discover", "werkzeug": null, "argumente": {}, "client": "einsatz-cli", "ticket": null, "trace_id": null, "ergebnis": "ok", "dauer_ms": 0.5}
INFO:     172.16.0.126:49244 - "POST /mcp HTTP/1.1" 200 OK
{"zeit": "2026-11-29T14:45:36.429+00:00", "pod": "worker1", "methode": "tools/call", "werkzeug": "wo_bin_ich", "argumente": {}, "client": "einsatz-cli", "ticket": "CHG-1001", "trace_id": null, "ergebnis": "ok", "dauer_ms": 4.3}
INFO:     172.16.0.126:49244 - "POST /mcp HTTP/1.1" 200 OK
{"zeit": "2026-11-29T14:45:36.445+00:00", "pod": "worker1", "methode": "tools/list", "werkzeug": null, "argumente": {}, "client": "einsatz-cli", "ticket": null, "trace_id": null, "ergebnis": "ok", "dauer_ms": 1.1}
INFO:     172.16.0.126:49244 - "POST /mcp HTTP/1.1" 200 OK
{"zeit": "2026-11-29T14:45:36.552+00:00", "pod": "worker1", "methode": "tools/call", "werkzeug": "dienst_neustarten", "argumente": {"dienst": "druckdienst", "grund": "hängt", "freigabecode": "sha256:7f9a4b41bf30"}, "client": "einsatz-cli", "ticket": "CHG-1001", "trace_id": null, "ergebnis": "ok", "dauer_ms": 1.7}

Read the lines from the top:

  • The client introduces itself with server/discover. There is no ticket there – einsatz.py only sends it with call_tool.
  • After the first tool call, the SDK fetches tools/list on its own. It needs the outputSchema information to validate results (Day 3). This also shows up in the log, because the middleware sees every request, not only tools.
  • For the restart, instead of 7731 there is only sha256:7f9a4b41bf30.
  • The call with mailserver appears further down with "ergebnis": "fehler", bericht with a good 1600 ms.
  • trace_id is null everywhere. There is no TracerProvider yet.

Step 6 – check the fingerprint. Internal audit receives the change ticket with the code 7731. Does it match what is in the log?

# on cp1
printf %s 7731 | sha256sum | cut -c1-12
  • printf %s 7731 prints the text without a newline. echo appends one, and then the hash does not match.
  • sha256sum computes the SHA-256 hash of the input.
  • cut -c1-12 keeps characters 1 to 12.

Expected: 7f9a4b41bf30

Step 7 – clean up. Stop leitwarte on worker1 with Ctrl+C. From Drill 3 on, the server runs on Kubernetes.

Remember: A middleware sees every request in one place – that is where the audit log belongs. Secrets go into the ledger only as a fingerprint.

If it doesn’t work

  • 421 Misdirected Request / Invalid Host header: You are calling leitwarte via a name that is not in ERLAUBTE_HOSTS, for example localhost. Use worker1:8010.
  • The line for the error is missing in the log: If it says "ergebnis": "ok" instead of "fehler", you are probably checking isinstance(ergebnis, CallToolResult). But with MCPServer, the result in the middleware is already a dict with the key isError.
  • ModuleNotFoundError: No module named 'opentelemetry.sdk': Step 1 is missing on this machine.

Save your progress? Sign up for free

Drill 2: k3s on three VMs

Where you are: on cp1, then on worker1 and worker2.

What you have afterwards: a Kubernetes cluster with cp1 as server and worker1 and worker2 as agents, kubectl on cp1, and Traefik as the built-in gateway.

k3s is a lightweight Kubernetes distribution from Rancher (SUSE) in a single file. It includes what you need today: containerd as runtime, Flannel as network, CoreDNS, the metrics-server and Traefik as ingress and gateway. One machine runs as server (control plane), the others as agents (worker nodes).

Step 1 – the server on cp1.

# on cp1
curl -sfL https://get.k3s.io | INSTALL_K3S_VERSION="v1.37.2+k3s1" sh -s - server
  • curl -sfL URL downloads the k3s installation script: -s silent, -f abort on HTTP errors instead of printing the error page, -L follow redirects.
  • | … sh -s - server passes the script to sh. -s means “read the script from standard input”, - ends the options of sh, server is the first argument for the script.
  • INSTALL_K3S_VERSION="v1.37.2+k3s1" before sh sets an environment variable only for this command. The script then installs exactly this version instead of the latest.

The script downloads the right file for your architecture, verifies its checksum, puts it at /usr/local/bin/k3s and sets up the systemd service k3s. It asks for the sudo password if needed.

Expected (at the end):

[INFO]  Creating /usr/local/bin/kubectl symlink to k3s
[INFO]  Creating /usr/local/bin/crictl symlink to k3s
[INFO]  Creating /usr/local/bin/ctr symlink to k3s
[INFO]  Creating killall script /usr/local/bin/k3s-killall.sh
[INFO]  Creating uninstall script /usr/local/bin/k3s-uninstall.sh
[INFO]  env: Creating environment file /etc/systemd/system/k3s.service.env
[INFO]  systemd: Creating service file /etc/systemd/system/k3s.service
[INFO]  systemd: Enabling k3s unit
Created symlink /etc/systemd/system/multi-user.target.wants/k3s.service → /etc/systemd/system/k3s.service.
[INFO]  systemd: Starting k3s

kubectl is now a link to k3s and works the same way. The access file (kubeconfig) is at /etc/rancher/k3s/k3s.yaml and belongs to root. Copy it for your user:

# on cp1
mkdir -p ~/.kube
# on cp1
sudo install -m 600 -o "$USER" -g "$USER" /etc/rancher/k3s/k3s.yaml ~/.kube/config
# on cp1
echo "export KUBECONFIG=~/.kube/config" >> ~/.bashrc
# on cp1
source ~/.bashrc
# on cp1
kubectl get nodes
  • install -m 600 -o "$USER" -g "$USER" quelle ziel copies a file and sets permissions (600: only the owner reads and writes), owner and group at the same time. $USER is your user name.
  • KUBECONFIG tells kubectl which access file to use. Without the variable, the k3s kubectl accesses /etc/rancher/k3s/k3s.yaml and fails because of the permissions. The line in ~/.bashrc sets it in every new terminal, source ~/.bashrc right away in this one.

Expected:

NAME   STATUS   ROLES           AGE   VERSION
cp1    Ready    control-plane   20s   v1.37.2+k3s1

If it says NotReady, wait a few seconds and ask again.

Step 2 – the join token. Agents need a secret to join the cluster. It is on cp1:

# on cp1
sudo cat /var/lib/rancher/k3s/server/node-token

Expected: a long line that starts with K10 and contains ::server:.

Whoever has this token can attach their own machines to your cluster. Copy it only into the two following commands and nowhere else.

Step 3 – the agents. On worker1 and on worker2 each:

# on worker1, then the same on worker2
read -rs -p "Token: " K3S_TOKEN; echo
# on worker1, then the same on worker2
curl -sfL https://get.k3s.io | INSTALL_K3S_VERSION="v1.37.2+k3s1" K3S_URL=https://cp1:6443 K3S_TOKEN="$K3S_TOKEN" sh -s - agent
  • read -rs -p "Token: " K3S_TOKEN reads the token hidden into a variable (Day 13). That way it does not end up in the history. The echo afterwards only adds the newline that the hidden input swallows.
  • K3S_URL=https://cp1:6443 is the address of the API server on cp1. Port 6443 is the Kubernetes default.
  • K3S_TOKEN="$K3S_TOKEN" passes the token to the script.
  • agent as argument sets up the k3s-agent service instead of a server.

Expected (at the end):

[INFO]  systemd: Enabling k3s-agent unit
Created symlink /etc/systemd/system/multi-user.target.wants/k3s-agent.service → /etc/systemd/system/k3s-agent.service.
[INFO]  systemd: Starting k3s-agent

Step 4 – the cluster.

# on cp1
kubectl get nodes
kubectl get pods -A

-A (all namespaces) shows the pods of all namespaces.

Expected (times and names differ):

NAME      STATUS   ROLES           AGE   VERSION
cp1       Ready    control-plane   15m   v1.37.2+k3s1
worker1   Ready    <none>          14m   v1.37.2+k3s1
worker2   Ready    <none>          14m   v1.37.2+k3s1
NAMESPACE     NAME                                      READY   STATUS      RESTARTS      AGE
kube-system   coredns-577d995dff-vzfml                  1/1     Running     0             88s
kube-system   helm-install-gateway-api-crd-nw6zd        0/1     Completed   0             88s
kube-system   helm-install-traefik-9kc5n                0/1     Completed   2 (53s ago)   88s
kube-system   helm-install-traefik-crd-tqhzm            0/1     Completed   0             88s
kube-system   local-path-provisioner-56c6584955-bk4dd   1/1     Running     0             88s
kube-system   metrics-server-778c4649b4-8dvlk           1/1     Running     0             88s
kube-system   svclb-traefik-6996785b-86nbd              2/2     Running     0             38s
kube-system   svclb-traefik-6996785b-thb9r              2/2     Running     0             30s
kube-system   svclb-traefik-6996785b-vn4rh              2/2     Running     0             29s
kube-system   traefik-68df944ff7-w6t6d                  1/1     Running     0             38s

Three nodes are Ready. The helm-install-… pods installed Traefik and the definitions (CRDs) for Traefik and the Gateway API and are finished (Completed). traefik is the gateway. svclb-traefik runs on every node and forwards ports 80 and 443 there to Traefik. That is why you reach Traefik via the IP of any node.

Remember: k3s ships Traefik as the gateway, and svclb-traefik makes it reachable on every node via ports 80 and 443.

If it doesn’t work

  • An agent stays missing from the list: Check on the agent with sudo journalctl -u k3s-agent -n 20. If it says 401 Unauthorized, the token was wrong. Remove the agent with sudo /usr/local/bin/k3s-agent-uninstall.sh and repeat step 3.
  • dial tcp: lookup cp1: The agent does not know the name cp1. Check /etc/hosts (Day 0).
  • permission denied with kubectl: KUBECONFIG is not set in this terminal. Run source ~/.bashrc.

Save your progress? Sign up for free

Drill 3: The control center with three replicas

Where you are: on your own computer, then on cp1 in ~/mcpa/tag14.

What you have afterwards: leitwarte as a Deployment with three pods on three nodes, reachable via Traefik at http://leitwarte.labor/mcp.

Step 1 – bring the code to cp1. leitwarte.py is on worker1, kubectl runs on cp1.

# on your computer
scp -3 worker1:mcpa/tag14/leitwarte.py cp1:mcpa/tag14/

scp -3 copies between two remote machines via your own (Day 8).

Step 2 – namespace and ConfigMap. You do not need an image of your own. The code goes into the pod as a ConfigMap, and a ready-made image with Python and uv runs it.

# on cp1, in ~/mcpa/tag14
kubectl create namespace leitwarte
kubectl -n leitwarte create configmap leitwarte-code --from-file=leitwarte.py
  • kubectl create namespace leitwarte creates a namespace, a separate area for all objects of the control center.
  • -n leitwarte applies to the command and means “in this namespace”.
  • create configmap NAME --from-file=datei creates a ConfigMap. The file name becomes the key, the content the value.

Expected:

namespace/leitwarte created
configmap/leitwarte-code created

Step 3 – Deployment, Service and route.

# on cp1, in ~/mcpa/tag14
nano leitwarte.yaml
leitwarte.yaml new file
apiVersion: apps/v1
kind: Deployment
metadata:
  name: leitwarte
  namespace: leitwarte
spec:
  replicas: 3
  selector:
    matchLabels:
      app: leitwarte
  template:
    metadata:
      labels:
        app: leitwarte
    spec:
      topologySpreadConstraints:
        - maxSkew: 1
          topologyKey: kubernetes.io/hostname
          whenUnsatisfiable: ScheduleAnyway
          labelSelector:
            matchLabels:
              app: leitwarte
      containers:
        - name: leitwarte
          image: ghcr.io/astral-sh/uv:0.13.10-python3.12-trixie-slim
          command:
            - uv
            - run
            - --no-project
            - --with=mcp==2.3.0
            - --with=opentelemetry-sdk==1.45.2
            - --with=opentelemetry-exporter-otlp-proto-http==1.45.2
            - python
            - /app/leitwarte.py
          env:
            - name: ERLAUBTE_HOSTS
              value: leitwarte.labor
          ports:
            - containerPort: 8010
          readinessProbe:
            tcpSocket:
              port: 8010
            periodSeconds: 3
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              cpu: 500m
              memory: 384Mi
          volumeMounts:
            - name: code
              mountPath: /app
      volumes:
        - name: code
          configMap:
            name: leitwarte-code
---
apiVersion: v1
kind: Service
metadata:
  name: leitwarte
  namespace: leitwarte
spec:
  selector:
    app: leitwarte
  ports:
    - port: 8010
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata:
  name: leitwarte
  namespace: leitwarte
spec:
  entryPoints:
    - web
  routes:
    - match: Host(`leitwarte.labor`)
      kind: Rule
      services:
        - name: leitwarte
          port: 8010
# on cp1, in ~/mcpa/tag14
kubectl apply -f leitwarte.yaml
kubectl -n leitwarte rollout status deployment/leitwarte --timeout=300s
kubectl -n leitwarte get pods -o wide

The file contains three objects, separated by ---.

The Deployment keeps three pods with the label app: leitwarte running (replicas: 3, selector.matchLabels).

  • topologySpreadConstraints spreads them across the nodes. topologyKey: kubernetes.io/hostname means “spread by machine”, maxSkew: 1 “at most one pod difference”, ScheduleAnyway “start anyway if necessary”.
  • image is an official uv image with Python 3.12 on Debian trixie, pinned to uv 0.13.10. It is available for amd64 and arm64.
  • command starts the server: uv run --no-project runs a program without pyproject.toml, and each --with=paket==version installs a package for it into a cache. On the first start this takes just under a minute, because every pod downloads the packages. In production you build an image of your own for this.
  • env sets ERLAUBTE_HOSTS to leitwarte.labor. Traefik passes the client’s Host header on unchanged, and the DNS rebinding protection from Day 8 lets only this name through.
  • readinessProbe with tcpSocket reports a pod as ready only when port 8010 accepts connections. Until then the Service sends it nothing. periodSeconds: 3 checks every three seconds.
  • resources.requests is what the scheduler reserves for the pod. limits is the upper bound: it gets no more than half a CPU (500m), and above 384 MiB of memory the kernel kills it.
  • volumeMounts and volumes mount the ConfigMap as the directory /app in the container. It contains leitwarte.py.

The Service gives the three pods a common name and an address in the cluster, leitwarte.leitwarte port 8010. It distributes connections to all pods whose label matches the selector.

The IngressRoute is a Traefik object. entryPoints: [web] means “on port 80”. The rule Host(`leitwarte.labor`) matches all requests with this host name and sends them to the Service.

  • kubectl apply -f datei creates all objects of the file or brings them to the state of the file.
  • rollout status deployment/NAME waits until all pods are ready. --timeout=300s aborts after five minutes.

Expected (names and IPs differ):

deployment.apps/leitwarte created
service/leitwarte created
ingressroute.traefik.io/leitwarte created
Waiting for deployment "leitwarte" rollout to finish: 0 of 3 updated replicas are available...
Waiting for deployment "leitwarte" rollout to finish: 1 of 3 updated replicas are available...
Waiting for deployment "leitwarte" rollout to finish: 2 of 3 updated replicas are available...
deployment "leitwarte" successfully rolled out
NAME                        READY   STATUS    RESTARTS   AGE   IP           NODE      NOMINATED NODE   READINESS GATES
leitwarte-d4b575c55-pfgmh   1/1     Running   0          61s   10.42.2.3    worker2   <none>           <none>
leitwarte-d4b575c55-stsc2   1/1     Running   0          61s   10.42.1.3    worker1   <none>           <none>
leitwarte-d4b575c55-v9kl2   1/1     Running   0          61s   10.42.0.10   cp1       <none>           <none>

One pod per node, exactly as the topologySpreadConstraints want.

Step 4 – the name leitwarte.labor. Nobody knows this name yet. Add it on cp1, together with the two names for Drill 4:

# on cp1
echo "172.16.0.126 leitwarte.labor jaeger.labor otlp.labor" | sudo tee -a /etc/hosts

All three names point to cp1. There, svclb-traefik accepts port 80 and passes it on to Traefik. Traefik decides by host name where it goes.

Step 5 – the operation against Kubernetes.

# on cp1, in ~/mcpa/tag14
LEITWARTE_URL=http://leitwarte.labor/mcp uv run python einsatz.py CHG-1002

Expected (pod names differ):

wo_bin_ich [OK]: Antwort von leitwarte-d4b575c55-stsc2
dienst_neustarten [OK]: druckdienst auf leitwarte-d4b575c55-stsc2 neu gestartet (Grund: hängt)
dienst_neustarten [FEHLER]: Error executing tool dienst_neustarten: Unbekannter Dienst mailserver. Bekannt: ['druckdienst', 'kantinenplan', 'zeiterfassung']
bericht [OK]: Lage ruhig, alle 3 Dienste laufen (leitwarte-d4b575c55-stsc2)

Here the same pod answers three times. The audit log shows that this is not the whole story.

Step 6 – the audit log of all pods.

# on cp1
kubectl -n leitwarte logs -l app=leitwarte --tail=-1 | grep '^{' | jq -c '{zeit: .zeit[11:23], pod: .pod[-5:], methode, werkzeug}' | sort
  • kubectl logs -l app=leitwarte fetches the logs of all pods with this label. --tail=-1 means “all lines”. Without the option, kubectl with -l returns only the last ten per pod.
  • grep '^{' keeps only the JSON lines.
  • jq -c '{…}' builds a smaller object from each line. .zeit[11:23] cuts the time of day out of the timestamp, .pod[-5:] the last five characters of the pod name. methode, werkzeug takes over the fields unchanged.
  • sort sorts by the time at the front. kubectl returns the logs pod by pod, not chronologically.

Expected:

{"zeit":"14:49:16.182","pod":"pfgmh","methode":"server/discover","werkzeug":null}
{"zeit":"14:49:16.223","pod":"stsc2","methode":"tools/call","werkzeug":"wo_bin_ich"}
{"zeit":"14:49:16.247","pod":"pfgmh","methode":"tools/list","werkzeug":null}
{"zeit":"14:49:16.453","pod":"stsc2","methode":"tools/call","werkzeug":"dienst_neustarten"}
{"zeit":"14:49:16.478","pod":"v9kl2","methode":"tools/call","werkzeug":"dienst_neustarten"}
{"zeit":"14:49:16.505","pod":"stsc2","methode":"tools/call","werkzeug":"bericht"}

Six requests from the same client, over one HTTP connection, spread across all three pods. Traefik distributes each request individually, and every pod can answer every one, because there is no session that only one pod knows. server/discover ran on pfgmh, the first tool call on stsc2 – and that works because everything needed is in the _meta of every request. With the protocol before 2026-07-28, stsc2 would not have known the session of pfgmh.

Remember: Since 2026-07-28 an MCP server needs no sticky sessions: every request carries everything in _meta, so any counter can serve any messenger.

If it doesn’t work

  • Pods stay at 0/1 Running: They are still downloading packages. kubectl -n leitwarte logs POD shows the progress. If it takes longer than five minutes, check whether the nodes can reach the internet.
  • OOMKilled in kubectl get pods: The memory limit is too small for downloading the packages. Set it to 512Mi in leitwarte.yaml and apply the file again.
  • 421 Misdirected Request: ERLAUBTE_HOSTS does not match the name in LEITWARTE_URL.
  • 404 page not found: Traefik knows no route for the name. Check with kubectl -n leitwarte get ingressroute whether the route exists and the name in /etc/hosts is right.

Save your progress? Sign up for free

Drill 4: Tracing an operation

Where you are: on cp1 in ~/mcpa/tag14, then in the browser on your computer.

What you have afterwards: Jaeger in the cluster, leitwarte and einsatz.py with OpenTelemetry switched on, and a trace that reaches from the client through three pods into the tools.

Jaeger is a free system for collecting and displaying traces and a CNCF project. Version 2 is built on the OpenTelemetry Collector and accepts OTLP directly. In the lab it runs as one pod that keeps everything in memory. After a restart the traces are gone.

Step 1 – Jaeger in the cluster.

# on cp1, in ~/mcpa/tag14
nano jaeger.yaml
jaeger.yaml new file
apiVersion: apps/v1
kind: Deployment
metadata:
  name: jaeger
  namespace: beobachtung
spec:
  replicas: 1
  selector:
    matchLabels:
      app: jaeger
  template:
    metadata:
      labels:
        app: jaeger
    spec:
      containers:
        - name: jaeger
          image: jaegertracing/jaeger:2.23.0
          ports:
            - containerPort: 4318
            - containerPort: 16686
          resources:
            limits:
              memory: 512Mi
---
apiVersion: v1
kind: Service
metadata:
  name: jaeger
  namespace: beobachtung
spec:
  selector:
    app: jaeger
  ports:
    - name: otlp-http
      port: 4318
    - name: ui
      port: 16686
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata:
  name: jaeger
  namespace: beobachtung
spec:
  entryPoints:
    - web
  routes:
    - match: Host(`jaeger.labor`)
      kind: Rule
      services:
        - name: jaeger
          port: 16686
    - match: Host(`otlp.labor`)
      kind: Rule
      services:
        - name: jaeger
          port: 4318
# on cp1, in ~/mcpa/tag14
kubectl create namespace beobachtung
kubectl apply -f jaeger.yaml
kubectl -n beobachtung rollout status deployment/jaeger --timeout=180s
curl -s http://jaeger.labor/api/v3/services
  • Without further options, the image jaegertracing/jaeger:2.23.0 starts as “all-in-one”: receiver, storage and UI in one process.
  • Port 4318 is OTLP over HTTP; server and client send their spans there. Port 16686 is the web UI and its API.
  • A Service with several ports needs a name for each.
  • The IngressRoute has two rules: jaeger.labor leads to the UI, otlp.labor to the receiver. That way einsatz.py on cp1, outside the cluster, can deliver spans too.
  • /api/v3/services is Jaeger’s API and lists all services from which spans have arrived.

Expected:

namespace/beobachtung created
deployment.apps/jaeger created
service/jaeger created
ingressroute.traefik.io/jaeger created
Waiting for deployment "jaeger" rollout to finish: 0 of 1 updated replicas are available...
deployment "jaeger" successfully rolled out
{"services":[]}

Nobody has sent anything yet.

Step 2 – switch on OpenTelemetry in the control center.

# on cp1
kubectl -n leitwarte set env deployment/leitwarte OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger.beobachtung:4318 OTEL_SERVICE_NAME=leitwarte
kubectl -n leitwarte rollout status deployment/leitwarte --timeout=300s
  • kubectl set env deployment/NAME VAR=value … sets environment variables in the Deployment’s pod template. Because the template changes, Kubernetes replaces the pods one after another with new ones.
  • OTEL_EXPORTER_OTLP_ENDPOINT is a standard OpenTelemetry variable. The OTLPSpanExporter reads it itself and appends /v1/traces. leitwarte.py sets up its TracerProvider only if it is set. jaeger.beobachtung is the Service jaeger in the namespace beobachtung (observation).
  • OTEL_SERVICE_NAME is also standard and becomes the service name in Jaeger.

Caution: leitwarte.yaml knows nothing about these variables. If you apply the file again later, they are gone again. In production you therefore put them into the file and the file into Git.

Expected (at the end): deployment "leitwarte" successfully rolled out

Step 3 – a traced operation.

# on cp1, in ~/mcpa/tag14
export LEITWARTE_URL=http://leitwarte.labor/mcp OTEL_EXPORTER_OTLP_ENDPOINT=http://otlp.labor OTEL_SERVICE_NAME=einsatz-cli
# on cp1, in ~/mcpa/tag14
uv run python einsatz.py CHG-1003

export sets the three variables for all further commands in this terminal. The client sends its spans to otlp.labor, that is, via Traefik to Jaeger.

Expected (pod names and trace ID differ):

wo_bin_ich [OK]: Antwort von leitwarte-549b68d44b-s7xdk
dienst_neustarten [OK]: druckdienst auf leitwarte-549b68d44b-s7xdk neu gestartet (Grund: hängt)
dienst_neustarten [FEHLER]: Error executing tool dienst_neustarten: Unbekannter Dienst mailserver. Bekannt: ['druckdienst', 'kantinenplan', 'zeiterfassung']
bericht [OK]: Lage ruhig, alle 3 Dienste laufen (leitwarte-549b68d44b-sp69l)
trace_id=b6002d6d2ae03ffc3fc7480e7001c581

Keep the trace ID in a variable:

# on cp1 – insert your trace ID
TRACE=b6002d6d2ae03ffc3fc7480e7001c581

Step 4 – the trace via the API.

First you ask which services Jaeger knows. jq -c . prints the answer on one line:

# on cp1
curl -s http://jaeger.labor/api/v3/services | jq -c .

Expected:

{"services":["einsatz-cli","jaeger","leitwarte"]}

Then you fetch the whole trace and store it in a file. -o trace.json writes the answer to the file instead of the screen; you need it twice:

# on cp1
curl -s http://jaeger.labor/api/v3/traces/$TRACE -o trace.json

Now jq reads the file and prints the spans in time order:

# on cp1
jq -r '[.result.resourceSpans[] | (.resource.attributes[] | select(.key == "service.name") | .value.stringValue) as $dienst | .scopeSpans[].spans[] | {zeit: .startTimeUnixNano, zeile: "\($dienst): \(.name)"}] | sort_by(.zeit) | .[].zeile' trace.json

/api/v3/traces/ID returns the whole trace in OTLP format. In it, the spans are grouped by origin: each resourceSpans group belongs to one service, whose name is in the service.name attribute. The jq expression reads it like this:

  • .result.resourceSpans[] goes through the groups.
  • (… | select(.key == "service.name") | .value.stringValue) as $dienst looks among the group’s attributes for the one with the key service.name and keeps its value in the variable $dienst.
  • .scopeSpans[].spans[] goes through all spans of the group.
  • {zeit: …, zeile: "\($dienst): \(.name)"} builds an object for each span with the start time (zeit) and a line (zeile) with service and span name. \(…) inserts a value into the text.
  • The square brackets […] collect all objects in a list, sort_by(.zeit) orders them by start time, .[].zeile prints only the line of each.

Expected:

einsatz-cli: einsatz CHG-1003
einsatz-cli: MCP send server/discover
leitwarte: server/discover
einsatz-cli: MCP send tools/call wo_bin_ich
leitwarte: tools/call wo_bin_ich
einsatz-cli: MCP send tools/list
leitwarte: tools/list
leitwarte: tools/call dienst_neustarten
einsatz-cli: MCP send tools/call dienst_neustarten
einsatz-cli: MCP send tools/call dienst_neustarten
leitwarte: tools/call dienst_neustarten
einsatz-cli: MCP send tools/call bericht
leitwarte: tools/call bericht
leitwarte: daten_sammeln
leitwarte: bericht_schreiben

Fifteen spans in one trace: the root span einsatz CHG-1003, one client span MCP send … and one server span per request, and the two custom spans from bericht. The server spans ran in three different pods on three machines, and still they hang in the right trace, because every pod read traceparent from _meta.

Look at lines 8 and 9: the server span for dienst_neustarten starts before the client span that triggered it. That is impossible – and a hint that the clocks of cp1 and of this pod’s node are a few milliseconds apart. Spans from different machines sorted by time are only as accurate as their clocks. That is why Jaeger orders by parent references, not by time.

Step 5 – what the server span knows.

# on cp1
jq -c '[.result.resourceSpans[].scopeSpans[].spans[] | select(.name == "tools/call wo_bin_ich") | .attributes[] | {(.key): .value.stringValue}] | add' trace.json

The expression finds the span tools/call wo_bin_ich, turns each attribute into an object {key: value} and merges them into one with add.

Expected:

{"gen_ai.operation.name":"execute_tool","gen_ai.tool.name":"wo_bin_ich","jsonrpc.request.id":"2","mcp.method.name":"tools/call","mcp.protocol.version":"2026-07-28"}

These are the attributes that the SDK’s OpenTelemetryMiddleware sets. Because they follow the Semantic Conventions, any tool can filter by gen_ai.tool.name – no matter which SDK the server was written with.

Step 6 – connect trace and audit log.

# on cp1
kubectl -n leitwarte logs -l app=leitwarte --tail=-1 | grep $TRACE | jq -c '{pod: .pod[-5:], methode, werkzeug, ergebnis}'

Expected:

{"pod":"s7xdk","methode":"tools/call","werkzeug":"wo_bin_ich","ergebnis":"ok"}
{"pod":"s7xdk","methode":"tools/call","werkzeug":"dienst_neustarten","ergebnis":"ok"}
{"pod":"sp69l","methode":"server/discover","werkzeug":null,"ergebnis":"ok"}
{"pod":"sp69l","methode":"tools/call","werkzeug":"bericht","ergebnis":"ok"}
{"pod":"xh5xj","methode":"tools/list","werkzeug":null,"ergebnis":"ok"}
{"pod":"xh5xj","methode":"tools/call","werkzeug":"dienst_neustarten","ergebnis":"fehler"}

Now every line in the audit log has a trace_id. With it you get from a conspicuous entry to the whole flow in Jaeger, and from a slow trace to the entries that belong to it.

Step 7 – the UI. So that your browser finds jaeger.labor, add the name on your own computer as well (on Windows in C:\Windows\System32\drivers\etc\hosts, as administrator):

# on your computer
echo "172.16.0.126 jaeger.labor" | sudo tee -a /etc/hosts

Open http://jaeger.labor/trace/ followed by your trace ID.

The operation CHG-1003 in Jaeger: client spans (blue) and server spans (orange) from three pods

At the top is the summary: 2.1 seconds, two services, 15 spans, and GenAI calls: 4 – Jaeger recognized the four tool calls by gen_ai.operation.name and marks them with a wrench icon. The failed restart carries a red exclamation mark, because the SDK’s middleware marks the span as an error on isError. At the very bottom you see where the time of bericht goes: 1.5 seconds in daten_sammeln, 100 milliseconds in bericht_schreiben.

Remember: The routing slip (traceparent in _meta) hangs the spans of all pods into one trace. Sorted by time they are only as accurate as the clocks – Jaeger orders by parent references.

If it doesn’t work

  • {"services":["jaeger"]} without leitwarte: The pods are still running with the old environment, or OTEL_EXPORTER_OTLP_ENDPOINT is misspelled. Check with kubectl -n leitwarte get deploy leitwarte -o jsonpath='{.spec.template.spec.containers[0].env}'.
  • einsatz-cli is missing in Jaeger: The program did not wait for anbieter.shutdown(), or otlp.labor is missing in /etc/hosts. Test with curl -s -o /dev/null -w '%{http_code}' http://otlp.labor/v1/traces – 405 means the receiver is there and just does not want a GET.
  • Two separate traces instead of one: The server did not find traceparent. This happens when the client runs without a TracerProvider: then there is nothing to transmit, and every server span starts a trace of its own.
  • 404 page not found from /api/services: That was the Jaeger 1 API. Version 2 uses /api/v3/….

Save your progress? Sign up for free

Drill 5: A gateway that blocks tools

Where you are: on cp1 in ~/mcpa/tag14.

What you have afterwards: a rule in Traefik that blocks dienst_neustarten at the gateway, a way to bypass it, and the rule that closes this way.

The situation: during a change freeze over the holidays, restarts via the control center should not be possible. Reading should still work. The rule belongs in the gateway, because there it applies to all replicas without anyone changing the server.

Step 1 – the rule.

# on cp1, in ~/mcpa/tag14
nano gateway.yaml
gateway.yaml new file
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
  name: gesperrt
  namespace: leitwarte
spec:
  ipAllowList:
    sourceRange:
      - 127.0.0.1/32
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata:
  name: leitwarte
  namespace: leitwarte
spec:
  entryPoints:
    - web
  routes:
    - match: Host(`leitwarte.labor`) && Header(`Mcp-Name`, `dienst_neustarten`)
      kind: Rule
      middlewares:
        - name: gesperrt
      services:
        - name: leitwarte
          port: 8010
    - match: Host(`leitwarte.labor`)
      kind: Rule
      services:
        - name: leitwarte
          port: 8010
# on cp1, in ~/mcpa/tag14
kubectl apply -f gateway.yaml
  • A Traefik middleware processes requests on their way to the service. ipAllowList lets through only senders from sourceRange and answers everyone else with 403 Forbidden. 127.0.0.1/32 never occurs from outside – so the middleware gesperrt (blocked) blocks everything that comes via this route. Traefik has no “always reject” middleware of its own; this is the usual way to do it.
  • The IngressRoute replaces the one from Drill 3 (same name, same namespace) and now has two rules. Header(`Mcp-Name`, `dienst_neustarten`) matches only requests whose Mcp-Name header has exactly this value. This rule goes through gesperrt.
  • Traefik checks longer rules first. The rule with && Header(…) is longer than the simple Host(…) rule and therefore wins when both match.

Expected:

middleware.traefik.io/gesperrt created
ingressroute.traefik.io/leitwarte configured

Step 2 – test the rule. From here on you talk with curl, so that you control the headers yourself. You know KOPF from Day 8.

# on cp1, in ~/mcpa/tag14
KOPF=(-H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28")
# on cp1, in ~/mcpa/tag14
nano neustart.json
neustart.json new file
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"dienst_neustarten","arguments":{"dienst":"druckdienst","grund":"Test","freigabecode":"7731"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
# on cp1, in ~/mcpa/tag14
curl -s -w " -> HTTP %{http_code}\n" http://leitwarte.labor/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: dienst_neustarten" --data @neustart.json

-w " -> HTTP %{http_code}\n" appends the status code after the response.

Expected: Forbidden -> HTTP 403

The response comes from Traefik, not from the server – it is not JSON. The request did not reach any pod and therefore does not appear in any audit log.

Step 3 – with a false header. An attacker knows that the gateway only looks at the header. They write a harmless name into it and leave the body as it is:

# on cp1, in ~/mcpa/tag14
curl -s -w " -> HTTP %{http_code}\n" http://leitwarte.labor/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: wo_bin_ich" --data @neustart.json
curl -s -w " -> HTTP %{http_code}\n" http://leitwarte.labor/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" --data @neustart.json

The second attempt leaves out Mcp-Name entirely.

Expected:

{"jsonrpc":"2.0","id":1,"error":{"code":-32020,"message":"mcp-name header does not match the request body's 'name' parameter"}} -> HTTP 400
{"jsonrpc":"2.0","id":1,"error":{"code":-32020,"message":"mcp-name header does not match the request body's 'name' parameter"}} -> HTTP 400

Both requests get past the gateway, because neither matches the blocking rule. But the server compares header and body and rejects with -32020. This is exactly why the specification requires this check: the gateway trusts the header, the server trusts the body, and only when both match do both see the same thing.

Step 4 – with an encoded header. The specification allows sending the value of Mcp-Name Base64-encoded: =?base64?…?=. This is meant for names that are not plain characters. The server must decode the value before comparing.

# on cp1, in ~/mcpa/tag14
printf %s dienst_neustarten | base64
curl -s -w " -> HTTP %{http_code}\n" http://leitwarte.labor/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: =?base64?ZGllbnN0X25ldXN0YXJ0ZW4=?=" --data @neustart.json | jq -c .result.content[0].text

base64 encodes the input. You put the result between =?base64? and ?=.

Expected (pod name differs):

ZGllbnN0X25ldXN0YXJ0ZW4=
"druckdienst auf leitwarte-549b68d44b-xh5xj neu gestartet (Grund: Test)"

The restart went through. Traefik compared the header =?base64?ZGllbnN0X25ldXN0YXJ0ZW4=?= with dienst_neustarten, found no match and sent the request via the open rule. The server decoded the header, correctly according to the specification, and found dienst_neustarten – matches the body. Both did their job correctly, but the gateway does not know MCP’s encoding. A gateway that evaluates MCP headers must decode them exactly like the server. Otherwise every block there can be bypassed.

Step 5 – close the gap. Traefik cannot decode. But it can block every encoded value – your tool names consist only of plain characters anyway. In gateway.yaml, replace the line

    - match: Host(`leitwarte.labor`) && Header(`Mcp-Name`, `dienst_neustarten`)

with these three lines (with nano gateway.yaml or another editor):

    - match: >-
        Host(`leitwarte.labor`) && (Header(`Mcp-Name`, `dienst_neustarten`)
        || HeaderRegexp(`Mcp-Name`, `^=\?base64\?`))
  • In YAML, >- introduces a text over several lines that YAML joins into one line. The backslash stays as it is.
  • HeaderRegexp(name, muster) matches if the header matches the regular expression. ^=\?base64\? means “starts with =?base64?”. The ? has a meaning in regular expressions; \? stands for the character itself.
  • || is “or”, the parentheses bind it to the && before it.
# on cp1, in ~/mcpa/tag14
kubectl apply -f gateway.yaml
curl -s -w " -> HTTP %{http_code}\n" http://leitwarte.labor/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: =?base64?ZGllbnN0X25ldXN0YXJ0ZW4=?=" --data @neustart.json
curl -s -w " -> HTTP %{http_code}\n" http://leitwarte.labor/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: =?BASE64?ZGllbnN0X25ldXN0YXJ0ZW4=?=" --data @neustart.json

The second attempt writes BASE64 in upper case – maybe the rule is case-sensitive?

Expected:

middleware.traefik.io/gesperrt unchanged
ingressroute.traefik.io/leitwarte configured
Forbidden -> HTTP 403
{"jsonrpc":"2.0","id":1,"error":{"code":-32020,"message":"mcp-name header does not match the request body's 'name' parameter"}} -> HTTP 400

The gateway now blocks the encoded form. The gateway lets the upper-case form through, but the server does not recognize it as an encoding, compares the text literally and rejects it. The gap is closed.

Step 6 – what the host notices.

# on cp1, in ~/mcpa/tag14, in the terminal with the variables from Drill 4
uv run python einsatz.py CHG-1004 2>&1 | tail -3

2>&1 redirects the error output into the normal output, so that tail -3 sees it too.

Expected (at the end of a long traceback):

      |     raise MCPError(code=outcome.code, message=outcome.message, data=outcome.data)
      | mcp.shared.exceptions.MCPError: Server returned an error response
      +------------------------------------

wo_bin_ich still worked, the restart fails. The SDK only sees “Server returned an error response”: it does not know that a gateway answered and not an MCP server. A host should report such an error to the model as a result instead of crashing. For troubleshooting this means: for an error without a JSON-RPC code, look at the gateway first.

Remember: An error without a JSON-RPC code usually comes from the doorman, not the server. And a doorman that doesn’t decode =?base64?…?= can be bypassed – which is why the server compares header and body itself.

If it doesn’t work

  • The block does not apply, step 2 returns 200: The IngressRoute from Drill 3 still applies. Check with kubectl -n leitwarte get ingressroute leitwarte -o yaml whether the two rules are in it.
  • After step 5 everything is blocked: The backslashes are missing in the pattern, or there is a double backslash. Then the pattern matches different values than intended.
  • middleware … not found in Traefik’s log: Middleware and IngressRoute are in different namespaces. Both belong in leitwarte.

Save your progress? Sign up for free

Drill 6: Setting limits

Where you are: on cp1 in ~/mcpa/tag14, with KOPF from Drill 5.

What you have afterwards: a rate limit and a size limit in the gateway, and a look at the pods’ resource limits.

Step 1 – two more middlewares. Replace gateway.yaml completely:

# on cp1, in ~/mcpa/tag14
nano gateway.yaml
gateway.yaml changes in green
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
  name: gesperrt
  namespace: leitwarte
spec:
  ipAllowList:
    sourceRange:
      - 127.0.0.1/32
---
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
  name: drossel
  namespace: leitwarte
spec:
  rateLimit:
    average: 5
    period: 1s
    burst: 10
---
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
  name: groesse
  namespace: leitwarte
spec:
  buffering:
    maxRequestBodyBytes: 4096
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata:
  name: leitwarte
  namespace: leitwarte
spec:
  entryPoints:
    - web
  routes:
    - match: >-
        Host(`leitwarte.labor`) && (Header(`Mcp-Name`, `dienst_neustarten`)
        || HeaderRegexp(`Mcp-Name`, `^=\?base64\?`))
      kind: Rule
      middlewares:
        - name: gesperrt
      services:
        - name: leitwarte
          port: 8010
    - match: Host(`leitwarte.labor`)
      kind: Rule
      middlewares:
        - name: drossel
        - name: groesse
      services:
        - name: leitwarte
          port: 8010
# on cp1, in ~/mcpa/tag14
kubectl apply -f gateway.yaml
  • rateLimit (middleware drossel, rate limiter) works like a bucket of coins (token bucket). average: 5 with period: 1s refills five coins per second. burst: 10 is the size of the bucket. Each request costs one coin. When the bucket is empty, Traefik answers with 429 Too Many Requests. Counting is per sender IP.
  • buffering (middleware groesse, size) reads the whole body first before passing it on. maxRequestBodyBytes: 4096 rejects everything above 4 KiB with 413 Request Entity Too Large.
  • The open rule now uses both, in this order.

Expected:

middleware.traefik.io/gesperrt unchanged
middleware.traefik.io/drossel created
middleware.traefik.io/groesse created
ingressroute.traefik.io/leitwarte configured

Step 2 – the rate limit. Twenty requests as fast as possible:

# on cp1, in ~/mcpa/tag14
nano wo.json
wo.json new file
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"wo_bin_ich","arguments":{},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
# on cp1, in ~/mcpa/tag14
for i in $(seq 1 20); do curl -s -o /dev/null -w "%{http_code} " http://leitwarte.labor/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: wo_bin_ich" --data @wo.json; done; echo
  • for i in $(seq 1 20); do …; done repeats the command twenty times. seq 1 20 produces the numbers 1 to 20.
  • -o /dev/null throws away the body, -w "%{http_code} " prints only the status code.

Expected (the position of the first 429 may differ):

200 200 200 200 200 200 200 200 200 200 200 200 200 429 429 200 429 429 200 429

The first ten go through from the full bucket. Because curl starts anew for every call, time passes between the requests and the bucket refills – that is why a few more succeed. After that, 429 and 200 alternate: exactly as many get through as are refilled.

Step 3 – the size limit. An argument with 5000 characters:

# on cp1, in ~/mcpa/tag14
NOTIZ=$(head -c 5000 /dev/zero | tr '\0' x)
# on cp1, in ~/mcpa/tag14
jq -c --arg notiz "$NOTIZ" '.params.arguments.notiz = $notiz' wo.json > gross.json
# on cp1, in ~/mcpa/tag14
wc -c gross.json
curl -s -w " -> HTTP %{http_code}\n" http://leitwarte.labor/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: wo_bin_ich" --data @gross.json
  • head -c 5000 /dev/zero returns 5000 null bytes, tr '\0' x turns them into 5000 times x.
  • jq --arg notiz "$NOTIZ" '…' passes the text to jq as the variable $notiz. The expression inserts it as an additional argument. -c writes the result on one line.
  • wc -c datei counts the bytes.

Expected:

5268 gross.json
Request Entity Too Large -> HTTP 413

A little over 5 KiB, so rejected before any pod sees any of it. Without the limit, every pod would have read the whole body and parsed it as JSON before even checking whether the argument is allowed. At 5 KiB that does not matter, at 500 MiB it does.

Step 4 – limits in the pod.

# on cp1
kubectl -n leitwarte top pods
kubectl -n leitwarte get pods -o jsonpath='{.items[0].spec.containers[0].resources}' | jq -c .
  • kubectl top pods shows the current CPU and memory consumption. The values come from the metrics-server that ships with k3s.
  • -o jsonpath='{…}' prints part of the object. .items[0] is the first pod in the list, .spec.containers[0].resources its limits.

Expected (similar values):

NAME                         CPU(cores)   MEMORY(bytes)   
leitwarte-549b68d44b-s7xdk   6m           100Mi           
leitwarte-549b68d44b-sp69l   6m           100Mi           
leitwarte-549b68d44b-xh5xj   8m           99Mi            
{"limits":{"cpu":"500m","memory":"384Mi"},"requests":{"cpu":"100m","memory":"128Mi"}}

When idle, a pod needs about 100 MiB and less than a hundredth of a CPU. The limit of 384 MiB leaves room for peaks. A tool that runs amok can occupy at most half a CPU and does not drag down the other pods on the node.

Remember: Limits belong in every layer: rate limit and size at the gateway, validation in the server, CPU and memory in Kubernetes.

If it doesn’t work

  • Never 429: The drossel middleware is not attached to the rule. Check the IngressRoute. Or your requests come slower than five per second – then everything is correct.
  • 413 even for small requests: A digit is missing in maxRequestBodyBytes.
  • error: Metrics API not available: The metrics-server needs one to two minutes after starting.

Save your progress? Sign up for free

Exercise: Who was that? (10 min)

Someone claims to be einsatz-cli and to be working on ticket CHG-1002. Use curl to send a call of wo_bin_ich that looks in the audit log exactly like the calls of einsatz.py from Drill 3. Then search for all entries for ticket CHG-1002. What do you find, and what follows from it?

Solution

# on cp1, in ~/mcpa/tag14, with KOPF from Drill 5
nano falsch.json
falsch.json new file
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"wo_bin_ich","arguments":{},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{},"io.modelcontextprotocol/clientInfo":{"name":"einsatz-cli","version":"1.0"},"de.itdrills/ticket":"CHG-1002"}}}
# on cp1, in ~/mcpa/tag14, with KOPF from Drill 5
curl -s http://leitwarte.labor/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: wo_bin_ich" --data @falsch.json | jq -r '.result.content[0].text'
kubectl -n leitwarte logs -l app=leitwarte --tail=-1 | grep '^{' | jq -c 'select(.ticket == "CHG-1002") | {zeit: .zeit[11:23], client, ticket, werkzeug}' | sort

In jq, select(bedingung) lets through only objects for which the condition holds.

Expected (pod and time differ):

Antwort von leitwarte-549b68d44b-xh5xj
{"zeit":"14:56:55.903","client":"einsatz-cli","ticket":"CHG-1002","werkzeug":"wo_bin_ich"}

Two insights:

  1. The forged line cannot be distinguished from a real one. The client itself writes clientInfo and custom fields in _meta. That is why the identity from the verified token (sub, azp, Day 12) belongs in the audit log, not what the client says about itself.
  2. The real entries for CHG-1002 from Drill 3 are gone. In Drill 4, kubectl set env replaced the pods, and with a pod its log disappears. An audit log that lives only in pods does not even last until the next rollout. In production, an agent on every node collects the logs (Fluent Bit, Vector or the OpenTelemetry Collector) and sends them to a store where nobody can change anything afterwards.

Save your progress? Sign up for free

Challenge: Follow-up questions with three replicas (20 min)

freigabe.py (approval) from Day 10 asks a follow-up question with Multi Round-Trip Requests: the server responds with input_required and a sealed requestState, and the client sends the answer back with this requestState. By default, the SDK seals it with a key that each process generates randomly at startup.

  1. What happens when freigabe.py, like leitwarte, runs with three replicas behind Traefik?
  2. How do you fix this without introducing sticky sessions?
  3. Why would “just use sticky sessions” be the worse answer?

Solution

  1. The first round lands, say, on pod A and gets a requestState sealed with A’s key. Traefik may distribute the second round to pod B. B cannot open the state with its own key and rejects it. On average, two out of three follow-up questions fail, and it looks like a random error.
  2. All replicas need the same key. The SDK accepts it via MCPServer(…, request_state_security=RequestStateSecurity(keys=[schluessel])). You create the key as a Kubernetes Secret and pass it into the pods as an environment variable. keys is a list so you can rotate it: first [alt, neu] (old, new), then [neu, alt], and after the validity period (TTL, 600 seconds by default) only [neu].
  3. Sticky sessions bind a client to a pod. If the pod fails or is replaced during a rollout, the state is gone anyway. In addition, load is distributed less evenly. Since 2026-07-28, MCP is built so that state travels in the message – the server just has to be able to read it everywhere.

Save your progress? Sign up for free

Checkpoint

# on cp1
kubectl get nodes --no-headers | wc -l

Expected: 3

# on cp1
kubectl -n leitwarte get deploy leitwarte -o jsonpath='{.status.readyReplicas}'; echo

Expected: 3

# on cp1
curl -s http://jaeger.labor/api/v3/services | jq -r '.services | index("leitwarte") != null'

Expected: true

# on cp1, in ~/mcpa/tag14, with KOPF from Drill 5
curl -s -o /dev/null -w "%{http_code}\n" http://leitwarte.labor/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: dienst_neustarten" --data @neustart.json

Expected: 403

Clean up: nothing. The cluster, leitwarte and Jaeger stay in place for the next days. If you shut down the VMs, k3s starts by itself at the next boot. The traces in Jaeger are gone then.

Exam questions

1. Which keys in _meta has the specification reserved for propagating Trace Context?

    1. io.modelcontextprotocol/traceId and io.modelcontextprotocol/spanId
    1. traceparent, tracestate and baggage
    1. X-Trace-Id and X-Span-Id
    1. None – Trace Context belongs only in HTTP headers.

2. A gateway blocks a tool based on the Mcp-Name header. A client sends Mcp-Name: lesen (read), but "name": "loeschen" (delete) in the body. What must the MCP server do?

    1. Ignore the header and execute loeschen.
    1. Execute lesen, because the header takes precedence.
    1. Reject with HTTP 400 and the error -32020 (HeaderMismatch).
    1. Reject with HTTP 403.

3. An MCP server according to specification 2026-07-28 without state of its own is to run with three replicas. What does the load balancer in front of it need?

    1. Sticky sessions via Mcp-Session-Id
    1. Nothing special – every replica can answer every request.
    1. A shared store for sessions
    1. WebSockets instead of HTTP

4. Which field is suitable as evidence of who triggered a tool call?

    1. io.modelcontextprotocol/clientInfo from _meta
    1. The User-Agent header
    1. The user (sub) from the access token verified by the server
    1. The IP address of the gateway

5. What does not belong in an MCP server’s audit log?

    1. The name of the called tool
    1. The caller’s access token
    1. The trace ID
    1. Whether the call ended with isError

Solutions

  1. B. The three keys are reserved without a prefix for OpenTelemetry. Their values follow W3C Trace Context and W3C Baggage. That way it works over every transport, including stdio.
  2. C. A server that processes the body must reject mismatches between header and body. Otherwise gateway and server see different requests.
  3. B. Since 2026-07-28 there are no more sessions. Every request carries what the server needs in _meta.
  4. C. The client itself writes clientInfo and User-Agent. Only the verified token proves who the caller is.
  5. B. Otherwise whoever can read the log could sign in with the token. Secrets go in at most as a fingerprint.

Interview Note

“How do you run an MCP server in production?” – As an ordinary, stateless HTTP service: a Deployment with several replicas, a gateway in front, no sticky sessions, because the protocol has had no sessions since 2026-07-28. State the server itself needs, such as sealed requestState, gets shared keys. Every request writes a line into the audit log with the identity from the token, the tool, sanitized arguments, the result and the trace ID. Traces run over OpenTelemetry, because the specification provides traceparent in _meta and the SDKs include it. The gateway may filter by Mcp-Method and Mcp-Name, must understand or block the Base64 form, and the server still checks whether header and body match. Whoever names all this has understood that an MCP server is first of all a web service.

Enterprise Note

In companies, there is usually a central MCP gateway in front of MCP servers: a product or an extension of the existing API gateway that bundles sign-in, approval of tools per team, rate limits and logging in one place. When choosing one, make sure it understands MCP: decode Mcp-Name, check header against body, answer errors as JSON-RPC. A plain HTTP gateway is only as secure as the rules you build around its gaps – Drill 5 showed one of them. The gateway logs by itself, because rejected requests reach no server and appear in no server audit log.

Audit logs belong outside the pods, in a place with fixed retention and without delete rights for operators (WORM storage, separate account). Decide beforehand with data protection and internal audit which arguments may appear in plain text. Personal content usually has no place there. For traces the opposite applies: they may be samples, be short-lived, and do not count as evidence.

Summary

  • Audit is evidence (who, what, when, with what, result), observability is understanding of operations. An audit log contains no tokens and no secrets in plain text.
  • A server middleware (MCPServer(middleware=[…])) sees every request and is suitable for the audit log. In it, the result is already a dict; you recognize errors by isError.
  • The client itself writes clientInfo and custom _meta fields. Identity comes from the verified token.
  • traceparent, tracestate, baggage are reserved in _meta for OpenTelemetry. The Python SDK transmits them itself and sets attributes such as mcp.method.name and gen_ai.tool.name. Without a TracerProvider this costs nothing.
  • Without sessions, an MCP server runs with any number of replicas behind an ordinary load balancer. State of its own needs shared keys or a shared store.
  • A gateway filters by Mcp-Method and Mcp-Name. The server must compare header and body (-32020). The gateway must decode or block the form =?base64?…?=.
  • Limits in every layer: 429 for too many requests, 413 for too large ones, 403 for blocked tools, CPU and memory limits in the pod.

Commands at a glance

For review: all commands and SDK calls of this day with the parameters you used.

Command / call What it does Parameters
MCPServer(…, middleware=[…]) attach a server middleware list of objects with __call__(ctx, call_next)
await call_next(ctx) run the rest of the chain –
trace.get_current_span().get_span_context() read the open span .trace_id, .is_valid
tracer.start_as_current_span(name) open a custom span set_attribute(k, v)
TracerProvider(), BatchSpanProcessor(OTLPSpanExporter()) send spans via OTLP OTEL_EXPORTER_OTLP_ENDPOINT
Client(url, client_info=Implementation(…)) what the client says about itself name, version
client.call_tool(name, args, meta={…}) custom entries in _meta prefix in domain notation
curl -sfL https://get.k3s.io, piped to sh -s - server install a k3s server INSTALL_K3S_VERSION
… sh -s - agent install a k3s agent K3S_URL, K3S_TOKEN
sudo install -m 600 -o U -g G quelle ziel copy a file with permissions -m permissions
kubectl create configmap NAME --from-file=datei file as ConfigMap -n namespace
kubectl apply -f datei create or reconcile objects –
kubectl rollout status deployment/NAME wait for ready pods --timeout
kubectl logs -l label=wert logs of several pods --tail=-1 all lines
kubectl set env deployment/NAME VAR=value set environment, replace pods –
kubectl top pods pod consumption needs metrics-server
kubectl get … -o jsonpath='{…}' print part of an object –
scp -3 a:pfad b:pfad copy between two machines -3 via your own
jq -c '{a: .x[11:23]}' reshape an object, cut text -c one line
jq --arg name wert '…' pass text as a variable to jq –
jq 'select(bedingung)' only matching objects –
printf %s text, piped to sha256sum hash without a newline –
base64 Base64-encode the input –
Traefik Header(`N`, `w`), HeaderRegexp(…) rule by header && and, two bars or
Traefik ipAllowList only certain senders sourceRange
Traefik rateLimit requests per time average, period, burst
Traefik buffering limit the size of the body maxRequestBodyBytes
GET /api/v3/services, /api/v3/traces/ID Jaeger 2 API –

Contents

More