Skip to content
Workload and AI agent identity · Chapter 14 of 20 Day 13: Securing an MCP server – the tool desk with a notice

Day 13: Securing an MCP server – the tool desk with a notice

Goal: run an MCP server for the warehouse tools that protects itself the way the MCP specification requires – a notice (Protected Resource Metadata), bearer tokens only for itself, a scope per tool, and never passing the client’s token on to the warehouse · Duration: about 120 min · Prerequisite: Day 12 completed

Where we start

# on id1
mkdir -p ~/kurs/13
# on id1
systemctl is-active keycloak lagerdienst

Expected:

active
active

If the kcadm.sh session has expired (Session has expired), log in again as on Day 4.

Introduction

So far every agent has brought its own tools: the assistant from Days 10 to 12 knows lager_bestand and lager_ausbuchen because they are part of its program. The Model Context Protocol (MCP) turns this around: tools live on an MCP server, and every MCP-capable agent – a chat program, an IDE, your own assistant – asks there which tools exist and calls them.

An MCP server that is reachable over the network is an API like any other – and gets attacked the same way. That is why the MCP specification prescribes how it protects itself: with OAuth 2.1, tokens issued for exactly this server, a public notice saying where to get tokens, and an explicit ban on passing tokens on to other services.

Today you build such a server for the warehouse and walk the path of an MCP client step by step with curl.

Today you will learn:

  • how an MCP server uses 401 and WWW-Authenticate to say where to get tokens,
  • what Protected Resource Metadata (RFC 9728) contains,
  • how a client gets from the notice to the reception desk and on to a token,
  • how an MCP server checks the scope per tool and answers with insufficient_scope,
  • why the MCP server exchanges the client’s token for its own token for the warehouse instead of passing the client’s token on,
  • what Keycloak 26.8 does with the resource parameter (nothing) and how you still end up with the right audience.

Background

The picture for today: the tool desk with a notice

The building now has a tool desk: a counter where every runner gets tools instead of owning them. A notice hangs on the door: “Entry only with a visitor pass for the tool desk. Passes are available at reception. We hand out: view stock, check out crates.”

Anyone who comes without a pass is pointed to the notice. Anyone with a pass for a different door is turned away. Anyone who wants to “check out crates” but only has “view” on their pass hears: “For that you need the write endorsement – go get a new pass.”

And the tool desk itself goes to the warehouse for every job – but never with the customer’s pass. It gets its own routing slip at reception that says: “for Anna, delivered by the tool desk”.

The terms

Term Meaning in the picture
MCP server provides tools over JSON-RPC tool desk
MCP client program that lists and calls tools runner
tools/list, tools/call list tools, call one “What do you have?”, “Give me …”
Protected Resource Metadata (RFC 9728) JSON document: who I am, where to get tokens, which scopes notice on the door
WWW-Authenticate header of a 401/403 response with the way to the notice “Please read the notice”
Authorization Server Metadata (RFC 8414) JSON document of the reception desk: which counters are where floor plan of the reception
insufficient_scope token valid, but scope missing (403) “write endorsement missing”
Step-up client gets a token with more scopes new pass with endorsement
Token passthrough passing the client’s token on to another service – forbidden showing the customer’s pass at the warehouse

Remember: An MCP server is a door like any other: it only accepts passes issued for it, and shows everyone else the way to reception.

The path of an MCP client

Step Request Response
1 POST /mcp without a token 401, WWW-Authenticate: Bearer resource_metadata="…"
2 GET on resource_metadata notice: resource, authorization_servers, scopes_supported
3 GET on the reception’s metadata addresses of the device login and the token counter
4 login of the human token with the MCP server in aud
5 POST /mcp with token tools

In the lab you do every step with curl. A real MCP client does the same automatically.

Drill 1: Registering the tool desk at reception

Where you are: on id1, kubectl and kcadm.sh ready.

What you have afterwards: a client for the MCP server that authenticates with a building badge and may exchange tokens, and a login client mcp-cli for humans.

The MCP server needs two things at reception: its own identity, with which it exchanges tokens for the warehouse – like the assistant on Days 10 and 11 –, and an audience for which tokens are issued to it. A single client whose clientId is the address of the MCP server takes care of both.

Step 1 – a building badge for the MCP server.

# on id1
kubectl create serviceaccount lager-mcp -n laden

Expected:

serviceaccount/lager-mcp created

Step 2 – the MCP server’s client.

# on id1
/opt/keycloak/bin/kcadm.sh create clients -r gebaeude -s clientId=http://172.16.0.126:8091/mcp -s publicClient=false -s standardFlowEnabled=false -s clientAuthenticatorType=federated-jwt -s 'attributes."jwt.credential.issuer"=cluster' -s 'attributes."jwt.credential.sub"=system:serviceaccount:laden:lager-mcp' -s 'attributes."standard.token.exchange.enabled"=true' -s 'attributes."access.token.lifespan"=60'
Option Value Meaning
clientId http://172.16.0.126:8091/mcp the address of the MCP server – the MCP specification calls it the canonical URI
publicClient=false – the server authenticates itself
standardFlowEnabled=false – no browser login through this client
clientAuthenticatorType=federated-jwt – authenticate with the Kubernetes token, as on Day 10
jwt.credential.issuer, jwt.credential.sub cluster, …:laden:lager-mcp only this building badge fits
standard.token.exchange.enabled true may exchange tokens (Day 11)
access.token.lifespan 60 routing slips for the warehouse are valid for one minute (Day 12)

Expected (your ID will differ):

Created new client with id '4f018220-13f3-4b2f-ac40-3f7aa5b11877'

Why the address as clientId? During the exchange, Keycloak checks whether the exchanging client is in the token’s aud (Day 11, diagnosis). The MCP server, in turn, should only accept tokens whose aud names its address. With the address as clientId, both are the same value.

Step 3 – the door to the warehouse. Like the assistant on Day 10, the client gets an audience mapper so that exchanged passes fit the warehouse. Insert the ID from step 2:

# on id1
/opt/keycloak/bin/kcadm.sh create clients/4f018220-13f3-4b2f-ac40-3f7aa5b11877/protocol-mappers/models -r gebaeude -s name=tuer-lager -s protocol=openid-connect -s protocolMapper=oidc-audience-mapper -s 'config."included.custom.audience"=lager' -s 'config."access.token.claim"=true'

Expected:

Created new model with id 'fb3320e2-2e6e-4f4a-90bf-9b390c0e14c6'

Step 4 – the warehouse scopes as routing slips. Both optional, as on Day 12:

# on id1
/opt/keycloak/bin/kcadm.sh update clients/4f018220-13f3-4b2f-ac40-3f7aa5b11877/optional-client-scopes/41ee786f-a7c2-40f3-bc99-0eb752ea480a -r gebaeude
# on id1
/opt/keycloak/bin/kcadm.sh update clients/4f018220-13f3-4b2f-ac40-3f7aa5b11877/optional-client-scopes/15701f7d-b3c6-4bcf-8a06-ea4a411dc384 -r gebaeude

Neither produces output.

Step 5 – the login client for humans. Like assistent-cli on Day 11:

# on id1
/opt/keycloak/bin/kcadm.sh create clients -r gebaeude -s clientId=mcp-cli -s publicClient=true -s standardFlowEnabled=false -s directAccessGrantsEnabled=false -s 'attributes."oauth2.device.authorization.grant.enabled"=true'

Expected:

Created new client with id '0d93bf1b-bfee-4b2a-8643-016fc8dfe0f5'

Step 6 – tokens from mcp-cli are for the MCP server. With included.client.audience as on Day 11 – Keycloak checks that the client exists:

# on id1
/opt/keycloak/bin/kcadm.sh create clients/0d93bf1b-bfee-4b2a-8643-016fc8dfe0f5/protocol-mappers/models -r gebaeude -s name=fuer-mcp -s protocol=openid-connect -s protocolMapper=oidc-audience-mapper -s 'config."included.client.audience"=http://172.16.0.126:8091/mcp' -s 'config."access.token.claim"=true'

Expected:

Created new model with id 'd0d63514-2f45-4591-b8ea-b09b4944b038'

Step 7 – mcp-cli also gets the warehouse scopes only on request.

# on id1
/opt/keycloak/bin/kcadm.sh update clients/0d93bf1b-bfee-4b2a-8643-016fc8dfe0f5/optional-client-scopes/41ee786f-a7c2-40f3-bc99-0eb752ea480a -r gebaeude
# on id1
/opt/keycloak/bin/kcadm.sh update clients/0d93bf1b-bfee-4b2a-8643-016fc8dfe0f5/optional-client-scopes/15701f7d-b3c6-4bcf-8a06-ea4a411dc384 -r gebaeude
# on id1
/opt/keycloak/bin/kcadm.sh get clients/0d93bf1b-bfee-4b2a-8643-016fc8dfe0f5/optional-client-scopes -r gebaeude --fields name

Expected:

[ {
  "name" : "address"
}, {
  "name" : "lager:schreiben"
}, {
  "name" : "phone"
}, {
  "name" : "organization"
}, {
  "name" : "offline_access"
}, {
  "name" : "lager:lesen"
}, {
  "name" : "microprofile-jwt"
} ]

Remember: To reception, the tool desk is two things: a door for which passes are issued (audience), and a runner who goes to exchange passes itself (client with a building badge).

Save your progress? Sign up for free

Drill 2: Building the tool desk

Where you are: on id1.

What you have afterwards: the service lager-mcp on port 8091.

Step 1 – the program.

# on id1
nano ~/kurs/13/mcp_lager.py
kurs/13/mcp_lager.py new file
"""Lager-MCP-Server: Lager-Werkzeuge per MCP, nur mit einem Token für genau diesen Server."""

import json
import urllib.error
import urllib.parse
import urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path

import jwt

AUSSTELLER = "http://172.16.0.126:8080/realms/gebaeude"
ICH = "http://172.16.0.126:8091/mcp"
METADATEN = "http://172.16.0.126:8091/.well-known/oauth-protected-resource/mcp"
AUSWEIS = Path.home() / "kurs/13/mcp-ausweis.jwt"
LAGER = "http://127.0.0.1:8090"
VERSION = "2026-07-28"

WERKZEUGE = {
    "lager_bestand": {
        "bereich": "lager:lesen",
        "description": "Liefert den Lagerbestand in Kisten und den Lieferschein.",
        "inputSchema": {"type": "object", "properties": {}},
    },
    "lager_ausbuchen": {
        "bereich": "lager:schreiben",
        "description": "Bucht Kisten aus dem Lager aus.",
        "inputSchema": {
            "type": "object",
            "properties": {"kisten": {"type": "integer"}},
            "required": ["kisten"],
        },
    },
}

musterkarte = jwt.PyJWKClient(AUSSTELLER + "/protocol/openid-connect/certs")


def pruefe(kopf):
    """Gibt (Inhalt, None) zurück oder (None, Grund); Grund None heißt: gar kein Token."""
    if not kopf or not kopf.startswith("Bearer "):
        return None, None
    schein = kopf.removeprefix("Bearer ")
    try:
        schluessel = musterkarte.get_signing_key_from_jwt(schein)
        inhalt = jwt.decode(
            schein, schluessel.key, algorithms=["RS256"], audience=ICH, issuer=AUSSTELLER
        )
    except jwt.PyJWTError as fehler:
        return None, str(fehler)
    return inhalt, None


def lagerschein(schein, bereich):
    """Eigener Schein fürs Lager per Token Exchange – das Token des Clients bleibt hier."""
    rumpf = urllib.parse.urlencode(
        {
            "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
            "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
            "client_assertion": AUSWEIS.read_text().strip(),
            "subject_token": schein,
            "subject_token_type": "urn:ietf:params:oauth:token-type:access_token",
            "scope": bereich,
        }
    ).encode()
    url = AUSSTELLER + "/protocol/openid-connect/token"
    with urllib.request.urlopen(url, rumpf, timeout=10) as antwort:
        return json.loads(antwort.read())["access_token"]


def lager(name, argumente, schein):
    kopf = {"Authorization": "Bearer " + schein, "Content-Type": "application/json"}
    if name == "lager_bestand":
        anfrage = urllib.request.Request(LAGER + "/bestand", headers=kopf)
    else:
        rumpf = json.dumps({"kisten": argumente.get("kisten")}).encode()
        anfrage = urllib.request.Request(LAGER + "/ausbuchen", rumpf, kopf)
    try:
        with urllib.request.urlopen(anfrage, timeout=10) as antwort:
            return antwort.status, antwort.read().decode()
    except urllib.error.HTTPError as fehler:
        return fehler.code, fehler.read().decode()


def ergebnis(nummer, inhalt):
    return {"jsonrpc": "2.0", "id": nummer, "result": inhalt}


def fehler(nummer, code, text):
    return {"jsonrpc": "2.0", "id": nummer, "error": {"code": code, "message": text}}


class Mcp(BaseHTTPRequestHandler):
    def antworte(self, status, daten, tor=None):
        text = json.dumps(daten, ensure_ascii=False).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        if tor:
            self.send_header("WWW-Authenticate", tor)
        self.send_header("Content-Length", str(len(text)))
        self.end_headers()
        self.wfile.write(text)

    def do_GET(self):
        if self.path != "/.well-known/oauth-protected-resource/mcp":
            return self.antworte(404, {"fehler": "unbekannter Pfad"})
        self.antworte(
            200,
            {
                "resource": ICH,
                "authorization_servers": [AUSSTELLER],
                "scopes_supported": ["lager:lesen", "lager:schreiben"],
                "bearer_methods_supported": ["header"],
            },
        )

    def do_POST(self):
        if self.path != "/mcp":
            return self.antworte(404, {"fehler": "unbekannter Pfad"})
        inhalt, grund = pruefe(self.headers.get("Authorization"))
        if inhalt is None:
            tor = f'Bearer resource_metadata="{METADATEN}"'
            if grund:
                tor += f', error="invalid_token", error_description="{grund}"'
            return self.antworte(401, {"fehler": grund or "kein Token"}, tor)
        laenge = int(self.headers.get("Content-Length", 0))
        anfrage = json.loads(self.rfile.read(laenge))
        nummer, methode = anfrage.get("id"), anfrage.get("method")
        params = anfrage.get("params", {})
        version = params.get("_meta", {}).get("io.modelcontextprotocol/protocolVersion")
        if self.headers.get("MCP-Protocol-Version") != VERSION or version != VERSION:
            return self.antworte(400, fehler(nummer, -32602, f"nur Protokollversion {VERSION}"))
        if methode == "tools/list":
            liste = [
                {"name": n, "description": w["description"], "inputSchema": w["inputSchema"]}
                for n, w in WERKZEUGE.items()
            ]
            return self.antworte(200, ergebnis(nummer, {"tools": liste}))
        if methode != "tools/call":
            return self.antworte(404, fehler(nummer, -32601, "Method not found"))
        name = params.get("name")
        if name not in WERKZEUGE:
            return self.antworte(400, fehler(nummer, -32602, f"unbekanntes Werkzeug {name}"))
        bereich = WERKZEUGE[name]["bereich"]
        if bereich not in inhalt.get("scope", "").split():
            tor = f'Bearer error="insufficient_scope", scope="{bereich}", resource_metadata="{METADATEN}"'
            return self.antworte(403, {"fehler": f"Bereich {bereich} fehlt"}, tor)
        print(
            f"WERKZEUG {name} sub={inhalt.get('sub')} azp={inhalt.get('azp')}"
            f" name={inhalt.get('preferred_username')}",
            flush=True,
        )
        schein = lagerschein(self.headers["Authorization"].removeprefix("Bearer "), bereich)
        status, text = lager(name, params.get("arguments", {}), schein)
        antwort = {"content": [{"type": "text", "text": text}], "isError": status != 200}
        self.antworte(200, ergebnis(nummer, antwort))


HTTPServer(("0.0.0.0", 8091), Mcp).serve_forever()

What happens where:

Lines Part in the picture
13–17 own address, address of the notice, building badge, MCP protocol version –
19–34 the tools, each with its scope list at the counter
39–51 check the token: signature, iss, aud = own address, expiry look at the pass
54–68 get its own warehouse pass via token exchange, with exactly one scope routing slip at reception
71–82 call the warehouse – with the exchanged pass walk to the warehouse
104–115 GET on the notice notice on the door
120–125 no token or an invalid one: 401 with WWW-Authenticate “Read the notice”
129–132 check the protocol version in header and body –
133–138 tools/list “What do you have?”
144–147 scope missing: 403 insufficient_scope “Endorsement missing”
148–152 visitor log of the tool desk –
153–156 exchange, call the warehouse, result as MCP response –

Three places in more detail:

  • Line 47: audience=ICH. PyJWT rejects a token that does not have http://172.16.0.126:8091/mcp in aud – even if Keycloak signed it properly.
  • Line 153: The client’s token goes to reception only as subject_token, never to the warehouse.
  • Line 155: If the warehouse answers with an error, that is not a protocol error for MCP but a tool result with "isError": true – that way the model sees what went wrong.

Version 2026-07-28 of the MCP specification is stateless: there is no initialize any more; every request carries the protocol version in the MCP-Protocol-Version header and in the body under _meta. The server here only supports tools/list and tools/call and always answers with JSON instead of an event stream – that is enough for two tools and is allowed.

Step 2 – the building badge. As for the assistant, but for the service account lager-mcp:

# on id1
kubectl create token lager-mcp -n laden --audience http://172.16.0.126:8080/realms/gebaeude --duration 1h > ~/kurs/13/mcp-ausweis.jwt

No output. The badge is valid for one hour; the server reads it afresh on every exchange, and for a longer exercise you simply create a new one.

Step 3 – the systemd unit.

# on id1
sudo nano /etc/systemd/system/lager-mcp.service
/etc/systemd/system/lager-mcp.service new file
[Unit]
Description=Lager-MCP-Server – nimmt nur Tokens für http://172.16.0.126:8091/mcp
After=network-online.target keycloak.service lagerdienst.service

[Service]
User=ubuntu
ExecStart=/usr/bin/python3 /home/ubuntu/kurs/13/mcp_lager.py
Restart=on-failure

[Install]
WantedBy=multi-user.target
# on id1
sudo systemctl daemon-reload
# on id1
sudo systemctl enable --now lager-mcp

Expected:

Created symlink /etc/systemd/system/multi-user.target.wants/lager-mcp.service → /etc/systemd/system/lager-mcp.service.
# on id1
ss -ltnp sport = :8091
  • sport = :8091 – an ss filter: only sockets with source port 8091.

Expected:

State  Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
LISTEN 0      5            0.0.0.0:8091      0.0.0.0:*    users:(("python3",pid=257112,fd=3))

Remember: The tool desk checks every pass itself and goes to the warehouse with its own. The customer’s token leaves it only in the direction of reception.

Save your progress? Sign up for free

Drill 3: From the notice to the tool

Where you are: on id1 and in the browser.

What you have afterwards: walked the path of an MCP client, up to the first tool call.

Step 1 – three requests as files. An MCP call is a JSON-RPC message. Create them as files, so the curl commands stay short:

# on id1
nano ~/kurs/13/liste.json
kurs/13/liste.json new file
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/list",
  "params": {
    "_meta": {
      "io.modelcontextprotocol/protocolVersion": "2026-07-28",
      "io.modelcontextprotocol/clientCapabilities": {}
    }
  }
}
Field Meaning
jsonrpc, id JSON-RPC 2.0; the id comes back in the response
method what the client wants
_meta … protocolVersion mandatory in every request, must match the header
_meta … clientCapabilities mandatory; what the client can do – nothing special here
# on id1
nano ~/kurs/13/bestand.json
kurs/13/bestand.json new file
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "lager_bestand",
    "arguments": {},
    "_meta": {
      "io.modelcontextprotocol/protocolVersion": "2026-07-28",
      "io.modelcontextprotocol/clientCapabilities": {}
    }
  }
}
# on id1
nano ~/kurs/13/ausbuchen.json
kurs/13/ausbuchen.json new file
{
  "jsonrpc": "2.0",
  "id": 3,
  "method": "tools/call",
  "params": {
    "name": "lager_ausbuchen",
    "arguments": {"kisten": 2},
    "_meta": {
      "io.modelcontextprotocol/protocolVersion": "2026-07-28",
      "io.modelcontextprotocol/clientCapabilities": {}
    }
  }
}

Step 2 – knocking without a token.

# on id1
curl -s -i http://172.16.0.126:8091/mcp -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28" -d @$HOME/kurs/13/liste.json
Option Meaning
-i also print the response headers – this is where the important part is
-H "Content-Type: …" the body is JSON
-H "Accept: …" the client understands JSON and event streams – mandatory in MCP
-H "MCP-Protocol-Version: …" protocol version, mandatory in every request
-d @<datei> body from the file

Expected:

HTTP/1.0 401 Unauthorized
Server: BaseHTTP/0.6 Python/3.12.3
Date: Wed, 02 Dec 2026 18:56:55 GMT
Content-Type: application/json; charset=utf-8
WWW-Authenticate: Bearer resource_metadata="http://172.16.0.126:8091/.well-known/oauth-protected-resource/mcp"
Content-Length: 24

{"fehler": "kein Token"}

What you see: WWW-Authenticate: Bearer – “I want a bearer token” –, and resource_metadata names the address of the notice. A client needs nothing more to get started.

Step 3 – reading the notice.

# on id1
curl -s http://172.16.0.126:8091/.well-known/oauth-protected-resource/mcp -o ~/kurs/13/metadaten.json -w "%{http_code}\n"

Expected:

200
# on id1
jq . ~/kurs/13/metadaten.json

Expected:

{
  "resource": "http://172.16.0.126:8091/mcp",
  "authorization_servers": [
    "http://172.16.0.126:8080/realms/gebaeude"
  ],
  "scopes_supported": [
    "lager:lesen",
    "lager:schreiben"
  ],
  "bearer_methods_supported": [
    "header"
  ]
}
Field Meaning
resource who I am – exactly this value must be in aud
authorization_servers where to get tokens
scopes_supported which scopes I know
bearer_methods_supported token only in the Authorization header, not in the URL

The path follows RFC 9728: /.well-known/oauth-protected-resource, followed by the service’s path (/mcp).

Step 4 – the reception’s floor plan. From authorization_servers the client builds the metadata address according to RFC 8414: /.well-known/oauth-authorization-server in front of the issuer’s path:

# on id1
curl -s http://172.16.0.126:8080/.well-known/oauth-authorization-server/realms/gebaeude -o ~/kurs/13/as.json -w "%{http_code}\n"

Expected:

200
# on id1
jq '{issuer, device_authorization_endpoint, token_endpoint}' ~/kurs/13/as.json

Expected:

{
  "issuer": "http://172.16.0.126:8080/realms/gebaeude",
  "device_authorization_endpoint": "http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/auth/device",
  "token_endpoint": "http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/token"
}

What you see: The two addresses for the device login that you have been typing in by hand since Day 9 – here the client found them on its own.

Step 5 – Anna logs in, read-only. The device login as on Day 9, with two differences:

# on id1
curl -s http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/auth/device -d client_id=mcp-cli --data-urlencode 'scope=openid lager:lesen' --data-urlencode resource=http://172.16.0.126:8091/mcp -o ~/kurs/13/geraet-anna.json -w "%{http_code}\n"
  • scope=openid lager:lesen – for now, Anna only allows the tool desk to read. The quotes keep the space together.
  • resource=… – RFC 8707: which service the token is meant for. The MCP specification requires clients to always send it. Whether Keycloak honors it, you check in the challenge.

Expected:

200
# on id1
jq -r .user_code ~/kurs/13/geraet-anna.json

Expected (your code will differ):

JZSK-VOLD

Enter the code in the browser at http://172.16.0.126:8080/realms/gebaeude/device and log in as anna:

The consent page for mcp-cli. The scope lager:lesen is not in the list.

The consent page only names profile, roles and email – lager:lesen is not listed. Only the token itself reveals what really ends up in it.

# on id1
jq -r .device_code ~/kurs/13/geraet-anna.json > ~/kurs/13/geraet-anna-code.txt
# on id1
curl -s http://172.16.0.126:8080/realms/gebaeude/protocol/openid-connect/token -d client_id=mcp-cli -d grant_type=urn:ietf:params:oauth:grant-type:device_code --data-urlencode device_code@$HOME/kurs/13/geraet-anna-code.txt --data-urlencode resource=http://172.16.0.126:8091/mcp -o ~/kurs/13/anmeldung-anna.json -w "%{http_code}\n"

Expected:

200
# on id1
jq -r .access_token ~/kurs/13/anmeldung-anna.json > ~/kurs/13/anna.jwt
# on id1
step crypto jwt inspect --insecure < ~/kurs/13/anna.jwt

Expected (excerpt):

    "aud": [
      "http://172.16.0.126:8091/mcp",
      "account"
    ],
    "sub": "ebaf76a2-697c-40f3-910a-75e4d935cb6c",
    "typ": "Bearer",
    "azp": "mcp-cli",
    "scope": "openid profile email lager:lesen",
    "preferred_username": "anna",

What you see: aud names the tool desk, scope contains only lager:lesen. From now on you have five minutes for the next steps.

Step 6 – with a token: which tools are there? Header file as on Day 9:

# on id1
jq -r '"Authorization: Bearer " + .access_token' ~/kurs/13/anmeldung-anna.json > ~/kurs/13/kopf-anna.txt
# on id1
sudo systemctl restart lagerdienst
# on id1
curl -s http://172.16.0.126:8091/mcp -H @$HOME/kurs/13/kopf-anna.txt -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28" -d @$HOME/kurs/13/liste.json -o ~/kurs/13/antwort.json -w "%{http_code}\n"

Expected:

200
# on id1
jq . ~/kurs/13/antwort.json

Expected:

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "tools": [
      {
        "name": "lager_bestand",
        "description": "Liefert den Lagerbestand in Kisten und den Lieferschein.",
        "inputSchema": {
          "type": "object",
          "properties": {}
        }
      },
      {
        "name": "lager_ausbuchen",
        "description": "Bucht Kisten aus dem Lager aus.",
        "inputSchema": {
          "type": "object",
          "properties": {
            "kisten": {
              "type": "integer"
            }
          },
          "required": [
            "kisten"
          ]
        }
      }
    ]
  }
}

What you see: Both tools with description and input schema – a model reads this to decide what to call. tools/list needs no warehouse scope, just a valid token.

Step 7 – calling a tool. The same command with bestand.json:

# on id1
curl -s http://172.16.0.126:8091/mcp -H @$HOME/kurs/13/kopf-anna.txt -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28" -d @$HOME/kurs/13/bestand.json -o ~/kurs/13/antwort.json -w "%{http_code}\n"

Expected:

200
# on id1
jq . ~/kurs/13/antwort.json

Expected:

{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "{\"kisten\": 42, \"lieferschein\": \"Lieferung vom Montag: 12 Kisten Äpfel, Lieferant Obsthof Krause.\"}"
      }
    ],
    "isError": false
  }
}

Step 8 – two visitor logs.

# on id1
journalctl -u lager-mcp --since "-3 min" --no-pager -o cat --grep WERKZEUG

Expected:

WERKZEUG lager_bestand sub=ebaf76a2-697c-40f3-910a-75e4d935cb6c azp=mcp-cli name=anna
# on id1
journalctl -u lagerdienst --since "-3 min" --no-pager -o cat --grep "BESTAND|AUSGEBUCHT"

Expected:

BESTAND sub=ebaf76a2-697c-40f3-910a-75e4d935cb6c azp=http://172.16.0.126:8091/mcp name=anna

What you see: At the tool desk, Anna came through mcp-cli. At the warehouse, Anna came through the tool desk – the warehouse saw a different pass than the tool desk.

Remember: Notice → reception → pass → tool. An MCP client only needs the server’s address; the 401 tells it everything else.

Save your progress? Sign up for free

Drill 4: “For that you need the write endorsement”

Where you are: on id1, Anna’s token from Drill 3 still valid.

What you have afterwards: seen the step-up – from read token to write token – and that it does not work for Ben.

Step 1 – checking out with the read token.

# on id1
curl -s -i http://172.16.0.126:8091/mcp -H @$HOME/kurs/13/kopf-anna.txt -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28" -d @$HOME/kurs/13/ausbuchen.json

Expected:

HTTP/1.0 403 Forbidden
Server: BaseHTTP/0.6 Python/3.12.3
Date: Wed, 02 Dec 2026 18:57:42 GMT
Content-Type: application/json; charset=utf-8
WWW-Authenticate: Bearer error="insufficient_scope", scope="lager:schreiben", resource_metadata="http://172.16.0.126:8091/.well-known/oauth-protected-resource/mcp"
Content-Length: 43

{"fehler": "Bereich lager:schreiben fehlt"}
Part Meaning
403 instead of 401 the token is valid, it just is not enough
error="insufficient_scope" error code from RFC 6750
scope="lager:schreiben" exactly the missing scope – the client does not have to guess
resource_metadata as with 401, so the client finds the notice

Step 2 – step-up. An MCP client now requests a new token, with the previous scopes plus the one from the response. Anna logs in again, as in Drill 3, step 5 – with scope=openid lager:lesen lager:schreiben and the file names geraet-anna2.json, geraet-anna2-code.txt and anmeldung-anna2.json. Then:

# on id1
jq -r .scope ~/kurs/13/anmeldung-anna2.json

Expected:

openid profile lager:schreiben email lager:lesen
# on id1
jq -r '"Authorization: Bearer " + .access_token' ~/kurs/13/anmeldung-anna2.json > ~/kurs/13/kopf-anna2.txt
# on id1
curl -s http://172.16.0.126:8091/mcp -H @$HOME/kurs/13/kopf-anna2.txt -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28" -d @$HOME/kurs/13/ausbuchen.json -o ~/kurs/13/antwort.json -w "%{http_code}\n"

Expected:

200
# on id1
jq . ~/kurs/13/antwort.json

Expected:

{
  "jsonrpc": "2.0",
  "id": 3,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "{\"ausgebucht\": 2, \"kisten\": 40}"
      }
    ],
    "isError": false
  }
}

Step 3 – Ben tries the same. Ben logs in like Anna in step 2, in a private browser window, with the file names geraet-ben.json, geraet-ben-code.txt and anmeldung-ben.json:

# on id1
jq -r .scope ~/kurs/13/anmeldung-ben.json

Expected:

openid profile email lager:lesen
# on id1
jq -r '"Authorization: Bearer " + .access_token' ~/kurs/13/anmeldung-ben.json > ~/kurs/13/kopf-ben.txt
# on id1
curl -s -i http://172.16.0.126:8091/mcp -H @$HOME/kurs/13/kopf-ben.txt -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28" -d @$HOME/kurs/13/ausbuchen.json

Expected:

HTTP/1.0 403 Forbidden
Server: BaseHTTP/0.6 Python/3.12.3
Date: Wed, 02 Dec 2026 18:58:22 GMT
Content-Type: application/json; charset=utf-8
WWW-Authenticate: Bearer error="insufficient_scope", scope="lager:schreiben", resource_metadata="http://172.16.0.126:8091/.well-known/oauth-protected-resource/mcp"
Content-Length: 43

{"fehler": "Bereich lager:schreiben fehlt"}

What you see: Ben requested lager:schreiben and silently did not get it (Day 11). A client that simply tries step-up again now ends up in a loop. That is why the MCP specification requires a limit: give up after a few attempts.

# on id1
journalctl -u lagerdienst --since "-3 min" --no-pager -o cat --grep AUSGEBUCHT

Expected:

AUSGEBUCHT kisten=2 sub=ebaf76a2-697c-40f3-910a-75e4d935cb6c azp=http://172.16.0.126:8091/mcp name=anna

Remember: 401 means “no valid pass”, 403 with insufficient_scope means “pass valid, endorsement missing” – and names the endorsement. More than one or two step-up attempts are pointless.

Save your progress? Sign up for free

Diagnosis task

Anna still has a token from logging in to the assistant (assistent-cli, as on Day 11) and tries it at the tool desk. Because they read that MCP clients should send resource, they did that too: the commands from Drill 3, step 5 with client_id=assistent-cli, scope=openid and the file names geraet-anna-assistent.json, geraet-anna-assistent-code.txt, anmeldung-anna-assistent.json. Then:

# on id1
jq -r '"Authorization: Bearer " + .access_token' ~/kurs/13/anmeldung-anna-assistent.json > ~/kurs/13/kopf-falsch.txt
# on id1
curl -s -i http://172.16.0.126:8091/mcp -H @$HOME/kurs/13/kopf-falsch.txt -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28" -d @$HOME/kurs/13/liste.json

Expected:

HTTP/1.0 401 Unauthorized
Server: BaseHTTP/0.6 Python/3.12.3
Date: Wed, 02 Dec 2026 18:58:48 GMT
Content-Type: application/json; charset=utf-8
WWW-Authenticate: Bearer resource_metadata="http://172.16.0.126:8091/.well-known/oauth-protected-resource/mcp", error="invalid_token", error_description="Audience doesn't match"
Content-Length: 36

{"fehler": "Audience doesn't match"}

They did specify resource=http://172.16.0.126:8091/mcp. Why does the audience not match?

Solution path:

  1. error_description="Audience doesn't match" – the check in line 47 kicked in. What is in the token? First put the token from the response into a file of its own:

    # on id1
    jq -r .access_token ~/kurs/13/anmeldung-anna-assistent.json > ~/kurs/13/anna-assistent.jwt
    # on id1
    step crypto jwt inspect --insecure < ~/kurs/13/anna-assistent.jwt > ~/kurs/13/anna-assistent-inhalt.json
    # on id1
    jq '.payload | {aud, azp, scope}' ~/kurs/13/anna-assistent-inhalt.json

    Expected:

    {
      "aud": [
        "assistent",
        "account"
      ],
      "azp": "assistent-cli",
      "scope": "openid profile email"
    }
  2. aud names the assistant, not the tool desk. The resource parameter had no effect: Keycloak 26.8 does not evaluate resource in this login. The audience comes solely from the client’s mapper – for assistent-cli that is fuer-assistent.

  3. The tool desk does everything right. It must not accept a token meant for the assistant, otherwise every service Anna has given a token to could also call tools with it.

  4. Solution: Anna logs in to mcp-cli. Sending resource to every client anyway is not wrong – it does no harm and takes effect as soon as reception supports it.

The lesson: with Keycloak, the client you log in to decides the audience – not a parameter in the request.

Challenge

A colleague finds the exchange in lagerschein() cumbersome: “The client’s token is valid and it’s Anna’s. Just pass it on to the warehouse.” And a second one thinks the protocol version check is unnecessary. What happens in each case? Write down your guess, then check with Anna’s write token from Drill 4.

Solution 1 – passing it on. What the warehouse does with Anna’s token for the tool desk:

# on id1
curl -s -w "\n%{http_code}\n" http://127.0.0.1:8090/bestand -H @$HOME/kurs/13/kopf-anna2.txt

Expected:

{"fehler": "Schein ungültig: Audience doesn't match"}
401

The warehouse rejects it because it has required aud=lager since Day 10. That is exactly the protection that the passthrough ban in the MCP specification secures: if a service accepts tokens for other audiences, any MCP server a human gives a token to can use it to call all of that human’s other services – without a trace that it was the server. So passing tokens on is not more cumbersome or simpler; it is either broken (as here) or dangerous (if the warehouse did not check aud). With the exchange, the warehouse also sees azp=http://172.16.0.126:8091/mcp and knows who brought the request.

Solution 2 – without a protocol version. The same call as in Drill 3, step 6, but without the MCP-Protocol-Version header:

# on id1
curl -s -w "\n%{http_code}\n" http://172.16.0.126:8091/mcp -H @$HOME/kurs/13/kopf-anna2.txt -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -d @$HOME/kurs/13/liste.json

Expected:

{"jsonrpc": "2.0", "id": 1, "error": {"code": -32602, "message": "nur Protokollversion 2026-07-28"}}
400

The check is not a security barrier but contract compliance: a server that accepts requests in a version it does not know may interpret them wrongly. Note the order in the program: first the token (line 120), then the version (line 131). Anyone coming without a valid token does not even learn which version the server speaks.

Save your progress? Sign up for free

Checkpoint

# on id1
systemctl is-active lager-mcp

Expected:

active
# on id1
jq . ~/kurs/13/metadaten.json

Expected: resource is http://172.16.0.126:8091/mcp, authorization_servers names the realm gebaeude (output as in Drill 3, step 3).

# on id1
curl -s -i http://172.16.0.126:8091/mcp -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28" -d @$HOME/kurs/13/liste.json

Expected: 401 Unauthorized and a line WWW-Authenticate: Bearer resource_metadata=… (as in Drill 3, step 2).

Test yourself

  1. An MCP client only knows http://172.16.0.126:8091/mcp. How does it find out where to get a token?
  2. What is the difference between a 401 response and a 403 insufficient_scope response?
  3. Why is the MCP server’s clientId its address?
  4. Why must the MCP server not pass Anna’s token on to the warehouse, even though it is Anna’s?
  5. Anna sends resource=http://172.16.0.126:8091/mcp but logs in to assistent-cli. What is in aud, and why?
  6. Ben gets 403 again after the step-up. What should a good MCP client do now?

Answers:

  1. It calls the server without a token and gets 401 with resource_metadata in WWW-Authenticate. The notice names the reception desk in authorization_servers, and the reception’s metadata (RFC 8414) names the addresses for login and tokens.
  2. 401: no token or an invalid one (wrong audience, expired, wrong signature). 403 insufficient_scope: token valid, but the scope for this tool is missing – the response names it in scope.
  3. So that the value in aud (which the server checks) and the client that has to be in aud during the exchange are the same – and it matches the resource in the notice.
  4. The token was issued for the tool desk, not for the warehouse. A warehouse that accepted it would trust every service Anna has ever given a token to. Instead, the server exchanges it, and the warehouse sees who brings the pass.
  5. assistent and account. Keycloak 26.8 does not evaluate resource here; the audience comes from the mapper of the client they log in to.
  6. Give up and tell the human that they lack the permission – no endless step-up loop.

Interview note

“How do you secure a remote MCP server?” – Good answer: The MCP server is an OAuth 2.1 resource server. It publishes Protected Resource Metadata according to RFC 9728 and points to it on 401 via WWW-Authenticate; this is how clients find the authorization server, and they send the resource parameter according to RFC 8707. The server only accepts tokens whose audience is itself, checks the scope per tool and answers with 403 insufficient_scope including the required scope for the step-up. When it calls upstream APIs, it never passes the token through but gets its own via token exchange or its own client authentication. In addition: if the IdP does not support resource indicators – like Keycloak –, the audience has to be established through client configuration.

Enterprise note

  • HTTPS is mandatory. In the lab everything runs over HTTP. The MCP specification requires HTTPS for all authorization server endpoints, and bearer tokens over unencrypted HTTP can be read by anyone listening.
  • Building badge from the projection. Today the MCP server reads a badge that you created with kubectl create token. If it runs as a pod, the badge comes as a projected token (Day 2) and is renewed by Kubernetes.
  • Registering clients. Real MCP clients register dynamically or via client ID metadata documents. In the lab you created mcp-cli by hand. Allow dynamic registration in Keycloak only with policies (Client Registration Policies), otherwise anyone can create as many clients as they like.
  • One MCP server, many tools. The tool → scope mapping belongs in the server and in scopes_supported, not in the agents. Prefer fine-grained scopes (lager:schreiben) over coarse ones (lager).

Summary

  • The MCP server lager-mcp on port 8091 has its own client with its address as clientId, authenticates with the Kubernetes token of lager-mcp and may exchange tokens.
  • Without a token: 401 with resource_metadata; the notice names resource, authorization_servers and scopes_supported; a client finds the reception’s metadata according to RFC 8414.
  • Humans log in to mcp-cli; the mapper fuer-mcp writes the MCP server’s address into aud. The client sends resource, but Keycloak 26.8 does not evaluate it.
  • One scope per tool; if it is missing: 403 insufficient_scope with the required scope. Step-up works for Anna, not for Ben.
  • The server goes to the warehouse with an exchanged pass; the warehouse sees azp=http://172.16.0.126:8091/mcp. Passed through, Anna’s token would fail at the warehouse.
  • The server rejects tokens for other clients (assistent-cli) with “Audience doesn’t match”.

Commands at a glance

Command What for
curl -s -i <mcp> -H "MCP-Protocol-Version: 2026-07-28" -d @<anfrage.json> MCP call with response headers
curl -s <server>/.well-known/oauth-protected-resource/<pfad> read Protected Resource Metadata
curl -s <host>/.well-known/oauth-authorization-server/<pfad-des-ausstellers> metadata of the reception desk (RFC 8414)
… auth/device … --data-urlencode 'scope=…' --data-urlencode resource=<mcp> login for an MCP server
kcadm.sh create clients -s clientId=<url> -s clientAuthenticatorType=federated-jwt … client for an MCP server
… -s 'config."included.client.audience"=<clientId>' tokens of a client for the MCP server
journalctl -u lager-mcp --grep WERKZEUG visitor log of the tool desk

Contents

More