Skip to content
MCPA · Chapter 14 of 21 Day 12: Authorization I

Day 12: Authorization I

Goal: protect an MCP server over HTTP with OAuth 2.1, set up Keycloak as the authorization server, and walk the path from the first 401 to a valid token once by hand and once with the SDK · Duration: about 3 h · Prerequisite: Day 11

Where we start

# on cp1
grep -c "def fingerabdruck" ~/mcpa/tag11/host.py

Expected: 1

# on cp1
getent hosts worker2

Expected: 172.16.0.83 worker2

getent hosts name queries the same sources as any program that resolves a name – here /etc/hosts from Day 0. Today you also need the control room from Day 8 on worker1. Start it in a terminal on worker1 with cd ~/mcpa/tag08 && uv run python fern.py.

Introduction

Since Day 8, your host has reached a server over the network. So far, anyone who can reach port 8000 on worker1 may do so: whoever knows the address can call tools. For a server that only reports disk space, that may be acceptable. For a server that creates tickets, reads customer data, or restarts services, it is not.

MCP does not handle this itself but adopts OAuth 2.1 – the same mechanism you use to “sign in with account X” at many web applications. The MCP server only checks tokens. Who issues them, who may sign in, and how, is decided by a separate authorization server. Today that is Keycloak on worker2.

You first rebuild the whole path by hand – with curl, openssl, and a browser – so that you have seen every step. After that, the SDK takes over the same steps, and your host signs in before it uses the tools of a protected server.

Today you learn:

  • which roles OAuth assigns in MCP: resource server, client, authorization server,
  • how a client uses Protected Resource Metadata and Authorization Server Metadata to find out by itself where it has to sign in,
  • how PKCE ensures that an intercepted code is useless,
  • what the resource parameter is for and why a server must check the audience,
  • how an MCP server checks tokens with the SDK and how a client obtains tokens with the SDK,
  • where the SDK’s limits lie when refreshing tokens.

Background

The picture for today: front desk and key card

In the hotel, no door opens on request. Anyone who wants to reach a contractor in the house needs a key card.

  • The front desk (Keycloak, the authorization server) issues cards. First the guest (Anna) identifies herself there – in the browser, with a password.
  • The concierge (your host, the client) picks up the card on the guest’s behalf and holds it to the door. He never learns the guest’s password.
  • The contractor’s door (pforte, the resource server) reads every card itself: genuine? still valid? issued for this door? Without a card it sends the concierge to the front desk with a hint.
  • So that nobody intercepts an ordered card, there is a claim ticket (PKCE): only someone who shows the secret whose fingerprint was left with the order may pick it up.
  • Cards expire. With a renewal slip (refresh token) the concierge gets a new one without the guest having to go back to the front desk.

The terms

Term Meaning in the picture
authorization server signs people in, issues tokens front desk
access token short-lived proof that the client sends along key card
resource server checks the token on every request the contractor’s door
audience / resource which server the token is valid for a card for this one door only
PKCE secret plus checksum, protects the code claim ticket
refresh token gets a new access token without a new sign-in renewal slip
realm self-contained area with users and clients a hotel of its own

Remember: The front desk issues cards, the door checks them. The MCP server signs nobody in – it only reads cards, every single one.

Three roles

Role in OAuth in the lab Job
Resource Server pforte on worker1 checks the token on every request and rejects anything that does not fit
Client your host or anmelden.py on cp1 obtains a token on behalf of the human and sends it along
Authorization server Keycloak on worker2 signs humans in, issues tokens, publishes its keys
Resource Owner Anna, who signs in in the browser allows the client to act on her behalf

The MCP server knows no passwords. It receives an access token and checks: did Keycloak sign it? Is it still valid? Was it issued for me? The specification covers this for all HTTP transports. It explicitly does not apply to stdio: a local server gets its credentials from the environment, for example from environment variables.

The path to the token

A client that knows only the server’s address finds out everything else by itself:

  1. It calls the server without a token and gets 401 Unauthorized. The WWW-Authenticate header contains an address under resource_metadata.
  2. That address holds the Protected Resource Metadata (RFC 9728): who am I (resource), which authorization server issues my tokens (authorization_servers), which scopes exist.
  3. From the authorization server, the client fetches the Authorization Server Metadata (RFC 8414 or OpenID Connect Discovery): addresses for sign-in and tokens, supported methods.
  4. The client sends the human to the browser with an Authorization Code Flow with PKCE. After sign-in, the browser redirects to a redirect URI of the client and brings along a short-lived code.
  5. At the token endpoint, the client exchanges the code for an access token (and usually a refresh token).
  6. Every further request to the server carries Authorization: Bearer <token>.

If the server does not return a WWW-Authenticate header with an address, the client tries fixed addresses: first /.well-known/oauth-protected-resource/mcp, then /.well-known/oauth-protected-resource. The same principle applies to the authorization server. For an issuer with a path such as http://worker2:8080/realms/mcpa, these are, in order:

  1. http://worker2:8080/.well-known/oauth-authorization-server/realms/mcpa
  2. http://worker2:8080/.well-known/openid-configuration/realms/mcpa
  3. http://worker2:8080/realms/mcpa/.well-known/openid-configuration

The issuer field in the document found must match exactly the issuer from which the client built the address. Otherwise it must not use the document.

PKCE

The code from step 4 travels through the browser and ends up in an address bar. There, another app on the same machine or a browser plugin can read it. PKCE (Proof Key for Code Exchange, “pixy”) makes a stolen code worthless:

  • Before starting, the client generates a random secret, the code verifier.
  • In the sign-in address, it puts only the verifier’s SHA-256 checksum, the code challenge, with code_challenge_method=S256.
  • When exchanging the code, it sends the verifier. The authorization server recomputes the checksum. Anyone who has only the code does not know the verifier.

MCP clients must use PKCE with S256. If the authorization server’s metadata contains no code_challenge_methods_supported, they must abort – such a server cannot do PKCE.

Resource and audience

A token that Keycloak issues for server A must not open server B. Otherwise, any server you give a token to could use it to act on your behalf at all other servers. Two rules interlock:

  • At sign-in and when exchanging the code, the client uses the parameter resource (RFC 8707) to say which server it wants the token for. The value is the server’s canonical URI: scheme and host in lowercase, no fragment, no trailing slash – in the lab http://worker1:8004/mcp.
  • The server checks that it is itself in the token’s audience – the aud field. It rejects a token for someone else, even if it is otherwise valid.

Keycloak has supported resource since version 26.8 as an experimental feature (resource-indicators). It checks whether a client may get tokens for the requested resource and then writes exactly that URI into aud. Without the feature, Keycloak ignores the parameter. Then the only option left is to fix the audience via a scope.

What is deliberately missing in the lab

The specification requires HTTPS for all endpoints of the authorization server. Redirect URIs must be localhost or HTTPS. In the lab, everything runs over HTTP so that you can read every step with curl. Tokens, codes, and passwords travel through the network in plain text. Outside an isolated lab, this is not acceptable. Keycloak also runs in development mode with a built-in database.

Drill 1: Keycloak on worker2

Where you are: on worker2, in the first terminal. Today this terminal belongs to Keycloak.

What you have afterwards: an authorization server at http://worker2:8080 and a computer on which your browser finds worker2.

Step 1 – Java and Keycloak. Keycloak is a Java program. It needs Java 21.

# on worker2
sudo apt-get update
# on worker2
sudo apt-get install -y openjdk-21-jre-headless unzip
# on worker2
java -version 2>&1 | head -1
  • openjdk-21-jre-headless is the Java runtime without graphical libraries – enough for servers.
  • unzip will unpack the Keycloak archive in a moment.
  • java -version writes its output to stderr. 2>&1 redirects it to stdout so that head -1 can show the first line.

Expected (the minor version may differ):

openjdk version "21.0.13.1" 2026-11-17
# on worker2
cd ~
# on worker2
KC=26.8.2
# on worker2
curl -sSLO https://github.com/keycloak/keycloak/releases/download/$KC/keycloak-$KC.zip
# on worker2
unzip -q keycloak-$KC.zip
# on worker2
ls keycloak-26.8.2
  • KC=26.8.2 holds the version so that the address stays short. curl -sSLO downloads the file: -s without a progress bar, -S still show errors, -L follow redirects (GitHub redirects downloads), -O save under the name from the address.
  • unzip -q unpacks quietly (-q, quiet). The archive is about 170 MB and contains a ready-made directory keycloak-26.8.2. Keycloak is pure Java and runs on amd64 and arm64.

Expected:

LICENSE.txt  README.md  bin  conf  lib  providers  themes  version.txt

Step 2 – start Keycloak.

# on worker2
cd ~/keycloak-26.8.2
# on worker2
KC_BOOTSTRAP_ADMIN_USERNAME=admin KC_BOOTSTRAP_ADMIN_PASSWORD=labor-admin bin/kc.sh start-dev --http-host 0.0.0.0 --http-port 8080 --features resource-indicators
  • KC_BOOTSTRAP_ADMIN_USERNAME and KC_BOOTSTRAP_ADMIN_PASSWORD apply only to this command. On first start, Keycloak uses them to create a temporary administrator admin. Without them, there would be no account with which you could set up Keycloak.
  • bin/kc.sh start-dev starts development mode: HTTP instead of HTTPS, a built-in H2 database in the directory data/, no fixed hostnames. For production there is start with TLS, a real database, and a fixed --hostname.
  • --http-host 0.0.0.0 listens on all network interfaces. Without this option, Keycloak in development mode listens only on localhost, and neither cp1 nor worker1 could reach it.
  • --http-port 8080 is the port for HTTP.
  • --features resource-indicators enables the experimental support for the resource parameter.

The first start takes a minute: Keycloak builds itself for the chosen options.

Expected (among other lines; times differ):

WARN  [org.keycloak.common.Profile] (main) Experimental features enabled: resource-indicators:v1
INFO  [org.keycloak.services] (main) KC-SERVICES0077: Created temporary admin user with username admin
INFO  [io.quarkus] (main) Keycloak 26.8.2 on JVM (powered by Quarkus 3.40.1.1) started in 42.053s. Listening on: http://0.0.0.0:8080

Keycloak stores everything in data/. If you stop it with Ctrl+C, you start it again later with the same command. The environment variables do no harm then – the administrator already exists.

Step 3 – check from cp1.

# on cp1
curl -s http://worker2:8080/realms/master | jq -r .realm

Expected: master

In Keycloak, a realm is a self-contained area with its own users, clients, and keys. master is the administration realm. You will create a separate one for the lab in a moment.

Step 4 – worker2 for your browser. Sign-in happens in a browser, and that runs on your own computer, not on the VMs. Keycloak sends it to addresses containing worker2. So add the name there as well – on macOS and Linux like this:

# on your computer (not on a VM)
echo "172.16.0.83 worker2" | sudo tee -a /etc/hosts

On Windows, open Notepad as administrator and append the same line to C:\Windows\System32\drivers\etc\hosts. Check in the browser: http://worker2:8080/realms/master shows a short JSON document that starts with {"realm":"master".

Remember: The front desk is a service of its own on a machine of its own. The contractor does not issue cards, he only checks them.

Save your progress? Sign up for free

Drill 2: A realm, a user, a client

Where you are: on worker2, in a second terminal (Keycloak is running in the first).

What you have afterwards: the realm mcpa with the user anna and the public client leitstand-host, which may sign in only with PKCE.

Keycloak can be set up in the browser or with kcadm.sh on the command line. You use the command line – then every step is a command you can repeat.

# 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
  • config credentials signs kcadm.sh in and stores a token in ~/.keycloak/kcadm.config. The following commands use it until it expires. If you get 401 later, sign in again with this command.
  • --server is Keycloak’s address, --realm master the administrator’s realm, --user and --password its credentials.

Expected: Logging into http://localhost:8080 as user admin of realm master

The realm.

# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh create realms -s realm=mcpa -s enabled=true -s displayName=MCPA-Labor -s internationalizationEnabled=true -s 'supportedLocales=["de","en"]' -s defaultLocale=de -s revokeRefreshToken=true

create realms creates a realm, and each -s field=value sets a field:

  • realm=mcpa is the name. It appears in every address: http://worker2:8080/realms/mcpa.
  • enabled=true enables the realm, and displayName is the title on the sign-in page.
  • internationalizationEnabled=true, supportedLocales, and defaultLocale=de show the sign-in page in German. Values with brackets and quotes are wrapped in single quotes so that the shell does not change them.
  • revokeRefreshToken=true rotates refresh tokens: every refresh returns a new refresh token, and the old one becomes invalid. The specification requires this for public clients.

Expected: Created new realm with id 'mcpa'

The user.

# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh create users -r mcpa -s username=anna -s enabled=true -s firstName=Anna -s lastName=Admin -s [email protected] -s emailVerified=true
# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh set-password -r mcpa --username anna --new-password anna-labor
  • -r mcpa selects the realm. Without -r, everything lands in the realm master.
  • First name, last name, and a verified email address (emailVerified=true) are needed because otherwise Keycloak asks the user to complete the profile on first sign-in.
  • set-password sets a permanent password. labor.test is a domain that will never exist.

Expected: Created new user with id '…' (a random ID)

The client. Your host signs in as the client leitstand-host:

# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh create clients -r mcpa -s clientId=leitstand-host -s publicClient=true -s standardFlowEnabled=true -s directAccessGrantsEnabled=false -s 'redirectUris=["http://localhost:3030/callback"]' -s 'attributes."pkce.code.challenge.method"=S256'
  • clientId=leitstand-host is the name under which the host introduces itself.
  • publicClient=true makes it a public client: it has no client secret. A program on a human’s computer cannot keep a secret – anyone could read it from the file. PKCE provides the protection instead.
  • standardFlowEnabled=true allows the Authorization Code Flow. directAccessGrantsEnabled=false forbids sending username and password directly to the token endpoint. OAuth 2.1 no longer has this path.
  • redirectUris is the list of allowed redirect addresses. Keycloak redirects only there, and only if the address matches exactly. Port 3030 on localhost is an arbitrary choice.
  • attributes."pkce.code.challenge.method"=S256 makes PKCE with S256 mandatory. Keycloak then rejects a sign-in without a code challenge.

Expected: Created new client with id '…'

# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh get clients -r mcpa -q clientId=leitstand-host --fields clientId,publicClient,redirectUris

get clients lists clients, -q clientId=… filters, and --fields limits the output to these fields.

Expected:

[ {
  "clientId" : "leitstand-host",
  "redirectUris" : [ "http://localhost:3030/callback" ],
  "publicClient" : true
} ]

Remember: A realm is a hotel of its own with guests and devices. A public client has no secret – that is why it may sign in only with a claim ticket (PKCE).

Save your progress? Sign up for free

Drill 3: The server as a resource

Where you are: on worker2, in the second terminal, in ~/keycloak-26.8.2/bin.

What you have afterwards: an entry for the MCP server in Keycloak, a scope mcp:tools, and permission for leitstand-host to get tokens for the server.

Keycloak must know the MCP server, otherwise it cannot issue tokens for it. For this, the server itself is registered as a client – one that never signs in:

# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh create clients -r mcpa -s clientId=leitstand-mcp -s publicClient=false -s standardFlowEnabled=false -s directAccessGrantsEnabled=false -s 'attributes.resource_url=http://worker1:8004/mcp'
  • clientId=leitstand-mcp is the server’s name in Keycloak.
  • publicClient=false and both flows off: nobody can sign in through this entry. It only describes the resource.
  • attributes.resource_url is the canonical URI of the MCP server. With resource-indicators, Keycloak compares the resource parameter with this value.

Expected: Created new client with id '…'

A scope. A scope names what a token is supposed to allow. The MCP server will require mcp:tools in a moment:

# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh create client-scopes -r mcpa -s name=mcp:tools -s protocol=openid-connect -s 'attributes."include.in.token.scope"=true' -s 'attributes."display.on.consent.screen"=false'
  • create client-scopes creates a scope, protocol=openid-connect for OAuth and OpenID Connect.
  • include.in.token.scope=true writes the scope into the token’s scope field. That is where the server reads it.
  • display.on.consent.screen=false hides it on a consent screen. In the lab, Keycloak does not ask for consent.

Expected: Created new client-scope with id '…'

Scope and audience for the host. For the next two commands, you need the internal IDs of the client and the scope:

# on worker2, in ~/keycloak-26.8.2/bin
HOST=$(./kcadm.sh get clients -r mcpa -q clientId=leitstand-host --fields id --format csv --noquotes)
# on worker2, in ~/keycloak-26.8.2/bin
SCOPE=$(./kcadm.sh get client-scopes -r mcpa --fields id,name --format csv --noquotes | grep ',mcp:tools$' | cut -d, -f1)
# on worker2, in ~/keycloak-26.8.2/bin
echo "$HOST $SCOPE"
  • --format csv --noquotes outputs the fields as a comma-separated line without quotes. A single field is then simply the ID.
  • grep ',mcp:tools$' finds the line that ends with ,mcp:tools ($ = end of line), and cut -d, -f1 cuts out the first field before it.
  • $( … ) puts the output of a command into a variable.

Expected: two IDs of the form 67628bdf-9241-43ae-92c2-449292dc7a07

# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh update clients/$HOST/optional-client-scopes/$SCOPE -r mcpa
# on worker2, in ~/keycloak-26.8.2/bin
./kcadm.sh create clients/$HOST/protocol-mappers/models -r mcpa -s name=audience-leitstand-mcp -s protocol=openid-connect -s protocolMapper=oidc-audience-mapper -s 'config."included.client.audience"=leitstand-mcp' -s 'config."access.token.claim"=true'
  • The first command assigns mcp:tools to the host as an optional scope: the host gets it when it requests it. A default scope would end up in every token, requested or not.
  • The second creates an audience mapper. It writes the client leitstand-mcp into the audience of the tokens of leitstand-host. Keycloak also treats this as permission: it accepts the resource parameter only for resources that appear in a client’s audience this way. Without the mapper, Keycloak answers every request with resource with invalid_target.
  • access.token.claim=true applies the mapper to the access token.

Expected: Created new model with id '…' (the first command prints nothing)

What the client sees. From cp1, check the metadata that an MCP client will find in a moment:

# on cp1
curl -s http://worker2:8080/.well-known/oauth-authorization-server/realms/mcpa | jq '{issuer, code_challenge_methods_supported, authorization_response_iss_parameter_supported}'

jq '{a, b}' builds a new object from only the named fields.

Expected:

{
  "issuer": "http://worker2:8080/realms/mcpa",
  "code_challenge_methods_supported": [
    "plain",
    "S256"
  ],
  "authorization_response_iss_parameter_supported": true
}
  • issuer is the issuer. It appears in every token, and the MCP server will check it.
  • S256 is included – the client may continue. Keycloak also offers plain (challenge = verifier); MCP clients do not use it.
  • authorization_response_iss_parameter_supported: true means: Keycloak appends iss= to the address on the redirect (RFC 9207). The client compares this with the expected issuer and thereby detects when a different authorization server has slipped it a code.

Remember: The card is valid only for the door it was issued for: resource in the request, audience in the token. Public metadata tells everyone where the front desk is.

Save your progress? Sign up for free

Drill 4: A protected server

Where you are: on worker1, in a second terminal (the control room is running in the first).

What you have afterwards: the server pforte (gate) on port 8004, which does nothing without a valid token, and the first step of discovery by hand.

# on worker1
mkdir -p ~/mcpa/tag12 && cd ~/mcpa/tag12
# on worker1
nano pforte.py
~/mcpa/tag12/pforte.py new file
import shutil

import 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.transport_security import TransportSecuritySettings
from mcp.types import ToolAnnotations

AUSSTELLER = "http://worker2:8080/realms/mcpa"
RESSOURCE = "http://worker1:8004/mcp"

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
        wer = f"sub={claims['sub']} azp={claims['azp']}"
        print(f"[pforte] Token angenommen: {wer}", flush=True)
        return AccessToken(
            token=token,
            client_id=claims["azp"],
            scopes=claims.get("scope", "").split(),
            expires_at=claims["exp"],
            resource=RESSOURCE,
            subject=claims["sub"],
        )


mcp = MCPServer(
    "pforte",
    instructions="Geschützter Server auf worker1. Jeder Aufruf braucht ein Token.",
    token_verifier=KeycloakPruefer(),
    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"


schutz = TransportSecuritySettings(
    enable_dns_rebinding_protection=True,
    allowed_hosts=["worker1:8004", "172.16.0.228:8004"],
    allowed_origins=[],
)

mcp.run(
    transport="streamable-http", host="0.0.0.0", port=8004, transport_security=schutz
)
# on worker1
uv run python pforte.py

Expected (the last line):

INFO:     Uvicorn running on http://0.0.0.0:8004 (Press CTRL+C to quit)

What is new:

  • jwt is the PyJWT library. It comes into your project with the SDK; you do not need to install anything. Keycloak issues JWTs (JSON Web Tokens): three Base64 parts with dots in between – header, payload (the claims), signature.
  • jwt.PyJWKClient(…/certs) fetches Keycloak’s public keys (the JWKS endpoint) and keeps them in memory. get_signing_key_from_jwt(token) looks up the key whose ID (kid) is in the token’s header. If Keycloak rotates its keys, the client fetches the new ones.
  • jwt.decode(…) checks in one step: the signature with the key, only with the RS256 algorithm (algorithms – without a fixed list, an attacker could slip in a weaker algorithm), the issuer (issuer), the expiry (exp, always), and the audience (audience=RESSOURCE). If anything fails, PyJWT raises a PyJWTError, and the server rejects the token.
  • KeycloakPruefer (Keycloak checker) fulfills the SDK’s TokenVerifier protocol: a method verify_token(token) that returns an AccessToken or None for “rejected”. The AccessToken gets the client (azp, the client for which Keycloak issued the token), scopes, expiry, resource, and user (sub).
  • AuthSettings describes the server’s role: issuer_url is the authorization server, resource_server_url its own canonical URI, required_scopes the scopes every token must have. validate_token_resource=False tells the SDK that the verifier already checks the audience itself. If you omit the option, the SDK warns – from version 3 on, it will then check by itself.
  • token_verifier= and auth= in the constructor turn on the protection. The SDK then puts a check in front of the /mcp endpoint that rejects every request without a valid token with 401, and it publishes the Protected Resource Metadata.
  • get_access_token() returns the verified token of the current request inside the tool. wer_bin_ich (who am I) uses it to show on whose behalf the tool was called.
  • You know TransportSecuritySettings from Day 8: protection against DNS rebinding, with the allowed Host headers for port 8004.

A call without a token.

# on cp1
curl -si http://worker1:8004/mcp -X POST -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28" -H "Mcp-Method: tools/list" -d '{}' | grep -i -E "^HTTP|^www-authenticate"
  • curl -si also shows the response headers (-i). grep -i -E filters case-insensitively (-i) with an extended pattern (-E, | = or) for the status line and the WWW-Authenticate header.
  • The body {} does not matter: the token check comes before everything else.

Expected:

HTTP/1.1 401 Unauthorized
www-authenticate: Bearer error="invalid_token", error_description="Authentication required", resource_metadata="http://worker1:8004/.well-known/oauth-protected-resource/mcp"

Bearer says what kind of token the server expects. resource_metadata points to the metadata. The SDK writes error="invalid_token" even when no token was sent at all. Strictly according to RFC 6750, there should be no error in that case. Clients do not mind.

The Protected Resource Metadata.

# on cp1
curl -s http://worker1:8004/.well-known/oauth-protected-resource/mcp | jq .

Expected:

{
  "resource": "http://worker1:8004/mcp",
  "authorization_servers": [
    "http://worker2:8080/realms/mcpa"
  ],
  "scopes_supported": [
    "mcp:tools"
  ],
  "bearer_methods_supported": [
    "header"
  ]
}
  • resource is the value that the client will send as the resource parameter.
  • authorization_servers names Keycloak. In the next step, the client fetches its metadata from there – exactly the document from Drill 3.
  • scopes_supported comes from required_scopes. A client requests these scopes if the WWW-Authenticate header names none.
  • bearer_methods_supported: ["header"]: the token belongs in the Authorization header, never in the address. Addresses end up in log files and browser history.

This metadata is not protected – otherwise nobody could find out how to get a token.

Remember: The door checks every card itself – issuer, expiry, audience – and sends guests without a card to the front desk with 401 and a hint (WWW-Authenticate).

Save your progress? Sign up for free

Drill 5: PKCE by hand

Where you are: on cp1 and in the browser on your computer.

What you have afterwards: an access token for pforte, obtained, decoded, and used by yourself.

You now walk through steps 4 to 6 from the background yourself – the way the SDK will do it shortly.

Step 1 – verifier and challenge.

# on cp1
mkdir -p ~/mcpa/tag12 && cd ~/mcpa/tag12
# 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
echo "${#VERIFIER} ${#CHALLENGE}"
  • openssl rand -base64 48 generates 48 random bytes and writes them as Base64 text (64 characters). tr -d '=+/\n' deletes characters that are not allowed in a verifier, plus the line break. What remains is a little over 60 letters and digits. PKCE requires 43 to 128 characters.
  • openssl dgst -sha256 -binary computes the SHA-256 checksum as 32 raw bytes. printf %s passes the verifier without a line break – an echo would append one and corrupt the checksum.
  • base64 | tr '+/' '-_' | tr -d '=' turns this into Base64url without padding: + becomes -, / becomes _, and = is dropped. This is how RFC 7636 specifies it.
  • ${#VARIABLE} is the length of the content.

Expected: two numbers like 62 43 – the first varies, the second is always 43.

Step 2 – the sign-in address.

# on cp1, in ~/mcpa/tag12
AUTH=http://worker2:8080/realms/mcpa/protocol/openid-connect
# on cp1, in ~/mcpa/tag12
URL="$AUTH/auth?response_type=code&client_id=leitstand-host"
# on cp1, in ~/mcpa/tag12
URL="$URL&redirect_uri=http%3A%2F%2Flocalhost%3A3030%2Fcallback"
# on cp1, in ~/mcpa/tag12
URL="$URL&scope=mcp%3Atools&state=drill5"
# on cp1, in ~/mcpa/tag12
URL="$URL&code_challenge=$CHALLENGE&code_challenge_method=S256"
# on cp1, in ~/mcpa/tag12
URL="$URL&resource=http%3A%2F%2Fworker1%3A8004%2Fmcp"
# on cp1, in ~/mcpa/tag12
echo "$URL"

Each URL="$URL&…" appends one piece – this keeps every line short. The parameters of the sign-in address (authorization_endpoint from the metadata):

Parameter Value Meaning
response_type code Authorization Code Flow
client_id leitstand-host who is having the user sign in
redirect_uri http://localhost:3030/callback redirect target, must be registered exactly
scope mcp:tools what the token should allow
state drill5 random value against injected responses; comes back unchanged
code_challenge checksum of the verifier PKCE
code_challenge_method S256 checksum method
resource http://worker1:8004/mcp which server the token is for

Special characters in values are URL-encoded: %3A stands for :, %2F for /. In real operation, state is a random value like the verifier; drill5 makes it readable here.

Step 3 – sign in. Copy the printed address into the browser on your computer. Keycloak shows the realm’s sign-in page:

Keycloak sign-in page for the realm mcpa

Sign in as anna with the password anna-labor. Keycloak then redirects the browser to http://localhost:3030/callback. Nothing is listening there, so the browser reports that the site cannot be reached. That is intended: only the address in the address bar matters. It looks like this:

http://localhost:3030/callback?state=drill5
  &session_state=KtcPt5xmDS53FvqupLNElhH0
  &iss=http%3A%2F%2Fworker2%3A8080%2Frealms%2Fmcpa
  &code=3df9e7b2-9ffa-e631-…

(wrapped here for readability – in the browser it is one line)

state came back unchanged, iss names the issuer, and code is the code. In Keycloak it is valid for 60 seconds. Have the next command ready before you copy the address.

Step 4 – exchange the code for a token. Insert the copied address in single quotes – it contains &, which the shell would otherwise read as “run in the background”:

# on cp1, in ~/mcpa/tag12 – insert the address from your browser
ANTWORT='http://localhost:3030/callback?state=drill5&…&code=…'
# on cp1, in ~/mcpa/tag12 – insert the address from your browser
CODE=$(echo "$ANTWORT" | sed -n 's/.*[?&]code=\([^&]*\).*/\1/p')
# on cp1, in ~/mcpa/tag12 – insert the address 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/tag12 – insert the address from your browser
jq 'del(.access_token, .refresh_token)' token.json
  • sed -n 's/…/\1/p' cuts out the value after code= up to the next &. -n suppresses all other lines, and p prints the edited line.
  • At the token endpoint, curl -d sends the fields as a form (application/x-www-form-urlencoded). grant_type=authorization_code says what is being exchanged. client_id and redirect_uri must match the sign-in. code_verifier is the secret from step 1. --data-urlencode encodes the URI for resource by itself.
  • jq 'del(…)' shows the response without the long tokens.

Expected:

{
  "expires_in": 300,
  "refresh_expires_in": 1800,
  "token_type": "Bearer",
  "not-before-policy": 0,
  "session_state": "KtcPt5xmDS53FvqupLNElhH0",
  "scope": "mcp:tools email profile"
}

The access token is valid for 300 seconds, the refresh token for 1800 seconds. email and profile are Keycloak default scopes that every client gets.

Step 5 – look inside the token. A JWT is not encrypted, only signed. Anyone who has it can read it:

# on cp1, in ~/mcpa/tag12
jq -r .access_token token.json | jq -R 'split(".")[1] | gsub("-";"+") | gsub("_";"/") | @base64d | fromjson | {iss, aud, azp, scope, preferred_username, exp}'
  • jq -R reads the input as text instead of JSON. split(".")[1] takes the middle part.
  • gsub("-";"+") | gsub("_";"/") turns Base64url back into Base64, @base64d decodes, and fromjson reads the result as JSON.

Expected:

{
  "iss": "http://worker2:8080/realms/mcpa",
  "aud": "http://worker1:8004/mcp",
  "azp": "leitstand-host",
  "scope": "mcp:tools email profile",
  "preferred_username": "anna",
  "exp": 1795941804
}

aud is exactly the value of resource – resource-indicators took care of that. azp (authorized party) is the client, and exp the expiry in seconds since 1970.

Step 6 – call the server.

# on cp1, in ~/mcpa/tag12
KOPF=(-H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28")
# on cp1, in ~/mcpa/tag12
nano wer.json
~/mcpa/tag12/wer.json new file
{"jsonrpc": "2.0", "id": 1, "method": "tools/call",
 "params": {"name": "wer_bin_ich", "arguments": {},
   "_meta": {"io.modelcontextprotocol/protocolVersion": "2026-07-28",
     "io.modelcontextprotocol/clientCapabilities": {}}}}
# on cp1, in ~/mcpa/tag12
TOKEN=$(jq -r .access_token token.json)
# on cp1, in ~/mcpa/tag12
curl -s http://worker1:8004/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: wer_bin_ich" -H "Authorization: Bearer $TOKEN" --data @wer.json | jq -r '.result.content[0].text'

You know KOPF and the shape of the request from Day 8. The only new thing is the header Authorization: Bearer …. It belongs on every request – MCP over HTTP has no session that could remember a sign-in.

Expected:

sub=fa146718-661d-420d-b8ee-7e05e74d48f3 client=leitstand-host scopes=mcp:tools email profile

In the terminal of pforte on worker1, you see [pforte] Token angenommen: sub=fa146718-… azp=leitstand-host (“token accepted”).

After five minutes, the token has expired. Then pforte answers with 401 again, and you get a new one with steps 1 to 4. Keycloak does not ask the browser for the password again: the browser sign-in is valid for 30 minutes, and Keycloak redirects immediately.

Remember: PKCE is a claim ticket: only someone who shows the secret whose checksum was left with the order may pick up the card.

Save your progress? Sign up for free

Drill 6: What gets rejected

Where you are: on cp1, in ~/mcpa/tag12, with AUTH, KOPF, CODE, VERIFIER, and TOKEN from Drill 5. Keep an eye on the terminal of pforte on worker1.

What you have afterwards: four rejections seen and understood who issues them.

A code used twice.

# on cp1, in ~/mcpa/tag12
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; echo

Expected: {"error":"invalid_grant","error_description":"Code not valid"}

A code is valid once. Keycloak goes even further: whoever redeems a code twice may have stolen it – so it also revokes the tokens from the first exchange. The refresh token from token.json is now worthless. pforte still accepts the access token until it expires: pforte checks signature and expiry itself and does not ask Keycloak. This is exactly why access tokens are short-lived.

A modified token.

# on cp1, in ~/mcpa/tag12
FALSCH="${TOKEN%?????}AAAAA"
# on cp1, in ~/mcpa/tag12
curl -s -o /dev/null -w "%{http_code}\n" http://worker1:8004/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: wer_bin_ich" -H "Authorization: Bearer $FALSCH" --data @wer.json
  • ${TOKEN%?????} cuts off the last five characters (% removes the shortest matching suffix, and each ? stands for one character). The command then appends AAAAA – the signature no longer matches.
  • -o /dev/null -w "%{http_code}\n" shows only the status code.

Expected: 401, and on worker1: [pforte] Token abgelehnt: Signature verification failed

Anyone who modifies a token, for example aud or exp in the middle part, destroys the signature. Only someone who has Keycloak’s private key can recreate it.

A token without resource. Get a new token, this time without the parameter:

# on cp1, in ~/mcpa/tag12
VERIFIER=$(openssl rand -base64 48 | tr -d '=+/\n')
# on cp1, in ~/mcpa/tag12
CHALLENGE=$(printf %s "$VERIFIER" | openssl dgst -sha256 -binary | base64 | tr '+/' '-_' | tr -d '=')
# on cp1, in ~/mcpa/tag12
URL="$AUTH/auth?response_type=code&client_id=leitstand-host"
# on cp1, in ~/mcpa/tag12
URL="$URL&redirect_uri=http%3A%2F%2Flocalhost%3A3030%2Fcallback"
# on cp1, in ~/mcpa/tag12
URL="$URL&scope=mcp%3Atools&state=drill6"
# on cp1, in ~/mcpa/tag12
URL="$URL&code_challenge=$CHALLENGE&code_challenge_method=S256"
# on cp1, in ~/mcpa/tag12
echo "$URL"

Open the address in the browser – Keycloak redirects immediately, because you are still signed in. Then:

# on cp1, in ~/mcpa/tag12 – insert the new address from your browser
ANTWORT='http://localhost:3030/callback?state=drill6&…&code=…'
# on cp1, in ~/mcpa/tag12 – insert the new address from your browser
CODE=$(echo "$ANTWORT" | sed -n 's/.*[?&]code=\([^&]*\).*/\1/p')
# on cp1, in ~/mcpa/tag12 – insert the new address 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" > ohne.json
# on cp1, in ~/mcpa/tag12 – insert the new address from your browser
jq -r .access_token ohne.json | jq -R 'split(".")[1] | gsub("-";"+") | gsub("_";"/") | @base64d | fromjson | .aud'
# on cp1, in ~/mcpa/tag12 – insert the new address from your browser
curl -s -o /dev/null -w "%{http_code}\n" http://worker1:8004/mcp "${KOPF[@]}" -H "Mcp-Method: tools/call" -H "Mcp-Name: wer_bin_ich" -H "Authorization: Bearer $(jq -r .access_token ohne.json)" --data @wer.json

Expected:

[
  "leitstand-mcp",
  "account"
]
401

and on worker1: [pforte] Token abgelehnt: Audience doesn't match

Without resource, Keycloak assembles the audience from its mappers: the client leitstand-mcp and the account service account. A valid, fresh, correctly signed token – and still not for http://worker1:8004/mcp. That is why the specification requires resource in both requests, and that is why the server checks aud.

A token for a different server. Now you request a token for the control room from Day 8 – resource points to port 8000:

# on cp1, in ~/mcpa/tag12
VERIFIER=$(openssl rand -base64 48 | tr -d '=+/\n')
# on cp1, in ~/mcpa/tag12
CHALLENGE=$(printf %s "$VERIFIER" | openssl dgst -sha256 -binary | base64 | tr '+/' '-_' | tr -d '=')
# on cp1, in ~/mcpa/tag12
URL="$AUTH/auth?response_type=code&client_id=leitstand-host"
# on cp1, in ~/mcpa/tag12
URL="$URL&redirect_uri=http%3A%2F%2Flocalhost%3A3030%2Fcallback"
# on cp1, in ~/mcpa/tag12
URL="$URL&scope=mcp%3Atools&state=drill6b"
# on cp1, in ~/mcpa/tag12
URL="$URL&code_challenge=$CHALLENGE&code_challenge_method=S256"
# on cp1, in ~/mcpa/tag12
URL="$URL&resource=http%3A%2F%2Fworker1%3A8000%2Fmcp"
# on cp1, in ~/mcpa/tag12
echo "$URL"

Open the address in the browser and exchange the code with the same resource:

# on cp1, in ~/mcpa/tag12 – insert the new address from your browser
ANTWORT='http://localhost:3030/callback?state=drill6b&…&code=…'
# on cp1, in ~/mcpa/tag12 – insert the new address from your browser
CODE=$(echo "$ANTWORT" | sed -n 's/.*[?&]code=\([^&]*\).*/\1/p')
# on cp1, in ~/mcpa/tag12 – insert the new address 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:8000/mcp; echo

Expected:

{"error":"invalid_target","error_description":"The requested resource is invalid, missing, unknown, or malformed."}

Keycloak does not know the control room as a resource. It still lets the sign-in through but rejects the request at the token endpoint. This rejection comes from the authorization server; the two before it came from the MCP server. Both sides check, and neither relies on the other.

Remember: Both sides check: the front desk issues no card for other doors, and the door accepts no card for other doors.

Save your progress? Sign up for free

Drill 7: The SDK obtains the token

Where you are: on cp1, in ~/mcpa/tag12.

What you have afterwards: a module anmeldung.py (sign-in) that does the steps from Drill 5 with the SDK, and a small program that uses it to call pforte.

The module.

# on cp1, in ~/mcpa/tag12
nano anmeldung.py
~/mcpa/tag12/anmeldung.py new file
import os
from pathlib import Path
from urllib.parse import parse_qs, urlparse

from mcp.client.auth import OAuthClientProvider
from mcp.shared.auth import (
    AuthorizationCodeResult,
    OAuthClientInformationFull,
    OAuthClientMetadata,
    OAuthToken,
)

RUECKRUF = "http://localhost:3030/callback"
TOKENDATEI = Path("tokens.json")


class Dateispeicher:
    """Vorregistrierte Client-Daten; Tokens in tokens.json, nur für dich lesbar."""

    async def get_tokens(self) -> OAuthToken | None:
        if TOKENDATEI.exists():
            return OAuthToken.model_validate_json(TOKENDATEI.read_text())
        return None

    async def set_tokens(self, tokens: OAuthToken) -> None:
        TOKENDATEI.write_text(tokens.model_dump_json())
        os.chmod(TOKENDATEI, 0o600)

    async def get_client_info(self) -> OAuthClientInformationFull | None:
        # preregistered in Keycloak: public client without a secret
        return OAuthClientInformationFull(
            client_id="leitstand-host",
            redirect_uris=[RUECKRUF],
            token_endpoint_auth_method="none",
        )

    async def set_client_info(self, client_info: OAuthClientInformationFull) -> None:
        pass


async def browser_oeffnen(adresse: str) -> None:
    print(f"\nÖffne diese Adresse im Browser und melde dich an:\n{adresse}\n")


async def rueckruf_einlesen() -> AuthorizationCodeResult:
    zeile = input("Füge die Adresse ein, bei der der Browser gelandet ist: ").strip()
    werte = parse_qs(urlparse(zeile).query)
    return AuthorizationCodeResult(
        code=werte["code"][0],
        state=werte["state"][0],
        iss=werte.get("iss", [None])[0],
    )


def anmeldung_fuer(url: str) -> OAuthClientProvider:
    """OAuth für einen geschützten MCP-Server: Discovery, PKCE, Token, Erneuerung."""
    return OAuthClientProvider(
        server_url=url,
        client_metadata=OAuthClientMetadata(
            redirect_uris=[RUECKRUF],
            token_endpoint_auth_method="none",
            grant_types=["authorization_code"],
        ),
        storage=Dateispeicher(),
        redirect_handler=browser_oeffnen,
        callback_handler=rueckruf_einlesen,
    )

With OAuthClientProvider, the SDK brings the whole flow: detect 401, fetch Protected Resource Metadata and Authorization Server Metadata, PKCE, state, resource, exchange the code, attach the token. It hooks into the HTTP library as auth. You supply only what the SDK cannot know:

  • Dateispeicher (file storage) fulfills the TokenStorage protocol. get_tokens and set_tokens load and save the tokens in tokens.json. os.chmod(TOKENDATEI, 0o600) makes the file readable only by you – whoever has it acts on your behalf. get_client_info returns the preregistered data from Drill 2: client ID leitstand-host, redirect address, and token_endpoint_auth_method none for a public client without a secret. Because this data exists, the SDK does not attempt registration (more on that on Day 13). set_client_info must exist but has nothing to do.
  • browser_oeffnen (open browser) is the redirect_handler: the SDK passes in the finished sign-in address. A desktop program would open the browser; here it is printed.
  • rueckruf_einlesen (read callback) is the callback_handler. It reads the address where the browser landed and returns code, state, and iss as an AuthorizationCodeResult. parse_qs splits the part after ? into a dictionary with lists as values. The SDK compares state and iss with what it expects by itself. Programs with their own user interface instead start a small web server on port 3030 that receives the redirect directly.
  • OAuthClientMetadata describes the client. grant_types=["authorization_code"] says: do not request refreshing via refresh tokens. If, as in the default, refresh_token is also listed there, the SDK appends the scope offline_access. Keycloak then returns an offline token that is valid for 30 days – more than a host needs. Keycloak still sends along a normal refresh token, which is tied to the browser sign-in.

The program.

# on cp1, in ~/mcpa/tag12
nano anmelden.py
~/mcpa/tag12/anmelden.py new file
import asyncio

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() -> None:
    async with httpx2.AsyncClient(auth=anmeldung_fuer(URL)) as http:
        async with Client(streamable_http_client(URL, http_client=http)) as client:
            for name in ("wer_bin_ich", "speicher"):
                ergebnis = await client.call_tool(name, {})
                print(f"{name}: {ergebnis.content[0].text}")


asyncio.run(main())
# on cp1, in ~/mcpa/tag12
uv run python anmelden.py
  • httpx2.AsyncClient(auth=…) is the SDK’s HTTP client with sign-in hooked in.
  • streamable_http_client(URL, http_client=http) builds the transport from Day 8 with this HTTP client. Until now you only gave Client the address. In that case, the SDK uses an HTTP client without sign-in.

Expected:

Öffne diese Adresse im Browser und melde dich an:
http://worker2:8080/realms/mcpa/protocol/openid-connect/auth?response_type=code
  &client_id=leitstand-host&redirect_uri=http%3A%2F%2Flocalhost%3A3030%2Fcallback
  &state=RW_RhX1NpTS7lUWo8OKViRY9osvFXk-vwD4p5bytmIM
  &code_challenge=73JQLtlDydRtcuLV3gKThJJ7JBFLqFV35Dg_Ci8wglU
  &code_challenge_method=S256
  &resource=http%3A%2F%2Fworker1%3A8004%2Fmcp&scope=mcp%3Atools

Füge die Adresse ein, bei der der Browser gelandet ist:

The SDK prints the address on one line; here it is wrapped. (“Open this address in the browser and sign in” / “Paste the address where the browser landed”.) Compare it with your address from Drill 5: the same parameters, only state is now random. The SDK took the scope mcp:tools from scopes_supported in the Protected Resource Metadata. Open the address in the browser, copy the redirect address back into the terminal, and press Enter.

Expected:

wer_bin_ich: sub=fa146718-661d-420d-b8ee-7e05e74d48f3 client=leitstand-host scopes=mcp:tools email profile
speicher: 13.8 % belegt

Start the program a second time:

# on cp1, in ~/mcpa/tag12
uv run python anmelden.py
# on cp1, in ~/mcpa/tag12
ls -l tokens.json

Expected: the same two lines without sign-in, and tokens.json with -rw-------.

The SDK loaded the token from tokens.json. After five minutes it has expired, and the next start asks for the redirect address again. This is due to the SDK in version 2.3.0:

  • Refreshing via the refresh token only works in the same process that signed in. A long-running host thus silently gets a new access token every five minutes – verified in the lab, with resource and the correct audience.
  • The SDK treats a token from storage as valid because it does not know its expiry time. If the server rejects it, the SDK starts the sign-in from scratch instead of using the refresh token.

Remember: The SDK takes the same path you took by hand – 401, metadata, sign-in, PKCE, token – just without the typing.

Save your progress? Sign up for free

Drill 8: The host signs in

Where you are: on cp1, in ~/mcpa/tag12.

What you have afterwards: your host from Day 11 with the protected server pforte.

# on cp1, in ~/mcpa/tag12
cp ../tag11/leitstand.py ../tag11/handbuch.py ../tag11/betriebsbuch.py ../tag11/betriebsbuch.json ../tag11/protokolle.py ../tag11/vorlagen.py ../tag11/host.py ../tag11/freigaben.json .
# on cp1, in ~/mcpa/tag12
nano host.py

freigaben.json comes along: the fingerprints from Day 11 remain valid. Change four places in host.py.

1. Imports – below import httpx and from mcp import …:

import httpx
import httpx2
from mcp import Client, StdioServerParameters
from mcp.client.streamable_http import streamable_http_client

from anmeldung import anmeldung_fuer

2. Servers – the line "paket": … from Day 11 is dropped; the third-party server is not running today. Below SERVER go the address of pforte and the new entry in VERTRAUT:

    "fern": "http://worker1:8000/mcp",
}
PFORTE = "http://worker1:8004/mcp"
VERTRAUT = {"leitstand", "handbuch", "betriebsbuch", "protokolle", "vorlagen", "fern", "pforte"}

3. System prompt – the model should know where pforte acts:

        "Du bist ein Betriebsassistent auf dem Rechner cp1. Die Werkzeuge der Server fern und pforte wirken "
        "auf dem Rechner worker1, alle anderen auf cp1. "

4. Connecting – in main, instead of the previous lines clients = { … for name, parameter in SERVER.items() }:

        pforte_http = await stapel.enter_async_context(httpx2.AsyncClient(auth=anmeldung_fuer(PFORTE)))
        alle = {**SERVER, "pforte": streamable_http_client(PFORTE, http_client=pforte_http)}
        clients = {
            name: await stapel.enter_async_context(Client(parameter))
            for name, parameter in alle.items()
        }
  • As with the clients, stapel.enter_async_context(…) makes sure that the HTTP client is closed at the end.
  • {**SERVER, "pforte": …} builds a new dictionary from all entries of SERVER plus pforte. Besides addresses and StdioServerParameters, Client also accepts a ready-made transport.
# on cp1, in ~/mcpa/tag12
uv run python host.py Als wer bin ich bei pforte angemeldet, und wie voll ist der Speicher auf worker1?

(The question asks who you are signed in as at pforte and how full the disk on worker1 is.) If tokens.json is older than five minutes, the host first asks for the redirect address – as in Drill 7.

Expected (shortened):

[host] neues Werkzeug pforte__wer_bin_ich, Fingerabdruck e2fad59a44acc59b gespeichert
[host] neues Werkzeug pforte__speicher, Fingerabdruck 6a249fc6bdf74ab3 gespeichert
[host] 14 Werkzeuge von 7 Servern: leitstand__speicher, …, fern__warten, pforte__wer_bin_ich, pforte__speicher
[runde 1] Modell will pforte__wer_bin_ich mit {}
[runde 1] Modell will pforte__speicher mit {}
[modell] Ich bin als `leitstand-host` mit dem Token `sub=fa146718-661d-420d-b8ee-7e05e74d48f3` angemeldet. Der Speicher auf worker1 ist auf 13,8 % belegt.

The model chooses the wording of the answer anew every time. In the lab, the two calls came in every run.

The host treats pforte like any other server: fingerprints, confirmation prompts, frames around results. The sign-in lives entirely in the HTTP client. Neither the model nor the tools see the token – it leaves the host only in the direction of pforte.

Remember: The card stays with the concierge: neither the model nor the tools see the token.

Save your progress? Sign up for free

If it doesn’t work

  • curl: (7) Failed to connect to worker2 port 8080: Keycloak is not running or listens only on localhost. Check on worker2 with ss -tlnp | grep 8080. It must show *:8080, not 127.0.0.1:8080 – in that case --http-host 0.0.0.0 is missing.
  • The browser does not find worker2: Step 4 of Drill 1 is missing on your computer.
  • kcadm.sh reports HTTP 401 Unauthorized: The kcadm.sh sign-in has expired. Repeat ./kcadm.sh config credentials ….
  • Code not valid on the first exchange: More than 60 seconds passed, or you copied one character too few. Reload the sign-in address in the browser – you are still signed in, and Keycloak redirects immediately with a new code.
  • PKCE verification failed: Code mismatch: The verifier does not match the challenge in the address, usually because VERIFIER was regenerated in the meantime. The code is used up after that. Start over with step 1.
  • invalid_target for resource=http://worker1:8004/mcp: The audience mapper from Drill 3 is missing, the resource_url of leitstand-mcp is spelled differently, or Keycloak is running without --features resource-indicators.
  • Missing parameter: code_challenge_method in the redirect: The sign-in address has no challenge. The client requires PKCE.
  • Refreshed tokens fail with Audience doesn't match: grant_types=["authorization_code"] is missing in anmeldung.py. The SDK then requests offline_access, and Keycloak 26.8 ignores resource when refreshing an offline token – the new token has the audience from Drill 6.
  • EOFError when starting the host or anmelden.py: The SDK wants a new sign-in and reads the redirect address but gets no input. Start the program without redirecting stdin.
  • WARNUNG: pforte__wer_bin_ich hat sich seit der Freigabe verändert … gesperrt: You changed pforte.py after the host’s first run – the protection from Day 11 kicks in. Review the change and approve the tool again: jq 'del(."pforte__wer_bin_ich")' freigaben.json > neu.json && mv neu.json freigaben.json.
  • pforte rejects every token with Audience doesn't match: Does RESSOURCE have a trailing slash or localhost instead of worker1? The value must match the aud in the token character for character.

Exercise: Refresh a token (15 min)

Get a fresh token with resource as in Drill 5 (the browser redirects immediately). Then refresh it by hand with the refresh token and check the audience of the new access token. What happens if you use the old refresh token a second time – and what happens to the new one after that?

Solution

After steps 1 to 4 from Drill 5, token.json contains a fresh token. Then:

# on cp1, in ~/mcpa/tag12
RT=$(jq -r .refresh_token token.json)
# on cp1, in ~/mcpa/tag12
curl -s $AUTH/token -d grant_type=refresh_token -d client_id=leitstand-host -d "refresh_token=$RT" --data-urlencode resource=http://worker1:8004/mcp > neu.json
# on cp1, in ~/mcpa/tag12
jq -r .access_token neu.json | jq -R 'split(".")[1] | gsub("-";"+") | gsub("_";"/") | @base64d | fromjson | .aud'
# on cp1, in ~/mcpa/tag12
curl -s $AUTH/token -d grant_type=refresh_token -d client_id=leitstand-host -d "refresh_token=$RT" --data-urlencode resource=http://worker1:8004/mcp; echo
# on cp1, in ~/mcpa/tag12
curl -s $AUTH/token -d grant_type=refresh_token -d client_id=leitstand-host -d "refresh_token=$(jq -r .refresh_token neu.json)" --data-urlencode resource=http://worker1:8004/mcp; echo

Expected:

"http://worker1:8004/mcp"
{"error":"invalid_grant","error_description":"Maximum allowed refresh token reuse exceeded"}
{"error":"invalid_grant","error_description":"Session doesn't have required client"}
  • grant_type=refresh_token exchanges the refresh token for a new pair. Here too, resource belongs in the request, otherwise the new token gets the audience from Drill 6.
  • Because of revokeRefreshToken=true, every refresh token is valid only once. If a used one shows up again, two parties have it – the client and perhaps a thief. Keycloak cannot know which of them is genuine and ends the sign-in session for this client entirely. That also invalidates the new refresh token. This refresh token reuse detection is the reason why the specification requires rotation for public clients.

Save your progress? Sign up for free

Challenge: A server without audience checking (20 min)

A colleague runs a second MCP server tickets on worker1, port 8005. It trusts the same Keycloak and checks signature and expiry, but not aud – “the tokens all come from our Keycloak anyway”. tickets can create and close tickets.

  1. What can the operator of pforte – or someone who has taken over pforte – do with the tokens your host sends to it?
  2. Which two places would have prevented this?
  3. Why doesn’t it help that pforte has only read-only tools?

Solution

  1. Every token that arrives at pforte is a valid, Keycloak-signed token for Anna. Until it expires, the operator can send it to tickets and create and close tickets there in Anna’s name. This is a token replay across server boundaries.
  2. First, tickets: it must check that it is itself in aud. Then a token for http://worker1:8004/mcp is useless to it. Second, the client: with resource, it requests tokens only for exactly the server it is talking to. A token with aud: ["leitstand-mcp", "account"] as in Drill 6 would also be usable for an account service that checks this way.
  3. What a token allows is decided by the server that accepts it, not by the one it was intended for. That is why the specification requires every MCP server to accept only tokens issued for it – and why clients may send tokens only to the server they obtained them for.

Save your progress? Sign up for free

Checkpoint

# 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
curl -s -o /dev/null -w "%{http_code}\n" -X POST http://worker1:8004/mcp -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -H "MCP-Protocol-Version: 2026-07-28" -d '{}'

Expected: 401

# on cp1
jq -r '."pforte__speicher"' ~/mcpa/tag12/freigaben.json

Expected: 6a249fc6bdf74ab3

Leave Keycloak running on worker2 and pforte on worker1 – Day 13 builds on them. If you stop them, you start them again with the same commands. Keycloak keeps the realm, user, and clients in data/.

Exam questions

1. An MCP client calls a server without a token and gets 401. Where does it learn which authorization server it has to sign in with?

    1. from the authorization_servers field of the Protected Resource Metadata
    1. from the response to server/discover
    1. from the issuer field in the token
    1. from a fixed address /.well-known/mcp-auth

2. An authorization server’s metadata contains no code_challenge_methods_supported field. What must an MCP client do?

    1. continue with plain
    1. continue without PKCE
    1. abort the sign-in
    1. try Dynamic Client Registration

3. What is the resource parameter in the authorization and token requests for?

    1. It names the tools the client wants to call.
    1. It binds the token to the MCP server for which it is issued.
    1. It replaces the redirect URI.
    1. It names the authorization server.

4. An MCP server receives a correctly signed, unexpired token from the same authorization server whose aud names a different server. How must it respond?

    1. 200, because signature and expiry are correct
    1. 401, because the token was not issued for it
    1. 403 with insufficient_scope
    1. It forwards the token to the named server.

5. Where does the access token belong in MCP over HTTP?

    1. in an access_token parameter of the address
    1. in params._meta of every JSON-RPC message
    1. in the Authorization: Bearer … header of every HTTP request
    1. only in the first request of a session

Solutions

  1. A. The path goes via resource_metadata in the WWW-Authenticate header or the fixed .well-known addresses to the Protected Resource Metadata (RFC 9728).
  2. C. If the field is missing, the server does not support PKCE, and the client must abort.
  3. B. resource (RFC 8707) names the server’s canonical URI. The authorization server writes it into the audience.
  4. B. Invalid tokens – including those for a different audience – get 401. Forwarding is explicitly forbidden (Day 13).
  5. C. Tokens never belong in the address, and because MCP over HTTP has no session, every request carries its own token.

Interview Note

“How do you secure an MCP server?” – Over HTTP, as an OAuth 2.1 resource server. The server publishes Protected Resource Metadata naming its authorization server and responds to requests without a token with 401 and resource_metadata. An existing identity provider handles sign-in. The client obtains a token with the Authorization Code Flow and PKCE and sends resource along. The server checks signature, issuer, expiry, audience, and scopes – on every request. If you add that an access token must be short-lived because the server does not notice a revocation when it checks JWTs locally, you have understood the essentials.

Enterprise Note

Companies already have their identity provider – Keycloak, Entra ID, Okta, Ping. MCP servers each get an entry there as a resource, and hosts one as a public client. This way, existing rules apply: multi-factor sign-in, locked accounts, groups, offboarding when people leave. Two points deserve a separate decision. First, the lifetime of access tokens: servers check JWTs locally, so a locked account only takes effect after expiry. If you need immediate revocation, check tokens via introspection at the identity provider – which costs one call per request. Second, support for resource: not every identity provider supports RFC 8707, and in Keycloak 26.8 it is still experimental. Without it, the audience stays fixed via scopes, and that deserves a test like Drill 6.

Summary

  • Over HTTP, an MCP server is an OAuth 2.1 resource server. Tokens are issued by a separate authorization server. This does not apply to stdio.
  • Discovery: 401 with resource_metadata → Protected Resource Metadata (resource, authorization_servers, scopes_supported) → Authorization Server Metadata with an exactly matching issuer.
  • Authorization Code Flow with PKCE (S256). Without code_challenge_methods_supported, the client aborts. A code is valid once and briefly.
  • resource in the authorization and token requests binds the token to one server. The server checks signature, issuer, expiry, and aud and rejects everything else with 401.
  • The token goes only in the Authorization: Bearer header, on every request. Refresh tokens of public clients are rotated. A reused one ends the sign-in session.
  • In the SDK: server with TokenVerifier and AuthSettings, client with OAuthClientProvider, TokenStorage, and two handlers. Version 2.3.0 refreshes tokens only in the same process.
  • Lab shortcuts: HTTP instead of HTTPS, Keycloak in development mode, resource-indicators experimental.

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
getent hosts name resolve a name like a program does –
apt-get install -y openjdk-21-jre-headless unzip Java 21 without graphics, unzip -y without prompting
curl -sSLO adresse download a file under its own name -L redirects, -O name from address
unzip -q archiv.zip unpack an archive quietly -q quiet
bin/kc.sh start-dev Keycloak in development mode --http-host, --http-port, --features
kcadm.sh config credentials sign kcadm in --server, --realm, --user, --password
kcadm.sh create realms -s … create a realm realm, revokeRefreshToken, defaultLocale
kcadm.sh create users -r mcpa -s … create a user -r realm
kcadm.sh set-password set a password --username, --new-password
kcadm.sh create clients -s … create a client publicClient, redirectUris, pkce.code.challenge.method, resource_url
kcadm.sh create client-scopes -s … create a scope include.in.token.scope
kcadm.sh update clients/ID/optional-client-scopes/ID assign a scope to a client –
kcadm.sh create clients/ID/protocol-mappers/models create a mapper oidc-audience-mapper, included.client.audience
kcadm.sh get … --fields … --format csv --noquotes output individual fields -q filter
openssl rand -base64 48 random value as Base64 number of bytes
openssl dgst -sha256 -binary SHA-256 as raw bytes –
tr '+/' '-_', tr -d '=' Base64 to Base64url -d delete
curl -d feld=wert, --data-urlencode send a form encodes by itself
jq -R with split(".")[1], @base64d, fromjson read the payload of a JWT -R text instead of JSON
${VAR%?????}, ${#VAR} cut off the end, length ? one character
jwt.PyJWKClient(url) fetch keys from Keycloak get_signing_key_from_jwt
jwt.decode(token, key, algorithms=…, issuer=…, audience=…) verify a JWT expiry always
MCPServer(…, token_verifier=…, auth=AuthSettings(…)) protect a server issuer_url, resource_server_url, required_scopes
get_access_token() token of the current request –
OAuthClientProvider(server_url=…, client_metadata=…, storage=…, …) OAuth in the client redirect_handler, callback_handler
httpx2.AsyncClient(auth=…) HTTP client with sign-in –
streamable_http_client(url, http_client=…) transport with your own HTTP client –

Contents

More