Day 13: Authorization II
Goal: Grant rights per tool with scopes and step-up, try the three ways of client registration, and build a server that calls a second server on behalf of a human – without token passthrough and without a confused deputy · Duration: about 3 h · Prerequisite: Day 12
Where we start
# on cp1
curl -s http://worker1:8004/.well-known/oauth-protected-resource/mcp | jq -r '.authorization_servers[0]'Expected:
http://worker2:8080/realms/mcpa
# on cp1
ls ~/mcpa/tag12/anmeldung.pyExpected:
/home/ubuntu/mcpa/tag12/anmeldung.py
Keycloak runs on worker2 in one terminal, pforte (gate)
from Day 12 on worker1 in another. If one of them is not running, start
it with the command from Day 12, Drill 1 or Drill 4. Today you need two
terminals on every VM.
Introduction
Since Day 12, only someone with a token gets through to
pforte. But every token may do everything there: whoever
may call wer_bin_ich (who am I) could also call a tool that
changes something. And pforte is alone: no server calls
another, and Keycloak only knows clients that an admin created by
hand.
Today things get tighter and more open at the same time. A writing
tool requires a scope of its own, and the client only fetches it when it
needs it – step-up. You let an unknown client register
itself, once via the older Dynamic Client Registration
and once via Client ID Metadata Documents, the way the
specification prefers today. Finally, pforte calls a second
protected server, an archive. You try three ways: simply passing the
token on, accessing with its own rights, and exchanging the token. Only
one of them is right, and the two wrong ones are instructive.
Today you learn:
- how a server asks for more rights with
403andinsufficient_scope, and how a client reacts to it, - in which order an MCP client gets its client ID: pre-registered, CIMD, Dynamic Client Registration,
- why a registered client is not yet an authorized client,
- why an MCP server must never pass on tokens it received,
- what a confused deputy is and what it looks like in the lab,
- how Token Exchange (RFC 8693) gives a server access on behalf of the human.
Background
The picture for today: floors, sign-up and errands
The key card from Day 12 no longer opens every door in the contractor’s building.
- Scopes are the floors on the card:
with
mcp:toolsyou get onto the ground floor (reading); for the first floor (mcp:write) the card needs another entry. - Step-up means: the door on the first floor says “this floor is missing from your card”, and the concierge goes back to the front desk with the guest to have it added.
- Client registration is the question of how a concierge becomes known to the front desk at all: entered by the hotel (pre-registered), signing up himself (DCR), or with a business card whose address anyone can check (CIMD).
- If the contractor sends a messenger to a second contractor, he must not simply hand the messenger the guest’s card (token passthrough) or his own master key (confused deputy). The right way is a new card, issued for the guest and the second door (token exchange).
The terms
| Term | Meaning | in the picture |
|---|---|---|
| scope | what the client may do on the person’s behalf | floor on the card |
| step-up | requesting more scopes later | having the card extended at the front desk |
| DCR | Dynamic Client Registration: the client signs itself up | the concierge enters himself |
| CIMD | Client ID Metadata Document: the client ID is a URL with metadata | business card with a checkable address |
| token passthrough | passing the person’s token on to another server | giving the messenger the guest card |
| confused deputy | a server uses its own rights for someone else’s request | giving the messenger the master key |
| token exchange | a new token for the person and the second server | a new card for guest and second door |
Remember: A card always names the guest, the door and the floors. Whoever passes something on needs a new card – never the old one and never the master key.
Scopes and step-up
A scope describes what the client
may do on behalf of the human. It says nothing about what the human may
do themselves – those are roles and rights in the server or in the
identity provider. Both limits apply at the same time: Anna may be
allowed to write, but a host that only requested mcp:tools
still does not write on her behalf.
Good clients initially request only the scopes they need for the first steps, and extend later. There is a fixed protocol for this:
- The server notices during a request that the token lacks a scope. It
responds with
403 ForbiddenandWWW-Authenticate: Bearer error="insufficient_scope", scope="…", resource_metadata="…". - The client reads
scopefrom the header. These scopes are authoritative for this call – even if they are not listed inscopes_supported. - It requests a new token, namely for the union of the previous and the new scopes. That way it loses nothing it already had.
- After signing in, it repeats the call. If it fails again, it tries at most a few more times and then gives up.
For comparison: 401 means “no token or no valid token”,
403 with insufficient_scope means “valid
token, but not enough rights”.
Where a client gets its client ID
Before a client can sign in, it needs a client ID at the authorization server. The specification names three ways and an order:
| Rank | Way | when | in the lab |
|---|---|---|---|
| 1 | pre-registered | client and server know each other, an admin created the client | leitstand-host from Day 12 |
| 2 | Client ID Metadata Document (CIMD) | the authorization server announces
client_id_metadata_document_supported |
Drill 4 |
| 3 | Dynamic Client Registration (DCR) | the authorization server has a
registration_endpoint |
Drill 3 |
| 4 | ask the human | none of this works | – |
With CIMD, the client ID is an HTTPS URL with a
path, for example https://host.example.com/client.json. At
this URL there is a JSON document with client_id (exactly
the same URL), client_name and redirect_uris.
The authorization server fetches it itself at the first sign-in. Nobody
has to register anything beforehand, and the client proves who it is
through its domain. Because the authorization server calls foreign URLs
in the process, it must protect itself: only allowed domains, size
limits, no access to its own network.
DCR (RFC 7591) was the old way: the client sends its data to an open endpoint and receives a fresh client ID. Anyone can create as many clients as they like this way, and the authorization server does not know who is behind them. With version 2026-07-28, DCR is deprecated in MCP and remains allowed only for a while for older clients.
A client ID is always valid only at the authorization server that issued it. A client must not use it at a different one. CIMD URLs are an exception: they are valid wherever the document can be fetched.
A server calls a server
Often an MCP server itself needs data from another service. How does it get a token for that?
- Token passthrough means simply forwarding the received token. The specification explicitly forbids this: an MCP server may only accept tokens issued for it and must not pass them on to other services. The second service would accept a token not intended for it, its own checks (audience, rate limits, logging) would be bypassed, and the log would not show who really asked.
- Its own rights means the server signs in with its own account (client credentials) and asks with its own, usually broad, rights. Then anyone who may use the server can do everything the server can. That is exactly a confused deputy: a deputy with many rights who lets someone with few rights talk it into something.
- Token Exchange (RFC 8693) means the server
exchanges the received token at the authorization server for a new one –
for the second service, but still on behalf of the same
human. The second service sees the human and checks their
rights. The
azpfield shows which server did the exchange.
The specification describes another confused deputy: an MCP server that acts as a proxy in front of a third-party API and is registered there with one fixed client ID. Once a human has consented to this client ID, the third-party API remembers it. An attacker registers their own client with their own redirect URI at the proxy, sends the human a link – and the third-party API does not ask again. The code ends up with the attacker. That is why such a proxy must obtain the human’s consent itself for every client registered with it.
Drill 1: A scope for writing
Where you are: on worker2 in the second terminal, then on worker1 and cp1.
What you have afterwards: a scope
mcp:write, the newpfortewith a writing tool, and a403 insufficient_scoperesponse.
Step 1 – the scope in Keycloak.
# on worker2
cd ~/keycloak-26.8.2/bin# on worker2
./kcadm.sh config credentials --server http://localhost:8080 --realm master --user admin --password labor-admin# on worker2
./kcadm.sh create client-scopes -r mcpa -s name=mcp:write -s protocol=openid-connect -s 'attributes."include.in.token.scope"=true' -s 'attributes."display.on.consent.screen"=false'# on worker2
HOST=$(./kcadm.sh get clients -r mcpa -q clientId=leitstand-host --fields id --format csv --noquotes)# on worker2
WRITE=$(./kcadm.sh get client-scopes -r mcpa --fields id,name --format csv --noquotes | grep ',mcp:write$' | cut -d, -f1)# on worker2
./kcadm.sh update clients/$HOST/optional-client-scopes/$WRITE -r mcpa# on worker2
./kcadm.sh get clients/$HOST/optional-client-scopes -r mcpa --fields name --format csv --noquotesThis is the same procedure as for mcp:tools in Day 12,
Drill 3: create the scope, fetch the IDs, assign the scope to the host
as an optional scope. So the host only gets
mcp:write when it explicitly asks for it.
Expected (the last list; the order may differ):
address
mcp:write
phone
offline_access
organization
mcp:tools
microprofile-jwt
Step 2 – the new pforte. Stop pforte
from Day 12 on worker1 with Ctrl+C. The new version gets
its own directory:
# on worker1
mkdir -p ~/mcpa/tag13 && cd ~/mcpa/tag13# on worker1
nano pforte.pyimport os
import shutil
from datetime import datetime
from pathlib import Path
import httpx2
import jwt
import uvicorn
from mcp import Client
from mcp.client.streamable_http import streamable_http_client
from mcp.server import MCPServer
from mcp.server.auth.middleware.auth_context import get_access_token
from mcp.server.auth.provider import AccessToken
from mcp.server.auth.settings import AuthSettings
from mcp.server.mcpserver.exceptions import ToolError
from mcp.server.transport_security import TransportSecuritySettings
from mcp.shared.exceptions import MCPError
from mcp.types import ToolAnnotations
AUSSTELLER = "http://worker2:8080/realms/mcpa"
TOKEN_ENDPUNKT = f"{AUSSTELLER}/protocol/openid-connect/token"
RESSOURCE = "http://worker1:8004/mcp"
ARCHIV = "http://worker1:8005/mcp"
METADATEN = "http://worker1:8004/.well-known/oauth-protected-resource/mcp"
NOTIZEN = Path("notizen.txt")
MODUS = os.environ.get("PFORTE_MODUS", "tausch")
GEHEIMNIS = os.environ.get("PFORTE_GEHEIMNIS", "")
# tools that need more than mcp:tools
EXTRA_SCOPES = {"notiz_schreiben": "mcp:write"}
schluessel = jwt.PyJWKClient(f"{AUSSTELLER}/protocol/openid-connect/certs")
class KeycloakPruefer:
"""Prüft Access Tokens von Keycloak: Signatur, Aussteller, Ablauf und Audience."""
async def verify_token(self, token: str) -> AccessToken | None:
try:
signatur = schluessel.get_signing_key_from_jwt(token)
claims = jwt.decode(
token,
signatur.key,
algorithms=["RS256"],
issuer=AUSSTELLER,
audience=RESSOURCE,
)
except jwt.PyJWTError as fehler:
print(f"[pforte] Token abgelehnt: {fehler}", flush=True)
return None
return AccessToken(
token=token,
client_id=claims["azp"],
scopes=claims.get("scope", "").split(),
expires_at=claims["exp"],
resource=RESSOURCE,
subject=claims["sub"],
claims=claims,
)
pruefer = KeycloakPruefer()
class ScopeWaechter:
"""Antwortet mit 403 insufficient_scope, wenn ein Werkzeug mehr Scopes braucht."""
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] == "http":
kopf = {k.decode().lower(): v.decode() for k, v in scope["headers"]}
noetig = None
if kopf.get("mcp-method") == "tools/call":
noetig = EXTRA_SCOPES.get(kopf.get("mcp-name", ""))
bearer = kopf.get("authorization", "")
if noetig and bearer.lower().startswith("bearer "):
token = await pruefer.verify_token(bearer[7:])
if token and noetig not in token.scopes:
print(f"[pforte] {kopf['mcp-name']} braucht {noetig}", flush=True)
challenge = (
f'Bearer error="insufficient_scope", '
f'scope="mcp:tools {noetig}", resource_metadata="{METADATEN}"'
)
await send({
"type": "http.response.start",
"status": 403,
"headers": [(b"www-authenticate", challenge.encode())],
})
await send({"type": "http.response.body", "body": b""})
return
await self.app(scope, receive, send)
mcp = MCPServer(
"pforte",
instructions="Geschützter Server auf worker1. Jeder Aufruf braucht ein Token.",
token_verifier=pruefer,
auth=AuthSettings(
issuer_url=AUSSTELLER,
resource_server_url=RESSOURCE,
required_scopes=["mcp:tools"],
validate_token_resource=False,
),
)
@mcp.tool(title="Wer bin ich", annotations=ToolAnnotations(read_only_hint=True))
def wer_bin_ich() -> str:
"""Zeigt, mit welchem Token der Aufruf kam: Benutzer, Client und Scopes."""
token = get_access_token()
scopes = " ".join(token.scopes)
return f"sub={token.subject} client={token.client_id} scopes={scopes}"
@mcp.tool(title="Speicher auf worker1", annotations=ToolAnnotations(read_only_hint=True))
def speicher() -> str:
"""Belegter Speicher des Dateisystems / auf worker1 in Prozent."""
belegt = shutil.disk_usage("/")
return f"{belegt.used / belegt.total * 100:.1f} % belegt"
@mcp.tool(title="Notiz schreiben", annotations=ToolAnnotations(read_only_hint=False))
def notiz_schreiben(text: str) -> str:
"""Hängt eine Notiz an notizen.txt auf worker1 an. Braucht den Scope mcp:write."""
wer = get_access_token().claims["preferred_username"]
with NOTIZEN.open("a") as datei:
datei.write(f"{datetime.now():%H:%M} {wer}: {text}\n")
return f"Notiz von {wer} gespeichert."
async def token_fuer_archiv() -> str:
"""Besorgt das Token, mit dem pforte das Archiv aufruft – je nach MODUS."""
eigenes = get_access_token().token
if MODUS == "durchreichen":
return eigenes
async with httpx2.AsyncClient() as http:
if MODUS == "eigenes":
daten = {"grant_type": "client_credentials"}
else:
daten = {
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"subject_token": eigenes,
"subject_token_type": "urn:ietf:params:oauth:token-type:access_token",
"audience": ARCHIV,
}
# pforte authenticates with client ID and secret (client_secret_post)
daten |= {"client_id": RESSOURCE, "client_secret": GEHEIMNIS}
antwort = await http.post(TOKEN_ENDPUNKT, data=daten)
if antwort.status_code != 200:
raise ToolError(f"Keycloak: {antwort.json().get('error_description')}")
return antwort.json()["access_token"]
@mcp.tool(title="Archiv lesen", annotations=ToolAnnotations(read_only_hint=True))
async def archiv_lesen() -> str:
"""Liest die Betriebsberichte aus dem Archiv auf worker1."""
print(f"[pforte] archiv_lesen im Modus {MODUS}", flush=True)
token = await token_fuer_archiv()
# for display only: read the content without verification – the archive verifies itself
inhalt = jwt.decode(token, options={"verify_signature": False})
wer, aud = inhalt["preferred_username"], inhalt["aud"]
print(f"[pforte] ans Archiv: {wer} aud={aud}", flush=True)
kopf = {"Authorization": f"Bearer {token}"}
abgelehnt = None
try:
async with httpx2.AsyncClient(headers=kopf) as http:
transport = streamable_http_client(ARCHIV, http_client=http)
async with Client(transport) as archiv:
ergebnis = await archiv.call_tool("eintraege", {})
except* MCPError as gruppe:
# the SDK nests errors in task groups; the innermost one is the real one
abgelehnt = gruppe
while isinstance(abgelehnt, BaseExceptionGroup):
abgelehnt = abgelehnt.exceptions[0]
if abgelehnt:
raise ToolError(f"Archiv lehnt ab: {abgelehnt}")
text = ergebnis.content[0].text
if ergebnis.is_error:
raise ToolError(f"Archiv: {text}")
return text
schutz = TransportSecuritySettings(
enable_dns_rebinding_protection=True,
allowed_hosts=["worker1:8004", "172.16.0.228:8004"],
allowed_origins=[],
)
app = mcp.streamable_http_app(transport_security=schutz)
uvicorn.run(ScopeWaechter(app), host="0.0.0.0", port=8004)# on worker1
uv run python pforte.pyExpected (the last line):
INFO: Uvicorn running on http://0.0.0.0:8004 (Press CTRL+C to quit)
The file already contains everything for today. You only need the
part from token_fuer_archiv (token for archive) onward
starting with Drill 6, where it is explained. New for this drill:
EXTRA_SCOPESassigns additional scopes to tools.notiz_schreiben(write note) needsmcp:write. Every request needsmcp:toolsanyway (required_scopes).ScopeWaechter(scope guard) is an ASGI middleware: a piece of code that sees every HTTP request before it reaches the MCP server.scope["headers"]are the headers as bytes. The guard reads theMcp-MethodandMcp-Nameheaders from Day 8. Fortools/callof a tool listed inEXTRA_SCOPES, it verifies the token itself with the samepruefer(verifier) and checks whether the scope is in it. If it is missing, it immediately sends back403with theWWW-Authenticateheader:error, the required scopes – the previous ones and the new one, so the client loses nothing – and the URL of the metadata.- The guard may trust the headers because the MCP server compares them
with the content of the request (Day 8). Whoever sends
Mcp-Name: wer_bin_ichand callsnotiz_schreibengets-32020. - If the token is invalid or missing, the guard lets the request
through. The SDK then sends the
401as before. - In version 2.3.0 the SDK only knows scopes for the whole server.
That is why the guard sits in front of the app:
mcp.streamable_http_app(…)returns the server’s ASGI app,uvicorn.run(ScopeWaechter(app), …)starts it with the guard in front. Until now,mcp.run(…)did both in one step. notiz_schreibenappends a line tonotizen.txt, with time and user. The name comes from thepreferred_usernameclaim. That is whyKeycloakPruefernow passes all claims to theAccessTokenwithclaims=claims.
Step 3 – a token without mcp:write. Get
a token as in Day 12, Drill 5, this time with
state=drill1:
# on cp1
mkdir -p ~/mcpa/tag13 && cd ~/mcpa/tag13# on cp1
AUTH=http://worker2:8080/realms/mcpa/protocol/openid-connect# on cp1
VERIFIER=$(openssl rand -base64 48 | tr -d '=+/\n')# on cp1
CHALLENGE=$(printf %s "$VERIFIER" | openssl dgst -sha256 -binary | base64 | tr '+/' '-_' | tr -d '=')# on cp1
URL="$AUTH/auth?response_type=code&client_id=leitstand-host"# on cp1
URL="$URL&redirect_uri=http%3A%2F%2Flocalhost%3A3030%2Fcallback"# on cp1
URL="$URL&scope=mcp%3Atools&state=drill1"# on cp1
URL="$URL&code_challenge=$CHALLENGE&code_challenge_method=S256"# on cp1
URL="$URL&resource=http%3A%2F%2Fworker1%3A8004%2Fmcp"# on cp1
echo "$URL"Open the URL in the browser (you are probably still signed in) and exchange the code:
# on cp1, in ~/mcpa/tag13 – insert the URL from your browser
ANTWORT='http://localhost:3030/callback?state=drill1&…&code=…'# on cp1, in ~/mcpa/tag13 – insert the URL from your browser
CODE=$(echo "$ANTWORT" | sed -n 's/.*[?&]code=\([^&]*\).*/\1/p')# on cp1, in ~/mcpa/tag13 – insert the URL from your browser
curl -s $AUTH/token -d grant_type=authorization_code -d client_id=leitstand-host -d "code=$CODE" -d redirect_uri=http://localhost:3030/callback -d "code_verifier=$VERIFIER" --data-urlencode resource=http://worker1:8004/mcp > token.json# on cp1, in ~/mcpa/tag13 – insert the URL from your browser
TOKEN=$(jq -r .access_token token.json)Use it to call notiz_schreiben:
# on cp1, in ~/mcpa/tag13
KOPF=(-H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28")# on cp1, in ~/mcpa/tag13
nano notiz.json{"jsonrpc": "2.0", "id": 1, "method": "tools/call",
"params": {"name": "notiz_schreiben", "arguments": {"text": "Backup geprüft"},
"_meta": {"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {}}}}# on cp1, in ~/mcpa/tag13
curl -si http://worker1:8004/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: notiz_schreiben" -H "Authorization: Bearer $TOKEN" --data @notiz.json | grep -i -E "^HTTP|^www-authenticate"Expected:
HTTP/1.1 403 Forbidden
www-authenticate: Bearer error="insufficient_scope", scope="mcp:tools mcp:write", resource_metadata="http://worker1:8004/.well-known/oauth-protected-resource/mcp"
and on worker1:
[pforte] notiz_schreiben braucht mcp:write (“needs
mcp:write”)
The token is valid – wer_bin_ich would still work with
it. It is just not enough for this one tool.
Remember: The card is genuine, but the floor is missing:
403withinsufficient_scopeinstead of401. The door says exactly which entry is missing.
Save your progress? Sign up for free
Drill 2: Step-up with the SDK
Where you are: on cp1, in
~/mcpa/tag13.What you have afterwards: a small program that calls any tool of
pforte, and a step-up in which the SDK fetchesmcp:writeby itself.
# on cp1, in ~/mcpa/tag13
cp ../tag12/anmeldung.py .# on cp1, in ~/mcpa/tag13
nano rufen.pyimport asyncio
import json
import sys
import httpx2
from mcp import Client
from mcp.client.streamable_http import streamable_http_client
from anmeldung import anmeldung_fuer
URL = "http://worker1:8004/mcp"
async def main(werkzeug: str, argumente: dict) -> None:
async with httpx2.AsyncClient(auth=anmeldung_fuer(URL)) as http:
async with Client(streamable_http_client(URL, http_client=http)) as client:
ergebnis = await client.call_tool(werkzeug, argumente)
art = "FEHLER" if ergebnis.is_error else "OK"
print(f"{werkzeug} [{art}]: {ergebnis.content[0].text}")
asyncio.run(main(sys.argv[1], json.loads(sys.argv[2]) if len(sys.argv) > 2 else {}))# on cp1, in ~/mcpa/tag13
uv run python rufen.py notiz_schreiben '{"text": "Dienst neu gestartet"}'rufen.py(call) calls the tool you pass as the first argument. The second argument is the tool’s arguments as JSON.json.loadsturns it into a dictionary; without a second argument it stays empty ({}).anmeldung.pyis the same file as in Day 12.tokens.jsondoes not exist in this directory yet – so the SDK signs in anew.
The program asks for the redirect URL twice. Open both URLs in the browser and copy the redirects back. Keycloak redirects immediately each time.
Expected (shortened):
Öffne diese Adresse im Browser und melde dich an:
http://worker2:8080/…/auth?…&scope=mcp%3Atools
Füge die Adresse ein, bei der der Browser gelandet ist:
Öffne diese Adresse im Browser und melde dich an:
http://worker2:8080/…/auth?…&scope=mcp%3Atools+email+profile+mcp%3Awrite
Füge die Adresse ein, bei der der Browser gelandet ist:
notiz_schreiben [OK]: Notiz von anna gespeichert.
What happened:
- The first call had no token,
pforteresponded with401. The SDK took the scopes fromscopes_supported–mcp:tools– and signed in. - With this token came
403 insufficient_scope. The SDK readscope="mcp:tools mcp:write"and formed the union with what it already had:mcp:tools email profileplusmcp:write. - After the second sign-in it repeated the call, this time successfully.
# on cp1, in ~/mcpa/tag13
jq -r .scope tokens.json# on cp1, in ~/mcpa/tag13
uv run python rufen.py wer_bin_ichExpected:
mcp:tools mcp:write email profile
wer_bin_ich [OK]: sub=d57b7977-e563-44d8-a0aa-b062a440fba0 client=leitstand-host scopes=mcp:tools mcp:write email profile
On worker1, the note is in ~/mcpa/tag13/notizen.txt:
# on worker1
cat ~/mcpa/tag13/notizen.txtExpected:
10:46 anna: Dienst neu gestartet (with your time)
Remember: Step-up is the second trip to the front desk – the SDK makes it as soon as the door reports
insufficient_scope.
Save your progress? Sign up for free
Drill 3: A client registers itself (DCR)
Where you are: on cp1 and on worker2 in the second terminal.
What you have afterwards: a client that Keycloak created via Dynamic Client Registration – and the insight that it is not allowed to do anything yet.
DCR is deprecated. You try it anyway, because many hosts and authorization servers still use it and because the difference from CIMD then becomes tangible.
# on cp1, in ~/mcpa/tag13
nano registrierung.json{"client_name": "Testhost",
"redirect_uris": ["http://localhost:3030/callback"],
"grant_types": ["authorization_code"], "response_types": ["code"],
"token_endpoint_auth_method": "none", "application_type": "native"}# on cp1, in ~/mcpa/tag13
curl -s http://worker2:8080/realms/mcpa/clients-registrations/openid-connect -H "Content-Type: application/json" --data @registrierung.json; echoThese are the fields from RFC 7591 that an MCP client sends.
application_type is mandatory for MCP: native
for programs on the human’s computer and localhost URLs,
web for applications on a server. The URL
clients-registrations/openid-connect is listed in
Keycloak’s metadata under registration_endpoint.
Expected:
{"error":"insufficient_scope","error_description":"Policy 'Trusted Hosts' rejected request to client-registration service. Details: Host not trusted."}
Keycloak accepts anonymous registrations only from trusted machines. Add cp1:
# on worker2, in ~/keycloak-26.8.2/bin
TRUST=$(./kcadm.sh get components -r mcpa -q name="Trusted Hosts" --fields id --format csv --noquotes)# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh update components/$TRUST -r mcpa -s 'config."trusted-hosts"=["172.16.0.126","localhost"]'# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh get components/$TRUST -r mcpa | jq .config- In Keycloak, registration rules are components.
-q name="Trusted Hosts"finds the rule for anonymous requests. trusted-hostsnames the allowed machines: cp1 by its IP, from which the request comes, andlocalhostfor the redirect URI. Both checks are enabled.
Expected:
{
"host-sending-registration-request-must-match": [
"true"
],
"trusted-hosts": [
"localhost",
"172.16.0.126"
],
"client-uris-must-match": [
"true"
]
}Now once more:
# on cp1, in ~/mcpa/tag13
curl -s http://worker2:8080/realms/mcpa/clients-registrations/openid-connect -H "Content-Type: application/json" --data @registrierung.json > registriert.json# on cp1, in ~/mcpa/tag13
jq '{client_id, client_name, token_endpoint_auth_method, scope}' registriert.jsonExpected:
{
"client_id": "187bbbe6-7cfa-4b45-90f7-f9bee2a3ef2f",
"client_name": "Testhost",
"token_endpoint_auth_method": "none",
"scope": "address phone offline_access organization microprofile-jwt"
}A fresh client ID. The full response also contains a
registration_access_token, with which the client can later
change or delete its entry. And now a sign-in with it:
# on cp1, in ~/mcpa/tag13
CLIENT=$(jq -r .client_id registriert.json)# on cp1, in ~/mcpa/tag13
VERIFIER=$(openssl rand -base64 48 | tr -d '=+/\n')# on cp1, in ~/mcpa/tag13
CHALLENGE=$(printf %s "$VERIFIER" | openssl dgst -sha256 -binary | base64 | tr '+/' '-_' | tr -d '=')# on cp1, in ~/mcpa/tag13
URL="$AUTH/auth?response_type=code&client_id=$CLIENT"# on cp1, in ~/mcpa/tag13
URL="$URL&redirect_uri=http%3A%2F%2Flocalhost%3A3030%2Fcallback"# on cp1, in ~/mcpa/tag13
URL="$URL&scope=mcp%3Atools&state=drill3"# on cp1, in ~/mcpa/tag13
URL="$URL&code_challenge=$CHALLENGE&code_challenge_method=S256"# on cp1, in ~/mcpa/tag13
URL="$URL&resource=http%3A%2F%2Fworker1%3A8004%2Fmcp"# on cp1, in ~/mcpa/tag13
curl -s -o /dev/null -w "%{redirect_url}\n" "$URL"curl -w "%{redirect_url}" shows where Keycloak would
redirect – you do not need a browser for this.
Expected:
http://localhost:3030/callback?error=invalid_scope
&error_description=Invalid+scopes%3A+mcp%3Atools
&state=drill3&iss=http%3A%2F%2Fworker2%3A8080%2Frealms%2Fmcpa
(wrapped here, curl prints one line)
The client exists, but mcp:tools is not among its
scopes. Keycloak gives a client that registered anonymously only
harmless default scopes. Until an admin assigns it
mcp:tools and an audience for pforte, it gets
no usable token. Registered does not mean authorized.
Remember: Signed up does not mean authorized: a client registered via DCR only gets floors once an admin grants them.
Save your progress? Sign up for free
Drill 4: The client ID as a URL (CIMD)
Where you are: on worker2 in both terminals, on cp1 in both terminals, in the browser.
What you have afterwards: a client that nobody created and that identifies itself through a document on cp1 – with a valid token for
pforte.
Step 1 – Keycloak with CIMD. In Keycloak 26.8, CIMD,
like resource-indicators, is an experimental feature. Stop
Keycloak in the first terminal on worker2 with Ctrl+C and
start it with both features:
# on worker2, in the first terminal
cd ~/keycloak-26.8.2# on worker2, in the first terminal
bin/kc.sh start-dev --http-host 0.0.0.0 --http-port 8080 --features resource-indicators,cimd--features takes a comma-separated list. You no longer
need the environment variables for the administrator. Wait for
Keycloak 26.8.2 on JVM … started.
# on cp1
curl -s http://worker2:8080/.well-known/oauth-authorization-server/realms/mcpa | jq .client_id_metadata_document_supportedExpected: true – an MCP client now
knows that it may use CIMD.
Step 2 – rules for CIMD. Keycloak only fetches documents according to rules you define. They consist of a profile (what to do) and a policy (when):
# on worker2, in the second terminal, in ~/keycloak-26.8.2/bin
nano ~/cimd-profil.json{"profiles": [{"name": "cimd-labor",
"executors": [{"executor": "client-id-metadata-document",
"configuration": {"cimd-allow-http-scheme": "true",
"cimd-allow-permitted-domains": ["cp1", "localhost"],
"cimd-resource-indicator-allow-list": ["http://worker1:8004/mcp"]}}]}]}# on worker2, in the second terminal, in ~/keycloak-26.8.2/bin
nano ~/cimd-policy.json# on worker2, in the second terminal, in ~/keycloak-26.8.2/bin
{"policies": [{"name": "cimd-labor", "enabled": true,# on worker2, in the second terminal, in ~/keycloak-26.8.2/bin
"conditions": [{"condition": "client-id-uri",# on worker2, in the second terminal, in ~/keycloak-26.8.2/bin
"configuration": {"client-id-uri-scheme": ["http"],# on worker2, in the second terminal, in ~/keycloak-26.8.2/bin
"client-id-uri-allow-permitted-domains": ["cp1"]}}],# on worker2, in the second terminal, in ~/keycloak-26.8.2/bin
"profiles": ["cimd-labor"]}]}# on worker2, in the second terminal, in ~/keycloak-26.8.2/bin# on worker2, in the second terminal, in ~/keycloak-26.8.2/bin
./kcadm.sh config credentials --server http://localhost:8080 --realm master --user admin --password labor-admin# on worker2, in the second terminal, in ~/keycloak-26.8.2/bin
./kcadm.sh update realms/mcpa/client-policies/profiles -r mcpa -f ~/cimd-profil.json# on worker2, in the second terminal, in ~/keycloak-26.8.2/bin
./kcadm.sh update realms/mcpa/client-policies/policies -r mcpa -f ~/cimd-policy.json# on worker2, in the second terminal, in ~/keycloak-26.8.2/bin
./kcadm.sh get realms/mcpa/client-policies/policies -r mcpa | jq -r '.policies[].name'The profile contains the executor
client-id-metadata-document, which fetches and checks the
document:
cimd-allow-http-schemeallows URLs withhttp://. The specification requires HTTPS – the lab has no TLS.cimd-allow-permitted-domainsnames the domains from which Keycloak accepts documents. The list also applies to the redirect URIs in them, which is whylocalhostis included.cimd-resource-indicator-allow-listnames the resources for which such clients may get tokens. Keycloak creates the audience mapper for this itself, the one you built by hand in Day 12.
The policy says when the profile applies: condition
client-id-uri – the client ID is a URL with scheme
http on the domain cp1. Nothing changes for
all other client IDs.
update … -f datei replaces the list of profiles or
policies with the content of the file.
Expected: cimd-labor (the two
update commands print nothing)
Step 3 – the document on cp1.
# on cp1, in the second terminal
mkdir -p ~/mcpa/tag13/cimd && cd ~/mcpa/tag13/cimd# on cp1, in the second terminal
nano leitstand-host.json{"client_id": "http://cp1:8090/leitstand-host.json",
"client_name": "Leitstand-Host",
"redirect_uris": ["http://localhost:3030/callback"],
"grant_types": ["authorization_code"], "response_types": ["code"],
"token_endpoint_auth_method": "none",
"scope": "mcp:tools"}# on cp1, in the second terminal
python3 -m http.server 8090client_idmust be exactly the URL where the document is located. Otherwise Keycloak rejects it – so nobody can pass off a foreign document as their own.- Keycloak shows
client_nameon the consent page;redirect_urisare the only allowed redirects. scopenames the scopes the client should get. Without this field, it would get only default scopes, as in Drill 3.python3 -m http.server 8090serves the files of the current directory over HTTP on port 8090. The terminal stays occupied and shows every request.
Expected:
Serving HTTP on 0.0.0.0 port 8090 (http://0.0.0.0:8090/) ...
Step 4 – sign in with the URL as client ID.
# on cp1, in the first terminal, in ~/mcpa/tag13
VERIFIER=$(openssl rand -base64 48 | tr -d '=+/\n')# on cp1, in the first terminal, in ~/mcpa/tag13
CHALLENGE=$(printf %s "$VERIFIER" | openssl dgst -sha256 -binary | base64 | tr '+/' '-_' | tr -d '=')# on cp1, in the first terminal, in ~/mcpa/tag13
URL="$AUTH/auth?response_type=code"# on cp1, in the first terminal, in ~/mcpa/tag13
URL="$URL&client_id=http%3A%2F%2Fcp1%3A8090%2Fleitstand-host.json"# on cp1, in the first terminal, in ~/mcpa/tag13
URL="$URL&redirect_uri=http%3A%2F%2Flocalhost%3A3030%2Fcallback"# on cp1, in the first terminal, in ~/mcpa/tag13
URL="$URL&scope=mcp%3Atools&state=drill4"# on cp1, in the first terminal, in ~/mcpa/tag13
URL="$URL&code_challenge=$CHALLENGE&code_challenge_method=S256"# on cp1, in the first terminal, in ~/mcpa/tag13
URL="$URL&resource=http%3A%2F%2Fworker1%3A8004%2Fmcp"# on cp1, in the first terminal, in ~/mcpa/tag13
echo "$URL"Open the URL in the browser. In the second terminal on cp1 a line
appears like
172.16.0.83 - - [29/Nov/2026 10:48:46] "GET /leitstand-host.json HTTP/1.1" 200 -
– Keycloak on worker2 fetched the document. After signing in, Keycloak
asks for your consent:
For clients from CIMD, Keycloak always requires the human’s consent – no admin has reviewed them. The page names the name from the document and the host it comes from. The name can be chosen freely, the host cannot. Click Ja (Yes) and exchange the code:
# on cp1, in ~/mcpa/tag13 – insert the URL from your browser
ANTWORT='http://localhost:3030/callback?state=drill4&…&code=…'# on cp1, in ~/mcpa/tag13 – insert the URL from your browser
CODE=$(echo "$ANTWORT" | sed -n 's/.*[?&]code=\([^&]*\).*/\1/p')# on cp1, in ~/mcpa/tag13 – insert the URL from your browser
curl -s $AUTH/token -d grant_type=authorization_code --data-urlencode client_id=http://cp1:8090/leitstand-host.json -d "code=$CODE" -d redirect_uri=http://localhost:3030/callback -d "code_verifier=$VERIFIER" --data-urlencode resource=http://worker1:8004/mcp > cimd-token.json# on cp1, in ~/mcpa/tag13 – insert the URL from your browser
jq -r .access_token cimd-token.json | jq -R 'split(".")[1] | gsub("-";"+") | gsub("_";"/") | @base64d | fromjson | {aud, azp, scope}'--data-urlencode client_id=… encodes the URL for the
form.
Expected:
{
"aud": "http://worker1:8004/mcp",
"azp": "http://cp1:8090/leitstand-host.json",
"scope": "mcp:tools"
}A token for pforte, issued to a client that nobody
created. Keycloak still made an entry for itself:
# on worker2, in the second terminal, in ~/keycloak-26.8.2/bin
./kcadm.sh get clients -r mcpa -q clientId=http://cp1:8090/leitstand-host.json --fields clientId,publicClient,consentRequiredExpected:
[ {
"clientId" : "http://cp1:8090/leitstand-host.json",
"consentRequired" : true,
"publicClient" : true
} ]
After a while (five minutes at the earliest) Keycloak fetches the
document again and applies changes. So whoever controls the domain
cp1 controls the client.
The Python SDK can do CIMD too:
OAuthClientProvider(…, client_metadata_url=…). But it only
accepts HTTPS URLs. That is why the lab sticks to the manual way. Stop
the web server in the second terminal with Ctrl+C.
Remember: With CIMD the client ID is a URL; the front desk fetches the business card there and checks it instead of relying on a sign-up.
Save your progress? Sign up for free
Drill 5: An archive with roles
Where you are: on worker2 in the second terminal, then on worker1 in a second terminal.
What you have afterwards: a role
archiv-leser(archive reader) that Anna has and a second user Bernd does not, and the protected serverarchivon port 8005.
Step 1 – role, user, resource.
# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh create roles -r mcpa -s name=archiv-leser# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh add-roles -r mcpa --uusername anna --rolename archiv-leser# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh create users -r mcpa -s username=bernd -s enabled=true -s firstName=Bernd -s lastName=Gast -s [email protected] -s emailVerified=true# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh set-password -r mcpa --username bernd --new-password bernd-labor# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh create clients -r mcpa -s clientId=http://worker1:8005/mcp -s publicClient=false -s standardFlowEnabled=false -s directAccessGrantsEnabled=false -s 'attributes.resource_url=http://worker1:8005/mcp'create rolescreates a realm role,add-roles --uusername anna --rolename …gives it to Anna. Keycloak writes a user’s roles into every token underrealm_access.roles.- Bernd gets no role.
- This time the client for the archive is named the same as its URL. Drill 6 shows why.
Expected:
Created new role with id 'archiv-leser',
Created new user with id '…' and
Created new client with id '…'
Step 2 – the server.
# on worker1, in the second terminal
cd ~/mcpa/tag13# on worker1, in the second terminal
nano archiv.pyimport jwt
from mcp.server import MCPServer
from mcp.server.auth.middleware.auth_context import get_access_token
from mcp.server.auth.provider import AccessToken
from mcp.server.auth.settings import AuthSettings
from mcp.server.mcpserver.exceptions import ToolError
from mcp.server.transport_security import TransportSecuritySettings
from mcp.types import ToolAnnotations
AUSSTELLER = "http://worker2:8080/realms/mcpa"
RESSOURCE = "http://worker1:8005/mcp"
ROLLE = "archiv-leser"
schluessel = jwt.PyJWKClient(f"{AUSSTELLER}/protocol/openid-connect/certs")
class KeycloakPruefer:
"""Wie in pforte, aber mit der eigenen Ressource als Audience."""
async def verify_token(self, token: str) -> AccessToken | None:
try:
signatur = schluessel.get_signing_key_from_jwt(token)
claims = jwt.decode(
token,
signatur.key,
algorithms=["RS256"],
issuer=AUSSTELLER,
audience=RESSOURCE,
)
except jwt.PyJWTError as fehler:
print(f"[archiv] Token abgelehnt: {fehler}", flush=True)
return None
wer = claims.get("preferred_username", claims["sub"])
print(f"[archiv] Token angenommen: {wer} über {claims['azp']}", flush=True)
return AccessToken(
token=token,
client_id=claims["azp"],
scopes=claims.get("scope", "").split(),
expires_at=claims["exp"],
resource=RESSOURCE,
subject=claims["sub"],
claims=claims,
)
mcp = MCPServer(
"archiv",
instructions="Archiv der Betriebsberichte. Nur für die Rolle archiv-leser.",
token_verifier=KeycloakPruefer(),
auth=AuthSettings(
issuer_url=AUSSTELLER,
resource_server_url=RESSOURCE,
validate_token_resource=False,
),
)
@mcp.tool(title="Archiv lesen", annotations=ToolAnnotations(read_only_hint=True))
def eintraege() -> str:
"""Liefert die vertraulichen Betriebsberichte aus dem Archiv."""
claims = get_access_token().claims
wer = claims.get("preferred_username", claims["sub"])
if ROLLE not in claims.get("realm_access", {}).get("roles", []):
raise ToolError(f"{wer} hat die Rolle {ROLLE} nicht.")
return f"Für {wer}: Ausfall Speicher (Mo), Zertifikat erneuert (Mi), Wartung (Fr)"
schutz = TransportSecuritySettings(
enable_dns_rebinding_protection=True,
allowed_hosts=["worker1:8005", "172.16.0.228:8005"],
allowed_origins=[],
)
mcp.run(
transport="streamable-http", host="0.0.0.0", port=8005, transport_security=schutz
)# on worker1, in the second terminal
uv run python archiv.pyExpected:
INFO: Uvicorn running on http://0.0.0.0:8005 (Press CTRL+C to quit)
archiv.py is built like pforte from Day 12,
with three differences: RESSOURCE is its own URL on port
8005, there are no required_scopes, and the tool
eintraege (entries) checks a role.
claims.get("realm_access", {}).get("roles", []) fetches the
list of roles from the token. If archiv-leser is missing,
it reports a ToolError with the user’s name. So the archive
decides itself who may read – based on the human, not on the program
that asks.
# on cp1
curl -s http://worker1:8005/.well-known/oauth-protected-resource/mcp | jq .Expected:
{
"resource": "http://worker1:8005/mcp",
"authorization_servers": [
"http://worker2:8080/realms/mcpa"
],
"bearer_methods_supported": [
"header"
]
}Without required_scopes, scopes_supported
is missing.
Remember: Roles belong in the card and are checked at the door –
required_scopesand a role check in the server.
Save your progress? Sign up for free
Drill 6: Passing through and own rights
Where you are: on worker2 in the second terminal, on worker1 in the first terminal (pforte), on cp1.
What you have afterwards:
pfortewith its own account in Keycloak – and two wrong ways of asking the archive, which you have seen with your own eyes.
Step 1 – pforte gets an account. Until now,
leitstand-mcp was only a resource in Keycloak. Now
pforte should be able to sign in to Keycloak itself:
# on worker2, in ~/keycloak-26.8.2/bin
MCP=$(./kcadm.sh get clients -r mcpa -q clientId=leitstand-mcp --fields id --format csv --noquotes)# on worker2, in ~/keycloak-26.8.2/bin
MAPPER=$(./kcadm.sh get clients/$HOST/protocol-mappers/models -r mcpa --fields id,name --format csv --noquotes | grep ',audience-leitstand-mcp$' | cut -d, -f1)# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh update clients/$MCP -r mcpa -s clientId=http://worker1:8004/mcp -s serviceAccountsEnabled=true# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh update clients/$HOST/protocol-mappers/models/$MAPPER -r mcpa -s 'config."included.client.audience"=http://worker1:8004/mcp'# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh create clients/$MCP/protocol-mappers/models -r mcpa -s name=audience-archiv -s protocol=openid-connect -s protocolMapper=oidc-audience-mapper -s 'config."included.client.audience"=http://worker1:8005/mcp' -s 'config."access.token.claim"=true'# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh add-roles -r mcpa --uusername 'service-account-http://worker1:8004/mcp' --rolename archiv-leser# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh get clients/$MCP/client-secret -r mcpa --fields value --format csv --noquotesHOST comes from Drill 1. If the terminal is new, fetch
the variable with the command from there.
clientId=http://worker1:8004/mcpnames the client after its URL. Token Exchange needs this in a moment: Keycloak only exchanges tokens whoseaudcontains the exchanging client. Withresource, that field contains the URL ofpforte, notleitstand-mcp. If the client is named like the URL, both match. The host’s audience mapper refers to the client by name, which is why it is switched over in the secondupdate. Side effect: a token withoutresourceas in Day 12, Drill 6 now also contains the URL ofpforteinaudand is accepted – rightly so, since it is meant for this server.serviceAccountsEnabled=truegives the client a service account: it can sign in by itself with client ID and secret (client credentials), entirely without a human. Keycloak creates the userservice-account-http://worker1:8004/mcpfor this.audience-archivwrites the archive’s URL into this client’s tokens – that allows it to get tokens for the archive.add-roles … service-account-…gives the service account the rolearchiv-leser. A server with more rights than some of its users – that is often exactly what it looks like in practice.client-secretshows the client’s secret, whichpforteuses to sign in. It is worth as much as a password.
Expected (the last line is your secret):
Created new model with id '…'
QYzT0…
Step 2 – the secret on worker1. Copy the secret and store it on worker1 in a file that only you can read:
# on worker1, in the first terminal (stop pforte with Ctrl+C)
cd ~/mcpa/tag13# on worker1, in the first terminal (stop pforte with Ctrl+C)
read -rs -p "Geheimnis: " GEHEIM; echo# on worker1, in the first terminal (stop pforte with Ctrl+C)
printf '%s' "$GEHEIM" > .geheimnis && chmod 600 .geheimnis && unset GEHEIMread -r -s -p "…" GEHEIMreads a line into the variableGEHEIM:-sdoes not echo the input,-rleaves backslashes alone,-pprints a prompt. This way the secret ends up neither on the screen nor in the shell history.printf '%s'writes it without a newline,chmod 600allows only you to read and write,unsetdeletes the variable again.
Step 3 – passing through.
# on worker1, in ~/mcpa/tag13
PFORTE_MODUS=durchreichen PFORTE_GEHEIMNIS=$(cat .geheimnis) uv run python pforte.pyVARIABLE=wert befehl sets environment variables only for
this command. Now to the part of pforte.py that Drill 1
skipped:
MODUS(mode) andGEHEIMNIS(secret) come from the environment variablesPFORTE_MODUSandPFORTE_GEHEIMNIS. A secret never belongs in the code.token_fuer_archivgets the token for the archive. In modedurchreichen(pass through) it is simply the token that arrived atpforte–get_access_token().token.archiv_lesen(read archive) reads the content of this token without verification (verify_signature: False– only for the log, the archive verifies itself) and writes user and audience to the terminal. Then it calls the archive with the SDK client: thehttpx2.AsyncClient(headers=…)attaches the token to every request,call_tool("eintraege", {})calls the tool.- If the archive rejects, the SDK raises an
MCPError. It is wrapped in nested exception groups, because the client works internally with task groups.except* MCPErrorcatches it anyway, the loop extracts the innermost exception, andpfortereports it as aToolError.
# on cp1, in ~/mcpa/tag13
uv run python rufen.py archiv_lesenExpected on cp1:
archiv_lesen [FEHLER]: Error executing tool archiv_lesen: Archiv lehnt ab: Server returned an error response
on worker1 at pforte:
[pforte] archiv_lesen im Modus durchreichen
[pforte] ans Archiv: anna aud=http://worker1:8004/mcp
and at the archive:
[archiv] Token abgelehnt: Audience doesn't match
The archive checks the audience and rejects a token for
pforte. So passing through fails here – but only because
the archive checks properly. A service that, as in the Day 12 challenge,
only checks signature and expiry would have accepted it. That is why the
specification forbids passing through on the sender’s side, not only on
the receiver’s side.
Step 4 – own rights. Stop pforte with
Ctrl+C and start it in mode eigenes (own):
# on worker1, in ~/mcpa/tag13
PFORTE_MODUS=eigenes PFORTE_GEHEIMNIS=$(cat .geheimnis) uv run python pforte.pyIn mode eigenes, token_fuer_archiv sends a
request with grant_type=client_credentials to Keycloak.
pforte authenticates with client ID and secret in the form
(client_secret_post). The result is a token for the service
account, not for the human.
# on cp1, in ~/mcpa/tag13
uv run python rufen.py archiv_lesenExpected:
archiv_lesen [OK]: Für service-account-http://worker1:8004/mcp: Ausfall Speicher (Mo), Zertifikat erneuert (Mi), Wartung (Fr)
Anna may read the archive, so the result is no surprise. Now Bernd. Delete the stored token and open the sign-in URL in a private window of the browser – in the normal window you are still signed in as Anna, and Keycloak would redirect you without asking:
# on cp1, in ~/mcpa/tag13
rm tokens.json# on cp1, in ~/mcpa/tag13
uv run python rufen.py archiv_lesenSign in as bernd with bernd-labor.
Expected:
archiv_lesen [OK]: Für service-account-http://worker1:8004/mcp: Ausfall Speicher (Mo), Zertifikat erneuert (Mi), Wartung (Fr)
Bernd does not have the role – and reads the archive anyway.
pforte is the confused deputy: it has the
rights, Bernd does not, and pforte lets Bernd use it. The
archive’s log shows only the service account. Whoever later asks who
read the reports will find Bernd nowhere.
Remember: Passing the guest card through fails on the audience; using the master key turns the server into a confused deputy. Both are wrong.
Save your progress? Sign up for free
Drill 7: Token Exchange
Where you are: on worker2 in the second terminal, on worker1 in the first terminal, on cp1.
What you have afterwards: a
pfortethat gets a token for the archive on behalf of the human.
# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh update clients/$MCP -r mcpa -s 'attributes."standard.token.exchange.enabled"=true'standard.token.exchange.enabled allows this client to
use Token Exchange according to RFC 8693. In Keycloak 26.8 this is no
longer an experimental feature; it only has to be enabled per
client.
# on worker1, in ~/mcpa/tag13 (stop pforte with Ctrl+C first)
PFORTE_MODUS=tausch PFORTE_GEHEIMNIS=$(cat .geheimnis) uv run python pforte.pyIn mode tausch (exchange),
token_fuer_archiv sends these fields to the token
endpoint:
| Field | Value | Meaning |
|---|---|---|
grant_type |
urn:ietf:params:oauth:grant-type:token-exchange |
Token Exchange |
subject_token |
the token that arrived at pforte |
on whose behalf the exchange happens |
subject_token_type |
urn:ietf:params:oauth:token-type:access_token |
what kind of token this is |
audience |
http://worker1:8005/mcp |
for whom the new token should be valid |
client_id, client_secret |
URL and secret of pforte |
who exchanges |
Keycloak checks that pforte is in the audience of the
old token and may get tokens for the new audience, and issues a new
token: same user, new audience, azp is
pforte.
Bernd is still signed in in the private window,
tokens.json belongs to him. If it is older than five
minutes, the SDK asks again – then open the URL in the private window
again:
# on cp1, in ~/mcpa/tag13
uv run python rufen.py archiv_lesenExpected on cp1:
archiv_lesen [FEHLER]: Error executing tool archiv_lesen: Archiv: Error executing tool eintraege: bernd hat die Rolle archiv-leser nicht.
at pforte:
[pforte] archiv_lesen im Modus tausch
[pforte] ans Archiv: bernd aud=http://worker1:8005/mcp
and at the archive:
[archiv] Token angenommen: bernd über http://worker1:8004/mcp
The archive accepts the token – it is issued for the archive – and
still rejects Bernd, because it now sees that Bernd is asking. And it
sees through which server he is asking. As a cross-check, Anna: close
the private window, delete tokens.json and sign in in the
normal window.
# on cp1, in ~/mcpa/tag13
rm tokens.json# on cp1, in ~/mcpa/tag13
uv run python rufen.py archiv_lesenExpected:
archiv_lesen [OK]: Für anna: Ausfall Speicher (Mo), Zertifikat erneuert (Mi), Wartung (Fr)
Three ways, three results in the log of pforte:
| Mode | Token to the archive | Result |
|---|---|---|
| durchreichen | anna aud=http://worker1:8004/mcp |
archive rejects (wrong audience) |
| eigenes | service-account-… aud=['http://worker1:8005/mcp', 'account'] |
everyone reads everything |
| tausch | bernd aud=http://worker1:8005/mcp |
right human, right audience |
Remember: Token exchange issues a new card: the right person, the right door – and the second server’s log shows who really asked.
Save your progress? Sign up for free
If it doesn’t work
- Drill 1 returns
200instead of403: Your token already hasmcp:write, for example because you are using an oldtoken.json. Get a new token withscope=mcp%3Atools. - The SDK asks only once in Drill 2:
tokens.jsonwas already in the directory and hadmcp:write. Delete the file and try again. Policy 'Trusted Hosts' rejected request, although cp1 is registered: The request comes from a different address. Check the IP of cp1 withhostname -Iand add it.Invalid Client ID: domain not allowedon the Keycloak page:cp1orlocalhostis missing incimd-allow-permitted-domains, or the client ID in the document differs from the URL.client_id_metadata_document_supportedisnull: Keycloak is running without--features cimd.- Keycloak reports
invalid_scopefor the CIMD client:scopeis missing in the document. Keycloak only fetches changed documents again after its cache expires. Delete the client in Keycloak with./kcadm.sh delete clients/ID -r mcpa; then it fetches the document immediately at the next sign-in. Keycloak: Invalid client or Invalid client credentialsin Drill 6 or 7:.geheimnisis wrong or empty. Read it out again with the command from Drill 6.Keycloak: Client is not within the token audiencein Drill 7: The client is still namedleitstand-mcp, or the host’s audience mapper still points to the old name. Repeat step 1 of Drill 6.- Bernd can read in Drill 7 after all:
pforteis still running in modeeigenes. Check the second line in the terminal ofpforte.
Exercise: Who sees the secret? (10 min)
pforte gets its secret via an environment variable. Can
another user on worker1 read it? Does it show up in the process
list?
Solution
# on worker1, in another terminal
P=$(pgrep -f "^/home/ubuntu/mcpa/.venv/bin/python pforte.py")# on worker1, in another terminal
ps -o args= -p $P# on worker1, in another terminal
tr '\0' '\n' < /proc/$P/environ | grep -c PFORTE_GEHEIMNIS# on worker1, in another terminal
sudo -u nobody cat /proc/$P/environpgrep -f mustersearches processes by their whole command line. The^and the full path match only the Python process, not theuvprocess in front of it and not this command itself.ps -o args= -p PIDshows only the command line./proc/PID/environcontains the process’s environment, separated by null bytes.tr '\0' '\n'turns it into lines.sudo -u nobodyruns the command as the usernobody– standing in for any other user.
Expected:
/home/ubuntu/mcpa/.venv/bin/python pforte.py
1
cat: /proc/10568/environ: Permission denied
(with your process number)
The secret is not in the command line –
PFORTE_GEHEIMNIS=$(cat .geheimnis) is a shell assignment,
not an argument. Only the owner of the process (and root) can read the
environment. It becomes dangerous when the secret ends up in plain text
in the command line or in the history, is written to a log, or to a file
that everyone may read. In production, a secret store or systemd with
LoadCredential= takes care of this.
Save your progress? Sign up for free
Challenge: The proxy with a fixed client ID (20 min)
An MCP server kalender (calendar) acts as a proxy in
front of the API of a calendar service. At the calendar service,
kalender is one client with a fixed client
ID. MCP hosts sign in to kalender, and
kalender allows Dynamic Client Registration. Anna has
already consented once via her host that kalender may
access her calendar, and the calendar service remembered this via a
cookie.
- An attacker registers their own client at
kalenderwith the redirect URIhttps://angreifer.example/cband sends Anna a sign-in link. What happens? - What must
kalenderdo to prevent this? - Why does it not help that the calendar service checks the redirect URI exactly every time?
Solution
- Anna clicks,
kalenderredirects her to the calendar service. It sees the fixed client ID ofkalender, finds Anna’s earlier consent and redirects back tokalenderwithout asking.kalenderpasses a code to the redirect URI of the newly registered client – to the attacker. The attacker exchanges it atkalenderand has access to Anna’s calendar.kalenderwas the confused deputy. - The specification requires: an MCP proxy with a fixed client ID must
obtain the human’s consent itself for every client
registered with it, before it redirects to the third-party authorization
server. The consent page names the client and its redirect URI and
remembers the consent per client. In addition,
stateand a check of the redirect URI at the proxy itself are needed. - The calendar service only sees the redirect URI of
kalender, and that one is correct. What happens afterwards in the proxy is outside its view. The check must sit where the new client is known – in the proxy.
Save your progress? Sign up for free
Checkpoint
# on cp1
curl -s http://worker2:8080/.well-known/oauth-authorization-server/realms/mcpa | jq .client_id_metadata_document_supportedExpected: true
# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh get clients -r mcpa -q clientId=http://worker1:8004/mcp | jq -r '.[0].attributes."standard.token.exchange.enabled"'Expected: true
# on worker1
grep -c "anna: Dienst neu gestartet" ~/mcpa/tag13/notizen.txtExpected: 1 (or more, if you wrote the
note more often)
Clean up: Stop archiv,
pforte and the control room (Leitstand) on worker1 with
Ctrl+C, and Keycloak on worker2 as well. Realm, users and
clients are preserved in data/.
Exam questions
1. A client calls a tool and gets 403
with
WWW-Authenticate: Bearer error="insufficient_scope", scope="files:read files:write".
What should it do?
- Repeat the request with the same token.
- Request a new token for the union of previous and named scopes and repeat the call.
- Request a new token only for
files:write.
- Request a new token only for
- Ask the human for a new password.
2. A client has no pre-registered client ID. The
authorization server announces
client_id_metadata_document_supported: true and has a
registration_endpoint. Which way should the client
take?
- Dynamic Client Registration
- Client ID Metadata Document
- Client Credentials
- It must abort.
3. An MCP server needs data from an internal API that trusts the same authorization server. What must it not do?
- Pass the received access token on to the API.
- Get a token for the API via Token Exchange.
- Check the audience of the received token.
- Return the API’s response as a tool result.
4. What must an MCP proxy do that is registered with a third-party authorization server with a fixed client ID and offers Dynamic Client Registration itself?
- Obtain the human’s consent for every client registered with it.
- Change the client ID regularly.
- Pass the third-party authorization server’s tokens on to the clients.
- Use HTTPS only.
5. Which client ID is valid for a Client ID Metadata Document?
leitstand-host
https://host.example.com
https://host.example.com/mcp/client.json
https://host.example.com/client.json?version=2
Solutions
- B. The scopes from the header are authoritative for this call. With the union, the client loses no rights it already has for other calls.
- B. Order: pre-registered, then CIMD, then DCR. DCR has been deprecated since 2026-07-28.
- A. Token passthrough is forbidden. Token Exchange is the intended way.
- A. Otherwise an attacker can exploit the human’s stored consent via their own client – a confused deputy.
- C. The client ID must be an HTTPS URL with a path and must not have a query part.
Interview Note
“Our MCP server has to call an internal API – how does it
authenticate?” – Not with the user’s token; that is passthrough and
forbidden. Also not simply with its own service account that may do
everything, otherwise the server becomes a confused deputy, and the
audit log only shows the server. The clean way is Token Exchange: the
server exchanges the user token at the identity provider for a token
with the API’s audience, on behalf of the same user. The API checks the
audience and the user’s rights and sees in azp through
which server the request came. Whoever can explain it this way also
knows the difference between scopes – what the client may do – and roles
– what the human may do.
Enterprise Note
For client registration, a clear rule pays off: known hosts are
pre-registered, with fixed redirect URIs and exactly the scopes they
need. You open CIMD only for domains you know – otherwise any domain on
the internet may create clients. Switch off anonymous DCR wherever you
can. For calls between services, Token Exchange has meanwhile arrived in
the major identity providers. Entra ID calls it “On-Behalf-Of”, Keycloak
has had it as a standard feature since version 26.2. Service accounts
remain for tasks without humans, for example nightly reports – with as
few rights as possible and with their own entry in the audit log. And
secrets like the one of pforte belong in a secret store
with rotation, not in a file in the project directory.
Summary
- Scopes limit what a client may do on behalf of a human. Roles limit what the human may do. Both apply.
- If a scope is missing, the server responds with
403andWWW-Authenticate: Bearer error="insufficient_scope", scope="…". The client requests the union of the scopes and repeats (step-up). The SDK does this by itself. - Client ID: pre-registered → CIMD
(URL as client ID, document with
client_id,client_name,redirect_uris) → DCR (deprecated since 2026-07-28). Registered does not mean authorized. - No token passthrough: A server never passes on tokens it received.
- Confused deputy: A server with broad rights of its own acts for humans with narrow ones. For proxies with a fixed client ID: consent per registered client.
- Token Exchange (RFC 8693) provides a token for the next service on behalf of the same human. In Keycloak, the exchanging client must be in the audience of the old token.
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 |
|---|---|---|
kcadm.sh create client-scopes -s name=… |
create a scope | include.in.token.scope |
kcadm.sh get components -q name="Trusted Hosts" |
find the rule for anonymous registration | – |
kcadm.sh update components/ID -s 'config."trusted-hosts"=[…]' |
set trusted machines | – |
kcadm.sh update realms/mcpa/client-policies/profiles -f datei |
replace profiles for client policies | -f JSON file |
kcadm.sh update realms/mcpa/client-policies/policies -f datei |
replace client policies | -f JSON file |
kcadm.sh create roles -s name=… |
create a realm role | – |
kcadm.sh add-roles --uusername … --rolename … |
assign a role | – |
kcadm.sh update clients/ID -s serviceAccountsEnabled=true |
enable a service account | – |
kcadm.sh get clients/ID/client-secret |
show the client secret | --fields value |
standard.token.exchange.enabled=true |
allow Token Exchange for a client | client attribute |
bin/kc.sh start-dev --features a,b |
enable several features | comma list |
curl -X POST …/clients-registrations/openid-connect |
register a client via DCR | JSON per RFC 7591 |
curl -w "%{redirect_url}" |
show the target of a redirect | – |
python3 -m http.server 8090 |
serve a directory over HTTP | port |
read -rs -p "…" VAR |
read input hidden | -s hidden, -r raw |
VAR=value befehl |
environment variable for one command | – |
pgrep -f muster, ps -o args= -p PID |
find a process, show its command line | -f whole line |
tr '\0' '\n' < /proc/PID/environ |
read a process’s environment | owner only |
sudo -u nobody befehl |
run as a different user | – |
mcp.streamable_http_app(transport_security=…) |
the server’s ASGI app | – |
uvicorn.run(app, host=…, port=…) |
start an ASGI app | – |
jwt.decode(token, options={"verify_signature": False}) |
read content without verification | only for the log |
except* Fehlertyp |
catch exceptions from groups | Python 3.11+ |
grant_type=client_credentials |
token for a service account | client ID + secret |
grant_type=urn:ietf:params:oauth:grant-type:token-exchange |
exchange a token | subject_token, audience |