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.tomlExpected:
/home/ubuntu/mcpa/pyproject.toml
# on worker1
ls ~/mcpa/pyproject.tomlExpected:
/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
clientInfois not an identity, - how the specification transports Trace Context in
_metaand 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-MethodandMcp-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 writestraceparentinto_meta. - The server reads
traceparentin its built-inOpenTelemetryMiddlewareand opens a span<method> <name>as a child of the client span. It sets attributes such asmcp.method.name,mcp.protocol.version,jsonrpc.request.idand, for tools,gen_ai.operation.name=execute_toolandgen_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:
- A server that processes the body must reject
requests where header and body do not match – with HTTP
400and-32020HeaderMismatch (Day 8). - 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
leitwarteon worker1, port 8010, which logs every request as a JSON line, and a clienteinsatz.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.2uv addadds packages topyproject.tomland installs them into.venv.opentelemetry-sdkis the implementation of the OpenTelemetry API: TracerProvider, span processors.opentelemetry-exporter-otlp-proto-httpsends spans via OTLP over HTTP.==1.45.2pins 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.pyimport 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_idisNonefor notifications. We do not log those.ctx.methodis the JSON-RPC method,ctx.paramsthe raw parameters as a dict, not yet validated.nameandargumentscome from there.ctx.metais_metafrom the request. The client enteredio.modelcontextprotocol/clientInfoitself.de.itdrills/ticketis 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")), otherwiseNone.try … except … finallyensures that a line is written in every case:ok,fehler(error) for a tool result withisError, orabgelehnt(rejected) with the exception type for a JSON-RPC error.raisethen 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 withgrepandjqand read by any log collector.ensure_ascii=Falsekeeps 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.pyExpected (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.pyimport 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-1001What is new:
URLcomes from the environment variableLEITWARTE_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 inio.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 thewithblock. All calls inside become its children. Without a TracerProvider its trace ID is0, which is why the program prints it only when it is set.anbieter.shutdown()flushes the buffer of theBatchSpanProcessor. 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.pyonly sends it withcall_tool. - After the first tool call, the SDK fetches
tools/liston its own. It needs theoutputSchemainformation 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
7731there is onlysha256:7f9a4b41bf30. - The call with
mailserverappears further down with"ergebnis": "fehler",berichtwith a good 1600 ms. trace_idisnulleverywhere. 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-12printf %s 7731prints the text without a newline.echoappends one, and then the hash does not match.sha256sumcomputes the SHA-256 hash of the input.cut -c1-12keeps 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 callingleitwartevia a name that is not inERLAUBTE_HOSTS, for examplelocalhost. Useworker1:8010.- The line for the error is missing in the log: If it
says
"ergebnis": "ok"instead of"fehler", you are probably checkingisinstance(ergebnis, CallToolResult). But withMCPServer, the result in the middleware is already a dict with the keyisError. 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,
kubectlon 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 - servercurl -sfL URLdownloads the k3s installation script:-ssilent,-fabort on HTTP errors instead of printing the error page,-Lfollow redirects.| … sh -s - serverpasses the script tosh.-smeans “read the script from standard input”,-ends the options ofsh,serveris the first argument for the script.INSTALL_K3S_VERSION="v1.37.2+k3s1"beforeshsets 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 nodesinstall -m 600 -o "$USER" -g "$USER" quelle zielcopies a file and sets permissions (600: only the owner reads and writes), owner and group at the same time.$USERis your user name.KUBECONFIGtellskubectlwhich access file to use. Without the variable, the k3skubectlaccesses/etc/rancher/k3s/k3s.yamland fails because of the permissions. The line in~/.bashrcsets it in every new terminal,source ~/.bashrcright 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-tokenExpected: 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 - agentread -rs -p "Token: " K3S_TOKENreads the token hidden into a variable (Day 13). That way it does not end up in the history. Theechoafterwards only adds the newline that the hidden input swallows.K3S_URL=https://cp1:6443is the address of the API server on cp1. Port 6443 is the Kubernetes default.K3S_TOKEN="$K3S_TOKEN"passes the token to the script.agentas argument sets up thek3s-agentservice 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-traefikmakes 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 says401 Unauthorized, the token was wrong. Remove the agent withsudo /usr/local/bin/k3s-agent-uninstall.shand repeat step 3. dial tcp: lookup cp1: The agent does not know the namecp1. Check/etc/hosts(Day 0).permission deniedwithkubectl:KUBECONFIGis not set in this terminal. Runsource ~/.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:
leitwarteas a Deployment with three pods on three nodes, reachable via Traefik athttp://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.pykubectl create namespace leitwartecreates a namespace, a separate area for all objects of the control center.-n leitwarteapplies to the command and means “in this namespace”.create configmap NAME --from-file=dateicreates 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.yamlapiVersion: 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 wideThe file contains three objects, separated by ---.
The Deployment keeps three pods with the label
app: leitwarte running (replicas: 3,
selector.matchLabels).
topologySpreadConstraintsspreads them across the nodes.topologyKey: kubernetes.io/hostnamemeans “spread by machine”,maxSkew: 1“at most one pod difference”,ScheduleAnyway“start anyway if necessary”.imageis an official uv image with Python 3.12 on Debian trixie, pinned to uv 0.13.10. It is available for amd64 and arm64.commandstarts the server:uv run --no-projectruns a program withoutpyproject.toml, and each--with=paket==versioninstalls 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.envsetsERLAUBTE_HOSTStoleitwarte.labor. Traefik passes the client’s Host header on unchanged, and the DNS rebinding protection from Day 8 lets only this name through.readinessProbewithtcpSocketreports a pod as ready only when port 8010 accepts connections. Until then the Service sends it nothing.periodSeconds: 3checks every three seconds.resources.requestsis what the scheduler reserves for the pod.limitsis the upper bound: it gets no more than half a CPU (500m), and above 384 MiB of memory the kernel kills it.volumeMountsandvolumesmount the ConfigMap as the directory/appin the container. It containsleitwarte.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 dateicreates all objects of the file or brings them to the state of the file.rollout status deployment/NAMEwaits until all pods are ready.--timeout=300saborts 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/hostsAll 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-1002Expected (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}' | sortkubectl logs -l app=leitwartefetches the logs of all pods with this label.--tail=-1means “all lines”. Without the option,kubectlwith-lreturns 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, werkzeugtakes over the fields unchanged.sortsorts by the time at the front.kubectlreturns 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 PODshows the progress. If it takes longer than five minutes, check whether the nodes can reach the internet. OOMKilledinkubectl get pods: The memory limit is too small for downloading the packages. Set it to512Miinleitwarte.yamland apply the file again.421 Misdirected Request:ERLAUBTE_HOSTSdoes not match the name inLEITWARTE_URL.404 page not found: Traefik knows no route for the name. Check withkubectl -n leitwarte get ingressroutewhether the route exists and the name in/etc/hostsis 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,
leitwarteandeinsatz.pywith 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.yamlapiVersion: 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.0starts 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
namefor each. - The IngressRoute has two rules:
jaeger.laborleads to the UI,otlp.laborto the receiver. That wayeinsatz.pyon cp1, outside the cluster, can deliver spans too. /api/v3/servicesis 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=300skubectl 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_ENDPOINTis a standard OpenTelemetry variable. TheOTLPSpanExporterreads it itself and appends/v1/traces.leitwarte.pysets up its TracerProvider only if it is set.jaeger.beobachtungis the Servicejaegerin the namespacebeobachtung(observation).OTEL_SERVICE_NAMEis 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-1003export 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=b6002d6d2ae03ffc3fc7480e7001c581Step 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.jsonNow 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 $dienstlooks among the group’s attributes for the one with the keyservice.nameand 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,.[].zeileprints 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.jsonThe 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/hostsOpen http://jaeger.labor/trace/ followed by your trace
ID.
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 (
traceparentin_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"]}withoutleitwarte: The pods are still running with the old environment, orOTEL_EXPORTER_OTLP_ENDPOINTis misspelled. Check withkubectl -n leitwarte get deploy leitwarte -o jsonpath='{.spec.template.spec.containers[0].env}'.einsatz-cliis missing in Jaeger: The program did not wait foranbieter.shutdown(), orotlp.laboris missing in/etc/hosts. Test withcurl -s -o /dev/null -w '%{http_code}' http://otlp.labor/v1/traces–405means 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 foundfrom/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_neustartenat 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.yamlapiVersion: 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.
ipAllowListlets through only senders fromsourceRangeand answers everyone else with403 Forbidden.127.0.0.1/32never occurs from outside – so the middlewaregesperrt(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 whoseMcp-Nameheader has exactly this value. This rule goes throughgesperrt. - Traefik checks longer rules first. The rule with
&& Header(…)is longer than the simpleHost(…)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{"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.jsonThe 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].textbase64 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.jsonThe 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 -32>&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 withkubectl -n leitwarte get ingressroute leitwarte -o yamlwhether 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 foundin Traefik’s log: Middleware and IngressRoute are in different namespaces. Both belong inleitwarte.
Save your progress? Sign up for free
Drill 6: Setting limits
Where you are: on cp1 in
~/mcpa/tag14, withKOPFfrom 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.yamlapiVersion: 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.yamlrateLimit(middlewaredrossel, rate limiter) works like a bucket of coins (token bucket).average: 5withperiod: 1srefills five coins per second.burst: 10is the size of the bucket. Each request costs one coin. When the bucket is empty, Traefik answers with429 Too Many Requests. Counting is per sender IP.buffering(middlewaregroesse, size) reads the whole body first before passing it on.maxRequestBodyBytes: 4096rejects everything above 4 KiB with413 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{"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; echofor i in $(seq 1 20); do …; donerepeats the command twenty times.seq 1 20produces the numbers 1 to 20.-o /dev/nullthrows 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.jsonhead -c 5000 /dev/zeroreturns 5000 null bytes,tr '\0' xturns them into 5000 timesx.jq --arg notiz "$NOTIZ" '…'passes the text tojqas the variable$notiz. The expression inserts it as an additional argument.-cwrites the result on one line.wc -c dateicounts 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 podsshows 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].resourcesits 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: Thedrosselmiddleware is not attached to the rule. Check the IngressRoute. Or your requests come slower than five per second – then everything is correct. 413even for small requests: A digit is missing inmaxRequestBodyBytes.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{"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}' | sortIn 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:
- The forged line cannot be distinguished from a real one. The client
itself writes
clientInfoand 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. - The real entries for
CHG-1002from Drill 3 are gone. In Drill 4,kubectl set envreplaced 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.
- What happens when
freigabe.py, likeleitwarte, runs with three replicas behind Traefik? - How do you fix this without introducing sticky sessions?
- Why would “just use sticky sessions” be the worse answer?
Solution
- The first round lands, say, on pod A and gets a
requestStatesealed 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. - 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.keysis 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]. - 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 -lExpected: 3
# on cp1
kubectl -n leitwarte get deploy leitwarte -o jsonpath='{.status.readyReplicas}'; echoExpected: 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.jsonExpected: 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?
io.modelcontextprotocol/traceIdandio.modelcontextprotocol/spanId
traceparent,tracestateandbaggage
X-Trace-IdandX-Span-Id
- 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?
- Ignore the header and execute
loeschen.
- Ignore the header and execute
- Execute
lesen, because the header takes precedence.
- Execute
- Reject with HTTP
400and the error-32020(HeaderMismatch).
- Reject with HTTP
- Reject with HTTP
403.
- Reject with HTTP
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?
- Sticky sessions via
Mcp-Session-Id
- Sticky sessions via
- Nothing special – every replica can answer every request.
- A shared store for sessions
- WebSockets instead of HTTP
4. Which field is suitable as evidence of who triggered a tool call?
io.modelcontextprotocol/clientInfofrom_meta
- The
User-Agentheader
- The
- The user (
sub) from the access token verified by the server
- The user (
- The IP address of the gateway
5. What does not belong in an MCP server’s audit log?
- The name of the called tool
- The caller’s access token
- The trace ID
- Whether the call ended with
isError
- Whether the call ended with
Solutions
- 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.
- C. A server that processes the body must reject mismatches between header and body. Otherwise gateway and server see different requests.
- B. Since 2026-07-28 there are no more sessions.
Every request carries what the server needs in
_meta. - C. The client itself writes
clientInfoandUser-Agent. Only the verified token proves who the caller is. - 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 byisError. - The client itself writes
clientInfoand custom_metafields. Identity comes from the verified token. traceparent,tracestate,baggageare reserved in_metafor OpenTelemetry. The Python SDK transmits them itself and sets attributes such asmcp.method.nameandgen_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-MethodandMcp-Name. The server must compare header and body (-32020). The gateway must decode or block the form=?base64?…?=. - Limits in every layer:
429for too many requests,413for too large ones,403for 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 | – |